public-runtime.test.ts (6098B)
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 WebSocket, { WebSocketServer } from 'ws'; 6 import { validateRelayPolicy } from '../../src/lib/config/relays.ts'; 7 import { 8 createPublicRuntimeContext, 9 mountPublicRuntime, 10 createPublicView, 11 beginPublicViewRun, 12 subscribePublicView, 13 publicViewRunCurrent, 14 closePublicRuntime 15 } from '../../src/lib/runtime/public-runtime.ts'; 16 import { 17 publicRunSnapshot, 18 publicRequestScopeSnapshot, 19 publicRunObservations, 20 type RequestClock 21 } from '../../src/lib/nostr/request-scope.ts'; 22 await test('actual SDK request ownership suppresses superseded results and preserves another view through its absolute deadline', 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 wires = corpus.vectors.find((v) => v.id.endsWith('_032'))!.signed_wires, 33 current = JSON.parse(wires.current) as { id: string }, 34 previous = JSON.parse(wires.previous) as { id: string }; 35 const origin = 'wss://one.example.org', 36 server = new WebSocketServer({ 37 host: '127.0.0.1', 38 port: 0, 39 maxPayload: 4096 40 }); 41 const sockets: WebSocket[] = []; 42 const ids: string[] = []; 43 let socket: WebSocket | undefined; 44 let firstClose = () => {}; 45 const closedFirst = new Promise<void>((resolve) => { 46 firstClose = resolve; 47 }); 48 server.on('connection', (connection) => { 49 sockets.push(connection); 50 socket = connection; 51 connection.on('message', (bytes) => { 52 const buffer = Array.isArray(bytes) 53 ? Buffer.concat(bytes) 54 : Buffer.isBuffer(bytes) 55 ? bytes 56 : Buffer.from(bytes); 57 const frame = JSON.parse(buffer.toString('utf8')) as unknown[]; 58 if (frame[0] === 'REQ') { 59 const id = String(frame[1]); 60 ids.push(id); 61 connection.send( 62 JSON.stringify(['EVENT', id, ids.length === 1 ? current : previous]) 63 ); 64 } else if (frame[0] === 'CLOSE' && frame[1] === ids[0]) firstClose(); 65 }); 66 }); 67 await once(server, 'listening'); 68 const address = server.address(); 69 assert.ok(address && typeof address !== 'string'); 70 const port = address.port; 71 const oldWindow = Object.getOwnPropertyDescriptor(globalThis, 'window'), 72 oldSocket = globalThis.WebSocket; 73 class FixtureSocket extends WebSocket { 74 constructor(url: string | URL) { 75 assert.equal(String(url).replace(/\/$/, ''), origin); 76 super(`ws://127.0.0.1:${port}`); 77 } 78 } 79 Object.defineProperty(globalThis, 'window', { 80 configurable: true, 81 value: {} 82 }); 83 globalThis.WebSocket = 84 FixtureSocket as unknown as typeof globalThis.WebSocket; 85 let now = 0; 86 const timers = new Map<() => void, { at: number; callback: () => void }>(); 87 const clock: RequestClock = { 88 now: () => now, 89 schedule(callback, delay) { 90 const cancel = () => { 91 timers.delete(cancel); 92 }; 93 timers.set(cancel, { at: now + delay, callback }); 94 return cancel; 95 } 96 }; 97 const policy = validateRelayPolicy( 98 JSON.stringify({ 99 schemaVersion: 1, 100 public: [{ origin, read: true, write: false, nip50: false }], 101 inbox: [], 102 postingEnabled: false, 103 messagingEnabled: false, 104 operatorDenylist: [] 105 }) 106 )!; 107 const context = createPublicRuntimeContext(), 108 runtime = mountPublicRuntime(context, policy, clock)!; 109 const a = createPublicView(runtime), 110 b = createPublicView(runtime), 111 ra = beginPublicViewRun(a), 112 rb = beginPublicViewRun(b); 113 let writesA = 0, 114 writesB = 0; 115 let firstA = () => {}, 116 firstB = () => {}, 117 secondB = () => {}; 118 const initialA = new Promise<void>((resolve) => { 119 firstA = resolve; 120 }), 121 initialB = new Promise<void>((resolve) => { 122 firstB = resolve; 123 }), 124 continuedB = new Promise<void>((resolve) => { 125 secondB = resolve; 126 }); 127 try { 128 const ha = subscribePublicView( 129 a, 130 ra, 131 'search', 132 [{ kinds: [30402], limit: 1 }], 133 () => { 134 writesA++; 135 firstA(); 136 } 137 ), 138 hb = subscribePublicView( 139 b, 140 rb, 141 'profile', 142 [{ kinds: [30402], limit: 2 }], 143 () => { 144 writesB++; 145 if (writesB === 1) firstB(); 146 else secondB(); 147 } 148 ); 149 await Promise.all([initialA, initialB]); 150 assert.equal(ids.length, 2); 151 const next = beginPublicViewRun(a); 152 await closedFirst; 153 assert.equal(publicViewRunCurrent(a, ra), false); 154 assert.equal(publicViewRunCurrent(a, next), true); 155 assert.equal(publicRequestScopeSnapshot(ha).state, 'cancelled'); 156 assert.equal(publicRequestScopeSnapshot(hb).state, 'active'); 157 assert.ok(socket); 158 socket.send(JSON.stringify(['EVENT', ids[0], previous])); 159 socket.send(JSON.stringify(['EVENT', ids[1], previous])); 160 await continuedB; 161 assert.equal(writesA, 1); 162 assert.equal(writesB, 2); 163 assert.equal(publicRunSnapshot(ra).ingress.deliveries, 1); 164 assert.equal(publicRunSnapshot(rb).ingress.deliveries, 2); 165 assert.equal(publicRunObservations(rb, hb).length, 1); 166 now = 10000; 167 for (const [cancel, row] of [...timers]) 168 if (row.at <= now) { 169 cancel(); 170 row.callback(); 171 } 172 assert.equal(publicRequestScopeSnapshot(hb).state, 'deadline'); 173 assert.equal( 174 publicRequestScopeSnapshot(hb).result.definitiveAbsence, 175 false 176 ); 177 assert.equal(timers.size, 0); 178 } finally { 179 closePublicRuntime(context); 180 for (const connection of sockets) connection.terminate(); 181 await new Promise<void>((resolve, reject) => 182 server.close((error) => (error ? reject(error) : resolve())) 183 ); 184 globalThis.WebSocket = oldSocket; 185 if (oldWindow) Object.defineProperty(globalThis, 'window', oldWindow); 186 else Reflect.deleteProperty(globalThis, 'window'); 187 } 188 });