loonfs-api 0.3.0

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

use crate::{
    AttributeRevisionNo, Attributes, ChangeSeq, CommitId, ContentRef, DisplayName, InodeId,
    NameKey, NamespaceId, RevisionNo,
};
use serde::{Deserialize, Serialize};

/// Result of one commit.
///
/// Every commit resolves to this envelope — path-oriented operations and
/// explicit commits, embedded or remote. The commit id is the caller's
/// reconciliation handle: resubmitting the same request with the same id
/// replays this result instead of committing twice.
///
/// The response includes the same attribution and events as
/// [`CommittedChange`], including IDs created by the commit.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct CommitResponse {
    /// Namespace that changed.
    pub namespace_id: NamespaceId,
    /// Idempotency key the commit landed under: caller-supplied, or
    /// generated on the caller's behalf when the request carried none.
    pub commit_id: CommitId,
    /// Sequence number where the commit became visible.
    pub committed_seq: ChangeSeq,
    /// Actor responsible for the commit, as supplied by the application.
    pub committed_by: crate::ActorRef,
    /// Wall-clock stamp of the commit, in Unix milliseconds.
    /// Observational: `committed_seq` is the order.
    pub committed_at_ms: u64,
    /// Caller annotation, omitted when absent and carrying no filesystem
    /// semantics.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(nullable = false))]
    pub message: Option<String>,
    /// Semantic filesystem events in commit order. This is omitted only when
    /// replaying a commit whose WAL history is no longer retained.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(nullable = false))]
    pub events: Option<Vec<FilesystemChange>>,
}

impl CommitResponse {
    /// Builds the response for a commit the change feed reports in full.
    pub fn from_committed_change(namespace_id: NamespaceId, change: CommittedChange) -> Self {
        Self {
            namespace_id,
            commit_id: change.commit_id,
            committed_seq: change.committed_seq,
            committed_by: change.committed_by,
            committed_at_ms: change.committed_at_ms,
            message: change.message,
            events: Some(change.events),
        }
    }
}

/// A directory entry's parent and name.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct DirectoryBinding {
    /// Parent directory containing the entry.
    #[serde(with = "crate::public_inode_id")]
    #[cfg_attr(
        feature = "openapi",
        schema(schema_with = crate::public_inode_id::schema)
    )]
    pub parent_inode_id: InodeId,
    /// Name used to look up the entry.
    pub name_key: NameKey,
    /// Name shown to users.
    pub display_name: DisplayName,
}

/// One semantic filesystem change inside a commit.
///
/// A commit's events are the operations it applied, in the order it applied
/// them. One request operation can apply several: creating missing parent
/// directories, or replacing a file by moving over it, each produce an event
/// per directory created or file replaced. So a request with three
/// operations may report more than three events, and the events stay in
/// request order. Events name inodes and their parent-directory bindings
/// rather than full paths; a consumer that needs paths can stat the inode or
/// maintain its own binding projection from this feed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum FilesystemChange {
    /// A directory was created.
    #[cfg_attr(
        feature = "openapi",
        schema(title = "FilesystemChangeDirectoryCreated")
    )]
    DirectoryCreated {
        /// Newly allocated namespace-scoped inode identity.
        #[serde(with = "crate::public_inode_id")]
        #[cfg_attr(
            feature = "openapi",
            schema(schema_with = crate::public_inode_id::schema)
        )]
        inode_id: InodeId,
        /// Directory the new entry was bound under.
        #[serde(with = "crate::public_inode_id")]
        #[cfg_attr(
            feature = "openapi",
            schema(schema_with = crate::public_inode_id::schema)
        )]
        parent_inode_id: InodeId,
        /// User-facing spelling of the new entry.
        display_name: DisplayName,
        /// Opaque identifier for the binding created by this event.
        binding_generation: String,
    },
    /// A file and its first revision were created.
    #[cfg_attr(feature = "openapi", schema(title = "FilesystemChangeFileCreated"))]
    FileCreated {
        /// Newly allocated namespace-scoped inode identity.
        #[serde(with = "crate::public_inode_id")]
        #[cfg_attr(
            feature = "openapi",
            schema(schema_with = crate::public_inode_id::schema)
        )]
        inode_id: InodeId,
        /// Directory the new entry was bound under.
        #[serde(with = "crate::public_inode_id")]
        #[cfg_attr(
            feature = "openapi",
            schema(schema_with = crate::public_inode_id::schema)
        )]
        parent_inode_id: InodeId,
        /// User-facing spelling of the new entry.
        display_name: DisplayName,
        /// Opaque identifier for the binding created by this event.
        binding_generation: String,
        /// First revision number.
        revision_no: RevisionNo,
        /// Content of the first revision.
        content_ref: ContentRef,
    },
    /// A file received a new current revision — a put over an existing
    /// file, or a revision restore (one durable fact for both).
    #[cfg_attr(feature = "openapi", schema(title = "FilesystemChangeContentChanged"))]
    ContentChanged {
        /// File inode whose history advanced.
        #[serde(with = "crate::public_inode_id")]
        #[cfg_attr(
            feature = "openapi",
            schema(schema_with = crate::public_inode_id::schema)
        )]
        inode_id: InodeId,
        /// New monotonic position in that file's revision history.
        revision_no: RevisionNo,
        /// Immutable content published by the revision.
        content_ref: ContentRef,
    },
    /// An inode moved to a new parent directory or name.
    #[cfg_attr(feature = "openapi", schema(title = "FilesystemChangeMoved"))]
    Moved {
        /// Inode whose binding changed.
        #[serde(with = "crate::public_inode_id")]
        #[cfg_attr(
            feature = "openapi",
            schema(schema_with = crate::public_inode_id::schema)
        )]
        inode_id: InodeId,
        /// Directory that held the old binding.
        #[serde(with = "crate::public_inode_id")]
        #[cfg_attr(
            feature = "openapi",
            schema(schema_with = crate::public_inode_id::schema)
        )]
        from_parent_inode_id: InodeId,
        /// Spelling of the old binding.
        from_display_name: DisplayName,
        /// Directory holding the new binding.
        #[serde(with = "crate::public_inode_id")]
        #[cfg_attr(
            feature = "openapi",
            schema(schema_with = crate::public_inode_id::schema)
        )]
        to_parent_inode_id: InodeId,
        /// Spelling of the new binding.
        to_display_name: DisplayName,
        /// Opaque identifier for the binding created by this event.
        binding_generation: String,
    },
    /// A file or directory subtree was deleted. Use the enclosing change's
    /// `committed_seq` as `deletion_seq` when restoring it.
    #[cfg_attr(feature = "openapi", schema(title = "FilesystemChangeDeleted"))]
    Deleted {
        /// Inode at the root of the deleted subtree.
        #[serde(with = "crate::public_inode_id")]
        #[cfg_attr(
            feature = "openapi",
            schema(schema_with = crate::public_inode_id::schema)
        )]
        inode_id: InodeId,
        /// Directory binding removed by the deletion, when the delete
        /// recorded one.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        #[cfg_attr(feature = "openapi", schema(nullable = false))]
        deleted_binding: Option<DirectoryBinding>,
    },
    /// A deleted inode was recovered and re-bound.
    #[cfg_attr(feature = "openapi", schema(title = "FilesystemChangeUndeleted"))]
    Undeleted {
        /// Recovered inode.
        #[serde(with = "crate::public_inode_id")]
        #[cfg_attr(
            feature = "openapi",
            schema(schema_with = crate::public_inode_id::schema)
        )]
        inode_id: InodeId,
        /// Directory the recovered entry was bound under.
        #[serde(with = "crate::public_inode_id")]
        #[cfg_attr(
            feature = "openapi",
            schema(schema_with = crate::public_inode_id::schema)
        )]
        parent_inode_id: InodeId,
        /// Spelling of the recovered binding.
        display_name: DisplayName,
        /// Opaque identifier for the binding created by this event.
        binding_generation: String,
    },
    /// An inode's attributes changed.
    #[cfg_attr(
        feature = "openapi",
        schema(title = "FilesystemChangeAttributesChanged")
    )]
    AttributesChanged {
        /// Inode whose attributes advanced.
        #[serde(with = "crate::public_inode_id")]
        #[cfg_attr(
            feature = "openapi",
            schema(schema_with = crate::public_inode_id::schema)
        )]
        inode_id: InodeId,
        /// New attribute revision for that inode.
        attributes_revision_no: AttributeRevisionNo,
        /// The inode's complete attribute map after the update, so a consumer
        /// projects it without reading anything back. An empty map is the
        /// cleared state.
        attributes: Attributes,
    },
}

/// One committed change in namespace order.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct CommittedChange {
    /// Namespace sequence for this logical commit.
    pub committed_seq: ChangeSeq,
    /// Client idempotency key for this logical commit.
    pub commit_id: CommitId,
    /// Actor responsible for the commit, as supplied by the application.
    pub committed_by: crate::ActorRef,
    /// Wall-clock stamp of the commit, in Unix milliseconds.
    /// Observational: `committed_seq` is the order.
    pub committed_at_ms: u64,
    /// Caller annotation, omitted when absent and carrying no filesystem semantics.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    /// Semantic filesystem events for this commit, in the order the commit
    /// applied them. One request operation may produce more than one event
    /// (see [`FilesystemChange`]).
    pub events: Vec<FilesystemChange>,
}

/// Change-feed response after a cursor.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct ListChangesResponse {
    /// Namespace whose ordered commit stream was read.
    pub namespace_id: NamespaceId,
    /// Exclusive cursor supplied by the caller, or the endpoint's initial position.
    pub after_seq: ChangeSeq,
    /// Snapshot head through which this page was evaluated.
    pub through_seq: ChangeSeq,
    /// Cursor to request when another page remains, or `None` at `through_seq`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(nullable = false))]
    pub next_after_seq: Option<ChangeSeq>,
    /// Logical commits after `after_seq`, ordered by ascending namespace sequence.
    pub changes: Vec<CommittedChange>,
}

#[cfg(test)]
mod tests {
    use super::{CommitResponse, CommittedChange, FilesystemChange};
    use crate::InodeId;

    fn binding_generation() -> String {
        "generation".to_owned()
    }

    #[test]
    fn committed_change_uses_committed_by_on_the_wire() {
        let change = CommittedChange {
            committed_seq: crate::ChangeSeq(7),
            commit_id: crate::CommitId::parse("example-commit").expect("valid commit id"),
            committed_by: crate::ActorRef::loonfs_system(),
            committed_at_ms: 1_752_624_000_000,
            message: None,
            events: Vec::new(),
        };

        assert_eq!(
            serde_json::to_value(change).expect("serialize committed change"),
            serde_json::json!({
                "committed_seq": 7,
                "commit_id": "example-commit",
                "committed_by": { "kind": "system", "id": "loonfs" },
                "committed_at_ms": 1_752_624_000_000_u64,
                "events": [],
            })
        );
    }

    #[test]
    fn a_commit_response_carries_the_committed_change_at_the_top_level() {
        let response = CommitResponse::from_committed_change(
            crate::NamespaceId::parse("demo").expect("valid namespace id"),
            CommittedChange {
                committed_seq: crate::ChangeSeq(419),
                commit_id: crate::CommitId::parse("example-commit").expect("valid commit id"),
                committed_by: crate::ActorRef::loonfs_system(),
                committed_at_ms: 1_752_624_000_000,
                message: Some("import the reports".to_owned()),
                events: vec![FilesystemChange::DirectoryCreated {
                    inode_id: InodeId(43),
                    parent_inode_id: InodeId(1),
                    display_name: crate::DisplayName::parse("docs").expect("valid display name"),
                    binding_generation: binding_generation(),
                }],
            },
        );

        assert_eq!(
            serde_json::to_value(response).expect("serialize commit response"),
            serde_json::json!({
                "namespace_id": "demo",
                "commit_id": "example-commit",
                "committed_seq": 419,
                "committed_by": { "kind": "system", "id": "loonfs" },
                "committed_at_ms": 1_752_624_000_000_u64,
                "message": "import the reports",
                "events": [{
                    "kind": "directory_created",
                    "inode_id": "ino_43",
                    "parent_inode_id": "ino_1",
                    "display_name": "docs",
                    "binding_generation": binding_generation(),
                }],
            })
        );
    }

    #[test]
    fn a_commit_response_omits_absent_events_and_message() {
        let response = CommitResponse {
            namespace_id: crate::NamespaceId::parse("demo").expect("valid namespace id"),
            commit_id: crate::CommitId::parse("example-commit").expect("valid commit id"),
            committed_seq: crate::ChangeSeq(419),
            committed_by: crate::ActorRef::loonfs_system(),
            committed_at_ms: 1_752_624_000_000,
            message: None,
            events: None,
        };

        assert_eq!(
            serde_json::to_value(response).expect("serialize commit response"),
            serde_json::json!({
                "namespace_id": "demo",
                "commit_id": "example-commit",
                "committed_seq": 419,
                "committed_by": { "kind": "system", "id": "loonfs" },
                "committed_at_ms": 1_752_624_000_000_u64,
            })
        );
    }

    #[test]
    fn filesystem_change_events_use_snake_case_kind_tags() {
        let sample_content_ref = crate::ContentRef::blob_v1(
            crate::ContentId::parse("con_0123456789abcdef0123456789abcdef")
                .expect("valid content id"),
            b"hello",
        );
        let sample_content_ref_json = r#"{"kind":"blob_v1","content_id":"con_0123456789abcdef0123456789abcdef","size_bytes":5,"checksum":{"algorithm":"sha256","value":"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"}}"#;

        let generation = binding_generation();
        let directory_created = FilesystemChange::DirectoryCreated {
            inode_id: InodeId(2),
            parent_inode_id: InodeId(1),
            display_name: crate::DisplayName::parse("Docs").expect("valid display name"),
            binding_generation: generation.clone(),
        };
        assert_eq!(
            serde_json::to_string(&directory_created).expect("serialize directory-created event"),
            format!(
                r#"{{"kind":"directory_created","inode_id":"ino_2","parent_inode_id":"ino_1","display_name":"Docs","binding_generation":"{generation}"}}"#
            )
        );

        let file_created = FilesystemChange::FileCreated {
            inode_id: InodeId(2),
            parent_inode_id: InodeId(1),
            display_name: crate::DisplayName::parse("a.txt").expect("valid display name"),
            binding_generation: generation.clone(),
            revision_no: crate::RevisionNo(1),
            content_ref: sample_content_ref.clone(),
        };
        assert_eq!(
            serde_json::to_string(&file_created).expect("serialize file-created event"),
            format!(
                r#"{{"kind":"file_created","inode_id":"ino_2","parent_inode_id":"ino_1","display_name":"a.txt","binding_generation":"{generation}","revision_no":1,"content_ref":{sample_content_ref_json}}}"#
            )
        );

        let missing_content_ref = r#"{"kind":"file_created","inode_id":"ino_2","parent_inode_id":"ino_1","display_name":"a.txt","revision_no":1}"#;
        assert!(serde_json::from_str::<FilesystemChange>(missing_content_ref).is_err());

        let retired_creation = serde_json::json!({
            "kind": (["cre", "ated"].concat()),
            "inode_id": "ino_2",
            "inode_kind": "file",
            "parent_inode_id": "ino_1",
            "display_name": "a.txt",
            "revision_no": 1,
        });
        assert!(serde_json::from_value::<FilesystemChange>(retired_creation).is_err());

        let content_changed = FilesystemChange::ContentChanged {
            inode_id: InodeId(2),
            revision_no: crate::RevisionNo(3),
            content_ref: sample_content_ref,
        };
        assert_eq!(
            serde_json::to_string(&content_changed).expect("serialize content changed event"),
            format!(
                r#"{{"kind":"content_changed","inode_id":"ino_2","revision_no":3,"content_ref":{sample_content_ref_json}}}"#
            )
        );

        let moved = FilesystemChange::Moved {
            inode_id: InodeId(2),
            from_parent_inode_id: InodeId(1),
            from_display_name: crate::DisplayName::parse("a.txt").expect("valid display name"),
            to_parent_inode_id: InodeId(3),
            to_display_name: crate::DisplayName::parse("b.txt").expect("valid display name"),
            binding_generation: generation.clone(),
        };
        assert_eq!(
            serde_json::to_string(&moved).expect("serialize moved event"),
            format!(
                r#"{{"kind":"moved","inode_id":"ino_2","from_parent_inode_id":"ino_1","from_display_name":"a.txt","to_parent_inode_id":"ino_3","to_display_name":"b.txt","binding_generation":"{generation}"}}"#
            )
        );

        let deleted = FilesystemChange::Deleted {
            inode_id: InodeId(2),
            deleted_binding: Some(super::DirectoryBinding {
                parent_inode_id: InodeId(1),
                name_key: crate::NameKey::parse("a.txt").expect("valid name key"),
                display_name: crate::DisplayName::parse("a.txt").expect("valid display name"),
            }),
        };
        assert_eq!(
            serde_json::to_string(&deleted).expect("serialize deleted event"),
            r#"{"kind":"deleted","inode_id":"ino_2","deleted_binding":{"parent_inode_id":"ino_1","name_key":"a.txt","display_name":"a.txt"}}"#
        );

        let undeleted = FilesystemChange::Undeleted {
            inode_id: InodeId(2),
            parent_inode_id: InodeId(1),
            display_name: crate::DisplayName::parse("a.txt").expect("valid display name"),
            binding_generation: generation.clone(),
        };
        assert_eq!(
            serde_json::to_string(&undeleted).expect("serialize undeleted event"),
            format!(
                r#"{{"kind":"undeleted","inode_id":"ino_2","parent_inode_id":"ino_1","display_name":"a.txt","binding_generation":"{generation}"}}"#
            )
        );

        let attributes_changed = FilesystemChange::AttributesChanged {
            inode_id: InodeId(2),
            attributes_revision_no: crate::AttributeRevisionNo(4),
            attributes: crate::Attributes::new(std::collections::BTreeMap::from([(
                crate::AttributeKey::parse("owner").expect("valid attribute key"),
                crate::AttributeValue::parse("ada").expect("valid attribute value"),
            )]))
            .expect("valid attribute map"),
        };
        assert_eq!(
            serde_json::to_string(&attributes_changed).expect("serialize attributes event"),
            r#"{"kind":"attributes_changed","inode_id":"ino_2","attributes_revision_no":4,"attributes":{"owner":"ada"}}"#
        );

        // A clear is a real event carrying the empty map, not an absence.
        let cleared = FilesystemChange::AttributesChanged {
            inode_id: InodeId(2),
            attributes_revision_no: crate::AttributeRevisionNo(5),
            attributes: crate::Attributes::default(),
        };
        assert_eq!(
            serde_json::to_string(&cleared).expect("serialize cleared attributes event"),
            r#"{"kind":"attributes_changed","inode_id":"ino_2","attributes_revision_no":5,"attributes":{}}"#
        );
    }
}