-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathtelemetry-example-plugin.ts
More file actions
520 lines (469 loc) · 16 KB
/
telemetry-example-plugin.ts
File metadata and controls
520 lines (469 loc) · 16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
/**
* Minimal plugin to register telemetry example routes
*/
import {
type BasePluginConfig,
CacheManager,
type Counter,
type Histogram,
Plugin,
SeverityNumber,
type Span,
SpanStatusCode,
toPlugin,
} from "@databricks/appkit";
import type { Request, Response, Router } from "express";
class TelemetryExamples extends Plugin {
public name = "telemetry-examples" as const;
protected envVars: string[] = [];
private requestCounter: Counter;
private durationHistogram: Histogram;
constructor(config: BasePluginConfig) {
super(config);
this.cache = new CacheManager({ enabled: true, ttl: 60 }, this.telemetry);
const meter = this.telemetry.getMeter({ name: "custom-telemetry-example" });
this.requestCounter = meter.createCounter("app.requests.total", {
description: "Total number of requests",
});
this.durationHistogram = meter.createHistogram("app.request.duration", {
description: "Request duration in ms",
unit: "ms",
});
}
injectRoutes(router: Router): void {
this.registerTelemetryExampleRoutes(router as any);
}
private registerTelemetryExampleRoutes(router: Router) {
this.route(router, {
name: "combined",
method: "post",
path: "/combined",
handler: async (req: Request, res: Response) => {
const startTime = Date.now();
return this.telemetry.startActiveSpan(
"combined-example",
{
attributes: {
"example.type": "combined",
"example.version": "v2",
},
},
async (span: Span) => {
try {
const userId =
req.body?.userId || req.query.userId || "demo-user-123";
this.telemetry.emit({
severityNumber: SeverityNumber.INFO,
severityText: "INFO",
body: "Processing telemetry example request",
attributes: {
"user.id": userId,
"request.type": "combined-example",
},
});
const result = await this.complexOperation(userId);
const duration = Date.now() - startTime;
this.requestCounter.add(1, { status: "success" });
this.durationHistogram.record(duration);
this.telemetry.emit({
severityNumber: SeverityNumber.INFO,
severityText: "INFO",
body: "Request completed successfully",
attributes: {
"user.id": userId,
"duration.ms": duration,
"result.fields": Object.keys(result).length,
},
});
span.setStatus({ code: SpanStatusCode.OK });
res.json({
success: true,
result,
duration_ms: duration,
tracing: {
hint: "Open Grafana at http://localhost:3000",
services: [
"app-template (main service)",
"user-operations (complex operation)",
"auth-validation (user validation)",
"data-access (database operations - with cache!)",
"auth-service (permissions)",
"external-api (external HTTP calls)",
"data-processing (transformation)",
],
expectedSpans: [
"HTTP POST (SDK auto-instrumentation)",
"combined-example (custom tracer: custom-telemetry-example)",
" └─ complex-operation (custom tracer: user-operations)",
" ├─ validate-user (100ms, custom tracer: auth-validation)",
" ├─ fetch-user-data (200ms first call / cached on repeat, custom tracer: data-access) [parallel]",
" │ └─ cache.hit attribute set by SDK (false on first call, true on repeat)",
" ├─ fetch-external-resource (custom tracer: external-api) [parallel]",
" │ └─ HTTP GET https://example.com (SDK auto-instrumentation)",
" ├─ fetch-permissions (150ms, custom tracer: auth-service) [parallel]",
" └─ transform-data (80ms, custom tracer: data-processing)",
],
},
metrics: {
recorded: ["app.requests.total", "app.request.duration"],
},
logs: {
emitted: [
"Starting complex operation workflow",
"Data fetching completed successfully",
"Data transformation completed",
"Permissions retrieved",
"External API call completed",
],
},
});
} catch (error) {
span.recordException(error as Error);
span.setStatus({ code: SpanStatusCode.ERROR });
this.requestCounter.add(1, { status: "error" });
this.telemetry.emit({
severityNumber: SeverityNumber.ERROR,
severityText: "ERROR",
body: error instanceof Error ? error.message : "Unknown error",
attributes: {
"error.type": error instanceof Error ? error.name : "Unknown",
"error.stack":
error instanceof Error ? error.stack : undefined,
"request.path": req.path,
},
});
res.status(500).json({
error: true,
message:
error instanceof Error ? error.message : "Unknown error",
});
} finally {
span.end();
}
},
{ name: "custom-telemetry-example" },
);
},
});
}
private async complexOperation(userId: string) {
return this.telemetry.startActiveSpan(
"complex-operation",
{
attributes: {
"user.id": userId,
"operation.type": "user-data-flow",
},
},
async (parentSpan: Span) => {
try {
this.telemetry.emit({
severityNumber: SeverityNumber.DEBUG,
severityText: "DEBUG",
body: "Starting complex operation workflow",
attributes: {
"user.id": userId,
"workflow.step": "start",
},
});
await this.validateUser();
const [userData, externalData, permissionsData] = await Promise.all([
this.fetchUserData(userId),
this.fetchExternalResource(),
this.fetchPermissions(),
]);
this.telemetry.emit({
severityNumber: SeverityNumber.INFO,
severityText: "INFO",
body: "Data fetching completed successfully",
attributes: {
"user.id": userId,
"data.sources": 3,
"workflow.step": "data-fetched",
},
});
await this.transformData();
parentSpan.setStatus({ code: SpanStatusCode.OK });
return {
...userData,
external: externalData,
permissions: permissionsData,
};
} catch (error) {
parentSpan.recordException(error as Error);
parentSpan.setStatus({ code: SpanStatusCode.ERROR });
throw error;
} finally {
parentSpan.end();
}
},
{ name: "user-operations" },
);
}
private async validateUser() {
return this.telemetry.startActiveSpan(
"validate-user",
{
attributes: {
"validation.type": "user",
"validation.method": "token",
},
},
async (span: Span) => {
try {
this.telemetry.emit({
severityNumber: SeverityNumber.DEBUG,
severityText: "DEBUG",
body: "Validating user credentials",
attributes: {
"validation.method": "token",
},
});
await new Promise((resolve) => setTimeout(resolve, 100));
this.telemetry.emit({
severityNumber: SeverityNumber.INFO,
severityText: "INFO",
body: "User validation successful",
attributes: {
"validation.duration_ms": 100,
},
});
span.setStatus({ code: SpanStatusCode.OK });
} catch (error) {
span.recordException(error as Error);
span.setStatus({ code: SpanStatusCode.ERROR });
throw error;
} finally {
span.end();
}
},
{ name: "auth-validation" },
);
}
private async fetchUserData(userId: string) {
return this.telemetry.startActiveSpan(
"fetch-user-data",
{
attributes: {
"data.source": "database",
"db.system": "databricks",
"db.operation": "SELECT",
},
},
async (span: Span) => {
try {
this.telemetry.emit({
severityNumber: SeverityNumber.DEBUG,
severityText: "DEBUG",
body: "Fetching user data from database",
attributes: {
"user.id": userId,
"cache.enabled": true,
},
});
const result = await this.cache.getOrExecute(
["user-data", userId],
async () => {
this.telemetry.emit({
severityNumber: SeverityNumber.WARN,
severityText: "WARN",
body: "Cache miss - fetching from database (slow operation)",
attributes: {
"user.id": userId,
"operation.expected_duration_ms": 2000,
},
});
await new Promise((resolve) => setTimeout(resolve, 2000));
return {
userId,
data: "sample user data",
preferences: { theme: "dark", language: "en" },
lastLogin: new Date().toISOString(),
};
},
"",
{ ttl: 60 }, // 60 seconds TTL
);
span.setAttribute("data.size_bytes", JSON.stringify(result).length);
span.setStatus({ code: SpanStatusCode.OK });
this.telemetry.emit({
severityNumber: SeverityNumber.INFO,
severityText: "INFO",
body: "User data retrieved successfully",
attributes: {
"user.id": userId,
"data.size_bytes": JSON.stringify(result).length,
},
});
return result;
} catch (error) {
span.recordException(error as Error);
span.setStatus({ code: SpanStatusCode.ERROR });
throw error;
} finally {
span.end();
}
},
{ name: "data-access" },
);
}
private async fetchExternalResource() {
return this.telemetry.startActiveSpan(
"fetch-external-resource",
{
attributes: {
"http.target": "example.com",
"external.api.purpose": "demo",
},
},
async (span: Span) => {
try {
this.telemetry.emit({
severityNumber: SeverityNumber.DEBUG,
severityText: "DEBUG",
body: "Calling external API",
attributes: {
"http.url": "https://example.com",
"http.method": "GET",
},
});
const response = await fetch("https://example.com");
const text = await response.text();
span.setAttribute("http.status_code", response.status);
span.setAttribute("http.response.size_bytes", text.length);
span.addEvent("external_fetch_completed", {
"response.status": response.status,
});
span.setStatus({ code: SpanStatusCode.OK });
this.telemetry.emit({
severityNumber: SeverityNumber.INFO,
severityText: "INFO",
body: "External API call completed",
attributes: {
"http.url": "https://example.com",
"http.status_code": response.status,
"http.response.size_bytes": text.length,
},
});
return { status: response.status, size: text.length };
} catch (error) {
span.recordException(error as Error);
span.setStatus({ code: SpanStatusCode.ERROR });
this.telemetry.emit({
severityNumber: SeverityNumber.ERROR,
severityText: "ERROR",
body: "External API call failed",
attributes: {
"http.url": "https://example.com",
"error.message":
error instanceof Error ? error.message : "Unknown error",
},
});
return { status: 0, size: 0, error: "fetch failed" };
} finally {
span.end();
}
},
{ name: "external-api" },
);
}
private async fetchPermissions() {
return this.telemetry.startActiveSpan(
"fetch-permissions",
{
attributes: {
"permissions.scope": "user",
"permissions.type": "rbac",
},
},
async (span: Span) => {
try {
this.telemetry.emit({
severityNumber: SeverityNumber.DEBUG,
severityText: "DEBUG",
body: "Fetching user permissions",
attributes: {
"permissions.type": "rbac",
},
});
await new Promise((resolve) => setTimeout(resolve, 150));
const permissions = {
canRead: true,
canWrite: false,
canDelete: false,
};
this.telemetry.emit({
severityNumber: SeverityNumber.INFO,
severityText: "INFO",
body: "Permissions retrieved",
attributes: {
"permissions.canRead": permissions.canRead,
"permissions.canWrite": permissions.canWrite,
"permissions.canDelete": permissions.canDelete,
},
});
span.setStatus({ code: SpanStatusCode.OK });
return permissions;
} catch (error) {
span.recordException(error as Error);
span.setStatus({ code: SpanStatusCode.ERROR });
throw error;
} finally {
span.end();
}
},
{ name: "auth-service" },
);
}
private async transformData() {
return this.telemetry.startActiveSpan(
"transform-data",
{
attributes: {
"transform.type": "enrichment",
"transform.steps": "normalize,enrich,validate",
"external.data.included": true,
},
},
async (span: Span) => {
try {
this.telemetry.emit({
severityNumber: SeverityNumber.DEBUG,
severityText: "DEBUG",
body: "Starting data transformation pipeline",
attributes: {
"transform.steps": ["normalize", "enrich", "validate"],
},
});
await new Promise((resolve) => setTimeout(resolve, 80));
span.addEvent("transformation_completed", {
"output.fields": 5,
"processing.success": true,
});
this.telemetry.emit({
severityNumber: SeverityNumber.INFO,
severityText: "INFO",
body: "Data transformation completed",
attributes: {
"transform.duration_ms": 80,
"output.fields": 5,
},
});
span.setStatus({ code: SpanStatusCode.OK });
} catch (error) {
span.recordException(error as Error);
span.setStatus({ code: SpanStatusCode.ERROR });
throw error;
} finally {
span.end();
}
},
{ name: "data-processing" },
);
}
}
export const telemetryExamples = toPlugin<
typeof TelemetryExamples,
BasePluginConfig,
"telemetryExamples"
>(TelemetryExamples, "telemetryExamples");