@8monkey/opentelemetry-instrumentation-bun-sql 0.1.0-rc0

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 ADDED
@@ -0,0 +1,201 @@
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
+ transformation or translation 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 provided 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
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,118 @@
1
+ # OpenTelemetry Bun.SQL Instrumentation
2
+
3
+ OpenTelemetry instrumentation for [Bun.SQL](https://bun.sh/docs/api/sql), the built-in database client in Bun supporting PostgreSQL, MySQL, and SQLite.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ bun add @8monkey/opentelemetry-instrumentation-bun-sql
9
+ ```
10
+
11
+ ## Supported Versions
12
+
13
+ - Bun >= 1.2
14
+
15
+ ## Usage
16
+
17
+ ```typescript
18
+ import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
19
+ import { SimpleSpanProcessor, ConsoleSpanExporter } from "@opentelemetry/sdk-trace-base";
20
+ import { registerInstrumentations } from "@opentelemetry/instrumentation";
21
+ import { BunSqlInstrumentation } from "@8monkey/opentelemetry-instrumentation-bun-sql";
22
+
23
+ // 1. Register instrumentation before creating any SQL instances.
24
+ // Bun built-ins bypass Node.js module hooks, so the instrumentation patches
25
+ // require("bun").SQL at enable time — instances created before this are not traced.
26
+ const provider = new NodeTracerProvider({
27
+ spanProcessors: [new SimpleSpanProcessor(new ConsoleSpanExporter())],
28
+ });
29
+ provider.register();
30
+
31
+ registerInstrumentations({
32
+ instrumentations: [new BunSqlInstrumentation()],
33
+ });
34
+
35
+ // 2. Create instances via require("bun"), not `import { SQL } from "bun"`.
36
+ // Static import bindings are resolved at module load time (before step 1 runs)
37
+ // and therefore always capture the original, unpatched constructor.
38
+ const sql = new (require("bun") as typeof Bun).SQL({ adapter: "sqlite" });
39
+
40
+ await sql`SELECT 1`;
41
+ await sql.close();
42
+ ```
43
+
44
+ ## Semantic Conventions
45
+
46
+ This instrumentation follows the [OpenTelemetry Database Semantic Conventions](https://opentelemetry.io/docs/specs/semconv/database/).
47
+
48
+ ### Attributes
49
+
50
+ | Attribute | Description |
51
+ | --------------------------- | ------------------------------------------------------------------------------------- |
52
+ | `db.system.name` | Database system: `postgresql`, `mysql`, or `sqlite` |
53
+ | `db.operation.name` | SQL operation: `SELECT`, `INSERT`, `UPDATE`, `DELETE`, etc. |
54
+ | `db.query.text` | The SQL query text (parameterized for tagged templates, sanitized for unsafe queries) |
55
+ | `db.namespace` | Database name or SQLite filename |
56
+ | `db.response.returned_rows` | Number of rows returned |
57
+ | `server.address` | Server hostname (PostgreSQL/MySQL) |
58
+ | `server.port` | Server port (PostgreSQL/MySQL) |
59
+ | `error.type` | Error class name (e.g., `SQLiteError`, `PostgresError`) |
60
+ | `db.response.status_code` | Database-specific error code |
61
+
62
+ ### Span names
63
+
64
+ Span names follow the OTel convention priority:
65
+
66
+ 1. `{db.operation.name} {db.namespace}` (e.g., `SELECT mydb`)
67
+ 2. `{db.operation.name}` (e.g., `SELECT`)
68
+ 3. `{db.namespace}` (e.g., `mydb`)
69
+ 4. `{db.system.name}` (e.g., `postgresql`)
70
+
71
+ ## Configuration
72
+
73
+ | Option | Type | Default | Description |
74
+ | --------------------------- | --------------------------- | --------------- | -------------------------------------------------------------------------------------------------- |
75
+ | `requireParentSpan` | `boolean` | `false` | Only create spans when a parent span exists in context |
76
+ | `enhancedDatabaseReporting` | `boolean` | `false` | Include query parameters (`db.query.parameter.<n>`) and result data in spans |
77
+ | `ignoreConnectionSpans` | `boolean` | `false` | Suppress spans for `CLOSE` and `RESERVE` operations |
78
+ | `maskStatement` | `boolean` | `true` | Replace integer literals and quoted strings with `?` in non-parameterized queries (`sql.unsafe()`) |
79
+ | `maskStatementHook` | `(query: string) => string` | Built-in masker | Custom masking function for non-parameterized queries |
80
+ | `addSqlCommenterComment` | `boolean` | `false` | Append SQL commenter traceparent comments to queries |
81
+ | `requestHook` | `(span, info) => void` | - | Called before query execution to customize span attributes |
82
+ | `responseHook` | `(span, info) => void` | - | Called after query execution with response metadata |
83
+
84
+ ### Example with hooks
85
+
86
+ ```typescript
87
+ import type {
88
+ BunSqlRequestHookInformation,
89
+ BunSqlResponseHookInformation,
90
+ } from "@8monkey/opentelemetry-instrumentation-bun-sql";
91
+
92
+ new BunSqlInstrumentation({
93
+ requestHook: (span, info: BunSqlRequestHookInformation) => {
94
+ span.setAttribute("custom.query", info.query);
95
+ },
96
+ responseHook: (span, info: BunSqlResponseHookInformation) => {
97
+ if (info.rowCount !== undefined) {
98
+ span.setAttribute("custom.row_count", info.rowCount);
99
+ }
100
+ },
101
+ });
102
+ ```
103
+
104
+ ## What gets instrumented
105
+
106
+ - **Tagged template queries**: `` sql`SELECT * FROM users WHERE id = ${id}` ``
107
+ - **Unsafe queries**: `sql.unsafe("SELECT * FROM users")`
108
+ - **Queries inside transactions**: queries run inside `sql.begin(tx => ...)`, `tx.savepoint(sp => ...)`, etc. are individually traced; no span is emitted for the transaction boundary itself
109
+ - **Connection management**: `sql.close()`, `sql.reserve()`
110
+ - **Chaining methods**: `.values()`, `.raw()`, `.simple()`, `.execute()`
111
+
112
+ ### Query text handling
113
+
114
+ | Query type | `db.query.text` behavior |
115
+ | ------------------------------------------ | ---------------------------------------------------------- |
116
+ | Tagged template | Parameterized: `SELECT * FROM users WHERE id = $1` |
117
+ | `sql.unsafe()` | Sanitized by default: `SELECT * FROM users WHERE name = ?` |
118
+ | `sql.unsafe()` with `maskStatement: false` | Raw text preserved |
@@ -0,0 +1,2 @@
1
+ export { BunSqlInstrumentation } from "./instrumentation.js";
2
+ export type { BunSqlInstrumentationConfig, BunSqlRequestHookInformation, BunSqlResponseHookInformation, BunSqlInstrumentationExecutionRequestHook, BunSqlInstrumentationExecutionResponseHook, } from "./types.js";
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { BunSqlInstrumentation } from "./instrumentation.js";
@@ -0,0 +1,33 @@
1
+ import { InstrumentationBase } from "@opentelemetry/instrumentation";
2
+ import type { SQL } from "bun";
3
+ import type { BunSqlInstrumentationConfig } from "./types.js";
4
+ export declare class BunSqlInstrumentation extends InstrumentationBase {
5
+ private _originalSQL;
6
+ private _originalSqlSingleton;
7
+ private _patched;
8
+ constructor(config?: BunSqlInstrumentationConfig);
9
+ getConfig(): BunSqlInstrumentationConfig;
10
+ init(): [];
11
+ enable(): void;
12
+ disable(): void;
13
+ private _getBunModule;
14
+ /**
15
+ * Wrap a Bun SQL instance with a Proxy to intercept tagged template calls
16
+ * and method invocations.
17
+ */
18
+ _wrapInstance(instance: SQL): SQL;
19
+ private _handleTaggedTemplate;
20
+ private _wrapUnsafe;
21
+ private _execQuery;
22
+ private _wrapConnOp;
23
+ /**
24
+ * Wrap a lazy query result (thenable) to intercept resolution/rejection
25
+ * for span lifecycle management, while preserving chaining methods.
26
+ * Uses a Proxy to intercept .then() and chaining methods without
27
+ * directly mutating the result object.
28
+ */
29
+ private _wrapQueryResult;
30
+ private _handleQuerySuccess;
31
+ private _recordError;
32
+ private _callRequestHook;
33
+ }
@@ -0,0 +1,354 @@
1
+ import { context, SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
2
+ import { InstrumentationBase, safeExecuteInTheMiddle } from "@opentelemetry/instrumentation";
3
+ import { ATTR_DB_NAMESPACE, ATTR_DB_OPERATION_NAME, ATTR_DB_QUERY_TEXT, ATTR_DB_RESPONSE_STATUS_CODE, ATTR_DB_SYSTEM_NAME, ATTR_ERROR_TYPE, ATTR_SERVER_ADDRESS, ATTR_SERVER_PORT, } from "@opentelemetry/semantic-conventions";
4
+ import { addSqlCommenterComment } from "@opentelemetry/sql-common";
5
+ import { ATTR_DB_QUERY_PARAMETER_PREFIX, ATTR_DB_RESPONSE_RETURNED_ROWS } from "./semconv.js";
6
+ import { buildParameterizedQuery, buildSpanName, extractOperationName, getDbNamespace, getDbSystemName, getServerAddress, getServerPort, sanitizeQuery, } from "./utils.js";
7
+ import { VERSION } from "./version.js";
8
+ const INSTRUMENTATION_NAME = "@8monkey/opentelemetry-instrumentation-bun-sql";
9
+ // Symbol to mark instances we've already wrapped
10
+ const WRAPPED = Symbol.for("bun-sql-otel-wrapped");
11
+ const CHAINING_METHODS = new Set(["values", "raw", "simple", "execute"]);
12
+ function isRecord(val) {
13
+ return typeof val === "object" && val !== null;
14
+ }
15
+ function buildCtxAttributes(ctx, extra) {
16
+ const attrs = {
17
+ [ATTR_DB_SYSTEM_NAME]: ctx.systemName,
18
+ ...extra,
19
+ };
20
+ if (ctx.namespace !== undefined)
21
+ attrs[ATTR_DB_NAMESPACE] = ctx.namespace;
22
+ if (ctx.serverAddress !== undefined)
23
+ attrs[ATTR_SERVER_ADDRESS] = ctx.serverAddress;
24
+ if (ctx.serverPort !== undefined)
25
+ attrs[ATTR_SERVER_PORT] = ctx.serverPort;
26
+ return attrs;
27
+ }
28
+ export class BunSqlInstrumentation extends InstrumentationBase {
29
+ constructor(config) {
30
+ super(INSTRUMENTATION_NAME, VERSION, config ?? {});
31
+ // Only initialize if not already set by enable() called from super()
32
+ this._originalSQL ??= null;
33
+ this._originalSqlSingleton ??= null;
34
+ this._patched ??= false;
35
+ }
36
+ getConfig() {
37
+ return {
38
+ maskStatement: true,
39
+ ...super.getConfig(),
40
+ };
41
+ }
42
+ init() {
43
+ // Bun built-in modules are not intercepted by Node.js module hooks.
44
+ // Patching is done directly in enable()/disable().
45
+ return [];
46
+ }
47
+ enable() {
48
+ if (this._patched)
49
+ return;
50
+ const bunModule = this._getBunModule();
51
+ if (bunModule === undefined)
52
+ return;
53
+ try {
54
+ if (bunModule.SQL !== undefined && bunModule.SQL !== null) {
55
+ // oxlint-disable-next-line no-unsafe-type-assertion
56
+ const OrigSQL = bunModule.SQL;
57
+ this._originalSQL = OrigSQL;
58
+ const wrapInstance = this._wrapInstance.bind(this);
59
+ // Wrap the SQL constructor so new instances are automatically instrumented
60
+ const wrappedSQL = function SQL(...args) {
61
+ const instance = new OrigSQL(...args);
62
+ return wrapInstance(instance);
63
+ };
64
+ // Preserve static properties
65
+ for (const key of ["prototype", "MySQLError", "PostgresError", "SQLError", "SQLiteError"]) {
66
+ const desc = Object.getOwnPropertyDescriptor(OrigSQL, key);
67
+ if (desc !== undefined) {
68
+ Object.defineProperty(wrappedSQL, key, desc);
69
+ }
70
+ }
71
+ bunModule.SQL = wrappedSQL;
72
+ }
73
+ // Also wrap the default `sql` singleton if present
74
+ const sqlVal = bunModule.sql;
75
+ if (sqlVal !== undefined && sqlVal !== null && Reflect.get(sqlVal, WRAPPED) !== true) {
76
+ this._originalSqlSingleton = sqlVal;
77
+ bunModule.sql = this._wrapInstance(sqlVal);
78
+ }
79
+ this._patched = true;
80
+ this._diag.debug("Bun.SQL instrumentation enabled");
81
+ }
82
+ catch (e) {
83
+ if (this._originalSQL !== null)
84
+ bunModule.SQL = this._originalSQL;
85
+ if (this._originalSqlSingleton !== null)
86
+ bunModule.sql = this._originalSqlSingleton;
87
+ this._originalSQL = this._originalSqlSingleton = null;
88
+ this._patched = false;
89
+ this._diag.error("Failed to enable Bun.SQL instrumentation", e);
90
+ }
91
+ }
92
+ disable() {
93
+ if (!this._patched)
94
+ return;
95
+ try {
96
+ const bunModule = this._getBunModule();
97
+ if (bunModule === undefined)
98
+ return;
99
+ if (this._originalSQL !== null) {
100
+ bunModule.SQL = this._originalSQL;
101
+ this._originalSQL = null;
102
+ }
103
+ if (this._originalSqlSingleton !== null) {
104
+ bunModule.sql = this._originalSqlSingleton;
105
+ this._originalSqlSingleton = null;
106
+ }
107
+ this._patched = false;
108
+ this._diag.debug("Bun.SQL instrumentation disabled");
109
+ }
110
+ catch (e) {
111
+ this._diag.error("Failed to disable Bun.SQL instrumentation", e);
112
+ }
113
+ }
114
+ _getBunModule() {
115
+ try {
116
+ // oxlint-disable-next-line no-unsafe-type-assertion
117
+ return require("bun");
118
+ }
119
+ catch {
120
+ return undefined;
121
+ }
122
+ }
123
+ /**
124
+ * Wrap a Bun SQL instance with a Proxy to intercept tagged template calls
125
+ * and method invocations.
126
+ */
127
+ _wrapInstance(instance) {
128
+ if (Reflect.get(instance, WRAPPED) === true) {
129
+ return instance;
130
+ }
131
+ const options = instance.options;
132
+ const optionsRecord = options;
133
+ const ctx = {
134
+ systemName: getDbSystemName(options.adapter),
135
+ namespace: getDbNamespace(optionsRecord),
136
+ serverAddress: getServerAddress(optionsRecord),
137
+ serverPort: getServerPort(optionsRecord),
138
+ };
139
+ return new Proxy(instance, {
140
+ apply: (_target, _thisArg, args) => this._handleTaggedTemplate(instance, args, ctx),
141
+ get: (target, prop, receiver) => {
142
+ if (prop === WRAPPED)
143
+ return true;
144
+ // Wrap known methods with typed access
145
+ switch (prop) {
146
+ case "unsafe":
147
+ return this._wrapUnsafe(target.unsafe.bind(target), ctx);
148
+ case "begin":
149
+ case "transaction":
150
+ return (callback) => target.begin((tx) => callback(this._wrapInstance(tx)));
151
+ case "savepoint":
152
+ return (callback) =>
153
+ // oxlint-disable-next-line no-unsafe-type-assertion
154
+ target.savepoint((tx) => callback(this._wrapInstance(tx)));
155
+ case "beginDistributed":
156
+ case "distributed":
157
+ return (id, callback) => target.beginDistributed(id, (tx) => callback(this._wrapInstance(tx)));
158
+ case "reserve":
159
+ return this._wrapConnOp("RESERVE", target.reserve.bind(target), ctx, (r) => this._wrapInstance(r));
160
+ case "close":
161
+ case "end":
162
+ return this._wrapConnOp("CLOSE", target.close.bind(target), ctx, (r) => r);
163
+ default: {
164
+ const value = Reflect.get(target, prop, receiver);
165
+ if (typeof value === "function") {
166
+ // oxlint-disable-next-line no-unsafe-return
167
+ return value.bind(target);
168
+ }
169
+ return value;
170
+ }
171
+ }
172
+ },
173
+ });
174
+ }
175
+ _handleTaggedTemplate(instance, args, ctx) {
176
+ const config = this.getConfig();
177
+ // oxlint-disable-next-line no-unsafe-type-assertion
178
+ const strings = args[0];
179
+ const params = args.slice(1);
180
+ const queryText = buildParameterizedQuery(strings);
181
+ const operationName = extractOperationName(queryText);
182
+ if (config.requireParentSpan === true && trace.getSpan(context.active()) === undefined) {
183
+ return instance(strings, ...params);
184
+ }
185
+ return this._execQuery(queryText, operationName, params, ctx, config, (span) => {
186
+ let templateStrings = strings;
187
+ if (config.addSqlCommenterComment === true) {
188
+ const suffix = addSqlCommenterComment(span, queryText).slice(queryText.length);
189
+ if (suffix !== "") {
190
+ const last = strings.length - 1;
191
+ const cooked = [...strings];
192
+ const raw = [...strings.raw];
193
+ cooked[last] += suffix;
194
+ raw[last] += suffix;
195
+ // oxlint-disable-next-line no-unsafe-type-assertion
196
+ templateStrings = Object.assign(cooked, { raw });
197
+ }
198
+ }
199
+ return instance(templateStrings, ...params);
200
+ });
201
+ }
202
+ _wrapUnsafe(original, ctx) {
203
+ return (query, params) => {
204
+ const config = this.getConfig();
205
+ if (config.requireParentSpan === true && trace.getSpan(context.active()) === undefined) {
206
+ return original(query, params);
207
+ }
208
+ const operationName = extractOperationName(query);
209
+ // Mask non-parameterized queries per OTel semconv
210
+ const queryText = config.maskStatement === false ? query : (config.maskStatementHook ?? sanitizeQuery)(query);
211
+ return this._execQuery(queryText, operationName, params, ctx, config, (span) => original(config.addSqlCommenterComment === true ? addSqlCommenterComment(span, query) : query, params));
212
+ };
213
+ }
214
+ _execQuery(queryText, operationName, params, ctx, config, execute) {
215
+ const attributes = buildCtxAttributes(ctx);
216
+ if (operationName !== undefined)
217
+ attributes[ATTR_DB_OPERATION_NAME] = operationName;
218
+ attributes[ATTR_DB_QUERY_TEXT] = queryText;
219
+ if (config.enhancedDatabaseReporting === true && params !== undefined) {
220
+ for (let i = 0; i < params.length; i++) {
221
+ attributes[`${ATTR_DB_QUERY_PARAMETER_PREFIX}.${i}`] = String(params[i]);
222
+ }
223
+ }
224
+ const span = this.tracer.startSpan(buildSpanName({ operationName, namespace: ctx.namespace, systemName: ctx.systemName }), { kind: SpanKind.CLIENT, attributes });
225
+ this._callRequestHook(span, {
226
+ query: queryText,
227
+ operation: operationName,
228
+ params: config.enhancedDatabaseReporting === true ? params : undefined,
229
+ }, config);
230
+ try {
231
+ const result = context.with(trace.setSpan(context.active(), span), () => execute(span));
232
+ return this._wrapQueryResult(result, span, config);
233
+ }
234
+ catch (error) {
235
+ this._recordError(span, error instanceof Error ? error : new Error(String(error)));
236
+ span.end();
237
+ throw error;
238
+ }
239
+ }
240
+ _wrapConnOp(op, original, ctx, onSuccess) {
241
+ return () => {
242
+ const config = this.getConfig();
243
+ if (config.ignoreConnectionSpans === true ||
244
+ (config.requireParentSpan === true && trace.getSpan(context.active()) === undefined)) {
245
+ return original().then(onSuccess);
246
+ }
247
+ const span = this.tracer.startSpan(buildSpanName({ operationName: op, namespace: ctx.namespace, systemName: ctx.systemName }), {
248
+ kind: SpanKind.CLIENT,
249
+ attributes: buildCtxAttributes(ctx, { [ATTR_DB_OPERATION_NAME]: op }),
250
+ });
251
+ try {
252
+ return original().then((r) => {
253
+ span.end();
254
+ return onSuccess(r);
255
+ }, (e) => {
256
+ this._recordError(span, e);
257
+ span.end();
258
+ throw e;
259
+ });
260
+ }
261
+ catch (e) {
262
+ this._recordError(span, e instanceof Error ? e : new Error(String(e)));
263
+ span.end();
264
+ throw e;
265
+ }
266
+ };
267
+ }
268
+ /**
269
+ * Wrap a lazy query result (thenable) to intercept resolution/rejection
270
+ * for span lifecycle management, while preserving chaining methods.
271
+ * Uses a Proxy to intercept .then() and chaining methods without
272
+ * directly mutating the result object.
273
+ */
274
+ _wrapQueryResult(queryResult, span, config) {
275
+ if (typeof queryResult !== "object" || queryResult === null || !("then" in queryResult)) {
276
+ span.end();
277
+ return queryResult;
278
+ }
279
+ const resultObj = queryResult;
280
+ // oxlint-disable-next-line no-unsafe-type-assertion
281
+ const origThen = resultObj["then"];
282
+ const wrappedThen = (onFulfilled, onRejected) => origThen.call(resultObj, (data) => {
283
+ this._handleQuerySuccess(span, data, config);
284
+ return onFulfilled === undefined ? data : onFulfilled(data);
285
+ }, (error) => {
286
+ this._recordError(span, error instanceof Error ? error : new Error(String(error)));
287
+ span.end();
288
+ if (onRejected !== undefined)
289
+ return onRejected(error);
290
+ throw error;
291
+ });
292
+ // Use Proxy to intercept .then() and chaining methods
293
+ return new Proxy(queryResult, {
294
+ get: (target, prop, receiver) => {
295
+ if (prop === "then")
296
+ return wrappedThen;
297
+ if (typeof prop === "string" && CHAINING_METHODS.has(prop)) {
298
+ const value = Reflect.get(target, prop, receiver);
299
+ if (typeof value === "function") {
300
+ return (...args) => {
301
+ const chainResult = value.apply(target, args);
302
+ return this._wrapQueryResult(chainResult, span, config);
303
+ };
304
+ }
305
+ return value;
306
+ }
307
+ // oxlint-disable-next-line no-unsafe-return
308
+ return Reflect.get(target, prop, receiver);
309
+ },
310
+ });
311
+ }
312
+ _handleQuerySuccess(span, data, config) {
313
+ const record = isRecord(data) ? data : null;
314
+ const rowCount = record !== null && typeof record["count"] === "number" ? record["count"] : undefined;
315
+ if (rowCount !== undefined)
316
+ span.setAttribute(ATTR_DB_RESPONSE_RETURNED_ROWS, rowCount);
317
+ if (config.responseHook !== undefined) {
318
+ const command = record !== null && typeof record["command"] === "string" ? record["command"] : undefined;
319
+ safeExecuteInTheMiddle(() => {
320
+ config.responseHook(span, {
321
+ rowCount,
322
+ command,
323
+ data: config.enhancedDatabaseReporting === true ? data : undefined,
324
+ });
325
+ }, (err) => {
326
+ if (err)
327
+ this._diag.error("Error in responseHook", err);
328
+ }, true);
329
+ }
330
+ span.end();
331
+ }
332
+ _recordError(span, error) {
333
+ span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
334
+ span.recordException(error);
335
+ span.setAttribute(ATTR_ERROR_TYPE, error.constructor.name);
336
+ // Capture database-specific error codes
337
+ if ("code" in error && typeof error.code === "string") {
338
+ span.setAttribute(ATTR_DB_RESPONSE_STATUS_CODE, error.code);
339
+ }
340
+ else if ("errno" in error && typeof error.errno === "number") {
341
+ span.setAttribute(ATTR_DB_RESPONSE_STATUS_CODE, String(error.errno));
342
+ }
343
+ }
344
+ _callRequestHook(span, info, config) {
345
+ if (config.requestHook !== undefined) {
346
+ safeExecuteInTheMiddle(() => {
347
+ config.requestHook(span, info);
348
+ }, (err) => {
349
+ if (err)
350
+ this._diag.error("Error in requestHook", err);
351
+ }, true);
352
+ }
353
+ }
354
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Semantic convention attribute names not yet in @opentelemetry/semantic-conventions.
3
+ */
4
+ /** Individual query parameter values (opt-in). Use as `db.query.parameter.<key>`. */
5
+ export declare const ATTR_DB_QUERY_PARAMETER_PREFIX = "db.query.parameter";
6
+ /** Number of rows returned by the query response. */
7
+ export declare const ATTR_DB_RESPONSE_RETURNED_ROWS = "db.response.returned_rows";
8
+ /** The database system name for SQLite (not yet a named constant in semconv). */
9
+ export declare const DB_SYSTEM_NAME_VALUE_SQLITE = "sqlite";
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Semantic convention attribute names not yet in @opentelemetry/semantic-conventions.
3
+ */
4
+ /** Individual query parameter values (opt-in). Use as `db.query.parameter.<key>`. */
5
+ export const ATTR_DB_QUERY_PARAMETER_PREFIX = "db.query.parameter";
6
+ /** Number of rows returned by the query response. */
7
+ export const ATTR_DB_RESPONSE_RETURNED_ROWS = "db.response.returned_rows";
8
+ /** The database system name for SQLite (not yet a named constant in semconv). */
9
+ export const DB_SYSTEM_NAME_VALUE_SQLITE = "sqlite";
@@ -0,0 +1,66 @@
1
+ import type { Span } from "@opentelemetry/api";
2
+ import type { InstrumentationConfig } from "@opentelemetry/instrumentation";
3
+ export interface BunSqlRequestHookInformation {
4
+ /** The SQL query text (parameterized for tagged templates, raw for unsafe). */
5
+ query: string;
6
+ /** The SQL operation name (SELECT, INSERT, etc.). */
7
+ operation?: string;
8
+ /** Query parameter values (only present for tagged template queries). */
9
+ params?: unknown[];
10
+ }
11
+ export interface BunSqlResponseHookInformation {
12
+ /** Number of rows returned. */
13
+ rowCount?: number;
14
+ /** The command type (SELECT, INSERT, etc.). */
15
+ command?: string;
16
+ /** Raw query result data. */
17
+ data?: unknown;
18
+ }
19
+ export type BunSqlInstrumentationExecutionRequestHook = (span: Span, info: BunSqlRequestHookInformation) => void;
20
+ export type BunSqlInstrumentationExecutionResponseHook = (span: Span, info: BunSqlResponseHookInformation) => void;
21
+ export interface BunSqlInstrumentationConfig extends InstrumentationConfig {
22
+ /**
23
+ * Attach query parameters and result data to spans.
24
+ * Parameters are Opt-In per OTel DB semconv.
25
+ * @default false
26
+ */
27
+ enhancedDatabaseReporting?: boolean;
28
+ /**
29
+ * Only create spans when a parent span exists in the current context.
30
+ * Useful for reducing noise in high-throughput systems.
31
+ * @default false
32
+ */
33
+ requireParentSpan?: boolean;
34
+ /**
35
+ * Suppress connection-level spans (reserve/release/close).
36
+ * @default false
37
+ */
38
+ ignoreConnectionSpans?: boolean;
39
+ /**
40
+ * Mask non-parameterized queries (sql.unsafe(), sql.file()) by
41
+ * replacing literal values with `?` placeholders.
42
+ * Per OTel semconv, non-parameterized queries SHOULD be masked by default.
43
+ * @default true
44
+ */
45
+ maskStatement?: boolean;
46
+ /**
47
+ * Custom masking function for non-parameterized queries.
48
+ * Only used when `maskStatement` is true.
49
+ * @default Replaces string/numeric/boolean literals with `?`
50
+ */
51
+ maskStatementHook?: (query: string) => string;
52
+ /**
53
+ * Add SQL commenter traceparent comments to queries.
54
+ * Per OTel semconv, SHOULD NOT be enabled by default.
55
+ * @default false
56
+ */
57
+ addSqlCommenterComment?: boolean;
58
+ /**
59
+ * Hook called before query execution to customize span attributes.
60
+ */
61
+ requestHook?: BunSqlInstrumentationExecutionRequestHook;
62
+ /**
63
+ * Hook called after query execution to customize span attributes from response.
64
+ */
65
+ responseHook?: BunSqlInstrumentationExecutionResponseHook;
66
+ }
package/dist/types.js ADDED
File without changes
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Extract the SQL operation name (SELECT, INSERT, etc.) from a query string.
3
+ * Returns the first word uppercased, matching the approach used by pg and mysql2 adapters.
4
+ */
5
+ export declare function extractOperationName(sql: string): string | undefined;
6
+ /**
7
+ * Build parameterized query text from tagged template strings.
8
+ * Replaces interpolated values with $1, $2, ... placeholders.
9
+ */
10
+ export declare function buildParameterizedQuery(strings: TemplateStringsArray): string;
11
+ /**
12
+ * Sanitize a non-parameterized query by replacing literal values with `?`.
13
+ * Matches the scope of mysql2's default masking (integers and single-quoted strings).
14
+ *
15
+ * Replaces:
16
+ * - Single-quoted strings: 'hello' → ?
17
+ * - Integer literals: 42 → ?
18
+ *
19
+ * Does NOT replace:
20
+ * - Double-quoted identifiers ("table_name") — these are identifiers in PostgreSQL/SQLite
21
+ * - Keywords
22
+ * - Operators
23
+ */
24
+ export declare function sanitizeQuery(sql: string): string;
25
+ /**
26
+ * Build span name per OTel DB semantic conventions:
27
+ * 1. {db.operation.name} {db.namespace} if both available
28
+ * 2. {db.operation.name} if no namespace
29
+ * 3. {db.namespace} alone
30
+ * 4. {db.system.name} as fallback
31
+ */
32
+ export declare function buildSpanName(opts: {
33
+ operationName?: string;
34
+ namespace?: string;
35
+ systemName: string;
36
+ }): string;
37
+ /**
38
+ * Map Bun.SQL adapter name to the OTel `db.system.name` value.
39
+ */
40
+ export declare function getDbSystemName(adapter: string | undefined): string;
41
+ /**
42
+ * Extract database namespace (database name) from SQL instance options.
43
+ */
44
+ export declare function getDbNamespace(options: Record<string, unknown>): string | undefined;
45
+ /**
46
+ * Extract server address from SQL instance options.
47
+ */
48
+ export declare function getServerAddress(options: Record<string, unknown>): string | undefined;
49
+ /**
50
+ * Extract server port from SQL instance options.
51
+ */
52
+ export declare function getServerPort(options: Record<string, unknown>): number | undefined;
package/dist/utils.js ADDED
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Extract the SQL operation name (SELECT, INSERT, etc.) from a query string.
3
+ * Returns the first word uppercased, matching the approach used by pg and mysql2 adapters.
4
+ */
5
+ export function extractOperationName(sql) {
6
+ const trimmed = sql.trimStart();
7
+ if (trimmed.length === 0)
8
+ return undefined;
9
+ const spaceIdx = trimmed.indexOf(" ");
10
+ let firstWord = spaceIdx === -1 ? trimmed : trimmed.slice(0, spaceIdx);
11
+ if (firstWord.endsWith(";"))
12
+ firstWord = firstWord.slice(0, -1);
13
+ if (firstWord.length === 0)
14
+ return undefined;
15
+ return firstWord.toUpperCase();
16
+ }
17
+ /**
18
+ * Build parameterized query text from tagged template strings.
19
+ * Replaces interpolated values with $1, $2, ... placeholders.
20
+ */
21
+ export function buildParameterizedQuery(strings) {
22
+ let query = "";
23
+ for (let i = 0; i < strings.length; i++) {
24
+ query += strings[i];
25
+ if (i < strings.length - 1) {
26
+ query += `$${i + 1}`;
27
+ }
28
+ }
29
+ return query;
30
+ }
31
+ /**
32
+ * Sanitize a non-parameterized query by replacing literal values with `?`.
33
+ * Matches the scope of mysql2's default masking (integers and single-quoted strings).
34
+ *
35
+ * Replaces:
36
+ * - Single-quoted strings: 'hello' → ?
37
+ * - Integer literals: 42 → ?
38
+ *
39
+ * Does NOT replace:
40
+ * - Double-quoted identifiers ("table_name") — these are identifiers in PostgreSQL/SQLite
41
+ * - Keywords
42
+ * - Operators
43
+ */
44
+ export function sanitizeQuery(sql) {
45
+ return sql.replaceAll(/\b\d+\b/g, "?").replaceAll(/'(?:\\.|''|[^'])*'/g, "?");
46
+ }
47
+ /**
48
+ * Build span name per OTel DB semantic conventions:
49
+ * 1. {db.operation.name} {db.namespace} if both available
50
+ * 2. {db.operation.name} if no namespace
51
+ * 3. {db.namespace} alone
52
+ * 4. {db.system.name} as fallback
53
+ */
54
+ export function buildSpanName(opts) {
55
+ if (opts.operationName !== undefined && opts.namespace !== undefined)
56
+ return `${opts.operationName} ${opts.namespace}`;
57
+ if (opts.operationName !== undefined)
58
+ return opts.operationName;
59
+ if (opts.namespace !== undefined)
60
+ return opts.namespace;
61
+ return opts.systemName;
62
+ }
63
+ /**
64
+ * Map Bun.SQL adapter name to the OTel `db.system.name` value.
65
+ */
66
+ export function getDbSystemName(adapter) {
67
+ switch (adapter) {
68
+ case "postgres":
69
+ case "postgresql":
70
+ return "postgresql";
71
+ case "mysql":
72
+ return "mysql";
73
+ case "sqlite":
74
+ return "sqlite";
75
+ case undefined:
76
+ return "unknown";
77
+ default:
78
+ return adapter;
79
+ }
80
+ }
81
+ /**
82
+ * Extract database namespace (database name) from SQL instance options.
83
+ */
84
+ export function getDbNamespace(options) {
85
+ if (typeof options["database"] === "string")
86
+ return options["database"];
87
+ if (typeof options["filename"] === "string") {
88
+ const filename = options["filename"];
89
+ return filename === ":memory:" ? ":memory:" : filename;
90
+ }
91
+ return undefined;
92
+ }
93
+ /**
94
+ * Extract server address from SQL instance options.
95
+ */
96
+ export function getServerAddress(options) {
97
+ if (typeof options["hostname"] === "string")
98
+ return options["hostname"];
99
+ if (typeof options["host"] === "string")
100
+ return options["host"];
101
+ return undefined;
102
+ }
103
+ /**
104
+ * Extract server port from SQL instance options.
105
+ */
106
+ export function getServerPort(options) {
107
+ if (typeof options["port"] === "number")
108
+ return options["port"];
109
+ return undefined;
110
+ }
@@ -0,0 +1 @@
1
+ export declare const VERSION = "0.1.0-rc0";
@@ -0,0 +1 @@
1
+ export const VERSION = "0.1.0-rc0";
package/package.json ADDED
@@ -0,0 +1,69 @@
1
+ {
2
+ "name": "@8monkey/opentelemetry-instrumentation-bun-sql",
3
+ "version": "0.1.0-rc0",
4
+ "description": "OpenTelemetry instrumentation for `Bun.SQL` database client for PostgreSQL / MySQL / SQLite",
5
+ "keywords": [
6
+ "bun",
7
+ "mysql",
8
+ "opentelemetry",
9
+ "otel",
10
+ "postgresql",
11
+ "sqlite"
12
+ ],
13
+ "homepage": "https://hebo.ai",
14
+ "bugs": {
15
+ "url": "https://github.com/8monkey-ai/opentelemetry-instrumentation-bun-sql/issues"
16
+ },
17
+ "license": "Apache-2.0",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/8monkey-ai/opentelemetry-instrumentation-bun-sql.git"
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "LICENSE",
25
+ "README.md"
26
+ ],
27
+ "type": "module",
28
+ "sideEffects": false,
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "import": "./dist/index.js"
33
+ }
34
+ },
35
+ "scripts": {
36
+ "build": "tsc -p tsconfig.build.json",
37
+ "clean": "git clean -fdx -e '.env*' .",
38
+ "format": "oxfmt .",
39
+ "format:staged": "oxfmt --no-error-on-unmatched-pattern",
40
+ "lint": "oxlint",
41
+ "lint:staged": "oxlint --fix",
42
+ "typecheck": "oxlint --type-check",
43
+ "test": "bun test",
44
+ "check": "bun lint && bun typecheck",
45
+ "fix": "bun lint:staged && bun format:staged"
46
+ },
47
+ "dependencies": {
48
+ "@opentelemetry/instrumentation": "^0.214.0",
49
+ "@opentelemetry/semantic-conventions": "^1.40.0",
50
+ "@opentelemetry/sql-common": "^0.41.2"
51
+ },
52
+ "devDependencies": {
53
+ "@electric-sql/pglite": "^0.4.4",
54
+ "@opentelemetry/api": "^1.9.1",
55
+ "@opentelemetry/context-async-hooks": "^2.6.1",
56
+ "@opentelemetry/resources": "^2.6.1",
57
+ "@opentelemetry/sdk-trace-base": "^2.6.1",
58
+ "@opentelemetry/sdk-trace-node": "^2.6.1",
59
+ "bun-types": "^1.3.12",
60
+ "oxfmt": "^0.44.0",
61
+ "oxlint": "^1.59.0",
62
+ "oxlint-tsgolint": "^0.20.0",
63
+ "typescript": "^6.0.2"
64
+ },
65
+ "peerDependencies": {
66
+ "@opentelemetry/api": "^1.3.0"
67
+ },
68
+ "peerDependenciesMeta": {}
69
+ }