Skip to content

Commit 76dde1a

Browse files
committed
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.
1 parent 6d955dc commit 76dde1a

16 files changed

Lines changed: 468 additions & 33 deletions

‎.agents/skills/exceptionless-javascript/SKILL.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,15 @@ Read only the references needed for the request. Start with the runtime for setu
3030

3131
## Rules
3232

33-
- Use `Exceptionless.startup(...)` once during app startup. `startup()` with no args is used later by lifecycle plugins to resume timers/queue processing.
33+
- 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.
3434
- Use the singleton from the platform package when automatic capture matters. Create `ExceptionlessClient` manually only for custom pipelines or tests.
3535
- For React Native or Expo apps, use `@exceptionless/react-native`; do not substitute `@exceptionless/browser` or `@exceptionless/react`.
3636
- 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.
3737
- `submitException` and `createException` take an `Error`. For unknown caught values, use exported `toError(value)` when available.
3838
- `markAsCritical()` marks the event critical; `markAsCritical(false)` leaves tags unchanged.
3939
- `config.serverUrl` also sets `configServerUrl` and `heartbeatServerUrl`; assign custom endpoint overrides after setting `serverUrl`.
4040
- Use lowercase log levels in new snippets: `"trace"`, `"debug"`, `"info"`, `"warn"`, `"error"`, `"fatal"`, `"off"`.
41-
- For short-lived Node/serverless work, call `await Exceptionless.processQueue()` after critical submissions.
41+
- 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.
4242

4343
## Integrator Guidance
4444

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,11 @@ await Exceptionless.startup((config) => {
2626
- `heartbeatInterval` defaults to 60000ms. Values below 30000ms are reset to 60000ms.
2727
- `useSessionIdManagement` adds `SessionIdManagementPlugin`, which creates a session id and links later events to it.
2828

29+
Session lifetime in the browser and React Native:
30+
31+
- `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.
32+
- 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.
33+
2934
Disable heartbeat traffic while still using session events:
3035

3136
```js

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@ Events are queued and sent in the background. If the app exits or navigates imme
2525
```js
2626
import { Exceptionless } from "@exceptionless/browser";
2727

28-
await Exceptionless.processQueue();
28+
// Waits at most 10 seconds by default; returns false if the queue didn't finish in time.
29+
await Exceptionless.flush();
2930
```
3031

3132
This matters most for Node scripts, CLIs, serverless handlers, route handlers, tests, and hard redirects.

‎packages/browser/src/BrowserExceptionlessClient.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { BrowserRequestInfoPlugin } from "./plugins/BrowserRequestInfoPlugin.js"
1010
export class BrowserExceptionlessClient extends ExceptionlessClient {
1111
public async startup(configurationOrApiKey?: ((config: Configuration) => void) | string): Promise<void> {
1212
const config = this.config;
13-
if (configurationOrApiKey && !this._initialized) {
13+
if (!this._initialized) {
1414
config.useLocalStorage();
1515

1616
config.addPlugin(new BrowserGlobalHandlerPlugin());

‎packages/browser/src/plugins/BrowserLifeCyclePlugin.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,22 @@ export class BrowserLifeCyclePlugin implements IEventPlugin {
1313

1414
this._client = context.client;
1515

16-
globalThis.addEventListener("beforeunload", () => {
16+
// pagehide fires reliably on mobile and doesn't stop the page from entering the back/forward cache, unlike beforeunload.
17+
globalThis.addEventListener("pagehide", () => {
1718
if (this._client?.config.sessionsEnabled) {
1819
void this._client?.submitSessionEnd();
1920
}
2021

2122
void this._client?.suspend();
2223
});
2324

25+
// A page restored from the back/forward cache starts a new session.
26+
globalThis.addEventListener("pageshow", (event: PageTransitionEvent) => {
27+
if (event.persisted) {
28+
void this._client?.startup();
29+
}
30+
});
31+
2432
document.addEventListener("visibilitychange", () => {
2533
if (document.visibilityState === "visible") {
2634
void this._client?.startup();

‎packages/browser/test/BrowserExceptionlessClient.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,22 @@ describe("BrowserExceptionlessClient", () => {
2525
await client.suspend();
2626
}
2727
});
28+
29+
test("should configure browser plugins when startup is called without arguments", async () => {
30+
const client = new BrowserExceptionlessClient();
31+
client.config.apiKey = "UNIT_TEST_API_KEY";
32+
client.config.updateSettingsWhenIdleInterval = -1;
33+
34+
await client.startup();
35+
36+
try {
37+
const pluginNames = client.config.plugins.map((plugin) => plugin.name);
38+
39+
expect(pluginNames).toContain("BrowserGlobalHandlerPlugin");
40+
expect(pluginNames).toContain("BrowserErrorPlugin");
41+
expect(pluginNames).not.toContain("SimpleErrorPlugin");
42+
} finally {
43+
await client.suspend();
44+
}
45+
});
2846
});
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import { afterEach, describe, expect, test, vi } from "vitest";
2+
3+
import { ExceptionlessClient } from "@exceptionless/core";
4+
5+
import { BrowserLifeCyclePlugin } from "../../src/plugins/BrowserLifeCyclePlugin.js";
6+
7+
describe("BrowserLifeCyclePlugin", () => {
8+
afterEach(() => {
9+
vi.restoreAllMocks();
10+
});
11+
12+
async function startPlugin() {
13+
const listeners = new Map<string, EventListener>();
14+
vi.spyOn(globalThis, "addEventListener").mockImplementation((type: string, listener: EventListenerOrEventListenerObject) => {
15+
listeners.set(type, listener as EventListener);
16+
});
17+
18+
const client = new ExceptionlessClient();
19+
client.config.sessionsEnabled = true;
20+
const suspend = vi.spyOn(client, "suspend").mockResolvedValue();
21+
const startup = vi.spyOn(client, "startup").mockResolvedValue();
22+
const submitSessionEnd = vi.spyOn(client, "submitSessionEnd").mockResolvedValue();
23+
24+
await new BrowserLifeCyclePlugin().startup({
25+
client,
26+
log: client.config.services.log
27+
});
28+
29+
return {
30+
listeners,
31+
suspend,
32+
startup,
33+
submitSessionEnd
34+
};
35+
}
36+
37+
test("ends the session and flushes on pagehide instead of beforeunload", async () => {
38+
const { listeners, suspend, submitSessionEnd } = await startPlugin();
39+
40+
expect(listeners.has("beforeunload")).toBe(false);
41+
listeners.get("pagehide")?.(new Event("pagehide"));
42+
43+
expect(submitSessionEnd).toHaveBeenCalledTimes(1);
44+
expect(suspend).toHaveBeenCalledTimes(1);
45+
});
46+
47+
test("resumes when the page is restored from the back/forward cache", async () => {
48+
const { listeners, startup } = await startPlugin();
49+
const pageshow = listeners.get("pageshow");
50+
51+
pageshow?.(
52+
Object.assign(new Event("pageshow"), {
53+
persisted: false
54+
})
55+
);
56+
expect(startup).not.toHaveBeenCalled();
57+
58+
pageshow?.(
59+
Object.assign(new Event("pageshow"), {
60+
persisted: true
61+
})
62+
);
63+
expect(startup).toHaveBeenCalledTimes(1);
64+
});
65+
});

‎packages/core/src/ExceptionlessClient.ts‎

Lines changed: 58 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,31 +12,46 @@ import { allowProcessToExitWithoutWaitingForTimerOrInterval } from "./Utils.js";
1212
export class ExceptionlessClient {
1313
private _intervalId: ReturnType<typeof setInterval> | undefined;
1414
private _timeoutId: ReturnType<typeof setTimeout> | undefined;
15+
private _sessionActive = false;
16+
private _suspendedAt: number | undefined;
17+
/** The server closes sessions that have had no activity for this long. */
18+
private readonly SESSION_INACTIVE_PERIOD = 5 * 60 * 1000;
1519
protected _initialized = false;
1620

1721
public constructor(public config: Configuration = new Configuration()) {}
1822

19-
/** Resume background submission, resume any timers. */
23+
/**
24+
* Starts the client, or resumes background submission and timers after `suspend()`.
25+
* The first call that leaves the client with a valid API key configures it; later calls only resume it.
26+
*/
2027
public async startup(configurationOrApiKey?: ((config: Configuration) => void) | string): Promise<void> {
21-
if (configurationOrApiKey && !this._initialized) {
22-
this._initialized = true;
23-
28+
const startingUp = !this._initialized;
29+
if (startingUp) {
2430
if (typeof configurationOrApiKey === "string") {
2531
this.config.apiKey = configurationOrApiKey;
26-
} else {
32+
} else if (configurationOrApiKey) {
2733
configurationOrApiKey(this.config);
2834
}
2935

36+
if (!this.config.isValid) {
37+
// Stay uninitialized so a later startup() call can still configure the client.
38+
this.config.services.log.warn("Exceptionless is not configured and will not process events.");
39+
return;
40+
}
41+
42+
this._initialized = true;
3043
this.config.services.queue.onEventsPosted(() => Promise.resolve(this.updateSettingsTimer()));
3144
await SettingsManager.applySavedServerSettings(this.config);
45+
} else if (configurationOrApiKey) {
46+
this.config.services.log.warn("Exceptionless has already been started; the configuration passed to startup() was ignored.");
3247
}
3348

3449
if (!this.config.isValid) {
3550
this.config.services.log.warn("Exceptionless is not configured and will not process events.");
3651
return;
3752
}
3853

39-
this.updateSettingsTimer(!!configurationOrApiKey);
54+
this.updateSettingsTimer(startingUp);
4055
await EventPluginManager.startup(new PluginContext(this));
4156

4257
const { queue } = this.config.services;
@@ -46,13 +61,19 @@ export class ExceptionlessClient {
4661
await queue.process();
4762
}
4863

49-
if (this.config.sessionsEnabled) {
64+
// Resuming (for example, when a hidden tab becomes visible) continues the current session unless the
65+
// server will already have closed it for inactivity.
66+
const suspendedAt = this._suspendedAt;
67+
this._suspendedAt = undefined;
68+
const sessionExpired = suspendedAt !== undefined && Date.now() - suspendedAt > this.SESSION_INACTIVE_PERIOD;
69+
if (this.config.sessionsEnabled && (!this._sessionActive || sessionExpired)) {
5070
await this.submitSessionStart();
5171
}
5272
}
5373

5474
/** Submit events, pause any timers and go into low power mode. */
5575
public async suspend(): Promise<void> {
76+
this._suspendedAt ??= Date.now();
5677
await EventPluginManager.suspend(new PluginContext(this));
5778
const { queue } = this.config.services;
5879
await queue.suspend();
@@ -71,6 +92,25 @@ export class ExceptionlessClient {
7192
await this.config.services.queue.process();
7293
}
7394

95+
/**
96+
* Sends queued events, waiting at most `timeoutMs`. Use it before a short-lived process,
97+
* serverless handler, or test exits.
98+
* @returns true when the queue finished processing within the timeout.
99+
*/
100+
public async flush(timeoutMs: number = 10000): Promise<boolean> {
101+
let timeoutId: ReturnType<typeof setTimeout> | undefined;
102+
const timeout = new Promise<boolean>((resolve) => {
103+
timeoutId = setTimeout(() => resolve(false), timeoutMs);
104+
allowProcessToExitWithoutWaitingForTimerOrInterval(timeoutId);
105+
});
106+
107+
try {
108+
return await Promise.race([this.processQueue().then(() => true), timeout]);
109+
} finally {
110+
clearTimeout(timeoutId);
111+
}
112+
}
113+
74114
private updateSettingsTimer(startingUp: boolean = false) {
75115
this.suspendSettingsTimer();
76116

@@ -172,13 +212,22 @@ export class ExceptionlessClient {
172212
return this.createEvent().setType("session");
173213
}
174214

175-
public submitSessionStart(): Promise<EventPluginContext> {
176-
return this.createSessionStart().submit();
215+
public async submitSessionStart(): Promise<EventPluginContext> {
216+
const context = await this.createSessionStart().submit();
217+
if (!context.cancelled) {
218+
this._sessionActive = true;
219+
}
220+
221+
return context;
177222
}
178223

179224
public async submitSessionEnd(sessionIdOrUserId?: string): Promise<void> {
180225
const { currentSessionIdentifier, enabled, isValid, services } = this.config;
181226
const sessionId = sessionIdOrUserId || currentSessionIdentifier;
227+
if (!sessionIdOrUserId || sessionIdOrUserId === currentSessionIdentifier) {
228+
this._sessionActive = false;
229+
}
230+
182231
if (sessionId && enabled && isValid) {
183232
services.log.info(`Submitting session end: ${sessionId}`);
184233
await services.submissionClient.submitHeartbeat(sessionId, true);

‎packages/core/src/configuration/Configuration.ts‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -347,7 +347,8 @@ export class Configuration {
347347
* The list of plugins that will be used in this configuration.
348348
*/
349349
public get plugins(): IEventPlugin[] {
350-
return this._plugins.sort((p1: IEventPlugin, p2: IEventPlugin) => {
350+
// Sort a copy: callers iterate this list while plugins may add or remove plugins.
351+
return [...this._plugins].sort((p1: IEventPlugin, p2: IEventPlugin) => {
351352
if (p1 == null && p2 == null) {
352353
return 0;
353354
}
@@ -529,8 +530,23 @@ export class Configuration {
529530
}
530531

531532
this.services.log.trace(`Applying saved settings: v${serverSettings.version}`);
532-
this.settings = Object.assign(this.originalSettings, serverSettings.settings);
533-
this.settingsVersion = serverSettings.version;
533+
// Start from the original settings each time so settings the server no longer sends are removed.
534+
const settings: Record<string, string> = {
535+
...this.originalSettings
536+
};
537+
const received: unknown = serverSettings?.settings;
538+
if (received && typeof received === "object") {
539+
for (const [key, value] of Object.entries(received)) {
540+
if (typeof value === "string") {
541+
settings[key] = value;
542+
} else {
543+
this.services.log.warn(`Ignoring server setting "${key}": expected a string value`);
544+
}
545+
}
546+
}
547+
548+
this.settings = settings;
549+
this.settingsVersion = typeof serverSettings?.version === "number" ? serverSettings.version : 0;
534550
this.notifySubscribers();
535551
}
536552

‎packages/core/src/configuration/SettingsManager.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ export class ServerSettings {
99

1010
export class SettingsManager {
1111
private static readonly SettingsKey: string = "settings";
12-
private static _isUpdatingSettings = false;
12+
private static readonly _updatingConfigurations = new WeakSet<Configuration>();
1313

1414
public static async applySavedServerSettings(config: Configuration): Promise<void> {
1515
if (!config?.isValid) {
@@ -23,11 +23,11 @@ export class SettingsManager {
2323
}
2424

2525
public static async updateSettings(config: Configuration): Promise<void> {
26-
if (!config?.enabled || this._isUpdatingSettings) {
26+
if (!config?.enabled || this._updatingConfigurations.has(config)) {
2727
return;
2828
}
2929

30-
this._isUpdatingSettings = true;
30+
this._updatingConfigurations.add(config);
3131
const { log, storage, submissionClient } = config.services;
3232

3333
try {
@@ -58,7 +58,7 @@ export class SettingsManager {
5858
} catch (ex) {
5959
log.error(`Error updating settings: ${ex instanceof Error ? ex.message : ex + ""}`);
6060
} finally {
61-
this._isUpdatingSettings = false;
61+
this._updatingConfigurations.delete(config);
6262
}
6363
}
6464

0 commit comments

Comments
 (0)