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
|
package main
// OpenTelemetry tracing.
//
// The Haskell version used hs-opentelemetry-sdk with the OTLP/HTTP exporter and
// exported to the jaeger-all-in-one that runs next to the service (OTLP on
// :4318, UI on :16686). We keep that setup, but write the exporter ourselves.
//
// Why not go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp? That
// package imports go.opentelemetry.io/proto/otlp, whose collector service
// definitions pull in google.golang.org/grpc, genproto and grpc-gateway even
// when only the *HTTP* transport is used — about 45 extra packages, every one of
// which would need to be pinned by hand in go-deps.nix (buildGo has no module
// resolution, see `man ./nix/buildGo/buildGo.7`).
//
// The OTLP spec defines a JSON encoding of the same protobuf messages, and
// Jaeger accepts it on the same /v1/traces endpoint. Encoding it with
// encoding/json is ~100 lines and costs zero dependencies, so that is what this
// file does. The wire format is the protobuf JSON mapping: 64-bit integers are
// strings, trace/span IDs are hex, enums are numbers.
//
// Span attributes are prefixed with "_." exactly as the Haskell `addAttribute`
// did, so existing saved Jaeger queries keep matching.
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"os"
"strconv"
"time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.43.0"
"go.opentelemetry.io/otel/trace"
)
const tracerName = "whatcd-resolver"
// tracer is the global tracer. Set by initTracing.
var tracer trace.Tracer = otel.Tracer(tracerName)
// initTracing installs a tracer provider exporting to the OTLP endpoint.
//
// Mirrors the Haskell `withTracer`: OTEL_SERVICE_NAME defaults to
// "whatcd-resolver". The endpoint is taken from OTEL_EXPORTER_OTLP_ENDPOINT
// (default http://localhost:4318, i.e. the local jaeger-all-in-one).
//
// If tracing is disabled the returned shutdown function is a no-op and spans
// become non-recording, so call sites need no conditionals.
func initTracing(ctx context.Context) (func(context.Context) error, error) {
if os.Getenv("WHATCD_RESOLVER_DISABLE_TRACING") != "" {
slog.Info("tracing disabled via WHATCD_RESOLVER_DISABLE_TRACING")
return func(context.Context) error { return nil }, nil
}
serviceName := os.Getenv("OTEL_SERVICE_NAME")
if serviceName == "" {
serviceName = "whatcd-resolver"
}
endpoint := os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT")
if endpoint == "" {
endpoint = "http://localhost:4318"
}
res, err := resource.Merge(
resource.Default(),
resource.NewWithAttributes(
semconv.SchemaURL,
semconv.ServiceName(serviceName),
),
)
if err != nil {
return nil, fmt.Errorf("building otel resource: %w", err)
}
exp := &otlpJSONExporter{
url: endpoint + "/v1/traces",
client: &http.Client{Timeout: 10 * time.Second},
}
tp := sdktrace.NewTracerProvider(
sdktrace.WithBatcher(exp),
sdktrace.WithResource(res),
)
otel.SetTracerProvider(tp)
tracer = tp.Tracer(tracerName)
slog.Info("tracing enabled", "service", serviceName, "endpoint", endpoint)
return tp.Shutdown, nil
}
// ---------------------------------------------------------------------------
// Span helpers
//
// The Haskell code wrapped nearly every operation in `inSpan`/`inSpan'`. These
// helpers keep call sites similarly short.
// ---------------------------------------------------------------------------
// inSpan runs f inside a new span, recording an error on the span if f fails.
func inSpan(ctx context.Context, name string, f func(context.Context, trace.Span) error) error {
ctx, span := tracer.Start(ctx, name)
defer span.End()
if err := f(ctx, span); err != nil {
recordError(span, err)
return err
}
return nil
}
// inSpan1 is inSpan for an operation returning a value.
func inSpan1[A any](ctx context.Context, name string, f func(context.Context, trace.Span) (A, error)) (A, error) {
ctx, span := tracer.Start(ctx, name)
defer span.End()
a, err := f(ctx, span)
if err != nil {
recordError(span, err)
}
return a, err
}
// recordError records err on the span and marks the span as failed.
//
// Matches the Haskell `recordError`, which also logged; we log here too so that
// failures are visible without a Jaeger instance.
func recordError(span trace.Span, err error) {
if err == nil {
return
}
slog.Error("span failed", "span", spanName(span), "err", err)
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
}
// spanName is best-effort: the OTel API exposes the name only on the SDK type.
func spanName(span trace.Span) string {
if ro, ok := span.(interface{ Name() string }); ok {
return ro.Name()
}
return ""
}
// attr adds an attribute under the "_." namespace, distinguishing our
// attributes from the semantic-convention ones, as the Haskell version did.
func attr(span trace.Span, key string, value any) {
span.SetAttributes(kv(key, value))
}
// kv builds a "_."-prefixed attribute.
func kv(key string, value any) attribute.KeyValue {
k := "_." + key
switch v := value.(type) {
case string:
return attribute.String(k, v)
case bool:
return attribute.Bool(k, v)
case int:
return attribute.Int(k, v)
case int64:
return attribute.Int64(k, v)
case uint64:
return attribute.String(k, strconv.FormatUint(v, 10))
case float64:
return attribute.Float64(k, v)
case []string:
return attribute.StringSlice(k, v)
case nil:
return attribute.String(k, "null")
default:
// Best effort, mirroring the Haskell `toOtelJsonAttr`: anything else is
// rendered as JSON so it is at least inspectable in the UI.
if b, err := json.Marshal(v); err == nil {
return attribute.String(k, string(b))
}
return attribute.String(k, fmt.Sprintf("%v", v))
}
}
// event adds a zero-attribute event, like the Haskell `addEventSimple`.
func event(span trace.Span, name string) {
span.AddEvent(name)
}
// ---------------------------------------------------------------------------
// OTLP/JSON exporter
// ---------------------------------------------------------------------------
type otlpJSONExporter struct {
url string
client *http.Client
}
// ExportSpans implements sdktrace.SpanExporter.
//
// Export failures are logged and swallowed: losing traces must never take the
// application down.
func (e *otlpJSONExporter) ExportSpans(ctx context.Context, spans []sdktrace.ReadOnlySpan) error {
if len(spans) == 0 {
return nil
}
payload := buildOTLPPayload(spans)
body, err := json.Marshal(payload)
if err != nil {
slog.Warn("otlp: encoding spans failed", "err", err)
return nil
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, e.url, bytes.NewReader(body))
if err != nil {
slog.Warn("otlp: building request failed", "err", err)
return nil
}
req.Header.Set("Content-Type", "application/json")
resp, err := e.client.Do(req)
if err != nil {
slog.Warn("otlp: exporting spans failed", "err", err)
return nil
}
defer resp.Body.Close()
if resp.StatusCode/100 != 2 {
slog.Warn("otlp: collector rejected spans", "status", resp.StatusCode)
}
return nil
}
func (e *otlpJSONExporter) Shutdown(context.Context) error { return nil }
// The OTLP JSON wire types. Only the fields we actually emit are modelled.
type otlpPayload struct {
ResourceSpans []otlpResourceSpans `json:"resourceSpans"`
}
type otlpResourceSpans struct {
Resource otlpResource `json:"resource"`
ScopeSpans []otlpScopeSpans `json:"scopeSpans"`
}
type otlpResource struct {
Attributes []otlpKeyValue `json:"attributes,omitempty"`
}
type otlpScopeSpans struct {
Scope otlpScope `json:"scope"`
Spans []otlpSpan `json:"spans"`
}
type otlpScope struct {
Name string `json:"name"`
Version string `json:"version,omitempty"`
}
type otlpSpan struct {
TraceID string `json:"traceId"`
SpanID string `json:"spanId"`
ParentSpanID string `json:"parentSpanId,omitempty"`
Name string `json:"name"`
Kind int `json:"kind"`
StartTimeUnixNano string `json:"startTimeUnixNano"`
EndTimeUnixNano string `json:"endTimeUnixNano"`
Attributes []otlpKeyValue `json:"attributes,omitempty"`
Events []otlpEvent `json:"events,omitempty"`
Status otlpStatus `json:"status"`
}
type otlpEvent struct {
TimeUnixNano string `json:"timeUnixNano"`
Name string `json:"name"`
Attributes []otlpKeyValue `json:"attributes,omitempty"`
}
type otlpStatus struct {
Message string `json:"message,omitempty"`
Code int `json:"code,omitempty"`
}
type otlpKeyValue struct {
Key string `json:"key"`
Value otlpValue `json:"value"`
}
// otlpValue is a protobuf oneof: exactly one field is set.
type otlpValue struct {
StringValue *string `json:"stringValue,omitempty"`
BoolValue *bool `json:"boolValue,omitempty"`
IntValue *string `json:"intValue,omitempty"`
DoubleValue *float64 `json:"doubleValue,omitempty"`
ArrayValue *otlpArrayVal `json:"arrayValue,omitempty"`
}
type otlpArrayVal struct {
Values []otlpValue `json:"values"`
}
// buildOTLPPayload groups spans by resource and instrumentation scope, as the
// protocol requires.
func buildOTLPPayload(spans []sdktrace.ReadOnlySpan) otlpPayload {
// Spans in one batch usually share a resource; group by scope name only,
// and take the resource from the first span.
byScope := map[string][]otlpSpan{}
order := []string{}
for _, s := range spans {
name := s.InstrumentationScope().Name
if _, seen := byScope[name]; !seen {
order = append(order, name)
}
byScope[name] = append(byScope[name], convertSpan(s))
}
var res otlpResource
if len(spans) > 0 && spans[0].Resource() != nil {
res.Attributes = convertAttrs(spans[0].Resource().Attributes())
}
scopeSpans := make([]otlpScopeSpans, 0, len(order))
for _, name := range order {
scopeSpans = append(scopeSpans, otlpScopeSpans{
Scope: otlpScope{Name: name},
Spans: byScope[name],
})
}
return otlpPayload{ResourceSpans: []otlpResourceSpans{{Resource: res, ScopeSpans: scopeSpans}}}
}
func convertSpan(s sdktrace.ReadOnlySpan) otlpSpan {
sc := s.SpanContext()
out := otlpSpan{
TraceID: sc.TraceID().String(),
SpanID: sc.SpanID().String(),
Name: s.Name(),
Kind: int(s.SpanKind()),
StartTimeUnixNano: strconv.FormatInt(s.StartTime().UnixNano(), 10),
EndTimeUnixNano: strconv.FormatInt(s.EndTime().UnixNano(), 10),
Attributes: convertAttrs(s.Attributes()),
}
if p := s.Parent(); p.IsValid() {
out.ParentSpanID = p.SpanID().String()
}
for _, ev := range s.Events() {
out.Events = append(out.Events, otlpEvent{
TimeUnixNano: strconv.FormatInt(ev.Time.UnixNano(), 10),
Name: ev.Name,
Attributes: convertAttrs(ev.Attributes),
})
}
switch s.Status().Code {
case codes.Error:
out.Status = otlpStatus{Code: 2, Message: s.Status().Description}
case codes.Ok:
out.Status = otlpStatus{Code: 1}
}
return out
}
func convertAttrs(attrs []attribute.KeyValue) []otlpKeyValue {
if len(attrs) == 0 {
return nil
}
out := make([]otlpKeyValue, 0, len(attrs))
for _, a := range attrs {
out = append(out, otlpKeyValue{Key: string(a.Key), Value: convertValue(a.Value)})
}
return out
}
func convertValue(v attribute.Value) otlpValue {
switch v.Type() {
case attribute.BOOL:
b := v.AsBool()
return otlpValue{BoolValue: &b}
case attribute.INT64:
s := strconv.FormatInt(v.AsInt64(), 10)
return otlpValue{IntValue: &s}
case attribute.FLOAT64:
f := v.AsFloat64()
return otlpValue{DoubleValue: &f}
case attribute.STRING:
s := v.AsString()
return otlpValue{StringValue: &s}
case attribute.BOOLSLICE:
vals := []otlpValue{}
for _, b := range v.AsBoolSlice() {
b := b
vals = append(vals, otlpValue{BoolValue: &b})
}
return otlpValue{ArrayValue: &otlpArrayVal{Values: vals}}
case attribute.INT64SLICE:
vals := []otlpValue{}
for _, i := range v.AsInt64Slice() {
s := strconv.FormatInt(i, 10)
vals = append(vals, otlpValue{IntValue: &s})
}
return otlpValue{ArrayValue: &otlpArrayVal{Values: vals}}
case attribute.FLOAT64SLICE:
vals := []otlpValue{}
for _, f := range v.AsFloat64Slice() {
f := f
vals = append(vals, otlpValue{DoubleValue: &f})
}
return otlpValue{ArrayValue: &otlpArrayVal{Values: vals}}
case attribute.STRINGSLICE:
vals := []otlpValue{}
for _, s := range v.AsStringSlice() {
s := s
vals = append(vals, otlpValue{StringValue: &s})
}
return otlpValue{ArrayValue: &otlpArrayVal{Values: vals}}
default:
s := v.Emit()
return otlpValue{StringValue: &s}
}
}
|