app

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

product-view.test.ts (13120B)


      1 import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
      2 import { readFileSync } from 'node:fs';
      3 import { finalizeEvent } from 'applesauce-core/helpers';
      4 import type { PublicPoolMessage } from '../../src/lib/nostr/exports.ts';
      5 import type { RequestClock } from '../../src/lib/nostr/request-scope.ts';
      6 let product: typeof import('../../src/lib/catalog/product-view.ts');
      7 let runtime: typeof import('../../src/lib/runtime/public-runtime.ts');
      8 let context: ReturnType<typeof runtime.createPublicRuntimeContext>;
      9 const keys: Uint8Array[] = [];
     10 beforeEach(async () => {
     11   vi.resetModules();
     12   vi.stubGlobal('window', {});
     13   product = await import('../../src/lib/catalog/product-view.ts');
     14   runtime = await import('../../src/lib/runtime/public-runtime.ts');
     15 });
     16 afterEach(() => {
     17   if (context) runtime.closePublicRuntime(context);
     18   for (const key of keys.splice(0)) key.fill(0);
     19   vi.restoreAllMocks();
     20   vi.unstubAllGlobals();
     21 });
     22 const corpus = JSON.parse(
     23   readFileSync(
     24     new URL(
     25       '../../../contracts/interop/food_availability/corpus.v1.json',
     26       import.meta.url
     27     ),
     28     'utf8'
     29   )
     30 ) as { vectors: { id: string; signed_wires: Record<string, string> }[] };
     31 const base = JSON.parse(
     32   corpus.vectors.find((v) => v.id.endsWith('_032'))!.signed_wires.previous
     33 ) as { tags: string[][]; content: string; created_at: number };
     34 async function fixture(nip50 = false, sourceCount = 1, throws = false) {
     35   const { RelayPool } = await import('applesauce-relay/pool');
     36   const { validateRelayPolicy } =
     37     await import('../../src/lib/config/relays.ts');
     38   const channels: {
     39     emit: (value: PublicPoolMessage) => void;
     40     stopped: () => boolean;
     41   }[] = [];
     42   const provider = vi.spyOn(RelayPool.prototype, 'req').mockImplementation(
     43     () =>
     44       ({
     45         subscribe(subscriber: { next?: (value: PublicPoolMessage) => void }) {
     46           let stopped = false;
     47           channels.push({
     48             emit: (value: PublicPoolMessage) => {
     49               if (!stopped) subscriber.next?.(value);
     50             },
     51             stopped: () => stopped
     52           });
     53           return {
     54             get closed() {
     55               return stopped;
     56             },
     57             unsubscribe() {
     58               stopped = true;
     59             }
     60           };
     61         }
     62       }) as unknown as ReturnType<InstanceType<typeof RelayPool>['req']>
     63   );
     64   const origin = 'wss://one.example.org';
     65   const policy = validateRelayPolicy(
     66     JSON.stringify({
     67       schemaVersion: 1,
     68       public: Array.from({ length: sourceCount }, (_, n) => ({
     69         origin: n === 0 ? origin : `wss://source${n}.example.org`,
     70         read: true,
     71         write: false,
     72         nip50
     73       })),
     74       inbox: [],
     75       postingEnabled: false,
     76       messagingEnabled: false,
     77       operatorDenylist: []
     78     })
     79   )!;
     80   const key = crypto.getRandomValues(new Uint8Array(32));
     81   keys.push(key);
     82   const wire = (
     83     title = 'Carrots',
     84     d?: string,
     85     time = base.created_at,
     86     content = base.content
     87   ) =>
     88     finalizeEvent(
     89       {
     90         kind: 30402,
     91         created_at: time,
     92         content,
     93         tags: base.tags.map((tag) =>
     94           tag[0] === 'title'
     95             ? ['title', title]
     96             : tag[0] === 'd' && d !== undefined
     97               ? ['d', d]
     98               : [...tag]
     99         )
    100       },
    101       key
    102     );
    103   let now = 0;
    104   const timers = new Map<() => void, { at: number; callback: () => void }>();
    105   const clock: RequestClock = {
    106     now: () => {
    107       return now;
    108     },
    109     schedule: (callback, delay) => {
    110       const cancel = () => {
    111         timers.delete(cancel);
    112       };
    113       timers.set(cancel, { at: now + delay, callback });
    114       return cancel;
    115     }
    116   };
    117   if (throws)
    118     provider.mockImplementation(() => {
    119       throw Error('fixture provider denied');
    120     });
    121   context = runtime.createPublicRuntimeContext();
    122   const owner = runtime.mountPublicRuntime(context, policy, clock)!;
    123   const view = runtime.createPublicView(owner);
    124   let onWall = () => {};
    125   const wallClock = {
    126     nowSeconds: () => {
    127       onWall();
    128       return base.created_at + 10;
    129     }
    130   };
    131   const { encodeProductReference } =
    132     await import('../../src/lib/nostr/references.ts');
    133   const initial = wire();
    134   const naddr = encodeProductReference({
    135     kind: 30402,
    136     pubkey: initial.pubkey,
    137     identifier: initial.tags.find((t) => t[0] === 'd')![1]
    138   })!;
    139   const observer = new Map<() => void, () => void>();
    140   const schedule = (callback: () => void) => {
    141     const cancel = () => {
    142       observer.delete(cancel);
    143     };
    144     observer.set(cancel, callback);
    145     return cancel;
    146   };
    147   const updated: ReturnType<typeof product.productViewSnapshot>[] = [];
    148   const token = product.createProductView(
    149     view,
    150     naddr,
    151     wallClock,
    152     (value) => updated.push(value),
    153     schedule
    154   );
    155   return {
    156     token,
    157     armWall: (callback: () => void) => {
    158       onWall = callback;
    159     },
    160     naddr,
    161     view,
    162     provider,
    163     channels,
    164     wire,
    165     initial,
    166     updated,
    167     observer,
    168     emit: (i: number, event: ReturnType<typeof wire>) =>
    169       channels[i].emit({ type: 'EVENT', id: 'fixture', from: origin, event }),
    170     eose: (i: number) =>
    171       channels[i].emit({ type: 'EOSE', id: 'fixture', from: origin }),
    172     snapshot: () => product.productViewSnapshot(token),
    173     tick: () => {
    174       const pending = [...observer.values()];
    175       observer.clear();
    176       for (const callback of pending) callback();
    177     },
    178     fail: (i: number) =>
    179       channels[i].emit({
    180         type: 'CLOSED',
    181         id: 'fixture',
    182         from: origin,
    183         reason: 'fixture failure'
    184       }),
    185     advance: () => {
    186       now = 16000;
    187       for (const timer of [...timers.values()]) timer.callback();
    188     }
    189   };
    190 }
    191 describe('genuine direct coordinate product view', () => {
    192   it('rechecks publication ownership after a snapshot clock creates a successor', async () => {
    193     const f = await fixture();
    194     f.emit(0, f.initial);
    195     const profileIndex = f.provider.mock.calls.findIndex((call) =>
    196       JSON.stringify(call[1]).includes('[0]')
    197     );
    198     expect(profileIndex).toBeGreaterThan(0);
    199     f.emit(
    200       profileIndex,
    201       finalizeEvent(
    202         {
    203           kind: 0,
    204           created_at: base.created_at,
    205           tags: [],
    206           content: JSON.stringify({ display_name: 'Actual asserted publisher' })
    207         },
    208         keys.at(-1)!
    209       )
    210     );
    211     const previous = f.updated.length;
    212     let successor: ReturnType<typeof product.createProductView> | undefined;
    213     f.armWall(() => {
    214       f.armWall(() => {});
    215       successor = product.createProductView(
    216         f.view,
    217         f.naddr,
    218         { nowSeconds: () => base.created_at + 10 },
    219         () => {},
    220         () => () => {}
    221       );
    222     });
    223     f.tick();
    224     expect(successor).toBeDefined();
    225     expect(f.updated.length).toBe(previous);
    226     expect(f.snapshot().outcome).toBe('unavailable');
    227     expect(f.snapshot().food).toBeUndefined();
    228     product.closeProductView(f.token);
    229     expect(product.productViewSnapshot(successor!).outcome).toBe('checking');
    230     product.closeProductView(successor!);
    231   });
    232 
    233   it('reports zero qualified sources unavailable without relay delivery or polling', async () => {
    234     const f = await fixture(false, 0);
    235     expect(f.snapshot().outcome).toBe('unavailable');
    236     expect(f.snapshot().sources[0]?.result.sources).toEqual([]);
    237     expect(f.observer.size).toBe(0);
    238     expect(f.channels.every((c) => c.stopped())).toBe(true);
    239   });
    240   it('ignores superseded retained callbacks and old cleanup cannot close successor view work', async () => {
    241     const f = await fixture();
    242     const pending = [...f.observer.values()];
    243     const count = f.updated.length;
    244     const nextUpdates: ReturnType<typeof product.productViewSnapshot>[] = [];
    245     const next = product.createProductView(
    246       f.view,
    247       f.naddr,
    248       { nowSeconds: () => base.created_at + 10 },
    249       (value) => nextUpdates.push(value),
    250       () => () => {}
    251     );
    252     for (const callback of pending) callback();
    253     expect(f.updated.length).toBe(count);
    254     const channel = f.channels.at(-1)!;
    255     expect(channel.stopped()).toBe(false);
    256     product.closeProductView(f.token);
    257     expect(channel.stopped()).toBe(false);
    258     expect(product.productViewSnapshot(next).outcome).toBe('checking');
    259     expect(nextUpdates.length).toBe(1);
    260     product.closeProductView(next);
    261     expect(channel.stopped()).toBe(true);
    262   });
    263   it('reports initial provider failure unavailable without retries', async () => {
    264     const f = await fixture(false, 1, true);
    265     expect(f.snapshot().outcome).toBe('unavailable');
    266     expect(f.updated.at(-1)?.outcome).toBe('unavailable');
    267     expect(f.observer.size).toBe(0);
    268     expect(f.provider).toHaveBeenCalledTimes(1);
    269   });
    270 
    271   it('publishes terminal deadline state once and never restarts reads', async () => {
    272     const f = await fixture();
    273     expect(f.updated.at(-1)?.outcome).toBe('checking');
    274     const calls = f.provider.mock.calls.length;
    275     f.advance();
    276     f.tick();
    277     expect(f.updated.at(-1)?.outcome).toBe('unobserved');
    278     expect(f.updated.at(-1)?.lastKnown).toBe(true);
    279     expect(f.observer.size).toBe(0);
    280     expect(f.provider.mock.calls.length).toBe(calls);
    281   });
    282   it('distinguishes failed sources from bounded empty observation', async () => {
    283     const f = await fixture();
    284     f.fail(0);
    285     f.tick();
    286     expect(f.snapshot().outcome).toBe('unavailable');
    287     expect(f.updated.at(-1)?.outcome).toBe('unavailable');
    288   });
    289 
    290   it('distinguishes bounded unobserved from invalid before effects', async () => {
    291     const f = await fixture();
    292     expect(f.snapshot().outcome).toBe('checking');
    293     const calls = f.provider.mock.calls.length;
    294     expect(() =>
    295       product.createProductView(
    296         f.view,
    297         'bad',
    298         { nowSeconds: () => 0 },
    299         () => {}
    300       )
    301     ).toThrow('product_reference_invalid');
    302     expect(f.provider.mock.calls.length).toBe(calls);
    303     f.eose(0);
    304     expect(f.snapshot().outcome).toBe('unobserved');
    305     expect(f.snapshot().lastKnown).toBe(true);
    306     product.closeProductView(f.token);
    307     expect(f.observer.size).toBe(0);
    308   });
    309   it('admits only actual exact coordinates and latest unsupported never revives older food', async () => {
    310     const f = await fixture();
    311     f.emit(0, f.wire('Other', 'other'));
    312     expect(f.snapshot().outcome).toBe('checking');
    313     f.emit(0, f.initial);
    314     expect(f.snapshot().outcome).toBe('active');
    315     expect(f.snapshot().food?.title).toBe('Carrots');
    316     const key = keys.at(-1)!;
    317     const unsupported = finalizeEvent(
    318       {
    319         kind: 30402,
    320         created_at: base.created_at + 1,
    321         content: 'other format',
    322         tags: [
    323           ['d', f.initial.tags.find((t) => t[0] === 'd')![1]],
    324           ['title', 'Unsupported']
    325         ]
    326       },
    327       key
    328     );
    329     f.emit(0, unsupported);
    330     f.emit(0, f.initial);
    331     expect(f.snapshot().outcome).toBe('unsupported');
    332     expect(f.snapshot().food).toBeUndefined();
    333     expect(f.snapshot().eventId).toBe(unsupported.id);
    334   });
    335   it('shows sold, future quarantine and authorized deletion without fabricated actions', async () => {
    336     const f = await fixture();
    337     const key = keys.at(-1)!;
    338     const sold = finalizeEvent(
    339       {
    340         kind: 30402,
    341         created_at: base.created_at + 1,
    342         content: base.content,
    343         tags: base.tags.map((t) =>
    344           t[0] === 'status' ? ['status', 'sold'] : [...t]
    345         )
    346       },
    347       key
    348     );
    349     f.emit(0, sold);
    350     expect(f.snapshot().outcome).toBe('sold');
    351     expect(f.snapshot().food?.status).toBe('sold');
    352     const deletion = finalizeEvent(
    353       {
    354         kind: 5,
    355         created_at: base.created_at + 2,
    356         content: '',
    357         tags: [['e', sold.id]]
    358       },
    359       key
    360     );
    361     const deletionIndex = f.provider.mock.calls.findIndex((c) =>
    362       JSON.stringify(c[1]).includes('[5]')
    363     );
    364     expect(deletionIndex).toBeGreaterThan(0);
    365     f.emit(deletionIndex, deletion);
    366     expect(f.snapshot().outcome).toBe('withdrawn');
    367     expect(f.snapshot().food).toBeUndefined();
    368     const future = f.wire('Future', undefined, base.created_at + 36000);
    369     f.emit(0, future);
    370     expect(f.snapshot().outcome).toBe('future_quarantined');
    371     expect(f.snapshot().food).toBeUndefined();
    372   });
    373   it('preserves uncertainty and scoped cleanup without closing another public view', async () => {
    374     const f = await fixture();
    375     f.emit(0, f.initial);
    376     f.fail(0);
    377     expect(f.snapshot().lastKnown).toBe(true);
    378     const retained = runtime.publicRuntime(context)!;
    379     const other = runtime.createPublicView(retained);
    380     const otherRun = runtime.beginPublicViewRun(other);
    381     const calls = f.provider.mock.calls.length;
    382     product.closeProductView(f.token);
    383     expect(f.observer.size).toBe(0);
    384     expect(f.channels.every((c) => c.stopped())).toBe(true);
    385     expect(runtime.publicViewRunCurrent(other, otherRun)).toBe(true);
    386     f.channels[0].emit({
    387       type: 'EVENT',
    388       id: 'fixture',
    389       from: 'wss://one.example.org',
    390       event: f.initial
    391     });
    392     f.tick();
    393     expect(f.provider.mock.calls.length).toBe(calls);
    394     expect(f.snapshot().outcome).toBe('unavailable');
    395     runtime.disposePublicView(other);
    396   });
    397 });