Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

13.9 KB
Raw Blame
/**
 * Lightweight collaborative network diagnostics tracker (EWMA RTT, rolling tx/rx throughput)
 * and fast cached FNV-1a document/tile consistency checksum auditing.
 */

import type { LayerItem } from '../types/editor';
import type {
  CollabDiagnostics,
  CollabIceCandidateType,
  LayerChecksumEntry,
} from '../types/multiplayer';
import type { WireTilePayload } from './collabTileCodec';

const BUCKET_MS = 500;
const BUCKET_COUNT = 4; // 2.0 second rolling window
const PING_EXPIRE_MS = 15_000;
const RTT_EWMA_ALPHA = 0.3;

export const DEFAULT_STATE_AUDIT_INTERVAL_MS = 30_000;
export const DEFAULT_STATE_AUDIT_IDLE_MS = 3_000;
export const DEFAULT_AUDIT_TILE_DIGEST_LIMIT = 128;

interface ThroughputBucket {
  slot: number;
  txBytes: number;
  rxBytes: number;
  txMsgs: number;
  rxMsgs: number;
}

function nowDefault(): number {
  return typeof performance !== 'undefined' && typeof performance.now === 'function'
    ? performance.now()
    : Date.now();
}

export class CollabDiagnosticsTracker {
  private buckets: ThroughputBucket[] = [];
  private totalTxBytes = 0;
  private totalRxBytes = 0;
  private rttMs: number | null = null;
  private lastRttMs: number | null = null;
  private pendingPings = new Map<number, number>();
  private iceCandidateType: CollabIceCandidateType | null = null;
  private lastAuditAt: number | null = null;
  private lastAuditStatus: 'idle' | 'ok' | 'resyncing' = 'idle';
  private auditResyncCount = 0;

  constructor() {
    for (let i = 0; i < BUCKET_COUNT; i++) {
      this.buckets.push({ slot: -1, txBytes: 0, rxBytes: 0, txMsgs: 0, rxMsgs: 0 });
    }
  }

  private getBucket(nowMs: number): ThroughputBucket {
    const slot = Math.floor(nowMs / BUCKET_MS);
    const idx = ((slot % BUCKET_COUNT) + BUCKET_COUNT) % BUCKET_COUNT;
    const bucket = this.buckets[idx];
    if (bucket.slot !== slot) {
      bucket.slot = slot;
      bucket.txBytes = 0;
      bucket.rxBytes = 0;
      bucket.txMsgs = 0;
      bucket.rxMsgs = 0;
    }
    return bucket;
  }

  public recordTx(bytes: number, nowMs: number = nowDefault()): void {
    const safeBytes = Number.isFinite(bytes) && bytes > 0 ? Math.floor(bytes) : 0;
    const b = this.getBucket(nowMs);
    b.txBytes += safeBytes;
    b.txMsgs += 1;
    this.totalTxBytes += safeBytes;
  }

  public recordRx(bytes: number, nowMs: number = nowDefault()): void {
    const safeBytes = Number.isFinite(bytes) && bytes > 0 ? Math.floor(bytes) : 0;
    const b = this.getBucket(nowMs);
    b.rxBytes += safeBytes;
    b.rxMsgs += 1;
    this.totalRxBytes += safeBytes;
  }

  public registerPing(pingId: number, nowMs: number = nowDefault()): void {
    // Prune stale unanswered pings so the map stays tiny
    if (this.pendingPings.size >= 16) {
      for (const [id, sentAt] of this.pendingPings.entries()) {
        if (nowMs - sentAt > PING_EXPIRE_MS) {
          this.pendingPings.delete(id);
        }
      }
      if (this.pendingPings.size >= 32) {
        const oldest = this.pendingPings.keys().next().value;
        if (oldest !== undefined) this.pendingPings.delete(oldest);
      }
    }
    this.pendingPings.set(pingId, nowMs);
  }

  public recordPong(
    pingId: number,
    nowMs: number = nowDefault(),
    fallbackSendMs?: number
  ): number | null {
    const trackedStart = this.pendingPings.get(pingId);
    if (trackedStart !== undefined) {
      this.pendingPings.delete(pingId);
    }
    const startMs = trackedStart ?? fallbackSendMs;
    if (startMs === undefined || !Number.isFinite(startMs)) return null;
    const sample = nowMs - startMs;
    if (!Number.isFinite(sample) || sample < 0 || sample > 60_000) return null;

    this.lastRttMs = sample;
    this.rttMs =
      this.rttMs === null
        ? sample
        : this.rttMs * (1 - RTT_EWMA_ALPHA) + sample * RTT_EWMA_ALPHA;
    return this.rttMs;
  }

  public setIceCandidateType(type: CollabIceCandidateType | null): void {
    this.iceCandidateType = type;
  }

  public recordAuditResult(status: 'ok' | 'resyncing', nowWallMs: number = Date.now()): void {
    this.lastAuditAt = nowWallMs;
    this.lastAuditStatus = status;
    if (status === 'resyncing') {
      this.auditResyncCount += 1;
    }
  }

  public getSnapshot(params: {
    transport: 'ws' | 'webrtc' | null;
    tileQueueDepth: number;
    droppedEphemeralCount: number;
    nowMs?: number;
  }): CollabDiagnostics {
    const nowMs = params.nowMs ?? nowDefault();
    const curSlot = Math.floor(nowMs / BUCKET_MS);
    const minSlot = curSlot - BUCKET_COUNT + 1;

    let txBytes = 0;
    let rxBytes = 0;
    let txMsgs = 0;
    let rxMsgs = 0;

    for (let i = 0; i < BUCKET_COUNT; i++) {
      const b = this.buckets[i];
      if (b.slot >= minSlot && b.slot <= curSlot) {
        txBytes += b.txBytes;
        rxBytes += b.rxBytes;
        txMsgs += b.txMsgs;
        rxMsgs += b.rxMsgs;
      }
    }

    const windowSec = (BUCKET_COUNT * BUCKET_MS) / 1000;
    return {
      rttMs: this.rttMs !== null ? Math.round(this.rttMs * 10) / 10 : null,
      lastRttMs: this.lastRttMs !== null ? Math.round(this.lastRttMs * 10) / 10 : null,
      txBytesPerSec: Math.round(txBytes / windowSec),
      rxBytesPerSec: Math.round(rxBytes / windowSec),
      txMsgsPerSec: Math.round((txMsgs / windowSec) * 10) / 10,
      rxMsgsPerSec: Math.round((rxMsgs / windowSec) * 10) / 10,
      totalTxBytes: this.totalTxBytes,
      totalRxBytes: this.totalRxBytes,
      tileQueueDepth: Math.max(0, Math.floor(params.tileQueueDepth)),
      droppedEphemeralCount: Math.max(0, Math.floor(params.droppedEphemeralCount)),
      transport: params.transport,
      iceCandidateType: params.transport === 'webrtc' ? this.iceCandidateType : null,
      lastAuditAt: this.lastAuditAt,
      lastAuditStatus: this.lastAuditStatus,
      auditResyncCount: this.auditResyncCount,
    };
  }

  public reset(): void {
    for (let i = 0; i < BUCKET_COUNT; i++) {
      this.buckets[i].slot = -1;
      this.buckets[i].txBytes = 0;
      this.buckets[i].rxBytes = 0;
      this.buckets[i].txMsgs = 0;
      this.buckets[i].rxMsgs = 0;
    }
    this.totalTxBytes = 0;
    this.totalRxBytes = 0;
    this.rttMs = null;
    this.lastRttMs = null;
    this.pendingPings.clear();
    this.iceCandidateType = null;
    this.lastAuditAt = null;
    this.lastAuditStatus = 'idle';
    this.auditResyncCount = 0;
  }
}

// --- Fast FNV-1a State Integrity Checksum Auditing ---

const FNV1A_OFFSET = 0x811c9dc5;
const FNV1A_PRIME = 0x01000193;

export function fnv1a32Bytes(bytes: Uint8Array, seed: number = FNV1A_OFFSET): number {
  let h = seed >>> 0;
  const len = bytes.byteLength;
  let i = 0;
  const limit = len - 3;
  while (i < limit) {
    h = Math.imul(h ^ bytes[i], FNV1A_PRIME);
    h = Math.imul(h ^ bytes[i + 1], FNV1A_PRIME);
    h = Math.imul(h ^ bytes[i + 2], FNV1A_PRIME);
    h = Math.imul(h ^ bytes[i + 3], FNV1A_PRIME);
    i += 4;
  }
  while (i < len) {
    h = Math.imul(h ^ bytes[i], FNV1A_PRIME);
    i += 1;
  }
  return h >>> 0;
}

function fnv1a32Str(str: string, seed: number): number {
  let h = seed >>> 0;
  for (let i = 0; i < str.length; i++) {
    const code = str.charCodeAt(i);
    h = Math.imul(h ^ (code & 0xff), FNV1A_PRIME);
    if (code > 0xff) {
      h = Math.imul(h ^ ((code >>> 8) & 0xff), FNV1A_PRIME);
    }
  }
  return h >>> 0;
}

function fnv1a32U32(val: number, seed: number): number {
  let h = seed >>> 0;
  h = Math.imul(h ^ (val & 0xff), FNV1A_PRIME);
  h = Math.imul(h ^ ((val >>> 8) & 0xff), FNV1A_PRIME);
  h = Math.imul(h ^ ((val >>> 16) & 0xff), FNV1A_PRIME);
  h = Math.imul(h ^ ((val >>> 24) & 0xff), FNV1A_PRIME);
  return h >>> 0;
}

export function isTileBufferAllZero(bytes: Uint8Array): boolean {
  const len = bytes.byteLength;
  if ((bytes.byteOffset & 3) === 0 && (len & 3) === 0) {
    const u32 = new Uint32Array(bytes.buffer, bytes.byteOffset, len >>> 2);
    for (let i = 0; i < u32.length; i++) {
      if (u32[i] !== 0) return false;
    }
    return true;
  }
  for (let i = 0; i < len; i++) {
    if (bytes[i] !== 0) return false;
  }
  return true;
}

export interface TileContentHashCacheEntry {
  version: number;
  hash: number;
  empty: boolean;
}

export function computeTileContentHash(
  tile: WireTilePayload,
  cache?: Map<string, TileContentHashCacheEntry>
): { hash: number; empty: boolean } {
  if (!tile.data || tile.data.byteLength === 0) {
    return { hash: 0, empty: true };
  }
  const cacheKey = `${tile.layerId}:${tile.tileX}:${tile.tileY}`;
  if (cache && tile.version > 0) {
    const cached = cache.get(cacheKey);
    if (cached && cached.version === tile.version) {
      return { hash: cached.hash, empty: cached.empty };
    }
  }

  if (isTileBufferAllZero(tile.data)) {
    if (cache && tile.version > 0) {
      cache.set(cacheKey, { version: tile.version, hash: 0, empty: true });
    }
    return { hash: 0, empty: true };
  }

  let h = fnv1a32Str(tile.format, FNV1A_OFFSET);
  h = fnv1a32Bytes(tile.data, h);
  if (cache && tile.version > 0) {
    if (cache.size > 8192) cache.clear();
    cache.set(cacheKey, { version: tile.version, hash: h, empty: false });
  }
  return { hash: h, empty: false };
}

function isLayerEffectivelyVisible(
  layer: LayerItem,
  byId: Map<string, LayerItem>
): boolean {
  let cur: LayerItem | undefined = layer;
  let hops = 0;
  while (cur && hops <= byId.size) {
    if (cur.visible === false) return false;
    if (!cur.parentId) break;
    cur = byId.get(cur.parentId);
    hops += 1;
  }
  return true;
}

export interface DocumentStateChecksum {
  docHash: number;
  layers: LayerChecksumEntry[];
}

/**
 * Builds a deterministic document state checksum from the Rust engine's native
 * FNV-1a hex checksum (`nativeCollabChecksum`) combined with visible layer metadata.
 */
export function buildNativeDocumentStateChecksum(
  layers: ReadonlyArray<LayerItem>,
  nativeDocHashHex: string | null
): DocumentStateChecksum {
  const byId = new Map<string, LayerItem>();
  for (let i = 0; i < layers.length; i++) {
    byId.set(layers[i].id, layers[i]);
  }

  const entries: LayerChecksumEntry[] = [];
  let docHash = nativeDocHashHex ? fnv1a32Str(nativeDocHashHex, FNV1A_OFFSET) : FNV1A_OFFSET;

  for (let i = 0; i < layers.length; i++) {
    const layer = layers[i];
    if (!isLayerEffectivelyVisible(layer, byId)) continue;
    let layerHash = FNV1A_OFFSET;
    layerHash = fnv1a32Str(layer.id, layerHash);
    layerHash = fnv1a32Str(layer.type || 'raster', layerHash);
    layerHash = fnv1a32U32(Math.round((layer.opacity ?? 1) * 1000), layerHash);
    layerHash = fnv1a32Str(layer.blendMode || 'normal', layerHash);
    if (nativeDocHashHex) {
      layerHash = fnv1a32Str(nativeDocHashHex, layerHash);
    }
    entries.push({
      layerId: layer.id,
      hash: layerHash >>> 0,
      tileCount: 0,
    });
    docHash = fnv1a32Str(layer.id, docHash);
    docHash = fnv1a32U32(layerHash, docHash);
  }

  return {
    docHash: docHash >>> 0,
    layers: entries,
  };
}

export interface StateChecksumDiff {
  matches: boolean;
  needsFullDocSync: boolean;
  mismatchedLayerIds: string[];
  mismatchedTileKeys: string[];
}

/**
 * Compares a local guest state checksum against the authoritative host checksum
 * to pinpoint exact missing/diverged layers or individual tile keys.
 */
export function diffStateChecksums(
  local: DocumentStateChecksum,
  remote: DocumentStateChecksum
): StateChecksumDiff {
  if (local.docHash === remote.docHash && local.layers.length === remote.layers.length) {
    return {
      matches: true,
      needsFullDocSync: false,
      mismatchedLayerIds: [],
      mismatchedTileKeys: [],
    };
  }

  const localById = new Map<string, LayerChecksumEntry>();
  for (let i = 0; i < local.layers.length; i++) {
    localById.set(local.layers[i].layerId, local.layers[i]);
  }
  const remoteById = new Map<string, LayerChecksumEntry>();
  for (let i = 0; i < remote.layers.length; i++) {
    remoteById.set(remote.layers[i].layerId, remote.layers[i]);
  }

  // Structural mismatch (missing/extra visible layers or reordered layer list) -> full DOC_SYNC_REQUEST
  if (local.layers.length !== remote.layers.length) {
    return {
      matches: false,
      needsFullDocSync: true,
      mismatchedLayerIds: [],
      mismatchedTileKeys: [],
    };
  }
  for (let i = 0; i < remote.layers.length; i++) {
    if (local.layers[i]?.layerId !== remote.layers[i].layerId) {
      return {
        matches: false,
        needsFullDocSync: true,
        mismatchedLayerIds: [],
        mismatchedTileKeys: [],
      };
    }
  }

  const mismatchedLayerIds: string[] = [];
  const mismatchedTileKeys: string[] = [];

  for (let i = 0; i < remote.layers.length; i++) {
    const r = remote.layers[i];
    const l = localById.get(r.layerId);
    if (!l || l.hash === r.hash) continue;

    if (r.tileDigests && l.tileDigests) {
      const seen = new Set<string>();
      for (const coord of Object.keys(r.tileDigests)) {
        seen.add(coord);
        if (l.tileDigests[coord] !== r.tileDigests[coord]) {
          mismatchedTileKeys.push(`${r.layerId}:${coord}`);
        }
      }
      for (const coord of Object.keys(l.tileDigests)) {
        if (!seen.has(coord)) {
          // Local guest has an extra phantom tile absent on host -> request tombstone
          mismatchedTileKeys.push(`${r.layerId}:${coord}`);
        }
      }
      // If tile hashes all matched but layer metadata (opacity/blendMode) differed, resync doc
      if (mismatchedTileKeys.length === 0) {
        return {
          matches: false,
          needsFullDocSync: true,
          mismatchedLayerIds: [],
          mismatchedTileKeys: [],
        };
      }
    } else if (r.tileDigests && l.tileCount === 0) {
      for (const coord of Object.keys(r.tileDigests)) {
        mismatchedTileKeys.push(`${r.layerId}:${coord}`);
      }
    } else if (l.tileDigests && r.tileCount === 0) {
      for (const coord of Object.keys(l.tileDigests)) {
        mismatchedTileKeys.push(`${r.layerId}:${coord}`);
      }
    } else {
      mismatchedLayerIds.push(r.layerId);
    }
  }

  const matches = mismatchedLayerIds.length === 0 && mismatchedTileKeys.length === 0;
  return {
    matches,
    needsFullDocSync: false,
    mismatchedLayerIds,
    mismatchedTileKeys,
  };
}