-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathtracer.server.ts
More file actions
302 lines (260 loc) · 8.69 KB
/
tracer.server.ts
File metadata and controls
302 lines (260 loc) · 8.69 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
import {
Attributes,
Context,
DiagConsoleLogger,
DiagLogLevel,
Link,
Span,
SpanKind,
SpanOptions,
SpanStatusCode,
Tracer,
diag,
trace,
} from "@opentelemetry/api";
import { logs, SeverityNumber } from "@opentelemetry/api-logs";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-http";
import { BatchLogRecordProcessor, LoggerProvider } from "@opentelemetry/sdk-logs";
import { type Instrumentation, registerInstrumentations } from "@opentelemetry/instrumentation";
import { ExpressInstrumentation } from "@opentelemetry/instrumentation-express";
import { HttpInstrumentation } from "@opentelemetry/instrumentation-http";
import { Resource } from "@opentelemetry/resources";
import {
BatchSpanProcessor,
ParentBasedSampler,
Sampler,
SamplingDecision,
SamplingResult,
SimpleSpanProcessor,
TraceIdRatioBasedSampler,
} from "@opentelemetry/sdk-trace-base";
import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
import { SEMRESATTRS_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
import { PrismaInstrumentation } from "@prisma/instrumentation";
import { env } from "~/env.server";
import { AuthenticatedEnvironment } from "~/services/apiAuth.server";
import { singleton } from "~/utils/singleton";
import { LoggerSpanExporter } from "./telemetry/loggerExporter.server";
import { logger } from "~/services/logger.server";
import { flattenAttributes } from "@trigger.dev/core/v3";
export const SEMINTATTRS_FORCE_RECORDING = "forceRecording";
class CustomWebappSampler implements Sampler {
constructor(private readonly _baseSampler: Sampler) {}
// Drop spans where a prisma library is the root span
shouldSample(
context: Context,
traceId: string,
name: string,
spanKind: SpanKind,
attributes: Attributes,
links: Link[]
): SamplingResult {
const parentContext = trace.getSpanContext(context);
// Exclude Prisma spans (adjust this logic as needed for your use case)
if (!parentContext && name.includes("prisma")) {
return { decision: SamplingDecision.NOT_RECORD };
}
// If the span has the forceRecording attribute, always record it
if (attributes[SEMINTATTRS_FORCE_RECORDING]) {
return { decision: SamplingDecision.RECORD_AND_SAMPLED };
}
// For all other spans, defer to the base sampler
const result = this._baseSampler.shouldSample(
context,
traceId,
name,
spanKind,
attributes,
links
);
return result;
}
toString(): string {
return `CustomWebappSampler`;
}
}
export const { tracer, logger: otelLogger, provider } = singleton("tracer", getTracer);
export async function startActiveSpan<T>(
name: string,
fn: (span: Span) => Promise<T>,
options?: SpanOptions
): Promise<T> {
return tracer.startActiveSpan(name, options ?? {}, async (span) => {
try {
return await fn(span);
} catch (error) {
if (error instanceof Error) {
span.recordException(error);
} else if (typeof error === "string") {
span.recordException(new Error(error));
} else {
span.recordException(new Error(String(error)));
}
span.setStatus({
code: SpanStatusCode.ERROR,
message: error instanceof Error ? error.message : String(error),
});
logger.debug(`Error in span: ${name}`, { error });
throw error;
} finally {
span.end();
}
});
}
export async function emitDebugLog(message: string, params: Record<string, unknown> = {}) {
otelLogger.emit({
severityNumber: SeverityNumber.DEBUG,
body: message,
attributes: { ...flattenAttributes(params, "params") },
});
}
export async function emitInfoLog(message: string, params: Record<string, unknown> = {}) {
otelLogger.emit({
severityNumber: SeverityNumber.INFO,
body: message,
attributes: { ...flattenAttributes(params, "params") },
});
}
export async function emitErrorLog(message: string, params: Record<string, unknown> = {}) {
otelLogger.emit({
severityNumber: SeverityNumber.ERROR,
body: message,
attributes: { ...flattenAttributes(params, "params") },
});
}
export async function emitWarnLog(message: string, params: Record<string, unknown> = {}) {
otelLogger.emit({
severityNumber: SeverityNumber.WARN,
body: message,
attributes: { ...flattenAttributes(params, "params") },
});
}
function getTracer() {
if (env.INTERNAL_OTEL_TRACE_DISABLED === "1") {
console.log(`🔦 Tracer disabled, returning a noop tracer`);
return {
tracer: trace.getTracer("trigger.dev", "3.3.12"),
logger: logs.getLogger("trigger.dev", "3.3.12"),
provider: new NodeTracerProvider(),
};
}
diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.ERROR);
const samplingRate = 1.0 / Math.max(parseInt(env.INTERNAL_OTEL_TRACE_SAMPLING_RATE, 10), 1);
const provider = new NodeTracerProvider({
forceFlushTimeoutMillis: 15_000,
resource: new Resource({
[SEMRESATTRS_SERVICE_NAME]: env.SERVICE_NAME,
}),
sampler: new ParentBasedSampler({
root: new CustomWebappSampler(new TraceIdRatioBasedSampler(samplingRate)),
}),
spanLimits: {
attributeCountLimit: 1024,
},
});
if (env.INTERNAL_OTEL_TRACE_EXPORTER_URL) {
const headers = parseInternalTraceHeaders() ?? {};
const exporter = new OTLPTraceExporter({
url: env.INTERNAL_OTEL_TRACE_EXPORTER_URL,
timeoutMillis: 15_000,
headers,
});
provider.addSpanProcessor(
new BatchSpanProcessor(exporter, {
maxExportBatchSize: 512,
scheduledDelayMillis: 1000,
exportTimeoutMillis: 30000,
maxQueueSize: 2048,
})
);
console.log(
`🔦 Tracer: OTLP exporter enabled to ${env.INTERNAL_OTEL_TRACE_EXPORTER_URL} (sampling = ${samplingRate})`
);
} else {
if (env.INTERNAL_OTEL_TRACE_LOGGING_ENABLED === "1") {
console.log(`🔦 Tracer: Logger exporter enabled (sampling = ${samplingRate})`);
const loggerExporter = new LoggerSpanExporter();
provider.addSpanProcessor(new SimpleSpanProcessor(loggerExporter));
}
}
if (env.INTERNAL_OTEL_LOG_EXPORTER_URL) {
const headers = parseInternalTraceHeaders() ?? {};
const logExporter = new OTLPLogExporter({
url: env.INTERNAL_OTEL_LOG_EXPORTER_URL,
timeoutMillis: 15_000,
headers,
});
const loggerProvider = new LoggerProvider({
resource: new Resource({
[SEMRESATTRS_SERVICE_NAME]: env.SERVICE_NAME,
}),
logRecordLimits: {
attributeCountLimit: 1000,
},
});
loggerProvider.addLogRecordProcessor(
new BatchLogRecordProcessor(logExporter, {
maxExportBatchSize: 64,
scheduledDelayMillis: 200,
exportTimeoutMillis: 30000,
maxQueueSize: 512,
})
);
logs.setGlobalLoggerProvider(loggerProvider);
console.log(
`🔦 Tracer: OTLP log exporter enabled to ${env.INTERNAL_OTEL_LOG_EXPORTER_URL} (sampling = ${samplingRate})`
);
}
provider.register();
let instrumentations: Instrumentation[] = [
new HttpInstrumentation(),
new ExpressInstrumentation(),
];
if (env.INTERNAL_OTEL_TRACE_INSTRUMENT_PRISMA_ENABLED === "1") {
instrumentations.push(new PrismaInstrumentation());
}
registerInstrumentations({
tracerProvider: provider,
loggerProvider: logs.getLoggerProvider(),
instrumentations,
});
return {
tracer: provider.getTracer("trigger.dev", "3.3.12"),
logger: logs.getLogger("trigger.dev", "3.3.12"),
provider,
};
}
const SemanticEnvResources = {
ENV_ID: "$trigger.env.id",
ENV_TYPE: "$trigger.env.type",
ENV_SLUG: "$trigger.env.slug",
ORG_ID: "$trigger.org.id",
ORG_SLUG: "$trigger.org.slug",
ORG_TITLE: "$trigger.org.title",
PROJECT_ID: "$trigger.project.id",
PROJECT_NAME: "$trigger.project.name",
USER_ID: "$trigger.user.id",
};
export function attributesFromAuthenticatedEnv(env: AuthenticatedEnvironment): Attributes {
return {
[SemanticEnvResources.ENV_ID]: env.id,
[SemanticEnvResources.ENV_TYPE]: env.type,
[SemanticEnvResources.ENV_SLUG]: env.slug,
[SemanticEnvResources.ORG_ID]: env.organizationId,
[SemanticEnvResources.ORG_SLUG]: env.organization.slug,
[SemanticEnvResources.ORG_TITLE]: env.organization.title,
[SemanticEnvResources.PROJECT_ID]: env.projectId,
[SemanticEnvResources.PROJECT_NAME]: env.project.name,
[SemanticEnvResources.USER_ID]: env.orgMember?.userId,
};
}
function parseInternalTraceHeaders(): Record<string, string> | undefined {
try {
return env.INTERNAL_OTEL_TRACE_EXPORTER_AUTH_HEADERS
? (JSON.parse(env.INTERNAL_OTEL_TRACE_EXPORTER_AUTH_HEADERS) as Record<string, string>)
: undefined;
} catch {
return;
}
}