Skip to content
Draft
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
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ await Exceptionless.startup((config) => {

- Lower `priority` values run earlier.
- Setting `context.cancelled = true` stops later plugins and prevents submission.
- Plugin errors are caught by `EventPluginManager`; the event is cancelled to avoid sending partially processed data.
- Plugin errors are caught by `EventPluginManager`, logged with the plugin name and error message, and the event continues through the remaining plugins. A throwing plugin does not cancel the event; set `context.cancelled = true` to drop it. A failing `startup` or `suspend` is logged the same way and does not stop other plugins.
- Keep plugins small. Prefer plugins for cross-cutting enrichment or filtering, not business logic.
- Be careful adding user, request, headers, cookies, query, or body data. Read [data-exclusions.md](data-exclusions.md) first.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ If expected data is absent from an event, check `includePrivateInformation`, `in

If expected events are missing, check synced settings and client-side filters such as `@@log:*`, `@@error:*`, `@@usage:*`, and custom plugins that set `context.cancelled = true`.

A log minimum level of `off` for a source (for example `@@log:*` = `off`) also drops logs submitted without a level. Exception type settings such as `@@error:TypeError` apply to both `@error` and `@simple_error` data, including inner errors.

If a custom plugin throws, the client logs `Error running plugin "<name>"` and keeps processing the event. Enable `config.useDebugLogger()` to see these messages; the default logger discards them.

## Source Anchors

- `packages/core/src/queue/DefaultEventQueue.ts`
Expand Down
176 changes: 123 additions & 53 deletions packages/core/src/Utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,38 @@ export function getCookies(cookies: string, exclusions?: string[]): Record<strin

const parts: string[] = (cookies || "").split("; ");
for (const part of parts) {
const cookie: string[] = part.split("=");
if (!isMatch(cookie[0], exclusions || [])) {
result[cookie[0]] = cookie[1];
const [name, value] = splitKeyValuePair(part);
if (name && !isMatch(name, exclusions || [])) {
result[name] = value;
}
}

return !isEmpty(result) ? result : null;
}

/**
* Splits a `key=value` pair on the first `=` and decodes both parts. A pair without a value yields an empty string.
*/
function splitKeyValuePair(pair: string): [string, string] {
const separatorIndex = pair.indexOf("=");
if (separatorIndex === -1) {
return [safeDecodeURIComponent(pair), ""];
}

return [safeDecodeURIComponent(pair.slice(0, separatorIndex)), safeDecodeURIComponent(pair.slice(separatorIndex + 1))];
}

/**
* Decodes a URI component, returning the original text when it is not valid percent encoding.
*/
function safeDecodeURIComponent(value: string): string {
try {
return decodeURIComponent(value);
} catch {
return value;
}
}

function getSecureCrypto(): Crypto | null {
const { crypto } = globalThis;
if (!crypto || typeof crypto.getRandomValues !== "function") {
Expand Down Expand Up @@ -184,9 +207,9 @@ export function parseQueryString(query: string, exclusions?: string[]): Record<s

const result: Record<string, string> = {};
for (const pair of pairs) {
const parts = pair.split("=");
if (!exclusions || !isMatch(parts[0], exclusions)) {
result[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
const [key, value] = splitKeyValuePair(pair);
if (key && (!exclusions || !isMatch(key, exclusions))) {
result[key] = value;
}
}

Expand Down Expand Up @@ -312,18 +335,19 @@ export function endsWith(input: string, suffix: string): boolean {
* 2. If the value is a function or unsupported type it will be return undefined.
* 3. If the value is an array, it will be pruned to the specified depth.
* 4. If the value is an object, it will be pruned to the specified depth and
* a. If the object is a Circular Reference it will return undefined.
* a. If the object is a Circular Reference (it contains itself, including through arrays and errors) it will return undefined. Repeated references that are not circular are kept.
* b. If the object is a Map, it will be converted to an object. Some data loss might occur if map keys are object types as last in wins.
* c. If the object is a Set, it will be converted to an array.
* d. If the object contains prototype properties, they will be picked up.
* e. If the object contains a toJSON function, it will be called and it's value will be normalized.
* e. If the object contains a toJSON function, it will be called and it's value will be normalized. Nested toJSON calls count against the depth.
* f. If the object is is not iterable or cloneable (e.g., WeakMap, WeakSet, etc.), it will return undefined.
* g. If a symbol property is encountered, it will be converted to a string representation and could overwrite existing object keys.
* 5. If the value is an Error, we will treat it as an object.
* 6. If the value is a primitive, it will be returned as is.
* 7. If the value is a Regexp, Symbol we will convert it to the string representation.
* 8. BigInt and other typed arrays will be converted to a string unless number type works.
* 9. All other values will be returned as undefined (E.g., Buffer, DataView, Promises, Generators etc..)
* 10. If reading a value throws (e.g., a throwing getter or toJSON, or a revoked Proxy), that value will return undefined and the rest of the object is kept.
*/
export function prune(value: unknown, depth: number = 10): unknown {
function isUnsupportedType(value: unknown): boolean {
Expand Down Expand Up @@ -358,7 +382,7 @@ export function prune(value: unknown, depth: number = 10): unknown {
return false;
}

function normalizeValue(value: unknown): unknown {
function normalizeValue(value: unknown, toJSONDepth: number): unknown {
function hasToJSONFunction(value: unknown): value is { toJSON: () => unknown } {
return value !== null && typeof value === "object" && typeof (value as { toJSON?: unknown }).toJSON === "function";
}
Expand Down Expand Up @@ -399,8 +423,12 @@ export function prune(value: unknown, depth: number = 10): unknown {
}

if (hasToJSONFunction(value)) {
// NOTE: We are not checking for circular references or overflow
return normalizeValue(value.toJSON());
// Each toJSON call counts against the depth so a toJSON that returns itself or another toJSON object terminates.
if (toJSONDepth > depth) {
return undefined;
}

return normalizeValue(value.toJSON(), toJSONDepth + 1);
}

return value;
Expand All @@ -413,13 +441,7 @@ export function prune(value: unknown, depth: number = 10): unknown {
return value;
}

function pruneImpl(
value: unknown,
maxDepth: number,
currentDepth: number = 10,
seen: WeakSet<object> = new WeakSet(),
parentIsArray: boolean = false
): unknown {
function pruneImpl(value: unknown, maxDepth: number, currentDepth: number = 10, ancestors: Set<object> = new Set(), parentIsArray: boolean = false): unknown {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

we need a ton of coverage for this if we are changing it and benchmarks. I did a ton of work to make sure this was performant and error free

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[AGENT] I ran a focused synthetic benchmark of stringify() on Node 24.22.3, comparing 54ac83f with 4cbe944. Across 10 warmed, alternating-order pairs, median paired time was 4.1% higher for a 111-byte log (1.153 → 1.200 µs per call) and 2.4% higher for a 1,431-byte nested error/request (14.117 → 14.424 µs). Both revisions produced byte-identical JSON. This covers two ordinary payloads. Browser and device performance, allocations, and malformed or cyclic inputs remain open.

if (value === null || value === undefined) {
return value;
}
Expand All @@ -428,55 +450,103 @@ export function prune(value: unknown, depth: number = 10): unknown {
return undefined;
}

if (isUnsupportedType(value)) {
return undefined;
}

const normalizedValue = normalizeValue(value);
if (typeof normalizedValue === "object") {
if (currentDepth == maxDepth) {
return undefined;
}
// Only the objects on the current path are tracked, so a value referenced more than once is kept unless it contains itself.
const pathEntries: object[] = [];
try {
if (typeof value === "object") {
if (ancestors.has(value)) {
return undefined;
}

if (Array.isArray(normalizedValue)) {
// Treat an object inside of an array as a single level
const depth: number = parentIsArray ? currentDepth + 1 : currentDepth;
return normalizedValue.map((e) => pruneImpl(e, maxDepth, depth, seen, true));
ancestors.add(value);
pathEntries.push(value);
}

if (normalizedValue instanceof Date) {
return normalizedValue;
if (isUnsupportedType(value)) {
return undefined;
}

// Check for circular references
if (Object.prototype.toString.call(normalizedValue) === "[object Object]") {
if (seen.has(normalizedValue as object)) {
const normalizedValue = normalizeValue(value, currentDepth);
if (normalizedValue !== null && typeof normalizedValue === "object") {
if (currentDepth == maxDepth) {
return undefined;
}

seen.add(normalizedValue as object);
}
if (normalizedValue !== value) {
if (ancestors.has(normalizedValue)) {
return undefined;
}

const keys = new Set<PropertyKey>([...Object.getOwnPropertyNames(normalizedValue), ...Object.getOwnPropertySymbols(normalizedValue)]);
// Loop over and add any inherited prototype properties
for (const key in normalizedValue) {
keys.add(key);
}
ancestors.add(normalizedValue);
pathEntries.push(normalizedValue);
}

type NonSymbolPropertyKey = Exclude<PropertyKey, symbol>;
const result: Record<NonSymbolPropertyKey, unknown> = {};
for (const key of keys) {
// Normalize the key so Symbols are converted to strings.
const normalizedKey = normalizeValue(key) as NonSymbolPropertyKey;
if (Array.isArray(normalizedValue)) {
// Treat an object inside of an array as a single level
const depth: number = parentIsArray ? currentDepth + 1 : currentDepth;
// Read each element separately so a throwing index getter only drops that element.
const array = normalizedValue as unknown[];
const result: unknown[] = [];
for (let index = 0; index < array.length; index++) {
let element: unknown;
try {
element = array[index];
} catch {
result[index] = undefined;
continue;
}

result[index] = pruneImpl(element, maxDepth, depth, ancestors, true);
}

return result;
}

const objectValue = (normalizedValue as { [index: PropertyKey]: unknown })[key];
result[normalizedKey] = pruneImpl(objectValue, maxDepth, currentDepth + 1, seen);
if (normalizedValue instanceof Date) {
if (normalizedValue.toJSON === Date.prototype.toJSON && normalizedValue.toISOString === Date.prototype.toISOString) {
return normalizedValue;
}

// A Date with an overridden toJSON is serialized here, where a throw only drops this value.
return normalizedValue.toJSON();
}

const keys = new Set<PropertyKey>([...Object.getOwnPropertyNames(normalizedValue), ...Object.getOwnPropertySymbols(normalizedValue)]);
// Loop over and add any inherited prototype properties
for (const key in normalizedValue) {
keys.add(key);
}

type NonSymbolPropertyKey = Exclude<PropertyKey, symbol>;
const result: Record<NonSymbolPropertyKey, unknown> = {};
for (const key of keys) {
// Normalize the key so Symbols are converted to strings.
const normalizedKey = normalizeValue(key, currentDepth) as NonSymbolPropertyKey;

let objectValue: unknown;
try {
objectValue = (normalizedValue as { [index: PropertyKey]: unknown })[key];
} catch {
// Drop properties whose getter throws.
result[normalizedKey] = undefined;
continue;
}

result[normalizedKey] = pruneImpl(objectValue, maxDepth, currentDepth + 1, ancestors);
}

return result;
}

return result;
return normalizedValue;
} catch {
// Drop values that cannot be read, such as a throwing toJSON or a revoked Proxy.
return undefined;
} finally {
for (const entry of pathEntries) {
ancestors.delete(entry);
}
}

return normalizedValue;
}

if (depth < 0) {
Expand Down
17 changes: 13 additions & 4 deletions packages/core/src/plugins/EventPluginManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export class EventPluginManager {
try {
await plugin.startup(context);
} catch (ex) {
context.log.error(`Error running plugin startup"${<string>plugin.name}": ${ex instanceof Error ? ex.message : ex + ""}`);
context.log.error(`Error running plugin startup "${<string>plugin.name}": ${getErrorMessage(ex)}`);
}
}
}
Expand All @@ -32,7 +32,7 @@ export class EventPluginManager {
try {
await plugin.suspend(context);
} catch (ex) {
context.log.error(`Error running plugin suspend"${<string>plugin.name}": ${ex instanceof Error ? ex.message : ex + ""}`);
context.log.error(`Error running plugin suspend "${<string>plugin.name}": ${getErrorMessage(ex)}`);
}
}
}
Expand All @@ -50,8 +50,8 @@ export class EventPluginManager {
try {
await plugin.run(context);
} catch (ex) {
context.cancelled = true;
context.log.error(`Error running plugin "${<string>plugin.name}": ${ex instanceof Error ? ex.message : ex + ""}. Discarding Event.`);
// A failing plugin must not drop the event; only an explicit context.cancelled does.
context.log.error(`Error running plugin "${<string>plugin.name}": ${getErrorMessage(ex)}. Continuing with the event.`);
}
}
}
Expand All @@ -65,3 +65,12 @@ export class EventPluginManager {
config.addPlugin(new SubmissionMethodPlugin());
}
}

function getErrorMessage(ex: unknown): string {
// Formatting must never throw (for example a thrown Symbol, or a revoked Proxy), or the event would still be lost.
try {
return ex instanceof Error ? String(ex.message) : String(ex);
} catch {
return "Unknown error";
}
}
6 changes: 3 additions & 3 deletions packages/core/src/plugins/default/DuplicateCheckerPlugin.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { InnerErrorInfo } from "../../models/data/ErrorInfo.js";
import { InnerErrorInfo, SimpleError } from "../../models/data/ErrorInfo.js";
import { KnownEventDataKeys } from "../../models/Event.js";
import { allowProcessToExitWithoutWaitingForTimerOrInterval, getHashCode } from "../../Utils.js";
import { EventPluginContext } from "../../plugins/EventPluginContext.js";
Expand Down Expand Up @@ -33,7 +33,7 @@ export class DuplicateCheckerPlugin implements IEventPlugin {
}

public run(context: EventPluginContext): Promise<void> {
function calculateHashCode(error: InnerErrorInfo | undefined): number {
function calculateHashCode(error: InnerErrorInfo | SimpleError | undefined): number {
let hash = 0;
while (error) {
if (error.message && error.message.length) {
Expand All @@ -49,7 +49,7 @@ export class DuplicateCheckerPlugin implements IEventPlugin {
return hash;
}

const error = context.event.data?.[KnownEventDataKeys.Error];
const error = context.event.data?.[KnownEventDataKeys.Error] ?? context.event.data?.[KnownEventDataKeys.SimpleError];
const hashCode = calculateHashCode(error);
if (hashCode) {
const count = context.event.count || 1;
Expand Down
6 changes: 4 additions & 2 deletions packages/core/src/plugins/default/EventExclusionPlugin.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { InnerErrorInfo, SimpleError } from "../../models/data/ErrorInfo.js";
import { KnownEventDataKeys, LogLevel } from "../../models/Event.js";
import { isMatch, startsWith, toBoolean } from "../../Utils.js";
import { EventPluginContext } from "../../plugins/EventPluginContext.js";
Expand All @@ -16,12 +17,13 @@ export class EventExclusionPlugin implements IEventPlugin {
const minLogLevel = this.getMinLogLevel(settings, ev.source);
const logLevel = this.getLogLevel(ev.data && ev.data[KnownEventDataKeys.Level]);

if (logLevel !== -1 && (logLevel === 6 || logLevel < minLogLevel)) {
// A log without a recognized level is only excluded when logging is turned off for its source.
if (logLevel === -1 ? minLogLevel === 6 : logLevel === 6 || logLevel < minLogLevel) {
log.info("Cancelling log event due to minimum log level.");
context.cancelled = true;
}
} else if (ev.type === "error") {
let error = ev.data && ev.data[KnownEventDataKeys.Error];
let error: InnerErrorInfo | SimpleError | undefined = ev.data?.[KnownEventDataKeys.Error] ?? ev.data?.[KnownEventDataKeys.SimpleError];
while (!context.cancelled && error) {
if (this.getTypeAndSourceSetting(settings, ev.type, error.type, true) === false) {
log.info(`Cancelling error from excluded exception type: ${<string>error.type}`);
Expand Down
Loading
Loading