app

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

private-send-reservations.spec.ts (18383B)


      1 import { expect, test, type Page } from '@playwright/test';
      2 import { build } from 'vite';
      3 import { fileURLToPath } from 'node:url';
      4 import { createHash } from 'node:crypto';
      5 import { createStaticHarness } from '../integration/harness/static.ts';
      6 import type * as Reservations from './harness/private-send-reservations.ts';
      7 import type { RumorPlan } from '../../src/lib/messaging/rumor-plan.ts';
      8 declare global {
      9   interface Window {
     10     hcp074: typeof Reservations;
     11     hcp074Fixture: Awaited<ReturnType<typeof Reservations.makeFixture>>;
     12     hcp074Plan: RumorPlan;
     13     hcp074Release: () => void;
     14     hcp074Held: Promise<unknown>;
     15   }
     16 }
     17 let server: Awaited<ReturnType<typeof createStaticHarness>>, bundle: string;
     18 test.beforeAll(async () => {
     19   server = await createStaticHarness();
     20   const result = await build({
     21     configFile: false,
     22     logLevel: 'silent',
     23     build: {
     24       write: false,
     25       minify: false,
     26       lib: {
     27         entry: fileURLToPath(
     28           new URL('./harness/private-send-reservations.ts', import.meta.url)
     29         ),
     30         name: 'hcp074',
     31         formats: ['iife']
     32       }
     33     }
     34   });
     35   const output = Array.isArray(result) ? result[0] : result;
     36   if (!('output' in output)) throw Error('missing bundle');
     37   const chunks = output.output.filter((item) => item.type === 'chunk');
     38   expect(chunks).toHaveLength(1);
     39   bundle = chunks[0].code;
     40   console.log(
     41     JSON.stringify({
     42       fixture: 'HCP074_ACTUAL_OWNER_LOCKS_IDB_RESERVATIONS',
     43       bundleSha256: createHash('sha256').update(bundle).digest('hex'),
     44       moduleIds: Object.keys(chunks[0].modules),
     45       qualification:
     46         'Controlled local Chromium clock/provider; not actual operator/installed extension/real clock qualification'
     47     })
     48   );
     49 });
     50 test.afterAll(async () => server.close());
     51 async function load(
     52   page: Page,
     53   shared?: Reservations.Shared,
     54   clock: 'controlled' | 'real' = 'controlled'
     55 ) {
     56   await page.goto(server.url + '/search');
     57   await page.addScriptTag({ content: bundle });
     58   return page.evaluate(
     59     async ({ shared, clock }) => {
     60       window.hcp074Fixture = await window.hcp074.makeFixture(shared, clock);
     61       window.hcp074Plan = window.hcp074Fixture.plan();
     62       return window.hcp074Fixture.shared();
     63     },
     64     { shared, clock }
     65   );
     66 }
     67 test('one command retries the identical rumor and stores only bounded metadata', async ({
     68   page
     69 }) => {
     70   await load(page);
     71   const result = await page.evaluate(async () => {
     72     const s = window.hcp074,
     73       f = window.hcp074Fixture,
     74       before = f.counts();
     75     const first = await f.reserve(s.command, window.hcp074Plan),
     76       retry = await f.reserve(s.command, window.hcp074Plan);
     77     const metadata =
     78       first.status === 'reserved'
     79         ? s.reservedSendSnapshot(first.identity)
     80         : undefined;
     81     const wire =
     82       first.status === 'reserved'
     83         ? s.reservedSendRumorWire(first.identity)
     84         : undefined;
     85     const rows = await f.rows();
     86     return {
     87       first: first.status,
     88       retry: retry.status,
     89       metadata,
     90       wirePresent: typeof wire === 'string',
     91       stored: JSON.stringify(rows),
     92       counts: f.counts(),
     93       before
     94     };
     95   });
     96   expect(result.first).toBe('reserved');
     97   expect(result.retry).toBe('existing');
     98   expect(result.wirePresent).toBe(true);
     99   expect(result.stored).not.toContain('Private reservation sentinel');
    100   expect(result.stored).not.toContain('Carrots');
    101   expect(result.stored).not.toContain('nostr:');
    102   expect(result.stored).not.toContain('"content"');
    103   expect(result.counts).toEqual(result.before);
    104   expect(result.metadata?.id).toBe('12345678-1234-4234-8234-123456789abc');
    105 });
    106 test('changed same command conflicts and distinct same-second identical intent cannot merge', async ({
    107   page
    108 }) => {
    109   await load(page);
    110   const result = await page.evaluate(async () => {
    111     const f = window.hcp074Fixture,
    112       s = window.hcp074;
    113     await f.reserve(s.command, window.hcp074Plan);
    114     const changed = await f.reserve(s.command, f.plan('Different body'));
    115     const collision = await f.reserve(
    116       '12345678-1234-4234-8234-123456789abd',
    117       f.plan()
    118     );
    119     return {
    120       changed: changed.status,
    121       collision: collision.status,
    122       count: (await f.rows()).length
    123     };
    124   });
    125   expect(result).toEqual({
    126     changed: 'conflict',
    127     collision: 'clock_conflict',
    128     count: 1
    129   });
    130 });
    131 test('actual observed clock progress permits a distinct intent without future timestamp or custom tags', async ({
    132   page
    133 }) => {
    134   await load(page);
    135   const result = await page.evaluate(async () => {
    136     const s = window.hcp074,
    137       f = window.hcp074Fixture,
    138       original = f.shared().milliseconds;
    139     const first = await f.reserve(s.command, window.hcp074Plan);
    140     f.setTime(original + 1000);
    141     const nextPlan = f.plan();
    142     const next = await f.reserve(
    143       '12345678-1234-4234-8234-123456789abd',
    144       nextPlan
    145     );
    146     if (first.status !== 'reserved' || next.status !== 'reserved')
    147       throw Error('expected source reservations');
    148     const a = s.reservedSendSnapshot(first.identity)!,
    149       b = s.reservedSendSnapshot(next.identity)!;
    150     const wire = JSON.parse(s.reservedSendRumorWire(next.identity)!) as {
    151       created_at: number;
    152       tags: string[][];
    153     };
    154     const retry = await f.reserve(s.command, window.hcp074Plan);
    155     return {
    156       different: a.rumorHash !== b.rumorHash,
    157       observed: wire.created_at === Math.floor(Date.now() / 1000),
    158       pOnly: wire.tags.length === 1 && wire.tags[0][0] === 'p',
    159       retry: retry.status,
    160       count: (await f.rows()).length
    161     };
    162   });
    163   expect(result).toEqual({
    164     different: true,
    165     observed: true,
    166     pOnly: true,
    167     retry: 'existing',
    168     count: 2
    169   });
    170 });
    171 test('future clock is rejected and an old provisional plan binds the actual reservation second', async ({
    172   page
    173 }) => {
    174   await load(page);
    175   const result = await page.evaluate(async () => {
    176     const f = window.hcp074Fixture,
    177       seconds = Math.floor(Date.now() / 1000);
    178     const future = await f.reserve(
    179       window.hcp074.command,
    180       f.plan('Future', seconds + 1)
    181     );
    182     const stale = await f.reserve(
    183       window.hcp074.command,
    184       f.plan('Stale', seconds - 1)
    185     );
    186     return {
    187       future: future.status,
    188       stale: stale.status,
    189       count: (await f.rows()).length
    190     };
    191   });
    192   expect(result).toEqual({
    193     future: 'clock_conflict',
    194     stale: 'reserved',
    195     count: 1
    196   });
    197 });
    198 test('two tabs share owner CAS and only one distinct identical intent can reserve', async ({
    199   page,
    200   context
    201 }) => {
    202   const shared = await load(page),
    203     second = await context.newPage();
    204   await load(second, shared);
    205   const [a, b] = await Promise.all([
    206     page.evaluate(
    207       async () =>
    208         (
    209           await window.hcp074Fixture.reserve(
    210             window.hcp074.command,
    211             window.hcp074Plan
    212           )
    213         ).status
    214     ),
    215     second.evaluate(
    216       async () =>
    217         (
    218           await window.hcp074Fixture.reserve(
    219             '12345678-1234-4234-8234-123456789abd',
    220             window.hcp074Plan
    221           )
    222         ).status
    223     )
    224   ]);
    225   expect([a, b].filter((status) => status === 'reserved')).toHaveLength(1);
    226   expect(
    227     [a, b].filter((status) => status === 'busy' || status === 'clock_conflict')
    228   ).toHaveLength(1);
    229   expect(
    230     await page.evaluate(async () => (await window.hcp074Fixture.rows()).length)
    231   ).toBe(1);
    232 });
    233 test('concurrent calls on one genuine plan keep a busy loser protected after the winner binds', async ({
    234   page
    235 }) => {
    236   await load(page);
    237   const result = await page.evaluate(async () => {
    238     const manager = navigator.locks,
    239       original = Reflect.get<LockManager, 'request'>(manager, 'request');
    240     let release = () => {},
    241       entered = () => {};
    242     const held = new Promise<void>((resolve) => {
    243       release = resolve;
    244     });
    245     const committed = new Promise<void>((resolve) => {
    246       entered = resolve;
    247     });
    248     manager.request = (...args: unknown[]) => {
    249       const index = args.length - 1,
    250         callback = args[index] as (lock: Lock | null) => Promise<unknown>;
    251       const forwarded = args.slice();
    252       forwarded[index] = async (lock: Lock | null) => {
    253         const value = await callback(lock);
    254         if (lock) {
    255           entered();
    256           await held;
    257         }
    258         return value;
    259       };
    260       return Reflect.apply(original, manager, forwarded) as Promise<unknown>;
    261     };
    262     try {
    263       const f = window.hcp074Fixture,
    264         s = window.hcp074;
    265       // Both calls enter the boundary before the actual first lock callback.
    266       const winner = f.reserve(s.command, window.hcp074Plan),
    267         loser = f.reserve(s.command, window.hcp074Plan);
    268       const refused = await loser;
    269       await committed;
    270       const rows = await f.rows();
    271       release();
    272       const accepted = await winner;
    273       return { accepted: accepted.status, refused, count: rows.length };
    274     } finally {
    275       release();
    276       manager.request = original;
    277     }
    278   });
    279   expect(result).toEqual({
    280     accepted: 'reserved',
    281     refused: { status: 'busy', disposition: 'may_exist' },
    282     count: 1
    283   });
    284 });
    285 
    286 test('stopping a fresh original before its real owner callback proves no attempt and permits a new draft', async ({
    287   page
    288 }) => {
    289   await load(page);
    290   const result = await page.evaluate(async () => {
    291     const f = window.hcp074Fixture,
    292       s = window.hcp074,
    293       before = f.counts(),
    294       manager = navigator.locks,
    295       original = Reflect.get<LockManager, 'request'>(manager, 'request');
    296     manager.request = (...args: unknown[]) => {
    297       const index = args.length - 1,
    298         callback = args[index] as (lock: Lock | null) => Promise<unknown>,
    299         forwarded = args.slice();
    300       forwarded[index] = (lock: Lock | null) => {
    301         if (lock) s.stopRumorPlan(window.hcp074Plan);
    302         return callback(lock);
    303       };
    304       return Reflect.apply(original, manager, forwarded) as Promise<unknown>;
    305     };
    306     let stopped: Awaited<ReturnType<typeof f.reserve>>;
    307     try {
    308       stopped = await f.reserve(s.command, window.hcp074Plan);
    309     } finally {
    310       manager.request = original;
    311     }
    312     const absent = (await f.rows()).length === 0;
    313     const next = await f.reserve(s.command, f.plan('New deliberate body'));
    314     return {
    315       stopped,
    316       absent,
    317       next: next.status,
    318       count: (await f.rows()).length,
    319       unchangedSdk: JSON.stringify(before) === JSON.stringify(f.counts())
    320     };
    321   });
    322   expect(result).toEqual({
    323     stopped: { status: 'stopped', disposition: 'not_created' },
    324     absent: true,
    325     next: 'reserved',
    326     count: 1,
    327     unchangedSdk: true
    328   });
    329 });
    330 
    331 test('an actual unknown completion reconciles the original full row without a second command', async ({
    332   page
    333 }) => {
    334   await load(page);
    335   const result = await page.evaluate(async () => {
    336     const original = Reflect.get<IDBObjectStore, 'put'>(
    337       IDBObjectStore.prototype,
    338       'put'
    339     );
    340     IDBObjectStore.prototype.put = function (...args) {
    341       const request = Reflect.apply(original, this, args);
    342       this.transaction.abort = () => {
    343         throw Error('controlled lost abort capability');
    344       };
    345       throw Error(
    346         'controlled lost result after queued write ' +
    347           String(request.readyState)
    348       );
    349     };
    350     const f = window.hcp074Fixture,
    351       s = window.hcp074;
    352     let uncertain: Awaited<ReturnType<typeof f.reserve>>;
    353     try {
    354       uncertain = await f.reserve(s.command, window.hcp074Plan);
    355     } finally {
    356       IDBObjectStore.prototype.put = original;
    357     }
    358     const before = await f.rows(),
    359       retry = await f.reserve(s.command, window.hcp074Plan),
    360       after = await f.rows();
    361     return {
    362       uncertain,
    363       retry: retry.status,
    364       count: after.length,
    365       unchanged: JSON.stringify(before) === JSON.stringify(after),
    366       counts: f.counts()
    367     };
    368   });
    369   expect(result).toMatchObject({
    370     uncertain: { status: 'unknown_completion', disposition: 'may_exist' },
    371     retry: 'existing',
    372     count: 1,
    373     unchanged: true,
    374     counts: { signs: 0, encrypts: 1, decrypts: 1 }
    375   });
    376 });
    377 test('held origin owner lock reports busy and identity disconnect cannot mint a reservation', async ({
    378   page
    379 }) => {
    380   await load(page);
    381   await page.evaluate(async () => {
    382     let entered = () => {};
    383     const ready = new Promise<void>((resolve) => {
    384       entered = resolve;
    385     });
    386     window.hcp074Held = navigator.locks.request(
    387       'harvestcircle:owner:' + window.hcp074.owner,
    388       () =>
    389         new Promise<void>((resolve) => {
    390           window.hcp074Release = resolve;
    391           entered();
    392         })
    393     );
    394     await ready;
    395   });
    396   expect(
    397     await page.evaluate(
    398       async () =>
    399         (
    400           await window.hcp074Fixture.reserve(
    401             window.hcp074.command,
    402             window.hcp074Plan
    403           )
    404         ).status
    405     )
    406   ).toBe('busy');
    407   await page.evaluate(async () => {
    408     window.hcp074Release();
    409     await window.hcp074Held;
    410     window.hcp074Fixture.disconnect();
    411   });
    412   const result = await page.evaluate(async () => ({
    413     status: (
    414       await window.hcp074Fixture.reserve(
    415         window.hcp074.command,
    416         window.hcp074Plan
    417       )
    418     ).status,
    419     count: (await window.hcp074Fixture.rows()).length
    420   }));
    421   expect(result.status).toBe('stopped');
    422   expect(result.count).toBe(0);
    423 });
    424 test('corrupt owner records stay preserved without implicit reset', async ({
    425   page
    426 }) => {
    427   await load(page);
    428   const result = await page.evaluate(async () => {
    429     const f = window.hcp074Fixture;
    430     await f.inject({
    431       owner: window.hcp074.owner,
    432       id: '12345678-1234-4234-8234-123456789abe',
    433       wire: '{bad'
    434     });
    435     const before = JSON.stringify(await f.rows()),
    436       value = await f.reserve(window.hcp074.command, window.hcp074Plan);
    437     return {
    438       status: value.status,
    439       unchanged: before === JSON.stringify(await f.rows())
    440     };
    441   });
    442   expect(result).toEqual({ status: 'corrupt_record', unchanged: true });
    443 });
    444 test('another owner namespace is ignored and remains preserved', async ({
    445   page
    446 }) => {
    447   await load(page);
    448   const result = await page.evaluate(async () => {
    449     const f = window.hcp074Fixture,
    450       other =
    451         'c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5';
    452     const foreign = {
    453       owner: other,
    454       id: window.hcp074.command,
    455       wire: JSON.stringify({
    456         schema: 1,
    457         family: 'private_send_reservation',
    458         owner: other,
    459         id: window.hcp074.command,
    460         revision: 0,
    461         peer: window.hcp074.owner,
    462         rumorHash: 'f'.repeat(64),
    463         createdAt: Math.floor(Date.now() / 1000)
    464       })
    465     };
    466     await f.inject(foreign);
    467     const value = await f.reserve(window.hcp074.command, window.hcp074Plan);
    468     const rows = await f.rows();
    469     return {
    470       status: value.status,
    471       count: rows.length,
    472       foreignPreserved: rows.some(
    473         (row) => JSON.stringify(row) === JSON.stringify(foreign)
    474       )
    475     };
    476   });
    477   expect(result).toEqual({
    478     status: 'reserved',
    479     count: 2,
    480     foreignPreserved: true
    481   });
    482 });
    483 test('real transaction abort never grants a reserved identity or leaves metadata', async ({
    484   page
    485 }) => {
    486   await load(page);
    487   const result = await page.evaluate(async () => {
    488     const original = Reflect.get<IDBObjectStore, 'put'>(
    489       IDBObjectStore.prototype,
    490       'put'
    491     );
    492     IDBObjectStore.prototype.put = function (...args) {
    493       const request = original.apply(this, args);
    494       request.addEventListener('success', () => this.transaction.abort(), {
    495         once: true
    496       });
    497       return request;
    498     };
    499     let value: Awaited<ReturnType<typeof window.hcp074Fixture.reserve>>;
    500     try {
    501       value = await window.hcp074Fixture.reserve(
    502         window.hcp074.command,
    503         window.hcp074Plan
    504       );
    505     } finally {
    506       IDBObjectStore.prototype.put = original;
    507     }
    508     return {
    509       status: value.status,
    510       disposition: value.disposition,
    511       identityPresent: 'identity' in value,
    512       count: (await window.hcp074Fixture.rows()).length
    513     };
    514   });
    515   expect(['aborted', 'unknown_completion']).toContain(result.status);
    516   expect(result.identityPresent).toBe(false);
    517   expect(result.disposition).toBe('not_created');
    518   expect(result.count).toBe(0);
    519 });
    520 test('100 unfinished metadata reservations enforce the existing count cap without eviction', async ({
    521   page
    522 }) => {
    523   await load(page);
    524   const result = await page.evaluate(async () => {
    525     const s = window.hcp074,
    526       f = window.hcp074Fixture;
    527     for (let index = 0; index < 100; index++) {
    528       const id =
    529         '12345678-1234-4234-8234-' + index.toString(16).padStart(12, '0');
    530       const value = await f.reserve(id, f.plan('Intent ' + index));
    531       if (value.status !== 'reserved')
    532         throw Error('capacity fixture not admitted');
    533     }
    534     const value = await f.reserve(s.command, window.hcp074Plan);
    535     return { status: value.status, count: (await f.rows()).length };
    536   });
    537   expect(result).toEqual({ status: 'capacity', count: 100 });
    538 });
    539 
    540 test('actual advancing browser wall clock reserves once at the owner boundary and preserves original retry identity', async ({
    541   page
    542 }) => {
    543   await load(page, undefined, 'real');
    544   const result = await page.evaluate(async () => {
    545     const f = window.hcp074Fixture,
    546       s = window.hcp074;
    547     const before = Date.now();
    548     await new Promise<void>((resolve) => setTimeout(resolve, 1100));
    549     const lower = Math.floor(Date.now() / 1000);
    550     const first = await f.reserve(s.command, window.hcp074Plan);
    551     if (first.status !== 'reserved')
    552       throw Error('advancing real-clock reservation failed');
    553     const original = s.reservedSendSnapshot(first.identity)!;
    554     const upper = Math.floor(Date.now() / 1000);
    555     await new Promise<void>((resolve) => setTimeout(resolve, 1100));
    556     const retry = await f.reserve(s.command, window.hcp074Plan);
    557     if (retry.status !== 'existing')
    558       throw Error('original reconciliation failed');
    559     return {
    560       advanced: Date.now() - before >= 2200,
    561       lower,
    562       upper,
    563       original,
    564       repeated: s.reservedSendSnapshot(retry.identity),
    565       count: (await f.rows()).length
    566     };
    567   });
    568   expect(result.advanced).toBe(true);
    569   expect(result.original.createdAt).toBeGreaterThanOrEqual(result.lower);
    570   expect(result.original.createdAt).toBeLessThanOrEqual(result.upper);
    571   expect(result.repeated).toEqual(result.original);
    572   expect(result.count).toBe(1);
    573 });