diff --git a/.agents/skills/exceptionless-javascript/references/troubleshooting.md b/.agents/skills/exceptionless-javascript/references/troubleshooting.md index 4e287503..10423614 100644 --- a/.agents/skills/exceptionless-javascript/references/troubleshooting.md +++ b/.agents/skills/exceptionless-javascript/references/troubleshooting.md @@ -30,6 +30,11 @@ await Exceptionless.processQueue(); This matters most for Node scripts, CLIs, serverless handlers, route handlers, tests, and hard redirects. +`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. + +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. + + ## Privacy Filters If expected data is absent from an event, check `includePrivateInformation`, `includeHeaders`, `includeCookies`, `includePostData`, `includeQueryString`, and `dataExclusions`. diff --git a/packages/core/src/queue/DefaultEventQueue.ts b/packages/core/src/queue/DefaultEventQueue.ts index 15e813cb..1cd8671e 100644 --- a/packages/core/src/queue/DefaultEventQueue.ts +++ b/packages/core/src/queue/DefaultEventQueue.ts @@ -2,12 +2,22 @@ import { Configuration } from "../configuration/Configuration.js"; import { ILog } from "../logging/ILog.js"; import { Event } from "../models/Event.js"; import { IEventQueue } from "../queue/IEventQueue.js"; +import { LocalStorage, withQueueLock } from "../storage/LocalStorage.js"; import { Response } from "../submission/Response.js"; -import { allowProcessToExitWithoutWaitingForTimerOrInterval } from "../Utils.js"; +import { allowProcessToExitWithoutWaitingForTimerOrInterval, guid } from "../Utils.js"; interface EventQueueItem { file: string; event: Event; + /** True once the event has been written to (or was loaded from) persisted storage. */ + persisted?: boolean; + /** The pending write to persisted storage. */ + write?: Promise; +} + +interface SubmissionResult { + continueProcessing: boolean; + retryWithBatchSize?: number; } export class DefaultEventQueue implements IEventQueue { @@ -33,11 +43,10 @@ export class DefaultEventQueue implements IEventQueue { private _discardQueuedItemsUntil?: Date; /** - * Returns true if the queue is processing. - * @type {boolean} + * The queue run that is currently sending events, if any. * @private */ - private _processingQueue = false; + private _processing: Promise | undefined; /** * Processes the queue every xx seconds. @@ -47,6 +56,7 @@ export class DefaultEventQueue implements IEventQueue { private _queueIntervalId: ReturnType | undefined; private readonly QUEUE_PREFIX: string = "q:"; + private readonly DEFAULT_SUSPENSION_MINUTES: number = 5; private _lastFileTimestamp = 0; private _queue: EventQueueItem[] = []; private _loadPersistedEvents = true; @@ -85,8 +95,8 @@ export class DefaultEventQueue implements IEventQueue { const queueNotProcessed = "The queue will not be processed"; const { log } = this.config.services; - if (this._processingQueue) { - return; + if (this._processing) { + return this._processing; } log.trace("Processing queue..."); @@ -100,7 +110,19 @@ export class DefaultEventQueue implements IEventQueue { return; } - this._processingQueue = true; + if (this.isQueueProcessingSuspended()) { + log.trace(`Queue processing is suspended: ${queueNotProcessed}`); + return; + } + + this._processing = this.processBatches().finally(() => { + this._processing = undefined; + }); + return this._processing; + } + + private async processBatches(): Promise { + const { log } = this.config.services; try { if (this._loadPersistedEvents) { if (this.config.usePersistedQueueStorage) { @@ -110,26 +132,54 @@ export class DefaultEventQueue implements IEventQueue { this._loadPersistedEvents = false; } - const items = this._queue.slice(0, this.config.submissionBatchSize); - if (!items || items.length === 0) { - this._processingQueue = false; - return; + // Send batches until the queue is empty or a submission fails. Events enqueued while sending are picked up too. + let batchSize = Math.max(1, this.config.submissionBatchSize); + while (this._queue.length > 0 && this.config.enabled && this.config.isValid && !this.isQueueProcessingSuspended()) { + const storage = this.config.services.storage; + const batch = + this.config.usePersistedQueueStorage && storage instanceof LocalStorage + ? await storage[withQueueLock](() => this.submitBatch(batchSize)) + : await this.submitBatch(batchSize); + if (!batch) { + continue; + } + + const { events, response, result } = batch; + // A handler can await this queue run. Delivery must continue independently of its completion. + void this.eventsPosted(events, response); + + if (result.retryWithBatchSize) { + batchSize = result.retryWithBatchSize; + } else if (!result.continueProcessing) { + break; + } } - log.info(`Sending ${items.length} events to ${this.config.serverUrl}`); - const events = items.map((i) => i.event); - const response = await this.config.services.submissionClient.submitEvents(events); - await this.processSubmissionResponse(response, items); - await this.eventsPosted(events, response); log.trace("Finished processing queue"); - this._processingQueue = false; } catch (ex) { log.error(`Error processing queue: ${ex instanceof Error ? ex.message : ex + ""}`); await this.suspendProcessing(); - this._processingQueue = false; } } + private async submitBatch(batchSize: number): Promise<{ events: Event[]; response: Response; result: SubmissionResult } | undefined> { + const items = await this.getNextBatch(batchSize); + // A tab can disable or suspend the client while this batch is waiting for another tab's lock. + if (items.length === 0 || !this.config.enabled || !this.config.isValid || this.isQueueProcessingSuspended()) { + return undefined; + } + + this.config.services.log.info(`Sending ${items.length} events to ${this.config.serverUrl}`); + const events = items.map((item) => item.event); + const response = await this.config.services.submissionClient.submitEvents(events); + const result = await this.processSubmissionResponse(response, items, batchSize); + return { + events, + response, + result + }; + } + public startup(): Promise { if (!this._queueIntervalId) { // TODO: Fix awaiting promise. @@ -151,7 +201,7 @@ export class DefaultEventQueue implements IEventQueue { const currentDate = new Date(); if (!durationInMinutes || durationInMinutes <= 0) { - durationInMinutes = Math.ceil(currentDate.getMinutes() / 15) * 15 - currentDate.getMinutes(); + durationInMinutes = this.DEFAULT_SUSPENSION_MINUTES; } config.services.log.info(`Suspending processing for ${durationInMinutes} minutes.`); @@ -178,7 +228,11 @@ export class DefaultEventQueue implements IEventQueue { try { await handler(events, response); } catch (ex) { - this.config.services.log.error(`Error calling onEventsPosted handler: ${ex instanceof Error ? ex.message : ex + ""}`); + try { + this.config.services.log.error(`Error calling onEventsPosted handler: ${ex instanceof Error ? ex.message : String(ex)}`); + } catch { + // A custom logger or thrown value can itself throw. Continue notifying the remaining handlers. + } } } } @@ -192,34 +246,40 @@ export class DefaultEventQueue implements IEventQueue { } private async onProcessQueue(): Promise { - if (!this.isQueueProcessingSuspended() && !this._processingQueue) { + if (!this.isQueueProcessingSuspended() && !this._processing) { await this.process(); } } - private async processSubmissionResponse(response: Response, items: EventQueueItem[]): Promise { + private async processSubmissionResponse(response: Response, items: EventQueueItem[], batchSize: number): Promise { const noSubmission = "The event will not be submitted"; const config: Configuration = this.config; const log: ILog = config.services.log; - if (response.status === 202) { + if (response.success) { log.info(`Sent ${items.length} events`); await this.removeEvents(items); - return; + return { + continueProcessing: response.rateLimitRemaining !== 0 + }; } - if (response.status === 429 || response.rateLimitRemaining === 0 || response.status === 503) { + if (response.status === 429 || response.status === 503) { // You are currently over your rate limit or the servers are under stress. log.error("Server returned service unavailable"); await this.suspendProcessing(); - return; + return { + continueProcessing: false + }; } if (response.status === 402) { // If the organization over the rate limit then discard the event. log.info("Too many events have been submitted, please upgrade your plan"); await this.suspendProcessing(0, true, true); - return; + return { + continueProcessing: false + }; } if (response.status === 401 || response.status === 403) { @@ -227,7 +287,9 @@ export class DefaultEventQueue implements IEventQueue { log.info(`Unable to authenticate, please check your configuration. ${noSubmission}`); await this.suspendProcessing(15); await this.removeEvents(items); - return; + return { + continueProcessing: false + }; } if (response.status === 400 || response.status === 404) { @@ -235,81 +297,184 @@ export class DefaultEventQueue implements IEventQueue { log.error(`Error while trying to submit data: ${response.message}`); await this.suspendProcessing(60 * 4); await this.removeEvents(items); - return; + return { + continueProcessing: false + }; } if (response.status === 413) { const message = "Event submission discarded for being too large."; - if (config.submissionBatchSize > 1) { + if (items.length > 1) { log.error(`${message} Retrying with smaller batch size.`); - config.submissionBatchSize = Math.max(1, Math.round(config.submissionBatchSize / 1.5)); - } else { - log.error(`${message} ${noSubmission}`); - await this.removeEvents(items); + return { + continueProcessing: true, + retryWithBatchSize: Math.max(1, Math.round(Math.min(batchSize, items.length) / 1.5)) + }; } - return; + log.error(`${message} ${noSubmission}`); + await this.removeEvents(items); + return { + continueProcessing: true + }; } log.error(`Error submitting events: ${response.message || "Please check the network tab for more info."}`); await this.suspendProcessing(); + return { + continueProcessing: false + }; } - private async loadEvents(): Promise { - if (this.config.usePersistedQueueStorage) { - const { log, storage } = this.config.services; + /** + * Returns the next batch of queued events. When the queue is persisted, events that another client instance + * sharing the same storage (for example, another browser tab) has already sent and removed are skipped. + */ + private async getNextBatch(batchSize: number): Promise { + const items = this._queue.slice(0, batchSize); + if (!this.config.usePersistedQueueStorage) { + return items; + } + + const { log, storage } = this.config.services; + const available: EventQueueItem[] = []; + const removed: EventQueueItem[] = []; + for (const item of items) { + await item.write; + if (!item.persisted) { + available.push(item); + continue; + } try { - const files: string[] = await storage.keys(); - - for (const file of files) { - if (file?.startsWith(this.QUEUE_PREFIX)) { - const json = await storage.getItem(file); - if (json) { - this._queue.push({ - file, - event: JSON.parse(json) as Event - }); - } - } + if ((await storage.getItem(item.file)) === null) { + removed.push(item); + continue; } } catch (ex) { - log.error(`Error loading queue items from storage: ${ex instanceof Error ? ex.message : ex + ""}`); + log.error(`Error reading queue item from storage: ${ex instanceof Error ? ex.message : ex + ""}`); } + + available.push(item); + } + + if (removed.length > 0) { + log.trace(`Skipping ${removed.length} queued events that were already submitted`); + this._queue = this._queue.filter((i) => !removed.includes(i)); + } + + return available; + } + + private async loadEvents(): Promise { + if (!this.config.usePersistedQueueStorage) { + return; + } + + const { log, storage } = this.config.services; + let files: string[]; + try { + files = await storage.keys(); + } catch (ex) { + log.error(`Error loading queue items from storage: ${ex instanceof Error ? ex.message : ex + ""}`); + return; + } + + const queuedFiles = new Set(this._queue.map((i) => i.file)); + const loaded: EventQueueItem[] = []; + for (const file of files) { + if (!file?.startsWith(this.QUEUE_PREFIX) || queuedFiles.has(file)) { + continue; + } + + let json: string | null; + try { + json = await storage.getItem(file); + } catch (ex) { + // Leave the entry in storage so a later session can load it. + log.error(`Error reading queue item "${file}" from storage: ${ex instanceof Error ? ex.message : ex + ""}`); + continue; + } + + if (!json) { + continue; + } + + try { + loaded.push({ + file, + event: JSON.parse(json) as Event, + persisted: true + }); + } catch (ex) { + log.error(`Removing malformed queue item "${file}" from storage: ${ex instanceof Error ? ex.message : ex + ""}`); + await this.removeStorageItem(file); + } + } + + if (loaded.length === 0) { + return; + } + + // Events persisted by an earlier session are older than anything queued in this one. + loaded.sort((a, b) => this.getFileTimestamp(a.file) - this.getFileTimestamp(b.file)); + this._queue = [...loaded, ...this._queue]; + log.info(`Loaded ${loaded.length} queued events from storage`); + + const overflow = this._queue.length - this.maxItems; + if (overflow > 0) { + log.trace("Removing oldest queue entries: maxItems exceeded"); + await this.removeEvents(this._queue.slice(0, overflow)); + } + } + + private getFileTimestamp(file: string): number { + const timestamp = parseInt(file.slice(this.QUEUE_PREFIX.length), 10); + return isNaN(timestamp) ? 0 : timestamp; + } + + private async removeStorageItem(file: string): Promise { + try { + await this.config.services.storage.removeItem(file); + } catch (ex) { + this.config.services.log.error(`Error removing queue item from storage: ${ex instanceof Error ? ex.message : ex + ""}`); } } private async enqueueEvent(event: Event): Promise { this._lastFileTimestamp = Math.max(Date.now(), this._lastFileTimestamp + 1); - const file = `${this.QUEUE_PREFIX}${this._lastFileTimestamp}.json`; + // The random suffix keeps client instances that share storage (for example, browser tabs) from overwriting each other's entries. + const file = `${this.QUEUE_PREFIX}${this._lastFileTimestamp}-${guid().slice(0, 8)}.json`; const { log, storage } = this.config.services; const useStorage: boolean = this.config.usePersistedQueueStorage; - if ( - this._queue.push({ - file, - event - }) > this.maxItems - ) { - log.trace("Removing oldest queue entry: maxItems exceeded"); - const item = this._queue.shift(); - if (useStorage && item) { - try { - await storage.removeItem(item.file); - } catch (ex) { - log.error(`Error removing oldest queue entry from storage: ${ex instanceof Error ? ex.message : ex + ""}`); + const item: EventQueueItem = { + file, + event + }; + if (useStorage) { + // Only an entry that was actually written counts as persisted; a failed write is still sent from memory. + // The executor turns a synchronous throw (for example, a full localStorage quota) into a rejection. + item.write = new Promise((resolve) => resolve(storage.setItem(file, JSON.stringify(event)))).then( + () => { + item.persisted = true; + }, + (ex: unknown) => { + log.error(`Error saving queue entry to storage: ${ex instanceof Error ? ex.message : ex + ""}`); } - } + ); } - if (useStorage) { - try { - await storage.setItem(file, JSON.stringify(event)); - } catch (ex) { - log.error(`Error saving queue entry to storage: ${ex instanceof Error ? ex.message : ex + ""}`); + if (this._queue.push(item) > this.maxItems) { + log.trace("Removing oldest queue entry: maxItems exceeded"); + const oldest = this._queue.shift(); + if (useStorage && oldest) { + await oldest.write; + await this.removeStorageItem(oldest.file); } } + await item.write; return file; } diff --git a/packages/core/src/queue/IEventQueue.ts b/packages/core/src/queue/IEventQueue.ts index 44cdff36..de876fa9 100644 --- a/packages/core/src/queue/IEventQueue.ts +++ b/packages/core/src/queue/IEventQueue.ts @@ -12,6 +12,6 @@ export interface IEventQueue { suspend(): Promise; /** Suspends processing of events for a specific duration */ suspendProcessing(durationInMinutes?: number, discardFutureQueuedItems?: boolean, clearQueue?: boolean): Promise; - // TODO: See if this makes sense. + /** Notifies handlers after each submission. Queue processing continues while asynchronous handlers are pending. */ onEventsPosted(handler: (events: Event[], response: Response) => Promise): void; } diff --git a/packages/core/src/storage/LocalStorage.ts b/packages/core/src/storage/LocalStorage.ts index c00077fb..834e1beb 100644 --- a/packages/core/src/storage/LocalStorage.ts +++ b/packages/core/src/storage/LocalStorage.ts @@ -1,11 +1,18 @@ import { IStorage } from "../storage/IStorage.js"; +export const withQueueLock = Symbol("withQueueLock"); + export class LocalStorage implements IStorage { constructor( private prefix: string = "exceptionless-", private storage: Storage = globalThis.localStorage ) {} + public [withQueueLock](action: () => Promise): Promise { + const locks = globalThis.navigator?.locks; + return locks ? locks.request(`exceptionless:queue:${this.prefix}`, action) : action(); + } + public length(): Promise { return Promise.resolve(this.getKeys().length); } diff --git a/packages/core/src/submission/DefaultSubmissionClient.ts b/packages/core/src/submission/DefaultSubmissionClient.ts index f5ae45b6..87d86a74 100644 --- a/packages/core/src/submission/DefaultSubmissionClient.ts +++ b/packages/core/src/submission/DefaultSubmissionClient.ts @@ -4,10 +4,16 @@ import { Event } from "../models/Event.js"; import { UserDescription } from "../models/data/UserDescription.js"; import { ISubmissionClient } from "../submission/ISubmissionClient.js"; import { Response } from "../submission/Response.js"; +import { allowProcessToExitWithoutWaitingForTimerOrInterval } from "../Utils.js"; export class DefaultSubmissionClient implements ISubmissionClient { protected readonly RateLimitRemainingHeader: string = "x-ratelimit-remaining"; protected readonly ConfigurationVersionHeader: string = "x-exceptionless-configversion"; + /** How long to wait for the server before a request is aborted. */ + protected readonly RequestTimeout: number = 30000; + /** Browsers reject keepalive requests once the in-flight keepalive bodies exceed 64 KiB, so stay under it. */ + protected readonly KeepAliveBodyLimit: number = 60000; + private _keepAliveBytesInFlight = 0; public constructor( protected config: Configuration, @@ -15,7 +21,7 @@ export class DefaultSubmissionClient implements ISubmissionClient { ) {} public getSettings(version: number): Promise> { - const url = `${this.config.serverUrl}/api/v2/projects/config?v=${version}`; + const url = `${this.config.configServerUrl}/api/v2/projects/config?v=${version}`; return this.apiFetch(url, { method: "GET" }); @@ -46,7 +52,7 @@ export class DefaultSubmissionClient implements ISubmissionClient { } public async submitHeartbeat(sessionIdOrUserId: string, closeSession: boolean): Promise> { - const url = `${this.config.heartbeatServerUrl}/api/v2/events/session/heartbeat?id=${sessionIdOrUserId}&close=${closeSession + ""}`; + const url = `${this.config.heartbeatServerUrl}/api/v2/events/session/heartbeat?id=${encodeURIComponent(sessionIdOrUserId)}&close=${closeSession + ""}`; return await this.apiFetch(url, { method: "GET" }); @@ -61,7 +67,6 @@ export class DefaultSubmissionClient implements ISubmissionClient { } protected async apiFetch(url: string, options: FetchOptions): Promise> { - // TODO: Figure out how to set a 10000 timeout. const requestOptions: RequestInit = { method: options.method, headers: { @@ -72,19 +77,76 @@ export class DefaultSubmissionClient implements ISubmissionClient { body: options.body ?? null }; - // TODO: Can we properly calculate content size? if (options.method === "POST" && this.isHeaders(requestOptions.headers)) { requestOptions.headers["Content-Type"] = "application/json"; } - const response = await this.fetch(url, requestOptions); - const rateLimitRemaining: number = parseInt(response.headers.get(this.RateLimitRemainingHeader) || "", 10); - const settingsVersion: number = parseInt(response.headers.get(this.ConfigurationVersionHeader) || "", 10); + // keepalive lets a submission started while the page is being hidden or unloaded finish after the page is gone. + const keepAliveBytes = this.getKeepAliveBytes(options.body); + if (keepAliveBytes > 0) { + requestOptions.keepalive = true; + this._keepAliveBytesInFlight += keepAliveBytes; + } + + const controller = typeof AbortController === "function" ? new AbortController() : undefined; + const timeoutId = controller ? setTimeout(() => controller.abort(), this.RequestTimeout) : undefined; + if (controller) { + requestOptions.signal = controller.signal; + allowProcessToExitWithoutWaitingForTimerOrInterval(timeoutId); + } + + try { + const response = await this.fetch(url, requestOptions); + const rateLimitRemaining: number = parseInt(response.headers.get(this.RateLimitRemainingHeader) || "", 10); + const settingsVersion: number = parseInt(response.headers.get(this.ConfigurationVersionHeader) || "", 10); + + const responseText = await response.text(); + return new Response(response.status, response.statusText, rateLimitRemaining, settingsVersion, this.parseResponseData(responseText)); + } catch (ex) { + if (controller?.signal.aborted) { + throw new Error(`Request to ${url} timed out after ${this.RequestTimeout}ms`, { + cause: ex + }); + } + + throw ex; + } finally { + clearTimeout(timeoutId); + this._keepAliveBytesInFlight -= keepAliveBytes; + } + } + + private parseResponseData(responseText: string): T | null { + if (!responseText) { + return null; + } - const responseText = await response.text(); - const data = responseText && responseText.length > 0 ? (JSON.parse(responseText) as T) : null; + try { + return JSON.parse(responseText) as T; + } catch { + // Proxies, captive portals and gateways can answer with HTML or plain text. + this.config.services.log.trace("Response body was not valid JSON"); + return null; + } + } + + private getKeepAliveBytes(body: string | undefined): number { + if (!body) { + return 0; + } + + // UTF-8 uses at most 3 bytes per UTF-16 code unit, so this avoids encoding the body just to measure it. + const maxBytes = body.length * 3; + let bytes = maxBytes; + if (maxBytes > this.KeepAliveBodyLimit) { + if (typeof TextEncoder !== "function" || body.length > this.KeepAliveBodyLimit) { + return 0; + } + + bytes = new TextEncoder().encode(body).length; + } - return new Response(response.status, response.statusText, rateLimitRemaining, settingsVersion, data); + return this._keepAliveBytesInFlight + bytes <= this.KeepAliveBodyLimit ? bytes : 0; } private isHeaders(headers: HeadersInit | undefined): headers is Record { diff --git a/packages/core/test/queue/DefaultEventQueue.test.ts b/packages/core/test/queue/DefaultEventQueue.test.ts index 65948ad9..25a1a8d3 100644 --- a/packages/core/test/queue/DefaultEventQueue.test.ts +++ b/packages/core/test/queue/DefaultEventQueue.test.ts @@ -1,10 +1,25 @@ -import { afterEach, beforeEach, describe, expect, test } from "vitest"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; import { Configuration } from "../../src/configuration/Configuration.js"; +import { ServerSettings } from "../../src/configuration/SettingsManager.js"; import { Event } from "../../src/models/Event.js"; import { DefaultEventQueue } from "../../src/queue/DefaultEventQueue.js"; +import { InMemoryStorage } from "../../src/storage/InMemoryStorage.js"; +import { ISubmissionClient } from "../../src/submission/ISubmissionClient.js"; +import { Response } from "../../src/submission/Response.js"; import { delay } from "../helpers.js"; +function signal(): { wait: Promise; release: () => void } { + let release!: () => void; + const wait = new Promise((resolve) => { + release = resolve; + }); + return { + wait, + release + }; +} + describe("DefaultEventQueue", () => { let config: Configuration; @@ -86,3 +101,451 @@ describe("DefaultEventQueue", () => { } }); }); + +class ScriptedSubmissionClient implements ISubmissionClient { + public submissions: Event[][] = []; + + public constructor(private statuses: number[] = []) {} + + public submitEvents(events: Event[]): Promise { + this.submissions.push(events); + const status = this.statuses.length > 0 ? (this.statuses.shift() as number) : 202; + return Promise.resolve(new Response(status, "", NaN, NaN, undefined)); + } + + public getSettings(): Promise> { + return Promise.reject(new Error("Not implemented")); + } + + public submitUserDescription(): Promise { + return Promise.reject(new Error("Not implemented")); + } + + public submitHeartbeat(): Promise { + return Promise.reject(new Error("Not implemented")); + } + + public get submittedReferenceIds(): (string | undefined)[] { + return this.submissions.flat().map((e) => e.reference_id); + } +} + +describe("DefaultEventQueue submission", () => { + let config: Configuration; + let client: ScriptedSubmissionClient; + + function useClient(statuses: number[] = []): ScriptedSubmissionClient { + client = new ScriptedSubmissionClient(statuses); + config.services.submissionClient = client; + return client; + } + + function createEvent(referenceId: string): Event { + return { + type: "log", + reference_id: referenceId + }; + } + + async function storedQueueKeys(): Promise { + return (await config.services.storage.keys()).filter((key) => key.startsWith("q:")); + } + + beforeEach(async () => { + config = new Configuration(); + config.apiKey = "UNIT_TEST_API_KEY"; + config.serverUrl = "http://server.localhost:5000"; + config.usePersistedQueueStorage = true; + await config.services.storage.clear(); + useClient(); + }); + + afterEach(async () => { + vi.useRealTimers(); + await config.services.queue.suspend(); + }); + + test("sends events enqueued before the first process exactly once", async () => { + await config.services.queue.enqueue(createEvent("event-0001")); + await config.services.queue.enqueue(createEvent("event-0002")); + + await config.services.queue.process(); + + expect(client.submittedReferenceIds).toEqual(["event-0001", "event-0002"]); + expect(await storedQueueKeys()).toHaveLength(0); + }); + + test("loads events persisted by an earlier session first and in order", async () => { + const { storage } = config.services; + await storage.setItem("q:2000.json", JSON.stringify(createEvent("persisted-2"))); + await storage.setItem("q:1000-abc.json", JSON.stringify(createEvent("persisted-1"))); + await config.services.queue.enqueue(createEvent("current-01")); + + await config.services.queue.process(); + + expect(client.submittedReferenceIds).toEqual(["persisted-1", "persisted-2", "current-01"]); + }); + + test("removes an unreadable persisted entry and still loads the rest", async () => { + const { storage } = config.services; + await storage.setItem("q:1000.json", "{not json"); + await storage.setItem("q:2000.json", JSON.stringify(createEvent("persisted-2"))); + + await config.services.queue.process(); + + expect(client.submittedReferenceIds).toEqual(["persisted-2"]); + expect(await storage.getItem("q:1000.json")).toBeNull(); + }); + + test("applies max items to persisted events", async () => { + config.services.queue = new DefaultEventQueue(config, 2); + const { storage } = config.services; + for (let index = 1; index <= 3; index++) { + await storage.setItem(`q:${index}000.json`, JSON.stringify(createEvent(`persisted-${index}`))); + } + + await config.services.queue.process(); + + expect(client.submittedReferenceIds).toEqual(["persisted-2", "persisted-3"]); + expect(await storedQueueKeys()).toHaveLength(0); + }); + + test("skips persisted events another client already submitted", async () => { + await config.services.queue.enqueue(createEvent("event-0001")); + await config.services.queue.enqueue(createEvent("event-0002")); + const [firstKey] = (await storedQueueKeys()).sort(); + await config.services.storage.removeItem(firstKey); + + await config.services.queue.process(); + + expect(client.submittedReferenceIds).toEqual(["event-0002"]); + }); + + test("concurrent queues sharing localStorage submit a persisted event once with Web Locks", async () => { + // Arrange + config.useLocalStorage(); + const otherQueue = new DefaultEventQueue(config); + await config.services.queue.enqueue(createEvent("event-0001")); + const held = new Map>(); + vi.stubGlobal("navigator", { + locks: { + async request(name: string, action: () => Promise) { + const previous = held.get(name); + const done = signal(); + held.set(name, done.wait); + await previous; + try { + return await action(); + } finally { + done.release(); + } + } + } + }); + + try { + // Act + await Promise.all([config.services.queue.process(), otherQueue.process()]); + + // Assert + expect(client.submittedReferenceIds).toEqual(["event-0001"]); + expect(await storedQueueKeys()).toHaveLength(0); + } finally { + vi.unstubAllGlobals(); + } + }); + + test("disabling a client while it waits for the storage lock preserves its queued events", async () => { + // Arrange + config.useLocalStorage(); + const requested = signal(); + const available = signal(); + vi.stubGlobal("navigator", { + locks: { + async request(_name: string, action: () => Promise) { + requested.release(); + await available.wait; + return action(); + } + } + }); + + try { + await config.services.queue.enqueue(createEvent("event-0001")); + + // Act + const processing = config.services.queue.process(); + await requested.wait; + config.enabled = false; + available.release(); + await processing; + + // Assert + expect(client.submissions).toHaveLength(0); + expect(await storedQueueKeys()).toHaveLength(1); + } finally { + vi.unstubAllGlobals(); + } + }); + + test("gives queue entries from the same millisecond distinct keys", async () => { + vi.useFakeTimers({ + toFake: ["Date"] + }); + vi.setSystemTime(new Date("2026-01-01T00:00:00Z")); + const otherQueue = new DefaultEventQueue(config); + + await config.services.queue.enqueue(createEvent("event-0001")); + await otherQueue.enqueue(createEvent("event-0002")); + + expect(await storedQueueKeys()).toHaveLength(2); + }); + + test.each([200, 201, 204])("treats a %i response as sent", async (status) => { + useClient([status]); + await config.services.queue.enqueue(createEvent("event-0001")); + + await config.services.queue.process(); + await config.services.queue.process(); + + expect(client.submissions).toHaveLength(1); + expect(await storedQueueKeys()).toHaveLength(0); + }); + + test("sends every batch in one process call", async () => { + config.submissionBatchSize = 2; + for (let index = 1; index <= 5; index++) { + await config.services.queue.enqueue(createEvent(`event-000${index}`)); + } + + await config.services.queue.process(); + + expect(client.submissions.map((batch) => batch.length)).toEqual([2, 2, 1]); + }); + + test("retries a too-large batch in smaller batches without changing the configured batch size", async () => { + config.submissionBatchSize = 4; + useClient([413]); + for (let index = 1; index <= 4; index++) { + await config.services.queue.enqueue(createEvent(`event-000${index}`)); + } + + await config.services.queue.process(); + + expect(client.submissions.map((batch) => batch.length)).toEqual([4, 3, 1]); + expect(client.submittedReferenceIds.slice(4)).toEqual(["event-0001", "event-0002", "event-0003", "event-0004"]); + expect(config.submissionBatchSize).toBe(4); + }); + + test("drops a single event that is too large and keeps sending", async () => { + config.submissionBatchSize = 1; + useClient([413]); + await config.services.queue.enqueue(createEvent("event-0001")); + await config.services.queue.enqueue(createEvent("event-0002")); + + await config.services.queue.process(); + + expect(client.submittedReferenceIds).toEqual(["event-0001", "event-0002"]); + expect(await storedQueueKeys()).toHaveLength(0); + }); + + test.each([429, 500, 503])("keeps events and backs off for five minutes after a %i response", async (status) => { + vi.useFakeTimers({ + toFake: ["Date"] + }); + // On a quarter hour, where the old backoff calculation produced no delay. + vi.setSystemTime(new Date("2026-01-01T10:15:00Z")); + useClient([status]); + await config.services.queue.enqueue(createEvent("event-0001")); + + await config.services.queue.process(); + await config.services.queue.process(); + expect(client.submissions).toHaveLength(1); + expect(await storedQueueKeys()).toHaveLength(1); + + vi.setSystemTime(new Date("2026-01-01T10:20:01Z")); + await config.services.queue.process(); + expect(client.submissions).toHaveLength(2); + expect(await storedQueueKeys()).toHaveLength(0); + }); + + test("keeps events and backs off when the submission throws", async () => { + vi.useFakeTimers({ + toFake: ["Date"] + }); + vi.setSystemTime(new Date("2026-01-01T10:15:00Z")); + const submitEvents = vi.spyOn(client, "submitEvents").mockRejectedValueOnce(new Error("Failed to fetch")); + await config.services.queue.enqueue(createEvent("event-0001")); + + await config.services.queue.process(); + await config.services.queue.process(); + + expect(submitEvents).toHaveBeenCalledTimes(1); + expect(await storedQueueKeys()).toHaveLength(1); + }); + + test("discards queued and new events after a 402 response", async () => { + vi.useFakeTimers({ + toFake: ["Date"] + }); + vi.setSystemTime(new Date("2026-01-01T10:00:00Z")); + useClient([402]); + await config.services.queue.enqueue(createEvent("event-0001")); + + await config.services.queue.process(); + await config.services.queue.enqueue(createEvent("event-0002")); + + expect(await storedQueueKeys()).toHaveLength(0); + }); + + test("sends an event from memory when persisting it fails", async () => { + const storage = new InMemoryStorage(); + vi.spyOn(storage, "setItem").mockRejectedValue(new Error("QuotaExceededError")); + config.services.storage = storage; + + await config.services.queue.enqueue(createEvent("event-0001")); + await config.services.queue.process(); + + expect(client.submittedReferenceIds).toEqual(["event-0001"]); + }); + + test("waits for a pending write before sending the event", async () => { + const storage = new InMemoryStorage(); + let finishWrite: () => void = () => {}; + const setItem = storage.setItem.bind(storage); + vi.spyOn(storage, "setItem").mockImplementationOnce( + (key, value) => + new Promise((resolve) => { + finishWrite = () => void setItem(key, value).then(resolve); + }) + ); + config.services.storage = storage; + + const enqueued = config.services.queue.enqueue(createEvent("event-0001")); + const processed = config.services.queue.process(); + finishWrite(); + await Promise.all([enqueued, processed]); + + expect(client.submittedReferenceIds).toEqual(["event-0001"]); + expect(await storage.keys()).toHaveLength(0); + }); + + test("stops sending batches once the client is disabled", async () => { + config.submissionBatchSize = 1; + config.services.queue.onEventsPosted(() => { + config.enabled = false; + return Promise.resolve(); + }); + await config.services.queue.enqueue(createEvent("event-0001")); + await config.services.queue.enqueue(createEvent("event-0002")); + + await config.services.queue.process(); + + expect(client.submittedReferenceIds).toEqual(["event-0001"]); + }); + + test("keeps a persisted entry that could not be read", async () => { + const { storage } = config.services; + await storage.setItem("q:1000.json", JSON.stringify(createEvent("persisted-1"))); + vi.spyOn(storage, "getItem").mockRejectedValueOnce(new Error("Storage unavailable")); + + await config.services.queue.process(); + + expect(client.submissions).toHaveLength(0); + expect(await storedQueueKeys()).toEqual(["q:1000.json"]); + }); + + test("sends an event from memory when storage throws synchronously", async () => { + const storage = new InMemoryStorage(); + vi.spyOn(storage, "setItem").mockImplementation(() => { + throw new Error("QuotaExceededError"); + }); + config.services.storage = storage; + + await config.services.queue.enqueue(createEvent("event-0001")); + await config.services.queue.process(); + + expect(client.submittedReferenceIds).toEqual(["event-0001"]); + }); + + test("process waits for a run that is already sending", async () => { + let finishSubmission: () => void = () => {}; + const submitEvents = client.submitEvents.bind(client); + vi.spyOn(client, "submitEvents").mockImplementationOnce( + (events) => + new Promise((resolve) => { + finishSubmission = () => void submitEvents(events).then(resolve); + }) + ); + await config.services.queue.enqueue(createEvent("event-0001")); + + const first = config.services.queue.process(); + let secondFinished = false; + const second = config.services.queue.process().then(() => { + secondFinished = true; + }); + await delay(10); + expect(secondFinished).toBe(false); + + finishSubmission(); + await Promise.all([first, second]); + expect(secondFinished).toBe(true); + expect(await storedQueueKeys()).toHaveLength(0); + }); + + test("an independent process call waits for delivery while an async handler reenters the queue", async () => { + // Arrange + config.submissionBatchSize = 1; + const { queue } = config.services; + const handlerStarted = signal(); + const resumeHandler = signal(); + const handlerDone = signal(); + const secondSubmission = signal(); + const submit = client.submitEvents.bind(client); + vi.spyOn(client, "submitEvents").mockImplementation(async (events) => { + if (events[0].reference_id === "event-0002") { + await secondSubmission.wait; + } + return submit(events); + }); + queue.onEventsPosted(async (events) => { + if (events[0].reference_id === "event-0001") { + handlerStarted.release(); + await resumeHandler.wait; + await queue.process(); + handlerDone.release(); + } + }); + await queue.enqueue(createEvent("event-0001")); + await queue.enqueue(createEvent("event-0002")); + + // Act + const first = queue.process(); + await handlerStarted.wait; + let externalFinished = false; + async function processIndependently(): Promise { + await queue.process(); + externalFinished = true; + } + const external = processIndependently(); + resumeHandler.release(); + await delay(0); + + // Assert + expect(externalFinished).toBe(false); + secondSubmission.release(); + await Promise.all([first, external, handlerDone.wait]); + expect(client.submittedReferenceIds).toEqual(["event-0001", "event-0002"]); + }); + + test("an onEventsPosted handler that processes the queue does not wait for its own run", async () => { + config.services.queue.onEventsPosted(() => config.services.queue.process()); + await config.services.queue.enqueue(createEvent("event-0001")); + + await config.services.queue.process(); + await config.services.queue.enqueue(createEvent("event-0002")); + await config.services.queue.process(); + + expect(client.submittedReferenceIds).toEqual(["event-0001", "event-0002"]); + }); +}); diff --git a/packages/core/test/submission/DefaultSubmissionClient.test.ts b/packages/core/test/submission/DefaultSubmissionClient.test.ts new file mode 100644 index 00000000..a339ccfe --- /dev/null +++ b/packages/core/test/submission/DefaultSubmissionClient.test.ts @@ -0,0 +1,187 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +import { Configuration } from "../../src/configuration/Configuration.js"; +import { DefaultSubmissionClient } from "../../src/submission/DefaultSubmissionClient.js"; + +type FetchMock = ReturnType Promise>>; + +describe("DefaultSubmissionClient", () => { + let config: Configuration; + let fetchMock: FetchMock; + + function respond(status: number, body: string = "", headers: Record = {}): void { + fetchMock.mockImplementation(() => + Promise.resolve( + new globalThis.Response(status === 204 ? null : body, { + status, + headers + }) + ) + ); + } + + function lastRequest(): { url: string; init: RequestInit } { + const [url, init] = fetchMock.mock.calls[fetchMock.mock.calls.length - 1]; + return { + url, + init + }; + } + + beforeEach(() => { + config = new Configuration(); + config.apiKey = "UNIT_TEST_API_KEY"; + config.serverUrl = "https://collector.example.test"; + config.configServerUrl = "https://config.example.test"; + config.heartbeatServerUrl = "https://heartbeat.example.test"; + config.updateSettingsWhenIdleInterval = -1; + fetchMock = vi.fn<(url: string, init: RequestInit) => Promise>(); + respond(202, "", { + "x-exceptionless-configversion": "0" + }); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + test("gets settings from the config server", async () => { + respond( + 200, + JSON.stringify({ + version: 2, + settings: {} + }) + ); + const client = new DefaultSubmissionClient(config, fetchMock); + + const response = await client.getSettings(1); + + expect(lastRequest().url).toBe("https://config.example.test/api/v2/projects/config?v=1"); + expect(response.data).toEqual({ + version: 2, + settings: {} + }); + }); + + test("encodes the session id in heartbeat requests", async () => { + respond(200); + const client = new DefaultSubmissionClient(config, fetchMock); + + await client.submitHeartbeat("user+name@example.com&close=true", false); + + expect(lastRequest().url).toBe("https://heartbeat.example.test/api/v2/events/session/heartbeat?id=user%2Bname%40example.com%26close%3Dtrue&close=false"); + }); + + test("returns the status when the response body is not JSON", async () => { + respond(502, "Bad Gateway"); + const client = new DefaultSubmissionClient(config, fetchMock); + + const response = await client.submitEvents([ + { + type: "log", + message: "test" + } + ]); + + expect(response.status).toBe(502); + expect(response.data).toBeNull(); + }); + + test("aborts a request the server never answers", async () => { + vi.useFakeTimers(); + fetchMock.mockImplementation( + (_url, init) => + new Promise((_resolve, reject) => { + init.signal?.addEventListener("abort", () => reject(new DOMException("The operation was aborted.", "AbortError"))); + }) + ); + const client = new DefaultSubmissionClient(config, fetchMock); + + const outcome = client + .submitEvents([ + { + type: "log", + message: "test" + } + ]) + .then( + () => undefined, + (error: unknown) => error + ); + await vi.advanceTimersByTimeAsync(30000); + + expect(await outcome).toEqual( + expect.objectContaining({ + message: expect.stringContaining("timed out") as string + }) + ); + }); + + test("sends small submissions with keepalive so they survive page unload", async () => { + const client = new DefaultSubmissionClient(config, fetchMock); + + await client.submitEvents([ + { + type: "log", + message: "test" + } + ]); + + expect(lastRequest().init.keepalive).toBe(true); + }); + + test("sends large submissions without keepalive", async () => { + const client = new DefaultSubmissionClient(config, fetchMock); + + await client.submitEvents([ + { + type: "log", + message: "x".repeat(70000) + } + ]); + + expect(lastRequest().init.keepalive).toBeUndefined(); + }); + + test("keeps concurrent keepalive submissions under the browser limit", async () => { + let release: () => void = () => {}; + fetchMock.mockImplementationOnce( + () => + new Promise((resolve) => { + release = () => + resolve( + new globalThis.Response("", { + status: 202 + }) + ); + }) + ); + const client = new DefaultSubmissionClient(config, fetchMock); + const message = "x".repeat(12000); + + const first = client.submitEvents([ + { + type: "log", + message + } + ]); + const second = client.submitEvents([ + { + type: "log", + message + } + ]); + await second; + release(); + await first; + await client.submitEvents([ + { + type: "log", + message + } + ]); + + expect(fetchMock.mock.calls.map(([, init]) => init.keepalive)).toEqual([true, undefined, true]); + }); +}); diff --git a/packages/core/test/submission/TestSubmissionClient.test.ts b/packages/core/test/submission/TestSubmissionClient.test.ts index 77d2844e..bceab6d5 100644 --- a/packages/core/test/submission/TestSubmissionClient.test.ts +++ b/packages/core/test/submission/TestSubmissionClient.test.ts @@ -85,7 +85,7 @@ describe("TestSubmissionClient", () => { method: "POST", body: JSON.stringify(description) }); - expect(apiFetchMock.mock.calls[1][0]).toBe(`${config.serverUrl}/api/v2/projects/config?v=0`); + expect(apiFetchMock.mock.calls[1][0]).toBe(`${config.configServerUrl}/api/v2/projects/config?v=0`); expect(apiFetchMock.mock.calls[1][1]).toEqual({ method: "GET" }); @@ -113,7 +113,7 @@ describe("TestSubmissionClient", () => { const client = new TestSubmissionClient(config, apiFetchMock); await client.getSettings(0); expect(apiFetchMock).toHaveBeenCalledTimes(1); - expect(apiFetchMock.mock.calls[0][0]).toBe(`${config.serverUrl}/api/v2/projects/config?v=0`); + expect(apiFetchMock.mock.calls[0][0]).toBe(`${config.configServerUrl}/api/v2/projects/config?v=0`); expect(apiFetchMock.mock.calls[0][1]).toEqual({ method: "GET" });