Skip to content

Commit a551e88

Browse files
committed
Keep events when core plugins or serialization hit bad data
- parseQueryString/getCookies: decode safely, split on the first "=", match exclusions on the decoded key, use "" for missing values and skip empty keys. - prune/stringify: drop values whose getter, toJSON or Proxy throws instead of throwing; cap nested toJSON calls by depth; track only ancestors for cycle detection (arrays and errors included) so shared, non-circular references are kept. - EventPluginManager: a throwing plugin is logged with its name and the error, and the event continues instead of being cancelled. - EventExclusionPlugin: logs without a level are cancelled when the source's minimum level is off; exception type exclusions also apply to @simple_error. - DuplicateCheckerPlugin: de-duplicate @simple_error events.
1 parent 54ac83f commit a551e88

10 files changed

Lines changed: 545 additions & 88 deletions

File tree

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ await Exceptionless.startup((config) => {
5555

5656
- Lower `priority` values run earlier.
5757
- Setting `context.cancelled = true` stops later plugins and prevents submission.
58-
- Plugin errors are caught by `EventPluginManager`; the event is cancelled to avoid sending partially processed data.
58+
- 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.
5959
- Keep plugins small. Prefer plugins for cross-cutting enrichment or filtering, not business logic.
6060
- Be careful adding user, request, headers, cookies, query, or body data. Read [data-exclusions.md](data-exclusions.md) first.
6161

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,10 @@ If expected data is absent from an event, check `includePrivateInformation`, `in
3838

3939
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`.
4040

41+
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.
42+
43+
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.
44+
4145
## Source Anchors
4246

4347
- `packages/core/src/queue/DefaultEventQueue.ts`

‎packages/core/src/Utils.ts‎

Lines changed: 103 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,38 @@ export function getCookies(cookies: string, exclusions?: string[]): Record<strin
1818

1919
const parts: string[] = (cookies || "").split("; ");
2020
for (const part of parts) {
21-
const cookie: string[] = part.split("=");
22-
if (!isMatch(cookie[0], exclusions || [])) {
23-
result[cookie[0]] = cookie[1];
21+
const [name, value] = splitKeyValuePair(part);
22+
if (name && !isMatch(name, exclusions || [])) {
23+
result[name] = value;
2424
}
2525
}
2626

2727
return !isEmpty(result) ? result : null;
2828
}
2929

30+
/**
31+
* Splits a `key=value` pair on the first `=` and decodes both parts. A pair without a value yields an empty string.
32+
*/
33+
function splitKeyValuePair(pair: string): [string, string] {
34+
const separatorIndex = pair.indexOf("=");
35+
if (separatorIndex === -1) {
36+
return [safeDecodeURIComponent(pair), ""];
37+
}
38+
39+
return [safeDecodeURIComponent(pair.slice(0, separatorIndex)), safeDecodeURIComponent(pair.slice(separatorIndex + 1))];
40+
}
41+
42+
/**
43+
* Decodes a URI component, returning the original text when it is not valid percent encoding.
44+
*/
45+
function safeDecodeURIComponent(value: string): string {
46+
try {
47+
return decodeURIComponent(value);
48+
} catch {
49+
return value;
50+
}
51+
}
52+
3053
function getSecureCrypto(): Crypto | null {
3154
const { crypto } = globalThis;
3255
if (!crypto || typeof crypto.getRandomValues !== "function") {
@@ -184,9 +207,9 @@ export function parseQueryString(query: string, exclusions?: string[]): Record<s
184207

185208
const result: Record<string, string> = {};
186209
for (const pair of pairs) {
187-
const parts = pair.split("=");
188-
if (!exclusions || !isMatch(parts[0], exclusions)) {
189-
result[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
210+
const [key, value] = splitKeyValuePair(pair);
211+
if (key && (!exclusions || !isMatch(key, exclusions))) {
212+
result[key] = value;
190213
}
191214
}
192215

@@ -312,18 +335,19 @@ export function endsWith(input: string, suffix: string): boolean {
312335
* 2. If the value is a function or unsupported type it will be return undefined.
313336
* 3. If the value is an array, it will be pruned to the specified depth.
314337
* 4. If the value is an object, it will be pruned to the specified depth and
315-
* a. If the object is a Circular Reference it will return undefined.
338+
* 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.
316339
* 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.
317340
* c. If the object is a Set, it will be converted to an array.
318341
* d. If the object contains prototype properties, they will be picked up.
319-
* e. If the object contains a toJSON function, it will be called and it's value will be normalized.
342+
* 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.
320343
* f. If the object is is not iterable or cloneable (e.g., WeakMap, WeakSet, etc.), it will return undefined.
321344
* g. If a symbol property is encountered, it will be converted to a string representation and could overwrite existing object keys.
322345
* 5. If the value is an Error, we will treat it as an object.
323346
* 6. If the value is a primitive, it will be returned as is.
324347
* 7. If the value is a Regexp, Symbol we will convert it to the string representation.
325348
* 8. BigInt and other typed arrays will be converted to a string unless number type works.
326349
* 9. All other values will be returned as undefined (E.g., Buffer, DataView, Promises, Generators etc..)
350+
* 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.
327351
*/
328352
export function prune(value: unknown, depth: number = 10): unknown {
329353
function isUnsupportedType(value: unknown): boolean {
@@ -358,7 +382,7 @@ export function prune(value: unknown, depth: number = 10): unknown {
358382
return false;
359383
}
360384

361-
function normalizeValue(value: unknown): unknown {
385+
function normalizeValue(value: unknown, toJSONDepth: number): unknown {
362386
function hasToJSONFunction(value: unknown): value is { toJSON: () => unknown } {
363387
return value !== null && typeof value === "object" && typeof (value as { toJSON?: unknown }).toJSON === "function";
364388
}
@@ -399,8 +423,12 @@ export function prune(value: unknown, depth: number = 10): unknown {
399423
}
400424

401425
if (hasToJSONFunction(value)) {
402-
// NOTE: We are not checking for circular references or overflow
403-
return normalizeValue(value.toJSON());
426+
// Each toJSON call counts against the depth so a toJSON that returns itself or another toJSON object terminates.
427+
if (toJSONDepth > depth) {
428+
return undefined;
429+
}
430+
431+
return normalizeValue(value.toJSON(), toJSONDepth + 1);
404432
}
405433

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

416-
function pruneImpl(
417-
value: unknown,
418-
maxDepth: number,
419-
currentDepth: number = 10,
420-
seen: WeakSet<object> = new WeakSet(),
421-
parentIsArray: boolean = false
422-
): unknown {
444+
function pruneImpl(value: unknown, maxDepth: number, currentDepth: number = 10, ancestors: Set<object> = new Set(), parentIsArray: boolean = false): unknown {
423445
if (value === null || value === undefined) {
424446
return value;
425447
}
@@ -428,55 +450,83 @@ export function prune(value: unknown, depth: number = 10): unknown {
428450
return undefined;
429451
}
430452

431-
if (isUnsupportedType(value)) {
432-
return undefined;
433-
}
434-
435-
const normalizedValue = normalizeValue(value);
436-
if (typeof normalizedValue === "object") {
437-
if (currentDepth == maxDepth) {
438-
return undefined;
439-
}
453+
// Only the objects on the current path are tracked, so a value referenced more than once is kept unless it contains itself.
454+
const pathEntries: object[] = [];
455+
try {
456+
if (typeof value === "object") {
457+
if (ancestors.has(value)) {
458+
return undefined;
459+
}
440460

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

447-
if (normalizedValue instanceof Date) {
448-
return normalizedValue;
465+
if (isUnsupportedType(value)) {
466+
return undefined;
449467
}
450468

451-
// Check for circular references
452-
if (Object.prototype.toString.call(normalizedValue) === "[object Object]") {
453-
if (seen.has(normalizedValue as object)) {
469+
const normalizedValue = normalizeValue(value, currentDepth);
470+
if (normalizedValue !== null && typeof normalizedValue === "object") {
471+
if (currentDepth == maxDepth) {
454472
return undefined;
455473
}
456474

457-
seen.add(normalizedValue as object);
458-
}
475+
if (normalizedValue !== value) {
476+
if (ancestors.has(normalizedValue)) {
477+
return undefined;
478+
}
459479

460-
const keys = new Set<PropertyKey>([...Object.getOwnPropertyNames(normalizedValue), ...Object.getOwnPropertySymbols(normalizedValue)]);
461-
// Loop over and add any inherited prototype properties
462-
for (const key in normalizedValue) {
463-
keys.add(key);
464-
}
480+
ancestors.add(normalizedValue);
481+
pathEntries.push(normalizedValue);
482+
}
483+
484+
if (Array.isArray(normalizedValue)) {
485+
// Treat an object inside of an array as a single level
486+
const depth: number = parentIsArray ? currentDepth + 1 : currentDepth;
487+
return normalizedValue.map((e) => pruneImpl(e, maxDepth, depth, ancestors, true));
488+
}
465489

466-
type NonSymbolPropertyKey = Exclude<PropertyKey, symbol>;
467-
const result: Record<NonSymbolPropertyKey, unknown> = {};
468-
for (const key of keys) {
469-
// Normalize the key so Symbols are converted to strings.
470-
const normalizedKey = normalizeValue(key) as NonSymbolPropertyKey;
490+
if (normalizedValue instanceof Date) {
491+
return normalizedValue;
492+
}
493+
494+
const keys = new Set<PropertyKey>([...Object.getOwnPropertyNames(normalizedValue), ...Object.getOwnPropertySymbols(normalizedValue)]);
495+
// Loop over and add any inherited prototype properties
496+
for (const key in normalizedValue) {
497+
keys.add(key);
498+
}
499+
500+
type NonSymbolPropertyKey = Exclude<PropertyKey, symbol>;
501+
const result: Record<NonSymbolPropertyKey, unknown> = {};
502+
for (const key of keys) {
503+
// Normalize the key so Symbols are converted to strings.
504+
const normalizedKey = normalizeValue(key, currentDepth) as NonSymbolPropertyKey;
505+
506+
let objectValue: unknown;
507+
try {
508+
objectValue = (normalizedValue as { [index: PropertyKey]: unknown })[key];
509+
} catch {
510+
// Drop properties whose getter throws.
511+
result[normalizedKey] = undefined;
512+
continue;
513+
}
514+
515+
result[normalizedKey] = pruneImpl(objectValue, maxDepth, currentDepth + 1, ancestors);
516+
}
471517

472-
const objectValue = (normalizedValue as { [index: PropertyKey]: unknown })[key];
473-
result[normalizedKey] = pruneImpl(objectValue, maxDepth, currentDepth + 1, seen);
518+
return result;
474519
}
475520

476-
return result;
521+
return normalizedValue;
522+
} catch {
523+
// Drop values that cannot be read, such as a throwing toJSON or a revoked Proxy.
524+
return undefined;
525+
} finally {
526+
for (const entry of pathEntries) {
527+
ancestors.delete(entry);
528+
}
477529
}
478-
479-
return normalizedValue;
480530
}
481531

482532
if (depth < 0) {

‎packages/core/src/plugins/EventPluginManager.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ export class EventPluginManager {
1818
try {
1919
await plugin.startup(context);
2020
} catch (ex) {
21-
context.log.error(`Error running plugin startup"${<string>plugin.name}": ${ex instanceof Error ? ex.message : ex + ""}`);
21+
context.log.error(`Error running plugin startup "${<string>plugin.name}": ${getErrorMessage(ex)}`);
2222
}
2323
}
2424
}
@@ -32,7 +32,7 @@ export class EventPluginManager {
3232
try {
3333
await plugin.suspend(context);
3434
} catch (ex) {
35-
context.log.error(`Error running plugin suspend"${<string>plugin.name}": ${ex instanceof Error ? ex.message : ex + ""}`);
35+
context.log.error(`Error running plugin suspend "${<string>plugin.name}": ${getErrorMessage(ex)}`);
3636
}
3737
}
3838
}
@@ -50,8 +50,8 @@ export class EventPluginManager {
5050
try {
5151
await plugin.run(context);
5252
} catch (ex) {
53-
context.cancelled = true;
54-
context.log.error(`Error running plugin "${<string>plugin.name}": ${ex instanceof Error ? ex.message : ex + ""}. Discarding Event.`);
53+
// A failing plugin must not drop the event; only an explicit context.cancelled does.
54+
context.log.error(`Error running plugin "${<string>plugin.name}": ${getErrorMessage(ex)}. Continuing with the event.`);
5555
}
5656
}
5757
}
@@ -65,3 +65,7 @@ export class EventPluginManager {
6565
config.addPlugin(new SubmissionMethodPlugin());
6666
}
6767
}
68+
69+
function getErrorMessage(ex: unknown): string {
70+
return ex instanceof Error ? ex.message : ex + "";
71+
}

‎packages/core/src/plugins/default/DuplicateCheckerPlugin.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { InnerErrorInfo } from "../../models/data/ErrorInfo.js";
1+
import { InnerErrorInfo, SimpleError } from "../../models/data/ErrorInfo.js";
22
import { KnownEventDataKeys } from "../../models/Event.js";
33
import { allowProcessToExitWithoutWaitingForTimerOrInterval, getHashCode } from "../../Utils.js";
44
import { EventPluginContext } from "../../plugins/EventPluginContext.js";
@@ -33,7 +33,7 @@ export class DuplicateCheckerPlugin implements IEventPlugin {
3333
}
3434

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

52-
const error = context.event.data?.[KnownEventDataKeys.Error];
52+
const error = context.event.data?.[KnownEventDataKeys.Error] ?? context.event.data?.[KnownEventDataKeys.SimpleError];
5353
const hashCode = calculateHashCode(error);
5454
if (hashCode) {
5555
const count = context.event.count || 1;

‎packages/core/src/plugins/default/EventExclusionPlugin.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { InnerErrorInfo, SimpleError } from "../../models/data/ErrorInfo.js";
12
import { KnownEventDataKeys, LogLevel } from "../../models/Event.js";
23
import { isMatch, startsWith, toBoolean } from "../../Utils.js";
34
import { EventPluginContext } from "../../plugins/EventPluginContext.js";
@@ -16,12 +17,13 @@ export class EventExclusionPlugin implements IEventPlugin {
1617
const minLogLevel = this.getMinLogLevel(settings, ev.source);
1718
const logLevel = this.getLogLevel(ev.data && ev.data[KnownEventDataKeys.Level]);
1819

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

0 commit comments

Comments
 (0)