-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathqueue-consumer.test.ts
More file actions
405 lines (361 loc) · 12.7 KB
/
queue-consumer.test.ts
File metadata and controls
405 lines (361 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
import { describe, it, expect, vi } from 'vitest';
import type * as SessionEvents from './session-events';
// Mock cloudflare:workers before any imports that might pull in DO code
vi.mock('cloudflare:workers', () => ({
DurableObject: class DurableObject {
constructor(_state: unknown, _env: unknown) {}
},
WorkerEntrypoint: class WorkerEntrypoint {
env: unknown;
ctx: ExecutionContext;
constructor() {
this.env = undefined;
this.ctx = {
waitUntil: () => {},
passThroughOnException: () => {},
} as unknown as ExecutionContext;
}
},
}));
vi.mock('@kilocode/db/client', () => ({
getWorkerDb: vi.fn(),
}));
vi.mock('./dos/SessionIngestDO', () => ({
getSessionIngestDO: vi.fn(),
}));
vi.mock('./session-events', async importOriginal => {
const actual = await importOriginal<typeof SessionEvents>();
return {
...actual,
notifyUserSessionEvent: vi.fn(),
};
});
// Mock ingest-limits so we can exercise both streaming and SQLite-row compaction thresholds.
vi.mock('./util/ingest-limits', () => ({
MAX_INGEST_ITEM_BYTES: 100,
MAX_SINGLE_ITEM_BYTES: 500,
}));
import { getWorkerDb } from '@kilocode/db/client';
import { getSessionIngestDO } from './dos/SessionIngestDO';
import { notifyUserSessionEvent } from './session-events';
import {
QUEUE_RETRY_DELAY_SECONDS,
computeSessionMetadataUpdates,
createItemExtractor,
queue,
} from './queue-consumer';
const encoder = new TextEncoder();
function feedAll(extractor: ReturnType<typeof createItemExtractor>, json: string) {
extractor.tokenizer.write(encoder.encode(json));
extractor.tokenizer.end();
}
describe('createItemExtractor', () => {
it('parses items from valid { data: [...] } payload', () => {
const ext = createItemExtractor('test-key');
const payload = JSON.stringify({
data: [
{ type: 'session', data: { title: 'Hello' } },
{ type: 'message', data: { id: 'msg_1' } },
],
});
feedAll(ext, payload);
expect(ext.pending).toHaveLength(2);
expect(ext.pending[0]).toEqual({ type: 'session', data: { title: 'Hello' } });
expect(ext.pending[1]).toEqual({ type: 'message', data: { id: 'msg_1' } });
expect(ext.getParseError()).toBeNull();
});
it('handles empty data array', () => {
const ext = createItemExtractor('test-key');
feedAll(ext, JSON.stringify({ data: [] }));
expect(ext.pending).toHaveLength(0);
expect(ext.getParseError()).toBeNull();
});
it('skips oversized items (byte budget)', () => {
// MAX_SINGLE_ITEM_BYTES is mocked to 500
const ext = createItemExtractor('test-key');
// Create an item that exceeds 500 bytes
const bigValue = 'x'.repeat(600);
const payload = JSON.stringify({
data: [
{ type: 'big', data: { content: bigValue } },
{ type: 'small', data: { ok: true } },
],
});
feedAll(ext, payload);
// The oversized item should be skipped, but the small one should parse
expect(ext.pending).toHaveLength(1);
expect(ext.pending[0]).toEqual({ type: 'small', data: { ok: true } });
});
it('clears skippingItem when oversize item ends on closing brace', () => {
// MAX_SINGLE_ITEM_BYTES is mocked to 500
const ext = createItemExtractor('test-key');
// A flat object (no nested braces) that exceeds budget — the closing }
// is the token that triggers the budget check AND ends the item at depth=2
const bigValue = 'y'.repeat(600);
const payload = JSON.stringify({
data: [{ big: bigValue }, { type: 'after', ok: true }],
});
feedAll(ext, payload);
// The first item is oversized and skipped; the second should parse fine
expect(ext.pending).toHaveLength(1);
expect(ext.pending[0]).toEqual({ type: 'after', ok: true });
});
it('sets parseError on malformed JSON', () => {
const ext = createItemExtractor('test-key');
// Feed invalid JSON
ext.tokenizer.write(encoder.encode('{ data: ['));
ext.tokenizer.end();
expect(ext.getParseError()).toBeInstanceOf(Error);
});
it('ignores non-data top-level keys', () => {
const ext = createItemExtractor('test-key');
const payload = JSON.stringify({
meta: { version: 1 },
other: [{ type: 'ignored' }],
data: [{ type: 'included', data: {} }],
});
feedAll(ext, payload);
expect(ext.pending).toHaveLength(1);
expect(ext.pending[0]).toEqual({ type: 'included', data: {} });
});
});
describe('queue', () => {
it('delays failed queue message retries to avoid immediately hammering hot DOs', async () => {
const limit = vi.fn(async () => [{ session_id: 'ses_retry' }]);
const where = vi.fn(() => ({ limit }));
const from = vi.fn(() => ({ where }));
vi.mocked(getWorkerDb).mockReturnValue({ select: vi.fn(() => ({ from })) } as never);
const env = {
HYPERDRIVE: { connectionString: 'postgres://unused' },
SESSION_INGEST_R2: { get: vi.fn(async () => null) },
} as never;
const ack = vi.fn();
const retry = vi.fn();
await queue(
{
messages: [
{
body: {
r2Key: 'ingest/retry-missing',
kiloUserId: 'usr_retry',
sessionId: 'ses_retry',
ingestVersion: 1,
ingestedAt: 1,
},
ack,
retry,
},
],
} as never,
env,
{ waitUntil: vi.fn() } as unknown as ExecutionContext
);
expect(ack).not.toHaveBeenCalled();
expect(retry).toHaveBeenCalledWith({ delaySeconds: QUEUE_RETRY_DELAY_SECONDS });
});
it('passes full parsed oversized message data and its R2 reference into ingest', async () => {
const ingest = vi.fn(async () => ({ changes: [] }));
vi.mocked(getSessionIngestDO).mockReturnValue({ ingest } as never);
const limit = vi.fn(async () => [{ session_id: 'ses_compacted' }]);
const where = vi.fn(() => ({ limit }));
const from = vi.fn(() => ({ where }));
vi.mocked(getWorkerDb).mockReturnValue({ select: vi.fn(() => ({ from })) } as never);
const data = {
id: 'msg_compacted',
sessionID: 'ses_compacted',
time: { created: 123 },
content: 'x'.repeat(150),
};
const body = JSON.stringify({ data: [{ type: 'message', data }] });
const put = vi.fn(async () => undefined);
const deleteObject = vi.fn(async () => undefined);
const env = {
HYPERDRIVE: { connectionString: 'postgres://unused' },
SESSION_INGEST_R2: {
get: vi.fn(async () => new Response(body)),
put,
delete: deleteObject,
},
} as never;
const ack = vi.fn();
const retry = vi.fn();
const ctx = { waitUntil: vi.fn() } as unknown as ExecutionContext;
await queue(
{
messages: [
{
body: {
r2Key: 'staging/items',
kiloUserId: 'usr_compacted',
sessionId: 'ses_compacted',
ingestVersion: 1,
ingestedAt: 456,
},
ack,
retry,
},
],
} as never,
env,
ctx
);
const expectedR2Key = 'items/usr_compacted/ses_compacted/message/msg_compacted/456';
expect(put).toHaveBeenCalledWith(expectedR2Key, JSON.stringify(data));
expect(ingest).toHaveBeenCalledWith(
[{ type: 'message', data }],
'usr_compacted',
'ses_compacted',
1,
456,
{ 'message/msg_compacted': expectedR2Key }
);
expect(deleteObject).toHaveBeenCalledWith('staging/items');
expect(ack).toHaveBeenCalledTimes(1);
expect(retry).not.toHaveBeenCalled();
});
});
describe('computeSessionMetadataUpdates', () => {
const fixedNow = () => '2026-05-05T00:00:00.000Z';
it('normalizes gitUrl to the canonical form before persisting', () => {
const updates = computeSessionMetadataUpdates(
new Map([['gitUrl', 'https://GitHub.com/ACME/Widgets.git']]),
fixedNow
);
expect(updates.git_url).toBe('https://github.com/acme/widgets');
});
it('collapses scp-style and ssh:// URLs to the same normalized form as https', () => {
const fromScp = computeSessionMetadataUpdates(
new Map([['gitUrl', 'git@github.com:acme/widgets.git']]),
fixedNow
);
const fromSsh = computeSessionMetadataUpdates(
new Map([['gitUrl', 'ssh://git@github.com/acme/widgets.git']]),
fixedNow
);
const fromHttps = computeSessionMetadataUpdates(
new Map([['gitUrl', 'https://github.com/acme/widgets']]),
fixedNow
);
expect(fromScp.git_url).toBe('https://github.com/acme/widgets');
expect(fromSsh.git_url).toBe(fromScp.git_url);
expect(fromHttps.git_url).toBe(fromScp.git_url);
});
it('writes null git_url when the ingest cleared the field', () => {
const updates = computeSessionMetadataUpdates(new Map([['gitUrl', null]]), fixedNow);
expect(updates.git_url).toBeNull();
});
it('does not set git_url when the change does not include it', () => {
const updates = computeSessionMetadataUpdates(
new Map([
['gitBranch', 'feature/x'],
['title', 'hello'],
]),
fixedNow
);
expect('git_url' in updates).toBe(false);
expect(updates.git_branch).toBe('feature/x');
expect(updates.title).toBe('hello');
});
it('stamps status_updated_at when status changes', () => {
const updates = computeSessionMetadataUpdates(new Map([['status', 'running']]), fixedNow);
expect(updates.status).toBe('running');
expect(updates.status_updated_at).toBe('2026-05-05T00:00:00.000Z');
});
it('ignores a null "platform" change (creation value stays sticky)', () => {
const updates = computeSessionMetadataUpdates(new Map([['platform', null]]), fixedNow);
expect('created_on_platform' in updates).toBe(false);
});
});
describe('queue status notifications', () => {
it('emits a status update using the locked pre-update status instead of the intake snapshot', async () => {
vi.mocked(notifyUserSessionEvent).mockClear();
const persistedSession = {
session_id: 'ses_12345678901234567890123456',
created_at: '2026-05-05T00:00:00.000Z',
updated_at: '2026-05-05T00:00:01.000Z',
title: null,
created_on_platform: null,
organization_id: null,
git_url: null,
git_branch: null,
parent_session_id: null,
status: 'idle',
status_updated_at: '2026-05-05T00:00:01.000Z',
};
const selectResults: unknown[][] = [
[{ session_id: persistedSession.session_id, status: 'idle' }],
[{ status: 'busy' }],
[persistedSession],
];
const selectResult = vi.fn(async () => selectResults.shift() ?? []);
const select = {
from: vi.fn(() => select),
where: vi.fn(() => select),
limit: vi.fn(() => select),
for: vi.fn(() => select),
then: vi.fn((resolve: (value: unknown) => unknown) => resolve(selectResult())),
};
const update = {
set: vi.fn(() => update),
where: vi.fn(() => update),
then: vi.fn((resolve: (value: undefined) => unknown) => resolve(undefined)),
};
const dbRef: Record<string, unknown> = {};
const db = {
select: vi.fn(() => select),
update: vi.fn(() => update),
transaction: vi.fn(async (fn: (tx: unknown) => Promise<unknown>) => fn(dbRef)),
} as unknown as ReturnType<typeof getWorkerDb>;
Object.assign(dbRef, db);
vi.mocked(getWorkerDb).mockReturnValue(db);
vi.mocked(getSessionIngestDO).mockReturnValue({
ingest: vi.fn(async () => ({ changes: [{ name: 'status', value: 'idle' }] })),
} as never);
const body = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(
encoder.encode(
JSON.stringify({ data: [{ type: 'session_status', data: { status: 'idle' } }] })
)
);
controller.close();
},
});
const env = {
HYPERDRIVE: { connectionString: 'postgres://test' },
SESSION_INGEST_R2: {
get: vi.fn(async () => ({ body })),
delete: vi.fn(async () => undefined),
put: vi.fn(async () => undefined),
},
} as never;
const ack = vi.fn();
const batch = {
messages: [
{
body: {
r2Key: 'ingest/status-change',
kiloUserId: 'usr_test',
sessionId: persistedSession.session_id,
ingestVersion: 1,
ingestedAt: 1,
},
ack,
retry: vi.fn(),
},
],
} as never;
const ctx = { waitUntil: vi.fn() } as unknown as ExecutionContext;
await queue(batch, env, ctx);
expect(ack).toHaveBeenCalledTimes(1);
expect(notifyUserSessionEvent).toHaveBeenCalledWith(
env,
'usr_test',
expect.objectContaining({
type: 'session.status.updated',
data: expect.objectContaining({ previousStatus: 'busy', status: 'idle' }),
}),
ctx
);
});
});