Skip to content

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

8.7 KB
Raw Blame
import { describe, it, expect, afterEach, vi } from 'vitest';
import {
  computeCrc32,
  formatWalFrame,
  parseWalFrames,
  WAL_ENTRY_STROKE_TILE_DELTA,
  WAL_ENTRY_VECTOR_STROKE,
  WAL_ENTRY_LAYER_MUTATION,
  recoveryService,
  RecoveryReplayData,
  packRecoveryCheckpointPayload,
  unpackRecoveryCheckpointPayload,
  encodeRecoveryReplayData,
  decodeRecoveryReplayData,
} from '../../services/recoveryService';

describe('Crash Recovery & WAL Architecture Engine', () => {
  describe('CRC32 & Binary Framing Headers', () => {
    it('computes standard IEEE 802.3 CRC32 checksums accurately', () => {
      const testVec = new TextEncoder().encode('123456789');
      const crc = computeCrc32(testVec);
      expect(crc).toBe(0xcbf43926);

      const emptyVec = new Uint8Array(0);
      expect(computeCrc32(emptyVec)).toBe(0x00000000);

      const simple = new Uint8Array([1, 2, 3, 4]);
      expect(computeCrc32(simple)).toBeGreaterThan(0);
    });

    it('serializes WAL frames with atomic 13-byte headers', () => {
      const payload = new Uint8Array([10, 20, 30, 40, 50]);
      const frame = formatWalFrame(WAL_ENTRY_STROKE_TILE_DELTA, payload);

      expect(frame.length).toBe(18);
      expect(frame[0]).toBe(0x49);
      expect(frame[1]).toBe(0x4e);
      expect(frame[2]).toBe(0x4b);
      expect(frame[3]).toBe(0x57);
      expect(frame[4]).toBe(WAL_ENTRY_STROKE_TILE_DELTA);

      const view = new DataView(frame.buffer, frame.byteOffset, frame.byteLength);
      expect(view.getUint32(5, true)).toBe(5);
      expect(view.getUint32(9, true)).toBe(computeCrc32(payload));
      expect(Array.from(frame.subarray(13))).toEqual([10, 20, 30, 40, 50]);
    });

    it('deserializes multiple contiguous valid WAL frames', () => {
      const p1 = new Uint8Array([1, 2, 3]);
      const p2 = new Uint8Array([4, 5, 6, 7]);
      const p3 = new Uint8Array([8, 9]);

      const f1 = formatWalFrame(WAL_ENTRY_STROKE_TILE_DELTA, p1);
      const f2 = formatWalFrame(WAL_ENTRY_VECTOR_STROKE, p2);
      const f3 = formatWalFrame(WAL_ENTRY_LAYER_MUTATION, p3);

      const combined = new Uint8Array(f1.length + f2.length + f3.length);
      combined.set(f1, 0);
      combined.set(f2, f1.length);
      combined.set(f3, f1.length + f2.length);

      const { validFrames, corruptedTail } = parseWalFrames(combined);
      expect(corruptedTail).toBe(false);
      expect(validFrames.length).toBe(3);
      expect(validFrames[0].entryType).toBe(WAL_ENTRY_STROKE_TILE_DELTA);
      expect(Array.from(validFrames[0].payload)).toEqual([1, 2, 3]);
      expect(validFrames[1].entryType).toBe(WAL_ENTRY_VECTOR_STROKE);
      expect(Array.from(validFrames[1].payload)).toEqual([4, 5, 6, 7]);
      expect(validFrames[2].entryType).toBe(WAL_ENTRY_LAYER_MUTATION);
      expect(Array.from(validFrames[2].payload)).toEqual([8, 9]);
    });

    it('safely discards incomplete tail chunks caused by crash mid-write', () => {
      const f1 = formatWalFrame(WAL_ENTRY_STROKE_TILE_DELTA, new Uint8Array([10, 20, 30]));
      const f2 = formatWalFrame(WAL_ENTRY_VECTOR_STROKE, new Uint8Array([40, 50, 60, 70, 80]));
      const truncatedF2 = f2.subarray(0, 15);

      const combined = new Uint8Array(f1.length + truncatedF2.length);
      combined.set(f1, 0);
      combined.set(truncatedF2, f1.length);

      const { validFrames, corruptedTail } = parseWalFrames(combined);
      expect(validFrames.length).toBe(1);
      expect(validFrames[0].entryType).toBe(WAL_ENTRY_STROKE_TILE_DELTA);
      expect(Array.from(validFrames[0].payload)).toEqual([10, 20, 30]);
      expect(corruptedTail).toBe(true);
    });

    it('safely detects and discards corrupted tail chunk with CRC32 mismatch', () => {
      const f1 = formatWalFrame(WAL_ENTRY_STROKE_TILE_DELTA, new Uint8Array([100, 101, 102]));
      const f2 = formatWalFrame(WAL_ENTRY_STROKE_TILE_DELTA, new Uint8Array([200, 201, 202, 203]));
      f2[14] = 99;

      const combined = new Uint8Array(f1.length + f2.length);
      combined.set(f1, 0);
      combined.set(f2, f1.length);

      const { validFrames, corruptedTail } = parseWalFrames(combined);
      expect(validFrames.length).toBe(1);
      expect(Array.from(validFrames[0].payload)).toEqual([100, 101, 102]);
      expect(corruptedTail).toBe(true);
    });
  });

  describe('Binary IPC Framing for Checkpoints and Session Replay', () => {
    it('packs and unpacks checkpoint binary frames losslessly', () => {
      const manifest = JSON.stringify({ documentName: 'Page 1', width: 2480 });
      const snapshot = new Uint8Array([1, 2, 3, 250, 255]);
      const thumb = new Uint8Array([0x89, 0x50, 0x4e, 0x47]);

      const packed = packRecoveryCheckpointPayload(manifest, snapshot, thumb);
      const unpacked = unpackRecoveryCheckpointPayload(packed);

      expect(unpacked.manifestJson).toBe(manifest);
      expect(Array.from(unpacked.baseSnapshot)).toEqual([1, 2, 3, 250, 255]);
      expect(Array.from(unpacked.thumbnailPng)).toEqual([0x89, 0x50, 0x4e, 0x47]);
      expect(() => unpackRecoveryCheckpointPayload(packed.subarray(0, packed.length - 1))).toThrow();
    });

    it('encodes and decodes INKR binary replay responses without JSON byte arrays', () => {
      const replay: RecoveryReplayData = {
        session_id: 'sess-bin-1',
        manifest_json: '{"width":1024}',
        base_snapshot: new Uint8Array([10, 20, 30]),
        wal_entries: [
          { entry_type: WAL_ENTRY_STROKE_TILE_DELTA, payload: new Uint8Array([1, 2, 3, 4]) },
          { entry_type: WAL_ENTRY_LAYER_MUTATION, payload: new Uint8Array([99]) },
        ],
      };

      const encoded = encodeRecoveryReplayData(replay);
      const decoded = decodeRecoveryReplayData(encoded.buffer as ArrayBuffer);

      expect(decoded.session_id).toBe('sess-bin-1');
      expect(decoded.manifest_json).toBe('{"width":1024}');
      expect(decoded.base_snapshot).toBeInstanceOf(Uint8Array);
      expect(Array.from(decoded.base_snapshot as Uint8Array)).toEqual([10, 20, 30]);
      expect(decoded.wal_entries).toHaveLength(2);
      expect(decoded.wal_entries[0].entry_type).toBe(WAL_ENTRY_STROKE_TILE_DELTA);
      expect(Array.from(decoded.wal_entries[0].payload as Uint8Array)).toEqual([1, 2, 3, 4]);
      expect(decoded.wal_entries[1].entry_type).toBe(WAL_ENTRY_LAYER_MUTATION);
      expect(Array.from(decoded.wal_entries[1].payload as Uint8Array)).toEqual([99]);

      const emptySnapEncoded = encodeRecoveryReplayData({
        session_id: 'sess-empty',
        manifest_json: '{}',
        base_snapshot: null,
        wal_entries: [],
      });
      const emptySnapDecoded = decodeRecoveryReplayData(emptySnapEncoded);
      expect(emptySnapDecoded.base_snapshot).toBeNull();
      expect(emptySnapDecoded.wal_entries).toEqual([]);
    });
  });

  describe('discardAllCrashedSessions', () => {
    const prevWindow = (globalThis as Record<string, unknown>).window;

    afterEach(() => {
      (globalThis as Record<string, unknown>).window = prevWindow;
      vi.restoreAllMocks();
    });

    it('deduplicates and discards all sessions in non-Tauri environments', async () => {
      (globalThis as Record<string, unknown>).window = {};
      const result = await recoveryService.discardAllCrashedSessions([
        'sess-a',
        'sess-b',
        'sess-a',
        '',
      ]);
      expect(result).toEqual({
        discardedIds: ['sess-a', 'sess-b'],
        failedIds: [],
      });
    });

    it('invokes recovery_close_session for every unique session and reports partial failures cleanly', async () => {
      (globalThis as Record<string, unknown>).window = { __TAURI_INTERNALS__: {} };
      const mockInvoke = vi.fn(async (_cmd: string, args?: { sessionId?: string }) => {
        if (args?.sessionId === 'sess-fail') {
          throw new Error('disk locked');
        }
      });
      const serviceAny = recoveryService as unknown as {
        invokePromise: Promise<typeof mockInvoke> | null;
      };
      const prevInvokePromise = serviceAny.invokePromise;
      serviceAny.invokePromise = Promise.resolve(mockInvoke);

      try {
        const result = await recoveryService.discardAllCrashedSessions([
          'sess-1',
          'sess-fail',
          'sess-2',
          'sess-1',
        ]);

        expect(mockInvoke).toHaveBeenCalledTimes(3);
        expect(mockInvoke).toHaveBeenNthCalledWith(1, 'recovery_close_session', {
          sessionId: 'sess-1',
        });
        expect(mockInvoke).toHaveBeenNthCalledWith(2, 'recovery_close_session', {
          sessionId: 'sess-fail',
        });
        expect(mockInvoke).toHaveBeenNthCalledWith(3, 'recovery_close_session', {
          sessionId: 'sess-2',
        });
        expect(result).toEqual({
          discardedIds: ['sess-1', 'sess-2'],
          failedIds: ['sess-fail'],
        });
      } finally {
        serviceAny.invokePromise = prevInvokePromise;
      }
    });
  });
});