Skip to content

gitflarePublicPartly agent-ready40

neon-drift

Real-time multiplayer arcade racer on Cloudflare Workers and Durable Objects.

Add the Apache-2.0 licence3efe3da
TypeScript271 lines9.6 KB
import { DurableObject } from 'cloudflare:workers';import { createState, addPlayer, removePlayer, step, sanitizeInput, TICK_HZ, MAX_PLAYERS } from '../public/shared/sim.js';import { makeSnapshot, encodeSnapshot, FULL_EVERY, RING, parseMessage } from '../public/shared/protocol.js';import { sanitizeName, joinRoom, leaveRoom, expireSlots, promoteQueued, createLimiter, admit, type Slot, type Limiter } from './room-logic.ts';import { writeScores } from './leaderboard.ts'; const TICK_MS = 1000 / TICK_HZ;const EMPTY_MS = 60000; interface Att { id: number; name: string; token: string; spectator: boolean; ack: number; seq: number; lim: Limiter; joined: boolean; watch?: boolean } export class Room extends DurableObject {  env: any;  state: any = null;  code = '';  slots = new Map<number, Slot>();  inputs = new Map<number, any>();  seqs = new Map<number, number>();  snapEvents: any[] = [];  ring = new Map<number, any>();  nextTickAt = 0;  nextId = 1;  emptySince = 0;  lastPhase = 'waiting';   constructor(ctx: DurableObjectState, env: any) {    super(ctx, env);    this.env = env;  }   ensure() {    if (this.state) return;    this.state = createState((Math.random() * 4294967296) >>> 0);    for (const ws of this.ctx.getWebSockets()) {      const a = ws.deserializeAttachment() as Att | null;      if (!a || !a.joined) continue;      this.slots.set(a.id, { id: a.id, token: a.token, connected: true, disconnectedAt: 0, spectator: a.spectator });      if (!a.spectator) addPlayer(this.state, a.id, a.name);      this.nextId = Math.max(this.nextId, a.id + 1);    }  }   async fetch(request: Request): Promise<Response> {    this.code = new URL(request.url).pathname.slice(4).toUpperCase();    this.ensure();    const pair = new WebSocketPair();    this.ctx.acceptWebSocket(pair[1]);    const att: Att = { id: 0, name: '', token: '', spectator: true, ack: -1, seq: 0, lim: createLimiter(Date.now()), joined: false };    pair[1].serializeAttachment(att);    return new Response(null, { status: 101, webSocket: pair[0] });  }   webSocketMessage(ws: WebSocket, data: string | ArrayBuffer) {    this.ensure();    const att = ws.deserializeAttachment() as Att;    const size = typeof data === 'string' ? data.length : data.byteLength;    const verdict = admit(att.lim, Date.now(), size);    if (!verdict.ok) {      ws.serializeAttachment(att);      if (verdict.close) ws.close(1008, 'rate limit');      return;    }    ws.serializeAttachment(att);    if (typeof data !== 'string') return;    const m = parseMessage(data);    if (!m) return;    switch (m[0]) {      case 'j':        if (!att.joined || (att.watch && m[4] !== 1)) { att.watch = false; att.joined = false; this.join(ws, att, m); }        break;      case 'i': {        if (att.spectator || !att.joined) return;        const inp = sanitizeInput(m.slice(1, 4));        if (!inp || inp.seq <= att.seq) return;        att.seq = inp.seq;        this.seqs.set(att.id, inp.seq);        if (Number.isInteger(m[4])) att.ack = Math.max(att.ack, m[4]);        this.inputs.set(att.id, inp);        ws.serializeAttachment(att);        break;      }      case 'a':        if (Number.isInteger(m[1])) {          att.ack = Math.max(att.ack, m[1]);          ws.serializeAttachment(att);        }        break;      case 'p':        if (typeof m[1] === 'number') ws.send(JSON.stringify(['o', m[1], this.state.tick]));        break;    }  }   join(ws: WebSocket, att: Att, m: any[]) {    if (m[4] === 1) {      Object.assign(att, { id: 0, name: '', token: '', spectator: true, ack: -1, seq: 0, joined: true, watch: true });      ws.serializeAttachment(att);      const snap = this.record();      ws.send(JSON.stringify(['w', 0, '', this.code, 'spectator', this.state.tick, encodeSnapshot(null, snap)]));      this.schedule();      return;    }    const name = sanitizeName(m[1]);    const token = typeof m[2] === 'string' ? m[2] : null;    const bytes = new Uint8Array(16);    crypto.getRandomValues(bytes);    const res = joinRoom(this.slots, token, Date.now(), MAX_PLAYERS, this.state.phase === 'results', () => Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join(''), () => this.nextId++);    const slot = res.slot;    for (const other of this.ctx.getWebSockets()) {      if (other === ws) continue;      const oa = other.deserializeAttachment() as Att | null;      if (oa && oa.joined && oa.id === slot.id) {        oa.joined = false;        other.serializeAttachment(oa);        try { other.close(1000, 'replaced'); } catch {}      }    }    if (res.kind === 'new') addPlayer(this.state, slot.id, name);    const p = this.state.players.get(slot.id);    Object.assign(att, { id: slot.id, name: p ? p.name : name, token: slot.token, spectator: slot.spectator, ack: -1, seq: 0, joined: true });    ws.serializeAttachment(att);    this.emptySince = 0;    const snap = this.record();    ws.send(JSON.stringify(['w', slot.id, slot.token, this.code, slot.spectator ? 'spectator' : 'player', this.state.tick, encodeSnapshot(null, snap), ...(slot.spectator && slot.queued ? [1] : [])]));    this.report();    this.schedule();  }   schedule() {    this.ctx.storage.getAlarm().then((a) => {      if (a === null) {        this.nextTickAt = Date.now() + TICK_MS;        return this.ctx.storage.setAlarm(this.nextTickAt);      }    });  }   async alarm() {    this.ensure();    const now = Date.now();    if (this.ctx.getWebSockets().length === 0) {      if (!this.emptySince) this.emptySince = now;      if (now - this.emptySince >= EMPTY_MS) {        this.state = null;        this.slots.clear();        this.ring.clear();        this.inputs.clear();        this.report(true);        await this.ctx.storage.deleteAll();        return;      }      await this.ctx.storage.setAlarm(now + 5000);      return;    }    this.emptySince = 0;    if (this.nextTickAt === 0) this.nextTickAt = now;    let due = Math.floor((now - this.nextTickAt) / TICK_MS) + 1;    if (due < 1) due = 1;    if (due > 3) {      due = 3;      this.nextTickAt = now - 2 * TICK_MS;    }    for (let i = 0; i < due; i++) {      const events = step(this.state, this.inputs);      this.nextTickAt += TICK_MS;      this.after(events);      this.broadcast();    }    for (const id of expireSlots(this.slots, now)) {      removePlayer(this.state, id);      this.inputs.delete(id);      this.seqs.delete(id);      this.report();    }    await this.ctx.storage.setAlarm(Math.max(Math.ceil(this.nextTickAt), now + 1));  }   after(events: any[]) {    const ph = this.state.phase;    if (ph !== this.lastPhase) {      if (ph === 'results') {        const rows = [...this.state.players.values()].map((p: any) => ({ name: p.name, score: p.score }));        this.ctx.waitUntil(writeScores(this.env.DB, 'arena', rows));      }      this.lastPhase = ph;      if (ph === 'countdown') this.promote();      this.ctx.storage.put('match', { phase: ph, seed: this.state.seed }).catch(() => {});      this.report();    }    if (events.length) {      const msg = JSON.stringify(['v', this.state.tick, ...events]);      for (const ws of this.ctx.getWebSockets()) ws.send(msg);    }  }   promote() {    const ids = promoteQueued(this.slots, MAX_PLAYERS);    if (!ids.length) return;    const socks = this.ctx.getWebSockets();    for (const id of ids) {      const slot = this.slots.get(id)!;      let name = 'Player';      for (const ws of socks) {        const a = ws.deserializeAttachment() as Att | null;        if (a && a.joined && a.token === slot.token) name = a.name || name;      }      addPlayer(this.state, id, name);    }    const snap = this.record();    for (const ws of socks) {      const a = ws.deserializeAttachment() as Att | null;      if (!a || !a.joined || !ids.includes(a.id)) continue;      a.spectator = false; a.ack = -1; a.seq = 0;      ws.serializeAttachment(a);      ws.send(JSON.stringify(['w', a.id, a.token, this.code, 'player', this.state.tick, encodeSnapshot(null, snap)]));    }    this.report();  }   record() {    const snap = makeSnapshot(this.state);    this.ring.set(snap.tick, snap);    this.ring.delete(snap.tick - RING);    return snap;  }   broadcast() {    const st = this.state;    const snap = this.record();    const fullTick = st.tick % FULL_EVERY === 0;    for (const ws of this.ctx.getWebSockets()) {      const a = ws.deserializeAttachment() as Att | null;      if (!a || !a.joined) continue;      const base = this.ring.get(a.ack);      const useFull = fullTick || !base;      const delta = encodeSnapshot(useFull ? null : base, snap);      try {        ws.send(JSON.stringify(['s', st.tick, useFull ? -1 : a.ack, a.seq, delta]));      } catch {}    }  }   report(closed = false) {    if (!this.code) return;    let players = 0;    for (const s of this.slots.values()) if (!s.spectator && s.connected) players++;    const info = { code: this.code, players: closed ? 0 : players, maxPlayers: MAX_PLAYERS, open: this.state ? this.state.phase !== 'results' : true };    try {      const lobby = this.env.LOBBY.get(this.env.LOBBY.idFromName('global'));      this.ctx.waitUntil(lobby.report(info));    } catch {}  }   webSocketClose(ws: WebSocket) { this.left(ws); }  webSocketError(ws: WebSocket) { this.left(ws); }   left(ws: WebSocket) {    this.ensure();    const a = ws.deserializeAttachment() as Att | null;    if (a && a.joined) {      const others = this.ctx.getWebSockets().some((o) => o !== ws && (o.deserializeAttachment() as Att | null)?.id === a.id);      if (!others) {        leaveRoom(this.slots, a.id, Date.now());        this.inputs.delete(a.id);      }    }    this.report();    this.schedule();  }}