Skip to content

Commit 405003a

Browse files
committed
Don't drop queued events when persisting or reading storage fails
- Mark an entry persisted only after its write succeeds, and wait for a pending write before sending, so a failed or in-flight write isn't mistaken for an event another tab already sent. - Keep entries that couldn't be read for a later session; only remove entries whose JSON is malformed. - Stop sending further batches once the client is disabled.
1 parent 6d955dc commit 405003a

2 files changed

Lines changed: 102 additions & 31 deletions

File tree

‎packages/core/src/queue/DefaultEventQueue.ts‎

Lines changed: 44 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,10 @@ import { allowProcessToExitWithoutWaitingForTimerOrInterval, guid } from "../Uti
88
interface EventQueueItem {
99
file: string;
1010
event: Event;
11-
/** True when the event was written to (or loaded from) persisted storage. */
11+
/** True once the event has been written to (or was loaded from) persisted storage. */
1212
persisted?: boolean;
13+
/** The pending write to persisted storage. */
14+
write?: Promise<void>;
1315
}
1416

1517
interface SubmissionResult {
@@ -125,7 +127,7 @@ export class DefaultEventQueue implements IEventQueue {
125127

126128
// Send batches until the queue is empty or a submission fails. Events enqueued while sending are picked up too.
127129
let batchSize = Math.max(1, this.config.submissionBatchSize);
128-
while (this._queue.length > 0 && !this.isQueueProcessingSuspended()) {
130+
while (this._queue.length > 0 && this.config.enabled && this.config.isValid && !this.isQueueProcessingSuspended()) {
129131
const items = await this.getNextBatch(batchSize);
130132
if (items.length === 0) {
131133
continue;
@@ -309,6 +311,7 @@ export class DefaultEventQueue implements IEventQueue {
309311
const available: EventQueueItem[] = [];
310312
const removed: EventQueueItem[] = [];
311313
for (const item of items) {
314+
await item.write;
312315
if (!item.persisted) {
313316
available.push(item);
314317
continue;
@@ -355,17 +358,27 @@ export class DefaultEventQueue implements IEventQueue {
355358
continue;
356359
}
357360

361+
let json: string | null;
358362
try {
359-
const json = await storage.getItem(file);
360-
if (json) {
361-
loaded.push({
362-
file,
363-
event: JSON.parse(json) as Event,
364-
persisted: true
365-
});
366-
}
363+
json = await storage.getItem(file);
364+
} catch (ex) {
365+
// Leave the entry in storage so a later session can load it.
366+
log.error(`Error reading queue item "${file}" from storage: ${ex instanceof Error ? ex.message : ex + ""}`);
367+
continue;
368+
}
369+
370+
if (!json) {
371+
continue;
372+
}
373+
374+
try {
375+
loaded.push({
376+
file,
377+
event: JSON.parse(json) as Event,
378+
persisted: true
379+
});
367380
} catch (ex) {
368-
log.error(`Removing unreadable queue item "${file}" from storage: ${ex instanceof Error ? ex.message : ex + ""}`);
381+
log.error(`Removing malformed queue item "${file}" from storage: ${ex instanceof Error ? ex.message : ex + ""}`);
369382
await this.removeStorageItem(file);
370383
}
371384
}
@@ -406,32 +419,32 @@ export class DefaultEventQueue implements IEventQueue {
406419

407420
const { log, storage } = this.config.services;
408421
const useStorage: boolean = this.config.usePersistedQueueStorage;
409-
if (
410-
this._queue.push({
411-
file,
412-
event,
413-
persisted: useStorage
414-
}) > this.maxItems
415-
) {
416-
log.trace("Removing oldest queue entry: maxItems exceeded");
417-
const item = this._queue.shift();
418-
if (useStorage && item) {
419-
try {
420-
await storage.removeItem(item.file);
421-
} catch (ex) {
422-
log.error(`Error removing oldest queue entry from storage: ${ex instanceof Error ? ex.message : ex + ""}`);
422+
const item: EventQueueItem = {
423+
file,
424+
event
425+
};
426+
if (useStorage) {
427+
// Only an entry that was actually written counts as persisted; a failed write is still sent from memory.
428+
item.write = storage.setItem(file, JSON.stringify(event)).then(
429+
() => {
430+
item.persisted = true;
431+
},
432+
(ex: unknown) => {
433+
log.error(`Error saving queue entry to storage: ${ex instanceof Error ? ex.message : ex + ""}`);
423434
}
424-
}
435+
);
425436
}
426437

427-
if (useStorage) {
428-
try {
429-
await storage.setItem(file, JSON.stringify(event));
430-
} catch (ex) {
431-
log.error(`Error saving queue entry to storage: ${ex instanceof Error ? ex.message : ex + ""}`);
438+
if (this._queue.push(item) > this.maxItems) {
439+
log.trace("Removing oldest queue entry: maxItems exceeded");
440+
const oldest = this._queue.shift();
441+
if (useStorage && oldest) {
442+
await oldest.write;
443+
await this.removeStorageItem(oldest.file);
432444
}
433445
}
434446

447+
await item.write;
435448
return file;
436449
}
437450

‎packages/core/test/queue/DefaultEventQueue.test.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { Configuration } from "../../src/configuration/Configuration.js";
44
import { ServerSettings } from "../../src/configuration/SettingsManager.js";
55
import { Event } from "../../src/models/Event.js";
66
import { DefaultEventQueue } from "../../src/queue/DefaultEventQueue.js";
7+
import { InMemoryStorage } from "../../src/storage/InMemoryStorage.js";
78
import { ISubmissionClient } from "../../src/submission/ISubmissionClient.js";
89
import { Response } from "../../src/submission/Response.js";
910
import { delay } from "../helpers.js";
@@ -318,4 +319,61 @@ describe("DefaultEventQueue submission", () => {
318319

319320
expect(await storedQueueKeys()).toHaveLength(0);
320321
});
322+
323+
test("sends an event from memory when persisting it fails", async () => {
324+
const storage = new InMemoryStorage();
325+
vi.spyOn(storage, "setItem").mockRejectedValue(new Error("QuotaExceededError"));
326+
config.services.storage = storage;
327+
328+
await config.services.queue.enqueue(createEvent("event-0001"));
329+
await config.services.queue.process();
330+
331+
expect(client.submittedReferenceIds).toEqual(["event-0001"]);
332+
});
333+
334+
test("waits for a pending write before sending the event", async () => {
335+
const storage = new InMemoryStorage();
336+
let finishWrite: () => void = () => {};
337+
const setItem = storage.setItem.bind(storage);
338+
vi.spyOn(storage, "setItem").mockImplementationOnce(
339+
(key, value) =>
340+
new Promise((resolve) => {
341+
finishWrite = () => void setItem(key, value).then(resolve);
342+
})
343+
);
344+
config.services.storage = storage;
345+
346+
const enqueued = config.services.queue.enqueue(createEvent("event-0001"));
347+
const processed = config.services.queue.process();
348+
finishWrite();
349+
await Promise.all([enqueued, processed]);
350+
351+
expect(client.submittedReferenceIds).toEqual(["event-0001"]);
352+
expect(await storage.keys()).toHaveLength(0);
353+
});
354+
355+
test("stops sending batches once the client is disabled", async () => {
356+
config.submissionBatchSize = 1;
357+
config.services.queue.onEventsPosted(() => {
358+
config.enabled = false;
359+
return Promise.resolve();
360+
});
361+
await config.services.queue.enqueue(createEvent("event-0001"));
362+
await config.services.queue.enqueue(createEvent("event-0002"));
363+
364+
await config.services.queue.process();
365+
366+
expect(client.submittedReferenceIds).toEqual(["event-0001"]);
367+
});
368+
369+
test("keeps a persisted entry that could not be read", async () => {
370+
const { storage } = config.services;
371+
await storage.setItem("q:1000.json", JSON.stringify(createEvent("persisted-1")));
372+
vi.spyOn(storage, "getItem").mockRejectedValueOnce(new Error("Storage unavailable"));
373+
374+
await config.services.queue.process();
375+
376+
expect(client.submissions).toHaveLength(0);
377+
expect(await storedQueueKeys()).toEqual(["q:1000.json"]);
378+
});
321379
});

0 commit comments

Comments
 (0)