diff --git a/.agents/skills/exceptionless-javascript/SKILL.md b/.agents/skills/exceptionless-javascript/SKILL.md index 99e273e0..a739baa0 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.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/sessions.md b/.agents/skills/exceptionless-javascript/references/sessions.md index e01a06e0..759fe06b 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. 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: ```js 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..3d105abb 100644 --- a/packages/core/src/ExceptionlessClient.ts +++ b/packages/core/src/ExceptionlessClient.ts @@ -12,23 +12,39 @@ import { allowProcessToExitWithoutWaitingForTimerOrInterval } from "./Utils.js"; 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; 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 +52,7 @@ export class ExceptionlessClient { return; } - this.updateSettingsTimer(!!configurationOrApiKey); + this.updateSettingsTimer(startingUp); await EventPluginManager.startup(new PluginContext(this)); const { queue } = this.config.services; @@ -46,13 +62,26 @@ export class ExceptionlessClient { await queue.process(); } - if (this.config.sessionsEnabled) { - await this.submitSessionStart(); + // 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 (sessionExpired) { + this._sessionActive = false; + } + + if (this.config.sessionsEnabled && !this._sessionActive) { + this._startingSession ??= this.submitSessionStart().finally(() => { + this._startingSession = undefined; + }); + await this._startingSession; } } /** 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(); @@ -172,13 +201,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..2b677155 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; } @@ -521,16 +522,58 @@ 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`); + } + } + } + + // 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.settings + }; + 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)) { + // 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]; + } + + settings[key] = setting; } - this.services.log.trace(`Applying saved settings: v${serverSettings.version}`); - this.settings = Object.assign(this.originalSettings, serverSettings.settings); - this.settingsVersion = serverSettings.version; + this._appliedServerSettings = received; + 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..ff533585 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,16 +16,20 @@ export class HeartbeatPlugin implements IEventPlugin { this._interval = heartbeatInterval >= 30000 ? heartbeatInterval : 60000; } - public startup(): Promise { - clearInterval(this._intervalId); - this._intervalId = undefined; - // TODO: Do we want to send a heartbeat for the last user? + public startup(context: PluginContext): Promise { + this.stopHeartbeats(); + + // 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(); } public suspend(): Promise { - clearInterval(this._intervalId); - this._intervalId = undefined; + this.stopHeartbeats(); return Promise.resolve(); } @@ -32,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) { @@ -46,11 +51,22 @@ 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 { + 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/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/ExceptionlessClientLifecycle.test.ts b/packages/core/test/ExceptionlessClientLifecycle.test.ts new file mode 100644 index 00000000..bb3a592f --- /dev/null +++ b/packages/core/test/ExceptionlessClientLifecycle.test.ts @@ -0,0 +1,384 @@ +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("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); + + 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("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 = () => {}; + const submitEvents = 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(); + let finished = false; + const secondRun = client.processQueue().then(() => { + finished = true; + }); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(finished).toBe(false); + + finishSubmission(); + await Promise.all([backgroundRun, secondRun]); + expect(finished).toBe(true); + expect(submitEvents).toHaveBeenCalledTimes(1); + }); +}); + +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("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("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(); + + 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/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); 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", {