1use std::collections::HashMap;
51use std::sync::Arc;
52use std::time::Duration;
53
54use adk_core::GovernanceControl;
55use adk_core::run_store::{DurableRunStore, Enqueued, NewRun, OnConflict, RunFilter, RunState};
56use adk_core::webhook::{VerifiedWebhook, WebhookHeaders, WebhookVerifier};
57use axum::Json;
58use axum::Router;
59use axum::body::Bytes;
60use axum::extract::{DefaultBodyLimit, Path, State};
61use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
62use axum::response::{IntoResponse, Response};
63use axum::routing::post;
64use serde::Serialize;
65use serde_json::{Value, json};
66
67pub const DEFAULT_HOOK_BODY_LIMIT: usize = 1024 * 1024;
69
70#[derive(Debug, Clone, Copy)]
72pub struct HookDelivery<'a> {
73 pub hook: &'a str,
75 pub webhook: &'a VerifiedWebhook,
77 pub payload: &'a Value,
79}
80
81type HookMapper = Arc<dyn Fn(&HookDelivery<'_>) -> adk_core::Result<NewRun> + Send + Sync>;
82
83#[derive(Clone)]
94pub struct WebhookHook {
95 name: String,
96 verifier: HookAuth,
97 queue: String,
98 app_name: String,
99 target: String,
100 user_id: String,
101 session_id: Option<String>,
102 input: Option<Value>,
103 concurrency_key: Option<(String, OnConflict)>,
104 max_attempts: u32,
105 max_pending: Option<usize>,
106 mapper: Option<HookMapper>,
107}
108
109impl std::fmt::Debug for WebhookHook {
110 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111 f.debug_struct("WebhookHook")
112 .field("name", &self.name)
113 .field("queue", &self.queue)
114 .field("app_name", &self.app_name)
115 .field("target", &self.target)
116 .field("max_pending", &self.max_pending)
117 .finish_non_exhaustive()
118 }
119}
120
121#[derive(Clone)]
123enum HookAuth {
124 Standard(WebhookVerifier),
125 Forge(super::forge::ForgeSignature),
126}
127
128impl WebhookHook {
129 pub fn forge(
143 name: impl Into<String>,
144 signature: super::forge::ForgeSignature,
145 app_name: impl Into<String>,
146 target: impl Into<String>,
147 ) -> Self {
148 Self::with_auth(name, HookAuth::Forge(signature), app_name, target)
149 }
150
151 pub fn new(
154 name: impl Into<String>,
155 verifier: WebhookVerifier,
156 app_name: impl Into<String>,
157 target: impl Into<String>,
158 ) -> Self {
159 Self::with_auth(name, HookAuth::Standard(verifier), app_name, target)
160 }
161
162 fn with_auth(
163 name: impl Into<String>,
164 verifier: HookAuth,
165 app_name: impl Into<String>,
166 target: impl Into<String>,
167 ) -> Self {
168 let name = name.into();
169 Self {
170 user_id: format!("webhook:{name}"),
171 name,
172 verifier,
173 queue: "default".to_string(),
174 app_name: app_name.into(),
175 target: target.into(),
176 session_id: None,
177 input: None,
178 concurrency_key: None,
179 max_attempts: NewRun::DEFAULT_MAX_ATTEMPTS,
180 max_pending: None,
181 mapper: None,
182 }
183 }
184
185 pub fn name(&self) -> &str {
187 &self.name
188 }
189
190 pub fn with_queue(mut self, queue: impl Into<String>) -> Self {
192 self.queue = queue.into();
193 self
194 }
195
196 pub fn with_user_id(mut self, template: impl Into<String>) -> Self {
198 self.user_id = template.into();
199 self
200 }
201
202 pub fn with_session_id(mut self, template: impl Into<String>) -> Self {
204 self.session_id = Some(template.into());
205 self
206 }
207
208 pub fn with_input_template(mut self, template: Value) -> Self {
210 self.input = Some(template);
211 self
212 }
213
214 pub fn with_concurrency_key(
217 mut self,
218 template: impl Into<String>,
219 on_conflict: OnConflict,
220 ) -> Self {
221 self.concurrency_key = Some((template.into(), on_conflict));
222 self
223 }
224
225 pub fn with_max_attempts(mut self, max_attempts: u32) -> Self {
227 self.max_attempts = max_attempts;
228 self
229 }
230
231 pub fn with_max_pending(mut self, max_pending: usize) -> Self {
233 self.max_pending = Some(max_pending);
234 self
235 }
236
237 pub fn with_mapper(
240 mut self,
241 mapper: impl Fn(&HookDelivery<'_>) -> adk_core::Result<NewRun> + Send + Sync + 'static,
242 ) -> Self {
243 self.mapper = Some(Arc::new(mapper));
244 self
245 }
246
247 pub fn idempotency_key(hook: &str, webhook_id: &str) -> String {
255 format!("hook:{hook}:{webhook_id}")
256 }
257
258 fn map(&self, delivery: &HookDelivery<'_>) -> Result<NewRun, String> {
259 let mut run = match &self.mapper {
260 Some(mapper) => mapper(delivery).map_err(|error| error.message.clone())?,
261 None => {
262 let context = json!({
263 "payload": delivery.payload,
264 "webhook": {
265 "id": delivery.webhook.id,
266 "timestamp": delivery.webhook.timestamp.to_rfc3339(),
267 },
268 "hook": { "name": self.name },
269 });
270 let text = |field: &str, template: &str| {
271 let rendered = render_key(template, &context)
272 .map_err(|reason| format!("{field} template `{template}`: {reason}"))?;
273 if rendered.trim().is_empty() {
274 Err(format!("{field} template `{template}` rendered empty"))
275 } else {
276 Ok(rendered)
277 }
278 };
279 let input = match &self.input {
280 Some(template) => render(template, &context),
281 None => delivery.payload.clone(),
282 };
283 let mut run = NewRun::new(
284 self.queue.clone(),
285 self.app_name.clone(),
286 text("userId", &self.user_id)?,
287 self.target.clone(),
288 input,
289 )
290 .with_max_attempts(self.max_attempts);
291 if let Some(template) = &self.session_id {
292 run = run.with_session_id(text("sessionId", template)?);
293 }
294 if let Some((template, on_conflict)) = &self.concurrency_key {
295 run = run.with_concurrency_key(text("concurrencyKey", template)?, *on_conflict);
296 }
297 run
298 }
299 };
300 run.idempotency_key = Some(Self::idempotency_key(&self.name, &delivery.webhook.id));
301 run.validate().map_err(|error| error.message)?;
302 Ok(run.with_service_subject())
303 }
304}
305
306fn render(template: &Value, context: &Value) -> Value {
308 match template {
309 Value::String(text) => {
310 let trimmed = text.trim();
311 if let Some(pointer) =
312 trimmed.strip_prefix("{{").and_then(|rest| rest.strip_suffix("}}"))
313 && !pointer.contains("{{")
314 {
315 return context.pointer(pointer.trim()).cloned().unwrap_or(Value::Null);
316 }
317 Value::String(render_text(text, context))
318 }
319 Value::Array(items) => {
320 Value::Array(items.iter().map(|item| render(item, context)).collect())
321 }
322 Value::Object(map) => Value::Object(
323 map.iter().map(|(key, value)| (key.clone(), render(value, context))).collect(),
324 ),
325 other => other.clone(),
326 }
327}
328
329fn render_text(template: &str, context: &Value) -> String {
332 render_placeholders(template, context, false).unwrap_or_default()
333}
334
335fn render_key(template: &str, context: &Value) -> Result<String, String> {
338 render_placeholders(template, context, true)
339}
340
341fn render_placeholders(template: &str, context: &Value, strict: bool) -> Result<String, String> {
342 let mut out = String::with_capacity(template.len());
343 let mut rest = template;
344 while let Some(start) = rest.find("{{") {
345 let Some(len) = rest[start + 2..].find("}}") else { break };
346 out.push_str(&rest[..start]);
347 let pointer = rest[start + 2..start + 2 + len].trim();
348 match context.pointer(pointer) {
349 Some(Value::String(text)) => out.push_str(text),
350 Some(Value::Null) | None if strict => {
351 return Err(format!("`{pointer}` is missing from the delivery"));
352 }
353 Some(Value::Null) | None => {}
354 Some(other) => out.push_str(&other.to_string()),
355 }
356 rest = &rest[start + 2 + len + 2..];
357 }
358 out.push_str(rest);
359 Ok(out)
360}
361
362#[derive(Clone)]
364pub struct WebhookIngress {
365 store: Arc<dyn DurableRunStore>,
366 hooks: Arc<HashMap<String, WebhookHook>>,
367 governance: Option<GovernanceControl>,
368 retry_after: Duration,
369 body_limit: usize,
370}
371
372impl std::fmt::Debug for WebhookIngress {
373 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
374 f.debug_struct("WebhookIngress")
375 .field("hooks", &self.hooks.keys().collect::<Vec<_>>())
376 .field("retry_after", &self.retry_after)
377 .field("body_limit", &self.body_limit)
378 .finish_non_exhaustive()
379 }
380}
381
382impl WebhookIngress {
383 pub fn new(store: Arc<dyn DurableRunStore>) -> Self {
385 Self {
386 store,
387 hooks: Arc::new(HashMap::new()),
388 governance: None,
389 retry_after: Duration::from_secs(30),
390 body_limit: DEFAULT_HOOK_BODY_LIMIT,
391 }
392 }
393
394 pub fn with_hook(mut self, hook: WebhookHook) -> Self {
396 Arc::make_mut(&mut self.hooks).insert(hook.name.clone(), hook);
397 self
398 }
399
400 pub fn with_governance(mut self, governance: GovernanceControl) -> Self {
406 self.governance = Some(governance);
407 self
408 }
409
410 pub fn with_retry_after(mut self, retry_after: Duration) -> Self {
412 self.retry_after = retry_after;
413 self
414 }
415
416 pub fn with_body_limit(mut self, bytes: usize) -> Self {
418 self.body_limit = bytes;
419 self
420 }
421
422 pub(crate) fn has_governance(&self) -> bool {
423 self.governance.is_some()
424 }
425
426 pub fn store(&self) -> &Arc<dyn DurableRunStore> {
428 &self.store
429 }
430
431 async fn pending(
433 &self,
434 hook: &WebhookHook,
435 ) -> adk_core::Result<Vec<adk_core::run_store::RunRecord>> {
436 let prefix = format!("hook:{}:", hook.name);
437 let unfinished = self
438 .store
439 .list(RunFilter::default().queue(hook.queue.clone()).states([
440 RunState::Queued,
441 RunState::Running,
442 RunState::Waiting,
443 ]))
444 .await?;
445 Ok(unfinished
446 .into_iter()
447 .filter(|run| {
448 run.idempotency_key.as_deref().is_some_and(|key| key.starts_with(&prefix))
449 })
450 .collect())
451 }
452
453 fn retry_later(&self, status: StatusCode, code: &str, message: String) -> Response {
454 let mut response =
455 (status, Json(json!({"error": code, "message": message}))).into_response();
456 if let Ok(value) = HeaderValue::from_str(&self.retry_after.as_secs().max(1).to_string()) {
457 response.headers_mut().insert(header::RETRY_AFTER, value);
458 }
459 response
460 }
461}
462
463#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
465#[serde(rename_all = "camelCase")]
466pub struct HookAccepted {
467 pub run_id: String,
469 pub state: RunState,
471 pub duplicate: bool,
473}
474
475async fn receive(
476 State(ingress): State<WebhookIngress>,
477 Path(name): Path<String>,
478 headers: HeaderMap,
479 body: Bytes,
480) -> Response {
481 let Some(hook) = ingress.hooks.get(&name) else {
482 return (StatusCode::NOT_FOUND, Json(json!({"error": "hook.not_found"}))).into_response();
483 };
484 let lookup = |name: &'static str| headers.get(name).and_then(|v| v.to_str().ok());
485 let verified = match &hook.verifier {
486 HookAuth::Standard(verifier) => {
487 WebhookHeaders::from_lookup(lookup).and_then(|parsed| verifier.verify(&parsed, &body))
488 }
489 HookAuth::Forge(forge) => forge.verify(lookup, &body),
490 };
491 let verified = match verified {
492 Ok(verified) => verified,
493 Err(error) => {
494 tracing::warn!(hook.name = %name, error.code = error.code(), error = %error, "webhook rejected");
495 return (StatusCode::UNAUTHORIZED, Json(json!({"error": "unauthorized"})))
496 .into_response();
497 }
498 };
499 if let Some(governance) = &ingress.governance
500 && let Err(error) = governance.check()
501 {
502 tracing::info!(hook.name = %name, webhook.id = %verified.id, error.code = %error.code, "webhook refused by governance");
503 return ingress.retry_later(StatusCode::SERVICE_UNAVAILABLE, error.code, error.message);
504 }
505 if let Some(max_pending) = hook.max_pending {
506 match ingress.pending(hook).await {
507 Ok(pending) if pending.len() >= max_pending => {
508 let key = WebhookHook::idempotency_key(&hook.name, &verified.id);
510 if let Some(run) =
511 pending.iter().find(|run| run.idempotency_key.as_deref() == Some(key.as_str()))
512 {
513 return (
514 StatusCode::OK,
515 Json(HookAccepted {
516 run_id: run.run_id.clone(),
517 state: run.state,
518 duplicate: true,
519 }),
520 )
521 .into_response();
522 }
523 return ingress.retry_later(
524 StatusCode::TOO_MANY_REQUESTS,
525 "hook.max_pending",
526 format!(
527 "hook '{name}' has {} unfinished runs (max {max_pending})",
528 pending.len()
529 ),
530 );
531 }
532 Ok(_) => {}
533 Err(error) => {
534 return ingress.retry_later(
535 StatusCode::SERVICE_UNAVAILABLE,
536 error.code,
537 error.message,
538 );
539 }
540 }
541 }
542 let payload: Value = match serde_json::from_slice(&body) {
543 Ok(payload) => payload,
544 Err(error) => {
545 return (
546 StatusCode::UNPROCESSABLE_ENTITY,
547 Json(json!({"error": "hook.invalid_body", "message": format!("body is not JSON: {error}")})),
548 )
549 .into_response();
550 }
551 };
552 let delivery = HookDelivery { hook: &hook.name, webhook: &verified, payload: &payload };
553 let run = match hook.map(&delivery) {
554 Ok(run) => run,
555 Err(message) => {
556 return (
557 StatusCode::UNPROCESSABLE_ENTITY,
558 Json(json!({"error": "hook.mapping_failed", "message": message})),
559 )
560 .into_response();
561 }
562 };
563 match ingress.store.enqueue(run).await {
564 Ok(Enqueued::Created(record)) => {
565 tracing::info!(hook.name = %name, webhook.id = %verified.id, run.id = %record.run_id, "webhook woke a run");
566 (
567 StatusCode::ACCEPTED,
568 Json(HookAccepted { run_id: record.run_id, state: record.state, duplicate: false }),
569 )
570 .into_response()
571 }
572 Ok(Enqueued::Existing(record)) => {
573 tracing::info!(hook.name = %name, webhook.id = %verified.id, run.id = %record.run_id, "webhook redelivery matched an existing run");
574 (
575 StatusCode::OK,
576 Json(HookAccepted { run_id: record.run_id, state: record.state, duplicate: true }),
577 )
578 .into_response()
579 }
580 Ok(Enqueued::Rejected { blocking_run_id }) => (
581 StatusCode::CONFLICT,
582 Json(json!({"error": "hook.concurrency_conflict", "blockingRunId": blocking_run_id})),
583 )
584 .into_response(),
585 Err(error) => {
586 tracing::warn!(hook.name = %name, webhook.id = %verified.id, error = %error, "webhook not enqueued");
587 ingress.retry_later(StatusCode::SERVICE_UNAVAILABLE, error.code, error.message)
588 }
589 }
590}
591
592pub fn webhook_ingress_router(ingress: WebhookIngress) -> Router {
598 let limit = ingress.body_limit;
599 Router::new()
600 .route("/hooks/{name}", post(receive))
601 .layer(DefaultBodyLimit::max(limit))
602 .with_state(ingress)
603}
604
605#[cfg(test)]
606mod tests {
607 use super::*;
608
609 #[test]
610 fn templates_render_values_and_text() {
611 let context = json!({"payload": {"issue": {"number": 42, "title": "Crash"}, "tags": ["a"]}, "hook": {"name": "gh"}});
612 let rendered = render(
613 &json!({
614 "text": "Issue #{{/payload/issue/number}}: {{/payload/issue/title}}{{/payload/missing}}",
615 "tags": "{{/payload/tags}}",
616 "missing": "{{ /payload/nope }}",
617 "fixed": 3
618 }),
619 &context,
620 );
621 assert_eq!(
622 rendered,
623 json!({"text": "Issue #42: Crash", "tags": ["a"], "missing": null, "fixed": 3})
624 );
625 assert_eq!(render_text("{{/hook/name}}:{{/payload/issue/number}}", &context), "gh:42");
626 assert_eq!(render_text("unterminated {{/hook/name", &context), "unterminated {{/hook/name");
627 assert_eq!(
628 render_key("repo:{{/payload/issue/number}}", &context),
629 Ok("repo:42".to_string())
630 );
631 assert!(render_key("thread:{{/payload/thread}}", &context).is_err());
632 }
633}