Skip to content

Fixes #85 Improvements to session management (Breaking Change) #124

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Feb 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions example/browser/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ await Exceptionless.startup((c) => {
c.updateSettingsWhenIdleInterval = 15000;
c.usePersistedQueueStorage = true;
c.setUserIdentity("12345678", "Blake");
c.useSessions();

// set some default data
c.defaultData["SampleUser"] = {
Expand Down
4 changes: 2 additions & 2 deletions packages/angularjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@
"./package.json": "./package.json"
},
"scripts": {
"build": "tsc -p tsconfig.json && esbuild src/index.ts --bundle --sourcemap --target=es2015 --format=esm --outfile=dist/index.bundle.js && esbuild src/index.ts --bundle --minify --sourcemap --target=es2015 --format=esm --outfile=dist/index.bundle.min.js",
"watch": "tsc -p ../core/tsconfig.json -w --preserveWatchOutput & tsc -p tsconfig.json -w --preserveWatchOutput & esbuild src/index.ts --bundle --sourcemap --target=es2015 --format=esm --watch --outfile=dist/index.bundle.js"
"build": "tsc -p tsconfig.json && esbuild src/index.ts --bundle --sourcemap --target=es2017 --format=esm --outfile=dist/index.bundle.js && esbuild src/index.ts --bundle --minify --sourcemap --target=es2017 --format=esm --outfile=dist/index.bundle.min.js",
"watch": "tsc -p ../core/tsconfig.json -w --preserveWatchOutput & tsc -p tsconfig.json -w --preserveWatchOutput & esbuild src/index.ts --bundle --sourcemap --target=es2017 --format=esm --watch --outfile=dist/index.bundle.js"
},
"sideEffects": false,
"publishConfig": {
Expand Down
2 changes: 1 addition & 1 deletion packages/browser/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
"testEnvironment": "jsdom"
},
"scripts": {
"build": "tsc -p tsconfig.json && esbuild src/index.ts --bundle --sourcemap --target=es2017 --format=esm --outfile=dist/index.bundle.js && esbuild src/index.ts --bundle --minify --sourcemap --target=es2019 --format=esm --outfile=dist/index.bundle.min.js",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why did you downgrade this one from es2019 to es2017?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because all the other ones were es2017. I'm going to upgrade all of these.

"build": "tsc -p tsconfig.json && esbuild src/index.ts --bundle --sourcemap --target=es2017 --format=esm --outfile=dist/index.bundle.js && esbuild src/index.ts --bundle --minify --sourcemap --target=es2017 --format=esm --outfile=dist/index.bundle.min.js",
"watch": "tsc -p ../core/tsconfig.json -w --preserveWatchOutput & tsc -p tsconfig.json -w --preserveWatchOutput & esbuild src/index.ts --bundle --sourcemap --target=es2017 --format=esm --watch --outfile=dist/index.bundle.js",
"test": "jest"
},
Expand Down
13 changes: 10 additions & 3 deletions packages/browser/src/plugins/BrowserLifeCyclePlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,19 @@ export class BrowserLifeCyclePlugin implements IEventPlugin {

this._client = context.client;

globalThis.addEventListener("beforeunload", () => void this._client?.suspend());
globalThis.addEventListener("beforeunload", () => {
if (this._client?.config.sessionsEnabled) {
void this._client?.submitSessionEnd();
}

void this._client?.suspend();
});

document.addEventListener("visibilitychange", () => {
if (document.visibilityState === 'visible') {
void this._client?.startup()
void this._client?.startup();
} else {
void this._client?.suspend()
void this._client?.suspend();
}
});

Expand Down
2 changes: 1 addition & 1 deletion packages/browser/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"compilerOptions": {
"lib": [
"DOM",
"ES2020"
"ES2021"
],
"outDir": "dist",
"rootDir": "src",
Expand Down
2 changes: 1 addition & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
"testEnvironment": "jsdom"
},
"scripts": {
"build": "tsc -p tsconfig.json && esbuild src/index.ts --bundle --sourcemap --target=es2017 --format=esm --outfile=dist/index.bundle.js && esbuild src/index.ts --bundle --minify --sourcemap --target=es2019 --format=esm --outfile=dist/index.bundle.min.js",
"build": "tsc -p tsconfig.json && esbuild src/index.ts --bundle --sourcemap --target=es2017 --format=esm --outfile=dist/index.bundle.js && esbuild src/index.ts --bundle --minify --sourcemap --target=es2017 --format=esm --outfile=dist/index.bundle.min.js",
"watch": "tsc -p tsconfig.json -w --preserveWatchOutput & esbuild src/index.ts --bundle --sourcemap --target=es2017 --format=esm --watch --outfile=dist/index.bundle.js",
"test": "jest"
},
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/EventBuilder.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ExceptionlessClient } from "./ExceptionlessClient.js";
import { Event, KnownEventDataKeys } from "./models/Event.js";
import { Event, EventType, KnownEventDataKeys } from "./models/Event.js";
import { ManualStackingInfo } from "./models/data/ManualStackingInfo.js";
import { UserInfo } from "./models/data/UserInfo.js";
import { EventContext } from "./models/EventContext.js";
Expand All @@ -19,7 +19,7 @@ export class EventBuilder {
this.context = context || new EventContext();
}

public setType(type: string): EventBuilder {
public setType(type: EventType): EventBuilder {
if (type) {
this.target.type = type;
}
Expand Down
34 changes: 16 additions & 18 deletions packages/core/src/ExceptionlessClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ export class ExceptionlessClient {
// TODO: Can we schedule this as part of startup?
await queue.process();
}

if (this.config.sessionsEnabled) {
await this.submitSessionStart();
}
}

/** Submit events, pause any timers and go into low power mode. */
Expand Down Expand Up @@ -175,27 +179,21 @@ export class ExceptionlessClient {
return this.createSessionStart().submit();
}

public async submitSessionEnd(sessionIdOrUserId: string): Promise<void> {
if (sessionIdOrUserId && this.config.enabled && this.config.isValid) {
this.config.services.log.info(
`Submitting session end: ${sessionIdOrUserId}`,
);
await this.config.services.submissionClient.submitHeartbeat(
sessionIdOrUserId,
true,
);
public async submitSessionEnd(sessionIdOrUserId?: string): Promise<void> {
const { currentSessionIdentifier, enabled, isValid, services } = this.config;
const sessionId = sessionIdOrUserId || currentSessionIdentifier;
if (sessionId && enabled && isValid) {
services.log.info(`Submitting session end: ${sessionId}`);
await services.submissionClient.submitHeartbeat(sessionId, true);
}
}

public async submitSessionHeartbeat(sessionIdOrUserId: string): Promise<void> {
if (sessionIdOrUserId && this.config.enabled && this.config.isValid) {
this.config.services.log.info(
`Submitting session heartbeat: ${sessionIdOrUserId}`,
);
await this.config.services.submissionClient.submitHeartbeat(
sessionIdOrUserId,
false,
);
public async submitSessionHeartbeat(sessionIdOrUserId?: string): Promise<void> {
const { currentSessionIdentifier, enabled, isValid, services } = this.config;
const sessionId = sessionIdOrUserId || currentSessionIdentifier;
if (sessionId && enabled && isValid) {
services.log.info(`Submitting session heartbeat: ${sessionId}`);
await services.submissionClient.submitHeartbeat(sessionId, false);
}
}

Expand Down
55 changes: 40 additions & 15 deletions packages/core/src/configuration/Configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { ConsoleLog } from "../logging/ConsoleLog.js";
import { NullLog } from "../logging/NullLog.js";
import { UserInfo } from "../models/data/UserInfo.js";
import { HeartbeatPlugin } from "../plugins/default/HeartbeatPlugin.js";
import { SessionIdManagementPlugin } from "../plugins/default/SessionIdManagementPlugin.js";
import { EventPluginContext } from "../plugins/EventPluginContext.js";
import { EventPluginManager } from "../plugins/EventPluginManager.js";
import { IEventPlugin } from "../plugins/IEventPlugin.js";
Expand Down Expand Up @@ -428,32 +429,24 @@ export class Configuration {
}

/**
* Set the default user identity for all events. If the heartbeat interval is
* greater than 0 (default: 30000ms), heartbeats will be sent after the first
* event submission.
* Set the default user identity for all events.
*/
public setUserIdentity(userInfo: UserInfo, heartbeatInterval?: number): void;
public setUserIdentity(identity: string, heartbeatInterval?: number): void;
public setUserIdentity(identity: string, name: string, heartbeatInterval?: number): void;
public setUserIdentity(userInfoOrIdentity: UserInfo | string, nameOrHeartbeatInterval?: string | number, heartbeatInterval: number = 30000): void {
const name: string | undefined = typeof nameOrHeartbeatInterval === "string" ? nameOrHeartbeatInterval : undefined;
public setUserIdentity(userInfo: UserInfo): void;
public setUserIdentity(identity: string): void;
public setUserIdentity(identity: string, name: string): void;
public setUserIdentity(userInfoOrIdentity: UserInfo | string, name?: string): void {
const userInfo: UserInfo = typeof userInfoOrIdentity !== "string"
? userInfoOrIdentity
: <UserInfo>{ identity: userInfoOrIdentity, name };

const interval: number = typeof nameOrHeartbeatInterval === "number" ? nameOrHeartbeatInterval : heartbeatInterval;
const plugin = new HeartbeatPlugin(interval);

const shouldRemove: boolean = !userInfo || (!userInfo.identity && !userInfo.name);
if (shouldRemove) {
this.removePlugin(plugin)
delete this.defaultData[KnownEventDataKeys.UserInfo];
} else {
this.addPlugin(plugin)
this.defaultData[KnownEventDataKeys.UserInfo] = userInfo;
}

this.services.log.info(`user identity: ${shouldRemove ? "null" : <string>userInfo.identity} (heartbeat interval: ${interval}ms)`);
this.services.log.info(`user identity: ${shouldRemove ? "null" : <string>userInfo.identity}`);
}

/**
Expand All @@ -477,7 +470,39 @@ export class Configuration {
* This setting only works in environments that supports persisted storage.
* There is also a performance penalty of extra IO/serialization.
*/
public usePersistedQueueStorage = false;
public usePersistedQueueStorage: boolean = false;

/**
* Gets or sets a value indicating whether to automatically send session start,
* session heartbeats and session end events.
*/
public sessionsEnabled = false;

/**
* Internal property used to track the current session identifier.
*/
public currentSessionIdentifier: string | null = null;

/**
*
* @param sendHeartbeats Controls whether heartbeat events are sent on an interval.
* @param heartbeatInterval The interval at which heartbeats are sent after the last sent event. The default is 1 minutes.
* @param useSessionIdManagement Allows you to manually control the session id. This is only recommended for single user desktop environments.
*/
public useSessions(sendHeartbeats: boolean = true, heartbeatInterval: number = 60000, useSessionIdManagement: boolean = false) {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ejsmith I'm not sure about useSessionIdManagement, I guess this is the safe default since this can be used on node.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems fine.

this.sessionsEnabled = true;

if (useSessionIdManagement) {
this.addPlugin(new SessionIdManagementPlugin());
}

const plugin = new HeartbeatPlugin(heartbeatInterval);
if (sendHeartbeats) {
this.addPlugin(plugin);
} else {
this.removePlugin(plugin);
}
}

private originalSettings?: Record<string, string>;

Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export type { ILog } from "./logging/ILog.js";
export { ConsoleLog } from "./logging/ConsoleLog.js";
export { NullLog } from "./logging/NullLog.js";

export type { Event, IEventData } from "./models/Event.js";
export type { Event, EventType, IEventData } from "./models/Event.js";
export { KnownEventDataKeys } from "./models/Event.js";
export type { EnvironmentInfo } from "./models/data/EnvironmentInfo.js";
export type { ManualStackingInfo } from "./models/data/ManualStackingInfo.js";
Expand All @@ -30,6 +30,7 @@ export { DuplicateCheckerPlugin } from "./plugins/default/DuplicateCheckerPlugin
export { EventExclusionPlugin } from "./plugins/default/EventExclusionPlugin.js";
export { HeartbeatPlugin } from "./plugins/default/HeartbeatPlugin.js";
export { ReferenceIdPlugin } from "./plugins/default/ReferenceIdPlugin.js";
export { SessionIdManagementPlugin } from "./plugins/default/SessionIdManagementPlugin.js";
export { IgnoredErrorProperties, SimpleErrorPlugin } from "./plugins/default/SimpleErrorPlugin.js"
export { SubmissionMethodPlugin } from "./plugins/default/SubmissionMethodPlugin.js";
export { EventContext } from "./models/EventContext.js";
Expand Down
4 changes: 3 additions & 1 deletion packages/core/src/models/Event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ import { UserInfo } from "./data/UserInfo.js";
import { UserDescription } from "./data/UserDescription.js";
import { ManualStackingInfo } from "./data/ManualStackingInfo.js";

export type EventType = "error" | "usage" | "log" | "404" | "session" | string;

export interface Event {
/** The event type (ie. error, log message, feature usage). */
type?: string;
type?: EventType;
/** The event source (ie. machine name, log name, feature name). */
source?: string;
/** The date that the event occurred on. */
Expand Down
19 changes: 14 additions & 5 deletions packages/core/src/plugins/default/HeartbeatPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export class HeartbeatPlugin implements IEventPlugin {
private _interval: number;
private _intervalId: ReturnType<typeof setInterval> | undefined;

constructor(heartbeatInterval: number = 30000) {
constructor(heartbeatInterval: number = 60000) {
this._interval = heartbeatInterval >= 30000 ? heartbeatInterval : 60000;
}

Expand All @@ -34,11 +34,20 @@ export class HeartbeatPlugin implements IEventPlugin {
clearInterval(this._intervalId);
this._intervalId = undefined;

const user = context.event.data?.[KnownEventDataKeys.UserInfo];
if (user?.identity) {
const { config } = context.client;
if (!config.currentSessionIdentifier) {
const user = context.event.data?.[KnownEventDataKeys.UserInfo];
if (!user?.identity) {
return Promise.resolve();
}

config.currentSessionIdentifier = user.identity;
}

if (config.currentSessionIdentifier) {
this._intervalId = setInterval(
() => void context.client.submitSessionHeartbeat(<string>user.identity),
this._interval,
() => void context.client.submitSessionHeartbeat(<string>config.currentSessionIdentifier),
this._interval
);
}

Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/plugins/default/ReferenceIdPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export class ReferenceIdPlugin implements IEventPlugin {
public run(context: EventPluginContext): Promise<void> {
if (!context.event.reference_id && context.event.type === "error") {
// PERF: Optimize identifier creation.
context.event.reference_id = guid().replace("-", "").substring(0, 10);
context.event.reference_id = guid().replaceAll("-", "").substring(0, 10);
}

return Promise.resolve();
Expand Down
29 changes: 29 additions & 0 deletions packages/core/src/plugins/default/SessionIdManagementPlugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { guid } from "../../Utils.js";
import { EventPluginContext } from "../EventPluginContext.js";
import { IEventPlugin } from "../IEventPlugin.js";

export class SessionIdManagementPlugin implements IEventPlugin {
public priority = 25;
public name = "SessionIdManagementPlugin";

public run(context: EventPluginContext): Promise<void> {
const ev = context.event;
const isSessionStart: boolean = ev.type === "session";
const { config } = context.client;
if (isSessionStart || !config.currentSessionIdentifier) {
config.currentSessionIdentifier = guid().replaceAll("-", "");
}

if (isSessionStart) {
ev.reference_id = config.currentSessionIdentifier;
} else {
if (!ev.data) {
ev.data = {};
}

ev.data["@ref:session"] = config.currentSessionIdentifier;
}

return Promise.resolve();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { describe, test } from "@jest/globals";
import { expect } from "expect";

import { ExceptionlessClient } from "../../../src/ExceptionlessClient.js";
import { Event, KnownEventDataKeys } from "../../../src/models/Event.js";
import { Event, EventType, KnownEventDataKeys } from "../../../src/models/Event.js";
import { InnerErrorInfo } from "../../../src/models/data/ErrorInfo.js";
import { EventExclusionPlugin } from "../../../src/plugins/default/EventExclusionPlugin.js";
import { EventPluginContext } from "../../../src/plugins/EventPluginContext.js";
Expand Down Expand Up @@ -142,7 +142,7 @@ describe("EventExclusionPlugin", () => {
});

describe("should exclude source type", () => {
const run = async (type: string | null | undefined, source: string | undefined, settingKey: string | null | undefined, settingValue: string | null | undefined): Promise<boolean> => {
const run = async (type: EventType | null | undefined, source: string | undefined, settingKey: string | null | undefined, settingValue: string | null | undefined): Promise<boolean> => {
const client = new ExceptionlessClient();

if (typeof settingKey === "string") {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/test/submission/TestSubmissionClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ describe("TestSubmissionClient", () => {
const apiFetchMock = jest.fn<(url: string, options: FetchOptions) => Promise<Response<undefined>>>()
.mockReturnValueOnce(Promise.resolve(new Response(202, "", NaN, NaN, undefined)));

const events = [{ type: "log", message: "From js client", reference_id: "123454321" }];
const events: Event[] = [{ type: "log", message: "From js client", reference_id: "123454321" }];
const client = new TestSubmissionClient(config, apiFetchMock);
await client.submitEvents(events);
expect(apiFetchMock).toHaveBeenCalledTimes(1);
Expand Down
4 changes: 4 additions & 0 deletions packages/node/src/plugins/NodeLifeCyclePlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ export class NodeLifeCyclePlugin implements IEventPlugin {
void this._client?.submitLog("beforeExit", message, "Error");
}

if (this._client?.config.sessionsEnabled) {
void this._client?.submitSessionEnd();
}

void this._client?.suspend();
// Application will now exit.
});
Expand Down
2 changes: 1 addition & 1 deletion packages/react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
"./package.json": "./package.json"
},
"scripts": {
"build": "tsc -p tsconfig.json && esbuild src/index.ts --bundle --sourcemap --target=es2017 --format=esm --outfile=dist/index.bundle.js && esbuild src/index.ts --bundle --minify --sourcemap --target=es2019 --format=esm --outfile=dist/index.bundle.min.js",
"build": "tsc -p tsconfig.json && esbuild src/index.ts --bundle --sourcemap --target=es2017 --format=esm --outfile=dist/index.bundle.js && esbuild src/index.ts --bundle --minify --sourcemap --target=es2017 --format=esm --outfile=dist/index.bundle.min.js",
"watch": "tsc -p ../core/tsconfig.json -w --preserveWatchOutput & tsc -p tsconfig.json -w --preserveWatchOutput & esbuild src/index.ts --bundle --sourcemap --target=es2017 --format=esm --watch --outfile=dist/index.bundle.js"
},
"sideEffects": false,
Expand Down
5 changes: 4 additions & 1 deletion packages/react/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"lib": ["DOM", "ES2020"],
"lib": [
"DOM",
"ES2021"
],
"outDir": "dist",
"rootDir": "src",
"jsx": "react",
Expand Down
2 changes: 1 addition & 1 deletion packages/vue/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
"./package.json": "./package.json"
},
"scripts": {
"build": "tsc -p tsconfig.json && esbuild src/index.ts --bundle --sourcemap --target=es2017 --format=esm --outfile=dist/index.bundle.js && esbuild src/index.ts --bundle --minify --sourcemap --target=es2019 --format=esm --outfile=dist/index.bundle.min.js",
"build": "tsc -p tsconfig.json && esbuild src/index.ts --bundle --sourcemap --target=es2017 --format=esm --outfile=dist/index.bundle.js && esbuild src/index.ts --bundle --minify --sourcemap --target=es2017 --format=esm --outfile=dist/index.bundle.min.js",
"watch": "tsc -p tsconfig.json -w --preserveWatchOutput & && esbuild src/index.ts --bundle --sourcemap --target=es2017 --format=esm --watch --outfile=dist/index.bundle.js &"
},
"sideEffects": false,
Expand Down
Loading