@softistx/telemetry-mongo 0.0.0-stage → 0.3.4
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/LICENSE +21 -0
- package/README.md +193 -2
- package/dist/attributes/db.d.ts +41 -0
- package/dist/attributes/db.d.ts.map +1 -0
- package/dist/export/documents.d.ts +33 -0
- package/dist/export/documents.d.ts.map +1 -0
- package/dist/export/mongo.d.ts +57 -0
- package/dist/export/mongo.d.ts.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +298 -0
- package/dist/index.js.map +14 -0
- package/dist/instrument/commands.d.ts +63 -0
- package/dist/instrument/commands.d.ts.map +1 -0
- package/dist/instrument/record.d.ts +28 -0
- package/dist/instrument/record.d.ts.map +1 -0
- package/package.json +71 -5
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Steve Tsala
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,194 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @softistx/telemetry-mongo
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
MongoDB for [`@softistx/telemetry`](https://www.npmjs.com/package/@softistx/telemetry),
|
|
4
|
+
two ways round: an **exporter** that stores signals in a collection, and an
|
|
5
|
+
**instrumentation** that turns every command the driver sends into a client
|
|
6
|
+
span.
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
bun add @softistx/telemetry @softistx/telemetry-mongo mongodb
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
The two are independent. Take the exporter if you already run Mongo and do not
|
|
13
|
+
want a collector; take the instrumentation whatever you export to.
|
|
14
|
+
|
|
15
|
+
## The exporter
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { createTelemetry } from '@softistx/telemetry';
|
|
19
|
+
import { mongoExporter } from '@softistx/telemetry-mongo';
|
|
20
|
+
|
|
21
|
+
createTelemetry('checkout', {
|
|
22
|
+
exporters: [mongoExporter({ db })],
|
|
23
|
+
}).install();
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
One document per signal, in `telemetry`. The documents **are** the signals, so
|
|
27
|
+
there is no query language to learn:
|
|
28
|
+
|
|
29
|
+
```js
|
|
30
|
+
db.telemetry.find({ traceId: '4bf92f3577b34da6a3ce929d0e0e4736' }).sort({ at: 1 })
|
|
31
|
+
db.telemetry.find({ type: 'span', status: 'error', at: { $gte: ISODate('…') } })
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Four things are changed on the way in, and nothing else:
|
|
35
|
+
|
|
36
|
+
| | |
|
|
37
|
+
| --- | --- |
|
|
38
|
+
| every instant | a BSON `Date` — an epoch number is neither a range nor expirable |
|
|
39
|
+
| the resource | stamped on each document: `service`, `version`, `environment`, and its attributes under `resource` |
|
|
40
|
+
| `traceId`, `spanId` | lifted to the top level — they live at `span.traceId` on a log and `context.traceId` on a span, so the query above would otherwise need an `$or` over two paths and an index on each |
|
|
41
|
+
| `at` | on **both** kinds. A span carries its start, so one index covers both |
|
|
42
|
+
|
|
43
|
+
The last one is why a TTL index works at all, and the second is why it is worth
|
|
44
|
+
it: a collection here is shared by every service that writes to it, which is the
|
|
45
|
+
opposite of a log file.
|
|
46
|
+
|
|
47
|
+
### Retention is an index
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
mongoExporter({ db, retention: 7 * 24 * 60 * 60 * 1000 }) // a week
|
|
51
|
+
mongoExporter({ db, retention: false }) // keep everything
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Default 30 days. The TTL index is created on the first batch and **recreated
|
|
55
|
+
when the value changes** — Mongo answers `IndexOptionsConflict` rather than
|
|
56
|
+
adopting a new `expireAfterSeconds`, so changing it means dropping and making
|
|
57
|
+
it again. The index has a fixed name, `nxgt_telemetry_retention`, which is what
|
|
58
|
+
makes it recognisable; nothing else should use that name. `retention: false`
|
|
59
|
+
removes an index an earlier configuration left behind.
|
|
60
|
+
|
|
61
|
+
### Its own pool, or yours
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
mongoExporter({ db }) // yours
|
|
65
|
+
mongoExporter({ uri: 'mongodb://…', database: 'obs' }) // its own
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
The compiler refuses both at once. A `db` you pass is **never closed** — it is
|
|
69
|
+
yours, and this is one of several things using it. The `uri` form opens its own
|
|
70
|
+
pool and closes it on `close()`, so a burst of telemetry cannot starve the
|
|
71
|
+
connections your application's queries need.
|
|
72
|
+
|
|
73
|
+
## The instrumentation
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
import { MongoClient } from 'mongodb';
|
|
77
|
+
import { instrumentMongo } from '@softistx/telemetry-mongo';
|
|
78
|
+
|
|
79
|
+
const client = new MongoClient(uri, { monitorCommands: true });
|
|
80
|
+
const stop = instrumentMongo(client);
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
**`monitorCommands: true` is required**, and cannot be turned on from here: it
|
|
84
|
+
is a connection option, read when the client is built. Without it the driver
|
|
85
|
+
emits nothing and this is silently inert. It is the first thing to check when
|
|
86
|
+
no spans appear.
|
|
87
|
+
|
|
88
|
+
It listens to the driver's **public** command monitoring. Nothing is patched,
|
|
89
|
+
which is what makes it work under Bun — `require-in-the-middle`, what the
|
|
90
|
+
OpenTelemetry auto-instrumentations hook with, does not.
|
|
91
|
+
|
|
92
|
+
With mongoose, reach the client through the connection:
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
instrumentMongo(mongoose.connection.getClient());
|
|
96
|
+
// mongoose.connect(uri, { monitorCommands: true })
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### What it records
|
|
100
|
+
|
|
101
|
+
| attribute | |
|
|
102
|
+
| --- | --- |
|
|
103
|
+
| `db.system.name` | `mongodb` |
|
|
104
|
+
| `db.namespace` | the database |
|
|
105
|
+
| `db.collection.name` | when the command names one |
|
|
106
|
+
| `db.operation.name` | `find`, `insert`, `aggregate`, … |
|
|
107
|
+
| `server.address`, `server.port` | the node that answered |
|
|
108
|
+
|
|
109
|
+
The span is named `"<command> <collection>"`, or the database when the command
|
|
110
|
+
is not about a collection. Its kind is `client`; a failure is `error`, an abort
|
|
111
|
+
is `cancelled`.
|
|
112
|
+
|
|
113
|
+
**Nothing from the command document is read** beyond the collection name. A
|
|
114
|
+
command document holds the query, and a query holds the data.
|
|
115
|
+
|
|
116
|
+
### Options
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
instrumentMongo(client, {
|
|
120
|
+
traced: (event) => event.databaseName !== 'admin',
|
|
121
|
+
spanName: (event) => `mongo ${event.commandName}`,
|
|
122
|
+
telemetry, // default: in scope, else installed
|
|
123
|
+
})
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
`traced` defaults to everything except the driver's own commands — the
|
|
127
|
+
handshake, the heartbeat, authentication, session cleanup (`DRIVER_COMMANDS`).
|
|
128
|
+
It is the one place in this library where something is skipped by default: a
|
|
129
|
+
`hello` every ten seconds on every connection is not your work, and a trace
|
|
130
|
+
full of them is a trace nobody reads.
|
|
131
|
+
|
|
132
|
+
`instrumentMongo` returns the function that removes the listeners.
|
|
133
|
+
|
|
134
|
+
## API
|
|
135
|
+
|
|
136
|
+
| | |
|
|
137
|
+
| --- | --- |
|
|
138
|
+
| `mongoExporter(options)`, `MongoExporterOptions` | the exporter |
|
|
139
|
+
| `DEFAULT_RETENTION`, `DEFAULT_COLLECTION`, `RETENTION_INDEX` | 30 days, `telemetry`, `nxgt_telemetry_retention` |
|
|
140
|
+
| `ensureRetention(db, collection, retention)` | the index, if you want it eagerly |
|
|
141
|
+
| `documentOf(resource, signal)`, `SignalDocument` | the stored shape |
|
|
142
|
+
| `instrumentMongo(client, options)`, `InstrumentOptions` | the instrumentation |
|
|
143
|
+
| `DRIVER_COMMANDS`, `MAX_IN_FLIGHT` | what is skipped, and the in-flight ceiling |
|
|
144
|
+
| `commandAttributes(event)`, `commandName(event)` | what a command's span carries, and what it is called |
|
|
145
|
+
| `collectionOf(event)`, `splitAddress(address)` | the collection a command is about, and a host and port |
|
|
146
|
+
| `DB_SYSTEM`, `DB_NAMESPACE`, `DB_COLLECTION`, `DB_OPERATION`, `SERVER_ADDRESS`, `SERVER_PORT`, `MONGODB` | the attribute names |
|
|
147
|
+
|
|
148
|
+
## Traps
|
|
149
|
+
|
|
150
|
+
- **`monitorCommands: true`, or nothing happens.** Said twice on purpose.
|
|
151
|
+
- **Do not export telemetry through the pool you are instrumenting.** The
|
|
152
|
+
exporter's own `insertMany` is a command, which becomes a span, which is
|
|
153
|
+
exported… Use a separate client for the exporter — the `uri` form — or
|
|
154
|
+
exclude the telemetry collection with `traced`.
|
|
155
|
+
- **`insertMany` is unordered.** One document Mongo refuses — an `_id` holding
|
|
156
|
+
a `$`-prefixed key, a size over the limit — must not cost the 511 behind it.
|
|
157
|
+
- **A dotted attribute name is not a path.** Every span here carries keys like
|
|
158
|
+
`db.system.name`, and `find({ 'attributes.db.system.name': 'mongodb' })` reads
|
|
159
|
+
that as a nested path and matches nothing. The document is fine; the query
|
|
160
|
+
needs `$getField`, or `$expr`:
|
|
161
|
+
```js
|
|
162
|
+
db.telemetry.find({ $expr: { $eq: [{ $getField: { field: 'db.system.name', input: '$attributes' } }, 'mongodb'] } })
|
|
163
|
+
```
|
|
164
|
+
It is the same for `resource`. `traceId`, `spanId`, `at`, `service` and
|
|
165
|
+
`status` are plain top-level fields precisely because they are the ones
|
|
166
|
+
anybody queries.
|
|
167
|
+
- **A first connection that fails is retried on the next batch.** Mongo is
|
|
168
|
+
routinely not up yet when a process boots, so a failed `uri` connection is not
|
|
169
|
+
cached; the batch after it opens a fresh one. Each failure reaches
|
|
170
|
+
`onExportError` and nothing else.
|
|
171
|
+
- **The TTL index is checked once per exporter.** An index dropped out of band
|
|
172
|
+
is not rebuilt for the life of the process — the alternative is a round trip
|
|
173
|
+
per batch to catch something nobody does by accident.
|
|
174
|
+
- **A span is recorded, not opened.** Monitoring gives a start event and an end
|
|
175
|
+
event, not a block to run inside, so `currentSpan()` inside a query callback
|
|
176
|
+
is still the *caller's* span. The command's parent is whatever was open when
|
|
177
|
+
it started.
|
|
178
|
+
- **An unsampled trace is unsampled all the way down.** The decision is read
|
|
179
|
+
from the parent, never taken again per command; a command with nothing above
|
|
180
|
+
it is a root and asks the sampler exactly as `span()` would.
|
|
181
|
+
- **A command that neither succeeds nor fails is forgotten** once
|
|
182
|
+
`MAX_IN_FLIGHT` others are in flight. A connection dropped between the two
|
|
183
|
+
events would otherwise be remembered for ever: forgetting it costs one span,
|
|
184
|
+
keeping it costs the process.
|
|
185
|
+
- **The duration is the driver's, not the wall clock.** It is closer to what
|
|
186
|
+
the server spent, so the start is derived from the end rather than measured
|
|
187
|
+
across a busy event loop.
|
|
188
|
+
- **`mongodb` is an optional peer, and the driver is imported lazily.** Nothing
|
|
189
|
+
loads it until the `uri` form opens a pool, so this package installs in an
|
|
190
|
+
application that has the exporter's sibling and no driver at all.
|
|
191
|
+
|
|
192
|
+
## License
|
|
193
|
+
|
|
194
|
+
MIT
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { type Attributes } from '@softistx/telemetry';
|
|
2
|
+
import type { CommandStartedEvent } from 'mongodb';
|
|
3
|
+
export declare const DB_SYSTEM = "db.system.name";
|
|
4
|
+
export declare const DB_NAMESPACE = "db.namespace";
|
|
5
|
+
export declare const DB_COLLECTION = "db.collection.name";
|
|
6
|
+
export declare const DB_OPERATION = "db.operation.name";
|
|
7
|
+
export declare const SERVER_ADDRESS = "server.address";
|
|
8
|
+
export declare const SERVER_PORT = "server.port";
|
|
9
|
+
export declare const MONGODB = "mongodb";
|
|
10
|
+
/**
|
|
11
|
+
* What is known about a command the moment it is sent.
|
|
12
|
+
*
|
|
13
|
+
* Through `attributesOf`, which is total: an address a driver reports as
|
|
14
|
+
* something unexpected is rendered rather than thrown over.
|
|
15
|
+
*/
|
|
16
|
+
export declare function commandAttributes(event: CommandStartedEvent): Attributes;
|
|
17
|
+
/**
|
|
18
|
+
* The collection a command is about.
|
|
19
|
+
*
|
|
20
|
+
* It is the command document's **first** value, by the wire protocol's own
|
|
21
|
+
* rule: `{ find: 'orders', filter: … }`. The value is not always a collection —
|
|
22
|
+
* `{ ping: 1 }` — so it is only taken when it is a string.
|
|
23
|
+
*
|
|
24
|
+
* Nothing else in the command is read. A command document holds the query, and
|
|
25
|
+
* a query holds the data.
|
|
26
|
+
*/
|
|
27
|
+
export declare function collectionOf(event: CommandStartedEvent): string | undefined;
|
|
28
|
+
/** `"<command> <collection>"`, or the database when there is no collection. */
|
|
29
|
+
export declare function commandName(event: CommandStartedEvent): string;
|
|
30
|
+
/**
|
|
31
|
+
* An address into a host and a port.
|
|
32
|
+
*
|
|
33
|
+
* The driver reports `host:port`, and `[::1]:27017` for an IPv6 literal — the
|
|
34
|
+
* brackets are kept, which is what `new URL(…).hostname` gives on the HTTP side
|
|
35
|
+
* too, so a client span from here and one from `@softistx/telemetry-httpyz` agree
|
|
36
|
+
* about `server.address`. Anything else — a unix socket path, a bare `::1` — is
|
|
37
|
+
* the whole address and no port, which is a looser answer than the two shapes
|
|
38
|
+
* above but never a wrong host.
|
|
39
|
+
*/
|
|
40
|
+
export declare function splitAddress(address: string): [string | undefined, number | undefined];
|
|
41
|
+
//# sourceMappingURL=db.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"db.d.ts","sourceRoot":"","sources":["../../src/attributes/db.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,UAAU,EAAgB,MAAM,qBAAqB,CAAC;AACpE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAEnD,eAAO,MAAM,SAAS,mBAAmB,CAAC;AAC1C,eAAO,MAAM,YAAY,iBAAiB,CAAC;AAC3C,eAAO,MAAM,aAAa,uBAAuB,CAAC;AAClD,eAAO,MAAM,YAAY,sBAAsB,CAAC;AAChD,eAAO,MAAM,cAAc,mBAAmB,CAAC;AAC/C,eAAO,MAAM,WAAW,gBAAgB,CAAC;AAEzC,eAAO,MAAM,OAAO,YAAY,CAAC;AAEjC;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,mBAAmB,GAAG,UAAU,CAYxE;AAED;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,mBAAmB,GAAG,MAAM,GAAG,SAAS,CAO3E;AAED,+EAA+E;AAC/E,wBAAgB,WAAW,CAAC,KAAK,EAAE,mBAAmB,GAAG,MAAM,CAG9D;AAED;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAC3B,OAAO,EAAE,MAAM,GACb,CAAC,MAAM,GAAG,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC,CAmB1C"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type Attributes, type Resource, type Signal } from '@softistx/telemetry';
|
|
2
|
+
/**
|
|
3
|
+
* A signal as it is stored.
|
|
4
|
+
*
|
|
5
|
+
* It is the signal, with four changes and no others:
|
|
6
|
+
*
|
|
7
|
+
* - **every instant becomes a BSON `Date`**, so a query can use a range and a
|
|
8
|
+
* TTL index can expire it. Stored as an epoch number it would be neither;
|
|
9
|
+
* - **the resource is stamped on each document** — `service`, `version`,
|
|
10
|
+
* `environment`, and its attributes under `resource` — because a collection
|
|
11
|
+
* here is shared by every service that writes to it, which is the opposite of
|
|
12
|
+
* a log file;
|
|
13
|
+
* - **`traceId` and `spanId` are lifted to the top level.** They live at
|
|
14
|
+
* `span.traceId` on a log and at `context.traceId` on a span, so without this
|
|
15
|
+
* the one query anybody actually writes — everything in this trace — would
|
|
16
|
+
* need an `$or` over two paths and an index on each;
|
|
17
|
+
* - **`at` exists on both kinds.** A span is stamped with its start, so one
|
|
18
|
+
* index answers "what happened in this minute" for logs and spans alike, and
|
|
19
|
+
* one TTL index expires both.
|
|
20
|
+
*/
|
|
21
|
+
export interface SignalDocument {
|
|
22
|
+
readonly at: Date;
|
|
23
|
+
readonly service: string;
|
|
24
|
+
readonly version?: string;
|
|
25
|
+
readonly environment?: string;
|
|
26
|
+
readonly resource?: Attributes;
|
|
27
|
+
readonly traceId?: string;
|
|
28
|
+
readonly spanId?: string;
|
|
29
|
+
readonly [field: string]: unknown;
|
|
30
|
+
}
|
|
31
|
+
/** Epoch milliseconds to a BSON `Date`, and nothing else touched. */
|
|
32
|
+
export declare function documentOf(resource: Resource, signal: Signal): SignalDocument;
|
|
33
|
+
//# sourceMappingURL=documents.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"documents.d.ts","sourceRoot":"","sources":["../../src/export/documents.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,UAAU,EACf,KAAK,QAAQ,EACb,KAAK,MAAM,EAGX,MAAM,qBAAqB,CAAC;AAE7B;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,WAAW,cAAc;IAC9B,QAAQ,CAAC,EAAE,EAAE,IAAI,CAAC;IAClB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,QAAQ,CAAC,EAAE,UAAU,CAAC;IAC/B,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB,QAAQ,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;CAClC;AAED,qEAAqE;AACrE,wBAAgB,UAAU,CAAC,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,GAAG,cAAc,CA+B7E"}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { Exporter } from '@softistx/telemetry';
|
|
2
|
+
import type { Db } from 'mongodb';
|
|
3
|
+
/** 30 days. Long enough to explain last month's incident, short enough to keep. */
|
|
4
|
+
export declare const DEFAULT_RETENTION: number;
|
|
5
|
+
export declare const DEFAULT_COLLECTION = "telemetry";
|
|
6
|
+
/** The TTL index's name. Fixed, so it can be recognised and replaced. */
|
|
7
|
+
export declare const RETENTION_INDEX = "nxgt_telemetry_retention";
|
|
8
|
+
interface Shared {
|
|
9
|
+
/** Default `telemetry`. */
|
|
10
|
+
readonly collection?: string;
|
|
11
|
+
/**
|
|
12
|
+
* How long a signal is kept, in milliseconds. Default 30 days. `false`
|
|
13
|
+
* keeps everything, and creates no index.
|
|
14
|
+
*/
|
|
15
|
+
readonly retention?: number | false;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Either write into a database you already have, or give a URI and let this
|
|
19
|
+
* open its own pool. The compiler refuses both: a `db` beside a `uri` would
|
|
20
|
+
* silently ignore one of them.
|
|
21
|
+
*/
|
|
22
|
+
export type MongoExporterOptions = (Shared & {
|
|
23
|
+
readonly db: Db;
|
|
24
|
+
readonly uri?: undefined;
|
|
25
|
+
}) | (Shared & {
|
|
26
|
+
readonly uri: string;
|
|
27
|
+
readonly database: string;
|
|
28
|
+
readonly db?: undefined;
|
|
29
|
+
});
|
|
30
|
+
/**
|
|
31
|
+
* Signals into a MongoDB collection, one document each.
|
|
32
|
+
*
|
|
33
|
+
* ```ts
|
|
34
|
+
* mongoExporter({ db, retention: 7 * 24 * 60 * 60 * 1000 })
|
|
35
|
+
* ```
|
|
36
|
+
*
|
|
37
|
+
* For an estate that already runs Mongo and does not want a collector: the
|
|
38
|
+
* documents are the signals, so `db.telemetry.find({ traceId })` is the whole
|
|
39
|
+
* query language, and a TTL index is the whole retention policy.
|
|
40
|
+
*
|
|
41
|
+
* **A `db` you pass is never closed** — it is yours, and this is one of several
|
|
42
|
+
* things using it. The `uri` form opens its **own pool**, so a burst of
|
|
43
|
+
* telemetry cannot starve the connections your application's queries need, and
|
|
44
|
+
* closes it on `close()`.
|
|
45
|
+
*/
|
|
46
|
+
export declare function mongoExporter(options: MongoExporterOptions): Exporter;
|
|
47
|
+
/**
|
|
48
|
+
* The TTL index, created lazily and **recreated when the retention changes**.
|
|
49
|
+
*
|
|
50
|
+
* Mongo will not redefine an index under the same name with different options:
|
|
51
|
+
* it answers `IndexOptionsConflict` rather than quietly adopting the new value.
|
|
52
|
+
* So a retention that changed means dropping the index and making it again —
|
|
53
|
+
* which is why the name is fixed, and why nothing else should use it.
|
|
54
|
+
*/
|
|
55
|
+
export declare function ensureRetention(db: Db, name: string, retention: number | false): Promise<void>;
|
|
56
|
+
export {};
|
|
57
|
+
//# sourceMappingURL=mongo.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mongo.d.ts","sourceRoot":"","sources":["../../src/export/mongo.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAoB,MAAM,qBAAqB,CAAC;AACtE,OAAO,KAAK,EAAE,EAAE,EAAe,MAAM,SAAS,CAAC;AAG/C,mFAAmF;AACnF,eAAO,MAAM,iBAAiB,QAA2B,CAAC;AAC1D,eAAO,MAAM,kBAAkB,cAAc,CAAC;AAC9C,yEAAyE;AACzE,eAAO,MAAM,eAAe,6BAA6B,CAAC;AAE1D,UAAU,MAAM;IACf,2BAA2B;IAC3B,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B;;;OAGG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;CACpC;AAED;;;;GAIG;AACH,MAAM,MAAM,oBAAoB,GAC7B,CAAC,MAAM,GAAG;IAAE,QAAQ,CAAC,EAAE,EAAE,EAAE,CAAC;IAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,SAAS,CAAA;CAAE,CAAC,GACxD,CAAC,MAAM,GAAG;IACV,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,EAAE,CAAC,EAAE,SAAS,CAAC;CACvB,CAAC,CAAC;AAEN;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,QAAQ,CA6DrE;AAED;;;;;;;GAOG;AACH,wBAAsB,eAAe,CACpC,EAAE,EAAE,EAAE,EACN,IAAI,EAAE,MAAM,EACZ,SAAS,EAAE,MAAM,GAAG,KAAK,GACvB,OAAO,CAAC,IAAI,CAAC,CAmBf"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC;AAChC,cAAc,oBAAoB,CAAC;AACnC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,uBAAuB,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
// src/attributes/db.ts
|
|
2
|
+
import { attributesOf } from "@softistx/telemetry";
|
|
3
|
+
var DB_SYSTEM = "db.system.name";
|
|
4
|
+
var DB_NAMESPACE = "db.namespace";
|
|
5
|
+
var DB_COLLECTION = "db.collection.name";
|
|
6
|
+
var DB_OPERATION = "db.operation.name";
|
|
7
|
+
var SERVER_ADDRESS = "server.address";
|
|
8
|
+
var SERVER_PORT = "server.port";
|
|
9
|
+
var MONGODB = "mongodb";
|
|
10
|
+
function commandAttributes(event) {
|
|
11
|
+
const collection = collectionOf(event);
|
|
12
|
+
const [host, port] = splitAddress(event.address);
|
|
13
|
+
return attributesOf({
|
|
14
|
+
[DB_SYSTEM]: MONGODB,
|
|
15
|
+
[DB_NAMESPACE]: event.databaseName,
|
|
16
|
+
[DB_OPERATION]: event.commandName,
|
|
17
|
+
...collection === undefined ? {} : { [DB_COLLECTION]: collection },
|
|
18
|
+
...host === undefined ? {} : { [SERVER_ADDRESS]: host },
|
|
19
|
+
...port === undefined ? {} : { [SERVER_PORT]: port }
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
function collectionOf(event) {
|
|
23
|
+
try {
|
|
24
|
+
const value = event.command?.[event.commandName];
|
|
25
|
+
return typeof value === "string" ? value : undefined;
|
|
26
|
+
} catch {
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function commandName(event) {
|
|
31
|
+
const collection = collectionOf(event);
|
|
32
|
+
return `${event.commandName} ${collection ?? event.databaseName}`;
|
|
33
|
+
}
|
|
34
|
+
function splitAddress(address) {
|
|
35
|
+
if (typeof address !== "string" || address === "") {
|
|
36
|
+
return [undefined, undefined];
|
|
37
|
+
}
|
|
38
|
+
const colon = address.lastIndexOf(":");
|
|
39
|
+
if (colon <= 0)
|
|
40
|
+
return [address, undefined];
|
|
41
|
+
const after = address.slice(colon + 1);
|
|
42
|
+
if (after === "" || !/^\d+$/.test(after))
|
|
43
|
+
return [address, undefined];
|
|
44
|
+
const host = address.slice(0, colon);
|
|
45
|
+
if (host.includes(":") && !host.startsWith("[")) {
|
|
46
|
+
return [address, undefined];
|
|
47
|
+
}
|
|
48
|
+
return [host, Number(after)];
|
|
49
|
+
}
|
|
50
|
+
// src/export/documents.ts
|
|
51
|
+
import {
|
|
52
|
+
signalAt,
|
|
53
|
+
signalSpan
|
|
54
|
+
} from "@softistx/telemetry";
|
|
55
|
+
function documentOf(resource, signal) {
|
|
56
|
+
const span = signalSpan(signal);
|
|
57
|
+
const stamped = {
|
|
58
|
+
service: resource.service,
|
|
59
|
+
...resource.version === undefined ? {} : { version: resource.version },
|
|
60
|
+
...resource.environment === undefined ? {} : { environment: resource.environment },
|
|
61
|
+
...hasAny(resource.attributes) ? { resource: resource.attributes } : {},
|
|
62
|
+
...span === undefined ? {} : { traceId: span.traceId, spanId: span.spanId },
|
|
63
|
+
at: new Date(signalAt(signal))
|
|
64
|
+
};
|
|
65
|
+
return signal.type === "log" ? { ...signal, ...stamped } : {
|
|
66
|
+
...signal,
|
|
67
|
+
...stamped,
|
|
68
|
+
startedAt: new Date(signal.startedAt),
|
|
69
|
+
endedAt: new Date(signal.endedAt),
|
|
70
|
+
events: signal.events.map((happened) => ({
|
|
71
|
+
...happened,
|
|
72
|
+
at: new Date(happened.at)
|
|
73
|
+
}))
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
function hasAny(attributes) {
|
|
77
|
+
return Object.keys(attributes).length > 0;
|
|
78
|
+
}
|
|
79
|
+
// src/export/mongo.ts
|
|
80
|
+
var DEFAULT_RETENTION = 30 * 24 * 60 * 60 * 1000;
|
|
81
|
+
var DEFAULT_COLLECTION = "telemetry";
|
|
82
|
+
var RETENTION_INDEX = "nxgt_telemetry_retention";
|
|
83
|
+
function mongoExporter(options) {
|
|
84
|
+
const name = options.collection ?? DEFAULT_COLLECTION;
|
|
85
|
+
const retention = options.retention ?? DEFAULT_RETENTION;
|
|
86
|
+
let owned;
|
|
87
|
+
let opening;
|
|
88
|
+
let indexed;
|
|
89
|
+
const database = async () => {
|
|
90
|
+
if (options.db !== undefined)
|
|
91
|
+
return options.db;
|
|
92
|
+
opening ??= open(options.uri, options.database).then((opened) => {
|
|
93
|
+
owned = opened.client;
|
|
94
|
+
return opened.db;
|
|
95
|
+
}, (failure) => {
|
|
96
|
+
opening = undefined;
|
|
97
|
+
throw failure;
|
|
98
|
+
});
|
|
99
|
+
return opening;
|
|
100
|
+
};
|
|
101
|
+
return {
|
|
102
|
+
async export(resource, batch) {
|
|
103
|
+
if (batch.length === 0)
|
|
104
|
+
return;
|
|
105
|
+
const db = await database();
|
|
106
|
+
const collection = db.collection(name);
|
|
107
|
+
if (indexed !== retention) {
|
|
108
|
+
await ensureRetention(db, name, retention);
|
|
109
|
+
indexed = retention;
|
|
110
|
+
}
|
|
111
|
+
await collection.insertMany(batch.map((signal) => documentOf(resource, signal)), { ordered: false });
|
|
112
|
+
},
|
|
113
|
+
async close() {
|
|
114
|
+
await owned?.close();
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
async function ensureRetention(db, name, retention) {
|
|
119
|
+
const collection = db.collection(name);
|
|
120
|
+
const found = await existing(collection, RETENTION_INDEX);
|
|
121
|
+
if (retention === false) {
|
|
122
|
+
if (found !== undefined)
|
|
123
|
+
await collection.dropIndex(RETENTION_INDEX);
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
const seconds = Math.max(Math.round(retention / 1000), 0);
|
|
127
|
+
if (found?.expireAfterSeconds === seconds)
|
|
128
|
+
return;
|
|
129
|
+
if (found !== undefined)
|
|
130
|
+
await collection.dropIndex(RETENTION_INDEX);
|
|
131
|
+
await collection.createIndex({ at: 1 }, { name: RETENTION_INDEX, expireAfterSeconds: seconds });
|
|
132
|
+
}
|
|
133
|
+
async function existing(collection, name) {
|
|
134
|
+
try {
|
|
135
|
+
const indexes = await collection.indexes();
|
|
136
|
+
return indexes.find((index) => index.name === name);
|
|
137
|
+
} catch {
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
async function open(uri, database) {
|
|
142
|
+
const { MongoClient: Client } = await import("mongodb");
|
|
143
|
+
const client = await Client.connect(uri);
|
|
144
|
+
return { client, db: client.db(database) };
|
|
145
|
+
}
|
|
146
|
+
// src/instrument/commands.ts
|
|
147
|
+
import {
|
|
148
|
+
currentSpan,
|
|
149
|
+
resolveTelemetry
|
|
150
|
+
} from "@softistx/telemetry";
|
|
151
|
+
|
|
152
|
+
// src/instrument/record.ts
|
|
153
|
+
import {
|
|
154
|
+
errorInfo,
|
|
155
|
+
isAbort,
|
|
156
|
+
randomSpanId,
|
|
157
|
+
randomTraceId
|
|
158
|
+
} from "@softistx/telemetry";
|
|
159
|
+
function spanOf(found, failure, duration) {
|
|
160
|
+
const endedAt = Date.now();
|
|
161
|
+
const startedAt = Math.min(endedAt - Math.max(duration, 0), found.startedAt);
|
|
162
|
+
return {
|
|
163
|
+
type: "span",
|
|
164
|
+
name: found.name,
|
|
165
|
+
context: found.context,
|
|
166
|
+
...found.parent === undefined ? {} : { parent: found.parent.spanId },
|
|
167
|
+
kind: "client",
|
|
168
|
+
startedAt,
|
|
169
|
+
endedAt,
|
|
170
|
+
status: failure === undefined ? "ok" : isAbort(failure) ? "cancelled" : "error",
|
|
171
|
+
attributes: found.attributes,
|
|
172
|
+
events: [],
|
|
173
|
+
...failure === undefined ? {} : { error: errorInfo(failure, found.telemetry.stackTraces) }
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
function contextFor(telemetry, parent) {
|
|
177
|
+
if (parent !== undefined) {
|
|
178
|
+
return {
|
|
179
|
+
traceId: parent.traceId,
|
|
180
|
+
spanId: randomSpanId(),
|
|
181
|
+
sampled: parent.sampled,
|
|
182
|
+
remote: false
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
const traceId = randomTraceId();
|
|
186
|
+
return {
|
|
187
|
+
traceId,
|
|
188
|
+
spanId: randomSpanId(),
|
|
189
|
+
sampled: sampled(telemetry, traceId),
|
|
190
|
+
remote: false
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
function sampled(telemetry, traceId) {
|
|
194
|
+
try {
|
|
195
|
+
return telemetry.sampler.sample(traceId);
|
|
196
|
+
} catch {
|
|
197
|
+
return true;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// src/instrument/commands.ts
|
|
202
|
+
var DRIVER_COMMANDS = new Set([
|
|
203
|
+
"hello",
|
|
204
|
+
"ismaster",
|
|
205
|
+
"isMaster",
|
|
206
|
+
"ping",
|
|
207
|
+
"endSessions",
|
|
208
|
+
"killSessions",
|
|
209
|
+
"saslStart",
|
|
210
|
+
"saslContinue",
|
|
211
|
+
"authenticate",
|
|
212
|
+
"getnonce",
|
|
213
|
+
"buildInfo",
|
|
214
|
+
"buildinfo"
|
|
215
|
+
]);
|
|
216
|
+
var MAX_IN_FLIGHT = 4096;
|
|
217
|
+
function instrumentMongo(client, options = {}) {
|
|
218
|
+
const traced = options.traced ?? notADriverCommand;
|
|
219
|
+
const named = options.spanName ?? commandName;
|
|
220
|
+
const inFlight = new Map;
|
|
221
|
+
const started = (event) => {
|
|
222
|
+
try {
|
|
223
|
+
if (!traced(event))
|
|
224
|
+
return;
|
|
225
|
+
const telemetry = options.telemetry ?? resolveTelemetry();
|
|
226
|
+
if (telemetry === undefined)
|
|
227
|
+
return;
|
|
228
|
+
const parent = currentSpan();
|
|
229
|
+
const context = contextFor(telemetry, parent);
|
|
230
|
+
if (!context.sampled)
|
|
231
|
+
return;
|
|
232
|
+
forget(inFlight);
|
|
233
|
+
inFlight.set(event.requestId, {
|
|
234
|
+
telemetry,
|
|
235
|
+
parent,
|
|
236
|
+
context,
|
|
237
|
+
name: named(event),
|
|
238
|
+
attributes: commandAttributes(event),
|
|
239
|
+
startedAt: Date.now()
|
|
240
|
+
});
|
|
241
|
+
} catch {}
|
|
242
|
+
};
|
|
243
|
+
const ended = (requestId, failure, duration) => {
|
|
244
|
+
try {
|
|
245
|
+
const found = inFlight.get(requestId);
|
|
246
|
+
if (found === undefined)
|
|
247
|
+
return;
|
|
248
|
+
inFlight.delete(requestId);
|
|
249
|
+
found.telemetry.emit(spanOf(found, failure, duration));
|
|
250
|
+
} catch {}
|
|
251
|
+
};
|
|
252
|
+
const succeeded = (event) => ended(event.requestId, undefined, event.duration);
|
|
253
|
+
const failed = (event) => ended(event.requestId, event.failure, event.duration);
|
|
254
|
+
client.on("commandStarted", started);
|
|
255
|
+
client.on("commandSucceeded", succeeded);
|
|
256
|
+
client.on("commandFailed", failed);
|
|
257
|
+
return () => {
|
|
258
|
+
client.off("commandStarted", started);
|
|
259
|
+
client.off("commandSucceeded", succeeded);
|
|
260
|
+
client.off("commandFailed", failed);
|
|
261
|
+
inFlight.clear();
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
function notADriverCommand(event) {
|
|
265
|
+
return !DRIVER_COMMANDS.has(event.commandName);
|
|
266
|
+
}
|
|
267
|
+
function forget(inFlight) {
|
|
268
|
+
if (inFlight.size < MAX_IN_FLIGHT)
|
|
269
|
+
return;
|
|
270
|
+
const oldest = inFlight.keys().next();
|
|
271
|
+
if (!oldest.done)
|
|
272
|
+
inFlight.delete(oldest.value);
|
|
273
|
+
}
|
|
274
|
+
export {
|
|
275
|
+
DB_COLLECTION,
|
|
276
|
+
DB_NAMESPACE,
|
|
277
|
+
DB_OPERATION,
|
|
278
|
+
DB_SYSTEM,
|
|
279
|
+
DEFAULT_COLLECTION,
|
|
280
|
+
DEFAULT_RETENTION,
|
|
281
|
+
DRIVER_COMMANDS,
|
|
282
|
+
MAX_IN_FLIGHT,
|
|
283
|
+
MONGODB,
|
|
284
|
+
RETENTION_INDEX,
|
|
285
|
+
SERVER_ADDRESS,
|
|
286
|
+
SERVER_PORT,
|
|
287
|
+
collectionOf,
|
|
288
|
+
commandAttributes,
|
|
289
|
+
commandName,
|
|
290
|
+
documentOf,
|
|
291
|
+
ensureRetention,
|
|
292
|
+
instrumentMongo,
|
|
293
|
+
mongoExporter,
|
|
294
|
+
splitAddress
|
|
295
|
+
};
|
|
296
|
+
|
|
297
|
+
//# debugId=12628BA2433AA01B64756E2164756E21
|
|
298
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/attributes/db.ts", "../src/export/documents.ts", "../src/export/mongo.ts", "../src/instrument/commands.ts", "../src/instrument/record.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import { type Attributes, attributesOf } from '@softistx/telemetry';\nimport type { CommandStartedEvent } from 'mongodb';\n\nexport const DB_SYSTEM = 'db.system.name';\nexport const DB_NAMESPACE = 'db.namespace';\nexport const DB_COLLECTION = 'db.collection.name';\nexport const DB_OPERATION = 'db.operation.name';\nexport const SERVER_ADDRESS = 'server.address';\nexport const SERVER_PORT = 'server.port';\n\nexport const MONGODB = 'mongodb';\n\n/**\n * What is known about a command the moment it is sent.\n *\n * Through `attributesOf`, which is total: an address a driver reports as\n * something unexpected is rendered rather than thrown over.\n */\nexport function commandAttributes(event: CommandStartedEvent): Attributes {\n\tconst collection = collectionOf(event);\n\tconst [host, port] = splitAddress(event.address);\n\n\treturn attributesOf({\n\t\t[DB_SYSTEM]: MONGODB,\n\t\t[DB_NAMESPACE]: event.databaseName,\n\t\t[DB_OPERATION]: event.commandName,\n\t\t...(collection === undefined ? {} : { [DB_COLLECTION]: collection }),\n\t\t...(host === undefined ? {} : { [SERVER_ADDRESS]: host }),\n\t\t...(port === undefined ? {} : { [SERVER_PORT]: port }),\n\t});\n}\n\n/**\n * The collection a command is about.\n *\n * It is the command document's **first** value, by the wire protocol's own\n * rule: `{ find: 'orders', filter: … }`. The value is not always a collection —\n * `{ ping: 1 }` — so it is only taken when it is a string.\n *\n * Nothing else in the command is read. A command document holds the query, and\n * a query holds the data.\n */\nexport function collectionOf(event: CommandStartedEvent): string | undefined {\n\ttry {\n\t\tconst value = event.command?.[event.commandName];\n\t\treturn typeof value === 'string' ? value : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** `\"<command> <collection>\"`, or the database when there is no collection. */\nexport function commandName(event: CommandStartedEvent): string {\n\tconst collection = collectionOf(event);\n\treturn `${event.commandName} ${collection ?? event.databaseName}`;\n}\n\n/**\n * An address into a host and a port.\n *\n * The driver reports `host:port`, and `[::1]:27017` for an IPv6 literal — the\n * brackets are kept, which is what `new URL(…).hostname` gives on the HTTP side\n * too, so a client span from here and one from `@softistx/telemetry-httpyz` agree\n * about `server.address`. Anything else — a unix socket path, a bare `::1` — is\n * the whole address and no port, which is a looser answer than the two shapes\n * above but never a wrong host.\n */\nexport function splitAddress(\n\taddress: string,\n): [string | undefined, number | undefined] {\n\tif (typeof address !== 'string' || address === '') {\n\t\treturn [undefined, undefined];\n\t}\n\n\tconst colon = address.lastIndexOf(':');\n\tif (colon <= 0) return [address, undefined];\n\n\tconst after = address.slice(colon + 1);\n\t// `Number('')` is 0, and a bracket-less `::1` would take `1` as its port.\n\tif (after === '' || !/^\\d+$/.test(after)) return [address, undefined];\n\n\tconst host = address.slice(0, colon);\n\t// `::1` splits to `::`, which is not a host. Only a bracketed literal is.\n\tif (host.includes(':') && !host.startsWith('[')) {\n\t\treturn [address, undefined];\n\t}\n\n\treturn [host, Number(after)];\n}\n",
|
|
6
|
+
"import {\n\ttype Attributes,\n\ttype Resource,\n\ttype Signal,\n\tsignalAt,\n\tsignalSpan,\n} from '@softistx/telemetry';\n\n/**\n * A signal as it is stored.\n *\n * It is the signal, with four changes and no others:\n *\n * - **every instant becomes a BSON `Date`**, so a query can use a range and a\n * TTL index can expire it. Stored as an epoch number it would be neither;\n * - **the resource is stamped on each document** — `service`, `version`,\n * `environment`, and its attributes under `resource` — because a collection\n * here is shared by every service that writes to it, which is the opposite of\n * a log file;\n * - **`traceId` and `spanId` are lifted to the top level.** They live at\n * `span.traceId` on a log and at `context.traceId` on a span, so without this\n * the one query anybody actually writes — everything in this trace — would\n * need an `$or` over two paths and an index on each;\n * - **`at` exists on both kinds.** A span is stamped with its start, so one\n * index answers \"what happened in this minute\" for logs and spans alike, and\n * one TTL index expires both.\n */\nexport interface SignalDocument {\n\treadonly at: Date;\n\treadonly service: string;\n\treadonly version?: string;\n\treadonly environment?: string;\n\treadonly resource?: Attributes;\n\treadonly traceId?: string;\n\treadonly spanId?: string;\n\treadonly [field: string]: unknown;\n}\n\n/** Epoch milliseconds to a BSON `Date`, and nothing else touched. */\nexport function documentOf(resource: Resource, signal: Signal): SignalDocument {\n\tconst span = signalSpan(signal);\n\n\tconst stamped = {\n\t\tservice: resource.service,\n\t\t...(resource.version === undefined ? {} : { version: resource.version }),\n\t\t...(resource.environment === undefined\n\t\t\t? {}\n\t\t\t: { environment: resource.environment }),\n\t\t// A sub-document rather than flattened beside them: a resource\n\t\t// attribute is named by whoever configured the service, and one called\n\t\t// `name` or `type` flattened here would overwrite the signal's own.\n\t\t...(hasAny(resource.attributes) ? { resource: resource.attributes } : {}),\n\t\t...(span === undefined\n\t\t\t? {}\n\t\t\t: { traceId: span.traceId as string, spanId: span.spanId as string }),\n\t\tat: new Date(signalAt(signal)),\n\t};\n\n\treturn signal.type === 'log'\n\t\t? { ...signal, ...stamped }\n\t\t: {\n\t\t\t\t...signal,\n\t\t\t\t...stamped,\n\t\t\t\tstartedAt: new Date(signal.startedAt),\n\t\t\t\tendedAt: new Date(signal.endedAt),\n\t\t\t\tevents: signal.events.map((happened) => ({\n\t\t\t\t\t...happened,\n\t\t\t\t\tat: new Date(happened.at),\n\t\t\t\t})),\n\t\t\t};\n}\n\nfunction hasAny(attributes: Attributes): boolean {\n\treturn Object.keys(attributes).length > 0;\n}\n",
|
|
7
|
+
"import type { Exporter, Resource, Signal } from '@softistx/telemetry';\nimport type { Db, MongoClient } from 'mongodb';\nimport { documentOf } from './documents';\n\n/** 30 days. Long enough to explain last month's incident, short enough to keep. */\nexport const DEFAULT_RETENTION = 30 * 24 * 60 * 60 * 1000;\nexport const DEFAULT_COLLECTION = 'telemetry';\n/** The TTL index's name. Fixed, so it can be recognised and replaced. */\nexport const RETENTION_INDEX = 'nxgt_telemetry_retention';\n\ninterface Shared {\n\t/** Default `telemetry`. */\n\treadonly collection?: string;\n\t/**\n\t * How long a signal is kept, in milliseconds. Default 30 days. `false`\n\t * keeps everything, and creates no index.\n\t */\n\treadonly retention?: number | false;\n}\n\n/**\n * Either write into a database you already have, or give a URI and let this\n * open its own pool. The compiler refuses both: a `db` beside a `uri` would\n * silently ignore one of them.\n */\nexport type MongoExporterOptions =\n\t| (Shared & { readonly db: Db; readonly uri?: undefined })\n\t| (Shared & {\n\t\t\treadonly uri: string;\n\t\t\treadonly database: string;\n\t\t\treadonly db?: undefined;\n\t });\n\n/**\n * Signals into a MongoDB collection, one document each.\n *\n * ```ts\n * mongoExporter({ db, retention: 7 * 24 * 60 * 60 * 1000 })\n * ```\n *\n * For an estate that already runs Mongo and does not want a collector: the\n * documents are the signals, so `db.telemetry.find({ traceId })` is the whole\n * query language, and a TTL index is the whole retention policy.\n *\n * **A `db` you pass is never closed** — it is yours, and this is one of several\n * things using it. The `uri` form opens its **own pool**, so a burst of\n * telemetry cannot starve the connections your application's queries need, and\n * closes it on `close()`.\n */\nexport function mongoExporter(options: MongoExporterOptions): Exporter {\n\tconst name = options.collection ?? DEFAULT_COLLECTION;\n\tconst retention = options.retention ?? DEFAULT_RETENTION;\n\n\tlet owned: MongoClient | undefined;\n\tlet opening: Promise<Db> | undefined;\n\t/**\n\t * The retention the index on disk was last made for.\n\t *\n\t * Per exporter, and never re-read: an index dropped out of band is not\n\t * rebuilt for the life of the process. The alternative is asking Mongo for\n\t * the collection's indexes on every batch, which is a round trip per batch\n\t * to catch something nobody does by accident.\n\t */\n\tlet indexed: number | false | undefined;\n\n\tconst database = async (): Promise<Db> => {\n\t\tif (options.db !== undefined) return options.db;\n\t\t// The connection is opened once and shared, but a *failed* one is not\n\t\t// kept: Mongo is routinely not up yet when a process boots, and a\n\t\t// rejected promise left in this slot would make every later batch await\n\t\t// the same rejection for the life of the process.\n\t\topening ??= open(options.uri, options.database).then(\n\t\t\t(opened) => {\n\t\t\t\towned = opened.client;\n\t\t\t\treturn opened.db;\n\t\t\t},\n\t\t\t(failure: unknown) => {\n\t\t\t\topening = undefined;\n\t\t\t\tthrow failure;\n\t\t\t},\n\t\t);\n\t\treturn opening;\n\t};\n\n\treturn {\n\t\tasync export(resource: Resource, batch: readonly Signal[]): Promise<void> {\n\t\t\tif (batch.length === 0) return;\n\n\t\t\tconst db = await database();\n\t\t\tconst collection = db.collection(name);\n\n\t\t\tif (indexed !== retention) {\n\t\t\t\tawait ensureRetention(db, name, retention);\n\t\t\t\tindexed = retention;\n\t\t\t}\n\n\t\t\t// **Unordered.** One document Mongo refuses — a key it will not\n\t\t\t// take, a size limit — must not cost the other 511 behind it.\n\t\t\tawait collection.insertMany(\n\t\t\t\tbatch.map((signal) => documentOf(resource, signal)),\n\t\t\t\t{ ordered: false },\n\t\t\t);\n\t\t},\n\n\t\tasync close(): Promise<void> {\n\t\t\t// Only a pool this exporter opened. A `db` that was passed in\n\t\t\t// belongs to the application.\n\t\t\tawait owned?.close();\n\t\t},\n\t};\n}\n\n/**\n * The TTL index, created lazily and **recreated when the retention changes**.\n *\n * Mongo will not redefine an index under the same name with different options:\n * it answers `IndexOptionsConflict` rather than quietly adopting the new value.\n * So a retention that changed means dropping the index and making it again —\n * which is why the name is fixed, and why nothing else should use it.\n */\nexport async function ensureRetention(\n\tdb: Db,\n\tname: string,\n\tretention: number | false,\n): Promise<void> {\n\tconst collection = db.collection(name);\n\tconst found = await existing(collection, RETENTION_INDEX);\n\n\tif (retention === false) {\n\t\t// Keeping everything means there must be no index, including one an\n\t\t// earlier configuration left behind.\n\t\tif (found !== undefined) await collection.dropIndex(RETENTION_INDEX);\n\t\treturn;\n\t}\n\n\tconst seconds = Math.max(Math.round(retention / 1_000), 0);\n\tif (found?.expireAfterSeconds === seconds) return;\n\tif (found !== undefined) await collection.dropIndex(RETENTION_INDEX);\n\n\tawait collection.createIndex(\n\t\t{ at: 1 },\n\t\t{ name: RETENTION_INDEX, expireAfterSeconds: seconds },\n\t);\n}\n\nasync function existing(\n\tcollection: ReturnType<Db['collection']>,\n\tname: string,\n): Promise<{ expireAfterSeconds?: number } | undefined> {\n\ttry {\n\t\tconst indexes = (await collection.indexes()) as {\n\t\t\tname?: string;\n\t\t\texpireAfterSeconds?: number;\n\t\t}[];\n\t\treturn indexes.find((index) => index.name === name);\n\t} catch {\n\t\t// The collection does not exist yet, which is not a problem: creating\n\t\t// the index creates it.\n\t\treturn undefined;\n\t}\n}\n\nasync function open(\n\turi: string,\n\tdatabase: string,\n): Promise<{ client: MongoClient; db: Db }> {\n\t// Imported here rather than at the top, so the package loads in an\n\t// application that has the exporter's sibling but not the driver.\n\tconst { MongoClient: Client } = await import('mongodb');\n\tconst client = await Client.connect(uri);\n\treturn { client, db: client.db(database) };\n}\n",
|
|
8
|
+
"import {\n\tcurrentSpan,\n\tresolveTelemetry,\n\ttype Telemetry,\n} from '@softistx/telemetry';\nimport type {\n\tCommandFailedEvent,\n\tCommandStartedEvent,\n\tCommandSucceededEvent,\n\tMongoClient,\n} from 'mongodb';\nimport { commandAttributes, commandName } from '../attributes/db';\nimport { contextFor, type InFlight, spanOf } from './record';\n\n/**\n * The commands the driver sends on its own behalf: the handshake, the heartbeat,\n * authentication, session cleanup.\n *\n * These are skipped by default, and it is the one place in this library where\n * something is. Everywhere else nothing is skipped, because a library that\n * decides which of *your* work does not matter hides the one that did — but a\n * heartbeat every ten seconds on every connection is not your work at all, and\n * a trace full of `hello` is a trace nobody reads.\n */\nexport const DRIVER_COMMANDS: ReadonlySet<string> = new Set([\n\t'hello',\n\t'ismaster',\n\t'isMaster',\n\t'ping',\n\t'endSessions',\n\t'killSessions',\n\t'saslStart',\n\t'saslContinue',\n\t'authenticate',\n\t'getnonce',\n\t'buildInfo',\n\t'buildinfo',\n]);\n\n/**\n * How many commands may be in flight before the oldest is forgotten.\n *\n * A command that neither succeeds nor fails — a connection dropped between the\n * two events — would otherwise be remembered for ever. Forgetting it costs one\n * span; not forgetting it costs the process.\n */\nexport const MAX_IN_FLIGHT = 4_096;\n\nexport interface InstrumentOptions {\n\t/**\n\t * Whether a command gets a span. Default: everything except\n\t * {@link DRIVER_COMMANDS}.\n\t */\n\treadonly traced?: (event: CommandStartedEvent) => boolean;\n\t/** The span's name. Default `\"<command> <collection>\"`, or the database. */\n\treadonly spanName?: (event: CommandStartedEvent) => string;\n\t/**\n\t * The telemetry to write to. Default: the one in scope when the command\n\t * started, and the installed one otherwise.\n\t */\n\treadonly telemetry?: Telemetry;\n}\n\n/**\n * Client spans for every command the driver sends.\n *\n * ```ts\n * const client = new MongoClient(uri, { monitorCommands: true });\n * const stop = instrumentMongo(client);\n * ```\n *\n * **`monitorCommands: true` is required** and cannot be turned on from here: it\n * is a connection option, read when the client is built. Without it the driver\n * emits nothing and this is silently inert — which is the one mistake worth\n * checking for first.\n *\n * It listens to the driver's **public** command monitoring rather than patching\n * anything. No monkey-patching means it keeps working under Bun, where\n * `require-in-the-middle` — what the OpenTelemetry auto-instrumentations use —\n * does not.\n *\n * The span is **recorded, not opened**: monitoring gives a start event and an\n * end event, not a block to run inside. The parent is whatever span was open\n * when the command started, so a query made inside a request lands under that\n * request; a command the driver sends on its own has no parent and starts its\n * own trace.\n *\n * Returns the function that removes the listeners.\n */\nexport function instrumentMongo(\n\tclient: MongoClient,\n\toptions: InstrumentOptions = {},\n): () => void {\n\tconst traced = options.traced ?? notADriverCommand;\n\tconst named = options.spanName ?? commandName;\n\tconst inFlight = new Map<number, InFlight>();\n\n\tconst started = (event: CommandStartedEvent): void => {\n\t\ttry {\n\t\t\tif (!traced(event)) return;\n\n\t\t\t// Read while the command's own async context is still current: by\n\t\t\t// the time the reply arrives, the caller's span may have closed and\n\t\t\t// the storage moved on.\n\t\t\tconst telemetry = options.telemetry ?? resolveTelemetry();\n\t\t\tif (telemetry === undefined) return;\n\n\t\t\tconst parent = currentSpan();\n\t\t\tconst context = contextFor(telemetry, parent);\n\t\t\t// An unsampled trace is unsampled all the way down. Deciding here\n\t\t\t// rather than at the end also means the command is never\n\t\t\t// remembered, so an unsampled service pays nothing for this.\n\t\t\tif (!context.sampled) return;\n\n\t\t\tforget(inFlight);\n\t\t\tinFlight.set(event.requestId, {\n\t\t\t\ttelemetry,\n\t\t\t\tparent,\n\t\t\t\tcontext,\n\t\t\t\tname: named(event),\n\t\t\t\tattributes: commandAttributes(event),\n\t\t\t\tstartedAt: Date.now(),\n\t\t\t});\n\t\t} catch {\n\t\t\t// Instrumentation must not become the reason a query fails.\n\t\t}\n\t};\n\n\tconst ended = (\n\t\trequestId: number,\n\t\tfailure: unknown,\n\t\tduration: number,\n\t): void => {\n\t\ttry {\n\t\t\tconst found = inFlight.get(requestId);\n\t\t\tif (found === undefined) return;\n\t\t\tinFlight.delete(requestId);\n\n\t\t\tfound.telemetry.emit(spanOf(found, failure, duration));\n\t\t} catch {\n\t\t\t// As above.\n\t\t}\n\t};\n\n\tconst succeeded = (event: CommandSucceededEvent): void =>\n\t\tended(event.requestId, undefined, event.duration);\n\tconst failed = (event: CommandFailedEvent): void =>\n\t\tended(event.requestId, event.failure, event.duration);\n\n\tclient.on('commandStarted', started);\n\tclient.on('commandSucceeded', succeeded);\n\tclient.on('commandFailed', failed);\n\n\treturn () => {\n\t\tclient.off('commandStarted', started);\n\t\tclient.off('commandSucceeded', succeeded);\n\t\tclient.off('commandFailed', failed);\n\t\tinFlight.clear();\n\t};\n}\n\nfunction notADriverCommand(event: CommandStartedEvent): boolean {\n\treturn !DRIVER_COMMANDS.has(event.commandName);\n}\n\n/** Drops the oldest entry once the map is full. Insertion order is age. */\nfunction forget(inFlight: Map<number, InFlight>): void {\n\tif (inFlight.size < MAX_IN_FLIGHT) return;\n\n\tconst oldest = inFlight.keys().next();\n\tif (!oldest.done) inFlight.delete(oldest.value);\n}\n",
|
|
9
|
+
"import {\n\ttype Attributes,\n\terrorInfo,\n\tisAbort,\n\trandomSpanId,\n\trandomTraceId,\n\ttype SpanContext,\n\ttype SpanRecord,\n\ttype Telemetry,\n\ttype TraceId,\n} from '@softistx/telemetry';\n\n/** A command that has started and whose reply has not arrived yet. */\nexport interface InFlight {\n\treadonly telemetry: Telemetry;\n\treadonly parent: SpanContext | undefined;\n\treadonly context: SpanContext;\n\treadonly name: string;\n\treadonly attributes: Attributes;\n\treadonly startedAt: number;\n}\n\n/**\n * The span, built rather than opened.\n *\n * The driver reports the command's own `duration`, which is closer to what the\n * server spent than the wall clock between two events on a busy loop, so the\n * start is derived from the end rather than the other way round.\n */\nexport function spanOf(\n\tfound: InFlight,\n\tfailure: unknown,\n\tduration: number,\n): SpanRecord {\n\tconst endedAt = Date.now();\n\tconst startedAt = Math.min(endedAt - Math.max(duration, 0), found.startedAt);\n\n\treturn {\n\t\ttype: 'span',\n\t\tname: found.name,\n\t\tcontext: found.context,\n\t\t...(found.parent === undefined ? {} : { parent: found.parent.spanId }),\n\t\tkind: 'client',\n\t\tstartedAt,\n\t\tendedAt,\n\t\tstatus:\n\t\t\tfailure === undefined ? 'ok' : isAbort(failure) ? 'cancelled' : 'error',\n\t\tattributes: found.attributes,\n\t\tevents: [],\n\t\t...(failure === undefined\n\t\t\t? {}\n\t\t\t: { error: errorInfo(failure, found.telemetry.stackTraces) }),\n\t};\n}\n\n/**\n * The span's place in a trace, decided when the command starts.\n *\n * A command inside a request inherits that request's trace **and its sampling\n * decision** — sampling is decided once, by the root, and a sampler asked again\n * per span produces traces missing their middles. A command with nothing above\n * it *is* a root, so it asks the sampler exactly as `span()` would.\n */\nexport function contextFor(\n\ttelemetry: Telemetry,\n\tparent: SpanContext | undefined,\n): SpanContext {\n\tif (parent !== undefined) {\n\t\treturn {\n\t\t\ttraceId: parent.traceId,\n\t\t\tspanId: randomSpanId(),\n\t\t\tsampled: parent.sampled,\n\t\t\tremote: false,\n\t\t};\n\t}\n\n\tconst traceId = randomTraceId();\n\treturn {\n\t\ttraceId,\n\t\tspanId: randomSpanId(),\n\t\tsampled: sampled(telemetry, traceId),\n\t\tremote: false,\n\t};\n}\n\nfunction sampled(telemetry: Telemetry, traceId: TraceId): boolean {\n\ttry {\n\t\treturn telemetry.sampler.sample(traceId);\n\t} catch {\n\t\t// A sampler that throws must not cost the command; keeping the span is\n\t\t// the answer that loses nothing.\n\t\treturn true;\n\t}\n}\n"
|
|
10
|
+
],
|
|
11
|
+
"mappings": ";AAAA;AAGO,IAAM,YAAY;AAClB,IAAM,eAAe;AACrB,IAAM,gBAAgB;AACtB,IAAM,eAAe;AACrB,IAAM,iBAAiB;AACvB,IAAM,cAAc;AAEpB,IAAM,UAAU;AAQhB,SAAS,iBAAiB,CAAC,OAAwC;AAAA,EACzE,MAAM,aAAa,aAAa,KAAK;AAAA,EACrC,OAAO,MAAM,QAAQ,aAAa,MAAM,OAAO;AAAA,EAE/C,OAAO,aAAa;AAAA,KAClB,YAAY;AAAA,KACZ,eAAe,MAAM;AAAA,KACrB,eAAe,MAAM;AAAA,OAClB,eAAe,YAAY,CAAC,IAAI,GAAG,gBAAgB,WAAW;AAAA,OAC9D,SAAS,YAAY,CAAC,IAAI,GAAG,iBAAiB,KAAK;AAAA,OACnD,SAAS,YAAY,CAAC,IAAI,GAAG,cAAc,KAAK;AAAA,EACrD,CAAC;AAAA;AAaK,SAAS,YAAY,CAAC,OAAgD;AAAA,EAC5E,IAAI;AAAA,IACH,MAAM,QAAQ,MAAM,UAAU,MAAM;AAAA,IACpC,OAAO,OAAO,UAAU,WAAW,QAAQ;AAAA,IAC1C,MAAM;AAAA,IACP;AAAA;AAAA;AAKK,SAAS,WAAW,CAAC,OAAoC;AAAA,EAC/D,MAAM,aAAa,aAAa,KAAK;AAAA,EACr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IAAI,iBAAiB,MAAM;AAAA,IAClC,SAAS,MAAM;AAAA;AAAA;AAIjB,SAAS,iBAAiB,CAAC,OAAqC;AAAA,EAC/D,OAAO,CAAC,gBAAgB,IAAI,MAAM,WAAW;AAAA;AAI9C,SAAS,MAAM,CAAC,UAAuC;AAAA,EACtD,IAAI,SAAS,OAAO;AAAA,IAAe;AAAA,EAEnC,MAAM,SAAS,SAAS,KAAK,EAAE,KAAK;AAAA,EACpC,IAAI,CAAC,OAAO;AAAA,IAAM,SAAS,OAAO,OAAO,KAAK;AAAA;",
|
|
12
|
+
"debugId": "12628BA2433AA01B64756E2164756E21",
|
|
13
|
+
"names": []
|
|
14
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { type Telemetry } from '@softistx/telemetry';
|
|
2
|
+
import type { CommandStartedEvent, MongoClient } from 'mongodb';
|
|
3
|
+
/**
|
|
4
|
+
* The commands the driver sends on its own behalf: the handshake, the heartbeat,
|
|
5
|
+
* authentication, session cleanup.
|
|
6
|
+
*
|
|
7
|
+
* These are skipped by default, and it is the one place in this library where
|
|
8
|
+
* something is. Everywhere else nothing is skipped, because a library that
|
|
9
|
+
* decides which of *your* work does not matter hides the one that did — but a
|
|
10
|
+
* heartbeat every ten seconds on every connection is not your work at all, and
|
|
11
|
+
* a trace full of `hello` is a trace nobody reads.
|
|
12
|
+
*/
|
|
13
|
+
export declare const DRIVER_COMMANDS: ReadonlySet<string>;
|
|
14
|
+
/**
|
|
15
|
+
* How many commands may be in flight before the oldest is forgotten.
|
|
16
|
+
*
|
|
17
|
+
* A command that neither succeeds nor fails — a connection dropped between the
|
|
18
|
+
* two events — would otherwise be remembered for ever. Forgetting it costs one
|
|
19
|
+
* span; not forgetting it costs the process.
|
|
20
|
+
*/
|
|
21
|
+
export declare const MAX_IN_FLIGHT = 4096;
|
|
22
|
+
export interface InstrumentOptions {
|
|
23
|
+
/**
|
|
24
|
+
* Whether a command gets a span. Default: everything except
|
|
25
|
+
* {@link DRIVER_COMMANDS}.
|
|
26
|
+
*/
|
|
27
|
+
readonly traced?: (event: CommandStartedEvent) => boolean;
|
|
28
|
+
/** The span's name. Default `"<command> <collection>"`, or the database. */
|
|
29
|
+
readonly spanName?: (event: CommandStartedEvent) => string;
|
|
30
|
+
/**
|
|
31
|
+
* The telemetry to write to. Default: the one in scope when the command
|
|
32
|
+
* started, and the installed one otherwise.
|
|
33
|
+
*/
|
|
34
|
+
readonly telemetry?: Telemetry;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Client spans for every command the driver sends.
|
|
38
|
+
*
|
|
39
|
+
* ```ts
|
|
40
|
+
* const client = new MongoClient(uri, { monitorCommands: true });
|
|
41
|
+
* const stop = instrumentMongo(client);
|
|
42
|
+
* ```
|
|
43
|
+
*
|
|
44
|
+
* **`monitorCommands: true` is required** and cannot be turned on from here: it
|
|
45
|
+
* is a connection option, read when the client is built. Without it the driver
|
|
46
|
+
* emits nothing and this is silently inert — which is the one mistake worth
|
|
47
|
+
* checking for first.
|
|
48
|
+
*
|
|
49
|
+
* It listens to the driver's **public** command monitoring rather than patching
|
|
50
|
+
* anything. No monkey-patching means it keeps working under Bun, where
|
|
51
|
+
* `require-in-the-middle` — what the OpenTelemetry auto-instrumentations use —
|
|
52
|
+
* does not.
|
|
53
|
+
*
|
|
54
|
+
* The span is **recorded, not opened**: monitoring gives a start event and an
|
|
55
|
+
* end event, not a block to run inside. The parent is whatever span was open
|
|
56
|
+
* when the command started, so a query made inside a request lands under that
|
|
57
|
+
* request; a command the driver sends on its own has no parent and starts its
|
|
58
|
+
* own trace.
|
|
59
|
+
*
|
|
60
|
+
* Returns the function that removes the listeners.
|
|
61
|
+
*/
|
|
62
|
+
export declare function instrumentMongo(client: MongoClient, options?: InstrumentOptions): () => void;
|
|
63
|
+
//# sourceMappingURL=commands.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"commands.d.ts","sourceRoot":"","sources":["../../src/instrument/commands.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,KAAK,SAAS,EACd,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAEX,mBAAmB,EAEnB,WAAW,EACX,MAAM,SAAS,CAAC;AAIjB;;;;;;;;;GASG;AACH,eAAO,MAAM,eAAe,EAAE,WAAW,CAAC,MAAM,CAa9C,CAAC;AAEH;;;;;;GAMG;AACH,eAAO,MAAM,aAAa,OAAQ,CAAC;AAEnC,MAAM,WAAW,iBAAiB;IACjC;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,mBAAmB,KAAK,OAAO,CAAC;IAC1D,4EAA4E;IAC5E,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,mBAAmB,KAAK,MAAM,CAAC;IAC3D;;;OAGG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,SAAS,CAAC;CAC/B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAgB,eAAe,CAC9B,MAAM,EAAE,WAAW,EACnB,OAAO,GAAE,iBAAsB,GAC7B,MAAM,IAAI,CAmEZ"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { type Attributes, type SpanContext, type SpanRecord, type Telemetry } from '@softistx/telemetry';
|
|
2
|
+
/** A command that has started and whose reply has not arrived yet. */
|
|
3
|
+
export interface InFlight {
|
|
4
|
+
readonly telemetry: Telemetry;
|
|
5
|
+
readonly parent: SpanContext | undefined;
|
|
6
|
+
readonly context: SpanContext;
|
|
7
|
+
readonly name: string;
|
|
8
|
+
readonly attributes: Attributes;
|
|
9
|
+
readonly startedAt: number;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* The span, built rather than opened.
|
|
13
|
+
*
|
|
14
|
+
* The driver reports the command's own `duration`, which is closer to what the
|
|
15
|
+
* server spent than the wall clock between two events on a busy loop, so the
|
|
16
|
+
* start is derived from the end rather than the other way round.
|
|
17
|
+
*/
|
|
18
|
+
export declare function spanOf(found: InFlight, failure: unknown, duration: number): SpanRecord;
|
|
19
|
+
/**
|
|
20
|
+
* The span's place in a trace, decided when the command starts.
|
|
21
|
+
*
|
|
22
|
+
* A command inside a request inherits that request's trace **and its sampling
|
|
23
|
+
* decision** — sampling is decided once, by the root, and a sampler asked again
|
|
24
|
+
* per span produces traces missing their middles. A command with nothing above
|
|
25
|
+
* it *is* a root, so it asks the sampler exactly as `span()` would.
|
|
26
|
+
*/
|
|
27
|
+
export declare function contextFor(telemetry: Telemetry, parent: SpanContext | undefined): SpanContext;
|
|
28
|
+
//# sourceMappingURL=record.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"record.d.ts","sourceRoot":"","sources":["../../src/instrument/record.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,UAAU,EAKf,KAAK,WAAW,EAChB,KAAK,UAAU,EACf,KAAK,SAAS,EAEd,MAAM,qBAAqB,CAAC;AAE7B,sEAAsE;AACtE,MAAM,WAAW,QAAQ;IACxB,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAC;IAC9B,QAAQ,CAAC,MAAM,EAAE,WAAW,GAAG,SAAS,CAAC;IACzC,QAAQ,CAAC,OAAO,EAAE,WAAW,CAAC;IAC9B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,UAAU,EAAE,UAAU,CAAC;IAChC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;CAC3B;AAED;;;;;;GAMG;AACH,wBAAgB,MAAM,CACrB,KAAK,EAAE,QAAQ,EACf,OAAO,EAAE,OAAO,EAChB,QAAQ,EAAE,MAAM,GACd,UAAU,CAoBZ;AAED;;;;;;;GAOG;AACH,wBAAgB,UAAU,CACzB,SAAS,EAAE,SAAS,EACpB,MAAM,EAAE,WAAW,GAAG,SAAS,GAC7B,WAAW,CAiBb"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,72 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@softistx/telemetry-mongo",
|
|
3
|
+
"version": "0.3.4",
|
|
4
|
+
"description": "MongoDB for @softistx/telemetry: an exporter that writes signals to a capped-by-TTL collection, and client spans from the driver's command monitoring",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"files": [
|
|
10
|
+
"dist",
|
|
11
|
+
"README.md",
|
|
12
|
+
"package.json",
|
|
13
|
+
"LICENSE"
|
|
14
|
+
],
|
|
15
|
+
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"import": "./dist/index.js",
|
|
19
|
+
"default": "./dist/index.js"
|
|
20
|
+
},
|
|
21
|
+
"./package.json": "./package.json"
|
|
22
|
+
},
|
|
23
|
+
"keywords": [
|
|
24
|
+
"mongodb",
|
|
25
|
+
"mongoose",
|
|
26
|
+
"telemetry",
|
|
27
|
+
"observability",
|
|
28
|
+
"tracing",
|
|
29
|
+
"logging",
|
|
30
|
+
"opentelemetry",
|
|
31
|
+
"typescript"
|
|
32
|
+
],
|
|
33
|
+
"repository": {
|
|
34
|
+
"type": "git",
|
|
35
|
+
"url": "git+https://github.com/softistx/nxgt-telemetry.git",
|
|
36
|
+
"directory": "packages/telemetry-mongo"
|
|
37
|
+
},
|
|
38
|
+
"publishConfig": {
|
|
39
|
+
"registry": "https://registry.npmjs.org",
|
|
40
|
+
"access": "public"
|
|
41
|
+
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"build": "bun run ../../build.ts",
|
|
44
|
+
"test": "bun test src",
|
|
45
|
+
"typecheck": "tsc --noEmit"
|
|
46
|
+
},
|
|
47
|
+
"nxgt": {
|
|
48
|
+
"entrypoints": [
|
|
49
|
+
"src/index.ts"
|
|
50
|
+
]
|
|
51
|
+
},
|
|
52
|
+
"dependencies": {
|
|
53
|
+
"@softistx/telemetry": "^0.5.0"
|
|
54
|
+
},
|
|
55
|
+
"devDependencies": {
|
|
56
|
+
"@types/bun": "^1.4.2",
|
|
57
|
+
"mongodb": "7.6.0",
|
|
58
|
+
"mongodb-memory-server-core": "11.2.0"
|
|
59
|
+
},
|
|
60
|
+
"peerDependencies": {
|
|
61
|
+
"mongodb": ">=7.0.0 <8",
|
|
62
|
+
"typescript": "^6.0.3 || ^7.0.0"
|
|
63
|
+
},
|
|
64
|
+
"peerDependenciesMeta": {
|
|
65
|
+
"mongodb": {
|
|
66
|
+
"optional": true
|
|
67
|
+
},
|
|
68
|
+
"typescript": {
|
|
69
|
+
"optional": true
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|