// A checkout traced end to end: a server span for the request, a child span for the payment
// call (its traceparent passed on), a log line tied to the trace, and the shop's gauges.
//
//   OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 quillo run otlp.qwe      then open http://localhost:8080/checkout
//   (Honeycomb, Grafana Cloud: set OTEL_EXPORTER_OTLP_HEADERS=x-honeycomb-team=... too)

use "otlp.qwer"

let CONFIG = { endpoint: env("OTEL_EXPORTER_OTLP_ENDPOINT", null) ?? env("SINK_URL", null), resource: { "deployment.environment": "production" } }

route GET /checkout {
    let start = now()
    // Join the caller's trace when it sent one.
    let parent = otlp_parse_traceparent(request.headers.traceparent ?? "")
    let trace = is_err(parent) ? otlp_ids().trace_id : parent.trace_id
    let server = otlp_span("POST /checkout", start, start + 180, { trace_id: trace, parent_span_id: is_err(parent) ? null : parent.parent_span_id, kind: "server", attributes: { "http.method": "POST", "http.route": "/checkout", "http.status_code": 200 }, status: "ok" })?
    let pay = otlp_span("stripe.charge", start + 20, start + 160, { trace_id: trace, parent_span_id: server.span_id, kind: "client", attributes: { "peer.service": "stripe", "order.total": 52.9 } })?
    {
        traces: otlp_send_traces("shop", [server, pay], CONFIG)?,
        logs: otlp_send_logs("shop", [{ body: "order A-1042 paid", severity: "INFO", trace_id: trace, span_id: pay.span_id, attributes: { order: "A-1042" } }], CONFIG)?,
        metrics: otlp_send_metrics("shop", [{ name: "shop.queue.length", value: 3, kind: "gauge" }, { name: "shop.orders", value: 1042, kind: "counter", unit: "{order}" }], CONFIG)?,
        next_hop: otlp_traceparent(trace, pay.span_id, true)?,
    }
}

route GET /ids = {
    parsed: otlp_parse_traceparent("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")?,
    bad: otlp_parse_traceparent("00-000-xyz-01").error,
    span: otlp_span("load cart", 1793260800000, 1793260800042, { trace_id: "4bf92f3577b34da6a3ce929d0e0e4736", span_id: "00f067aa0ba902b7", attributes: { items: 3 } })?,
}
