Skip to content

Commit 2c45ed9

Browse files
committed
Integrate queue concurrency fixes into client lifecycle
2 parents 23abcbd + 53121cc commit 2c45ed9

5 files changed

Lines changed: 168 additions & 18 deletions

File tree

‎.agents/skills/exceptionless-javascript/references/troubleshooting.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,9 @@ This matters most for Node scripts, CLIs, serverless handlers, route handlers, t
3232

3333
`processQueue()` sends every queued batch until the queue is empty or a submission fails. After a failed submission (network error, timeout after 30 seconds, `429`, `503`, or `5xx`) the queue keeps the events and pauses for 5 minutes; `processQueue()` does nothing during the pause. Authentication failures pause for 15 minutes and a `400` or `404` for 4 hours; those batches are discarded. Submissions small enough for the browser `keepalive` budget can finish after the page is hidden or closed.
3434

35+
Overlapping `processQueue()` calls wait for the same delivery run. Asynchronous `onEventsPosted` callbacks can call `processQueue()` themselves. Callbacks for successive batches may overlap. Browser clients using persisted local storage coordinate submissions across same-origin tabs when Web Locks are available. Without Web Locks, overlapping tabs may submit the same event.
36+
37+
3538
## Privacy Filters
3639

3740
If expected data is absent from an event, check `includePrivateInformation`, `includeHeaders`, `includeCookies`, `includePostData`, `includeQueryString`, and `dataExclusions`.

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

Lines changed: 34 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { Configuration } from "../configuration/Configuration.js";
22
import { ILog } from "../logging/ILog.js";
33
import { Event } from "../models/Event.js";
44
import { IEventQueue } from "../queue/IEventQueue.js";
5+
import { LocalStorage, withQueueLock } from "../storage/LocalStorage.js";
56
import { Response } from "../submission/Response.js";
67
import { allowProcessToExitWithoutWaitingForTimerOrInterval, guid } from "../Utils.js";
78

@@ -46,7 +47,6 @@ export class DefaultEventQueue implements IEventQueue {
4647
* @private
4748
*/
4849
private _processing: Promise<void> | undefined;
49-
private _notifyingHandlers = false;
5050

5151
/**
5252
* Processes the queue every xx seconds.
@@ -96,9 +96,7 @@ export class DefaultEventQueue implements IEventQueue {
9696
const { log } = this.config.services;
9797

9898
if (this._processing) {
99-
// Callers such as processQueue() need to wait for the run that is already sending events. An onEventsPosted
100-
// handler calling back into the queue is part of that run, so it must not wait for it.
101-
return this._notifyingHandlers ? Promise.resolve() : this._processing;
99+
return this._processing;
102100
}
103101

104102
log.trace("Processing queue...");
@@ -137,21 +135,18 @@ export class DefaultEventQueue implements IEventQueue {
137135
// Send batches until the queue is empty or a submission fails. Events enqueued while sending are picked up too.
138136
let batchSize = Math.max(1, this.config.submissionBatchSize);
139137
while (this._queue.length > 0 && this.config.enabled && this.config.isValid && !this.isQueueProcessingSuspended()) {
140-
const items = await this.getNextBatch(batchSize);
141-
if (items.length === 0) {
138+
const storage = this.config.services.storage;
139+
const batch =
140+
this.config.usePersistedQueueStorage && storage instanceof LocalStorage
141+
? await storage[withQueueLock](() => this.submitBatch(batchSize))
142+
: await this.submitBatch(batchSize);
143+
if (!batch) {
142144
continue;
143145
}
144146

145-
log.info(`Sending ${items.length} events to ${this.config.serverUrl}`);
146-
const events = items.map((i) => i.event);
147-
const response = await this.config.services.submissionClient.submitEvents(events);
148-
const result = await this.processSubmissionResponse(response, items, batchSize);
149-
this._notifyingHandlers = true;
150-
try {
151-
await this.eventsPosted(events, response);
152-
} finally {
153-
this._notifyingHandlers = false;
154-
}
147+
const { events, response, result } = batch;
148+
// A handler can await this queue run. Delivery must continue independently of its completion.
149+
void this.eventsPosted(events, response);
155150

156151
if (result.retryWithBatchSize) {
157152
batchSize = result.retryWithBatchSize;
@@ -167,6 +162,24 @@ export class DefaultEventQueue implements IEventQueue {
167162
}
168163
}
169164

165+
private async submitBatch(batchSize: number): Promise<{ events: Event[]; response: Response; result: SubmissionResult } | undefined> {
166+
const items = await this.getNextBatch(batchSize);
167+
// A tab can disable or suspend the client while this batch is waiting for another tab's lock.
168+
if (items.length === 0 || !this.config.enabled || !this.config.isValid || this.isQueueProcessingSuspended()) {
169+
return undefined;
170+
}
171+
172+
this.config.services.log.info(`Sending ${items.length} events to ${this.config.serverUrl}`);
173+
const events = items.map((item) => item.event);
174+
const response = await this.config.services.submissionClient.submitEvents(events);
175+
const result = await this.processSubmissionResponse(response, items, batchSize);
176+
return {
177+
events,
178+
response,
179+
result
180+
};
181+
}
182+
170183
public startup(): Promise<void> {
171184
if (!this._queueIntervalId) {
172185
// TODO: Fix awaiting promise.
@@ -215,7 +228,11 @@ export class DefaultEventQueue implements IEventQueue {
215228
try {
216229
await handler(events, response);
217230
} catch (ex) {
218-
this.config.services.log.error(`Error calling onEventsPosted handler: ${ex instanceof Error ? ex.message : ex + ""}`);
231+
try {
232+
this.config.services.log.error(`Error calling onEventsPosted handler: ${ex instanceof Error ? ex.message : String(ex)}`);
233+
} catch {
234+
// A custom logger or thrown value can itself throw. Continue notifying the remaining handlers.
235+
}
219236
}
220237
}
221238
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,6 @@ export interface IEventQueue {
1212
suspend(): Promise<void>;
1313
/** Suspends processing of events for a specific duration */
1414
suspendProcessing(durationInMinutes?: number, discardFutureQueuedItems?: boolean, clearQueue?: boolean): Promise<void>;
15-
// TODO: See if this makes sense.
15+
/** Notifies handlers after each submission. Queue processing continues while asynchronous handlers are pending. */
1616
onEventsPosted(handler: (events: Event[], response: Response) => Promise<void>): void;
1717
}

‎packages/core/src/storage/LocalStorage.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,18 @@
11
import { IStorage } from "../storage/IStorage.js";
22

3+
export const withQueueLock = Symbol("withQueueLock");
4+
35
export class LocalStorage implements IStorage {
46
constructor(
57
private prefix: string = "exceptionless-",
68
private storage: Storage = globalThis.localStorage
79
) {}
810

11+
public [withQueueLock]<T>(action: () => Promise<T>): Promise<T> {
12+
const locks = globalThis.navigator?.locks;
13+
return locks ? locks.request(`exceptionless:queue:${this.prefix}`, action) : action();
14+
}
15+
916
public length(): Promise<number> {
1017
return Promise.resolve(this.getKeys().length);
1118
}

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

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,17 @@ import { ISubmissionClient } from "../../src/submission/ISubmissionClient.js";
99
import { Response } from "../../src/submission/Response.js";
1010
import { delay } from "../helpers.js";
1111

12+
function signal(): { wait: Promise<void>; release: () => void } {
13+
let release!: () => void;
14+
const wait = new Promise<void>((resolve) => {
15+
release = resolve;
16+
});
17+
return {
18+
wait,
19+
release
20+
};
21+
}
22+
1223
describe("DefaultEventQueue", () => {
1324
let config: Configuration;
1425

@@ -210,6 +221,73 @@ describe("DefaultEventQueue submission", () => {
210221
expect(client.submittedReferenceIds).toEqual(["event-0002"]);
211222
});
212223

224+
test("concurrent queues sharing localStorage submit a persisted event once with Web Locks", async () => {
225+
// Arrange
226+
config.useLocalStorage();
227+
const otherQueue = new DefaultEventQueue(config);
228+
await config.services.queue.enqueue(createEvent("event-0001"));
229+
const held = new Map<string, Promise<unknown>>();
230+
vi.stubGlobal("navigator", {
231+
locks: {
232+
async request(name: string, action: () => Promise<unknown>) {
233+
const previous = held.get(name);
234+
const done = signal();
235+
held.set(name, done.wait);
236+
await previous;
237+
try {
238+
return await action();
239+
} finally {
240+
done.release();
241+
}
242+
}
243+
}
244+
});
245+
246+
try {
247+
// Act
248+
await Promise.all([config.services.queue.process(), otherQueue.process()]);
249+
250+
// Assert
251+
expect(client.submittedReferenceIds).toEqual(["event-0001"]);
252+
expect(await storedQueueKeys()).toHaveLength(0);
253+
} finally {
254+
vi.unstubAllGlobals();
255+
}
256+
});
257+
258+
test("disabling a client while it waits for the storage lock preserves its queued events", async () => {
259+
// Arrange
260+
config.useLocalStorage();
261+
const requested = signal();
262+
const available = signal();
263+
vi.stubGlobal("navigator", {
264+
locks: {
265+
async request(_name: string, action: () => Promise<unknown>) {
266+
requested.release();
267+
await available.wait;
268+
return action();
269+
}
270+
}
271+
});
272+
273+
try {
274+
await config.services.queue.enqueue(createEvent("event-0001"));
275+
276+
// Act
277+
const processing = config.services.queue.process();
278+
await requested.wait;
279+
config.enabled = false;
280+
available.release();
281+
await processing;
282+
283+
// Assert
284+
expect(client.submissions).toHaveLength(0);
285+
expect(await storedQueueKeys()).toHaveLength(1);
286+
} finally {
287+
vi.unstubAllGlobals();
288+
}
289+
});
290+
213291
test("gives queue entries from the same millisecond distinct keys", async () => {
214292
vi.useFakeTimers({
215293
toFake: ["Date"]
@@ -415,6 +493,51 @@ describe("DefaultEventQueue submission", () => {
415493
expect(await storedQueueKeys()).toHaveLength(0);
416494
});
417495

496+
test("an independent process call waits for delivery while an async handler reenters the queue", async () => {
497+
// Arrange
498+
config.submissionBatchSize = 1;
499+
const { queue } = config.services;
500+
const handlerStarted = signal();
501+
const resumeHandler = signal();
502+
const handlerDone = signal();
503+
const secondSubmission = signal();
504+
const submit = client.submitEvents.bind(client);
505+
vi.spyOn(client, "submitEvents").mockImplementation(async (events) => {
506+
if (events[0].reference_id === "event-0002") {
507+
await secondSubmission.wait;
508+
}
509+
return submit(events);
510+
});
511+
queue.onEventsPosted(async (events) => {
512+
if (events[0].reference_id === "event-0001") {
513+
handlerStarted.release();
514+
await resumeHandler.wait;
515+
await queue.process();
516+
handlerDone.release();
517+
}
518+
});
519+
await queue.enqueue(createEvent("event-0001"));
520+
await queue.enqueue(createEvent("event-0002"));
521+
522+
// Act
523+
const first = queue.process();
524+
await handlerStarted.wait;
525+
let externalFinished = false;
526+
async function processIndependently(): Promise<void> {
527+
await queue.process();
528+
externalFinished = true;
529+
}
530+
const external = processIndependently();
531+
resumeHandler.release();
532+
await delay(0);
533+
534+
// Assert
535+
expect(externalFinished).toBe(false);
536+
secondSubmission.release();
537+
await Promise.all([first, external, handlerDone.wait]);
538+
expect(client.submittedReferenceIds).toEqual(["event-0001", "event-0002"]);
539+
});
540+
418541
test("an onEventsPosted handler that processes the queue does not wait for its own run", async () => {
419542
config.services.queue.onEventsPosted(() => config.services.queue.process());
420543
await config.services.queue.enqueue(createEvent("event-0001"));

0 commit comments

Comments
 (0)