@webority/server-timing 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 +4 -0
- package/dist/chunk-FI5VOB3J.js +1 -0
- package/dist/core.d.ts +1 -0
- package/dist/index.js +1 -1
- package/dist/register.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-NUJXVMFQ.js +0 -1
package/README.md
CHANGED
|
@@ -60,6 +60,10 @@ Keep the token itself in the product's secret store. The server holds only the f
|
|
|
60
60
|
|
|
61
61
|
Calls made with `fetch` (Node's built-in undici), `node:http` or `https` are covered, and axios sends its calls through `node:http`. A call to a host in `WEBORITY_TIMING_FORWARD_HOSTS` carries the token and `traceparent` on that hop only; a redirect to any other host drops both.
|
|
62
62
|
|
|
63
|
+
## Cross-origin pages
|
|
64
|
+
|
|
65
|
+
An authorised response to a request that carries an `Origin` header also carries `Timing-Allow-Origin` with that origin, so a browser on another origin can read the `Server-Timing` entries. Example: a request from `https://app.example.com` with the token gets `Timing-Allow-Origin: https://app.example.com`. An unauthorised response never carries it.
|
|
66
|
+
|
|
63
67
|
## Cache bypass
|
|
64
68
|
|
|
65
69
|
A cache in front of the server must not serve or store an authorised response. In nginx, bypass the cache on the token header:
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHash as V,timingSafeEqual as X}from"node:crypto";var Y=/^[0-9a-f]{64}$/,Q=/^[a-z][a-z0-9-]{0,19}$/,Z=/^[a-z0-9][a-z0-9.-]*$/,J=/^(?:\d+(?:\.\d+)?|\.\d+)$/,ee=40,te=2048,ne=500,A="private, no-store",re=new Set(["server-timing","traceparent","traceresponse","timing-allow-origin"]);function b(e){return{ok:!1,setting:e}}function p(e){return Math.round(Math.round(e*1e9)/1e9*10)/10}var f=e=>e!=null;function $(e){let n=f(e.busyMs)?e.busyMs:(e.dbMs??0)+(e.cacheMs??0)+(e.extMs??0)+(e.renderMs??0);return Math.max(0,e.totalMs-n)}var se=/'(?:[^'\\]|\\.|'')*'/g,oe=/"(?:[^"\\]|\\.)*"/g,ie=/(?<![A-Za-z0-9_$])-?(?:0x[0-9A-Fa-f]+|\d+(?:\.\d+)?)(?![A-Za-z0-9_])/g,ae=/\b(IN)(\s*)\(\s*\?(?:\s*,\s*\?)*\s*\)/gi;function S(e){return e.replace(se,"?").replace(oe,"?").replace(ie,"?").replace(ae,"$1$2(?)")}function Je(e){let n="WEBORITY_TIMING_TOKEN_SHA256",t=(e[n]??"").split(",");if(t.length>2||!t.every(c=>Y.test(c)))return b(n);let r=e.WEBORITY_TIMING_SERVICE??"";if(!Q.test(r))return b("WEBORITY_TIMING_SERVICE");let s="WEBORITY_TIMING_FORWARD_HOSTS",o=e[s],i;if(o==="none")i=[];else if(i=(o??"").split(",").map(c=>c.trim().toLowerCase()),!i.every(c=>Z.test(c)))return b(s);let a=e.APPLICATIONINSIGHTS_CONNECTION_STRING??"";if(a.trim()==="")return b("APPLICATIONINSIGHTS_CONNECTION_STRING");let u="WEBORITY_TRACE_SAMPLE_RATIO",d=e[u]??"";if(!J.test(d)||Number(d)>1)return b(u);let m={tokenFingerprints:t,service:r,forwardHosts:i,sampleRatio:Number(d),connectionString:a};return Object.defineProperty(m,"connectionString",{value:a,enumerable:!1,writable:!1,configurable:!1}),{ok:!0,config:m}}function v(e,n){if(!n)return!1;let t=Buffer.from(V("sha256").update(n,"utf8").digest("hex"));return e.some(r=>{let s=Buffer.from(r);return s.length===t.length&&X(s,t)})}function O(e,n){return!e||!n?null:n}function w(e,n,t){return(t??[]).slice(0,3).map((r,s)=>`${e}.${n}${s+1};dur=${p(r.ms)};desc="${r.desc}"`)}function q(e,n){let t=n,r=[`${e}.total;dur=${p(t.totalMs)}`,`${e}.app;dur=${p($(t))}`,`${e}.db;dur=${p(t.dbMs??0)};desc="${t.dbCount??0} queries"`,...w(e,"db",t.dbTop)];if(f(t.cacheMs)){let o=t.cacheResult?`;desc="${t.cacheResult}"`:"";r.push(`${e}.cache;dur=${p(t.cacheMs)}${o}`)}r.push(`${e}.ext;dur=${p(t.extMs??0)};desc="${t.extCount??0} calls"`,...w(e,"ext",t.extTop),`${e}.render;dur=${p(t.renderMs??0)}`,...w(e,"render",t.renderTop)),f(t.preMs)&&r.push(`${e}.pre;dur=${p(t.preMs)}`),f(t.endpointMs)&&r.push(`${e}.endpoint;dur=${p(t.endpointMs)}`),t.queueMs!==void 0&&r.push(`${e}.queue;dur=${p(t.queueMs)}`),t.bootMs!==void 0&&r.push(`${e}.boot;dur=${p(t.bootMs)}`),t.pluginsMs!==void 0&&r.push(`${e}.plugins;dur=${p(t.pluginsMs)};desc="${t.pluginCount} plugins"`);let s=Object.entries(t.runtime??{}).sort(([o],[i])=>o<i?-1:o>i?1:0);if(s.length>0){let o=s.map(([i,a])=>`${i}=${p(a)}`).join(" ");r.push(`${e}.runtime;desc="${o}"`)}return r.push(`trace;desc="${t.traceId}"`),r.join(", ")}function L(e){let n=new Map,t=null;for(let o of e){let i=S(o.sql);n.set(i,(n.get(i)??0)+1),f(o.rows)&&(t===null||o.rows>t)&&(t=o.rows)}let r=0,s=null;for(let[o,i]of n)i>r&&(r=i,s=o);return{dbCount:e.length,dbRepeatMax:r,dbRepeatSql:s===null?null:s.slice(0,ne),dbRowsMax:t}}function ue(e,n){return e||n>=1||n<=0?1:Math.round(1e4/n)/1e4}function P(e,n,t){let r=e,s={"webority.timing.authorised":n,"webority.sample_rate":ue(n,t),"webority.timing.total_ms":p(r.totalMs),"webority.timing.app_ms":p($(r))},o={db_ms:r.dbMs,cache_ms:r.cacheMs,ext_ms:r.extMs,render_ms:r.renderMs,queue_ms:r.queueMs,boot_ms:r.bootMs,plugins_ms:r.pluginsMs};for(let[a,u]of Object.entries(o))f(u)&&(s[`webority.timing.${a}`]=p(u));let i={db_count:r.dbCount,ext_count:r.extCount,plugin_count:r.pluginCount,db_repeat_max:r.dbRepeatMax,db_repeat_sql:r.dbRepeatSql,db_rows_max:r.dbRowsMax,cache_result:r.cacheResult};for(let[a,u]of Object.entries(i))f(u)&&(s[`webority.timing.${a}`]=u);f(r.memPeakKb)&&(s["webority.mem.peak_kb"]=r.memPeakKb),f(r.cpuMs)&&(s["webority.cpu_ms"]=p(r.cpuMs));for(let[a,u]of Object.entries(r.runtime??{}))s[`webority.runtime.${a}`]=p(u);return s}function N(e){let n=[],t="",r=!1;for(let s of e)s==='"'&&(r=!r),s===","&&!r?(n.push(t.trim()),t=""):t+=s;return n.push(t.trim()),n.filter(s=>s.length>0)}var T=e=>e.startsWith("trace;");function D(e,n){let t=N(e),r=t.filter(T),s=t.filter(u=>!T(u)),o=n.flatMap(N).filter(u=>!T(u)),i=()=>[...s,...o,...r],a=i();for(;o.length>0&&(a.length>ee||a.join(", ").length>te);)o.pop(),a=i();return a.join(", ")}function G(e,n,t){if(!n||!t)return!1;let r=String(t).toLowerCase().replace(/:\d+$/,"");return e.includes(r)}function B(e,n){if(!n)return e.filter(([s])=>!re.has(s.toLowerCase()));let t=[],r=!1;for(let[s,o]of e)s.toLowerCase()!=="cache-control"?t.push([s,o]):r||(t.push(["Cache-Control",A]),r=!0);return r||t.push(["Cache-Control",A]),t}import{createRequire as pe,syncBuiltinESMExports as ce}from"node:module";import{NodeSDK as me}from"@opentelemetry/sdk-node";import{BatchSpanProcessor as fe,TraceIdRatioBasedSampler as le,SamplingDecision as ge}from"@opentelemetry/sdk-trace-base";import{resourceFromAttributes as be}from"@opentelemetry/resources";import{ATTR_SERVICE_NAME as he}from"@opentelemetry/semantic-conventions";import{SpanKind as W,trace as Re}from"@opentelemetry/api";import{ClientRequest as z,IncomingMessage as Se}from"node:http";import{HttpInstrumentation as Me}from"@opentelemetry/instrumentation-http";import{MongoDBInstrumentation as we}from"@opentelemetry/instrumentation-mongodb";import{IORedisInstrumentation as Te}from"@opentelemetry/instrumentation-ioredis";import{RedisInstrumentation as xe}from"@opentelemetry/instrumentation-redis";import{MySQL2Instrumentation as ye}from"@opentelemetry/instrumentation-mysql2";import{PgInstrumentation as Ce}from"@opentelemetry/instrumentation-pg";import{UndiciInstrumentation as _e}from"@opentelemetry/instrumentation-undici";import{AzureMonitorTraceExporter as Ee}from"@azure/monitor-opentelemetry-exporter";import{AsyncLocalStorage as de}from"node:async_hooks";var h=new de,g=()=>h.getStore();var F="Webority-Timing-Token",He=/^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,y=["db.statement","db.query.text"],Ie="db.response.returned_rows",x=500,j=new WeakMap,l=([e,n])=>e*1e3+n/1e6,C=class{inject(){}extract(n,t,r){let s=r.get(t,"traceparent"),o=Array.isArray(s)?s[0]:s,i=typeof o=="string"?He.exec(o):null;if(!i)return n;let[,a,u,d]=i;return a===void 0||u===void 0||d===void 0||!/[1-9a-f]/.test(a)||!/[1-9a-f]/.test(u)?n:Re.setSpanContext(n,{traceId:a,spanId:u,traceFlags:parseInt(d,16),isRemote:!0})}fields(){return["traceparent"]}},_=class{attributes;span;constructor(n,t){this.span=n,this.attributes=t}get name(){return this.span.name}get kind(){return this.span.kind}spanContext(){return this.span.spanContext()}get parentSpanContext(){return this.span.parentSpanContext}get startTime(){return this.span.startTime}get endTime(){return this.span.endTime}get status(){return this.span.status}get links(){return this.span.links}get events(){return this.span.events}get duration(){return this.span.duration}get ended(){return this.span.ended}get resource(){return this.span.resource}get instrumentationScope(){return this.span.instrumentationScope}get droppedAttributesCount(){return this.span.droppedAttributesCount}get droppedEventsCount(){return this.span.droppedEventsCount}get droppedLinksCount(){return this.span.droppedLinksCount}};function ke(e){if(!y.some(t=>typeof e.attributes[t]=="string"))return e;let n={...e.attributes};for(let t of y){let r=n[t];typeof r=="string"&&(n[t]=S(r))}return new _(e,n)}function Ae(e){for(let n of y){let t=e.attributes[n];if(typeof t=="string")return t}return e.name}var E=class{constructor(n){this.inner=n}export(n,t){this.inner.export(n.map(ke),t)}shutdown(){return this.inner.shutdown()}forceFlush(){return this.inner.forceFlush?.()??Promise.resolve()}},H=class{onStart(n){let t=h.getStore();t&&(n.kind===W.SERVER&&!t.serverSpan&&(t.serverSpan=n,n.setAttribute("webority.timing.authorised",t.authorised)),j.set(n,t))}onEnd(n){let t=j.get(n);if(!t)return;let r=n.instrumentationScope.name;if(r.includes("mongodb")||r.includes("mysql2")||r.includes("pg")){t.dbMs+=l(n.duration),t.intervals.length<x&&t.intervals.push([l(n.startTime),l(n.endTime)]);let s={sql:S(Ae(n))},o=n.attributes[Ie];typeof o=="number"&&(s.rows=o),t.statements.push(s)}else r.includes("ioredis")||r.includes("redis")?(t.cacheMs+=l(n.duration),t.cacheCount+=1,t.intervals.length<x&&t.intervals.push([l(n.startTime),l(n.endTime)])):n.kind===W.CLIENT&&(r.includes("instrumentation-http")||r.includes("instrumentation-undici"))&&(t.extMs+=l(n.duration),t.extCount+=1,t.intervals.length<x&&t.intervals.push([l(n.startTime),l(n.endTime)]))}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}};function Ne(e){let n=new le(e);return{shouldSample(t,r,s,o,i,a){return g()?.authorised?{decision:ge.RECORD_AND_SAMPLED}:n.shouldSample(t,r,s,o,i,a)},toString(){return"WeborityTimingSampler"}}}function $e(e){return e instanceof Se&&(!("req"in e)||e.req===void 0||e.req instanceof z)}function U(e){let{traceId:n,spanId:t,traceFlags:r}=e.spanContext();return`00-${n}-${t}-${r.toString(16).padStart(2,"0")}`}function Mt(e){let n=s=>G(e.forwardHosts,!!g()?.authorised,s),t=new me({resource:be({[he]:e.service}),sampler:Ne(e.sampleRatio),spanProcessors:[new fe(new E(new Ee({connectionString:e.connectionString}))),new H],textMapPropagator:new C,instrumentations:[new Me({requestHook(s,o){let i=g()?.token;!(o instanceof z)||i===void 0||!n(o.host)||(o.setHeader(F,i),o.setHeader("traceparent",U(s)))},responseHook(s,o){let i=g();if(!$e(o))return;let a=o.headers["server-timing"];a&&i&&n(o.req?.host)&&i.inner.push(String(a))}}),new _e({requestHook(s,o){let i=g()?.token;i===void 0||!n(new URL(o.origin).hostname)||(o.addHeader(F,i),o.addHeader("traceparent",U(s)))},responseHook(s,{request:o,response:i}){let a=g();if(!a||!n(new URL(o.origin).hostname))return;let u=i.headers;for(let d=0;d+1<u.length;d+=2){let m=u[d],c=u[d+1];m&&c&&m.toString("latin1").toLowerCase()==="server-timing"&&a.inner.push(c.toString("latin1"))}}}),new we({enhancedDatabaseReporting:!1}),new Te,new xe,new ye,new Ce({enhancedDatabaseReporting:!1})]});t.start();let r=pe(import.meta.url);return r("node:http"),r("node:https"),ce(),t}import k from"node:http";import ve from"node:https";import{getHeapStatistics as Oe}from"node:v8";import{monitorEventLoopDelay as qe}from"node:perf_hooks";var I=1024*1024,Le=6e4,Pe=/^t=(\d+\.\d+)$/,De=/^t=(\d+)$/,M;function Ge(e,n){if(typeof e!="string")return;let t=Pe.exec(e),r=De.exec(e),s;if(t)s=Number(t[1])*1e3;else if(r)s=Number(r[1])/1e3;else return;let o=n-s;return o<0||o>Le?void 0:o}function Be(e,n,t){let r={authorised:e,queueMs:t,startNs:process.hrtime.bigint(),dbMs:0,cacheMs:0,cacheCount:0,extMs:0,extCount:0,statements:[],intervals:[],inner:[],serverSpan:void 0};return e&&Object.defineProperty(r,"token",{value:n,enumerable:!1}),r}function We(){let e=Oe();if(M===void 0)throw new TypeError("Webority server timing: the event loop monitor is not installed");return{eventloop_p99_ms:M.percentile(99)/1e6,heap_used_mb:e.used_heap_size/I,heap_limit_mb:e.heap_size_limit/I,rss_mb:process.memoryUsage.rss()/I}}function Fe(e){let n=0,t=-1/0;for(let[r,s]of[...e].sort((o,i)=>o[0]-i[0])){let o=Math.max(r,t);s>o&&(n+=s-o),t=Math.max(t,s)}return n}function je(e,n){let t=L(e.statements);return{totalMs:Number(process.hrtime.bigint()-e.startNs)/1e6,dbMs:e.dbMs,dbCount:t.dbCount,dbRepeatMax:t.dbRepeatMax,dbRepeatSql:t.dbRepeatSql,dbRowsMax:t.dbRowsMax,cacheMs:e.cacheCount>0?e.cacheMs:void 0,extMs:e.extMs,extCount:e.extCount,busyMs:e.intervals.length>0?Fe(e.intervals):void 0,queueMs:e.queueMs,runtime:We(),traceId:n}}function Ue(e){let n=e.route?.path;return typeof n=="string"?`${e.baseUrl??""}${n}`:void 0}function ze(e){let n=[];for(let t=0;t<e.length;t+=2)n.push([String(e[t]),e[t+1]]);return n}function Ke(e,n){let t=e.getRawHeaderNames().map(o=>[o,e.getHeader(o)]);if(!n)return t;let r=Array.isArray(n)?ze(n):Object.entries(n),s=new Set(r.map(([o])=>o.toLowerCase()));return[...t.filter(([o])=>!s.has(o.toLowerCase())),...r]}function K(e,n){if(n===void 0)throw new TypeError(`Webority server timing: header ${e} has no value`);return n}function Ve(e,n){let t=new Map;for(let[r,s]of n){let o=r.toLowerCase(),i=t.get(o)??{name:r,values:[]};i.values.push(...Array.isArray(s)?s:[s]),t.set(o,i)}for(let r of e.getRawHeaderNames())e.removeHeader(r);for(let{name:r,values:s}of t.values())s.length===1?e.setHeader(r,K(r,s[0])):e.setHeader(r,s.map(o=>String(K(r,o))))}function Xe(e,n,t,r){let s=n.serverSpan;if(!s){if(n.authorised)throw new Error("Webority server timing: an authorised request has no server span");return r}let o=je(n,s.spanContext().traceId),i=Ue(e),a=e.method;if(a===void 0)throw new TypeError("Webority server timing: a request has no method");if(s.updateName(i===void 0?a:`${a} ${i}`),s.setAttribute("http.route",i??"unmatched"),s.setAttributes(P(o,n.authorised,t.sampleRatio)),!n.authorised)return r;let u=D(q(t.service,o),n.inner),d=O(n.authorised,e.headers.origin),c=[...r.filter(([R])=>!["server-timing","timing-allow-origin"].includes(R.toLowerCase())),["Server-Timing",u]];return d!==null&&c.push(["Timing-Allow-Origin",d]),c}function Ye(e){return e instanceof k.ServerResponse&&"getRawHeaderNames"in e&&typeof e.getRawHeaderNames=="function"}function Qe(e,n,t,r){let s=n.writeHead;n.writeHead=function(o,...i){let[a,u]=i,d=typeof a=="string"?a:void 0,m=typeof a=="string"?u:a;if(n.headersSent)return s.call(this,o,d,m);let c=B(Ke(n,m),t.authorised);return o>=200&&(c=Xe(e,t,r,c)),Ve(n,c),s.call(this,o,d)}}function Ht(e){if(M)return;let n=qe({resolution:20});M=n,n.enable(),setInterval(()=>n.reset(),1e4).unref();for(let t of[k.Server,ve.Server]){let r=t.prototype.emit;t.prototype.emit=function(o,...i){if(o!=="request")return r.call(this,o,...i);let[a,u]=i;if(!(a instanceof k.IncomingMessage)||!Ye(u))throw new TypeError("Webority server timing: a request event carries no request and response");let d=a.headers["webority-timing-token"],m=typeof d=="string"?d:void 0,c=v(e.tokenFingerprints,m),R=Be(c,m,Ge(a.headers["x-request-start"],Date.now()));return Qe(a,u,R,e),h.run(R,()=>r.call(this,o,...i))}}}export{S as a,Je as b,v as c,q as d,D as e,G as f,B as g,Mt as h,Ht as i};
|
package/dist/core.d.ts
CHANGED
|
@@ -52,6 +52,7 @@ export type Header = [string, OutgoingHttpHeader | undefined];
|
|
|
52
52
|
export declare function maskSql(statement: string): string;
|
|
53
53
|
export declare function readConfig(env: NodeJS.ProcessEnv): ConfigResult;
|
|
54
54
|
export declare function authorise(tokenFingerprints: string[], token: string | undefined): boolean;
|
|
55
|
+
export declare function timingAllowOrigin(authorised: boolean, origin: string | undefined): string | null;
|
|
55
56
|
export declare function format(service: string, measurements: Measurements): string;
|
|
56
57
|
export declare function summariseStatements(statements: Statement[]): {
|
|
57
58
|
dbCount: number;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as r,b as o,c as e,d as t,e as a,f as s,g as m,h as f,i as p}from"./chunk-
|
|
1
|
+
import{a as r,b as o,c as e,d as t,e as a,f as s,g as m,h as f,i as p}from"./chunk-FI5VOB3J.js";export{e as authorise,t as format,p as installHttpHook,r as maskSql,a as merge,o as readConfig,m as scrubResponseHeaders,s as shouldForward,f as startTracing};
|
package/dist/register.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as i,h as o,i as t}from"./chunk-
|
|
1
|
+
import{b as i,h as o,i as t}from"./chunk-FI5VOB3J.js";var r=i(process.env);if(!r.ok)throw new Error(`Webority server timing: ${r.setting} is missing or invalid`);o(r.config);t(r.config);
|
package/package.json
CHANGED
package/dist/chunk-NUJXVMFQ.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{createHash as K,timingSafeEqual as V}from"node:crypto";var X=/^[0-9a-f]{64}$/,Y=/^[a-z][a-z0-9-]{0,19}$/,Q=/^[a-z0-9][a-z0-9.-]*$/,Z=/^(?:\d+(?:\.\d+)?|\.\d+)$/,J=40,ee=2048,te=500,N="private, no-store",ne=new Set(["server-timing","traceparent","traceresponse"]);function b(e){return{ok:!1,setting:e}}function p(e){return Math.round(Math.round(e*1e9)/1e9*10)/10}var f=e=>e!=null;function A(e){let n=f(e.busyMs)?e.busyMs:(e.dbMs??0)+(e.cacheMs??0)+(e.extMs??0)+(e.renderMs??0);return Math.max(0,e.totalMs-n)}var re=/'(?:[^'\\]|\\.|'')*'/g,se=/"(?:[^"\\]|\\.)*"/g,oe=/(?<![A-Za-z0-9_$])-?(?:0x[0-9A-Fa-f]+|\d+(?:\.\d+)?)(?![A-Za-z0-9_])/g,ie=/\b(IN)(\s*)\(\s*\?(?:\s*,\s*\?)*\s*\)/gi;function R(e){return e.replace(re,"?").replace(se,"?").replace(oe,"?").replace(ie,"$1$2(?)")}function Ze(e){let n="WEBORITY_TIMING_TOKEN_SHA256",t=(e[n]??"").split(",");if(t.length>2||!t.every(c=>X.test(c)))return b(n);let r=e.WEBORITY_TIMING_SERVICE??"";if(!Y.test(r))return b("WEBORITY_TIMING_SERVICE");let s="WEBORITY_TIMING_FORWARD_HOSTS",o=e[s],i;if(o==="none")i=[];else if(i=(o??"").split(",").map(c=>c.trim().toLowerCase()),!i.every(c=>Q.test(c)))return b(s);let a=e.APPLICATIONINSIGHTS_CONNECTION_STRING??"";if(a.trim()==="")return b("APPLICATIONINSIGHTS_CONNECTION_STRING");let u="WEBORITY_TRACE_SAMPLE_RATIO",d=e[u]??"";if(!Z.test(d)||Number(d)>1)return b(u);let m={tokenFingerprints:t,service:r,forwardHosts:i,sampleRatio:Number(d),connectionString:a};return Object.defineProperty(m,"connectionString",{value:a,enumerable:!1,writable:!1,configurable:!1}),{ok:!0,config:m}}function v(e,n){if(!n)return!1;let t=Buffer.from(K("sha256").update(n,"utf8").digest("hex"));return e.some(r=>{let s=Buffer.from(r);return s.length===t.length&&V(s,t)})}function M(e,n,t){return(t??[]).slice(0,3).map((r,s)=>`${e}.${n}${s+1};dur=${p(r.ms)};desc="${r.desc}"`)}function O(e,n){let t=n,r=[`${e}.total;dur=${p(t.totalMs)}`,`${e}.app;dur=${p(A(t))}`,`${e}.db;dur=${p(t.dbMs??0)};desc="${t.dbCount??0} queries"`,...M(e,"db",t.dbTop)];if(f(t.cacheMs)){let o=t.cacheResult?`;desc="${t.cacheResult}"`:"";r.push(`${e}.cache;dur=${p(t.cacheMs)}${o}`)}r.push(`${e}.ext;dur=${p(t.extMs??0)};desc="${t.extCount??0} calls"`,...M(e,"ext",t.extTop),`${e}.render;dur=${p(t.renderMs??0)}`,...M(e,"render",t.renderTop)),f(t.preMs)&&r.push(`${e}.pre;dur=${p(t.preMs)}`),f(t.endpointMs)&&r.push(`${e}.endpoint;dur=${p(t.endpointMs)}`),t.queueMs!==void 0&&r.push(`${e}.queue;dur=${p(t.queueMs)}`),t.bootMs!==void 0&&r.push(`${e}.boot;dur=${p(t.bootMs)}`),t.pluginsMs!==void 0&&r.push(`${e}.plugins;dur=${p(t.pluginsMs)};desc="${t.pluginCount} plugins"`);let s=Object.entries(t.runtime??{}).sort(([o],[i])=>o<i?-1:o>i?1:0);if(s.length>0){let o=s.map(([i,a])=>`${i}=${p(a)}`).join(" ");r.push(`${e}.runtime;desc="${o}"`)}return r.push(`trace;desc="${t.traceId}"`),r.join(", ")}function q(e){let n=new Map,t=null;for(let o of e){let i=R(o.sql);n.set(i,(n.get(i)??0)+1),f(o.rows)&&(t===null||o.rows>t)&&(t=o.rows)}let r=0,s=null;for(let[o,i]of n)i>r&&(r=i,s=o);return{dbCount:e.length,dbRepeatMax:r,dbRepeatSql:s===null?null:s.slice(0,te),dbRowsMax:t}}function ae(e,n){return e||n>=1||n<=0?1:Math.round(1e4/n)/1e4}function L(e,n,t){let r=e,s={"webority.timing.authorised":n,"webority.sample_rate":ae(n,t),"webority.timing.total_ms":p(r.totalMs),"webority.timing.app_ms":p(A(r))},o={db_ms:r.dbMs,cache_ms:r.cacheMs,ext_ms:r.extMs,render_ms:r.renderMs,queue_ms:r.queueMs,boot_ms:r.bootMs,plugins_ms:r.pluginsMs};for(let[a,u]of Object.entries(o))f(u)&&(s[`webority.timing.${a}`]=p(u));let i={db_count:r.dbCount,ext_count:r.extCount,plugin_count:r.pluginCount,db_repeat_max:r.dbRepeatMax,db_repeat_sql:r.dbRepeatSql,db_rows_max:r.dbRowsMax,cache_result:r.cacheResult};for(let[a,u]of Object.entries(i))f(u)&&(s[`webority.timing.${a}`]=u);f(r.memPeakKb)&&(s["webority.mem.peak_kb"]=r.memPeakKb),f(r.cpuMs)&&(s["webority.cpu_ms"]=p(r.cpuMs));for(let[a,u]of Object.entries(r.runtime??{}))s[`webority.runtime.${a}`]=p(u);return s}function $(e){let n=[],t="",r=!1;for(let s of e)s==='"'&&(r=!r),s===","&&!r?(n.push(t.trim()),t=""):t+=s;return n.push(t.trim()),n.filter(s=>s.length>0)}var w=e=>e.startsWith("trace;");function P(e,n){let t=$(e),r=t.filter(w),s=t.filter(u=>!w(u)),o=n.flatMap($).filter(u=>!w(u)),i=()=>[...s,...o,...r],a=i();for(;o.length>0&&(a.length>J||a.join(", ").length>ee);)o.pop(),a=i();return a.join(", ")}function D(e,n,t){if(!n||!t)return!1;let r=String(t).toLowerCase().replace(/:\d+$/,"");return e.includes(r)}function G(e,n){if(!n)return e.filter(([s])=>!ne.has(s.toLowerCase()));let t=[],r=!1;for(let[s,o]of e)s.toLowerCase()!=="cache-control"?t.push([s,o]):r||(t.push(["Cache-Control",N]),r=!0);return r||t.push(["Cache-Control",N]),t}import{createRequire as de,syncBuiltinESMExports as pe}from"node:module";import{NodeSDK as ce}from"@opentelemetry/sdk-node";import{BatchSpanProcessor as me,TraceIdRatioBasedSampler as fe,SamplingDecision as le}from"@opentelemetry/sdk-trace-base";import{resourceFromAttributes as ge}from"@opentelemetry/resources";import{ATTR_SERVICE_NAME as be}from"@opentelemetry/semantic-conventions";import{SpanKind as B,trace as he}from"@opentelemetry/api";import{ClientRequest as U,IncomingMessage as Re}from"node:http";import{HttpInstrumentation as Se}from"@opentelemetry/instrumentation-http";import{MongoDBInstrumentation as Me}from"@opentelemetry/instrumentation-mongodb";import{IORedisInstrumentation as we}from"@opentelemetry/instrumentation-ioredis";import{RedisInstrumentation as Te}from"@opentelemetry/instrumentation-redis";import{MySQL2Instrumentation as xe}from"@opentelemetry/instrumentation-mysql2";import{PgInstrumentation as ye}from"@opentelemetry/instrumentation-pg";import{UndiciInstrumentation as Ce}from"@opentelemetry/instrumentation-undici";import{AzureMonitorTraceExporter as _e}from"@azure/monitor-opentelemetry-exporter";import{AsyncLocalStorage as ue}from"node:async_hooks";var h=new ue,g=()=>h.getStore();var W="Webority-Timing-Token",Ee=/^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,x=["db.statement","db.query.text"],He="db.response.returned_rows",T=500,F=new WeakMap,l=([e,n])=>e*1e3+n/1e6,y=class{inject(){}extract(n,t,r){let s=r.get(t,"traceparent"),o=Array.isArray(s)?s[0]:s,i=typeof o=="string"?Ee.exec(o):null;if(!i)return n;let[,a,u,d]=i;return a===void 0||u===void 0||d===void 0||!/[1-9a-f]/.test(a)||!/[1-9a-f]/.test(u)?n:he.setSpanContext(n,{traceId:a,spanId:u,traceFlags:parseInt(d,16),isRemote:!0})}fields(){return["traceparent"]}},C=class{attributes;span;constructor(n,t){this.span=n,this.attributes=t}get name(){return this.span.name}get kind(){return this.span.kind}spanContext(){return this.span.spanContext()}get parentSpanContext(){return this.span.parentSpanContext}get startTime(){return this.span.startTime}get endTime(){return this.span.endTime}get status(){return this.span.status}get links(){return this.span.links}get events(){return this.span.events}get duration(){return this.span.duration}get ended(){return this.span.ended}get resource(){return this.span.resource}get instrumentationScope(){return this.span.instrumentationScope}get droppedAttributesCount(){return this.span.droppedAttributesCount}get droppedEventsCount(){return this.span.droppedEventsCount}get droppedLinksCount(){return this.span.droppedLinksCount}};function Ie(e){if(!x.some(t=>typeof e.attributes[t]=="string"))return e;let n={...e.attributes};for(let t of x){let r=n[t];typeof r=="string"&&(n[t]=R(r))}return new C(e,n)}function ke(e){for(let n of x){let t=e.attributes[n];if(typeof t=="string")return t}return e.name}var _=class{constructor(n){this.inner=n}export(n,t){this.inner.export(n.map(Ie),t)}shutdown(){return this.inner.shutdown()}forceFlush(){return this.inner.forceFlush?.()??Promise.resolve()}},E=class{onStart(n){let t=h.getStore();t&&(n.kind===B.SERVER&&!t.serverSpan&&(t.serverSpan=n,n.setAttribute("webority.timing.authorised",t.authorised)),F.set(n,t))}onEnd(n){let t=F.get(n);if(!t)return;let r=n.instrumentationScope.name;if(r.includes("mongodb")||r.includes("mysql2")||r.includes("pg")){t.dbMs+=l(n.duration),t.intervals.length<T&&t.intervals.push([l(n.startTime),l(n.endTime)]);let s={sql:R(ke(n))},o=n.attributes[He];typeof o=="number"&&(s.rows=o),t.statements.push(s)}else r.includes("ioredis")||r.includes("redis")?(t.cacheMs+=l(n.duration),t.cacheCount+=1,t.intervals.length<T&&t.intervals.push([l(n.startTime),l(n.endTime)])):n.kind===B.CLIENT&&(r.includes("instrumentation-http")||r.includes("instrumentation-undici"))&&(t.extMs+=l(n.duration),t.extCount+=1,t.intervals.length<T&&t.intervals.push([l(n.startTime),l(n.endTime)]))}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}};function Ne(e){let n=new fe(e);return{shouldSample(t,r,s,o,i,a){return g()?.authorised?{decision:le.RECORD_AND_SAMPLED}:n.shouldSample(t,r,s,o,i,a)},toString(){return"WeborityTimingSampler"}}}function $e(e){return e instanceof Re&&(!("req"in e)||e.req===void 0||e.req instanceof U)}function j(e){let{traceId:n,spanId:t,traceFlags:r}=e.spanContext();return`00-${n}-${t}-${r.toString(16).padStart(2,"0")}`}function St(e){let n=s=>D(e.forwardHosts,!!g()?.authorised,s),t=new ce({resource:ge({[be]:e.service}),sampler:Ne(e.sampleRatio),spanProcessors:[new me(new _(new _e({connectionString:e.connectionString}))),new E],textMapPropagator:new y,instrumentations:[new Se({requestHook(s,o){let i=g()?.token;!(o instanceof U)||i===void 0||!n(o.host)||(o.setHeader(W,i),o.setHeader("traceparent",j(s)))},responseHook(s,o){let i=g();if(!$e(o))return;let a=o.headers["server-timing"];a&&i&&n(o.req?.host)&&i.inner.push(String(a))}}),new Ce({requestHook(s,o){let i=g()?.token;i===void 0||!n(new URL(o.origin).hostname)||(o.addHeader(W,i),o.addHeader("traceparent",j(s)))},responseHook(s,{request:o,response:i}){let a=g();if(!a||!n(new URL(o.origin).hostname))return;let u=i.headers;for(let d=0;d+1<u.length;d+=2){let m=u[d],c=u[d+1];m&&c&&m.toString("latin1").toLowerCase()==="server-timing"&&a.inner.push(c.toString("latin1"))}}}),new Me({enhancedDatabaseReporting:!1}),new we,new Te,new xe,new ye({enhancedDatabaseReporting:!1})]});t.start();let r=de(import.meta.url);return r("node:http"),r("node:https"),pe(),t}import I from"node:http";import Ae from"node:https";import{getHeapStatistics as ve}from"node:v8";import{monitorEventLoopDelay as Oe}from"node:perf_hooks";var H=1024*1024,qe=6e4,Le=/^t=(\d+\.\d+)$/,Pe=/^t=(\d+)$/,S;function De(e,n){if(typeof e!="string")return;let t=Le.exec(e),r=Pe.exec(e),s;if(t)s=Number(t[1])*1e3;else if(r)s=Number(r[1])/1e3;else return;let o=n-s;return o<0||o>qe?void 0:o}function Ge(e,n,t){let r={authorised:e,queueMs:t,startNs:process.hrtime.bigint(),dbMs:0,cacheMs:0,cacheCount:0,extMs:0,extCount:0,statements:[],intervals:[],inner:[],serverSpan:void 0};return e&&Object.defineProperty(r,"token",{value:n,enumerable:!1}),r}function Be(){let e=ve();if(S===void 0)throw new TypeError("Webority server timing: the event loop monitor is not installed");return{eventloop_p99_ms:S.percentile(99)/1e6,heap_used_mb:e.used_heap_size/H,heap_limit_mb:e.heap_size_limit/H,rss_mb:process.memoryUsage.rss()/H}}function We(e){let n=0,t=-1/0;for(let[r,s]of[...e].sort((o,i)=>o[0]-i[0])){let o=Math.max(r,t);s>o&&(n+=s-o),t=Math.max(t,s)}return n}function Fe(e,n){let t=q(e.statements);return{totalMs:Number(process.hrtime.bigint()-e.startNs)/1e6,dbMs:e.dbMs,dbCount:t.dbCount,dbRepeatMax:t.dbRepeatMax,dbRepeatSql:t.dbRepeatSql,dbRowsMax:t.dbRowsMax,cacheMs:e.cacheCount>0?e.cacheMs:void 0,extMs:e.extMs,extCount:e.extCount,busyMs:e.intervals.length>0?We(e.intervals):void 0,queueMs:e.queueMs,runtime:Be(),traceId:n}}function je(e){let n=e.route?.path;return typeof n=="string"?`${e.baseUrl??""}${n}`:void 0}function Ue(e){let n=[];for(let t=0;t<e.length;t+=2)n.push([String(e[t]),e[t+1]]);return n}function ze(e,n){let t=e.getRawHeaderNames().map(o=>[o,e.getHeader(o)]);if(!n)return t;let r=Array.isArray(n)?Ue(n):Object.entries(n),s=new Set(r.map(([o])=>o.toLowerCase()));return[...t.filter(([o])=>!s.has(o.toLowerCase())),...r]}function z(e,n){if(n===void 0)throw new TypeError(`Webority server timing: header ${e} has no value`);return n}function Ke(e,n){let t=new Map;for(let[r,s]of n){let o=r.toLowerCase(),i=t.get(o)??{name:r,values:[]};i.values.push(...Array.isArray(s)?s:[s]),t.set(o,i)}for(let r of e.getRawHeaderNames())e.removeHeader(r);for(let{name:r,values:s}of t.values())s.length===1?e.setHeader(r,z(r,s[0])):e.setHeader(r,s.map(o=>String(z(r,o))))}function Ve(e,n,t,r){let s=n.serverSpan;if(!s){if(n.authorised)throw new Error("Webority server timing: an authorised request has no server span");return r}let o=Fe(n,s.spanContext().traceId),i=je(e),a=e.method;if(a===void 0)throw new TypeError("Webority server timing: a request has no method");if(s.updateName(i===void 0?a:`${a} ${i}`),s.setAttribute("http.route",i??"unmatched"),s.setAttributes(L(o,n.authorised,t.sampleRatio)),!n.authorised)return r;let u=P(O(t.service,o),n.inner);return[...r.filter(([d])=>d.toLowerCase()!=="server-timing"),["Server-Timing",u]]}function Xe(e){return e instanceof I.ServerResponse&&"getRawHeaderNames"in e&&typeof e.getRawHeaderNames=="function"}function Ye(e,n,t,r){let s=n.writeHead;n.writeHead=function(o,...i){let[a,u]=i,d=typeof a=="string"?a:void 0,m=typeof a=="string"?u:a;if(n.headersSent)return s.call(this,o,d,m);let c=G(ze(n,m),t.authorised);return o>=200&&(c=Ve(e,t,r,c)),Ke(n,c),s.call(this,o,d)}}function Et(e){if(S)return;let n=Oe({resolution:20});S=n,n.enable(),setInterval(()=>n.reset(),1e4).unref();for(let t of[I.Server,Ae.Server]){let r=t.prototype.emit;t.prototype.emit=function(o,...i){if(o!=="request")return r.call(this,o,...i);let[a,u]=i;if(!(a instanceof I.IncomingMessage)||!Xe(u))throw new TypeError("Webority server timing: a request event carries no request and response");let d=a.headers["webority-timing-token"],m=typeof d=="string"?d:void 0,c=v(e.tokenFingerprints,m),k=Ge(c,m,De(a.headers["x-request-start"],Date.now()));return Ye(a,u,k,e),h.run(k,()=>r.call(this,o,...i))}}}export{R as a,Ze as b,v as c,O as d,P as e,D as f,G as g,St as h,Et as i};
|