diff --git a/docs/api/openapi.json b/docs/api/openapi.json index 1bfae60ea..11c587bf1 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -1,6 +1,22 @@ { "components": { "schemas": { + "Backfill": { + "description": "Whether the records from before rollups existed are all counted yet.", + "properties": { + "complete": { + "description": "False while older records are still being counted; numbers grow until it is true.", + "examples": [ + true + ], + "type": "boolean" + } + }, + "required": [ + "complete" + ], + "type": "object" + }, "CiUploadResult": { "description": "A report that was taken in.", "properties": { @@ -209,6 +225,261 @@ ], "type": "object" }, + "DeliveryAnalytics": { + "description": "The Deliveries overview for one period.", + "examples": [ + { + "backfill": { + "complete": true + }, + "endpoints": [ + { + "deleted": false, + "deliveries": 214, + "description": "Incident bot", + "disabled_reason": "", + "enabled": true, + "failed": 12, + "failing_since": null, + "id": "ep_01JBENDPT4K2M8N3P5Q7R9S1T3", + "last_failure_at": "2026-10-26T09:14:02Z", + "last_failure_message": "Your webhook endpoint answered with a server error (5xx).", + "last_failure_reason": "webhook_server_error", + "last_success_at": "2026-10-26T15:02:40Z", + "ok": 202, + "p50_ms": 320, + "p95_ms": 2900, + "streak": 0, + "success_rate": 0.9439, + "url": "https://hooks.example.com/coderhelm" + } + ], + "events": [ + { + "event": "run.failed", + "failed": 9, + "source": "webhook" + } + ], + "from": "2026-10-20T00:00:00Z", + "granularity": "day", + "kept_days": 120, + "period": "7d", + "previous": { + "deliveries": 1120, + "failed": 28, + "handled": 1040, + "ignored": 52, + "p50_ms": 170, + "p95_ms": 1100, + "p99_ms": 4100, + "retried": 30, + "retried_ok": 26, + "retries": 44, + "success_rate": 0.975 + }, + "previous_from": "2026-10-13T00:00:00Z", + "previous_to": "2026-10-20T00:00:00Z", + "reasons": [ + { + "code": "webhook_server_error", + "count": 12, + "fix": "Check your endpoint's logs for this event id. CoderHelm retries for about a day.", + "message": "Your webhook endpoint answered with a server error (5xx).", + "previous_count": 3, + "sources": [ + "webhook" + ] + } + ], + "records_kept_days": 14, + "seen_sources": [ + "github", + "webhook", + "slack", + "email" + ], + "series": [ + { + "deliveries": 190, + "end": "2026-10-27T00:00:00Z", + "failed": 4, + "ok": 186, + "p95_ms": 1100, + "previous_deliveries": 171, + "start": "2026-10-26T00:00:00Z", + "success_rate": 0.9789 + } + ], + "sources": [ + { + "deliveries": 912, + "direction": "inbound", + "failed": 7, + "ok": 905, + "p95_ms": 640, + "previous_deliveries": 870, + "previous_success_rate": 0.9897, + "source": "github", + "success_rate": 0.9923 + } + ], + "summary": { + "deliveries": 1284, + "failed": 33, + "handled": 1190, + "ignored": 61, + "p50_ms": 180, + "p95_ms": 1240, + "p99_ms": 4800, + "retried": 41, + "retried_ok": 37, + "retries": 58, + "success_rate": 0.9743 + }, + "to": "2026-10-27T00:00:00Z" + } + ], + "properties": { + "backfill": { + "$ref": "#/components/schemas/Backfill" + }, + "endpoints": { + "description": "The team's outbound webhook endpoints, and any that had deliveries\nin the period since. Empty when another source is chosen.", + "items": { + "$ref": "#/components/schemas/EndpointRow" + }, + "type": "array" + }, + "events": { + "description": "The event types that failed most (up to 10).", + "items": { + "$ref": "#/components/schemas/EventRow" + }, + "type": "array" + }, + "from": { + "description": "The period: from (inclusive) to (exclusive), RFC 3339.", + "examples": [ + "2026-10-20T00:00:00Z" + ], + "type": "string" + }, + "granularity": { + "description": "`hour` or `day`.", + "examples": [ + "day" + ], + "type": "string" + }, + "kept_days": { + "description": "Days the counts are kept.", + "examples": [ + 120 + ], + "format": "int64", + "type": "integer" + }, + "period": { + "description": "`24h`, `7d` or `30d`.", + "examples": [ + "7d" + ], + "type": "string" + }, + "previous": { + "$ref": "#/components/schemas/Totals" + }, + "previous_from": { + "description": "The period before, as long as this one.", + "examples": [ + "2026-10-13T00:00:00Z" + ], + "type": "string" + }, + "previous_to": { + "description": "The end of the period before, exclusive.", + "examples": [ + "2026-10-20T00:00:00Z" + ], + "type": "string" + }, + "reasons": { + "description": "Failures by reason, most first.", + "items": { + "$ref": "#/components/schemas/ReasonRow" + }, + "type": "array" + }, + "records_kept_days": { + "description": "Days each delivery's record is kept (what a drill-in can list).", + "examples": [ + 14 + ], + "format": "int64", + "type": "integer" + }, + "seen_sources": { + "description": "Every source with deliveries in either period, for the filter.", + "examples": [ + [ + "github", + "webhook", + "slack", + "email" + ] + ], + "items": { + "type": "string" + }, + "type": "array" + }, + "series": { + "description": "One point per hour (24h) or day, oldest first.", + "items": { + "$ref": "#/components/schemas/Point" + }, + "type": "array" + }, + "sources": { + "description": "By source and direction, most deliveries first.", + "items": { + "$ref": "#/components/schemas/SourceRow" + }, + "type": "array" + }, + "summary": { + "$ref": "#/components/schemas/Totals" + }, + "to": { + "description": "The end of the period, exclusive.", + "examples": [ + "2026-10-27T00:00:00Z" + ], + "type": "string" + } + }, + "required": [ + "period", + "granularity", + "from", + "to", + "previous_from", + "previous_to", + "summary", + "previous", + "series", + "sources", + "reasons", + "events", + "endpoints", + "seen_sources", + "backfill", + "kept_days", + "records_kept_days" + ], + "type": "object" + }, "DeliveryAttempt": { "description": "One attempt.", "properties": { @@ -255,6 +526,183 @@ ], "type": "object" }, + "EndpointRow": { + "description": "One outbound webhook endpoint.", + "properties": { + "deleted": { + "description": "The endpoint no longer exists; its counts stay for the period.", + "examples": [ + false + ], + "type": "boolean" + }, + "deliveries": { + "description": "Finished deliveries to it in the period.", + "examples": [ + 214 + ], + "format": "int64", + "type": "integer" + }, + "description": { + "description": "The endpoint's description, as the team wrote it.", + "examples": [ + "Incident bot" + ], + "type": "string" + }, + "disabled_reason": { + "description": "Why it's off: `manual` or `failing`. Empty while on.", + "examples": [ + "" + ], + "type": "string" + }, + "enabled": { + "description": "Whether the endpoint is on.", + "examples": [ + true + ], + "type": "boolean" + }, + "failed": { + "description": "Failed.", + "examples": [ + 12 + ], + "format": "int64", + "type": "integer" + }, + "failing_since": { + "description": "The first failure since its last success, while it's failing.", + "examples": [ + null + ], + "type": [ + "string", + "null" + ] + }, + "id": { + "description": "The endpoint's id.", + "examples": [ + "ep_01JBENDPT4K2M8N3P5Q7R9S1T3" + ], + "type": "string" + }, + "last_failure_at": { + "description": "When it last failed.", + "examples": [ + "2026-10-26T09:14:02Z" + ], + "type": [ + "string", + "null" + ] + }, + "last_failure_message": { + "description": "The last failure's reason in plain words.", + "examples": [ + "Your webhook endpoint answered with a server error (5xx)." + ], + "type": [ + "string", + "null" + ] + }, + "last_failure_reason": { + "description": "The last failure's reason code.", + "examples": [ + "webhook_server_error" + ], + "type": [ + "string", + "null" + ] + }, + "last_success_at": { + "description": "When it last took a delivery.", + "examples": [ + "2026-10-26T15:02:40Z" + ], + "type": [ + "string", + "null" + ] + }, + "ok": { + "description": "Delivered.", + "examples": [ + 202 + ], + "format": "int64", + "type": "integer" + }, + "p50_ms": { + "description": "Median latency, milliseconds.", + "examples": [ + 320 + ], + "format": "int64", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "p95_ms": { + "description": "95th percentile latency, milliseconds.", + "examples": [ + 2900 + ], + "format": "int64", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "streak": { + "description": "Failures in a row since its last success.", + "examples": [ + 0 + ], + "format": "int64", + "type": "integer" + }, + "success_rate": { + "description": "Delivered, out of finished. Null with none.", + "examples": [ + 0.9439 + ], + "format": "double", + "type": [ + "number", + "null" + ] + }, + "url": { + "description": "The endpoint's address (empty once the endpoint is deleted).", + "examples": [ + "https://hooks.example.com/coderhelm" + ], + "type": "string" + } + }, + "required": [ + "id", + "url", + "description", + "deleted", + "enabled", + "disabled_reason", + "deliveries", + "ok", + "failed", + "streak" + ], + "type": "object" + }, "ErrorBody": { "description": "The body of every error an API key request gets.", "examples": [ @@ -296,6 +744,39 @@ ], "type": "object" }, + "EventRow": { + "description": "An event type that failed.", + "properties": { + "event": { + "description": "The event or message type.", + "examples": [ + "run.failed" + ], + "type": "string" + }, + "failed": { + "description": "Failures of this type in the period.", + "examples": [ + 9 + ], + "format": "int64", + "type": "integer" + }, + "source": { + "description": "Where it came from or went.", + "examples": [ + "webhook" + ], + "type": "string" + } + }, + "required": [ + "event", + "source", + "failed" + ], + "type": "object" + }, "JiraComment": { "description": "The comment in a Jira comment event.", "properties": { @@ -1331,6 +1812,89 @@ ], "type": "object" }, + "Point": { + "description": "One hour or day of the period.", + "properties": { + "deliveries": { + "description": "Finished deliveries in the bucket.", + "examples": [ + 190 + ], + "format": "int64", + "type": "integer" + }, + "end": { + "description": "The bucket's end, exclusive.", + "examples": [ + "2026-10-27T00:00:00Z" + ], + "type": "string" + }, + "failed": { + "description": "Failed.", + "examples": [ + 4 + ], + "format": "int64", + "type": "integer" + }, + "ok": { + "description": "Handled or ignored.", + "examples": [ + 186 + ], + "format": "int64", + "type": "integer" + }, + "p95_ms": { + "description": "95th percentile latency, milliseconds.", + "examples": [ + 1100 + ], + "format": "int64", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "previous_deliveries": { + "description": "Deliveries in the matching bucket of the period before.", + "examples": [ + 171 + ], + "format": "int64", + "type": "integer" + }, + "start": { + "description": "The bucket's start (RFC 3339, UTC).", + "examples": [ + "2026-10-26T00:00:00Z" + ], + "type": "string" + }, + "success_rate": { + "description": "Handled or ignored, out of finished. Null with none.", + "examples": [ + 0.9789 + ], + "format": "double", + "type": [ + "number", + "null" + ] + } + }, + "required": [ + "start", + "end", + "deliveries", + "ok", + "failed", + "previous_deliveries" + ], + "type": "object" + }, "Quarantine": { "description": "The tests quarantined for the calling repository.", "properties": { @@ -1445,6 +2009,69 @@ ], "type": "object" }, + "ReasonRow": { + "description": "Failures with one reason.", + "properties": { + "code": { + "description": "The reason code, as on each delivery.", + "examples": [ + "webhook_server_error" + ], + "type": "string" + }, + "count": { + "description": "Failures with this reason in the period.", + "examples": [ + 12 + ], + "format": "int64", + "type": "integer" + }, + "fix": { + "description": "What to do about it.", + "examples": [ + "Check your endpoint's logs for this event id. CoderHelm retries for about a day." + ], + "type": "string" + }, + "message": { + "description": "What happened, in plain words.", + "examples": [ + "Your webhook endpoint answered with a server error (5xx)." + ], + "type": "string" + }, + "previous_count": { + "description": "Failures with this reason in the period before.", + "examples": [ + 3 + ], + "format": "int64", + "type": "integer" + }, + "sources": { + "description": "The sources it happened on, most first.", + "examples": [ + [ + "webhook" + ] + ], + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "code", + "message", + "fix", + "count", + "previous_count", + "sources" + ], + "type": "object" + }, "ReplayBody": { "description": "Which kept events to send again.", "properties": { @@ -2661,112 +3288,326 @@ } }, "required": [ - "secret" + "secret" + ], + "type": "object" + }, + "SnsEnvelope": { + "description": "An Amazon SNS message, as SNS posts it to an HTTPS subscription.", + "examples": [ + { + "Message": "{\"AlarmName\":\"api-5xx\",\"NewStateValue\":\"ALARM\"}", + "MessageId": "6c3f7c6e-2f4b-5b8e-9b0e-1f0a2b3c4d5e", + "Signature": "EXAMPLE...", + "SignatureVersion": "2", + "SigningCertURL": "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-0000.pem", + "Subject": "ALARM: \"api-5xx\" in US East (N. Virginia)", + "Timestamp": "2026-10-22T14:00:00.000Z", + "TopicArn": "arn:aws:sns:us-east-1:123456789012:prod-alarms", + "Type": "Notification" + } + ], + "properties": { + "Message": { + "description": "The message: a CloudWatch alarm, an AWS Chatbot custom notification,\nan EventBridge event (as JSON text) or plain text.", + "examples": [ + "{\"AlarmName\":\"api-5xx\",\"NewStateValue\":\"ALARM\"}" + ], + "type": "string" + }, + "MessageId": { + "description": "SNS's id for the message.", + "examples": [ + "6c3f7c6e-2f4b-5b8e-9b0e-1f0a2b3c4d5e" + ], + "type": "string" + }, + "Signature": { + "description": "SNS's signature over the message's fields.", + "examples": [ + "EXAMPLEpH+DcEwjAPg8O9mY8dReBSwksfg2S7WKQcikcNKWLQjwu6A4VbeS0QHVCkhRS7fUQvi2egU3N858fiTDN6bkkOxYDVrY0Ad8L10Hs3zH81mtnPk5uvvolIC1CXGu43obcgFxeL3khZl8IKvO61GWB6jI9b5+gLPoBc1Q=" + ], + "type": "string" + }, + "SignatureVersion": { + "description": "`1` (SHA1) or `2` (SHA256).", + "examples": [ + "2" + ], + "type": "string" + }, + "SigningCertURL": { + "description": "The certificate that signed it; must be served by SNS.", + "examples": [ + "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-0000000000000000000000.pem" + ], + "type": "string" + }, + "Subject": { + "description": "The subject, when the publisher set one.", + "examples": [ + "ALARM: \"api-5xx\" in US East (N. Virginia)" + ], + "type": [ + "string", + "null" + ] + }, + "SubscribeURL": { + "description": "For a subscription confirmation: the address CoderHelm visits to confirm.", + "examples": [ + null + ], + "type": [ + "string", + "null" + ] + }, + "Timestamp": { + "description": "When SNS sent it.", + "examples": [ + "2026-10-22T14:00:00.000Z" + ], + "type": "string" + }, + "TopicArn": { + "description": "The topic. It must have an enabled alert route in the dashboard.", + "examples": [ + "arn:aws:sns:us-east-1:123456789012:prod-alarms" + ], + "type": "string" + }, + "Type": { + "description": "`SubscriptionConfirmation`, `Notification` or `UnsubscribeConfirmation`.", + "examples": [ + "Notification" + ], + "type": "string" + } + }, + "required": [ + "Type", + "MessageId", + "TopicArn", + "Message", + "Timestamp", + "SignatureVersion", + "Signature", + "SigningCertURL" + ], + "type": "object" + }, + "SourceRow": { + "description": "One source and direction.", + "properties": { + "deliveries": { + "description": "Finished deliveries in the period.", + "examples": [ + 912 + ], + "format": "int64", + "type": "integer" + }, + "direction": { + "description": "`inbound` or `outbound`.", + "examples": [ + "inbound" + ], + "type": "string" + }, + "failed": { + "description": "Failed.", + "examples": [ + 7 + ], + "format": "int64", + "type": "integer" + }, + "ok": { + "description": "Handled or ignored.", + "examples": [ + 905 + ], + "format": "int64", + "type": "integer" + }, + "p95_ms": { + "description": "95th percentile latency, milliseconds.", + "examples": [ + 640 + ], + "format": "int64", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "previous_deliveries": { + "description": "Finished deliveries in the period before.", + "examples": [ + 870 + ], + "format": "int64", + "type": "integer" + }, + "previous_success_rate": { + "description": "The success rate in the period before.", + "examples": [ + 0.9897 + ], + "format": "double", + "type": [ + "number", + "null" + ] + }, + "source": { + "description": "`github`, `relay`, `webhook`, `alerts`, `jira`, `slack`, `teams`, `email`, `broker`, `knowledge`.", + "examples": [ + "github" + ], + "type": "string" + }, + "success_rate": { + "description": "Handled or ignored, out of finished. Null with none.", + "examples": [ + 0.9923 + ], + "format": "double", + "type": [ + "number", + "null" + ] + } + }, + "required": [ + "source", + "direction", + "deliveries", + "ok", + "failed", + "previous_deliveries" ], "type": "object" }, - "SnsEnvelope": { - "description": "An Amazon SNS message, as SNS posts it to an HTTPS subscription.", - "examples": [ - { - "Message": "{\"AlarmName\":\"api-5xx\",\"NewStateValue\":\"ALARM\"}", - "MessageId": "6c3f7c6e-2f4b-5b8e-9b0e-1f0a2b3c4d5e", - "Signature": "EXAMPLE...", - "SignatureVersion": "2", - "SigningCertURL": "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-0000.pem", - "Subject": "ALARM: \"api-5xx\" in US East (N. Virginia)", - "Timestamp": "2026-10-22T14:00:00.000Z", - "TopicArn": "arn:aws:sns:us-east-1:123456789012:prod-alarms", - "Type": "Notification" - } - ], + "Totals": { + "description": "Headline numbers for one period.", "properties": { - "Message": { - "description": "The message: a CloudWatch alarm, an AWS Chatbot custom notification,\nan EventBridge event (as JSON text) or plain text.", + "deliveries": { + "description": "Finished deliveries (handled, ignored or failed).", "examples": [ - "{\"AlarmName\":\"api-5xx\",\"NewStateValue\":\"ALARM\"}" + 1284 ], - "type": "string" + "format": "int64", + "type": "integer" }, - "MessageId": { - "description": "SNS's id for the message.", + "failed": { + "description": "Finished and failed.", "examples": [ - "6c3f7c6e-2f4b-5b8e-9b0e-1f0a2b3c4d5e" + 33 ], - "type": "string" + "format": "int64", + "type": "integer" }, - "Signature": { - "description": "SNS's signature over the message's fields.", + "handled": { + "description": "Finished and handled.", "examples": [ - "EXAMPLEpH+DcEwjAPg8O9mY8dReBSwksfg2S7WKQcikcNKWLQjwu6A4VbeS0QHVCkhRS7fUQvi2egU3N858fiTDN6bkkOxYDVrY0Ad8L10Hs3zH81mtnPk5uvvolIC1CXGu43obcgFxeL3khZl8IKvO61GWB6jI9b5+gLPoBc1Q=" + 1190 ], - "type": "string" + "format": "int64", + "type": "integer" }, - "SignatureVersion": { - "description": "`1` (SHA1) or `2` (SHA256).", + "ignored": { + "description": "Finished and ignored on purpose (a duplicate, an event nothing needed).", "examples": [ - "2" + 61 ], - "type": "string" + "format": "int64", + "type": "integer" }, - "SigningCertURL": { - "description": "The certificate that signed it; must be served by SNS.", + "p50_ms": { + "description": "Latency percentiles in milliseconds (the last attempt's), from a\nhistogram, so within a bucket's width. Null with no timed deliveries.", "examples": [ - "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-0000000000000000000000.pem" + 180 ], - "type": "string" + "format": "int64", + "minimum": 0, + "type": [ + "integer", + "null" + ] }, - "Subject": { - "description": "The subject, when the publisher set one.", + "p95_ms": { + "description": "95th percentile latency, milliseconds.", "examples": [ - "ALARM: \"api-5xx\" in US East (N. Virginia)" + 1240 ], + "format": "int64", + "minimum": 0, "type": [ - "string", + "integer", "null" ] }, - "SubscribeURL": { - "description": "For a subscription confirmation: the address CoderHelm visits to confirm.", + "p99_ms": { + "description": "99th percentile latency, milliseconds.", "examples": [ - null + 4800 ], + "format": "int64", + "minimum": 0, "type": [ - "string", + "integer", "null" ] }, - "Timestamp": { - "description": "When SNS sent it.", + "retried": { + "description": "Deliveries that took more than one attempt.", "examples": [ - "2026-10-22T14:00:00.000Z" + 41 ], - "type": "string" + "format": "int64", + "type": "integer" }, - "TopicArn": { - "description": "The topic. It must have an enabled alert route in the dashboard.", + "retried_ok": { + "description": "Of those, the ones that went fine in the end.", "examples": [ - "arn:aws:sns:us-east-1:123456789012:prod-alarms" + 37 ], - "type": "string" + "format": "int64", + "type": "integer" }, - "Type": { - "description": "`SubscriptionConfirmation`, `Notification` or `UnsubscribeConfirmation`.", + "retries": { + "description": "Attempts after the first, in all. Null when a status filter is on.", "examples": [ - "Notification" + 58 ], - "type": "string" + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "success_rate": { + "description": "Handled or ignored, out of finished. Null with none.", + "examples": [ + 0.9743 + ], + "format": "double", + "type": [ + "number", + "null" + ] } }, "required": [ - "Type", - "MessageId", - "TopicArn", - "Message", - "Timestamp", - "SignatureVersion", - "Signature", - "SigningCertURL" + "deliveries", + "handled", + "ignored", + "failed", + "retried", + "retried_ok" ], "type": "object" }, @@ -3379,7 +4220,7 @@ "name": "CoderHelm support", "url": "https://docs.coderhelm.com/api" }, - "description": "The CoderHelm API lets your own programs start and follow CoderHelm's work: list and inspect runs, retry or cancel them, create and run plans, read the reviewer's reviews, check token usage, and manage the webhook endpoints CoderHelm sends your team's events to.\n\nEvery request is authenticated with a team API key sent as a bearer token. Admins create keys in the dashboard under Settings, API keys. A key holds scopes, never more than the admin who made it, and has its own rate limit.\n\nCI jobs upload test reports with a GitHub Actions OIDC token instead of a key, and the webhooks are verified by their signatures.", + "description": "The CoderHelm API lets your own programs start and follow CoderHelm's work: list and inspect runs, retry or cancel them, create and run plans, read the reviewer's reviews, check token usage, manage the webhook endpoints CoderHelm sends your team's events to, and see how deliveries went.\n\nEvery request is authenticated with a team API key sent as a bearer token. Admins create keys in the dashboard under Settings, API keys. A key holds scopes, never more than the admin who made it, and has its own rate limit.\n\nCI jobs upload test reports with a GitHub Actions OIDC token instead of a key, and the webhooks are verified by their signatures.", "license": { "identifier": "MIT", "name": "MIT" @@ -3389,6 +4230,173 @@ }, "openapi": "3.1.0", "paths": { + "/api/deliveries/analytics": { + "get": { + "description": "How the team's deliveries went over a period, against the period before: webhooks CoderHelm received (GitHub, Jira, alerts), events it relayed, and what it sent (webhook endpoints, Slack, Teams, email). Per hour for `24h`, per day otherwise: volume, success rate, latency percentiles, retries and how many of them went fine, failures by reason in plain words, the event types that failed most, and each webhook endpoint's success rate, latency, failure streak and whether it is turned off. Counts are kept 120 days; each delivery's own record 14.", + "operationId": "getDeliveryAnalytics", + "parameters": [ + { + "description": "`24h` (by hour), `7d` or `30d` (by day). Default `7d`. Each is\ncompared with the period before it, as long.", + "example": "7d", + "in": "query", + "name": "period", + "required": false, + "schema": { + "type": "string" + } + }, + { + "description": "Only one source: `github`, `relay`, `webhook`, `alerts`, `jira`,\n`slack`, `teams`, `email`, `broker`, `knowledge`.", + "example": "webhook", + "in": "query", + "name": "source", + "required": false, + "schema": { + "type": "string" + } + }, + { + "description": "`all` (default), `ok` (handled or ignored), `handled`, `ignored` or\n`failed`. Retrying deliveries count once they finish.", + "example": "failed", + "in": "query", + "name": "status", + "required": false, + "schema": { + "type": "string" + } + }, + { + "description": "Only one outbound webhook endpoint (its id).", + "example": "ep_01JBENDPT4K2M8N3P5Q7R9S1T3", + "in": "query", + "name": "endpoint", + "required": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeliveryAnalytics" + } + } + }, + "description": "The overview.", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + } + } + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "An unknown `period` or `status`." + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The key is missing, malformed, revoked or expired, or the person who made it left the team." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "The key lacks the scope this endpoint needs (`missing_scope`)." + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Over the key's rate limit (`rate_limited`), or, for endpoints that start work, over the team's monthly token limit (`token_limit_reached`).", + "headers": { + "RateLimit-Limit": { + "description": "Requests this key may make in a minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Remaining": { + "description": "Requests left in the current minute.", + "schema": { + "type": "integer" + } + }, + "RateLimit-Reset": { + "description": "Seconds until the current minute ends and the count starts over.", + "schema": { + "type": "integer" + } + }, + "Retry-After": { + "description": "With `rate_limited`: seconds to wait before trying again.", + "schema": { + "type": "integer" + } + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + }, + "description": "Something failed on CoderHelm's side. Safe to retry reads." + } + }, + "security": [ + { + "api_key": [ + "deliveries" + ] + } + ], + "summary": "Get delivery analytics", + "tags": [ + "Deliveries" + ] + } + }, "/api/me": { "get": { "description": "Returns who the request is authenticated as. With an API key this is the key itself: its name, who made it, when it expires, its rate limit, and in `capabilities` the scopes it holds right now (cut down to what its maker holds). Call it first to check a key works.", @@ -7406,6 +8414,11 @@ "name": "Usage", "x-displayName": "Usage" }, + { + "description": "How the webhooks CoderHelm receives and the messages it sends went over time: volume, success rate, latency, retries and failures by reason.", + "name": "Deliveries", + "x-displayName": "Deliveries" + }, { "description": "Endpoints a CI job calls with its GitHub Actions OIDC token, so no CoderHelm secret is stored in CI.", "name": "CI", diff --git a/docs/self-host/deliveries.md b/docs/self-host/deliveries.md index 0c7fb648a..82d869dad 100644 --- a/docs/self-host/deliveries.md +++ b/docs/self-host/deliveries.md @@ -28,6 +28,22 @@ Open a row for its details: Records are kept for 14 days, then deleted. +## Overview + +The **Overview** tab shows how deliveries went over the last 24 hours (by hour), 7 days or 30 days (by day), against the period before: + +- the success rate, the number of deliveries and failures, and how long the slowest 5% took; +- deliveries and the success rate over time; +- failures by reason, in plain words with the fix; +- each outbound webhook endpoint's success rate, latency, last failure, failures in a row and whether it is turned off; +- deliveries by source, and the event types that failed most. + +It has the same source and status filters as the list, plus the endpoint. Every bar, tile, reason, endpoint and source opens the list filtered to it. + +The overview reads counters that are updated as each delivery is recorded, one set per hour (kept 3 days) and per day (kept 120 days), so it stays fast however many deliveries there are, and it covers more than the 14 days records are kept. A delivery counts once it finishes (retries included), so one still retrying shows in the list but not yet in the overview. The first time it opens after an update, deliveries recorded before then are counted once, which can take a few reloads on a busy install. On a hybrid install, the relay's counters come from CoderHelm, like its records. + +The same numbers are in the API: `GET /api/deliveries/analytics` with an API key holding the `deliveries` scope. + ## Sharing with CoderHelm support Self-hosted and hybrid installs can choose to share delivery data with CoderHelm support, in the install guide or in **Settings, System, Hybrid**. It's **off** by default. diff --git a/services/common/src/deliveries.rs b/services/common/src/deliveries.rs index 6cfc8d61e..10e0bd51d 100644 --- a/services/common/src/deliveries.rs +++ b/services/common/src/deliveries.rs @@ -550,12 +550,19 @@ pub struct Filter { /// Only deliveries at or after this time (RFC 3339). #[serde(default)] pub since: Option, + /// Only deliveries before this time (RFC 3339): with `since`, one hour + /// or day of the overview. + #[serde(default)] + pub until: Option, /// A delivery id, GitHub delivery id, repository or PR number. #[serde(default)] pub q: Option, /// Only deliveries to this webhook endpoint. #[serde(default)] pub endpoint: Option, + /// Only failures with this reason code (a drill-in from the overview). + #[serde(default)] + pub reason: Option, } impl Filter { @@ -583,13 +590,23 @@ impl Filter { return false; } } + if let Some(r) = self.reason.as_deref().filter(|r| !r.is_empty()) { + if d.reason != r { + return false; + } + } if let Some(ep) = self.endpoint.as_deref().filter(|e| !e.is_empty()) { if d.endpoint_id != ep { return false; } } if let Some(since) = self.since.as_deref().filter(|s| !s.is_empty()) { - if d.created_at.as_str() < since { + if !before_or_at(since, &d.created_at) { + return false; + } + } + if let Some(until) = self.until.as_deref().filter(|s| !s.is_empty()) { + if before_or_at(until, &d.created_at) { return false; } } @@ -610,6 +627,18 @@ impl Filter { } } +/// `a` is at or before `b` (RFC 3339 times; compared as instants when both +/// parse, so `Z` and `.000Z` forms agree, as text otherwise). +fn before_or_at(a: &str, b: &str) -> bool { + match ( + chrono::DateTime::parse_from_rfc3339(a), + chrono::DateTime::parse_from_rfc3339(b), + ) { + (Ok(x), Ok(y)) => x <= y, + _ => a <= b, + } +} + /// The `ttl` for a record created now. pub fn ttl_from(now_epoch: i64) -> i64 { now_epoch + RETENTION_DAYS * 86_400 @@ -636,6 +665,11 @@ pub fn to_item( "ttl".into(), AttributeValue::N(ttl_from(now_epoch).to_string()), ); + // Counted by the rollups as it is written ([`record`]). + item.insert( + crate::deliveries_rollup::ROLLED.into(), + AttributeValue::N("1".into()), + ); item } @@ -645,21 +679,44 @@ pub fn from_item(item: &std::collections::HashMap) -> Op serde_json::from_str(data).ok() } -/// Writes (or replaces) one delivery record. Failures are logged and never -/// fail the delivery itself: the record is for people, the work matters more. +/// The record an item held before it was replaced, when the rollups had +/// counted it (it carries `rolled`). A record written before rollups existed +/// is counted by the backfill instead, so it is not taken away here. +pub fn counted_before( + old: Option<&std::collections::HashMap>, +) -> Option { + old.filter(|i| i.contains_key(crate::deliveries_rollup::ROLLED)) + .and_then(from_item) +} + +/// Writes (or replaces) one delivery record, and moves the rollups by the +/// difference from the record it replaced ([`crate::deliveries_rollup`]). +/// Failures are logged and never fail the delivery itself: the record is for +/// people, the work matters more. pub async fn record(dynamo: &aws_sdk_dynamodb::Client, table: &str, pk: &str, d: &Delivery) { if table.is_empty() || pk.is_empty() { return; } let now = chrono::Utc::now().timestamp(); - if let Err(e) = dynamo + match dynamo .put_item() .table_name(table) .set_item(Some(to_item(pk, d, now))) + .return_values(aws_sdk_dynamodb::types::ReturnValue::AllOld) .send() .await { - tracing::warn!(error = %e, delivery = %d.id, source = %d.source, "Could not record a delivery"); + Ok(r) => { + let old = counted_before(r.attributes()); + let store = crate::deliveries_rollup::Dynamo { + client: dynamo, + table, + }; + crate::deliveries_rollup::apply(&store, pk, old.as_ref(), d).await; + } + Err(e) => { + tracing::warn!(error = %e, delivery = %d.id, source = %d.source, "Could not record a delivery"); + } } } @@ -793,6 +850,15 @@ mod tests { ); assert_eq!(item["status"].as_s().unwrap(), "handled"); assert_eq!(from_item(&item).unwrap(), d); + assert!( + item.contains_key("rolled"), + "written records are counted by the rollups" + ); + assert_eq!(counted_before(Some(&item)), Some(d.clone())); + let mut before_rollups = item.clone(); + before_rollups.remove("rolled"); + assert_eq!(counted_before(Some(&before_rollups)), None); + assert_eq!(counted_before(None), None); } #[test] @@ -935,8 +1001,10 @@ mod tests { source: source.map(Into::into), status: status.map(Into::into), since: None, + until: None, q: q.map(Into::into), endpoint: None, + reason: None, }; assert!(f(Some("github"), Some("failed"), None).matches(&d)); assert!(!f(Some("relay"), None, None).matches(&d)); @@ -968,5 +1036,31 @@ mod tests { "webhook_server_error" ); assert_eq!(reason_for_http("webhook", None), "webhook_unreachable"); + // One hour of the overview: from (inclusive) to (exclusive), however + // the times are written. + let hour = |a: &str, b: &str| Filter { + since: Some(a.into()), + until: Some(b.into()), + ..Default::default() + }; + assert!(hour("2026-10-25T10:00:00Z", "2026-10-25T11:00:00Z").matches(&d)); + assert!(!hour("2026-10-25T09:00:00Z", "2026-10-25T10:00:00Z").matches(&d)); + let mut ms = d.clone(); + ms.created_at = "2026-10-25T10:59:59.999Z".into(); + assert!(hour("2026-10-25T10:00:00Z", "2026-10-25T11:00:00Z").matches(&ms)); + let mut ep = d.clone(); + ep.endpoint_id = "ep_1".into(); + let by_ep = Filter { + endpoint: Some("ep_1".into()), + ..Default::default() + }; + assert!(by_ep.matches(&ep) && !by_ep.matches(&d)); + let mut why = d.clone(); + why.reason = "handler_error".into(); + let by_reason = Filter { + reason: Some("handler_error".into()), + ..Default::default() + }; + assert!(by_reason.matches(&why) && !by_reason.matches(&d)); } } diff --git a/services/common/src/deliveries_rollup.rs b/services/common/src/deliveries_rollup.rs new file mode 100644 index 000000000..052caee15 --- /dev/null +++ b/services/common/src/deliveries_rollup.rs @@ -0,0 +1,1249 @@ +//! Delivery rollups: counters per hour and per day, written when a delivery +//! record is written, so the Deliveries overview reads a handful of items +//! instead of scanning records (which expire after 14 days anyway). +//! +//! Every write of a record ([`crate::deliveries::record`]) replaces the item +//! and gets the one it replaced back. The rollups then take the difference +//! between what the new record counts for and what the old one counted for +//! ([`changes`]). The differences telescope: however many times a record is +//! rewritten (retried, redelivered, resent), and in whatever order two writers +//! race, the rollups end up counting its last state once. +//! +//! A record counts only once it is finished (handled, ignored or failed). It +//! counts under two scopes: its source and direction (`s#github#in`), and, +//! for an outbound webhook, its endpoint (`ep#ep_123`). Under each scope: +//! handled, ignored and failed counts; retried records, extra attempts and +//! retried records that went fine; a latency histogram ([`LATENCY_BOUNDS_MS`], +//! kept apart for records that went fine and those that failed); +//! and, for failures, the reason code and the event type. +//! +//! Items on the settings table, beside the records: +//! - `DELIVERY_ROLLUP#D#`: a UTC day, kept [`DAY_RETENTION_DAYS`]. +//! - `DELIVERY_ROLLUP#H#`: a UTC hour, kept [`HOUR_RETENTION_HOURS`]. +//! - `DELIVERY_ENDPOINT#`: an endpoint's failure streak and its +//! last failure and success. +//! - `DELIVERY_ROLLUP#BACKFILL`: written once the records that were written +//! before rollups existed have been counted ([`backfill`]). +//! +//! A record counted by the rollups carries `rolled`. Records without it were +//! written before; [`backfill`] counts each of them once, in a transaction +//! that sets `rolled` only where it is still missing, so a record rewritten +//! meanwhile (the write path counts it) is never counted twice. + +use std::collections::{BTreeMap, HashMap}; + +use aws_sdk_dynamodb::types::{AttributeValue, TransactWriteItem, Update}; +use chrono::{DateTime, Duration, Utc}; + +use crate::deliveries::{Delivery, Direction, Status}; + +pub const DAY_PREFIX: &str = "DELIVERY_ROLLUP#D#"; +pub const HOUR_PREFIX: &str = "DELIVERY_ROLLUP#H#"; +pub const ENDPOINT_PREFIX: &str = "DELIVERY_ENDPOINT#"; +pub const BACKFILL_SK: &str = "DELIVERY_ROLLUP#BACKFILL"; +/// The attribute a counted record carries. +pub const ROLLED: &str = "rolled"; +/// Days a day rollup is kept: 90 days and a comparison period's worth more. +pub const DAY_RETENTION_DAYS: i64 = 120; +/// Hours an hour rollup is kept: the last 24 hours, the 24 before, and slack. +pub const HOUR_RETENTION_HOURS: i64 = 72; + +/// Upper bounds (inclusive) of the latency histogram's buckets, in +/// milliseconds. Anything slower falls in a last, open bucket (`inf`). +pub const LATENCY_BOUNDS_MS: &[u64] = &[ + 25, 50, 100, 200, 300, 500, 750, 1_000, 1_500, 2_000, 3_000, 5_000, 7_500, 10_000, 15_000, + 30_000, 60_000, +]; + +/// Counter name to amount. Names are DynamoDB attribute names. +pub type Counters = BTreeMap; + +/// A key part as it may appear in a counter name: lowercase letters, digits, +/// `.`, `_` and `-`, at most 64 characters (`#` separates parts). +pub fn part(raw: &str) -> String { + let p: String = raw + .trim() + .chars() + .take(64) + .map(|c| { + let c = c.to_ascii_lowercase(); + if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') { + c + } else { + '_' + } + }) + .collect(); + if p.is_empty() { + "none".into() + } else { + p + } +} + +/// The latency bucket's name: its upper bound, or `inf`. +pub fn latency_bucket(ms: u64) -> String { + LATENCY_BOUNDS_MS + .iter() + .find(|b| ms <= **b) + .map(|b| b.to_string()) + .unwrap_or_else(|| "inf".into()) +} + +/// How a finished record counts. +pub fn class(status: Status) -> Option<&'static str> { + match status { + Status::Handled => Some("handled"), + Status::Ignored => Some("ignored"), + Status::Failed => Some("failed"), + Status::Pending | Status::Received => None, + } +} + +fn dir(d: Direction) -> &'static str { + match d { + Direction::Inbound => "in", + Direction::Outbound => "out", + } +} + +/// The scope of a source and direction: `s##`. +pub fn source_scope(source: &str, direction: Direction) -> String { + format!("s#{}#{}", part(source), dir(direction)) +} + +/// The scope of a webhook endpoint: `ep#`. +pub fn endpoint_scope(endpoint_id: &str) -> String { + format!("ep#{}", part(endpoint_id)) +} + +/// What one record counts for (nothing until it is finished). +pub fn contribution(d: &Delivery) -> Counters { + let mut c = Counters::new(); + let Some(class) = class(d.status) else { + return c; + }; + let mut scopes = vec![source_scope(&d.source, d.direction)]; + if !d.endpoint_id.is_empty() { + scopes.push(endpoint_scope(&d.endpoint_id)); + } + let attempts = d.attempts.len().max(1) as i64; + for s in scopes { + c.insert(format!("{s}#{class}"), 1); + if attempts > 1 { + c.insert(format!("{s}#retried"), 1); + c.insert(format!("{s}#retries"), attempts - 1); + if d.status.is_ok() { + c.insert(format!("{s}#retried_ok"), 1); + } + } + if d.duration_ms > 0 { + let how = if d.status.is_ok() { "ok" } else { "failed" }; + c.insert( + format!("{s}#lat#{how}#{}", latency_bucket(d.duration_ms)), + 1, + ); + } + if d.status == Status::Failed { + let reason = if d.reason.is_empty() { + "unknown" + } else { + &d.reason + }; + c.insert(format!("{s}#r#{}", part(reason)), 1); + c.insert(format!("{s}#e#{}", part(&d.event)), 1); + } + } + c +} + +/// The UTC day and hour a record counts in (by when it was created, which +/// never changes when it is rewritten). +pub fn bucket_time(d: &Delivery) -> DateTime { + DateTime::parse_from_rfc3339(&d.created_at) + .map(|t| t.with_timezone(&Utc)) + .unwrap_or_else(|_| Utc::now()) +} + +pub fn day_key(t: DateTime) -> String { + t.format("%Y-%m-%d").to_string() +} + +pub fn hour_key(t: DateTime) -> String { + t.format("%Y-%m-%dT%H").to_string() +} + +/// One rollup item's change: its sort key, the counters to add, and the +/// item's expiry (epoch seconds). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Change { + pub sk: String, + pub add: Counters, + pub ttl: i64, +} + +/// The rollup items a record at `t` counts in that are still kept at `now`. +fn rollup_items(t: DateTime, now: DateTime) -> Vec<(String, i64)> { + let mut out = vec![]; + let day_end = t + .date_naive() + .and_hms_opt(0, 0, 0) + .map(|d| d.and_utc() + Duration::days(1)) + .unwrap_or(t); + let day_ttl = (day_end + Duration::days(DAY_RETENTION_DAYS)).timestamp(); + if day_ttl > now.timestamp() { + out.push((format!("{DAY_PREFIX}{}", day_key(t)), day_ttl)); + } + let hour_ttl = (t + Duration::hours(HOUR_RETENTION_HOURS + 1)).timestamp(); + if hour_ttl > now.timestamp() { + out.push((format!("{HOUR_PREFIX}{}", hour_key(t)), hour_ttl)); + } + out +} + +fn merge_into(into: &mut Counters, from: &Counters, sign: i64) { + for (k, v) in from { + *into.entry(k.clone()).or_insert(0) += sign * v; + } +} + +/// What the rollups must add when `old` (the record as last counted, or +/// None) becomes `new`: the new record's counters in its buckets less the +/// old one's in its own. Unchanged counters and empty items are left out. +pub fn changes(old: Option<&Delivery>, new: &Delivery, now: DateTime) -> Vec { + let mut by_sk: BTreeMap = BTreeMap::new(); + let mut put = |d: &Delivery, sign: i64| { + let c = contribution(d); + if c.is_empty() { + return; + } + for (sk, ttl) in rollup_items(bucket_time(d), now) { + let e = by_sk.entry(sk).or_insert_with(|| (Counters::new(), ttl)); + e.1 = e.1.max(ttl); + merge_into(&mut e.0, &c, sign); + } + }; + if let Some(o) = old { + put(o, -1); + } + put(new, 1); + by_sk + .into_iter() + .filter_map(|(sk, (mut add, ttl))| { + add.retain(|_, v| *v != 0); + (!add.is_empty()).then_some(Change { sk, add, ttl }) + }) + .collect() +} + +/// What a record's write means for its endpoint's streak. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum EndpointChange { + /// One more failure in a row. + Failed { + at: String, + reason: String, + event: String, + }, + /// A success: the streak is over. + Succeeded { at: String }, +} + +/// The endpoint streak change when `old` becomes `new`, if any: only a record +/// that just finished (or just changed between failed and fine) counts. +pub fn endpoint_change( + old: Option<&Delivery>, + new: &Delivery, + now: DateTime, +) -> Option<(String, EndpointChange)> { + if new.endpoint_id.is_empty() { + return None; + } + let at = now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true); + let was = old.and_then(|o| class(o.status).map(|_| o.status.is_ok())); + let change = match new.status { + Status::Failed if was != Some(false) => EndpointChange::Failed { + at, + reason: new.reason.clone(), + event: new.event.clone(), + }, + s if s.is_ok() && was != Some(true) => EndpointChange::Succeeded { at }, + _ => return None, + }; + Some((new.endpoint_id.clone(), change)) +} + +/// An endpoint's streak item, as read back. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct EndpointStat { + pub endpoint_id: String, + /// Failures in a row since the last success. + pub streak: i64, + pub last_failure_at: Option, + pub last_failure_reason: Option, + pub last_failure_event: Option, + pub last_success_at: Option, +} + +/// An item to mark counted in a backfill: its table and key. +#[derive(Debug, Clone, PartialEq)] +pub struct MarkKey { + pub table: String, + pub key: HashMap, +} + +/// A record written before rollups existed, as found by a backfill. +#[derive(Debug, Clone)] +pub struct Unrolled { + pub mark: MarkKey, + pub delivery: Delivery, +} + +/// Why a backfill transaction didn't go through. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum MarkError { + /// These marks (indexes into the batch) were already counted: the + /// record was rewritten (and counted) after it was read. + AlreadyCounted(Vec), + Other(String), +} + +/// Where rollups are kept. DynamoDB in production ([`Dynamo`]); a map in tests. +#[async_trait::async_trait] +pub trait Store: Send + Sync { + /// Adds counters to one rollup item (creating it with `ttl`). + async fn add(&self, pk: &str, change: &Change) -> Result<(), String>; + /// Applies an endpoint streak change. + async fn endpoint(&self, pk: &str, endpoint_id: &str, c: &EndpointChange) + -> Result<(), String>; + /// Rollup items with sort keys from `from` to `to` (inclusive). + async fn read(&self, pk: &str, from: &str, to: &str) + -> Result, String>; + /// Every endpoint streak item of `pk`. + async fn endpoints(&self, pk: &str) -> Result, String>; + /// In one transaction: marks each item counted (only where it isn't yet) + /// and adds the counters. + async fn mark_and_add( + &self, + pk: &str, + marks: &[MarkKey], + adds: &[Change], + ) -> Result<(), MarkError>; + /// Whether `pk`'s backfill finished. + async fn backfilled(&self, pk: &str) -> Result; + async fn set_backfilled(&self, pk: &str, at: &str) -> Result<(), String>; +} + +/// Updates the rollups for one record write. Failures are logged: a record +/// is never refused because its counters couldn't be written. +pub async fn apply(store: &dyn Store, pk: &str, old: Option<&Delivery>, new: &Delivery) { + let now = Utc::now(); + apply_at(store, pk, old, new, now).await +} + +pub async fn apply_at( + store: &dyn Store, + pk: &str, + old: Option<&Delivery>, + new: &Delivery, + now: DateTime, +) { + for c in changes(old, new, now) { + let mut tries = 0; + loop { + tries += 1; + match store.add(pk, &c).await { + Ok(()) => break, + Err(e) if tries < 3 => { + tracing::debug!(error = %e, sk = %c.sk, "Retrying a delivery rollup write"); + tokio::time::sleep(std::time::Duration::from_millis(50 * tries)).await; + } + Err(e) => { + tracing::warn!(error = %e, sk = %c.sk, delivery = %new.id, "Could not update a delivery rollup"); + break; + } + } + } + } + if let Some((ep, change)) = endpoint_change(old, new, now) { + if let Err(e) = store.endpoint(pk, &ep, &change).await { + tracing::warn!(error = %e, endpoint = %ep, "Could not update an endpoint's delivery streak"); + } + } +} + +/// How a backfill went. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BackfillReport { + /// Records counted now. + pub counted: usize, + /// Records already counted by a write meanwhile. + pub skipped: usize, + /// Records left for the next backfill (a write failed). + pub left: usize, +} + +/// Records per backfill transaction: each record and each distinct rollup +/// item is one action, and a transaction takes at most 100. +pub const BACKFILL_BATCH: usize = 30; + +/// Counts records written before rollups existed, each exactly once. +/// Stops starting batches at `deadline`; the rest are `left` for next time. +pub async fn backfill( + store: &dyn Store, + pk: &str, + items: Vec, + now: DateTime, + deadline: std::time::Instant, +) -> BackfillReport { + let mut report = BackfillReport::default(); + let mut rest = items.as_slice(); + while !rest.is_empty() { + let take = rest.len().min(BACKFILL_BATCH); + let (batch, tail) = rest.split_at(take); + rest = tail; + if std::time::Instant::now() >= deadline { + report.left += batch.len(); + continue; + } + let mut live: Vec<&Unrolled> = batch.iter().collect(); + let mut tries = 0; + loop { + tries += 1; + if live.is_empty() { + break; + } + let mut adds: BTreeMap = BTreeMap::new(); + for u in &live { + for c in changes(None, &u.delivery, now) { + let e = adds.entry(c.sk.clone()).or_insert_with(|| Change { + sk: c.sk.clone(), + add: Counters::new(), + ttl: c.ttl, + }); + merge_into(&mut e.add, &c.add, 1); + } + } + let marks: Vec = live.iter().map(|u| u.mark.clone()).collect(); + let adds: Vec = adds.into_values().collect(); + match store.mark_and_add(pk, &marks, &adds).await { + Ok(()) => { + report.counted += live.len(); + break; + } + Err(MarkError::AlreadyCounted(idx)) if tries < 5 && !idx.is_empty() => { + report.skipped += idx.len(); + live = live + .into_iter() + .enumerate() + .filter(|(i, _)| !idx.contains(i)) + .map(|(_, u)| u) + .collect(); + } + Err(e) => { + tracing::warn!(error = ?e, pk, "A delivery rollup backfill batch failed; it is retried next time"); + report.left += live.len(); + break; + } + } + } + } + report +} + +// ── Reading ──────────────────────────────────────────────────────────── + +/// A value at quantile `q` (0..=1) of a latency histogram (bucket name to +/// count), in milliseconds, interpolated inside its bucket. None when empty. +/// A value in the open last bucket reads as its lower bound. +pub fn percentile(hist: &BTreeMap, q: f64) -> Option { + let counts: Vec<(u64, u64, i64)> = { + let mut lo = 0u64; + let mut v = vec![]; + for b in LATENCY_BOUNDS_MS { + v.push(( + lo, + *b, + hist.get(&b.to_string()).copied().unwrap_or(0).max(0), + )); + lo = *b; + } + v.push((lo, lo, hist.get("inf").copied().unwrap_or(0).max(0))); + v + }; + let n: i64 = counts.iter().map(|c| c.2).sum(); + if n <= 0 { + return None; + } + let rank = (q.clamp(0.0, 1.0) * n as f64).max(1.0); + let mut cum = 0f64; + for (lo, hi, c) in counts { + if c == 0 { + continue; + } + let next = cum + c as f64; + if next >= rank { + let within = (rank - cum) / c as f64; + return Some((lo as f64 + (hi - lo) as f64 * within).round() as u64); + } + cum = next; + } + None +} + +// ── DynamoDB ─────────────────────────────────────────────────────────── + +/// Rollups on the settings table. +pub struct Dynamo<'a> { + pub client: &'a aws_sdk_dynamodb::Client, + pub table: &'a str, +} + +fn s(v: &str) -> AttributeValue { + AttributeValue::S(v.to_string()) +} + +fn n(v: i64) -> AttributeValue { + AttributeValue::N(v.to_string()) +} + +/// The update for one rollup change: `ADD` every counter, keep the first +/// expiry. Pure, so the exact expression is tested. +pub fn add_expression( + c: &Change, +) -> ( + String, + HashMap, + HashMap, +) { + let mut names = HashMap::from([("#ttl".to_string(), "ttl".to_string())]); + let mut values = HashMap::from([(":ttl".to_string(), n(c.ttl))]); + let mut parts = vec![]; + for (i, (k, v)) in c.add.iter().enumerate() { + names.insert(format!("#a{i}"), k.clone()); + values.insert(format!(":v{i}"), n(*v)); + parts.push(format!("#a{i} :v{i}")); + } + ( + format!( + "SET #ttl = if_not_exists(#ttl, :ttl) ADD {}", + parts.join(", ") + ), + names, + values, + ) +} + +/// Counters from a rollup item (every numeric attribute but the expiry). +pub fn counters_of(item: &HashMap) -> Counters { + item.iter() + .filter(|(k, _)| k.as_str() != "ttl") + .filter_map(|(k, v)| { + let n = v.as_n().ok()?.parse::().ok()?; + Some((k.clone(), n)) + }) + .collect() +} + +fn endpoint_stat(item: &HashMap) -> Option { + let g = |k: &str| item.get(k).and_then(|v| v.as_s().ok()).cloned(); + let id = g("sk")?.strip_prefix(ENDPOINT_PREFIX)?.to_string(); + Some(EndpointStat { + endpoint_id: id, + streak: item + .get("streak") + .and_then(|v| v.as_n().ok()) + .and_then(|v| v.parse().ok()) + .unwrap_or(0), + last_failure_at: g("last_failure_at"), + last_failure_reason: g("last_failure_reason"), + last_failure_event: g("last_failure_event"), + last_success_at: g("last_success_at"), + }) +} + +/// The indexes a cancelled transaction's reasons name as failed conditions. +pub fn failed_conditions<'a>(codes: impl IntoIterator>) -> Vec { + codes + .into_iter() + .enumerate() + .filter(|(_, c)| *c == Some("ConditionalCheckFailed")) + .map(|(i, _)| i) + .collect() +} + +#[async_trait::async_trait] +impl Store for Dynamo<'_> { + async fn add(&self, pk: &str, c: &Change) -> Result<(), String> { + let (expr, names, values) = add_expression(c); + self.client + .update_item() + .table_name(self.table) + .key("pk", s(pk)) + .key("sk", s(&c.sk)) + .update_expression(expr) + .set_expression_attribute_names(Some(names)) + .set_expression_attribute_values(Some(values)) + .send() + .await + .map(|_| ()) + .map_err(|e| format!("{e:?}").chars().take(300).collect()) + } + + async fn endpoint( + &self, + pk: &str, + endpoint_id: &str, + c: &EndpointChange, + ) -> Result<(), String> { + let ttl = (Utc::now() + Duration::days(DAY_RETENTION_DAYS)).timestamp(); + let req = self + .client + .update_item() + .table_name(self.table) + .key("pk", s(pk)) + .key("sk", s(&format!("{ENDPOINT_PREFIX}{endpoint_id}"))) + .expression_attribute_names("#ttl", "ttl") + .expression_attribute_values(":ttl", n(ttl)); + let req = match c { + EndpointChange::Failed { at, reason, event } => req + .update_expression( + "ADD streak :one SET last_failure_at = :at, last_failure_reason = :r, \ + last_failure_event = :e, #ttl = :ttl", + ) + .expression_attribute_values(":one", n(1)) + .expression_attribute_values(":at", s(at)) + .expression_attribute_values(":r", s(reason)) + .expression_attribute_values(":e", s(event)), + EndpointChange::Succeeded { at } => req + .update_expression("SET streak = :zero, last_success_at = :at, #ttl = :ttl") + .expression_attribute_values(":zero", n(0)) + .expression_attribute_values(":at", s(at)), + }; + req.send() + .await + .map(|_| ()) + .map_err(|e| format!("{e:?}").chars().take(300).collect()) + } + + async fn read( + &self, + pk: &str, + from: &str, + to: &str, + ) -> Result, String> { + let mut out = vec![]; + let mut start = None; + loop { + let r = self + .client + .query() + .table_name(self.table) + .key_condition_expression("pk = :pk AND sk BETWEEN :a AND :b") + .expression_attribute_values(":pk", s(pk)) + .expression_attribute_values(":a", s(from)) + .expression_attribute_values(":b", s(to)) + .set_exclusive_start_key(start) + .send() + .await + .map_err(|e| format!("{e:?}").chars().take(300).collect::())?; + for item in r.items() { + if let Some(sk) = item.get("sk").and_then(|v| v.as_s().ok()) { + out.push((sk.clone(), counters_of(item))); + } + } + start = r.last_evaluated_key().cloned(); + if start.is_none() { + break; + } + } + Ok(out) + } + + async fn endpoints(&self, pk: &str) -> Result, String> { + let r = self + .client + .query() + .table_name(self.table) + .key_condition_expression("pk = :pk AND begins_with(sk, :p)") + .expression_attribute_values(":pk", s(pk)) + .expression_attribute_values(":p", s(ENDPOINT_PREFIX)) + .send() + .await + .map_err(|e| format!("{e:?}").chars().take(300).collect::())?; + Ok(r.items().iter().filter_map(endpoint_stat).collect()) + } + + async fn mark_and_add( + &self, + pk: &str, + marks: &[MarkKey], + adds: &[Change], + ) -> Result<(), MarkError> { + use aws_sdk_dynamodb::operation::transact_write_items::TransactWriteItemsError; + let mut items = vec![]; + for m in marks { + let u = Update::builder() + .table_name(&m.table) + .set_key(Some(m.key.clone())) + .update_expression("SET #rolled = :one") + .condition_expression("attribute_not_exists(#rolled)") + .expression_attribute_names("#rolled", ROLLED) + .expression_attribute_values(":one", n(1)) + .build() + .map_err(|e| MarkError::Other(e.to_string()))?; + items.push(TransactWriteItem::builder().update(u).build()); + } + for c in adds { + let (expr, names, values) = add_expression(c); + let u = Update::builder() + .table_name(self.table) + .key("pk", s(pk)) + .key("sk", s(&c.sk)) + .update_expression(expr) + .set_expression_attribute_names(Some(names)) + .set_expression_attribute_values(Some(values)) + .build() + .map_err(|e| MarkError::Other(e.to_string()))?; + items.push(TransactWriteItem::builder().update(u).build()); + } + match self + .client + .transact_write_items() + .set_transact_items(Some(items)) + .send() + .await + { + Ok(_) => Ok(()), + Err(e) => { + if let Some(TransactWriteItemsError::TransactionCanceledException(c)) = + e.as_service_error() + { + let idx = failed_conditions( + c.cancellation_reasons() + .iter() + .take(marks.len()) + .map(|r| r.code()), + ); + if !idx.is_empty() { + return Err(MarkError::AlreadyCounted(idx)); + } + } + Err(MarkError::Other( + format!("{e:?}").chars().take(300).collect(), + )) + } + } + } + + async fn backfilled(&self, pk: &str) -> Result { + let r = self + .client + .get_item() + .table_name(self.table) + .key("pk", s(pk)) + .key("sk", s(BACKFILL_SK)) + .send() + .await + .map_err(|e| format!("{e:?}").chars().take(300).collect::())?; + Ok(r.item().is_some()) + } + + async fn set_backfilled(&self, pk: &str, at: &str) -> Result<(), String> { + self.client + .put_item() + .table_name(self.table) + .item("pk", s(pk)) + .item("sk", s(BACKFILL_SK)) + .item("done_at", s(at)) + .send() + .await + .map(|_| ()) + .map_err(|e| format!("{e:?}").chars().take(300).collect()) + } +} + +// ── A store in memory, for tests here and in the gateway ─────────────── + +/// Rollups in memory, with the same semantics as [`Dynamo`]: counters add, +/// marks are conditional and a transaction is all or nothing. +#[derive(Default)] +pub struct Memory { + pub items: std::sync::Mutex>, + pub endpoints: std::sync::Mutex>, + /// Marked records, by table and a printed key. + pub marked: std::sync::Mutex>, + pub done: std::sync::Mutex>, + /// Makes every `add` fail (to test that a record is never refused). + pub fail_adds: std::sync::atomic::AtomicBool, +} + +impl Memory { + /// The printed key a mark is kept under. + pub fn mark_id(m: &MarkKey) -> String { + let mut k: Vec = m + .key + .iter() + .map(|(k, v)| format!("{k}={}", v.as_s().map(String::as_str).unwrap_or(""))) + .collect(); + k.sort(); + format!("{}|{}", m.table, k.join(",")) + } + + pub fn get(&self, pk: &str, sk: &str) -> Counters { + self.items + .lock() + .unwrap() + .get(&(pk.to_string(), sk.to_string())) + .cloned() + .unwrap_or_default() + } +} + +#[async_trait::async_trait] +impl Store for Memory { + async fn add(&self, pk: &str, c: &Change) -> Result<(), String> { + if self.fail_adds.load(std::sync::atomic::Ordering::SeqCst) { + return Err("unavailable".into()); + } + let mut items = self.items.lock().unwrap(); + let e = items.entry((pk.to_string(), c.sk.clone())).or_default(); + merge_into(e, &c.add, 1); + Ok(()) + } + + async fn endpoint( + &self, + pk: &str, + endpoint_id: &str, + c: &EndpointChange, + ) -> Result<(), String> { + let mut eps = self.endpoints.lock().unwrap(); + let e = eps + .entry((pk.to_string(), endpoint_id.to_string())) + .or_insert_with(|| EndpointStat { + endpoint_id: endpoint_id.to_string(), + ..Default::default() + }); + match c { + EndpointChange::Failed { at, reason, event } => { + e.streak += 1; + e.last_failure_at = Some(at.clone()); + e.last_failure_reason = Some(reason.clone()); + e.last_failure_event = Some(event.clone()); + } + EndpointChange::Succeeded { at } => { + e.streak = 0; + e.last_success_at = Some(at.clone()); + } + } + Ok(()) + } + + async fn read( + &self, + pk: &str, + from: &str, + to: &str, + ) -> Result, String> { + Ok(self + .items + .lock() + .unwrap() + .iter() + .filter(|((p, sk), _)| p == pk && sk.as_str() >= from && sk.as_str() <= to) + .map(|((_, sk), c)| (sk.clone(), c.clone())) + .collect()) + } + + async fn endpoints(&self, pk: &str) -> Result, String> { + Ok(self + .endpoints + .lock() + .unwrap() + .iter() + .filter(|((p, _), _)| p == pk) + .map(|(_, e)| e.clone()) + .collect()) + } + + async fn mark_and_add( + &self, + pk: &str, + marks: &[MarkKey], + adds: &[Change], + ) -> Result<(), MarkError> { + let mut marked = self.marked.lock().unwrap(); + let taken = failed_conditions(marks.iter().map(|m| { + marked + .contains(&Self::mark_id(m)) + .then_some("ConditionalCheckFailed") + })); + if !taken.is_empty() { + return Err(MarkError::AlreadyCounted(taken)); + } + for m in marks { + marked.insert(Self::mark_id(m)); + } + let mut items = self.items.lock().unwrap(); + for c in adds { + let e = items.entry((pk.to_string(), c.sk.clone())).or_default(); + merge_into(e, &c.add, 1); + } + Ok(()) + } + + async fn backfilled(&self, pk: &str) -> Result { + Ok(self.done.lock().unwrap().contains(pk)) + } + + async fn set_backfilled(&self, pk: &str, _at: &str) -> Result<(), String> { + self.done.lock().unwrap().insert(pk.to_string()); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::deliveries::Attempt; + + fn at(t: &str, source: &str, status: Status) -> Delivery { + let mut d = Delivery::new(Direction::Outbound, source, "run.failed", "x"); + d.created_at = t.into(); + d.status = status; + d + } + + fn attempt(ms: u64) -> Attempt { + Attempt { + at: "t".into(), + code: Some(500), + duration_ms: ms, + error: String::new(), + } + } + + fn now() -> DateTime { + DateTime::parse_from_rfc3339("2026-10-26T15:30:00Z") + .unwrap() + .with_timezone(&Utc) + } + + #[test] + fn parts_are_safe_attribute_names() { + assert_eq!(part("pull_request.opened"), "pull_request.opened"); + assert_eq!(part("shared:GitHub"), "shared_github"); + assert_eq!(part("a#b c"), "a_b_c"); + assert_eq!(part(""), "none"); + assert_eq!(part(&"x".repeat(200)).len(), 64); + assert_eq!(latency_bucket(0), "25"); + assert_eq!(latency_bucket(25), "25"); + assert_eq!(latency_bucket(26), "50"); + assert_eq!(latency_bucket(60_000), "60000"); + assert_eq!(latency_bucket(60_001), "inf"); + } + + #[test] + fn a_record_counts_once_it_is_finished() { + let mut d = at("2026-10-26T15:10:00Z", "webhook", Status::Pending); + d.endpoint_id = "ep_1".into(); + assert!( + contribution(&d).is_empty(), + "a retrying record counts for nothing yet" + ); + d.push_attempt(attempt(120)); + d.push_attempt(attempt(80)); + d.status = Status::Handled; + let c = contribution(&d); + assert_eq!(c["s#webhook#out#handled"], 1); + assert_eq!(c["s#webhook#out#retried"], 1); + assert_eq!(c["s#webhook#out#retries"], 1); + assert_eq!(c["s#webhook#out#retried_ok"], 1); + assert_eq!(c["s#webhook#out#lat#ok#100"], 1); + assert_eq!(c["ep#ep_1#handled"], 1); + assert_eq!(c["ep#ep_1#retried_ok"], 1); + assert!( + !c.keys().any(|k| k.contains("#r#")), + "no reason when it went fine" + ); + d.status = Status::Failed; + d.reason = "webhook_server_error".into(); + let c = contribution(&d); + assert_eq!(c["s#webhook#out#failed"], 1); + assert_eq!(c["s#webhook#out#r#webhook_server_error"], 1); + assert_eq!(c["s#webhook#out#e#run.failed"], 1); + assert!(!c.contains_key("s#webhook#out#retried_ok")); + let mut g = at("2026-10-26T15:10:00Z", "github", Status::Failed); + g.direction = Direction::Inbound; + assert_eq!(contribution(&g)["s#github#in#r#unknown"], 1); + } + + #[test] + fn rewrites_telescope_to_the_last_state() { + let m = Memory::default(); + let rt = tokio::runtime::Builder::new_current_thread() + .build() + .unwrap(); + rt.block_on(async { + let mut d = at("2026-10-26T15:10:00Z", "relay", Status::Pending); + apply_at(&m, "TEAM#1", None, &d, now()).await; + assert!(m.get("TEAM#1", "DELIVERY_ROLLUP#D#2026-10-26").is_empty()); + let first = d.clone(); + d.push_attempt(attempt(3000)); + d.status = Status::Failed; + d.reason = "relay_unreachable".into(); + apply_at(&m, "TEAM#1", Some(&first), &d, now()).await; + let failed = d.clone(); + d.push_attempt(attempt(200)); + d.status = Status::Handled; + d.reason.clear(); + apply_at(&m, "TEAM#1", Some(&failed), &d, now()).await; + // A second write of the same state changes nothing. + apply_at(&m, "TEAM#1", Some(&d), &d, now()).await; + for sk in [ + "DELIVERY_ROLLUP#D#2026-10-26", + "DELIVERY_ROLLUP#H#2026-10-26T15", + ] { + let c = m.get("TEAM#1", sk); + let live: Counters = c.into_iter().filter(|(_, v)| *v != 0).collect(); + assert_eq!( + live, + Counters::from([ + ("s#relay#out#handled".into(), 1), + ("s#relay#out#retried".into(), 1), + ("s#relay#out#retries".into(), 1), + ("s#relay#out#retried_ok".into(), 1), + ("s#relay#out#lat#ok#200".into(), 1), + ]), + "{sk}" + ); + } + }); + } + + #[test] + fn old_records_change_only_the_buckets_still_kept() { + let d = at("2026-10-20T10:00:00Z", "email", Status::Failed); + let ch = changes(None, &d, now()); + assert_eq!( + ch.len(), + 1, + "the hour is gone after 72 hours; the day stays" + ); + assert_eq!(ch[0].sk, "DELIVERY_ROLLUP#D#2026-10-20"); + let day_end = DateTime::parse_from_rfc3339("2026-10-21T00:00:00Z").unwrap(); + assert_eq!(ch[0].ttl, (day_end + Duration::days(120)).timestamp()); + let ancient = at("2026-01-01T10:00:00Z", "email", Status::Failed); + assert!(changes(None, &ancient, now()).is_empty()); + } + + #[test] + fn endpoint_streaks_follow_finished_records() { + let mut d = at("2026-10-26T15:10:00Z", "webhook", Status::Pending); + assert_eq!(endpoint_change(None, &d, now()), None, "no endpoint"); + d.endpoint_id = "ep_1".into(); + assert_eq!(endpoint_change(None, &d, now()), None, "still retrying"); + let pending = d.clone(); + d.status = Status::Failed; + d.reason = "webhook_gave_up".into(); + assert!(matches!( + endpoint_change(Some(&pending), &d, now()), + Some((_, EndpointChange::Failed { .. })) + )); + assert_eq!( + endpoint_change(Some(&d), &d, now()), + None, + "the same failure twice" + ); + let failed = d.clone(); + d.status = Status::Handled; + assert!(matches!( + endpoint_change(Some(&failed), &d, now()), + Some((_, EndpointChange::Succeeded { .. })) + )); + } + + #[test] + fn percentiles_interpolate_inside_buckets() { + let h = |pairs: &[(&str, i64)]| -> BTreeMap { + pairs.iter().map(|(k, v)| (k.to_string(), *v)).collect() + }; + assert_eq!(percentile(&h(&[]), 0.5), None); + // 100 values in (100, 200]: the median is halfway. + assert_eq!(percentile(&h(&[("200", 100)]), 0.5), Some(150)); + // 90 fast, 10 slow: p50 is fast, p95 sits in the slow bucket. + let mixed = h(&[("50", 90), ("1000", 10)]); + assert_eq!(percentile(&mixed, 0.5), Some(39), "25 + 25 x 50/90"); + assert_eq!(percentile(&mixed, 0.95), Some(750 + 250 / 2)); + assert_eq!(percentile(&mixed, 0.99), Some(750 + 250 * 9 / 10)); + // The open bucket reads as its lower bound. + assert_eq!(percentile(&h(&[("inf", 3)]), 0.99), Some(60_000)); + // A single value is its bucket's top. + assert_eq!(percentile(&h(&[("25", 1)]), 0.5), Some(25)); + } + + #[test] + fn the_rollup_update_adds_and_keeps_the_first_expiry() { + let c = Change { + sk: "DELIVERY_ROLLUP#D#2026-10-26".into(), + add: Counters::from([ + ("s#github#in#handled".into(), 1), + ("s#github#in#failed".into(), -1), + ]), + ttl: 99, + }; + let (expr, names, values) = add_expression(&c); + assert_eq!( + expr, + "SET #ttl = if_not_exists(#ttl, :ttl) ADD #a0 :v0, #a1 :v1" + ); + assert_eq!(names["#a0"], "s#github#in#failed"); + assert_eq!(values[":v0"], AttributeValue::N("-1".into())); + assert_eq!(values[":ttl"], AttributeValue::N("99".into())); + let mut item = HashMap::from([ + ("pk".to_string(), s("TEAM#1")), + ("sk".to_string(), s("DELIVERY_ROLLUP#D#2026-10-26")), + ("ttl".to_string(), n(5)), + ("s#github#in#handled".to_string(), n(4)), + ]); + assert_eq!( + counters_of(&item), + Counters::from([("s#github#in#handled".into(), 4)]) + ); + item.insert("sk".into(), s("DELIVERY_ENDPOINT#ep_9")); + item.insert("streak".into(), n(3)); + assert_eq!(endpoint_stat(&item).unwrap().streak, 3); + assert_eq!( + failed_conditions([None, Some("ConditionalCheckFailed"), Some("None")]), + vec![1] + ); + } + + fn unrolled(id: &str, d: Delivery) -> Unrolled { + Unrolled { + mark: MarkKey { + table: "settings".into(), + key: HashMap::from([ + ("pk".to_string(), s("TEAM#1")), + ("sk".to_string(), s(&format!("DELIVERY#{id}"))), + ]), + }, + delivery: d, + } + } + + #[test] + fn a_backfill_counts_each_old_record_once() { + let m = Memory::default(); + let rt = tokio::runtime::Builder::new_current_thread() + .build() + .unwrap(); + rt.block_on(async { + let far = std::time::Instant::now() + std::time::Duration::from_secs(60); + let mut items = vec![]; + for i in 0..70 { + let st = if i % 7 == 0 { + Status::Failed + } else { + Status::Handled + }; + items.push(unrolled( + &i.to_string(), + at("2026-10-25T09:00:00Z", "github", st), + )); + } + items.push(unrolled( + "pending", + at("2026-10-25T09:00:00Z", "relay", Status::Pending), + )); + // One record was rewritten (and counted by the write path) after the backfill read it. + m.marked + .lock() + .unwrap() + .insert(Memory::mark_id(&items[3].mark)); + let r = backfill(&m, "TEAM#1", items.clone(), now(), far).await; + assert_eq!( + r, + BackfillReport { + counted: 70, + skipped: 1, + left: 0 + } + ); + let day = m.get("TEAM#1", "DELIVERY_ROLLUP#D#2026-10-25"); + assert_eq!(day["s#github#out#failed"], 10); + assert_eq!( + day["s#github#out#handled"], 59, + "the record counted elsewhere is left out" + ); + // Running it again counts nothing more. + let again = backfill(&m, "TEAM#1", items, now(), far).await; + assert_eq!(again.counted, 0); + assert_eq!( + m.get("TEAM#1", "DELIVERY_ROLLUP#D#2026-10-25")["s#github#out#failed"], + 10 + ); + // Past the deadline nothing starts: it is all left for next time. + let late = backfill( + &m, + "TEAM#1", + vec![unrolled( + "z", + at("2026-10-25T09:00:00Z", "github", Status::Handled), + )], + now(), + std::time::Instant::now(), + ) + .await; + assert_eq!( + late, + BackfillReport { + counted: 0, + skipped: 0, + left: 1 + } + ); + }); + } + + #[test] + fn teams_never_see_each_others_counters() { + let m = Memory::default(); + let rt = tokio::runtime::Builder::new_current_thread() + .build() + .unwrap(); + rt.block_on(async { + let mut d = at("2026-10-26T15:10:00Z", "webhook", Status::Failed); + d.endpoint_id = "ep_1".into(); + apply_at(&m, "TEAM#a", None, &d, now()).await; + let b = m + .read("TEAM#b", DAY_PREFIX, &format!("{DAY_PREFIX}~")) + .await + .unwrap(); + assert!(b.is_empty()); + assert!(m.endpoints("TEAM#b").await.unwrap().is_empty()); + assert_eq!(m.endpoints("TEAM#a").await.unwrap()[0].streak, 1); + let a = m + .read("TEAM#a", DAY_PREFIX, &format!("{DAY_PREFIX}~")) + .await + .unwrap(); + assert_eq!(a.len(), 1); + }); + } + + #[test] + fn a_failed_counter_write_never_fails_the_record() { + let m = Memory::default(); + m.fail_adds.store(true, std::sync::atomic::Ordering::SeqCst); + let rt = tokio::runtime::Builder::new_current_thread() + .enable_time() + .build() + .unwrap(); + rt.block_on(async { + let d = at("2026-10-26T15:10:00Z", "email", Status::Handled); + apply_at(&m, "TEAM#1", None, &d, now()).await; + }); + assert!(m.get("TEAM#1", "DELIVERY_ROLLUP#D#2026-10-26").is_empty()); + } +} diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index e6ec02eae..b4c8884cc 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -17,6 +17,7 @@ pub mod code_graph; /// Every delivery in and out (webhooks, relay forwards, notifications, /// email), with what happened, for the Deliveries page. pub mod deliveries; +pub mod deliveries_rollup; /// The shared dead-letter queue: whose each failed message is, whether the /// worker can read it, and when the cleanup archives it. pub mod dlq; diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index b8c3d1491..5c7b15d93 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -236,6 +236,10 @@ async fn main() -> Result<(), Error> { ) // Deliveries: every event in and out, with what happened (admins). .route("/deliveries", get(routes::deliveries::list)) + .route( + "/deliveries/analytics", + get(routes::deliveries_analytics::analytics), + ) .route("/deliveries/:id", get(routes::deliveries::get)) .route( "/deliveries/:id/redeliver", @@ -1224,6 +1228,7 @@ async fn main() -> Result<(), Error> { .route("/github/token", post(routes::hybrid::github_token)) .route("/deliveries", get(routes::hybrid::list_deliveries)) .route("/deliveries/shared", post(routes::hybrid::share)) + .route("/deliveries/rollups", post(routes::hybrid::rollups)) .route("/deliveries/:id/redeliver", post(routes::hybrid::redeliver)) .route( "/oauth/:kind/authorize", diff --git a/services/gateway/src/openapi.rs b/services/gateway/src/openapi.rs index e7fb252fb..250265bc7 100644 --- a/services/gateway/src/openapi.rs +++ b/services/gateway/src/openapi.rs @@ -145,6 +145,11 @@ pub const PUBLIC_ROUTES: &[PublicRoute] = &[ "/api/webhooks/endpoints/:endpoint_id/replay", "webhooks::replay", ), + key( + "GET", + "/api/deliveries/analytics", + "deliveries_analytics::analytics", + ), PublicRoute { method: "POST", path: "/webhooks/ci/tests/results", @@ -250,7 +255,7 @@ pub fn default_code(status: axum::http::StatusCode) -> &'static str { const DESCRIPTION: &str = "The CoderHelm API lets your own programs start and follow CoderHelm's work: \ list and inspect runs, retry or cancel them, create and run plans, read the reviewer's reviews, \ -check token usage, and manage the webhook endpoints CoderHelm sends your team's events to.\n\n\ +check token usage, manage the webhook endpoints CoderHelm sends your team's events to, and see how deliveries went.\n\n\ Every request is authenticated with a team API key sent as a bearer token. Admins create keys in \ the dashboard under Settings, API keys. A key holds scopes, never more than the admin who made it, \ and has its own rate limit.\n\n\ @@ -293,6 +298,7 @@ are verified by their signatures."; crate::routes::webhooks::list_endpoint_deliveries, crate::routes::webhooks::resend_delivery, crate::routes::webhooks::replay, + crate::routes::deliveries_analytics::analytics, crate::routes::tests::ci_upload, crate::routes::tests::ci_quarantine, crate::routes::github_webhook::handle, @@ -310,6 +316,7 @@ are verified by their signatures."; (name = "Repositories", description = "The repositories connected to the team through the CoderHelm GitHub App."), (name = "Reviews", description = "Pull request reviews written by CoderHelm's reviewer."), (name = "Usage", description = "Tokens used this month and the team's limits."), + (name = "Deliveries", description = "How the webhooks CoderHelm receives and the messages it sends went over time: volume, success rate, latency, retries and failures by reason."), (name = "CI", description = "Endpoints a CI job calls with its GitHub Actions OIDC token, so no CoderHelm secret is stored in CI."), (name = "Webhook endpoints", description = "Where CoderHelm sends your team's events (runs, pull requests, reviews, CI fixes, alerts, log findings, releases, plans). Each request is signed the Standard Webhooks way. The `webhooks` section of this document has every event's schema."), (name = "Webhooks", description = "Webhooks CoderHelm receives from GitHub, Jira, AWS SNS, Sanity and Notion. CoderHelm verifies each one before anything happens."), diff --git a/services/gateway/src/permissions.rs b/services/gateway/src/permissions.rs index 7257da94b..48d053468 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -606,10 +606,11 @@ pub const CAPABILITIES: &[Capability] = &[ }, Capability { key: "deliveries", - label: "See every event in and out (webhooks, relay forwards, notifications, email) and send failed ones again", + label: "See every event in and out (webhooks, relay forwards, notifications, email), how they went over time, and send failed ones again", min_role: "admin", handlers: &[ "deliveries::list", + "deliveries_analytics::analytics", "deliveries::get", "deliveries::redeliver", ], diff --git a/services/gateway/src/routes/alerts.rs b/services/gateway/src/routes/alerts.rs index 5b8953d83..f8d79684d 100644 --- a/services/gateway/src/routes/alerts.rs +++ b/services/gateway/src/routes/alerts.rs @@ -1310,10 +1310,43 @@ async fn record_event( None => put, } .item("ttl", AttributeValue::N(ttl.to_string())) + .item( + common::deliveries_rollup::ROLLED, + AttributeValue::N("1".into()), + ) + .return_values(aws_sdk_dynamodb::types::ReturnValue::AllOld) .send() .await; - if let Err(e) = written { - warn!(topic = %msg.topic_arn, ticket = %tid, error = %e, "Could not record alert event"); + match written { + Ok(r) => { + // The Deliveries overview counts alerts too. An SNS redelivery + // rewrites the same record, so the rollups move by the difference. + let old = r + .attributes() + .filter(|i| i.contains_key(common::deliveries_rollup::ROLLED)) + .and_then(super::deliveries::alert_to_delivery); + let mut item = std::collections::HashMap::new(); + for (k, v) in [ + ("id", id.as_str()), + ("received_at", received_at.as_str()), + ("topic_arn", msg.topic_arn.as_str()), + ("repo", repo), + ("kind", alert.kind), + ("outcome", outcome.as_str()), + ] { + item.insert(k.to_string(), attr_s(v)); + } + if let Some(new) = super::deliveries::alert_to_delivery(&item) { + let store = common::deliveries_rollup::Dynamo { + client: &state.dynamo, + table: &state.config.settings_table_name, + }; + common::deliveries_rollup::apply(&store, &route.team_id, old.as_ref(), &new).await; + } + } + Err(e) => { + warn!(topic = %msg.topic_arn, ticket = %tid, error = %e, "Could not record alert event"); + } } // The alert's id seeds the event's, so an SNS redelivery is sent once. common::webhooks::emit_event_keyed( diff --git a/services/gateway/src/routes/deliveries.rs b/services/gateway/src/routes/deliveries.rs index a8d5fa883..b32c9468e 100644 --- a/services/gateway/src/routes/deliveries.rs +++ b/services/gateway/src/routes/deliveries.rs @@ -61,7 +61,9 @@ pub async fn record_email( save(state, pk, &deliveries::email(kind, to, &result)).await; } -fn alert_to_delivery(item: &std::collections::HashMap) -> Option { +pub fn alert_to_delivery( + item: &std::collections::HashMap, +) -> Option { let g = |k: &str| { item.get(k) .and_then(|v| v.as_s().ok()) @@ -94,7 +96,7 @@ fn alert_to_delivery(item: &std::collections::HashMap) - Some(d) } -fn jira_to_delivery(v: &Value) -> Option { +pub fn jira_to_delivery(v: &Value) -> Option { let s = |k: &str| v[k].as_str().unwrap_or("").to_string(); let id = s("event_id"); if id.is_empty() { @@ -216,7 +218,10 @@ pub struct ListQuery { source: Option, status: Option, since: Option, + until: Option, q: Option, + endpoint: Option, + reason: Option, limit: Option, } @@ -229,7 +234,7 @@ fn sharing_view() -> Value { }) } -/// GET /api/deliveries?source=&status=&since=&q=&limit= +/// GET /api/deliveries?source=&status=&since=&until=&q=&endpoint=&reason=&limit= pub async fn list( State(state): State>, Extension(claims): Extension, @@ -240,15 +245,24 @@ pub async fn list( source: q.source, status: q.status, since: q.since, + until: q.until, q: q.q, - endpoint: None, + endpoint: q.endpoint, + reason: q.reason, }; let limit = q.limit.unwrap_or(100).clamp(1, 500); let all = everything(&state, &claims, &f).await; // The summary always covers the last 24 hours, whatever the filters say. let day_ago = (chrono::Utc::now() - chrono::Duration::hours(24)) .to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let recent = if f.source.is_none() && f.status.is_none() && f.q.is_none() && f.since.is_none() { + let recent = if f.source.is_none() + && f.status.is_none() + && f.q.is_none() + && f.since.is_none() + && f.until.is_none() + && f.endpoint.is_none() + && f.reason.is_none() + { all.clone() } else { everything(&state, &claims, &Filter::default()).await diff --git a/services/gateway/src/routes/deliveries_analytics.rs b/services/gateway/src/routes/deliveries_analytics.rs new file mode 100644 index 000000000..7d6b965c7 --- /dev/null +++ b/services/gateway/src/routes/deliveries_analytics.rs @@ -0,0 +1,1829 @@ +//! The Deliveries overview: how deliveries went over a period, against the +//! period before. +//! +//! `GET /api/deliveries/analytics?period=24h|7d|30d&source=&status=&endpoint=` +//! reads the hour or day rollups ([`common::deliveries_rollup`]) for the +//! period and the one before it: at most 60 items, however many deliveries +//! there were. Nothing scans the records themselves, which are kept 14 days; +//! rollups are kept 120. +//! +//! The first request for a team counts the records written before rollups +//! existed (deliveries, alert events and the Jira event log), each once, a +//! few seconds' worth at a time ([`ensure_backfilled`]); the reply says when +//! that is still going. +//! +//! On a hybrid install the hosted relay's rollups for it are added +//! (`POST /hybrid/deliveries/rollups`), the same way the list adds the relay's +//! records. A self-hosted install adds the deliveries that reached no team. + +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::sync::Arc; + +use aws_sdk_dynamodb::types::AttributeValue; +use axum::{ + extract::{Query, State}, + http::StatusCode, + Extension, Json, +}; +use chrono::{DateTime, Duration, SecondsFormat, Timelike, Utc}; +use common::deliveries::{self, Delivery}; +use common::deliveries_rollup::{ + self as rollup, Counters, EndpointStat, MarkKey, Store, Unrolled, DAY_PREFIX, HOUR_PREFIX, +}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use tracing::warn; + +use crate::models::Claims; +use crate::AppState; + +type Item = HashMap; +type Fail = (StatusCode, Json); + +fn fail(code: StatusCode, c: &str, message: &str) -> Fail { + (code, Json(json!({ "error": message, "code": c }))) +} + +// ── Periods ──────────────────────────────────────────────────────────── + +/// The periods the overview offers. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Period { + /// The last 24 hours, by hour. + Day, + /// The last 7 days (today included), by day. + Week, + /// The last 30 days (today included), by day. + Month, +} + +impl Period { + pub fn parse(raw: Option<&str>) -> Option { + match raw.unwrap_or("7d") { + "24h" | "1d" => Some(Self::Day), + "7d" | "" => Some(Self::Week), + "30d" => Some(Self::Month), + _ => None, + } + } + + pub fn name(self) -> &'static str { + match self { + Self::Day => "24h", + Self::Week => "7d", + Self::Month => "30d", + } + } + + fn slots(self) -> i64 { + match self { + Self::Day => 24, + Self::Week => 7, + Self::Month => 30, + } + } + + pub fn hourly(self) -> bool { + self == Self::Day + } +} + +/// The buckets of a period and of the one before it, oldest first, each as +/// the start of its hour or day. +#[derive(Debug, Clone, PartialEq)] +pub struct Plan { + pub hourly: bool, + pub current: Vec>, + pub previous: Vec>, +} + +pub fn plan(period: Period, now: DateTime) -> Plan { + let hourly = period.hourly(); + let (last, step) = if hourly { + let h = now + .with_minute(0) + .and_then(|t| t.with_second(0)) + .and_then(|t| t.with_nanosecond(0)) + .unwrap_or(now); + (h, Duration::hours(1)) + } else { + let d = now + .date_naive() + .and_hms_opt(0, 0, 0) + .map(|d| d.and_utc()) + .unwrap_or(now); + (d, Duration::days(1)) + }; + let n = period.slots(); + let at = |i: i64| last - step * (i as i32); + let current = (0..n).rev().map(at).collect(); + let previous = (n..2 * n).rev().map(at).collect(); + Plan { + hourly, + current, + previous, + } +} + +fn bucket_key(hourly: bool, t: DateTime) -> String { + if hourly { + rollup::hour_key(t) + } else { + rollup::day_key(t) + } +} + +fn bucket_sk(hourly: bool, t: DateTime) -> String { + let prefix = if hourly { HOUR_PREFIX } else { DAY_PREFIX }; + format!("{prefix}{}", bucket_key(hourly, t)) +} + +// ── Tallies ──────────────────────────────────────────────────────────── + +/// A latency histogram: bucket name to count. +pub type Hist = BTreeMap; + +/// The counters of one scope (a source and direction, or an endpoint). +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Tally { + pub handled: i64, + pub ignored: i64, + pub failed: i64, + pub retried: i64, + pub retried_ok: i64, + pub retries: i64, + pub lat_ok: Hist, + pub lat_failed: Hist, + pub reasons: BTreeMap, + pub events: BTreeMap, +} + +fn add_map(into: &mut BTreeMap, from: &BTreeMap) { + for (k, v) in from { + *into.entry(k.clone()).or_insert(0) += v; + } +} + +impl Tally { + pub fn add(&mut self, o: &Tally) { + self.handled += o.handled; + self.ignored += o.ignored; + self.failed += o.failed; + self.retried += o.retried; + self.retried_ok += o.retried_ok; + self.retries += o.retries; + add_map(&mut self.lat_ok, &o.lat_ok); + add_map(&mut self.lat_failed, &o.lat_failed); + add_map(&mut self.reasons, &o.reasons); + add_map(&mut self.events, &o.events); + } + + pub fn total(&self) -> i64 { + self.handled + self.ignored + self.failed + } + + /// Only what the status filter shows. + pub fn only(&self, st: StatusSel) -> Tally { + let ok = st != StatusSel::Failed; + let failed = matches!(st, StatusSel::All | StatusSel::Failed); + Tally { + handled: if matches!(st, StatusSel::All | StatusSel::Ok | StatusSel::Handled) { + self.handled + } else { + 0 + }, + ignored: if matches!(st, StatusSel::All | StatusSel::Ok | StatusSel::Ignored) { + self.ignored + } else { + 0 + }, + failed: if failed { self.failed } else { 0 }, + retried: match st { + StatusSel::All => self.retried, + StatusSel::Failed => (self.retried - self.retried_ok).max(0), + _ => self.retried_ok, + }, + retried_ok: if st == StatusSel::Failed { + 0 + } else { + self.retried_ok + }, + retries: if st == StatusSel::All { + self.retries + } else { + 0 + }, + lat_ok: if ok { self.lat_ok.clone() } else { Hist::new() }, + lat_failed: if failed { + self.lat_failed.clone() + } else { + Hist::new() + }, + reasons: if failed { + self.reasons.clone() + } else { + BTreeMap::new() + }, + events: if failed { + self.events.clone() + } else { + BTreeMap::new() + }, + } + } + + fn latency(&self) -> Hist { + let mut h = self.lat_ok.clone(); + add_map(&mut h, &self.lat_failed); + h + } +} + +/// The status filter, as the list offers it (`pending` has no rollup: a +/// retrying delivery counts once it finishes). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StatusSel { + All, + Ok, + Failed, + Handled, + Ignored, +} + +impl StatusSel { + pub fn parse(raw: Option<&str>) -> Option { + Some(match raw.unwrap_or("all") { + "" | "all" => Self::All, + "ok" => Self::Ok, + "failed" => Self::Failed, + "handled" => Self::Handled, + "ignored" => Self::Ignored, + _ => return None, + }) + } +} + +/// One bucket's counters by scope: `s##` or `ep#`. +pub fn by_scope(c: &Counters) -> BTreeMap { + let mut out: BTreeMap = BTreeMap::new(); + for (k, v) in c { + let parts: Vec<&str> = k.split('#').collect(); + let (scope, field) = match parts.first() { + Some(&"s") if parts.len() >= 4 => (parts[..3].join("#"), &parts[3..]), + Some(&"ep") if parts.len() >= 3 => (parts[..2].join("#"), &parts[2..]), + _ => continue, + }; + let t = out.entry(scope).or_default(); + match field { + ["handled"] => t.handled += v, + ["ignored"] => t.ignored += v, + ["failed"] => t.failed += v, + ["retried"] => t.retried += v, + ["retried_ok"] => t.retried_ok += v, + ["retries"] => t.retries += v, + ["lat", "ok", b] => *t.lat_ok.entry(b.to_string()).or_insert(0) += v, + ["lat", "failed", b] => *t.lat_failed.entry(b.to_string()).or_insert(0) += v, + ["r", code] => *t.reasons.entry(code.to_string()).or_insert(0) += v, + ["e", event] => *t.events.entry(event.to_string()).or_insert(0) += v, + _ => {} + } + } + out +} + +/// What the overview is narrowed to. +#[derive(Debug, Clone, PartialEq)] +pub struct Selection { + pub source: Option, + pub status: StatusSel, + pub endpoint: Option, +} + +impl Selection { + /// A source scope's source and direction, when the selection takes it. + fn source_of<'a>(&self, scope: &'a str) -> Option<(&'a str, &'a str)> { + let mut p = scope.split('#'); + if p.next()? != "s" { + return None; + } + let (src, dir) = (p.next()?, p.next()?); + match &self.source { + Some(s) if s != src => None, + _ => Some((src, dir)), + } + } + + /// Whether the headline numbers take this scope: the endpoint's own + /// scope when one is chosen, otherwise every source scope that matches. + fn takes(&self, scope: &str) -> bool { + match &self.endpoint { + Some(ep) => scope == rollup::endpoint_scope(ep), + None => self.source_of(scope).is_some(), + } + } + + /// Endpoints show unless another source than webhooks is chosen. + fn shows_endpoints(&self) -> bool { + self.source.as_deref().is_none_or(|s| s == "webhook") + } +} + +// ── The reply ────────────────────────────────────────────────────────── + +/// Headline numbers for one period. +#[derive(Debug, Clone, Default, PartialEq, Serialize, utoipa::ToSchema)] +pub struct Totals { + /// Finished deliveries (handled, ignored or failed). + #[schema(example = 1284)] + pub deliveries: i64, + /// Finished and handled. + #[schema(example = 1190)] + pub handled: i64, + /// Finished and ignored on purpose (a duplicate, an event nothing needed). + #[schema(example = 61)] + pub ignored: i64, + /// Finished and failed. + #[schema(example = 33)] + pub failed: i64, + /// Handled or ignored, out of finished. Null with none. + #[schema(example = 0.9743)] + pub success_rate: Option, + /// Deliveries that took more than one attempt. + #[schema(example = 41)] + pub retried: i64, + /// Of those, the ones that went fine in the end. + #[schema(example = 37)] + pub retried_ok: i64, + /// Attempts after the first, in all. Null when a status filter is on. + #[schema(example = 58)] + pub retries: Option, + /// Latency percentiles in milliseconds (the last attempt's), from a + /// histogram, so within a bucket's width. Null with no timed deliveries. + #[schema(example = 180)] + pub p50_ms: Option, + /// 95th percentile latency, milliseconds. + #[schema(example = 1240)] + pub p95_ms: Option, + /// 99th percentile latency, milliseconds. + #[schema(example = 4800)] + pub p99_ms: Option, +} + +pub fn totals(t: &Tally, status: StatusSel) -> Totals { + let n = t.total(); + let ok = t.handled + t.ignored; + let h = t.latency(); + Totals { + deliveries: n, + handled: t.handled, + ignored: t.ignored, + failed: t.failed, + success_rate: (n > 0).then(|| round4(ok as f64 / n as f64)), + retried: t.retried, + retried_ok: t.retried_ok, + retries: (status == StatusSel::All).then_some(t.retries), + p50_ms: rollup::percentile(&h, 0.50), + p95_ms: rollup::percentile(&h, 0.95), + p99_ms: rollup::percentile(&h, 0.99), + } +} + +fn round4(v: f64) -> f64 { + (v * 10_000.0).round() / 10_000.0 +} + +/// One hour or day of the period. +#[derive(Debug, Clone, PartialEq, Serialize, utoipa::ToSchema)] +pub struct Point { + /// The bucket's start (RFC 3339, UTC). + #[schema(example = "2026-10-26T00:00:00Z")] + pub start: String, + /// The bucket's end, exclusive. + #[schema(example = "2026-10-27T00:00:00Z")] + pub end: String, + /// Finished deliveries in the bucket. + #[schema(example = 190)] + pub deliveries: i64, + /// Handled or ignored. + #[schema(example = 186)] + pub ok: i64, + /// Failed. + #[schema(example = 4)] + pub failed: i64, + /// Handled or ignored, out of finished. Null with none. + #[schema(example = 0.9789)] + pub success_rate: Option, + /// 95th percentile latency, milliseconds. + #[schema(example = 1100)] + pub p95_ms: Option, + /// Deliveries in the matching bucket of the period before. + #[schema(example = 171)] + pub previous_deliveries: i64, +} + +/// One source and direction. +#[derive(Debug, Clone, PartialEq, Serialize, utoipa::ToSchema)] +pub struct SourceRow { + /// `github`, `relay`, `webhook`, `alerts`, `jira`, `slack`, `teams`, `email`, `broker`, `knowledge`. + #[schema(example = "github")] + pub source: String, + /// `inbound` or `outbound`. + #[schema(example = "inbound")] + pub direction: String, + /// Finished deliveries in the period. + #[schema(example = 912)] + pub deliveries: i64, + /// Handled or ignored. + #[schema(example = 905)] + pub ok: i64, + /// Failed. + #[schema(example = 7)] + pub failed: i64, + /// Handled or ignored, out of finished. Null with none. + #[schema(example = 0.9923)] + pub success_rate: Option, + /// 95th percentile latency, milliseconds. + #[schema(example = 640)] + pub p95_ms: Option, + /// Finished deliveries in the period before. + #[schema(example = 870)] + pub previous_deliveries: i64, + /// The success rate in the period before. + #[schema(example = 0.9897)] + pub previous_success_rate: Option, +} + +/// Failures with one reason. +#[derive(Debug, Clone, PartialEq, Serialize, utoipa::ToSchema)] +pub struct ReasonRow { + /// The reason code, as on each delivery. + #[schema(example = "webhook_server_error")] + pub code: String, + /// What happened, in plain words. + #[schema(example = "Your webhook endpoint answered with a server error (5xx).")] + pub message: String, + /// What to do about it. + #[schema( + example = "Check your endpoint's logs for this event id. CoderHelm retries for about a day." + )] + pub fix: String, + /// Failures with this reason in the period. + #[schema(example = 12)] + pub count: i64, + /// Failures with this reason in the period before. + #[schema(example = 3)] + pub previous_count: i64, + /// The sources it happened on, most first. + #[schema(example = json!(["webhook"]))] + pub sources: Vec, +} + +/// An event type that failed. +#[derive(Debug, Clone, PartialEq, Serialize, utoipa::ToSchema)] +pub struct EventRow { + /// The event or message type. + #[schema(example = "run.failed")] + pub event: String, + /// Where it came from or went. + #[schema(example = "webhook")] + pub source: String, + /// Failures of this type in the period. + #[schema(example = 9)] + pub failed: i64, +} + +/// One outbound webhook endpoint. +#[derive(Debug, Clone, PartialEq, Serialize, utoipa::ToSchema)] +pub struct EndpointRow { + /// The endpoint's id. + #[schema(example = "ep_01JBENDPT4K2M8N3P5Q7R9S1T3")] + pub id: String, + /// The endpoint's address (empty once the endpoint is deleted). + #[schema(example = "https://hooks.example.com/coderhelm")] + pub url: String, + /// The endpoint's description, as the team wrote it. + #[schema(example = "Incident bot")] + pub description: String, + /// The endpoint no longer exists; its counts stay for the period. + #[schema(example = false)] + pub deleted: bool, + /// Whether the endpoint is on. + #[schema(example = true)] + pub enabled: bool, + /// Why it's off: `manual` or `failing`. Empty while on. + #[schema(example = "")] + pub disabled_reason: String, + /// Finished deliveries to it in the period. + #[schema(example = 214)] + pub deliveries: i64, + /// Delivered. + #[schema(example = 202)] + pub ok: i64, + /// Failed. + #[schema(example = 12)] + pub failed: i64, + /// Delivered, out of finished. Null with none. + #[schema(example = 0.9439)] + pub success_rate: Option, + /// Median latency, milliseconds. + #[schema(example = 320)] + pub p50_ms: Option, + /// 95th percentile latency, milliseconds. + #[schema(example = 2900)] + pub p95_ms: Option, + /// Failures in a row since its last success. + #[schema(example = 0)] + pub streak: i64, + /// When it last failed. + #[schema(example = "2026-10-26T09:14:02Z")] + pub last_failure_at: Option, + /// The last failure's reason code. + #[schema(example = "webhook_server_error")] + pub last_failure_reason: Option, + /// The last failure's reason in plain words. + #[schema(example = "Your webhook endpoint answered with a server error (5xx).")] + pub last_failure_message: Option, + /// The first failure since its last success, while it's failing. + #[schema(example = json!(null))] + pub failing_since: Option, + /// When it last took a delivery. + #[schema(example = "2026-10-26T15:02:40Z")] + pub last_success_at: Option, +} + +/// Whether the records from before rollups existed are all counted yet. +#[derive(Debug, Clone, PartialEq, Serialize, utoipa::ToSchema)] +pub struct Backfill { + /// False while older records are still being counted; numbers grow until it is true. + #[schema(example = true)] + pub complete: bool, +} + +/// The Deliveries overview for one period. +#[derive(Debug, Clone, PartialEq, Serialize, utoipa::ToSchema)] +#[schema(example = json!({ + "period": "7d", + "granularity": "day", + "from": "2026-10-20T00:00:00Z", + "to": "2026-10-27T00:00:00Z", + "previous_from": "2026-10-13T00:00:00Z", + "previous_to": "2026-10-20T00:00:00Z", + "summary": {"deliveries": 1284, "handled": 1190, "ignored": 61, "failed": 33, "success_rate": 0.9743, "retried": 41, "retried_ok": 37, "retries": 58, "p50_ms": 180, "p95_ms": 1240, "p99_ms": 4800}, + "previous": {"deliveries": 1120, "handled": 1040, "ignored": 52, "failed": 28, "success_rate": 0.975, "retried": 30, "retried_ok": 26, "retries": 44, "p50_ms": 170, "p95_ms": 1100, "p99_ms": 4100}, + "series": [{"start": "2026-10-26T00:00:00Z", "end": "2026-10-27T00:00:00Z", "deliveries": 190, "ok": 186, "failed": 4, "success_rate": 0.9789, "p95_ms": 1100, "previous_deliveries": 171}], + "sources": [{"source": "github", "direction": "inbound", "deliveries": 912, "ok": 905, "failed": 7, "success_rate": 0.9923, "p95_ms": 640, "previous_deliveries": 870, "previous_success_rate": 0.9897}], + "reasons": [{"code": "webhook_server_error", "message": "Your webhook endpoint answered with a server error (5xx).", "fix": "Check your endpoint's logs for this event id. CoderHelm retries for about a day.", "count": 12, "previous_count": 3, "sources": ["webhook"]}], + "events": [{"event": "run.failed", "source": "webhook", "failed": 9}], + "endpoints": [{"id": "ep_01JBENDPT4K2M8N3P5Q7R9S1T3", "url": "https://hooks.example.com/coderhelm", "description": "Incident bot", "deleted": false, "enabled": true, "disabled_reason": "", "deliveries": 214, "ok": 202, "failed": 12, "success_rate": 0.9439, "p50_ms": 320, "p95_ms": 2900, "streak": 0, "last_failure_at": "2026-10-26T09:14:02Z", "last_failure_reason": "webhook_server_error", "last_failure_message": "Your webhook endpoint answered with a server error (5xx).", "failing_since": null, "last_success_at": "2026-10-26T15:02:40Z"}], + "seen_sources": ["github", "webhook", "slack", "email"], + "backfill": {"complete": true}, + "kept_days": 120, + "records_kept_days": 14 +}))] +pub struct DeliveryAnalytics { + /// `24h`, `7d` or `30d`. + #[schema(example = "7d")] + pub period: String, + /// `hour` or `day`. + #[schema(example = "day")] + pub granularity: String, + /// The period: from (inclusive) to (exclusive), RFC 3339. + #[schema(example = "2026-10-20T00:00:00Z")] + pub from: String, + /// The end of the period, exclusive. + #[schema(example = "2026-10-27T00:00:00Z")] + pub to: String, + /// The period before, as long as this one. + #[schema(example = "2026-10-13T00:00:00Z")] + pub previous_from: String, + /// The end of the period before, exclusive. + #[schema(example = "2026-10-20T00:00:00Z")] + pub previous_to: String, + pub summary: Totals, + pub previous: Totals, + /// One point per hour (24h) or day, oldest first. + pub series: Vec, + /// By source and direction, most deliveries first. + pub sources: Vec, + /// Failures by reason, most first. + pub reasons: Vec, + /// The event types that failed most (up to 10). + pub events: Vec, + /// The team's outbound webhook endpoints, and any that had deliveries + /// in the period since. Empty when another source is chosen. + pub endpoints: Vec, + /// Every source with deliveries in either period, for the filter. + #[schema(example = json!(["github", "webhook", "slack", "email"]))] + pub seen_sources: Vec, + pub backfill: Backfill, + /// Days the counts are kept. + #[schema(example = 120)] + pub kept_days: i64, + /// Days each delivery's record is kept (what a drill-in can list). + #[schema(example = 14)] + pub records_kept_days: i64, +} + +/// An endpoint as the settings table keeps it (only what the overview +/// shows; the signing secret is never read). +#[derive(Debug, Clone, Default, PartialEq)] +pub struct EndpointMeta { + pub id: String, + pub url: String, + pub description: String, + pub enabled: bool, + pub disabled_reason: String, + pub failing_since: Option, + pub last_failure_at: Option, + pub last_success_at: Option, +} + +pub fn endpoint_meta(item: &Item) -> Option { + let g = |k: &str| { + item.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + let opt = |k: &str| Some(g(k)).filter(|v| !v.is_empty()); + let id = g("id"); + if id.is_empty() || !g("sk").starts_with(ENDPOINT_SK) { + return None; + } + Some(EndpointMeta { + id, + url: g("url"), + description: g("description"), + enabled: item + .get("enabled") + .and_then(|v| v.as_bool().ok()) + .copied() + .unwrap_or(false), + disabled_reason: g("disabled_reason"), + failing_since: opt("failing_since"), + last_failure_at: opt("last_failure_at"), + last_success_at: opt("last_success_at"), + }) +} + +/// Where webhook endpoints are kept (`common::webhooks::endpoint`). +pub const ENDPOINT_SK: &str = "WEBHOOK_ENDPOINT#"; + +fn direction_word(dir: &str) -> &'static str { + if dir == "in" { + "inbound" + } else { + "outbound" + } +} + +/// The overview from the rollups (`rows`: sort key to counters), the +/// endpoints and their streaks. Pure: every number is tested. +pub fn build( + period: Period, + p: &Plan, + rows: &BTreeMap, + sel: &Selection, + metas: &[EndpointMeta], + stats: &[EndpointStat], +) -> DeliveryAnalytics { + let step = if p.hourly { + Duration::hours(1) + } else { + Duration::days(1) + }; + let scoped = |t: &DateTime| { + rows.get(&bucket_sk(p.hourly, *t)) + .map(by_scope) + .unwrap_or_default() + }; + let cur: Vec> = p.current.iter().map(scoped).collect(); + let prev: Vec> = p.previous.iter().map(scoped).collect(); + let st = sel.status; + + let pick = |b: &BTreeMap| { + let mut t = Tally::default(); + for (scope, x) in b { + if sel.takes(scope) { + t.add(&x.only(st)); + } + } + t + }; + let sum = |bs: &[BTreeMap]| { + let mut t = Tally::default(); + for b in bs { + t.add(&pick(b)); + } + t + }; + let now_t = sum(&cur); + let prev_t = sum(&prev); + + let series = p + .current + .iter() + .enumerate() + .map(|(i, t)| { + let x = pick(&cur[i]); + let tt = totals(&x, st); + Point { + start: t.to_rfc3339_opts(SecondsFormat::Secs, true), + end: (*t + step).to_rfc3339_opts(SecondsFormat::Secs, true), + deliveries: tt.deliveries, + ok: tt.handled + tt.ignored, + failed: tt.failed, + success_rate: tt.success_rate, + p95_ms: tt.p95_ms, + previous_deliveries: prev.get(i).map(|b| pick(b).total()).unwrap_or(0), + } + }) + .collect(); + + // By source and direction (the endpoint filter doesn't narrow these). + let mut src_now: BTreeMap<(String, String), Tally> = BTreeMap::new(); + let mut src_prev: BTreeMap<(String, String), Tally> = BTreeMap::new(); + let mut seen: BTreeSet = BTreeSet::new(); + for (bs, into) in [(&cur, &mut src_now), (&prev, &mut src_prev)] { + for b in bs.iter() { + for (scope, x) in b { + if let Some(src) = scope.strip_prefix("s#").and_then(|r| r.split('#').next()) { + if x.total() != 0 { + seen.insert(src.to_string()); + } + } + if let Some((src, dir)) = sel.source_of(scope) { + into.entry((src.to_string(), dir.to_string())) + .or_default() + .add(&x.only(st)); + } + } + } + } + let mut sources: Vec = src_now + .iter() + .filter(|(_, t)| t.total() != 0) + .map(|((src, dir), t)| { + let tt = totals(t, st); + let pt = src_prev + .get(&(src.clone(), dir.clone())) + .map(|x| totals(x, st)) + .unwrap_or_default(); + SourceRow { + source: src.clone(), + direction: direction_word(dir).into(), + deliveries: tt.deliveries, + ok: tt.handled + tt.ignored, + failed: tt.failed, + success_rate: tt.success_rate, + p95_ms: tt.p95_ms, + previous_deliveries: pt.deliveries, + previous_success_rate: pt.success_rate, + } + }) + .collect(); + sources.sort_by(|a, b| { + b.deliveries + .cmp(&a.deliveries) + .then(a.source.cmp(&b.source)) + }); + + // Reasons and events, with the sources they happened on. + let mut reason_sources: BTreeMap> = BTreeMap::new(); + let mut events: BTreeMap<(String, String), i64> = BTreeMap::new(); + for b in &cur { + for (scope, x) in b { + if !sel.takes(scope) { + continue; + } + let x = x.only(st); + let src = match scope.strip_prefix("s#") { + Some(r) => r.split('#').next().unwrap_or("").to_string(), + None => "webhook".to_string(), + }; + for (code, n) in &x.reasons { + *reason_sources + .entry(code.clone()) + .or_default() + .entry(src.clone()) + .or_insert(0) += n; + } + for (ev, n) in &x.events { + *events.entry((src.clone(), ev.clone())).or_insert(0) += n; + } + } + } + let mut reasons: Vec = now_t + .reasons + .iter() + .filter(|(_, n)| **n > 0) + .map(|(code, n)| { + let r = deliveries::reason(code); + let mut srcs: Vec<(String, i64)> = reason_sources + .get(code) + .map(|m| m.iter().map(|(k, v)| (k.clone(), *v)).collect()) + .unwrap_or_default(); + srcs.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0))); + ReasonRow { + code: code.clone(), + message: r.message.into(), + fix: r.fix.into(), + count: *n, + previous_count: prev_t.reasons.get(code).copied().unwrap_or(0), + sources: srcs.into_iter().filter(|s| s.1 > 0).map(|s| s.0).collect(), + } + }) + .collect(); + reasons.sort_by(|a, b| b.count.cmp(&a.count).then(a.code.cmp(&b.code))); + let mut events: Vec = events + .into_iter() + .filter(|(_, n)| *n > 0) + .map(|((source, event), failed)| EventRow { + event, + source, + failed, + }) + .collect(); + events.sort_by(|a, b| b.failed.cmp(&a.failed).then(a.event.cmp(&b.event))); + events.truncate(10); + + // Endpoints: every one the team has, plus any with deliveries since deleted. + let mut endpoints = vec![]; + if sel.shows_endpoints() { + let mut ep_t: BTreeMap = BTreeMap::new(); + for b in &cur { + for (scope, x) in b { + if let Some(id) = scope.strip_prefix("ep#") { + ep_t.entry(id.to_string()).or_default().add(&x.only(st)); + } + } + } + let mut ids: Vec = metas.iter().map(|m| m.id.clone()).collect(); + for (id, t) in &ep_t { + if t.total() != 0 && !metas.iter().any(|m| rollup::part(&m.id) == *id) { + ids.push(id.clone()); + } + } + for id in ids { + let meta = metas.iter().find(|m| m.id == id); + let key = rollup::part(&id); + let t = ep_t.get(&key).cloned().unwrap_or_default(); + let tt = totals(&t, st); + let stat = stats.iter().find(|s| rollup::part(&s.endpoint_id) == key); + let last_failure_at = stat + .and_then(|s| s.last_failure_at.clone()) + .or_else(|| meta.and_then(|m| m.last_failure_at.clone())); + let last_failure_reason = stat + .and_then(|s| s.last_failure_reason.clone()) + .filter(|r| !r.is_empty()); + endpoints.push(EndpointRow { + id: id.clone(), + url: meta.map(|m| m.url.clone()).unwrap_or_default(), + description: meta.map(|m| m.description.clone()).unwrap_or_default(), + deleted: meta.is_none(), + enabled: meta.is_some_and(|m| m.enabled), + disabled_reason: meta.map(|m| m.disabled_reason.clone()).unwrap_or_default(), + deliveries: tt.deliveries, + ok: tt.handled + tt.ignored, + failed: tt.failed, + success_rate: tt.success_rate, + p50_ms: tt.p50_ms, + p95_ms: tt.p95_ms, + streak: stat.map(|s| s.streak.max(0)).unwrap_or(0), + last_failure_message: last_failure_reason + .as_deref() + .map(|r| deliveries::reason(r).message.to_string()), + last_failure_reason, + last_failure_at, + failing_since: meta.and_then(|m| m.failing_since.clone()), + last_success_at: stat + .and_then(|s| s.last_success_at.clone()) + .or_else(|| meta.and_then(|m| m.last_success_at.clone())), + }); + } + endpoints.sort_by(|a, b| { + b.streak + .cmp(&a.streak) + .then(b.failed.cmp(&a.failed)) + .then(b.deliveries.cmp(&a.deliveries)) + .then(a.id.cmp(&b.id)) + }); + } + + let first = |v: &[DateTime]| { + v.first() + .map(|t| t.to_rfc3339_opts(SecondsFormat::Secs, true)) + .unwrap_or_default() + }; + let end = |v: &[DateTime]| { + v.last() + .map(|t| (*t + step).to_rfc3339_opts(SecondsFormat::Secs, true)) + .unwrap_or_default() + }; + DeliveryAnalytics { + period: period.name().into(), + granularity: if p.hourly { "hour" } else { "day" }.into(), + from: first(&p.current), + to: end(&p.current), + previous_from: first(&p.previous), + previous_to: end(&p.previous), + summary: totals(&now_t, st), + previous: totals(&prev_t, st), + series, + sources, + reasons, + events, + endpoints, + seen_sources: seen.into_iter().collect(), + backfill: Backfill { complete: true }, + kept_days: rollup::DAY_RETENTION_DAYS, + records_kept_days: deliveries::RETENTION_DAYS, + } +} + +/// Adds rows into `into` (counters of the same item add up). +pub fn merge_rows(into: &mut BTreeMap, rows: Vec<(String, Counters)>) { + for (sk, c) in rows { + let e = into.entry(sk).or_default(); + for (k, v) in c { + *e.entry(k).or_insert(0) += v; + } + } +} + +/// Only the hosted relay's own counters (relay forwards and the broker): +/// what an install adds from CoderHelm's side. +pub fn relay_only(c: Counters) -> Counters { + c.into_iter() + .filter(|(k, _)| k.starts_with("s#relay#") || k.starts_with("s#broker#")) + .collect() +} + +// ── Backfill ─────────────────────────────────────────────────────────── + +fn store(state: &AppState) -> rollup::Dynamo<'_> { + rollup::Dynamo { + client: &state.dynamo, + table: &state.config.settings_table_name, + } +} + +async fn query_unrolled( + state: &AppState, + table: &str, + key_expr: &str, + values: Vec<(&str, AttributeValue)>, +) -> Result, String> { + let mut out = vec![]; + let mut start = None; + loop { + let mut q = state + .dynamo + .query() + .table_name(table) + .key_condition_expression(key_expr) + .filter_expression("attribute_not_exists(#rolled)") + .expression_attribute_names("#rolled", rollup::ROLLED) + .set_exclusive_start_key(start); + for (k, v) in &values { + q = q.expression_attribute_values(*k, v.clone()); + } + let r = q + .send() + .await + .map_err(|e| format!("{e:?}").chars().take(300).collect::())?; + out.extend(r.items().iter().cloned()); + start = r.last_evaluated_key().cloned(); + if start.is_none() { + break; + } + } + Ok(out) +} + +fn key_of(item: &Item, names: &[&str]) -> HashMap { + names + .iter() + .filter_map(|n| item.get(*n).map(|v| (n.to_string(), v.clone()))) + .collect() +} + +/// A Jira event log item as a delivery (the gateway's list mapping). +pub fn jira_item_to_delivery(item: &Item) -> Option { + let mut v = serde_json::Map::new(); + for (k, a) in item { + if let Ok(s) = a.as_s() { + v.insert(k.clone(), Value::String(s.clone())); + } + } + super::deliveries::jira_to_delivery(&Value::Object(v)) +} + +/// The records of `pk` (and, for a team, its alert events and Jira event +/// log) that rollups haven't counted yet. +async fn unrolled(state: &AppState, pk: &str, team: bool) -> Result, String> { + let settings = state.config.settings_table_name.clone(); + let s = |v: &str| AttributeValue::S(v.to_string()); + let mut out = vec![]; + for item in query_unrolled( + state, + &settings, + "pk = :pk AND begins_with(sk, :p)", + vec![(":pk", s(pk)), (":p", s(deliveries::SK_PREFIX))], + ) + .await? + { + if let Some(d) = deliveries::from_item(&item) { + out.push(Unrolled { + mark: MarkKey { + table: settings.clone(), + key: key_of(&item, &["pk", "sk"]), + }, + delivery: d, + }); + } + } + if !team { + return Ok(out); + } + for item in query_unrolled( + state, + &settings, + "pk = :pk AND begins_with(sk, :p)", + vec![(":pk", s(pk)), (":p", s("ALERT_EVENT#"))], + ) + .await? + { + if let Some(d) = super::deliveries::alert_to_delivery(&item) { + out.push(Unrolled { + mark: MarkKey { + table: settings.clone(), + key: key_of(&item, &["pk", "sk"]), + }, + delivery: d, + }); + } + } + let jira = state.config.jira_events_table_name.clone(); + if !jira.is_empty() { + for item in query_unrolled(state, &jira, "team_id = :t", vec![(":t", s(pk))]).await? { + let dedup = item + .get("event_id") + .and_then(|v| v.as_s().ok()) + .is_some_and(|e| e.starts_with("DEDUP#")); + if dedup { + continue; + } + if let Some(d) = jira_item_to_delivery(&item) { + out.push(Unrolled { + mark: MarkKey { + table: jira.clone(), + key: key_of(&item, &["team_id", "event_id"]), + }, + delivery: d, + }); + } + } + } + Ok(out) +} + +/// Counts `pk`'s records from before rollups existed, once, until +/// `deadline`. True once every one is counted (and from then on, at the cost +/// of one read). +pub async fn ensure_backfilled( + state: &AppState, + pk: &str, + team: bool, + deadline: std::time::Instant, +) -> bool { + let st = store(state); + match st.backfilled(pk).await { + Ok(true) => return true, + Ok(false) => {} + Err(e) => { + warn!(error = %e, "Could not read the delivery rollup backfill marker"); + return false; + } + } + let items = match unrolled(state, pk, team).await { + Ok(i) => i, + Err(e) => { + warn!(error = %e, "Could not list records for the delivery rollup backfill"); + return false; + } + }; + let report = rollup::backfill(&st, pk, items, Utc::now(), deadline).await; + tracing::info!( + counted = report.counted, + skipped = report.skipped, + left = report.left, + "Delivery rollup backfill" + ); + if report.left > 0 { + return false; + } + let at = Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true); + if let Err(e) = st.set_backfilled(pk, &at).await { + warn!(error = %e, "Could not mark the delivery rollup backfill done"); + } + true +} + +/// The rollup rows of `pk` for a plan (the previous period's first bucket to +/// this one's last). +pub async fn read_rows( + state: &AppState, + pk: &str, + p: &Plan, +) -> Result, String> { + let (Some(a), Some(b)) = (p.previous.first(), p.current.last()) else { + return Ok(vec![]); + }; + store(state) + .read(pk, &bucket_sk(p.hourly, *a), &bucket_sk(p.hourly, *b)) + .await +} + +async fn endpoint_metas(state: &AppState, team: &str) -> Vec { + let r = state + .dynamo + .query() + .table_name(&state.config.settings_table_name) + .key_condition_expression("pk = :pk AND begins_with(sk, :p)") + .expression_attribute_values(":pk", AttributeValue::S(team.into())) + .expression_attribute_values(":p", AttributeValue::S(ENDPOINT_SK.into())) + .projection_expression( + "pk, sk, id, #u, description, enabled, disabled_reason, failing_since, last_failure_at, last_success_at", + ) + .expression_attribute_names("#u", "url") + .send() + .await; + match r { + Ok(r) => r.items().iter().filter_map(endpoint_meta).collect(), + Err(e) => { + warn!(error = %e, "Could not read webhook endpoints for the overview"); + vec![] + } + } +} + +/// The hosted relay's rollups for this install (hybrid only). +async fn relayed_rows(state: &AppState, p: &Plan) -> Vec<(String, Counters)> { + let Some(creds) = common::hybrid::client::credentials() else { + return vec![]; + }; + let (Some(a), Some(b)) = (p.previous.first(), p.current.last()) else { + return vec![]; + }; + let body = json!({ "from": bucket_sk(p.hourly, *a), "to": bucket_sk(p.hourly, *b) }); + match common::hybrid::client::call( + &state.http, + &creds, + "POST", + "/hybrid/deliveries/rollups", + Some(&body), + ) + .await + { + Ok(v) => parse_relayed(&v), + Err(e) => { + warn!(error = %e.message, "Could not read relay rollups from CoderHelm"); + vec![] + } + } +} + +/// The hosted side's reply, as rows (relay counters only). +pub fn parse_relayed(v: &Value) -> Vec<(String, Counters)> { + v["buckets"] + .as_array() + .map(|a| { + a.iter() + .filter_map(|b| { + let sk = b["sk"].as_str()?; + if !sk.starts_with(DAY_PREFIX) && !sk.starts_with(HOUR_PREFIX) { + return None; + } + let c: Counters = b["counters"] + .as_object()? + .iter() + .filter_map(|(k, v)| Some((k.clone(), v.as_i64()?))) + .collect(); + Some((sk.to_string(), relay_only(c))) + }) + .collect() + }) + .unwrap_or_default() +} + +// ── The route ────────────────────────────────────────────────────────── + +#[derive(Debug, Deserialize, utoipa::IntoParams)] +#[into_params(parameter_in = Query)] +pub struct AnalyticsQuery { + /// `24h` (by hour), `7d` or `30d` (by day). Default `7d`. Each is + /// compared with the period before it, as long. + #[param(example = "7d")] + period: Option, + /// Only one source: `github`, `relay`, `webhook`, `alerts`, `jira`, + /// `slack`, `teams`, `email`, `broker`, `knowledge`. + #[param(example = "webhook")] + source: Option, + /// `all` (default), `ok` (handled or ignored), `handled`, `ignored` or + /// `failed`. Retrying deliveries count once they finish. + #[param(example = "failed")] + status: Option, + /// Only one outbound webhook endpoint (its id). + #[param(example = "ep_01JBENDPT4K2M8N3P5Q7R9S1T3")] + endpoint: Option, +} + +/// How long one request spends counting older records before it answers. +const BACKFILL_BUDGET: std::time::Duration = std::time::Duration::from_secs(5); + +/// GET /api/deliveries/analytics +#[utoipa::path( + get, + path = "/api/deliveries/analytics", + tag = "Deliveries", + operation_id = "getDeliveryAnalytics", + summary = "Get delivery analytics", + description = "How the team's deliveries went over a period, against the period before: \ + webhooks CoderHelm received (GitHub, Jira, alerts), events it relayed, and what it sent \ + (webhook endpoints, Slack, Teams, email). Per hour for `24h`, per day otherwise: volume, \ + success rate, latency percentiles, retries and how many of them went fine, failures by \ + reason in plain words, the event types that failed most, and each webhook endpoint's \ + success rate, latency, failure streak and whether it is turned off. Counts are kept \ + 120 days; each delivery's own record 14.", + params(AnalyticsQuery), + responses( + (status = 200, description = "The overview.", body = DeliveryAnalytics), + (status = 400, description = "An unknown `period` or `status`.", body = crate::openapi::ErrorBody), + ), + security(("api_key" = ["deliveries"])), +)] +pub async fn analytics( + State(state): State>, + Extension(claims): Extension, + Query(q): Query, +) -> Result, Fail> { + let allowed = claims.require_role(3); + allowed.map_err(|c| fail(c, "forbidden", "Admins only."))?; + let period = Period::parse(q.period.as_deref()).ok_or_else(|| { + fail( + StatusCode::BAD_REQUEST, + "bad_request", + "period is 24h, 7d or 30d.", + ) + })?; + let status = StatusSel::parse(q.status.as_deref()).ok_or_else(|| { + fail( + StatusCode::BAD_REQUEST, + "bad_request", + "status is all, ok, handled, ignored or failed.", + ) + })?; + let clean = |v: Option| { + v.map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty() && s != "all") + }; + let sel = Selection { + source: clean(q.source).map(|s| rollup::part(&s)), + status, + endpoint: clean(q.endpoint), + }; + let team = claims.team_id.clone(); + let unrouted = super::setup_checks::self_hosted(); + let deadline = std::time::Instant::now() + BACKFILL_BUDGET; + let (own_done, unrouted_done) = + tokio::join!(ensure_backfilled(&state, &team, true, deadline), async { + !unrouted + || ensure_backfilled(&state, super::deliveries::UNROUTED, false, deadline).await + }); + + let p = plan(period, Utc::now()); + let st = store(&state); + let (own, other, relayed, metas, stats) = tokio::join!( + read_rows(&state, &team, &p), + async { + if unrouted { + read_rows(&state, super::deliveries::UNROUTED, &p) + .await + .unwrap_or_default() + } else { + vec![] + } + }, + relayed_rows(&state, &p), + endpoint_metas(&state, &team), + st.endpoints(&team), + ); + let own = own.map_err(|e| { + warn!(error = %e, "Could not read delivery rollups"); + fail( + StatusCode::SERVICE_UNAVAILABLE, + "unavailable", + "The delivery counts couldn't be read. Try again in a minute.", + ) + })?; + let mut rows = BTreeMap::new(); + merge_rows(&mut rows, own); + merge_rows(&mut rows, other); + merge_rows(&mut rows, relayed); + let mut out = build(period, &p, &rows, &sel, &metas, &stats.unwrap_or_default()); + out.backfill.complete = own_done && unrouted_done; + Ok(Json(out)) +} + +/// The hosted relay's rollups for one install, between two rollup sort +/// keys: what `POST /hybrid/deliveries/rollups` answers. Counts the install's +/// older relay records first, a few seconds' worth. +pub async fn install_rollups(state: &AppState, pk: &str, from: &str, to: &str) -> Value { + let ok_key = |k: &str| k.starts_with(DAY_PREFIX) || k.starts_with(HOUR_PREFIX); + if !ok_key(from) || !ok_key(to) || from > to { + return json!({ "buckets": [] }); + } + ensure_backfilled( + state, + pk, + false, + std::time::Instant::now() + BACKFILL_BUDGET, + ) + .await; + let rows = store(state).read(pk, from, to).await.unwrap_or_default(); + json!({ + "buckets": rows + .into_iter() + .map(|(sk, c)| json!({ "sk": sk, "counters": relay_only(c) })) + .collect::>(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use common::deliveries::{Attempt, Direction, Status}; + + fn t(s: &str) -> DateTime { + DateTime::parse_from_rfc3339(s).unwrap().with_timezone(&Utc) + } + + #[test] + fn periods_cover_themselves_and_the_one_before() { + let now = t("2026-10-26T15:42:10Z"); + let day = plan(Period::Day, now); + assert!(day.hourly); + assert_eq!(day.current.len(), 24); + assert_eq!(day.current.last().unwrap(), &t("2026-10-26T15:00:00Z")); + assert_eq!(day.current.first().unwrap(), &t("2026-10-25T16:00:00Z")); + assert_eq!(day.previous.last().unwrap(), &t("2026-10-25T15:00:00Z")); + assert_eq!(day.previous.first().unwrap(), &t("2026-10-24T16:00:00Z")); + let week = plan(Period::Week, now); + assert!(!week.hourly); + assert_eq!(week.current.first().unwrap(), &t("2026-10-20T00:00:00Z")); + assert_eq!(week.current.last().unwrap(), &t("2026-10-26T00:00:00Z")); + assert_eq!(week.previous.first().unwrap(), &t("2026-10-13T00:00:00Z")); + assert_eq!(week.previous.len(), 7); + let month = plan(Period::Month, now); + assert_eq!(month.current.len(), 30); + assert_eq!(month.previous.first().unwrap(), &t("2026-08-28T00:00:00Z")); + // 60 days of daily rollups fit in what is kept. + const { assert!(60 < rollup::DAY_RETENTION_DAYS) }; + const { assert!(48 < rollup::HOUR_RETENTION_HOURS) }; + assert_eq!(Period::parse(None), Some(Period::Week)); + assert_eq!(Period::parse(Some("90d")), None); + assert_eq!(StatusSel::parse(Some("pending")), None); + } + + fn delivery(at: &str, source: &str, dir: Direction, status: Status, ms: u64) -> Delivery { + let mut d = Delivery::new(dir, source, "pull_request.opened", "x"); + d.created_at = at.into(); + d.status = status; + d.duration_ms = ms; + if status == Status::Failed { + d.reason = "handler_error".into(); + } + d + } + + /// Rows as the write path makes them, through the in-memory store. + fn rows_of(pk: &str, ds: &[Delivery], now: DateTime) -> BTreeMap { + let m = rollup::Memory::default(); + let rt = tokio::runtime::Builder::new_current_thread() + .enable_time() + .build() + .unwrap(); + rt.block_on(async { + for d in ds { + rollup::apply_at(&m, pk, None, d, now).await; + } + let mut rows = BTreeMap::new(); + merge_rows( + &mut rows, + m.read(pk, "DELIVERY_ROLLUP#", "DELIVERY_ROLLUP#~") + .await + .unwrap(), + ); + rows + }) + } + + fn all() -> Selection { + Selection { + source: None, + status: StatusSel::All, + endpoint: None, + } + } + + #[test] + fn the_week_adds_up_and_compares_with_the_week_before() { + let now = t("2026-10-26T15:00:00Z"); + let mut ds = vec![]; + for i in 0..18 { + ds.push(delivery( + "2026-10-26T09:00:00Z", + "github", + Direction::Inbound, + Status::Handled, + 100 + i, + )); + } + ds.push(delivery( + "2026-10-26T09:00:00Z", + "github", + Direction::Inbound, + Status::Ignored, + 0, + )); + ds.push(delivery( + "2026-10-24T09:00:00Z", + "github", + Direction::Inbound, + Status::Failed, + 900, + )); + for _ in 0..5 { + ds.push(delivery( + "2026-10-15T09:00:00Z", + "slack", + Direction::Outbound, + Status::Handled, + 300, + )); + } + ds.push(delivery( + "2026-10-15T09:00:00Z", + "slack", + Direction::Outbound, + Status::Failed, + 300, + )); + // Before the previous week: left out. + ds.push(delivery( + "2026-10-01T09:00:00Z", + "slack", + Direction::Outbound, + Status::Failed, + 300, + )); + let rows = rows_of("TEAM#1", &ds, now); + let p = plan(Period::Week, now); + let a = build(Period::Week, &p, &rows, &all(), &[], &[]); + assert_eq!(a.summary.deliveries, 20); + assert_eq!( + (a.summary.handled, a.summary.ignored, a.summary.failed), + (18, 1, 1) + ); + assert_eq!(a.summary.success_rate, Some(0.95)); + assert_eq!(a.previous.deliveries, 6); + assert_eq!(a.previous.success_rate, Some(0.8333)); + assert_eq!(a.series.len(), 7); + assert_eq!(a.series[6].deliveries, 19, "today"); + assert_eq!(a.series[4].failed, 1, "two days ago"); + assert_eq!( + a.series[2].previous_deliveries, 6, + "Oct 22 lines up with Oct 15" + ); + assert_eq!(a.from, "2026-10-20T00:00:00Z"); + assert_eq!(a.to, "2026-10-27T00:00:00Z"); + assert_eq!(a.previous_to, "2026-10-20T00:00:00Z"); + assert_eq!( + a.sources.len(), + 1, + "only sources with deliveries in the period" + ); + assert_eq!(a.sources[0].source, "github"); + assert_eq!(a.sources[0].direction, "inbound"); + assert_eq!(a.seen_sources, vec!["github", "slack"]); + assert_eq!(a.reasons.len(), 1); + assert_eq!(a.reasons[0].code, "handler_error"); + assert_eq!(a.reasons[0].count, 1); + assert_eq!(a.reasons[0].previous_count, 1); + assert_eq!(a.reasons[0].sources, vec!["github"]); + assert!(a.reasons[0].message.ends_with('.')); + assert_eq!(a.events[0].event, "pull_request.opened"); + // Latency: 18 in (100, 200], one in (750, 1000]; the ignored one wasn't timed. + assert_eq!(a.summary.p50_ms, Some(150)); + assert!(a.summary.p95_ms.unwrap() > 750, "{:?}", a.summary.p95_ms); + assert_eq!(a.summary.retries, Some(0)); + } + + #[test] + fn filters_narrow_every_number() { + let now = t("2026-10-26T15:00:00Z"); + let mut ok = delivery( + "2026-10-26T10:00:00Z", + "webhook", + Direction::Outbound, + Status::Handled, + 400, + ); + ok.endpoint_id = "ep_a".into(); + ok.attempts = vec![Attempt::default(), Attempt::default(), Attempt::default()]; + let mut bad = delivery( + "2026-10-26T10:00:00Z", + "webhook", + Direction::Outbound, + Status::Failed, + 9_000, + ); + bad.endpoint_id = "ep_b".into(); + bad.reason = "webhook_timeout".into(); + bad.attempts = vec![Attempt::default(), Attempt::default()]; + let gh = delivery( + "2026-10-26T10:00:00Z", + "github", + Direction::Inbound, + Status::Handled, + 50, + ); + let rows = rows_of("TEAM#1", &[ok, bad, gh], now); + let p = plan(Period::Day, now); + + let a = build(Period::Day, &p, &rows, &all(), &[], &[]); + assert_eq!(a.summary.deliveries, 3); + assert_eq!( + (a.summary.retried, a.summary.retried_ok, a.summary.retries), + (2, 1, Some(3)) + ); + assert_eq!(a.granularity, "hour"); + assert_eq!(a.series.len(), 24); + assert_eq!(a.series.iter().map(|s| s.deliveries).sum::(), 3); + + let failed = Selection { + status: StatusSel::Failed, + ..all() + }; + let f = build(Period::Day, &p, &rows, &failed, &[], &[]); + assert_eq!((f.summary.deliveries, f.summary.failed), (1, 1)); + assert_eq!( + (f.summary.retried, f.summary.retried_ok, f.summary.retries), + (1, 0, None) + ); + assert_eq!( + f.summary.p50_ms, + Some(10_000), + "only the failed one's latency (its bucket's top)" + ); + assert_eq!(f.summary.success_rate, Some(0.0)); + + let okay = Selection { + status: StatusSel::Ok, + ..all() + }; + let o = build(Period::Day, &p, &rows, &okay, &[], &[]); + assert_eq!((o.summary.deliveries, o.summary.failed), (2, 0)); + assert!(o.reasons.is_empty()); + + let gh_only = Selection { + source: Some("github".into()), + ..all() + }; + let g = build(Period::Day, &p, &rows, &gh_only, &[], &[]); + assert_eq!(g.summary.deliveries, 1); + assert!( + g.endpoints.is_empty(), + "endpoints hide when another source is chosen" + ); + + let one = Selection { + endpoint: Some("ep_b".into()), + ..all() + }; + let e = build(Period::Day, &p, &rows, &one, &[], &[]); + assert_eq!((e.summary.deliveries, e.summary.failed), (1, 1)); + assert_eq!(e.reasons[0].code, "webhook_timeout"); + assert_eq!(e.reasons[0].sources, vec!["webhook"]); + } + + #[test] + fn endpoints_show_rates_streaks_and_whether_they_are_on() { + let now = t("2026-10-26T15:00:00Z"); + let mut ds = vec![]; + for i in 0..4 { + let mut d = delivery( + "2026-10-26T10:00:00Z", + "webhook", + Direction::Outbound, + if i == 0 { + Status::Failed + } else { + Status::Handled + }, + 300, + ); + d.endpoint_id = "ep_on".into(); + if i == 0 { + d.reason = "webhook_server_error".into(); + } + ds.push(d); + } + let mut gone = delivery( + "2026-10-25T10:00:00Z", + "webhook", + Direction::Outbound, + Status::Failed, + 0, + ); + gone.endpoint_id = "ep_gone".into(); + ds.push(gone); + let rows = rows_of("TEAM#1", &ds, now); + let metas = vec![ + EndpointMeta { + id: "ep_on".into(), + url: "https://hooks.example.com/a".into(), + enabled: true, + ..Default::default() + }, + EndpointMeta { + id: "ep_off".into(), + url: "https://hooks.example.com/b".into(), + enabled: false, + disabled_reason: "failing".into(), + failing_since: Some("2026-10-20T00:00:00Z".into()), + ..Default::default() + }, + ]; + let stats = vec![EndpointStat { + endpoint_id: "ep_off".into(), + streak: 40, + last_failure_at: Some("2026-10-26T01:00:00Z".into()), + last_failure_reason: Some("webhook_unreachable".into()), + ..Default::default() + }]; + let a = build( + Period::Week, + &plan(Period::Week, now), + &rows, + &all(), + &metas, + &stats, + ); + let ids: Vec<&str> = a.endpoints.iter().map(|e| e.id.as_str()).collect(); + assert_eq!( + ids, + vec!["ep_off", "ep_on", "ep_gone"], + "the longest streak first, then failures, then volume" + ); + let off = &a.endpoints[0]; + assert!(!off.enabled && off.disabled_reason == "failing" && !off.deleted); + assert_eq!(off.deliveries, 0, "no traffic while off"); + assert_eq!(off.success_rate, None); + assert_eq!(off.streak, 40); + assert!(off.last_failure_message.is_some()); + assert_eq!(off.failing_since.as_deref(), Some("2026-10-20T00:00:00Z")); + let gone = &a.endpoints[2]; + assert!(gone.deleted && gone.url.is_empty()); + let on = &a.endpoints[1]; + assert_eq!((on.deliveries, on.ok, on.failed), (4, 3, 1)); + assert_eq!(on.success_rate, Some(0.75)); + assert_eq!(on.p50_ms, Some(250)); + } + + #[test] + fn empty_periods_read_as_nothing_not_zero_percent() { + let now = t("2026-10-26T15:00:00Z"); + let a = build( + Period::Month, + &plan(Period::Month, now), + &BTreeMap::new(), + &all(), + &[], + &[], + ); + assert_eq!( + a.summary, + Totals { + retries: Some(0), + ..Default::default() + } + ); + assert_eq!(a.summary.success_rate, None); + assert_eq!(a.series.len(), 30); + assert!(a.series.iter().all(|s| s.success_rate.is_none())); + assert!(a.sources.is_empty() && a.reasons.is_empty() && a.endpoints.is_empty()); + } + + #[test] + fn a_team_reads_only_its_own_rollups() { + let now = t("2026-10-26T15:00:00Z"); + let a_rows = rows_of( + "TEAM#a", + &[delivery( + "2026-10-26T10:00:00Z", + "email", + Direction::Outbound, + Status::Failed, + 10, + )], + now, + ); + let b_rows = rows_of("TEAM#b", &[], now); + let p = plan(Period::Week, now); + assert_eq!( + build(Period::Week, &p, &a_rows, &all(), &[], &[]) + .summary + .deliveries, + 1 + ); + assert_eq!( + build(Period::Week, &p, &b_rows, &all(), &[], &[]) + .summary + .deliveries, + 0 + ); + } + + #[test] + fn an_install_adds_only_the_relays_counters_from_coderhelm() { + let v = json!({"buckets": [ + {"sk": "DELIVERY_ROLLUP#D#2026-10-26", "counters": {"s#relay#out#handled": 4, "s#github#in#handled": 99, "s#broker#out#failed": 1}}, + {"sk": "TEAM#x", "counters": {"s#relay#out#handled": 1}}, + {"sk": "DELIVERY_ROLLUP#D#2026-10-25"} + ]}); + let rows = parse_relayed(&v); + assert_eq!(rows.len(), 1); + assert_eq!( + rows[0].1, + Counters::from([ + ("s#relay#out#handled".into(), 4), + ("s#broker#out#failed".into(), 1) + ]) + ); + let mut all_rows = BTreeMap::new(); + merge_rows( + &mut all_rows, + vec![( + "DELIVERY_ROLLUP#D#2026-10-26".into(), + Counters::from([("s#relay#out#handled".into(), 1)]), + )], + ); + merge_rows(&mut all_rows, rows); + assert_eq!( + all_rows["DELIVERY_ROLLUP#D#2026-10-26"]["s#relay#out#handled"], + 5 + ); + } + + #[test] + fn endpoint_items_are_read_without_their_secrets() { + let s = |v: &str| AttributeValue::S(v.into()); + let item = HashMap::from([ + ("sk".to_string(), s("WEBHOOK_ENDPOINT#ep_1")), + ("id".to_string(), s("ep_1")), + ("url".to_string(), s("https://hooks.example.com/x")), + ("enabled".to_string(), AttributeValue::Bool(true)), + ("secret_sealed".to_string(), s("sealed")), + ("failing_since".to_string(), s("")), + ]); + let m = endpoint_meta(&item).unwrap(); + assert_eq!( + (m.id.as_str(), m.enabled, m.failing_since.as_deref()), + ("ep_1", true, None) + ); + assert!(!format!("{m:?}").contains("sealed")); + let mut other = item.clone(); + other.insert("sk".into(), s("DELIVERY#1")); + assert!(endpoint_meta(&other).is_none()); + } + + #[test] + fn jira_log_items_map_like_the_list() { + let s = |v: &str| AttributeValue::S(v.into()); + let item = HashMap::from([ + ("team_id".to_string(), s("TEAM#1")), + ("event_id".to_string(), s("01J")), + ("event_type".to_string(), s("issue_updated")), + ("status".to_string(), s("token_limit")), + ("created_at".to_string(), s("2026-10-26T10:00:00Z")), + ("expires_at".to_string(), AttributeValue::N("1".into())), + ]); + let d = jira_item_to_delivery(&item).unwrap(); + assert_eq!( + (d.source.as_str(), d.status, d.reason.as_str()), + ("jira", Status::Failed, "jira_limit") + ); + } +} diff --git a/services/gateway/src/routes/hybrid.rs b/services/gateway/src/routes/hybrid.rs index cb348f0cb..41db4985b 100644 --- a/services/gateway/src/routes/hybrid.rs +++ b/services/gateway/src/routes/hybrid.rs @@ -2024,6 +2024,36 @@ pub async fn list_deliveries( Ok(Json(json!({ "deliveries": own }))) } +/// POST /hybrid/deliveries/rollups (signed) `{from, to}`: this install's +/// relay and broker counters between two rollup sort keys, for its own +/// Deliveries overview. A POST so the signature covers the range. +pub async fn rollups( + State(state): State>, + method: Method, + uri: Uri, + headers: HeaderMap, + body: Bytes, +) -> Reply { + let install = signed(&state, &headers, &method, &uri, &body).await?; + let b = body_json(&body); + let (Some(from), Some(to)) = (b["from"].as_str(), b["to"].as_str()) else { + return Err(fail( + StatusCode::BAD_REQUEST, + "bad_request", + "Send {from, to}.", + )); + }; + Ok(Json( + super::deliveries_analytics::install_rollups( + &state, + &relay::install_pk(&install.id), + from, + to, + ) + .await, + )) +} + /// POST /hybrid/deliveries/:id/redeliver (signed): forward a held event again. pub async fn redeliver( State(state): State>, diff --git a/services/gateway/src/routes/jira_webhook.rs b/services/gateway/src/routes/jira_webhook.rs index 11967220b..315a98f44 100644 --- a/services/gateway/src/routes/jira_webhook.rs +++ b/services/gateway/src/routes/jira_webhook.rs @@ -1236,9 +1236,30 @@ async fn log_jira_event( if let Some(r) = repo { put = put.item("repo", attr_s(r)); } + // Counted by the Deliveries overview as it is written. + put = put.item( + common::deliveries_rollup::ROLLED, + aws_sdk_dynamodb::types::AttributeValue::N("1".into()), + ); if let Err(e) = put.send().await { error!("Failed to log Jira event: {e}"); + return; + } + let logged = serde_json::json!({ + "event_id": event_id, + "event_type": event_type, + "ticket_key": ticket_key, + "status": status, + "created_at": now, + "repo": repo.unwrap_or(""), + }); + if let Some(d) = super::deliveries::jira_to_delivery(&logged) { + let store = common::deliveries_rollup::Dynamo { + client: &state.dynamo, + table: &state.config.settings_table_name, + }; + common::deliveries_rollup::apply(&store, team_id, None, &d).await; } } diff --git a/services/gateway/src/routes/mod.rs b/services/gateway/src/routes/mod.rs index 09d688c88..7509c0926 100644 --- a/services/gateway/src/routes/mod.rs +++ b/services/gateway/src/routes/mod.rs @@ -16,6 +16,7 @@ pub mod chat_policy; pub mod connectors; pub mod data_sources; pub mod deliveries; +pub mod deliveries_analytics; pub mod dlq; pub mod email; pub mod github;