app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

deliver-listing.spec.ts (10869B)


      1 import { expect, test } from '@playwright/test';
      2 import { build } from 'vite';
      3 import { fileURLToPath } from 'node:url';
      4 import { once } from 'node:events';
      5 import { WebSocketServer } from 'ws';
      6 import { createStaticHarness } from '../integration/harness/static.ts';
      7 import type * as Fixture from './harness/deliver-listing.ts';
      8 declare global {
      9   interface Window {
     10     hcp112: typeof Fixture;
     11     hcp112Fixture: Awaited<ReturnType<typeof Fixture.createFixture>>;
     12   }
     13 }
     14 let server: Awaited<ReturnType<typeof createStaticHarness>>,
     15   sockets: WebSocketServer,
     16   bundle: string,
     17   endpoint: string;
     18 let frames: unknown[][] = [],
     19   stored: Record<string, unknown> | undefined,
     20   response: 'accepted' | 'refused' | 'timeout-refusal' | 'silent' = 'accepted',
     21   readback: 'exact' | 'different' | 'invalid' | 'missing' = 'exact';
     22 test.beforeAll(async () => {
     23   server = await createStaticHarness();
     24   sockets = new WebSocketServer({
     25     host: '127.0.0.1',
     26     port: 0,
     27     maxPayload: 262144
     28   });
     29   await once(sockets, 'listening');
     30   const address = sockets.address();
     31   if (!address || typeof address === 'string')
     32     throw Error('loopback unavailable');
     33   endpoint = 'ws://127.0.0.1:' + address.port;
     34   sockets.on('connection', (socket) => {
     35     socket.on('message', (bytes) => {
     36       const raw = Buffer.isBuffer(bytes)
     37         ? bytes.toString()
     38         : Array.isArray(bytes)
     39           ? Buffer.concat(bytes).toString()
     40           : Buffer.from(bytes).toString();
     41       const frame = JSON.parse(raw) as unknown[];
     42       frames.push(frame);
     43       if (frame[0] === 'EVENT') {
     44         stored = frame[1] as Record<string, unknown>;
     45         if (response === 'silent') return;
     46         socket.send(
     47           JSON.stringify([
     48             'OK',
     49             stored.id,
     50             response === 'accepted',
     51             response === 'accepted'
     52               ? ''
     53               : response === 'timeout-refusal'
     54                 ? 'Timeout'
     55                 : 'blocked: controlled refusal'
     56           ])
     57         );
     58       } else if (frame[0] === 'REQ') {
     59         if (stored && readback !== 'missing') {
     60           const event =
     61             readback === 'exact'
     62               ? stored
     63               : {
     64                   ...stored,
     65                   ...(readback === 'different'
     66                     ? { id: '0'.repeat(64) }
     67                     : { sig: '0'.repeat(128) })
     68                 };
     69           socket.send(JSON.stringify(['EVENT', frame[1], event]));
     70         }
     71         socket.send(JSON.stringify(['EOSE', frame[1]]));
     72       }
     73     });
     74   });
     75   const built = await build({
     76     configFile: false,
     77     logLevel: 'silent',
     78     build: {
     79       write: false,
     80       minify: false,
     81       lib: {
     82         entry: fileURLToPath(
     83           new URL('./harness/deliver-listing.ts', import.meta.url)
     84         ),
     85         name: 'hcp112',
     86         formats: ['iife']
     87       }
     88     }
     89   });
     90   const output = Array.isArray(built) ? built[0] : built;
     91   if (!('output' in output)) throw Error('fixture bundle unavailable');
     92   const chunks = output.output.filter((row) => row.type === 'chunk');
     93   expect(chunks).toHaveLength(1);
     94   bundle = chunks[0].code;
     95 });
     96 test.afterAll(async () => {
     97   for (const socket of sockets.clients) socket.terminate();
     98   await new Promise<void>((resolve) => sockets.close(() => resolve()));
     99   await server.close();
    100 });
    101 test.beforeEach(async ({ page }) => {
    102   frames = [];
    103   stored = undefined;
    104   response = 'accepted';
    105   readback = 'exact';
    106   await page.addInitScript(
    107     ({ endpoint }) => {
    108       const Native = window.WebSocket;
    109       class LoopbackSocket extends Native {
    110         constructor(url: string | URL, protocols?: string | string[]) {
    111           if (String(url) !== 'wss://discovery.example.org/')
    112             throw Error('unfrozen destination');
    113           super(endpoint, protocols);
    114         }
    115       }
    116       window.WebSocket = LoopbackSocket;
    117     },
    118     { endpoint }
    119   );
    120   await page.goto(server.url + '/search');
    121   await page.addScriptTag({ content: bundle });
    122   await page.evaluate(async () => {
    123     window.hcp112Fixture = await window.hcp112.createFixture();
    124   });
    125 });
    126 test.afterEach(async ({ page }) => {
    127   if (!page.isClosed())
    128     await page.evaluate(() => window.hcp112Fixture?.close());
    129 });
    130 test('HCP112 actual durable signed listing precedes SDK EVENT and acceptance stays separate from exact loopback readback', async ({
    131   page
    132 }) => {
    133   const r = await page.evaluate(() => window.hcp112Fixture.run());
    134   expect(r.result.status).toBe('completed');
    135   expect(r.same).toBe(true);
    136   expect(r.signs).toBe(1);
    137   expect(r.trace.indexOf('ack:2')).toBeGreaterThan(-1);
    138   expect(r.trace.indexOf('EVENT')).toBeGreaterThan(r.trace.indexOf('ack:2'));
    139   expect(r.originalCapture).toBe(true);
    140   expect(r.row.receipts).toHaveLength(2);
    141   expect(r.row.receipts[0].status).toBe('accepted');
    142   expect(r.row.receipts[0].readbackWire).toBeNull();
    143   expect(r.row.receipts[1].readbackWire).toBe(r.row.artifact?.wire);
    144   const events = frames.filter((frame) => frame[0] === 'EVENT');
    145   expect(events).toHaveLength(1);
    146   expect(events[0][1]).toEqual(JSON.parse(r.row.artifact!.wire));
    147   const requests = frames.filter((frame) => frame[0] === 'REQ');
    148   expect(requests).toHaveLength(1);
    149   expect(requests[0][2]).toEqual({
    150     ids: [r.row.artifact!.eventId],
    151     authors: [r.owner],
    152     kinds: [30402],
    153     limit: 1
    154   });
    155 });
    156 for (const mode of ['different', 'invalid', 'missing'] as const)
    157   test(`HCP112 ${mode} loopback event cannot replace exact-ID signed readback`, async ({
    158     page
    159   }) => {
    160     readback = mode;
    161     const r = await page.evaluate(() => window.hcp112Fixture.run());
    162     expect(r.row.receipts).toHaveLength(1);
    163     expect(r.row.receipts[0].status).toBe('accepted');
    164     expect(r.row.receipts[0].readbackWire).toBeNull();
    165     expect(frames.filter((frame) => frame[0] === 'EVENT')).toHaveLength(1);
    166     expect(frames.filter((frame) => frame[0] === 'REQ')).toHaveLength(1);
    167   });
    168 for (const mode of ['refused', 'timeout-refusal'] as const)
    169   test(`HCP112 actual ${mode} is retained without spinning or fabricating a retryable deadline`, async ({
    170     page
    171   }) => {
    172     response = mode;
    173     const r = await page.evaluate(() => window.hcp112Fixture.run());
    174     expect(r.result.status).toBe('needs_action');
    175     expect(r.row.receipts).toHaveLength(1);
    176     expect(r.row.receipts[0].status).toBe(
    177       mode === 'refused' ? 'refused' : 'unknown'
    178     );
    179     expect(r.row.receipts[0].readbackWire).toBeNull();
    180     expect(frames.filter((frame) => frame[0] === 'EVENT')).toHaveLength(1);
    181     expect(frames.filter((frame) => frame[0] === 'REQ')).toHaveLength(0);
    182   });
    183 for (const mode of ['logout', 'stop', 'changeKey'] as const)
    184   test(`HCP112 original ${mode} revokes the final effect without changing the artifact`, async ({
    185     page
    186   }) => {
    187     const r = await page.evaluate(async (mode) => {
    188       const f = window.hcp112Fixture;
    189       f[mode]();
    190       return await f.run();
    191     }, mode);
    192     expect(r.result.status).not.toBe('completed');
    193     expect(r.row.receipts).toHaveLength(0);
    194     expect(r.signs).toBe(1);
    195     expect(frames.filter((frame) => frame[0] === 'EVENT')).toHaveLength(0);
    196   });
    197 test('HCP112 detached publication snapshot cannot borrow final delivery ownership', async ({
    198   page
    199 }) => {
    200   const r = await page.evaluate(() => window.hcp112Fixture.copied());
    201   expect(r.status).toBe('invalid');
    202   expect(frames).toHaveLength(0);
    203 });
    204 test('HCP112 actual original lease refuses a foreign target and changed policy without a relay effect', async ({
    205   page
    206 }) => {
    207   const r = await page.evaluate(async () => {
    208     const f = window.hcp112Fixture;
    209     return { foreign: await f.foreignTarget(), changed: await f.retargeted() };
    210   });
    211   expect(r.foreign).toEqual({ status: 'completed', value: false });
    212   expect(r.changed).toEqual({ status: 'invalid' });
    213   expect(frames).toHaveLength(0);
    214 });
    215 test('HCP112 actual cached signed event is not an exact relay readback receipt', async ({
    216   page
    217 }) => {
    218   readback = 'missing';
    219   const r = await page.evaluate(async () => {
    220     const f = window.hcp112Fixture,
    221       cachedId = await f.cacheArtifact();
    222     return { cachedId, ...(await f.run()) };
    223   });
    224   expect(r.cachedId.id).toBe(r.row.artifact?.eventId);
    225   expect(r.cachedId.seen).toEqual([
    226     'wss://discovery.example.org',
    227     'wss://other.example.org'
    228   ]);
    229   expect(r.row.receipts).toHaveLength(1);
    230   expect(r.row.receipts[0].status).toBe('accepted');
    231   expect(r.row.receipts[0].readbackWire).toBeNull();
    232   expect(frames.filter((frame) => frame[0] === 'REQ')).toHaveLength(1);
    233 });
    234 test('HCP112 actual silent relay deadlines retain three bounded timed-out attempts without a new signature', async ({
    235   page
    236 }) => {
    237   response = 'silent';
    238   readback = 'missing';
    239   const r = await page.evaluate(() => window.hcp112Fixture.run());
    240   expect(r.result.status).toBe('needs_action');
    241   expect(r.signs).toBe(1);
    242   expect(r.row.receipts.map((fact) => fact.status)).toEqual([
    243     'timed_out',
    244     'timed_out',
    245     'timed_out'
    246   ]);
    247   expect(r.row.receipts.map((fact) => fact.attempt)).toEqual([1, 2, 3]);
    248   expect(new Set(r.row.receipts.map((fact) => fact.actionId)).size).toBe(1);
    249   expect(frames.filter((frame) => frame[0] === 'EVENT')).toHaveLength(3);
    250   expect(
    251     new Set(
    252       frames
    253         .filter((frame) => frame[0] === 'EVENT')
    254         .map((frame) => JSON.stringify(frame[1]))
    255     ).size
    256   ).toBe(1);
    257 });
    258 test('HCP112 logout after the actual EVENT retains a stopped observation and schedules no dependent readback', async ({
    259   page
    260 }) => {
    261   response = 'silent';
    262   const run = page.evaluate(() => window.hcp112Fixture.run());
    263   await expect
    264     .poll(() => frames.filter((frame) => frame[0] === 'EVENT').length)
    265     .toBe(1);
    266   await page.evaluate(() => window.hcp112Fixture.logout());
    267   const r = await run;
    268   expect(r.result.status).toBe('stopped');
    269   expect(r.row.receipts).toHaveLength(1);
    270   expect(r.row.receipts[0].status).toBe('stopped');
    271   expect(r.row.receipts[0].readbackWire).toBeNull();
    272   expect(frames.filter((frame) => frame[0] === 'REQ')).toHaveLength(0);
    273 });
    274 for (const unknown of [false, true])
    275   test(`HCP112 actual receipt write unknown=${unknown} is reconciled before dependent readback`, async ({
    276     page
    277   }) => {
    278     const r = await page.evaluate(
    279       (unknown) => window.hcp112Fixture.receiptFault(unknown),
    280       unknown
    281     );
    282     expect(r.signs).toBe(1);
    283     expect(r.faultPuts).toBe(1);
    284     expect(frames.filter((frame) => frame[0] === 'EVENT')).toHaveLength(1);
    285     if (unknown) {
    286       expect(r.result.status).toBe('completed');
    287       expect(r.row.receipts).toHaveLength(2);
    288       expect(r.row.receipts[1].readbackWire).toBe(r.row.artifact?.wire);
    289       expect(frames.filter((frame) => frame[0] === 'REQ')).toHaveLength(1);
    290     } else {
    291       expect(r.result.status).toBe('storage_failed');
    292       expect(r.row.receipts).toHaveLength(0);
    293       expect(frames.filter((frame) => frame[0] === 'REQ')).toHaveLength(0);
    294     }
    295   });