Skip to main content

lean_ctx_cloud/sync/
writer.rs

1// SPDX-License-Identifier: Apache-2.0
2//! What writes signed events into a workspace vault: the instance key, a
3//! registered workspace worker and the place as C0 2.0 names it. Every
4//! engine path that queues vault events (sync capture, `cloud maintain`,
5//! `knowledge contradict|retract`) builds its signer and place here, so the
6//! C0 spellings (`hlc.node` and place id as hyphenated UUIDs) cannot drift
7//! between paths again (dogfood 25.10.: the maintain CLI signed with the raw
8//! `inst_<hex>` id and Cloud refused `invalid_event shape /hlc/node`).
9
10use crate::CloudError;
11use crate::auth::Session;
12use crate::events::build::{Place, Signer};
13use crate::instance_key::InstanceKeys;
14use crate::replica::Replica;
15use crate::vault::VaultRecord;
16use crate::workers::card::{Availability, Budget, WorkerCard};
17use crate::workers::{attach, canonical_instance_id, register};
18
19use super::place::{CAPTURE_HOST, place_id};
20
21/// The instance key and a registered workspace worker of one role.
22pub struct VaultWriter {
23    pub keys: InstanceKeys,
24    /// The canonical instance id (hyphenated UUID).
25    pub instance_id: String,
26    pub worker_id: String,
27}
28
29impl VaultWriter {
30    /// Attach the `role` worker of this instance and make sure Cloud knows
31    /// it (E10), as the capture worker of a sync.
32    pub fn open(session: &Session, role: &str) -> Result<Self, CloudError> {
33        let keys = InstanceKeys::load(&session.store)?;
34        let instance_id = canonical_instance_id(&session.instance.instance_id);
35        let worker = attach::attach(&session.store, &instance_id, CAPTURE_HOST, role)?.worker;
36        let worker = register::ensure_registered(
37            session,
38            &worker,
39            &WorkerCard::new(
40                CAPTURE_HOST,
41                None,
42                Vec::new(),
43                Budget::default(),
44                Availability::Online,
45            ),
46        )?;
47        Ok(Self {
48            keys,
49            instance_id,
50            worker_id: worker.worker_id,
51        })
52    }
53
54    pub fn signer(&self) -> Signer<'_> {
55        Signer::workspace(self.keys.signing_key(), &self.instance_id, &self.worker_id)
56    }
57}
58
59/// `vault:<place id>`, the place reference of the E5/E6 routes.
60pub fn vault_ref(record: &VaultRecord) -> String {
61    format!("vault:{}", place_id(&record.vault_id))
62}
63
64/// The vault as an event place, keyed with the replica's id salt at its
65/// folded cursor.
66pub fn vault_place(record: &VaultRecord, replica: &Replica) -> Result<Place, CloudError> {
67    let pk_id = replica.id_salt()?.ok_or_else(|| {
68        CloudError::Local("replica has no id_salt: run `lean-ctx cloud sync`".into())
69    })?;
70    Ok(Place {
71        kind: "vault".into(),
72        id: place_id(&record.vault_id),
73        pk_id,
74        causal_base: replica.cursor()?.unwrap_or(0),
75    })
76}
77
78#[cfg(test)]
79mod tests {
80    use ed25519_dalek::SigningKey;
81
82    use crate::events::build::Signer;
83
84    /// The 1.x enrolment's `inst_<hex>` id signs as its UUID: the C0 2.0
85    /// event schema only takes a UUID or 16 hex digits as `hlc.node`.
86    #[test]
87    fn a_workspace_signer_names_the_instance_as_its_uuid() {
88        let key = SigningKey::from_bytes(&[0x49; 32]);
89        for spelling in [
90            "inst_6f2b9c4e1a3d4e5f8a7b0c1d2e3f4a5b",
91            "6f2b9c4e1a3d4e5f8a7b0c1d2e3f4a5b",
92            "6F2B9C4E-1A3D-4E5F-8A7B-0C1D2E3F4A5B",
93        ] {
94            let signer = Signer::workspace(&key, spelling, "wkr_vk4oelpv5lzjmev44hun");
95            assert_eq!(
96                signer.hlc_node, "6f2b9c4e-1a3d-4e5f-8a7b-0c1d2e3f4a5b",
97                "{spelling}"
98            );
99        }
100    }
101}