@zharp/node 0.3.0 → 0.5.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 +22 -1
- package/dist/index.d.mts +107 -2
- package/dist/index.d.ts +107 -2
- package/dist/index.js +1279 -79
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1246 -53
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
2
3
|
var __defProp = Object.defineProperty;
|
|
3
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
5
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
5
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
8
|
var __export = (target, all) => {
|
|
7
9
|
for (var name in all)
|
|
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
15
17
|
}
|
|
16
18
|
return to;
|
|
17
19
|
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
18
28
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
29
|
|
|
20
30
|
// src/index.ts
|
|
@@ -33,7 +43,8 @@ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
|
|
|
33
43
|
|
|
34
44
|
// src/zharp.ts
|
|
35
45
|
var import_node_module = require("module");
|
|
36
|
-
var
|
|
46
|
+
var import_node_path2 = require("path");
|
|
47
|
+
var import_api5 = require("@opentelemetry/api");
|
|
37
48
|
var import_core = require("@opentelemetry/core");
|
|
38
49
|
var import_resources = require("@opentelemetry/resources");
|
|
39
50
|
var import_sdk_node = require("@opentelemetry/sdk-node");
|
|
@@ -668,6 +679,577 @@ function withBodyCapture(settings, config = {}) {
|
|
|
668
679
|
};
|
|
669
680
|
}
|
|
670
681
|
|
|
682
|
+
// src/headers.ts
|
|
683
|
+
var import_node_http2 = require("http");
|
|
684
|
+
|
|
685
|
+
// ../../internal/src/headers.ts
|
|
686
|
+
var SECRET = /* @__PURE__ */ new Set(["authorization", "proxy-authorization", "cookie", "set-cookie", "x-api-key", "x-auth-token", "x-csrf-token", "x-xsrf-token"]);
|
|
687
|
+
var MAX_HEADERS = 40;
|
|
688
|
+
var MAX_VALUE = 512;
|
|
689
|
+
function headerSettings(option, env) {
|
|
690
|
+
if (option === false || env === "false" || env === "0") return null;
|
|
691
|
+
return { redact: typeof option === "object" && option?.redact ? option.redact : [] };
|
|
692
|
+
}
|
|
693
|
+
function shown(name, value, settings) {
|
|
694
|
+
if (value === void 0 || value === null) return null;
|
|
695
|
+
if (SECRET.has(name) || isSecretKey(name, settings.redact)) return FILTERED;
|
|
696
|
+
const text = Array.isArray(value) ? value.join(", ") : String(value);
|
|
697
|
+
return text.length > MAX_VALUE ? `${text.slice(0, MAX_VALUE)}\u2026` : text;
|
|
698
|
+
}
|
|
699
|
+
function headerAttributes(side, headers, settings) {
|
|
700
|
+
const out = {};
|
|
701
|
+
if (!headers) return out;
|
|
702
|
+
const entries = typeof headers[Symbol.iterator] === "function" ? [...headers] : Object.entries(headers);
|
|
703
|
+
let count = 0;
|
|
704
|
+
for (const [rawName, value] of entries) {
|
|
705
|
+
if (count >= MAX_HEADERS) break;
|
|
706
|
+
const name = rawName.toLowerCase();
|
|
707
|
+
const text = shown(name, value, settings);
|
|
708
|
+
if (text === null) continue;
|
|
709
|
+
out[`http.${side}.header.${name}`] = text;
|
|
710
|
+
count++;
|
|
711
|
+
}
|
|
712
|
+
return out;
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
// src/headers.ts
|
|
716
|
+
function withHeaderCapture(settings, config = {}) {
|
|
717
|
+
return {
|
|
718
|
+
...config,
|
|
719
|
+
applyCustomAttributesOnSpan(span, request, response) {
|
|
720
|
+
config.applyCustomAttributesOnSpan?.(span, request, response);
|
|
721
|
+
try {
|
|
722
|
+
if (request instanceof import_node_http2.IncomingMessage) {
|
|
723
|
+
span.setAttributes(headerAttributes("request", request.headers, settings));
|
|
724
|
+
if (response instanceof import_node_http2.ServerResponse) span.setAttributes(headerAttributes("response", response.getHeaders(), settings));
|
|
725
|
+
} else if (request instanceof import_node_http2.ClientRequest) {
|
|
726
|
+
span.setAttributes(headerAttributes("request", request.getHeaders(), settings));
|
|
727
|
+
if (response instanceof import_node_http2.IncomingMessage) span.setAttributes(headerAttributes("response", response.headers, settings));
|
|
728
|
+
}
|
|
729
|
+
} catch {
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
};
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
// src/db-errors.ts
|
|
736
|
+
var import_api = require("@opentelemetry/api");
|
|
737
|
+
var import_instrumentation = require("@opentelemetry/instrumentation");
|
|
738
|
+
|
|
739
|
+
// src/version.ts
|
|
740
|
+
var VERSION = "0.5.0";
|
|
741
|
+
|
|
742
|
+
// src/source.ts
|
|
743
|
+
var import_node_fs = require("fs");
|
|
744
|
+
var import_node_path = require("path");
|
|
745
|
+
var import_node_url = require("url");
|
|
746
|
+
var nodeModule = __toESM(require("module"));
|
|
747
|
+
var SOURCE_CONTEXT_ATTRIBUTE = "zharp.source_context";
|
|
748
|
+
var AROUND = 5;
|
|
749
|
+
var MAX_FRAMES = 5;
|
|
750
|
+
var MAX_LINE = 300;
|
|
751
|
+
var MAX_BYTES = 12e3;
|
|
752
|
+
var MAX_FILE = 5e6;
|
|
753
|
+
var MAX_MAP = 3e7;
|
|
754
|
+
var MAX_CACHED = 50;
|
|
755
|
+
var enabled = true;
|
|
756
|
+
function setSourceContext(on) {
|
|
757
|
+
enabled = on;
|
|
758
|
+
}
|
|
759
|
+
var files = /* @__PURE__ */ new Map();
|
|
760
|
+
var maps = /* @__PURE__ */ new Map();
|
|
761
|
+
function remember(cache, key, value) {
|
|
762
|
+
if (cache.size >= MAX_CACHED) cache.delete(cache.keys().next().value);
|
|
763
|
+
cache.set(key, value);
|
|
764
|
+
return value;
|
|
765
|
+
}
|
|
766
|
+
function toPath(file) {
|
|
767
|
+
if (file.startsWith("file://")) {
|
|
768
|
+
try {
|
|
769
|
+
return (0, import_node_url.fileURLToPath)(file);
|
|
770
|
+
} catch {
|
|
771
|
+
return null;
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
return (0, import_node_path.isAbsolute)(file) ? file : null;
|
|
775
|
+
}
|
|
776
|
+
function isApp(path) {
|
|
777
|
+
return !/[\\/]node_modules[\\/]/.test(path) && !path.startsWith("node:") && !/[\\/]@zharp[\\/]/.test(path);
|
|
778
|
+
}
|
|
779
|
+
function linesOf(path, text) {
|
|
780
|
+
if (files.has(path)) return files.get(path);
|
|
781
|
+
let content = text ?? null;
|
|
782
|
+
if (content === null) {
|
|
783
|
+
try {
|
|
784
|
+
if ((0, import_node_fs.statSync)(path).size > MAX_FILE) return remember(files, path, null);
|
|
785
|
+
content = (0, import_node_fs.readFileSync)(path, "utf8");
|
|
786
|
+
} catch {
|
|
787
|
+
return remember(files, path, null);
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
return remember(files, path, content.split(/\r\n|\n|\r/));
|
|
791
|
+
}
|
|
792
|
+
function mapOf(path) {
|
|
793
|
+
if (maps.has(path)) return maps.get(path);
|
|
794
|
+
const SourceMap2 = nodeModule.SourceMap;
|
|
795
|
+
const lines = linesOf(path);
|
|
796
|
+
if (!SourceMap2 || !lines) return remember(maps, path, null);
|
|
797
|
+
try {
|
|
798
|
+
let payload = null;
|
|
799
|
+
let mapPath = `${path}.map`;
|
|
800
|
+
const tail = lines.slice(-5).join("\n");
|
|
801
|
+
const url = /[#@]\s*sourceMappingURL=(\S+)\s*$/m.exec(tail)?.[1];
|
|
802
|
+
if (url?.startsWith("data:")) {
|
|
803
|
+
const base64 = /;base64,(.*)$/.exec(url)?.[1];
|
|
804
|
+
payload = base64 ? JSON.parse(Buffer.from(base64, "base64").toString("utf8")) : null;
|
|
805
|
+
mapPath = path;
|
|
806
|
+
} else {
|
|
807
|
+
if (url) mapPath = (0, import_node_path.resolve)((0, import_node_path.dirname)(path), decodeURIComponent(url));
|
|
808
|
+
if ((0, import_node_fs.statSync)(mapPath).size > MAX_MAP) return remember(maps, path, null);
|
|
809
|
+
payload = JSON.parse((0, import_node_fs.readFileSync)(mapPath, "utf8"));
|
|
810
|
+
}
|
|
811
|
+
if (!payload || !Array.isArray(payload.sources)) return remember(maps, path, null);
|
|
812
|
+
return remember(maps, path, {
|
|
813
|
+
map: new SourceMap2(payload),
|
|
814
|
+
dir: (0, import_node_path.dirname)(mapPath),
|
|
815
|
+
sources: payload.sources,
|
|
816
|
+
sourceRoot: typeof payload.sourceRoot === "string" ? payload.sourceRoot : "",
|
|
817
|
+
contents: Array.isArray(payload.sourcesContent) ? payload.sourcesContent : []
|
|
818
|
+
});
|
|
819
|
+
} catch {
|
|
820
|
+
return remember(maps, path, null);
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
function original(path, line, column) {
|
|
824
|
+
const loaded = mapOf(path);
|
|
825
|
+
if (!loaded) return null;
|
|
826
|
+
const entry = loaded.map.findEntry(line - 1, Math.max(0, column - 1));
|
|
827
|
+
if (!entry?.originalSource || entry.originalLine === void 0) return null;
|
|
828
|
+
const index = loaded.sources.findIndex((s) => s === entry.originalSource || entry.originalSource.endsWith(s));
|
|
829
|
+
const source = entry.originalSource.replace(/^webpack:\/\/[^/]*\//, "").replace(/^file:\/\//, "");
|
|
830
|
+
const file = (0, import_node_path.isAbsolute)(source) ? source : (0, import_node_path.resolve)(loaded.dir, loaded.sourceRoot, source);
|
|
831
|
+
return { file, line: entry.originalLine + 1, column: (entry.originalColumn ?? 0) + 1, text: index >= 0 ? loaded.contents[index] ?? null : null };
|
|
832
|
+
}
|
|
833
|
+
var FRAME = /^(\s*at (?:async )?(?:.*? \()?)((?:file:\/\/)?(?:\/|[A-Za-z]:[\\/]).*?):(\d+):(\d+)(\)?)\s*$/;
|
|
834
|
+
function sourced(stack) {
|
|
835
|
+
if (!enabled || !stack) return { stack, context: null };
|
|
836
|
+
const out = [];
|
|
837
|
+
const seen = /* @__PURE__ */ new Set();
|
|
838
|
+
let mapped = 0;
|
|
839
|
+
const lines = stack.split("\n").map((text) => {
|
|
840
|
+
const m = FRAME.exec(text);
|
|
841
|
+
if (!m) return text;
|
|
842
|
+
const path = toPath(m[2]);
|
|
843
|
+
if (!path || !isApp(path) || mapped > 40) return text;
|
|
844
|
+
let file = m[2];
|
|
845
|
+
let line = Number(m[3]);
|
|
846
|
+
let column = Number(m[4]);
|
|
847
|
+
let content = null;
|
|
848
|
+
const from = /\.(c|m)?js$/.test(path) ? original(path, line, column) : null;
|
|
849
|
+
mapped++;
|
|
850
|
+
if (from && isApp(from.file)) {
|
|
851
|
+
file = from.file;
|
|
852
|
+
line = from.line;
|
|
853
|
+
column = from.column;
|
|
854
|
+
content = linesOf(from.file, from.text);
|
|
855
|
+
text = `${m[1]}${file}:${line}:${column}${m[5]}`;
|
|
856
|
+
} else if (!from) {
|
|
857
|
+
const built = linesOf(path);
|
|
858
|
+
const tail = built ? built.slice(-5).join("\n") : "";
|
|
859
|
+
content = /[#@]\s*(?:sourceMappingURL|debugId)=/.test(tail) ? null : built;
|
|
860
|
+
}
|
|
861
|
+
const key = `${file}:${line}`;
|
|
862
|
+
if (content && out.length < MAX_FRAMES && !seen.has(key) && content[line - 1] !== void 0) {
|
|
863
|
+
seen.add(key);
|
|
864
|
+
const cut = (s) => s.length > MAX_LINE ? `${s.slice(0, MAX_LINE - 1)}\u2026` : s;
|
|
865
|
+
out.push({
|
|
866
|
+
file,
|
|
867
|
+
line,
|
|
868
|
+
pre: content.slice(Math.max(0, line - 1 - AROUND), line - 1).map(cut),
|
|
869
|
+
code: cut(content[line - 1]),
|
|
870
|
+
post: content.slice(line, line + AROUND).map(cut)
|
|
871
|
+
});
|
|
872
|
+
}
|
|
873
|
+
return text;
|
|
874
|
+
});
|
|
875
|
+
while (out.length) {
|
|
876
|
+
const json = JSON.stringify(out);
|
|
877
|
+
if (Buffer.byteLength(json) <= MAX_BYTES) return { stack: lines.join("\n"), context: json };
|
|
878
|
+
out.pop();
|
|
879
|
+
}
|
|
880
|
+
return { stack: lines.join("\n"), context: null };
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
// src/db-errors.ts
|
|
884
|
+
var SQLSTATE = {
|
|
885
|
+
"23505": "UniqueViolation",
|
|
886
|
+
"23503": "ForeignKeyViolation",
|
|
887
|
+
"23502": "NotNullViolation",
|
|
888
|
+
"23514": "CheckViolation",
|
|
889
|
+
"23P01": "ExclusionViolation",
|
|
890
|
+
"22001": "StringDataRightTruncation",
|
|
891
|
+
"22003": "NumericValueOutOfRange",
|
|
892
|
+
"22P02": "InvalidTextRepresentation",
|
|
893
|
+
"22007": "InvalidDatetimeFormat",
|
|
894
|
+
"22008": "DatetimeFieldOverflow",
|
|
895
|
+
"22012": "DivisionByZero",
|
|
896
|
+
"42P01": "UndefinedTable",
|
|
897
|
+
"42703": "UndefinedColumn",
|
|
898
|
+
"42883": "UndefinedFunction",
|
|
899
|
+
"42601": "SyntaxError",
|
|
900
|
+
"42501": "InsufficientPrivilege",
|
|
901
|
+
"40001": "SerializationFailure",
|
|
902
|
+
"40P01": "DeadlockDetected",
|
|
903
|
+
"55P03": "LockNotAvailable",
|
|
904
|
+
"57014": "QueryCanceled",
|
|
905
|
+
"53300": "TooManyConnections",
|
|
906
|
+
"08006": "ConnectionFailure",
|
|
907
|
+
"08001": "ConnectionRefused",
|
|
908
|
+
"28P01": "InvalidPassword",
|
|
909
|
+
"3D000": "InvalidCatalogName"
|
|
910
|
+
};
|
|
911
|
+
var SYSTEM_NAMES = { postgresql: "Postgres", mysql: "MySQL", mariadb: "MariaDB", mongodb: "Mongo", redis: "Redis", mssql: "SqlServer", oracle: "Oracle", sqlite: "Sqlite" };
|
|
912
|
+
function dbErrorType(system, code, name) {
|
|
913
|
+
if (code && system === "postgresql" && SQLSTATE[code]) return SQLSTATE[code];
|
|
914
|
+
if (code && /^ER_[A-Z_]+$/.test(code)) return code;
|
|
915
|
+
if (name && !/^(error|Error|DatabaseError)$/.test(name)) return name;
|
|
916
|
+
return `${SYSTEM_NAMES[system] ?? "Database"}Error`;
|
|
917
|
+
}
|
|
918
|
+
function callSiteFrames(stack) {
|
|
919
|
+
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));
|
|
920
|
+
const firstApp = frames.findIndex((line) => !/[\\/]node_modules[\\/]/.test(line));
|
|
921
|
+
return (firstApp > 0 ? frames.slice(firstApp) : frames).slice(0, 40);
|
|
922
|
+
}
|
|
923
|
+
var CALL_SITE = (0, import_api.createContextKey)("zharp.db.callSite");
|
|
924
|
+
function stackFrom(fn) {
|
|
925
|
+
const limit = Error.stackTraceLimit;
|
|
926
|
+
Error.stackTraceLimit = 60;
|
|
927
|
+
const holder = {};
|
|
928
|
+
Error.captureStackTrace(holder, fn);
|
|
929
|
+
Error.stackTraceLimit = limit;
|
|
930
|
+
return holder.stack;
|
|
931
|
+
}
|
|
932
|
+
var attr = (attributes, ...names) => {
|
|
933
|
+
for (const name of names) {
|
|
934
|
+
const value = attributes[name];
|
|
935
|
+
if (value !== void 0 && value !== null && value !== "") return String(value);
|
|
936
|
+
}
|
|
937
|
+
return null;
|
|
938
|
+
};
|
|
939
|
+
function reportOf(failure) {
|
|
940
|
+
const error = failure.error;
|
|
941
|
+
const code = (error?.code !== void 0 ? String(error.code) : null) ?? failure.code;
|
|
942
|
+
const type = dbErrorType(failure.system, code, error?.name);
|
|
943
|
+
const message = error?.message || failure.scrubbed?.replace(/^.*?error of type '[^']*' occurred/i, `${SYSTEM_NAMES[failure.system] ?? "Database"} error`) || "The query failed";
|
|
944
|
+
const { stack, context: context3 } = sourced([`${type}: ${message}`, ...failure.frames].join("\n"));
|
|
945
|
+
const attributes = {
|
|
946
|
+
...context3 ? { [SOURCE_CONTEXT_ATTRIBUTE]: context3 } : {},
|
|
947
|
+
"zharp.mechanism": "db",
|
|
948
|
+
"db.system": failure.system,
|
|
949
|
+
...failure.statement ? { "db.statement": failure.statement.slice(0, 4e3) } : {},
|
|
950
|
+
...failure.database ? { "db.name": failure.database } : {},
|
|
951
|
+
...code ? { "db.error.code": code } : {},
|
|
952
|
+
...error?.constraint ? { "db.error.constraint": error.constraint } : {}
|
|
953
|
+
};
|
|
954
|
+
return { type, message, stack, attributes, spanContext: failure.spanContext };
|
|
955
|
+
}
|
|
956
|
+
var LONE_WAIT_MS = 1500;
|
|
957
|
+
var MAX_PENDING = 200;
|
|
958
|
+
var DbErrorSpanProcessor = class _DbErrorSpanProcessor {
|
|
959
|
+
constructor(send) {
|
|
960
|
+
this.send = send;
|
|
961
|
+
}
|
|
962
|
+
send;
|
|
963
|
+
callSites = /* @__PURE__ */ new WeakMap();
|
|
964
|
+
/** Failures not yet reported, by trace. */
|
|
965
|
+
pending = /* @__PURE__ */ new Map();
|
|
966
|
+
onStart(span, parentContext) {
|
|
967
|
+
const attributes = span.attributes ?? {};
|
|
968
|
+
if (!attr(attributes, "db.system", "db.system.name")) return;
|
|
969
|
+
const carried = (parentContext ?? import_api.context.active()).getValue(CALL_SITE);
|
|
970
|
+
const entry = {
|
|
971
|
+
frames: callSiteFrames(carried ?? stackFrom(_DbErrorSpanProcessor.prototype.onStart))
|
|
972
|
+
};
|
|
973
|
+
this.callSites.set(span, entry);
|
|
974
|
+
const record = span.recordException.bind(span);
|
|
975
|
+
span.recordException = (exception, time) => {
|
|
976
|
+
if (entry.exception === void 0) entry.exception = exception;
|
|
977
|
+
else record(exception, time);
|
|
978
|
+
};
|
|
979
|
+
}
|
|
980
|
+
onEnd(span) {
|
|
981
|
+
const entry = this.callSites.get(span);
|
|
982
|
+
if (entry && span.status.code === import_api.SpanStatusCode.ERROR) {
|
|
983
|
+
const attributes = span.attributes ?? {};
|
|
984
|
+
const exception = entry.exception;
|
|
985
|
+
const failure = {
|
|
986
|
+
spanContext: span.spanContext(),
|
|
987
|
+
traceId: span.spanContext().traceId,
|
|
988
|
+
system: attr(attributes, "db.system", "db.system.name") ?? "database",
|
|
989
|
+
statement: attr(attributes, "db.statement", "db.query.text"),
|
|
990
|
+
database: attr(attributes, "db.name", "db.namespace"),
|
|
991
|
+
code: attr(attributes, "error.type", "db.response.status_code"),
|
|
992
|
+
frames: entry.frames,
|
|
993
|
+
scrubbed: typeof exception === "string" ? exception : exception?.message ?? span.status.message ?? null,
|
|
994
|
+
...exception instanceof Error ? { error: exception } : {}
|
|
995
|
+
};
|
|
996
|
+
this.add(failure);
|
|
997
|
+
}
|
|
998
|
+
const root = span.kind === import_api.SpanKind.SERVER || !span.parentSpanContext || !!span.parentSpanContext.isRemote;
|
|
999
|
+
if (root) {
|
|
1000
|
+
const traceId = span.spanContext().traceId;
|
|
1001
|
+
if (!this.pending.has(traceId)) return;
|
|
1002
|
+
if (entry || span.status.code === import_api.SpanStatusCode.ERROR) setTimeout(() => this.flush(traceId), LONE_WAIT_MS).unref?.();
|
|
1003
|
+
else this.flush(traceId);
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
add(failure) {
|
|
1007
|
+
const list = this.pending.get(failure.traceId) ?? [];
|
|
1008
|
+
list.push(failure);
|
|
1009
|
+
this.pending.set(failure.traceId, list);
|
|
1010
|
+
if (this.pending.size > MAX_PENDING) this.flush(this.pending.keys().next().value);
|
|
1011
|
+
}
|
|
1012
|
+
/** The driver's error, seen by the query wrapper: joined to the trace's latest failure. */
|
|
1013
|
+
attach(traceId, error) {
|
|
1014
|
+
if (!traceId || !(error instanceof Error)) return;
|
|
1015
|
+
const list = this.pending.get(traceId);
|
|
1016
|
+
if (!list || list.some((f) => f.error === error)) return;
|
|
1017
|
+
const failure = [...list].reverse().find((f) => !f.error && !f.done);
|
|
1018
|
+
if (failure) failure.error = error;
|
|
1019
|
+
}
|
|
1020
|
+
/**
|
|
1021
|
+
* `error` is being reported (by a framework's handler, as unhandled, or by captureError): the
|
|
1022
|
+
* failed query it came from, if any, so its details go into that one report and it isn't sent
|
|
1023
|
+
* again. Matched by the error itself, or what wraps it (`driverError`, `cause`); `latest` also
|
|
1024
|
+
* takes the request's latest failure whose driver error was never seen.
|
|
1025
|
+
*/
|
|
1026
|
+
consume(traceId, error, latest = false) {
|
|
1027
|
+
const inner = (candidate) => {
|
|
1028
|
+
if (!candidate || typeof candidate !== "object") return [];
|
|
1029
|
+
const c = candidate;
|
|
1030
|
+
return [candidate, c.driverError, c.cause, c.originalError].filter(Boolean);
|
|
1031
|
+
};
|
|
1032
|
+
const wanted2 = inner(error);
|
|
1033
|
+
const lists = traceId ? [this.pending.get(traceId) ?? []] : [...this.pending.values()];
|
|
1034
|
+
for (const list of lists) {
|
|
1035
|
+
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);
|
|
1036
|
+
if (failure) {
|
|
1037
|
+
failure.done = true;
|
|
1038
|
+
return failure;
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
return null;
|
|
1042
|
+
}
|
|
1043
|
+
flush(traceId) {
|
|
1044
|
+
const list = this.pending.get(traceId);
|
|
1045
|
+
if (!list) return;
|
|
1046
|
+
this.pending.delete(traceId);
|
|
1047
|
+
for (const failure of list) if (!failure.done) this.send(failure);
|
|
1048
|
+
}
|
|
1049
|
+
forceFlush() {
|
|
1050
|
+
for (const traceId of [...this.pending.keys()]) this.flush(traceId);
|
|
1051
|
+
return Promise.resolve();
|
|
1052
|
+
}
|
|
1053
|
+
shutdown() {
|
|
1054
|
+
return this.forceFlush();
|
|
1055
|
+
}
|
|
1056
|
+
};
|
|
1057
|
+
var DbDriverErrorsInstrumentation = class extends import_instrumentation.InstrumentationBase {
|
|
1058
|
+
constructor(onError) {
|
|
1059
|
+
super("@zharp/node/db-driver-errors", VERSION, {});
|
|
1060
|
+
this.onError = onError;
|
|
1061
|
+
}
|
|
1062
|
+
onError;
|
|
1063
|
+
init() {
|
|
1064
|
+
const onError = (traceId, err) => {
|
|
1065
|
+
try {
|
|
1066
|
+
this.onError(traceId, err);
|
|
1067
|
+
} catch {
|
|
1068
|
+
}
|
|
1069
|
+
};
|
|
1070
|
+
const wrapQuery = (original2) => {
|
|
1071
|
+
const run = (self, args) => {
|
|
1072
|
+
const traceId = import_api.trace.getActiveSpan()?.spanContext().traceId;
|
|
1073
|
+
const callback = args.findIndex((a) => typeof a === "function");
|
|
1074
|
+
if (callback >= 0) {
|
|
1075
|
+
const cb = args[callback];
|
|
1076
|
+
args[callback] = function(err, ...rest) {
|
|
1077
|
+
if (err) onError(traceId, err);
|
|
1078
|
+
return cb.call(this, err, ...rest);
|
|
1079
|
+
};
|
|
1080
|
+
return original2.apply(self, args);
|
|
1081
|
+
}
|
|
1082
|
+
const result = original2.apply(self, args);
|
|
1083
|
+
if (!result || typeof result.then !== "function" || typeof result.submit === "function") return result;
|
|
1084
|
+
result.then(void 0, (err) => onError(traceId, err));
|
|
1085
|
+
return result;
|
|
1086
|
+
};
|
|
1087
|
+
return function query(...args) {
|
|
1088
|
+
const active = import_api.context.active();
|
|
1089
|
+
if (active.getValue(CALL_SITE) !== void 0) return run(this, args);
|
|
1090
|
+
return import_api.context.with(active.setValue(CALL_SITE, stackFrom(query)), () => run(this, args));
|
|
1091
|
+
};
|
|
1092
|
+
};
|
|
1093
|
+
const patch = (moduleExports) => {
|
|
1094
|
+
for (const target of [moduleExports?.Client?.prototype, moduleExports?.Pool?.prototype]) {
|
|
1095
|
+
if (target?.query && !target.query.__zharpWrapped) {
|
|
1096
|
+
const wrapped = wrapQuery(target.query);
|
|
1097
|
+
wrapped.__zharpWrapped = true;
|
|
1098
|
+
wrapped.__zharpOriginal = target.query;
|
|
1099
|
+
target.query = wrapped;
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
return moduleExports;
|
|
1103
|
+
};
|
|
1104
|
+
const unpatch = (moduleExports) => {
|
|
1105
|
+
for (const target of [moduleExports?.Client?.prototype, moduleExports?.Pool?.prototype]) {
|
|
1106
|
+
if (target?.query?.__zharpOriginal) target.query = target.query.__zharpOriginal;
|
|
1107
|
+
}
|
|
1108
|
+
};
|
|
1109
|
+
return [new import_instrumentation.InstrumentationNodeModuleDefinition("pg", [">=8 <9"], patch, unpatch)];
|
|
1110
|
+
}
|
|
1111
|
+
};
|
|
1112
|
+
|
|
1113
|
+
// src/framework-errors.ts
|
|
1114
|
+
var import_instrumentation2 = require("@opentelemetry/instrumentation");
|
|
1115
|
+
function statusOf(error) {
|
|
1116
|
+
if (!error || typeof error !== "object") return 500;
|
|
1117
|
+
const e = error;
|
|
1118
|
+
try {
|
|
1119
|
+
if (typeof e.getStatus === "function") {
|
|
1120
|
+
const status = Number(e.getStatus());
|
|
1121
|
+
if (Number.isFinite(status)) return status;
|
|
1122
|
+
}
|
|
1123
|
+
} catch {
|
|
1124
|
+
}
|
|
1125
|
+
for (const value of [e.status, e.statusCode]) {
|
|
1126
|
+
const status = Number(value);
|
|
1127
|
+
if (Number.isInteger(status) && status >= 100 && status < 600) return status;
|
|
1128
|
+
}
|
|
1129
|
+
return 500;
|
|
1130
|
+
}
|
|
1131
|
+
var WRAPPED = /* @__PURE__ */ Symbol.for("zharp.frameworkErrors");
|
|
1132
|
+
var FrameworkErrorsInstrumentation = class extends import_instrumentation2.InstrumentationBase {
|
|
1133
|
+
constructor(sink) {
|
|
1134
|
+
super("@zharp/node/framework-errors", VERSION, {});
|
|
1135
|
+
this.sink = sink;
|
|
1136
|
+
}
|
|
1137
|
+
sink;
|
|
1138
|
+
init() {
|
|
1139
|
+
const report = (error, mechanism) => {
|
|
1140
|
+
try {
|
|
1141
|
+
if (statusOf(error) >= 500) this.sink(error, mechanism);
|
|
1142
|
+
} catch {
|
|
1143
|
+
}
|
|
1144
|
+
};
|
|
1145
|
+
const nest = new import_instrumentation2.InstrumentationNodeModuleFile(
|
|
1146
|
+
"@nestjs/core/exceptions/exceptions-handler.js",
|
|
1147
|
+
[">=8 <13"],
|
|
1148
|
+
(moduleExports) => {
|
|
1149
|
+
const proto = moduleExports?.ExceptionsHandler?.prototype;
|
|
1150
|
+
if (proto?.next && !proto.next[WRAPPED]) {
|
|
1151
|
+
const original2 = proto.next;
|
|
1152
|
+
const next = function(exception, ...rest) {
|
|
1153
|
+
report(exception, "nestjs");
|
|
1154
|
+
return original2.call(this, exception, ...rest);
|
|
1155
|
+
};
|
|
1156
|
+
next[WRAPPED] = original2;
|
|
1157
|
+
proto.next = next;
|
|
1158
|
+
}
|
|
1159
|
+
return moduleExports;
|
|
1160
|
+
},
|
|
1161
|
+
(moduleExports) => {
|
|
1162
|
+
const proto = moduleExports?.ExceptionsHandler?.prototype;
|
|
1163
|
+
if (proto?.next?.[WRAPPED]) proto.next = proto.next[WRAPPED];
|
|
1164
|
+
}
|
|
1165
|
+
);
|
|
1166
|
+
const finalhandler = new import_instrumentation2.InstrumentationNodeModuleDefinition(
|
|
1167
|
+
"finalhandler",
|
|
1168
|
+
[">=1 <3"],
|
|
1169
|
+
(moduleExports) => {
|
|
1170
|
+
if (typeof moduleExports !== "function" || moduleExports[WRAPPED]) return moduleExports;
|
|
1171
|
+
const original2 = moduleExports;
|
|
1172
|
+
const wrapped = function(...args) {
|
|
1173
|
+
const done = original2.apply(this, args);
|
|
1174
|
+
return function(err, ...rest) {
|
|
1175
|
+
if (err) report(err, "express");
|
|
1176
|
+
return done.call(this, err, ...rest);
|
|
1177
|
+
};
|
|
1178
|
+
};
|
|
1179
|
+
Object.assign(wrapped, original2);
|
|
1180
|
+
wrapped[WRAPPED] = original2;
|
|
1181
|
+
return wrapped;
|
|
1182
|
+
},
|
|
1183
|
+
(moduleExports) => moduleExports?.[WRAPPED] ?? moduleExports
|
|
1184
|
+
);
|
|
1185
|
+
return [new import_instrumentation2.InstrumentationNodeModuleDefinition("@nestjs/core", [">=8 <13"], void 0, void 0, [nest]), finalhandler];
|
|
1186
|
+
}
|
|
1187
|
+
};
|
|
1188
|
+
var RecordedExceptionsProcessor = class {
|
|
1189
|
+
constructor(report) {
|
|
1190
|
+
this.report = report;
|
|
1191
|
+
}
|
|
1192
|
+
report;
|
|
1193
|
+
pending = /* @__PURE__ */ new Map();
|
|
1194
|
+
onStart(span) {
|
|
1195
|
+
const scope = span.instrumentationScope?.name ?? span.instrumentationLibrary?.name ?? "";
|
|
1196
|
+
if (!scope.startsWith("@opentelemetry/instrumentation-") && scope !== "next.js") return;
|
|
1197
|
+
if (span.attributes?.["db.system"] || span.attributes?.["db.system.name"]) return;
|
|
1198
|
+
const original2 = span.recordException.bind(span);
|
|
1199
|
+
span.recordException = (exception, time) => {
|
|
1200
|
+
try {
|
|
1201
|
+
if (!exception || typeof exception !== "object") return original2(exception, time);
|
|
1202
|
+
const name = typeof exception.name === "string" && exception.name !== "error" ? exception.name : exception.constructor?.name || "Error";
|
|
1203
|
+
span.addEvent("exception", {
|
|
1204
|
+
"exception.type": name,
|
|
1205
|
+
"exception.message": String(exception.message ?? ""),
|
|
1206
|
+
...typeof exception.stack === "string" ? { "exception.stacktrace": exception.stack } : {},
|
|
1207
|
+
"zharp.deferred": "true"
|
|
1208
|
+
}, time);
|
|
1209
|
+
const traceId = span.spanContext().traceId;
|
|
1210
|
+
const list = this.pending.get(traceId) ?? [];
|
|
1211
|
+
if (!list.some((p) => p.error === exception)) list.push({ error: exception, spanContext: span.spanContext(), scope: mechanismOf(scope) });
|
|
1212
|
+
this.pending.set(traceId, list);
|
|
1213
|
+
if (this.pending.size > 500) this.pending.delete(this.pending.keys().next().value);
|
|
1214
|
+
} catch {
|
|
1215
|
+
original2(exception, time);
|
|
1216
|
+
}
|
|
1217
|
+
};
|
|
1218
|
+
}
|
|
1219
|
+
onEnd(span) {
|
|
1220
|
+
const parent = span.parentSpanContext;
|
|
1221
|
+
const isRoot = span.kind === 1 || !parent || parent.isRemote;
|
|
1222
|
+
if (!isRoot) return;
|
|
1223
|
+
const traceId = span.spanContext().traceId;
|
|
1224
|
+
const list = this.pending.get(traceId);
|
|
1225
|
+
if (!list) return;
|
|
1226
|
+
this.pending.delete(traceId);
|
|
1227
|
+
const status = Number(span.attributes?.["http.response.status_code"] ?? span.attributes?.["http.status_code"]);
|
|
1228
|
+
const failed = Number.isFinite(status) && status > 0 ? status >= 500 : span.status?.code === 2;
|
|
1229
|
+
if (!failed) return;
|
|
1230
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1231
|
+
for (const p of list) {
|
|
1232
|
+
if (seen.has(p.error)) continue;
|
|
1233
|
+
seen.add(p.error);
|
|
1234
|
+
if (statusOf(p.error) < 500) continue;
|
|
1235
|
+
this.report(p.error, p.spanContext, p.scope);
|
|
1236
|
+
break;
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
forceFlush() {
|
|
1240
|
+
return Promise.resolve();
|
|
1241
|
+
}
|
|
1242
|
+
shutdown() {
|
|
1243
|
+
this.pending.clear();
|
|
1244
|
+
return Promise.resolve();
|
|
1245
|
+
}
|
|
1246
|
+
};
|
|
1247
|
+
function mechanismOf(scope) {
|
|
1248
|
+
const name = scope.replace("@opentelemetry/instrumentation-", "").replace(/-core$/, "");
|
|
1249
|
+
if (name === "router") return "express";
|
|
1250
|
+
return name === "next.js" ? "nextjs" : name;
|
|
1251
|
+
}
|
|
1252
|
+
|
|
671
1253
|
// src/urls.ts
|
|
672
1254
|
var URL_KEYS = ["url.full", "http.url", "http.target"];
|
|
673
1255
|
var UrlRedactionSpanProcessor = class {
|
|
@@ -703,7 +1285,7 @@ var UrlRedactionSpanProcessor = class {
|
|
|
703
1285
|
};
|
|
704
1286
|
|
|
705
1287
|
// src/context.ts
|
|
706
|
-
var
|
|
1288
|
+
var import_api2 = require("@opentelemetry/api");
|
|
707
1289
|
var BAGGAGE_KEYS = ["enduser.id", "session.id"];
|
|
708
1290
|
function userAttributes(user) {
|
|
709
1291
|
const out = { "enduser.id": String(user.id) };
|
|
@@ -720,7 +1302,7 @@ var ContextStore = class {
|
|
|
720
1302
|
localRoots = /* @__PURE__ */ new Map();
|
|
721
1303
|
/** Set the user for the request in progress, or for the whole process outside one. */
|
|
722
1304
|
setUser(user) {
|
|
723
|
-
const span =
|
|
1305
|
+
const span = import_api2.trace.getActiveSpan();
|
|
724
1306
|
const traceId = span?.spanContext().traceId;
|
|
725
1307
|
if (!span || !traceId) {
|
|
726
1308
|
this.globalUser = user;
|
|
@@ -740,7 +1322,7 @@ var ContextStore = class {
|
|
|
740
1322
|
return user ? { ...this.tags, ...user } : { ...this.tags };
|
|
741
1323
|
}
|
|
742
1324
|
noteStart(span, parent) {
|
|
743
|
-
const parentSpan =
|
|
1325
|
+
const parentSpan = import_api2.trace.getSpanContext(parent);
|
|
744
1326
|
if (!parentSpan || parentSpan.isRemote) {
|
|
745
1327
|
const { traceId, spanId } = span.spanContext();
|
|
746
1328
|
if (!this.localRoots.has(traceId)) this.localRoots.set(traceId, { spanId, span });
|
|
@@ -755,7 +1337,7 @@ var ContextStore = class {
|
|
|
755
1337
|
};
|
|
756
1338
|
function fromBaggage(ctx) {
|
|
757
1339
|
const out = {};
|
|
758
|
-
const baggage =
|
|
1340
|
+
const baggage = import_api2.propagation.getBaggage(ctx);
|
|
759
1341
|
if (!baggage) return out;
|
|
760
1342
|
for (const key of BAGGAGE_KEYS) {
|
|
761
1343
|
const value = baggage.getEntry(key)?.value;
|
|
@@ -792,8 +1374,8 @@ var ContextLogProcessor = class {
|
|
|
792
1374
|
store;
|
|
793
1375
|
onEmit(record, ctx) {
|
|
794
1376
|
try {
|
|
795
|
-
const active = ctx ??
|
|
796
|
-
const traceId = record.spanContext?.traceId ??
|
|
1377
|
+
const active = ctx ?? import_api2.context.active();
|
|
1378
|
+
const traceId = record.spanContext?.traceId ?? import_api2.trace.getSpanContext(active)?.traceId;
|
|
797
1379
|
const add = { ...this.store.attributesFor(traceId), ...fromBaggage(active) };
|
|
798
1380
|
for (const [key, value] of Object.entries(add)) {
|
|
799
1381
|
if (record.attributes[key] === void 0) record.setAttribute(key, value);
|
|
@@ -811,7 +1393,7 @@ var ContextLogProcessor = class {
|
|
|
811
1393
|
|
|
812
1394
|
// src/console.ts
|
|
813
1395
|
var import_node_util = require("util");
|
|
814
|
-
var
|
|
1396
|
+
var import_api3 = require("@opentelemetry/api");
|
|
815
1397
|
|
|
816
1398
|
// src/capture-state.ts
|
|
817
1399
|
var depth = 0;
|
|
@@ -851,22 +1433,22 @@ function alreadySent(line) {
|
|
|
851
1433
|
|
|
852
1434
|
// src/console.ts
|
|
853
1435
|
var LEVELS = [
|
|
854
|
-
["debug",
|
|
855
|
-
["trace",
|
|
856
|
-
["log",
|
|
857
|
-
["info",
|
|
858
|
-
["warn",
|
|
859
|
-
["error",
|
|
1436
|
+
["debug", import_api3.SeverityNumber.DEBUG, "DEBUG"],
|
|
1437
|
+
["trace", import_api3.SeverityNumber.TRACE, "TRACE"],
|
|
1438
|
+
["log", import_api3.SeverityNumber.INFO, "INFO"],
|
|
1439
|
+
["info", import_api3.SeverityNumber.INFO, "INFO"],
|
|
1440
|
+
["warn", import_api3.SeverityNumber.WARN, "WARN"],
|
|
1441
|
+
["error", import_api3.SeverityNumber.ERROR, "ERROR"]
|
|
860
1442
|
];
|
|
861
1443
|
var emitting = false;
|
|
862
1444
|
function captureConsole(logger) {
|
|
863
1445
|
const originals = /* @__PURE__ */ new Map();
|
|
864
1446
|
for (const [method, severityNumber, severityText] of LEVELS) {
|
|
865
|
-
const
|
|
866
|
-
if (typeof
|
|
867
|
-
originals.set(method,
|
|
1447
|
+
const original2 = console[method];
|
|
1448
|
+
if (typeof original2 !== "function" || original2.__zharp) continue;
|
|
1449
|
+
originals.set(method, original2);
|
|
868
1450
|
const patched = function(...args) {
|
|
869
|
-
quiet(() =>
|
|
1451
|
+
quiet(() => original2.apply(this ?? console, args));
|
|
870
1452
|
if (emitting) return;
|
|
871
1453
|
emitting = true;
|
|
872
1454
|
try {
|
|
@@ -883,34 +1465,34 @@ function captureConsole(logger) {
|
|
|
883
1465
|
console[method] = patched;
|
|
884
1466
|
}
|
|
885
1467
|
return () => {
|
|
886
|
-
for (const [method,
|
|
1468
|
+
for (const [method, original2] of originals) console[method] = original2;
|
|
887
1469
|
};
|
|
888
1470
|
}
|
|
889
1471
|
|
|
890
1472
|
// src/stdout.ts
|
|
891
|
-
var
|
|
1473
|
+
var import_api4 = require("@opentelemetry/api");
|
|
892
1474
|
var LEVELS2 = {
|
|
893
|
-
trace: [
|
|
894
|
-
verbose: [
|
|
895
|
-
debug: [
|
|
896
|
-
log: [
|
|
897
|
-
info: [
|
|
898
|
-
notice: [
|
|
899
|
-
warn: [
|
|
900
|
-
warning: [
|
|
901
|
-
error: [
|
|
902
|
-
err: [
|
|
903
|
-
crit: [
|
|
904
|
-
critical: [
|
|
905
|
-
fatal: [
|
|
906
|
-
emerg: [
|
|
907
|
-
alert: [
|
|
1475
|
+
trace: [import_api4.SeverityNumber.TRACE, "TRACE"],
|
|
1476
|
+
verbose: [import_api4.SeverityNumber.DEBUG, "DEBUG"],
|
|
1477
|
+
debug: [import_api4.SeverityNumber.DEBUG, "DEBUG"],
|
|
1478
|
+
log: [import_api4.SeverityNumber.INFO, "INFO"],
|
|
1479
|
+
info: [import_api4.SeverityNumber.INFO, "INFO"],
|
|
1480
|
+
notice: [import_api4.SeverityNumber.INFO, "INFO"],
|
|
1481
|
+
warn: [import_api4.SeverityNumber.WARN, "WARN"],
|
|
1482
|
+
warning: [import_api4.SeverityNumber.WARN, "WARN"],
|
|
1483
|
+
error: [import_api4.SeverityNumber.ERROR, "ERROR"],
|
|
1484
|
+
err: [import_api4.SeverityNumber.ERROR, "ERROR"],
|
|
1485
|
+
crit: [import_api4.SeverityNumber.FATAL, "FATAL"],
|
|
1486
|
+
critical: [import_api4.SeverityNumber.FATAL, "FATAL"],
|
|
1487
|
+
fatal: [import_api4.SeverityNumber.FATAL, "FATAL"],
|
|
1488
|
+
emerg: [import_api4.SeverityNumber.FATAL, "FATAL"],
|
|
1489
|
+
alert: [import_api4.SeverityNumber.FATAL, "FATAL"]
|
|
908
1490
|
};
|
|
909
1491
|
var NUMERIC = [[60, "fatal"], [50, "error"], [40, "warn"], [30, "info"], [20, "debug"], [0, "trace"]];
|
|
910
1492
|
var ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]/g;
|
|
911
1493
|
var NEST = /^\[Nest\]\s+\d+\s+-\s+.*?\s+(LOG|ERROR|WARN|DEBUG|VERBOSE|FATAL)\s+(?:\[([^\]]+)\]\s+)?([\s\S]*)$/;
|
|
912
1494
|
var WORD = /(?:^|[\s[(|:=])(trace|verbose|debug|info|notice|warn(?:ing)?|err(?:or)?|crit(?:ical)?|fatal|emerg|alert)(?=$|[\s\]):|,])/i;
|
|
913
|
-
var
|
|
1495
|
+
var MAX_LINE2 = 32 * 1024;
|
|
914
1496
|
var FLUSH_MS = 200;
|
|
915
1497
|
function levelOf(value) {
|
|
916
1498
|
if (typeof value === "number") {
|
|
@@ -963,13 +1545,13 @@ function captureOutput(logger) {
|
|
|
963
1545
|
[process.stderr, "stderr", LEVELS2.warn]
|
|
964
1546
|
]) {
|
|
965
1547
|
if (!stream || typeof stream.write !== "function" || stream.write.__zharp) continue;
|
|
966
|
-
const
|
|
1548
|
+
const original2 = stream.write;
|
|
967
1549
|
let pending = "";
|
|
968
1550
|
let pendingContext;
|
|
969
1551
|
let timer;
|
|
970
1552
|
const emitLine = (line, ctx) => {
|
|
971
1553
|
if (!line.trim() || line.includes("[Zharp]") || alreadySent(line)) return;
|
|
972
|
-
const parsed2 = parseLine(line.length >
|
|
1554
|
+
const parsed2 = parseLine(line.length > MAX_LINE2 ? line.slice(0, MAX_LINE2) : line);
|
|
973
1555
|
if (!parsed2.body.trim()) return;
|
|
974
1556
|
const [severityNumber, severityText] = parsed2.level ?? fallback;
|
|
975
1557
|
quiet(() => logger.emit({
|
|
@@ -992,14 +1574,14 @@ function captureOutput(logger) {
|
|
|
992
1574
|
if (isQuiet()) return;
|
|
993
1575
|
const text = typeof chunk === "string" ? chunk : chunk instanceof Uint8Array ? Buffer.from(chunk).toString(typeof encoding === "string" ? encoding : "utf8") : "";
|
|
994
1576
|
if (!text) return;
|
|
995
|
-
if (!pending) pendingContext =
|
|
1577
|
+
if (!pending) pendingContext = import_api4.context.active();
|
|
996
1578
|
pending += text;
|
|
997
1579
|
const lines = pending.split("\n");
|
|
998
1580
|
pending = lines.pop() ?? "";
|
|
999
1581
|
const ctx = pendingContext;
|
|
1000
|
-
if (pending) pendingContext =
|
|
1582
|
+
if (pending) pendingContext = import_api4.context.active();
|
|
1001
1583
|
for (const line of lines) emitLine(line, ctx);
|
|
1002
|
-
if (pending.length >
|
|
1584
|
+
if (pending.length > MAX_LINE2) flush();
|
|
1003
1585
|
else if (pending && !timer) {
|
|
1004
1586
|
timer = setTimeout(flush, FLUSH_MS);
|
|
1005
1587
|
timer.unref?.();
|
|
@@ -1010,14 +1592,14 @@ function captureOutput(logger) {
|
|
|
1010
1592
|
take(chunk, encoding);
|
|
1011
1593
|
} catch {
|
|
1012
1594
|
}
|
|
1013
|
-
return
|
|
1595
|
+
return original2.call(this ?? stream, chunk, encoding, callback);
|
|
1014
1596
|
};
|
|
1015
1597
|
patched.__zharp = true;
|
|
1016
1598
|
stream.write = patched;
|
|
1017
1599
|
undo.push(() => {
|
|
1018
1600
|
if (timer) clearTimeout(timer);
|
|
1019
1601
|
if (pending) flush();
|
|
1020
|
-
stream.write =
|
|
1602
|
+
stream.write = original2;
|
|
1021
1603
|
});
|
|
1022
1604
|
}
|
|
1023
1605
|
return () => undo.forEach((fn) => fn());
|
|
@@ -1026,26 +1608,26 @@ function stampOutput() {
|
|
|
1026
1608
|
const undo = [];
|
|
1027
1609
|
for (const stream of [process.stdout, process.stderr]) {
|
|
1028
1610
|
if (!stream || typeof stream.write !== "function" || stream.write.__zharpStamp) continue;
|
|
1029
|
-
const
|
|
1611
|
+
const original2 = stream.write;
|
|
1030
1612
|
const patched = function(chunk, encoding, callback) {
|
|
1031
1613
|
let out = chunk;
|
|
1032
1614
|
try {
|
|
1033
1615
|
out = stamped(chunk, encoding);
|
|
1034
1616
|
} catch {
|
|
1035
1617
|
}
|
|
1036
|
-
return
|
|
1618
|
+
return original2.call(this ?? stream, out, encoding, callback);
|
|
1037
1619
|
};
|
|
1038
1620
|
patched.__zharpStamp = true;
|
|
1039
1621
|
stream.write = patched;
|
|
1040
1622
|
undo.push(() => {
|
|
1041
|
-
stream.write =
|
|
1623
|
+
stream.write = original2;
|
|
1042
1624
|
});
|
|
1043
1625
|
}
|
|
1044
1626
|
return () => undo.forEach((fn) => fn());
|
|
1045
1627
|
}
|
|
1046
1628
|
function stamped(chunk, encoding) {
|
|
1047
|
-
const span =
|
|
1048
|
-
if (!span || !(0,
|
|
1629
|
+
const span = import_api4.trace.getActiveSpan()?.spanContext();
|
|
1630
|
+
if (!span || !(0, import_api4.isSpanContextValid)(span)) return chunk;
|
|
1049
1631
|
const isBytes = chunk instanceof Uint8Array;
|
|
1050
1632
|
if (typeof chunk !== "string" && !isBytes) return chunk;
|
|
1051
1633
|
const enc = typeof encoding === "string" && Buffer.isEncoding(encoding) ? encoding : "utf8";
|
|
@@ -1090,7 +1672,7 @@ function stampLine(line, traceId, spanId) {
|
|
|
1090
1672
|
|
|
1091
1673
|
// ../../internal/src/debug-ids.ts
|
|
1092
1674
|
var DEBUG_IDS_ATTRIBUTE = "zharp.debug_ids";
|
|
1093
|
-
var
|
|
1675
|
+
var files2 = /* @__PURE__ */ new Map();
|
|
1094
1676
|
var parsed = /* @__PURE__ */ new Set();
|
|
1095
1677
|
function registry() {
|
|
1096
1678
|
const g2 = typeof globalThis !== "undefined" ? globalThis : void 0;
|
|
@@ -1106,7 +1688,8 @@ function frameFile(line) {
|
|
|
1106
1688
|
match = /^(?:[^@]*@)?(.+?):\d+:\d+$/.exec(text);
|
|
1107
1689
|
return match ? clean(match[1]) : void 0;
|
|
1108
1690
|
}
|
|
1109
|
-
function clean(
|
|
1691
|
+
function clean(raw) {
|
|
1692
|
+
const file = raw.replace(/^address at /, "");
|
|
1110
1693
|
if (!file || file.includes("eval at ") || file === "<anonymous>" || file === "native") return void 0;
|
|
1111
1694
|
return file;
|
|
1112
1695
|
}
|
|
@@ -1129,7 +1712,7 @@ function refresh() {
|
|
|
1129
1712
|
for (const line of stack.split("\n")) {
|
|
1130
1713
|
const file = frameFile(line);
|
|
1131
1714
|
if (file) {
|
|
1132
|
-
|
|
1715
|
+
files2.set(file, id);
|
|
1133
1716
|
break;
|
|
1134
1717
|
}
|
|
1135
1718
|
}
|
|
@@ -1139,10 +1722,10 @@ function debugIdsFor(stack) {
|
|
|
1139
1722
|
if (!stack) return void 0;
|
|
1140
1723
|
try {
|
|
1141
1724
|
refresh();
|
|
1142
|
-
if (
|
|
1725
|
+
if (files2.size === 0) return void 0;
|
|
1143
1726
|
let out;
|
|
1144
1727
|
for (const file of stackFiles(stack)) {
|
|
1145
|
-
const id =
|
|
1728
|
+
const id = files2.get(file);
|
|
1146
1729
|
if (id) (out ??= {})[file] = id;
|
|
1147
1730
|
}
|
|
1148
1731
|
return out;
|
|
@@ -1225,17 +1808,284 @@ function exceptionAttributes(error, handled) {
|
|
|
1225
1808
|
const cause = error.cause;
|
|
1226
1809
|
if (cause instanceof Error && cause.stack) stack += `
|
|
1227
1810
|
Caused by: ${cause.stack}`;
|
|
1811
|
+
const { stack: readable, context: context3 } = sourced(stack);
|
|
1228
1812
|
return {
|
|
1229
1813
|
"exception.type": type,
|
|
1230
1814
|
"exception.message": message,
|
|
1231
|
-
"exception.stacktrace":
|
|
1815
|
+
"exception.stacktrace": readable,
|
|
1232
1816
|
"zharp.handled": handled ? "true" : "false",
|
|
1233
|
-
|
|
1817
|
+
// From the stack as it ran: frames resolved here keep their bundle's ID for uploaded maps.
|
|
1818
|
+
...debugIdAttributes(stack),
|
|
1819
|
+
...context3 ? { [SOURCE_CONTEXT_ATTRIBUTE]: context3 } : {}
|
|
1234
1820
|
};
|
|
1235
1821
|
}
|
|
1236
1822
|
|
|
1237
|
-
// src/
|
|
1238
|
-
var
|
|
1823
|
+
// src/serverless.ts
|
|
1824
|
+
var import_node_crypto = require("crypto");
|
|
1825
|
+
var DEFAULT_FLUSH_MS = 2e3;
|
|
1826
|
+
var headerGetter = {
|
|
1827
|
+
get(carrier, key) {
|
|
1828
|
+
return header2(carrier, key);
|
|
1829
|
+
},
|
|
1830
|
+
keys(carrier) {
|
|
1831
|
+
if (!carrier || typeof carrier !== "object") return [];
|
|
1832
|
+
if (typeof carrier.keys === "function" && typeof carrier.get === "function") {
|
|
1833
|
+
try {
|
|
1834
|
+
return [...carrier.keys()];
|
|
1835
|
+
} catch {
|
|
1836
|
+
return [];
|
|
1837
|
+
}
|
|
1838
|
+
}
|
|
1839
|
+
return Object.keys(carrier);
|
|
1840
|
+
}
|
|
1841
|
+
};
|
|
1842
|
+
function header2(carrier, name) {
|
|
1843
|
+
if (!carrier || typeof carrier !== "object") return void 0;
|
|
1844
|
+
const c = carrier;
|
|
1845
|
+
if (typeof c.get === "function" && typeof c.has === "function") {
|
|
1846
|
+
try {
|
|
1847
|
+
return c.get(name) ?? void 0;
|
|
1848
|
+
} catch {
|
|
1849
|
+
return void 0;
|
|
1850
|
+
}
|
|
1851
|
+
}
|
|
1852
|
+
const wanted2 = name.toLowerCase();
|
|
1853
|
+
for (const key of Object.keys(c)) {
|
|
1854
|
+
if (key.toLowerCase() !== wanted2) continue;
|
|
1855
|
+
const value = c[key];
|
|
1856
|
+
if (Array.isArray(value)) return value.join(",");
|
|
1857
|
+
return value == null ? void 0 : String(value);
|
|
1858
|
+
}
|
|
1859
|
+
return void 0;
|
|
1860
|
+
}
|
|
1861
|
+
function pathOf(url) {
|
|
1862
|
+
if (typeof url !== "string" || !url) return void 0;
|
|
1863
|
+
try {
|
|
1864
|
+
return new URL(url, "http://x").pathname;
|
|
1865
|
+
} catch {
|
|
1866
|
+
return url.split("?")[0];
|
|
1867
|
+
}
|
|
1868
|
+
}
|
|
1869
|
+
function clean2(attrs) {
|
|
1870
|
+
const out = {};
|
|
1871
|
+
for (const [key, value] of Object.entries(attrs)) {
|
|
1872
|
+
if (value === void 0 || value === null || value === "") continue;
|
|
1873
|
+
out[key] = typeof value === "number" || typeof value === "boolean" ? value : String(value);
|
|
1874
|
+
}
|
|
1875
|
+
return out;
|
|
1876
|
+
}
|
|
1877
|
+
var STREAMING = /* @__PURE__ */ Symbol.for("aws.lambda.runtime.handler.streaming");
|
|
1878
|
+
var isStreamingLambda = (handler) => handler?.[STREAMING] === "response";
|
|
1879
|
+
function lambdaInvocation(event, ctx, coldstart) {
|
|
1880
|
+
const rc = event?.requestContext;
|
|
1881
|
+
const v2 = rc?.http && typeof rc.http.method === "string";
|
|
1882
|
+
const v1 = typeof event?.httpMethod === "string" && (rc || event.headers);
|
|
1883
|
+
const http = !!(v2 || v1);
|
|
1884
|
+
const functionName = ctx?.functionName ?? process.env.AWS_LAMBDA_FUNCTION_NAME;
|
|
1885
|
+
const arn = ctx?.invokedFunctionArn;
|
|
1886
|
+
const base = {
|
|
1887
|
+
"faas.trigger": lambdaTrigger(event, http),
|
|
1888
|
+
"faas.invocation_id": ctx?.awsRequestId,
|
|
1889
|
+
"faas.coldstart": coldstart,
|
|
1890
|
+
"faas.name": functionName,
|
|
1891
|
+
"faas.version": ctx?.functionVersion ?? process.env.AWS_LAMBDA_FUNCTION_VERSION,
|
|
1892
|
+
"cloud.provider": "aws",
|
|
1893
|
+
"cloud.platform": "aws_lambda",
|
|
1894
|
+
"cloud.region": process.env.AWS_REGION,
|
|
1895
|
+
"cloud.resource_id": arn,
|
|
1896
|
+
"cloud.account.id": arn?.split(":")[4]
|
|
1897
|
+
};
|
|
1898
|
+
if (!http) {
|
|
1899
|
+
const source = lambdaSource(event);
|
|
1900
|
+
return {
|
|
1901
|
+
name: functionName ?? "lambda",
|
|
1902
|
+
attributes: clean2({ ...base, ...source ? { "faas.event_source": source } : {} }),
|
|
1903
|
+
http: false,
|
|
1904
|
+
mechanism: "aws-lambda"
|
|
1905
|
+
};
|
|
1906
|
+
}
|
|
1907
|
+
const method = v2 ? rc.http.method : event.httpMethod;
|
|
1908
|
+
const path = v2 ? rc.http.path ?? event.rawPath : event.path;
|
|
1909
|
+
const routeKey = rc?.routeKey && rc.routeKey !== "$default" ? rc.routeKey.split(" ").slice(-1)[0] : void 0;
|
|
1910
|
+
const route = routeKey ?? (typeof event.resource === "string" && !event.resource.includes("{proxy+}") ? event.resource : void 0);
|
|
1911
|
+
return {
|
|
1912
|
+
name: `${method} ${route ?? path ?? "/"}`,
|
|
1913
|
+
attributes: clean2({
|
|
1914
|
+
...base,
|
|
1915
|
+
"http.request.method": method,
|
|
1916
|
+
"url.path": path,
|
|
1917
|
+
"http.route": route,
|
|
1918
|
+
"url.scheme": header2(event.headers, "x-forwarded-proto"),
|
|
1919
|
+
"server.address": header2(event.headers, "host") ?? rc?.domainName,
|
|
1920
|
+
"user_agent.original": v2 ? rc.http.userAgent : header2(event.headers, "user-agent"),
|
|
1921
|
+
"client.address": v2 ? rc.http.sourceIp : rc?.identity?.sourceIp
|
|
1922
|
+
}),
|
|
1923
|
+
// REST API events may carry the same header in both maps; the single-value one is enough.
|
|
1924
|
+
carrier: event.headers ?? event.multiValueHeaders,
|
|
1925
|
+
http: true,
|
|
1926
|
+
mechanism: "aws-lambda"
|
|
1927
|
+
};
|
|
1928
|
+
}
|
|
1929
|
+
function lambdaSource(event) {
|
|
1930
|
+
const record = Array.isArray(event?.Records) ? event.Records[0] : void 0;
|
|
1931
|
+
return record?.eventSource ?? record?.EventSource ?? (typeof event?.source === "string" ? event.source : void 0);
|
|
1932
|
+
}
|
|
1933
|
+
function lambdaTrigger(event, http) {
|
|
1934
|
+
if (http || event?.requestContext?.elb) return "http";
|
|
1935
|
+
const source = lambdaSource(event) ?? "";
|
|
1936
|
+
if (/^aws:(sqs|sns|kinesis|kafka)$/.test(source) || source === "aws:mq" || event?.eventSource === "aws:kafka") return "pubsub";
|
|
1937
|
+
if (/^aws:(s3|dynamodb)$/.test(source)) return "datasource";
|
|
1938
|
+
if (event?.["detail-type"] === "Scheduled Event" || source === "aws.scheduler") return "timer";
|
|
1939
|
+
return "other";
|
|
1940
|
+
}
|
|
1941
|
+
function lambdaStatus(result, event) {
|
|
1942
|
+
if (result && typeof result === "object" && typeof result.statusCode === "number") return result.statusCode;
|
|
1943
|
+
if (event?.requestContext?.http) return 200;
|
|
1944
|
+
return void 0;
|
|
1945
|
+
}
|
|
1946
|
+
function azureInvocation(args, coldstart) {
|
|
1947
|
+
const v4 = args[1] && typeof args[1] === "object" && typeof args[1].invocationId === "string";
|
|
1948
|
+
const v3 = !v4 && args[0] && typeof args[0] === "object" && typeof args[0].invocationId === "string";
|
|
1949
|
+
if (!v4 && !v3) return null;
|
|
1950
|
+
const ctx = v4 ? args[1] : args[0];
|
|
1951
|
+
const triggerType = v4 ? ctx.options?.trigger?.type : (ctx.bindingDefinitions ?? []).find((b) => b?.direction === "in" && /Trigger$/.test(b?.type ?? ""))?.type;
|
|
1952
|
+
const functionName = ctx.functionName ?? ctx.executionContext?.functionName;
|
|
1953
|
+
const request = v4 ? triggerType === "httpTrigger" ? args[0] : void 0 : ctx.req ?? (triggerType === "httpTrigger" ? args[1] : void 0);
|
|
1954
|
+
const http = !!request && typeof request.method === "string";
|
|
1955
|
+
const base = {
|
|
1956
|
+
"faas.trigger": azureTrigger(triggerType, http),
|
|
1957
|
+
"faas.invocation_id": ctx.invocationId,
|
|
1958
|
+
"faas.coldstart": coldstart,
|
|
1959
|
+
"faas.name": functionName,
|
|
1960
|
+
"cloud.provider": "azure",
|
|
1961
|
+
"cloud.platform": "azure_functions",
|
|
1962
|
+
"cloud.region": process.env.REGION_NAME
|
|
1963
|
+
};
|
|
1964
|
+
if (!http) {
|
|
1965
|
+
return { name: functionName ?? "function", attributes: clean2(base), http: false, mechanism: "azure-functions" };
|
|
1966
|
+
}
|
|
1967
|
+
const path = pathOf(request.url) ?? pathOf(request.originalUrl);
|
|
1968
|
+
return {
|
|
1969
|
+
name: `${request.method} ${path ?? "/"}`,
|
|
1970
|
+
attributes: clean2({
|
|
1971
|
+
...base,
|
|
1972
|
+
"http.request.method": request.method,
|
|
1973
|
+
"url.path": path,
|
|
1974
|
+
"user_agent.original": header2(request.headers, "user-agent")
|
|
1975
|
+
}),
|
|
1976
|
+
carrier: request.headers,
|
|
1977
|
+
http: true,
|
|
1978
|
+
mechanism: "azure-functions"
|
|
1979
|
+
};
|
|
1980
|
+
}
|
|
1981
|
+
function azureTrigger(type, http) {
|
|
1982
|
+
if (http || type === "httpTrigger") return "http";
|
|
1983
|
+
if (type === "timerTrigger") return "timer";
|
|
1984
|
+
if (type && /^(queue|serviceBus|eventHub|eventGrid|kafka|rabbitMQ|webPubSub|signalR)/i.test(type)) return "pubsub";
|
|
1985
|
+
if (type && /^(blob|cosmosDB|sql|mysql)/i.test(type)) return "datasource";
|
|
1986
|
+
return "other";
|
|
1987
|
+
}
|
|
1988
|
+
function azureStatus(result, args) {
|
|
1989
|
+
const v4 = args[1] && typeof args[1]?.invocationId === "string";
|
|
1990
|
+
const response = v4 ? result : args[0]?.res ?? result;
|
|
1991
|
+
const status = response?.status ?? response?.statusCode;
|
|
1992
|
+
const n = typeof status === "string" ? Number(status) : status;
|
|
1993
|
+
return typeof n === "number" && Number.isFinite(n) ? n : 200;
|
|
1994
|
+
}
|
|
1995
|
+
var gcfName = () => process.env.K_SERVICE ?? process.env.FUNCTION_TARGET ?? process.env.FUNCTION_NAME;
|
|
1996
|
+
var gcfBase = (coldstart) => ({
|
|
1997
|
+
"faas.coldstart": coldstart,
|
|
1998
|
+
"faas.name": gcfName(),
|
|
1999
|
+
"faas.version": process.env.K_REVISION,
|
|
2000
|
+
"cloud.provider": "gcp",
|
|
2001
|
+
"cloud.platform": "gcp_cloud_functions",
|
|
2002
|
+
"cloud.region": process.env.FUNCTION_REGION
|
|
2003
|
+
});
|
|
2004
|
+
var isHttpPair = (req, res) => !!req && typeof req === "object" && typeof req.method === "string" && !!req.headers && !!res && typeof res.end === "function";
|
|
2005
|
+
function gcfHttpInvocation(req, coldstart) {
|
|
2006
|
+
const path = pathOf(req.originalUrl ?? req.url);
|
|
2007
|
+
const id = header2(req.headers, "function-execution-id") ?? header2(req.headers, "x-cloud-trace-context")?.split("/")[0] ?? (0, import_node_crypto.randomUUID)();
|
|
2008
|
+
return {
|
|
2009
|
+
name: `${req.method} ${path ?? "/"}`,
|
|
2010
|
+
attributes: clean2({
|
|
2011
|
+
...gcfBase(coldstart),
|
|
2012
|
+
"faas.trigger": "http",
|
|
2013
|
+
"faas.invocation_id": id,
|
|
2014
|
+
"http.request.method": req.method,
|
|
2015
|
+
"url.path": path,
|
|
2016
|
+
"server.address": header2(req.headers, "host"),
|
|
2017
|
+
"user_agent.original": header2(req.headers, "user-agent")
|
|
2018
|
+
}),
|
|
2019
|
+
carrier: req.headers,
|
|
2020
|
+
http: true,
|
|
2021
|
+
mechanism: "gcp-functions"
|
|
2022
|
+
};
|
|
2023
|
+
}
|
|
2024
|
+
function gcfEventInvocation(args, coldstart) {
|
|
2025
|
+
const ce = args[0] && typeof args[0] === "object" && typeof args[0].specversion === "string" ? args[0] : void 0;
|
|
2026
|
+
const legacy = !ce && args[1] && typeof args[1] === "object" ? args[1] : void 0;
|
|
2027
|
+
const type = ce?.type ?? legacy?.eventType ?? legacy?.type ?? "";
|
|
2028
|
+
const trigger = /pubsub/i.test(type) ? "pubsub" : /storage|firestore|firebase|datastore|database/i.test(type) ? "datasource" : /scheduler/i.test(type) ? "timer" : "other";
|
|
2029
|
+
return {
|
|
2030
|
+
name: gcfName() ?? "function",
|
|
2031
|
+
attributes: clean2({
|
|
2032
|
+
...gcfBase(coldstart),
|
|
2033
|
+
"faas.trigger": trigger,
|
|
2034
|
+
"faas.invocation_id": ce?.id ?? legacy?.eventId ?? (0, import_node_crypto.randomUUID)(),
|
|
2035
|
+
"cloudevents.event_type": type || void 0,
|
|
2036
|
+
"cloudevents.event_source": ce?.source
|
|
2037
|
+
}),
|
|
2038
|
+
// The CloudEvents distributed tracing extension.
|
|
2039
|
+
carrier: ce ? { traceparent: ce.traceparent, tracestate: ce.tracestate } : void 0,
|
|
2040
|
+
http: false,
|
|
2041
|
+
mechanism: "gcp-functions"
|
|
2042
|
+
};
|
|
2043
|
+
}
|
|
2044
|
+
function serverlessResource() {
|
|
2045
|
+
const env = process.env;
|
|
2046
|
+
if (env.AWS_LAMBDA_FUNCTION_NAME) {
|
|
2047
|
+
const memory = Number(env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE);
|
|
2048
|
+
return clean2({
|
|
2049
|
+
"cloud.provider": "aws",
|
|
2050
|
+
"cloud.platform": "aws_lambda",
|
|
2051
|
+
"cloud.region": env.AWS_REGION,
|
|
2052
|
+
"faas.name": env.AWS_LAMBDA_FUNCTION_NAME,
|
|
2053
|
+
"faas.version": env.AWS_LAMBDA_FUNCTION_VERSION,
|
|
2054
|
+
"faas.instance": env.AWS_LAMBDA_LOG_STREAM_NAME,
|
|
2055
|
+
"faas.max_memory": Number.isFinite(memory) && memory > 0 ? memory * 1024 * 1024 : void 0
|
|
2056
|
+
});
|
|
2057
|
+
}
|
|
2058
|
+
if (env.FUNCTIONS_WORKER_RUNTIME && (env.WEBSITE_SITE_NAME || env.AzureWebJobsStorage || env.FUNCTIONS_EXTENSION_VERSION)) {
|
|
2059
|
+
return clean2({
|
|
2060
|
+
"cloud.provider": "azure",
|
|
2061
|
+
"cloud.platform": "azure_functions",
|
|
2062
|
+
"cloud.region": env.REGION_NAME,
|
|
2063
|
+
"faas.instance": env.WEBSITE_INSTANCE_ID
|
|
2064
|
+
});
|
|
2065
|
+
}
|
|
2066
|
+
if (env.FUNCTION_TARGET && (env.K_SERVICE || env.FUNCTION_NAME)) {
|
|
2067
|
+
return clean2({
|
|
2068
|
+
"cloud.provider": "gcp",
|
|
2069
|
+
"cloud.platform": "gcp_cloud_functions",
|
|
2070
|
+
"cloud.region": env.FUNCTION_REGION,
|
|
2071
|
+
"faas.name": gcfName(),
|
|
2072
|
+
"faas.version": env.K_REVISION
|
|
2073
|
+
});
|
|
2074
|
+
}
|
|
2075
|
+
return {};
|
|
2076
|
+
}
|
|
2077
|
+
function serverlessName() {
|
|
2078
|
+
return process.env.AWS_LAMBDA_FUNCTION_NAME ?? process.env.WEBSITE_SITE_NAME ?? (process.env.FUNCTION_TARGET ? gcfName() : void 0);
|
|
2079
|
+
}
|
|
2080
|
+
function sameShape(wrapper, handler) {
|
|
2081
|
+
try {
|
|
2082
|
+
Object.defineProperty(wrapper, "length", { value: handler.length });
|
|
2083
|
+
Object.defineProperty(wrapper, "name", { value: handler.name });
|
|
2084
|
+
for (const key of Object.getOwnPropertySymbols(handler)) wrapper[key] = handler[key];
|
|
2085
|
+
} catch {
|
|
2086
|
+
}
|
|
2087
|
+
return wrapper;
|
|
2088
|
+
}
|
|
1239
2089
|
|
|
1240
2090
|
// src/zharp.ts
|
|
1241
2091
|
var DEFAULT_ENDPOINT = "https://api.zharp.io/api/v1/otlp";
|
|
@@ -1251,6 +2101,15 @@ var ZharpNode = class {
|
|
|
1251
2101
|
tracing = true;
|
|
1252
2102
|
/** Errors already sent, so one that is both rejected and then thrown is reported once. */
|
|
1253
2103
|
reported = /* @__PURE__ */ new WeakSet();
|
|
2104
|
+
/** Failed queries waiting to be reported, once and with their call site. */
|
|
2105
|
+
dbErrors = null;
|
|
2106
|
+
/** No invocation has run in this process yet: the next one is the cold start. */
|
|
2107
|
+
cold = true;
|
|
2108
|
+
/**
|
|
2109
|
+
* A Cloud Function is wrapped: its wrapper makes each request's span (and flushes before the
|
|
2110
|
+
* response), so the http server instrumentation leaves incoming requests alone.
|
|
2111
|
+
*/
|
|
2112
|
+
wrapsHttp = false;
|
|
1254
2113
|
/** `Zharp.log.info("Order placed", { orderId })` — and debug, warn, error, fatal, trace. */
|
|
1255
2114
|
log = {
|
|
1256
2115
|
trace: (m, a) => this.emit("trace", m, a),
|
|
@@ -1290,7 +2149,7 @@ var ZharpNode = class {
|
|
|
1290
2149
|
warn("No key found \u2014 pass Zharp.init({ key }) or set ZHARP_API_KEY. Nothing will be sent.");
|
|
1291
2150
|
return;
|
|
1292
2151
|
}
|
|
1293
|
-
const service = pick(options.service, nodeEnv("ZHARP_SERVICE"), nodeEnv("OTEL_SERVICE_NAME"), packageName()) ?? "node-app";
|
|
2152
|
+
const service = pick(options.service, nodeEnv("ZHARP_SERVICE"), nodeEnv("OTEL_SERVICE_NAME"), packageName(), serverlessName()) ?? "node-app";
|
|
1294
2153
|
const environment = pick(options.environment, nodeEnv("ZHARP_ENV"), nodeEnv("NODE_ENV"));
|
|
1295
2154
|
const release = pick(options.release, nodeEnv("ZHARP_RELEASE"), nodeEnv("ZHARP_VERSION"));
|
|
1296
2155
|
const endpoint = (pick(options.endpoint, nodeEnv("ZHARP_ENDPOINT")) ?? DEFAULT_ENDPOINT).replace(/\/+$/, "");
|
|
@@ -1304,13 +2163,20 @@ var ZharpNode = class {
|
|
|
1304
2163
|
const prefixed = Object.fromEntries(
|
|
1305
2164
|
Object.entries(out).map(([level, fn]) => [level, (message, ...args) => fn.call(console, `[Zharp][otel] ${message}`, ...args)])
|
|
1306
2165
|
);
|
|
1307
|
-
|
|
2166
|
+
import_api5.diag.setLogger(prefixed, import_api5.DiagLogLevel.DEBUG);
|
|
1308
2167
|
}
|
|
1309
2168
|
registerEsmHook();
|
|
1310
2169
|
const headers = { Authorization: `Bearer ${key}` };
|
|
1311
2170
|
const exporterOptions = { headers, compression: "gzip" };
|
|
2171
|
+
setSourceContext(switchOn(options.captureSourceContext, "ZHARP_CAPTURE_SOURCE_CONTEXT", true));
|
|
2172
|
+
const queryErrors = tracing && switchOn(options.captureQueryErrors, "ZHARP_CAPTURE_QUERY_ERRORS", true);
|
|
2173
|
+
this.dbErrors = queryErrors ? new DbErrorSpanProcessor((failure) => this.sendQueryError(failure, true, "error", { "zharp.mechanism": "db" })) : null;
|
|
1312
2174
|
this.spanProcessors = tracing ? [
|
|
1313
2175
|
new ContextSpanProcessor(this.store),
|
|
2176
|
+
// Before the database processor: a request that failed claims its query's error first.
|
|
2177
|
+
...options.captureUncaught !== false ? [new RecordedExceptionsProcessor((error, spanContext, mechanism) => import_api5.context.with(import_api5.trace.setSpanContext(import_api5.context.active(), spanContext), () => this.report(error, false, "error", { "zharp.mechanism": mechanism }, true)))] : [],
|
|
2178
|
+
// Before the exporter: it keeps the query's scrubbed exception off the span.
|
|
2179
|
+
...this.dbErrors ? [this.dbErrors] : [],
|
|
1314
2180
|
new UrlRedactionSpanProcessor(),
|
|
1315
2181
|
new DebugIdSpanProcessor(),
|
|
1316
2182
|
new import_sdk_trace.BatchSpanProcessor({ exporter: new import_exporter_trace_otlp_proto.OTLPTraceExporter({ ...exporterOptions, url: `${endpoint}/v1/traces` }) })
|
|
@@ -1329,13 +2195,20 @@ var ZharpNode = class {
|
|
|
1329
2195
|
"telemetry.sdk.language": "nodejs",
|
|
1330
2196
|
"telemetry.sdk.version": VERSION,
|
|
1331
2197
|
"process.runtime.name": "nodejs",
|
|
1332
|
-
"process.runtime.version": process.versions.node
|
|
2198
|
+
"process.runtime.version": process.versions.node,
|
|
2199
|
+
// Lambda, Azure Functions, Cloud Functions: cloud.provider, cloud.platform, faas.name…
|
|
2200
|
+
...serverlessResource()
|
|
1333
2201
|
});
|
|
1334
2202
|
const propagator = new import_core.CompositePropagator({
|
|
1335
2203
|
propagators: [new import_core.W3CTraceContextPropagator(), new import_core.W3CBaggagePropagator()]
|
|
1336
2204
|
});
|
|
1337
2205
|
const bodies = bodySettings(options.captureBodies, nodeEnv("ZHARP_CAPTURE_BODIES"));
|
|
2206
|
+
const headerCapture = headerSettings(options.captureHeaders, nodeEnv("ZHARP_CAPTURE_HEADERS"));
|
|
2207
|
+
const ownHttp = this.withWrappedRequests(options.instrumentations?.["@opentelemetry/instrumentation-http"]);
|
|
2208
|
+
const withBodies = bodies ? withBodyCapture(bodies, ownHttp) : ownHttp;
|
|
2209
|
+
const httpConfig = headerCapture ? withHeaderCapture(headerCapture, withBodies) : withBodies;
|
|
1338
2210
|
const rate = typeof options.sampleRate === "number" ? Math.min(1, Math.max(0, options.sampleRate)) : 1;
|
|
2211
|
+
let instrumentations = [];
|
|
1339
2212
|
this.sdk = new import_sdk_node.NodeSDK({
|
|
1340
2213
|
resource,
|
|
1341
2214
|
// Host and OTEL_RESOURCE_ATTRIBUTES only. The process detector would send the command line,
|
|
@@ -1347,23 +2220,28 @@ var ZharpNode = class {
|
|
|
1347
2220
|
logRecordProcessors: this.logProcessors,
|
|
1348
2221
|
// Without this the SDK would start an OTLP metrics exporter pointed at localhost:4318.
|
|
1349
2222
|
metricReaders: [],
|
|
1350
|
-
instrumentations: [
|
|
2223
|
+
instrumentations: instrumentations = [
|
|
1351
2224
|
...tracing ? (0, import_auto_instrumentations_node.getNodeAutoInstrumentations)({
|
|
1352
2225
|
// A span per DNS lookup, socket and file read buries the requests that matter.
|
|
1353
2226
|
"@opentelemetry/instrumentation-dns": { enabled: false },
|
|
1354
2227
|
"@opentelemetry/instrumentation-net": { enabled: false },
|
|
1355
2228
|
"@opentelemetry/instrumentation-fs": { enabled: false },
|
|
2229
|
+
// Zharp.lambda() makes the invocation's span and flushes before returning; this one
|
|
2230
|
+
// would wrap the handler again (a second span) from _HANDLER, when it can find it.
|
|
2231
|
+
"@opentelemetry/instrumentation-aws-lambda": { enabled: false },
|
|
1356
2232
|
...options.instrumentations,
|
|
1357
2233
|
...bridges,
|
|
1358
|
-
...
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
2234
|
+
...httpConfig && { "@opentelemetry/instrumentation-http": httpConfig }
|
|
2235
|
+
}) : logsOnlyInstrumentations({ ...options, instrumentations: { ...options.instrumentations, ...bridges, "@opentelemetry/instrumentation-http": ownHttp } }),
|
|
2236
|
+
...this.dbErrors ? [new DbDriverErrorsInstrumentation((traceId, error) => this.dbErrors?.attach(traceId, error))] : [],
|
|
2237
|
+
...tracing && options.captureUncaught !== false ? [new FrameworkErrorsInstrumentation((error, mechanism) => this.report(error, false, "error", { "zharp.mechanism": mechanism }, true))] : [],
|
|
1362
2238
|
...options.extraInstrumentations ?? []
|
|
1363
2239
|
]
|
|
1364
2240
|
});
|
|
1365
2241
|
this.sdk.start();
|
|
1366
|
-
|
|
2242
|
+
if (tracing) preloadCommonJsFrameworks();
|
|
2243
|
+
if (isBun()) patchWithoutHooks(instrumentations);
|
|
2244
|
+
this.logger = import_api5.logs.getLogger("@zharp/node", VERSION);
|
|
1367
2245
|
if (correlation) this.teardowns.push(stampOutput());
|
|
1368
2246
|
if (sendLogs) {
|
|
1369
2247
|
if (options.captureConsole !== false) this.teardowns.push(captureConsole(this.logger));
|
|
@@ -1406,16 +2284,36 @@ var ZharpNode = class {
|
|
|
1406
2284
|
captureError(error, attributes) {
|
|
1407
2285
|
this.report(error, true, "error", attributes);
|
|
1408
2286
|
}
|
|
2287
|
+
/**
|
|
2288
|
+
* Next.js (15+): errors a route handler, server component, server action or middleware threw,
|
|
2289
|
+
* which Next answers with an error page and only prints. Export it from instrumentation.ts:
|
|
2290
|
+
*
|
|
2291
|
+
* export const onRequestError = Zharp.onRequestError;
|
|
2292
|
+
*
|
|
2293
|
+
* Each is reported once as a crash, with the request's path, method and route. A bound function,
|
|
2294
|
+
* so it can be exported as it is.
|
|
2295
|
+
*/
|
|
2296
|
+
onRequestError = (error, request, context3) => {
|
|
2297
|
+
this.report(error, false, "error", {
|
|
2298
|
+
"zharp.mechanism": "nextjs",
|
|
2299
|
+
...request?.method ? { "http.request.method": request.method } : {},
|
|
2300
|
+
...request?.path ? { "url.path": request.path } : {},
|
|
2301
|
+
...context3?.routePath ? { "http.route": context3.routePath } : {},
|
|
2302
|
+
...context3?.routeType ? { "next.route_type": context3.routeType } : {},
|
|
2303
|
+
...context3?.routerKind ? { "next.router_kind": context3.routerKind } : {},
|
|
2304
|
+
...context3?.renderSource ? { "next.render_source": context3.renderSource } : {}
|
|
2305
|
+
}, true);
|
|
2306
|
+
};
|
|
1409
2307
|
/**
|
|
1410
2308
|
* Run `fn` inside a span named `name`, which ends when `fn` returns or its promise settles. A
|
|
1411
2309
|
* throw or rejection marks the span as failed and is passed on unchanged.
|
|
1412
2310
|
*/
|
|
1413
2311
|
startSpan(name, fn, options = {}) {
|
|
1414
|
-
if (!this.tracing) return fn(
|
|
1415
|
-
const tracer =
|
|
2312
|
+
if (!this.tracing) return fn(import_api5.trace.wrapSpanContext(import_api5.trace.getActiveSpan()?.spanContext() ?? import_api5.INVALID_SPAN_CONTEXT));
|
|
2313
|
+
const tracer = import_api5.trace.getTracer("@zharp/node", VERSION);
|
|
1416
2314
|
return tracer.startActiveSpan(name, options, (span) => {
|
|
1417
2315
|
const fail = (error) => {
|
|
1418
|
-
span.setStatus({ code:
|
|
2316
|
+
span.setStatus({ code: import_api5.SpanStatusCode.ERROR, message: asError(error).message });
|
|
1419
2317
|
span.end();
|
|
1420
2318
|
};
|
|
1421
2319
|
let result;
|
|
@@ -1445,7 +2343,208 @@ var ZharpNode = class {
|
|
|
1445
2343
|
async flush(timeoutMs = 5e3) {
|
|
1446
2344
|
const all = Promise.all([...this.spanProcessors, ...this.logProcessors].map((p) => p.forceFlush().catch(() => {
|
|
1447
2345
|
})));
|
|
1448
|
-
await Promise.race([all, new Promise((
|
|
2346
|
+
await Promise.race([all, new Promise((resolve2) => setTimeout(resolve2, timeoutMs).unref())]);
|
|
2347
|
+
}
|
|
2348
|
+
// ── serverless ────────────────────────────────────────────────────────
|
|
2349
|
+
//
|
|
2350
|
+
// Each wrapper returns a function of the same shape as the handler: same arguments, same
|
|
2351
|
+
// result. Every invocation is one SERVER span (continuing the caller's trace when the trigger
|
|
2352
|
+
// carries a `traceparent`), an error the handler throws is reported once and thrown on, and
|
|
2353
|
+
// everything is flushed — within `flushTimeout` — before the result goes back, because the
|
|
2354
|
+
// platform freezes the process as soon as it has it.
|
|
2355
|
+
/**
|
|
2356
|
+
* An AWS Lambda handler (async, callback, or `awslambda.streamifyResponse`):
|
|
2357
|
+
*
|
|
2358
|
+
* export const handler = Zharp.lambda(async (event, context) => { … });
|
|
2359
|
+
*/
|
|
2360
|
+
lambda(handler, options = {}) {
|
|
2361
|
+
const self = this;
|
|
2362
|
+
const streaming = isStreamingLambda(handler);
|
|
2363
|
+
return sameShape(function zharpLambda(...args) {
|
|
2364
|
+
if (!self.sdk) return handler.apply(this, args);
|
|
2365
|
+
const event = args[0];
|
|
2366
|
+
const ctx = streaming ? args[2] : args[1];
|
|
2367
|
+
const budget = () => {
|
|
2368
|
+
const limit = options.flushTimeout ?? DEFAULT_FLUSH_MS;
|
|
2369
|
+
const left = typeof ctx?.getRemainingTimeInMillis === "function" ? Number(ctx.getRemainingTimeInMillis()) : NaN;
|
|
2370
|
+
return Number.isFinite(left) ? Math.max(0, Math.min(limit, left - 100)) : limit;
|
|
2371
|
+
};
|
|
2372
|
+
const invocation = lambdaInvocation(event, ctx, self.takeColdstart());
|
|
2373
|
+
const callback = !streaming && handler.length >= 3 ? 2 : null;
|
|
2374
|
+
return self.runInvocation(invocation, budget, (result) => invocation.http ? lambdaStatus(result, event) : void 0, handler, this, args, callback);
|
|
2375
|
+
}, handler);
|
|
2376
|
+
}
|
|
2377
|
+
/**
|
|
2378
|
+
* An Azure Functions handler, v4 programming model (`(request, context)`, any trigger) or v3
|
|
2379
|
+
* (`(context, req)`):
|
|
2380
|
+
*
|
|
2381
|
+
* app.http('orders', { handler: Zharp.azureFunction(async (request, context) => { … }) });
|
|
2382
|
+
*/
|
|
2383
|
+
azureFunction(handler, options = {}) {
|
|
2384
|
+
const self = this;
|
|
2385
|
+
return sameShape(function zharpAzureFunction(...args) {
|
|
2386
|
+
if (!self.sdk) return handler.apply(this, args);
|
|
2387
|
+
const invocation = azureInvocation(args, self.takeColdstart());
|
|
2388
|
+
if (!invocation) return handler.apply(this, args);
|
|
2389
|
+
const budget = () => options.flushTimeout ?? DEFAULT_FLUSH_MS;
|
|
2390
|
+
return self.runInvocation(invocation, budget, (result) => invocation.http ? azureStatus(result, args) : void 0, handler, this, args, null);
|
|
2391
|
+
}, handler);
|
|
2392
|
+
}
|
|
2393
|
+
/**
|
|
2394
|
+
* A Google Cloud Function: an HTTP function `(req, res)`, a CloudEvent function `(cloudEvent)`,
|
|
2395
|
+
* or a background function `(data, context)`.
|
|
2396
|
+
*
|
|
2397
|
+
* functions.http('orders', Zharp.cloudFunction((req, res) => { … }));
|
|
2398
|
+
*
|
|
2399
|
+
* An HTTP function's response is held until everything is sent — Cloud Functions may stop
|
|
2400
|
+
* the instance's CPU the moment the response is out.
|
|
2401
|
+
*/
|
|
2402
|
+
cloudFunction(handler, options = {}) {
|
|
2403
|
+
const self = this;
|
|
2404
|
+
this.wrapsHttp = true;
|
|
2405
|
+
const budget = () => options.flushTimeout ?? DEFAULT_FLUSH_MS;
|
|
2406
|
+
return sameShape(function zharpCloudFunction(...args) {
|
|
2407
|
+
if (!self.sdk) return handler.apply(this, args);
|
|
2408
|
+
if (isHttpPair(args[0], args[1])) return self.runHttpFunction(gcfHttpInvocation(args[0], self.takeColdstart()), budget, handler, this, args);
|
|
2409
|
+
const cloudEvent = args[0] && typeof args[0] === "object" && typeof args[0].specversion === "string";
|
|
2410
|
+
const callback = cloudEvent ? handler.length >= 2 ? 1 : null : handler.length >= 3 ? 2 : null;
|
|
2411
|
+
return self.runInvocation(gcfEventInvocation(args, self.takeColdstart()), budget, () => void 0, handler, this, args, callback);
|
|
2412
|
+
}, handler);
|
|
2413
|
+
}
|
|
2414
|
+
/** The first invocation in the process is the cold start (not under provisioned concurrency). */
|
|
2415
|
+
takeColdstart() {
|
|
2416
|
+
if (!this.cold) return false;
|
|
2417
|
+
this.cold = false;
|
|
2418
|
+
return process.env.AWS_LAMBDA_INITIALIZATION_TYPE !== "provisioned-concurrency";
|
|
2419
|
+
}
|
|
2420
|
+
/** The http instrumentation's config, leaving incoming requests to a wrapped Cloud Function. */
|
|
2421
|
+
withWrappedRequests(config) {
|
|
2422
|
+
const own = config?.ignoreIncomingRequestHook;
|
|
2423
|
+
return {
|
|
2424
|
+
...config,
|
|
2425
|
+
ignoreIncomingRequestHook: (request) => this.wrapsHttp || !!own?.(request)
|
|
2426
|
+
};
|
|
2427
|
+
}
|
|
2428
|
+
/** The invocation's span, in a context of its own: the caller's trace, or a new one. */
|
|
2429
|
+
beginInvocation(invocation) {
|
|
2430
|
+
let base = (0, import_core.unsuppressTracing)(import_api5.context.active());
|
|
2431
|
+
if (invocation.carrier) base = import_api5.propagation.extract(base, invocation.carrier, headerGetter);
|
|
2432
|
+
const span = import_api5.trace.getTracer("@zharp/node", VERSION).startSpan(invocation.name, { kind: import_api5.SpanKind.SERVER, attributes: invocation.attributes }, base);
|
|
2433
|
+
return { span, ctx: import_api5.trace.setSpan(base, span) };
|
|
2434
|
+
}
|
|
2435
|
+
/** Report what the handler threw, in its invocation, and fail the span. Once per error. */
|
|
2436
|
+
invocationFailed(span, ctx, invocation, error) {
|
|
2437
|
+
try {
|
|
2438
|
+
import_api5.context.with(ctx, () => this.report(error, false, "error", { "zharp.mechanism": invocation.mechanism }));
|
|
2439
|
+
const e = asError(error);
|
|
2440
|
+
span.setStatus({ code: import_api5.SpanStatusCode.ERROR, message: e.message });
|
|
2441
|
+
span.setAttribute("error.type", e.name || "Error");
|
|
2442
|
+
} catch {
|
|
2443
|
+
}
|
|
2444
|
+
}
|
|
2445
|
+
/** End the invocation's span, then send everything waiting, within the budget. */
|
|
2446
|
+
async endInvocation(span, status, budgetMs) {
|
|
2447
|
+
try {
|
|
2448
|
+
if (status !== void 0) {
|
|
2449
|
+
span.setAttribute("http.response.status_code", status);
|
|
2450
|
+
if (status >= 500) span.setStatus({ code: import_api5.SpanStatusCode.ERROR });
|
|
2451
|
+
}
|
|
2452
|
+
span.end();
|
|
2453
|
+
} catch {
|
|
2454
|
+
}
|
|
2455
|
+
if (budgetMs > 0) await this.flush(budgetMs).catch(() => {
|
|
2456
|
+
});
|
|
2457
|
+
}
|
|
2458
|
+
/**
|
|
2459
|
+
* Run a handler as one invocation. Its result (a value, a promise, or what it passes to its
|
|
2460
|
+
* callback) comes back unchanged — after the span has ended and been flushed.
|
|
2461
|
+
*/
|
|
2462
|
+
runInvocation(invocation, budget, statusOf2, handler, thisArg, args, callbackIndex) {
|
|
2463
|
+
let span;
|
|
2464
|
+
let ctx;
|
|
2465
|
+
try {
|
|
2466
|
+
({ span, ctx } = this.beginInvocation(invocation));
|
|
2467
|
+
} catch {
|
|
2468
|
+
return handler.apply(thisArg, args);
|
|
2469
|
+
}
|
|
2470
|
+
let done = null;
|
|
2471
|
+
const finish = (failed, error, result2) => {
|
|
2472
|
+
if (done) return done;
|
|
2473
|
+
if (failed) this.invocationFailed(span, ctx, invocation, error);
|
|
2474
|
+
let status;
|
|
2475
|
+
try {
|
|
2476
|
+
status = failed ? void 0 : statusOf2(result2);
|
|
2477
|
+
} catch {
|
|
2478
|
+
status = void 0;
|
|
2479
|
+
}
|
|
2480
|
+
return done = this.endInvocation(span, status, budget());
|
|
2481
|
+
};
|
|
2482
|
+
const usesCallback = callbackIndex !== null && typeof args[callbackIndex] === "function";
|
|
2483
|
+
if (usesCallback) {
|
|
2484
|
+
const index = callbackIndex;
|
|
2485
|
+
const callback = args[index];
|
|
2486
|
+
args = [...args];
|
|
2487
|
+
args[index] = function(error, ...rest) {
|
|
2488
|
+
const failed = error !== void 0 && error !== null;
|
|
2489
|
+
finish(failed, error, rest[0]).then(() => callback.call(this, error, ...rest));
|
|
2490
|
+
};
|
|
2491
|
+
}
|
|
2492
|
+
let result;
|
|
2493
|
+
try {
|
|
2494
|
+
result = import_api5.context.with(ctx, () => handler.apply(thisArg, args));
|
|
2495
|
+
} catch (error) {
|
|
2496
|
+
return finish(true, error, void 0).then(() => {
|
|
2497
|
+
throw error;
|
|
2498
|
+
});
|
|
2499
|
+
}
|
|
2500
|
+
if (result && typeof result.then === "function") {
|
|
2501
|
+
return Promise.resolve(result).then(
|
|
2502
|
+
(value) => finish(false, void 0, value).then(() => value),
|
|
2503
|
+
(error) => finish(true, error, void 0).then(() => {
|
|
2504
|
+
throw error;
|
|
2505
|
+
})
|
|
2506
|
+
);
|
|
2507
|
+
}
|
|
2508
|
+
if (usesCallback) return result;
|
|
2509
|
+
return finish(false, void 0, result).then(() => result);
|
|
2510
|
+
}
|
|
2511
|
+
/**
|
|
2512
|
+
* An HTTP function `(req, res)`: the invocation ends with the response. `res.end` is held
|
|
2513
|
+
* until the span has ended and everything is flushed, then goes out as the handler wrote it.
|
|
2514
|
+
*/
|
|
2515
|
+
runHttpFunction(invocation, budget, handler, thisArg, args) {
|
|
2516
|
+
const self = this;
|
|
2517
|
+
let span;
|
|
2518
|
+
let ctx;
|
|
2519
|
+
try {
|
|
2520
|
+
({ span, ctx } = this.beginInvocation(invocation));
|
|
2521
|
+
} catch {
|
|
2522
|
+
return handler.apply(thisArg, args);
|
|
2523
|
+
}
|
|
2524
|
+
const res = args[1];
|
|
2525
|
+
const end = res.end;
|
|
2526
|
+
res.end = function zharpEnd(...endArgs) {
|
|
2527
|
+
res.end = end;
|
|
2528
|
+
const status = typeof res.statusCode === "number" ? res.statusCode : void 0;
|
|
2529
|
+
const send = () => end.apply(res, endArgs);
|
|
2530
|
+
self.endInvocation(span, status, budget()).then(send, send);
|
|
2531
|
+
return res;
|
|
2532
|
+
};
|
|
2533
|
+
const failed = (error) => this.invocationFailed(span, ctx, invocation, error);
|
|
2534
|
+
let result;
|
|
2535
|
+
try {
|
|
2536
|
+
result = import_api5.context.with(ctx, () => handler.apply(thisArg, args));
|
|
2537
|
+
} catch (error) {
|
|
2538
|
+
failed(error);
|
|
2539
|
+
throw error;
|
|
2540
|
+
}
|
|
2541
|
+
if (result && typeof result.then === "function") {
|
|
2542
|
+
return Promise.resolve(result).then(void 0, (error) => {
|
|
2543
|
+
failed(error);
|
|
2544
|
+
throw error;
|
|
2545
|
+
});
|
|
2546
|
+
}
|
|
2547
|
+
return result;
|
|
1449
2548
|
}
|
|
1450
2549
|
/** Flush, stop, and put back everything that was patched. */
|
|
1451
2550
|
async shutdown() {
|
|
@@ -1477,14 +2576,20 @@ var ZharpNode = class {
|
|
|
1477
2576
|
} catch {
|
|
1478
2577
|
}
|
|
1479
2578
|
}
|
|
1480
|
-
report(value, handled, level, attributes) {
|
|
2579
|
+
report(value, handled, level, attributes, fromFramework = false) {
|
|
1481
2580
|
try {
|
|
1482
2581
|
if (!this.logger) return;
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
2582
|
+
if (value && typeof value === "object" && this.reported.has(value)) return;
|
|
2583
|
+
const traceId = import_api5.trace.getActiveSpan()?.spanContext().traceId;
|
|
2584
|
+
const failure = this.dbErrors?.consume(traceId, value, fromFramework);
|
|
2585
|
+
if (failure) {
|
|
2586
|
+
if (value && typeof value === "object") this.reported.add(value);
|
|
2587
|
+
this.sendQueryError(failure, handled, level, attributes);
|
|
2588
|
+
if (!handled) import_api5.trace.getActiveSpan()?.setStatus({ code: import_api5.SpanStatusCode.ERROR, message: failure.error?.message ?? "The query failed" });
|
|
2589
|
+
return;
|
|
1487
2590
|
}
|
|
2591
|
+
const error = asError(value);
|
|
2592
|
+
if (value && typeof value === "object") this.reported.add(value);
|
|
1488
2593
|
const exception = exceptionAttributes(error, handled);
|
|
1489
2594
|
this.logger.emit({
|
|
1490
2595
|
severityNumber: SEVERITY[level],
|
|
@@ -1492,7 +2597,33 @@ var ZharpNode = class {
|
|
|
1492
2597
|
body: `${exception["exception.type"]}: ${exception["exception.message"]}`,
|
|
1493
2598
|
attributes: { ...attributes, ...exception }
|
|
1494
2599
|
});
|
|
1495
|
-
if (!handled)
|
|
2600
|
+
if (!handled) import_api5.trace.getActiveSpan()?.setStatus({ code: import_api5.SpanStatusCode.ERROR, message: error.message });
|
|
2601
|
+
} catch {
|
|
2602
|
+
}
|
|
2603
|
+
}
|
|
2604
|
+
/** A failed query as an error, in the query's own span so the error shows the query. */
|
|
2605
|
+
sendQueryError(failure, handled, level = "error", attributes) {
|
|
2606
|
+
try {
|
|
2607
|
+
if (!this.logger) return;
|
|
2608
|
+
if (failure.error) {
|
|
2609
|
+
if (this.reported.has(failure.error) && handled) return;
|
|
2610
|
+
this.reported.add(failure.error);
|
|
2611
|
+
}
|
|
2612
|
+
const report = reportOf(failure);
|
|
2613
|
+
this.logger.emit({
|
|
2614
|
+
severityNumber: SEVERITY[level],
|
|
2615
|
+
severityText: level.toUpperCase(),
|
|
2616
|
+
body: `${report.type}: ${report.message}`,
|
|
2617
|
+
attributes: {
|
|
2618
|
+
...report.attributes,
|
|
2619
|
+
...attributes,
|
|
2620
|
+
"exception.type": report.type,
|
|
2621
|
+
"exception.message": report.message,
|
|
2622
|
+
"exception.stacktrace": report.stack,
|
|
2623
|
+
"zharp.handled": handled ? "true" : "false"
|
|
2624
|
+
},
|
|
2625
|
+
context: import_api5.trace.setSpanContext(import_api5.context.active(), report.spanContext)
|
|
2626
|
+
});
|
|
1496
2627
|
} catch {
|
|
1497
2628
|
}
|
|
1498
2629
|
}
|
|
@@ -1587,14 +2718,83 @@ function safeJson(value) {
|
|
|
1587
2718
|
return String(value);
|
|
1588
2719
|
}
|
|
1589
2720
|
}
|
|
2721
|
+
var ESM_HOOK_EXCLUDE = ["connect", "@hapi/hapi"];
|
|
2722
|
+
function preloadCommonJsFrameworks() {
|
|
2723
|
+
let appRequire;
|
|
2724
|
+
try {
|
|
2725
|
+
appRequire = (0, import_node_module.createRequire)((0, import_node_path2.join)(process.cwd(), "noop.js"));
|
|
2726
|
+
} catch {
|
|
2727
|
+
return;
|
|
2728
|
+
}
|
|
2729
|
+
for (const name of ESM_HOOK_EXCLUDE) {
|
|
2730
|
+
try {
|
|
2731
|
+
appRequire(name);
|
|
2732
|
+
} catch {
|
|
2733
|
+
}
|
|
2734
|
+
}
|
|
2735
|
+
}
|
|
2736
|
+
var isBun = () => typeof globalThis.Bun !== "undefined";
|
|
2737
|
+
function patchWithoutHooks(instrumentations) {
|
|
2738
|
+
let appRequire;
|
|
2739
|
+
try {
|
|
2740
|
+
appRequire = (0, import_node_module.createRequire)((0, import_node_path2.join)(process.cwd(), "noop.js"));
|
|
2741
|
+
} catch {
|
|
2742
|
+
return;
|
|
2743
|
+
}
|
|
2744
|
+
for (const instrumentation of instrumentations) {
|
|
2745
|
+
let definitions = [];
|
|
2746
|
+
for (const flag of ["_httpPatched", "_httpsPatched"]) if (instrumentation && flag in instrumentation) instrumentation[flag] = false;
|
|
2747
|
+
try {
|
|
2748
|
+
definitions = instrumentation?.getModuleDefinitions?.() ?? [];
|
|
2749
|
+
} catch {
|
|
2750
|
+
continue;
|
|
2751
|
+
}
|
|
2752
|
+
for (const definition of definitions) {
|
|
2753
|
+
let exported;
|
|
2754
|
+
try {
|
|
2755
|
+
exported = appRequire(definition.name);
|
|
2756
|
+
} catch {
|
|
2757
|
+
continue;
|
|
2758
|
+
}
|
|
2759
|
+
let version;
|
|
2760
|
+
try {
|
|
2761
|
+
version = definition.name.includes(":") || !definition.name.includes("/") && (0, import_node_module.isBuiltin)(definition.name) ? process.versions.node : appRequire(`${definition.name}/package.json`).version;
|
|
2762
|
+
} catch {
|
|
2763
|
+
version = void 0;
|
|
2764
|
+
}
|
|
2765
|
+
try {
|
|
2766
|
+
definition.patch?.(exported, version);
|
|
2767
|
+
} catch {
|
|
2768
|
+
}
|
|
2769
|
+
for (const file of definition.files ?? []) {
|
|
2770
|
+
try {
|
|
2771
|
+
file.patch?.(appRequire(file.name), version);
|
|
2772
|
+
} catch {
|
|
2773
|
+
}
|
|
2774
|
+
}
|
|
2775
|
+
}
|
|
2776
|
+
}
|
|
2777
|
+
}
|
|
1590
2778
|
function registerEsmHook() {
|
|
1591
2779
|
const g2 = globalThis;
|
|
1592
2780
|
if (g2.__ZHARP_ESM_HOOK__) return;
|
|
1593
2781
|
g2.__ZHARP_ESM_HOOK__ = true;
|
|
1594
2782
|
try {
|
|
1595
|
-
(0, import_node_module.register)?.("@opentelemetry/instrumentation/hook.mjs", importMetaUrl);
|
|
2783
|
+
(0, import_node_module.register)?.("@opentelemetry/instrumentation/hook.mjs", importMetaUrl, esmHookOptions());
|
|
2784
|
+
} catch {
|
|
2785
|
+
}
|
|
2786
|
+
}
|
|
2787
|
+
function esmHookOptions() {
|
|
2788
|
+
try {
|
|
2789
|
+
const otel = (0, import_node_module.createRequire)((0, import_node_module.createRequire)(importMetaUrl).resolve("@opentelemetry/instrumentation"));
|
|
2790
|
+
const { createAddHookMessageChannel } = otel("import-in-the-middle");
|
|
2791
|
+
if (typeof createAddHookMessageChannel === "function") {
|
|
2792
|
+
const { registerOptions } = createAddHookMessageChannel();
|
|
2793
|
+
return { data: { ...registerOptions.data, exclude: ESM_HOOK_EXCLUDE }, transferList: registerOptions.transferList };
|
|
2794
|
+
}
|
|
1596
2795
|
} catch {
|
|
1597
2796
|
}
|
|
2797
|
+
return { data: { exclude: ESM_HOOK_EXCLUDE } };
|
|
1598
2798
|
}
|
|
1599
2799
|
function switchOn(option, variable, fallback) {
|
|
1600
2800
|
if (typeof option === "boolean") return option;
|
|
@@ -1651,8 +2851,8 @@ var ExtractOnlyPropagator = class {
|
|
|
1651
2851
|
inner;
|
|
1652
2852
|
inject() {
|
|
1653
2853
|
}
|
|
1654
|
-
extract(
|
|
1655
|
-
return this.inner.extract(
|
|
2854
|
+
extract(context3, carrier, getter) {
|
|
2855
|
+
return this.inner.extract(context3, carrier, getter);
|
|
1656
2856
|
}
|
|
1657
2857
|
fields() {
|
|
1658
2858
|
return [];
|