@alwaysmeticulous/backend-recorder-workerd 2.324.0 → 2.326.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 +94 -4
- package/dist/binding-patch.js +17 -8
- package/dist/binding-patch.js.map +1 -1
- package/dist/capture-buffer.js +114 -0
- package/dist/capture-buffer.js.map +1 -0
- package/dist/context.js +6 -3
- package/dist/context.js.map +1 -1
- package/dist/error-capture.d.ts +44 -0
- package/dist/error-capture.js +65 -0
- package/dist/error-capture.js.map +1 -0
- package/dist/fetch-patch.js +5 -5
- package/dist/fetch-patch.js.map +1 -1
- package/dist/index.d.ts +63 -39
- package/dist/index.js +0 -0
- package/dist/index.js.map +1 -1
- package/dist/kv-capture.d.ts +39 -0
- package/dist/kv-capture.js +92 -0
- package/dist/kv-capture.js.map +1 -0
- package/dist/kv-patch.js +21 -94
- package/dist/kv-patch.js.map +1 -1
- package/dist/outbound-capture.js +20 -28
- package/dist/outbound-capture.js.map +1 -1
- package/dist/pages-function.d.ts +33 -0
- package/dist/pages-function.js +28 -0
- package/dist/pages-function.js.map +1 -0
- package/dist/postgres/capture.d.ts +108 -0
- package/dist/postgres/capture.js +136 -0
- package/dist/postgres/capture.js.map +1 -0
- package/dist/postgres/with-meticulous-postgres.d.ts +32 -0
- package/dist/postgres/with-meticulous-postgres.js +152 -0
- package/dist/postgres/with-meticulous-postgres.js.map +1 -0
- package/dist/protocol.d.ts +76 -11
- package/dist/protocol.js +12 -7
- package/dist/protocol.js.map +1 -1
- package/dist/provisional-session-id.d.ts +58 -0
- package/dist/provisional-session-id.js +75 -0
- package/dist/provisional-session-id.js.map +1 -0
- package/dist/publish-session-id.js +41 -0
- package/dist/publish-session-id.js.map +1 -0
- package/dist/replay-fetch.js +4 -3
- package/dist/replay-fetch.js.map +1 -1
- package/dist/sidecar-client.js +29 -18
- package/dist/sidecar-client.js.map +1 -1
- package/dist/sidecar-transport.d.ts +38 -0
- package/dist/sidecar-transport.js +52 -0
- package/dist/sidecar-transport.js.map +1 -0
- package/dist/spans/attributes.d.ts +84 -0
- package/dist/spans/attributes.js +88 -0
- package/dist/spans/attributes.js.map +1 -0
- package/dist/spans/readable-span.d.ts +78 -0
- package/dist/spans/readable-span.js +35 -0
- package/dist/spans/readable-span.js.map +1 -0
- package/dist/spans/serialize-span.d.ts +14 -0
- package/dist/spans/serialize-span.js +38 -0
- package/dist/spans/serialize-span.js.map +1 -0
- package/dist/spans/span-builder.d.ts +61 -0
- package/dist/spans/span-builder.js +250 -0
- package/dist/spans/span-builder.js.map +1 -0
- package/dist/spans/url-redaction.d.ts +14 -0
- package/dist/spans/url-redaction.js +40 -0
- package/dist/spans/url-redaction.js.map +1 -0
- package/dist/with-meticulous.d.ts +32 -0
- package/dist/with-meticulous.js +0 -0
- package/dist/with-meticulous.js.map +1 -0
- package/package.json +2 -1
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
|
|
2
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="7437e682-9879-55d9-aa51-34f2920d26d3")}catch(e){}}();
|
|
3
|
+
import { requestCaptureContext } from "../context.js";
|
|
4
|
+
import { warnOnce } from "../log.js";
|
|
5
|
+
import { MAX_POSTGRES_JS_RESULT_SIZE, isSupportedPostgresJsQuery, reconstructQueryText, resolveRowMode, serializePostgresJsArgs, serializePostgresJsError, serializePostgresJsResult } from "./capture.js";
|
|
6
|
+
//#region src/postgres/with-meticulous-postgres.ts
|
|
7
|
+
/**
|
|
8
|
+
* Records postgres.js queries a deployed Worker makes — typically over Hyperdrive, which is the
|
|
9
|
+
* only way a Worker reaches Postgres.
|
|
10
|
+
*
|
|
11
|
+
* There is no seam to patch automatically here. The Node recorder can hook Node's module loader
|
|
12
|
+
* to patch `postgres/{src,cjs/src,cf/src}/query.js`, but a Worker is a single bundle: `postgres`
|
|
13
|
+
* was inlined at build time and never passes through a loader. So the app hands us its client:
|
|
14
|
+
*
|
|
15
|
+
* const sql = withMeticulousPostgres(postgres(env.HYPERDRIVE.connectionString));
|
|
16
|
+
*
|
|
17
|
+
* Every postgres.js query funnels through one internal method, `Query.prototype.handle`, and this
|
|
18
|
+
* reaches that shared prototype *through the instance* — via a throwaway query, which is free
|
|
19
|
+
* because postgres.js queries are lazy and nothing executes until awaited. One call therefore also
|
|
20
|
+
* covers read-replica clients and any other client in the isolate.
|
|
21
|
+
*
|
|
22
|
+
* Apply it **outermost** if something else also wraps the client (Sentry's
|
|
23
|
+
* `instrumentPostgresJsSql`, a logging proxy): those wrappers return a proxy whose `handle` is
|
|
24
|
+
* still the shared prototype's, so ordering does not change what is captured — but keeping ours
|
|
25
|
+
* outermost matches the Node recorder's contract and stays correct if that ever changes.
|
|
26
|
+
*
|
|
27
|
+
* Record-only, deliberately. A Worker recording is replayed against the app running under Node,
|
|
28
|
+
* where `@alwaysmeticulous/backend-recorder-js` serves these queries from its own mock store —
|
|
29
|
+
* which is why the captured attributes here are exactly the ones that store reads. Outside a
|
|
30
|
+
* recorded request this is a complete pass-through, so it is safe to leave in deployed code.
|
|
31
|
+
*
|
|
32
|
+
* Returns the client unchanged; the patch is on the prototype.
|
|
33
|
+
*/
|
|
34
|
+
const withMeticulousPostgres = (sql) => {
|
|
35
|
+
try {
|
|
36
|
+
const prototype = findQueryPrototype(sql);
|
|
37
|
+
if (prototype === void 0) {
|
|
38
|
+
warnOnce("postgres-wrapper-unsupported", "withMeticulousPostgres could not reach postgres.js' Query prototype — queries will not be recorded.");
|
|
39
|
+
return sql;
|
|
40
|
+
}
|
|
41
|
+
patchHandle(prototype);
|
|
42
|
+
} catch (error) {
|
|
43
|
+
warnOnce("postgres-wrapper-failed", "withMeticulousPostgres failed — queries will not be recorded.", error);
|
|
44
|
+
}
|
|
45
|
+
return sql;
|
|
46
|
+
};
|
|
47
|
+
const HANDLE_PATCHED = Symbol.for("meticulous.workerd.postgresJsPatched");
|
|
48
|
+
/**
|
|
49
|
+
* The `Query` prototype, reached by building a query and reading its prototype.
|
|
50
|
+
*
|
|
51
|
+
* `sql.unsafe` is used rather than a tagged template because it takes the text as a plain
|
|
52
|
+
* argument: no interpolation, and postgres.js does not touch a connection until the query is
|
|
53
|
+
* awaited, which nothing here does. The query is discarded.
|
|
54
|
+
*/
|
|
55
|
+
const findQueryPrototype = (sql) => {
|
|
56
|
+
const unsafe = sql?.unsafe;
|
|
57
|
+
if (typeof unsafe !== "function") return;
|
|
58
|
+
const probe = unsafe.call(sql, "select 1");
|
|
59
|
+
if (probe === null || typeof probe !== "object") return;
|
|
60
|
+
const prototype = Object.getPrototypeOf(probe);
|
|
61
|
+
if (prototype === null) return;
|
|
62
|
+
const descriptor = Object.getOwnPropertyDescriptor(prototype, "handle");
|
|
63
|
+
return descriptor !== void 0 && typeof descriptor.value === "function" && descriptor.configurable === true ? prototype : void 0;
|
|
64
|
+
};
|
|
65
|
+
const patchHandle = (prototype) => {
|
|
66
|
+
const original = Object.getOwnPropertyDescriptor(prototype, "handle")?.value;
|
|
67
|
+
if (original === void 0 || original[HANDLE_PATCHED] === true) return;
|
|
68
|
+
const patched = function() {
|
|
69
|
+
if (this.executed || !isSupportedPostgresJsQuery(this)) return original.call(this);
|
|
70
|
+
const ctx = requestCaptureContext.getStore();
|
|
71
|
+
if (!ctx || ctx.mode !== "record") return original.call(this);
|
|
72
|
+
try {
|
|
73
|
+
captureQuery(ctx, this);
|
|
74
|
+
} catch (error) {
|
|
75
|
+
warnOnce("postgres-capture", "Failed to capture a postgres.js query.", error);
|
|
76
|
+
}
|
|
77
|
+
return original.call(this);
|
|
78
|
+
};
|
|
79
|
+
Object.defineProperty(patched, HANDLE_PATCHED, {
|
|
80
|
+
value: true,
|
|
81
|
+
enumerable: false,
|
|
82
|
+
configurable: true
|
|
83
|
+
});
|
|
84
|
+
Object.defineProperty(prototype, "handle", {
|
|
85
|
+
value: patched,
|
|
86
|
+
writable: true,
|
|
87
|
+
enumerable: false,
|
|
88
|
+
configurable: true
|
|
89
|
+
});
|
|
90
|
+
};
|
|
91
|
+
/**
|
|
92
|
+
* Wraps the query's own `resolve`/`reject` so the outcome is captured without the query being
|
|
93
|
+
* awaited here — the same trick the Node instrumentation uses, and the only place a query's input
|
|
94
|
+
* and its result are both visible.
|
|
95
|
+
*/
|
|
96
|
+
const captureQuery = (ctx, query) => {
|
|
97
|
+
const queryText = reconstructQueryText(query.strings);
|
|
98
|
+
if (queryText === void 0) return;
|
|
99
|
+
const startTimeMs = Date.now();
|
|
100
|
+
const base = {
|
|
101
|
+
kind: "postgres",
|
|
102
|
+
requestId: ctx.requestId,
|
|
103
|
+
...ctx.frontendSessionId !== void 0 ? { frontendSessionId: ctx.frontendSessionId } : {},
|
|
104
|
+
traceId: ctx.traceId,
|
|
105
|
+
serverSpanId: ctx.serverSpanId,
|
|
106
|
+
queryText,
|
|
107
|
+
params: serializePostgresJsArgs(query.args),
|
|
108
|
+
rowMode: resolveRowMode(query.isRaw),
|
|
109
|
+
startTimeMs
|
|
110
|
+
};
|
|
111
|
+
const report = (outcome) => {
|
|
112
|
+
try {
|
|
113
|
+
ctx.buffer.add({
|
|
114
|
+
...base,
|
|
115
|
+
...outcome,
|
|
116
|
+
endTimeMs: Date.now()
|
|
117
|
+
});
|
|
118
|
+
} catch (error) {
|
|
119
|
+
warnOnce("postgres-report", "Failed to report a postgres.js query.", error);
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
const originalResolve = query.resolve;
|
|
123
|
+
const originalReject = query.reject;
|
|
124
|
+
query.resolve = (result) => {
|
|
125
|
+
let json;
|
|
126
|
+
try {
|
|
127
|
+
json = serializePostgresJsResult(result);
|
|
128
|
+
} catch {
|
|
129
|
+
json = void 0;
|
|
130
|
+
}
|
|
131
|
+
report(json === void 0 ? {} : { result: {
|
|
132
|
+
body: json.length > 262144 ? json.slice(0, MAX_POSTGRES_JS_RESULT_SIZE) : json,
|
|
133
|
+
truncated: json.length > MAX_POSTGRES_JS_RESULT_SIZE
|
|
134
|
+
} });
|
|
135
|
+
return originalResolve.call(query, result);
|
|
136
|
+
};
|
|
137
|
+
query.reject = (error) => {
|
|
138
|
+
let errorJson;
|
|
139
|
+
try {
|
|
140
|
+
errorJson = serializePostgresJsError(error);
|
|
141
|
+
} catch {
|
|
142
|
+
errorJson = void 0;
|
|
143
|
+
}
|
|
144
|
+
report(errorJson === void 0 ? {} : { errorJson });
|
|
145
|
+
return originalReject.call(query, error);
|
|
146
|
+
};
|
|
147
|
+
};
|
|
148
|
+
//#endregion
|
|
149
|
+
export { withMeticulousPostgres };
|
|
150
|
+
|
|
151
|
+
//# sourceMappingURL=with-meticulous-postgres.js.map
|
|
152
|
+
//# debugId=7437e682-9879-55d9-aa51-34f2920d26d3
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"with-meticulous-postgres.js","sources":["../../src/postgres/with-meticulous-postgres.ts"],"sourcesContent":["import { type RequestCaptureContext, requestCaptureContext } from \"../context\";\nimport { warnOnce } from \"../log\";\nimport type { PostgresQueryEvent } from \"../protocol\";\nimport {\n isSupportedPostgresJsQuery,\n MAX_POSTGRES_JS_RESULT_SIZE,\n type PostgresJsQueryLike,\n reconstructQueryText,\n resolveRowMode,\n serializePostgresJsArgs,\n serializePostgresJsError,\n serializePostgresJsResult,\n} from \"./capture\";\n\n/**\n * Records postgres.js queries a deployed Worker makes — typically over Hyperdrive, which is the\n * only way a Worker reaches Postgres.\n *\n * There is no seam to patch automatically here. The Node recorder can hook Node's module loader\n * to patch `postgres/{src,cjs/src,cf/src}/query.js`, but a Worker is a single bundle: `postgres`\n * was inlined at build time and never passes through a loader. So the app hands us its client:\n *\n * const sql = withMeticulousPostgres(postgres(env.HYPERDRIVE.connectionString));\n *\n * Every postgres.js query funnels through one internal method, `Query.prototype.handle`, and this\n * reaches that shared prototype *through the instance* — via a throwaway query, which is free\n * because postgres.js queries are lazy and nothing executes until awaited. One call therefore also\n * covers read-replica clients and any other client in the isolate.\n *\n * Apply it **outermost** if something else also wraps the client (Sentry's\n * `instrumentPostgresJsSql`, a logging proxy): those wrappers return a proxy whose `handle` is\n * still the shared prototype's, so ordering does not change what is captured — but keeping ours\n * outermost matches the Node recorder's contract and stays correct if that ever changes.\n *\n * Record-only, deliberately. A Worker recording is replayed against the app running under Node,\n * where `@alwaysmeticulous/backend-recorder-js` serves these queries from its own mock store —\n * which is why the captured attributes here are exactly the ones that store reads. Outside a\n * recorded request this is a complete pass-through, so it is safe to leave in deployed code.\n *\n * Returns the client unchanged; the patch is on the prototype.\n */\nexport const withMeticulousPostgres = <Sql>(sql: Sql): Sql => {\n try {\n const prototype = findQueryPrototype(sql);\n if (prototype === undefined) {\n warnOnce(\n \"postgres-wrapper-unsupported\",\n \"withMeticulousPostgres could not reach postgres.js' Query prototype — queries will not be recorded.\",\n );\n return sql;\n }\n patchHandle(prototype);\n } catch (error) {\n warnOnce(\n \"postgres-wrapper-failed\",\n \"withMeticulousPostgres failed — queries will not be recorded.\",\n error,\n );\n }\n return sql;\n};\n\n// Symbol.for so a second copy of the shim (e.g. bundled twice) still detects the patch.\nconst HANDLE_PATCHED = Symbol.for(\"meticulous.workerd.postgresJsPatched\");\n\ntype HandleFn = (this: PostgresJsQueryLike) => unknown;\n\n/**\n * The `Query` prototype, reached by building a query and reading its prototype.\n *\n * `sql.unsafe` is used rather than a tagged template because it takes the text as a plain\n * argument: no interpolation, and postgres.js does not touch a connection until the query is\n * awaited, which nothing here does. The query is discarded.\n */\nconst findQueryPrototype = (sql: unknown): object | undefined => {\n const unsafe = (sql as { unsafe?: unknown } | null)?.unsafe;\n if (typeof unsafe !== \"function\") {\n return undefined;\n }\n const probe: unknown = (unsafe as (text: string) => unknown).call(\n sql,\n \"select 1\",\n );\n if (probe === null || typeof probe !== \"object\") {\n return undefined;\n }\n const prototype = Object.getPrototypeOf(probe) as object | null;\n if (prototype === null) {\n return undefined;\n }\n const descriptor = Object.getOwnPropertyDescriptor(prototype, \"handle\");\n return descriptor !== undefined &&\n typeof descriptor.value === \"function\" &&\n descriptor.configurable === true\n ? prototype\n : undefined;\n};\n\nconst patchHandle = (prototype: object): void => {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, \"handle\");\n const original = descriptor?.value as HandleFn | undefined;\n if (\n original === undefined ||\n (original as unknown as Record<symbol, unknown>)[HANDLE_PATCHED] === true\n ) {\n return;\n }\n\n const patched = function (this: PostgresJsQueryLike): unknown {\n // `handle` is reachable from then/catch/finally/execute, so it can be called more than once\n // for one query; postgres.js itself no-ops on the repeats via `executed`. Bail before\n // instrumenting so a query is never captured twice.\n if (this.executed || !isSupportedPostgresJsQuery(this)) {\n return original.call(this);\n }\n const ctx = requestCaptureContext.getStore();\n if (!ctx || ctx.mode !== \"record\") {\n return original.call(this);\n }\n try {\n captureQuery(ctx, this);\n } catch (error) {\n warnOnce(\n \"postgres-capture\",\n \"Failed to capture a postgres.js query.\",\n error,\n );\n }\n return original.call(this);\n };\n Object.defineProperty(patched, HANDLE_PATCHED, {\n value: true,\n enumerable: false,\n configurable: true,\n });\n Object.defineProperty(prototype, \"handle\", {\n value: patched,\n writable: true,\n enumerable: false,\n configurable: true,\n });\n};\n\n/**\n * Wraps the query's own `resolve`/`reject` so the outcome is captured without the query being\n * awaited here — the same trick the Node instrumentation uses, and the only place a query's input\n * and its result are both visible.\n */\nconst captureQuery = (\n ctx: RequestCaptureContext,\n query: PostgresJsQueryLike,\n): void => {\n const queryText = reconstructQueryText(query.strings);\n if (queryText === undefined) {\n return;\n }\n const startTimeMs = Date.now();\n const base = {\n kind: \"postgres\" as const,\n requestId: ctx.requestId,\n ...(ctx.frontendSessionId !== undefined\n ? { frontendSessionId: ctx.frontendSessionId }\n : {}),\n traceId: ctx.traceId,\n serverSpanId: ctx.serverSpanId,\n queryText,\n params: serializePostgresJsArgs(query.args),\n rowMode: resolveRowMode(query.isRaw),\n startTimeMs,\n };\n\n const report = (outcome: Partial<PostgresQueryEvent>): void => {\n try {\n ctx.buffer.add({ ...base, ...outcome, endTimeMs: Date.now() });\n } catch (error) {\n warnOnce(\n \"postgres-report\",\n \"Failed to report a postgres.js query.\",\n error,\n );\n }\n };\n\n const originalResolve = query.resolve;\n const originalReject = query.reject;\n query.resolve = (result: unknown) => {\n // A result that cannot be serialized is simply not captured → it misses during replay and\n // errors hermetically, rather than serving something wrong.\n let json: string | undefined;\n try {\n json = serializePostgresJsResult(result);\n } catch {\n json = undefined;\n }\n report(\n json === undefined\n ? {}\n : {\n result: {\n body:\n json.length > MAX_POSTGRES_JS_RESULT_SIZE\n ? json.slice(0, MAX_POSTGRES_JS_RESULT_SIZE)\n : json,\n truncated: json.length > MAX_POSTGRES_JS_RESULT_SIZE,\n },\n },\n );\n return originalResolve.call(query, result);\n };\n query.reject = (error: unknown) => {\n let errorJson: string | undefined;\n try {\n errorJson = serializePostgresJsError(error);\n } catch {\n errorJson = undefined;\n }\n report(errorJson === undefined ? {} : { errorJson });\n return originalReject.call(query, error);\n };\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAa,0BAA+B,QAAkB;AAC5D,KAAI;EACF,MAAM,YAAY,mBAAmB,IAAI;AACzC,MAAI,cAAc,KAAA,GAAW;AAC3B,YACE,gCACA,sGACD;AACD,UAAO;;AAET,cAAY,UAAU;UACf,OAAO;AACd,WACE,2BACA,iEACA,MACD;;AAEH,QAAO;;AAIT,MAAM,iBAAiB,OAAO,IAAI,uCAAuC;;;;;;;;AAWzE,MAAM,sBAAsB,QAAqC;CAC/D,MAAM,SAAU,KAAqC;AACrD,KAAI,OAAO,WAAW,WACpB;CAEF,MAAM,QAAkB,OAAqC,KAC3D,KACA,WACD;AACD,KAAI,UAAU,QAAQ,OAAO,UAAU,SACrC;CAEF,MAAM,YAAY,OAAO,eAAe,MAAM;AAC9C,KAAI,cAAc,KAChB;CAEF,MAAM,aAAa,OAAO,yBAAyB,WAAW,SAAS;AACvE,QAAO,eAAe,KAAA,KACpB,OAAO,WAAW,UAAU,cAC5B,WAAW,iBAAiB,OAC1B,YACA,KAAA;;AAGN,MAAM,eAAe,cAA4B;CAE/C,MAAM,WADa,OAAO,yBAAyB,WAAW,SACnC,EAAE;AAC7B,KACE,aAAa,KAAA,KACZ,SAAgD,oBAAoB,KAErE;CAGF,MAAM,UAAU,WAA8C;AAI5D,MAAI,KAAK,YAAY,CAAC,2BAA2B,KAAK,CACpD,QAAO,SAAS,KAAK,KAAK;EAE5B,MAAM,MAAM,sBAAsB,UAAU;AAC5C,MAAI,CAAC,OAAO,IAAI,SAAS,SACvB,QAAO,SAAS,KAAK,KAAK;AAE5B,MAAI;AACF,gBAAa,KAAK,KAAK;WAChB,OAAO;AACd,YACE,oBACA,0CACA,MACD;;AAEH,SAAO,SAAS,KAAK,KAAK;;AAE5B,QAAO,eAAe,SAAS,gBAAgB;EAC7C,OAAO;EACP,YAAY;EACZ,cAAc;EACf,CAAC;AACF,QAAO,eAAe,WAAW,UAAU;EACzC,OAAO;EACP,UAAU;EACV,YAAY;EACZ,cAAc;EACf,CAAC;;;;;;;AAQJ,MAAM,gBACJ,KACA,UACS;CACT,MAAM,YAAY,qBAAqB,MAAM,QAAQ;AACrD,KAAI,cAAc,KAAA,EAChB;CAEF,MAAM,cAAc,KAAK,KAAK;CAC9B,MAAM,OAAO;EACX,MAAM;EACN,WAAW,IAAI;EACf,GAAI,IAAI,sBAAsB,KAAA,IAC1B,EAAE,mBAAmB,IAAI,mBAAmB,GAC5C,EAAE;EACN,SAAS,IAAI;EACb,cAAc,IAAI;EAClB;EACA,QAAQ,wBAAwB,MAAM,KAAK;EAC3C,SAAS,eAAe,MAAM,MAAM;EACpC;EACD;CAED,MAAM,UAAU,YAA+C;AAC7D,MAAI;AACF,OAAI,OAAO,IAAI;IAAE,GAAG;IAAM,GAAG;IAAS,WAAW,KAAK,KAAK;IAAE,CAAC;WACvD,OAAO;AACd,YACE,mBACA,yCACA,MACD;;;CAIL,MAAM,kBAAkB,MAAM;CAC9B,MAAM,iBAAiB,MAAM;AAC7B,OAAM,WAAW,WAAoB;EAGnC,IAAI;AACJ,MAAI;AACF,UAAO,0BAA0B,OAAO;UAClC;AACN,UAAO,KAAA;;AAET,SACE,SAAS,KAAA,IACL,EAAE,GACF,EACE,QAAQ;GACN,MACE,KAAK,SAAA,SACD,KAAK,MAAM,GAAG,4BAA4B,GAC1C;GACN,WAAW,KAAK,SAAS;GAC1B,EACF,CACN;AACD,SAAO,gBAAgB,KAAK,OAAO,OAAO;;AAE5C,OAAM,UAAU,UAAmB;EACjC,IAAI;AACJ,MAAI;AACF,eAAY,yBAAyB,MAAM;UACrC;AACN,eAAY,KAAA;;AAEd,SAAO,cAAc,KAAA,IAAY,EAAE,GAAG,EAAE,WAAW,CAAC;AACpD,SAAO,eAAe,KAAK,OAAO,MAAM","debugId":"7437e682-9879-55d9-aa51-34f2920d26d3"}
|
package/dist/protocol.d.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* recorder sidecar. The sidecar imports these types (type-only), so this file
|
|
5
5
|
* is the single source of truth for the shape of capture events.
|
|
6
6
|
*/
|
|
7
|
-
declare const SIDECAR_PROTOCOL_VERSION = "
|
|
7
|
+
declare const SIDECAR_PROTOCOL_VERSION = "2";
|
|
8
8
|
/** Header carrying {@link SIDECAR_PROTOCOL_VERSION} on every shim → sidecar request. */
|
|
9
9
|
declare const SIDECAR_PROTOCOL_VERSION_HEADER = "x-meticulous-sidecar-protocol-version";
|
|
10
10
|
/**
|
|
@@ -12,6 +12,8 @@ declare const SIDECAR_PROTOCOL_VERSION_HEADER = "x-meticulous-sidecar-protocol-v
|
|
|
12
12
|
* under recording; its value ties backend spans to the frontend session.
|
|
13
13
|
*/
|
|
14
14
|
declare const FRONTEND_SESSION_ID_HEADER = "x-meticulous-session-id";
|
|
15
|
+
/** Header identifying one replay attempt of a recorded frontend session. */
|
|
16
|
+
declare const REPLAY_ID_HEADER = "x-meticulous-replay-id";
|
|
15
17
|
/**
|
|
16
18
|
* A request carrying this header set to `"true"` is never served from the recording and
|
|
17
19
|
* never fails on a miss — it goes to the real network. Use it for a call that must be live
|
|
@@ -42,9 +44,12 @@ declare const REPLAY_SIDECAR_URL_HEADER = "x-meticulous-backend-replay-sidecar-u
|
|
|
42
44
|
/**
|
|
43
45
|
* The only headers persisted on capture events. Everything else — notably
|
|
44
46
|
* authorization, cookie/set-cookie, and API-key headers — is dropped at
|
|
45
|
-
* capture time, before it ever leaves the worker.
|
|
46
|
-
*
|
|
47
|
-
*
|
|
47
|
+
* capture time, before it ever leaves the worker.
|
|
48
|
+
*
|
|
49
|
+
* The Node backend recorder persists the same two, plus the inbound request's
|
|
50
|
+
* `Cookie` header on SERVER spans (`recorded-request-headers.ts`). This list
|
|
51
|
+
* has not followed it there, so a workerd recording of an authenticated server
|
|
52
|
+
* render still carries no session cookie.
|
|
48
53
|
*/
|
|
49
54
|
declare const CAPTURED_HEADERS: readonly ["content-type", "x-meticulous-session-id"];
|
|
50
55
|
interface CapturedBody {
|
|
@@ -53,11 +58,33 @@ interface CapturedBody {
|
|
|
53
58
|
/** True when the body exceeded the capture cap or the read was cut short. */
|
|
54
59
|
truncated: boolean;
|
|
55
60
|
}
|
|
56
|
-
|
|
61
|
+
/**
|
|
62
|
+
* The fields every capture event carries to say which request, session and trace it belongs to.
|
|
63
|
+
*/
|
|
64
|
+
interface CorrelatedEvent {
|
|
57
65
|
/** Correlates outbound events to the inbound request being handled. */
|
|
58
66
|
requestId: string;
|
|
59
67
|
/** Value of {@link FRONTEND_SESSION_ID_HEADER} on the inbound request, if any. */
|
|
60
68
|
frontendSessionId?: string;
|
|
69
|
+
/**
|
|
70
|
+
* Trace the request's spans belong to (32 hex chars), minted by the shim.
|
|
71
|
+
*
|
|
72
|
+
* The shim mints it, rather than the sidecar deriving it from {@link requestId}, so span
|
|
73
|
+
* assembly is stateless: a sidecar that had to remember `requestId → traceId` would give a
|
|
74
|
+
* request's SERVER span and its CLIENT children different traces whenever it lost that memory
|
|
75
|
+
* between two batches — which, for a Worker-hosted sidecar, an eviction can do at any moment.
|
|
76
|
+
*
|
|
77
|
+
* Optional so a sidecar keeps working against a shim that predates this field, in which case
|
|
78
|
+
* it falls back to its own per-`requestId` map.
|
|
79
|
+
*/
|
|
80
|
+
traceId?: string;
|
|
81
|
+
/**
|
|
82
|
+
* Span id of the request's SERVER span (16 hex chars), also minted by the shim: it is the
|
|
83
|
+
* parent of every CLIENT span the request produced, and the inbound event's own span id.
|
|
84
|
+
*/
|
|
85
|
+
serverSpanId?: string;
|
|
86
|
+
}
|
|
87
|
+
interface BaseRequestEvent extends CorrelatedEvent {
|
|
61
88
|
method: string;
|
|
62
89
|
/** Full URL including query string. */
|
|
63
90
|
url: string;
|
|
@@ -76,6 +103,19 @@ interface BaseRequestEvent {
|
|
|
76
103
|
*/
|
|
77
104
|
interface InboundRequestEvent extends BaseRequestEvent {
|
|
78
105
|
kind: "inbound";
|
|
106
|
+
/**
|
|
107
|
+
* Where {@link BaseRequestEvent.frontendSessionId} came from. Absent means the browser
|
|
108
|
+
* minted it and sent it on the request, which is the normal case. `"backend"` means the
|
|
109
|
+
* shim minted it for a document navigation the browser could not tag, and the page may or
|
|
110
|
+
* may not have gone on to adopt it — a distinction ingestion needs, because an unadopted
|
|
111
|
+
* backend-minted id names a session that will never exist and must be treated as unstamped.
|
|
112
|
+
* The sidecar turns it into `meticulous.session_id_origin`.
|
|
113
|
+
*
|
|
114
|
+
* Optional, and therefore compatible with an older sidecar (which ignores it) — which is
|
|
115
|
+
* why adding it does not bump {@link SIDECAR_PROTOCOL_VERSION}, a strict-equality check
|
|
116
|
+
* whose bump would instead make this shim unusable against one.
|
|
117
|
+
*/
|
|
118
|
+
sessionIdOrigin?: "backend";
|
|
79
119
|
}
|
|
80
120
|
/**
|
|
81
121
|
* An outgoing `fetch` call made while handling an inbound request (becomes a
|
|
@@ -123,11 +163,8 @@ type KvOmittedReason = "binary" | "stream";
|
|
|
123
163
|
* {@link BaseRequestEvent} beyond correlation and timing. Values are JSON so that a single
|
|
124
164
|
* `JSON.parse` reconstructs exactly what the app saw, whichever `type` the read asked for.
|
|
125
165
|
*/
|
|
126
|
-
interface KvOperationEvent {
|
|
166
|
+
interface KvOperationEvent extends CorrelatedEvent {
|
|
127
167
|
kind: "kv";
|
|
128
|
-
/** Correlates the operation to the inbound request being handled. */
|
|
129
|
-
requestId: string;
|
|
130
|
-
frontendSessionId?: string;
|
|
131
168
|
/**
|
|
132
169
|
* The `env` key the KV namespace was found under. Always present, unlike on a binding
|
|
133
170
|
* event: a namespace has no factory equivalent to `DurableObjectNamespace.get()`, so one
|
|
@@ -164,7 +201,34 @@ interface KvOperationEvent {
|
|
|
164
201
|
/** Set when the operation threw. */
|
|
165
202
|
error?: string;
|
|
166
203
|
}
|
|
167
|
-
|
|
204
|
+
/**
|
|
205
|
+
* One postgres.js query made while handling an inbound request (becomes a CLIENT span).
|
|
206
|
+
*
|
|
207
|
+
* Deliberately carries the same fields the Node recorder puts on a postgres.js span rather than
|
|
208
|
+
* anything Worker-specific: `PostgresJsMockStore` builds its match key from those attributes at
|
|
209
|
+
* load time, so a query recorded here replays through the existing Node mock path unchanged.
|
|
210
|
+
* See `postgres/capture.ts` for the serialization, which both surfaces share.
|
|
211
|
+
*/
|
|
212
|
+
interface PostgresQueryEvent extends CorrelatedEvent {
|
|
213
|
+
kind: "postgres";
|
|
214
|
+
/** SQL rebuilt from the tagged template's chunks, with `$1`, `$2`… placeholders. */
|
|
215
|
+
queryText: string;
|
|
216
|
+
/** JSON of the interpolated values, from `serializePostgresJsArgs`. */
|
|
217
|
+
params: string;
|
|
218
|
+
/** `""`, `"raw"` or `"values"` — the row shape the query asked for. */
|
|
219
|
+
rowMode: string;
|
|
220
|
+
/** JSON of the resolved `Result`, capped at {@link MAX_POSTGRES_JS_RESULT_SIZE}. */
|
|
221
|
+
result?: CapturedBody;
|
|
222
|
+
/**
|
|
223
|
+
* JSON of the rejection, from `serializePostgresJsError`. Set instead of {@link result}, and
|
|
224
|
+
* distinct from the transport-level `error` string on the HTTP-shaped events: this one is a
|
|
225
|
+
* recorded outcome the replay reproduces, not a note that capture failed.
|
|
226
|
+
*/
|
|
227
|
+
errorJson?: string;
|
|
228
|
+
startTimeMs: number;
|
|
229
|
+
endTimeMs: number;
|
|
230
|
+
}
|
|
231
|
+
type CaptureEvent = InboundRequestEvent | OutboundRequestEvent | BindingRequestEvent | KvOperationEvent | PostgresQueryEvent;
|
|
168
232
|
interface CaptureEventsPayload {
|
|
169
233
|
events: CaptureEvent[];
|
|
170
234
|
}
|
|
@@ -183,6 +247,7 @@ interface ReplaySessionInfoResponse {
|
|
|
183
247
|
/** Lookup for a single outbound `fetch`, sent to {@link SIDECAR_REPLAY_OUTBOUND_FETCH_PATH}. */
|
|
184
248
|
interface OutboundFetchLookupRequest {
|
|
185
249
|
frontendSessionId: string;
|
|
250
|
+
replayId: string;
|
|
186
251
|
method: string;
|
|
187
252
|
/** Full URL including query string. */
|
|
188
253
|
url: string;
|
|
@@ -221,5 +286,5 @@ type OutboundFetchLookupResponse = {
|
|
|
221
286
|
outcome: "passthrough";
|
|
222
287
|
};
|
|
223
288
|
//#endregion
|
|
224
|
-
export { BindingRequestEvent, CAPTURED_HEADERS, CaptureEvent, CaptureEventsPayload, CapturedBody, FRONTEND_SESSION_ID_HEADER, InboundRequestEvent, KvOmittedReason, KvOperation, KvOperationEvent, METICULOUS_PASSTHROUGH_HEADER, OutboundFetchLookupRequest, OutboundFetchLookupResponse, OutboundRequestEvent, REPLAY_SIDECAR_URL_HEADER, ReplaySessionInfoResponse, SIDECAR_EVENTS_PATH, SIDECAR_PROTOCOL_VERSION, SIDECAR_PROTOCOL_VERSION_HEADER, SIDECAR_REPLAY_OUTBOUND_FETCH_PATH, SIDECAR_REPLAY_SESSION_PATH };
|
|
289
|
+
export { BindingRequestEvent, CAPTURED_HEADERS, CaptureEvent, CaptureEventsPayload, CapturedBody, FRONTEND_SESSION_ID_HEADER, InboundRequestEvent, KvOmittedReason, KvOperation, KvOperationEvent, METICULOUS_PASSTHROUGH_HEADER, OutboundFetchLookupRequest, OutboundFetchLookupResponse, OutboundRequestEvent, PostgresQueryEvent, REPLAY_ID_HEADER, REPLAY_SIDECAR_URL_HEADER, ReplaySessionInfoResponse, SIDECAR_EVENTS_PATH, SIDECAR_PROTOCOL_VERSION, SIDECAR_PROTOCOL_VERSION_HEADER, SIDECAR_REPLAY_OUTBOUND_FETCH_PATH, SIDECAR_REPLAY_SESSION_PATH };
|
|
225
290
|
//# sourceMappingURL=protocol.d.ts.map
|
package/dist/protocol.js
CHANGED
|
@@ -5,8 +5,8 @@
|
|
|
5
5
|
* is the single source of truth for the shape of capture events.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
9
|
-
const SIDECAR_PROTOCOL_VERSION = "
|
|
8
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="36a20e1c-cf70-5563-a474-2863eaacfbe8")}catch(e){}}();
|
|
9
|
+
const SIDECAR_PROTOCOL_VERSION = "2";
|
|
10
10
|
/** Header carrying {@link SIDECAR_PROTOCOL_VERSION} on every shim → sidecar request. */
|
|
11
11
|
const SIDECAR_PROTOCOL_VERSION_HEADER = "x-meticulous-sidecar-protocol-version";
|
|
12
12
|
/**
|
|
@@ -14,6 +14,8 @@ const SIDECAR_PROTOCOL_VERSION_HEADER = "x-meticulous-sidecar-protocol-version";
|
|
|
14
14
|
* under recording; its value ties backend spans to the frontend session.
|
|
15
15
|
*/
|
|
16
16
|
const FRONTEND_SESSION_ID_HEADER = "x-meticulous-session-id";
|
|
17
|
+
/** Header identifying one replay attempt of a recorded frontend session. */
|
|
18
|
+
const REPLAY_ID_HEADER = "x-meticulous-replay-id";
|
|
17
19
|
/**
|
|
18
20
|
* A request carrying this header set to `"true"` is never served from the recording and
|
|
19
21
|
* never fails on a miss — it goes to the real network. Use it for a call that must be live
|
|
@@ -44,13 +46,16 @@ const REPLAY_SIDECAR_URL_HEADER = "x-meticulous-backend-replay-sidecar-url";
|
|
|
44
46
|
/**
|
|
45
47
|
* The only headers persisted on capture events. Everything else — notably
|
|
46
48
|
* authorization, cookie/set-cookie, and API-key headers — is dropped at
|
|
47
|
-
* capture time, before it ever leaves the worker.
|
|
48
|
-
*
|
|
49
|
-
*
|
|
49
|
+
* capture time, before it ever leaves the worker.
|
|
50
|
+
*
|
|
51
|
+
* The Node backend recorder persists the same two, plus the inbound request's
|
|
52
|
+
* `Cookie` header on SERVER spans (`recorded-request-headers.ts`). This list
|
|
53
|
+
* has not followed it there, so a workerd recording of an authenticated server
|
|
54
|
+
* render still carries no session cookie.
|
|
50
55
|
*/
|
|
51
56
|
const CAPTURED_HEADERS = ["content-type", FRONTEND_SESSION_ID_HEADER];
|
|
52
57
|
//#endregion
|
|
53
|
-
export { CAPTURED_HEADERS, FRONTEND_SESSION_ID_HEADER, METICULOUS_PASSTHROUGH_HEADER, REPLAY_SIDECAR_URL_HEADER, SIDECAR_EVENTS_PATH, SIDECAR_PROTOCOL_VERSION, SIDECAR_PROTOCOL_VERSION_HEADER, SIDECAR_REPLAY_OUTBOUND_FETCH_PATH, SIDECAR_REPLAY_SESSION_PATH };
|
|
58
|
+
export { CAPTURED_HEADERS, FRONTEND_SESSION_ID_HEADER, METICULOUS_PASSTHROUGH_HEADER, REPLAY_ID_HEADER, REPLAY_SIDECAR_URL_HEADER, SIDECAR_EVENTS_PATH, SIDECAR_PROTOCOL_VERSION, SIDECAR_PROTOCOL_VERSION_HEADER, SIDECAR_REPLAY_OUTBOUND_FETCH_PATH, SIDECAR_REPLAY_SESSION_PATH };
|
|
54
59
|
|
|
55
60
|
//# sourceMappingURL=protocol.js.map
|
|
56
|
-
//# debugId=
|
|
61
|
+
//# debugId=36a20e1c-cf70-5563-a474-2863eaacfbe8
|
package/dist/protocol.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"protocol.js","sources":["../src/protocol.ts"],"sourcesContent":["/**\n * Wire protocol between the in-worker shim and the Meticulous backend\n * recorder sidecar. The sidecar imports these types (type-only), so this file\n * is the single source of truth for the shape of capture events.\n */\n\nexport const SIDECAR_PROTOCOL_VERSION = \"1\";\n\n/** Header carrying {@link SIDECAR_PROTOCOL_VERSION} on every shim → sidecar request. */\nexport const SIDECAR_PROTOCOL_VERSION_HEADER =\n \"x-meticulous-sidecar-protocol-version\";\n\n/**\n * Header the Meticulous frontend recorder stamps on requests made by the app\n * under recording; its value ties backend spans to the frontend session.\n */\nexport const FRONTEND_SESSION_ID_HEADER = \"x-meticulous-session-id\";\n\n/**\n * A request carrying this header set to `\"true\"` is never served from the recording and\n * never fails on a miss — it goes to the real network. Use it for a call that must be live\n * during replay (a health probe, telemetry, a resource the recording cannot cover).\n *\n * Same convention and value as the frontend network stubbing and the Node backend recorder\n * (`METICULOUS_PASSTHROUGH_HEADER` in `@alwaysmeticulous/backend-recorder-js`); the value\n * must stay in step with both.\n */\nexport const METICULOUS_PASSTHROUGH_HEADER = \"meticulous-passthrough\";\n\nexport const SIDECAR_EVENTS_PATH = \"/v1/events\";\n\n/**\n * Replay routes. A sidecar started in record mode answers 404 on both, which the shim\n * treats as \"replay unavailable\" and falls back to plain pass-through — so a new shim\n * keeps working against an older, record-only sidecar.\n */\nexport const SIDECAR_REPLAY_SESSION_PATH = \"/v1/replay/session\";\nexport const SIDECAR_REPLAY_OUTBOUND_FETCH_PATH = \"/v1/replay/outbound-fetch\";\n\n/**\n * Header carrying the replay sidecar's origin, injected by the Meticulous replay runner\n * on requests to the app under test. Workerd cannot see container environment variables,\n * so an inbound header is the only way per-replay config can reach the shim.\n *\n * The shim validates the value before using it and only honours a loopback /\n * `host.docker.internal` / private-network `http:` origin — see `replay-sidecar-url.ts`.\n */\nexport const REPLAY_SIDECAR_URL_HEADER =\n \"x-meticulous-backend-replay-sidecar-url\";\n\n/**\n * The only headers persisted on capture events. Everything else — notably\n * authorization, cookie/set-cookie, and API-key headers — is dropped at\n * capture time, before it ever leaves the worker. Mirrors the Node backend\n * recorder, which persists only content-type plus the Meticulous session\n * header.\n */\nexport const CAPTURED_HEADERS = [\n \"content-type\",\n FRONTEND_SESSION_ID_HEADER,\n] as const;\n\nexport interface CapturedBody {\n /** UTF-8 decoded body, truncated to the capture cap. */\n body: string;\n /** True when the body exceeded the capture cap or the read was cut short. */\n truncated: boolean;\n}\n\ninterface BaseRequestEvent {\n /** Correlates outbound events to the inbound request being handled. */\n requestId: string;\n /** Value of {@link FRONTEND_SESSION_ID_HEADER} on the inbound request, if any. */\n frontendSessionId?: string;\n method: string;\n /** Full URL including query string. */\n url: string;\n /** Lower-cased header name → values. */\n requestHeaders: Record<string, string[]>;\n responseHeaders?: Record<string, string[]>;\n statusCode?: number;\n startTimeMs: number;\n endTimeMs: number;\n /** Set when the request failed before a response was produced. */\n error?: string;\n}\n\n/**\n * The worker's own inbound request (becomes a SERVER span). Bodies are not\n * captured, matching the Node backend recorder's SERVER-span contract.\n */\nexport interface InboundRequestEvent extends BaseRequestEvent {\n kind: \"inbound\";\n}\n\n/**\n * An outgoing `fetch` call made while handling an inbound request (becomes a\n * CLIENT span).\n */\nexport interface OutboundRequestEvent extends BaseRequestEvent {\n kind: \"outbound\";\n requestBody?: CapturedBody;\n responseBody?: CapturedBody;\n}\n\n/**\n * A `fetch` through a Cloudflare binding — a service binding, an assets binding, or a\n * Durable Object stub — made while handling an inbound request (becomes a CLIENT span).\n *\n * Request/Response-shaped like {@link OutboundRequestEvent}, but a distinct kind because the\n * call never leaves the isolate and its URL is whatever the caller invented. Keeping the two\n * apart means a binding call and real egress can never be confused for one another when\n * these spans are eventually mocked.\n */\nexport interface BindingRequestEvent extends BaseRequestEvent {\n kind: \"binding\";\n /**\n * The `env` key the binding was found under. Absent when the instance was never seen on\n * `env` — most commonly a Durable Object stub, which `namespace.get()` produces rather\n * than being a binding in its own right.\n */\n bindingName?: string;\n requestBody?: CapturedBody;\n responseBody?: CapturedBody;\n}\n\n/** KV namespace methods the shim records. */\nexport type KvOperation = \"get\" | \"getWithMetadata\" | \"put\" | \"delete\" | \"list\";\n\n/**\n * Why a KV value is absent from an event: workerd handed it over in a form that cannot be\n * persisted as text. A `\"stream\"` value must not even be read — consuming it would take the\n * bytes away from the app — and binary values are skipped deliberately, since KV blobs are\n * large and would both bloat the recording and be mangled by UTF-8 capture.\n */\nexport type KvOmittedReason = \"binary\" | \"stream\";\n\n/**\n * An operation on a Cloudflare KV namespace binding, made while handling an inbound request\n * (becomes a CLIENT span).\n *\n * KV is not HTTP: there is no method, URL or status code, so this event shares nothing with\n * {@link BaseRequestEvent} beyond correlation and timing. Values are JSON so that a single\n * `JSON.parse` reconstructs exactly what the app saw, whichever `type` the read asked for.\n */\nexport interface KvOperationEvent {\n kind: \"kv\";\n /** Correlates the operation to the inbound request being handled. */\n requestId: string;\n frontendSessionId?: string;\n /**\n * The `env` key the KV namespace was found under. Always present, unlike on a binding\n * event: a namespace has no factory equivalent to `DurableObjectNamespace.get()`, so one\n * that was never seen on `env` is not recorded at all.\n */\n bindingName: string;\n operation: KvOperation;\n /**\n * The key operated on, when it is a single string. Absent for `list` (which spans keys) and\n * for a bulk `get` (which takes an array) — both keep their arguments in {@link args}.\n */\n key?: string;\n /**\n * JSON of the call's arguments: the read `type`, the `put` options, the `list` selector.\n * A `put` value appears as `null` here — it is captured in {@link value} instead, so that\n * redaction applies to it.\n */\n args?: CapturedBody;\n /** JSON of the value a `put` wrote, with secret-looking fields redacted. */\n value?: CapturedBody;\n /**\n * JSON of what the operation returned: the value for `get`, `{value, metadata}` for\n * `getWithMetadata`, the key page for `list`. Absent for `put`/`delete`, which return\n * nothing, and for a value that could not be captured (see {@link omitted}).\n */\n result?: CapturedBody;\n /**\n * Why the operation's value is missing. Refers to the written value for `put` and to the\n * read value otherwise — a `put` has no result, so this is never ambiguous.\n */\n omitted?: KvOmittedReason;\n startTimeMs: number;\n endTimeMs: number;\n /** Set when the operation threw. */\n error?: string;\n}\n\nexport type CaptureEvent =\n | InboundRequestEvent\n | OutboundRequestEvent\n | BindingRequestEvent\n | KvOperationEvent;\n\nexport interface CaptureEventsPayload {\n events: CaptureEvent[];\n}\n\n/**\n * Answer to `GET {SIDECAR_REPLAY_SESSION_PATH}?sessionId=<id>`: whether the sidecar holds\n * mocks for a session, and the virtual clock anchor to freeze `Date` at while serving it.\n */\nexport interface ReplaySessionInfoResponse {\n found: boolean;\n /**\n * Epoch ms of the session's last recorded activity. The worker freezes its clock here so\n * that credentials minted during the recording are already issued but not yet expired.\n */\n clockAnchorMs?: number;\n}\n\n/** Lookup for a single outbound `fetch`, sent to {@link SIDECAR_REPLAY_OUTBOUND_FETCH_PATH}. */\nexport interface OutboundFetchLookupRequest {\n frontendSessionId: string;\n method: string;\n /** Full URL including query string. */\n url: string;\n /**\n * Request body as captured by `readBodyWithCap`. The sidecar hashes this itself, so the\n * hash it compares against a recording is derived from byte-identical input on both the\n * record and replay sides.\n */\n requestBody?: CapturedBody;\n}\n\n/**\n * A recorded response to serve, a miss the caller must fail, or an instruction to let the\n * real call through. An unrecognised `outcome` must be treated as `passthrough`, so an older\n * shim keeps working against a newer sidecar.\n */\nexport type OutboundFetchLookupResponse =\n | {\n outcome: \"mock\";\n statusCode: number;\n body: string;\n headers: Record<string, string>;\n }\n /**\n * The store was consulted and holds nothing for this call. Replay is hermetic, so the\n * shim fails the request rather than letting it reach the real service — matching the\n * Node backend recorder's http/undici mocks.\n */\n | { outcome: \"no-mock\" }\n /**\n * The call cannot be looked up at all (an unparseable URL), so there is no miss to report.\n * Also what an older sidecar answers on a miss, in which case the shim degrades to the\n * pre-`no-mock` fail-open behaviour rather than breaking the app.\n */\n | { outcome: \"passthrough\" };\n"],"names":[],"mappings":";;;;;;;;AAMA,MAAa,2BAA2B;;AAGxC,MAAa,kCACX;;;;;AAMF,MAAa,6BAA6B;;;;;;;;;;AAW1C,MAAa,gCAAgC;AAE7C,MAAa,sBAAsB;;;;;;AAOnC,MAAa,8BAA8B;AAC3C,MAAa,qCAAqC;;;;;;;;;AAUlD,MAAa,4BACX;;;;;;;;AASF,MAAa,mBAAmB,CAC9B,gBACA,2BACD","debugId":"40d02ddc-000e-5f33-972c-1fa95ad7e2ea"}
|
|
1
|
+
{"version":3,"file":"protocol.js","sources":["../src/protocol.ts"],"sourcesContent":["/**\n * Wire protocol between the in-worker shim and the Meticulous backend\n * recorder sidecar. The sidecar imports these types (type-only), so this file\n * is the single source of truth for the shape of capture events.\n */\n\nexport const SIDECAR_PROTOCOL_VERSION = \"2\";\n\n/** Header carrying {@link SIDECAR_PROTOCOL_VERSION} on every shim → sidecar request. */\nexport const SIDECAR_PROTOCOL_VERSION_HEADER =\n \"x-meticulous-sidecar-protocol-version\";\n\n/**\n * Header the Meticulous frontend recorder stamps on requests made by the app\n * under recording; its value ties backend spans to the frontend session.\n */\nexport const FRONTEND_SESSION_ID_HEADER = \"x-meticulous-session-id\";\n\n/** Header identifying one replay attempt of a recorded frontend session. */\nexport const REPLAY_ID_HEADER = \"x-meticulous-replay-id\";\n\n/**\n * A request carrying this header set to `\"true\"` is never served from the recording and\n * never fails on a miss — it goes to the real network. Use it for a call that must be live\n * during replay (a health probe, telemetry, a resource the recording cannot cover).\n *\n * Same convention and value as the frontend network stubbing and the Node backend recorder\n * (`METICULOUS_PASSTHROUGH_HEADER` in `@alwaysmeticulous/backend-recorder-js`); the value\n * must stay in step with both.\n */\nexport const METICULOUS_PASSTHROUGH_HEADER = \"meticulous-passthrough\";\n\nexport const SIDECAR_EVENTS_PATH = \"/v1/events\";\n\n/**\n * Replay routes. A sidecar started in record mode answers 404 on both, which the shim\n * treats as \"replay unavailable\" and falls back to plain pass-through — so a new shim\n * keeps working against an older, record-only sidecar.\n */\nexport const SIDECAR_REPLAY_SESSION_PATH = \"/v1/replay/session\";\nexport const SIDECAR_REPLAY_OUTBOUND_FETCH_PATH = \"/v1/replay/outbound-fetch\";\n\n/**\n * Header carrying the replay sidecar's origin, injected by the Meticulous replay runner\n * on requests to the app under test. Workerd cannot see container environment variables,\n * so an inbound header is the only way per-replay config can reach the shim.\n *\n * The shim validates the value before using it and only honours a loopback /\n * `host.docker.internal` / private-network `http:` origin — see `replay-sidecar-url.ts`.\n */\nexport const REPLAY_SIDECAR_URL_HEADER =\n \"x-meticulous-backend-replay-sidecar-url\";\n\n/**\n * The only headers persisted on capture events. Everything else — notably\n * authorization, cookie/set-cookie, and API-key headers — is dropped at\n * capture time, before it ever leaves the worker.\n *\n * The Node backend recorder persists the same two, plus the inbound request's\n * `Cookie` header on SERVER spans (`recorded-request-headers.ts`). This list\n * has not followed it there, so a workerd recording of an authenticated server\n * render still carries no session cookie.\n */\nexport const CAPTURED_HEADERS = [\n \"content-type\",\n FRONTEND_SESSION_ID_HEADER,\n] as const;\n\nexport interface CapturedBody {\n /** UTF-8 decoded body, truncated to the capture cap. */\n body: string;\n /** True when the body exceeded the capture cap or the read was cut short. */\n truncated: boolean;\n}\n\n/**\n * The fields every capture event carries to say which request, session and trace it belongs to.\n */\ninterface CorrelatedEvent {\n /** Correlates outbound events to the inbound request being handled. */\n requestId: string;\n /** Value of {@link FRONTEND_SESSION_ID_HEADER} on the inbound request, if any. */\n frontendSessionId?: string;\n /**\n * Trace the request's spans belong to (32 hex chars), minted by the shim.\n *\n * The shim mints it, rather than the sidecar deriving it from {@link requestId}, so span\n * assembly is stateless: a sidecar that had to remember `requestId → traceId` would give a\n * request's SERVER span and its CLIENT children different traces whenever it lost that memory\n * between two batches — which, for a Worker-hosted sidecar, an eviction can do at any moment.\n *\n * Optional so a sidecar keeps working against a shim that predates this field, in which case\n * it falls back to its own per-`requestId` map.\n */\n traceId?: string;\n /**\n * Span id of the request's SERVER span (16 hex chars), also minted by the shim: it is the\n * parent of every CLIENT span the request produced, and the inbound event's own span id.\n */\n serverSpanId?: string;\n}\n\ninterface BaseRequestEvent extends CorrelatedEvent {\n method: string;\n /** Full URL including query string. */\n url: string;\n /** Lower-cased header name → values. */\n requestHeaders: Record<string, string[]>;\n responseHeaders?: Record<string, string[]>;\n statusCode?: number;\n startTimeMs: number;\n endTimeMs: number;\n /** Set when the request failed before a response was produced. */\n error?: string;\n}\n\n/**\n * The worker's own inbound request (becomes a SERVER span). Bodies are not\n * captured, matching the Node backend recorder's SERVER-span contract.\n */\nexport interface InboundRequestEvent extends BaseRequestEvent {\n kind: \"inbound\";\n /**\n * Where {@link BaseRequestEvent.frontendSessionId} came from. Absent means the browser\n * minted it and sent it on the request, which is the normal case. `\"backend\"` means the\n * shim minted it for a document navigation the browser could not tag, and the page may or\n * may not have gone on to adopt it — a distinction ingestion needs, because an unadopted\n * backend-minted id names a session that will never exist and must be treated as unstamped.\n * The sidecar turns it into `meticulous.session_id_origin`.\n *\n * Optional, and therefore compatible with an older sidecar (which ignores it) — which is\n * why adding it does not bump {@link SIDECAR_PROTOCOL_VERSION}, a strict-equality check\n * whose bump would instead make this shim unusable against one.\n */\n sessionIdOrigin?: \"backend\";\n}\n\n/**\n * An outgoing `fetch` call made while handling an inbound request (becomes a\n * CLIENT span).\n */\nexport interface OutboundRequestEvent extends BaseRequestEvent {\n kind: \"outbound\";\n requestBody?: CapturedBody;\n responseBody?: CapturedBody;\n}\n\n/**\n * A `fetch` through a Cloudflare binding — a service binding, an assets binding, or a\n * Durable Object stub — made while handling an inbound request (becomes a CLIENT span).\n *\n * Request/Response-shaped like {@link OutboundRequestEvent}, but a distinct kind because the\n * call never leaves the isolate and its URL is whatever the caller invented. Keeping the two\n * apart means a binding call and real egress can never be confused for one another when\n * these spans are eventually mocked.\n */\nexport interface BindingRequestEvent extends BaseRequestEvent {\n kind: \"binding\";\n /**\n * The `env` key the binding was found under. Absent when the instance was never seen on\n * `env` — most commonly a Durable Object stub, which `namespace.get()` produces rather\n * than being a binding in its own right.\n */\n bindingName?: string;\n requestBody?: CapturedBody;\n responseBody?: CapturedBody;\n}\n\n/** KV namespace methods the shim records. */\nexport type KvOperation = \"get\" | \"getWithMetadata\" | \"put\" | \"delete\" | \"list\";\n\n/**\n * Why a KV value is absent from an event: workerd handed it over in a form that cannot be\n * persisted as text. A `\"stream\"` value must not even be read — consuming it would take the\n * bytes away from the app — and binary values are skipped deliberately, since KV blobs are\n * large and would both bloat the recording and be mangled by UTF-8 capture.\n */\nexport type KvOmittedReason = \"binary\" | \"stream\";\n\n/**\n * An operation on a Cloudflare KV namespace binding, made while handling an inbound request\n * (becomes a CLIENT span).\n *\n * KV is not HTTP: there is no method, URL or status code, so this event shares nothing with\n * {@link BaseRequestEvent} beyond correlation and timing. Values are JSON so that a single\n * `JSON.parse` reconstructs exactly what the app saw, whichever `type` the read asked for.\n */\nexport interface KvOperationEvent extends CorrelatedEvent {\n kind: \"kv\";\n /**\n * The `env` key the KV namespace was found under. Always present, unlike on a binding\n * event: a namespace has no factory equivalent to `DurableObjectNamespace.get()`, so one\n * that was never seen on `env` is not recorded at all.\n */\n bindingName: string;\n operation: KvOperation;\n /**\n * The key operated on, when it is a single string. Absent for `list` (which spans keys) and\n * for a bulk `get` (which takes an array) — both keep their arguments in {@link args}.\n */\n key?: string;\n /**\n * JSON of the call's arguments: the read `type`, the `put` options, the `list` selector.\n * A `put` value appears as `null` here — it is captured in {@link value} instead, so that\n * redaction applies to it.\n */\n args?: CapturedBody;\n /** JSON of the value a `put` wrote, with secret-looking fields redacted. */\n value?: CapturedBody;\n /**\n * JSON of what the operation returned: the value for `get`, `{value, metadata}` for\n * `getWithMetadata`, the key page for `list`. Absent for `put`/`delete`, which return\n * nothing, and for a value that could not be captured (see {@link omitted}).\n */\n result?: CapturedBody;\n /**\n * Why the operation's value is missing. Refers to the written value for `put` and to the\n * read value otherwise — a `put` has no result, so this is never ambiguous.\n */\n omitted?: KvOmittedReason;\n startTimeMs: number;\n endTimeMs: number;\n /** Set when the operation threw. */\n error?: string;\n}\n\n/**\n * One postgres.js query made while handling an inbound request (becomes a CLIENT span).\n *\n * Deliberately carries the same fields the Node recorder puts on a postgres.js span rather than\n * anything Worker-specific: `PostgresJsMockStore` builds its match key from those attributes at\n * load time, so a query recorded here replays through the existing Node mock path unchanged.\n * See `postgres/capture.ts` for the serialization, which both surfaces share.\n */\nexport interface PostgresQueryEvent extends CorrelatedEvent {\n kind: \"postgres\";\n /** SQL rebuilt from the tagged template's chunks, with `$1`, `$2`… placeholders. */\n queryText: string;\n /** JSON of the interpolated values, from `serializePostgresJsArgs`. */\n params: string;\n /** `\"\"`, `\"raw\"` or `\"values\"` — the row shape the query asked for. */\n rowMode: string;\n /** JSON of the resolved `Result`, capped at {@link MAX_POSTGRES_JS_RESULT_SIZE}. */\n result?: CapturedBody;\n /**\n * JSON of the rejection, from `serializePostgresJsError`. Set instead of {@link result}, and\n * distinct from the transport-level `error` string on the HTTP-shaped events: this one is a\n * recorded outcome the replay reproduces, not a note that capture failed.\n */\n errorJson?: string;\n startTimeMs: number;\n endTimeMs: number;\n}\n\nexport type CaptureEvent =\n | InboundRequestEvent\n | OutboundRequestEvent\n | BindingRequestEvent\n | KvOperationEvent\n | PostgresQueryEvent;\n\nexport interface CaptureEventsPayload {\n events: CaptureEvent[];\n}\n\n/**\n * Answer to `GET {SIDECAR_REPLAY_SESSION_PATH}?sessionId=<id>`: whether the sidecar holds\n * mocks for a session, and the virtual clock anchor to freeze `Date` at while serving it.\n */\nexport interface ReplaySessionInfoResponse {\n found: boolean;\n /**\n * Epoch ms of the session's last recorded activity. The worker freezes its clock here so\n * that credentials minted during the recording are already issued but not yet expired.\n */\n clockAnchorMs?: number;\n}\n\n/** Lookup for a single outbound `fetch`, sent to {@link SIDECAR_REPLAY_OUTBOUND_FETCH_PATH}. */\nexport interface OutboundFetchLookupRequest {\n frontendSessionId: string;\n replayId: string;\n method: string;\n /** Full URL including query string. */\n url: string;\n /**\n * Request body as captured by `readBodyWithCap`. The sidecar hashes this itself, so the\n * hash it compares against a recording is derived from byte-identical input on both the\n * record and replay sides.\n */\n requestBody?: CapturedBody;\n}\n\n/**\n * A recorded response to serve, a miss the caller must fail, or an instruction to let the\n * real call through. An unrecognised `outcome` must be treated as `passthrough`, so an older\n * shim keeps working against a newer sidecar.\n */\nexport type OutboundFetchLookupResponse =\n | {\n outcome: \"mock\";\n statusCode: number;\n body: string;\n headers: Record<string, string>;\n }\n /**\n * The store was consulted and holds nothing for this call. Replay is hermetic, so the\n * shim fails the request rather than letting it reach the real service — matching the\n * Node backend recorder's http/undici mocks.\n */\n | { outcome: \"no-mock\" }\n /**\n * The call cannot be looked up at all (an unparseable URL), so there is no miss to report.\n * Also what an older sidecar answers on a miss, in which case the shim degrades to the\n * pre-`no-mock` fail-open behaviour rather than breaking the app.\n */\n | { outcome: \"passthrough\" };\n"],"names":[],"mappings":";;;;;;;;AAMA,MAAa,2BAA2B;;AAGxC,MAAa,kCACX;;;;;AAMF,MAAa,6BAA6B;;AAG1C,MAAa,mBAAmB;;;;;;;;;;AAWhC,MAAa,gCAAgC;AAE7C,MAAa,sBAAsB;;;;;;AAOnC,MAAa,8BAA8B;AAC3C,MAAa,qCAAqC;;;;;;;;;AAUlD,MAAa,4BACX;;;;;;;;;;;AAYF,MAAa,mBAAmB,CAC9B,gBACA,2BACD","debugId":"36a20e1c-cf70-5563-a474-2863eaacfbe8"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
//#region src/provisional-session-id.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* A session id the *backend* mints, for the one request that can never carry one from the
|
|
4
|
+
* browser: a top-level document navigation. Browsers cannot add custom headers to a
|
|
5
|
+
* navigation, and on the session-starting navigation the frontend has not minted an id yet
|
|
6
|
+
* (it does so only once the HTML has arrived and the snippet has run) — so the server-side
|
|
7
|
+
* render's spans are recorded against no session and nothing about that traffic can be
|
|
8
|
+
* replayed exactly.
|
|
9
|
+
*
|
|
10
|
+
* Everything here is runtime-agnostic on purpose. Both backend recorders mint the same ids
|
|
11
|
+
* by the same rule and publish them under the same `Server-Timing` metric, and all three are
|
|
12
|
+
* wire contracts with the page, so there is exactly one implementation — the same reason
|
|
13
|
+
* kv-capture.ts lives here rather than being written twice. The Node recorder imports these
|
|
14
|
+
* from the package entry; see `provisional-session-id.ts` in
|
|
15
|
+
* `@alwaysmeticulous/backend-recorder-js` for the `http.IncomingMessage` adapter, and
|
|
16
|
+
* `publish-session-id.ts` next door for the workerd one.
|
|
17
|
+
*/
|
|
18
|
+
/**
|
|
19
|
+
* Reads one request header by its lower-cased name. Both `IncomingMessage.headers[name]`
|
|
20
|
+
* (after the caller flattens Node's `string | string[]`) and `Headers.get(name)` satisfy it,
|
|
21
|
+
* which is what lets the rules below be shared.
|
|
22
|
+
*/
|
|
23
|
+
type HeaderReader = (name: string) => string | null | undefined;
|
|
24
|
+
declare const SERVER_TIMING_HEADER = "server-timing";
|
|
25
|
+
/**
|
|
26
|
+
* The `Server-Timing` metric name carrying a backend-minted session id to the page. A wire
|
|
27
|
+
* contract with the frontend recorder, which matches on it case-insensitively when reading
|
|
28
|
+
* `PerformanceNavigationTiming.serverTiming` (see `resolve-session-id.ts` in
|
|
29
|
+
* packages/recorder). Must be a valid HTTP token — no `.` or `:`, which is why it is not the
|
|
30
|
+
* dotted span-attribute name.
|
|
31
|
+
*/
|
|
32
|
+
declare const SERVER_TIMING_SESSION_METRIC = "metsession";
|
|
33
|
+
/**
|
|
34
|
+
* `Server-Timing` is the one response header a document's own JavaScript can read back, and
|
|
35
|
+
* the navigation entry persists for the document's lifetime — so unlike a header-sniffing
|
|
36
|
+
* approach this works no matter how late the snippet loads.
|
|
37
|
+
*/
|
|
38
|
+
declare const buildServerTimingSessionEntry: (sessionId: string) => string;
|
|
39
|
+
/**
|
|
40
|
+
* Mints an id in exactly the frontend recorder's format: `<ISO timestamp>_<nanoid>` (see
|
|
41
|
+
* `createConfig` in packages/recorder). The format is a wire contract, not cosmetic —
|
|
42
|
+
* ingestion parses the ISO prefix back out to anchor the inferred-attachment window
|
|
43
|
+
* (`parseTimestampFromFrontendSessionId` in lambda-upload-sessions), and the page uses it to
|
|
44
|
+
* reject an id stale enough to have come from a cache.
|
|
45
|
+
*/
|
|
46
|
+
declare const mintProvisionalSessionId: () => string;
|
|
47
|
+
/**
|
|
48
|
+
* Whether to mint for this inbound request. Deliberately narrow: an id nothing adopts is
|
|
49
|
+
* worse than no id at all, because a span stamped with a session that never materialises is
|
|
50
|
+
* excluded from the time-window fallback that would otherwise have caught it. So we mint only
|
|
51
|
+
* for what is plausibly a browser navigating to a page.
|
|
52
|
+
*
|
|
53
|
+
* The caller decides separately whether minting is enabled at all.
|
|
54
|
+
*/
|
|
55
|
+
declare const isProvisionalSessionIdCandidate: (method: string, getHeader: HeaderReader) => boolean;
|
|
56
|
+
//#endregion
|
|
57
|
+
export { HeaderReader, SERVER_TIMING_HEADER, SERVER_TIMING_SESSION_METRIC, buildServerTimingSessionEntry, isProvisionalSessionIdCandidate, mintProvisionalSessionId };
|
|
58
|
+
//# sourceMappingURL=provisional-session-id.d.ts.map
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
|
|
2
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="6222100c-04df-5fc9-b0f6-dcdf8a7b87ab")}catch(e){}}();
|
|
3
|
+
import "./protocol.js";
|
|
4
|
+
//#region src/provisional-session-id.ts
|
|
5
|
+
const SERVER_TIMING_HEADER = "server-timing";
|
|
6
|
+
/**
|
|
7
|
+
* The `Server-Timing` metric name carrying a backend-minted session id to the page. A wire
|
|
8
|
+
* contract with the frontend recorder, which matches on it case-insensitively when reading
|
|
9
|
+
* `PerformanceNavigationTiming.serverTiming` (see `resolve-session-id.ts` in
|
|
10
|
+
* packages/recorder). Must be a valid HTTP token — no `.` or `:`, which is why it is not the
|
|
11
|
+
* dotted span-attribute name.
|
|
12
|
+
*/
|
|
13
|
+
const SERVER_TIMING_SESSION_METRIC = "metsession";
|
|
14
|
+
/**
|
|
15
|
+
* `Server-Timing` is the one response header a document's own JavaScript can read back, and
|
|
16
|
+
* the navigation entry persists for the document's lifetime — so unlike a header-sniffing
|
|
17
|
+
* approach this works no matter how late the snippet loads.
|
|
18
|
+
*/
|
|
19
|
+
const buildServerTimingSessionEntry = (sessionId) => `${SERVER_TIMING_SESSION_METRIC};desc="${sessionId}"`;
|
|
20
|
+
/**
|
|
21
|
+
* nanoid's default alphabet and length, reproduced rather than imported: this package carries
|
|
22
|
+
* no runtime dependencies, and an id that did not look like every other session id would be a
|
|
23
|
+
* gratuitous difference in S3 keys and URLs. 64 characters divides 256 exactly, so masking a
|
|
24
|
+
* random byte with 63 is uniform — which is how nanoid itself generates them.
|
|
25
|
+
*/
|
|
26
|
+
const ID_ALPHABET = "ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW";
|
|
27
|
+
const ID_LENGTH = 21;
|
|
28
|
+
/**
|
|
29
|
+
* Mints an id in exactly the frontend recorder's format: `<ISO timestamp>_<nanoid>` (see
|
|
30
|
+
* `createConfig` in packages/recorder). The format is a wire contract, not cosmetic —
|
|
31
|
+
* ingestion parses the ISO prefix back out to anchor the inferred-attachment window
|
|
32
|
+
* (`parseTimestampFromFrontendSessionId` in lambda-upload-sessions), and the page uses it to
|
|
33
|
+
* reject an id stale enough to have come from a cache.
|
|
34
|
+
*/
|
|
35
|
+
const mintProvisionalSessionId = () => {
|
|
36
|
+
const bytes = new Uint8Array(ID_LENGTH);
|
|
37
|
+
crypto.getRandomValues(bytes);
|
|
38
|
+
let suffix = "";
|
|
39
|
+
for (const byte of bytes) suffix += ID_ALPHABET[byte & 63];
|
|
40
|
+
return `${(/* @__PURE__ */ new Date()).toISOString()}_${suffix}`;
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* Whether to mint for this inbound request. Deliberately narrow: an id nothing adopts is
|
|
44
|
+
* worse than no id at all, because a span stamped with a session that never materialises is
|
|
45
|
+
* excluded from the time-window fallback that would otherwise have caught it. So we mint only
|
|
46
|
+
* for what is plausibly a browser navigating to a page.
|
|
47
|
+
*
|
|
48
|
+
* The caller decides separately whether minting is enabled at all.
|
|
49
|
+
*/
|
|
50
|
+
const isProvisionalSessionIdCandidate = (method, getHeader) => {
|
|
51
|
+
if (getHeader("x-meticulous-session-id") != null) return false;
|
|
52
|
+
const normalizedMethod = method.toUpperCase();
|
|
53
|
+
if (normalizedMethod !== "GET" && normalizedMethod !== "HEAD") return false;
|
|
54
|
+
return isDocumentNavigation(getHeader);
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* `Sec-Fetch-Dest` is the exact signal and every current browser sends it: `document` for a
|
|
58
|
+
* navigation, `empty` for an in-page fetch (so a Next.js RSC navigation, which is a fetch, is
|
|
59
|
+
* correctly excluded), `iframe` for a subframe — excluded too, since the top frame owns the
|
|
60
|
+
* session and an iframe recorder reports into it.
|
|
61
|
+
*
|
|
62
|
+
* Absent, the caller is an older browser or not a browser at all (curl, a health check, a
|
|
63
|
+
* crawler), and `Accept` is the only hint left.
|
|
64
|
+
*/
|
|
65
|
+
const isDocumentNavigation = (getHeader) => {
|
|
66
|
+
const dest = getHeader("sec-fetch-dest");
|
|
67
|
+
if (typeof dest === "string") return dest === "document";
|
|
68
|
+
const accept = getHeader("accept");
|
|
69
|
+
return typeof accept === "string" && accept.includes("text/html");
|
|
70
|
+
};
|
|
71
|
+
//#endregion
|
|
72
|
+
export { SERVER_TIMING_HEADER, SERVER_TIMING_SESSION_METRIC, buildServerTimingSessionEntry, isProvisionalSessionIdCandidate, mintProvisionalSessionId };
|
|
73
|
+
|
|
74
|
+
//# sourceMappingURL=provisional-session-id.js.map
|
|
75
|
+
//# debugId=6222100c-04df-5fc9-b0f6-dcdf8a7b87ab
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provisional-session-id.js","sources":["../src/provisional-session-id.ts"],"sourcesContent":["import { FRONTEND_SESSION_ID_HEADER } from \"./protocol\";\n\n/**\n * A session id the *backend* mints, for the one request that can never carry one from the\n * browser: a top-level document navigation. Browsers cannot add custom headers to a\n * navigation, and on the session-starting navigation the frontend has not minted an id yet\n * (it does so only once the HTML has arrived and the snippet has run) — so the server-side\n * render's spans are recorded against no session and nothing about that traffic can be\n * replayed exactly.\n *\n * Everything here is runtime-agnostic on purpose. Both backend recorders mint the same ids\n * by the same rule and publish them under the same `Server-Timing` metric, and all three are\n * wire contracts with the page, so there is exactly one implementation — the same reason\n * kv-capture.ts lives here rather than being written twice. The Node recorder imports these\n * from the package entry; see `provisional-session-id.ts` in\n * `@alwaysmeticulous/backend-recorder-js` for the `http.IncomingMessage` adapter, and\n * `publish-session-id.ts` next door for the workerd one.\n */\n\n/**\n * Reads one request header by its lower-cased name. Both `IncomingMessage.headers[name]`\n * (after the caller flattens Node's `string | string[]`) and `Headers.get(name)` satisfy it,\n * which is what lets the rules below be shared.\n */\nexport type HeaderReader = (name: string) => string | null | undefined;\n\nexport const SERVER_TIMING_HEADER = \"server-timing\";\n\n/**\n * The `Server-Timing` metric name carrying a backend-minted session id to the page. A wire\n * contract with the frontend recorder, which matches on it case-insensitively when reading\n * `PerformanceNavigationTiming.serverTiming` (see `resolve-session-id.ts` in\n * packages/recorder). Must be a valid HTTP token — no `.` or `:`, which is why it is not the\n * dotted span-attribute name.\n */\nexport const SERVER_TIMING_SESSION_METRIC = \"metsession\";\n\n/**\n * `Server-Timing` is the one response header a document's own JavaScript can read back, and\n * the navigation entry persists for the document's lifetime — so unlike a header-sniffing\n * approach this works no matter how late the snippet loads.\n */\nexport const buildServerTimingSessionEntry = (sessionId: string): string =>\n `${SERVER_TIMING_SESSION_METRIC};desc=\"${sessionId}\"`;\n\n/**\n * nanoid's default alphabet and length, reproduced rather than imported: this package carries\n * no runtime dependencies, and an id that did not look like every other session id would be a\n * gratuitous difference in S3 keys and URLs. 64 characters divides 256 exactly, so masking a\n * random byte with 63 is uniform — which is how nanoid itself generates them.\n */\nconst ID_ALPHABET =\n \"ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW\";\nconst ID_LENGTH = 21;\n\n/**\n * Mints an id in exactly the frontend recorder's format: `<ISO timestamp>_<nanoid>` (see\n * `createConfig` in packages/recorder). The format is a wire contract, not cosmetic —\n * ingestion parses the ISO prefix back out to anchor the inferred-attachment window\n * (`parseTimestampFromFrontendSessionId` in lambda-upload-sessions), and the page uses it to\n * reject an id stale enough to have come from a cache.\n */\nexport const mintProvisionalSessionId = (): string => {\n const bytes = new Uint8Array(ID_LENGTH);\n crypto.getRandomValues(bytes);\n let suffix = \"\";\n for (const byte of bytes) {\n suffix += ID_ALPHABET[byte & 63];\n }\n return `${new Date().toISOString()}_${suffix}`;\n};\n\n/**\n * Whether to mint for this inbound request. Deliberately narrow: an id nothing adopts is\n * worse than no id at all, because a span stamped with a session that never materialises is\n * excluded from the time-window fallback that would otherwise have caught it. So we mint only\n * for what is plausibly a browser navigating to a page.\n *\n * The caller decides separately whether minting is enabled at all.\n */\nexport const isProvisionalSessionIdCandidate = (\n method: string,\n getHeader: HeaderReader,\n): boolean => {\n // A request that already names its session needs nothing from us.\n if (getHeader(FRONTEND_SESSION_ID_HEADER) != null) {\n return false;\n }\n const normalizedMethod = method.toUpperCase();\n if (normalizedMethod !== \"GET\" && normalizedMethod !== \"HEAD\") {\n return false;\n }\n return isDocumentNavigation(getHeader);\n};\n\n/**\n * `Sec-Fetch-Dest` is the exact signal and every current browser sends it: `document` for a\n * navigation, `empty` for an in-page fetch (so a Next.js RSC navigation, which is a fetch, is\n * correctly excluded), `iframe` for a subframe — excluded too, since the top frame owns the\n * session and an iframe recorder reports into it.\n *\n * Absent, the caller is an older browser or not a browser at all (curl, a health check, a\n * crawler), and `Accept` is the only hint left.\n */\nconst isDocumentNavigation = (getHeader: HeaderReader): boolean => {\n const dest = getHeader(\"sec-fetch-dest\");\n if (typeof dest === \"string\") {\n return dest === \"document\";\n }\n const accept = getHeader(\"accept\");\n return typeof accept === \"string\" && accept.includes(\"text/html\");\n};\n"],"names":[],"mappings":";;;;AA0BA,MAAa,uBAAuB;;;;;;;;AASpC,MAAa,+BAA+B;;;;;;AAO5C,MAAa,iCAAiC,cAC5C,GAAG,6BAA6B,SAAS,UAAU;;;;;;;AAQrD,MAAM,cACJ;AACF,MAAM,YAAY;;;;;;;;AASlB,MAAa,iCAAyC;CACpD,MAAM,QAAQ,IAAI,WAAW,UAAU;AACvC,QAAO,gBAAgB,MAAM;CAC7B,IAAI,SAAS;AACb,MAAK,MAAM,QAAQ,MACjB,WAAU,YAAY,OAAO;AAE/B,QAAO,oBAAG,IAAI,MAAM,EAAC,aAAa,CAAC,GAAG;;;;;;;;;;AAWxC,MAAa,mCACX,QACA,cACY;AAEZ,KAAI,UAAA,0BAAqC,IAAI,KAC3C,QAAO;CAET,MAAM,mBAAmB,OAAO,aAAa;AAC7C,KAAI,qBAAqB,SAAS,qBAAqB,OACrD,QAAO;AAET,QAAO,qBAAqB,UAAU;;;;;;;;;;;AAYxC,MAAM,wBAAwB,cAAqC;CACjE,MAAM,OAAO,UAAU,iBAAiB;AACxC,KAAI,OAAO,SAAS,SAClB,QAAO,SAAS;CAElB,MAAM,SAAS,UAAU,SAAS;AAClC,QAAO,OAAO,WAAW,YAAY,OAAO,SAAS,YAAY","debugId":"6222100c-04df-5fc9-b0f6-dcdf8a7b87ab"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
|
|
2
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f69367d2-e59d-5650-b0fe-e117c8ca00ac")}catch(e){}}();
|
|
3
|
+
import { warnOnce } from "./log.js";
|
|
4
|
+
import { hasWebSocket } from "./outbound-capture.js";
|
|
5
|
+
import { SERVER_TIMING_HEADER, buildServerTimingSessionEntry } from "./provisional-session-id.js";
|
|
6
|
+
//#region src/publish-session-id.ts
|
|
7
|
+
/**
|
|
8
|
+
* Publishes a backend-minted session id to the page on the response it is about to receive,
|
|
9
|
+
* so the frontend recorder adopts it instead of minting its own and the whole page load —
|
|
10
|
+
* server-side render included — ends up under one session id.
|
|
11
|
+
*
|
|
12
|
+
* Returns the response to send, which is not always the one passed in: a `Response` handed
|
|
13
|
+
* back by `fetch` or by an assets binding has immutable headers, and the only way to add one
|
|
14
|
+
* is to rebuild around the same body. Best-effort throughout — a recorder must never break
|
|
15
|
+
* the customer's app, so anything unexpected returns the original response unchanged.
|
|
16
|
+
*
|
|
17
|
+
* Unlike the Node recorder there is no `headersSent` race to lose: workerd flushes the
|
|
18
|
+
* response only once the handler has returned it to us, so even a streaming SSR body still
|
|
19
|
+
* has its headers in front of it at this point.
|
|
20
|
+
*/
|
|
21
|
+
const publishSessionIdOnResponse = (response, sessionId) => {
|
|
22
|
+
const entry = buildServerTimingSessionEntry(sessionId);
|
|
23
|
+
try {
|
|
24
|
+
response.headers.append(SERVER_TIMING_HEADER, entry);
|
|
25
|
+
return response;
|
|
26
|
+
} catch {}
|
|
27
|
+
try {
|
|
28
|
+
if (hasWebSocket(response) || response.status === 101) return response;
|
|
29
|
+
const rebuilt = new Response(response.body, response);
|
|
30
|
+
rebuilt.headers.append(SERVER_TIMING_HEADER, entry);
|
|
31
|
+
return rebuilt;
|
|
32
|
+
} catch (error) {
|
|
33
|
+
warnOnce("publish-session-id", "Failed to publish the backend-minted session id on the response.", error);
|
|
34
|
+
return response;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
//#endregion
|
|
38
|
+
export { publishSessionIdOnResponse };
|
|
39
|
+
|
|
40
|
+
//# sourceMappingURL=publish-session-id.js.map
|
|
41
|
+
//# debugId=f69367d2-e59d-5650-b0fe-e117c8ca00ac
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"publish-session-id.js","sources":["../src/publish-session-id.ts"],"sourcesContent":["import { warnOnce } from \"./log\";\nimport { hasWebSocket } from \"./outbound-capture\";\nimport {\n SERVER_TIMING_HEADER,\n buildServerTimingSessionEntry,\n} from \"./provisional-session-id\";\n\n/**\n * Publishes a backend-minted session id to the page on the response it is about to receive,\n * so the frontend recorder adopts it instead of minting its own and the whole page load —\n * server-side render included — ends up under one session id.\n *\n * Returns the response to send, which is not always the one passed in: a `Response` handed\n * back by `fetch` or by an assets binding has immutable headers, and the only way to add one\n * is to rebuild around the same body. Best-effort throughout — a recorder must never break\n * the customer's app, so anything unexpected returns the original response unchanged.\n *\n * Unlike the Node recorder there is no `headersSent` race to lose: workerd flushes the\n * response only once the handler has returned it to us, so even a streaming SSR body still\n * has its headers in front of it at this point.\n */\nexport const publishSessionIdOnResponse = (\n response: Response,\n sessionId: string,\n): Response => {\n const entry = buildServerTimingSessionEntry(sessionId);\n\n try {\n // Appends rather than replaces: apps publish their own server timings, and clobbering\n // them would be a visible regression in their tooling.\n response.headers.append(SERVER_TIMING_HEADER, entry);\n return response;\n } catch {\n // Immutable headers. Fall through and rebuild.\n }\n\n try {\n // A WebSocket upgrade carries the socket rather than a body and cannot survive being\n // rebuilt; it is never a document navigation either, so there is nothing to publish to.\n if (hasWebSocket(response) || response.status === 101) {\n return response;\n }\n const rebuilt = new Response(response.body, response);\n rebuilt.headers.append(SERVER_TIMING_HEADER, entry);\n return rebuilt;\n } catch (error) {\n warnOnce(\n \"publish-session-id\",\n \"Failed to publish the backend-minted session id on the response.\",\n error,\n );\n return response;\n }\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,8BACX,UACA,cACa;CACb,MAAM,QAAQ,8BAA8B,UAAU;AAEtD,KAAI;AAGF,WAAS,QAAQ,OAAO,sBAAsB,MAAM;AACpD,SAAO;SACD;AAIR,KAAI;AAGF,MAAI,aAAa,SAAS,IAAI,SAAS,WAAW,IAChD,QAAO;EAET,MAAM,UAAU,IAAI,SAAS,SAAS,MAAM,SAAS;AACrD,UAAQ,QAAQ,OAAO,sBAAsB,MAAM;AACnD,SAAO;UACA,OAAO;AACd,WACE,sBACA,oEACA,MACD;AACD,SAAO","debugId":"f69367d2-e59d-5650-b0fe-e117c8ca00ac"}
|