@zharp/node 0.4.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 +60 -2
- package/dist/index.d.ts +60 -2
- package/dist/index.js +569 -9
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +573 -11
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -6,17 +6,20 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
|
|
|
6
6
|
});
|
|
7
7
|
|
|
8
8
|
// src/zharp.ts
|
|
9
|
-
import { register as registerLoader } from "module";
|
|
9
|
+
import { createRequire, isBuiltin, register as registerLoader } from "module";
|
|
10
|
+
import { join } from "path";
|
|
10
11
|
import {
|
|
11
12
|
context as context2,
|
|
12
13
|
DiagLogLevel,
|
|
13
14
|
diag,
|
|
14
15
|
INVALID_SPAN_CONTEXT,
|
|
15
16
|
logs,
|
|
17
|
+
propagation as propagation2,
|
|
18
|
+
SpanKind as SpanKind2,
|
|
16
19
|
SpanStatusCode as SpanStatusCode2,
|
|
17
20
|
trace as trace4
|
|
18
21
|
} from "@opentelemetry/api";
|
|
19
|
-
import { CompositePropagator, W3CBaggagePropagator, W3CTraceContextPropagator } from "@opentelemetry/core";
|
|
22
|
+
import { CompositePropagator, unsuppressTracing, W3CBaggagePropagator, W3CTraceContextPropagator } from "@opentelemetry/core";
|
|
20
23
|
import { envDetector, hostDetector, resourceFromAttributes } from "@opentelemetry/resources";
|
|
21
24
|
import { NodeSDK } from "@opentelemetry/sdk-node";
|
|
22
25
|
import {
|
|
@@ -657,6 +660,8 @@ function withBodyCapture(settings, config = {}) {
|
|
|
657
660
|
|
|
658
661
|
// src/headers.ts
|
|
659
662
|
import { ClientRequest as ClientRequest2, IncomingMessage as IncomingMessage2, ServerResponse as ServerResponse2 } from "http";
|
|
663
|
+
|
|
664
|
+
// ../../internal/src/headers.ts
|
|
660
665
|
var SECRET = /* @__PURE__ */ new Set(["authorization", "proxy-authorization", "cookie", "set-cookie", "x-api-key", "x-auth-token", "x-csrf-token", "x-xsrf-token"]);
|
|
661
666
|
var MAX_HEADERS = 40;
|
|
662
667
|
var MAX_VALUE = 512;
|
|
@@ -672,8 +677,10 @@ function shown(name, value, settings) {
|
|
|
672
677
|
}
|
|
673
678
|
function headerAttributes(side, headers, settings) {
|
|
674
679
|
const out = {};
|
|
680
|
+
if (!headers) return out;
|
|
681
|
+
const entries = typeof headers[Symbol.iterator] === "function" ? [...headers] : Object.entries(headers);
|
|
675
682
|
let count = 0;
|
|
676
|
-
for (const [rawName, value] of
|
|
683
|
+
for (const [rawName, value] of entries) {
|
|
677
684
|
if (count >= MAX_HEADERS) break;
|
|
678
685
|
const name = rawName.toLowerCase();
|
|
679
686
|
const text = shown(name, value, settings);
|
|
@@ -683,6 +690,8 @@ function headerAttributes(side, headers, settings) {
|
|
|
683
690
|
}
|
|
684
691
|
return out;
|
|
685
692
|
}
|
|
693
|
+
|
|
694
|
+
// src/headers.ts
|
|
686
695
|
function withHeaderCapture(settings, config = {}) {
|
|
687
696
|
return {
|
|
688
697
|
...config,
|
|
@@ -707,7 +716,7 @@ import { context, createContextKey, SpanKind, SpanStatusCode, trace } from "@ope
|
|
|
707
716
|
import { InstrumentationBase, InstrumentationNodeModuleDefinition } from "@opentelemetry/instrumentation";
|
|
708
717
|
|
|
709
718
|
// src/version.ts
|
|
710
|
-
var VERSION = "0.
|
|
719
|
+
var VERSION = "0.5.0";
|
|
711
720
|
|
|
712
721
|
// src/source.ts
|
|
713
722
|
import { readFileSync, statSync } from "fs";
|
|
@@ -1658,7 +1667,8 @@ function frameFile(line) {
|
|
|
1658
1667
|
match = /^(?:[^@]*@)?(.+?):\d+:\d+$/.exec(text);
|
|
1659
1668
|
return match ? clean(match[1]) : void 0;
|
|
1660
1669
|
}
|
|
1661
|
-
function clean(
|
|
1670
|
+
function clean(raw) {
|
|
1671
|
+
const file = raw.replace(/^address at /, "");
|
|
1662
1672
|
if (!file || file.includes("eval at ") || file === "<anonymous>" || file === "native") return void 0;
|
|
1663
1673
|
return file;
|
|
1664
1674
|
}
|
|
@@ -1789,6 +1799,273 @@ Caused by: ${cause.stack}`;
|
|
|
1789
1799
|
};
|
|
1790
1800
|
}
|
|
1791
1801
|
|
|
1802
|
+
// src/serverless.ts
|
|
1803
|
+
import { randomUUID } from "crypto";
|
|
1804
|
+
var DEFAULT_FLUSH_MS = 2e3;
|
|
1805
|
+
var headerGetter = {
|
|
1806
|
+
get(carrier, key) {
|
|
1807
|
+
return header2(carrier, key);
|
|
1808
|
+
},
|
|
1809
|
+
keys(carrier) {
|
|
1810
|
+
if (!carrier || typeof carrier !== "object") return [];
|
|
1811
|
+
if (typeof carrier.keys === "function" && typeof carrier.get === "function") {
|
|
1812
|
+
try {
|
|
1813
|
+
return [...carrier.keys()];
|
|
1814
|
+
} catch {
|
|
1815
|
+
return [];
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
return Object.keys(carrier);
|
|
1819
|
+
}
|
|
1820
|
+
};
|
|
1821
|
+
function header2(carrier, name) {
|
|
1822
|
+
if (!carrier || typeof carrier !== "object") return void 0;
|
|
1823
|
+
const c = carrier;
|
|
1824
|
+
if (typeof c.get === "function" && typeof c.has === "function") {
|
|
1825
|
+
try {
|
|
1826
|
+
return c.get(name) ?? void 0;
|
|
1827
|
+
} catch {
|
|
1828
|
+
return void 0;
|
|
1829
|
+
}
|
|
1830
|
+
}
|
|
1831
|
+
const wanted2 = name.toLowerCase();
|
|
1832
|
+
for (const key of Object.keys(c)) {
|
|
1833
|
+
if (key.toLowerCase() !== wanted2) continue;
|
|
1834
|
+
const value = c[key];
|
|
1835
|
+
if (Array.isArray(value)) return value.join(",");
|
|
1836
|
+
return value == null ? void 0 : String(value);
|
|
1837
|
+
}
|
|
1838
|
+
return void 0;
|
|
1839
|
+
}
|
|
1840
|
+
function pathOf(url) {
|
|
1841
|
+
if (typeof url !== "string" || !url) return void 0;
|
|
1842
|
+
try {
|
|
1843
|
+
return new URL(url, "http://x").pathname;
|
|
1844
|
+
} catch {
|
|
1845
|
+
return url.split("?")[0];
|
|
1846
|
+
}
|
|
1847
|
+
}
|
|
1848
|
+
function clean2(attrs) {
|
|
1849
|
+
const out = {};
|
|
1850
|
+
for (const [key, value] of Object.entries(attrs)) {
|
|
1851
|
+
if (value === void 0 || value === null || value === "") continue;
|
|
1852
|
+
out[key] = typeof value === "number" || typeof value === "boolean" ? value : String(value);
|
|
1853
|
+
}
|
|
1854
|
+
return out;
|
|
1855
|
+
}
|
|
1856
|
+
var STREAMING = /* @__PURE__ */ Symbol.for("aws.lambda.runtime.handler.streaming");
|
|
1857
|
+
var isStreamingLambda = (handler) => handler?.[STREAMING] === "response";
|
|
1858
|
+
function lambdaInvocation(event, ctx, coldstart) {
|
|
1859
|
+
const rc = event?.requestContext;
|
|
1860
|
+
const v2 = rc?.http && typeof rc.http.method === "string";
|
|
1861
|
+
const v1 = typeof event?.httpMethod === "string" && (rc || event.headers);
|
|
1862
|
+
const http = !!(v2 || v1);
|
|
1863
|
+
const functionName = ctx?.functionName ?? process.env.AWS_LAMBDA_FUNCTION_NAME;
|
|
1864
|
+
const arn = ctx?.invokedFunctionArn;
|
|
1865
|
+
const base = {
|
|
1866
|
+
"faas.trigger": lambdaTrigger(event, http),
|
|
1867
|
+
"faas.invocation_id": ctx?.awsRequestId,
|
|
1868
|
+
"faas.coldstart": coldstart,
|
|
1869
|
+
"faas.name": functionName,
|
|
1870
|
+
"faas.version": ctx?.functionVersion ?? process.env.AWS_LAMBDA_FUNCTION_VERSION,
|
|
1871
|
+
"cloud.provider": "aws",
|
|
1872
|
+
"cloud.platform": "aws_lambda",
|
|
1873
|
+
"cloud.region": process.env.AWS_REGION,
|
|
1874
|
+
"cloud.resource_id": arn,
|
|
1875
|
+
"cloud.account.id": arn?.split(":")[4]
|
|
1876
|
+
};
|
|
1877
|
+
if (!http) {
|
|
1878
|
+
const source = lambdaSource(event);
|
|
1879
|
+
return {
|
|
1880
|
+
name: functionName ?? "lambda",
|
|
1881
|
+
attributes: clean2({ ...base, ...source ? { "faas.event_source": source } : {} }),
|
|
1882
|
+
http: false,
|
|
1883
|
+
mechanism: "aws-lambda"
|
|
1884
|
+
};
|
|
1885
|
+
}
|
|
1886
|
+
const method = v2 ? rc.http.method : event.httpMethod;
|
|
1887
|
+
const path = v2 ? rc.http.path ?? event.rawPath : event.path;
|
|
1888
|
+
const routeKey = rc?.routeKey && rc.routeKey !== "$default" ? rc.routeKey.split(" ").slice(-1)[0] : void 0;
|
|
1889
|
+
const route = routeKey ?? (typeof event.resource === "string" && !event.resource.includes("{proxy+}") ? event.resource : void 0);
|
|
1890
|
+
return {
|
|
1891
|
+
name: `${method} ${route ?? path ?? "/"}`,
|
|
1892
|
+
attributes: clean2({
|
|
1893
|
+
...base,
|
|
1894
|
+
"http.request.method": method,
|
|
1895
|
+
"url.path": path,
|
|
1896
|
+
"http.route": route,
|
|
1897
|
+
"url.scheme": header2(event.headers, "x-forwarded-proto"),
|
|
1898
|
+
"server.address": header2(event.headers, "host") ?? rc?.domainName,
|
|
1899
|
+
"user_agent.original": v2 ? rc.http.userAgent : header2(event.headers, "user-agent"),
|
|
1900
|
+
"client.address": v2 ? rc.http.sourceIp : rc?.identity?.sourceIp
|
|
1901
|
+
}),
|
|
1902
|
+
// REST API events may carry the same header in both maps; the single-value one is enough.
|
|
1903
|
+
carrier: event.headers ?? event.multiValueHeaders,
|
|
1904
|
+
http: true,
|
|
1905
|
+
mechanism: "aws-lambda"
|
|
1906
|
+
};
|
|
1907
|
+
}
|
|
1908
|
+
function lambdaSource(event) {
|
|
1909
|
+
const record = Array.isArray(event?.Records) ? event.Records[0] : void 0;
|
|
1910
|
+
return record?.eventSource ?? record?.EventSource ?? (typeof event?.source === "string" ? event.source : void 0);
|
|
1911
|
+
}
|
|
1912
|
+
function lambdaTrigger(event, http) {
|
|
1913
|
+
if (http || event?.requestContext?.elb) return "http";
|
|
1914
|
+
const source = lambdaSource(event) ?? "";
|
|
1915
|
+
if (/^aws:(sqs|sns|kinesis|kafka)$/.test(source) || source === "aws:mq" || event?.eventSource === "aws:kafka") return "pubsub";
|
|
1916
|
+
if (/^aws:(s3|dynamodb)$/.test(source)) return "datasource";
|
|
1917
|
+
if (event?.["detail-type"] === "Scheduled Event" || source === "aws.scheduler") return "timer";
|
|
1918
|
+
return "other";
|
|
1919
|
+
}
|
|
1920
|
+
function lambdaStatus(result, event) {
|
|
1921
|
+
if (result && typeof result === "object" && typeof result.statusCode === "number") return result.statusCode;
|
|
1922
|
+
if (event?.requestContext?.http) return 200;
|
|
1923
|
+
return void 0;
|
|
1924
|
+
}
|
|
1925
|
+
function azureInvocation(args, coldstart) {
|
|
1926
|
+
const v4 = args[1] && typeof args[1] === "object" && typeof args[1].invocationId === "string";
|
|
1927
|
+
const v3 = !v4 && args[0] && typeof args[0] === "object" && typeof args[0].invocationId === "string";
|
|
1928
|
+
if (!v4 && !v3) return null;
|
|
1929
|
+
const ctx = v4 ? args[1] : args[0];
|
|
1930
|
+
const triggerType = v4 ? ctx.options?.trigger?.type : (ctx.bindingDefinitions ?? []).find((b) => b?.direction === "in" && /Trigger$/.test(b?.type ?? ""))?.type;
|
|
1931
|
+
const functionName = ctx.functionName ?? ctx.executionContext?.functionName;
|
|
1932
|
+
const request = v4 ? triggerType === "httpTrigger" ? args[0] : void 0 : ctx.req ?? (triggerType === "httpTrigger" ? args[1] : void 0);
|
|
1933
|
+
const http = !!request && typeof request.method === "string";
|
|
1934
|
+
const base = {
|
|
1935
|
+
"faas.trigger": azureTrigger(triggerType, http),
|
|
1936
|
+
"faas.invocation_id": ctx.invocationId,
|
|
1937
|
+
"faas.coldstart": coldstart,
|
|
1938
|
+
"faas.name": functionName,
|
|
1939
|
+
"cloud.provider": "azure",
|
|
1940
|
+
"cloud.platform": "azure_functions",
|
|
1941
|
+
"cloud.region": process.env.REGION_NAME
|
|
1942
|
+
};
|
|
1943
|
+
if (!http) {
|
|
1944
|
+
return { name: functionName ?? "function", attributes: clean2(base), http: false, mechanism: "azure-functions" };
|
|
1945
|
+
}
|
|
1946
|
+
const path = pathOf(request.url) ?? pathOf(request.originalUrl);
|
|
1947
|
+
return {
|
|
1948
|
+
name: `${request.method} ${path ?? "/"}`,
|
|
1949
|
+
attributes: clean2({
|
|
1950
|
+
...base,
|
|
1951
|
+
"http.request.method": request.method,
|
|
1952
|
+
"url.path": path,
|
|
1953
|
+
"user_agent.original": header2(request.headers, "user-agent")
|
|
1954
|
+
}),
|
|
1955
|
+
carrier: request.headers,
|
|
1956
|
+
http: true,
|
|
1957
|
+
mechanism: "azure-functions"
|
|
1958
|
+
};
|
|
1959
|
+
}
|
|
1960
|
+
function azureTrigger(type, http) {
|
|
1961
|
+
if (http || type === "httpTrigger") return "http";
|
|
1962
|
+
if (type === "timerTrigger") return "timer";
|
|
1963
|
+
if (type && /^(queue|serviceBus|eventHub|eventGrid|kafka|rabbitMQ|webPubSub|signalR)/i.test(type)) return "pubsub";
|
|
1964
|
+
if (type && /^(blob|cosmosDB|sql|mysql)/i.test(type)) return "datasource";
|
|
1965
|
+
return "other";
|
|
1966
|
+
}
|
|
1967
|
+
function azureStatus(result, args) {
|
|
1968
|
+
const v4 = args[1] && typeof args[1]?.invocationId === "string";
|
|
1969
|
+
const response = v4 ? result : args[0]?.res ?? result;
|
|
1970
|
+
const status = response?.status ?? response?.statusCode;
|
|
1971
|
+
const n = typeof status === "string" ? Number(status) : status;
|
|
1972
|
+
return typeof n === "number" && Number.isFinite(n) ? n : 200;
|
|
1973
|
+
}
|
|
1974
|
+
var gcfName = () => process.env.K_SERVICE ?? process.env.FUNCTION_TARGET ?? process.env.FUNCTION_NAME;
|
|
1975
|
+
var gcfBase = (coldstart) => ({
|
|
1976
|
+
"faas.coldstart": coldstart,
|
|
1977
|
+
"faas.name": gcfName(),
|
|
1978
|
+
"faas.version": process.env.K_REVISION,
|
|
1979
|
+
"cloud.provider": "gcp",
|
|
1980
|
+
"cloud.platform": "gcp_cloud_functions",
|
|
1981
|
+
"cloud.region": process.env.FUNCTION_REGION
|
|
1982
|
+
});
|
|
1983
|
+
var isHttpPair = (req, res) => !!req && typeof req === "object" && typeof req.method === "string" && !!req.headers && !!res && typeof res.end === "function";
|
|
1984
|
+
function gcfHttpInvocation(req, coldstart) {
|
|
1985
|
+
const path = pathOf(req.originalUrl ?? req.url);
|
|
1986
|
+
const id = header2(req.headers, "function-execution-id") ?? header2(req.headers, "x-cloud-trace-context")?.split("/")[0] ?? randomUUID();
|
|
1987
|
+
return {
|
|
1988
|
+
name: `${req.method} ${path ?? "/"}`,
|
|
1989
|
+
attributes: clean2({
|
|
1990
|
+
...gcfBase(coldstart),
|
|
1991
|
+
"faas.trigger": "http",
|
|
1992
|
+
"faas.invocation_id": id,
|
|
1993
|
+
"http.request.method": req.method,
|
|
1994
|
+
"url.path": path,
|
|
1995
|
+
"server.address": header2(req.headers, "host"),
|
|
1996
|
+
"user_agent.original": header2(req.headers, "user-agent")
|
|
1997
|
+
}),
|
|
1998
|
+
carrier: req.headers,
|
|
1999
|
+
http: true,
|
|
2000
|
+
mechanism: "gcp-functions"
|
|
2001
|
+
};
|
|
2002
|
+
}
|
|
2003
|
+
function gcfEventInvocation(args, coldstart) {
|
|
2004
|
+
const ce = args[0] && typeof args[0] === "object" && typeof args[0].specversion === "string" ? args[0] : void 0;
|
|
2005
|
+
const legacy = !ce && args[1] && typeof args[1] === "object" ? args[1] : void 0;
|
|
2006
|
+
const type = ce?.type ?? legacy?.eventType ?? legacy?.type ?? "";
|
|
2007
|
+
const trigger = /pubsub/i.test(type) ? "pubsub" : /storage|firestore|firebase|datastore|database/i.test(type) ? "datasource" : /scheduler/i.test(type) ? "timer" : "other";
|
|
2008
|
+
return {
|
|
2009
|
+
name: gcfName() ?? "function",
|
|
2010
|
+
attributes: clean2({
|
|
2011
|
+
...gcfBase(coldstart),
|
|
2012
|
+
"faas.trigger": trigger,
|
|
2013
|
+
"faas.invocation_id": ce?.id ?? legacy?.eventId ?? randomUUID(),
|
|
2014
|
+
"cloudevents.event_type": type || void 0,
|
|
2015
|
+
"cloudevents.event_source": ce?.source
|
|
2016
|
+
}),
|
|
2017
|
+
// The CloudEvents distributed tracing extension.
|
|
2018
|
+
carrier: ce ? { traceparent: ce.traceparent, tracestate: ce.tracestate } : void 0,
|
|
2019
|
+
http: false,
|
|
2020
|
+
mechanism: "gcp-functions"
|
|
2021
|
+
};
|
|
2022
|
+
}
|
|
2023
|
+
function serverlessResource() {
|
|
2024
|
+
const env = process.env;
|
|
2025
|
+
if (env.AWS_LAMBDA_FUNCTION_NAME) {
|
|
2026
|
+
const memory = Number(env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE);
|
|
2027
|
+
return clean2({
|
|
2028
|
+
"cloud.provider": "aws",
|
|
2029
|
+
"cloud.platform": "aws_lambda",
|
|
2030
|
+
"cloud.region": env.AWS_REGION,
|
|
2031
|
+
"faas.name": env.AWS_LAMBDA_FUNCTION_NAME,
|
|
2032
|
+
"faas.version": env.AWS_LAMBDA_FUNCTION_VERSION,
|
|
2033
|
+
"faas.instance": env.AWS_LAMBDA_LOG_STREAM_NAME,
|
|
2034
|
+
"faas.max_memory": Number.isFinite(memory) && memory > 0 ? memory * 1024 * 1024 : void 0
|
|
2035
|
+
});
|
|
2036
|
+
}
|
|
2037
|
+
if (env.FUNCTIONS_WORKER_RUNTIME && (env.WEBSITE_SITE_NAME || env.AzureWebJobsStorage || env.FUNCTIONS_EXTENSION_VERSION)) {
|
|
2038
|
+
return clean2({
|
|
2039
|
+
"cloud.provider": "azure",
|
|
2040
|
+
"cloud.platform": "azure_functions",
|
|
2041
|
+
"cloud.region": env.REGION_NAME,
|
|
2042
|
+
"faas.instance": env.WEBSITE_INSTANCE_ID
|
|
2043
|
+
});
|
|
2044
|
+
}
|
|
2045
|
+
if (env.FUNCTION_TARGET && (env.K_SERVICE || env.FUNCTION_NAME)) {
|
|
2046
|
+
return clean2({
|
|
2047
|
+
"cloud.provider": "gcp",
|
|
2048
|
+
"cloud.platform": "gcp_cloud_functions",
|
|
2049
|
+
"cloud.region": env.FUNCTION_REGION,
|
|
2050
|
+
"faas.name": gcfName(),
|
|
2051
|
+
"faas.version": env.K_REVISION
|
|
2052
|
+
});
|
|
2053
|
+
}
|
|
2054
|
+
return {};
|
|
2055
|
+
}
|
|
2056
|
+
function serverlessName() {
|
|
2057
|
+
return process.env.AWS_LAMBDA_FUNCTION_NAME ?? process.env.WEBSITE_SITE_NAME ?? (process.env.FUNCTION_TARGET ? gcfName() : void 0);
|
|
2058
|
+
}
|
|
2059
|
+
function sameShape(wrapper, handler) {
|
|
2060
|
+
try {
|
|
2061
|
+
Object.defineProperty(wrapper, "length", { value: handler.length });
|
|
2062
|
+
Object.defineProperty(wrapper, "name", { value: handler.name });
|
|
2063
|
+
for (const key of Object.getOwnPropertySymbols(handler)) wrapper[key] = handler[key];
|
|
2064
|
+
} catch {
|
|
2065
|
+
}
|
|
2066
|
+
return wrapper;
|
|
2067
|
+
}
|
|
2068
|
+
|
|
1792
2069
|
// src/zharp.ts
|
|
1793
2070
|
var DEFAULT_ENDPOINT = "https://api.zharp.io/api/v1/otlp";
|
|
1794
2071
|
var EXIT_FLUSH_MS = 2e3;
|
|
@@ -1805,6 +2082,13 @@ var ZharpNode = class {
|
|
|
1805
2082
|
reported = /* @__PURE__ */ new WeakSet();
|
|
1806
2083
|
/** Failed queries waiting to be reported, once and with their call site. */
|
|
1807
2084
|
dbErrors = null;
|
|
2085
|
+
/** No invocation has run in this process yet: the next one is the cold start. */
|
|
2086
|
+
cold = true;
|
|
2087
|
+
/**
|
|
2088
|
+
* A Cloud Function is wrapped: its wrapper makes each request's span (and flushes before the
|
|
2089
|
+
* response), so the http server instrumentation leaves incoming requests alone.
|
|
2090
|
+
*/
|
|
2091
|
+
wrapsHttp = false;
|
|
1808
2092
|
/** `Zharp.log.info("Order placed", { orderId })` — and debug, warn, error, fatal, trace. */
|
|
1809
2093
|
log = {
|
|
1810
2094
|
trace: (m, a) => this.emit("trace", m, a),
|
|
@@ -1844,7 +2128,7 @@ var ZharpNode = class {
|
|
|
1844
2128
|
warn("No key found \u2014 pass Zharp.init({ key }) or set ZHARP_API_KEY. Nothing will be sent.");
|
|
1845
2129
|
return;
|
|
1846
2130
|
}
|
|
1847
|
-
const service = pick(options.service, nodeEnv("ZHARP_SERVICE"), nodeEnv("OTEL_SERVICE_NAME"), packageName()) ?? "node-app";
|
|
2131
|
+
const service = pick(options.service, nodeEnv("ZHARP_SERVICE"), nodeEnv("OTEL_SERVICE_NAME"), packageName(), serverlessName()) ?? "node-app";
|
|
1848
2132
|
const environment = pick(options.environment, nodeEnv("ZHARP_ENV"), nodeEnv("NODE_ENV"));
|
|
1849
2133
|
const release = pick(options.release, nodeEnv("ZHARP_RELEASE"), nodeEnv("ZHARP_VERSION"));
|
|
1850
2134
|
const endpoint = (pick(options.endpoint, nodeEnv("ZHARP_ENDPOINT")) ?? DEFAULT_ENDPOINT).replace(/\/+$/, "");
|
|
@@ -1890,17 +2174,20 @@ var ZharpNode = class {
|
|
|
1890
2174
|
"telemetry.sdk.language": "nodejs",
|
|
1891
2175
|
"telemetry.sdk.version": VERSION,
|
|
1892
2176
|
"process.runtime.name": "nodejs",
|
|
1893
|
-
"process.runtime.version": process.versions.node
|
|
2177
|
+
"process.runtime.version": process.versions.node,
|
|
2178
|
+
// Lambda, Azure Functions, Cloud Functions: cloud.provider, cloud.platform, faas.name…
|
|
2179
|
+
...serverlessResource()
|
|
1894
2180
|
});
|
|
1895
2181
|
const propagator = new CompositePropagator({
|
|
1896
2182
|
propagators: [new W3CTraceContextPropagator(), new W3CBaggagePropagator()]
|
|
1897
2183
|
});
|
|
1898
2184
|
const bodies = bodySettings(options.captureBodies, nodeEnv("ZHARP_CAPTURE_BODIES"));
|
|
1899
2185
|
const headerCapture = headerSettings(options.captureHeaders, nodeEnv("ZHARP_CAPTURE_HEADERS"));
|
|
1900
|
-
const ownHttp = options.instrumentations?.["@opentelemetry/instrumentation-http"];
|
|
2186
|
+
const ownHttp = this.withWrappedRequests(options.instrumentations?.["@opentelemetry/instrumentation-http"]);
|
|
1901
2187
|
const withBodies = bodies ? withBodyCapture(bodies, ownHttp) : ownHttp;
|
|
1902
2188
|
const httpConfig = headerCapture ? withHeaderCapture(headerCapture, withBodies) : withBodies;
|
|
1903
2189
|
const rate = typeof options.sampleRate === "number" ? Math.min(1, Math.max(0, options.sampleRate)) : 1;
|
|
2190
|
+
let instrumentations = [];
|
|
1904
2191
|
this.sdk = new NodeSDK({
|
|
1905
2192
|
resource,
|
|
1906
2193
|
// Host and OTEL_RESOURCE_ATTRIBUTES only. The process detector would send the command line,
|
|
@@ -1912,22 +2199,27 @@ var ZharpNode = class {
|
|
|
1912
2199
|
logRecordProcessors: this.logProcessors,
|
|
1913
2200
|
// Without this the SDK would start an OTLP metrics exporter pointed at localhost:4318.
|
|
1914
2201
|
metricReaders: [],
|
|
1915
|
-
instrumentations: [
|
|
2202
|
+
instrumentations: instrumentations = [
|
|
1916
2203
|
...tracing ? getNodeAutoInstrumentations({
|
|
1917
2204
|
// A span per DNS lookup, socket and file read buries the requests that matter.
|
|
1918
2205
|
"@opentelemetry/instrumentation-dns": { enabled: false },
|
|
1919
2206
|
"@opentelemetry/instrumentation-net": { enabled: false },
|
|
1920
2207
|
"@opentelemetry/instrumentation-fs": { enabled: false },
|
|
2208
|
+
// Zharp.lambda() makes the invocation's span and flushes before returning; this one
|
|
2209
|
+
// would wrap the handler again (a second span) from _HANDLER, when it can find it.
|
|
2210
|
+
"@opentelemetry/instrumentation-aws-lambda": { enabled: false },
|
|
1921
2211
|
...options.instrumentations,
|
|
1922
2212
|
...bridges,
|
|
1923
2213
|
...httpConfig && { "@opentelemetry/instrumentation-http": httpConfig }
|
|
1924
|
-
}) : logsOnlyInstrumentations({ ...options, instrumentations: { ...options.instrumentations, ...bridges } }),
|
|
2214
|
+
}) : logsOnlyInstrumentations({ ...options, instrumentations: { ...options.instrumentations, ...bridges, "@opentelemetry/instrumentation-http": ownHttp } }),
|
|
1925
2215
|
...this.dbErrors ? [new DbDriverErrorsInstrumentation((traceId, error) => this.dbErrors?.attach(traceId, error))] : [],
|
|
1926
2216
|
...tracing && options.captureUncaught !== false ? [new FrameworkErrorsInstrumentation((error, mechanism) => this.report(error, false, "error", { "zharp.mechanism": mechanism }, true))] : [],
|
|
1927
2217
|
...options.extraInstrumentations ?? []
|
|
1928
2218
|
]
|
|
1929
2219
|
});
|
|
1930
2220
|
this.sdk.start();
|
|
2221
|
+
if (tracing) preloadCommonJsFrameworks();
|
|
2222
|
+
if (isBun()) patchWithoutHooks(instrumentations);
|
|
1931
2223
|
this.logger = logs.getLogger("@zharp/node", VERSION);
|
|
1932
2224
|
if (correlation) this.teardowns.push(stampOutput());
|
|
1933
2225
|
if (sendLogs) {
|
|
@@ -2032,6 +2324,207 @@ var ZharpNode = class {
|
|
|
2032
2324
|
})));
|
|
2033
2325
|
await Promise.race([all, new Promise((resolve2) => setTimeout(resolve2, timeoutMs).unref())]);
|
|
2034
2326
|
}
|
|
2327
|
+
// ── serverless ────────────────────────────────────────────────────────
|
|
2328
|
+
//
|
|
2329
|
+
// Each wrapper returns a function of the same shape as the handler: same arguments, same
|
|
2330
|
+
// result. Every invocation is one SERVER span (continuing the caller's trace when the trigger
|
|
2331
|
+
// carries a `traceparent`), an error the handler throws is reported once and thrown on, and
|
|
2332
|
+
// everything is flushed — within `flushTimeout` — before the result goes back, because the
|
|
2333
|
+
// platform freezes the process as soon as it has it.
|
|
2334
|
+
/**
|
|
2335
|
+
* An AWS Lambda handler (async, callback, or `awslambda.streamifyResponse`):
|
|
2336
|
+
*
|
|
2337
|
+
* export const handler = Zharp.lambda(async (event, context) => { … });
|
|
2338
|
+
*/
|
|
2339
|
+
lambda(handler, options = {}) {
|
|
2340
|
+
const self = this;
|
|
2341
|
+
const streaming = isStreamingLambda(handler);
|
|
2342
|
+
return sameShape(function zharpLambda(...args) {
|
|
2343
|
+
if (!self.sdk) return handler.apply(this, args);
|
|
2344
|
+
const event = args[0];
|
|
2345
|
+
const ctx = streaming ? args[2] : args[1];
|
|
2346
|
+
const budget = () => {
|
|
2347
|
+
const limit = options.flushTimeout ?? DEFAULT_FLUSH_MS;
|
|
2348
|
+
const left = typeof ctx?.getRemainingTimeInMillis === "function" ? Number(ctx.getRemainingTimeInMillis()) : NaN;
|
|
2349
|
+
return Number.isFinite(left) ? Math.max(0, Math.min(limit, left - 100)) : limit;
|
|
2350
|
+
};
|
|
2351
|
+
const invocation = lambdaInvocation(event, ctx, self.takeColdstart());
|
|
2352
|
+
const callback = !streaming && handler.length >= 3 ? 2 : null;
|
|
2353
|
+
return self.runInvocation(invocation, budget, (result) => invocation.http ? lambdaStatus(result, event) : void 0, handler, this, args, callback);
|
|
2354
|
+
}, handler);
|
|
2355
|
+
}
|
|
2356
|
+
/**
|
|
2357
|
+
* An Azure Functions handler, v4 programming model (`(request, context)`, any trigger) or v3
|
|
2358
|
+
* (`(context, req)`):
|
|
2359
|
+
*
|
|
2360
|
+
* app.http('orders', { handler: Zharp.azureFunction(async (request, context) => { … }) });
|
|
2361
|
+
*/
|
|
2362
|
+
azureFunction(handler, options = {}) {
|
|
2363
|
+
const self = this;
|
|
2364
|
+
return sameShape(function zharpAzureFunction(...args) {
|
|
2365
|
+
if (!self.sdk) return handler.apply(this, args);
|
|
2366
|
+
const invocation = azureInvocation(args, self.takeColdstart());
|
|
2367
|
+
if (!invocation) return handler.apply(this, args);
|
|
2368
|
+
const budget = () => options.flushTimeout ?? DEFAULT_FLUSH_MS;
|
|
2369
|
+
return self.runInvocation(invocation, budget, (result) => invocation.http ? azureStatus(result, args) : void 0, handler, this, args, null);
|
|
2370
|
+
}, handler);
|
|
2371
|
+
}
|
|
2372
|
+
/**
|
|
2373
|
+
* A Google Cloud Function: an HTTP function `(req, res)`, a CloudEvent function `(cloudEvent)`,
|
|
2374
|
+
* or a background function `(data, context)`.
|
|
2375
|
+
*
|
|
2376
|
+
* functions.http('orders', Zharp.cloudFunction((req, res) => { … }));
|
|
2377
|
+
*
|
|
2378
|
+
* An HTTP function's response is held until everything is sent — Cloud Functions may stop
|
|
2379
|
+
* the instance's CPU the moment the response is out.
|
|
2380
|
+
*/
|
|
2381
|
+
cloudFunction(handler, options = {}) {
|
|
2382
|
+
const self = this;
|
|
2383
|
+
this.wrapsHttp = true;
|
|
2384
|
+
const budget = () => options.flushTimeout ?? DEFAULT_FLUSH_MS;
|
|
2385
|
+
return sameShape(function zharpCloudFunction(...args) {
|
|
2386
|
+
if (!self.sdk) return handler.apply(this, args);
|
|
2387
|
+
if (isHttpPair(args[0], args[1])) return self.runHttpFunction(gcfHttpInvocation(args[0], self.takeColdstart()), budget, handler, this, args);
|
|
2388
|
+
const cloudEvent = args[0] && typeof args[0] === "object" && typeof args[0].specversion === "string";
|
|
2389
|
+
const callback = cloudEvent ? handler.length >= 2 ? 1 : null : handler.length >= 3 ? 2 : null;
|
|
2390
|
+
return self.runInvocation(gcfEventInvocation(args, self.takeColdstart()), budget, () => void 0, handler, this, args, callback);
|
|
2391
|
+
}, handler);
|
|
2392
|
+
}
|
|
2393
|
+
/** The first invocation in the process is the cold start (not under provisioned concurrency). */
|
|
2394
|
+
takeColdstart() {
|
|
2395
|
+
if (!this.cold) return false;
|
|
2396
|
+
this.cold = false;
|
|
2397
|
+
return process.env.AWS_LAMBDA_INITIALIZATION_TYPE !== "provisioned-concurrency";
|
|
2398
|
+
}
|
|
2399
|
+
/** The http instrumentation's config, leaving incoming requests to a wrapped Cloud Function. */
|
|
2400
|
+
withWrappedRequests(config) {
|
|
2401
|
+
const own = config?.ignoreIncomingRequestHook;
|
|
2402
|
+
return {
|
|
2403
|
+
...config,
|
|
2404
|
+
ignoreIncomingRequestHook: (request) => this.wrapsHttp || !!own?.(request)
|
|
2405
|
+
};
|
|
2406
|
+
}
|
|
2407
|
+
/** The invocation's span, in a context of its own: the caller's trace, or a new one. */
|
|
2408
|
+
beginInvocation(invocation) {
|
|
2409
|
+
let base = unsuppressTracing(context2.active());
|
|
2410
|
+
if (invocation.carrier) base = propagation2.extract(base, invocation.carrier, headerGetter);
|
|
2411
|
+
const span = trace4.getTracer("@zharp/node", VERSION).startSpan(invocation.name, { kind: SpanKind2.SERVER, attributes: invocation.attributes }, base);
|
|
2412
|
+
return { span, ctx: trace4.setSpan(base, span) };
|
|
2413
|
+
}
|
|
2414
|
+
/** Report what the handler threw, in its invocation, and fail the span. Once per error. */
|
|
2415
|
+
invocationFailed(span, ctx, invocation, error) {
|
|
2416
|
+
try {
|
|
2417
|
+
context2.with(ctx, () => this.report(error, false, "error", { "zharp.mechanism": invocation.mechanism }));
|
|
2418
|
+
const e = asError(error);
|
|
2419
|
+
span.setStatus({ code: SpanStatusCode2.ERROR, message: e.message });
|
|
2420
|
+
span.setAttribute("error.type", e.name || "Error");
|
|
2421
|
+
} catch {
|
|
2422
|
+
}
|
|
2423
|
+
}
|
|
2424
|
+
/** End the invocation's span, then send everything waiting, within the budget. */
|
|
2425
|
+
async endInvocation(span, status, budgetMs) {
|
|
2426
|
+
try {
|
|
2427
|
+
if (status !== void 0) {
|
|
2428
|
+
span.setAttribute("http.response.status_code", status);
|
|
2429
|
+
if (status >= 500) span.setStatus({ code: SpanStatusCode2.ERROR });
|
|
2430
|
+
}
|
|
2431
|
+
span.end();
|
|
2432
|
+
} catch {
|
|
2433
|
+
}
|
|
2434
|
+
if (budgetMs > 0) await this.flush(budgetMs).catch(() => {
|
|
2435
|
+
});
|
|
2436
|
+
}
|
|
2437
|
+
/**
|
|
2438
|
+
* Run a handler as one invocation. Its result (a value, a promise, or what it passes to its
|
|
2439
|
+
* callback) comes back unchanged — after the span has ended and been flushed.
|
|
2440
|
+
*/
|
|
2441
|
+
runInvocation(invocation, budget, statusOf2, handler, thisArg, args, callbackIndex) {
|
|
2442
|
+
let span;
|
|
2443
|
+
let ctx;
|
|
2444
|
+
try {
|
|
2445
|
+
({ span, ctx } = this.beginInvocation(invocation));
|
|
2446
|
+
} catch {
|
|
2447
|
+
return handler.apply(thisArg, args);
|
|
2448
|
+
}
|
|
2449
|
+
let done = null;
|
|
2450
|
+
const finish = (failed, error, result2) => {
|
|
2451
|
+
if (done) return done;
|
|
2452
|
+
if (failed) this.invocationFailed(span, ctx, invocation, error);
|
|
2453
|
+
let status;
|
|
2454
|
+
try {
|
|
2455
|
+
status = failed ? void 0 : statusOf2(result2);
|
|
2456
|
+
} catch {
|
|
2457
|
+
status = void 0;
|
|
2458
|
+
}
|
|
2459
|
+
return done = this.endInvocation(span, status, budget());
|
|
2460
|
+
};
|
|
2461
|
+
const usesCallback = callbackIndex !== null && typeof args[callbackIndex] === "function";
|
|
2462
|
+
if (usesCallback) {
|
|
2463
|
+
const index = callbackIndex;
|
|
2464
|
+
const callback = args[index];
|
|
2465
|
+
args = [...args];
|
|
2466
|
+
args[index] = function(error, ...rest) {
|
|
2467
|
+
const failed = error !== void 0 && error !== null;
|
|
2468
|
+
finish(failed, error, rest[0]).then(() => callback.call(this, error, ...rest));
|
|
2469
|
+
};
|
|
2470
|
+
}
|
|
2471
|
+
let result;
|
|
2472
|
+
try {
|
|
2473
|
+
result = context2.with(ctx, () => handler.apply(thisArg, args));
|
|
2474
|
+
} catch (error) {
|
|
2475
|
+
return finish(true, error, void 0).then(() => {
|
|
2476
|
+
throw error;
|
|
2477
|
+
});
|
|
2478
|
+
}
|
|
2479
|
+
if (result && typeof result.then === "function") {
|
|
2480
|
+
return Promise.resolve(result).then(
|
|
2481
|
+
(value) => finish(false, void 0, value).then(() => value),
|
|
2482
|
+
(error) => finish(true, error, void 0).then(() => {
|
|
2483
|
+
throw error;
|
|
2484
|
+
})
|
|
2485
|
+
);
|
|
2486
|
+
}
|
|
2487
|
+
if (usesCallback) return result;
|
|
2488
|
+
return finish(false, void 0, result).then(() => result);
|
|
2489
|
+
}
|
|
2490
|
+
/**
|
|
2491
|
+
* An HTTP function `(req, res)`: the invocation ends with the response. `res.end` is held
|
|
2492
|
+
* until the span has ended and everything is flushed, then goes out as the handler wrote it.
|
|
2493
|
+
*/
|
|
2494
|
+
runHttpFunction(invocation, budget, handler, thisArg, args) {
|
|
2495
|
+
const self = this;
|
|
2496
|
+
let span;
|
|
2497
|
+
let ctx;
|
|
2498
|
+
try {
|
|
2499
|
+
({ span, ctx } = this.beginInvocation(invocation));
|
|
2500
|
+
} catch {
|
|
2501
|
+
return handler.apply(thisArg, args);
|
|
2502
|
+
}
|
|
2503
|
+
const res = args[1];
|
|
2504
|
+
const end = res.end;
|
|
2505
|
+
res.end = function zharpEnd(...endArgs) {
|
|
2506
|
+
res.end = end;
|
|
2507
|
+
const status = typeof res.statusCode === "number" ? res.statusCode : void 0;
|
|
2508
|
+
const send = () => end.apply(res, endArgs);
|
|
2509
|
+
self.endInvocation(span, status, budget()).then(send, send);
|
|
2510
|
+
return res;
|
|
2511
|
+
};
|
|
2512
|
+
const failed = (error) => this.invocationFailed(span, ctx, invocation, error);
|
|
2513
|
+
let result;
|
|
2514
|
+
try {
|
|
2515
|
+
result = context2.with(ctx, () => handler.apply(thisArg, args));
|
|
2516
|
+
} catch (error) {
|
|
2517
|
+
failed(error);
|
|
2518
|
+
throw error;
|
|
2519
|
+
}
|
|
2520
|
+
if (result && typeof result.then === "function") {
|
|
2521
|
+
return Promise.resolve(result).then(void 0, (error) => {
|
|
2522
|
+
failed(error);
|
|
2523
|
+
throw error;
|
|
2524
|
+
});
|
|
2525
|
+
}
|
|
2526
|
+
return result;
|
|
2527
|
+
}
|
|
2035
2528
|
/** Flush, stop, and put back everything that was patched. */
|
|
2036
2529
|
async shutdown() {
|
|
2037
2530
|
const sdk = this.sdk;
|
|
@@ -2204,14 +2697,83 @@ function safeJson(value) {
|
|
|
2204
2697
|
return String(value);
|
|
2205
2698
|
}
|
|
2206
2699
|
}
|
|
2700
|
+
var ESM_HOOK_EXCLUDE = ["connect", "@hapi/hapi"];
|
|
2701
|
+
function preloadCommonJsFrameworks() {
|
|
2702
|
+
let appRequire;
|
|
2703
|
+
try {
|
|
2704
|
+
appRequire = createRequire(join(process.cwd(), "noop.js"));
|
|
2705
|
+
} catch {
|
|
2706
|
+
return;
|
|
2707
|
+
}
|
|
2708
|
+
for (const name of ESM_HOOK_EXCLUDE) {
|
|
2709
|
+
try {
|
|
2710
|
+
appRequire(name);
|
|
2711
|
+
} catch {
|
|
2712
|
+
}
|
|
2713
|
+
}
|
|
2714
|
+
}
|
|
2715
|
+
var isBun = () => typeof globalThis.Bun !== "undefined";
|
|
2716
|
+
function patchWithoutHooks(instrumentations) {
|
|
2717
|
+
let appRequire;
|
|
2718
|
+
try {
|
|
2719
|
+
appRequire = createRequire(join(process.cwd(), "noop.js"));
|
|
2720
|
+
} catch {
|
|
2721
|
+
return;
|
|
2722
|
+
}
|
|
2723
|
+
for (const instrumentation of instrumentations) {
|
|
2724
|
+
let definitions = [];
|
|
2725
|
+
for (const flag of ["_httpPatched", "_httpsPatched"]) if (instrumentation && flag in instrumentation) instrumentation[flag] = false;
|
|
2726
|
+
try {
|
|
2727
|
+
definitions = instrumentation?.getModuleDefinitions?.() ?? [];
|
|
2728
|
+
} catch {
|
|
2729
|
+
continue;
|
|
2730
|
+
}
|
|
2731
|
+
for (const definition of definitions) {
|
|
2732
|
+
let exported;
|
|
2733
|
+
try {
|
|
2734
|
+
exported = appRequire(definition.name);
|
|
2735
|
+
} catch {
|
|
2736
|
+
continue;
|
|
2737
|
+
}
|
|
2738
|
+
let version;
|
|
2739
|
+
try {
|
|
2740
|
+
version = definition.name.includes(":") || !definition.name.includes("/") && isBuiltin(definition.name) ? process.versions.node : appRequire(`${definition.name}/package.json`).version;
|
|
2741
|
+
} catch {
|
|
2742
|
+
version = void 0;
|
|
2743
|
+
}
|
|
2744
|
+
try {
|
|
2745
|
+
definition.patch?.(exported, version);
|
|
2746
|
+
} catch {
|
|
2747
|
+
}
|
|
2748
|
+
for (const file of definition.files ?? []) {
|
|
2749
|
+
try {
|
|
2750
|
+
file.patch?.(appRequire(file.name), version);
|
|
2751
|
+
} catch {
|
|
2752
|
+
}
|
|
2753
|
+
}
|
|
2754
|
+
}
|
|
2755
|
+
}
|
|
2756
|
+
}
|
|
2207
2757
|
function registerEsmHook() {
|
|
2208
2758
|
const g2 = globalThis;
|
|
2209
2759
|
if (g2.__ZHARP_ESM_HOOK__) return;
|
|
2210
2760
|
g2.__ZHARP_ESM_HOOK__ = true;
|
|
2211
2761
|
try {
|
|
2212
|
-
registerLoader?.("@opentelemetry/instrumentation/hook.mjs", import.meta.url);
|
|
2762
|
+
registerLoader?.("@opentelemetry/instrumentation/hook.mjs", import.meta.url, esmHookOptions());
|
|
2763
|
+
} catch {
|
|
2764
|
+
}
|
|
2765
|
+
}
|
|
2766
|
+
function esmHookOptions() {
|
|
2767
|
+
try {
|
|
2768
|
+
const otel = createRequire(createRequire(import.meta.url).resolve("@opentelemetry/instrumentation"));
|
|
2769
|
+
const { createAddHookMessageChannel } = otel("import-in-the-middle");
|
|
2770
|
+
if (typeof createAddHookMessageChannel === "function") {
|
|
2771
|
+
const { registerOptions } = createAddHookMessageChannel();
|
|
2772
|
+
return { data: { ...registerOptions.data, exclude: ESM_HOOK_EXCLUDE }, transferList: registerOptions.transferList };
|
|
2773
|
+
}
|
|
2213
2774
|
} catch {
|
|
2214
2775
|
}
|
|
2776
|
+
return { data: { exclude: ESM_HOOK_EXCLUDE } };
|
|
2215
2777
|
}
|
|
2216
2778
|
function switchOn(option, variable, fallback) {
|
|
2217
2779
|
if (typeof option === "boolean") return option;
|