encore-dev 2.0.0-beta.18

Rust SDK for Encore applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
//! Custom gateway middleware for authenticating, authorizing, rate-limiting,
//! logging, or metering public requests before they reach a service and after
//! responses return. Requires the `gateway` Cargo feature.
//!
//! A programmable gateway is hosted by a service with a `"gateway"` section in
//! its `encore.service.json`. That section accepts the same configuration as
//! `encore.gateway.json` except `name` — the gateway takes the service's name:
//!
//! ```json
//! {
//!   "name": "edge",
//!   "lang": "rust",
//!   "gateway": {}
//! }
//! ```
//!
//! The service's binary runs only the gateway and its middleware. Like any
//! Encore service, it can declare its own secrets, caches, databases, topics,
//! and configs, and call other services.
//!
//! Middleware implements the [`Middleware`] trait directly in-process with no
//! serialization or IPC boundary:
//!
//! ```ignore
//! use encore::gateway::{self, async_trait, Decision, Hooks, HookError, RequestExt, RequestView};
//! use encore::ErrCode;
//!
//! struct Auth;
//!
//! #[async_trait]
//! impl gateway::Middleware for Auth {
//!     async fn on_request(&self, req: &RequestView) -> Result<Decision, HookError> {
//!         let Some(user) = verify(req.header("authorization")).await else {
//!             return Ok(gateway::reject(ErrCode::Unauthenticated, "invalid token"));
//!         };
//!         Ok(gateway::proceed().set_header("x-user-id", user.id).into())
//!     }
//! }
//!
//! #[tokio::main]
//! async fn main() -> Result<(), gateway::Error> {
//!     gateway::serve([gateway::register("auth", Hooks::REQUEST, Auth)
//!         .matching(gateway::matcher::path_prefix("/api"))])
//!     .await
//! }
//! ```
//!
//! # Hooks
//!
//! Middleware is invoked only for the hooks enabled when calling [`register`]:
//!
//! - `on_request`: runs before forwarding the request. Lets the request
//!   continue (optionally modified via [`Decision::Continue`]) or responds
//!   immediately ([`reject`], [`respond`]).
//! - `on_request_body` and `on_response_body`: called with each body chunk for
//!   observation.
//! - `on_response`: runs before writing the response to the client, allowing
//!   header edits.
//! - `on_complete`: runs off the request path once the request finishes; ideal
//!   for logging, metrics, or billing.
//!
//! The body hooks and `on_complete` are synchronous and must not block — they
//! run inline on the gateway, and `on_complete` executes serially. Offload slow
//! work to a spawned task or channel. `on_finish` runs last for each request
//! and is where you should clean up per-request data stored in [`State`].
//!
//! Middleware only runs on requests matched by [`Registration::matching`]. The
//! gateway evaluates matchers up front so unmatched requests incur no overhead.
//! Hooks can inspect request headers, query parameters, and cookies via
//! [`RequestExt::cookie`].
//!
//! Middleware only sees public requests routed by the gateway. Service-to-service
//! calls, Pub/Sub pushes, and unexposed paths are handled directly by Encore.
//! CORS preflight requests are also handled by the gateway unless CORS is
//! disabled (`"cors": false`), in which case preflights route like normal
//! requests.
//!
//! # Handling requests and errors
//!
//! `on_request` returns `Ok(Decision)` to either forward or answer a request.
//! Returning `Err`, panicking, or timing out fails the hook; the middleware's
//! [`OnError`] policy then determines the outcome ([`OnError::FailClosed`]
//! rejects the request, while [`OnError::FailOpen`] forwards it).
//!
//! # Request Context
//!
//! `on_request` can attach [`reqctx`](crate::reqctx) fields to forwarded
//! requests with [`ContinueExt::set_field`]. Downstream middleware, the target
//! service, and any services it calls with the request context can read those
//! fields using `CURRENT_USER.get()`. External clients cannot spoof Request
//! Context fields.
//!
//! ```ignore
//! static CURRENT_USER: reqctx::Field<User> = reqctx::Field::new("user");
//!
//! #[async_trait]
//! impl gateway::Middleware for Auth {
//!     async fn on_request(&self, req: &RequestView) -> Result<Decision, HookError> {
//!         let Some(user) = verify(req.header("authorization")).await else {
//!             return Ok(gateway::reject(ErrCode::Unauthenticated, "invalid token"));
//!         };
//!         Ok(gateway::proceed().set_field(&CURRENT_USER, &user)?.into())
//!     }
//! }
//! ```
//!
//! Every hook runs within the request's context, so
//! [`Field::get`](crate::reqctx::Field::get) returns fields set by earlier
//! middleware. In `on_response` and the body hooks, this also includes fields
//! set by this middleware's own `on_request`; in `on_complete`, it reflects the
//! final forwarded context.
//!
//! # Tracing
//!
//! While a hook runs, the request's trace and Request Context are active as
//! [`opentelemetry::Context::current`](crate::opentelemetry::Context::current).
//! Spans started in the hook join the request trace and inherit fields marked
//! with [`trace`](crate::reqctx::Field::trace), infrastructure operations are
//! traced automatically, and outbound service calls propagate the Request
//! Context.

use std::collections::{BTreeMap, HashMap};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use bytes::Bytes;
use encore_gateway::program::ProgramEnv;
use encore_sdk_core::reqctx::Values;
use encore_sdk_core::telemetry::{SpanContext, SpanContextExt};
use opentelemetry::trace::{FutureExt as _, TraceContextExt as _};
use opentelemetry::Context;
use serde::de::DeserializeOwned;
use serde::Serialize;

use crate::opentelemetry;
use crate::reqctx::Field;
use crate::ErrCode;

pub use async_trait::async_trait;
pub use encore_gateway::middleware::{
    cookies, AttributeValue, Completed, Cond, Continue, Decision, FieldMatch, HeaderEdit, Hook,
    HookError, Hooks, Match, Middleware, OnError, PathMatch, Rejection, RequestId, RequestView,
    ResponseView, RouteMatch, REJECTED_BY_GATEWAY,
};

/// Error returned when the gateway cannot be served (for example, the process
/// was not launched as a gateway program, a middleware registration is invalid,
/// or the gateway is already running).
#[derive(Debug, Clone)]
pub struct Error(String);

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for Error {}

/// A registered middleware with its name, enabled hooks, matcher, and error
/// policy, passed to [`serve`].
pub struct Registration {
    name: String,
    hooks: Hooks,
    matches: Option<Match>,
    timeout: Duration,
    on_error: OnError,
    handler: Arc<dyn Middleware>,
}

/// Registers `handler` under `name` for the specified `hooks` (for example,
/// `Hooks::REQUEST | Hooks::COMPLETE`).
///
/// The handler is only invoked for the hooks listed here. `name` must be
/// kebab-case and unique within the gateway; it identifies the middleware in
/// logs, traces, and [`Completed::rejected_by`].
pub fn register(name: impl Into<String>, hooks: Hooks, handler: impl Middleware) -> Registration {
    Registration {
        name: name.into(),
        hooks,
        matches: None,
        timeout: encore_gateway::middleware::MiddlewareSpec::DEFAULT_TIMEOUT,
        on_error: OnError::default(),
        handler: Arc::new(handler),
    }
}

impl Registration {
    /// Restricts this middleware to requests matching `m`. By default, the
    /// middleware runs on every request. See [`matcher`].
    pub fn matching(mut self, m: Match) -> Self {
        self.matches = Some(m);
        self
    }

    /// Sets the timeout for `on_request` and `on_response` hooks (defaults to
    /// 5 seconds).
    ///
    /// If a hook times out, the gateway applies the middleware's [`OnError`]
    /// policy (returning 503 when failing closed).
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Sets the behavior when `on_request` fails, panics, or times out.
    /// Defaults to [`OnError::FailClosed`].
    pub fn on_error(mut self, on_error: OnError) -> Self {
        self.on_error = on_error;
        self
    }

    /// The registration as the Gateway Core takes it: shown everything of a
    /// request, cookies parsed only as a hook asks for one, and called with
    /// the request's trace.
    fn spec(self, mark: bool) -> encore_gateway::middleware::MiddlewareSpec {
        use encore_gateway::middleware::{Interest, MiddlewareSpec, ReadSet, Reads};
        // A Middleware taking a later hook without `request` is called at
        // `request` too, for its trace, as the SDK core's host is.
        let remembers = [Hook::RequestBody, Hook::Response, Hook::ResponseBody]
            .into_iter()
            .any(|hook| self.hooks.contains(hook.into()));
        let observes = remembers && !self.hooks.contains(Hooks::REQUEST);
        let interest = Interest {
            hooks: if observes {
                self.hooks | Hooks::REQUEST
            } else {
                self.hooks
            },
            matches: self.matches,
            reads: Reads {
                headers: ReadSet::All,
                query: ReadSet::All,
                cookies: ReadSet::Names(Vec::new()),
                response_headers: ReadSet::All,
            },
        };
        let traced = Traced {
            inner: self.handler,
            observes,
            remembers,
            mark,
            contexts: Mutex::new(HashMap::new()),
        };
        let mut spec = MiddlewareSpec::new(self.name, interest, Arc::new(traced));
        spec.timeout = self.timeout;
        spec.on_error = self.on_error;
        spec
    }
}

/// A Middleware, called with its request's trace and Request Context as the
/// current context.
struct Traced {
    inner: Arc<dyn Middleware>,
    /// Whether it takes no `request` hook, and is called at it only to learn
    /// the request's trace.
    observes: bool,
    /// Whether it keeps the context for later hooks, which are shown only the
    /// request's id.
    remembers: bool,
    /// Whether the trace carries the propagation mark (encore_gateway ADR
    /// 0003), as every request Encore hands a service's code does.
    mark: bool,
    contexts: Mutex<HashMap<RequestId, Context>>,
}

impl Traced {
    /// The context `req`'s hooks run in: its trace, and the Request Context
    /// fields it has.
    fn context_of(&self, req: &RequestView) -> Context {
        let cx = self.trace_of(req);
        if req.context.is_empty() {
            return cx;
        }
        Values::from_map(req.context.iter().cloned().collect()).in_context(&cx)
    }

    fn trace_of(&self, req: &RequestView) -> Context {
        let Some(trace) = &req.trace else {
            return Context::new();
        };
        let tracestate = if self.mark {
            Some(encore_telemetry::propagation::with_mark(
                trace.tracestate.as_deref(),
                !req.context.is_empty(),
            ))
        } else {
            trace.tracestate.clone()
        };
        match SpanContext::parse_traceparent(&trace.traceparent, tracestate.as_deref()) {
            Some(sc) => Context::new().with_remote_span_context(sc),
            None => Context::new(),
        }
    }

    fn remember(&self, req: RequestId, cx: Context) {
        self.contexts
            .lock()
            .expect("contexts lock poisoned")
            .insert(req, cx);
    }

    fn remembered(&self, req: RequestId) -> Context {
        self.contexts
            .lock()
            .expect("contexts lock poisoned")
            .get(&req)
            .cloned()
            .unwrap_or_default()
    }
}

#[allow(clippy::double_must_use)]
#[async_trait]
impl Middleware for Traced {
    async fn on_request(&self, req: &RequestView) -> Result<Decision, HookError> {
        let cx = self.context_of(req);
        if self.remembers {
            self.remember(req.id, cx.clone());
        }
        if self.observes {
            return Ok(Decision::proceed());
        }
        let decision = self.inner.on_request(req).with_context(cx.clone()).await;
        // The later hooks run with the fields it set.
        if let Ok(Decision::Continue(cont)) = &decision {
            if self.remembers && !cont.context.is_empty() {
                let values = with_edits(&Values::of(&cx), &cont.context);
                self.remember(req.id, values.in_context(&cx));
            }
        }
        decision
    }

    async fn on_response(
        &self,
        req: RequestId,
        resp: &ResponseView,
    ) -> Result<Vec<HeaderEdit>, HookError> {
        let cx = self.remembered(req);
        self.inner.on_response(req, resp).with_context(cx).await
    }

    fn on_request_body(&self, req: RequestId, chunk: &Bytes, end: bool) {
        let _guard = self.remembered(req).attach();
        self.inner.on_request_body(req, chunk, end)
    }

    fn on_response_body(&self, req: RequestId, chunk: &Bytes, end: bool) {
        let _guard = self.remembered(req).attach();
        self.inner.on_response_body(req, chunk, end)
    }

    fn on_complete(&self, done: &Completed) {
        let _guard = self.context_of(&done.request).attach();
        self.inner.on_complete(done)
    }

    fn on_finish(&self, req: RequestId) {
        if self.remembers {
            self.contexts
                .lock()
                .expect("contexts lock poisoned")
                .remove(&req);
        }
        self.inner.on_finish(req)
    }
}

/// Starts a [`Continue`] decision that lets the request proceed.
///
/// Chain [`ContinueExt`] methods to modify headers, attributes, or Request
/// Context fields, then convert into a [`Decision`] with `.into()`.
pub fn proceed() -> Continue {
    Continue::default()
}

/// Rejects the request with an Encore error using `code` and `message`.
///
/// The HTTP status code is derived from `code` (for example, 401 for
/// [`ErrCode::Unauthenticated`], 403 for [`ErrCode::PermissionDenied`], and 429
/// for [`ErrCode::ResourceExhausted`]), and Encore clients decode the response
/// as a structured error.
pub fn reject(code: ErrCode, message: impl Into<String>) -> Decision {
    let code = encore_sdk_core::api::ErrCode::from(code);
    Decision::Respond(Rejection::error(
        code.status_code().as_u16(),
        code.to_string(),
        message,
    ))
}

/// Responds directly to the client with the given `status`, `headers`, and
/// `body` (for example, a login redirect:
/// `respond(302, [("location", "/login")], "")`).
pub fn respond<K, V>(
    status: u16,
    headers: impl IntoIterator<Item = (K, V)>,
    body: impl Into<Bytes>,
) -> Decision
where
    K: Into<String>,
    V: Into<String>,
{
    Decision::Respond(Rejection {
        status,
        code: None,
        message: String::new(),
        headers: headers
            .into_iter()
            .map(|(k, v)| (k.into(), v.into()))
            .collect(),
        body: Some(body.into()),
    })
}

/// Builder methods chained onto [`proceed`] to modify a forwarded request.
pub trait ContinueExt: Sized {
    /// Sets request header `name` to `value` (replacing any existing values) for
    /// downstream middleware and the target service.
    ///
    /// Attempting to modify protected Encore headers (`x-encore-*`, trace
    /// context), framing headers, or CORS headers fails the hook.
    fn set_header(self, name: impl Into<String>, value: impl Into<String>) -> Self;
    /// Appends `value` to request header `name`, preserving any existing values.
    fn add_header(self, name: impl Into<String>, value: impl Into<String>) -> Self;
    /// Removes request header `name`.
    fn del_header(self, name: impl Into<String>) -> Self;
    /// Attaches an attribute to the gateway's request span (for example, a user
    /// or tenant ID for searching traces). Never include secrets.
    fn attribute(self, key: impl Into<String>, value: impl Into<AttributeValue>) -> Self;
    /// Skips the specified later `hooks` of this middleware for the current
    /// request (for example, skipping `on_response` when no session exists).
    fn skip(self, hooks: Hooks) -> Self;
    /// Sets a Request Context `field` to `value` for the forwarded request.
    ///
    /// Downstream middleware, the target service, and any services called with
    /// the request context can read the value via [`Field::get`].
    ///
    /// The field takes effect once `on_request` returns. Outbound calls made
    /// inside `on_request` itself still see the incoming context unless wrapped
    /// in [`Field::scope`].
    ///
    /// # Errors
    ///
    /// Returns a [`HookError`] if `value` fails to serialize, exceeds the
    /// per-field encoded size limit (4 KiB, or 1 KiB for fields declared with
    /// [`Field::pubsub`]), or causes the total encoded Request Context to exceed
    /// 8 KiB.
    fn set_field<T: Serialize + DeserializeOwned>(
        self,
        field: &Field<T>,
        value: &T,
    ) -> Result<Self, HookError>;
    /// Clears a Request Context `field` for the forwarded request (such as one
    /// set by earlier middleware).
    fn unset_field<T>(self, field: &Field<T>) -> Self;
}

impl ContinueExt for Continue {
    fn set_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.header_edits.push(HeaderEdit::Set {
            name: name.into(),
            value: value.into(),
        });
        self
    }

    fn add_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.header_edits.push(HeaderEdit::Add {
            name: name.into(),
            value: value.into(),
        });
        self
    }

    fn del_header(mut self, name: impl Into<String>) -> Self {
        self.header_edits
            .push(HeaderEdit::Remove { name: name.into() });
        self
    }

    fn attribute(mut self, key: impl Into<String>, value: impl Into<AttributeValue>) -> Self {
        self.attributes.push((key.into(), value.into()));
        self
    }

    fn skip(mut self, hooks: Hooks) -> Self {
        self.skip |= hooks;
        self
    }

    fn set_field<T: Serialize + DeserializeOwned>(
        mut self,
        field: &Field<T>,
        value: &T,
    ) -> Result<Self, HookError> {
        // In a hook, the current context holds the request's fields: the
        // limits are checked against them, with those set before this.
        let cx = Context::current();
        let fields = with_edits(&Values::of(&cx), &self.context).in_context(&cx);
        let set = field
            .context_in(&fields, value)
            .map_err(|err| HookError::failed(err.to_string()))?;
        let encoded = Values::of(&set)
            .get(field.name())
            .expect("the field was just set")
            .to_string();
        self.context.push((field.name().to_string(), Some(encoded)));
        Ok(self)
    }

    fn unset_field<T>(mut self, field: &Field<T>) -> Self {
        self.context.push((field.name().to_string(), None));
        self
    }
}

/// `values` with Request Context `edits` made: each set (`Some`, encoded) or
/// cleared (`None`), as [`Continue::context`] holds them.
fn with_edits(values: &Values, edits: &[(String, Option<String>)]) -> Values {
    if edits.is_empty() {
        return values.clone();
    }
    let mut fields: BTreeMap<String, String> = values
        .iter()
        .map(|(name, value)| (name.to_string(), value.to_string()))
        .collect();
    for (name, value) in edits {
        match value {
            Some(value) => fields.insert(name.clone(), value.clone()),
            None => fields.remove(name),
        };
    }
    Values::from_map(fields)
}

/// Extension methods for inspecting an incoming request in middleware hooks.
pub trait RequestExt {
    /// Returns the first value of header `name` (case-insensitive), including
    /// edits made by earlier middleware.
    fn header(&self, name: &str) -> Option<&str>;
    /// Returns all values of header `name` (case-insensitive) in order.
    fn header_values(&self, name: &str) -> Vec<&str>;
    /// Returns the first percent-decoded value of query parameter `name`.
    fn query(&self, name: &str) -> Option<&str>;
    /// Returns all percent-decoded values of query parameter `name` in order.
    fn query_values(&self, name: &str) -> Vec<&str>;
    /// Returns the value of cookie `name`, parsed from `Cookie` headers as left
    /// by earlier middleware.
    fn cookie(&self, name: &str) -> Option<&str>;
    /// Returns route path parameter `name` (not percent-decoded).
    fn path_param(&self, name: &str) -> Option<&str>;
}

impl RequestExt for RequestView {
    fn header(&self, name: &str) -> Option<&str> {
        header_values(&self.headers, name).next()
    }

    fn header_values(&self, name: &str) -> Vec<&str> {
        header_values(&self.headers, name).collect()
    }

    fn query(&self, name: &str) -> Option<&str> {
        self.query
            .iter()
            .find(|(n, _)| n == name)
            .map(|(_, v)| v.as_str())
    }

    fn query_values(&self, name: &str) -> Vec<&str> {
        self.query
            .iter()
            .filter(|(n, _)| n == name)
            .map(|(_, v)| v.as_str())
            .collect()
    }

    fn cookie(&self, name: &str) -> Option<&str> {
        header_values(&self.headers, "cookie")
            .flat_map(cookies)
            .find_map(|(n, v)| (n == name).then_some(v))
    }

    fn path_param(&self, name: &str) -> Option<&str> {
        self.params
            .iter()
            .find(|(n, _)| n == name)
            .map(|(_, v)| v.as_str())
    }
}

/// Extension methods for inspecting a response in `on_response`.
pub trait ResponseExt {
    /// Returns the first value of header `name` (case-insensitive), including
    /// edits made by downstream middleware.
    fn header(&self, name: &str) -> Option<&str>;
    /// Returns all values of header `name` (case-insensitive) in order.
    fn header_values(&self, name: &str) -> Vec<&str>;
}

impl ResponseExt for ResponseView {
    fn header(&self, name: &str) -> Option<&str> {
        header_values(&self.headers, name).next()
    }

    fn header_values(&self, name: &str) -> Vec<&str> {
        header_values(&self.headers, name).collect()
    }
}

fn header_values<'a: 'n, 'n>(
    headers: &'a [(String, String)],
    name: &'n str,
) -> impl Iterator<Item = &'a str> + 'n {
    headers
        .iter()
        .filter(move |(n, _)| n.eq_ignore_ascii_case(name))
        .map(|(_, v)| v.as_str())
}

/// Per-request state shared across hooks of a middleware (for example, storing
/// the authenticated user in `on_request` for billing in `on_complete`).
///
/// Remove each request's entry in `on_finish` to avoid leaking memory.
pub struct State<T> {
    shards: Box<[Mutex<HashMap<RequestId, T>>]>,
}

impl<T> Default for State<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T> State<T> {
    pub fn new() -> Self {
        State {
            shards: (0..16).map(|_| Mutex::new(HashMap::new())).collect(),
        }
    }

    fn shard(&self, req: RequestId) -> std::sync::MutexGuard<'_, HashMap<RequestId, T>> {
        let i = (req.0 as usize) % self.shards.len();
        self.shards[i].lock().expect("state lock poisoned")
    }

    /// Stores `value` for `req`, replacing any existing value.
    pub fn insert(&self, req: RequestId, value: T) {
        self.shard(req).insert(req, value);
    }

    /// Passes a mutable reference to the value stored for `req` (if any) to `f`.
    pub fn with<R>(&self, req: RequestId, f: impl FnOnce(Option<&mut T>) -> R) -> R {
        f(self.shard(req).get_mut(&req))
    }

    /// Removes and returns the value stored for `req`.
    pub fn remove(&self, req: RequestId) -> Option<T> {
        self.shard(req).remove(&req)
    }
}

impl<T: Clone> State<T> {
    /// Returns a clone of the value stored for `req`.
    pub fn get(&self, req: RequestId) -> Option<T> {
        self.with(req, |v| v.cloned())
    }
}

/// Request matchers that control which requests trigger a middleware.
///
/// Matchers are evaluated by the gateway against the original request as sent
/// by the client, so header edits made by earlier middleware do not affect
/// whether later middleware runs.
pub mod matcher {
    use super::{Cond, FieldMatch, Match, PathMatch, RouteMatch};

    fn strings<S: Into<String>>(values: impl IntoIterator<Item = S>) -> Vec<String> {
        values.into_iter().map(Into::into).collect()
    }

    /// Matches requests that satisfy all matchers in `ms` (or all requests if
    /// `ms` is empty).
    pub fn all_of(ms: impl IntoIterator<Item = Match>) -> Match {
        Match::All(ms.into_iter().collect())
    }

    /// Matches requests that satisfy at least one matcher in `ms` (or no
    /// requests if `ms` is empty).
    pub fn any_of(ms: impl IntoIterator<Item = Match>) -> Match {
        Match::AnyOf(ms.into_iter().collect())
    }

    /// Matches requests that do not match `m`.
    pub fn not(m: Match) -> Match {
        Match::Not(Box::new(m))
    }

    /// Matches requests routed by the gateway to any of the named `services`.
    pub fn service<S: Into<String>>(services: impl IntoIterator<Item = S>) -> Match {
        Match::Service(strings(services))
    }

    /// Matches requests routed to the route matching `template` (such as
    /// `/users/{id}`) and `method` (or any HTTP method when `method` is `None`).
    ///
    /// Parameter names in `template` are ignored during matching.
    pub fn route(method: Option<&str>, template: impl Into<String>) -> Match {
        Match::Route(RouteMatch {
            method: method.map(str::to_string),
            template: template.into(),
        })
    }

    /// Matches requests with any of the given HTTP `methods` (such as `"POST"`).
    pub fn method<S: Into<String>>(methods: impl IntoIterator<Item = S>) -> Match {
        Match::Method(strings(methods))
    }

    /// Matches requests whose path equals `path` exactly. Trailing slashes are
    /// normalized, matching router behavior.
    pub fn path(path: impl Into<String>) -> Match {
        Match::Path(PathMatch::Exact(path.into()))
    }

    /// Matches requests whose path begins with `prefix` on a segment boundary
    /// (for example, `/admin` matches `/admin/users` but not `/administrators`).
    pub fn path_prefix(prefix: impl Into<String>) -> Match {
        Match::Path(PathMatch::Prefix(prefix.into()))
    }

    /// Matches requests whose path matches `glob`: `*` matches a single path
    /// segment and `**` matches zero or more segments (for example,
    /// `/users/*/posts/**`).
    pub fn path_glob(glob: impl Into<String>) -> Match {
        Match::Path(PathMatch::Glob(glob.into()))
    }

    /// Matches requests where header `name` (case-insensitive) satisfies `cond`.
    /// Header values are compared as sent.
    pub fn header(name: impl Into<String>, cond: Cond) -> Match {
        Match::Header(FieldMatch {
            name: name.into(),
            cond,
        })
    }

    /// Matches requests where query parameter `name` satisfies `cond`.
    /// Values are percent-decoded before comparison.
    pub fn query(name: impl Into<String>, cond: Cond) -> Match {
        Match::Query(FieldMatch {
            name: name.into(),
            cond,
        })
    }

    /// Matches requests where cookie `name` satisfies `cond`.
    pub fn cookie(name: impl Into<String>, cond: Cond) -> Match {
        Match::Cookie(FieldMatch {
            name: name.into(),
            cond,
        })
    }

    /// Matches when the field is present.
    pub fn present() -> Cond {
        Cond::Present
    }

    /// Matches when the field is absent.
    pub fn absent() -> Cond {
        Cond::Absent
    }

    /// Matches when the field equals `value`.
    pub fn equals(value: impl Into<String>) -> Cond {
        Cond::Equals(value.into())
    }

    /// Matches when the field starts with `prefix` (for example, `"Bearer "`).
    pub fn prefix(prefix: impl Into<String>) -> Cond {
        Cond::Prefix(prefix.into())
    }

    /// Matches when the field equals any element of `values`.
    pub fn one_of<S: Into<String>>(values: impl IntoIterator<Item = S>) -> Cond {
        Cond::OneOf(strings(values))
    }

    /// Matches when the entire field value matches the RE2 regular expression
    /// `pattern`. An invalid pattern causes [`serve`](super::serve) to return
    /// an error.
    pub fn regex(pattern: impl Into<String>) -> Cond {
        Cond::Regex(pattern.into())
    }
}

fn served() -> &'static Mutex<bool> {
    static SERVED: Mutex<bool> = Mutex::new(false);
    &SERVED
}

/// Serves the gateway hosted by this service with `middleware` applied in order,
/// running until Encore initiates graceful shutdown.
///
/// Call this at the end of `main` instead of starting an HTTP server. When
/// shutdown begins (on the first `SIGTERM`), the gateway stops accepting new
/// requests, finishes in-flight requests, and runs remaining `on_complete`
/// hooks before closing infrastructure clients; a second `SIGTERM` aborts
/// draining. Returns once the gateway has stopped.
///
/// # Errors
///
/// Returns an error if:
/// - the process was not launched as an Encore gateway program (e.g. via
///   `encore run`),
/// - a middleware registration is invalid (such as a non-kebab-case or
///   duplicate name, no hooks enabled, or an invalid regex),
/// - the gateway is already being served in this process, or
/// - serving fails after startup.
///
/// If `serve` fails before the gateway starts, it may be called again.
pub async fn serve(middleware: impl IntoIterator<Item = Registration>) -> Result<(), Error> {
    let middleware: Vec<Registration> = middleware.into_iter().collect();
    if middleware.is_empty() {
        return Err(Error(
            "gateway::serve requires at least one middleware".into(),
        ));
    }
    if let Some(none) = middleware.iter().find(|m| m.hooks == Hooks::NONE) {
        return Err(Error(format!(
            "middleware {:?} has no hooks enabled",
            none.name
        )));
    }
    {
        let mut served = served().lock().expect("served lock poisoned");
        if *served {
            return Err(Error(
                "gateway::serve can only be called once per process".into(),
            ));
        }
        *served = true;
    }
    // A gateway that failed to start was not served: a corrected call may
    // serve it.
    let stopped = start(middleware).inspect_err(|_| {
        *served().lock().expect("served lock poisoned") = false;
    })?;
    match stopped.await {
        Ok(Ok(())) | Err(_) => Ok(()),
        Ok(Err(err)) => Err(Error(format!("gateway server failed: {err}"))),
    }
}

/// Binds and starts the gateway with `middleware`, returning what is told
/// once it has stopped, with why.
fn start(
    middleware: Vec<Registration>,
) -> Result<tokio::sync::oneshot::Receiver<Result<(), encore_gateway::GatewayError>>, Error> {
    let env = ProgramEnv::from_env().map_err(|err| {
        Error(format!(
            "this process is not a gateway program: {err}. Encore launches services with a \
             \"gateway\" section in encore.service.json as gateway programs and sets {} to \
             the listen address",
            encore_gateway::program::LISTEN_ENV
        ))
    })?;
    let core = crate::runtime::core();
    crate::pubsub::start_registered();
    let cfg = core.config_proto();
    let mark = cfg
        .deployment
        .as_ref()
        .and_then(|d| d.observability.as_ref())
        .and_then(|o| o.telemetry.as_ref())
        .is_some_and(|t| t.check_propagation);
    let specs = middleware.into_iter().map(|m| m.spec(mark)).collect();
    let (stopped_tx, stopped) = tokio::sync::oneshot::channel();
    let listen = encore_sdk_core_gateway::serve::serve(
        cfg,
        &env,
        core.tokio_handle(),
        core.resources().serving(),
        specs,
        move |result| {
            let _ = stopped_tx.send(result);
        },
    )
    .map_err(|err| Error(err.to_string()))?;
    tracing::debug!("serving the gateway on {listen}");
    hurry_on_second_signal(core);
    Ok(stopped)
}

/// Once the shutdown has begun, a second SIGTERM or SIGINT stops waiting for
/// the gateway's drain, as the supervisor's second SIGTERM means.
fn hurry_on_second_signal(core: &'static encore_sdk_core::Runtime) {
    let controller = core.shutdown_controller();
    core.tokio_handle().spawn(async move {
        if controller.started().await.is_err() {
            return;
        }
        let signal = {
            let _guard = core.tokio_handle().enter();
            encore_os::signal::listen_shutdown_signal()
        };
        match signal {
            Ok(signal) => {
                signal.await;
                tracing::info!("received a second shutdown signal: the gateway stops draining");
                let _ = controller.force_cleanup();
            }
            Err(err) => tracing::warn!("not listening for a second shutdown signal: {err}"),
        }
    });
}

#[cfg(test)]
mod tests {
    use super::*;

    fn view(headers: &[(&str, &str)]) -> RequestView {
        RequestView {
            id: RequestId(1),
            gateway: "edge".into(),
            service: "users".into(),
            route: "/users/{id}".into(),
            method: "GET".into(),
            path: "/users/7".into(),
            host: None,
            client_ip: None,
            params: vec![("id".into(), "7".into())],
            headers: headers
                .iter()
                .map(|(n, v)| (n.to_string(), v.to_string()))
                .collect(),
            query: vec![("q".into(), "a".into()), ("q".into(), "b".into())],
            cookies: Vec::new(),
            trace: None,
            context: Vec::new(),
            hooks: Hooks::REQUEST,
        }
    }

    #[test]
    fn a_request_reads_its_headers_query_and_cookies() {
        let req = view(&[
            ("authorization", "Bearer t"),
            ("cookie", "a=1; theme=\"dark\""),
            ("cookie", "b=2"),
        ]);
        assert_eq!(req.header("Authorization"), Some("Bearer t"));
        assert_eq!(req.query_values("q"), ["a", "b"]);
        assert_eq!(req.cookie("theme"), Some("dark"));
        assert_eq!(req.cookie("b"), Some("2"));
        assert_eq!(req.cookie("c"), None);
        assert_eq!(req.path_param("id"), Some("7"));
    }

    #[test]
    fn reject_answers_with_the_code_and_its_status() {
        let Decision::Respond(rej) = reject(ErrCode::ResourceExhausted, "slow down") else {
            panic!("not an answer");
        };
        assert_eq!(rej.status, 429);
        assert_eq!(rej.code.as_deref(), Some("resource_exhausted"));
        assert_eq!(rej.message, "slow down");
        let Decision::Respond(rej) = respond(302, [("location", "/login")], "") else {
            panic!("not an answer");
        };
        assert_eq!((rej.status, rej.code), (302, None));
        assert_eq!(
            rej.headers,
            [("location".to_string(), "/login".to_string())]
        );
    }

    #[test]
    fn edits_chain_on_proceed() {
        let c = proceed()
            .set_header("x-user", "ada")
            .del_header("x-drop")
            .attribute("user.id", "ada")
            .skip(Hooks::COMPLETE);
        assert_eq!(c.header_edits.len(), 2);
        assert_eq!(c.attributes.len(), 1);
        assert!(c.skip == Hooks::COMPLETE);
    }

    struct Body;

    impl Middleware for Body {}

    #[test]
    fn a_middleware_is_shown_everything_and_told_of_requests_for_its_later_hooks() {
        let spec = register("body", Hooks::from(Hook::RequestBody), Body)
            .matching(matcher::path_prefix("/api"))
            .timeout(Duration::from_millis(250))
            .on_error(OnError::FailOpen)
            .spec(false);
        assert_eq!(spec.name, "body");
        assert!(spec.interest.hooks == Hooks::REQUEST | Hook::RequestBody.into());
        assert_eq!(
            spec.interest.reads.headers,
            encore_gateway::middleware::ReadSet::All
        );
        assert!(spec.interest.reads.cookies.is_empty());
        assert_eq!(spec.timeout, Duration::from_millis(250));
        assert_eq!(spec.on_error, OnError::FailOpen);
        assert_eq!(
            spec.interest.matches,
            Some(Match::Path(PathMatch::Prefix("/api".into())))
        );
    }

    #[test]
    fn state_is_kept_per_request() {
        let state = State::new();
        state.insert(RequestId(1), "ada");
        state.insert(RequestId(17), "bob");
        assert_eq!(state.get(RequestId(1)), Some("ada"));
        assert_eq!(state.remove(RequestId(17)), Some("bob"));
        assert_eq!(state.get(RequestId(17)), None);
    }

    #[tokio::test]
    async fn a_gateway_that_failed_to_start_may_be_served_again() {
        // Outside a gateway program, as unit tests are, serving fails before
        // the gateway starts; the second call fails the same way rather than
        // as already served.
        assert!(std::env::var_os(encore_gateway::program::LISTEN_ENV).is_none());
        for _ in 0..2 {
            let err = serve([register("body", Hooks::from(Hook::RequestBody), Body)])
                .await
                .expect_err("served outside a gateway program");
            assert!(
                err.to_string().contains("not a gateway program"),
                "unexpected error: {err}"
            );
        }
    }

    #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
    struct User {
        id: String,
    }

    static USER: Field<User> = Field::new("gw-user");
    static PLAN: Field<String> = Field::new("gw-plan");

    fn wire(json: &str) -> String {
        encore_sdk_core::reqctx::encode(json.as_bytes())
    }

    fn ada() -> User {
        User { id: "ada".into() }
    }

    /// What [`USER`] and [`PLAN`] read in a hook.
    type Seen = (&'static str, Option<User>, Option<String>);

    /// Records what [`USER`] and [`PLAN`] read in each hook.
    #[derive(Default)]
    struct Auth {
        seen: Mutex<Vec<Seen>>,
    }

    impl Auth {
        fn saw(&self, hook: &'static str) {
            self.seen
                .lock()
                .unwrap()
                .push((hook, USER.get(), PLAN.get()));
        }
    }

    #[async_trait]
    impl Middleware for Auth {
        async fn on_request(&self, _req: &RequestView) -> Result<Decision, HookError> {
            self.saw("request");
            Ok(proceed()
                .set_field(&USER, &ada())?
                .unset_field(&PLAN)
                .into())
        }

        async fn on_response(
            &self,
            _req: RequestId,
            _resp: &ResponseView,
        ) -> Result<Vec<HeaderEdit>, HookError> {
            self.saw("response");
            Ok(Vec::new())
        }

        fn on_complete(&self, _done: &Completed) {
            self.saw("complete");
        }
    }

    #[tokio::test]
    async fn hooks_run_in_their_request_s_context_as_on_request_sets_it() {
        let auth = Arc::new(Auth::default());
        let traced = Traced {
            inner: auth.clone(),
            observes: false,
            remembers: true,
            mark: false,
            contexts: Mutex::new(HashMap::new()),
        };
        let mut req = view(&[]);
        req.context = vec![("gw-plan".into(), wire("\"pro\""))];
        let Ok(Decision::Continue(cont)) = traced.on_request(&req).await else {
            panic!("not let through");
        };
        assert_eq!(
            cont.context,
            [
                ("gw-user".to_string(), Some(wire(r#"{"id":"ada"}"#))),
                ("gw-plan".to_string(), None),
            ]
        );
        let resp = ResponseView {
            status: 200,
            headers: Vec::new(),
        };
        traced.on_response(req.id, &resp).await.unwrap();
        let mut forwarded = req.clone();
        forwarded.context = vec![("gw-plan".into(), wire("\"team\""))];
        traced.on_complete(&Completed {
            request: forwarded,
            status: 200,
            rejected_by: None,
            error: None,
            received: std::time::SystemTime::UNIX_EPOCH,
            duration: Duration::from_millis(3),
            upstream_duration: None,
            request_body_size: 0,
            response_body_size: 0,
        });
        traced.on_finish(req.id);
        assert_eq!(
            *auth.seen.lock().unwrap(),
            [
                ("request", None, Some("pro".to_string())),
                ("response", Some(ada()), None),
                ("complete", None, Some("team".to_string())),
            ]
        );
        // Outside its hooks, none of the request's context is current.
        assert!(Values::current().is_empty());
        assert!(traced.contexts.lock().unwrap().is_empty());
    }

    #[test]
    fn a_field_set_beyond_its_limits_fails_the_hook() {
        let err = proceed()
            .set_field(&PLAN, &"x".repeat(4096))
            .expect_err("set beyond its limit");
        assert!(
            err.message()
                .starts_with("reqctx: field \"gw-plan\": the value encodes to")
                && err.message().contains("more than the 4096 a field may"),
            "{}",
            err.message()
        );
        // The limit on all of a request's fields counts the request's, and
        // those set before.
        let big = "x".repeat(3000);
        let _guard = Values::from_map([("gw-a".to_string(), wire(&format!("\"{big}\"")))].into())
            .in_context(&Context::new())
            .attach();
        let err = proceed()
            .set_field(&PLAN, &big)
            .unwrap()
            .set_field(&USER, &User { id: big.clone() })
            .expect_err("set beyond the request's limit");
        assert!(
            err.message().contains("more than the 8192 they may"),
            "{}",
            err.message()
        );
    }

    #[test]
    fn matchers_spell_the_cores_json() {
        let m = matcher::all_of([
            matcher::header("authorization", matcher::prefix("Bearer ")),
            matcher::not(matcher::method(["OPTIONS"])),
        ]);
        assert_eq!(
            serde_json::to_value(&m).unwrap(),
            serde_json::json!({"all": [
                {"header": {"name": "authorization", "cond": {"prefix": "Bearer "}}},
                {"not": {"method": ["OPTIONS"]}},
            ]})
        );
    }
}