Back to Faultline
SOURCE / PINNED RELEASE

Made of little things.

Faultline

Release
da1ffaa5624c…
Author-recorded commit
60f5f03189db…
License
LICENSE
Author’s source reference
nostr://npub182jczunncwe0jn6frpqwq3e0qjws7yqqnc3auccqv9nte2dnd63scjm4rf/wss%3A%2F%2Fgit.napplet.soy%2F/n-6932b12c78c

Archive hash verified: 5a2e0492417ec4e7…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

src/network.ts
import { cvm, webrtc } from '@napplet/sdk';
import backend from '../.napplet-space/soy-backend.json';
import { protocol, roomEntry, type Entry } from './room-entry';
export function parseEntry(value: unknown) {
  if (
    !record(value) ||
    typeof value.provider !== 'string' ||
    !/^[a-f0-9]{64}$/.test(value.provider)
  )
    return null;
  return roomEntry(value, value.provider, backend.napplet);
}
export type Room = { room: string; name: string; peers: string[]; capacity: number };
export const titleOf = (room: Room) => room.name.slice(65);
// Ordinary hosts use '|'. A dedicated browser reserves one transport connection.
export const isDedicated = (room: Room) => room.name[64] === ':';
export const playerCount = (room: Room) => room.peers.length - Number(isDedicated(room));
export const playerCapacity = (room: Room) => room.capacity - Number(isDedicated(room));
const ownerOf = (room: Room) => room.name.slice(0, 64);
export type Packet = Record<string, unknown>;
export function record(v: unknown): v is Packet {
  return !!v && typeof v === 'object' && !Array.isArray(v);
}
function validRoom(v: unknown): v is Room {
  return (
    record(v) &&
    typeof v.room === 'string' &&
    v.protocol === protocol &&
    typeof v.name === 'string' &&
    /^[a-f0-9]{64}[|:].{1,15}$/u.test(v.name) &&
    Array.isArray(v.peers) &&
    v.peers.length <= 8 &&
    new Set(v.peers).size === v.peers.length &&
    v.peers.every((p) => typeof p === 'string' && /^[a-f0-9]{64}$/.test(p)) &&
    typeof v.capacity === 'number' &&
    Number.isInteger(v.capacity) &&
    v.capacity >= 2 &&
    v.capacity <= 8 &&
    v.peers.length <= v.capacity
  );
}
async function call(tool: string, args: Record<string, unknown> = {}): Promise<Packet> {
  const result = await cvm.callTool(backend.provider, tool, args);
  if (result.isError)
    throw new Error(
      result.content?.find((c) => c.type === 'text')?.text ?? 'Room service declined the request',
    );
  if (!record(result.structuredContent))
    throw new Error('Room service returned an incomplete response');
  return result.structuredContent;
}
export class Rooms {
  actor = '';
  room: Room | null = null;
  connected = new Set<string>();
  fast = new Set<string>();
  notice = '';
  rtt = 0;
  private ctl = '';
  private state = '';
  private allow = '';
  private generation = 0;
  private timer = 0;
  private polling = false;
  private opening = false;
  private needsRetry = false;
  private subscription?: { close(): void };
  transientInputs = false;
  private pendingState: unknown;
  private sendingState = false;
  private connectSince = 0;
  private pingTime = 0;
  private probe = 0;
  private replies = new Set<string>();
  private measured = new Map<string, { ms: number; at: number }>();
  pingFor(key: string) {
    const sample = this.measured.get(key);
    if (sample && this.connected.has(key) && performance.now() - sample.at < 10000)
      return sample.ms;
    return undefined;
  }
  private dead = false;
  private lastSeen = 0;
  constructor(
    private changed: () => void,
    private receive: (from: string, msg: Packet) => void,
    private ended: (reason: string) => void,
  ) {}
  get host() {
    return !!this.room && this.actor === ownerOf(this.room);
  }
  get owner() {
    return this.room ? ownerOf(this.room) : '';
  }
  get fastReady() {
    return this.connected.size > 0 && [...this.connected].every((k) => this.fast.has(k));
  }
  async list() {
    const r = await call('soy_room_list', { napplet: backend.napplet, protocol });
    return (Array.isArray(r.rooms) ? r.rooms : [])
      .filter(validRoom)
      .filter((r) => r.peers.includes(ownerOf(r)));
  }
  async advertise(
    listing: {
      title: string;
      phase: 'lobby' | 'playing';
      accepting: boolean;
      badges: string[];
    } | null,
  ) {
    if (!this.host || !this.room) throw new Error('Only the host can list a room');
    await call('soy_room_advertise', { room: this.room.room, listing });
  }
  async enter(id: string | null, name: string, entry?: Entry, dedicated = false, listed = true) {
    const session = await call('soy_session');
    if (typeof session.actor !== 'string' || !/^[a-f0-9]{64}$/.test(session.actor))
      throw new Error('No transport identity available');
    // Contact only the configured provider. soyLI may alias it to a disposable
    // key in local previews. Validate its authenticated identity before admission.
    if (
      entry &&
      (session.provider !== entry.provider || !roomEntry(entry, entry.provider, backend.napplet))
    )
      throw new Error('This link belongs to another room service or game.');
    this.actor = session.actor;
    this.dead = false;
    this.needsRetry = false;
    const raw = entry
      ? await call('soy_room_enter', entry)
      : id
        ? await call('soy_room_join', { room: id })
        : await call('soy_room_create', {
            napplet: backend.napplet,
            protocol,
            name: this.actor + (dedicated ? ':' : '|') + name.trim().slice(0, 15),
            capacity: 8,
            listed,
          });
    if (!validRoom(raw) || !raw.peers.includes(this.actor) || !raw.peers.includes(ownerOf(raw))) {
      if (id || entry) await call('soy_room_leave', { room: id ?? entry!.room });
      throw new Error('This is not an active Faultline room.');
    }
    this.room = raw;
    this.notice = '';
    this.lastSeen = performance.now();
    this.changed();
    if (!this.subscription)
      this.subscription = webrtc.onEvent((e) => {
        if (e.sessionId !== this.ctl && e.sessionId !== this.state) return;
        const fast = e.sessionId === this.state;
        if (e.type === 'peer') {
          if (!this.room?.peers.includes(e.pubkey)) return;
          const peers = fast ? this.fast : this.connected;
          if (e.state === 'joined') peers.add(e.pubkey);
          else {
            peers.delete(e.pubkey);
            if (!fast) {
              this.measured.delete(e.pubkey);
              this.replies.delete(e.pubkey);
              if (e.pubkey === this.owner) this.rtt = 0;
            }
          }
          if (!fast && e.state === 'joined') {
            this.notice = '';
            this.lastSeen = performance.now();
          }
          this.changed();
        } else if (
          e.type === 'message' &&
          record(e.payload) &&
          this.room?.peers.includes(e.from) &&
          (this.host || e.from === this.owner)
        ) {
          if (fast && e.payload.t !== (this.host ? 'input' : 'state')) return;
          if (
            e.payload.t === 'probe' &&
            !this.host &&
            typeof e.payload.n === 'number' &&
            Number.isFinite(e.payload.n)
          ) {
            this.send({ t: 'echo', n: e.payload.n });
            return;
          }
          if (e.payload.t === 'echo' && this.host) {
            if (this.probe && e.payload.n === this.probe && this.replies.delete(e.from)) {
              const now = performance.now();
              if (now - this.probe <= 10000)
                this.measured.set(e.from, { ms: Math.round(now - this.probe), at: now });
            }
            return;
          }
          if (
            e.payload.t === 'ping' &&
            this.host &&
            typeof e.payload.n === 'number' &&
            Number.isFinite(e.payload.n)
          ) {
            this.send({ t: 'pong', to: e.from, n: e.payload.n });
            return;
          }
          if (
            e.payload.t === 'pong' &&
            e.payload.to === this.actor &&
            e.payload.n === this.pingTime
          ) {
            this.rtt = Math.round(performance.now() - this.pingTime);
            return;
          }
          this.receive(e.from, e.payload);
        } else if (e.type === 'closed') {
          if (fast) {
            this.state = '';
            this.fast.clear();
          } else {
            this.ctl = '';
            this.connected.clear();
            this.allow = '';
            this.notice = e.reason || 'Peer connection closed';
          }
          this.changed();
        }
      });
    try {
      await this.transport();
    } catch (e) {
      this.notice = String(e);
      this.changed();
    }
    this.timer = window.setInterval(() => void this.poll(), 2600);
  }
  private async transport() {
    const room = this.room;
    if (!room || this.opening || this.needsRetry) return;
    const peers = this.host ? room.peers.filter((p) => p !== this.actor) : [this.owner],
      allow = peers.join(',');
    if (this.allow === allow && (!allow || this.ctl)) return;
    this.opening = true;
    const epoch = this.generation;
    try {
      await this.closeChannels();
      if (!peers.length || epoch !== this.generation) {
        this.allow = '';
        return;
      }
      const scope = { type: 'room' as const, room: room.room, peers };
      const bind = async (fast: boolean) => {
        const req = {
          scope,
          protocol,
          channel: fast ? 'frames' : 'match',
          ...(fast ? { ordered: false, maxRetransmits: 0 } : {}),
        };
        const { session } = await webrtc.open(req);
        const delivery = session as typeof session & { ordered?: boolean; maxRetransmits?: number };
        if (
          epoch !== this.generation ||
          (fast && (delivery.ordered !== false || delivery.maxRetransmits !== 0))
        ) {
          await webrtc.close(session.id, 'Unused channel');
          return;
        }
        if (fast) this.state = session.id;
        else this.ctl = session.id;
      };
      try {
        await bind(false);
      } catch (error) {
        if (epoch === this.generation) this.needsRetry = true;
        throw error;
      }
      if (epoch !== this.generation) return;
      this.allow = allow;
      this.connectSince = performance.now();
      this.notice = '';
      try {
        await bind(true);
      } catch {
        /* Reliable snapshots work when realtime delivery is unavailable. */
      }
    } finally {
      this.opening = false;
      this.changed();
    }
  }
  private async poll() {
    const room = this.room,
      epoch = this.generation;
    if (!room || this.polling) return;
    this.polling = true;
    try {
      const r = await call('soy_room_status', { room: room.room });
      if (epoch !== this.generation) return;
      if (!validRoom(r) || !r.peers.includes(ownerOf(r)))
        throw new Error('The host left this room');
      this.room = r;
      this.lastSeen = performance.now();
      await this.transport();
      if (
        this.ctl &&
        r.peers.length > 1 &&
        this.connected.size === 0 &&
        performance.now() - this.connectSince > 12000
      )
        this.notice = 'Peer connection timed out. Retry or check the host network settings.';
      if (this.host && this.connected.size) {
        this.probe = performance.now();
        this.replies = new Set(this.connected);
        this.send({ t: 'probe', n: this.probe });
      } else if (this.connected.size) {
        this.pingTime = performance.now();
        this.send({ t: 'ping', n: this.pingTime });
      }
      this.changed();
    } catch (e) {
      if (epoch !== this.generation) return;
      const message = e instanceof Error ? e.message : String(e);
      if (
        /expired|host left|join this room/i.test(message) ||
        performance.now() - this.lastSeen > 59000
      ) {
        void this.leave();
        this.ended(message);
      } else {
        this.notice = message;
        this.changed();
      }
    } finally {
      this.polling = false;
    }
  }
  retry() {
    this.needsRetry = false;
    this.allow = '';
    return this.transport();
  }
  send(msg: Packet) {
    if (!this.ctl || !this.connected.size) return;
    void webrtc.send(this.ctl, msg).catch((e) => {
      if (this.room) {
        this.notice = String(e);
        this.changed();
      }
    });
  }
  async snapshot(msg: Packet) {
    if (!this.connected.size) return;
    this.pendingState = msg;
    if (this.sendingState) return;
    this.sendingState = true;
    try {
      while (this.pendingState && this.ctl) {
        const value = this.pendingState;
        this.pendingState = undefined;
        await webrtc.send(this.fastReady ? this.state : this.ctl, value);
      }
    } catch {
      /* A newer full snapshot replaces a dropped or backpressured one. */
    } finally {
      this.sendingState = false;
    }
  }
  private async closeChannels() {
    const ids = [this.ctl, this.state].filter(Boolean);
    this.transientInputs = false;
    this.ctl = this.state = '';
    this.connected.clear();
    this.fast.clear();
    this.replies.clear();
    this.measured.clear();
    this.probe = this.rtt = 0;
    this.pendingState = undefined;
    await Promise.allSettled(ids.map((id) => webrtc.close(id, 'Room membership changed')));
  }
  async leave() {
    const room = this.room;
    this.generation++;
    this.room = null;
    this.dead = true;
    clearInterval(this.timer);
    this.allow = '';
    this.rtt = 0;
    this.notice = '';
    this.subscription?.close();
    this.subscription = undefined;
    await Promise.allSettled([
      this.closeChannels(),
      ...(room ? [call('soy_room_leave', { room: room.room })] : []),
    ]);
    if (this.dead) this.changed();
  }
}