Skip to main content

gent_daemon/
configuration_log.rs

1//! Ordered configuration transport. No network operation holds the Store lock.
2//! Migration activation and trusted joining remain separate control-plane work.
3use crate::{
4    access, config,
5    store::Store,
6    sync::{Relay, bounded},
7};
8use anyhow::{Result, ensure};
9use gent_protocol::configuration_log::{Bootstrap, Commit, Head, MAX_COMMIT_BYTES, Receipt};
10use reqwest::StatusCode;
11use serde::de::DeserializeOwned;
12use std::{
13    path::Path,
14    sync::{Arc, Mutex},
15};
16
17pub struct ConfigurationRelay {
18    relay: Relay,
19}
20
21impl ConfigurationRelay {
22    pub fn open(settings: &config::RelayConfig, home: &Path) -> Result<Self> {
23        Ok(Self {
24            relay: Relay::open(settings, home)?,
25        })
26    }
27
28    pub(crate) fn from_relay(relay: Relay) -> Self {
29        Self { relay }
30    }
31
32    async fn get<T: DeserializeOwned>(&self, path: &str, limit: usize) -> Result<Option<T>> {
33        let response = self
34            .relay
35            .client
36            .get(
37                self.relay
38                    .origin
39                    .join(&format!("v1/configuration/{path}"))?,
40            )
41            .send()
42            .await?;
43        if response.status() == StatusCode::NOT_FOUND {
44            return Ok(None);
45        }
46        ensure!(
47            response.status() == StatusCode::OK,
48            "configuration relay read failed ({})",
49            response.status()
50        );
51        Ok(Some(serde_json::from_slice(
52            &bounded(response, limit).await?,
53        )?))
54    }
55
56    async fn publish(&self, commit: &Commit) -> Result<Option<Receipt>> {
57        let response = self
58            .relay
59            .client
60            .put(self.relay.origin.join("v1/configuration/commits")?)
61            .json(commit)
62            .send()
63            .await?;
64        if response.status() == StatusCode::CONFLICT {
65            return Ok(None);
66        }
67        ensure!(
68            response.status() == StatusCode::OK,
69            "configuration relay write failed ({})",
70            response.status()
71        );
72        let receipt: Receipt = serde_json::from_slice(&bounded(response, 4096).await?)?;
73        ensure!(
74            receipt.cluster == commit.header.cluster
75                && receipt.origin == commit.header.origin
76                && receipt.operation == commit.header.operation
77                && receipt.intent == commit.header.intent,
78            "configuration retry receipt mismatch"
79        );
80        Ok(Some(receipt))
81    }
82
83    async fn receive(&self, store: Arc<Mutex<Store>>, sequence: u64) -> Result<Receipt> {
84        let commit: Commit = self
85            .get(&format!("records/{sequence}"), MAX_COMMIT_BYTES)
86            .await?
87            .ok_or_else(|| anyhow::anyhow!("configuration log has a history gap"))?;
88        ensure!(
89            commit.header.previous.sequence + 1 == sequence,
90            "configuration record sequence mismatch"
91        );
92        access::run(store, "configuration commit", move |store| {
93            store.accept_configuration_commit(&commit)
94        })
95        .await
96    }
97
98    /// One bounded reconciliation pass, including discovery of a committed
99    /// transition for nodes that were offline while migration happened.
100    pub async fn sync_once(&self, store: Arc<Mutex<Store>>) -> Result<bool> {
101        let Some(mut local) = access::run(store.clone(), "configuration checkpoint", |store| {
102            store.configuration_log_head()
103        })
104        .await?
105        else {
106            let Some(bootstrap) = self.get::<Bootstrap>("bootstrap", 2048).await? else {
107                access::run(store, "configuration discovery", |store| {
108                    store.configuration_discovery(true);
109                    Ok(())
110                })
111                .await?;
112                return Ok(false);
113            };
114            access::run(store.clone(), "configuration discovery", |store| {
115                store.configuration_discovery(false);
116                Ok(())
117            })
118            .await?;
119            ensure!(bootstrap.head.valid(), "invalid configuration bootstrap");
120            let Some(commit) = self
121                .get::<Commit>(
122                    &format!("records/{}", bootstrap.head.sequence + 1),
123                    MAX_COMMIT_BYTES,
124                )
125                .await?
126            else {
127                return Ok(false);
128            };
129            ensure!(
130                commit.header.cluster == bootstrap.cluster
131                    && commit.header.previous == bootstrap.head,
132                "configuration migration bootstrap mismatch"
133            );
134            access::run(store, "configuration migration", move |store| {
135                store.accept_configuration_commit(&commit)?;
136                Ok(())
137            })
138            .await?;
139            return Ok(true);
140        };
141        let remote: Head = self
142            .get("head", 2048)
143            .await?
144            .ok_or_else(|| anyhow::anyhow!("configuration log has not been provisioned"))?;
145        ensure!(
146            remote.valid() && remote.sequence >= local.sequence,
147            "configuration service head rolled back"
148        );
149        let mut progressed = false;
150        for _ in 0..8 {
151            if local.sequence == remote.sequence {
152                break;
153            }
154            self.receive(store.clone(), local.sequence + 1).await?;
155            local = access::run(store.clone(), "configuration checkpoint", |store| {
156                store.configuration_log_head()
157            })
158            .await?
159            .ok_or_else(|| anyhow::anyhow!("configuration checkpoint disappeared"))?;
160            progressed = true;
161        }
162        if local.sequence < remote.sequence {
163            return Ok(true);
164        }
165        ensure!(
166            local == remote,
167            "configuration service head conflicts with the saved checkpoint"
168        );
169        if let Some(migration) = access::run(store.clone(), "configuration migration", |store| {
170            store.configuration_log_migration()
171        })
172        .await?
173        {
174            if let Some(receipt) = self.publish(&migration).await? {
175                ensure!(
176                    self.receive(store, receipt.head.sequence).await? == receipt,
177                    "configuration receipt does not match the committed record"
178                );
179            }
180            return Ok(true);
181        }
182        let pending = access::run(store.clone(), "configuration queue", |store| {
183            store.queue_configuration_renewal()?;
184            store.configuration_proposals()
185        })
186        .await?;
187        for queued in pending {
188            if let Some(receipt) = self
189                .get::<Receipt>(&format!("operations/{}", queued.operation), 4096)
190                .await?
191            {
192                let operation = queued.clone();
193                let intent = access::run(store.clone(), "configuration retry", move |store| {
194                    store.configuration_intent_for(&operation.origin, &operation.id)
195                })
196                .await?;
197                ensure!(
198                    receipt.operation == queued.operation && intent == Some(receipt.intent),
199                    "configuration receipt has no matching durable intent"
200                );
201                ensure!(
202                    self.receive(store.clone(), receipt.head.sequence).await? == receipt,
203                    "configuration receipt does not match the committed record"
204                );
205            } else {
206                let operation = queued.clone();
207                if !access::run(store.clone(), "configuration authorization", move |store| {
208                    store.validate_configuration_for(&operation)
209                })
210                .await?
211                {
212                    progressed = true;
213                    continue;
214                }
215                let candidate =
216                    access::run(store.clone(), "configuration proposal", move |store| {
217                        store.prepare_configuration_for(&queued)
218                    })
219                    .await?;
220                let Some(receipt) = self.publish(&candidate).await? else {
221                    return Ok(true);
222                };
223                ensure!(
224                    self.receive(store.clone(), receipt.head.sequence).await? == receipt,
225                    "configuration receipt does not match the committed record"
226                );
227            }
228            progressed = true;
229        }
230        Ok(progressed)
231    }
232}