-
Notifications
You must be signed in to change notification settings - Fork 47
/
todo-service.ts
90 lines (76 loc) · 2.8 KB
/
todo-service.ts
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
import start from './tracer';
const meter = start('todo-service');
import express from 'express';
import axios from 'axios';
import opentelemetry from "@opentelemetry/api";
const app = express();
import Redis from "ioredis";
import { api } from '@opentelemetry/sdk-node';
const redis = new Redis({ host: 'redis' });
const calls = meter.createHistogram('http-calls');
app.use((req, res, next) => {
const startTime = Date.now();
req.on('end', () => {
const endTime = Date.now();
calls.record(endTime - startTime, {
route: req.route?.path,
status: res.statusCode,
method: req.method
})
})
next();
})
const sleep = (time: number) => { return new Promise((resolve) => { setTimeout(resolve, time) }) };
app.get('/todos', async (req, res) => {
const baggage = opentelemetry.propagation.createBaggage({
"user.plan": {
value: "enterprise"
}
})
const contextWithBaggage = opentelemetry.propagation.setBaggage(opentelemetry.context.active(), baggage);
opentelemetry.context.with(contextWithBaggage, async () => {
const user = await axios.get('http://auth:8080/auth');
const todoKeys = await redis.keys('todo:*');
const todos: any = [];
for (let i = 0; i < todoKeys.length; i++) {
const todoItem = await redis.get(todoKeys[i])
if (todoItem) {
todos.push(JSON.parse(todoItem));
}
}
if (req.query['slow']) {
await sleep(1000);
}
if (req.query['fail']) {
try {
throw new Error('Really bad error!')
} catch (e: any) {
const activeSpan = api.trace.getSpan(api.context.active());
activeSpan?.recordException(e)
console.error('Really bad error!', {
spanId: activeSpan?.spanContext().spanId,
traceId: activeSpan?.spanContext().traceId,
traceFlag: activeSpan?.spanContext().traceFlags,
});
res.sendStatus(500);
return;
}
}
res.json({ todos, user: user.data });
})
})
app.listen(8080, () => {
console.log('service is up and running!');
})
async function init() {
opentelemetry.trace.getTracer('init').startActiveSpan('Set default items', async (span) => {
await Promise.all([
redis.set('todo:1', JSON.stringify({ name: 'Install OpenTelemetry SDK' })),
redis.set('todo:2', JSON.stringify({ name: 'Deploy OpenTelemetry Collector' })),
redis.set('todo:3', JSON.stringify({ name: 'Configure sampling rule' })),
redis.set('todo:4', JSON.stringify({ name: 'You are OpenTelemetry master!' }))]
);
span.end();
})
}
init();