@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.js
CHANGED
|
@@ -43,6 +43,7 @@ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
|
|
|
43
43
|
|
|
44
44
|
// src/zharp.ts
|
|
45
45
|
var import_node_module = require("module");
|
|
46
|
+
var import_node_path2 = require("path");
|
|
46
47
|
var import_api5 = require("@opentelemetry/api");
|
|
47
48
|
var import_core = require("@opentelemetry/core");
|
|
48
49
|
var import_resources = require("@opentelemetry/resources");
|
|
@@ -680,6 +681,8 @@ function withBodyCapture(settings, config = {}) {
|
|
|
680
681
|
|
|
681
682
|
// src/headers.ts
|
|
682
683
|
var import_node_http2 = require("http");
|
|
684
|
+
|
|
685
|
+
// ../../internal/src/headers.ts
|
|
683
686
|
var SECRET = /* @__PURE__ */ new Set(["authorization", "proxy-authorization", "cookie", "set-cookie", "x-api-key", "x-auth-token", "x-csrf-token", "x-xsrf-token"]);
|
|
684
687
|
var MAX_HEADERS = 40;
|
|
685
688
|
var MAX_VALUE = 512;
|
|
@@ -695,8 +698,10 @@ function shown(name, value, settings) {
|
|
|
695
698
|
}
|
|
696
699
|
function headerAttributes(side, headers, settings) {
|
|
697
700
|
const out = {};
|
|
701
|
+
if (!headers) return out;
|
|
702
|
+
const entries = typeof headers[Symbol.iterator] === "function" ? [...headers] : Object.entries(headers);
|
|
698
703
|
let count = 0;
|
|
699
|
-
for (const [rawName, value] of
|
|
704
|
+
for (const [rawName, value] of entries) {
|
|
700
705
|
if (count >= MAX_HEADERS) break;
|
|
701
706
|
const name = rawName.toLowerCase();
|
|
702
707
|
const text = shown(name, value, settings);
|
|
@@ -706,6 +711,8 @@ function headerAttributes(side, headers, settings) {
|
|
|
706
711
|
}
|
|
707
712
|
return out;
|
|
708
713
|
}
|
|
714
|
+
|
|
715
|
+
// src/headers.ts
|
|
709
716
|
function withHeaderCapture(settings, config = {}) {
|
|
710
717
|
return {
|
|
711
718
|
...config,
|
|
@@ -730,7 +737,7 @@ var import_api = require("@opentelemetry/api");
|
|
|
730
737
|
var import_instrumentation = require("@opentelemetry/instrumentation");
|
|
731
738
|
|
|
732
739
|
// src/version.ts
|
|
733
|
-
var VERSION = "0.
|
|
740
|
+
var VERSION = "0.5.0";
|
|
734
741
|
|
|
735
742
|
// src/source.ts
|
|
736
743
|
var import_node_fs = require("fs");
|
|
@@ -1681,7 +1688,8 @@ function frameFile(line) {
|
|
|
1681
1688
|
match = /^(?:[^@]*@)?(.+?):\d+:\d+$/.exec(text);
|
|
1682
1689
|
return match ? clean(match[1]) : void 0;
|
|
1683
1690
|
}
|
|
1684
|
-
function clean(
|
|
1691
|
+
function clean(raw) {
|
|
1692
|
+
const file = raw.replace(/^address at /, "");
|
|
1685
1693
|
if (!file || file.includes("eval at ") || file === "<anonymous>" || file === "native") return void 0;
|
|
1686
1694
|
return file;
|
|
1687
1695
|
}
|
|
@@ -1812,6 +1820,273 @@ Caused by: ${cause.stack}`;
|
|
|
1812
1820
|
};
|
|
1813
1821
|
}
|
|
1814
1822
|
|
|
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
|
+
}
|
|
2089
|
+
|
|
1815
2090
|
// src/zharp.ts
|
|
1816
2091
|
var DEFAULT_ENDPOINT = "https://api.zharp.io/api/v1/otlp";
|
|
1817
2092
|
var EXIT_FLUSH_MS = 2e3;
|
|
@@ -1828,6 +2103,13 @@ var ZharpNode = class {
|
|
|
1828
2103
|
reported = /* @__PURE__ */ new WeakSet();
|
|
1829
2104
|
/** Failed queries waiting to be reported, once and with their call site. */
|
|
1830
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;
|
|
1831
2113
|
/** `Zharp.log.info("Order placed", { orderId })` — and debug, warn, error, fatal, trace. */
|
|
1832
2114
|
log = {
|
|
1833
2115
|
trace: (m, a) => this.emit("trace", m, a),
|
|
@@ -1867,7 +2149,7 @@ var ZharpNode = class {
|
|
|
1867
2149
|
warn("No key found \u2014 pass Zharp.init({ key }) or set ZHARP_API_KEY. Nothing will be sent.");
|
|
1868
2150
|
return;
|
|
1869
2151
|
}
|
|
1870
|
-
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";
|
|
1871
2153
|
const environment = pick(options.environment, nodeEnv("ZHARP_ENV"), nodeEnv("NODE_ENV"));
|
|
1872
2154
|
const release = pick(options.release, nodeEnv("ZHARP_RELEASE"), nodeEnv("ZHARP_VERSION"));
|
|
1873
2155
|
const endpoint = (pick(options.endpoint, nodeEnv("ZHARP_ENDPOINT")) ?? DEFAULT_ENDPOINT).replace(/\/+$/, "");
|
|
@@ -1913,17 +2195,20 @@ var ZharpNode = class {
|
|
|
1913
2195
|
"telemetry.sdk.language": "nodejs",
|
|
1914
2196
|
"telemetry.sdk.version": VERSION,
|
|
1915
2197
|
"process.runtime.name": "nodejs",
|
|
1916
|
-
"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()
|
|
1917
2201
|
});
|
|
1918
2202
|
const propagator = new import_core.CompositePropagator({
|
|
1919
2203
|
propagators: [new import_core.W3CTraceContextPropagator(), new import_core.W3CBaggagePropagator()]
|
|
1920
2204
|
});
|
|
1921
2205
|
const bodies = bodySettings(options.captureBodies, nodeEnv("ZHARP_CAPTURE_BODIES"));
|
|
1922
2206
|
const headerCapture = headerSettings(options.captureHeaders, nodeEnv("ZHARP_CAPTURE_HEADERS"));
|
|
1923
|
-
const ownHttp = options.instrumentations?.["@opentelemetry/instrumentation-http"];
|
|
2207
|
+
const ownHttp = this.withWrappedRequests(options.instrumentations?.["@opentelemetry/instrumentation-http"]);
|
|
1924
2208
|
const withBodies = bodies ? withBodyCapture(bodies, ownHttp) : ownHttp;
|
|
1925
2209
|
const httpConfig = headerCapture ? withHeaderCapture(headerCapture, withBodies) : withBodies;
|
|
1926
2210
|
const rate = typeof options.sampleRate === "number" ? Math.min(1, Math.max(0, options.sampleRate)) : 1;
|
|
2211
|
+
let instrumentations = [];
|
|
1927
2212
|
this.sdk = new import_sdk_node.NodeSDK({
|
|
1928
2213
|
resource,
|
|
1929
2214
|
// Host and OTEL_RESOURCE_ATTRIBUTES only. The process detector would send the command line,
|
|
@@ -1935,22 +2220,27 @@ var ZharpNode = class {
|
|
|
1935
2220
|
logRecordProcessors: this.logProcessors,
|
|
1936
2221
|
// Without this the SDK would start an OTLP metrics exporter pointed at localhost:4318.
|
|
1937
2222
|
metricReaders: [],
|
|
1938
|
-
instrumentations: [
|
|
2223
|
+
instrumentations: instrumentations = [
|
|
1939
2224
|
...tracing ? (0, import_auto_instrumentations_node.getNodeAutoInstrumentations)({
|
|
1940
2225
|
// A span per DNS lookup, socket and file read buries the requests that matter.
|
|
1941
2226
|
"@opentelemetry/instrumentation-dns": { enabled: false },
|
|
1942
2227
|
"@opentelemetry/instrumentation-net": { enabled: false },
|
|
1943
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 },
|
|
1944
2232
|
...options.instrumentations,
|
|
1945
2233
|
...bridges,
|
|
1946
2234
|
...httpConfig && { "@opentelemetry/instrumentation-http": httpConfig }
|
|
1947
|
-
}) : logsOnlyInstrumentations({ ...options, instrumentations: { ...options.instrumentations, ...bridges } }),
|
|
2235
|
+
}) : logsOnlyInstrumentations({ ...options, instrumentations: { ...options.instrumentations, ...bridges, "@opentelemetry/instrumentation-http": ownHttp } }),
|
|
1948
2236
|
...this.dbErrors ? [new DbDriverErrorsInstrumentation((traceId, error) => this.dbErrors?.attach(traceId, error))] : [],
|
|
1949
2237
|
...tracing && options.captureUncaught !== false ? [new FrameworkErrorsInstrumentation((error, mechanism) => this.report(error, false, "error", { "zharp.mechanism": mechanism }, true))] : [],
|
|
1950
2238
|
...options.extraInstrumentations ?? []
|
|
1951
2239
|
]
|
|
1952
2240
|
});
|
|
1953
2241
|
this.sdk.start();
|
|
2242
|
+
if (tracing) preloadCommonJsFrameworks();
|
|
2243
|
+
if (isBun()) patchWithoutHooks(instrumentations);
|
|
1954
2244
|
this.logger = import_api5.logs.getLogger("@zharp/node", VERSION);
|
|
1955
2245
|
if (correlation) this.teardowns.push(stampOutput());
|
|
1956
2246
|
if (sendLogs) {
|
|
@@ -2055,6 +2345,207 @@ var ZharpNode = class {
|
|
|
2055
2345
|
})));
|
|
2056
2346
|
await Promise.race([all, new Promise((resolve2) => setTimeout(resolve2, timeoutMs).unref())]);
|
|
2057
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;
|
|
2548
|
+
}
|
|
2058
2549
|
/** Flush, stop, and put back everything that was patched. */
|
|
2059
2550
|
async shutdown() {
|
|
2060
2551
|
const sdk = this.sdk;
|
|
@@ -2227,14 +2718,83 @@ function safeJson(value) {
|
|
|
2227
2718
|
return String(value);
|
|
2228
2719
|
}
|
|
2229
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
|
+
}
|
|
2230
2778
|
function registerEsmHook() {
|
|
2231
2779
|
const g2 = globalThis;
|
|
2232
2780
|
if (g2.__ZHARP_ESM_HOOK__) return;
|
|
2233
2781
|
g2.__ZHARP_ESM_HOOK__ = true;
|
|
2234
2782
|
try {
|
|
2235
|
-
(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
|
+
}
|
|
2236
2795
|
} catch {
|
|
2237
2796
|
}
|
|
2797
|
+
return { data: { exclude: ESM_HOOK_EXCLUDE } };
|
|
2238
2798
|
}
|
|
2239
2799
|
function switchOn(option, variable, fallback) {
|
|
2240
2800
|
if (typeof option === "boolean") return option;
|