app

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

search-view.test.ts (7663B)


      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   createSearchView,
     16   startSearchView,
     17   searchViewSnapshot,
     18   moreSearchView,
     19   closeSearchView
     20 } from '../../src/lib/catalog/search-view.ts';
     21 await test('actual SDK foreground search publishes genuine rows and metadata and local pages without older discovery', async () => {
     22   const corpus = JSON.parse(
     23     await readFile(
     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   const keys: Uint8Array[] = [];
     35   const listings = Array.from({ length: 21 }, (_, n) => {
     36     const key = crypto.getRandomValues(new Uint8Array(32));
     37     keys.push(key);
     38     return finalizeEvent(
     39       {
     40         kind: 30402,
     41         created_at: base.created_at - n,
     42         tags: base.tags.map((t) =>
     43           t[0] === 'd' ? ['d', `listing_${n}`] : [...t]
     44         ),
     45         content: base.content
     46       },
     47       key
     48     );
     49   });
     50   const profiles = keys.map((key, n) =>
     51     finalizeEvent(
     52       {
     53         kind: 0,
     54         created_at: base.created_at,
     55         tags: [],
     56         content: JSON.stringify({
     57           display_name: `<script>Farmer ${n}</script>`,
     58           pubkey: 'forged',
     59           nip05: 'identity@example.org',
     60           picture: 'https://tracking.example.org'
     61         })
     62       },
     63       key
     64     )
     65   );
     66   for (const key of keys) key.fill(0);
     67   const origin = 'wss://one.example.org',
     68     server = new WebSocketServer({
     69       host: '127.0.0.1',
     70       port: 0,
     71       maxPayload: 65536
     72     });
     73   let releaseLast: (() => void) | undefined;
     74   const sockets: WebSocket[] = [],
     75     filters: Record<string, unknown>[] = [];
     76   server.on('connection', (socket) => {
     77     sockets.push(socket);
     78     socket.on('message', (bytes) => {
     79       const buffer = Array.isArray(bytes)
     80         ? Buffer.concat(bytes)
     81         : Buffer.isBuffer(bytes)
     82           ? bytes
     83           : Buffer.from(bytes);
     84       const frame = JSON.parse(buffer.toString('utf8')) as unknown[];
     85       if (frame[0] !== 'REQ') return;
     86       const id = String(frame[1]),
     87         queries = frame.slice(2) as Record<string, unknown>[];
     88       filters.push(...queries);
     89       const kind = (queries[0].kinds as number[])[0];
     90       const matches = (pubkey: string, identifier?: string) =>
     91         queries.some((q) => {
     92           const authors = q.authors as string[] | undefined;
     93           return (
     94             !authors ||
     95             (authors.includes(pubkey) &&
     96               (identifier === undefined ||
     97                 (q['#d'] as string[]).includes(identifier)))
     98           );
     99         });
    100       const values =
    101         kind === 0
    102           ? profiles.filter((v) => matches(v.pubkey))
    103           : kind === 30402
    104             ? listings.filter((v) =>
    105                 matches(v.pubkey, v.tags.find((t) => t[0] === 'd')![1])
    106               )
    107             : [];
    108       for (const [index, value] of values.entries()) {
    109         // Real delivery can expose20 visible rows before the21st is admitted.
    110         // Hold that final discovery event to test both pagination states.
    111         if (kind === 30402 && !queries[0].authors && index === 20) {
    112           releaseLast = () => {
    113             socket.send(JSON.stringify(['EVENT', id, value]));
    114             socket.send(JSON.stringify(['EOSE', id]));
    115           };
    116           return;
    117         }
    118         socket.send(JSON.stringify(['EVENT', id, value]));
    119       }
    120       socket.send(JSON.stringify(['EOSE', id]));
    121     });
    122   });
    123   await once(server, 'listening');
    124   const address = server.address();
    125   assert.ok(address && typeof address !== 'string');
    126   const port = address.port;
    127   const oldWindow = Object.getOwnPropertyDescriptor(globalThis, 'window'),
    128     oldSocket = globalThis.WebSocket;
    129   class FixtureSocket extends WebSocket {
    130     constructor(url: string | URL) {
    131       assert.equal(String(url).replace(/\/$/, ''), origin);
    132       super(`ws://127.0.0.1:${port}`);
    133     }
    134   }
    135   Object.defineProperty(globalThis, 'window', {
    136     configurable: true,
    137     value: {}
    138   });
    139   globalThis.WebSocket =
    140     FixtureSocket as unknown as typeof globalThis.WebSocket;
    141   const context = createPublicRuntimeContext();
    142   try {
    143     const policy = validateRelayPolicy(
    144       JSON.stringify({
    145         schemaVersion: 1,
    146         public: [{ origin, read: true, write: false, nip50: false }],
    147         inbox: [],
    148         postingEnabled: false,
    149         messagingEnabled: false,
    150         operatorDenylist: []
    151       })
    152     )!;
    153     const view = createPublicView(mountPublicRuntime(context, policy)!);
    154     const updates: number[] = [];
    155     const owner = createSearchView(
    156       view,
    157       { nowSeconds: () => base.created_at + 10 },
    158       (snapshot) => {
    159         updates.push(snapshot.listings.length);
    160       }
    161     );
    162     startSearchView(owner, '');
    163     for (
    164       let n = 0;
    165       n < 300 &&
    166       !searchViewSnapshot(owner)?.listings.every(
    167         (v) => v.publisher.assertedName
    168       );
    169       n++
    170     )
    171       await new Promise((resolve) => setTimeout(resolve, 10));
    172     // Empty initial arrays are not success; wait for actual signed rows as well.
    173     for (
    174       let n = 0;
    175       n < 300 && searchViewSnapshot(owner)?.listings.length !== 20;
    176       n++
    177     )
    178       await new Promise((resolve) => setTimeout(resolve, 10));
    179     const first = searchViewSnapshot(owner)!;
    180     assert.equal(first.listings.length, 20);
    181     assert.equal(first.hasMore, false);
    182     assert.equal(typeof releaseLast, 'function');
    183     releaseLast!();
    184     for (let n = 0; n < 300 && !searchViewSnapshot(owner)?.hasMore; n++)
    185       await new Promise((resolve) => setTimeout(resolve, 10));
    186     assert.equal(searchViewSnapshot(owner)!.hasMore, true);
    187     assert.deepEqual(
    188       first.listings.map((v) => v.eventId),
    189       listings.slice(0, 20).map((v) => v.id)
    190     );
    191     for (
    192       let n = 0;
    193       n < 300 &&
    194       !searchViewSnapshot(owner)?.listings.every(
    195         (v) => v.publisher.assertedName
    196       );
    197       n++
    198     )
    199       await new Promise((resolve) => setTimeout(resolve, 10));
    200     assert.ok(
    201       searchViewSnapshot(owner)!.listings.every((v) => v.publisher.assertedName)
    202     );
    203     assert.ok(updates.includes(20));
    204     const count = filters.length;
    205     moreSearchView(owner);
    206     assert.equal(filters.length, count);
    207     assert.equal(searchViewSnapshot(owner)!.listings.length, 21);
    208     assert.equal(searchViewSnapshot(owner)!.definitiveAbsence, false);
    209     closeSearchView(owner);
    210     const settled = filters.length;
    211     await new Promise((resolve) => setTimeout(resolve, 300));
    212     assert.equal(filters.length, settled);
    213     assert.throws(() => startSearchView(owner, ''));
    214   } finally {
    215     closePublicRuntime(context);
    216     for (const key of keys) key.fill(0);
    217     globalThis.WebSocket = oldSocket;
    218     if (oldWindow) Object.defineProperty(globalThis, 'window', oldWindow);
    219     else delete (globalThis as { window?: unknown }).window;
    220     for (const socket of sockets) socket.terminate();
    221     await new Promise<void>((resolve, reject) =>
    222       server.close((e) => (e ? reject(e) : resolve()))
    223     );
    224   }
    225 });