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