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