app

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

search-run.test.ts (6183B)


      1 import test from 'node:test';
      2 import assert from 'node:assert/strict';
      3 import { once } from 'node:events';
      4 import { readFile } from 'node:fs/promises';
      5 import { finalizeEvent } from 'applesauce-core/helpers';
      6 import WebSocket, { WebSocketServer } from 'ws';
      7 import { validateRelayPolicy } from '../../src/lib/config/relays.ts';
      8 import {
      9   createPublicRuntimeContext,
     10   mountPublicRuntime,
     11   createPublicView,
     12   closePublicRuntime
     13 } from '../../src/lib/runtime/public-runtime.ts';
     14 import {
     15   createFoodSearchCoordinator,
     16   beginFoodSearch,
     17   subscribeFoodSearch,
     18   foodSearchSnapshot,
     19   cancelFoodSearch
     20 } from '../../src/lib/catalog/search-run.ts';
     21 
     22 await test('actual SDK finite discovery shares latest/deletion budgets and replaces an old local match with suppressed newest evidence', async () => {
     23   const corpus = JSON.parse(
     24     await readFile(
     25       new URL(
     26         '../../../contracts/interop/food_availability/corpus.v1.json',
     27         import.meta.url
     28       ),
     29       'utf8'
     30     )
     31   ) as { vectors: { id: string; signed_wires: Record<string, string> }[] };
     32   const base = JSON.parse(
     33     corpus.vectors.find((v) => v.id.endsWith('_032'))!.signed_wires.previous
     34   ) as { tags: string[][]; content: string; created_at: number };
     35   const key = crypto.getRandomValues(new Uint8Array(32));
     36   const previous = finalizeEvent(
     37     {
     38       kind: 30402,
     39       created_at: base.created_at,
     40       tags: base.tags,
     41       content: base.content
     42     },
     43     key
     44   );
     45   const current = finalizeEvent(
     46     {
     47       kind: 30402,
     48       created_at: base.created_at + 1,
     49       tags: base.tags.map((t) =>
     50         t[0] === 'status'
     51           ? ['status', 'sold']
     52           : t[0] === 'title'
     53             ? ['title', 'Renamed celery']
     54             : [...t]
     55       ),
     56       content: base.content
     57     },
     58     key
     59   );
     60   const deletion = finalizeEvent(
     61     {
     62       kind: 5,
     63       created_at: base.created_at - 1,
     64       tags: [['e', current.id]],
     65       content: ''
     66     },
     67     key
     68   );
     69   key.fill(0);
     70   const origin = 'wss://one.example.org',
     71     server = new WebSocketServer({
     72       host: '127.0.0.1',
     73       port: 0,
     74       maxPayload: 4096
     75     });
     76   const sockets: WebSocket[] = [];
     77   const filters: Record<string, unknown>[] = [];
     78   let sent = () => {};
     79   const sentBoth = new Promise<void>((resolve) => {
     80     sent = resolve;
     81   });
     82   server.on('connection', (socket) => {
     83     sockets.push(socket);
     84     socket.on('message', (bytes) => {
     85       const buffer = Array.isArray(bytes)
     86         ? Buffer.concat(bytes)
     87         : Buffer.isBuffer(bytes)
     88           ? bytes
     89           : Buffer.from(bytes);
     90       const frame = JSON.parse(buffer.toString('utf8')) as unknown[];
     91       if (frame[0] !== 'REQ') return;
     92       const id = String(frame[1]),
     93         query = frame[2] as Record<string, unknown>;
     94       filters.push(query);
     95       const values =
     96         (query.kinds as number[])[0] === 30402
     97           ? query.authors === undefined
     98             ? [previous]
     99             : [current]
    100           : [deletion];
    101       for (const value of values)
    102         socket.send(JSON.stringify(['EVENT', id, value]));
    103       socket.send(JSON.stringify(['EOSE', id]));
    104       if (filters.length === 1) sent();
    105     });
    106   });
    107   await once(server, 'listening');
    108   const address = server.address();
    109   assert.ok(address && typeof address !== 'string');
    110   const port = address.port;
    111   const oldWindow = Object.getOwnPropertyDescriptor(globalThis, 'window'),
    112     oldSocket = globalThis.WebSocket;
    113   class FixtureSocket extends WebSocket {
    114     constructor(url: string | URL) {
    115       assert.equal(String(url).replace(/\/$/, ''), origin);
    116       super(`ws://127.0.0.1:${port}`);
    117     }
    118   }
    119   Object.defineProperty(globalThis, 'window', {
    120     configurable: true,
    121     value: {}
    122   });
    123   globalThis.WebSocket =
    124     FixtureSocket as unknown as typeof globalThis.WebSocket;
    125   const context = createPublicRuntimeContext();
    126   try {
    127     const policy = validateRelayPolicy(
    128       JSON.stringify({
    129         schemaVersion: 1,
    130         public: [{ origin, read: true, write: false, nip50: false }],
    131         inbox: [],
    132         postingEnabled: false,
    133         messagingEnabled: false,
    134         operatorDenylist: []
    135       })
    136     )!;
    137     const runtime = mountPublicRuntime(context, policy)!;
    138     const view = createPublicView(runtime);
    139     const coordinator = createFoodSearchCoordinator(view, {
    140       nowSeconds: () => base.created_at + 10
    141     });
    142     const generation = beginFoodSearch(coordinator, '');
    143     subscribeFoodSearch(generation, [{ kinds: [30402], limit: 200 }]);
    144     await sentBoth;
    145     for (
    146       let n = 0;
    147       n < 100 && foodSearchSnapshot(coordinator)?.refresh !== 'bounded-eose';
    148       n++
    149     )
    150       await new Promise((resolve) => setTimeout(resolve, 5));
    151     assert.equal(filters.length, 3);
    152     const head = filters.find(
    153       (q) => (q.kinds as number[])[0] === 30402 && q.authors !== undefined
    154     )!;
    155     const requests = filters.find((q) => (q.kinds as number[])[0] === 5)!;
    156     assert.deepEqual(head.authors, [previous.pubkey]);
    157     assert.deepEqual(head['#d'], [base.tags.find((t) => t[0] === 'd')![1]]);
    158     assert.deepEqual(requests.authors, [previous.pubkey]);
    159     for (const q of filters) {
    160       assert.equal(q.limit, 200);
    161       assert.equal('q' in q, false);
    162       assert.equal('search' in q, false);
    163       assert.equal('since' in q, false);
    164       assert.equal('#k' in q, false);
    165     }
    166     const snapshot = foodSearchSnapshot(coordinator)!;
    167     assert.equal(snapshot.query, '');
    168     assert.equal(snapshot.refresh, 'bounded-eose');
    169     assert.equal(snapshot.rows.length, 0);
    170     assert.equal(snapshot.definitiveAbsence, false);
    171     assert.equal(snapshot.run?.ingress.deliveries, 3);
    172     assert.equal(snapshot.run?.activeRequests, 0);
    173     assert.equal(snapshot.scopes.length, 3);
    174     cancelFoodSearch(generation);
    175   } finally {
    176     closePublicRuntime(context);
    177     key.fill(0);
    178     globalThis.WebSocket = oldSocket;
    179     if (oldWindow) Object.defineProperty(globalThis, 'window', oldWindow);
    180     else delete (globalThis as { window?: unknown }).window;
    181     for (const socket of sockets) socket.terminate();
    182     await new Promise<void>((resolve, reject) =>
    183       server.close((error) => (error ? reject(error) : resolve()))
    184     );
    185   }
    186 });