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