keldra-api 0.11.0

Rust gRPC API types for Keldra object storage
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
//! Generated Rust types for the Keldra 0.11 gRPC API.

pub mod v1 {
    tonic::include_proto!("keldra.v1");
}

#[cfg(test)]
mod tests {
    use super::v1::{DeletedObject, NeverExisted, ObjectHead, PresentObject, object_head};

    #[test]
    fn exact_path_states_are_distinct() {
        let states = [
            ObjectHead {
                state: Some(object_head::State::Present(PresentObject {
                    version: 7,
                    content_hash: vec![7; 32],
                    content_length: 99,
                    content_type: String::new(),
                })),
            },
            ObjectHead {
                state: Some(object_head::State::Deleted(DeletedObject { version: 8 })),
            },
            ObjectHead {
                state: Some(object_head::State::NeverExisted(NeverExisted {})),
            },
        ];

        assert!(matches!(
            &states[0].state,
            Some(object_head::State::Present(_))
        ));
        assert!(matches!(
            &states[1].state,
            Some(object_head::State::Deleted(_))
        ));
        assert!(matches!(
            &states[2].state,
            Some(object_head::State::NeverExisted(_))
        ));
    }

    #[test]
    fn schema_keeps_removed_capabilities_out() {
        let schema = include_str!("../proto/keldra.proto").to_ascii_lowercase();
        for forbidden in [
            "rpc uploadblob",
            "rpc publishobject",
            "rpc putobject",
            "message blobref",
            "rpc listprefix",
            "rpc begintransaction",
            "rpc committransaction",
            "personaldb",
        ] {
            assert!(!schema.contains(forbidden), "schema contains `{forbidden}`");
        }

        assert!(schema.contains("executor_nomination_log_index"));
        assert!(schema.contains("commit_log_index"));
        assert!(schema.contains("immutable_path_prefixes"));
        assert!(schema.contains("program_only_path_prefixes"));
        assert!(!schema.contains("rpc registerprogram"));
        assert!(!schema.contains("message registerprogram"));
        assert!(schema.contains("objectaddress program"));
        assert!(schema.contains("_keldra/programs/{name}@{version}"));
        assert!(schema.contains("rpc startput(putheader) returns (puttoken)"));
        assert!(schema.contains("rpc put(stream putrequest) returns (puttoken)"));
        assert!(schema.contains("rpc putend(puttoken) returns (mutationreceipt)"));
        for rpc in [
            "rpc createindex(createindexrequest)",
            "rpc updateindex(updateindexrequest)",
            "rpc getindex(getindexrequest)",
            "rpc listindices(listindicesrequest)",
            "rpc deleteindex(deleteindexrequest)",
            "rpc queryindex(queryindexrequest)",
        ] {
            assert!(schema.contains(rpc), "schema is missing `{rpc}`");
        }
        assert!(schema.contains("index_kind_tensor"));
        assert!(schema.contains("tensorindexspec tensor"));
        assert!(schema.contains("tensorindexquery tensor"));

        for rpc in [
            "rpc exchangeclientcredentials",
            "rpc provisiontenant",
            "rpc createapplication",
            "rpc rotateapplicationcredential",
            "rpc disableapplicationcredential",
            "rpc createbucket",
            "rpc grantapplicationrole",
            "rpc revokeapplicationrole",
            "rpc putschema",
            "rpc bindschema",
            "rpc getbinding",
            "rpc getschema",
            "rpc mutatetuples",
            "rpc readtuples",
            "rpc checkpermission",
            "rpc checkpermissions",
            "rpc watchprefix",
            "rpc listobjects",
            "rpc deleteversion",
            "rpc listobjectversions",
            "rpc setbucketversioning",
        ] {
            assert!(schema.contains(rpc), "schema is missing `{rpc}`");
        }
        for forbidden in [
            "rpc createrealm",
            "rpc deleterealm",
            "rpc applyschema",
            "zookie",
            "caveat",
            "publication_metadata",
            "insecure_no_auth",
            "api_token",
        ] {
            assert!(!schema.contains(forbidden), "schema contains `{forbidden}`");
        }
    }

    #[test]
    fn generated_index_client_is_publicly_exposed() {
        let _: Option<
            super::v1::index_service_client::IndexServiceClient<tonic::transport::Channel>,
        > = None;
    }

    #[test]
    fn typed_json_fields_have_explicit_type_cardinality_and_capabilities() {
        use super::v1::{
            IndexField, IndexFieldCapability, IndexFieldCardinality, KeywordIndexField, index_field,
        };

        let field = IndexField {
            name: "document_id".into(),
            json_pointer: "/id".into(),
            cardinality: IndexFieldCardinality::Single as i32,
            capabilities: vec![IndexFieldCapability::Exact as i32],
            field_type: Some(index_field::FieldType::Keyword(KeywordIndexField {})),
        };

        assert!(matches!(
            field.field_type,
            Some(index_field::FieldType::Keyword(_))
        ));
        assert_eq!(field.capabilities, [IndexFieldCapability::Exact as i32]);

        let schema = include_str!("../proto/keldra.proto").to_ascii_lowercase();
        assert!(schema.contains("rpc listindices(listindicesrequest)"));
        assert!(schema.contains("repeated indexdefinition indices = 1"));
        assert!(!schema.contains("listindexes"));
        assert!(!schema.contains("fields_json"));
        assert!(!schema.contains("bool multi_valued"));
    }

    #[test]
    fn typed_json_queries_expose_fielded_text_facets_and_aggregates() {
        use super::v1::{
            IndexAggregateOperation, IndexAggregateRequest, IndexAggregateResult, IndexFacetBucket,
            IndexFacetRequest, IndexFacetResult, IndexPredicate, IndexPredicateOperator,
            IndexQueryHit, QueryIndexResponse, TypedJsonIndexQuery,
        };

        let query = TypedJsonIndexQuery {
            predicates: vec![
                IndexPredicate {
                    field: "summary".into(),
                    operator: IndexPredicateOperator::FullText as i32,
                    values_json: vec![br#""memory safety""#.to_vec()],
                },
                IndexPredicate {
                    field: "summary".into(),
                    operator: IndexPredicateOperator::Phrase as i32,
                    values_json: vec![br#""memory safety""#.to_vec()],
                },
            ],
            order: Vec::new(),
            facets: vec![IndexFacetRequest {
                field: "ecosystem".into(),
                limit: 10,
            }],
            aggregates: vec![IndexAggregateRequest {
                field: "severity".into(),
                operation: IndexAggregateOperation::Average as i32,
            }],
        };
        let response = QueryIndexResponse {
            hits: vec![IndexQueryHit {
                address: None,
                object_version: 7,
                score: Some(0.75),
            }],
            next_page_token: Vec::new(),
            freshness: None,
            facet_results: vec![IndexFacetResult {
                field: "ecosystem".into(),
                buckets: vec![IndexFacetBucket {
                    value_json: br#""cargo""#.to_vec(),
                    count: 4,
                }],
            }],
            aggregate_results: vec![IndexAggregateResult {
                field: "severity".into(),
                operation: IndexAggregateOperation::Average as i32,
                value_json: Some(b"7.5".to_vec()),
                contributing_count: 4,
            }],
        };

        assert_eq!(query.facets[0].limit, 10);
        assert_eq!(response.hits[0].object_version, 7);
        assert_eq!(response.aggregate_results[0].contributing_count, 4);
    }

    #[test]
    fn generated_personaldb_client_is_publicly_exposed() {
        let _: Option<
            super::v1::personal_db_service_client::PersonalDbServiceClient<
                tonic::transport::Channel,
            >,
        > = None;

        let schema = include_str!("../proto/personaldb.proto").to_ascii_lowercase();
        for rpc in [
            "rpc creategroup(",
            "rpc describegroup(",
            "rpc listgroups(",
            "rpc grantgrouprole(",
            "rpc revokegrouprole(",
            "rpc appendentry(",
            "rpc materializeprojection(",
            "rpc catchup(",
            "rpc registersnapshot(",
            "rpc getsnapshot(",
        ] {
            assert!(schema.contains(rpc), "PersonalDB schema is missing `{rpc}`");
        }
    }

    #[test]
    fn object_surface_has_only_explicit_typed_mutations() {
        use super::v1::{
            BulkOperation, BulkPutIfVersionRequest, CreateBucketRequest, DeleteIfVersionRequest,
            DeleteRequest, DeleteVersionRequest, DeleteVersionResponse, Durability,
            ListObjectsRequest, ListObjectsResponse, ObjectAddress, ObjectVersioning, PutHeader,
            PutIfVersionOperation, PutRequest, PutToken, bulk_operation, put_header,
        };

        let address = Some(ObjectAddress {
            tenant: "acme".into(),
            bucket: "objects".into(),
            path: "one".into(),
        });
        let header = PutHeader {
            address: address.clone(),
            content_type: "application/json".into(),
            command_id: "command-1".into(),
            durability: Durability::Local as i32,
            operation: Some(put_header::Operation::PutIfVersion(PutIfVersionOperation {
                expected_version: 8,
            })),
        };
        let frame = PutRequest {
            token: Some(PutToken {
                value: b"opaque".to_vec(),
                expires_at: None,
            }),
            chunk: Vec::new(),
        };
        assert!(matches!(
            header.operation,
            Some(put_header::Operation::PutIfVersion(_))
        ));
        assert!(frame.chunk.is_empty());

        let operations = [
            bulk_operation::Operation::Put(Default::default()),
            bulk_operation::Operation::PutIfAbsent(Default::default()),
            bulk_operation::Operation::PutIfVersion(BulkPutIfVersionRequest::default()),
            bulk_operation::Operation::PutImmutable(Default::default()),
            bulk_operation::Operation::Delete(DeleteRequest {
                address: address.clone(),
                ..Default::default()
            }),
            bulk_operation::Operation::DeleteIfVersion(DeleteIfVersionRequest {
                address: address.clone(),
                expected_version: 8,
                ..Default::default()
            }),
        ];
        assert_eq!(
            operations
                .into_iter()
                .map(|operation| BulkOperation {
                    operation: Some(operation),
                })
                .count(),
            6
        );

        let current_head_delete = DeleteIfVersionRequest {
            address: address.clone(),
            expected_version: 8,
            ..Default::default()
        };
        let retained_version_delete = DeleteVersionRequest {
            address,
            version: 7,
            ..Default::default()
        };
        assert_eq!(current_head_delete.expected_version, 8);
        assert_eq!(retained_version_delete.version, 7);
        let replaced_current = DeleteVersionResponse {
            deleted: true,
            replacement_tombstone_version: Some(9),
        };
        assert_eq!(replaced_current.replacement_tombstone_version, Some(9));
        assert_eq!(
            CreateBucketRequest::default().versioning,
            ObjectVersioning::Unversioned as i32
        );

        let list_request = ListObjectsRequest {
            tenant: "acme".into(),
            bucket: "objects".into(),
            prefix: "reports/".into(),
            start_after: Some("reports/2025.json".into()),
            limit: 100,
        };
        let list_response = ListObjectsResponse {
            paths: vec!["reports/2026.json".into()],
            has_more: false,
        };
        assert_eq!(
            list_request.start_after.as_deref(),
            Some("reports/2025.json")
        );
        assert_eq!(list_response.paths, vec!["reports/2026.json".to_owned()]);
    }

    #[test]
    fn authorization_wire_types_preserve_scope_and_typed_unions() {
        use super::v1::{
            AnyUsersetSelector, AtLeastRevision, AuthzConsistency, AuthzScope, DirectRelation,
            InheritRule, NamespaceDefinition, ObjectRef, Permission, PermissionRule,
            PutSchemaRequest, RelationDefinition, SubjectSelector, Userset, authz_consistency,
            object_ref, permission_rule, relation_definition, subject, subject_selector,
        };

        let account = ObjectRef {
            namespace: "account".into(),
            id: Some(object_ref::Id::OpaqueId("acme".into())),
        };
        let members = Userset {
            object: Some(account),
            relation: "member".into(),
        };
        let schema = NamespaceDefinition {
            name: "ledger".into(),
            relations: vec![
                RelationDefinition {
                    name: "reader".into(),
                    kind: Some(relation_definition::Kind::Direct(DirectRelation {
                        allowed_subjects: vec![SubjectSelector {
                            selector: Some(subject_selector::Selector::AnyUserset(
                                AnyUsersetSelector {
                                    namespace: "account".into(),
                                    relation: "member".into(),
                                },
                            )),
                        }],
                    })),
                },
                RelationDefinition {
                    name: "read".into(),
                    kind: Some(relation_definition::Kind::Permission(Permission {
                        rules: vec![PermissionRule {
                            rule: Some(permission_rule::Rule::Inherit(InheritRule {
                                relation: "reader".into(),
                            })),
                        }],
                    })),
                },
            ],
        };
        let subject = super::v1::Subject {
            kind: Some(subject::Kind::Userset(members)),
        };
        let publication = PutSchemaRequest {
            schema_id: "acme".into(),
            namespaces: vec![schema],
        };
        let consistency = AuthzConsistency {
            requirement: Some(authz_consistency::Requirement::AtLeast(AtLeastRevision {
                revision: 42,
            })),
        };
        let system_scope = AuthzScope {
            storage_tenant: "keldra-internal".into(),
            realm: "_keldra/system".into(),
        };

        assert_eq!(publication.namespaces[0].relations.len(), 2);
        assert!(matches!(subject.kind, Some(subject::Kind::Userset(_))));
        assert!(matches!(
            consistency.requirement,
            Some(authz_consistency::Requirement::AtLeast(AtLeastRevision {
                revision: 42
            }))
        ));
        assert_eq!(system_scope.realm, "_keldra/system");
    }

    #[test]
    fn tuple_mutation_and_batch_checks_share_request_scope() {
        use super::v1::{
            AuthzScope, CheckPermissionsRequest, MutateTuplesRequest, ObjectRef, PermissionCheck,
            RelationTuple, Subject, TupleMutation, authz_consistency, object_ref, subject,
            tuple_mutation,
        };

        let scope = AuthzScope {
            storage_tenant: "acme".into(),
            realm: "default".into(),
        };
        let ledger = ObjectRef {
            namespace: "ledger".into(),
            id: Some(object_ref::Id::OpaqueId("main".into())),
        };
        let alice = Subject {
            kind: Some(subject::Kind::Object(ObjectRef {
                namespace: "user".into(),
                id: Some(object_ref::Id::OpaqueId("alice".into())),
            })),
        };
        let tuple = RelationTuple {
            object: Some(ledger.clone()),
            relation: "reader".into(),
            subject: Some(alice.clone()),
        };
        let mutation = MutateTuplesRequest {
            scope: Some(scope.clone()),
            operation_id: "grant-alice".into(),
            expected_revision: Some(41),
            mutations: vec![TupleMutation {
                operation: Some(tuple_mutation::Operation::Add(tuple)),
            }],
        };
        let checks = CheckPermissionsRequest {
            scope: Some(scope),
            checks: vec![PermissionCheck {
                subject: Some(alice),
                object: Some(ledger),
                relation: "read".into(),
            }],
            consistency: Some(super::v1::AuthzConsistency {
                requirement: Some(authz_consistency::Requirement::Exact(
                    super::v1::ExactRevision { revision: 42 },
                )),
            }),
        };

        assert_eq!(mutation.expected_revision, Some(41));
        assert_eq!(mutation.mutations.len(), 1);
        assert_eq!(checks.checks.len(), 1);
        assert!(matches!(
            checks
                .consistency
                .and_then(|consistency| consistency.requirement),
            Some(authz_consistency::Requirement::Exact(_))
        ));
    }
}