|
| 1 | +package delayq |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/gob" |
| 7 | + |
| 8 | + ztrace "github.com/zeromicro/go-zero/core/trace" |
| 9 | + "go.opentelemetry.io/otel" |
| 10 | + "go.opentelemetry.io/otel/propagation" |
| 11 | + "go.opentelemetry.io/otel/trace" |
| 12 | +) |
| 13 | + |
| 14 | +type ( |
| 15 | + Action string |
| 16 | + Message struct { |
| 17 | + Carrier propagation.MapCarrier |
| 18 | + Action Action |
| 19 | + Body []byte |
| 20 | + } |
| 21 | +) |
| 22 | + |
| 23 | +func (m *Message) Encode() ([]byte, error) { |
| 24 | + var buf bytes.Buffer |
| 25 | + enc := gob.NewEncoder(&buf) |
| 26 | + if err := enc.Encode(m); err != nil { |
| 27 | + return nil, err |
| 28 | + } |
| 29 | + return buf.Bytes(), nil |
| 30 | +} |
| 31 | + |
| 32 | +func (m *Message) Inject(ctx context.Context) (context.Context, trace.Span) { |
| 33 | + tracer := otel.Tracer(ztrace.TraceName) |
| 34 | + spanCtx, span := tracer.Start(ctx, string(m.Action), trace.WithSpanKind(trace.SpanKindProducer)) |
| 35 | + m.Carrier = propagation.MapCarrier{} |
| 36 | + propagator := otel.GetTextMapPropagator() |
| 37 | + propagator.Inject(spanCtx, m.Carrier) |
| 38 | + return spanCtx, span |
| 39 | +} |
| 40 | + |
| 41 | +func (m *Message) Decode(data []byte) error { |
| 42 | + buf := bytes.NewBuffer(data) |
| 43 | + dec := gob.NewDecoder(buf) |
| 44 | + return dec.Decode(m) |
| 45 | +} |
| 46 | + |
| 47 | +func (m *Message) Extract(ctx context.Context) (context.Context, trace.Span) { |
| 48 | + propagator := otel.GetTextMapPropagator() |
| 49 | + ctx = propagator.Extract(ctx, m.Carrier) |
| 50 | + tracer := otel.Tracer(ztrace.TraceName) |
| 51 | + spanCtx, span := tracer.Start(ctx, string(m.Action), trace.WithSpanKind(trace.SpanKindConsumer)) |
| 52 | + return spanCtx, span |
| 53 | +} |
0 commit comments