search-publishers.test.ts (7891B)
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 chronologicalFoodSearch, 18 foodSearchSnapshot, 19 resolveFoodSearchPublishers, 20 showMoreFoodSearch, 21 cancelFoodSearch 22 } from '../../src/lib/catalog/search-run.ts'; 23 await test('actual SDK listings request only twenty displayed publishers, keep asserted text separate and share lifecycle budgets', async () => { 24 const corpus = JSON.parse( 25 await readFile( 26 new URL( 27 '../../../contracts/interop/food_availability/corpus.v1.json', 28 import.meta.url 29 ), 30 'utf8' 31 ) 32 ) as { vectors: { id: string; signed_wires: Record<string, string> }[] }; 33 const base = JSON.parse( 34 corpus.vectors.find((v) => v.id.endsWith('_032'))!.signed_wires.previous 35 ) as { tags: string[][]; content: string; created_at: number }; 36 const keys: Uint8Array[] = []; 37 const listings = Array.from({ length: 21 }, (_, n) => { 38 const key = crypto.getRandomValues(new Uint8Array(32)); 39 keys.push(key); 40 return finalizeEvent( 41 { 42 kind: 30402, 43 created_at: base.created_at - n, 44 tags: base.tags.map((t) => 45 t[0] === 'd' ? ['d', `listing_${n}`] : [...t] 46 ), 47 content: base.content 48 }, 49 key 50 ); 51 }); 52 const profiles = keys.map((key, n) => 53 finalizeEvent( 54 { 55 kind: 0, 56 created_at: base.created_at, 57 tags: [], 58 content: JSON.stringify({ 59 display_name: `<script>Farmer ${n}</script>`, 60 pubkey: 'forged', 61 nip05: 'identity@example.org', 62 picture: 'https://tracking.example.org' 63 }) 64 }, 65 key 66 ) 67 ); 68 for (const key of keys) key.fill(0); 69 const origin = 'wss://one.example.org', 70 server = new WebSocketServer({ 71 host: '127.0.0.1', 72 port: 0, 73 maxPayload: 65536 74 }); 75 const sockets: WebSocket[] = [], 76 filters: Record<string, unknown>[] = []; 77 server.on('connection', (socket) => { 78 sockets.push(socket); 79 socket.on('message', (bytes) => { 80 const buffer = Array.isArray(bytes) 81 ? Buffer.concat(bytes) 82 : Buffer.isBuffer(bytes) 83 ? bytes 84 : Buffer.from(bytes); 85 const frame = JSON.parse(buffer.toString('utf8')) as unknown[]; 86 if (frame[0] !== 'REQ') return; 87 const id = String(frame[1]), 88 queries = frame.slice(2) as Record<string, unknown>[]; 89 filters.push(...queries); 90 const kind = (queries[0].kinds as number[])[0]; 91 const matches = (pubkey: string, identifier?: string) => 92 queries.some((q) => { 93 const authors = q.authors as string[] | undefined; 94 return ( 95 !authors || 96 (authors.includes(pubkey) && 97 (identifier === undefined || 98 (q['#d'] as string[]).includes(identifier))) 99 ); 100 }); 101 const values = 102 kind === 0 103 ? profiles.filter((v) => matches(v.pubkey)) 104 : kind === 30402 105 ? listings.filter((v) => 106 matches(v.pubkey, v.tags.find((t) => t[0] === 'd')![1]) 107 ) 108 : []; 109 for (const value of values) 110 socket.send(JSON.stringify(['EVENT', id, value])); 111 socket.send(JSON.stringify(['EOSE', id])); 112 }); 113 }); 114 await once(server, 'listening'); 115 const address = server.address(); 116 assert.ok(address && typeof address !== 'string'); 117 const port = address.port; 118 const oldWindow = Object.getOwnPropertyDescriptor(globalThis, 'window'), 119 oldSocket = globalThis.WebSocket; 120 class FixtureSocket extends WebSocket { 121 constructor(url: string | URL) { 122 assert.equal(String(url).replace(/\/$/, ''), origin); 123 super(`ws://127.0.0.1:${port}`); 124 } 125 } 126 Object.defineProperty(globalThis, 'window', { 127 configurable: true, 128 value: {} 129 }); 130 globalThis.WebSocket = 131 FixtureSocket as unknown as typeof globalThis.WebSocket; 132 const context = createPublicRuntimeContext(); 133 try { 134 const policy = validateRelayPolicy( 135 JSON.stringify({ 136 schemaVersion: 1, 137 public: [{ origin, read: true, write: false, nip50: false }], 138 inbox: [], 139 postingEnabled: false, 140 messagingEnabled: false, 141 operatorDenylist: [] 142 }) 143 )!; 144 const view = createPublicView(mountPublicRuntime(context, policy)!); 145 const coordinator = createFoodSearchCoordinator(view, { 146 nowSeconds: () => base.created_at + 10 147 }), 148 token = beginFoodSearch(coordinator, ''); 149 chronologicalFoodSearch(token); 150 for ( 151 let n = 0; 152 n < 200 && foodSearchSnapshot(coordinator)?.refresh !== 'bounded-eose'; 153 n++ 154 ) 155 await new Promise((resolve) => setTimeout(resolve, 5)); 156 const before = foodSearchSnapshot(coordinator)!; 157 assert.equal(before.listings.length, 20); 158 assert.equal(before.hasMore, true); 159 assert.deepEqual( 160 before.listings.map((v) => v.eventId), 161 listings.slice(0, 20).map((v) => v.id) 162 ); 163 assert.ok( 164 before.listings.every((v) => v.publisher.label === v.publisher.pubkey) 165 ); 166 resolveFoodSearchPublishers(token); 167 resolveFoodSearchPublishers(token); 168 for ( 169 let n = 0; 170 n < 200 && 171 !foodSearchSnapshot(coordinator)?.listings.every( 172 (v) => v.publisher.assertedName 173 ); 174 n++ 175 ) 176 await new Promise((resolve) => setTimeout(resolve, 5)); 177 const first = foodSearchSnapshot(coordinator)!; 178 const profileQueries = filters.filter( 179 (q) => (q.kinds as number[])[0] === 0 180 ); 181 assert.equal(profileQueries.length, 1); 182 assert.equal((profileQueries[0].authors as string[]).length, 20); 183 assert.equal(profileQueries[0].limit, 200); 184 assert.deepEqual( 185 first.listings.map((v) => v.publisher.pubkey), 186 listings.slice(0, 20).map((v) => v.pubkey) 187 ); 188 assert.ok( 189 first.listings.every( 190 (v) => 191 v.publisher.assertedName && v.publisher.label.startsWith('<script>') 192 ) 193 ); 194 assert.equal(first.run?.ingress.deliveries, 62); 195 assert.equal(first.run?.activeRequests, 0); 196 const count = filters.length; 197 showMoreFoodSearch(token); 198 assert.equal(filters.length, count); 199 assert.equal(foodSearchSnapshot(coordinator)!.listings.length, 21); 200 resolveFoodSearchPublishers(token); 201 for ( 202 let n = 0; 203 n < 200 && 204 !foodSearchSnapshot(coordinator)?.listings[20].publisher.assertedName; 205 n++ 206 ) 207 await new Promise((resolve) => setTimeout(resolve, 5)); 208 const all = foodSearchSnapshot(coordinator)!; 209 assert.equal(all.run?.ingress.deliveries, 63); 210 const queries = filters.filter((q) => (q.kinds as number[])[0] === 0); 211 assert.equal(queries.length, 2); 212 assert.deepEqual(queries[1].authors, [listings[20].pubkey]); 213 assert.equal(all.definitiveAbsence, false); 214 assert.ok( 215 all.listings.every( 216 (v) => v.price.amount === before.listings[0].price.amount 217 ) 218 ); 219 cancelFoodSearch(token); 220 assert.throws(() => resolveFoodSearchPublishers(token)); 221 } finally { 222 closePublicRuntime(context); 223 for (const key of keys) key.fill(0); 224 globalThis.WebSocket = oldSocket; 225 if (oldWindow) Object.defineProperty(globalThis, 'window', oldWindow); 226 else delete (globalThis as { window?: unknown }).window; 227 for (const socket of sockets) socket.terminate(); 228 await new Promise<void>((resolve, reject) => 229 server.close((e) => (e ? reject(e) : resolve())) 230 ); 231 } 232 });