Skip to main content

cufflink_types/
features.rs

1//! Platform capability names: what `/api/version` advertises in `supports`
2//! and a manifest may demand in `required_platform_features`.
3
4use crate::{
5    CustomRouteDefinition, ScheduleDefinition, ServiceManifest, SubscriptionDefinition,
6    TableDefinition,
7};
8use std::collections::BTreeSet;
9
10pub const ROUTE_POSTURE: &str = "route_posture";
11pub const DB_V2: &str = "db_v2";
12pub const CACHE: &str = "cache";
13pub const SERVICE_CALL: &str = "service_call";
14pub const RESPONSE_V2: &str = "response_v2";
15pub const RESPONSE_RAW_JSON: &str = "response_raw_json";
16pub const SSE_BRIDGE: &str = "sse_bridge";
17pub const ROUTE_MATCHING: &str = "route_matching";
18pub const ROUTE_LIMITS: &str = "route_limits";
19pub const ROUTE_CONCURRENCY: &str = "route_concurrency";
20pub const ERROR_PROFILE: &str = "error_profile";
21pub const INTERNAL_POSTURE: &str = "internal_posture";
22pub const API_KEY_POSTURE: &str = "api_key_posture";
23pub const SCOPED_PERMISSIONS: &str = "scoped_permissions";
24pub const SCOPED_POSTURE: &str = "scoped_posture";
25pub const TYPED_ROUTES: &str = "typed_routes";
26pub const NATS_CONSUMER_CONFIG: &str = "nats_consumer_config";
27pub const NATS_MESSAGE_META: &str = "nats_message_meta";
28pub const NATS_PUBLISH_V2: &str = "nats_publish_v2";
29pub const STREAMS: &str = "streams";
30pub const SCHEDULES: &str = "schedules";
31pub const JOBS_V2: &str = "jobs_v2";
32pub const DELIVERY_CONTROL: &str = "delivery_control";
33pub const HTTP_V2: &str = "http_v2";
34pub const STORAGE_V2: &str = "storage_v2";
35pub const STORAGE_ACL: &str = "storage_acl";
36pub const TENANT_BUCKETS: &str = "tenant_buckets";
37pub const UTIL_V2: &str = "util_v2";
38pub const SCHEMA_ADOPTED: &str = "schema_adopted";
39pub const SQL_MIGRATIONS: &str = "sql_migrations";
40pub const COLUMN_TYPES_V2: &str = "column_types_v2";
41pub const AUDIT_REDACTION: &str = "audit_redaction";
42pub const KEYSET_LISTS: &str = "keyset_lists";
43pub const OUTBOX: &str = "outbox";
44pub const DB_ROLES: &str = "db_roles";
45pub const SCHEMA_GUARD: &str = "schema_guard";
46pub const NAMESPACE_CLAIMS: &str = "namespace_claims";
47pub const SECRET_ENCRYPTION: &str = "secret_encryption";
48pub const CONSUMER_RECONCILER: &str = "consumer_reconciler";
49pub const ASYNC_DEPLOY: &str = "async_deploy";
50pub const EXT_CALL: &str = "ext_call";
51pub const NATIVE_SERVICES: &str = "native_services";
52pub const PRIVATE_TABLES: &str = "private_tables";
53pub const INACTIVE_DEPLOY: &str = "inactive_deploy";
54pub const CONFIG_APPLY: &str = "config_apply";
55pub const COLUMN_PERMISSIONS: &str = "column_permissions";
56pub const GUEST_MEMORY_BUDGET: &str = "guest_memory_budget";
57pub const GUEST_STATEMENT_TIMEOUT: &str = "guest_statement_timeout";
58pub const SQL_PARSE: &str = "sql_parse";
59pub const WEB_RELEASES: &str = "web_releases";
60pub const PUBLIC_DOCS: &str = "public_docs";
61
62impl ServiceManifest {
63    /// Features this manifest's declared shape requires, sorted and
64    /// deduplicated. A manifest that needs a capability always demands it, so
65    /// a platform too old to provide it rejects the deploy instead of silently
66    /// running the service without it.
67    pub fn derived_features(&self) -> BTreeSet<&'static str> {
68        self.custom_routes
69            .iter()
70            .flat_map(CustomRouteDefinition::derived_features)
71            .chain(
72                self.declared_tables()
73                    .flat_map(TableDefinition::derived_features),
74            )
75            .chain(
76                self.subscriptions
77                    .iter()
78                    .flat_map(SubscriptionDefinition::derived_features),
79            )
80            .chain(
81                self.schedules
82                    .iter()
83                    .flat_map(ScheduleDefinition::derived_features),
84            )
85            .chain(self.service_features())
86            .collect()
87    }
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93    use crate::manifest::fixtures::sample_manifest;
94    use crate::RoutePosture;
95    use serde_json::Value;
96
97    const SAMPLE: &str = include_str!("../fixtures/sample_manifest.json");
98    const TODO: &str = include_str!("../fixtures/todo_manifest.json");
99    const BLOG: &str = include_str!("../fixtures/blog_manifest.json");
100    /// Every shape v0.27.0 accepted, canonicalised and hashed by v0.27.0.
101    /// It wrote a subscription's `config` in an order that changed from
102    /// one process to the next; the hashes are those of the runs that
103    /// wrote it in the order of its keys, as every run does now.
104    const LEGACY_SHAPES: &str = include_str!("../fixtures/legacy_shapes_manifest.json");
105
106    fn manifest(json: &str) -> ServiceManifest {
107        serde_json::from_str(json).expect("fixture manifest")
108    }
109
110    fn route(handler: &str, posture: Option<RoutePosture>) -> CustomRouteDefinition {
111        CustomRouteDefinition {
112            method: "GET".into(),
113            path: format!("/{handler}"),
114            handler: handler.into(),
115            job: None,
116            posture,
117            forward_auth: false,
118            ..Default::default()
119        }
120    }
121
122    #[test]
123    fn sample_manifest_derives_only_route_posture() {
124        let sample = manifest(SAMPLE);
125        assert_eq!(sample.derived_features(), BTreeSet::from([ROUTE_POSTURE]));
126        assert_eq!(sample.required_platform_features, vec![ROUTE_POSTURE]);
127        for crud_only in [TODO, BLOG] {
128            assert!(manifest(crud_only).derived_features().is_empty());
129        }
130    }
131
132    #[test]
133    fn route_posture_is_derived_once_from_any_declared_posture() {
134        let mut m = sample_manifest();
135        assert!(m.derived_features().is_empty());
136        m.custom_routes.push(route("legacy", None));
137        assert!(m.derived_features().is_empty());
138        m.custom_routes
139            .push(route("me", Some(RoutePosture::Authenticated)));
140        m.custom_routes.push(route(
141            "hook",
142            Some(RoutePosture::Public {
143                reason: "signed webhook".into(),
144            }),
145        ));
146        assert_eq!(m.derived_features(), BTreeSet::from([ROUTE_POSTURE]));
147    }
148
149    #[test]
150    fn strict_routing_demands_route_matching() {
151        let mut m = sample_manifest();
152        m.routing = crate::RoutingMode::Strict;
153        assert_eq!(m.derived_features(), BTreeSet::from([ROUTE_MATCHING]));
154    }
155
156    #[test]
157    fn an_error_profile_demands_error_profile() {
158        let mut m = sample_manifest();
159        m.errors = Some(crate::ErrorProfile {
160            key: "error_message".into(),
161        });
162        assert_eq!(m.derived_features(), BTreeSet::from([ERROR_PROFILE]));
163    }
164
165    fn sql_migration() -> crate::SqlMigration {
166        crate::SqlMigration {
167            version: 1,
168            name: "initial_tables".into(),
169            sql: "CREATE TABLE loans ();".into(),
170            no_transaction: false,
171        }
172    }
173
174    fn stream() -> crate::StreamDefinition {
175        serde_json::from_value(serde_json::json!({
176            "name": "LOANS", "subjects": ["loans.created"], "retention": "limits"
177        }))
178        .expect("stream")
179    }
180
181    fn schedule() -> crate::ScheduleDefinition {
182        serde_json::from_value(serde_json::json!({
183            "name": "order_retry", "handler": "retry_orders", "spec": {"kind": "every", "secs": 30}
184        }))
185        .expect("schedule")
186    }
187
188    fn private_table() -> TableDefinition {
189        serde_json::from_value(serde_json::json!({
190            "name": "loans", "managed": false,
191            "columns": [{"name": "body", "column_type": "text"}]
192        }))
193        .expect("table")
194    }
195
196    /// One case per R3 field: where the field lands in the manifest JSON,
197    /// the manifest before it is set, the same manifest with only that
198    /// field set, and the features it demands.
199    fn r3_fields() -> Vec<(
200        &'static str,
201        ServiceManifest,
202        ServiceManifest,
203        Vec<&'static str>,
204    )> {
205        use crate::{
206            AckMode, ConsumerNaming, HandlerType, JobConfig, MigrationHistory, Pagination, RetryOn,
207            SchemaOwnership,
208        };
209        let base = || manifest(SAMPLE);
210        let subscribed = || {
211            let mut m = base();
212            m.subscriptions.insert(
213                0,
214                SubscriptionDefinition::new("dw.{tenant}.items.created", "h", HandlerType::Wasm),
215            );
216            m
217        };
218        let service =
219            |pointer, after: ServiceManifest, features| (pointer, base(), after, features);
220        let table = |pointer, edit: fn(&mut TableDefinition), features| {
221            let mut after = base();
222            edit(&mut after.tables[0]);
223            (pointer, base(), after, features)
224        };
225        let route = |pointer, edit: fn(&mut crate::CustomRouteDefinition), features| {
226            let mut after = base();
227            edit(&mut after.custom_routes[0]);
228            (pointer, base(), after, features)
229        };
230        let subscription = |pointer, edit: fn(&mut SubscriptionDefinition), features| {
231            let mut after = subscribed();
232            edit(&mut after.subscriptions[0]);
233            (pointer, subscribed(), after, features)
234        };
235        vec![
236            service(
237                "/consumers",
238                ServiceManifest {
239                    consumers: ConsumerNaming::Scoped,
240                    ..base()
241                },
242                vec![NATS_CONSUMER_CONFIG],
243            ),
244            service(
245                "/streams",
246                ServiceManifest {
247                    streams: vec![stream()],
248                    ..base()
249                },
250                vec![STREAMS],
251            ),
252            service(
253                "/schedules",
254                ServiceManifest {
255                    schedules: vec![schedule()],
256                    ..base()
257                },
258                vec![SCHEDULES],
259            ),
260            service(
261                "/schedules/0/job/retry_on",
262                ServiceManifest {
263                    schedules: vec![crate::ScheduleDefinition {
264                        job: Some(JobConfig {
265                            retry_on: vec![RetryOn::Timeout],
266                            ..Default::default()
267                        }),
268                        ..schedule()
269                    }],
270                    ..base()
271                },
272                vec![SCHEDULES, JOBS_V2],
273            ),
274            service(
275                "/schema",
276                ServiceManifest {
277                    schema: SchemaOwnership::Adopted,
278                    ..base()
279                },
280                vec![SCHEMA_ADOPTED],
281            ),
282            service(
283                "/schema_name",
284                ServiceManifest {
285                    schema_name: Some("loan_service".into()),
286                    ..base()
287                },
288                vec![SCHEMA_ADOPTED],
289            ),
290            service(
291                "/migrations",
292                ServiceManifest {
293                    migrations: vec![sql_migration()],
294                    ..base()
295                },
296                vec![SQL_MIGRATIONS],
297            ),
298            service(
299                "/extensions",
300                ServiceManifest {
301                    extensions: vec!["google.token".into()],
302                    ..base()
303                },
304                vec![EXT_CALL],
305            ),
306            service(
307                "/provides",
308                ServiceManifest {
309                    mode: crate::ServiceMode::Native,
310                    provides: vec![crate::ProvidedExtension {
311                        name: "google.token".into(),
312                        callers: vec!["reports-service".into()],
313                    }],
314                    ..base()
315                },
316                vec![NATIVE_SERVICES],
317            ),
318            service(
319                "/migration_history",
320                ServiceManifest {
321                    migration_history: Some(MigrationHistory::default()),
322                    ..base()
323                },
324                vec![],
325            ),
326            subscription(
327                "/subscriptions/0/ack",
328                |s| s.ack = AckMode::OnSuccess,
329                vec![NATS_CONSUMER_CONFIG],
330            ),
331            subscription(
332                "/subscriptions/0/consumer",
333                |s| s.consumer = Some(Default::default()),
334                vec![NATS_CONSUMER_CONFIG],
335            ),
336            subscription(
337                "/subscriptions/0/timeout_secs",
338                |s| s.timeout_secs = Some(30),
339                vec![NATS_CONSUMER_CONFIG],
340            ),
341            table(
342                "/tables/0/managed",
343                |t| t.managed = false,
344                vec![SCHEMA_ADOPTED],
345            ),
346            table(
347                "/tables/0/checks",
348                |t| {
349                    t.checks.push(crate::CheckConstraint {
350                        name: "c".into(),
351                        expr: "a > 0".into(),
352                    })
353                },
354                vec![COLUMN_TYPES_V2],
355            ),
356            table(
357                "/tables/0/search",
358                |t| t.search = Some(Default::default()),
359                vec![COLUMN_TYPES_V2],
360            ),
361            table(
362                "/tables/0/indexes/0/predicate",
363                |t| {
364                    t.indexes.insert(
365                        0,
366                        crate::IndexDefinition {
367                            name: "i".into(),
368                            columns: vec!["id".into()],
369                            predicate: Some("id IS NOT NULL".into()),
370                            ..Default::default()
371                        },
372                    )
373                },
374                vec![COLUMN_TYPES_V2],
375            ),
376            table(
377                "/tables/0/indexes/0/method",
378                |t| {
379                    t.indexes.insert(
380                        0,
381                        crate::IndexDefinition {
382                            name: "i".into(),
383                            columns: vec!["id".into()],
384                            method: crate::IndexMethod::Hash,
385                            ..Default::default()
386                        },
387                    )
388                },
389                vec![COLUMN_TYPES_V2],
390            ),
391            table(
392                "/tables/0/audit_redact",
393                |t| t.audit_redact.push("dob".into()),
394                vec![AUDIT_REDACTION],
395            ),
396            table(
397                "/tables/0/sensitive",
398                |t| t.sensitive = true,
399                vec![AUDIT_REDACTION],
400            ),
401            route(
402                "/custom_routes/0/audit_redact",
403                |r| r.audit_redact.push("card.number".into()),
404                vec![AUDIT_REDACTION],
405            ),
406            route(
407                "/custom_routes/0/max_concurrent",
408                |r| r.max_concurrent = Some(4),
409                vec![ROUTE_CONCURRENCY],
410            ),
411            table(
412                "/tables/0/pagination",
413                |t| t.pagination = Pagination::Keyset,
414                vec![KEYSET_LISTS],
415            ),
416            table(
417                "/tables/0/columns/1/access",
418                |t| {
419                    t.columns[1].access = Some(crate::ColumnAccess {
420                        read: Some("internal".into()),
421                        write: None,
422                    })
423                },
424                vec![COLUMN_PERMISSIONS],
425            ),
426            service(
427                "/private_tables",
428                ServiceManifest {
429                    private_tables: vec![private_table()],
430                    ..base()
431                },
432                vec![PRIVATE_TABLES, SCHEMA_ADOPTED],
433            ),
434        ]
435    }
436
437    fn json(manifest: &ServiceManifest) -> Value {
438        serde_json::to_value(manifest).expect("serialize")
439    }
440
441    #[test]
442    fn every_r3_field_is_absent_until_it_is_set() {
443        for (pointer, before, after, _) in r3_fields() {
444            assert_eq!(json(&before).pointer(pointer), None, "{pointer}");
445            assert!(json(&after).pointer(pointer).is_some(), "{pointer}");
446        }
447    }
448
449    #[test]
450    fn every_r3_field_changes_the_hash_and_round_trips() {
451        for (pointer, before, after, _) in r3_fields() {
452            assert_ne!(
453                after.deploy_hash().expect("hash"),
454                before.deploy_hash().expect("hash"),
455                "{pointer}"
456            );
457            let wire = json(&after);
458            let reparsed: ServiceManifest = serde_json::from_value(wire.clone()).expect("parse");
459            assert_eq!(json(&reparsed), wire, "{pointer}");
460        }
461    }
462
463    #[test]
464    fn every_r3_field_demands_its_features() {
465        for (pointer, before, after, demanded) in r3_fields() {
466            assert_eq!(
467                before.derived_features(),
468                BTreeSet::from([ROUTE_POSTURE]),
469                "{pointer}"
470            );
471            let expected: BTreeSet<&str> = demanded.into_iter().chain([ROUTE_POSTURE]).collect();
472            assert_eq!(after.derived_features(), expected, "{pointer}");
473        }
474    }
475
476    #[test]
477    fn deploy_hash_unchanged_for_legacy_manifest() {
478        for (json, deploy, schema) in [
479            (
480                SAMPLE,
481                "eee68954141745273b4157ffa4da676f33db4a908f63949bc9a4d7a2a437a17e",
482                "c1bfff7742704c2d5c1849a6eb964cece595080d25bcddf9e899dbd137ce5978",
483            ),
484            (
485                TODO,
486                "927dfafc66a426e311dc92eee91f2964e6ad450f7d57266a8cab4300a1359bab",
487                "aa0463d8a7e1fd9e3c6bca62fa0480e4ee6ce4083d17441f02061dca699e9907",
488            ),
489            (
490                BLOG,
491                "9d931c651c3bff3d9be5105b7867ffae01913757bdd8db0a13b1337dd17b7ae5",
492                "98cd636af82779af1d42ccc7f7daff5b1fd0e70cb553a15233ce4a4e3655e43f",
493            ),
494            (
495                LEGACY_SHAPES,
496                "6bcd77c75c7980173facd21b6032b82636e6ec4119c0c6636acd1a67a1f2343a",
497                "11dc0ab100791653dc63e43a52d5c870ccf2a9d6997f64775664887400107439",
498            ),
499        ] {
500            let m = manifest(json);
501            assert_eq!(m.deploy_hash().expect("hash"), deploy, "{}", m.name);
502            assert_eq!(m.schema_hash().expect("schema hash"), schema, "{}", m.name);
503        }
504    }
505
506    #[test]
507    fn a_manifest_without_private_tables_serialises_as_before() {
508        for json in [SAMPLE, TODO, BLOG, LEGACY_SHAPES] {
509            let stored: Value = serde_json::from_str(json).expect("fixture json");
510            let m = manifest(json);
511            assert!(m.private_tables.is_empty(), "{}", m.name);
512            let wire = serde_json::to_value(&m).expect("serialize");
513            assert_eq!(wire.get("private_tables"), None, "{}", m.name);
514            assert_eq!(wire, stored, "{}", m.name);
515            assert_eq!(m.declared_tables().count(), m.tables.len(), "{}", m.name);
516        }
517    }
518
519    #[test]
520    fn private_tables_demand_their_feature() {
521        let mut m = sample_manifest();
522        assert!(m.derived_features().is_empty());
523        m.private_tables = vec![private_table()];
524        assert_eq!(
525            m.derived_features(),
526            BTreeSet::from([PRIVATE_TABLES, SCHEMA_ADOPTED])
527        );
528        m.private_tables[0].columns[0].column_type = crate::ColumnType::JsonbArray;
529        assert_eq!(
530            m.derived_features(),
531            BTreeSet::from([COLUMN_TYPES_V2, PRIVATE_TABLES, SCHEMA_ADOPTED])
532        );
533    }
534
535    #[test]
536    fn public_docs_are_demanded_only_by_a_manifest_declaring_one() {
537        let mut m = sample_manifest();
538        m.openapi = Some(crate::OpenApiOptions::default());
539        assert!(!m.derived_features().contains(PUBLIC_DOCS));
540        m.openapi = Some(crate::OpenApiOptions {
541            docs: vec![serde_json::from_value(serde_json::json!({
542                "name": "public-api",
543                "mount": "/docs/public-api",
544                "include_tags": ["Catalog"],
545                "info": {"title": "Catalog Public API", "version": "1.0.0"}
546            }))
547            .expect("document")],
548            ..Default::default()
549        });
550        assert_eq!(m.derived_features(), BTreeSet::from([PUBLIC_DOCS]));
551    }
552
553    #[test]
554    fn legacy_manifest_json_round_trips_unchanged() {
555        for json in [SAMPLE, TODO, BLOG, LEGACY_SHAPES] {
556            let stored: Value = serde_json::from_str(json).expect("fixture json");
557            let reserialized = serde_json::to_value(manifest(json)).expect("serialize");
558            assert_eq!(reserialized, stored);
559        }
560    }
561
562    #[test]
563    fn a_legacy_manifest_demands_what_it_demanded_of_v0_27_0() {
564        assert_eq!(
565            manifest(LEGACY_SHAPES).derived_features(),
566            BTreeSet::from([
567                "api_key_posture",
568                "error_profile",
569                "internal_posture",
570                "route_limits",
571                "route_matching",
572                "route_posture",
573                "scoped_permissions",
574                "scoped_posture",
575                "sse_bridge",
576            ])
577        );
578    }
579}