@pingops/sdk 0.1.1 → 0.1.3

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/dist/pingops.js DELETED
@@ -1,259 +0,0 @@
1
- /**
2
- * PingOps SDK singleton for manual instrumentation
3
- *
4
- * Provides initializePingops and shutdownPingops functions.
5
- * wrapHttp is available from @pingops/core and will auto-initialize
6
- * from environment variables if needed.
7
- */
8
- import { NodeSDK } from "@opentelemetry/sdk-node";
9
- import { resourceFromAttributes } from "@opentelemetry/resources";
10
- import { ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
11
- import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
12
- import { setPingopsTracerProvider, shutdownTracerProvider, PingopsSpanProcessor, } from "@pingops/otel";
13
- import { createLogger } from "@pingops/core";
14
- import { setSdkInitialized, isGlobalInstrumentationEnabled, } from "./init-state";
15
- import { wrapHttp as coreWrapHttp, } from "@pingops/core";
16
- import { getPingopsTracerProvider } from "@pingops/otel";
17
- import { getInstrumentations } from "@pingops/otel";
18
- const initLogger = createLogger("[PingOps Initialize]");
19
- const logger = createLogger("[PingOps Pingops]");
20
- let sdkInstance = null;
21
- let isSdkInitializedFlag = false;
22
- /**
23
- * Global state to track initialization
24
- */
25
- let isInitialized = false;
26
- let initializationPromise = null;
27
- /**
28
- * Initializes PingOps SDK
29
- *
30
- * This function:
31
- * 1. Creates an OpenTelemetry NodeSDK instance
32
- * 2. Configures Resource with service.name
33
- * 3. Registers PingopsSpanProcessor
34
- * 4. Enables HTTP/fetch/GenAI instrumentation
35
- * 5. Starts the SDK
36
- *
37
- * @param config - Configuration for the SDK
38
- * @param explicit - Whether this is an explicit call (default: true).
39
- * Set to false when called internally by wrapHttp auto-initialization.
40
- */
41
- export function initializePingops(config, explicit = true) {
42
- if (isSdkInitializedFlag) {
43
- if (config.debug) {
44
- initLogger.warn("[PingOps] SDK already initialized, skipping");
45
- }
46
- return;
47
- }
48
- // Create resource with service name
49
- const resource = resourceFromAttributes({
50
- [ATTR_SERVICE_NAME]: config.serviceName,
51
- });
52
- const processor = new PingopsSpanProcessor(config);
53
- const instrumentations = getInstrumentations(isGlobalInstrumentationEnabled);
54
- // Node.js SDK
55
- const nodeSdk = new NodeSDK({
56
- resource,
57
- spanProcessors: [processor],
58
- instrumentations,
59
- });
60
- nodeSdk.start();
61
- sdkInstance = nodeSdk;
62
- // Mark SDK as initialized
63
- isSdkInitializedFlag = true;
64
- // Only enable global instrumentation if this was an explicit call
65
- // If called via wrapHttp auto-initialization, global instrumentation stays disabled
66
- setSdkInitialized(explicit);
67
- // Initialize isolated TracerProvider for manual spans AFTER NodeSDK starts
68
- // This ensures manual spans created via startSpan are processed by the same processor
69
- // We register it after NodeSDK so it takes precedence as the global provider
70
- try {
71
- // In version 2.2.0, span processors are passed in the constructor
72
- const isolatedProvider = new NodeTracerProvider({
73
- resource,
74
- spanProcessors: [processor],
75
- });
76
- // Register the provider globally
77
- isolatedProvider.register();
78
- // Set it in global state
79
- setPingopsTracerProvider(isolatedProvider);
80
- }
81
- catch (error) {
82
- if (config.debug) {
83
- initLogger.error("[PingOps] Failed to create isolated TracerProvider:", error instanceof Error ? error.message : String(error));
84
- }
85
- // Continue without isolated provider - manual spans will use global provider
86
- }
87
- if (config.debug) {
88
- initLogger.info("[PingOps] SDK initialized");
89
- }
90
- }
91
- /**
92
- * Shuts down the SDK and flushes remaining spans
93
- */
94
- export async function shutdownPingops() {
95
- // Shutdown isolated TracerProvider first
96
- await shutdownTracerProvider();
97
- if (!sdkInstance) {
98
- return;
99
- }
100
- await sdkInstance.shutdown();
101
- sdkInstance = null;
102
- isSdkInitializedFlag = false;
103
- setSdkInitialized(false);
104
- }
105
- /**
106
- * Checks if the SDK is already initialized by checking if a NodeTracerProvider is available
107
- */
108
- function isSdkInitialized() {
109
- try {
110
- const provider = getPingopsTracerProvider();
111
- // If we have a NodeTracerProvider (not the default NoOpTracerProvider), SDK is initialized
112
- const initialized = provider instanceof NodeTracerProvider;
113
- logger.debug("Checked SDK initialization status", {
114
- initialized,
115
- providerType: provider.constructor.name,
116
- });
117
- return initialized;
118
- }
119
- catch (error) {
120
- logger.debug("Error checking SDK initialization status", {
121
- error: error instanceof Error ? error.message : String(error),
122
- });
123
- return false;
124
- }
125
- }
126
- /**
127
- * Auto-initializes the SDK from environment variables if not already initialized
128
- */
129
- async function ensureInitialized() {
130
- // Check if SDK is already initialized (e.g., by calling initializePingops directly)
131
- if (isSdkInitialized()) {
132
- logger.debug("SDK already initialized, skipping auto-initialization");
133
- isInitialized = true;
134
- return;
135
- }
136
- if (isInitialized) {
137
- logger.debug("SDK initialization flag already set, skipping");
138
- return;
139
- }
140
- // If initialization is in progress, wait for it
141
- if (initializationPromise) {
142
- logger.debug("SDK initialization already in progress, waiting...");
143
- return initializationPromise;
144
- }
145
- // Start initialization
146
- logger.info("Starting SDK auto-initialization from environment variables");
147
- initializationPromise = Promise.resolve().then(() => {
148
- const apiKey = process.env.PINGOPS_API_KEY;
149
- const baseUrl = process.env.PINGOPS_BASE_URL;
150
- const serviceName = process.env.PINGOPS_SERVICE_NAME;
151
- const debug = process.env.PINGOPS_DEBUG === "true";
152
- logger.debug("Reading environment variables", {
153
- hasApiKey: !!apiKey,
154
- hasBaseUrl: !!baseUrl,
155
- hasServiceName: !!serviceName,
156
- debug,
157
- });
158
- if (!apiKey || !baseUrl || !serviceName) {
159
- const missing = [
160
- !apiKey && "PINGOPS_API_KEY",
161
- !baseUrl && "PINGOPS_BASE_URL",
162
- !serviceName && "PINGOPS_SERVICE_NAME",
163
- ].filter(Boolean);
164
- logger.error("Missing required environment variables for auto-initialization", {
165
- missing,
166
- });
167
- throw new Error(`PingOps SDK auto-initialization requires PINGOPS_API_KEY, PINGOPS_BASE_URL, and PINGOPS_SERVICE_NAME environment variables. Missing: ${missing.join(", ")}`);
168
- }
169
- const config = {
170
- apiKey,
171
- baseUrl,
172
- serviceName,
173
- debug,
174
- };
175
- logger.info("Initializing SDK with config", {
176
- baseUrl,
177
- serviceName,
178
- debug,
179
- });
180
- // Call initializePingops with explicit=false since this is auto-initialization
181
- initializePingops(config, false);
182
- isInitialized = true;
183
- logger.info("SDK auto-initialization completed successfully");
184
- });
185
- try {
186
- await initializationPromise;
187
- }
188
- catch (error) {
189
- logger.error("SDK auto-initialization failed", {
190
- error: error instanceof Error ? error.message : String(error),
191
- });
192
- throw error;
193
- }
194
- finally {
195
- initializationPromise = null;
196
- }
197
- }
198
- /**
199
- * Wraps a function to set attributes on HTTP spans created within the wrapped block.
200
- *
201
- * This function sets attributes (userId, sessionId, tags, metadata) in the OpenTelemetry
202
- * context, which are automatically propagated to all spans created within the wrapped function.
203
- *
204
- * Instrumentation behavior:
205
- * - If `initializePingops` was called: All HTTP requests are instrumented by default.
206
- * `wrapHttp` only adds attributes to spans created within the wrapped block.
207
- * - If `initializePingops` was NOT called: Only HTTP requests within `wrapHttp` blocks
208
- * are instrumented. Requests outside `wrapHttp` are not instrumented.
209
- *
210
- * @param options - Options including attributes to propagate to spans
211
- * @param fn - Function to execute within the attribute context
212
- * @returns The result of the function
213
- *
214
- * @example
215
- * ```typescript
216
- * import { wrapHttp } from '@pingops/sdk';
217
- *
218
- * // Scenario 1: initializePingops was called
219
- * initializePingops({ ... });
220
- *
221
- * // All HTTP requests are instrumented, but this block adds attributes
222
- * const result = await wrapHttp({
223
- * attributes: {
224
- * userId: 'user-123',
225
- * sessionId: 'session-456',
226
- * tags: ['production', 'api'],
227
- * metadata: { environment: 'prod', version: '1.0.0' }
228
- * }
229
- * }, async () => {
230
- * // This HTTP request will be instrumented AND have the attributes set above
231
- * const response = await fetch('https://api.example.com/users/123');
232
- * return response.json();
233
- * });
234
- *
235
- * // HTTP requests outside wrapHttp are still instrumented, just without the attributes
236
- * const otherResponse = await fetch('https://api.example.com/other');
237
- *
238
- * // Scenario 2: initializePingops was NOT called
239
- * // Only requests within wrapHttp are instrumented
240
- * await wrapHttp({
241
- * attributes: { userId: 'user-123' }
242
- * }, async () => {
243
- * // This request IS instrumented
244
- * return fetch('https://api.example.com/data');
245
- * });
246
- *
247
- * // This request is NOT instrumented (outside wrapHttp)
248
- * await fetch('https://api.example.com/other');
249
- * ```
250
- */
251
- export function wrapHttp(options, fn) {
252
- return coreWrapHttp({
253
- ...options,
254
- checkInitialized: isSdkInitialized,
255
- isGlobalInstrumentationEnabled: isGlobalInstrumentationEnabled,
256
- ensureInitialized: ensureInitialized,
257
- }, fn);
258
- }
259
- //# sourceMappingURL=pingops.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"pingops.js","sourceRoot":"","sources":["../src/pingops.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,yBAAyB,CAAC;AAClD,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AACxE,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAEnE,OAAO,EACL,wBAAwB,EACxB,sBAAsB,EACtB,oBAAoB,GACrB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EACL,iBAAiB,EACjB,8BAA8B,GAC/B,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,QAAQ,IAAI,YAAY,GAEzB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AACzD,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAEpD,MAAM,UAAU,GAAG,YAAY,CAAC,sBAAsB,CAAC,CAAC;AACxD,MAAM,MAAM,GAAG,YAAY,CAAC,mBAAmB,CAAC,CAAC;AAEjD,IAAI,WAAW,GAAmB,IAAI,CAAC;AACvC,IAAI,oBAAoB,GAAG,KAAK,CAAC;AAEjC;;GAEG;AACH,IAAI,aAAa,GAAG,KAAK,CAAC;AAC1B,IA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