0
# Platform Utilities
1
2
Cross-platform abstractions for environment variable access, performance measurement, SDK information, and timer utilities that work across Node.js and browser environments.
3
4
## Capabilities
5
6
### Environment Variable Access
7
8
Functions to safely access and parse environment variables with type conversion and fallback handling.
9
10
```typescript { .api }
11
/**
12
* Get boolean value from environment variable
13
* @param key - Environment variable name
14
* @returns Boolean value, undefined if not set or invalid
15
*/
16
function getBooleanFromEnv(key: string): boolean | undefined;
17
18
/**
19
* Get string value from environment variable
20
* @param key - Environment variable name
21
* @returns String value, undefined if not set
22
*/
23
function getStringFromEnv(key: string): string | undefined;
24
25
/**
26
* Get number value from environment variable
27
* @param key - Environment variable name
28
* @returns Number value, undefined if not set or invalid
29
*/
30
function getNumberFromEnv(key: string): number | undefined;
31
32
/**
33
* Get comma-separated string list from environment variable
34
* @param key - Environment variable name
35
* @param separator - Optional separator (defaults to comma)
36
* @returns Array of strings, empty array if not set
37
*/
38
function getStringListFromEnv(key: string, separator?: string): string[];
39
```
40
41
**Usage Examples:**
42
43
```typescript
44
import {
45
getBooleanFromEnv,
46
getStringFromEnv,
47
getNumberFromEnv,
48
getStringListFromEnv
49
} from "@opentelemetry/core";
50
51
// Get configuration from environment variables
52
const debugEnabled = getBooleanFromEnv("OTEL_DEBUG");
53
const serviceName = getStringFromEnv("OTEL_SERVICE_NAME");
54
const samplingRatio = getNumberFromEnv("OTEL_TRACE_SAMPLING_RATIO");
55
const endpoints = getStringListFromEnv("OTEL_EXPORTER_OTLP_ENDPOINTS");
56
57
// Use with defaults
58
const config = {
59
debug: debugEnabled ?? false,
60
serviceName: serviceName ?? "unknown-service",
61
samplingRatio: samplingRatio ?? 1.0,
62
endpoints: endpoints.length > 0 ? endpoints : ["http://localhost:4318"]
63
};
64
65
console.log("Configuration:", config);
66
67
// Parse custom separators
68
const features = getStringListFromEnv("ENABLED_FEATURES", "|");
69
console.log("Enabled features:", features); // From "feature1|feature2|feature3"
70
71
// Boolean parsing examples
72
// "true", "TRUE", "1" -> true
73
// "false", "FALSE", "0" -> false
74
// anything else -> undefined
75
const sslEnabled = getBooleanFromEnv("SSL_ENABLED");
76
if (sslEnabled !== undefined) {
77
console.log("SSL explicitly configured:", sslEnabled);
78
} else {
79
console.log("SSL not configured, using default");
80
}
81
```
82
83
### SDK Information
84
85
Access to SDK metadata and version information.
86
87
```typescript { .api }
88
/**
89
* SDK information object containing version and metadata
90
*/
91
const SDK_INFO: {
92
name: string;
93
version: string;
94
language: string;
95
};
96
```
97
98
**Usage Examples:**
99
100
```typescript
101
import { SDK_INFO } from "@opentelemetry/core";
102
103
// Access SDK information
104
console.log("SDK Name:", SDK_INFO.name); // "@opentelemetry/core"
105
console.log("SDK Version:", SDK_INFO.version); // "2.1.0"
106
console.log("Language:", SDK_INFO.language); // "javascript"
107
108
// Use in resource attributes
109
const resourceAttributes = {
110
"telemetry.sdk.name": SDK_INFO.name,
111
"telemetry.sdk.version": SDK_INFO.version,
112
"telemetry.sdk.language": SDK_INFO.language
113
};
114
115
// Include in exported data
116
const exportData = {
117
resource: resourceAttributes,
118
// ... other data
119
};
120
```
121
122
### Global Object Access
123
124
Cross-platform access to the global object.
125
126
```typescript { .api }
127
/**
128
* Cross-platform global object reference
129
* Works in Node.js (global), Browser (window), Web Workers (self)
130
*/
131
const _globalThis: object;
132
```
133
134
**Usage Examples:**
135
136
```typescript
137
import { _globalThis } from "@opentelemetry/core";
138
139
// Access global object safely across platforms
140
const globalObj = _globalThis as any;
141
142
// Store global state (use carefully)
143
globalObj.__OTEL_INITIALIZED__ = true;
144
145
// Check for global features
146
if (typeof globalObj.fetch === "function") {
147
console.log("Fetch API available");
148
}
149
150
// Access platform-specific globals
151
if (typeof globalObj.process !== "undefined") {
152
console.log("Running in Node.js");
153
} else if (typeof globalObj.window !== "undefined") {
154
console.log("Running in browser");
155
} else if (typeof globalObj.self !== "undefined") {
156
console.log("Running in web worker");
157
}
158
```
159
160
### Performance Utilities
161
162
Cross-platform performance measurement utilities.
163
164
```typescript { .api }
165
/**
166
* Cross-platform performance object with timing capabilities
167
*/
168
const otperformance: {
169
now(): number;
170
timeOrigin?: number;
171
};
172
```
173
174
**Usage Examples:**
175
176
```typescript
177
import { otperformance } from "@opentelemetry/core";
178
179
// High-precision timing
180
const startTime = otperformance.now();
181
182
// Simulate some work
183
await new Promise(resolve => setTimeout(resolve, 100));
184
185
const endTime = otperformance.now();
186
const duration = endTime - startTime;
187
188
console.log(`Operation took ${duration.toFixed(3)}ms`);
189
190
// Access time origin if available
191
if (otperformance.timeOrigin) {
192
const absoluteTime = otperformance.timeOrigin + otperformance.now();
193
console.log("Absolute timestamp:", absoluteTime);
194
}
195
196
// Use for span timing
197
function createTimingSpan(name: string) {
198
const startTime = otperformance.now();
199
200
return {
201
name,
202
startTime,
203
end() {
204
const endTime = otperformance.now();
205
const duration = endTime - startTime;
206
console.log(`Span ${name} duration: ${duration.toFixed(3)}ms`);
207
return duration;
208
}
209
};
210
}
211
212
const span = createTimingSpan("database-query");
213
// ... perform database query ...
214
span.end();
215
```
216
217
### Timer Utilities
218
219
Timer functions that don't keep the Node.js process alive.
220
221
```typescript { .api }
222
/**
223
* Create a timer that doesn't keep the Node.js process alive
224
* @param fn - Function to execute
225
* @param delay - Delay in milliseconds
226
* @returns Timer reference (platform-specific)
227
*/
228
function unrefTimer(fn: Function, delay: number): any;
229
```
230
231
**Usage Examples:**
232
233
```typescript
234
import { unrefTimer } from "@opentelemetry/core";
235
236
// Create timer that won't prevent process exit
237
const timer = unrefTimer(() => {
238
console.log("Periodic cleanup task");
239
}, 5000);
240
241
// Timer runs every 5 seconds but won't keep process alive
242
console.log("Timer created, process can exit naturally");
243
244
// Use for background telemetry tasks
245
function startPeriodicExport() {
246
return unrefTimer(() => {
247
// Export telemetry data
248
console.log("Exporting telemetry data...");
249
250
// This won't prevent the application from shutting down
251
exportTelemetryData().catch(console.error);
252
}, 30000); // Every 30 seconds
253
}
254
255
const exportTimer = startPeriodicExport();
256
257
// Use for connection health checks
258
function startHealthCheck(connection: any) {
259
return unrefTimer(() => {
260
if (connection.isConnected()) {
261
console.log("Connection healthy");
262
} else {
263
console.warn("Connection lost, attempting reconnect");
264
connection.reconnect().catch(console.error);
265
}
266
}, 10000); // Every 10 seconds
267
}
268
269
// In Node.js, this prevents the timer from keeping the process alive
270
// In browsers, this works like regular setTimeout
271
```
272
273
### Platform Detection
274
275
Utilities for detecting the current platform and environment.
276
277
**Usage Examples:**
278
279
```typescript
280
import { _globalThis, otperformance } from "@opentelemetry/core";
281
282
function detectPlatform() {
283
const globalObj = _globalThis as any;
284
285
if (typeof globalObj.process !== "undefined" && globalObj.process.versions?.node) {
286
return {
287
platform: "node",
288
version: globalObj.process.versions.node,
289
hasPerformanceHooks: typeof globalObj.process.hrtime === "function"
290
};
291
}
292
293
if (typeof globalObj.window !== "undefined") {
294
return {
295
platform: "browser",
296
userAgent: globalObj.navigator?.userAgent,
297
hasPerformanceAPI: typeof otperformance.now === "function"
298
};
299
}
300
301
if (typeof globalObj.self !== "undefined") {
302
return {
303
platform: "webworker",
304
hasPerformanceAPI: typeof otperformance.now === "function"
305
};
306
}
307
308
return {
309
platform: "unknown"
310
};
311
}
312
313
const platformInfo = detectPlatform();
314
console.log("Platform info:", platformInfo);
315
316
// Use platform info for conditional behavior
317
if (platformInfo.platform === "node") {
318
// Use Node.js specific features
319
console.log("Using Node.js optimizations");
320
} else if (platformInfo.platform === "browser") {
321
// Use browser specific features
322
console.log("Using browser optimizations");
323
}
324
```