Skip to main content

cufflink_types/manifest/
service.rs

1use super::{
2    AuthorizationConfig, CustomRouteDefinition, HandlerType, MigrationHistory, ScheduleDefinition,
3    SqlMigration, StreamDefinition, SubscriptionDefinition, TableDefinition,
4};
5use crate::features;
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8use std::collections::BTreeMap;
9
10/// A service manifest describes the complete definition of a cufflink service.
11/// This is generated by the SDK macros from the user's Rust struct definitions.
12#[derive(Debug, Clone, Default, Serialize, Deserialize)]
13pub struct ServiceManifest {
14    pub name: String,
15    pub version: Option<String>,
16    pub tables: Vec<TableDefinition>,
17    /// Tables only the service's own SQL reaches. The platform checks them
18    /// against the database as it does `tables`, and serves none of them.
19    #[serde(default, skip_serializing_if = "Vec::is_empty")]
20    pub private_tables: Vec<TableDefinition>,
21    #[serde(default)]
22    pub cells: Vec<CellDefinition>,
23    #[serde(default)]
24    pub events: Vec<EventDefinition>,
25    #[serde(default)]
26    pub subscriptions: Vec<SubscriptionDefinition>,
27    #[serde(default)]
28    pub custom_routes: Vec<CustomRouteDefinition>,
29    #[serde(default)]
30    pub mode: ServiceMode,
31    /// Authorization configuration (permission areas and default roles).
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub authorization: Option<AuthorizationConfig>,
34    /// Optional WASM handler invoked between additive and destructive schema
35    /// phases of a deploy. Used to backfill or restructure data when columns
36    /// are split, renamed, or have their semantics changed. The handler must
37    /// be idempotent — it may be re-invoked on retried deploys.
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    pub on_migrate: Option<String>,
40    /// NATS subject patterns (with `*`/`>` wildcards) this service is allowed to
41    /// publish or request outside its own `dw.{tenant}.*` namespace. `None` marks
42    /// a manifest built before publish authorization existed: the platform then
43    /// runs in legacy mode (allow + warn). `Some` — always emitted by the current
44    /// SDK — enables enforcement.
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub publishes: Option<Vec<String>>,
47    /// Extensions the service's handlers may call through `ext_call`.
48    #[serde(default, skip_serializing_if = "Vec::is_empty")]
49    pub extensions: Vec<String>,
50    /// Extensions a native service serves, and who may call each.
51    #[serde(default, skip_serializing_if = "Vec::is_empty")]
52    pub provides: Vec<ProvidedExtension>,
53    /// Platform capabilities this service requires to run safely. The platform
54    /// rejects a deploy whose required features it does not advertise at
55    /// `/api/version`. The SDK auto-derives this (e.g. `route_posture` when any
56    /// route declares a posture) so a security-relevant manifest cannot be
57    /// silently deployed to a platform too old to enforce it.
58    #[serde(default, skip_serializing_if = "Vec::is_empty")]
59    pub required_platform_features: Vec<String>,
60    /// Serve the auto-generated GraphQL endpoint. Off unless the service
61    /// opts in.
62    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
63    pub graphql: bool,
64    /// How custom routes are reached: `legacy` serves each only by handler
65    /// name under `_fn/`; `strict` also matches their declared paths.
66    #[serde(default, skip_serializing_if = "RoutingMode::is_legacy")]
67    pub routing: RoutingMode,
68    /// The JSON key the platform's own error responses for this service
69    /// carry their message under, instead of `error`.
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub errors: Option<ErrorProfile>,
72    /// The service's OpenAPI document settings; its presence (or any
73    /// documented route) makes the spec server-relative.
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub openapi: Option<OpenApiOptions>,
76    /// Shared JSON Schemas the route docs refer to as
77    /// `#/components/schemas/{name}`.
78    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
79    pub components: BTreeMap<String, Value>,
80    /// How the durable consumers of the service's subscriptions are named.
81    #[serde(default, skip_serializing_if = "ConsumerNaming::is_legacy")]
82    pub consumers: ConsumerNaming,
83    #[serde(default, skip_serializing_if = "Vec::is_empty")]
84    pub streams: Vec<StreamDefinition>,
85    #[serde(default, skip_serializing_if = "Vec::is_empty")]
86    pub schedules: Vec<ScheduleDefinition>,
87    /// Who owns the DDL of the service's schema.
88    #[serde(default, skip_serializing_if = "SchemaOwnership::is_managed")]
89    pub schema: SchemaOwnership,
90    /// The service's Postgres schema; derived from its name when unset.
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub schema_name: Option<String>,
93    /// The service's SQL migrations, in version order.
94    #[serde(default, skip_serializing_if = "Vec::is_empty")]
95    pub migrations: Vec<SqlMigration>,
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub migration_history: Option<MigrationHistory>,
98}
99
100#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
101#[serde(rename_all = "snake_case")]
102pub enum ConsumerNaming {
103    /// `{service}_{handler}`.
104    #[default]
105    Legacy,
106    /// Named for the tenant, the service, the handler and what it consumes.
107    Scoped,
108}
109
110impl ConsumerNaming {
111    pub fn is_legacy(&self) -> bool {
112        *self == ConsumerNaming::Legacy
113    }
114}
115
116#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
117#[serde(rename_all = "snake_case")]
118pub enum SchemaOwnership {
119    /// The platform creates and alters the schema from the manifest.
120    #[default]
121    Managed,
122    /// The schema exists already; the platform never emits DDL for it.
123    Adopted,
124}
125
126impl SchemaOwnership {
127    pub fn is_managed(&self) -> bool {
128        *self == SchemaOwnership::Managed
129    }
130}
131
132#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
133pub struct OpenApiOptions {
134    /// Defaults to the service name.
135    #[serde(default, skip_serializing_if = "Option::is_none")]
136    pub title: Option<String>,
137    /// Defaults to the manifest version.
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub version: Option<String>,
140    #[serde(default, skip_serializing_if = "Option::is_none")]
141    pub description: Option<String>,
142    /// Defaults to the service's own `/svc/{tenant}/{service}` base.
143    #[serde(default, skip_serializing_if = "Vec::is_empty")]
144    pub servers: Vec<ServerDoc>,
145    /// The document's tag list.
146    #[serde(default, skip_serializing_if = "Vec::is_empty")]
147    pub tags: Vec<TagDoc>,
148    /// The HTTP bearer scheme authenticated routes name; `bearer_auth`
149    /// when unset.
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    pub security_scheme: Option<String>,
152    /// Public, unauthenticated documents, each a tag-selected subset of this spec.
153    #[serde(default, skip_serializing_if = "Vec::is_empty")]
154    pub docs: Vec<PublicDoc>,
155}
156
157impl OpenApiOptions {
158    pub const DEFAULT_SECURITY_SCHEME: &'static str = "bearer_auth";
159
160    pub fn security_scheme(&self) -> &str {
161        self.security_scheme
162            .as_deref()
163            .unwrap_or(Self::DEFAULT_SECURITY_SCHEME)
164    }
165}
166
167/// A public document: the operations of the spec carrying any of
168/// `include_tags`, served without authentication under `mount`.
169#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
170pub struct PublicDoc {
171    /// Unique among the service's documents; `[a-z][a-z0-9-]{0,62}`.
172    pub name: String,
173    /// A literal service-relative path the document is served under.
174    pub mount: String,
175    /// The operations published: those tagged with any of these.
176    pub include_tags: Vec<String>,
177    pub info: PublicDocInfo,
178    /// Defaults to `OpenApiOptions::servers`, then to the service's own base.
179    #[serde(default, skip_serializing_if = "Vec::is_empty")]
180    pub servers: Vec<ServerDoc>,
181    /// The document's tag list.
182    #[serde(default, skip_serializing_if = "Vec::is_empty")]
183    pub tags: Vec<TagDoc>,
184    /// Prepended to every path, for a gateway that publishes them under one; needs `servers`.
185    #[serde(default, skip_serializing_if = "Option::is_none")]
186    pub path_prefix: Option<String>,
187    /// How the `api_key` scheme is presented; the platform's `X-Api-Key` when unset.
188    #[serde(default, skip_serializing_if = "Option::is_none")]
189    pub api_key: Option<ApiKeyDoc>,
190    /// Cross-origin access to the document's answers; `Restricted` when unset.
191    #[serde(default, skip_serializing_if = "PublicDocCors::is_restricted")]
192    pub cors: PublicDocCors,
193}
194
195#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
196pub struct PublicDocInfo {
197    pub title: String,
198    pub version: String,
199    #[serde(default, skip_serializing_if = "Option::is_none")]
200    pub description: Option<String>,
201    #[serde(default, skip_serializing_if = "Option::is_none")]
202    pub contact: Option<ContactDoc>,
203}
204
205#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
206pub struct ContactDoc {
207    #[serde(default, skip_serializing_if = "Option::is_none")]
208    pub name: Option<String>,
209    #[serde(default, skip_serializing_if = "Option::is_none")]
210    pub email: Option<String>,
211    #[serde(default, skip_serializing_if = "Option::is_none")]
212    pub url: Option<String>,
213}
214
215/// The `api_key` security scheme as a document presents it.
216#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
217pub struct ApiKeyDoc {
218    /// The request header the key is sent in.
219    pub header: String,
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub description: Option<String>,
222}
223
224/// Cross-origin access to a public document. A new mode is always a unit
225/// variant: `Unknown` catches only an unknown string, so a platform rolled
226/// back below a mode still decodes the manifest naming it.
227#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
228#[serde(rename_all = "snake_case")]
229pub enum PublicDocCors {
230    /// The platform's own CORS policy, as for every route.
231    #[default]
232    Restricted,
233    /// `access-control-allow-origin: *`, without credentials.
234    Any,
235    /// The request's origin, methods and headers echoed, with credentials.
236    Mirror,
237    /// A mode this platform does not know; served as `Restricted`, refused at deploy.
238    #[serde(other)]
239    Unknown,
240}
241
242impl PublicDocCors {
243    pub fn is_restricted(&self) -> bool {
244        *self == PublicDocCors::Restricted
245    }
246}
247
248#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
249pub struct ServerDoc {
250    pub url: String,
251    #[serde(default, skip_serializing_if = "Option::is_none")]
252    pub description: Option<String>,
253}
254
255#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
256pub struct TagDoc {
257    pub name: String,
258    #[serde(default, skip_serializing_if = "Option::is_none")]
259    pub description: Option<String>,
260}
261
262#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
263pub struct ErrorProfile {
264    pub key: String,
265}
266
267impl ErrorProfile {
268    /// Whether `key` is a valid error key: `[a-z_][a-z0-9_]{0,63}`.
269    pub fn is_valid_key(key: &str) -> bool {
270        let mut bytes = key.bytes();
271        key.len() <= 64
272            && bytes
273                .next()
274                .is_some_and(|b| b.is_ascii_lowercase() || b == b'_')
275            && bytes.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
276    }
277}
278
279#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
280#[serde(rename_all = "snake_case")]
281pub enum RoutingMode {
282    #[default]
283    Legacy,
284    Strict,
285}
286
287impl RoutingMode {
288    pub fn is_legacy(&self) -> bool {
289        *self == RoutingMode::Legacy
290    }
291}
292
293#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
294#[serde(rename_all = "lowercase")]
295pub enum ServiceMode {
296    #[default]
297    Crud,
298    Wasm,
299    Container,
300    Web,
301    /// A Rust binary supervised by the extension runner that serves the
302    /// extensions it `provides`.
303    Native,
304}
305
306impl ServiceMode {
307    /// The mode as a manifest names it.
308    pub fn as_str(&self) -> &'static str {
309        match self {
310            ServiceMode::Crud => "crud",
311            ServiceMode::Wasm => "wasm",
312            ServiceMode::Container => "container",
313            ServiceMode::Web => "web",
314            ServiceMode::Native => "native",
315        }
316    }
317
318    /// Whether the platform runs the service itself: its schema, module,
319    /// database role, subscriptions and schedules. A web app and a native
320    /// service run in a runner of their own and have none of them.
321    pub fn runs_on_platform(&self) -> bool {
322        match self {
323            ServiceMode::Crud | ServiceMode::Wasm | ServiceMode::Container => true,
324            ServiceMode::Web | ServiceMode::Native => false,
325        }
326    }
327}
328
329/// An extension a native service serves.
330#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
331pub struct ProvidedExtension {
332    pub name: String,
333    /// Service names, or [`ANY_CALLER`](crate::ext::ANY_CALLER).
334    pub callers: Vec<String>,
335}
336
337#[derive(Debug, Clone, Serialize, Deserialize)]
338pub struct CellDefinition {
339    pub name: String,
340}
341
342#[derive(Debug, Clone, Serialize, Deserialize)]
343pub struct EventDefinition {
344    pub name: String,
345    pub table: String,
346    pub action: EventAction,
347}
348
349#[derive(Debug, Clone, Serialize, Deserialize)]
350#[serde(rename_all = "lowercase")]
351pub enum EventAction {
352    Create,
353    Update,
354    Delete,
355}
356
357impl ServiceManifest {
358    /// The served table named `name`; a private table is never found.
359    pub fn get_table(&self, name: &str) -> Option<&TableDefinition> {
360        self.tables.iter().find(|t| t.name == name)
361    }
362
363    /// Every table the service declares, served or not.
364    pub fn declared_tables(&self) -> impl Iterator<Item = &TableDefinition> {
365        self.tables.iter().chain(&self.private_tables)
366    }
367
368    /// Whether this manifest needs a WASM artifact bundled at deploy time.
369    ///
370    /// A WASM module is required when the service runs user code: explicit
371    /// `mode: wasm`, an `on_migrate` schema hook, table CRUD lifecycle hooks,
372    /// a schedule, or any `Wasm` subscription/custom-route handler. The CLI uses this to
373    /// decide whether to compile a WASM artifact; the platform uses it to
374    /// reject deploys that arrive without one.
375    pub fn requires_wasm(&self) -> bool {
376        match self.mode {
377            ServiceMode::Wasm => true,
378            ServiceMode::Native => false,
379            ServiceMode::Crud | ServiceMode::Container | ServiceMode::Web => {
380                self.on_migrate.is_some()
381                    || self.tables.iter().any(|t| t.hooks.is_some())
382                    || !self.custom_routes.is_empty()
383                    || !self.schedules.is_empty()
384                    || self
385                        .subscriptions
386                        .iter()
387                        .any(|s| matches!(s.handler_type, HandlerType::Wasm))
388            }
389        }
390    }
391
392    /// All handler names this manifest expects the WASM module to export.
393    /// Used at deploy time to reject manifests whose declared handlers are
394    /// missing from the bundled binary.
395    pub fn declared_wasm_handlers(&self) -> Vec<&str> {
396        let mut handlers: Vec<&str> = Vec::new();
397        if let Some(ref h) = self.on_migrate {
398            handlers.push(h.as_str());
399        }
400        for route in &self.custom_routes {
401            handlers.push(route.handler.as_str());
402            if let Some(reducer) = route.sse.as_ref().and_then(|sse| sse.reducer.as_deref()) {
403                handlers.push(reducer);
404            }
405        }
406        for sub in &self.subscriptions {
407            if matches!(sub.handler_type, HandlerType::Wasm) {
408                handlers.push(sub.handler.as_str());
409            }
410        }
411        handlers.extend(self.schedules.iter().map(|s| s.handler.as_str()));
412        for table in &self.tables {
413            if let Some(ref hooks) = table.hooks {
414                for h in [
415                    hooks.before_create.as_deref(),
416                    hooks.after_create.as_deref(),
417                    hooks.before_update.as_deref(),
418                    hooks.after_update.as_deref(),
419                    hooks.before_delete.as_deref(),
420                    hooks.after_delete.as_deref(),
421                ]
422                .iter()
423                .flatten()
424                {
425                    handlers.push(h);
426                }
427            }
428        }
429        handlers.sort();
430        handlers.dedup();
431        handlers
432    }
433
434    /// The `custom_routes` entry exposing `handler` over the HTTP `_fn/`
435    /// surface, if any. Only custom routes are HTTP-invocable; subscription,
436    /// `on_migrate`, and table-hook handlers run solely via their internal
437    /// triggers, so a handler absent here must not be dispatched from an
438    /// inbound request. Matched by name alone — the `_fn/` route accepts every
439    /// method, so a verb-aware match would demote a job handler to inline
440    /// execution on the wrong verb.
441    pub fn http_route(&self, handler: &str) -> Option<&CustomRouteDefinition> {
442        self.http_route_index(handler)
443            .and_then(|index| self.custom_routes.get(index))
444    }
445
446    /// The position of [`http_route`](Self::http_route) in `custom_routes`.
447    pub fn http_route_index(&self, handler: &str) -> Option<usize> {
448        self.custom_routes.iter().position(|r| r.handler == handler)
449    }
450
451    /// Whether this manifest was built by a posture-aware SDK. True when any
452    /// custom route carries a posture — the current SDK emits a posture on
453    /// every route, so a posture-aware manifest is all-or-nothing and a lone
454    /// undeclared route among declared ones signals tampering or a bug.
455    pub fn is_posture_aware(&self) -> bool {
456        self.custom_routes.iter().any(|r| r.posture.is_some())
457    }
458
459    /// The service's Postgres schema: `schema_name`, or the service name
460    /// with `-` as `_`. Every other derivation of it is a bug.
461    pub fn schema(&self) -> String {
462        service_schema(&self.name, self.schema_name.as_deref())
463    }
464
465    /// Where the service's applied SQL migrations are recorded.
466    pub fn migration_history(&self) -> MigrationHistory {
467        self.migration_history.clone().unwrap_or_default()
468    }
469
470    /// The manifest without the text of its SQL migrations, which only a
471    /// deploy reads.
472    pub fn without_migration_bodies(mut self) -> Self {
473        self.migrations
474            .iter_mut()
475            .for_each(|migration| migration.sql = String::new());
476        self
477    }
478
479    /// The public documents the service declares.
480    pub fn public_docs(&self) -> impl Iterator<Item = &PublicDoc> {
481        self.openapi.iter().flat_map(|options| &options.docs)
482    }
483
484    /// Platform features required by service-level fields.
485    pub(crate) fn service_features(&self) -> impl Iterator<Item = &'static str> {
486        let adopted = !self.schema.is_managed() || self.schema_name.is_some();
487        [
488            (self.routing == RoutingMode::Strict).then_some(features::ROUTE_MATCHING),
489            self.errors.is_some().then_some(features::ERROR_PROFILE),
490            (!self.consumers.is_legacy()).then_some(features::NATS_CONSUMER_CONFIG),
491            (!self.streams.is_empty()).then_some(features::STREAMS),
492            (!self.schedules.is_empty()).then_some(features::SCHEDULES),
493            adopted.then_some(features::SCHEMA_ADOPTED),
494            (!self.migrations.is_empty()).then_some(features::SQL_MIGRATIONS),
495            (!self.extensions.is_empty()).then_some(features::EXT_CALL),
496            (self.mode == ServiceMode::Native).then_some(features::NATIVE_SERVICES),
497            (!self.private_tables.is_empty()).then_some(features::PRIVATE_TABLES),
498            self.public_docs()
499                .next()
500                .is_some()
501                .then_some(features::PUBLIC_DOCS),
502        ]
503        .into_iter()
504        .flatten()
505    }
506
507    /// SHA-256 of the whole manifest: the deploy skip check compares this, so
508    /// a change to any field (`publishes`, `events`, `mode`, …) deploys.
509    pub fn deploy_hash(&self) -> serde_json::Result<String> {
510        use sha2::{Digest, Sha256};
511        serde_json::to_vec(self).map(|bytes| hex::encode(Sha256::digest(bytes)))
512    }
513
514    /// SHA-256 of the schema-bearing fields, stored on schema snapshots. A
515    /// field added since contributes only when it is set, so the hash of a
516    /// manifest without it never changes.
517    pub fn schema_hash(&self) -> serde_json::Result<String> {
518        use sha2::{Digest, Sha256};
519        let ownership = [
520            (!self.schema.is_managed())
521                .then(|| serde_json::to_string(&self.schema))
522                .transpose()?,
523            self.schema_name
524                .as_ref()
525                .map(serde_json::to_string)
526                .transpose()?,
527            (!self.migrations.is_empty())
528                .then(|| serde_json::to_string(&self.migrations))
529                .transpose()?,
530            self.migration_history
531                .as_ref()
532                .map(serde_json::to_string)
533                .transpose()?,
534        ];
535        let private_tables = (!self.private_tables.is_empty())
536            .then(|| serde_json::to_string(&self.private_tables))
537            .transpose()?;
538        let digest = [
539            serde_json::to_string(&self.tables)?,
540            serde_json::to_string(&self.custom_routes)?,
541            serde_json::to_string(&self.subscriptions)?,
542            serde_json::to_string(&self.authorization)?,
543            serde_json::to_string(&self.on_migrate)?,
544        ]
545        .into_iter()
546        .chain(ownership.into_iter().flatten())
547        .chain(private_tables)
548        .fold(Sha256::new(), |hasher, part| hasher.chain_update(part))
549        .finalize();
550        Ok(hex::encode(digest))
551    }
552}
553
554/// The Postgres schema of the service `name`: the `schema_name` it
555/// declares, or its name with `-` as `_`.
556pub fn service_schema(name: &str, schema_name: Option<&str>) -> String {
557    schema_name.map_or_else(|| name.replace('-', "_"), str::to_string)
558}
559
560#[cfg(test)]
561mod tests {
562    use super::*;
563    use crate::manifest::fixtures::sample_manifest;
564    use crate::manifest::{
565        ColumnDefinition, ColumnType, ForeignKeyAction, JobConfig, RoutePosture, TableHooks,
566    };
567
568    #[test]
569    fn test_manifest_serialization_roundtrip() {
570        let manifest = sample_manifest();
571        let json = serde_json::to_string(&manifest).unwrap();
572        let parsed: ServiceManifest = serde_json::from_str(&json).unwrap();
573        assert_eq!(parsed.name, "test-service");
574        assert_eq!(parsed.tables.len(), 1);
575        assert_eq!(parsed.tables[0].columns.len(), 3);
576    }
577
578    #[test]
579    fn routing_is_serialized_only_when_strict() {
580        let mut manifest = sample_manifest();
581        let json = serde_json::to_value(&manifest).unwrap();
582        assert!(json.get("routing").is_none(), "{json}");
583        manifest.routing = RoutingMode::Strict;
584        let json = serde_json::to_value(&manifest).unwrap();
585        assert_eq!(json["routing"], "strict");
586        let parsed: ServiceManifest = serde_json::from_value(json).unwrap();
587        assert_eq!(parsed.routing, RoutingMode::Strict);
588    }
589
590    #[test]
591    fn error_profile_keys_are_snake_case_identifiers() {
592        for key in ["error_message", "_e", "e1", &"e".repeat(64)] {
593            assert!(ErrorProfile::is_valid_key(key), "{key}");
594        }
595        for key in [
596            "",
597            "1e",
598            "Error",
599            "error-message",
600            "error message",
601            &"e".repeat(65),
602        ] {
603            assert!(!ErrorProfile::is_valid_key(key), "{key}");
604        }
605        let mut manifest = sample_manifest();
606        assert!(serde_json::to_value(&manifest)
607            .unwrap()
608            .get("errors")
609            .is_none());
610        manifest.errors = Some(ErrorProfile {
611            key: "error_message".into(),
612        });
613        assert_eq!(
614            serde_json::to_value(&manifest).unwrap()["errors"],
615            serde_json::json!({"key": "error_message"})
616        );
617    }
618
619    #[test]
620    fn test_get_table() {
621        let manifest = sample_manifest();
622        assert!(manifest.get_table("todos").is_some());
623        assert!(manifest.get_table("nonexistent").is_none());
624    }
625
626    #[test]
627    fn test_schema_hash_deterministic() {
628        let m1 = sample_manifest();
629        let m2 = sample_manifest();
630        assert_eq!(
631            m1.schema_hash().expect("schema hash"),
632            m2.schema_hash().expect("schema hash")
633        );
634    }
635
636    #[test]
637    fn test_schema_hash_changes() {
638        let mut m1 = sample_manifest();
639        let m2 = sample_manifest();
640        m1.tables[0].columns.push(ColumnDefinition {
641            name: "extra".into(),
642            column_type: ColumnType::Text,
643            primary_key: false,
644            nullable: true,
645            auto_generate: false,
646            default_value: None,
647            references: None,
648            on_delete: None,
649            unique: false,
650            validations: vec![],
651            ..Default::default()
652        });
653        assert_ne!(
654            m1.schema_hash().expect("schema hash"),
655            m2.schema_hash().expect("schema hash")
656        );
657    }
658
659    #[test]
660    fn test_fk_serialization() {
661        let manifest = sample_manifest();
662        let json = serde_json::to_string(&manifest).unwrap();
663        assert!(json.contains("\"references\":\"users.id\""));
664        assert!(json.contains("\"on_delete\":\"cascade\""));
665
666        let parsed: ServiceManifest = serde_json::from_str(&json).unwrap();
667        let user_id_col = &parsed.tables[0].columns[2];
668        assert_eq!(user_id_col.references.as_deref(), Some("users.id"));
669        assert_eq!(user_id_col.on_delete, Some(ForeignKeyAction::Cascade));
670    }
671
672    #[test]
673    fn test_service_mode_default() {
674        let json = r#"{"name":"svc","tables":[]}"#;
675        let m: ServiceManifest = serde_json::from_str(json).unwrap();
676        assert_eq!(m.mode, ServiceMode::Crud);
677    }
678
679    #[test]
680    fn test_on_migrate_defaults_to_none() {
681        let json = r#"{"name":"svc","tables":[]}"#;
682        let m: ServiceManifest = serde_json::from_str(json).unwrap();
683        assert!(m.on_migrate.is_none());
684    }
685
686    #[test]
687    fn test_on_migrate_serialization_roundtrip() {
688        let mut m = sample_manifest();
689        m.on_migrate = Some("handle_on_migrate".into());
690        let json = serde_json::to_string(&m).unwrap();
691        assert!(json.contains("\"on_migrate\":\"handle_on_migrate\""));
692        let parsed: ServiceManifest = serde_json::from_str(&json).unwrap();
693        assert_eq!(parsed.on_migrate.as_deref(), Some("handle_on_migrate"));
694    }
695
696    #[test]
697    fn test_on_migrate_skipped_when_none() {
698        let m = sample_manifest();
699        let json = serde_json::to_string(&m).unwrap();
700        assert!(!json.contains("on_migrate"));
701    }
702
703    #[test]
704    fn deploy_hash_covers_fields_schema_hash_ignores() {
705        let m1 = sample_manifest();
706        let mut m2 = sample_manifest();
707        let hash = |m: &ServiceManifest| m.deploy_hash().expect("hash");
708        assert_eq!(hash(&m1), hash(&m2));
709        m2.publishes = Some(vec!["acme.orders.>".into()]);
710        assert_ne!(hash(&m1), hash(&m2));
711        assert_eq!(
712            m1.schema_hash().expect("schema hash"),
713            m2.schema_hash().expect("schema hash")
714        );
715    }
716
717    #[test]
718    fn test_on_migrate_changes_schema_hash() {
719        let m1 = sample_manifest();
720        let mut m2 = sample_manifest();
721        m2.on_migrate = Some("handle_on_migrate".into());
722        assert_ne!(
723            m1.schema_hash().expect("schema hash"),
724            m2.schema_hash().expect("schema hash")
725        );
726    }
727
728    #[test]
729    fn test_requires_wasm_false_for_plain_crud() {
730        let m = sample_manifest();
731        assert!(!m.requires_wasm());
732    }
733
734    #[test]
735    fn test_requires_wasm_true_for_wasm_mode() {
736        let mut m = sample_manifest();
737        m.mode = ServiceMode::Wasm;
738        assert!(m.requires_wasm());
739    }
740
741    #[test]
742    fn a_mode_is_named_as_a_manifest_names_it() {
743        for (mode, on_platform) in [
744            (ServiceMode::Crud, true),
745            (ServiceMode::Wasm, true),
746            (ServiceMode::Container, true),
747            (ServiceMode::Web, false),
748            (ServiceMode::Native, false),
749        ] {
750            assert_eq!(serde_json::to_value(&mode).unwrap(), mode.as_str());
751            assert_eq!(mode.runs_on_platform(), on_platform, "{}", mode.as_str());
752        }
753    }
754
755    #[test]
756    fn a_native_service_runs_no_wasm_and_demands_native_services() {
757        let mut m = sample_manifest();
758        m.on_migrate = Some("handle_on_migrate".into());
759        m.mode = ServiceMode::Native;
760        assert!(!m.requires_wasm());
761        assert!(m.derived_features().contains(features::NATIVE_SERVICES));
762        let json = serde_json::to_value(&m).unwrap();
763        assert_eq!(json["mode"], "native");
764        let parsed: ServiceManifest = serde_json::from_value(json).unwrap();
765        assert_eq!(parsed.mode, ServiceMode::Native);
766    }
767
768    #[test]
769    fn test_requires_wasm_true_for_on_migrate() {
770        let mut m = sample_manifest();
771        m.on_migrate = Some("handle_on_migrate".into());
772        assert!(m.requires_wasm());
773    }
774
775    #[test]
776    fn test_requires_wasm_true_for_table_hooks() {
777        let mut m = sample_manifest();
778        m.tables[0].hooks = Some(TableHooks {
779            before_create: Some("validate".into()),
780            ..Default::default()
781        });
782        assert!(m.requires_wasm());
783    }
784
785    #[test]
786    fn test_requires_wasm_true_for_custom_routes() {
787        let mut m = sample_manifest();
788        m.custom_routes.push(CustomRouteDefinition {
789            method: "GET".into(),
790            path: "/hello".into(),
791            handler: "hello".into(),
792            job: None,
793            posture: None,
794            forward_auth: false,
795            ..Default::default()
796        });
797        assert!(m.requires_wasm());
798    }
799
800    #[test]
801    fn test_requires_wasm_true_for_wasm_subscription() {
802        let mut m = sample_manifest();
803        m.subscriptions.push(SubscriptionDefinition::new(
804            "events.foo",
805            "on_foo",
806            HandlerType::Wasm,
807        ));
808        assert!(m.requires_wasm());
809    }
810
811    #[test]
812    fn test_requires_wasm_false_for_non_wasm_subscription() {
813        let mut m = sample_manifest();
814        m.subscriptions.push(SubscriptionDefinition::new(
815            "events.foo",
816            "on_foo",
817            HandlerType::Webhook,
818        ));
819        assert!(!m.requires_wasm());
820    }
821
822    #[test]
823    fn test_declared_wasm_handlers_collects_all_sources() {
824        let mut m = sample_manifest();
825        m.on_migrate = Some("on_mig".into());
826        m.custom_routes.push(CustomRouteDefinition {
827            method: "GET".into(),
828            path: "/h".into(),
829            handler: "route_h".into(),
830            job: None,
831            posture: None,
832            forward_auth: false,
833            ..Default::default()
834        });
835        m.subscriptions
836            .push(SubscriptionDefinition::new("x", "sub_h", HandlerType::Wasm));
837        m.subscriptions.push(SubscriptionDefinition::new(
838            "y",
839            "wh_ignored",
840            HandlerType::Webhook,
841        ));
842        m.tables[0].hooks = Some(TableHooks {
843            before_create: Some("bc".into()),
844            after_create: Some("ac".into()),
845            before_delete: Some("bc".into()),
846            ..Default::default()
847        });
848        let handlers = m.declared_wasm_handlers();
849        assert!(handlers.contains(&"on_mig"));
850        assert!(handlers.contains(&"route_h"));
851        assert!(handlers.contains(&"sub_h"));
852        assert!(handlers.contains(&"bc"));
853        assert!(handlers.contains(&"ac"));
854        assert!(!handlers.contains(&"wh_ignored"));
855        assert_eq!(handlers.iter().filter(|h| **h == "bc").count(), 1);
856    }
857
858    #[test]
859    fn http_route_exposes_only_custom_routes() {
860        let mut m = sample_manifest();
861        m.on_migrate = Some("on_mig".into());
862        m.custom_routes.push(CustomRouteDefinition {
863            method: "GET".into(),
864            path: "/h".into(),
865            handler: "route_h".into(),
866            job: None,
867            posture: None,
868            forward_auth: false,
869            ..Default::default()
870        });
871        m.subscriptions.push(SubscriptionDefinition::new(
872            "evt.sub",
873            "sub_h",
874            HandlerType::Wasm,
875        ));
876        m.tables[0].hooks = Some(TableHooks {
877            after_create: Some("hook_h".into()),
878            ..Default::default()
879        });
880
881        assert_eq!(
882            m.http_route("route_h").map(|r| r.handler.as_str()),
883            Some("route_h")
884        );
885        assert!(m.http_route("sub_h").is_none());
886        assert!(m.http_route("on_mig").is_none());
887        assert!(m.http_route("hook_h").is_none());
888        assert!(m.http_route("unknown").is_none());
889    }
890
891    #[test]
892    fn http_route_allows_handler_declared_as_both_route_and_subscription() {
893        let mut m = sample_manifest();
894        m.custom_routes.push(CustomRouteDefinition {
895            method: "POST".into(),
896            path: "/dual".into(),
897            handler: "dual".into(),
898            job: Some(JobConfig::default()),
899            posture: None,
900            forward_auth: false,
901            ..Default::default()
902        });
903        m.subscriptions.push(SubscriptionDefinition::new(
904            "evt.dual",
905            "dual",
906            HandlerType::Wasm,
907        ));
908
909        let route = m
910            .http_route("dual")
911            .expect("dual-purpose handler stays HTTP-invocable");
912        assert!(route.job.is_some());
913    }
914
915    #[test]
916    fn posture_aware_detects_any_declared_route() {
917        let mut m = sample_manifest();
918        assert!(!m.is_posture_aware());
919        m.custom_routes.push(CustomRouteDefinition {
920            method: "GET".into(),
921            path: "/a".into(),
922            handler: "a".into(),
923            job: None,
924            posture: None,
925            forward_auth: false,
926            ..Default::default()
927        });
928        assert!(!m.is_posture_aware());
929        m.custom_routes.push(CustomRouteDefinition {
930            method: "GET".into(),
931            path: "/b".into(),
932            handler: "b".into(),
933            job: None,
934            posture: Some(RoutePosture::Authenticated),
935            forward_auth: false,
936            ..Default::default()
937        });
938        assert!(m.is_posture_aware());
939    }
940
941    #[test]
942    fn manifest_publishes_and_features_default_absent() {
943        let json = serde_json::to_value(sample_manifest()).unwrap();
944        assert!(json.get("publishes").is_none());
945        assert!(json.get("required_platform_features").is_none());
946        let legacy = r#"{"name":"s","tables":[],"mode":"crud"}"#;
947        let parsed: ServiceManifest = serde_json::from_str(legacy).unwrap();
948        assert!(parsed.publishes.is_none());
949        assert!(parsed.required_platform_features.is_empty());
950    }
951
952    #[test]
953    fn the_schema_is_the_override_or_the_name_with_underscores() {
954        let mut m = sample_manifest();
955        for (name, schema) in [
956            ("stock-service", "stock_service"),
957            ("loan_service", "loan_service"),
958            ("Blog-Service", "Blog_Service"),
959            ("a-b-c", "a_b_c"),
960        ] {
961            m.name = name.into();
962            assert_eq!(m.schema(), schema);
963            assert_eq!(service_schema(name, None), schema);
964            assert_eq!(service_schema(name, Some("notes")), "notes");
965        }
966        m.schema_name = Some("notes".into());
967        assert_eq!(m.schema(), "notes");
968    }
969
970    #[test]
971    fn migration_bodies_are_stripped_and_nothing_else() {
972        let mut m = sample_manifest();
973        m.migrations = vec![
974            SqlMigration {
975                version: 1,
976                name: "initial_tables".into(),
977                sql: "CREATE TABLE notes ();".into(),
978                no_transaction: false,
979            },
980            SqlMigration {
981                version: 6,
982                name: "add_loan_kind".into(),
983                sql: "-- cufflink:no-transaction\nSELECT 1;".into(),
984                no_transaction: true,
985            },
986        ];
987        let stripped = m.clone().without_migration_bodies();
988        assert!(stripped.migrations.iter().all(|m| m.sql.is_empty()));
989        let shape = |m: &ServiceManifest| -> Vec<(u32, String, bool)> {
990            m.migrations
991                .iter()
992                .map(|m| (m.version, m.name.clone(), m.no_transaction))
993                .collect()
994        };
995        assert_eq!(shape(&stripped), shape(&m));
996        assert_eq!(stripped.name, m.name);
997        assert_eq!(stripped.tables.len(), m.tables.len());
998    }
999
1000    #[test]
1001    fn the_history_defaults_to_refinerys_table() {
1002        let mut m = sample_manifest();
1003        assert_eq!(m.migration_history(), MigrationHistory::default());
1004        let declared = MigrationHistory {
1005            table: "schema_history".into(),
1006            baseline: Some(6),
1007            ..Default::default()
1008        };
1009        m.migration_history = Some(declared.clone());
1010        assert_eq!(m.migration_history(), declared);
1011    }
1012
1013    #[test]
1014    fn schema_ownership_changes_the_schema_hash_only_when_set() {
1015        let base = sample_manifest();
1016        let hash = |m: &ServiceManifest| m.schema_hash().expect("schema hash");
1017        let changed: Vec<ServiceManifest> = vec![
1018            ServiceManifest {
1019                schema: SchemaOwnership::Adopted,
1020                ..base.clone()
1021            },
1022            ServiceManifest {
1023                schema_name: Some("notes".into()),
1024                ..base.clone()
1025            },
1026            ServiceManifest {
1027                migrations: vec![SqlMigration {
1028                    version: 1,
1029                    name: "a".into(),
1030                    sql: "SELECT 1;".into(),
1031                    no_transaction: false,
1032                }],
1033                ..base.clone()
1034            },
1035            ServiceManifest {
1036                migration_history: Some(MigrationHistory::default()),
1037                ..base.clone()
1038            },
1039        ];
1040        let hashes: std::collections::BTreeSet<String> = changed.iter().map(hash).collect();
1041        assert_eq!(hashes.len(), changed.len());
1042        assert!(!hashes.contains(&hash(&base)));
1043    }
1044
1045    #[test]
1046    fn a_schedule_runs_user_code() {
1047        let mut m = sample_manifest();
1048        m.schedules = serde_json::from_value(serde_json::json!([
1049            {"name": "order_retry", "handler": "retry_orders", "spec": {"kind": "every", "secs": 30}}
1050        ]))
1051        .unwrap();
1052        assert!(m.requires_wasm());
1053        assert_eq!(m.declared_wasm_handlers(), ["retry_orders"]);
1054        assert!(m.http_route("retry_orders").is_none());
1055    }
1056
1057    fn private(name: &str) -> TableDefinition {
1058        TableDefinition {
1059            name: name.into(),
1060            columns: vec![ColumnDefinition {
1061                name: "body".into(),
1062                column_type: ColumnType::Text,
1063                ..Default::default()
1064            }],
1065            managed: false,
1066            ..Default::default()
1067        }
1068    }
1069
1070    #[test]
1071    fn declared_tables_chains_both_lists() {
1072        let mut m = sample_manifest();
1073        let names = |m: &ServiceManifest| -> Vec<String> {
1074            m.declared_tables().map(|t| t.name.clone()).collect()
1075        };
1076        assert_eq!(names(&m), ["todos"]);
1077        m.private_tables = vec![private("notes"), private("audit_log")];
1078        assert_eq!(names(&m), ["todos", "notes", "audit_log"]);
1079        m.tables.clear();
1080        assert_eq!(names(&m), ["notes", "audit_log"]);
1081    }
1082
1083    #[test]
1084    fn get_table_does_not_find_a_private_table() {
1085        let mut m = sample_manifest();
1086        m.private_tables = vec![private("notes")];
1087        assert!(m.get_table("todos").is_some());
1088        assert!(m.get_table("notes").is_none());
1089    }
1090
1091    #[test]
1092    fn a_reader_without_the_key_sees_no_private_table() {
1093        let mut m = sample_manifest();
1094        m.private_tables = vec![private("notes")];
1095        let mut wire = serde_json::to_value(&m).unwrap();
1096        assert_eq!(wire["private_tables"][0]["name"], "notes");
1097        wire.as_object_mut().unwrap().remove("private_tables");
1098        let older: ServiceManifest = serde_json::from_value(wire).unwrap();
1099        assert!(older.private_tables.is_empty());
1100        assert!(older.get_table("notes").is_none());
1101        assert_eq!(older.declared_tables().count(), 1);
1102    }
1103
1104    #[test]
1105    fn private_tables_join_the_schema_hash_last_and_only_when_declared() {
1106        use sha2::{Digest, Sha256};
1107        let base = sample_manifest();
1108        let mut declaring = base.clone();
1109        declaring.private_tables = vec![private("notes")];
1110        let parts = |m: &ServiceManifest| {
1111            [
1112                serde_json::to_string(&m.tables).unwrap(),
1113                serde_json::to_string(&m.custom_routes).unwrap(),
1114                serde_json::to_string(&m.subscriptions).unwrap(),
1115                serde_json::to_string(&m.authorization).unwrap(),
1116                serde_json::to_string(&m.on_migrate).unwrap(),
1117            ]
1118            .concat()
1119        };
1120        let hash = |text: String| hex::encode(Sha256::digest(text));
1121        assert_eq!(base.schema_hash().unwrap(), hash(parts(&base)));
1122        assert_eq!(
1123            declaring.schema_hash().unwrap(),
1124            hash(parts(&declaring) + &serde_json::to_string(&declaring.private_tables).unwrap())
1125        );
1126        let mut moved = declaring.clone();
1127        moved.private_tables[0].name = "memos".into();
1128        assert_ne!(
1129            moved.schema_hash().unwrap(),
1130            declaring.schema_hash().unwrap()
1131        );
1132    }
1133
1134    fn documented() -> ServiceManifest {
1135        serde_json::from_value(serde_json::json!({
1136            "name": "catalog-service",
1137            "version": "0.1.0",
1138            "mode": "wasm",
1139            "tables": [],
1140            "routing": "strict",
1141            "openapi": {"title": "Catalog", "servers": [{"url": "https://api.example.com"}]},
1142            "custom_routes": [{
1143                "method": "GET",
1144                "path": "/products",
1145                "handler": "list_products",
1146                "posture": {"kind": "public", "reason": "catalog"},
1147                "doc": {"tags": ["Catalog"]}
1148            }]
1149        }))
1150        .expect("parses")
1151    }
1152
1153    fn public_api() -> PublicDoc {
1154        PublicDoc {
1155            name: "public-api".into(),
1156            mount: "/docs/public-api".into(),
1157            include_tags: vec!["Catalog".into()],
1158            info: PublicDocInfo {
1159                title: "Catalog Public API".into(),
1160                version: "1.0.0".into(),
1161                description: None,
1162                contact: None,
1163            },
1164            servers: vec![],
1165            tags: vec![],
1166            path_prefix: None,
1167            api_key: None,
1168            cors: PublicDocCors::Restricted,
1169        }
1170    }
1171
1172    #[test]
1173    fn a_documented_manifest_without_docs_keeps_its_deploy_hash() {
1174        let manifest = documented();
1175        assert_eq!(
1176            manifest.deploy_hash().expect("hash"),
1177            "1b1ec49a81e9ad3c3fb0dd276aaba2ce75c1d0a3d17667a08f3d940d2e75cd32",
1178            "the hash v0.38.1 gave this manifest"
1179        );
1180        let schema_hash = "80a073df5167dc4b58a94bdec030b5991cc3d13d6896c3812d6434bdd70e0922";
1181        assert_eq!(manifest.schema_hash().expect("schema hash"), schema_hash);
1182        assert!(
1183            serde_json::to_value(&manifest).expect("serializes")["openapi"]
1184                .get("docs")
1185                .is_none()
1186        );
1187
1188        let mut declaring = manifest.clone();
1189        declaring
1190            .openapi
1191            .as_mut()
1192            .expect("openapi")
1193            .docs
1194            .push(public_api());
1195        assert_ne!(declaring.deploy_hash().ok(), manifest.deploy_hash().ok());
1196        assert_eq!(
1197            declaring.schema_hash().expect("schema hash"),
1198            schema_hash,
1199            "documents change no schema"
1200        );
1201        let wire = serde_json::to_value(&declaring).expect("serializes");
1202        assert_eq!(
1203            wire["openapi"]["docs"],
1204            serde_json::json!([{
1205                "name": "public-api",
1206                "mount": "/docs/public-api",
1207                "include_tags": ["Catalog"],
1208                "info": {"title": "Catalog Public API", "version": "1.0.0"}
1209            }])
1210        );
1211        let parsed: ServiceManifest = serde_json::from_value(wire).expect("parses");
1212        assert_eq!(parsed.public_docs().collect::<Vec<_>>(), [&public_api()]);
1213    }
1214
1215    #[test]
1216    fn a_cors_mode_this_platform_does_not_know_still_decodes_the_manifest() {
1217        for (mode, decoded) in [
1218            ("restricted", PublicDocCors::Restricted),
1219            ("any", PublicDocCors::Any),
1220            ("mirror", PublicDocCors::Mirror),
1221            ("reflect", PublicDocCors::Unknown),
1222            ("unknown", PublicDocCors::Unknown),
1223        ] {
1224            let mut wire = serde_json::to_value(documented()).expect("serializes");
1225            let mut doc = serde_json::to_value(public_api()).expect("serializes");
1226            doc["cors"] = mode.into();
1227            wire["openapi"]["docs"] = serde_json::json!([doc]);
1228            let manifest: ServiceManifest = serde_json::from_value(wire).expect("decodes whole");
1229            assert_eq!(
1230                manifest.public_docs().next().map(|doc| doc.cors),
1231                Some(decoded),
1232                "{mode}"
1233            );
1234            assert_eq!(manifest.custom_routes.len(), 1, "{mode}");
1235        }
1236        assert_eq!(
1237            serde_json::to_value(PublicDocCors::Unknown).expect("serializes"),
1238            "unknown"
1239        );
1240        let restricted = serde_json::to_value(public_api()).expect("serializes");
1241        assert!(restricted.get("cors").is_none(), "{restricted}");
1242        let mirrored = PublicDoc {
1243            cors: PublicDocCors::Mirror,
1244            ..public_api()
1245        };
1246        assert_eq!(
1247            serde_json::to_value(mirrored).expect("serializes")["cors"],
1248            "mirror"
1249        );
1250    }
1251
1252    #[test]
1253    fn a_manifest_from_before_route_concurrency_keeps_its_deploy_hash() {
1254        let older = serde_json::json!({
1255            "name": "catalog-service",
1256            "version": "0.1.0",
1257            "mode": "wasm",
1258            "tables": [],
1259            "custom_routes": [{
1260                "method": "POST",
1261                "path": "/reprice",
1262                "handler": "reprice",
1263                "posture": {"kind": "public", "reason": "pinned"},
1264            }],
1265        });
1266        let manifest: ServiceManifest = serde_json::from_value(older.clone()).expect("parses");
1267        assert_eq!(
1268            manifest.deploy_hash().expect("hash"),
1269            "6ff5a2b081b2b65d9d9491fa3743817da838dbfe368b3245a815693cce3f1b2c",
1270            "a deployed manifest without max_concurrent is not redeployed"
1271        );
1272        assert!(!manifest
1273            .derived_features()
1274            .contains(crate::features::ROUTE_CONCURRENCY));
1275
1276        let mut limited = older;
1277        limited["custom_routes"][0]["max_concurrent"] = 2.into();
1278        let limited: ServiceManifest = serde_json::from_value(limited).expect("parses");
1279        assert_ne!(limited.deploy_hash().ok(), manifest.deploy_hash().ok());
1280        assert!(limited
1281            .derived_features()
1282            .contains(crate::features::ROUTE_CONCURRENCY));
1283    }
1284}