request-scope.test.ts (19332B)
1 import { describe, it, expect } from 'vitest'; 2 import { readFileSync } from 'node:fs'; 3 import { validateRelayPolicy } from '../../src/lib/config/relays.ts'; 4 import type { PublicPoolMessage } from '../../src/lib/nostr/exports.ts'; 5 import { 6 createPublicScheduler, 7 createPublicRun, 8 openPublicRequest, 9 closePublicRequest, 10 cancelPublicRun, 11 disposePublicRun, 12 closePublicScheduler, 13 publicRunSnapshot, 14 publicRequestScopeSnapshot, 15 publicSchedulerSnapshot, 16 publicRunObservations, 17 type RequestClock 18 } from '../../src/lib/nostr/request-scope.ts'; 19 const origin = 'wss://one.example.org'; 20 const policy = validateRelayPolicy( 21 JSON.stringify({ 22 schemaVersion: 1, 23 public: [{ origin, read: true, write: false, nip50: false }], 24 inbox: [], 25 postingEnabled: false, 26 messagingEnabled: false, 27 operatorDenylist: [] 28 }) 29 )!; 30 const corpus = JSON.parse( 31 readFileSync( 32 new URL( 33 '../../../contracts/interop/food_availability/corpus.v1.json', 34 import.meta.url 35 ), 36 'utf8' 37 ) 38 ) as { vectors: { id: string; signed_wires: Record<string, string> }[] }; 39 const wire = corpus.vectors.find((v) => v.id.endsWith('_032'))!.signed_wires 40 .current; 41 const event = () => 42 JSON.parse(wire) as Extract<PublicPoolMessage, { type: 'EVENT' }>['event']; 43 function fixture() { 44 let now = 0; 45 const timers = new Map<() => void, { at: number; callback: () => void }>(); 46 const clock: RequestClock = { 47 now: () => now, 48 schedule(callback, delay) { 49 const cancel = () => { 50 timers.delete(cancel); 51 }; 52 timers.set(cancel, { at: now + delay, callback }); 53 return cancel; 54 } 55 }; 56 const scheduler = createPublicScheduler(clock); 57 return { 58 scheduler, 59 advance(value: number, flush = true) { 60 now = value; 61 if (flush) 62 for (const [cancel, row] of [...timers]) 63 if (row.at <= now) { 64 cancel(); 65 row.callback(); 66 } 67 }, 68 timers 69 }; 70 } 71 function channel() { 72 let sink: (message: PublicPoolMessage) => void = () => {}; 73 let stopped = 0; 74 let opened = 0; 75 return { 76 open(this: void, next: (message: PublicPoolMessage) => void) { 77 opened++; 78 sink = next; 79 return () => { 80 stopped++; 81 }; 82 }, 83 emit(message: PublicPoolMessage) { 84 sink(message); 85 }, 86 counts: () => ({ opened, stopped }) 87 }; 88 } 89 describe('owned public request scopes', () => { 90 it('admits only six aggregate primary and auxiliary scopes before effects', () => { 91 const f = fixture(), 92 a = createPublicRun(f.scheduler, policy), 93 b = createPublicRun(f.scheduler, policy), 94 c = channel(); 95 const requests = Array.from({ length: 6 }, (_, i) => 96 openPublicRequest( 97 i < 3 ? a : b, 98 ['search', 'head', 'deletion', 'profile'][i % 4] as 99 'search' | 'head' | 'deletion' | 'profile', 100 c.open, 101 () => {} 102 ) 103 ); 104 expect(() => openPublicRequest(b, 'profile', c.open, () => {})).toThrow( 105 'public_request_concurrency_limit' 106 ); 107 expect(c.counts().opened).toBe(6); 108 expect(publicSchedulerSnapshot(f.scheduler).activeRequests).toBe(6); 109 closePublicRequest(requests[0]); 110 expect(publicSchedulerSnapshot(f.scheduler).activeRequests).toBe(5); 111 expect(publicRequestScopeSnapshot(requests[1]).state).toBe('active'); 112 openPublicRequest(b, 'head', c.open, () => {}); 113 closePublicScheduler(f.scheduler); 114 expect(f.timers.size).toBe(0); 115 expect(publicSchedulerSnapshot(f.scheduler).activeRequests).toBe(0); 116 }); 117 it('caps each request at ten seconds and never extends the absolute run deadline', () => { 118 const f = fixture(), 119 run = createPublicRun(f.scheduler, policy), 120 c = channel(); 121 const first = openPublicRequest(run, 'search', c.open, () => {}); 122 expect(publicRunSnapshot(run).deadline).toBe(15000); 123 expect(publicRequestScopeSnapshot(first).deadline).toBe(10000); 124 f.advance(10000); 125 expect(publicRequestScopeSnapshot(first).state).toBe('deadline'); 126 f.advance(14000); 127 const late = openPublicRequest(run, 'profile', c.open, () => {}); 128 expect(publicRequestScopeSnapshot(late).deadline).toBe(15000); 129 f.advance(15000); 130 expect(publicRequestScopeSnapshot(late).state).toBe('deadline'); 131 expect(() => openPublicRequest(run, 'head', c.open, () => {})).toThrow( 132 'public_run_inactive' 133 ); 134 expect(c.counts().stopped).toBe(2); 135 }); 136 it('checks absolute time on callbacks even when timer dispatch is delayed', () => { 137 const f = fixture(), 138 run = createPublicRun(f.scheduler, policy), 139 c = channel(); 140 let writes = 0; 141 const request = openPublicRequest(run, 'search', c.open, () => { 142 writes++; 143 }); 144 f.advance(10001, false); 145 c.emit({ type: 'EVENT', id: 'fixture', from: origin, event: event() }); 146 expect(writes).toBe(0); 147 expect(publicRequestScopeSnapshot(request).state).toBe('deadline'); 148 expect(publicRunSnapshot(run).ingress.deliveries).toBe(0); 149 expect(f.timers.size).toBe(0); 150 }); 151 it('cancellation invalidates late writes and leaves another owner running', () => { 152 const f = fixture(), 153 a = createPublicRun(f.scheduler, policy), 154 b = createPublicRun(f.scheduler, policy), 155 ca = channel(), 156 cb = channel(); 157 let writes = 0; 158 const ra = openPublicRequest(a, 'search', ca.open, () => { 159 writes++; 160 }), 161 rb = openPublicRequest(b, 'profile', cb.open, () => { 162 writes++; 163 }); 164 cancelPublicRun(a); 165 ca.emit({ type: 'EVENT', id: 'fixture', from: origin, event: event() }); 166 cb.emit({ type: 'EVENT', id: 'fixture', from: origin, event: event() }); 167 expect(writes).toBe(1); 168 expect(publicRequestScopeSnapshot(ra).state).toBe('cancelled'); 169 expect(publicRequestScopeSnapshot(rb).state).toBe('active'); 170 expect(cb.counts().stopped).toBe(0); 171 closePublicScheduler(f.scheduler); 172 }); 173 it('shares duplicate and rejected candidate charges across auxiliary scopes', () => { 174 const f = fixture(), 175 run = createPublicRun(f.scheduler, policy), 176 a = channel(), 177 b = channel(); 178 let writes = 0; 179 const ra = openPublicRequest(run, 'search', a.open, () => { 180 writes++; 181 }), 182 rb = openPublicRequest(run, 'deletion', b.open, () => { 183 writes++; 184 }); 185 a.emit({ type: 'EVENT', id: 'fixture', from: origin, event: event() }); 186 b.emit({ type: 'EVENT', id: 'fixture', from: origin, event: event() }); 187 b.emit({ 188 type: 'EVENT', 189 id: 'fixture', 190 from: origin, 191 event: { ...event(), sig: '0'.repeat(128) } 192 }); 193 expect(publicRunSnapshot(run).ingress.deliveries).toBe(3); 194 expect(writes).toBe(2); 195 expect(publicRunObservations(run, ra)).toHaveLength(1); 196 expect(publicRunObservations(run, rb)).toHaveLength(1); 197 closePublicScheduler(f.scheduler); 198 }); 199 it('finishes a bounded source at EOSE while preserving exact evidence', () => { 200 const f = fixture(), 201 run = createPublicRun(f.scheduler, policy), 202 c = channel(); 203 const request = openPublicRequest(run, 'head', c.open, () => {}); 204 c.emit({ type: 'EVENT', id: 'fixture', from: origin, event: event() }); 205 c.emit({ type: 'EOSE', id: 'fixture', from: origin }); 206 expect(publicRequestScopeSnapshot(request).state).toBe('eose'); 207 expect(publicRequestScopeSnapshot(request).result.definitiveAbsence).toBe( 208 false 209 ); 210 expect(publicRunObservations(run, request)).toHaveLength(1); 211 expect(c.counts().stopped).toBe(1); 212 cancelPublicRun(run); 213 expect(publicRunObservations(run, request)).toHaveLength(1); 214 disposePublicRun(run); 215 expect(publicRunObservations(run, request)).toEqual([]); 216 }); 217 it('cleans a synchronously completed open without orphaning its stop control', () => { 218 const f = fixture(), 219 run = createPublicRun(f.scheduler, policy); 220 let stops = 0; 221 const request = openPublicRequest( 222 run, 223 'search', 224 (next) => { 225 next({ type: 'EOSE', id: 'fixture', from: origin }); 226 return () => { 227 stops++; 228 }; 229 }, 230 () => {} 231 ); 232 expect(publicRequestScopeSnapshot(request).state).toBe('eose'); 233 expect(stops).toBe(1); 234 expect(publicSchedulerSnapshot(f.scheduler).activeRequests).toBe(0); 235 expect(f.timers.size).toBe(0); 236 }); 237 it('cleans rejected open and callback failures with safe outcome text', () => { 238 const f = fixture(), 239 run = createPublicRun(f.scheduler, policy); 240 expect(() => 241 openPublicRequest( 242 run, 243 'search', 244 () => { 245 throw new Error('PRIVATE_RAW_ERROR'); 246 }, 247 () => {} 248 ) 249 ).toThrow('public_request_open_failed'); 250 expect(publicSchedulerSnapshot(f.scheduler).activeRequests).toBe(0); 251 expect(f.timers.size).toBe(0); 252 const c = channel(); 253 const request = openPublicRequest(run, 'profile', c.open, () => { 254 throw new Error('PRIVATE_UI_ERROR'); 255 }); 256 c.emit({ type: 'EVENT', id: 'fixture', from: origin, event: event() }); 257 expect(publicRequestScopeSnapshot(request).state).toBe('error'); 258 expect(JSON.stringify(publicRequestScopeSnapshot(request))).not.toMatch( 259 /PRIVATE/ 260 ); 261 }); 262 it('rejects forged handles and another run observation context', () => { 263 const f = fixture(), 264 a = createPublicRun(f.scheduler, policy), 265 b = createPublicRun(f.scheduler, policy), 266 c = channel(); 267 const request = openPublicRequest(a, 'search', c.open, () => {}); 268 expect(Object.keys(request)).toEqual([]); 269 expect(Object.isFrozen(request)).toBe(true); 270 expect(() => publicRunObservations(b, request)).toThrow( 271 'public_request_run_changed' 272 ); 273 expect(() => closePublicRequest({} as typeof request)).toThrow( 274 'public_request_invalid' 275 ); 276 closePublicScheduler(f.scheduler); 277 expect(() => createPublicRun(f.scheduler, policy)).toThrow( 278 'public_scheduler_closed' 279 ); 280 }); 281 it('retains failed cleanup admission until explicit retry and stops successful controls once', () => { 282 const f = fixture(), 283 run = createPublicRun(f.scheduler, policy); 284 let stops = 0; 285 const request = openPublicRequest( 286 run, 287 'search', 288 () => () => { 289 stops++; 290 if (stops === 1) throw new Error('RAW_CLEANUP_ERROR'); 291 }, 292 () => {} 293 ); 294 expect(() => closePublicRequest(request)).toThrow( 295 'public_request_close_failed' 296 ); 297 expect(publicSchedulerSnapshot(f.scheduler).activeRequests).toBe(1); 298 expect(publicRequestScopeSnapshot(request).state).toBe('cancelled'); 299 closePublicRequest(request); 300 closePublicRequest(request); 301 expect(stops).toBe(2); 302 expect(publicSchedulerSnapshot(f.scheduler).activeRequests).toBe(0); 303 expect(f.timers.size).toBe(0); 304 closePublicScheduler(f.scheduler); 305 }); 306 it('lets the inclusive two-thousandth candidate finish then cancels every auxiliary scope', () => { 307 const f = fixture(), 308 run = createPublicRun(f.scheduler, policy), 309 a = channel(), 310 b = channel(); 311 let writes = 0; 312 const ra = openPublicRequest(run, 'search', a.open, () => { 313 writes++; 314 }), 315 rb = openPublicRequest(run, 'profile', b.open, () => { 316 writes++; 317 }); 318 for (let i = 0; i < 2000; i++) 319 (i % 2 === 0 ? a : b).emit({ 320 type: 'EVENT', 321 id: 'fixture', 322 from: origin, 323 event: event() 324 }); 325 expect(writes).toBe(2000); 326 expect(publicRunSnapshot(run).ingress.deliveries).toBe(2000); 327 expect(publicRunSnapshot(run).ingress.stopped).toBe(true); 328 expect(publicSchedulerSnapshot(f.scheduler).activeRequests).toBe(0); 329 expect(publicRequestScopeSnapshot(rb).state).toBe('limit'); 330 expect(publicRequestScopeSnapshot(ra).state).toBe('cancelled'); 331 expect(f.timers.size).toBe(0); 332 expect(publicRunObservations(run, ra)).toHaveLength(1); 333 expect(publicRunObservations(run, rb)).toHaveLength(1); 334 a.emit({ type: 'EVENT', id: 'fixture', from: origin, event: event() }); 335 expect(writes).toBe(2000); 336 disposePublicRun(run); 337 }); 338 it('does not extend captured deadlines when an injected clock moves backwards', () => { 339 const f = fixture(), 340 run = createPublicRun(f.scheduler, policy), 341 c = channel(); 342 f.advance(5000); 343 const request = openPublicRequest(run, 'head', c.open, () => {}); 344 expect(publicRequestScopeSnapshot(request).deadline).toBe(15000); 345 f.advance(1000, false); 346 expect(publicRunSnapshot(run).deadline).toBe(15000); 347 c.emit({ type: 'EVENT', id: 'fixture', from: origin, event: event() }); 348 expect(publicRequestScopeSnapshot(request).state).toBe('active'); 349 f.advance(15000); 350 expect(publicRequestScopeSnapshot(request).state).toBe('deadline'); 351 closePublicScheduler(f.scheduler); 352 }); 353 it('fails closed on invalid clock values and returns detached outcome snapshots', () => { 354 const f = fixture(), 355 run = createPublicRun(f.scheduler, policy), 356 c = channel(); 357 let writes = 0; 358 const request = openPublicRequest(run, 'search', c.open, () => { 359 writes++; 360 }); 361 const snapshot = publicRequestScopeSnapshot(request); 362 (snapshot as unknown as { state: string }).state = 'eose'; 363 expect(publicRequestScopeSnapshot(request).state).toBe('active'); 364 f.advance(Number.NaN, false); 365 c.emit({ type: 'EVENT', id: 'fixture', from: origin, event: event() }); 366 expect(writes).toBe(0); 367 expect(publicRequestScopeSnapshot(request).state).toBe('error'); 368 expect(publicSchedulerSnapshot(f.scheduler).activeRequests).toBe(0); 369 closePublicScheduler(f.scheduler); 370 }); 371 it('retries only a failed timer cancellation without repeating successful subscription cleanup', () => { 372 let timerCalls = 0, 373 stopCalls = 0; 374 const clock: RequestClock = { 375 now: () => 0, 376 schedule: () => () => { 377 timerCalls++; 378 if (timerCalls === 1) throw new Error('timer_failed'); 379 } 380 }; 381 const scheduler = createPublicScheduler(clock), 382 run = createPublicRun(scheduler, policy), 383 request = openPublicRequest( 384 run, 385 'search', 386 () => () => { 387 stopCalls++; 388 }, 389 () => {} 390 ); 391 expect(() => closePublicRequest(request)).toThrow( 392 'public_request_close_failed' 393 ); 394 expect(stopCalls).toBe(1); 395 expect(publicSchedulerSnapshot(scheduler).activeRequests).toBe(1); 396 closePublicRequest(request); 397 expect(timerCalls).toBe(2); 398 expect(stopCalls).toBe(1); 399 expect(publicSchedulerSnapshot(scheduler).activeRequests).toBe(0); 400 closePublicScheduler(scheduler); 401 }); 402 it('cancels auxiliary work even when the inclusive final candidate view callback throws', () => { 403 const f = fixture(), 404 run = createPublicRun(f.scheduler, policy), 405 a = channel(), 406 b = channel(); 407 let calls = 0; 408 const ra = openPublicRequest(run, 'search', a.open, () => {}), 409 rb = openPublicRequest(run, 'profile', b.open, () => { 410 calls++; 411 throw new Error('final_callback_failed'); 412 }); 413 for (let i = 0; i < 1999; i++) 414 a.emit({ type: 'EVENT', id: 'fixture', from: origin, event: event() }); 415 b.emit({ type: 'EVENT', id: 'fixture', from: origin, event: event() }); 416 expect(calls).toBe(1); 417 expect(publicRunSnapshot(run).ingress.deliveries).toBe(2000); 418 expect(publicRequestScopeSnapshot(rb).state).toBe('error'); 419 expect(publicRequestScopeSnapshot(ra).state).toBe('cancelled'); 420 expect(publicSchedulerSnapshot(f.scheduler).activeRequests).toBe(0); 421 expect(f.timers.size).toBe(0); 422 expect(publicRunObservations(run, ra)).toHaveLength(1); 423 expect(publicRunObservations(run, rb)).toHaveLength(1); 424 closePublicScheduler(f.scheduler); 425 }); 426 it('checks captured absolute time again when a deadline timer fires early', () => { 427 const f = fixture(), 428 run = createPublicRun(f.scheduler, policy), 429 c = channel(), 430 request = openPublicRequest(run, 'head', c.open, () => {}); 431 f.advance(9999, false); 432 const [cancel, row] = [...f.timers][0]; 433 cancel(); 434 row.callback(); 435 expect(publicRequestScopeSnapshot(request).state).toBe('active'); 436 expect(f.timers.size).toBe(1); 437 f.advance(10000); 438 expect(publicRequestScopeSnapshot(request).state).toBe('deadline'); 439 expect(f.timers.size).toBe(0); 440 closePublicScheduler(f.scheduler); 441 }); 442 }); 443 444 describe('per-source optional sample admission', () => { 445 const samplePolicy = validateRelayPolicy( 446 JSON.stringify({ 447 schemaVersion: 1, 448 public: [ 449 { origin, read: true, write: false, nip50: true }, 450 { 451 origin: 'wss://two.example.org', 452 read: true, 453 write: false, 454 nip50: false 455 } 456 ], 457 inbox: [], 458 postingEnabled: false, 459 messagingEnabled: false, 460 operatorDenylist: [] 461 }) 462 )!; 463 it('stops only the sample at100 including duplicate and rejected deliveries, leaving fallback alive', () => { 464 const f = fixture(), 465 run = createPublicRun(f.scheduler, samplePolicy), 466 sample = channel(), 467 fallback = channel(); 468 let accepted = 0; 469 const request = openPublicRequest( 470 run, 471 'search', 472 sample.open, 473 () => { 474 accepted++; 475 }, 476 origin 477 ); 478 const other = openPublicRequest(run, 'search', fallback.open, () => {}); 479 for (let i = 0; i < 99; i++) 480 sample.emit({ 481 type: 'EVENT', 482 id: 'sample', 483 from: origin, 484 event: i % 2 === 0 ? event() : { ...event(), id: '0'.repeat(64) } 485 }); 486 expect(publicRequestScopeSnapshot(request).state).toBe('active'); 487 sample.emit({ type: 'EVENT', id: 'sample', from: origin, event: event() }); 488 expect(accepted).toBe(51); 489 expect(publicRequestScopeSnapshot(request).state).toBe('partial'); 490 expect(publicRequestScopeSnapshot(request).result.sources).toHaveLength(1); 491 expect(publicRequestScopeSnapshot(request).result.sources[0]).toMatchObject( 492 { state: 'limit', candidates: 100, rejected: 49 } 493 ); 494 expect(publicRunSnapshot(run)).toMatchObject({ 495 active: true, 496 activeRequests: 1, 497 ingress: { deliveries: 100 } 498 }); 499 sample.emit({ type: 'EVENT', id: 'sample', from: origin, event: event() }); 500 expect(publicRunSnapshot(run).ingress.deliveries).toBe(100); 501 fallback.emit({ 502 type: 'EVENT', 503 id: 'fallback', 504 from: origin, 505 event: event() 506 }); 507 expect(publicRunSnapshot(run).ingress.deliveries).toBe(101); 508 expect(publicRequestScopeSnapshot(other).state).toBe('active'); 509 cancelPublicRun(run); 510 closePublicScheduler(f.scheduler); 511 }); 512 it('denies unqualified sample destinations and auxiliary sample misuse before provider acquisition', () => { 513 const f = fixture(), 514 run = createPublicRun(f.scheduler, samplePolicy), 515 provider = channel(); 516 expect(() => 517 openPublicRequest( 518 run, 519 'search', 520 provider.open, 521 () => {}, 522 'wss://two.example.org' 523 ) 524 ).toThrow('nip50_source_unqualified'); 525 expect(() => 526 openPublicRequest(run, 'head', provider.open, () => {}, origin) 527 ).toThrow('nip50_request_kind'); 528 expect(publicRunSnapshot(run)).toMatchObject({ 529 activeRequests: 0, 530 ingress: { deliveries: 0 } 531 }); 532 cancelPublicRun(run); 533 closePublicScheduler(f.scheduler); 534 }); 535 });