@tracemole/nextjs-mongodb-explain 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +176 -0
- package/README.md +60 -0
- package/dist/chunk-P6U6LTVD.js +62 -0
- package/dist/client.d.ts +38 -0
- package/dist/client.js +14 -0
- package/dist/index.d.ts +33 -0
- package/dist/index.js +324 -0
- package/package.json +70 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. for the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
translation or transformation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if distributed along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
package/README.md
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# @tracemole/nextjs-mongodb-explain
|
|
2
|
+
|
|
3
|
+
Attach `executionStats` from MongoDB explain queries to your active OpenTelemetry spans. This allows APM dashboards (such as TraceMole) to render database execution plans, highlighting index usage, document scan ratios, and collection scan warnings in query waterfalls.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install @tracemole/nextjs-mongodb-explain
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Make sure you also have `@opentelemetry/api` and `mongodb` installed in your project.
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
### 1. Wrap query executions with `withMongoExplain`
|
|
16
|
+
|
|
17
|
+
The easiest way to measure query efficiency is to wrap your database commands with `withMongoExplain`:
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { withMongoExplain } from "@tracemole/nextjs-mongodb-explain";
|
|
21
|
+
|
|
22
|
+
const users = await withMongoExplain({
|
|
23
|
+
// Run your actual query instrumented by OTel
|
|
24
|
+
run: () => db.collection("users").find({ status: "active" }).limit(10).toArray(),
|
|
25
|
+
|
|
26
|
+
// Run the same query filter with .explain("executionStats")
|
|
27
|
+
explain: () =>
|
|
28
|
+
db.collection("users").find({ status: "active" }).limit(10).explain("executionStats"),
|
|
29
|
+
|
|
30
|
+
// Optional label shown in the APM trace
|
|
31
|
+
label: "find active users",
|
|
32
|
+
});
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
### 2. Manual Attachment
|
|
36
|
+
|
|
37
|
+
If you already have an explain result block, you can attach it manually to the active span:
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
import {
|
|
41
|
+
attachExplainToActiveSpan,
|
|
42
|
+
parseExplainStats,
|
|
43
|
+
} from "@tracemole/nextjs-mongodb-explain";
|
|
44
|
+
|
|
45
|
+
const explainResult = await collection.find(filter).explain("executionStats");
|
|
46
|
+
const stats = parseExplainStats(explainResult);
|
|
47
|
+
|
|
48
|
+
// Attaches database explain attributes to the current span
|
|
49
|
+
await attachExplainToActiveSpan(stats);
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Features
|
|
53
|
+
|
|
54
|
+
- **Zero overhead in production**: Set `TRACE_MOLE_MONGO_EXPLAIN=0` to skip the explain queries entirely in production environments.
|
|
55
|
+
- **Automatic Parsing**: Formats verbose MongoDB execution plan trees into standardized `db.mongodb.explain.*` OpenTelemetry span attributes.
|
|
56
|
+
- **Supports pipelines**: Works with both `find` operations and `aggregate` stages.
|
|
57
|
+
|
|
58
|
+
## License
|
|
59
|
+
|
|
60
|
+
[Apache-2.0](LICENSE)
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// src/attributes.ts
|
|
2
|
+
var MONGO_EXPLAIN_PREFIX = "db.mongodb.explain";
|
|
3
|
+
var MONGO_EXPLAIN_ATTR = {
|
|
4
|
+
operation: `${MONGO_EXPLAIN_PREFIX}.operation`,
|
|
5
|
+
collection: `${MONGO_EXPLAIN_PREFIX}.collection`,
|
|
6
|
+
docsExamined: `${MONGO_EXPLAIN_PREFIX}.docs_examined`,
|
|
7
|
+
docsReturned: `${MONGO_EXPLAIN_PREFIX}.docs_returned`,
|
|
8
|
+
keysExamined: `${MONGO_EXPLAIN_PREFIX}.keys_examined`,
|
|
9
|
+
executionTimeMs: `${MONGO_EXPLAIN_PREFIX}.execution_time_ms`,
|
|
10
|
+
indexUsed: `${MONGO_EXPLAIN_PREFIX}.index_used`,
|
|
11
|
+
indexName: `${MONGO_EXPLAIN_PREFIX}.index_name`,
|
|
12
|
+
stage: `${MONGO_EXPLAIN_PREFIX}.stage`
|
|
13
|
+
};
|
|
14
|
+
function explainAttributes(stats) {
|
|
15
|
+
const attrs = {
|
|
16
|
+
[MONGO_EXPLAIN_ATTR.operation]: stats.operation,
|
|
17
|
+
[MONGO_EXPLAIN_ATTR.docsExamined]: stats.docsExamined,
|
|
18
|
+
[MONGO_EXPLAIN_ATTR.docsReturned]: stats.docsReturned,
|
|
19
|
+
[MONGO_EXPLAIN_ATTR.keysExamined]: stats.keysExamined,
|
|
20
|
+
[MONGO_EXPLAIN_ATTR.executionTimeMs]: stats.executionTimeMs,
|
|
21
|
+
[MONGO_EXPLAIN_ATTR.indexUsed]: stats.indexUsed,
|
|
22
|
+
[MONGO_EXPLAIN_ATTR.stage]: stats.stage
|
|
23
|
+
};
|
|
24
|
+
if (stats.collection) attrs[MONGO_EXPLAIN_ATTR.collection] = stats.collection;
|
|
25
|
+
if (stats.indexName) attrs[MONGO_EXPLAIN_ATTR.indexName] = stats.indexName;
|
|
26
|
+
return attrs;
|
|
27
|
+
}
|
|
28
|
+
function readExplainFromAttributes(attributes) {
|
|
29
|
+
const operation = attributes[MONGO_EXPLAIN_ATTR.operation];
|
|
30
|
+
if (typeof operation !== "string" || !operation) return null;
|
|
31
|
+
const docsExamined = attributes[MONGO_EXPLAIN_ATTR.docsExamined];
|
|
32
|
+
const docsReturned = attributes[MONGO_EXPLAIN_ATTR.docsReturned];
|
|
33
|
+
const keysExamined = attributes[MONGO_EXPLAIN_ATTR.keysExamined];
|
|
34
|
+
const executionTimeMs = attributes[MONGO_EXPLAIN_ATTR.executionTimeMs];
|
|
35
|
+
const indexUsed = attributes[MONGO_EXPLAIN_ATTR.indexUsed];
|
|
36
|
+
const stage = attributes[MONGO_EXPLAIN_ATTR.stage];
|
|
37
|
+
const collection = attributes[MONGO_EXPLAIN_ATTR.collection];
|
|
38
|
+
const indexName = attributes[MONGO_EXPLAIN_ATTR.indexName];
|
|
39
|
+
return {
|
|
40
|
+
operation,
|
|
41
|
+
collection: typeof collection === "string" ? collection : void 0,
|
|
42
|
+
docsExamined: typeof docsExamined === "number" ? docsExamined : Number(docsExamined ?? 0),
|
|
43
|
+
docsReturned: typeof docsReturned === "number" ? docsReturned : Number(docsReturned ?? 0),
|
|
44
|
+
keysExamined: typeof keysExamined === "number" ? keysExamined : Number(keysExamined ?? 0),
|
|
45
|
+
executionTimeMs: typeof executionTimeMs === "number" ? executionTimeMs : Number(executionTimeMs ?? 0),
|
|
46
|
+
indexUsed: indexUsed === true || indexUsed === "true",
|
|
47
|
+
indexName: typeof indexName === "string" ? indexName : void 0,
|
|
48
|
+
stage: typeof stage === "string" ? stage : "unknown",
|
|
49
|
+
scanType: indexUsed === true || indexUsed === "true" ? "index" : stage === "COLLSCAN" ? "collection" : "other"
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function hasMongoExplainAttributes(attributes) {
|
|
53
|
+
return MONGO_EXPLAIN_ATTR.operation in attributes;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export {
|
|
57
|
+
MONGO_EXPLAIN_PREFIX,
|
|
58
|
+
MONGO_EXPLAIN_ATTR,
|
|
59
|
+
explainAttributes,
|
|
60
|
+
readExplainFromAttributes,
|
|
61
|
+
hasMongoExplainAttributes
|
|
62
|
+
};
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
type MongoExplainStats = {
|
|
2
|
+
/** MongoDB command type: find, aggregate, count, etc. */
|
|
3
|
+
operation: string;
|
|
4
|
+
collection?: string;
|
|
5
|
+
/** Documents examined (scanned) during execution. */
|
|
6
|
+
docsExamined: number;
|
|
7
|
+
/** Documents returned to the client. */
|
|
8
|
+
docsReturned: number;
|
|
9
|
+
/** Index keys examined (0 when no index used). */
|
|
10
|
+
keysExamined: number;
|
|
11
|
+
executionTimeMs: number;
|
|
12
|
+
/** True when the winning plan used an index (IXSCAN). */
|
|
13
|
+
indexUsed: boolean;
|
|
14
|
+
indexName?: string;
|
|
15
|
+
/** Winning plan stage: IXSCAN, COLLSCAN, FETCH, etc. */
|
|
16
|
+
stage: string;
|
|
17
|
+
scanType: "index" | "collection" | "other";
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/** OpenTelemetry span attribute prefix for MongoDB explain stats. */
|
|
21
|
+
declare const MONGO_EXPLAIN_PREFIX = "db.mongodb.explain";
|
|
22
|
+
declare const MONGO_EXPLAIN_ATTR: {
|
|
23
|
+
readonly operation: "db.mongodb.explain.operation";
|
|
24
|
+
readonly collection: "db.mongodb.explain.collection";
|
|
25
|
+
readonly docsExamined: "db.mongodb.explain.docs_examined";
|
|
26
|
+
readonly docsReturned: "db.mongodb.explain.docs_returned";
|
|
27
|
+
readonly keysExamined: "db.mongodb.explain.keys_examined";
|
|
28
|
+
readonly executionTimeMs: "db.mongodb.explain.execution_time_ms";
|
|
29
|
+
readonly indexUsed: "db.mongodb.explain.index_used";
|
|
30
|
+
readonly indexName: "db.mongodb.explain.index_name";
|
|
31
|
+
readonly stage: "db.mongodb.explain.stage";
|
|
32
|
+
};
|
|
33
|
+
type MongoExplainAttributeValue = string | number | boolean;
|
|
34
|
+
declare function explainAttributes(stats: MongoExplainStats): Record<string, MongoExplainAttributeValue>;
|
|
35
|
+
declare function readExplainFromAttributes(attributes: Record<string, string | number | boolean>): MongoExplainStats | null;
|
|
36
|
+
declare function hasMongoExplainAttributes(attributes: Record<string, string | number | boolean>): boolean;
|
|
37
|
+
|
|
38
|
+
export { MONGO_EXPLAIN_ATTR, MONGO_EXPLAIN_PREFIX, type MongoExplainAttributeValue, type MongoExplainStats, explainAttributes, hasMongoExplainAttributes, readExplainFromAttributes };
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import {
|
|
2
|
+
MONGO_EXPLAIN_ATTR,
|
|
3
|
+
MONGO_EXPLAIN_PREFIX,
|
|
4
|
+
explainAttributes,
|
|
5
|
+
hasMongoExplainAttributes,
|
|
6
|
+
readExplainFromAttributes
|
|
7
|
+
} from "./chunk-P6U6LTVD.js";
|
|
8
|
+
export {
|
|
9
|
+
MONGO_EXPLAIN_ATTR,
|
|
10
|
+
MONGO_EXPLAIN_PREFIX,
|
|
11
|
+
explainAttributes,
|
|
12
|
+
hasMongoExplainAttributes,
|
|
13
|
+
readExplainFromAttributes
|
|
14
|
+
};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { MongoExplainStats } from './client.js';
|
|
2
|
+
export { MONGO_EXPLAIN_ATTR, MONGO_EXPLAIN_PREFIX, MongoExplainAttributeValue, explainAttributes, hasMongoExplainAttributes, readExplainFromAttributes } from './client.js';
|
|
3
|
+
import { Span } from '@opentelemetry/api';
|
|
4
|
+
|
|
5
|
+
declare function attachExplainToSpan(span: Span, stats: MongoExplainStats): void;
|
|
6
|
+
declare function attachExplainToActiveSpan(stats: MongoExplainStats): Promise<boolean>;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Parse a MongoDB explain result (`verbosity: "executionStats"`) into summary stats.
|
|
10
|
+
* Supports find, aggregate (`stages` + `$cursor`), and profiler-style shapes.
|
|
11
|
+
*/
|
|
12
|
+
declare function parseExplainStats(explain: unknown): MongoExplainStats;
|
|
13
|
+
|
|
14
|
+
type WithMongoExplainOptions<T> = {
|
|
15
|
+
/** Run the real query (already instrumented by OTel MongoDB driver). */
|
|
16
|
+
run: () => Promise<T>;
|
|
17
|
+
/** Run the same command with `.explain("executionStats")`. */
|
|
18
|
+
explain: () => Promise<unknown>;
|
|
19
|
+
/** Skip explain entirely (default: only when `TRACE_MOLE_MONGO_EXPLAIN=0`). */
|
|
20
|
+
enabled?: boolean;
|
|
21
|
+
/** Optional span label shown in the dashboard (e.g. "events aggregate"). */
|
|
22
|
+
label?: string;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Run a MongoDB operation and attach executionStats from a parallel explain call
|
|
26
|
+
* to a dedicated query span (one per `withMongoExplain` call).
|
|
27
|
+
*
|
|
28
|
+
* Explain runs after the query without creating a `mongodb.explain` driver span.
|
|
29
|
+
* Set `TRACE_MOLE_MONGO_EXPLAIN=0` to disable in production.
|
|
30
|
+
*/
|
|
31
|
+
declare function withMongoExplain<T>({ run, explain, enabled, label, }: WithMongoExplainOptions<T>): Promise<T>;
|
|
32
|
+
|
|
33
|
+
export { MongoExplainStats, type WithMongoExplainOptions, attachExplainToActiveSpan, attachExplainToSpan, parseExplainStats, withMongoExplain };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
import {
|
|
2
|
+
MONGO_EXPLAIN_ATTR,
|
|
3
|
+
MONGO_EXPLAIN_PREFIX,
|
|
4
|
+
explainAttributes,
|
|
5
|
+
hasMongoExplainAttributes,
|
|
6
|
+
readExplainFromAttributes
|
|
7
|
+
} from "./chunk-P6U6LTVD.js";
|
|
8
|
+
|
|
9
|
+
// src/attach.ts
|
|
10
|
+
function attachExplainToSpan(span, stats) {
|
|
11
|
+
span.setAttributes(explainAttributes(stats));
|
|
12
|
+
}
|
|
13
|
+
async function attachExplainToActiveSpan(stats) {
|
|
14
|
+
try {
|
|
15
|
+
const { trace } = await import("@opentelemetry/api");
|
|
16
|
+
const span = trace.getActiveSpan();
|
|
17
|
+
if (!span) return false;
|
|
18
|
+
attachExplainToSpan(span, stats);
|
|
19
|
+
return true;
|
|
20
|
+
} catch {
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// src/parse.ts
|
|
26
|
+
function asRecord(value) {
|
|
27
|
+
return value != null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
28
|
+
}
|
|
29
|
+
function asNumber(value) {
|
|
30
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
31
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
32
|
+
const n = Number(value);
|
|
33
|
+
if (Number.isFinite(n)) return n;
|
|
34
|
+
}
|
|
35
|
+
return void 0;
|
|
36
|
+
}
|
|
37
|
+
function asStage(value) {
|
|
38
|
+
const record = asRecord(value);
|
|
39
|
+
if (!record) return null;
|
|
40
|
+
return {
|
|
41
|
+
stage: typeof record.stage === "string" ? record.stage : void 0,
|
|
42
|
+
indexName: typeof record.indexName === "string" ? record.indexName : void 0,
|
|
43
|
+
docsExamined: asNumber(record.docsExamined),
|
|
44
|
+
keysExamined: asNumber(record.keysExamined),
|
|
45
|
+
inputStage: asStage(record.inputStage) ?? void 0,
|
|
46
|
+
inputStages: Array.isArray(record.inputStages) ? record.inputStages.map((s) => asStage(s)).filter((s) => s != null) : void 0
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
function walkStages(stage) {
|
|
50
|
+
if (!stage) return [];
|
|
51
|
+
const nested = stage.inputStage ? walkStages(stage.inputStage) : (stage.inputStages ?? []).flatMap((s) => walkStages(s));
|
|
52
|
+
return [stage, ...nested];
|
|
53
|
+
}
|
|
54
|
+
function findIndexStage(stages) {
|
|
55
|
+
return stages.find((s) => s.stage === "IXSCAN");
|
|
56
|
+
}
|
|
57
|
+
function findCollScanStage(stages) {
|
|
58
|
+
return stages.find((s) => s.stage === "COLLSCAN");
|
|
59
|
+
}
|
|
60
|
+
function readIndexesUsed(value) {
|
|
61
|
+
if (!Array.isArray(value)) return [];
|
|
62
|
+
return value.filter((v) => typeof v === "string" && v.length > 0);
|
|
63
|
+
}
|
|
64
|
+
function mergeExecution(current, next) {
|
|
65
|
+
if (!current) return next;
|
|
66
|
+
return {
|
|
67
|
+
nReturned: Math.max(current.nReturned, next.nReturned),
|
|
68
|
+
executionTimeMs: current.executionTimeMs + next.executionTimeMs,
|
|
69
|
+
keysExamined: current.keysExamined + next.keysExamined,
|
|
70
|
+
docsExamined: current.docsExamined + next.docsExamined,
|
|
71
|
+
executionStages: current.executionStages ?? next.executionStages,
|
|
72
|
+
indexesUsed: [.../* @__PURE__ */ new Set([...current.indexesUsed, ...next.indexesUsed])],
|
|
73
|
+
planSummary: current.planSummary ?? next.planSummary
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
function fromExecutionStatsBlock(stats) {
|
|
77
|
+
const executionStages = asStage(stats.executionStages) ?? (typeof stats.stage === "string" ? asStage(stats) : null);
|
|
78
|
+
return {
|
|
79
|
+
nReturned: asNumber(stats.nReturned) ?? 0,
|
|
80
|
+
executionTimeMs: asNumber(stats.executionTimeMillis) ?? asNumber(stats.executionTimeMillisEstimate) ?? 0,
|
|
81
|
+
keysExamined: asNumber(stats.totalKeysExamined) ?? 0,
|
|
82
|
+
docsExamined: asNumber(stats.totalDocsExamined) ?? 0,
|
|
83
|
+
executionStages: executionStages ?? void 0,
|
|
84
|
+
indexesUsed: readIndexesUsed(stats.indexesUsed),
|
|
85
|
+
planSummary: typeof stats.planSummary === "string" ? stats.planSummary : void 0
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
function fromStageTree(stats) {
|
|
89
|
+
const stageTree = asStage(stats.executionStages ?? stats) ?? void 0;
|
|
90
|
+
const walked = walkStages(stageTree);
|
|
91
|
+
const indexStage = findIndexStage(walked);
|
|
92
|
+
const collScan = findCollScanStage(walked);
|
|
93
|
+
const docsFromStages = walked.reduce(
|
|
94
|
+
(sum, s) => sum + (s.docsExamined ?? 0),
|
|
95
|
+
0
|
|
96
|
+
);
|
|
97
|
+
const keysFromStages = walked.reduce(
|
|
98
|
+
(sum, s) => sum + (s.keysExamined ?? 0),
|
|
99
|
+
0
|
|
100
|
+
);
|
|
101
|
+
return {
|
|
102
|
+
nReturned: asNumber(stats.nReturned) ?? 0,
|
|
103
|
+
executionTimeMs: asNumber(stats.executionTimeMillis) ?? asNumber(stats.executionTimeMillisEstimate) ?? 0,
|
|
104
|
+
keysExamined: asNumber(stats.totalKeysExamined) ?? keysFromStages,
|
|
105
|
+
docsExamined: asNumber(stats.totalDocsExamined) ?? docsFromStages,
|
|
106
|
+
executionStages: stageTree,
|
|
107
|
+
indexesUsed: [
|
|
108
|
+
...readIndexesUsed(stats.indexesUsed),
|
|
109
|
+
...indexStage?.indexName ? [indexStage.indexName] : []
|
|
110
|
+
],
|
|
111
|
+
planSummary: typeof stats.planSummary === "string" ? stats.planSummary : void 0
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
function collectFromPipelineStages(stages) {
|
|
115
|
+
let merged = null;
|
|
116
|
+
for (const stageEntry of stages) {
|
|
117
|
+
const entry = asRecord(stageEntry);
|
|
118
|
+
if (!entry) continue;
|
|
119
|
+
for (const [stageName, stageBody] of Object.entries(entry)) {
|
|
120
|
+
const body = asRecord(stageBody);
|
|
121
|
+
if (!body) continue;
|
|
122
|
+
const stats = asRecord(body.executionStats);
|
|
123
|
+
if (stats) {
|
|
124
|
+
const normalized = asNumber(stats.totalDocsExamined) != null || asNumber(stats.totalKeysExamined) != null ? fromExecutionStatsBlock(stats) : fromStageTree(stats);
|
|
125
|
+
merged = mergeExecution(merged, normalized);
|
|
126
|
+
} else if (asNumber(body.executionTimeMillisEstimate) != null) {
|
|
127
|
+
merged = mergeExecution(merged, {
|
|
128
|
+
nReturned: 0,
|
|
129
|
+
executionTimeMs: asNumber(body.executionTimeMillisEstimate) ?? 0,
|
|
130
|
+
keysExamined: 0,
|
|
131
|
+
docsExamined: 0,
|
|
132
|
+
indexesUsed: []
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
if (stageName === "$cursor") {
|
|
136
|
+
const planner = asRecord(body.queryPlanner);
|
|
137
|
+
const winning = asRecord(planner?.winningPlan);
|
|
138
|
+
if (winning && !merged?.executionStages) {
|
|
139
|
+
const stageTree = asStage(winning) ?? void 0;
|
|
140
|
+
merged = mergeExecution(merged, {
|
|
141
|
+
nReturned: 0,
|
|
142
|
+
executionTimeMs: 0,
|
|
143
|
+
keysExamined: 0,
|
|
144
|
+
docsExamined: 0,
|
|
145
|
+
executionStages: stageTree,
|
|
146
|
+
indexesUsed: []
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return merged;
|
|
153
|
+
}
|
|
154
|
+
function normalizeExecution(explain) {
|
|
155
|
+
const topStats = asRecord(explain.executionStats);
|
|
156
|
+
if (topStats) {
|
|
157
|
+
const normalized = asNumber(topStats.totalDocsExamined) != null || asNumber(topStats.totalKeysExamined) != null || topStats.executionStages != null ? fromExecutionStatsBlock(topStats) : fromStageTree(topStats);
|
|
158
|
+
return normalized;
|
|
159
|
+
}
|
|
160
|
+
if (Array.isArray(explain.stages)) {
|
|
161
|
+
return collectFromPipelineStages(explain.stages);
|
|
162
|
+
}
|
|
163
|
+
if (asNumber(explain.docsExamined) != null) {
|
|
164
|
+
return {
|
|
165
|
+
nReturned: asNumber(explain.nreturned) ?? asNumber(explain.nReturned) ?? 0,
|
|
166
|
+
executionTimeMs: asNumber(explain.millis) ?? asNumber(explain.durationMillis) ?? 0,
|
|
167
|
+
keysExamined: asNumber(explain.keysExamined) ?? 0,
|
|
168
|
+
docsExamined: asNumber(explain.docsExamined) ?? 0,
|
|
169
|
+
indexesUsed: [],
|
|
170
|
+
planSummary: typeof explain.planSummary === "string" ? explain.planSummary : void 0
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
return null;
|
|
174
|
+
}
|
|
175
|
+
function commandOperation(command) {
|
|
176
|
+
const ops = [
|
|
177
|
+
"find",
|
|
178
|
+
"aggregate",
|
|
179
|
+
"count",
|
|
180
|
+
"distinct",
|
|
181
|
+
"delete",
|
|
182
|
+
"update",
|
|
183
|
+
"findAndModify"
|
|
184
|
+
];
|
|
185
|
+
for (const op of ops) {
|
|
186
|
+
if (op in command) return op;
|
|
187
|
+
}
|
|
188
|
+
if (Array.isArray(command.pipeline)) return "aggregate";
|
|
189
|
+
return "unknown";
|
|
190
|
+
}
|
|
191
|
+
function commandCollection(command, operation) {
|
|
192
|
+
const direct = command[operation];
|
|
193
|
+
if (typeof direct === "string" && direct) return direct;
|
|
194
|
+
const collection = command.collection;
|
|
195
|
+
if (typeof collection === "string" && collection) return collection;
|
|
196
|
+
return void 0;
|
|
197
|
+
}
|
|
198
|
+
function inferOperation(explain) {
|
|
199
|
+
const command = asRecord(explain.command);
|
|
200
|
+
if (command) {
|
|
201
|
+
const op = commandOperation(command);
|
|
202
|
+
if (op !== "unknown") return op;
|
|
203
|
+
}
|
|
204
|
+
if (Array.isArray(explain.stages)) return "aggregate";
|
|
205
|
+
return "unknown";
|
|
206
|
+
}
|
|
207
|
+
function inferCollection(explain, operation) {
|
|
208
|
+
const command = asRecord(explain.command);
|
|
209
|
+
if (command) {
|
|
210
|
+
const name = commandCollection(command, operation);
|
|
211
|
+
if (name) return name;
|
|
212
|
+
}
|
|
213
|
+
const namespace = explain.namespace;
|
|
214
|
+
if (typeof namespace === "string" && namespace.includes(".")) {
|
|
215
|
+
return namespace.split(".").slice(1).join(".");
|
|
216
|
+
}
|
|
217
|
+
return void 0;
|
|
218
|
+
}
|
|
219
|
+
function indexUsedFrom(execution, walked) {
|
|
220
|
+
const indexStage = findIndexStage(walked);
|
|
221
|
+
const collScanStage = findCollScanStage(walked);
|
|
222
|
+
const indexName = indexStage?.indexName ?? execution.indexesUsed[0];
|
|
223
|
+
const indexUsed = indexStage != null || execution.indexesUsed.length > 0 || execution.planSummary?.includes("IXSCAN") === true;
|
|
224
|
+
const winningStage = indexStage ?? collScanStage ?? walked[0] ?? { stage: execution.planSummary?.split(",")[0] ?? "unknown" };
|
|
225
|
+
const stage = winningStage.stage ?? "unknown";
|
|
226
|
+
const scanType = indexUsed ? "index" : collScanStage || stage === "COLLSCAN" || execution.planSummary === "COLLSCAN" ? "collection" : "other";
|
|
227
|
+
return { indexUsed, indexName, stage, scanType };
|
|
228
|
+
}
|
|
229
|
+
function parseExplainStats(explain) {
|
|
230
|
+
const root = asRecord(explain);
|
|
231
|
+
if (!root) {
|
|
232
|
+
return emptyStats("unknown");
|
|
233
|
+
}
|
|
234
|
+
const execution = normalizeExecution(root);
|
|
235
|
+
const operation = inferOperation(root);
|
|
236
|
+
const collection = inferCollection(root, operation);
|
|
237
|
+
const walked = walkStages(execution?.executionStages);
|
|
238
|
+
const index = indexUsedFrom(execution ?? emptyExecution(), walked);
|
|
239
|
+
return {
|
|
240
|
+
operation,
|
|
241
|
+
collection,
|
|
242
|
+
docsExamined: execution?.docsExamined ?? 0,
|
|
243
|
+
docsReturned: execution?.nReturned ?? 0,
|
|
244
|
+
keysExamined: execution?.keysExamined ?? 0,
|
|
245
|
+
executionTimeMs: execution?.executionTimeMs ?? 0,
|
|
246
|
+
indexUsed: index.indexUsed,
|
|
247
|
+
indexName: index.indexName,
|
|
248
|
+
stage: index.stage,
|
|
249
|
+
scanType: index.scanType
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
function emptyExecution() {
|
|
253
|
+
return {
|
|
254
|
+
nReturned: 0,
|
|
255
|
+
executionTimeMs: 0,
|
|
256
|
+
keysExamined: 0,
|
|
257
|
+
docsExamined: 0,
|
|
258
|
+
indexesUsed: []
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
function emptyStats(operation) {
|
|
262
|
+
return {
|
|
263
|
+
operation,
|
|
264
|
+
docsExamined: 0,
|
|
265
|
+
docsReturned: 0,
|
|
266
|
+
keysExamined: 0,
|
|
267
|
+
executionTimeMs: 0,
|
|
268
|
+
indexUsed: false,
|
|
269
|
+
stage: "unknown",
|
|
270
|
+
scanType: "other"
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// src/suppress-tracing.ts
|
|
275
|
+
import { context, createContextKey } from "@opentelemetry/api";
|
|
276
|
+
var SUPPRESS_TRACING_KEY = createContextKey("suppress_tracing");
|
|
277
|
+
function suppressTracing(ctx) {
|
|
278
|
+
return ctx.setValue(SUPPRESS_TRACING_KEY, true);
|
|
279
|
+
}
|
|
280
|
+
function runWithoutTracing(fn) {
|
|
281
|
+
return context.with(suppressTracing(context.active()), fn);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// src/with-mongo-explain.ts
|
|
285
|
+
function isExplainEnabled(explicit) {
|
|
286
|
+
if (explicit != null) return explicit;
|
|
287
|
+
return process.env.TRACE_MOLE_MONGO_EXPLAIN !== "0";
|
|
288
|
+
}
|
|
289
|
+
async function withMongoExplain({
|
|
290
|
+
run,
|
|
291
|
+
explain,
|
|
292
|
+
enabled,
|
|
293
|
+
label
|
|
294
|
+
}) {
|
|
295
|
+
const { trace } = await import("@opentelemetry/api");
|
|
296
|
+
const tracer = trace.getTracer("tracemole.mongo");
|
|
297
|
+
return tracer.startActiveSpan(label ?? "mongodb.query", async (span) => {
|
|
298
|
+
try {
|
|
299
|
+
const result = await run();
|
|
300
|
+
if (isExplainEnabled(enabled)) {
|
|
301
|
+
try {
|
|
302
|
+
const explainResult = await runWithoutTracing(() => explain());
|
|
303
|
+
const stats = parseExplainStats(explainResult);
|
|
304
|
+
attachExplainToSpan(span, stats);
|
|
305
|
+
} catch {
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
return result;
|
|
309
|
+
} finally {
|
|
310
|
+
span.end();
|
|
311
|
+
}
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
export {
|
|
315
|
+
MONGO_EXPLAIN_ATTR,
|
|
316
|
+
MONGO_EXPLAIN_PREFIX,
|
|
317
|
+
attachExplainToActiveSpan,
|
|
318
|
+
attachExplainToSpan,
|
|
319
|
+
explainAttributes,
|
|
320
|
+
hasMongoExplainAttributes,
|
|
321
|
+
parseExplainStats,
|
|
322
|
+
readExplainFromAttributes,
|
|
323
|
+
withMongoExplain
|
|
324
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@tracemole/nextjs-mongodb-explain",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Attach MongoDB executionStats explain plans to OpenTelemetry spans for Next.js and Node apps",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"files": ["dist", "LICENSE", "README.md"],
|
|
8
|
+
"keywords": [
|
|
9
|
+
"mongodb",
|
|
10
|
+
"explain",
|
|
11
|
+
"opentelemetry",
|
|
12
|
+
"nextjs",
|
|
13
|
+
"tracing",
|
|
14
|
+
"apm",
|
|
15
|
+
"tracemole"
|
|
16
|
+
],
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "https://github.com/tracemole/nextjs-mongodb-explain.git"
|
|
20
|
+
},
|
|
21
|
+
"bugs": {
|
|
22
|
+
"url": "https://github.com/tracemole/nextjs-mongodb-explain/issues"
|
|
23
|
+
},
|
|
24
|
+
"homepage": "https://github.com/tracemole/nextjs-mongodb-explain#readme",
|
|
25
|
+
"publishConfig": {
|
|
26
|
+
"access": "public"
|
|
27
|
+
},
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"typesVersions": {
|
|
30
|
+
"*": {
|
|
31
|
+
"client": ["dist/client.d.ts"],
|
|
32
|
+
"*": ["dist/index.d.ts"]
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"exports": {
|
|
36
|
+
".": {
|
|
37
|
+
"types": "./dist/index.d.ts",
|
|
38
|
+
"import": "./dist/index.js"
|
|
39
|
+
},
|
|
40
|
+
"./client": {
|
|
41
|
+
"types": "./dist/client.d.ts",
|
|
42
|
+
"import": "./dist/client.js"
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
"scripts": {
|
|
46
|
+
"build": "tsup",
|
|
47
|
+
"prepare": "npm run build",
|
|
48
|
+
"check-types": "tsc --noEmit",
|
|
49
|
+
"test": "tsx --test src/parse.test.ts",
|
|
50
|
+
"prepublishOnly": "npm run check-types && npm run test && npm run build"
|
|
51
|
+
},
|
|
52
|
+
"peerDependencies": {
|
|
53
|
+
"@opentelemetry/api": ">=1.9.0"
|
|
54
|
+
},
|
|
55
|
+
"peerDependenciesMeta": {
|
|
56
|
+
"@opentelemetry/api": {
|
|
57
|
+
"optional": true
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
"devDependencies": {
|
|
61
|
+
"@opentelemetry/api": "^1.9.0",
|
|
62
|
+
"@types/node": "^22.15.3",
|
|
63
|
+
"tsup": "^8.5.0",
|
|
64
|
+
"tsx": "^4.19.4",
|
|
65
|
+
"typescript": "5.9.2"
|
|
66
|
+
},
|
|
67
|
+
"engines": {
|
|
68
|
+
"node": ">=18"
|
|
69
|
+
}
|
|
70
|
+
}
|