@nestjs/observe 0.3.25 → 0.3.27
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 +55 -2
- package/dist/agent/detached-observe-worker.js +50 -6
- package/dist/agent/observe-agent.shared-buffer.d.ts +44 -0
- package/dist/agent/observe-agent.shared-buffer.js +201 -19
- package/dist/agent/observe-agent.worker.d.ts +22 -2
- package/dist/agent/observe-agent.worker.js +43 -7
- package/dist/agent/telemetry-wire-contract.js +10 -4
- package/dist/cli/agent-notes.js +16 -4
- package/dist/cli/link.js +51 -4
- package/dist/cli/observe-cli.js +1 -19
- package/dist/cli/open-url.d.ts +27 -0
- package/dist/cli/open-url.js +63 -0
- package/dist/cli/package-manager.d.ts +6 -0
- package/dist/cli/package-manager.js +60 -3
- package/dist/cli/project-files.d.ts +62 -1
- package/dist/cli/project-files.js +229 -7
- package/dist/cli/project-setup.d.ts +6 -0
- package/dist/cli/project-setup.js +14 -1
- package/dist/cli/wire-application.js +6 -0
- package/dist/custom-metrics/counter.d.ts +13 -2
- package/dist/custom-metrics/counter.js +33 -16
- package/dist/custom-metrics/finite-value.util.d.ts +14 -0
- package/dist/custom-metrics/finite-value.util.js +33 -1
- package/dist/custom-metrics/gauge.d.ts +2 -0
- package/dist/custom-metrics/gauge.js +41 -17
- package/dist/custom-metrics/label-values.util.d.ts +37 -0
- package/dist/custom-metrics/label-values.util.js +51 -0
- package/dist/custom-metrics/summary.d.ts +23 -0
- package/dist/custom-metrics/summary.js +90 -12
- package/dist/instrument/create-instance-decorator.instrument.js +504 -116
- package/dist/instrument/raw-receiver.d.ts +6 -0
- package/dist/instrument/raw-receiver.js +32 -0
- package/dist/interfaces/observe-options.interface.d.ts +17 -6
- package/dist/objectives/objectives.registry.js +12 -0
- package/dist/observe.module.js +119 -3
- package/dist/otlp/otlp-encoders.js +22 -5
- package/dist/otlp/otlp-span.mapper.d.ts +2 -0
- package/dist/otlp/otlp-span.mapper.js +26 -4
- package/dist/otlp/otlp-trace-exporter.service.d.ts +63 -9
- package/dist/otlp/otlp-trace-exporter.service.js +295 -43
- package/dist/outgoing/http.integration.d.ts +8 -4
- package/dist/outgoing/http.integration.js +49 -17
- package/dist/outgoing/llm/llm-fetch.integration.js +62 -1
- package/dist/outgoing/llm/llm-providers.d.ts +16 -4
- package/dist/outgoing/llm/llm-providers.js +72 -22
- package/dist/outgoing/llm/llm-usage.d.ts +11 -6
- package/dist/outgoing/llm/llm-usage.js +72 -25
- package/dist/outgoing/mongodb.integration.d.ts +3 -1
- package/dist/outgoing/mongodb.integration.js +93 -18
- package/dist/outgoing/mssql.integration.js +25 -6
- package/dist/outgoing/mysql2.integration.js +17 -1
- package/dist/outgoing/outgoing-observe-agent.service.js +20 -4
- package/dist/outgoing/outgoing-span.recorder.js +17 -3
- package/dist/outgoing/pg.integration.d.ts +3 -2
- package/dist/outgoing/pg.integration.js +39 -11
- package/dist/outgoing/sql-statement.util.js +139 -21
- package/dist/outgoing/undici.integration.d.ts +13 -0
- package/dist/outgoing/undici.integration.js +68 -0
- package/dist/protocols/bull-observe-agent.service.js +23 -12
- package/dist/protocols/deferred-trace-completion.d.ts +17 -3
- package/dist/protocols/deferred-trace-completion.js +76 -9
- package/dist/protocols/graphql-observe-agent.service.d.ts +97 -6
- package/dist/protocols/graphql-observe-agent.service.js +354 -19
- package/dist/protocols/graphql-operation-parser.js +111 -26
- package/dist/protocols/http-observe-agent.service.d.ts +50 -9
- package/dist/protocols/http-observe-agent.service.js +220 -59
- package/dist/protocols/job-trace-runner.d.ts +42 -3
- package/dist/protocols/job-trace-runner.js +197 -36
- package/dist/protocols/queue-observe-agent.service.js +44 -20
- package/dist/protocols/rpc-observe-agent.service.d.ts +111 -8
- package/dist/protocols/rpc-observe-agent.service.js +332 -56
- package/dist/protocols/ws-observe-agent.service.d.ts +55 -5
- package/dist/protocols/ws-observe-agent.service.js +227 -21
- package/dist/services/index.d.ts +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/logger-patcher.service.js +16 -7
- package/dist/services/operation-trace.registry.d.ts +58 -1
- package/dist/services/operation-trace.registry.js +576 -63
- package/dist/services/stdout-forwarder.service.d.ts +69 -0
- package/dist/services/stdout-forwarder.service.js +308 -51
- package/dist/services/tracer.service.d.ts +39 -11
- package/dist/services/tracer.service.js +145 -36
- package/dist/utils/capture-request.util.d.ts +3 -1
- package/dist/utils/capture-request.util.js +128 -12
- package/dist/utils/context-accessor.util.d.ts +16 -0
- package/dist/utils/context-accessor.util.js +28 -0
- package/dist/utils/default-trace-id-generator.util.js +5 -7
- package/dist/utils/error-stack.util.d.ts +13 -0
- package/dist/utils/error-stack.util.js +166 -0
- package/dist/utils/fit-to-length.util.js +33 -10
- package/dist/utils/log-line.parser.d.ts +22 -0
- package/dist/utils/log-line.parser.js +20 -7
- package/dist/utils/log-redactor.d.ts +14 -0
- package/dist/utils/log-redactor.js +690 -65
- package/dist/utils/operation-state.util.d.ts +39 -0
- package/dist/utils/operation-state.util.js +50 -0
- package/dist/utils/redact-url-query.d.ts +37 -4
- package/dist/utils/redact-url-query.js +197 -32
- package/dist/utils/sensitive-keys.d.ts +4 -1
- package/dist/utils/sensitive-keys.js +48 -10
- package/dist/utils/shared-hook-slot.util.d.ts +48 -0
- package/dist/utils/shared-hook-slot.util.js +103 -0
- package/dist/utils/source-context.util.d.ts +14 -0
- package/dist/utils/source-context.util.js +142 -43
- package/dist/utils/source-map-resolver.util.js +33 -6
- package/dist/utils/store-copy.util.d.ts +10 -0
- package/dist/utils/store-copy.util.js +43 -0
- package/dist/utils/trace-context.util.js +21 -6
- package/package.json +2 -2
|
@@ -104,6 +104,21 @@ export function activateLlmFetchObserver(recorder, options = {}) {
|
|
|
104
104
|
}
|
|
105
105
|
};
|
|
106
106
|
}
|
|
107
|
+
/**
|
|
108
|
+
* Cancels a provider's stream once the stream handed to the caller in its
|
|
109
|
+
* place can no longer be read. undici does this for an unread response it
|
|
110
|
+
* created, but not for one whose body is locked, as the provider's is once
|
|
111
|
+
* it is read through here: a reply the application drops would otherwise
|
|
112
|
+
* hold its socket, its buffered body and its span for good.
|
|
113
|
+
*/
|
|
114
|
+
const abandonedBodies = new FinalizationRegistry((release) => {
|
|
115
|
+
try {
|
|
116
|
+
release();
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
/* thrown from here it would be an uncaught exception in the host */
|
|
120
|
+
}
|
|
121
|
+
});
|
|
107
122
|
async function observeCall(original, input, init, call) {
|
|
108
123
|
const startedAt = performance.now();
|
|
109
124
|
const holder = {};
|
|
@@ -150,6 +165,8 @@ async function observeCall(original, input, init, call) {
|
|
|
150
165
|
return;
|
|
151
166
|
}
|
|
152
167
|
tagged = true;
|
|
168
|
+
// Read to its end, failed or cancelled: nothing is left to release.
|
|
169
|
+
abandonedBodies.unregister(holder);
|
|
153
170
|
let usage = {};
|
|
154
171
|
try {
|
|
155
172
|
usage = reader.finish();
|
|
@@ -164,6 +181,21 @@ async function observeCall(original, input, init, call) {
|
|
|
164
181
|
// go on generating - and billing - a completion nobody reads.
|
|
165
182
|
const source = response.body.getReader();
|
|
166
183
|
const body = new ReadableStream({
|
|
184
|
+
start(controller) {
|
|
185
|
+
// Failed between two reads - the call's signal aborted, the
|
|
186
|
+
// connection reset: the caller hears of it now, as from plain
|
|
187
|
+
// `fetch`, not at a read that may never come. A stream piped on
|
|
188
|
+
// (`Readable.fromWeb`) stops reading while its buffer is full and
|
|
189
|
+
// waits on `closed` to hang up. A normal end or a cancel fulfils
|
|
190
|
+
// `closed`, and `error` does nothing to a stream already done.
|
|
191
|
+
// Held weakly: `source` is reachable from `abandonedBodies`, and so
|
|
192
|
+
// is what waits on it - a strong hold here would keep `body` alive.
|
|
193
|
+
const handle = new WeakRef(controller);
|
|
194
|
+
source.closed.catch((error) => {
|
|
195
|
+
finish();
|
|
196
|
+
handle.deref()?.error(error);
|
|
197
|
+
});
|
|
198
|
+
},
|
|
167
199
|
async pull(controller) {
|
|
168
200
|
let chunk;
|
|
169
201
|
try {
|
|
@@ -192,7 +224,36 @@ async function observeCall(original, input, init, call) {
|
|
|
192
224
|
return source.cancel(reason);
|
|
193
225
|
},
|
|
194
226
|
}, { highWaterMark: 0 });
|
|
195
|
-
|
|
227
|
+
let wrapped;
|
|
228
|
+
try {
|
|
229
|
+
wrapped = rewrap(response, body);
|
|
230
|
+
}
|
|
231
|
+
catch {
|
|
232
|
+
// The `Response` constructor refuses what `fetch` takes off the wire: a
|
|
233
|
+
// status past 599, a reason phrase with a control character or past
|
|
234
|
+
// Latin-1. The caller gets the reply as it came, tagged without its
|
|
235
|
+
// usage. Nothing has been read from it - `pull` runs on demand - so its
|
|
236
|
+
// body is whole once the lock is given back. Tagged first: giving the
|
|
237
|
+
// lock back rejects `closed`, which `start` above would act on.
|
|
238
|
+
tagged = true;
|
|
239
|
+
source.releaseLock();
|
|
240
|
+
tag({}, stream);
|
|
241
|
+
return response;
|
|
242
|
+
}
|
|
243
|
+
// Watching `body`, not the response: a caller that keeps only the body,
|
|
244
|
+
// or a clone, can still read it. Nothing registered may reach `body`, or
|
|
245
|
+
// it would never be collected.
|
|
246
|
+
abandonedBodies.register(body, () => {
|
|
247
|
+
try {
|
|
248
|
+
finish();
|
|
249
|
+
}
|
|
250
|
+
finally {
|
|
251
|
+
source
|
|
252
|
+
.cancel("Response object has been garbage collected")
|
|
253
|
+
.catch(() => undefined);
|
|
254
|
+
}
|
|
255
|
+
}, holder);
|
|
256
|
+
return wrapped;
|
|
196
257
|
}
|
|
197
258
|
/** The same response, reading through `body`. */
|
|
198
259
|
function rewrap(response, body) {
|
|
@@ -8,13 +8,25 @@
|
|
|
8
8
|
*/
|
|
9
9
|
/** The provider a call to `host` goes to, or undefined when it is not one. */
|
|
10
10
|
export declare function llmProviderForHost(host: string, extraHosts?: ReadonlySet<string>): string | undefined;
|
|
11
|
+
/**
|
|
12
|
+
* The `model` of the outermost object of a JSON document, or of as much of
|
|
13
|
+
* one as `text` holds - and nothing for text that does not open with `{`.
|
|
14
|
+
*
|
|
15
|
+
* A scan rather than `JSON.parse`, which a cut-off document would fail, and
|
|
16
|
+
* rather than a search for `"model":`, which finds that key at any depth: a
|
|
17
|
+
* tool call's input, a tool result or a JSON-mode completion can carry one,
|
|
18
|
+
* and what it holds is the prompt's, not the model's. Strings are skipped
|
|
19
|
+
* whole, so a brace or a key inside one counts for nothing. Linear, and done
|
|
20
|
+
* at the first `model` key of the outermost object - where clients put it.
|
|
21
|
+
*/
|
|
22
|
+
export declare function topLevelModel(text: string): string | undefined;
|
|
11
23
|
/**
|
|
12
24
|
* The model a JSON request body names, read from its first 64 KB.
|
|
13
25
|
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
26
|
+
* Read with `topLevelModel`: the body is the application's prompt, often far
|
|
27
|
+
* larger than the one field wanted, and every client puts `model` near the
|
|
28
|
+
* top. Bodies that are streams or forms are not read at all - reading them
|
|
29
|
+
* would consume what the request is about to send.
|
|
18
30
|
*/
|
|
19
31
|
export declare function modelFromRequestBody(body: unknown): string | undefined;
|
|
20
32
|
/**
|
|
@@ -6,21 +6,25 @@
|
|
|
6
6
|
* SDK, LangChain and a hand-written `fetch` all end in the same request to the
|
|
7
7
|
* same host, so a host list covers every client without knowing any of them.
|
|
8
8
|
*/
|
|
9
|
-
/**
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
"api.
|
|
16
|
-
"
|
|
17
|
-
"
|
|
18
|
-
"api.
|
|
19
|
-
"api.
|
|
20
|
-
"
|
|
21
|
-
"api.
|
|
22
|
-
"api.
|
|
23
|
-
|
|
9
|
+
/**
|
|
10
|
+
* Exact hosts, each with the provider name the dashboard groups by. A `Map`,
|
|
11
|
+
* not an object literal: looked up by the host of any outgoing call, and a
|
|
12
|
+
* host spelt `constructor` or `__proto__` found an inherited member there.
|
|
13
|
+
*/
|
|
14
|
+
const EXACT_HOSTS = new Map([
|
|
15
|
+
["api.openai.com", "openai"],
|
|
16
|
+
["api.anthropic.com", "anthropic"],
|
|
17
|
+
["generativelanguage.googleapis.com", "google"],
|
|
18
|
+
["api.mistral.ai", "mistral"],
|
|
19
|
+
["api.groq.com", "groq"],
|
|
20
|
+
["openrouter.ai", "openrouter"],
|
|
21
|
+
["api.together.xyz", "together"],
|
|
22
|
+
["api.deepseek.com", "deepseek"],
|
|
23
|
+
["api.x.ai", "xai"],
|
|
24
|
+
["api.cohere.ai", "cohere"],
|
|
25
|
+
["api.cohere.com", "cohere"],
|
|
26
|
+
["api.perplexity.ai", "perplexity"],
|
|
27
|
+
]);
|
|
24
28
|
/** Hosts that carry a tenant or a region in a subdomain. */
|
|
25
29
|
const HOST_PATTERNS = [
|
|
26
30
|
[/^[a-z0-9-]+\.openai\.azure\.com$/, "azure-openai"],
|
|
@@ -32,7 +36,7 @@ const HOST_PATTERNS = [
|
|
|
32
36
|
export function llmProviderForHost(host, extraHosts = new Set()) {
|
|
33
37
|
const normalized = host.toLowerCase();
|
|
34
38
|
const hostname = normalized.replace(/:\d+$/, "");
|
|
35
|
-
const exact = EXACT_HOSTS
|
|
39
|
+
const exact = EXACT_HOSTS.get(hostname);
|
|
36
40
|
if (exact) {
|
|
37
41
|
return exact;
|
|
38
42
|
}
|
|
@@ -48,14 +52,60 @@ export function llmProviderForHost(host, extraHosts = new Set()) {
|
|
|
48
52
|
}
|
|
49
53
|
/** Most of a request body read for its `model` field. Prompts can be megabytes. */
|
|
50
54
|
const MODEL_SCAN_BYTES = 64 * 1024;
|
|
51
|
-
|
|
55
|
+
/** What follows a `"model"` key: the value, when it is a short string. */
|
|
56
|
+
const MODEL_VALUE = /\s*:\s*"([^"\\]{1,128})"/y;
|
|
57
|
+
/**
|
|
58
|
+
* The `model` of the outermost object of a JSON document, or of as much of
|
|
59
|
+
* one as `text` holds - and nothing for text that does not open with `{`.
|
|
60
|
+
*
|
|
61
|
+
* A scan rather than `JSON.parse`, which a cut-off document would fail, and
|
|
62
|
+
* rather than a search for `"model":`, which finds that key at any depth: a
|
|
63
|
+
* tool call's input, a tool result or a JSON-mode completion can carry one,
|
|
64
|
+
* and what it holds is the prompt's, not the model's. Strings are skipped
|
|
65
|
+
* whole, so a brace or a key inside one counts for nothing. Linear, and done
|
|
66
|
+
* at the first `model` key of the outermost object - where clients put it.
|
|
67
|
+
*/
|
|
68
|
+
export function topLevelModel(text) {
|
|
69
|
+
let index = text.search(/\S/);
|
|
70
|
+
if (index === -1 || text[index] !== "{") {
|
|
71
|
+
return undefined;
|
|
72
|
+
}
|
|
73
|
+
let depth = 0;
|
|
74
|
+
for (; index < text.length; index++) {
|
|
75
|
+
const char = text[index];
|
|
76
|
+
if (char === '"') {
|
|
77
|
+
const start = index;
|
|
78
|
+
for (index++; index < text.length && text[index] !== '"'; index++) {
|
|
79
|
+
if (text[index] === "\\") {
|
|
80
|
+
index++;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
if (depth === 1 &&
|
|
84
|
+
index - start === 6 &&
|
|
85
|
+
text.startsWith('"model"', start)) {
|
|
86
|
+
MODEL_VALUE.lastIndex = index + 1;
|
|
87
|
+
const value = MODEL_VALUE.exec(text);
|
|
88
|
+
if (value) {
|
|
89
|
+
return value[1];
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
else if (char === "{" || char === "[") {
|
|
94
|
+
depth++;
|
|
95
|
+
}
|
|
96
|
+
else if ((char === "}" || char === "]") && --depth === 0) {
|
|
97
|
+
return undefined;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return undefined;
|
|
101
|
+
}
|
|
52
102
|
/**
|
|
53
103
|
* The model a JSON request body names, read from its first 64 KB.
|
|
54
104
|
*
|
|
55
|
-
*
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
105
|
+
* Read with `topLevelModel`: the body is the application's prompt, often far
|
|
106
|
+
* larger than the one field wanted, and every client puts `model` near the
|
|
107
|
+
* top. Bodies that are streams or forms are not read at all - reading them
|
|
108
|
+
* would consume what the request is about to send.
|
|
59
109
|
*/
|
|
60
110
|
export function modelFromRequestBody(body) {
|
|
61
111
|
let text;
|
|
@@ -68,7 +118,7 @@ export function modelFromRequestBody(body) {
|
|
|
68
118
|
else if (body instanceof ArrayBuffer) {
|
|
69
119
|
text = new TextDecoder().decode(new Uint8Array(body, 0, Math.min(body.byteLength, MODEL_SCAN_BYTES)));
|
|
70
120
|
}
|
|
71
|
-
return text ?
|
|
121
|
+
return text ? topLevelModel(text) : undefined;
|
|
72
122
|
}
|
|
73
123
|
/**
|
|
74
124
|
* The model a URL names, for the providers that put it in the path rather
|
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Reading token usage out of a model provider's response - a JSON body, or
|
|
3
|
-
* the events of a server-sent stream - without ever keeping its text.
|
|
4
|
-
*/
|
|
5
1
|
/** What one call consumed, as far as the response said. */
|
|
6
2
|
export interface LlmUsage {
|
|
7
3
|
/** The model that answered - more precise than the one asked for. */
|
|
@@ -35,10 +31,14 @@ export declare function usageFromDocument(document: unknown): LlmUsage;
|
|
|
35
31
|
* A larger body - a long completion, a batch of embeddings - is not kept: its
|
|
36
32
|
* first and last 32 KB are, and the usage is matched out of those. Every
|
|
37
33
|
* provider writes `usage` after the content and `model` before it.
|
|
34
|
+
*
|
|
35
|
+
* The bytes are copied, not the chunks kept: a chunk object costs a few
|
|
36
|
+
* hundred bytes of heap whatever it holds, and the sender decides how the
|
|
37
|
+
* body is cut - one byte at a time, a 2 MB body would be held a hundred
|
|
38
|
+
* times over.
|
|
38
39
|
*/
|
|
39
40
|
export declare class JsonUsageReader {
|
|
40
|
-
private
|
|
41
|
-
private size;
|
|
41
|
+
private body;
|
|
42
42
|
private head;
|
|
43
43
|
private tail;
|
|
44
44
|
push(chunk: Uint8Array): void;
|
|
@@ -50,6 +50,11 @@ export declare class JsonUsageReader {
|
|
|
50
50
|
* Only `data:` lines that can carry usage or a model are parsed - the first
|
|
51
51
|
* event, and any that mention `usage` - so a long stream of text deltas costs
|
|
52
52
|
* a substring search per line rather than a parse.
|
|
53
|
+
*
|
|
54
|
+
* A line still arriving is held as bytes, copied, and decoded once it is
|
|
55
|
+
* whole: grown a chunk at a time as a string, a line sent a byte at a time
|
|
56
|
+
* would be a million string objects. A line feed is never part of another
|
|
57
|
+
* UTF-8 character, so the bytes split into lines as the text does.
|
|
53
58
|
*/
|
|
54
59
|
export declare class SseUsageReader {
|
|
55
60
|
private readonly now;
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* Reading token usage out of a model provider's response - a JSON body, or
|
|
3
3
|
* the events of a server-sent stream - without ever keeping its text.
|
|
4
4
|
*/
|
|
5
|
+
import { topLevelModel } from "./llm-providers.js";
|
|
5
6
|
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
6
7
|
const count = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0
|
|
7
8
|
? Math.round(value)
|
|
@@ -103,10 +104,14 @@ const EDGE_BYTES = 32 * 1024;
|
|
|
103
104
|
* A larger body - a long completion, a batch of embeddings - is not kept: its
|
|
104
105
|
* first and last 32 KB are, and the usage is matched out of those. Every
|
|
105
106
|
* provider writes `usage` after the content and `model` before it.
|
|
107
|
+
*
|
|
108
|
+
* The bytes are copied, not the chunks kept: a chunk object costs a few
|
|
109
|
+
* hundred bytes of heap whatever it holds, and the sender decides how the
|
|
110
|
+
* body is cut - one byte at a time, a 2 MB body would be held a hundred
|
|
111
|
+
* times over.
|
|
106
112
|
*/
|
|
107
113
|
export class JsonUsageReader {
|
|
108
|
-
|
|
109
|
-
size = 0;
|
|
114
|
+
body = new Bytes(MAX_JSON_BYTES);
|
|
110
115
|
head;
|
|
111
116
|
tail;
|
|
112
117
|
push(chunk) {
|
|
@@ -114,20 +119,23 @@ export class JsonUsageReader {
|
|
|
114
119
|
this.tail = keepTail(this.tail, chunk, EDGE_BYTES);
|
|
115
120
|
return;
|
|
116
121
|
}
|
|
117
|
-
this.
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
const whole = concat(this.chunks, this.size);
|
|
121
|
-
this.head = whole.subarray(0, EDGE_BYTES);
|
|
122
|
-
this.tail = whole.subarray(whole.byteLength - EDGE_BYTES);
|
|
123
|
-
this.chunks.length = 0;
|
|
122
|
+
if (this.body.size + chunk.byteLength <= MAX_JSON_BYTES) {
|
|
123
|
+
this.body.append(chunk);
|
|
124
|
+
return;
|
|
124
125
|
}
|
|
126
|
+
const kept = this.body.view();
|
|
127
|
+
this.head =
|
|
128
|
+
kept.byteLength >= EDGE_BYTES
|
|
129
|
+
? kept.slice(0, EDGE_BYTES)
|
|
130
|
+
: concat([kept, chunk.subarray(0, EDGE_BYTES - kept.byteLength)], Math.min(EDGE_BYTES, kept.byteLength + chunk.byteLength));
|
|
131
|
+
this.tail = keepTail(kept, chunk, EDGE_BYTES);
|
|
132
|
+
this.body = new Bytes(0);
|
|
125
133
|
}
|
|
126
134
|
finish() {
|
|
127
135
|
const decoder = new TextDecoder();
|
|
128
136
|
if (!this.head) {
|
|
129
137
|
try {
|
|
130
|
-
return usageFromDocument(JSON.parse(decoder.decode(
|
|
138
|
+
return usageFromDocument(JSON.parse(decoder.decode(this.body.view())));
|
|
131
139
|
}
|
|
132
140
|
catch {
|
|
133
141
|
return {};
|
|
@@ -157,10 +165,10 @@ function usageFromEdges(head, tail) {
|
|
|
157
165
|
if (cached && usage.cachedInputTokens === undefined) {
|
|
158
166
|
usage.cachedInputTokens = Number(cached[1]);
|
|
159
167
|
}
|
|
160
|
-
const model =
|
|
168
|
+
const model = topLevelModel(head);
|
|
161
169
|
return { ...usage, ...(model ? { model } : {}) };
|
|
162
170
|
}
|
|
163
|
-
/** Longest stream line examined. Longer lines carry content, not usage. */
|
|
171
|
+
/** Longest stream line examined, in bytes. Longer lines carry content, not usage. */
|
|
164
172
|
const MAX_SSE_LINE = 1024 * 1024;
|
|
165
173
|
/**
|
|
166
174
|
* Reads a server-sent event stream as it passes through, one line at a time.
|
|
@@ -168,11 +176,16 @@ const MAX_SSE_LINE = 1024 * 1024;
|
|
|
168
176
|
* Only `data:` lines that can carry usage or a model are parsed - the first
|
|
169
177
|
* event, and any that mention `usage` - so a long stream of text deltas costs
|
|
170
178
|
* a substring search per line rather than a parse.
|
|
179
|
+
*
|
|
180
|
+
* A line still arriving is held as bytes, copied, and decoded once it is
|
|
181
|
+
* whole: grown a chunk at a time as a string, a line sent a byte at a time
|
|
182
|
+
* would be a million string objects. A line feed is never part of another
|
|
183
|
+
* UTF-8 character, so the bytes split into lines as the text does.
|
|
171
184
|
*/
|
|
172
185
|
export class SseUsageReader {
|
|
173
186
|
now;
|
|
174
187
|
decoder = new TextDecoder();
|
|
175
|
-
pending =
|
|
188
|
+
pending = new Bytes(MAX_SSE_LINE);
|
|
176
189
|
skipping = false;
|
|
177
190
|
usage = {};
|
|
178
191
|
sawEvent = false;
|
|
@@ -182,10 +195,9 @@ export class SseUsageReader {
|
|
|
182
195
|
this.now = now;
|
|
183
196
|
}
|
|
184
197
|
push(chunk) {
|
|
185
|
-
const text = this.decoder.decode(chunk, { stream: true });
|
|
186
198
|
let start = 0;
|
|
187
199
|
for (;;) {
|
|
188
|
-
const newline =
|
|
200
|
+
const newline = chunk.indexOf(0x0a, start);
|
|
189
201
|
if (newline === -1) {
|
|
190
202
|
break;
|
|
191
203
|
}
|
|
@@ -193,29 +205,32 @@ export class SseUsageReader {
|
|
|
193
205
|
// The oversized line ends here, unread.
|
|
194
206
|
this.skipping = false;
|
|
195
207
|
}
|
|
208
|
+
else if (this.pending.size === 0) {
|
|
209
|
+
this.line(this.decoder.decode(chunk.subarray(start, newline)));
|
|
210
|
+
}
|
|
196
211
|
else {
|
|
197
|
-
this.
|
|
212
|
+
this.pending.append(chunk.subarray(start, newline));
|
|
213
|
+
this.line(this.decoder.decode(this.pending.view()));
|
|
198
214
|
}
|
|
199
|
-
this.pending
|
|
215
|
+
this.pending.clear();
|
|
200
216
|
start = newline + 1;
|
|
201
217
|
}
|
|
202
|
-
if (this.skipping) {
|
|
218
|
+
if (this.skipping || start === chunk.byteLength) {
|
|
203
219
|
return;
|
|
204
220
|
}
|
|
205
|
-
|
|
206
|
-
if (this.pending.length + rest.length > MAX_SSE_LINE) {
|
|
221
|
+
if (this.pending.size + chunk.byteLength - start > MAX_SSE_LINE) {
|
|
207
222
|
// An oversized line is content; drop it until its end comes past.
|
|
208
|
-
this.pending
|
|
223
|
+
this.pending.clear();
|
|
209
224
|
this.skipping = true;
|
|
210
225
|
return;
|
|
211
226
|
}
|
|
212
|
-
this.pending
|
|
227
|
+
this.pending.append(chunk.subarray(start));
|
|
213
228
|
}
|
|
214
229
|
finish() {
|
|
215
|
-
if (this.pending) {
|
|
216
|
-
this.line(this.pending);
|
|
217
|
-
this.pending = "";
|
|
230
|
+
if (this.pending.size > 0 && !this.skipping) {
|
|
231
|
+
this.line(this.decoder.decode(this.pending.view()));
|
|
218
232
|
}
|
|
233
|
+
this.pending.clear();
|
|
219
234
|
return this.usage;
|
|
220
235
|
}
|
|
221
236
|
line(raw) {
|
|
@@ -241,6 +256,38 @@ export class SseUsageReader {
|
|
|
241
256
|
}
|
|
242
257
|
}
|
|
243
258
|
}
|
|
259
|
+
/**
|
|
260
|
+
* Bytes copied in as they arrive, into one buffer that doubles as it fills -
|
|
261
|
+
* up to `expected`, past it only as far as is needed.
|
|
262
|
+
*/
|
|
263
|
+
class Bytes {
|
|
264
|
+
expected;
|
|
265
|
+
buffer = new Uint8Array(0);
|
|
266
|
+
size = 0;
|
|
267
|
+
constructor(expected) {
|
|
268
|
+
this.expected = expected;
|
|
269
|
+
}
|
|
270
|
+
append(chunk) {
|
|
271
|
+
const needed = this.size + chunk.byteLength;
|
|
272
|
+
if (needed > this.buffer.byteLength) {
|
|
273
|
+
const grown = new Uint8Array(Math.max(needed, Math.min(Math.max(this.buffer.byteLength * 2, 1024), this.expected)));
|
|
274
|
+
grown.set(this.view());
|
|
275
|
+
this.buffer = grown;
|
|
276
|
+
}
|
|
277
|
+
this.buffer.set(chunk, this.size);
|
|
278
|
+
this.size = needed;
|
|
279
|
+
}
|
|
280
|
+
view() {
|
|
281
|
+
return this.buffer.subarray(0, this.size);
|
|
282
|
+
}
|
|
283
|
+
/** Empties it, and lets a large buffer go rather than keep it for later. */
|
|
284
|
+
clear() {
|
|
285
|
+
this.size = 0;
|
|
286
|
+
if (this.buffer.byteLength > 64 * 1024) {
|
|
287
|
+
this.buffer = new Uint8Array(0);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
244
291
|
function concat(chunks, size) {
|
|
245
292
|
const whole = new Uint8Array(size);
|
|
246
293
|
let offset = 0;
|
|
@@ -6,7 +6,9 @@ interface MongoConnectionModule {
|
|
|
6
6
|
}
|
|
7
7
|
/**
|
|
8
8
|
* A command with its values removed: field names and operators stay, since
|
|
9
|
-
* they are the query's shape, and every primitive becomes `?`.
|
|
9
|
+
* they are the query's shape, and every primitive becomes `?`. The one value
|
|
10
|
+
* kept is the collection a command names, which is to a command what the
|
|
11
|
+
* table is to a SQL statement.
|
|
10
12
|
*
|
|
11
13
|
* Arrays come in two kinds and are told apart by what they hold. A list of
|
|
12
14
|
* values keeps one element - `$in: [1, 2, 3]` and `$in: [4]` are the same
|
|
@@ -24,9 +24,49 @@ const DRIVER_HOUSEKEEPING = new Set([
|
|
|
24
24
|
"endSessions",
|
|
25
25
|
"killCursors",
|
|
26
26
|
]);
|
|
27
|
+
/**
|
|
28
|
+
* Commands whose first value is the collection, or the namespace, they act
|
|
29
|
+
* on: what the driver builds for a collection's own methods, and the
|
|
30
|
+
* collection commands an application sends through `db.command()`. Only these
|
|
31
|
+
* keep that value. Anywhere else it is data like any other - the user of
|
|
32
|
+
* `createUser`, `dropUser` and `usersInfo`, the role of `createRole`, the free
|
|
33
|
+
* text of `logApplicationMessage`. A command missing from the list loses its
|
|
34
|
+
* collection from the span, and nothing else.
|
|
35
|
+
*/
|
|
36
|
+
const NAMES_A_COLLECTION = new Set([
|
|
37
|
+
"find",
|
|
38
|
+
"insert",
|
|
39
|
+
"update",
|
|
40
|
+
"delete",
|
|
41
|
+
"aggregate",
|
|
42
|
+
"count",
|
|
43
|
+
"distinct",
|
|
44
|
+
"findAndModify",
|
|
45
|
+
"findandmodify",
|
|
46
|
+
"mapReduce",
|
|
47
|
+
"mapreduce",
|
|
48
|
+
"create",
|
|
49
|
+
"drop",
|
|
50
|
+
"renameCollection",
|
|
51
|
+
"collMod",
|
|
52
|
+
"collStats",
|
|
53
|
+
"validate",
|
|
54
|
+
"compact",
|
|
55
|
+
"reIndex",
|
|
56
|
+
"convertToCapped",
|
|
57
|
+
"cloneCollectionAsCapped",
|
|
58
|
+
"createIndexes",
|
|
59
|
+
"dropIndexes",
|
|
60
|
+
"listIndexes",
|
|
61
|
+
"createSearchIndexes",
|
|
62
|
+
"updateSearchIndex",
|
|
63
|
+
"dropSearchIndex",
|
|
64
|
+
]);
|
|
27
65
|
/**
|
|
28
66
|
* A command with its values removed: field names and operators stay, since
|
|
29
|
-
* they are the query's shape, and every primitive becomes `?`.
|
|
67
|
+
* they are the query's shape, and every primitive becomes `?`. The one value
|
|
68
|
+
* kept is the collection a command names, which is to a command what the
|
|
69
|
+
* table is to a SQL statement.
|
|
30
70
|
*
|
|
31
71
|
* Arrays come in two kinds and are told apart by what they hold. A list of
|
|
32
72
|
* values keeps one element - `$in: [1, 2, 3]` and `$in: [4]` are the same
|
|
@@ -36,13 +76,33 @@ const DRIVER_HOUSEKEEPING = new Set([
|
|
|
36
76
|
*/
|
|
37
77
|
export function describeMongoCommand(command) {
|
|
38
78
|
const [name] = Object.keys(command);
|
|
39
|
-
const target = name
|
|
79
|
+
const target = name !== undefined && NAMES_A_COLLECTION.has(name)
|
|
80
|
+
? command[name]
|
|
81
|
+
: undefined;
|
|
40
82
|
const operation = name === undefined
|
|
41
83
|
? "command"
|
|
42
84
|
: typeof target === "string"
|
|
43
85
|
? `${name} ${target}`
|
|
44
86
|
: name;
|
|
87
|
+
// What is left of the statement to write. A command is the application's
|
|
88
|
+
// data, and often its client's: a document that refers to one sub-document
|
|
89
|
+
// from many fields - a GraphQL variable used many times over, a YAML alias -
|
|
90
|
+
// is small to hold and has no end when copied out as a tree, and the
|
|
91
|
+
// command is described before the driver's size limit can refuse it. Every
|
|
92
|
+
// value is charged one character and every field its name, never more than
|
|
93
|
+
// they take up once written, so by the time the budget is spent the walk is
|
|
94
|
+
// past the cut below and the statement is what it would have been.
|
|
95
|
+
let budget = MAX_STATEMENT_LENGTH;
|
|
96
|
+
// Telling a list of values from a list of documents means looking at every
|
|
97
|
+
// element, which the budget cannot charge for: a list of values is one `?`
|
|
98
|
+
// however long it is. So each array is looked through once, and the fields
|
|
99
|
+
// that refer to it again are answered from here.
|
|
100
|
+
const documentsOf = new Map();
|
|
45
101
|
const scrub = (value, depth) => {
|
|
102
|
+
budget -= 1;
|
|
103
|
+
if (budget <= 0) {
|
|
104
|
+
return "?";
|
|
105
|
+
}
|
|
46
106
|
if (value === null || typeof value !== "object") {
|
|
47
107
|
return "?";
|
|
48
108
|
}
|
|
@@ -50,7 +110,11 @@ export function describeMongoCommand(command) {
|
|
|
50
110
|
return "?";
|
|
51
111
|
}
|
|
52
112
|
if (Array.isArray(value)) {
|
|
53
|
-
|
|
113
|
+
let documents = documentsOf.get(value);
|
|
114
|
+
if (documents === undefined) {
|
|
115
|
+
documents = value.filter((item) => item !== null && typeof item === "object");
|
|
116
|
+
documentsOf.set(value, documents);
|
|
117
|
+
}
|
|
54
118
|
if (documents.length === 0) {
|
|
55
119
|
return value.length === 0 ? [] : ["?"];
|
|
56
120
|
}
|
|
@@ -63,21 +127,10 @@ export function describeMongoCommand(command) {
|
|
|
63
127
|
if (proto !== Object.prototype && proto !== null) {
|
|
64
128
|
return "?";
|
|
65
129
|
}
|
|
66
|
-
|
|
67
|
-
for (const [key, item] of Object.entries(value)) {
|
|
68
|
-
out[key] = scrub(item, depth + 1);
|
|
69
|
-
}
|
|
70
|
-
return out;
|
|
130
|
+
return fields(Object.entries(value), (item) => scrub(item, depth + 1));
|
|
71
131
|
};
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
// Session, cluster time and read preference: driver bookkeeping.
|
|
75
|
-
if (key === "lsid" || key.startsWith("$")) {
|
|
76
|
-
continue;
|
|
77
|
-
}
|
|
78
|
-
shape[key] =
|
|
79
|
-
key === name && typeof value === "string" ? value : scrub(value, 0);
|
|
80
|
-
}
|
|
132
|
+
// Session, cluster time and read preference: driver bookkeeping.
|
|
133
|
+
const shape = fields(Object.entries(command).filter(([key]) => key !== "lsid" && !key.startsWith("$")), (value, key) => key === name && typeof target === "string" ? target : scrub(value, 0));
|
|
81
134
|
let statement;
|
|
82
135
|
try {
|
|
83
136
|
statement = JSON.stringify(shape).slice(0, MAX_STATEMENT_LENGTH);
|
|
@@ -86,6 +139,24 @@ export function describeMongoCommand(command) {
|
|
|
86
139
|
statement = operation;
|
|
87
140
|
}
|
|
88
141
|
return { operation, statement };
|
|
142
|
+
/**
|
|
143
|
+
* The fields of a document, described one by one until the budget is spent.
|
|
144
|
+
* Defined, not assigned: the names are the application's data, and
|
|
145
|
+
* assigning one called `__proto__` or `constructor` reaches
|
|
146
|
+
* `Object.prototype` instead of making a field - an accessor that throws
|
|
147
|
+
* under `--disable-proto=throw`, a read-only property once it is frozen.
|
|
148
|
+
*/
|
|
149
|
+
function fields(entries, describe) {
|
|
150
|
+
const described = [];
|
|
151
|
+
for (const [key, value] of entries) {
|
|
152
|
+
if (budget <= 0) {
|
|
153
|
+
break;
|
|
154
|
+
}
|
|
155
|
+
budget -= key.length;
|
|
156
|
+
described.push([key, describe(value, key)]);
|
|
157
|
+
}
|
|
158
|
+
return Object.fromEntries(described);
|
|
159
|
+
}
|
|
89
160
|
}
|
|
90
161
|
/**
|
|
91
162
|
* Command spans for the `mongodb` driver, and so for Mongoose and the Mongo
|
|
@@ -110,7 +181,11 @@ export function patchMongodb(connectionModule, recorder) {
|
|
|
110
181
|
return original.apply(this, args);
|
|
111
182
|
}
|
|
112
183
|
const [commandName] = Object.keys(command);
|
|
113
|
-
|
|
184
|
+
// Asked before the command is described: an untraced or sampled-out
|
|
185
|
+
// call should not pay for a description nobody will read.
|
|
186
|
+
if (commandName === undefined ||
|
|
187
|
+
DRIVER_HOUSEKEEPING.has(commandName) ||
|
|
188
|
+
!recorder.isRecording()) {
|
|
114
189
|
return original.apply(this, args);
|
|
115
190
|
}
|
|
116
191
|
const { operation, statement } = describeMongoCommand(command);
|