| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448 |
- import test from 'node:test';
- import assert from 'node:assert/strict';
- import { createHash } from 'node:crypto';
- import { createStore } from '../src/store.js';
- import { createNetworkHistory, validateHistoryCursor } from '../src/network-history.js';
- import { normalizeMessages } from '../src/teams-network-records.js';
- import { abortableDelay } from '../src/request-pacing.js';
- const accountId = 'web-api:11111111-1111-1111-1111-111111111111:22222222-2222-2222-2222-222222222222';
- const chatId = '19:fictional-history@thread.v2';
- const prefix = 'https://teams.cloud.microsoft/api/chatsvc/apac/v1/users/ME/conversations/';
- const view = 'msnp24Equivalent|supportsMessageProperties';
- const token = `fake.${Buffer.from(JSON.stringify({ tid: '11111111-1111-1111-1111-111111111111', oid: '22222222-2222-2222-2222-222222222222' })).toString('base64url')}.signature`;
- function url({ chat = chatId, cursor, start = '0', size = 2 } = {}) {
- const result = new URL(`${prefix}${encodeURIComponent(chat)}/messages`);
- result.searchParams.set('view', view); result.searchParams.set('pageSize', String(size)); result.searchParams.set('startTime', start);
- if (cursor) result.searchParams.set('syncState', cursor);
- return result.href;
- }
- function message(id, overrides = {}) {
- return { id, conversationid: chatId, conversationLink: `${prefix}${encodeURIComponent(chatId)}`,
- type: 'Message', messagetype: 'RichText/Html', contenttype: 'text', content: `<p>Fictional ${id}</p>`, imdisplayname: 'Fictional author',
- composetime: '2023-11-14T22:13:20Z', originalarrivaltime: '2023-11-14T22:13:20Z', version: '1700000000000', ...overrides };
- }
- function page(messages, { backward, boundary = 0, sync = url({ cursor: 'incremental-secret' }) } = {}) {
- return { messages, tenantId: 'fictional-tenant', _metadata: { lastCompleteSegmentStartTime: boundary, lastCompleteSegmentEndTime: 1800000000000,
- syncState: sync, ...(backward ? { backwardLink: backward } : {}) } };
- }
- const json = (payload, status = 200) => new Response(JSON.stringify(payload), { status, headers: { 'content-type': 'application/json' } });
- function har() {
- return { log: { entries: [{ request: { method: 'GET', url: url({ start: '1700000000000', size: 200 }),
- headers: [{ name: 'Authorization', value: `Bearer ${token}` }] },
- response: { status: 200, content: { mimeType: 'application/json', text: JSON.stringify(page([message('captured')], { boundary: 1700000000000 })) } },
- }] } };
- }
- function setup(fetch, options = {}) {
- const store = createStore(':memory:'), writes = [], originalSet = store.setState.bind(store);
- store.setState = (key, value) => { writes.push({ key, value: structuredClone(value) }); return originalSet(key, value); };
- let milliseconds = Date.parse('2026-09-08T00:00:00Z');
- const timing = { random: () => 0.5, clock: () => milliseconds, now: () => new Date(milliseconds).toISOString(),
- sleep: async (delay, { signal } = {}) => { if (signal?.aborted) throw new Error('cancelled'); milliseconds += delay; } };
- const history = createNetworkHistory({ har: har(), store, fetch, pageSize: 2, ...timing, ...options });
- return { store, history, writes, timing, advance: delay => { milliseconds += delay; }, close: () => store.close() };
- }
- test('history shares validated committed message pages for optional conversation names without making metadata failures fatal', async () => {
- const observed = [];
- const payload = page([message('history-name-link')]);
- const f = setup(async () => json(payload), { onMessages: (scope, body) => {
- assert.equal(f.store.stats().total, 1, 'record must be committed before discovery');
- assert.equal(f.history.coverage().complete, 1, 'history must already be committed');
- observed.push({ scope, body });
- throw new Error('Optional metadata failed with private details');
- } });
- try {
- const result = await f.history.runOnce();
- assert.equal(result.complete, true); assert.equal(result.successful, 1); assert.deepEqual(result.errors, []);
- assert.equal(observed.length, 1); assert.deepEqual(observed[0].body, payload);
- assert.equal(observed[0].scope.accountId, accountId); assert.equal(observed[0].scope.chatId, chatId);
- assert.equal(observed[0].scope.requestUrl, url());
- assert.equal(observed[0].scope.headers.Authorization, `Bearer ${token}`);
- await f.history.runOnce(); assert.equal(observed.length, 1, 'completed history must not be rescanned');
- assert.doesNotMatch(JSON.stringify(result), /private details|Bearer|signature/);
- } finally { f.close(); }
- });
- test('rejected or cancelled history responses never supply optional conversation-name evidence', async () => {
- for (const scenario of ['wrong-chat', 'invalid-cursor', 'invalid-boundary', 'cancelled']) {
- let observations = 0;
- const controller = new AbortController();
- const f = setup(async () => {
- if (scenario === 'cancelled') controller.abort();
- const payload = page([message('rejected', scenario === 'wrong-chat' ? { conversationid: 'other-chat' } : {})],
- scenario === 'invalid-cursor' ? { backward: 'https://untrusted.example/messages' } : {});
- if (scenario === 'invalid-boundary') delete payload._metadata.lastCompleteSegmentStartTime;
- return json(payload);
- }, { onMessages: () => { observations++; } });
- try {
- const result = await f.history.runOnce({ signal: controller.signal });
- assert.equal(observations, 0, scenario); assert.equal(f.store.stats().total, 0, scenario);
- assert.ok(result.cancelled || result.errors.length > 0, scenario);
- } finally { f.close(); }
- }
- });
- test('history starts at zero, follows only backwardLink, and completes only with an explicit zero boundary', async () => {
- const calls = [];
- const f = setup(async (request, options) => {
- calls.push({ request, options });
- return json(calls.length === 1 ? page([message('newer')], { backward: url({ cursor: 'older-secret' }), boundary: 100 }) : page([message('older')]));
- });
- try {
- const result = await f.history.runOnce();
- assert.equal(result.complete, true); assert.equal(result.coverage.complete, 1); assert.equal(result.coverage.pages, 2);
- assert.equal(new URL(calls[0].request).searchParams.get('startTime'), '0');
- assert.equal(new URL(calls[0].request).searchParams.has('syncState'), false);
- assert.equal(new URL(calls[1].request).searchParams.get('syncState'), 'older-secret');
- assert.ok(calls.every(call => call.options.method === 'GET' && call.options.redirect === 'manual'));
- assert.equal(f.store.stats().total, 2);
- assert.ok(f.writes.every(write => write.key.startsWith('web-api:history:')));
- assert.doesNotMatch(JSON.stringify(f.writes.map(write => write.value)), /Authorization|signature|Bearer/);
- assert.doesNotMatch(JSON.stringify(result), /older-secret|incremental-secret|fictional-history/);
- await f.history.runOnce(); assert.equal(calls.length, 2);
- } finally { f.close(); }
- });
- test('captured draftVersion is omitted from the history seed without widening backward-link validation or resetting progress', async () => {
- const captured = har(), recent = new URL(captured.log.entries[0].request.url);
- recent.searchParams.set('draftVersion', 'fictional-private-draft'); recent.searchParams.set('syncState', 'recent-secret');
- captured.log.entries[0].request.url = recent.href;
- const calls = [];
- const f = setup(async request => {
- calls.push(new URL(request));
- return json(page([message('archived')], calls.length === 1 ? { backward: url({ cursor: 'older-secret' }), boundary: 100 } : {}));
- }, { har: captured });
- try {
- const result = await f.history.runOnce();
- assert.equal(result.complete, true); assert.equal(calls.length, 2);
- assert.equal(calls[0].searchParams.get('startTime'), '0');
- assert.ok(calls.every(request => !request.searchParams.has('draftVersion')));
- assert.equal(calls[0].searchParams.has('syncState'), false);
- assert.equal(calls[1].searchParams.get('syncState'), 'older-secret');
- assert.equal(new URL(captured.log.entries[0].request.url).searchParams.get('draftVersion'), 'fictional-private-draft');
- assert.doesNotMatch(JSON.stringify(f.writes), /fictional-private-draft/);
- const resumed = createNetworkHistory({ har: captured, store: f.store, pageSize: 2, ...f.timing, fetch: async () => { throw new Error('Completed history must not fetch again'); } });
- assert.equal((await resumed.runOnce()).coverage.pages, 2);
- const untrusted = new URL(url({ cursor: 'older-secret' })); untrusted.searchParams.set('draftVersion', 'unapproved');
- assert.throws(() => validateHistoryCursor(untrusted.href, recent.href), { code: 'invalid_history_cursor' });
- } finally { f.close(); }
- });
- test('history derives only chat metadata from the peer and uses its current title on later pages despite a stale catalogue', async () => {
- const self='22222222-2222-2222-2222-222222222222', peer='33333333-3333-3333-3333-333333333333';
- let calls=0;
- const sender=id=>`https://teams.cloud.microsoft/api/chatsvc/apac/v1/users/ME/contacts/${encodeURIComponent(`8:orgid:${id}`)}`;
- const f=setup(async()=>json(++calls===1
- ?page([message('peer-author',{from:sender(peer),imdisplayname:'Fictional peer'})],{backward:url({cursor:'older-page'}),boundary:1})
- :page([message('self-author',{from:sender(self),imdisplayname:'Fictional self'})])));
- try {
- f.store.upsertRecord({source:'web-api',accountId,kind:'chat',externalId:chatId,title:'聊天',raw:{isOneOnOne:true,titleSource:'placeholder'}});
- const catalogueKey='web-api:chats:'+createHash('sha256').update(accountId+'https://teams.cloud.microsoft'+'/api/chatsvc/apac/v1/users/ME/conversations/').digest('hex').slice(0,24);
- f.store.setState(catalogueKey,{chats:[{id:chatId,title:'聊天'}]});f.history.refreshChats();
- const result=await f.history.runOnce();assert.equal(result.complete,true);assert.equal(calls,2);
- const named=f.store.getRecordByIdentity({source:'web-api',accountId,kind:'chat',externalId:chatId});
- assert.equal(named.title,'Fictional peer');assert.equal(named.raw.titleSource,'message-author');
- const messages=f.store.listRecords({kind:'message'}).items;
- assert.equal(messages.find(record=>record.raw.messageId==='self-author').title,'Fictional peer');
- assert.equal(messages.find(record=>record.raw.messageId==='self-author').raw.author,'Fictional self');
- const messageChanges=f.store.readRows("SELECT c.ingestion FROM change_log c JOIN records r ON c.recordId=r.id WHERE r.kind='message'");
- assert.ok(messageChanges.every(row=>row.ingestion==='history'));
- const versions=f.store.stats().versions;f.history.refreshChats();await f.history.runOnce();
- assert.equal(calls,2);assert.equal(f.store.stats().versions,versions);
- } finally {f.close();}
- });
- test('request-budget exhaustion persists an independent checkpoint and a fresh instance resumes its next page', async () => {
- let calls = 0;
- const fetch = async request => { calls++; return json(new URL(request).searchParams.has('syncState') ? page([message('old')]) : page([message('new')], { backward: url({ cursor: 'next-history-secret' }), boundary: 100 })); };
- const f = setup(fetch, { maxRequests: 1 });
- try {
- f.store.setState('web-api:cursor:watch-owned', { url: 'watch-private-cursor' });
- const first = await f.history.runOnce();
- assert.equal(first.complete, false); assert.equal(first.budgetExhausted, true); assert.equal(first.coverage.pending, 1);
- const next = createNetworkHistory({ har: har(), store: f.store, fetch, maxRequests: 1, pageSize: 2, ...f.timing });
- const second = await next.runOnce();
- assert.equal(second.complete, true); assert.equal(calls, 2);
- assert.deepEqual(f.store.getState('web-api:cursor:watch-owned'), { url: 'watch-private-cursor' });
- assert.equal(f.store.stats().total, 2);
- } finally { f.close(); }
- });
- test('an empty incremental-looking response or a missing backwardLink above zero is explicitly incomplete', async () => {
- for (const messages of [[], [message('recent')]]) {
- const f = setup(async () => json(page(messages, { boundary: 1700000000000 })));
- try {
- const result = await f.history.runOnce();
- assert.equal(result.complete, false); assert.equal(result.coverage.truncated, 1);
- assert.equal(result.coverage.stopReasons['unproven-start'], 1);
- } finally { f.close(); }
- }
- });
- test('control-only pages still advance history instead of treating zero normalized records as completion', async () => {
- let calls = 0;
- const f = setup(async () => json(++calls === 1
- ? page([message('control', { messagetype: 'ThreadActivity/MemberJoined' })], { boundary: 100, backward: url({ cursor: 'next' }) })
- : page([message('user')])));
- try {
- const result = await f.history.runOnce();
- assert.equal(calls, 2); assert.equal(result.complete, true); assert.equal(result.skippedItems, 1); assert.equal(f.store.stats().total, 1);
- } finally { f.close(); }
- });
- test('invalid cross-chat and cross-origin cursors cannot advance a checkpoint or commit a page', async () => {
- for (const backward of [url({ chat: '19:other-chat', cursor: 'private-marker' }), url({ cursor: 'private-marker' }).replace('teams.cloud.microsoft', 'untrusted.example')]) {
- const f = setup(async () => json(page([message('unsafe')], { backward, boundary: 100 })));
- try {
- const result = await f.history.runOnce();
- assert.equal(result.successful, 0); assert.equal(result.errors.length, 1); assert.equal(f.store.stats().total, 0);
- assert.equal(result.coverage.errors, 1); assert.equal(f.writes.at(-1).value.pages, 0);
- assert.equal(new URL(f.writes.at(-1).value.nextUrl).searchParams.has('syncState'), false);
- assert.doesNotMatch(JSON.stringify(result), /private-marker|untrusted|other-chat/);
- } finally { f.close(); }
- }
- });
- test('cursor validation accepts path encoding differences but rejects duplicate or unsupported query parameters', () => {
- const original = url();
- const compatible = url({ cursor: 'safe' }).replace(encodeURIComponent(chatId), chatId);
- assert.equal(new URL(validateHistoryCursor(compatible, original)).origin, 'https://teams.cloud.microsoft');
- for (const candidate of [`${url({ cursor: 'safe' })}&startTime=0`, `${url()}&endTime=1`, `${url()}&token=secret`, url().replace('pageSize=2', 'pageSize=500')]) {
- assert.throws(() => validateHistoryCursor(candidate, original), { code: 'invalid_history_cursor' });
- }
- });
- test('message and checkpoint commits roll back together and the same page is retryable after storage recovers', async () => {
- const f = setup(async () => json(page([message('transactional')])));
- const originalSet = f.store.setState;
- try {
- f.store.setState = () => { throw new Error('fictional database error private-marker'); };
- const failed = await f.history.runOnce();
- assert.equal(failed.successful, 0); assert.equal(f.store.stats().total, 0); assert.equal(f.history.coverage().pages, 0);
- assert.doesNotMatch(JSON.stringify(failed), /private-marker/);
- f.store.setState = originalSet;
- const recovered = await f.history.runOnce();
- assert.equal(recovered.complete, true); assert.equal(f.store.stats().total, 1);
- } finally { f.close(); }
- });
- test('repeated cursors and per-conversation page limits stop explicitly rather than claiming completion', async () => {
- const f = setup(async () => json(page([message('loop')], { backward: url(), boundary: 100 })));
- try {
- const result = await f.history.runOnce();
- assert.equal(result.requests, 1); assert.equal(result.complete, false); assert.equal(result.coverage.stopReasons['repeated-cursor'], 1);
- } finally { f.close(); }
- const g = setup(async () => json(page([message('bounded')], { backward: url({ cursor: 'next' }), boundary: 100 })), { maxPages: 1 });
- try {
- const result = await g.history.runOnce();
- assert.equal(result.coverage.stopReasons['page-limit'], 1); assert.equal(result.complete, false);
- const resumed = createNetworkHistory({ har: har(), store: g.store, pageSize: 2, maxPages: 2, fetch: async () => json(page([message('last')])), ...g.timing });
- assert.equal((await resumed.runOnce()).complete, true);
- } finally { g.close(); }
- });
- test('authentication pauses until a renewed collector; 429 and 5xx defer rounds until cooldown expires', async () => {
- for (const status of [429, 503]) {
- let calls = 0;
- const f = setup(async () => ++calls === 1 ? json({}, status) : json(page([message('retry')])));
- try {
- assert.equal((await f.history.runOnce()).ok, false);
- const deferred = await f.history.runOnce();
- assert.equal(deferred.deferred, true); assert.equal(deferred.requests, 0); assert.equal(calls, 1);
- f.advance(30_000);
- assert.equal((await f.history.runOnce()).complete, true); assert.equal(calls, 2);
- } finally { f.close(); }
- }
- let authCalls = 0;
- const f = setup(async () => { authCalls++; return json({}, 401); });
- try {
- assert.equal((await f.history.runOnce()).authRequired, true);
- await f.history.runOnce(); assert.equal(authCalls, 1);
- const renewed = createNetworkHistory({ har: har(), store: f.store, fetch: async () => json(page([message('renewed')])), pageSize: 2, ...f.timing });
- assert.equal((await renewed.runOnce()).complete, true);
- } finally { f.close(); }
- });
- test('refreshChats reads new persisted chat records without requiring mutable watch cursors or duplicate targets', () => {
- const f = setup(async () => json(page([])));
- try {
- f.store.upsertRecord({ source: 'web-api', accountId, kind: 'chat', externalId: '19:later-discovered', title: 'Fictional later chat', text: '' });
- assert.equal(f.history.coverage().conversations, 1);
- assert.equal(f.history.refreshChats().conversations, 2);
- assert.equal(f.history.refreshChats().conversations, 2);
- assert.equal(f.writes.length, 0);
- const empty = createNetworkHistory({ har: { log: { entries: [] } }, store: f.store, ...f.timing });
- assert.equal(empty.coverage().conversations, 0);
- } finally { f.close(); }
- });
- test('older history never overwrites a newer real-time record when both versions have valid timestamps', async () => {
- const f = setup(async () => json(page([message('same-id')])));
- try {
- const newer = normalizeMessages(page([message('same-id', { content: '<p>New live version</p>', version: '1800000000000' })]), { accountId, chatId }).records[0];
- f.store.upsertRecord(newer);
- const result = await f.history.runOnce();
- assert.equal(result.complete, true); assert.equal(result.skippedOlderRecords, 1);
- assert.equal(f.store.getRecordByIdentity(newer).text, 'New live version');
- assert.equal(f.store.stats().versions, 1);
- } finally { f.close(); }
- });
- test('concurrent calls share one pass and cancellation does not commit an in-flight response', async () => {
- let release, calls = 0;
- const f = setup(async () => { calls++; return new Promise(resolve => { release = resolve; }); });
- const controller = new AbortController();
- try {
- const first = f.history.runOnce({ signal: controller.signal });
- while (!release) await new Promise(resolve => setImmediate(resolve));
- const duplicate = f.history.runOnce({ signal: controller.signal });
- controller.abort(); release(json(page([message('cancelled')])));
- const result = await first; await duplicate;
- assert.equal(calls, 1); assert.equal(result.cancelled, true); assert.equal(f.store.stats().total, 0); assert.equal(f.writes.length, 0);
- } finally { f.close(); }
- });
- test('backward pagination accepts the observed property-capability reduction only', async () => {
- const backward = new URL(url({ cursor: 'older' })); backward.searchParams.set('view', 'msnp24Equivalent');
- assert.equal(validateHistoryCursor(backward.href, url()), backward.href);
- const unknown = new URL(backward); unknown.searchParams.set('view', 'unobserved-mode');
- assert.throws(() => validateHistoryCursor(unknown.href, url()));
- let calls = 0;
- const f = setup(async () => json(++calls === 1 ? page([message('new')], { backward: backward.href, boundary: 1 }) : page([message('old')])));
- try { assert.equal((await f.history.runOnce()).complete, true); assert.equal(calls, 2); }
- finally { f.close(); }
- });
- test('history restores the same authenticated catalogue as monitoring and excludes activity service streams', () => {
- const f = setup(async () => json(page([])));
- try {
- const key = 'web-api:chats:' + createHash('sha256').update(accountId + 'https://teams.cloud.microsoft' + '/api/chatsvc/apac/v1/users/ME/conversations/').digest('hex').slice(0, 24);
- f.store.setState(key, { chats: [{ id: chatId }, { id: '19:captured-earlier@thread.v2' }, { id: '48:activity' }, { id: 'bad\nidentity' }] });
- const before = structuredClone(f.store.getState(key));
- const coverage = f.history.refreshChats();
- assert.equal(coverage.conversations, 2); assert.equal(coverage.skipped.activityConversation, 1); assert.equal(coverage.skipped.invalidCatalogueChat, 1);
- f.history.refreshChats(); assert.equal(f.history.coverage().conversations, 2); assert.deepEqual(f.store.getState(key), before);
- } finally { f.close(); }
- });
- test('completed legacy checkpoints rescan once for newly supported Text without duplicating existing records', async () => {
- const f = setup(async () => json(page([message('existing')])));
- try {
- await f.history.runOnce();
- const saved = f.writes.at(-1), legacy = { ...saved.value }; delete legacy.adapterVersion;
- f.store.setState(saved.key, legacy);
- let calls = 0;
- const fetch = async () => { calls++; return json(page([message('existing'), message('plain', { messagetype: 'Text', content: '<literal>' })])); };
- const upgraded = createNetworkHistory({ har: har(), store: f.store, fetch, ...f.timing });
- const result = await upgraded.runOnce(); assert.equal(result.complete, true); assert.equal(result.changed, 1); assert.equal(f.store.stats().total, 2);
- const restarted = createNetworkHistory({ har: har(), store: f.store, fetch, ...f.timing });
- await restarted.runOnce(); assert.equal(calls, 1); assert.equal(f.store.getState(saved.key).adapterVersion, 5);
- } finally { f.close(); }
- });
- test('history waits randomly before its first and following requests, then skips waiting when work is complete', async () => {
- const events = [], samples = [0, 1];
- let calls = 0;
- const f = setup(async () => {
- events.push('request');
- return json(++calls === 1 ? page([message('new')], { backward: url({ cursor: 'older' }), boundary: 1 }) : page([message('old')]));
- }, { random: () => samples.shift(), sleep: async delay => { events.push(delay); } });
- try {
- assert.equal((await f.history.runOnce()).complete, true);
- assert.deepEqual(events, [2000, 'request', 5000, 'request']);
- await f.history.runOnce(); assert.equal(events.length, 4);
- const empty = createNetworkHistory({ har: { log: { entries: [] } }, store: f.store,
- sleep: async () => { throw new Error('No work must not wait.'); }, fetch: async () => { throw new Error('No work must not request.'); } });
- assert.equal((await empty.runOnce()).requests, 0);
- } finally { f.close(); }
- });
- test('cancellation during initial jitter prevents all requests and writes', async () => {
- let calls = 0;
- const controller = new AbortController();
- const f = setup(async () => { calls++; return json(page([])); }, { sleep: abortableDelay });
- try {
- const run = f.history.runOnce({ signal: controller.signal });
- assert.equal(f.history.pacing().waiting, true);
- controller.abort(); const result = await run;
- assert.equal(result.cancelled, true); assert.equal(result.requests, 0); assert.equal(calls, 0); assert.equal(f.writes.length, 0);
- assert.equal(f.history.pacing().waiting, false);
- } finally { f.close(); }
- });
- test('cancelling between pages preserves a valid cursor and a replacement continues that page', async () => {
- let waits = 0, calls = 0;
- const controller = new AbortController();
- const f = setup(async () => { calls++; return json(page([message('new')], { backward: url({ cursor: 'durable-next' }), boundary: 1 })); },
- { sleep: async (delay, options) => { if (++waits > 1) await abortableDelay(delay, options); } });
- try {
- const run = f.history.runOnce({ signal: controller.signal });
- while (waits < 2) await new Promise(resolve => setImmediate(resolve));
- const checkpoint = f.writes.at(-1);
- controller.abort(); const stopped = await run;
- assert.equal(stopped.cancelled, true); assert.equal(calls, 1); assert.equal(stopped.coverage.pages, 1);
- assert.deepEqual(f.store.getState(checkpoint.key), checkpoint.value);
- const resumed = createNetworkHistory({ har: har(), store: f.store, ...f.timing, fetch: async request => {
- assert.equal(new URL(request).searchParams.get('syncState'), 'durable-next');
- return json(page([message('old')]));
- } });
- assert.equal((await resumed.runOnce()).complete, true);
- assert.equal(f.store.stats().total, 2);
- } finally { f.close(); }
- });
- test('Retry-After stops same-origin chat switching and stays deferred across rounds and worker restart', async () => {
- let calls = 0;
- const fetch = async () => { calls++; return new Response('{}', { status: 429, headers: { 'retry-after': '90' } }); };
- const f = setup(fetch);
- try {
- f.store.upsertRecord({ source: 'web-api', accountId, kind: 'chat', externalId: '19:second', title: 'Other chat' });
- f.history.refreshChats();
- const first = await f.history.runOnce();
- assert.equal(first.requests, 1); assert.equal(first.deferred, true); assert.equal(first.pacing.coolingDownOrigins, 1);
- const restarted = createNetworkHistory({ har: har(), store: f.store, fetch, ...f.timing });
- assert.equal((await restarted.runOnce()).requests, 0); assert.equal(calls, 1);
- f.advance(89_999); assert.equal((await restarted.runOnce()).requests, 0); assert.equal(calls, 1);
- f.advance(1); assert.equal((await restarted.runOnce()).requests, 1); assert.equal(calls, 2);
- assert.doesNotMatch(JSON.stringify(first.pacing), /https|fictional|second|signature/);
- } finally { f.close(); }
- });
- test('a received server cooldown survives simultaneous cancellation while pure cancellation adds no cooldown', async () => {
- for (const status of [429, 503]) {
- const controller = new AbortController();
- const f = setup(async () => { controller.abort(); return new Response('{}', { status, headers: { 'retry-after': '120' } }); });
- try {
- const result = await f.history.runOnce({ signal: controller.signal });
- assert.equal(result.cancelled, true); assert.equal(result.pacing.coolingDownOrigins, 1);
- const restarted = createNetworkHistory({ har: har(), store: f.store, ...f.timing, fetch: async () => { throw new Error('Must remain deferred.'); } });
- assert.equal((await restarted.runOnce()).deferred, true);
- assert.equal(f.history.coverage().pages, 0);
- } finally { f.close(); }
- }
- const controller = new AbortController();
- const f = setup(async () => { controller.abort(); throw new Error('cancelled network'); });
- try {
- const result = await f.history.runOnce({ signal: controller.signal });
- assert.equal(result.cancelled, true); assert.equal(result.pacing.coolingDownOrigins, 0); assert.equal(f.writes.length, 0);
- } finally { f.close(); }
- });
- test('version 3 history is rescanned once for emoji recovery and all restored changes stay historical', async () => {
- const f = setup(async () => json(page([])));
- try {
- await f.history.runOnce();
- const checkpoint = f.writes.at(-1);
- f.store.setState(checkpoint.key, { ...checkpoint.value, adapterVersion: 3 });
- let calls = 0;
- const fetch = async () => { calls++; return json(page([message('emoji', { messagetype: 'Text', content: '😀' })])); };
- const upgraded = createNetworkHistory({ har: har(), store: f.store, fetch, ...f.timing });
- assert.equal((await upgraded.runOnce()).changed, 1);
- const changes = f.store.readRows('SELECT ingestion FROM change_log');
- assert.deepEqual(changes.map(row => row.ingestion), ['history']);
- const restarted = createNetworkHistory({ har: har(), store: f.store, fetch, ...f.timing });
- assert.equal((await restarted.runOnce()).requests, 0); assert.equal(calls, 1);
- assert.equal(f.store.getState(checkpoint.key).adapterVersion, 5);
- } finally { f.close(); }
- });
|