@zharp/node 0.2.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/README.md +8 -6
- package/dist/index.d.mts +74 -2
- package/dist/index.d.ts +74 -2
- package/dist/index.js +964 -55
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +945 -45
- 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";
|
|
@@ -196,24 +197,24 @@ function shorten(value) {
|
|
|
196
197
|
if (BASE64.test(value) && /[0-9+/]/.test(value)) return `[base64 \xB7 ${formatSize(Math.floor(value.length * 3 / 4))}]`;
|
|
197
198
|
return value;
|
|
198
199
|
}
|
|
199
|
-
function filterAll(value,
|
|
200
|
-
if (
|
|
200
|
+
function filterAll(value, depth2) {
|
|
201
|
+
if (depth2 > 20) return FILTERED;
|
|
201
202
|
if (value === null || value === "") return value;
|
|
202
|
-
if (Array.isArray(value)) return value.map((v) => filterAll(v,
|
|
203
|
+
if (Array.isArray(value)) return value.map((v) => filterAll(v, depth2 + 1));
|
|
203
204
|
if (typeof value === "object") {
|
|
204
205
|
const out = {};
|
|
205
|
-
for (const [k, v] of Object.entries(value)) out[k] = filterAll(v,
|
|
206
|
+
for (const [k, v] of Object.entries(value)) out[k] = filterAll(v, depth2 + 1);
|
|
206
207
|
return out;
|
|
207
208
|
}
|
|
208
209
|
return FILTERED;
|
|
209
210
|
}
|
|
210
|
-
function redactValue(value, extra,
|
|
211
|
+
function redactValue(value, extra, depth2 = 0) {
|
|
211
212
|
if (typeof value === "string") return shorten(value);
|
|
212
|
-
if (
|
|
213
|
-
if (Array.isArray(value)) return value.map((v) => redactValue(v, extra,
|
|
213
|
+
if (depth2 > 20 || value === null || typeof value !== "object") return value;
|
|
214
|
+
if (Array.isArray(value)) return value.map((v) => redactValue(v, extra, depth2 + 1));
|
|
214
215
|
const out = {};
|
|
215
216
|
for (const [k, v] of Object.entries(value)) {
|
|
216
|
-
out[k] = isSecretKey(k, extra) ? filterAll(v,
|
|
217
|
+
out[k] = isSecretKey(k, extra) ? filterAll(v, depth2 + 1) : redactValue(v, extra, depth2 + 1);
|
|
217
218
|
}
|
|
218
219
|
return out;
|
|
219
220
|
}
|
|
@@ -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);
|
|
@@ -798,6 +1364,44 @@ var ContextLogProcessor = class {
|
|
|
798
1364
|
// src/console.ts
|
|
799
1365
|
import { format } from "util";
|
|
800
1366
|
import { SeverityNumber } from "@opentelemetry/api";
|
|
1367
|
+
|
|
1368
|
+
// src/capture-state.ts
|
|
1369
|
+
var depth = 0;
|
|
1370
|
+
function quiet(fn) {
|
|
1371
|
+
depth++;
|
|
1372
|
+
try {
|
|
1373
|
+
return fn();
|
|
1374
|
+
} finally {
|
|
1375
|
+
depth--;
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
var isQuiet = () => depth > 0;
|
|
1379
|
+
var RECENT_MS = 3e3;
|
|
1380
|
+
var RECENT_MAX = 500;
|
|
1381
|
+
var recent = [];
|
|
1382
|
+
var normalise = (text) => text.replace(/\s+/g, " ").trim();
|
|
1383
|
+
function rememberSent(body) {
|
|
1384
|
+
if (typeof body !== "string") return;
|
|
1385
|
+
const text = normalise(body);
|
|
1386
|
+
if (text.length < 4) return;
|
|
1387
|
+
recent.push({ at: Date.now(), text });
|
|
1388
|
+
if (recent.length > RECENT_MAX) recent.splice(0, recent.length - RECENT_MAX);
|
|
1389
|
+
}
|
|
1390
|
+
function alreadySent(line) {
|
|
1391
|
+
const now = Date.now();
|
|
1392
|
+
while (recent.length && now - recent[0].at > RECENT_MS) recent.shift();
|
|
1393
|
+
if (!recent.length) return false;
|
|
1394
|
+
const text = normalise(line);
|
|
1395
|
+
for (let i = recent.length - 1; i >= 0; i--) {
|
|
1396
|
+
if (text.includes(recent[i].text)) {
|
|
1397
|
+
recent.splice(i, 1);
|
|
1398
|
+
return true;
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
return false;
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
// src/console.ts
|
|
801
1405
|
var LEVELS = [
|
|
802
1406
|
["debug", SeverityNumber.DEBUG, "DEBUG"],
|
|
803
1407
|
["trace", SeverityNumber.TRACE, "TRACE"],
|
|
@@ -810,11 +1414,11 @@ var emitting = false;
|
|
|
810
1414
|
function captureConsole(logger) {
|
|
811
1415
|
const originals = /* @__PURE__ */ new Map();
|
|
812
1416
|
for (const [method, severityNumber, severityText] of LEVELS) {
|
|
813
|
-
const
|
|
814
|
-
if (typeof
|
|
815
|
-
originals.set(method,
|
|
1417
|
+
const original2 = console[method];
|
|
1418
|
+
if (typeof original2 !== "function" || original2.__zharp) continue;
|
|
1419
|
+
originals.set(method, original2);
|
|
816
1420
|
const patched = function(...args) {
|
|
817
|
-
|
|
1421
|
+
quiet(() => original2.apply(this ?? console, args));
|
|
818
1422
|
if (emitting) return;
|
|
819
1423
|
emitting = true;
|
|
820
1424
|
try {
|
|
@@ -831,13 +1435,214 @@ function captureConsole(logger) {
|
|
|
831
1435
|
console[method] = patched;
|
|
832
1436
|
}
|
|
833
1437
|
return () => {
|
|
834
|
-
for (const [method,
|
|
1438
|
+
for (const [method, original2] of originals) console[method] = original2;
|
|
835
1439
|
};
|
|
836
1440
|
}
|
|
837
1441
|
|
|
1442
|
+
// src/stdout.ts
|
|
1443
|
+
import { context as otelContext2, isSpanContextValid, SeverityNumber as SeverityNumber2, trace as trace3 } from "@opentelemetry/api";
|
|
1444
|
+
var LEVELS2 = {
|
|
1445
|
+
trace: [SeverityNumber2.TRACE, "TRACE"],
|
|
1446
|
+
verbose: [SeverityNumber2.DEBUG, "DEBUG"],
|
|
1447
|
+
debug: [SeverityNumber2.DEBUG, "DEBUG"],
|
|
1448
|
+
log: [SeverityNumber2.INFO, "INFO"],
|
|
1449
|
+
info: [SeverityNumber2.INFO, "INFO"],
|
|
1450
|
+
notice: [SeverityNumber2.INFO, "INFO"],
|
|
1451
|
+
warn: [SeverityNumber2.WARN, "WARN"],
|
|
1452
|
+
warning: [SeverityNumber2.WARN, "WARN"],
|
|
1453
|
+
error: [SeverityNumber2.ERROR, "ERROR"],
|
|
1454
|
+
err: [SeverityNumber2.ERROR, "ERROR"],
|
|
1455
|
+
crit: [SeverityNumber2.FATAL, "FATAL"],
|
|
1456
|
+
critical: [SeverityNumber2.FATAL, "FATAL"],
|
|
1457
|
+
fatal: [SeverityNumber2.FATAL, "FATAL"],
|
|
1458
|
+
emerg: [SeverityNumber2.FATAL, "FATAL"],
|
|
1459
|
+
alert: [SeverityNumber2.FATAL, "FATAL"]
|
|
1460
|
+
};
|
|
1461
|
+
var NUMERIC = [[60, "fatal"], [50, "error"], [40, "warn"], [30, "info"], [20, "debug"], [0, "trace"]];
|
|
1462
|
+
var ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]/g;
|
|
1463
|
+
var NEST = /^\[Nest\]\s+\d+\s+-\s+.*?\s+(LOG|ERROR|WARN|DEBUG|VERBOSE|FATAL)\s+(?:\[([^\]]+)\]\s+)?([\s\S]*)$/;
|
|
1464
|
+
var WORD = /(?:^|[\s[(|:=])(trace|verbose|debug|info|notice|warn(?:ing)?|err(?:or)?|crit(?:ical)?|fatal|emerg|alert)(?=$|[\s\]):|,])/i;
|
|
1465
|
+
var MAX_LINE2 = 32 * 1024;
|
|
1466
|
+
var FLUSH_MS = 200;
|
|
1467
|
+
function levelOf(value) {
|
|
1468
|
+
if (typeof value === "number") {
|
|
1469
|
+
const found = NUMERIC.find(([n]) => value >= n);
|
|
1470
|
+
return found ? LEVELS2[found[1]] : null;
|
|
1471
|
+
}
|
|
1472
|
+
return typeof value === "string" ? LEVELS2[value.toLowerCase()] ?? null : null;
|
|
1473
|
+
}
|
|
1474
|
+
function parseLine(raw) {
|
|
1475
|
+
const line = raw.replace(ANSI, "").replace(/\s+$/, "");
|
|
1476
|
+
if (line.startsWith("{") && line.endsWith("}")) {
|
|
1477
|
+
try {
|
|
1478
|
+
const record = JSON.parse(line);
|
|
1479
|
+
const message = record.msg ?? record.message ?? record.event;
|
|
1480
|
+
return {
|
|
1481
|
+
level: levelOf(record.level ?? record.severity ?? record.lvl),
|
|
1482
|
+
body: typeof message === "string" ? message : line,
|
|
1483
|
+
attributes: {}
|
|
1484
|
+
};
|
|
1485
|
+
} catch {
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
const nest = NEST.exec(line);
|
|
1489
|
+
if (nest) {
|
|
1490
|
+
return {
|
|
1491
|
+
level: LEVELS2[nest[1].toLowerCase()],
|
|
1492
|
+
body: nest[3],
|
|
1493
|
+
attributes: nest[2] ? { "log.logger": nest[2] } : {}
|
|
1494
|
+
};
|
|
1495
|
+
}
|
|
1496
|
+
const word = WORD.exec(line.slice(0, 120));
|
|
1497
|
+
return { level: word ? LEVELS2[word[1].toLowerCase()] ?? null : null, body: line, attributes: {} };
|
|
1498
|
+
}
|
|
1499
|
+
var SentLineProcessor = class {
|
|
1500
|
+
onEmit(record) {
|
|
1501
|
+
const source = record.attributes?.["log.source"];
|
|
1502
|
+
if (source !== "stdout" && source !== "stderr") rememberSent(record.body);
|
|
1503
|
+
}
|
|
1504
|
+
forceFlush() {
|
|
1505
|
+
return Promise.resolve();
|
|
1506
|
+
}
|
|
1507
|
+
shutdown() {
|
|
1508
|
+
return Promise.resolve();
|
|
1509
|
+
}
|
|
1510
|
+
};
|
|
1511
|
+
function captureOutput(logger) {
|
|
1512
|
+
const undo = [];
|
|
1513
|
+
for (const [stream, name, fallback] of [
|
|
1514
|
+
[process.stdout, "stdout", LEVELS2.info],
|
|
1515
|
+
[process.stderr, "stderr", LEVELS2.warn]
|
|
1516
|
+
]) {
|
|
1517
|
+
if (!stream || typeof stream.write !== "function" || stream.write.__zharp) continue;
|
|
1518
|
+
const original2 = stream.write;
|
|
1519
|
+
let pending = "";
|
|
1520
|
+
let pendingContext;
|
|
1521
|
+
let timer;
|
|
1522
|
+
const emitLine = (line, ctx) => {
|
|
1523
|
+
if (!line.trim() || line.includes("[Zharp]") || alreadySent(line)) return;
|
|
1524
|
+
const parsed2 = parseLine(line.length > MAX_LINE2 ? line.slice(0, MAX_LINE2) : line);
|
|
1525
|
+
if (!parsed2.body.trim()) return;
|
|
1526
|
+
const [severityNumber, severityText] = parsed2.level ?? fallback;
|
|
1527
|
+
quiet(() => logger.emit({
|
|
1528
|
+
severityNumber,
|
|
1529
|
+
severityText,
|
|
1530
|
+
body: parsed2.body,
|
|
1531
|
+
attributes: { "log.source": name, "log.iostream": name, ...parsed2.attributes },
|
|
1532
|
+
...ctx ? { context: ctx } : {}
|
|
1533
|
+
}));
|
|
1534
|
+
};
|
|
1535
|
+
const flush = () => {
|
|
1536
|
+
timer = void 0;
|
|
1537
|
+
const line = pending;
|
|
1538
|
+
const ctx = pendingContext;
|
|
1539
|
+
pending = "";
|
|
1540
|
+
pendingContext = void 0;
|
|
1541
|
+
emitLine(line, ctx);
|
|
1542
|
+
};
|
|
1543
|
+
const take = (chunk, encoding) => {
|
|
1544
|
+
if (isQuiet()) return;
|
|
1545
|
+
const text = typeof chunk === "string" ? chunk : chunk instanceof Uint8Array ? Buffer.from(chunk).toString(typeof encoding === "string" ? encoding : "utf8") : "";
|
|
1546
|
+
if (!text) return;
|
|
1547
|
+
if (!pending) pendingContext = otelContext2.active();
|
|
1548
|
+
pending += text;
|
|
1549
|
+
const lines = pending.split("\n");
|
|
1550
|
+
pending = lines.pop() ?? "";
|
|
1551
|
+
const ctx = pendingContext;
|
|
1552
|
+
if (pending) pendingContext = otelContext2.active();
|
|
1553
|
+
for (const line of lines) emitLine(line, ctx);
|
|
1554
|
+
if (pending.length > MAX_LINE2) flush();
|
|
1555
|
+
else if (pending && !timer) {
|
|
1556
|
+
timer = setTimeout(flush, FLUSH_MS);
|
|
1557
|
+
timer.unref?.();
|
|
1558
|
+
}
|
|
1559
|
+
};
|
|
1560
|
+
const patched = function(chunk, encoding, callback) {
|
|
1561
|
+
try {
|
|
1562
|
+
take(chunk, encoding);
|
|
1563
|
+
} catch {
|
|
1564
|
+
}
|
|
1565
|
+
return original2.call(this ?? stream, chunk, encoding, callback);
|
|
1566
|
+
};
|
|
1567
|
+
patched.__zharp = true;
|
|
1568
|
+
stream.write = patched;
|
|
1569
|
+
undo.push(() => {
|
|
1570
|
+
if (timer) clearTimeout(timer);
|
|
1571
|
+
if (pending) flush();
|
|
1572
|
+
stream.write = original2;
|
|
1573
|
+
});
|
|
1574
|
+
}
|
|
1575
|
+
return () => undo.forEach((fn) => fn());
|
|
1576
|
+
}
|
|
1577
|
+
function stampOutput() {
|
|
1578
|
+
const undo = [];
|
|
1579
|
+
for (const stream of [process.stdout, process.stderr]) {
|
|
1580
|
+
if (!stream || typeof stream.write !== "function" || stream.write.__zharpStamp) continue;
|
|
1581
|
+
const original2 = stream.write;
|
|
1582
|
+
const patched = function(chunk, encoding, callback) {
|
|
1583
|
+
let out = chunk;
|
|
1584
|
+
try {
|
|
1585
|
+
out = stamped(chunk, encoding);
|
|
1586
|
+
} catch {
|
|
1587
|
+
}
|
|
1588
|
+
return original2.call(this ?? stream, out, encoding, callback);
|
|
1589
|
+
};
|
|
1590
|
+
patched.__zharpStamp = true;
|
|
1591
|
+
stream.write = patched;
|
|
1592
|
+
undo.push(() => {
|
|
1593
|
+
stream.write = original2;
|
|
1594
|
+
});
|
|
1595
|
+
}
|
|
1596
|
+
return () => undo.forEach((fn) => fn());
|
|
1597
|
+
}
|
|
1598
|
+
function stamped(chunk, encoding) {
|
|
1599
|
+
const span = trace3.getActiveSpan()?.spanContext();
|
|
1600
|
+
if (!span || !isSpanContextValid(span)) return chunk;
|
|
1601
|
+
const isBytes = chunk instanceof Uint8Array;
|
|
1602
|
+
if (typeof chunk !== "string" && !isBytes) return chunk;
|
|
1603
|
+
const enc = typeof encoding === "string" && Buffer.isEncoding(encoding) ? encoding : "utf8";
|
|
1604
|
+
if (isBytes && enc !== "utf8") return chunk;
|
|
1605
|
+
const text = isBytes ? Buffer.from(chunk).toString("utf8") : chunk;
|
|
1606
|
+
if (!text.includes("\n")) return chunk;
|
|
1607
|
+
const parts = text.split("\n");
|
|
1608
|
+
let last = -1;
|
|
1609
|
+
for (let i = parts.length - 2; i >= 0; i--) {
|
|
1610
|
+
if (parts[i].trim()) {
|
|
1611
|
+
last = i;
|
|
1612
|
+
break;
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
let changed = false;
|
|
1616
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
1617
|
+
if (i !== last && !parts[i].trimStart().startsWith("{")) continue;
|
|
1618
|
+
const next = stampLine(parts[i], span.traceId, span.spanId);
|
|
1619
|
+
if (next !== parts[i]) {
|
|
1620
|
+
parts[i] = next;
|
|
1621
|
+
changed = true;
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
if (!changed) return chunk;
|
|
1625
|
+
const joined = parts.join("\n");
|
|
1626
|
+
return isBytes ? Buffer.from(joined, "utf8") : joined;
|
|
1627
|
+
}
|
|
1628
|
+
function stampLine(line, traceId, spanId) {
|
|
1629
|
+
const cr = line.endsWith("\r") ? "\r" : "";
|
|
1630
|
+
const body = cr ? line.slice(0, -1) : line;
|
|
1631
|
+
const trimmed = body.trimEnd();
|
|
1632
|
+
if (!trimmed.trim() || body.includes("trace_id") || body.includes("[Zharp]")) return line;
|
|
1633
|
+
if (trimmed.endsWith("}")) {
|
|
1634
|
+
if (!trimmed.trimStart().startsWith("{")) return line;
|
|
1635
|
+
const close = trimmed.lastIndexOf("}");
|
|
1636
|
+
const inner = trimmed.slice(trimmed.indexOf("{") + 1, close).trim();
|
|
1637
|
+
const fields = `"trace_id":"${traceId}","span_id":"${spanId}"`;
|
|
1638
|
+
return `${trimmed.slice(0, close)}${inner ? "," : ""}${fields}}${body.slice(trimmed.length)}${cr}`;
|
|
1639
|
+
}
|
|
1640
|
+
return `${trimmed} trace_id=${traceId} span_id=${spanId}${body.slice(trimmed.length)}${cr}`;
|
|
1641
|
+
}
|
|
1642
|
+
|
|
838
1643
|
// ../../internal/src/debug-ids.ts
|
|
839
1644
|
var DEBUG_IDS_ATTRIBUTE = "zharp.debug_ids";
|
|
840
|
-
var
|
|
1645
|
+
var files2 = /* @__PURE__ */ new Map();
|
|
841
1646
|
var parsed = /* @__PURE__ */ new Set();
|
|
842
1647
|
function registry() {
|
|
843
1648
|
const g2 = typeof globalThis !== "undefined" ? globalThis : void 0;
|
|
@@ -876,7 +1681,7 @@ function refresh() {
|
|
|
876
1681
|
for (const line of stack.split("\n")) {
|
|
877
1682
|
const file = frameFile(line);
|
|
878
1683
|
if (file) {
|
|
879
|
-
|
|
1684
|
+
files2.set(file, id);
|
|
880
1685
|
break;
|
|
881
1686
|
}
|
|
882
1687
|
}
|
|
@@ -886,10 +1691,10 @@ function debugIdsFor(stack) {
|
|
|
886
1691
|
if (!stack) return void 0;
|
|
887
1692
|
try {
|
|
888
1693
|
refresh();
|
|
889
|
-
if (
|
|
1694
|
+
if (files2.size === 0) return void 0;
|
|
890
1695
|
let out;
|
|
891
1696
|
for (const file of stackFiles(stack)) {
|
|
892
|
-
const id =
|
|
1697
|
+
const id = files2.get(file);
|
|
893
1698
|
if (id) (out ??= {})[file] = id;
|
|
894
1699
|
}
|
|
895
1700
|
return out;
|
|
@@ -972,18 +1777,18 @@ function exceptionAttributes(error, handled) {
|
|
|
972
1777
|
const cause = error.cause;
|
|
973
1778
|
if (cause instanceof Error && cause.stack) stack += `
|
|
974
1779
|
Caused by: ${cause.stack}`;
|
|
1780
|
+
const { stack: readable, context: context3 } = sourced(stack);
|
|
975
1781
|
return {
|
|
976
1782
|
"exception.type": type,
|
|
977
1783
|
"exception.message": message,
|
|
978
|
-
"exception.stacktrace":
|
|
1784
|
+
"exception.stacktrace": readable,
|
|
979
1785
|
"zharp.handled": handled ? "true" : "false",
|
|
980
|
-
|
|
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 } : {}
|
|
981
1789
|
};
|
|
982
1790
|
}
|
|
983
1791
|
|
|
984
|
-
// src/version.ts
|
|
985
|
-
var VERSION = "0.2.0";
|
|
986
|
-
|
|
987
1792
|
// src/zharp.ts
|
|
988
1793
|
var DEFAULT_ENDPOINT = "https://api.zharp.io/api/v1/otlp";
|
|
989
1794
|
var EXIT_FLUSH_MS = 2e3;
|
|
@@ -998,6 +1803,8 @@ var ZharpNode = class {
|
|
|
998
1803
|
tracing = true;
|
|
999
1804
|
/** Errors already sent, so one that is both rejected and then thrown is reported once. */
|
|
1000
1805
|
reported = /* @__PURE__ */ new WeakSet();
|
|
1806
|
+
/** Failed queries waiting to be reported, once and with their call site. */
|
|
1807
|
+
dbErrors = null;
|
|
1001
1808
|
/** `Zharp.log.info("Order placed", { orderId })` — and debug, warn, error, fatal, trace. */
|
|
1002
1809
|
log = {
|
|
1003
1810
|
trace: (m, a) => this.emit("trace", m, a),
|
|
@@ -1043,6 +1850,9 @@ var ZharpNode = class {
|
|
|
1043
1850
|
const endpoint = (pick(options.endpoint, nodeEnv("ZHARP_ENDPOINT")) ?? DEFAULT_ENDPOINT).replace(/\/+$/, "");
|
|
1044
1851
|
const tracing = tracingEnabled(options.tracing);
|
|
1045
1852
|
this.tracing = tracing;
|
|
1853
|
+
const sendLogs = switchOn(options.logs, "ZHARP_LOGS", false);
|
|
1854
|
+
const correlation = switchOn(options.logCorrelation, "ZHARP_LOG_CORRELATION", true);
|
|
1855
|
+
const bridges = logBridges(sendLogs, correlation, options.instrumentations);
|
|
1046
1856
|
if (options.debug) {
|
|
1047
1857
|
const out = { error: console.error, warn: console.warn, info: console.info, debug: console.debug, verbose: console.debug };
|
|
1048
1858
|
const prefixed = Object.fromEntries(
|
|
@@ -1053,13 +1863,21 @@ var ZharpNode = class {
|
|
|
1053
1863
|
registerEsmHook();
|
|
1054
1864
|
const headers = { Authorization: `Bearer ${key}` };
|
|
1055
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;
|
|
1056
1869
|
this.spanProcessors = tracing ? [
|
|
1057
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] : [],
|
|
1058
1875
|
new UrlRedactionSpanProcessor(),
|
|
1059
1876
|
new DebugIdSpanProcessor(),
|
|
1060
1877
|
new BatchSpanProcessor({ exporter: new OTLPTraceExporter({ ...exporterOptions, url: `${endpoint}/v1/traces` }) })
|
|
1061
1878
|
] : [new ContextSpanProcessor(this.store)];
|
|
1062
1879
|
this.logProcessors = [
|
|
1880
|
+
new SentLineProcessor(),
|
|
1063
1881
|
new ContextLogProcessor(this.store),
|
|
1064
1882
|
new DebugIdLogProcessor(),
|
|
1065
1883
|
new BatchLogRecordProcessor({ exporter: new OTLPLogExporter({ ...exporterOptions, url: `${endpoint}/v1/logs` }) })
|
|
@@ -1078,6 +1896,10 @@ var ZharpNode = class {
|
|
|
1078
1896
|
propagators: [new W3CTraceContextPropagator(), new W3CBaggagePropagator()]
|
|
1079
1897
|
});
|
|
1080
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;
|
|
1081
1903
|
const rate = typeof options.sampleRate === "number" ? Math.min(1, Math.max(0, options.sampleRate)) : 1;
|
|
1082
1904
|
this.sdk = new NodeSDK({
|
|
1083
1905
|
resource,
|
|
@@ -1097,16 +1919,23 @@ var ZharpNode = class {
|
|
|
1097
1919
|
"@opentelemetry/instrumentation-net": { enabled: false },
|
|
1098
1920
|
"@opentelemetry/instrumentation-fs": { enabled: false },
|
|
1099
1921
|
...options.instrumentations,
|
|
1100
|
-
...
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1922
|
+
...bridges,
|
|
1923
|
+
...httpConfig && { "@opentelemetry/instrumentation-http": httpConfig }
|
|
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))] : [],
|
|
1104
1927
|
...options.extraInstrumentations ?? []
|
|
1105
1928
|
]
|
|
1106
1929
|
});
|
|
1107
1930
|
this.sdk.start();
|
|
1108
1931
|
this.logger = logs.getLogger("@zharp/node", VERSION);
|
|
1109
|
-
if (
|
|
1932
|
+
if (correlation) this.teardowns.push(stampOutput());
|
|
1933
|
+
if (sendLogs) {
|
|
1934
|
+
if (options.captureConsole !== false) this.teardowns.push(captureConsole(this.logger));
|
|
1935
|
+
if (options.captureOutput !== false && nodeEnv("ZHARP_CAPTURE_OUTPUT") !== "false") {
|
|
1936
|
+
this.teardowns.push(captureOutput(this.logger));
|
|
1937
|
+
}
|
|
1938
|
+
}
|
|
1110
1939
|
if (options.captureUncaught !== false) this.teardowns.push(this.captureProcessErrors());
|
|
1111
1940
|
this.teardowns.push(this.flushOnExit());
|
|
1112
1941
|
announce(`Application monitoring active${tracing ? "" : " (logs only)"} \u2014 ${describeTarget(service, environment)}`);
|
|
@@ -1142,16 +1971,36 @@ var ZharpNode = class {
|
|
|
1142
1971
|
captureError(error, attributes) {
|
|
1143
1972
|
this.report(error, true, "error", attributes);
|
|
1144
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
|
+
};
|
|
1145
1994
|
/**
|
|
1146
1995
|
* Run `fn` inside a span named `name`, which ends when `fn` returns or its promise settles. A
|
|
1147
1996
|
* throw or rejection marks the span as failed and is passed on unchanged.
|
|
1148
1997
|
*/
|
|
1149
1998
|
startSpan(name, fn, options = {}) {
|
|
1150
|
-
if (!this.tracing) return fn(
|
|
1151
|
-
const tracer =
|
|
1999
|
+
if (!this.tracing) return fn(trace4.wrapSpanContext(trace4.getActiveSpan()?.spanContext() ?? INVALID_SPAN_CONTEXT));
|
|
2000
|
+
const tracer = trace4.getTracer("@zharp/node", VERSION);
|
|
1152
2001
|
return tracer.startActiveSpan(name, options, (span) => {
|
|
1153
2002
|
const fail = (error) => {
|
|
1154
|
-
span.setStatus({ code:
|
|
2003
|
+
span.setStatus({ code: SpanStatusCode2.ERROR, message: asError(error).message });
|
|
1155
2004
|
span.end();
|
|
1156
2005
|
};
|
|
1157
2006
|
let result;
|
|
@@ -1181,7 +2030,7 @@ var ZharpNode = class {
|
|
|
1181
2030
|
async flush(timeoutMs = 5e3) {
|
|
1182
2031
|
const all = Promise.all([...this.spanProcessors, ...this.logProcessors].map((p) => p.forceFlush().catch(() => {
|
|
1183
2032
|
})));
|
|
1184
|
-
await Promise.race([all, new Promise((
|
|
2033
|
+
await Promise.race([all, new Promise((resolve2) => setTimeout(resolve2, timeoutMs).unref())]);
|
|
1185
2034
|
}
|
|
1186
2035
|
/** Flush, stop, and put back everything that was patched. */
|
|
1187
2036
|
async shutdown() {
|
|
@@ -1213,14 +2062,20 @@ var ZharpNode = class {
|
|
|
1213
2062
|
} catch {
|
|
1214
2063
|
}
|
|
1215
2064
|
}
|
|
1216
|
-
report(value, handled, level, attributes) {
|
|
2065
|
+
report(value, handled, level, attributes, fromFramework = false) {
|
|
1217
2066
|
try {
|
|
1218
2067
|
if (!this.logger) return;
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
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;
|
|
1223
2076
|
}
|
|
2077
|
+
const error = asError(value);
|
|
2078
|
+
if (value && typeof value === "object") this.reported.add(value);
|
|
1224
2079
|
const exception = exceptionAttributes(error, handled);
|
|
1225
2080
|
this.logger.emit({
|
|
1226
2081
|
severityNumber: SEVERITY[level],
|
|
@@ -1228,7 +2083,33 @@ var ZharpNode = class {
|
|
|
1228
2083
|
body: `${exception["exception.type"]}: ${exception["exception.message"]}`,
|
|
1229
2084
|
attributes: { ...attributes, ...exception }
|
|
1230
2085
|
});
|
|
1231
|
-
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
|
+
});
|
|
1232
2113
|
} catch {
|
|
1233
2114
|
}
|
|
1234
2115
|
}
|
|
@@ -1332,6 +2213,25 @@ function registerEsmHook() {
|
|
|
1332
2213
|
} catch {
|
|
1333
2214
|
}
|
|
1334
2215
|
}
|
|
2216
|
+
function switchOn(option, variable, fallback) {
|
|
2217
|
+
if (typeof option === "boolean") return option;
|
|
2218
|
+
const value = nodeEnv(variable);
|
|
2219
|
+
if (value && /^(true|1|yes|on)$/i.test(value)) return true;
|
|
2220
|
+
if (value && /^(false|0|no|off)$/i.test(value)) return false;
|
|
2221
|
+
return fallback;
|
|
2222
|
+
}
|
|
2223
|
+
function logBridges(sendLogs, correlation, own = {}) {
|
|
2224
|
+
const config = (name) => ({
|
|
2225
|
+
disableLogSending: !sendLogs,
|
|
2226
|
+
disableLogCorrelation: !correlation,
|
|
2227
|
+
...own[name]
|
|
2228
|
+
});
|
|
2229
|
+
return {
|
|
2230
|
+
"@opentelemetry/instrumentation-pino": config("@opentelemetry/instrumentation-pino"),
|
|
2231
|
+
"@opentelemetry/instrumentation-winston": config("@opentelemetry/instrumentation-winston"),
|
|
2232
|
+
"@opentelemetry/instrumentation-bunyan": config("@opentelemetry/instrumentation-bunyan")
|
|
2233
|
+
};
|
|
2234
|
+
}
|
|
1335
2235
|
function tracingEnabled(option) {
|
|
1336
2236
|
if (typeof option === "boolean") return option;
|
|
1337
2237
|
const value = nodeEnv("ZHARP_TRACING");
|
|
@@ -1368,8 +2268,8 @@ var ExtractOnlyPropagator = class {
|
|
|
1368
2268
|
inner;
|
|
1369
2269
|
inject() {
|
|
1370
2270
|
}
|
|
1371
|
-
extract(
|
|
1372
|
-
return this.inner.extract(
|
|
2271
|
+
extract(context3, carrier, getter) {
|
|
2272
|
+
return this.inner.extract(context3, carrier, getter);
|
|
1373
2273
|
}
|
|
1374
2274
|
fields() {
|
|
1375
2275
|
return [];
|