@zharp/node 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +48 -1
- package/dist/index.d.ts +48 -1
- package/dist/index.js +714 -74
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +677 -46
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -8,12 +8,13 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
|
|
|
8
8
|
// src/zharp.ts
|
|
9
9
|
import { register as registerLoader } from "module";
|
|
10
10
|
import {
|
|
11
|
+
context as context2,
|
|
11
12
|
DiagLogLevel,
|
|
12
13
|
diag,
|
|
13
14
|
INVALID_SPAN_CONTEXT,
|
|
14
15
|
logs,
|
|
15
|
-
SpanStatusCode,
|
|
16
|
-
trace as
|
|
16
|
+
SpanStatusCode as SpanStatusCode2,
|
|
17
|
+
trace as trace4
|
|
17
18
|
} from "@opentelemetry/api";
|
|
18
19
|
import { CompositePropagator, W3CBaggagePropagator, W3CTraceContextPropagator } from "@opentelemetry/core";
|
|
19
20
|
import { envDetector, hostDetector, resourceFromAttributes } from "@opentelemetry/resources";
|
|
@@ -654,6 +655,571 @@ function withBodyCapture(settings, config = {}) {
|
|
|
654
655
|
};
|
|
655
656
|
}
|
|
656
657
|
|
|
658
|
+
// src/headers.ts
|
|
659
|
+
import { ClientRequest as ClientRequest2, IncomingMessage as IncomingMessage2, ServerResponse as ServerResponse2 } from "http";
|
|
660
|
+
var SECRET = /* @__PURE__ */ new Set(["authorization", "proxy-authorization", "cookie", "set-cookie", "x-api-key", "x-auth-token", "x-csrf-token", "x-xsrf-token"]);
|
|
661
|
+
var MAX_HEADERS = 40;
|
|
662
|
+
var MAX_VALUE = 512;
|
|
663
|
+
function headerSettings(option, env) {
|
|
664
|
+
if (option === false || env === "false" || env === "0") return null;
|
|
665
|
+
return { redact: typeof option === "object" && option?.redact ? option.redact : [] };
|
|
666
|
+
}
|
|
667
|
+
function shown(name, value, settings) {
|
|
668
|
+
if (value === void 0 || value === null) return null;
|
|
669
|
+
if (SECRET.has(name) || isSecretKey(name, settings.redact)) return FILTERED;
|
|
670
|
+
const text = Array.isArray(value) ? value.join(", ") : String(value);
|
|
671
|
+
return text.length > MAX_VALUE ? `${text.slice(0, MAX_VALUE)}\u2026` : text;
|
|
672
|
+
}
|
|
673
|
+
function headerAttributes(side, headers, settings) {
|
|
674
|
+
const out = {};
|
|
675
|
+
let count = 0;
|
|
676
|
+
for (const [rawName, value] of Object.entries(headers ?? {})) {
|
|
677
|
+
if (count >= MAX_HEADERS) break;
|
|
678
|
+
const name = rawName.toLowerCase();
|
|
679
|
+
const text = shown(name, value, settings);
|
|
680
|
+
if (text === null) continue;
|
|
681
|
+
out[`http.${side}.header.${name}`] = text;
|
|
682
|
+
count++;
|
|
683
|
+
}
|
|
684
|
+
return out;
|
|
685
|
+
}
|
|
686
|
+
function withHeaderCapture(settings, config = {}) {
|
|
687
|
+
return {
|
|
688
|
+
...config,
|
|
689
|
+
applyCustomAttributesOnSpan(span, request, response) {
|
|
690
|
+
config.applyCustomAttributesOnSpan?.(span, request, response);
|
|
691
|
+
try {
|
|
692
|
+
if (request instanceof IncomingMessage2) {
|
|
693
|
+
span.setAttributes(headerAttributes("request", request.headers, settings));
|
|
694
|
+
if (response instanceof ServerResponse2) span.setAttributes(headerAttributes("response", response.getHeaders(), settings));
|
|
695
|
+
} else if (request instanceof ClientRequest2) {
|
|
696
|
+
span.setAttributes(headerAttributes("request", request.getHeaders(), settings));
|
|
697
|
+
if (response instanceof IncomingMessage2) span.setAttributes(headerAttributes("response", response.headers, settings));
|
|
698
|
+
}
|
|
699
|
+
} catch {
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
};
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
// src/db-errors.ts
|
|
706
|
+
import { context, createContextKey, SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
|
|
707
|
+
import { InstrumentationBase, InstrumentationNodeModuleDefinition } from "@opentelemetry/instrumentation";
|
|
708
|
+
|
|
709
|
+
// src/version.ts
|
|
710
|
+
var VERSION = "0.4.0";
|
|
711
|
+
|
|
712
|
+
// src/source.ts
|
|
713
|
+
import { readFileSync, statSync } from "fs";
|
|
714
|
+
import { dirname, isAbsolute, resolve } from "path";
|
|
715
|
+
import { fileURLToPath } from "url";
|
|
716
|
+
import * as nodeModule from "module";
|
|
717
|
+
var SOURCE_CONTEXT_ATTRIBUTE = "zharp.source_context";
|
|
718
|
+
var AROUND = 5;
|
|
719
|
+
var MAX_FRAMES = 5;
|
|
720
|
+
var MAX_LINE = 300;
|
|
721
|
+
var MAX_BYTES = 12e3;
|
|
722
|
+
var MAX_FILE = 5e6;
|
|
723
|
+
var MAX_MAP = 3e7;
|
|
724
|
+
var MAX_CACHED = 50;
|
|
725
|
+
var enabled = true;
|
|
726
|
+
function setSourceContext(on) {
|
|
727
|
+
enabled = on;
|
|
728
|
+
}
|
|
729
|
+
var files = /* @__PURE__ */ new Map();
|
|
730
|
+
var maps = /* @__PURE__ */ new Map();
|
|
731
|
+
function remember(cache, key, value) {
|
|
732
|
+
if (cache.size >= MAX_CACHED) cache.delete(cache.keys().next().value);
|
|
733
|
+
cache.set(key, value);
|
|
734
|
+
return value;
|
|
735
|
+
}
|
|
736
|
+
function toPath(file) {
|
|
737
|
+
if (file.startsWith("file://")) {
|
|
738
|
+
try {
|
|
739
|
+
return fileURLToPath(file);
|
|
740
|
+
} catch {
|
|
741
|
+
return null;
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
return isAbsolute(file) ? file : null;
|
|
745
|
+
}
|
|
746
|
+
function isApp(path) {
|
|
747
|
+
return !/[\\/]node_modules[\\/]/.test(path) && !path.startsWith("node:") && !/[\\/]@zharp[\\/]/.test(path);
|
|
748
|
+
}
|
|
749
|
+
function linesOf(path, text) {
|
|
750
|
+
if (files.has(path)) return files.get(path);
|
|
751
|
+
let content = text ?? null;
|
|
752
|
+
if (content === null) {
|
|
753
|
+
try {
|
|
754
|
+
if (statSync(path).size > MAX_FILE) return remember(files, path, null);
|
|
755
|
+
content = readFileSync(path, "utf8");
|
|
756
|
+
} catch {
|
|
757
|
+
return remember(files, path, null);
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
return remember(files, path, content.split(/\r\n|\n|\r/));
|
|
761
|
+
}
|
|
762
|
+
function mapOf(path) {
|
|
763
|
+
if (maps.has(path)) return maps.get(path);
|
|
764
|
+
const SourceMap2 = nodeModule.SourceMap;
|
|
765
|
+
const lines = linesOf(path);
|
|
766
|
+
if (!SourceMap2 || !lines) return remember(maps, path, null);
|
|
767
|
+
try {
|
|
768
|
+
let payload = null;
|
|
769
|
+
let mapPath = `${path}.map`;
|
|
770
|
+
const tail = lines.slice(-5).join("\n");
|
|
771
|
+
const url = /[#@]\s*sourceMappingURL=(\S+)\s*$/m.exec(tail)?.[1];
|
|
772
|
+
if (url?.startsWith("data:")) {
|
|
773
|
+
const base64 = /;base64,(.*)$/.exec(url)?.[1];
|
|
774
|
+
payload = base64 ? JSON.parse(Buffer.from(base64, "base64").toString("utf8")) : null;
|
|
775
|
+
mapPath = path;
|
|
776
|
+
} else {
|
|
777
|
+
if (url) mapPath = resolve(dirname(path), decodeURIComponent(url));
|
|
778
|
+
if (statSync(mapPath).size > MAX_MAP) return remember(maps, path, null);
|
|
779
|
+
payload = JSON.parse(readFileSync(mapPath, "utf8"));
|
|
780
|
+
}
|
|
781
|
+
if (!payload || !Array.isArray(payload.sources)) return remember(maps, path, null);
|
|
782
|
+
return remember(maps, path, {
|
|
783
|
+
map: new SourceMap2(payload),
|
|
784
|
+
dir: dirname(mapPath),
|
|
785
|
+
sources: payload.sources,
|
|
786
|
+
sourceRoot: typeof payload.sourceRoot === "string" ? payload.sourceRoot : "",
|
|
787
|
+
contents: Array.isArray(payload.sourcesContent) ? payload.sourcesContent : []
|
|
788
|
+
});
|
|
789
|
+
} catch {
|
|
790
|
+
return remember(maps, path, null);
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
function original(path, line, column) {
|
|
794
|
+
const loaded = mapOf(path);
|
|
795
|
+
if (!loaded) return null;
|
|
796
|
+
const entry = loaded.map.findEntry(line - 1, Math.max(0, column - 1));
|
|
797
|
+
if (!entry?.originalSource || entry.originalLine === void 0) return null;
|
|
798
|
+
const index = loaded.sources.findIndex((s) => s === entry.originalSource || entry.originalSource.endsWith(s));
|
|
799
|
+
const source = entry.originalSource.replace(/^webpack:\/\/[^/]*\//, "").replace(/^file:\/\//, "");
|
|
800
|
+
const file = isAbsolute(source) ? source : resolve(loaded.dir, loaded.sourceRoot, source);
|
|
801
|
+
return { file, line: entry.originalLine + 1, column: (entry.originalColumn ?? 0) + 1, text: index >= 0 ? loaded.contents[index] ?? null : null };
|
|
802
|
+
}
|
|
803
|
+
var FRAME = /^(\s*at (?:async )?(?:.*? \()?)((?:file:\/\/)?(?:\/|[A-Za-z]:[\\/]).*?):(\d+):(\d+)(\)?)\s*$/;
|
|
804
|
+
function sourced(stack) {
|
|
805
|
+
if (!enabled || !stack) return { stack, context: null };
|
|
806
|
+
const out = [];
|
|
807
|
+
const seen = /* @__PURE__ */ new Set();
|
|
808
|
+
let mapped = 0;
|
|
809
|
+
const lines = stack.split("\n").map((text) => {
|
|
810
|
+
const m = FRAME.exec(text);
|
|
811
|
+
if (!m) return text;
|
|
812
|
+
const path = toPath(m[2]);
|
|
813
|
+
if (!path || !isApp(path) || mapped > 40) return text;
|
|
814
|
+
let file = m[2];
|
|
815
|
+
let line = Number(m[3]);
|
|
816
|
+
let column = Number(m[4]);
|
|
817
|
+
let content = null;
|
|
818
|
+
const from = /\.(c|m)?js$/.test(path) ? original(path, line, column) : null;
|
|
819
|
+
mapped++;
|
|
820
|
+
if (from && isApp(from.file)) {
|
|
821
|
+
file = from.file;
|
|
822
|
+
line = from.line;
|
|
823
|
+
column = from.column;
|
|
824
|
+
content = linesOf(from.file, from.text);
|
|
825
|
+
text = `${m[1]}${file}:${line}:${column}${m[5]}`;
|
|
826
|
+
} else if (!from) {
|
|
827
|
+
const built = linesOf(path);
|
|
828
|
+
const tail = built ? built.slice(-5).join("\n") : "";
|
|
829
|
+
content = /[#@]\s*(?:sourceMappingURL|debugId)=/.test(tail) ? null : built;
|
|
830
|
+
}
|
|
831
|
+
const key = `${file}:${line}`;
|
|
832
|
+
if (content && out.length < MAX_FRAMES && !seen.has(key) && content[line - 1] !== void 0) {
|
|
833
|
+
seen.add(key);
|
|
834
|
+
const cut = (s) => s.length > MAX_LINE ? `${s.slice(0, MAX_LINE - 1)}\u2026` : s;
|
|
835
|
+
out.push({
|
|
836
|
+
file,
|
|
837
|
+
line,
|
|
838
|
+
pre: content.slice(Math.max(0, line - 1 - AROUND), line - 1).map(cut),
|
|
839
|
+
code: cut(content[line - 1]),
|
|
840
|
+
post: content.slice(line, line + AROUND).map(cut)
|
|
841
|
+
});
|
|
842
|
+
}
|
|
843
|
+
return text;
|
|
844
|
+
});
|
|
845
|
+
while (out.length) {
|
|
846
|
+
const json = JSON.stringify(out);
|
|
847
|
+
if (Buffer.byteLength(json) <= MAX_BYTES) return { stack: lines.join("\n"), context: json };
|
|
848
|
+
out.pop();
|
|
849
|
+
}
|
|
850
|
+
return { stack: lines.join("\n"), context: null };
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
// src/db-errors.ts
|
|
854
|
+
var SQLSTATE = {
|
|
855
|
+
"23505": "UniqueViolation",
|
|
856
|
+
"23503": "ForeignKeyViolation",
|
|
857
|
+
"23502": "NotNullViolation",
|
|
858
|
+
"23514": "CheckViolation",
|
|
859
|
+
"23P01": "ExclusionViolation",
|
|
860
|
+
"22001": "StringDataRightTruncation",
|
|
861
|
+
"22003": "NumericValueOutOfRange",
|
|
862
|
+
"22P02": "InvalidTextRepresentation",
|
|
863
|
+
"22007": "InvalidDatetimeFormat",
|
|
864
|
+
"22008": "DatetimeFieldOverflow",
|
|
865
|
+
"22012": "DivisionByZero",
|
|
866
|
+
"42P01": "UndefinedTable",
|
|
867
|
+
"42703": "UndefinedColumn",
|
|
868
|
+
"42883": "UndefinedFunction",
|
|
869
|
+
"42601": "SyntaxError",
|
|
870
|
+
"42501": "InsufficientPrivilege",
|
|
871
|
+
"40001": "SerializationFailure",
|
|
872
|
+
"40P01": "DeadlockDetected",
|
|
873
|
+
"55P03": "LockNotAvailable",
|
|
874
|
+
"57014": "QueryCanceled",
|
|
875
|
+
"53300": "TooManyConnections",
|
|
876
|
+
"08006": "ConnectionFailure",
|
|
877
|
+
"08001": "ConnectionRefused",
|
|
878
|
+
"28P01": "InvalidPassword",
|
|
879
|
+
"3D000": "InvalidCatalogName"
|
|
880
|
+
};
|
|
881
|
+
var SYSTEM_NAMES = { postgresql: "Postgres", mysql: "MySQL", mariadb: "MariaDB", mongodb: "Mongo", redis: "Redis", mssql: "SqlServer", oracle: "Oracle", sqlite: "Sqlite" };
|
|
882
|
+
function dbErrorType(system, code, name) {
|
|
883
|
+
if (code && system === "postgresql" && SQLSTATE[code]) return SQLSTATE[code];
|
|
884
|
+
if (code && /^ER_[A-Z_]+$/.test(code)) return code;
|
|
885
|
+
if (name && !/^(error|Error|DatabaseError)$/.test(name)) return name;
|
|
886
|
+
return `${SYSTEM_NAMES[system] ?? "Database"}Error`;
|
|
887
|
+
}
|
|
888
|
+
function callSiteFrames(stack) {
|
|
889
|
+
const frames = (stack ?? "").split("\n").slice(1).filter((line) => /^\s+at /.test(line)).filter((line) => !/[\\/]@opentelemetry[\\/]|[\\/]@zharp[\\/]|\(node:|\bnode:internal\b|[\\/]require-in-the-middle[\\/]|[\\/]import-in-the-middle[\\/]/.test(line));
|
|
890
|
+
const firstApp = frames.findIndex((line) => !/[\\/]node_modules[\\/]/.test(line));
|
|
891
|
+
return (firstApp > 0 ? frames.slice(firstApp) : frames).slice(0, 40);
|
|
892
|
+
}
|
|
893
|
+
var CALL_SITE = createContextKey("zharp.db.callSite");
|
|
894
|
+
function stackFrom(fn) {
|
|
895
|
+
const limit = Error.stackTraceLimit;
|
|
896
|
+
Error.stackTraceLimit = 60;
|
|
897
|
+
const holder = {};
|
|
898
|
+
Error.captureStackTrace(holder, fn);
|
|
899
|
+
Error.stackTraceLimit = limit;
|
|
900
|
+
return holder.stack;
|
|
901
|
+
}
|
|
902
|
+
var attr = (attributes, ...names) => {
|
|
903
|
+
for (const name of names) {
|
|
904
|
+
const value = attributes[name];
|
|
905
|
+
if (value !== void 0 && value !== null && value !== "") return String(value);
|
|
906
|
+
}
|
|
907
|
+
return null;
|
|
908
|
+
};
|
|
909
|
+
function reportOf(failure) {
|
|
910
|
+
const error = failure.error;
|
|
911
|
+
const code = (error?.code !== void 0 ? String(error.code) : null) ?? failure.code;
|
|
912
|
+
const type = dbErrorType(failure.system, code, error?.name);
|
|
913
|
+
const message = error?.message || failure.scrubbed?.replace(/^.*?error of type '[^']*' occurred/i, `${SYSTEM_NAMES[failure.system] ?? "Database"} error`) || "The query failed";
|
|
914
|
+
const { stack, context: context3 } = sourced([`${type}: ${message}`, ...failure.frames].join("\n"));
|
|
915
|
+
const attributes = {
|
|
916
|
+
...context3 ? { [SOURCE_CONTEXT_ATTRIBUTE]: context3 } : {},
|
|
917
|
+
"zharp.mechanism": "db",
|
|
918
|
+
"db.system": failure.system,
|
|
919
|
+
...failure.statement ? { "db.statement": failure.statement.slice(0, 4e3) } : {},
|
|
920
|
+
...failure.database ? { "db.name": failure.database } : {},
|
|
921
|
+
...code ? { "db.error.code": code } : {},
|
|
922
|
+
...error?.constraint ? { "db.error.constraint": error.constraint } : {}
|
|
923
|
+
};
|
|
924
|
+
return { type, message, stack, attributes, spanContext: failure.spanContext };
|
|
925
|
+
}
|
|
926
|
+
var LONE_WAIT_MS = 1500;
|
|
927
|
+
var MAX_PENDING = 200;
|
|
928
|
+
var DbErrorSpanProcessor = class _DbErrorSpanProcessor {
|
|
929
|
+
constructor(send) {
|
|
930
|
+
this.send = send;
|
|
931
|
+
}
|
|
932
|
+
send;
|
|
933
|
+
callSites = /* @__PURE__ */ new WeakMap();
|
|
934
|
+
/** Failures not yet reported, by trace. */
|
|
935
|
+
pending = /* @__PURE__ */ new Map();
|
|
936
|
+
onStart(span, parentContext) {
|
|
937
|
+
const attributes = span.attributes ?? {};
|
|
938
|
+
if (!attr(attributes, "db.system", "db.system.name")) return;
|
|
939
|
+
const carried = (parentContext ?? context.active()).getValue(CALL_SITE);
|
|
940
|
+
const entry = {
|
|
941
|
+
frames: callSiteFrames(carried ?? stackFrom(_DbErrorSpanProcessor.prototype.onStart))
|
|
942
|
+
};
|
|
943
|
+
this.callSites.set(span, entry);
|
|
944
|
+
const record = span.recordException.bind(span);
|
|
945
|
+
span.recordException = (exception, time) => {
|
|
946
|
+
if (entry.exception === void 0) entry.exception = exception;
|
|
947
|
+
else record(exception, time);
|
|
948
|
+
};
|
|
949
|
+
}
|
|
950
|
+
onEnd(span) {
|
|
951
|
+
const entry = this.callSites.get(span);
|
|
952
|
+
if (entry && span.status.code === SpanStatusCode.ERROR) {
|
|
953
|
+
const attributes = span.attributes ?? {};
|
|
954
|
+
const exception = entry.exception;
|
|
955
|
+
const failure = {
|
|
956
|
+
spanContext: span.spanContext(),
|
|
957
|
+
traceId: span.spanContext().traceId,
|
|
958
|
+
system: attr(attributes, "db.system", "db.system.name") ?? "database",
|
|
959
|
+
statement: attr(attributes, "db.statement", "db.query.text"),
|
|
960
|
+
database: attr(attributes, "db.name", "db.namespace"),
|
|
961
|
+
code: attr(attributes, "error.type", "db.response.status_code"),
|
|
962
|
+
frames: entry.frames,
|
|
963
|
+
scrubbed: typeof exception === "string" ? exception : exception?.message ?? span.status.message ?? null,
|
|
964
|
+
...exception instanceof Error ? { error: exception } : {}
|
|
965
|
+
};
|
|
966
|
+
this.add(failure);
|
|
967
|
+
}
|
|
968
|
+
const root = span.kind === SpanKind.SERVER || !span.parentSpanContext || !!span.parentSpanContext.isRemote;
|
|
969
|
+
if (root) {
|
|
970
|
+
const traceId = span.spanContext().traceId;
|
|
971
|
+
if (!this.pending.has(traceId)) return;
|
|
972
|
+
if (entry || span.status.code === SpanStatusCode.ERROR) setTimeout(() => this.flush(traceId), LONE_WAIT_MS).unref?.();
|
|
973
|
+
else this.flush(traceId);
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
add(failure) {
|
|
977
|
+
const list = this.pending.get(failure.traceId) ?? [];
|
|
978
|
+
list.push(failure);
|
|
979
|
+
this.pending.set(failure.traceId, list);
|
|
980
|
+
if (this.pending.size > MAX_PENDING) this.flush(this.pending.keys().next().value);
|
|
981
|
+
}
|
|
982
|
+
/** The driver's error, seen by the query wrapper: joined to the trace's latest failure. */
|
|
983
|
+
attach(traceId, error) {
|
|
984
|
+
if (!traceId || !(error instanceof Error)) return;
|
|
985
|
+
const list = this.pending.get(traceId);
|
|
986
|
+
if (!list || list.some((f) => f.error === error)) return;
|
|
987
|
+
const failure = [...list].reverse().find((f) => !f.error && !f.done);
|
|
988
|
+
if (failure) failure.error = error;
|
|
989
|
+
}
|
|
990
|
+
/**
|
|
991
|
+
* `error` is being reported (by a framework's handler, as unhandled, or by captureError): the
|
|
992
|
+
* failed query it came from, if any, so its details go into that one report and it isn't sent
|
|
993
|
+
* again. Matched by the error itself, or what wraps it (`driverError`, `cause`); `latest` also
|
|
994
|
+
* takes the request's latest failure whose driver error was never seen.
|
|
995
|
+
*/
|
|
996
|
+
consume(traceId, error, latest = false) {
|
|
997
|
+
const inner = (candidate) => {
|
|
998
|
+
if (!candidate || typeof candidate !== "object") return [];
|
|
999
|
+
const c = candidate;
|
|
1000
|
+
return [candidate, c.driverError, c.cause, c.originalError].filter(Boolean);
|
|
1001
|
+
};
|
|
1002
|
+
const wanted2 = inner(error);
|
|
1003
|
+
const lists = traceId ? [this.pending.get(traceId) ?? []] : [...this.pending.values()];
|
|
1004
|
+
for (const list of lists) {
|
|
1005
|
+
const failure = list.find((f) => !f.done && f.error && wanted2.includes(f.error)) ?? (latest && traceId ? [...list].reverse().find((f) => !f.done && !f.error) : void 0);
|
|
1006
|
+
if (failure) {
|
|
1007
|
+
failure.done = true;
|
|
1008
|
+
return failure;
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
return null;
|
|
1012
|
+
}
|
|
1013
|
+
flush(traceId) {
|
|
1014
|
+
const list = this.pending.get(traceId);
|
|
1015
|
+
if (!list) return;
|
|
1016
|
+
this.pending.delete(traceId);
|
|
1017
|
+
for (const failure of list) if (!failure.done) this.send(failure);
|
|
1018
|
+
}
|
|
1019
|
+
forceFlush() {
|
|
1020
|
+
for (const traceId of [...this.pending.keys()]) this.flush(traceId);
|
|
1021
|
+
return Promise.resolve();
|
|
1022
|
+
}
|
|
1023
|
+
shutdown() {
|
|
1024
|
+
return this.forceFlush();
|
|
1025
|
+
}
|
|
1026
|
+
};
|
|
1027
|
+
var DbDriverErrorsInstrumentation = class extends InstrumentationBase {
|
|
1028
|
+
constructor(onError) {
|
|
1029
|
+
super("@zharp/node/db-driver-errors", VERSION, {});
|
|
1030
|
+
this.onError = onError;
|
|
1031
|
+
}
|
|
1032
|
+
onError;
|
|
1033
|
+
init() {
|
|
1034
|
+
const onError = (traceId, err) => {
|
|
1035
|
+
try {
|
|
1036
|
+
this.onError(traceId, err);
|
|
1037
|
+
} catch {
|
|
1038
|
+
}
|
|
1039
|
+
};
|
|
1040
|
+
const wrapQuery = (original2) => {
|
|
1041
|
+
const run = (self, args) => {
|
|
1042
|
+
const traceId = trace.getActiveSpan()?.spanContext().traceId;
|
|
1043
|
+
const callback = args.findIndex((a) => typeof a === "function");
|
|
1044
|
+
if (callback >= 0) {
|
|
1045
|
+
const cb = args[callback];
|
|
1046
|
+
args[callback] = function(err, ...rest) {
|
|
1047
|
+
if (err) onError(traceId, err);
|
|
1048
|
+
return cb.call(this, err, ...rest);
|
|
1049
|
+
};
|
|
1050
|
+
return original2.apply(self, args);
|
|
1051
|
+
}
|
|
1052
|
+
const result = original2.apply(self, args);
|
|
1053
|
+
if (!result || typeof result.then !== "function" || typeof result.submit === "function") return result;
|
|
1054
|
+
result.then(void 0, (err) => onError(traceId, err));
|
|
1055
|
+
return result;
|
|
1056
|
+
};
|
|
1057
|
+
return function query(...args) {
|
|
1058
|
+
const active = context.active();
|
|
1059
|
+
if (active.getValue(CALL_SITE) !== void 0) return run(this, args);
|
|
1060
|
+
return context.with(active.setValue(CALL_SITE, stackFrom(query)), () => run(this, args));
|
|
1061
|
+
};
|
|
1062
|
+
};
|
|
1063
|
+
const patch = (moduleExports) => {
|
|
1064
|
+
for (const target of [moduleExports?.Client?.prototype, moduleExports?.Pool?.prototype]) {
|
|
1065
|
+
if (target?.query && !target.query.__zharpWrapped) {
|
|
1066
|
+
const wrapped = wrapQuery(target.query);
|
|
1067
|
+
wrapped.__zharpWrapped = true;
|
|
1068
|
+
wrapped.__zharpOriginal = target.query;
|
|
1069
|
+
target.query = wrapped;
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
return moduleExports;
|
|
1073
|
+
};
|
|
1074
|
+
const unpatch = (moduleExports) => {
|
|
1075
|
+
for (const target of [moduleExports?.Client?.prototype, moduleExports?.Pool?.prototype]) {
|
|
1076
|
+
if (target?.query?.__zharpOriginal) target.query = target.query.__zharpOriginal;
|
|
1077
|
+
}
|
|
1078
|
+
};
|
|
1079
|
+
return [new InstrumentationNodeModuleDefinition("pg", [">=8 <9"], patch, unpatch)];
|
|
1080
|
+
}
|
|
1081
|
+
};
|
|
1082
|
+
|
|
1083
|
+
// src/framework-errors.ts
|
|
1084
|
+
import { InstrumentationBase as InstrumentationBase2, InstrumentationNodeModuleDefinition as InstrumentationNodeModuleDefinition2, InstrumentationNodeModuleFile } from "@opentelemetry/instrumentation";
|
|
1085
|
+
function statusOf(error) {
|
|
1086
|
+
if (!error || typeof error !== "object") return 500;
|
|
1087
|
+
const e = error;
|
|
1088
|
+
try {
|
|
1089
|
+
if (typeof e.getStatus === "function") {
|
|
1090
|
+
const status = Number(e.getStatus());
|
|
1091
|
+
if (Number.isFinite(status)) return status;
|
|
1092
|
+
}
|
|
1093
|
+
} catch {
|
|
1094
|
+
}
|
|
1095
|
+
for (const value of [e.status, e.statusCode]) {
|
|
1096
|
+
const status = Number(value);
|
|
1097
|
+
if (Number.isInteger(status) && status >= 100 && status < 600) return status;
|
|
1098
|
+
}
|
|
1099
|
+
return 500;
|
|
1100
|
+
}
|
|
1101
|
+
var WRAPPED = /* @__PURE__ */ Symbol.for("zharp.frameworkErrors");
|
|
1102
|
+
var FrameworkErrorsInstrumentation = class extends InstrumentationBase2 {
|
|
1103
|
+
constructor(sink) {
|
|
1104
|
+
super("@zharp/node/framework-errors", VERSION, {});
|
|
1105
|
+
this.sink = sink;
|
|
1106
|
+
}
|
|
1107
|
+
sink;
|
|
1108
|
+
init() {
|
|
1109
|
+
const report = (error, mechanism) => {
|
|
1110
|
+
try {
|
|
1111
|
+
if (statusOf(error) >= 500) this.sink(error, mechanism);
|
|
1112
|
+
} catch {
|
|
1113
|
+
}
|
|
1114
|
+
};
|
|
1115
|
+
const nest = new InstrumentationNodeModuleFile(
|
|
1116
|
+
"@nestjs/core/exceptions/exceptions-handler.js",
|
|
1117
|
+
[">=8 <13"],
|
|
1118
|
+
(moduleExports) => {
|
|
1119
|
+
const proto = moduleExports?.ExceptionsHandler?.prototype;
|
|
1120
|
+
if (proto?.next && !proto.next[WRAPPED]) {
|
|
1121
|
+
const original2 = proto.next;
|
|
1122
|
+
const next = function(exception, ...rest) {
|
|
1123
|
+
report(exception, "nestjs");
|
|
1124
|
+
return original2.call(this, exception, ...rest);
|
|
1125
|
+
};
|
|
1126
|
+
next[WRAPPED] = original2;
|
|
1127
|
+
proto.next = next;
|
|
1128
|
+
}
|
|
1129
|
+
return moduleExports;
|
|
1130
|
+
},
|
|
1131
|
+
(moduleExports) => {
|
|
1132
|
+
const proto = moduleExports?.ExceptionsHandler?.prototype;
|
|
1133
|
+
if (proto?.next?.[WRAPPED]) proto.next = proto.next[WRAPPED];
|
|
1134
|
+
}
|
|
1135
|
+
);
|
|
1136
|
+
const finalhandler = new InstrumentationNodeModuleDefinition2(
|
|
1137
|
+
"finalhandler",
|
|
1138
|
+
[">=1 <3"],
|
|
1139
|
+
(moduleExports) => {
|
|
1140
|
+
if (typeof moduleExports !== "function" || moduleExports[WRAPPED]) return moduleExports;
|
|
1141
|
+
const original2 = moduleExports;
|
|
1142
|
+
const wrapped = function(...args) {
|
|
1143
|
+
const done = original2.apply(this, args);
|
|
1144
|
+
return function(err, ...rest) {
|
|
1145
|
+
if (err) report(err, "express");
|
|
1146
|
+
return done.call(this, err, ...rest);
|
|
1147
|
+
};
|
|
1148
|
+
};
|
|
1149
|
+
Object.assign(wrapped, original2);
|
|
1150
|
+
wrapped[WRAPPED] = original2;
|
|
1151
|
+
return wrapped;
|
|
1152
|
+
},
|
|
1153
|
+
(moduleExports) => moduleExports?.[WRAPPED] ?? moduleExports
|
|
1154
|
+
);
|
|
1155
|
+
return [new InstrumentationNodeModuleDefinition2("@nestjs/core", [">=8 <13"], void 0, void 0, [nest]), finalhandler];
|
|
1156
|
+
}
|
|
1157
|
+
};
|
|
1158
|
+
var RecordedExceptionsProcessor = class {
|
|
1159
|
+
constructor(report) {
|
|
1160
|
+
this.report = report;
|
|
1161
|
+
}
|
|
1162
|
+
report;
|
|
1163
|
+
pending = /* @__PURE__ */ new Map();
|
|
1164
|
+
onStart(span) {
|
|
1165
|
+
const scope = span.instrumentationScope?.name ?? span.instrumentationLibrary?.name ?? "";
|
|
1166
|
+
if (!scope.startsWith("@opentelemetry/instrumentation-") && scope !== "next.js") return;
|
|
1167
|
+
if (span.attributes?.["db.system"] || span.attributes?.["db.system.name"]) return;
|
|
1168
|
+
const original2 = span.recordException.bind(span);
|
|
1169
|
+
span.recordException = (exception, time) => {
|
|
1170
|
+
try {
|
|
1171
|
+
if (!exception || typeof exception !== "object") return original2(exception, time);
|
|
1172
|
+
const name = typeof exception.name === "string" && exception.name !== "error" ? exception.name : exception.constructor?.name || "Error";
|
|
1173
|
+
span.addEvent("exception", {
|
|
1174
|
+
"exception.type": name,
|
|
1175
|
+
"exception.message": String(exception.message ?? ""),
|
|
1176
|
+
...typeof exception.stack === "string" ? { "exception.stacktrace": exception.stack } : {},
|
|
1177
|
+
"zharp.deferred": "true"
|
|
1178
|
+
}, time);
|
|
1179
|
+
const traceId = span.spanContext().traceId;
|
|
1180
|
+
const list = this.pending.get(traceId) ?? [];
|
|
1181
|
+
if (!list.some((p) => p.error === exception)) list.push({ error: exception, spanContext: span.spanContext(), scope: mechanismOf(scope) });
|
|
1182
|
+
this.pending.set(traceId, list);
|
|
1183
|
+
if (this.pending.size > 500) this.pending.delete(this.pending.keys().next().value);
|
|
1184
|
+
} catch {
|
|
1185
|
+
original2(exception, time);
|
|
1186
|
+
}
|
|
1187
|
+
};
|
|
1188
|
+
}
|
|
1189
|
+
onEnd(span) {
|
|
1190
|
+
const parent = span.parentSpanContext;
|
|
1191
|
+
const isRoot = span.kind === 1 || !parent || parent.isRemote;
|
|
1192
|
+
if (!isRoot) return;
|
|
1193
|
+
const traceId = span.spanContext().traceId;
|
|
1194
|
+
const list = this.pending.get(traceId);
|
|
1195
|
+
if (!list) return;
|
|
1196
|
+
this.pending.delete(traceId);
|
|
1197
|
+
const status = Number(span.attributes?.["http.response.status_code"] ?? span.attributes?.["http.status_code"]);
|
|
1198
|
+
const failed = Number.isFinite(status) && status > 0 ? status >= 500 : span.status?.code === 2;
|
|
1199
|
+
if (!failed) return;
|
|
1200
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1201
|
+
for (const p of list) {
|
|
1202
|
+
if (seen.has(p.error)) continue;
|
|
1203
|
+
seen.add(p.error);
|
|
1204
|
+
if (statusOf(p.error) < 500) continue;
|
|
1205
|
+
this.report(p.error, p.spanContext, p.scope);
|
|
1206
|
+
break;
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
forceFlush() {
|
|
1210
|
+
return Promise.resolve();
|
|
1211
|
+
}
|
|
1212
|
+
shutdown() {
|
|
1213
|
+
this.pending.clear();
|
|
1214
|
+
return Promise.resolve();
|
|
1215
|
+
}
|
|
1216
|
+
};
|
|
1217
|
+
function mechanismOf(scope) {
|
|
1218
|
+
const name = scope.replace("@opentelemetry/instrumentation-", "").replace(/-core$/, "");
|
|
1219
|
+
if (name === "router") return "express";
|
|
1220
|
+
return name === "next.js" ? "nextjs" : name;
|
|
1221
|
+
}
|
|
1222
|
+
|
|
657
1223
|
// src/urls.ts
|
|
658
1224
|
var URL_KEYS = ["url.full", "http.url", "http.target"];
|
|
659
1225
|
var UrlRedactionSpanProcessor = class {
|
|
@@ -689,7 +1255,7 @@ var UrlRedactionSpanProcessor = class {
|
|
|
689
1255
|
};
|
|
690
1256
|
|
|
691
1257
|
// src/context.ts
|
|
692
|
-
import { context as otelContext, propagation, trace } from "@opentelemetry/api";
|
|
1258
|
+
import { context as otelContext, propagation, trace as trace2 } from "@opentelemetry/api";
|
|
693
1259
|
var BAGGAGE_KEYS = ["enduser.id", "session.id"];
|
|
694
1260
|
function userAttributes(user) {
|
|
695
1261
|
const out = { "enduser.id": String(user.id) };
|
|
@@ -706,7 +1272,7 @@ var ContextStore = class {
|
|
|
706
1272
|
localRoots = /* @__PURE__ */ new Map();
|
|
707
1273
|
/** Set the user for the request in progress, or for the whole process outside one. */
|
|
708
1274
|
setUser(user) {
|
|
709
|
-
const span =
|
|
1275
|
+
const span = trace2.getActiveSpan();
|
|
710
1276
|
const traceId = span?.spanContext().traceId;
|
|
711
1277
|
if (!span || !traceId) {
|
|
712
1278
|
this.globalUser = user;
|
|
@@ -726,7 +1292,7 @@ var ContextStore = class {
|
|
|
726
1292
|
return user ? { ...this.tags, ...user } : { ...this.tags };
|
|
727
1293
|
}
|
|
728
1294
|
noteStart(span, parent) {
|
|
729
|
-
const parentSpan =
|
|
1295
|
+
const parentSpan = trace2.getSpanContext(parent);
|
|
730
1296
|
if (!parentSpan || parentSpan.isRemote) {
|
|
731
1297
|
const { traceId, spanId } = span.spanContext();
|
|
732
1298
|
if (!this.localRoots.has(traceId)) this.localRoots.set(traceId, { spanId, span });
|
|
@@ -779,7 +1345,7 @@ var ContextLogProcessor = class {
|
|
|
779
1345
|
onEmit(record, ctx) {
|
|
780
1346
|
try {
|
|
781
1347
|
const active = ctx ?? otelContext.active();
|
|
782
|
-
const traceId = record.spanContext?.traceId ??
|
|
1348
|
+
const traceId = record.spanContext?.traceId ?? trace2.getSpanContext(active)?.traceId;
|
|
783
1349
|
const add = { ...this.store.attributesFor(traceId), ...fromBaggage(active) };
|
|
784
1350
|
for (const [key, value] of Object.entries(add)) {
|
|
785
1351
|
if (record.attributes[key] === void 0) record.setAttribute(key, value);
|
|
@@ -848,11 +1414,11 @@ var emitting = false;
|
|
|
848
1414
|
function captureConsole(logger) {
|
|
849
1415
|
const originals = /* @__PURE__ */ new Map();
|
|
850
1416
|
for (const [method, severityNumber, severityText] of LEVELS) {
|
|
851
|
-
const
|
|
852
|
-
if (typeof
|
|
853
|
-
originals.set(method,
|
|
1417
|
+
const original2 = console[method];
|
|
1418
|
+
if (typeof original2 !== "function" || original2.__zharp) continue;
|
|
1419
|
+
originals.set(method, original2);
|
|
854
1420
|
const patched = function(...args) {
|
|
855
|
-
quiet(() =>
|
|
1421
|
+
quiet(() => original2.apply(this ?? console, args));
|
|
856
1422
|
if (emitting) return;
|
|
857
1423
|
emitting = true;
|
|
858
1424
|
try {
|
|
@@ -869,12 +1435,12 @@ function captureConsole(logger) {
|
|
|
869
1435
|
console[method] = patched;
|
|
870
1436
|
}
|
|
871
1437
|
return () => {
|
|
872
|
-
for (const [method,
|
|
1438
|
+
for (const [method, original2] of originals) console[method] = original2;
|
|
873
1439
|
};
|
|
874
1440
|
}
|
|
875
1441
|
|
|
876
1442
|
// src/stdout.ts
|
|
877
|
-
import { context as otelContext2, isSpanContextValid, SeverityNumber as SeverityNumber2, trace as
|
|
1443
|
+
import { context as otelContext2, isSpanContextValid, SeverityNumber as SeverityNumber2, trace as trace3 } from "@opentelemetry/api";
|
|
878
1444
|
var LEVELS2 = {
|
|
879
1445
|
trace: [SeverityNumber2.TRACE, "TRACE"],
|
|
880
1446
|
verbose: [SeverityNumber2.DEBUG, "DEBUG"],
|
|
@@ -896,7 +1462,7 @@ var NUMERIC = [[60, "fatal"], [50, "error"], [40, "warn"], [30, "info"], [20, "d
|
|
|
896
1462
|
var ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]/g;
|
|
897
1463
|
var NEST = /^\[Nest\]\s+\d+\s+-\s+.*?\s+(LOG|ERROR|WARN|DEBUG|VERBOSE|FATAL)\s+(?:\[([^\]]+)\]\s+)?([\s\S]*)$/;
|
|
898
1464
|
var WORD = /(?:^|[\s[(|:=])(trace|verbose|debug|info|notice|warn(?:ing)?|err(?:or)?|crit(?:ical)?|fatal|emerg|alert)(?=$|[\s\]):|,])/i;
|
|
899
|
-
var
|
|
1465
|
+
var MAX_LINE2 = 32 * 1024;
|
|
900
1466
|
var FLUSH_MS = 200;
|
|
901
1467
|
function levelOf(value) {
|
|
902
1468
|
if (typeof value === "number") {
|
|
@@ -949,13 +1515,13 @@ function captureOutput(logger) {
|
|
|
949
1515
|
[process.stderr, "stderr", LEVELS2.warn]
|
|
950
1516
|
]) {
|
|
951
1517
|
if (!stream || typeof stream.write !== "function" || stream.write.__zharp) continue;
|
|
952
|
-
const
|
|
1518
|
+
const original2 = stream.write;
|
|
953
1519
|
let pending = "";
|
|
954
1520
|
let pendingContext;
|
|
955
1521
|
let timer;
|
|
956
1522
|
const emitLine = (line, ctx) => {
|
|
957
1523
|
if (!line.trim() || line.includes("[Zharp]") || alreadySent(line)) return;
|
|
958
|
-
const parsed2 = parseLine(line.length >
|
|
1524
|
+
const parsed2 = parseLine(line.length > MAX_LINE2 ? line.slice(0, MAX_LINE2) : line);
|
|
959
1525
|
if (!parsed2.body.trim()) return;
|
|
960
1526
|
const [severityNumber, severityText] = parsed2.level ?? fallback;
|
|
961
1527
|
quiet(() => logger.emit({
|
|
@@ -985,7 +1551,7 @@ function captureOutput(logger) {
|
|
|
985
1551
|
const ctx = pendingContext;
|
|
986
1552
|
if (pending) pendingContext = otelContext2.active();
|
|
987
1553
|
for (const line of lines) emitLine(line, ctx);
|
|
988
|
-
if (pending.length >
|
|
1554
|
+
if (pending.length > MAX_LINE2) flush();
|
|
989
1555
|
else if (pending && !timer) {
|
|
990
1556
|
timer = setTimeout(flush, FLUSH_MS);
|
|
991
1557
|
timer.unref?.();
|
|
@@ -996,14 +1562,14 @@ function captureOutput(logger) {
|
|
|
996
1562
|
take(chunk, encoding);
|
|
997
1563
|
} catch {
|
|
998
1564
|
}
|
|
999
|
-
return
|
|
1565
|
+
return original2.call(this ?? stream, chunk, encoding, callback);
|
|
1000
1566
|
};
|
|
1001
1567
|
patched.__zharp = true;
|
|
1002
1568
|
stream.write = patched;
|
|
1003
1569
|
undo.push(() => {
|
|
1004
1570
|
if (timer) clearTimeout(timer);
|
|
1005
1571
|
if (pending) flush();
|
|
1006
|
-
stream.write =
|
|
1572
|
+
stream.write = original2;
|
|
1007
1573
|
});
|
|
1008
1574
|
}
|
|
1009
1575
|
return () => undo.forEach((fn) => fn());
|
|
@@ -1012,25 +1578,25 @@ function stampOutput() {
|
|
|
1012
1578
|
const undo = [];
|
|
1013
1579
|
for (const stream of [process.stdout, process.stderr]) {
|
|
1014
1580
|
if (!stream || typeof stream.write !== "function" || stream.write.__zharpStamp) continue;
|
|
1015
|
-
const
|
|
1581
|
+
const original2 = stream.write;
|
|
1016
1582
|
const patched = function(chunk, encoding, callback) {
|
|
1017
1583
|
let out = chunk;
|
|
1018
1584
|
try {
|
|
1019
1585
|
out = stamped(chunk, encoding);
|
|
1020
1586
|
} catch {
|
|
1021
1587
|
}
|
|
1022
|
-
return
|
|
1588
|
+
return original2.call(this ?? stream, out, encoding, callback);
|
|
1023
1589
|
};
|
|
1024
1590
|
patched.__zharpStamp = true;
|
|
1025
1591
|
stream.write = patched;
|
|
1026
1592
|
undo.push(() => {
|
|
1027
|
-
stream.write =
|
|
1593
|
+
stream.write = original2;
|
|
1028
1594
|
});
|
|
1029
1595
|
}
|
|
1030
1596
|
return () => undo.forEach((fn) => fn());
|
|
1031
1597
|
}
|
|
1032
1598
|
function stamped(chunk, encoding) {
|
|
1033
|
-
const span =
|
|
1599
|
+
const span = trace3.getActiveSpan()?.spanContext();
|
|
1034
1600
|
if (!span || !isSpanContextValid(span)) return chunk;
|
|
1035
1601
|
const isBytes = chunk instanceof Uint8Array;
|
|
1036
1602
|
if (typeof chunk !== "string" && !isBytes) return chunk;
|
|
@@ -1076,7 +1642,7 @@ function stampLine(line, traceId, spanId) {
|
|
|
1076
1642
|
|
|
1077
1643
|
// ../../internal/src/debug-ids.ts
|
|
1078
1644
|
var DEBUG_IDS_ATTRIBUTE = "zharp.debug_ids";
|
|
1079
|
-
var
|
|
1645
|
+
var files2 = /* @__PURE__ */ new Map();
|
|
1080
1646
|
var parsed = /* @__PURE__ */ new Set();
|
|
1081
1647
|
function registry() {
|
|
1082
1648
|
const g2 = typeof globalThis !== "undefined" ? globalThis : void 0;
|
|
@@ -1115,7 +1681,7 @@ function refresh() {
|
|
|
1115
1681
|
for (const line of stack.split("\n")) {
|
|
1116
1682
|
const file = frameFile(line);
|
|
1117
1683
|
if (file) {
|
|
1118
|
-
|
|
1684
|
+
files2.set(file, id);
|
|
1119
1685
|
break;
|
|
1120
1686
|
}
|
|
1121
1687
|
}
|
|
@@ -1125,10 +1691,10 @@ function debugIdsFor(stack) {
|
|
|
1125
1691
|
if (!stack) return void 0;
|
|
1126
1692
|
try {
|
|
1127
1693
|
refresh();
|
|
1128
|
-
if (
|
|
1694
|
+
if (files2.size === 0) return void 0;
|
|
1129
1695
|
let out;
|
|
1130
1696
|
for (const file of stackFiles(stack)) {
|
|
1131
|
-
const id =
|
|
1697
|
+
const id = files2.get(file);
|
|
1132
1698
|
if (id) (out ??= {})[file] = id;
|
|
1133
1699
|
}
|
|
1134
1700
|
return out;
|
|
@@ -1211,18 +1777,18 @@ function exceptionAttributes(error, handled) {
|
|
|
1211
1777
|
const cause = error.cause;
|
|
1212
1778
|
if (cause instanceof Error && cause.stack) stack += `
|
|
1213
1779
|
Caused by: ${cause.stack}`;
|
|
1780
|
+
const { stack: readable, context: context3 } = sourced(stack);
|
|
1214
1781
|
return {
|
|
1215
1782
|
"exception.type": type,
|
|
1216
1783
|
"exception.message": message,
|
|
1217
|
-
"exception.stacktrace":
|
|
1784
|
+
"exception.stacktrace": readable,
|
|
1218
1785
|
"zharp.handled": handled ? "true" : "false",
|
|
1219
|
-
|
|
1786
|
+
// From the stack as it ran: frames resolved here keep their bundle's ID for uploaded maps.
|
|
1787
|
+
...debugIdAttributes(stack),
|
|
1788
|
+
...context3 ? { [SOURCE_CONTEXT_ATTRIBUTE]: context3 } : {}
|
|
1220
1789
|
};
|
|
1221
1790
|
}
|
|
1222
1791
|
|
|
1223
|
-
// src/version.ts
|
|
1224
|
-
var VERSION = "0.3.0";
|
|
1225
|
-
|
|
1226
1792
|
// src/zharp.ts
|
|
1227
1793
|
var DEFAULT_ENDPOINT = "https://api.zharp.io/api/v1/otlp";
|
|
1228
1794
|
var EXIT_FLUSH_MS = 2e3;
|
|
@@ -1237,6 +1803,8 @@ var ZharpNode = class {
|
|
|
1237
1803
|
tracing = true;
|
|
1238
1804
|
/** Errors already sent, so one that is both rejected and then thrown is reported once. */
|
|
1239
1805
|
reported = /* @__PURE__ */ new WeakSet();
|
|
1806
|
+
/** Failed queries waiting to be reported, once and with their call site. */
|
|
1807
|
+
dbErrors = null;
|
|
1240
1808
|
/** `Zharp.log.info("Order placed", { orderId })` — and debug, warn, error, fatal, trace. */
|
|
1241
1809
|
log = {
|
|
1242
1810
|
trace: (m, a) => this.emit("trace", m, a),
|
|
@@ -1295,8 +1863,15 @@ var ZharpNode = class {
|
|
|
1295
1863
|
registerEsmHook();
|
|
1296
1864
|
const headers = { Authorization: `Bearer ${key}` };
|
|
1297
1865
|
const exporterOptions = { headers, compression: "gzip" };
|
|
1866
|
+
setSourceContext(switchOn(options.captureSourceContext, "ZHARP_CAPTURE_SOURCE_CONTEXT", true));
|
|
1867
|
+
const queryErrors = tracing && switchOn(options.captureQueryErrors, "ZHARP_CAPTURE_QUERY_ERRORS", true);
|
|
1868
|
+
this.dbErrors = queryErrors ? new DbErrorSpanProcessor((failure) => this.sendQueryError(failure, true, "error", { "zharp.mechanism": "db" })) : null;
|
|
1298
1869
|
this.spanProcessors = tracing ? [
|
|
1299
1870
|
new ContextSpanProcessor(this.store),
|
|
1871
|
+
// Before the database processor: a request that failed claims its query's error first.
|
|
1872
|
+
...options.captureUncaught !== false ? [new RecordedExceptionsProcessor((error, spanContext, mechanism) => context2.with(trace4.setSpanContext(context2.active(), spanContext), () => this.report(error, false, "error", { "zharp.mechanism": mechanism }, true)))] : [],
|
|
1873
|
+
// Before the exporter: it keeps the query's scrubbed exception off the span.
|
|
1874
|
+
...this.dbErrors ? [this.dbErrors] : [],
|
|
1300
1875
|
new UrlRedactionSpanProcessor(),
|
|
1301
1876
|
new DebugIdSpanProcessor(),
|
|
1302
1877
|
new BatchSpanProcessor({ exporter: new OTLPTraceExporter({ ...exporterOptions, url: `${endpoint}/v1/traces` }) })
|
|
@@ -1321,6 +1896,10 @@ var ZharpNode = class {
|
|
|
1321
1896
|
propagators: [new W3CTraceContextPropagator(), new W3CBaggagePropagator()]
|
|
1322
1897
|
});
|
|
1323
1898
|
const bodies = bodySettings(options.captureBodies, nodeEnv("ZHARP_CAPTURE_BODIES"));
|
|
1899
|
+
const headerCapture = headerSettings(options.captureHeaders, nodeEnv("ZHARP_CAPTURE_HEADERS"));
|
|
1900
|
+
const ownHttp = options.instrumentations?.["@opentelemetry/instrumentation-http"];
|
|
1901
|
+
const withBodies = bodies ? withBodyCapture(bodies, ownHttp) : ownHttp;
|
|
1902
|
+
const httpConfig = headerCapture ? withHeaderCapture(headerCapture, withBodies) : withBodies;
|
|
1324
1903
|
const rate = typeof options.sampleRate === "number" ? Math.min(1, Math.max(0, options.sampleRate)) : 1;
|
|
1325
1904
|
this.sdk = new NodeSDK({
|
|
1326
1905
|
resource,
|
|
@@ -1341,10 +1920,10 @@ var ZharpNode = class {
|
|
|
1341
1920
|
"@opentelemetry/instrumentation-fs": { enabled: false },
|
|
1342
1921
|
...options.instrumentations,
|
|
1343
1922
|
...bridges,
|
|
1344
|
-
...
|
|
1345
|
-
"@opentelemetry/instrumentation-http": withBodyCapture(bodies, options.instrumentations?.["@opentelemetry/instrumentation-http"])
|
|
1346
|
-
}
|
|
1923
|
+
...httpConfig && { "@opentelemetry/instrumentation-http": httpConfig }
|
|
1347
1924
|
}) : logsOnlyInstrumentations({ ...options, instrumentations: { ...options.instrumentations, ...bridges } }),
|
|
1925
|
+
...this.dbErrors ? [new DbDriverErrorsInstrumentation((traceId, error) => this.dbErrors?.attach(traceId, error))] : [],
|
|
1926
|
+
...tracing && options.captureUncaught !== false ? [new FrameworkErrorsInstrumentation((error, mechanism) => this.report(error, false, "error", { "zharp.mechanism": mechanism }, true))] : [],
|
|
1348
1927
|
...options.extraInstrumentations ?? []
|
|
1349
1928
|
]
|
|
1350
1929
|
});
|
|
@@ -1392,16 +1971,36 @@ var ZharpNode = class {
|
|
|
1392
1971
|
captureError(error, attributes) {
|
|
1393
1972
|
this.report(error, true, "error", attributes);
|
|
1394
1973
|
}
|
|
1974
|
+
/**
|
|
1975
|
+
* Next.js (15+): errors a route handler, server component, server action or middleware threw,
|
|
1976
|
+
* which Next answers with an error page and only prints. Export it from instrumentation.ts:
|
|
1977
|
+
*
|
|
1978
|
+
* export const onRequestError = Zharp.onRequestError;
|
|
1979
|
+
*
|
|
1980
|
+
* Each is reported once as a crash, with the request's path, method and route. A bound function,
|
|
1981
|
+
* so it can be exported as it is.
|
|
1982
|
+
*/
|
|
1983
|
+
onRequestError = (error, request, context3) => {
|
|
1984
|
+
this.report(error, false, "error", {
|
|
1985
|
+
"zharp.mechanism": "nextjs",
|
|
1986
|
+
...request?.method ? { "http.request.method": request.method } : {},
|
|
1987
|
+
...request?.path ? { "url.path": request.path } : {},
|
|
1988
|
+
...context3?.routePath ? { "http.route": context3.routePath } : {},
|
|
1989
|
+
...context3?.routeType ? { "next.route_type": context3.routeType } : {},
|
|
1990
|
+
...context3?.routerKind ? { "next.router_kind": context3.routerKind } : {},
|
|
1991
|
+
...context3?.renderSource ? { "next.render_source": context3.renderSource } : {}
|
|
1992
|
+
}, true);
|
|
1993
|
+
};
|
|
1395
1994
|
/**
|
|
1396
1995
|
* Run `fn` inside a span named `name`, which ends when `fn` returns or its promise settles. A
|
|
1397
1996
|
* throw or rejection marks the span as failed and is passed on unchanged.
|
|
1398
1997
|
*/
|
|
1399
1998
|
startSpan(name, fn, options = {}) {
|
|
1400
|
-
if (!this.tracing) return fn(
|
|
1401
|
-
const tracer =
|
|
1999
|
+
if (!this.tracing) return fn(trace4.wrapSpanContext(trace4.getActiveSpan()?.spanContext() ?? INVALID_SPAN_CONTEXT));
|
|
2000
|
+
const tracer = trace4.getTracer("@zharp/node", VERSION);
|
|
1402
2001
|
return tracer.startActiveSpan(name, options, (span) => {
|
|
1403
2002
|
const fail = (error) => {
|
|
1404
|
-
span.setStatus({ code:
|
|
2003
|
+
span.setStatus({ code: SpanStatusCode2.ERROR, message: asError(error).message });
|
|
1405
2004
|
span.end();
|
|
1406
2005
|
};
|
|
1407
2006
|
let result;
|
|
@@ -1431,7 +2030,7 @@ var ZharpNode = class {
|
|
|
1431
2030
|
async flush(timeoutMs = 5e3) {
|
|
1432
2031
|
const all = Promise.all([...this.spanProcessors, ...this.logProcessors].map((p) => p.forceFlush().catch(() => {
|
|
1433
2032
|
})));
|
|
1434
|
-
await Promise.race([all, new Promise((
|
|
2033
|
+
await Promise.race([all, new Promise((resolve2) => setTimeout(resolve2, timeoutMs).unref())]);
|
|
1435
2034
|
}
|
|
1436
2035
|
/** Flush, stop, and put back everything that was patched. */
|
|
1437
2036
|
async shutdown() {
|
|
@@ -1463,14 +2062,20 @@ var ZharpNode = class {
|
|
|
1463
2062
|
} catch {
|
|
1464
2063
|
}
|
|
1465
2064
|
}
|
|
1466
|
-
report(value, handled, level, attributes) {
|
|
2065
|
+
report(value, handled, level, attributes, fromFramework = false) {
|
|
1467
2066
|
try {
|
|
1468
2067
|
if (!this.logger) return;
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
2068
|
+
if (value && typeof value === "object" && this.reported.has(value)) return;
|
|
2069
|
+
const traceId = trace4.getActiveSpan()?.spanContext().traceId;
|
|
2070
|
+
const failure = this.dbErrors?.consume(traceId, value, fromFramework);
|
|
2071
|
+
if (failure) {
|
|
2072
|
+
if (value && typeof value === "object") this.reported.add(value);
|
|
2073
|
+
this.sendQueryError(failure, handled, level, attributes);
|
|
2074
|
+
if (!handled) trace4.getActiveSpan()?.setStatus({ code: SpanStatusCode2.ERROR, message: failure.error?.message ?? "The query failed" });
|
|
2075
|
+
return;
|
|
1473
2076
|
}
|
|
2077
|
+
const error = asError(value);
|
|
2078
|
+
if (value && typeof value === "object") this.reported.add(value);
|
|
1474
2079
|
const exception = exceptionAttributes(error, handled);
|
|
1475
2080
|
this.logger.emit({
|
|
1476
2081
|
severityNumber: SEVERITY[level],
|
|
@@ -1478,7 +2083,33 @@ var ZharpNode = class {
|
|
|
1478
2083
|
body: `${exception["exception.type"]}: ${exception["exception.message"]}`,
|
|
1479
2084
|
attributes: { ...attributes, ...exception }
|
|
1480
2085
|
});
|
|
1481
|
-
if (!handled)
|
|
2086
|
+
if (!handled) trace4.getActiveSpan()?.setStatus({ code: SpanStatusCode2.ERROR, message: error.message });
|
|
2087
|
+
} catch {
|
|
2088
|
+
}
|
|
2089
|
+
}
|
|
2090
|
+
/** A failed query as an error, in the query's own span so the error shows the query. */
|
|
2091
|
+
sendQueryError(failure, handled, level = "error", attributes) {
|
|
2092
|
+
try {
|
|
2093
|
+
if (!this.logger) return;
|
|
2094
|
+
if (failure.error) {
|
|
2095
|
+
if (this.reported.has(failure.error) && handled) return;
|
|
2096
|
+
this.reported.add(failure.error);
|
|
2097
|
+
}
|
|
2098
|
+
const report = reportOf(failure);
|
|
2099
|
+
this.logger.emit({
|
|
2100
|
+
severityNumber: SEVERITY[level],
|
|
2101
|
+
severityText: level.toUpperCase(),
|
|
2102
|
+
body: `${report.type}: ${report.message}`,
|
|
2103
|
+
attributes: {
|
|
2104
|
+
...report.attributes,
|
|
2105
|
+
...attributes,
|
|
2106
|
+
"exception.type": report.type,
|
|
2107
|
+
"exception.message": report.message,
|
|
2108
|
+
"exception.stacktrace": report.stack,
|
|
2109
|
+
"zharp.handled": handled ? "true" : "false"
|
|
2110
|
+
},
|
|
2111
|
+
context: trace4.setSpanContext(context2.active(), report.spanContext)
|
|
2112
|
+
});
|
|
1482
2113
|
} catch {
|
|
1483
2114
|
}
|
|
1484
2115
|
}
|
|
@@ -1637,8 +2268,8 @@ var ExtractOnlyPropagator = class {
|
|
|
1637
2268
|
inner;
|
|
1638
2269
|
inject() {
|
|
1639
2270
|
}
|
|
1640
|
-
extract(
|
|
1641
|
-
return this.inner.extract(
|
|
2271
|
+
extract(context3, carrier, getter) {
|
|
2272
|
+
return this.inner.extract(context3, carrier, getter);
|
|
1642
2273
|
}
|
|
1643
2274
|
fields() {
|
|
1644
2275
|
return [];
|