aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


tools/stress/protocol.go (7322B)


      1 package main
      2 
      3 import (
      4 	"context"
      5 	"encoding/binary"
      6 	"fmt"
      7 	"io"
      8 	"net/http"
      9 	"strings"
     10 	"time"
     11 
     12 	"github.com/coder/websocket"
     13 )
     14 
     15 func packet(kind uint16, opcode uint32, body []byte) []byte {
     16 	length := 20 + len(body)
     17 	result := make([]byte, (length+3)&^3)
     18 	binary.BigEndian.PutUint16(result, 0xdfdf)
     19 	binary.BigEndian.PutUint16(result[2:], kind)
     20 	binary.BigEndian.PutUint16(result[4:], 1)
     21 	binary.BigEndian.PutUint16(result[6:], uint16(length))
     22 	binary.BigEndian.PutUint32(result[8:], 1)
     23 	binary.BigEndian.PutUint32(result[16:], opcode)
     24 	copy(result[20:], body)
     25 	return result
     26 }
     27 
     28 func command(id, opcode uint32, body []byte) []byte {
     29 	prefix := binary.BigEndian.AppendUint32(nil, 50000)
     30 	prefix = binary.BigEndian.AppendUint32(prefix, id)
     31 	prefix = append(prefix, 0)
     32 	return packet(10, opcode, append(prefix, body...))
     33 }
     34 
     35 func movement(person visitor, action uint32) []byte {
     36 	// 14.9.1 quantizes XYZ and the quaternion into a 17-byte movement body.
     37 	body := []byte{byte(action)}
     38 	for axis, scale := range [3]float32{8, 16, 8} {
     39 		body = binary.BigEndian.AppendUint16(body, uint16(int32(person.Place.Position[axis]*scale)))
     40 	}
     41 	for _, value := range person.Place.Rotation {
     42 		body = binary.BigEndian.AppendUint16(body, uint16(int16(value*16384)))
     43 	}
     44 	body = binary.BigEndian.AppendUint16(body, 0)
     45 	return command(person.ID, 0x54111123, body)
     46 }
     47 
     48 func readPacket(reader io.Reader) ([]byte, error) {
     49 	var header [16]byte
     50 	if _, err := io.ReadFull(reader, header[:]); err != nil {
     51 		return nil, err
     52 	}
     53 	length := int(binary.BigEndian.Uint16(header[6:8]))
     54 	if length < 20 {
     55 		return nil, fmt.Errorf("invalid packet length %d", length)
     56 	}
     57 	result := make([]byte, (length+3)&^3)
     58 	copy(result, header[:])
     59 	if _, err := io.ReadFull(reader, result[16:]); err != nil {
     60 		return nil, err
     61 	}
     62 	return result[:length], nil
     63 }
     64 
     65 type acknowledgement struct{ opcode, action uint32 }
     66 
     67 func exercise(ctx context.Context, address string, person visitor, scheduled time.Time, events chan<- event) error {
     68 	dial, cancel := context.WithTimeout(ctx, 30*time.Second)
     69 	socket, response, err := websocket.Dial(dial, "ws"+strings.TrimPrefix(address, "http")+"/browser-world", &websocket.DialOptions{HTTPHeader: http.Header{"Cookie": {person.Cookie}}})
     70 	cancel()
     71 	if err != nil {
     72 		if response != nil {
     73 			response.Body.Close()
     74 		}
     75 		return err
     76 	}
     77 	defer socket.CloseNow()
     78 	connection := websocket.NetConn(ctx, socket, websocket.MessageBinary)
     79 	defer connection.Close()
     80 	acks := make(chan acknowledgement, 4)
     81 	readDone := make(chan struct{})
     82 	var readError error
     83 	readerContext, stopReader := context.WithCancel(ctx)
     84 	defer stopReader()
     85 	go func() {
     86 		defer close(readDone)
     87 		traffic := event{playfield: person.Place.Playfield, kind: "traffic"}
     88 		reported := time.Now()
     89 		defer func() { events <- traffic }()
     90 		for {
     91 			body, err := readPacket(connection)
     92 			if err != nil {
     93 				readError = err
     94 				return
     95 			}
     96 			traffic.packets++
     97 			traffic.bytes += (len(body) + 3) &^ 3
     98 			if time.Since(reported) >= time.Second {
     99 				events <- traffic
    100 				traffic = event{playfield: person.Place.Playfield, kind: "traffic"}
    101 				reported = time.Now()
    102 			}
    103 			ack := acknowledgement{}
    104 			if binary.BigEndian.Uint16(body[2:4]) == 11 && binary.BigEndian.Uint32(body[16:20]) == 2 {
    105 				ack.opcode = 2
    106 			} else {
    107 				if binary.BigEndian.Uint16(body[2:4]) != 10 || len(body) < 29 || binary.BigEndian.Uint32(body[24:28]) != person.ID {
    108 					continue
    109 				}
    110 				ack.opcode = binary.BigEndian.Uint32(body[16:20])
    111 				if ack.opcode == 0x5e477770 && len(body) >= 33 {
    112 					ack.action = binary.BigEndian.Uint32(body[29:33])
    113 				}
    114 				if ack.opcode != 0x5f52412e && ack.opcode != 0x570c2039 && (ack.opcode != 0x5e477770 || ack.action != 86 && ack.action != 87) {
    115 					continue
    116 				}
    117 			}
    118 			select {
    119 			case acks <- ack:
    120 			case <-readerContext.Done():
    121 				readError = readerContext.Err()
    122 				return
    123 			}
    124 		}
    125 	}()
    126 	// Join the reader before the client worker exits, including failed handshakes.
    127 	defer func() { stopReader(); socket.CloseNow(); <-readDone }()
    128 	write := func(body []byte) error {
    129 		if err := connection.SetWriteDeadline(time.Now().Add(30 * time.Second)); err != nil {
    130 			return err
    131 		}
    132 		_, err := connection.Write(body)
    133 		return err
    134 	}
    135 	await := func(want acknowledgement) error {
    136 		timer := time.NewTimer(30 * time.Second)
    137 		defer timer.Stop()
    138 		for {
    139 			select {
    140 			case got := <-acks:
    141 				if got == want {
    142 					return nil
    143 				}
    144 			case <-readDone:
    145 				return readError
    146 			case <-timer.C:
    147 				return fmt.Errorf("game acknowledgement timed out: %#x", want.opcode)
    148 			case <-ctx.Done():
    149 				return ctx.Err()
    150 			}
    151 		}
    152 	}
    153 	body := binary.BigEndian.AppendUint32(nil, person.ID)
    154 	if err := write(packet(1, 0x1b, append(body, make([]byte, 8)...))); err != nil {
    155 		return err
    156 	}
    157 	if err := await(acknowledgement{opcode: 0x5f52412e}); err != nil {
    158 		return err
    159 	}
    160 	if err := write(command(person.ID, 0x570c2039, nil)); err != nil {
    161 		return err
    162 	}
    163 	if err := await(acknowledgement{opcode: 0x570c2039}); err != nil {
    164 		return err
    165 	}
    166 	events <- event{playfield: person.Place.Playfield, kind: "ready", elapsed: time.Since(scheduled)}
    167 	defer func() { events <- event{playfield: person.Place.Playfield, kind: "disconnected"} }()
    168 
    169 	// One scheduled action per second per client. Skipped deadlines are counted;
    170 	// a slow reply must not silently turn the test into a lighter workload.
    171 	next := time.Now().Add(time.Second)
    172 	pending := false
    173 	defer func() {
    174 		if pending {
    175 			events <- event{playfield: person.Place.Playfield, kind: "unanswered_action"}
    176 		}
    177 	}()
    178 	for step := 0; waitUntil(ctx, next); step++ {
    179 		sent := time.Now()
    180 		pending = true
    181 		want := acknowledgement{opcode: 2}
    182 		if person.Place.Activity == "crowd" {
    183 			for _, action := range []uint32{2, 4} {
    184 				if err := write(movement(person, action)); err != nil {
    185 					return err
    186 				}
    187 			}
    188 			want = acknowledgement{opcode: 0x5e477770, action: uint32(86 + step%2)}
    189 			body := binary.BigEndian.AppendUint32(nil, want.action)
    190 			body = append(body, make([]byte, 16)...)
    191 			if err := write(command(person.ID, want.opcode, body)); err != nil {
    192 				return err
    193 			}
    194 		} else {
    195 			// Walkers move for two seconds, then rest for eight, reversing each leg.
    196 			if person.Place.Activity == "walk" && (step%10 == 0 || step%10 == 2) {
    197 				action := uint32(1 + 2*(step/10%2))
    198 				if step%10 == 2 {
    199 					distance := float32(2)
    200 					if action == 3 {
    201 						distance = -distance
    202 					}
    203 					person.Place.Position[2] += distance
    204 					action++
    205 				}
    206 				if err := write(movement(person, action)); err != nil {
    207 					return err
    208 				}
    209 			}
    210 			if err := write(packet(11, 1, nil)); err != nil {
    211 				return err
    212 			}
    213 		}
    214 		if err := await(want); err != nil {
    215 			return err
    216 		}
    217 		pending = false
    218 		events <- event{playfield: person.Place.Playfield, kind: "action", elapsed: time.Since(sent), at: time.Now()}
    219 		events <- event{playfield: person.Place.Playfield, kind: "scheduled_action", elapsed: time.Since(next)}
    220 		if want.opcode == 0x5e477770 && want.action == 87 {
    221 			if err := write(movement(person, uint32(1+2*(step/2%2)))); err != nil {
    222 				return err
    223 			}
    224 		}
    225 		next = next.Add(time.Second)
    226 		if late := time.Since(next); late >= 0 {
    227 			missed := int(late/time.Second) + 1
    228 			events <- event{playfield: person.Place.Playfield, kind: "late", missed: missed}
    229 			next = next.Add(time.Duration(missed) * time.Second)
    230 		}
    231 	}
    232 	return nil
    233 }