Merge branch 'issue-180-tag-link-sync' into issue-181-tag-updated-at

This commit is contained in:
le king fu 2026-11-03 20:42:41 -05:00
commit 9a81322527
6 changed files with 87 additions and 8 deletions

View file

@ -30,7 +30,7 @@ export interface RequestTracker {
export interface SyncRun extends RequestTracker {
/**
* POST batches this run may send: the remaining budget minus one place for
* the GET of the pull. The rest of the queue goes to the next run.
* the GET of the pull, at least 1. The rest of the queue goes to the next run.
*/
readonly pushBatches: number;
/** True once a 429 suspended the scheduler: the run sends nothing more. */
@ -154,9 +154,12 @@ export function createSyncScheduler(deps: SchedulerDeps): SyncScheduler {
return;
}
const left = remaining(now);
if (left < 1) {
// The oldest request leaves the window first
arm(sent[0] + BUDGET_WINDOW_MS - now);
if (left < 2) {
// A run needs a place for one POST and one for the GET. Starting with a
// single place would only pull, and a queue whose places free up one by
// one would never be sent (review of PR #184). Wait until the second
// oldest request in the window leaves it.
arm(sent[sent.length - REQUEST_BUDGET + 1] + BUDGET_WINDOW_MS - now);
return;
}
start(left);

View file

@ -243,6 +243,11 @@ check('sync on write and every sync go through the scheduler (#178)', () => {
assert.match(body, /await scheduler\.beginInitialSync\(\);\s*try \{[^]*\} finally \{\s*scheduler\.endInitialSync\(\);/, `${name} must hold the first-sync state`);
}
assert.equal((client.match(/pullChanges\(SYNC_EPOCH, scheduler\.tracker\)/g) || []).length, 2, 'the first-sync pulls are counted');
// Review of PR #184: initialMerge's POST batches count against the budget,
// and pushChanges tells the scheduler when the budget left entries unsent
const merge = client.slice(client.indexOf('async function mergeLocalData('), client.indexOf('export async function initialReset('));
assert.match(merge, /post: \(batch\) => postBatch\(batch, headers, scheduler\.tracker\),/, 'initialMerge must count its POST batches');
assert.match(client, /return \{ more: ok && operations\.length > maxBatches \* BATCH_SIZE \};\n\}/, 'pushChanges must report an unsent queue');
});
// No merge across accounts (#165). firstSyncChoice and canSync are executed
@ -439,7 +444,7 @@ check('tag links: removals written by the app, pull aligned without the outbox (
assert.match(set, /tagLinkDiff\(/, 'setTagsForTask must diff with the local links');
assert.match(set, /for \(const tagId of removed\) \{\s*writeOutboxEntry\('taskTag', taskId, 'delete', \{ tagId \}\)/);
assert.match(set, /for \(const tagId of added\) \{\s*writeOutboxEntry\('taskTag', taskId, 'create', \{ tagId \}\)/);
assert.ok(!/db\.delete\(taskTags\)\.where\(eq\(taskTags\.taskId, taskId\)\)/.test(set), 'setTagsForTask must not wipe every link');
assert.ok(!/db\s*\.delete\(taskTags\)\s*\.where\(eq\(taskTags\.taskId, taskId\)\)/.test(set), 'setTagsForTask must not wipe every link');
assert.match(fnOf(tags, 'addTagToTask'), /writeOutboxEntry\('taskTag', taskId, 'create', \{ tagId \}\)\.then\(requestSync\)/);
assert.match(fnOf(tags, 'removeTagFromTask'), /writeOutboxEntry\('taskTag', taskId, 'delete', \{ tagId \}\)\.then\(requestSync\)/);

View file

@ -12,6 +12,7 @@ import assert from 'node:assert/strict';
import {
BUDGET_WINDOW_MS,
DEFAULT_RETRY_AFTER_S,
MAX_RETRY_AFTER_S,
REQUEST_BUDGET,
canSync,
createSyncScheduler,
@ -51,11 +52,15 @@ async function flush() {
// A server stand-in: a queue of POST batches, each run pushes up to
// ctx.pushBatches of them then pulls once. Records every request time.
function fakeServer(clock, { batches = 0, status = () => 200, duration = 0 } = {}) {
const state = { queue: batches, requests: [], runs: 0, active: 0, maxActive: 0, starts: [] };
// `latency` is the response time of each request: the requests of one run
// are then spread in time, as on a real network (review of PR #184).
function fakeServer(clock, { batches = 0, status = () => 200, duration = 0, latency = 0 } = {}) {
const state = { queue: batches, requests: [], runs: 0, active: 0, maxActive: 0, starts: [], emptyPushRuns: 0 };
const respond = () => (latency ? new Promise((resolve) => clock.setTimer(resolve, latency)) : undefined);
state.run = async (ctx) => {
state.runs++;
state.starts.push(clock.now());
if (state.queue > 0 && ctx.pushBatches < 1) state.emptyPushRuns++;
state.active++;
state.maxActive = Math.max(state.maxActive, state.active);
try {
@ -65,6 +70,7 @@ function fakeServer(clock, { batches = 0, status = () => 200, duration = 0 } = {
ctx.request();
state.requests.push(clock.now());
sent++;
await respond();
const s = status('POST');
if (s === 429) {
ctx.rateLimited(20);
@ -75,6 +81,7 @@ function fakeServer(clock, { batches = 0, status = () => 200, duration = 0 } = {
if (ctx.isSuspended()) return { more: state.queue > 0 };
ctx.request();
state.requests.push(clock.now());
await respond();
const s = status('GET');
if (s === 429) ctx.rateLimited(20);
return { more: state.queue > 0 };
@ -204,6 +211,37 @@ test('an unsent queue is resumed without a new request once the budget allows',
assert.ok(maxInAnyWindow(server.requests) <= REQUEST_BUDGET);
});
test('with 300 ms per request, a 9-batch queue empties in bounded time and no run starts without a POST place', async () => {
const clock = fakeClock();
const server = fakeServer(clock, { batches: 9, latency: 300 });
const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run });
s.request();
// The 30 s foreground interval keeps asking
for (let t = 0; t < 4 * BUDGET_WINDOW_MS; t += 30_000) {
await clock.advance(30_000);
s.request();
}
assert.equal(server.queue, 0, `${server.queue} batch(es) still queued after 4 min (${server.runs} runs)`);
assert.equal(server.emptyPushRuns, 0, 'a run started with pushBatches = 0 while the queue was not empty');
assert.ok(maxInAnyWindow(server.requests) <= REQUEST_BUDGET, `max ${maxInAnyWindow(server.requests)} in a window`);
});
test('with a single free place, no run starts until a second one frees up', async () => {
const clock = fakeClock();
const server = fakeServer(clock, { batches: 1 });
const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run });
s.tracker.request();
await clock.advance(1000);
for (let i = 1; i < REQUEST_BUDGET - 1; i++) s.tracker.request();
s.request();
await clock.advance(BUDGET_WINDOW_MS - 1001);
assert.equal(server.runs, 0, 'one place left: a run would only pull');
await clock.advance(1);
assert.equal(server.runs, 1, 'the run starts once the oldest request leaves the window');
assert.equal(server.emptyPushRuns, 0);
assert.equal(server.queue, 0);
});
test('after a 429 with Retry-After: 20, no request before 20 s', async () => {
const clock = fakeClock();
let first = true;
@ -250,6 +288,18 @@ test('a 429 without a readable Retry-After suspends for the default delay', asyn
assert.equal(starts, 2);
});
test('a huge Retry-After is bounded to MAX_RETRY_AFTER_S', async () => {
const clock = fakeClock();
const server = fakeServer(clock);
const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run });
s.tracker.rateLimited(100_000);
s.request();
await clock.advance(MAX_RETRY_AFTER_S * 1000 - 1);
assert.equal(server.runs, 0);
await clock.advance(1);
assert.equal(server.runs, 1, 'the scheduler resumes after MAX_RETRY_AFTER_S');
});
test('a 429 reported outside a run (initial sync) also suspends the scheduler', async () => {
const clock = fakeClock();
const server = fakeServer(clock);

View file

@ -181,6 +181,22 @@ describe('GET /api/lists/[id]/tasks?tags=', () => {
expect((await res.json() as { id: string }[]).map((t) => t.id)).toEqual([a.t2]);
});
it('applies dueDate with a tag filter', async () => {
const a = await seedAccount();
await exec('UPDATE sl_tasks SET due_date = $1 WHERE id = $2', ['2026-01-10T00:00:00Z', a.t1]);
// t2 (blue too) has no due date: excluded by the dueDate filter
const res = await getTasks(a.userId, a.list, `?tags=${a.blue}&dueDate=2026-02-01T00:00:00Z`);
expect(res.status).toBe(200);
expect((await res.json() as { id: string }[]).map((t) => t.id)).toEqual([a.t1]);
});
it('ignores a non-integer priority instead of failing', async () => {
const a = await seedAccount();
const res = await getTasks(a.userId, a.list, '?priority=abc');
expect(res.status).toBe(200);
expect((await res.json() as { id: string }[]).map((t) => t.id)).toEqual([a.t1, a.t2, a.t3]);
});
it('still answers 404 for a list of another account', async () => {
const a = await seedAccount();
const res = await getTasks(`user-${u()}`, a.list, '');

View file

@ -12,6 +12,7 @@ type FakeSocket = EventEmitter & {
userId: string;
readyState: number;
send: ReturnType<typeof vi.fn>;
terminate: ReturnType<typeof vi.fn>;
};
const OPEN = 1; // WebSocket.OPEN
@ -22,7 +23,7 @@ const g = globalThis as unknown as {
};
function fakeSocket(userId: string): FakeSocket {
return Object.assign(new EventEmitter(), { userId, readyState: OPEN, send: vi.fn() });
return Object.assign(new EventEmitter(), { userId, readyState: OPEN, send: vi.fn(), terminate: vi.fn() });
}
async function freshModule() {
@ -106,6 +107,7 @@ describe('notifyUserChanged', () => {
ws.notifyUserChanged('user-a');
expect(() => vi.advanceTimersByTime(ws.NOTIFY_DEBOUNCE_MS)).not.toThrow();
expect(ws.getActiveConnections()).toBe(0);
expect(a.terminate).toHaveBeenCalledTimes(1);
});
});

View file

@ -171,7 +171,10 @@ export function broadcastToUser(userId: string, message: WsMessage) {
try {
ws.send(payload);
} catch {
// Close it too: left open, it would escape the heartbeat and the page
// would never be notified again (its onclose reconnects it).
clients.delete(ws);
ws.terminate();
}
}
}