From f73162320704d9491cd8163d4c790d6f2ce2714a Mon Sep 17 00:00:00 2001 From: "Eric J. Smith" Date: Tue, 1 Dec 2026 19:11:42 -0600 Subject: [PATCH 1/7] Fix client startup, session and settings lifecycle - startup() with no arguments now configures runtime plugins when the API key was set beforehand; the client stays unconfigured until a call leaves a valid key, and later calls only resume (configuration passed to them is ignored with a warning). - Resuming a hidden tab no longer starts a new session every time; the session continues unless the client was suspended longer than the server's 5-minute inactivity period. Heartbeats resume with it. - Browser: end the session and flush on pagehide instead of beforeunload, and resume on back/forward cache restore. React Native web also uses pagehide. - Add flush(timeoutMs) for short-lived processes. - Applying server settings no longer overwrites the original settings, so settings the server stops sending are removed; non-string values are ignored. - Settings updates lock per configuration instead of globally. - config.plugins returns a sorted copy so removing a plugin while iterating doesn't skip the next one. --- .../skills/exceptionless-javascript/SKILL.md | 4 +- .../references/sessions.md | 5 + .../references/troubleshooting.md | 3 +- .../browser/src/BrowserExceptionlessClient.ts | 2 +- .../src/plugins/BrowserLifeCyclePlugin.ts | 10 +- .../test/BrowserExceptionlessClient.test.ts | 18 ++ .../plugins/BrowserLifeCyclePlugin.test.ts | 65 +++++ packages/core/src/ExceptionlessClient.ts | 67 ++++- .../core/src/configuration/Configuration.ts | 22 +- .../core/src/configuration/SettingsManager.ts | 8 +- .../src/plugins/default/HeartbeatPlugin.ts | 22 +- .../test/ExceptionlessClientLifecycle.test.ts | 261 ++++++++++++++++++ packages/node/src/NodeExceptionlessClient.ts | 2 +- .../src/ReactNativeExceptionlessClient.ts | 2 +- .../src/plugins/ReactNativeLifeCyclePlugin.ts | 4 +- .../ReactNativeLifeCyclePlugin.test.ts | 6 +- 16 files changed, 468 insertions(+), 33 deletions(-) create mode 100644 packages/browser/test/plugins/BrowserLifeCyclePlugin.test.ts create mode 100644 packages/core/test/ExceptionlessClientLifecycle.test.ts diff --git a/.agents/skills/exceptionless-javascript/SKILL.md b/.agents/skills/exceptionless-javascript/SKILL.md index 99e273e0..23099f92 100644 --- a/.agents/skills/exceptionless-javascript/SKILL.md +++ b/.agents/skills/exceptionless-javascript/SKILL.md @@ -30,7 +30,7 @@ Read only the references needed for the request. Start with the runtime for setu ## Rules -- Use `Exceptionless.startup(...)` once during app startup. `startup()` with no args is used later by lifecycle plugins to resume timers/queue processing. +- Use `Exceptionless.startup(...)` once during app startup. The first call that leaves a valid API key configures the client, including when `config.apiKey` was set beforehand and `startup()` gets no arguments; later calls only resume timers and queue processing, and configuration passed to them is ignored with a warning. - Use the singleton from the platform package when automatic capture matters. Create `ExceptionlessClient` manually only for custom pipelines or tests. - For React Native or Expo apps, use `@exceptionless/react-native`; do not substitute `@exceptionless/browser` or `@exceptionless/react`. - In Expo, add `@exceptionless/react-native/expo-plugin` when native iOS crash reporting is expected. Expo Go can report JavaScript errors but cannot load the native crash reporter. @@ -38,7 +38,7 @@ Read only the references needed for the request. Start with the runtime for setu - `markAsCritical()` marks the event critical; `markAsCritical(false)` leaves tags unchanged. - `config.serverUrl` also sets `configServerUrl` and `heartbeatServerUrl`; assign custom endpoint overrides after setting `serverUrl`. - Use lowercase log levels in new snippets: `"trace"`, `"debug"`, `"info"`, `"warn"`, `"error"`, `"fatal"`, `"off"`. -- For short-lived Node/serverless work, call `await Exceptionless.processQueue()` after critical submissions. +- For short-lived Node/serverless work, call `await Exceptionless.flush()` (waits up to 10 seconds by default, returns `false` on timeout) or `await Exceptionless.processQueue()` after critical submissions. ## Integrator Guidance diff --git a/.agents/skills/exceptionless-javascript/references/sessions.md b/.agents/skills/exceptionless-javascript/references/sessions.md index e01a06e0..5a5027ca 100644 --- a/.agents/skills/exceptionless-javascript/references/sessions.md +++ b/.agents/skills/exceptionless-javascript/references/sessions.md @@ -26,6 +26,11 @@ await Exceptionless.startup((config) => { - `heartbeatInterval` defaults to 60000ms. Values below 30000ms are reset to 60000ms. - `useSessionIdManagement` adds `SessionIdManagementPlugin`, which creates a session id and links later events to it. +Session lifetime in the browser and React Native: + +- `startup()` sends a session start once. Resuming after a hidden tab continues the same session (and its heartbeats) unless the client was suspended for more than 5 minutes, after which the server has closed the session and a new one starts. +- The browser ends the session on `pagehide` and starts a new one if the page is restored from the back/forward cache. React Native ends it when the app goes to the background and starts a new one when it becomes active. + Disable heartbeat traffic while still using session events: ```js diff --git a/.agents/skills/exceptionless-javascript/references/troubleshooting.md b/.agents/skills/exceptionless-javascript/references/troubleshooting.md index 4fe2c2d2..bf21b7f8 100644 --- a/.agents/skills/exceptionless-javascript/references/troubleshooting.md +++ b/.agents/skills/exceptionless-javascript/references/troubleshooting.md @@ -25,7 +25,8 @@ Events are queued and sent in the background. If the app exits or navigates imme ```js import { Exceptionless } from "@exceptionless/browser"; -await Exceptionless.processQueue(); +// Waits at most 10 seconds by default; returns false if the queue didn't finish in time. +await Exceptionless.flush(); ``` This matters most for Node scripts, CLIs, serverless handlers, route handlers, tests, and hard redirects. diff --git a/packages/browser/src/BrowserExceptionlessClient.ts b/packages/browser/src/BrowserExceptionlessClient.ts index bc162739..b9cb0d9c 100644 --- a/packages/browser/src/BrowserExceptionlessClient.ts +++ b/packages/browser/src/BrowserExceptionlessClient.ts @@ -10,7 +10,7 @@ import { BrowserRequestInfoPlugin } from "./plugins/BrowserRequestInfoPlugin.js" export class BrowserExceptionlessClient extends ExceptionlessClient { public async startup(configurationOrApiKey?: ((config: Configuration) => void) | string): Promise { const config = this.config; - if (configurationOrApiKey && !this._initialized) { + if (!this._initialized) { config.useLocalStorage(); config.addPlugin(new BrowserGlobalHandlerPlugin()); diff --git a/packages/browser/src/plugins/BrowserLifeCyclePlugin.ts b/packages/browser/src/plugins/BrowserLifeCyclePlugin.ts index e33ed329..b73eea9c 100644 --- a/packages/browser/src/plugins/BrowserLifeCyclePlugin.ts +++ b/packages/browser/src/plugins/BrowserLifeCyclePlugin.ts @@ -13,7 +13,8 @@ export class BrowserLifeCyclePlugin implements IEventPlugin { this._client = context.client; - globalThis.addEventListener("beforeunload", () => { + // pagehide fires reliably on mobile and doesn't stop the page from entering the back/forward cache, unlike beforeunload. + globalThis.addEventListener("pagehide", () => { if (this._client?.config.sessionsEnabled) { void this._client?.submitSessionEnd(); } @@ -21,6 +22,13 @@ export class BrowserLifeCyclePlugin implements IEventPlugin { void this._client?.suspend(); }); + // A page restored from the back/forward cache starts a new session. + globalThis.addEventListener("pageshow", (event: PageTransitionEvent) => { + if (event.persisted) { + void this._client?.startup(); + } + }); + document.addEventListener("visibilitychange", () => { if (document.visibilityState === "visible") { void this._client?.startup(); diff --git a/packages/browser/test/BrowserExceptionlessClient.test.ts b/packages/browser/test/BrowserExceptionlessClient.test.ts index fef43605..a4b2c84a 100644 --- a/packages/browser/test/BrowserExceptionlessClient.test.ts +++ b/packages/browser/test/BrowserExceptionlessClient.test.ts @@ -25,4 +25,22 @@ describe("BrowserExceptionlessClient", () => { await client.suspend(); } }); + + test("should configure browser plugins when startup is called without arguments", async () => { + const client = new BrowserExceptionlessClient(); + client.config.apiKey = "UNIT_TEST_API_KEY"; + client.config.updateSettingsWhenIdleInterval = -1; + + await client.startup(); + + try { + const pluginNames = client.config.plugins.map((plugin) => plugin.name); + + expect(pluginNames).toContain("BrowserGlobalHandlerPlugin"); + expect(pluginNames).toContain("BrowserErrorPlugin"); + expect(pluginNames).not.toContain("SimpleErrorPlugin"); + } finally { + await client.suspend(); + } + }); }); diff --git a/packages/browser/test/plugins/BrowserLifeCyclePlugin.test.ts b/packages/browser/test/plugins/BrowserLifeCyclePlugin.test.ts new file mode 100644 index 00000000..4c87f35d --- /dev/null +++ b/packages/browser/test/plugins/BrowserLifeCyclePlugin.test.ts @@ -0,0 +1,65 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { ExceptionlessClient } from "@exceptionless/core"; + +import { BrowserLifeCyclePlugin } from "../../src/plugins/BrowserLifeCyclePlugin.js"; + +describe("BrowserLifeCyclePlugin", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + async function startPlugin() { + const listeners = new Map(); + vi.spyOn(globalThis, "addEventListener").mockImplementation((type: string, listener: EventListenerOrEventListenerObject) => { + listeners.set(type, listener as EventListener); + }); + + const client = new ExceptionlessClient(); + client.config.sessionsEnabled = true; + const suspend = vi.spyOn(client, "suspend").mockResolvedValue(); + const startup = vi.spyOn(client, "startup").mockResolvedValue(); + const submitSessionEnd = vi.spyOn(client, "submitSessionEnd").mockResolvedValue(); + + await new BrowserLifeCyclePlugin().startup({ + client, + log: client.config.services.log + }); + + return { + listeners, + suspend, + startup, + submitSessionEnd + }; + } + + test("ends the session and flushes on pagehide instead of beforeunload", async () => { + const { listeners, suspend, submitSessionEnd } = await startPlugin(); + + expect(listeners.has("beforeunload")).toBe(false); + listeners.get("pagehide")?.(new Event("pagehide")); + + expect(submitSessionEnd).toHaveBeenCalledTimes(1); + expect(suspend).toHaveBeenCalledTimes(1); + }); + + test("resumes when the page is restored from the back/forward cache", async () => { + const { listeners, startup } = await startPlugin(); + const pageshow = listeners.get("pageshow"); + + pageshow?.( + Object.assign(new Event("pageshow"), { + persisted: false + }) + ); + expect(startup).not.toHaveBeenCalled(); + + pageshow?.( + Object.assign(new Event("pageshow"), { + persisted: true + }) + ); + expect(startup).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/core/src/ExceptionlessClient.ts b/packages/core/src/ExceptionlessClient.ts index e4590dca..1cb021ec 100644 --- a/packages/core/src/ExceptionlessClient.ts +++ b/packages/core/src/ExceptionlessClient.ts @@ -12,23 +12,38 @@ import { allowProcessToExitWithoutWaitingForTimerOrInterval } from "./Utils.js"; export class ExceptionlessClient { private _intervalId: ReturnType | undefined; private _timeoutId: ReturnType | undefined; + private _sessionActive = false; + private _suspendedAt: number | undefined; + /** The server closes sessions that have had no activity for this long. */ + private readonly SESSION_INACTIVE_PERIOD = 5 * 60 * 1000; protected _initialized = false; public constructor(public config: Configuration = new Configuration()) {} - /** Resume background submission, resume any timers. */ + /** + * Starts the client, or resumes background submission and timers after `suspend()`. + * The first call that leaves the client with a valid API key configures it; later calls only resume it. + */ public async startup(configurationOrApiKey?: ((config: Configuration) => void) | string): Promise { - if (configurationOrApiKey && !this._initialized) { - this._initialized = true; - + const startingUp = !this._initialized; + if (startingUp) { if (typeof configurationOrApiKey === "string") { this.config.apiKey = configurationOrApiKey; - } else { + } else if (configurationOrApiKey) { configurationOrApiKey(this.config); } + if (!this.config.isValid) { + // Stay uninitialized so a later startup() call can still configure the client. + this.config.services.log.warn("Exceptionless is not configured and will not process events."); + return; + } + + this._initialized = true; this.config.services.queue.onEventsPosted(() => Promise.resolve(this.updateSettingsTimer())); await SettingsManager.applySavedServerSettings(this.config); + } else if (configurationOrApiKey) { + this.config.services.log.warn("Exceptionless has already been started; the configuration passed to startup() was ignored."); } if (!this.config.isValid) { @@ -36,7 +51,7 @@ export class ExceptionlessClient { return; } - this.updateSettingsTimer(!!configurationOrApiKey); + this.updateSettingsTimer(startingUp); await EventPluginManager.startup(new PluginContext(this)); const { queue } = this.config.services; @@ -46,13 +61,19 @@ export class ExceptionlessClient { await queue.process(); } - if (this.config.sessionsEnabled) { + // Resuming (for example, when a hidden tab becomes visible) continues the current session unless the + // server will already have closed it for inactivity. + const suspendedAt = this._suspendedAt; + this._suspendedAt = undefined; + const sessionExpired = suspendedAt !== undefined && Date.now() - suspendedAt > this.SESSION_INACTIVE_PERIOD; + if (this.config.sessionsEnabled && (!this._sessionActive || sessionExpired)) { await this.submitSessionStart(); } } /** Submit events, pause any timers and go into low power mode. */ public async suspend(): Promise { + this._suspendedAt ??= Date.now(); await EventPluginManager.suspend(new PluginContext(this)); const { queue } = this.config.services; await queue.suspend(); @@ -71,6 +92,25 @@ export class ExceptionlessClient { await this.config.services.queue.process(); } + /** + * Sends queued events, waiting at most `timeoutMs`. Use it before a short-lived process, + * serverless handler, or test exits. + * @returns true when the queue finished processing within the timeout. + */ + public async flush(timeoutMs: number = 10000): Promise { + let timeoutId: ReturnType | undefined; + const timeout = new Promise((resolve) => { + timeoutId = setTimeout(() => resolve(false), timeoutMs); + allowProcessToExitWithoutWaitingForTimerOrInterval(timeoutId); + }); + + try { + return await Promise.race([this.processQueue().then(() => true), timeout]); + } finally { + clearTimeout(timeoutId); + } + } + private updateSettingsTimer(startingUp: boolean = false) { this.suspendSettingsTimer(); @@ -172,13 +212,22 @@ export class ExceptionlessClient { return this.createEvent().setType("session"); } - public submitSessionStart(): Promise { - return this.createSessionStart().submit(); + public async submitSessionStart(): Promise { + const context = await this.createSessionStart().submit(); + if (!context.cancelled) { + this._sessionActive = true; + } + + return context; } public async submitSessionEnd(sessionIdOrUserId?: string): Promise { const { currentSessionIdentifier, enabled, isValid, services } = this.config; const sessionId = sessionIdOrUserId || currentSessionIdentifier; + if (!sessionIdOrUserId || sessionIdOrUserId === currentSessionIdentifier) { + this._sessionActive = false; + } + if (sessionId && enabled && isValid) { services.log.info(`Submitting session end: ${sessionId}`); await services.submissionClient.submitHeartbeat(sessionId, true); diff --git a/packages/core/src/configuration/Configuration.ts b/packages/core/src/configuration/Configuration.ts index 8bb93381..00f8e51c 100644 --- a/packages/core/src/configuration/Configuration.ts +++ b/packages/core/src/configuration/Configuration.ts @@ -347,7 +347,8 @@ export class Configuration { * The list of plugins that will be used in this configuration. */ public get plugins(): IEventPlugin[] { - return this._plugins.sort((p1: IEventPlugin, p2: IEventPlugin) => { + // Sort a copy: callers iterate this list while plugins may add or remove plugins. + return [...this._plugins].sort((p1: IEventPlugin, p2: IEventPlugin) => { if (p1 == null && p2 == null) { return 0; } @@ -529,8 +530,23 @@ export class Configuration { } this.services.log.trace(`Applying saved settings: v${serverSettings.version}`); - this.settings = Object.assign(this.originalSettings, serverSettings.settings); - this.settingsVersion = serverSettings.version; + // Start from the original settings each time so settings the server no longer sends are removed. + const settings: Record = { + ...this.originalSettings + }; + const received: unknown = serverSettings?.settings; + if (received && typeof received === "object") { + for (const [key, value] of Object.entries(received)) { + if (typeof value === "string") { + settings[key] = value; + } else { + this.services.log.warn(`Ignoring server setting "${key}": expected a string value`); + } + } + } + + this.settings = settings; + this.settingsVersion = typeof serverSettings?.version === "number" ? serverSettings.version : 0; this.notifySubscribers(); } diff --git a/packages/core/src/configuration/SettingsManager.ts b/packages/core/src/configuration/SettingsManager.ts index 682c42b0..9d50a289 100644 --- a/packages/core/src/configuration/SettingsManager.ts +++ b/packages/core/src/configuration/SettingsManager.ts @@ -9,7 +9,7 @@ export class ServerSettings { export class SettingsManager { private static readonly SettingsKey: string = "settings"; - private static _isUpdatingSettings = false; + private static readonly _updatingConfigurations = new WeakSet(); public static async applySavedServerSettings(config: Configuration): Promise { if (!config?.isValid) { @@ -23,11 +23,11 @@ export class SettingsManager { } public static async updateSettings(config: Configuration): Promise { - if (!config?.enabled || this._isUpdatingSettings) { + if (!config?.enabled || this._updatingConfigurations.has(config)) { return; } - this._isUpdatingSettings = true; + this._updatingConfigurations.add(config); const { log, storage, submissionClient } = config.services; try { @@ -58,7 +58,7 @@ export class SettingsManager { } catch (ex) { log.error(`Error updating settings: ${ex instanceof Error ? ex.message : ex + ""}`); } finally { - this._isUpdatingSettings = false; + this._updatingConfigurations.delete(config); } } diff --git a/packages/core/src/plugins/default/HeartbeatPlugin.ts b/packages/core/src/plugins/default/HeartbeatPlugin.ts index 2563d00e..f26af8a9 100644 --- a/packages/core/src/plugins/default/HeartbeatPlugin.ts +++ b/packages/core/src/plugins/default/HeartbeatPlugin.ts @@ -2,6 +2,8 @@ import { KnownEventDataKeys } from "../../models/Event.js"; import { allowProcessToExitWithoutWaitingForTimerOrInterval } from "../../Utils.js"; import { EventPluginContext } from "../../plugins/EventPluginContext.js"; import { IEventPlugin } from "../../plugins/IEventPlugin.js"; +import { PluginContext } from "../../plugins/PluginContext.js"; +import type { ExceptionlessClient } from "../../ExceptionlessClient.js"; export class HeartbeatPlugin implements IEventPlugin { public priority = 100; @@ -14,10 +16,16 @@ export class HeartbeatPlugin implements IEventPlugin { this._interval = heartbeatInterval >= 30000 ? heartbeatInterval : 60000; } - public startup(): Promise { + public startup(context: PluginContext): Promise { clearInterval(this._intervalId); this._intervalId = undefined; - // TODO: Do we want to send a heartbeat for the last user? + + // Resume heartbeats for the current session (for example, when a hidden tab becomes visible again). + const { client } = context; + if (this._interval > 0 && client.config.currentSessionIdentifier) { + this.startHeartbeats(client); + } + return Promise.resolve(); } @@ -46,11 +54,15 @@ export class HeartbeatPlugin implements IEventPlugin { } if (config.currentSessionIdentifier) { - this._intervalId = setInterval(() => void context.client.submitSessionHeartbeat(config.currentSessionIdentifier), this._interval); - - allowProcessToExitWithoutWaitingForTimerOrInterval(this._intervalId); + this.startHeartbeats(context.client); } return Promise.resolve(); } + + private startHeartbeats(client: ExceptionlessClient): void { + // Heartbeats always go to the session that is current when they fire. + this._intervalId = setInterval(() => void client.submitSessionHeartbeat(), this._interval); + allowProcessToExitWithoutWaitingForTimerOrInterval(this._intervalId); + } } diff --git a/packages/core/test/ExceptionlessClientLifecycle.test.ts b/packages/core/test/ExceptionlessClientLifecycle.test.ts new file mode 100644 index 00000000..fdc8b9ba --- /dev/null +++ b/packages/core/test/ExceptionlessClientLifecycle.test.ts @@ -0,0 +1,261 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +import { Configuration } from "../src/configuration/Configuration.js"; +import { ServerSettings, SettingsManager } from "../src/configuration/SettingsManager.js"; +import { ExceptionlessClient } from "../src/ExceptionlessClient.js"; +import { Event } from "../src/models/Event.js"; +import { IEventPlugin } from "../src/plugins/IEventPlugin.js"; +import { ISubmissionClient } from "../src/submission/ISubmissionClient.js"; +import { Response } from "../src/submission/Response.js"; + +class StubSubmissionClient implements ISubmissionClient { + public heartbeats: { id: string; close: boolean }[] = []; + public getSettings = vi.fn( + (): Promise> => Promise.resolve(new Response(304, "", NaN, NaN, new ServerSettings({}, 0))) + ); + + public submitEvents(): Promise { + return Promise.resolve(new Response(202, "", NaN, NaN, undefined)); + } + + public submitUserDescription(): Promise { + return Promise.resolve(new Response(202, "", NaN, NaN, undefined)); + } + + public submitHeartbeat(id: string, close: boolean): Promise { + this.heartbeats.push({ + id, + close + }); + return Promise.resolve(new Response(200, "", NaN, NaN, undefined)); + } +} + +function createClient(): { client: ExceptionlessClient; enqueued: Event[]; submissionClient: StubSubmissionClient } { + const client = new ExceptionlessClient(); + const submissionClient = new StubSubmissionClient(); + client.config.services.submissionClient = submissionClient; + client.config.updateSettingsWhenIdleInterval = -1; + + const enqueued: Event[] = []; + vi.spyOn(client.config.services.queue, "enqueue").mockImplementation((event: Event) => { + enqueued.push(event); + return Promise.resolve(); + }); + + return { + client, + enqueued, + submissionClient + }; +} + +function createStartupPlugin(): IEventPlugin & { startup: ReturnType } { + return { + name: "StartupSpy", + priority: 1, + startup: vi.fn(() => Promise.resolve()) + }; +} + +describe("ExceptionlessClient lifecycle", () => { + let clients: ExceptionlessClient[] = []; + + function track(client: ExceptionlessClient): ExceptionlessClient { + clients.push(client); + return client; + } + + beforeEach(() => { + clients = []; + }); + + afterEach(async () => { + vi.useRealTimers(); + for (const client of clients) { + await client.suspend(); + } + }); + + test("startup without arguments starts a client configured beforehand", async () => { + const { client } = createClient(); + track(client); + const plugin = createStartupPlugin(); + client.config.apiKey = "UNIT_TEST_API_KEY"; + client.config.addPlugin(plugin); + + await client.startup(); + + expect(plugin.startup).toHaveBeenCalledTimes(1); + }); + + test("startup before an API key is set can be configured by a later call", async () => { + const { client } = createClient(); + track(client); + const plugin = createStartupPlugin(); + + await client.startup(); + await client.startup((config) => { + config.apiKey = "UNIT_TEST_API_KEY"; + config.addPlugin(plugin); + }); + + expect(client.config.apiKey).toBe("UNIT_TEST_API_KEY"); + expect(plugin.startup).toHaveBeenCalledTimes(1); + }); + + test("startup after the client has started ignores new configuration", async () => { + const { client } = createClient(); + track(client); + + await client.startup("UNIT_TEST_API_KEY"); + await client.startup("OTHER_UNIT_TEST_API_KEY"); + + expect(client.config.apiKey).toBe("UNIT_TEST_API_KEY"); + }); + + test("resuming after a short suspension continues the current session", async () => { + const { client, enqueued } = createClient(); + track(client); + + await client.startup((config) => { + config.apiKey = "UNIT_TEST_API_KEY"; + config.useSessions(false); + }); + await client.suspend(); + await client.startup(); + + expect(enqueued.filter((e) => e.type === "session")).toHaveLength(1); + }); + + test("resuming after the server's inactivity period starts a new session", async () => { + vi.useFakeTimers({ + toFake: ["Date"] + }); + vi.setSystemTime(new Date("2026-01-01T10:00:00Z")); + const { client, enqueued } = createClient(); + track(client); + + await client.startup((config) => { + config.apiKey = "UNIT_TEST_API_KEY"; + config.useSessions(false); + }); + await client.suspend(); + vi.setSystemTime(new Date("2026-01-01T10:05:01Z")); + await client.startup(); + + expect(enqueued.filter((e) => e.type === "session")).toHaveLength(2); + }); + + test("resuming after the session ended starts a new session", async () => { + const { client, enqueued } = createClient(); + track(client); + + await client.startup((config) => { + config.apiKey = "UNIT_TEST_API_KEY"; + config.useSessions(false, undefined, true); + }); + await client.submitSessionEnd(); + await client.suspend(); + await client.startup(); + + const sessions = enqueued.filter((e) => e.type === "session"); + expect(sessions).toHaveLength(2); + expect(sessions[0].reference_id).not.toBe(sessions[1].reference_id); + }); + + test("flush reports whether the queue finished in time", async () => { + const { client } = createClient(); + client.config.apiKey = "UNIT_TEST_API_KEY"; + + expect(await client.flush(1000)).toBe(true); + + vi.spyOn(client.config.services.queue, "process").mockReturnValue(new Promise(() => {})); + expect(await client.flush(10)).toBe(false); + }); +}); + +describe("Server settings", () => { + test("removes settings the server no longer sends and keeps local settings", () => { + const config = new Configuration(); + config.settings["local"] = "value"; + + config.applyServerSettings( + new ServerSettings( + { + "@@error:TypeError": "false" + }, + 1 + ) + ); + config.applyServerSettings( + new ServerSettings( + { + "@@log:*": "info" + }, + 2 + ) + ); + + expect(config.settings).toEqual({ + local: "value", + "@@log:*": "info" + }); + expect(config.settingsVersion).toBe(2); + }); + + test("ignores server settings that are not strings", () => { + const config = new Configuration(); + + config.applyServerSettings( + new ServerSettings( + { + "@@DataExclusions": ["password"] as unknown as string, + "@@log:*": "info" + }, + 1 + ) + ); + + expect(config.settings).toEqual({ + "@@log:*": "info" + }); + expect(config.dataExclusions).toEqual([]); + }); + + test("updates settings for each configuration independently", async () => { + const first = createClient(); + const second = createClient(); + first.client.config.apiKey = "UNIT_TEST_API_KEY"; + second.client.config.apiKey = "OTHER_UNIT_TEST_API_KEY"; + let release: () => void = () => {}; + first.submissionClient.getSettings.mockReturnValueOnce( + new Promise((resolve) => { + release = () => resolve(new Response(304, "", NaN, NaN, new ServerSettings({}, 0))); + }) + ); + + const firstUpdate = SettingsManager.updateSettings(first.client.config); + await SettingsManager.updateSettings(second.client.config); + release(); + await firstUpdate; + + expect(second.submissionClient.getSettings).toHaveBeenCalledTimes(1); + }); +}); + +describe("Configuration plugins", () => { + test("removing a plugin while iterating does not skip the next plugin", () => { + const config = new Configuration(); + const visited: string[] = []; + + for (const plugin of config.plugins) { + visited.push(plugin.name as string); + if (visited.length === 1) { + config.removePlugin(plugin); + } + } + + expect(visited).toHaveLength(new Configuration().plugins.length); + }); +}); diff --git a/packages/node/src/NodeExceptionlessClient.ts b/packages/node/src/NodeExceptionlessClient.ts index fb5f530d..ca13ab0a 100644 --- a/packages/node/src/NodeExceptionlessClient.ts +++ b/packages/node/src/NodeExceptionlessClient.ts @@ -13,7 +13,7 @@ export class NodeExceptionlessClient extends ExceptionlessClient { public async startup(configurationOrApiKey?: ((config: Configuration) => void) | string): Promise { const config = this.config; - if (configurationOrApiKey && !this._initialized) { + if (!this._initialized) { try { const storage = new LocalStorage(undefined, new LocalStoragePolyfill(process.cwd() + "/.exceptionless")); config.useLocalStorage = () => storage; diff --git a/packages/react-native/src/ReactNativeExceptionlessClient.ts b/packages/react-native/src/ReactNativeExceptionlessClient.ts index 9cee8a61..9680dedf 100644 --- a/packages/react-native/src/ReactNativeExceptionlessClient.ts +++ b/packages/react-native/src/ReactNativeExceptionlessClient.ts @@ -12,7 +12,7 @@ export class ReactNativeExceptionlessClient extends ExceptionlessClient { public async startup(configurationOrApiKey?: ((config: Configuration) => void) | string): Promise { const config = this.config; - if (configurationOrApiKey && !this._initialized) { + if (!this._initialized) { this.configureStorage(config); if (Platform.OS === "ios") { diff --git a/packages/react-native/src/plugins/ReactNativeLifeCyclePlugin.ts b/packages/react-native/src/plugins/ReactNativeLifeCyclePlugin.ts index c6cd5cee..d003ef03 100644 --- a/packages/react-native/src/plugins/ReactNativeLifeCyclePlugin.ts +++ b/packages/react-native/src/plugins/ReactNativeLifeCyclePlugin.ts @@ -43,13 +43,13 @@ export class ReactNativeLifeCyclePlugin implements IEventPlugin { } private setupWebListeners(): void { - const handleBeforeUnload = () => { + const handlePageHide = () => { if (this._client?.config.sessionsEnabled) { void this._client?.submitSessionEnd(); } void this._client?.suspend(); }; - globalThis.addEventListener("beforeunload", handleBeforeUnload); + globalThis.addEventListener("pagehide", handlePageHide); if (typeof document !== "undefined") { const handleVisibilityChange = () => { diff --git a/packages/react-native/test/plugins/ReactNativeLifeCyclePlugin.test.ts b/packages/react-native/test/plugins/ReactNativeLifeCyclePlugin.test.ts index b5c2be91..bc19b166 100644 --- a/packages/react-native/test/plugins/ReactNativeLifeCyclePlugin.test.ts +++ b/packages/react-native/test/plugins/ReactNativeLifeCyclePlugin.test.ts @@ -34,7 +34,7 @@ describe("ReactNativeLifeCyclePlugin", () => { log: client.config.services.log }); - expect(addEventListenerSpy).toHaveBeenCalledWith("beforeunload", expect.any(Function)); + expect(addEventListenerSpy).toHaveBeenCalledWith("pagehide", expect.any(Function)); addEventListenerSpy.mockRestore(); Object.defineProperty(Platform, "OS", { @@ -60,8 +60,8 @@ describe("ReactNativeLifeCyclePlugin", () => { log: client.config.services.log }); - const beforeUnloadCalls = addEventListenerSpy.mock.calls.filter(([event]) => event === "beforeunload"); - expect(beforeUnloadCalls).toHaveLength(1); + const pageHideCalls = addEventListenerSpy.mock.calls.filter(([event]) => event === "pagehide"); + expect(pageHideCalls).toHaveLength(1); addEventListenerSpy.mockRestore(); Object.defineProperty(Platform, "OS", { From eda30ab4016b130516557be3a70b084800d7c7e2 Mon Sep 17 00:00:00 2001 From: "Eric J. Smith" Date: Tue, 1 Dec 2026 19:12:09 -0600 Subject: [PATCH 2/7] Send session heartbeats and ends with keepalive A session end submitted on pagehide is a GET without a body, so it was cancelled with the page. --- .../core/src/submission/DefaultSubmissionClient.ts | 12 +++++++----- .../test/submission/DefaultSubmissionClient.test.ts | 9 +++++++++ 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/packages/core/src/submission/DefaultSubmissionClient.ts b/packages/core/src/submission/DefaultSubmissionClient.ts index 87d86a74..47f15849 100644 --- a/packages/core/src/submission/DefaultSubmissionClient.ts +++ b/packages/core/src/submission/DefaultSubmissionClient.ts @@ -83,7 +83,7 @@ export class DefaultSubmissionClient implements ISubmissionClient { // 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) { + if (keepAliveBytes !== undefined) { requestOptions.keepalive = true; this._keepAliveBytesInFlight += keepAliveBytes; } @@ -112,7 +112,7 @@ export class DefaultSubmissionClient implements ISubmissionClient { throw ex; } finally { clearTimeout(timeoutId); - this._keepAliveBytesInFlight -= keepAliveBytes; + this._keepAliveBytesInFlight -= keepAliveBytes ?? 0; } } @@ -130,8 +130,10 @@ export class DefaultSubmissionClient implements ISubmissionClient { } } - private getKeepAliveBytes(body: string | undefined): number { + /** Returns the body size to reserve from the keepalive budget, or undefined when the request can't use keepalive. */ + private getKeepAliveBytes(body: string | undefined): number | undefined { if (!body) { + // Requests without a body (session heartbeats and ends) don't count against the budget. return 0; } @@ -140,13 +142,13 @@ export class DefaultSubmissionClient implements ISubmissionClient { let bytes = maxBytes; if (maxBytes > this.KeepAliveBodyLimit) { if (typeof TextEncoder !== "function" || body.length > this.KeepAliveBodyLimit) { - return 0; + return undefined; } bytes = new TextEncoder().encode(body).length; } - return this._keepAliveBytesInFlight + bytes <= this.KeepAliveBodyLimit ? bytes : 0; + return this._keepAliveBytesInFlight + bytes <= this.KeepAliveBodyLimit ? bytes : undefined; } private isHeaders(headers: HeadersInit | undefined): headers is Record { diff --git a/packages/core/test/submission/DefaultSubmissionClient.test.ts b/packages/core/test/submission/DefaultSubmissionClient.test.ts index a339ccfe..17948dc6 100644 --- a/packages/core/test/submission/DefaultSubmissionClient.test.ts +++ b/packages/core/test/submission/DefaultSubmissionClient.test.ts @@ -131,6 +131,15 @@ describe("DefaultSubmissionClient", () => { expect(lastRequest().init.keepalive).toBe(true); }); + test("sends session heartbeats with keepalive so a session end on page hide is delivered", async () => { + respond(200); + const client = new DefaultSubmissionClient(config, fetchMock); + + await client.submitHeartbeat("session-id", true); + + expect(lastRequest().init.keepalive).toBe(true); + }); + test("sends large submissions without keepalive", async () => { const client = new DefaultSubmissionClient(config, fetchMock); From 275c6bcade1f134cd30aecc954423e0f1a90b4b8 Mon Sep 17 00:00:00 2001 From: "Eric J. Smith" Date: Tue, 1 Dec 2026 19:20:59 -0600 Subject: [PATCH 3/7] Test that flush waits for an in-flight submission --- .../test/ExceptionlessClientLifecycle.test.ts | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/packages/core/test/ExceptionlessClientLifecycle.test.ts b/packages/core/test/ExceptionlessClientLifecycle.test.ts index fdc8b9ba..fa769f9a 100644 --- a/packages/core/test/ExceptionlessClientLifecycle.test.ts +++ b/packages/core/test/ExceptionlessClientLifecycle.test.ts @@ -173,6 +173,31 @@ describe("ExceptionlessClient lifecycle", () => { vi.spyOn(client.config.services.queue, "process").mockReturnValue(new Promise(() => {})); expect(await client.flush(10)).toBe(false); }); + + test("flush waits for a submission that is already in flight", async () => { + const client = new ExceptionlessClient(); + client.config.apiKey = "UNIT_TEST_API_KEY"; + client.config.updateSettingsWhenIdleInterval = -1; + const submissionClient = new StubSubmissionClient(); + client.config.services.submissionClient = submissionClient; + let finishSubmission: () => void = () => {}; + vi.spyOn(submissionClient, "submitEvents").mockReturnValueOnce( + new Promise((resolve) => { + finishSubmission = () => resolve(new Response(202, "", NaN, NaN, undefined)); + }) + ); + await client.config.services.queue.enqueue({ + type: "log", + message: "in flight" + }); + + const backgroundRun = client.processQueue(); + expect(await client.flush(10)).toBe(false); + + finishSubmission(); + await backgroundRun; + expect(await client.flush(1000)).toBe(true); + }); }); describe("Server settings", () => { From ed4cdbfef0c6fe5b9b3f4c9f30239e35d9f9f9b3 Mon Sep 17 00:00:00 2001 From: "Eric J. Smith" Date: Tue, 1 Dec 2026 19:25:21 -0600 Subject: [PATCH 4/7] Keep local settings changed after server settings are applied Track which settings came from the server instead of rebuilding from a snapshot taken at the first apply, so removed server settings are cleared, overridden local values come back, and local changes made after startup survive a refresh. --- .../core/src/configuration/Configuration.ts | 54 ++++++++++++++----- .../test/ExceptionlessClientLifecycle.test.ts | 37 +++++++++++++ 2 files changed, 77 insertions(+), 14 deletions(-) diff --git a/packages/core/src/configuration/Configuration.ts b/packages/core/src/configuration/Configuration.ts index 00f8e51c..36a6845d 100644 --- a/packages/core/src/configuration/Configuration.ts +++ b/packages/core/src/configuration/Configuration.ts @@ -522,29 +522,55 @@ export class Configuration { } } - private originalSettings?: Record; + /** Local values of settings the server has overridden, restored when the server stops sending them. */ + private _overriddenLocalSettings: Record = {}; + /** The server settings that were applied last. */ + private _appliedServerSettings: Record = {}; public applyServerSettings(serverSettings: ServerSettings): void { - if (!this.originalSettings) { - this.originalSettings = JSON.parse(JSON.stringify(this.settings)) as Record; + this.services.log.trace(`Applying saved settings: v${serverSettings?.version}`); + + const received: Record = {}; + const value: unknown = serverSettings?.settings; + if (value && typeof value === "object") { + for (const [key, setting] of Object.entries(value)) { + if (typeof setting === "string") { + received[key] = setting; + } else { + this.services.log.warn(`Ignoring server setting "${key}": expected a string value`); + } + } } - this.services.log.trace(`Applying saved settings: v${serverSettings.version}`); - // Start from the original settings each time so settings the server no longer sends are removed. + // Settings still holding the value the server last sent are server-owned: drop them (restoring any local value they + // replaced) so settings the server no longer sends are removed. Anything else, including local changes made after + // startup, is kept. const settings: Record = { - ...this.originalSettings + ...this.settings }; - const received: unknown = serverSettings?.settings; - if (received && typeof received === "object") { - for (const [key, value] of Object.entries(received)) { - if (typeof value === "string") { - settings[key] = value; - } else { - this.services.log.warn(`Ignoring server setting "${key}": expected a string value`); - } + for (const [key, setting] of Object.entries(this._appliedServerSettings)) { + if (settings[key] !== setting) { + delete this._overriddenLocalSettings[key]; + continue; } + + if (key in this._overriddenLocalSettings) { + settings[key] = this._overriddenLocalSettings[key]; + delete this._overriddenLocalSettings[key]; + } else { + delete settings[key]; + } + } + + for (const [key, setting] of Object.entries(received)) { + if (key in settings && settings[key] !== setting) { + this._overriddenLocalSettings[key] = settings[key]; + } + + settings[key] = setting; } + this._appliedServerSettings = received; this.settings = settings; this.settingsVersion = typeof serverSettings?.version === "number" ? serverSettings.version : 0; this.notifySubscribers(); diff --git a/packages/core/test/ExceptionlessClientLifecycle.test.ts b/packages/core/test/ExceptionlessClientLifecycle.test.ts index fa769f9a..2c893d6d 100644 --- a/packages/core/test/ExceptionlessClientLifecycle.test.ts +++ b/packages/core/test/ExceptionlessClientLifecycle.test.ts @@ -229,6 +229,43 @@ describe("Server settings", () => { expect(config.settingsVersion).toBe(2); }); + test("keeps local settings changed after server settings were applied", () => { + const config = new Configuration(); + config.applyServerSettings( + new ServerSettings( + { + "@@error:TypeError": "false" + }, + 1 + ) + ); + + config.settings["@@log:*"] = "off"; + config.applyServerSettings(new ServerSettings({}, 2)); + + expect(config.settings).toEqual({ + "@@log:*": "off" + }); + }); + + test("restores a local setting when the server stops overriding it", () => { + const config = new Configuration(); + config.settings["@@log:*"] = "info"; + + config.applyServerSettings( + new ServerSettings( + { + "@@log:*": "off" + }, + 1 + ) + ); + expect(config.settings["@@log:*"]).toBe("off"); + + config.applyServerSettings(new ServerSettings({}, 2)); + expect(config.settings["@@log:*"]).toBe("info"); + }); + test("ignores server settings that are not strings", () => { const config = new Configuration(); From 4e9b4905c0a46ff21ff86f5a6d62714a3bb27f10 Mon Sep 17 00:00:00 2001 From: "Eric J. Smith" Date: Tue, 1 Dec 2026 19:28:46 -0600 Subject: [PATCH 5/7] Restore a local setting that matched the server's override A local value equal to the incoming server value wasn't saved, so it was deleted when the server later stopped sending that key. --- .../core/src/configuration/Configuration.ts | 3 ++- .../test/ExceptionlessClientLifecycle.test.ts | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/packages/core/src/configuration/Configuration.ts b/packages/core/src/configuration/Configuration.ts index 36a6845d..2b677155 100644 --- a/packages/core/src/configuration/Configuration.ts +++ b/packages/core/src/configuration/Configuration.ts @@ -563,7 +563,8 @@ export class Configuration { } for (const [key, setting] of Object.entries(received)) { - if (key in settings && settings[key] !== setting) { + // Server-owned keys were removed above, so any remaining value is local, even if it equals the server value. + if (key in settings) { this._overriddenLocalSettings[key] = settings[key]; } diff --git a/packages/core/test/ExceptionlessClientLifecycle.test.ts b/packages/core/test/ExceptionlessClientLifecycle.test.ts index 2c893d6d..99b6e0ec 100644 --- a/packages/core/test/ExceptionlessClientLifecycle.test.ts +++ b/packages/core/test/ExceptionlessClientLifecycle.test.ts @@ -266,6 +266,23 @@ describe("Server settings", () => { expect(config.settings["@@log:*"]).toBe("info"); }); + test("restores a local setting that matched the server override", () => { + const config = new Configuration(); + config.settings["@@log:*"] = "off"; + + config.applyServerSettings( + new ServerSettings( + { + "@@log:*": "off" + }, + 1 + ) + ); + config.applyServerSettings(new ServerSettings({}, 2)); + + expect(config.settings["@@log:*"]).toBe("off"); + }); + test("ignores server settings that are not strings", () => { const config = new Configuration(); From e66c52d574a2eb39b7c27504186a459dbfee6b95 Mon Sep 17 00:00:00 2001 From: "Eric J. Smith" Date: Tue, 1 Dec 2026 21:23:21 -0600 Subject: [PATCH 6/7] Remove flush() in favor of processQueue(); stop heartbeats inside startHeartbeats --- .../skills/exceptionless-javascript/SKILL.md | 2 +- .../references/troubleshooting.md | 3 +-- packages/core/src/ExceptionlessClient.ts | 19 -------------- .../src/plugins/default/HeartbeatPlugin.ts | 16 +++++++----- packages/core/src/queue/DefaultEventQueue.ts | 2 +- .../test/ExceptionlessClientLifecycle.test.ts | 26 ++++++++----------- 6 files changed, 24 insertions(+), 44 deletions(-) diff --git a/.agents/skills/exceptionless-javascript/SKILL.md b/.agents/skills/exceptionless-javascript/SKILL.md index 23099f92..a739baa0 100644 --- a/.agents/skills/exceptionless-javascript/SKILL.md +++ b/.agents/skills/exceptionless-javascript/SKILL.md @@ -38,7 +38,7 @@ Read only the references needed for the request. Start with the runtime for setu - `markAsCritical()` marks the event critical; `markAsCritical(false)` leaves tags unchanged. - `config.serverUrl` also sets `configServerUrl` and `heartbeatServerUrl`; assign custom endpoint overrides after setting `serverUrl`. - Use lowercase log levels in new snippets: `"trace"`, `"debug"`, `"info"`, `"warn"`, `"error"`, `"fatal"`, `"off"`. -- For short-lived Node/serverless work, call `await Exceptionless.flush()` (waits up to 10 seconds by default, returns `false` on timeout) or `await Exceptionless.processQueue()` after critical submissions. +- For short-lived Node/serverless work, call `await Exceptionless.processQueue()` after critical submissions. If a send is already in progress, it waits for that send to finish. ## Integrator Guidance diff --git a/.agents/skills/exceptionless-javascript/references/troubleshooting.md b/.agents/skills/exceptionless-javascript/references/troubleshooting.md index bf21b7f8..4fe2c2d2 100644 --- a/.agents/skills/exceptionless-javascript/references/troubleshooting.md +++ b/.agents/skills/exceptionless-javascript/references/troubleshooting.md @@ -25,8 +25,7 @@ Events are queued and sent in the background. If the app exits or navigates imme ```js import { Exceptionless } from "@exceptionless/browser"; -// Waits at most 10 seconds by default; returns false if the queue didn't finish in time. -await Exceptionless.flush(); +await Exceptionless.processQueue(); ``` This matters most for Node scripts, CLIs, serverless handlers, route handlers, tests, and hard redirects. diff --git a/packages/core/src/ExceptionlessClient.ts b/packages/core/src/ExceptionlessClient.ts index 1cb021ec..93c3cea5 100644 --- a/packages/core/src/ExceptionlessClient.ts +++ b/packages/core/src/ExceptionlessClient.ts @@ -92,25 +92,6 @@ export class ExceptionlessClient { await this.config.services.queue.process(); } - /** - * Sends queued events, waiting at most `timeoutMs`. Use it before a short-lived process, - * serverless handler, or test exits. - * @returns true when the queue finished processing within the timeout. - */ - public async flush(timeoutMs: number = 10000): Promise { - let timeoutId: ReturnType | undefined; - const timeout = new Promise((resolve) => { - timeoutId = setTimeout(() => resolve(false), timeoutMs); - allowProcessToExitWithoutWaitingForTimerOrInterval(timeoutId); - }); - - try { - return await Promise.race([this.processQueue().then(() => true), timeout]); - } finally { - clearTimeout(timeoutId); - } - } - private updateSettingsTimer(startingUp: boolean = false) { this.suspendSettingsTimer(); diff --git a/packages/core/src/plugins/default/HeartbeatPlugin.ts b/packages/core/src/plugins/default/HeartbeatPlugin.ts index f26af8a9..ff533585 100644 --- a/packages/core/src/plugins/default/HeartbeatPlugin.ts +++ b/packages/core/src/plugins/default/HeartbeatPlugin.ts @@ -17,8 +17,7 @@ export class HeartbeatPlugin implements IEventPlugin { } public startup(context: PluginContext): Promise { - clearInterval(this._intervalId); - this._intervalId = undefined; + this.stopHeartbeats(); // Resume heartbeats for the current session (for example, when a hidden tab becomes visible again). const { client } = context; @@ -30,8 +29,7 @@ export class HeartbeatPlugin implements IEventPlugin { } public suspend(): Promise { - clearInterval(this._intervalId); - this._intervalId = undefined; + this.stopHeartbeats(); return Promise.resolve(); } @@ -40,8 +38,7 @@ export class HeartbeatPlugin implements IEventPlugin { return Promise.resolve(); } - clearInterval(this._intervalId); - this._intervalId = undefined; + this.stopHeartbeats(); const { config } = context.client; if (!config.currentSessionIdentifier) { @@ -61,8 +58,15 @@ export class HeartbeatPlugin implements IEventPlugin { } private startHeartbeats(client: ExceptionlessClient): void { + this.stopHeartbeats(); + // Heartbeats always go to the session that is current when they fire. this._intervalId = setInterval(() => void client.submitSessionHeartbeat(), this._interval); allowProcessToExitWithoutWaitingForTimerOrInterval(this._intervalId); } + + private stopHeartbeats(): void { + clearInterval(this._intervalId); + this._intervalId = undefined; + } } diff --git a/packages/core/src/queue/DefaultEventQueue.ts b/packages/core/src/queue/DefaultEventQueue.ts index 8074b5b1..3ad81168 100644 --- a/packages/core/src/queue/DefaultEventQueue.ts +++ b/packages/core/src/queue/DefaultEventQueue.ts @@ -96,7 +96,7 @@ export class DefaultEventQueue implements IEventQueue { const { log } = this.config.services; if (this._processing) { - // Callers such as flush() need to wait for the run that is already sending events. An onEventsPosted + // Callers such as processQueue() need to wait for the run that is already sending events. An onEventsPosted // handler calling back into the queue is part of that run, so it must not wait for it. return this._notifyingHandlers ? Promise.resolve() : this._processing; } diff --git a/packages/core/test/ExceptionlessClientLifecycle.test.ts b/packages/core/test/ExceptionlessClientLifecycle.test.ts index 99b6e0ec..eec9bc7c 100644 --- a/packages/core/test/ExceptionlessClientLifecycle.test.ts +++ b/packages/core/test/ExceptionlessClientLifecycle.test.ts @@ -164,24 +164,14 @@ describe("ExceptionlessClient lifecycle", () => { expect(sessions[0].reference_id).not.toBe(sessions[1].reference_id); }); - test("flush reports whether the queue finished in time", async () => { - const { client } = createClient(); - client.config.apiKey = "UNIT_TEST_API_KEY"; - - expect(await client.flush(1000)).toBe(true); - - vi.spyOn(client.config.services.queue, "process").mockReturnValue(new Promise(() => {})); - expect(await client.flush(10)).toBe(false); - }); - - test("flush waits for a submission that is already in flight", async () => { + test("processQueue waits for a submission that is already in flight", async () => { const client = new ExceptionlessClient(); client.config.apiKey = "UNIT_TEST_API_KEY"; client.config.updateSettingsWhenIdleInterval = -1; const submissionClient = new StubSubmissionClient(); client.config.services.submissionClient = submissionClient; let finishSubmission: () => void = () => {}; - vi.spyOn(submissionClient, "submitEvents").mockReturnValueOnce( + const submitEvents = vi.spyOn(submissionClient, "submitEvents").mockReturnValueOnce( new Promise((resolve) => { finishSubmission = () => resolve(new Response(202, "", NaN, NaN, undefined)); }) @@ -192,11 +182,17 @@ describe("ExceptionlessClient lifecycle", () => { }); const backgroundRun = client.processQueue(); - expect(await client.flush(10)).toBe(false); + let finished = false; + const secondRun = client.processQueue().then(() => { + finished = true; + }); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(finished).toBe(false); finishSubmission(); - await backgroundRun; - expect(await client.flush(1000)).toBe(true); + await Promise.all([backgroundRun, secondRun]); + expect(finished).toBe(true); + expect(submitEvents).toHaveBeenCalledTimes(1); }); }); From 23abcbd1f6ba8cbcd1eb00b40b404e5bec7e0edd Mon Sep 17 00:00:00 2001 From: Blake Niemyjski Date: Thu, 3 Dec 2026 06:40:08 -0600 Subject: [PATCH 7/7] Coalesce overlapping automatic session starts --- .../references/sessions.md | 2 +- packages/core/src/ExceptionlessClient.ts | 12 ++++- .../test/ExceptionlessClientLifecycle.test.ts | 48 +++++++++++++++++++ 3 files changed, 59 insertions(+), 3 deletions(-) diff --git a/.agents/skills/exceptionless-javascript/references/sessions.md b/.agents/skills/exceptionless-javascript/references/sessions.md index 5a5027ca..759fe06b 100644 --- a/.agents/skills/exceptionless-javascript/references/sessions.md +++ b/.agents/skills/exceptionless-javascript/references/sessions.md @@ -28,7 +28,7 @@ await Exceptionless.startup((config) => { Session lifetime in the browser and React Native: -- `startup()` sends a session start once. Resuming after a hidden tab continues the same session (and its heartbeats) unless the client was suspended for more than 5 minutes, after which the server has closed the session and a new one starts. +- `startup()` sends a session start once. Resuming after a hidden tab continues the same session (and its heartbeats) unless the client was suspended for more than 5 minutes, after which the server has closed the session and a new one starts. Overlapping startups share the automatic session start. If a plugin cancels it, a later startup can retry. - The browser ends the session on `pagehide` and starts a new one if the page is restored from the back/forward cache. React Native ends it when the app goes to the background and starts a new one when it becomes active. Disable heartbeat traffic while still using session events: diff --git a/packages/core/src/ExceptionlessClient.ts b/packages/core/src/ExceptionlessClient.ts index 93c3cea5..3d105abb 100644 --- a/packages/core/src/ExceptionlessClient.ts +++ b/packages/core/src/ExceptionlessClient.ts @@ -13,6 +13,7 @@ export class ExceptionlessClient { private _intervalId: ReturnType | undefined; private _timeoutId: ReturnType | undefined; private _sessionActive = false; + private _startingSession: Promise | undefined; private _suspendedAt: number | undefined; /** The server closes sessions that have had no activity for this long. */ private readonly SESSION_INACTIVE_PERIOD = 5 * 60 * 1000; @@ -66,8 +67,15 @@ export class ExceptionlessClient { const suspendedAt = this._suspendedAt; this._suspendedAt = undefined; const sessionExpired = suspendedAt !== undefined && Date.now() - suspendedAt > this.SESSION_INACTIVE_PERIOD; - if (this.config.sessionsEnabled && (!this._sessionActive || sessionExpired)) { - await this.submitSessionStart(); + if (sessionExpired) { + this._sessionActive = false; + } + + if (this.config.sessionsEnabled && !this._sessionActive) { + this._startingSession ??= this.submitSessionStart().finally(() => { + this._startingSession = undefined; + }); + await this._startingSession; } } diff --git a/packages/core/test/ExceptionlessClientLifecycle.test.ts b/packages/core/test/ExceptionlessClientLifecycle.test.ts index eec9bc7c..bb3a592f 100644 --- a/packages/core/test/ExceptionlessClientLifecycle.test.ts +++ b/packages/core/test/ExceptionlessClientLifecycle.test.ts @@ -114,6 +114,54 @@ describe("ExceptionlessClient lifecycle", () => { expect(client.config.apiKey).toBe("UNIT_TEST_API_KEY"); }); + test("concurrent startups share the session start", async () => { + // Arrange + const { client, enqueued } = createClient(); + track(client); + client.config.apiKey = "UNIT_TEST_API_KEY"; + client.config.useSessions(false, undefined, true); + + // Act + await Promise.all([client.startup(), client.startup()]); + + // Assert + expect(enqueued.filter((event) => event.type === "session")).toHaveLength(1); + }); + + test("a cancelled start after session expiry can be retried", async () => { + // Arrange + vi.useFakeTimers({ + toFake: ["Date"] + }); + const { client, enqueued } = createClient(); + track(client); + client.config.apiKey = "UNIT_TEST_API_KEY"; + client.config.useSessions(false, undefined, true); + await client.startup(); + await client.suspend(); + vi.setSystemTime(Date.now() + 6 * 60 * 1000); + let attempts = 0; + client.config.addPlugin({ + name: "CancelFirstStart", + priority: 1, + run(context) { + if (context.event.type === "session") { + context.cancelled = ++attempts === 1; + } + return Promise.resolve(); + } + }); + + // Act + await Promise.all([client.startup(), client.startup()]); + expect(attempts).toBe(1); + await client.startup(); + + // Assert + expect(attempts).toBe(2); + expect(enqueued.filter((event) => event.type === "session")).toHaveLength(2); + }); + test("resuming after a short suspension continues the current session", async () => { const { client, enqueued } = createClient(); track(client);