Skip to main content

stateknot_runtime/agent_maintenance/
binding.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4use super::{AgentMaintenanceError, AgentMaintenanceJob, AgentMaintenanceJobReport};
5use crate::{
6    AgentDeadlineSweepCursor, ChildJoinPublicationCursor, ChildReconciliationCursor,
7    DurableAgentDeadlineReconciler, DurableChildJoinPublisher, DurableChildReconciler,
8    DurableChildReconcilerOptions, DurableGraphLifecycleOptions, DurableRunFailureCloser,
9    JsonSchemaRegistry, RunFailureCloseSweepCursor,
10};
11use stateknot_core::{CancellationSignal, TenantId};
12use stateknot_store_postgres::{PostgresStore, StoreError};
13
14/// Existing validated mutation retry policies, shared by the relevant jobs.
15#[derive(Clone, Copy, Debug, Default)]
16pub struct AgentMaintenanceMutationOptions {
17    /// Deadline and failure-close retries.
18    pub lifecycle: DurableGraphLifecycleOptions,
19    /// Child cancellation/settlement and Join publication retries.
20    pub child: DurableChildReconcilerOptions,
21}
22
23/// Exclusive ownership of concrete maintainers over the same store and frozen
24/// schemas. The host must authorize every tenant before construction.
25pub struct AgentMaintenanceBinding {
26    store: PostgresStore,
27    tenants: Vec<TenantId>,
28    deadline: DurableAgentDeadlineReconciler,
29    child: DurableChildReconciler,
30    join: DurableChildJoinPublisher,
31    close: DurableRunFailureCloser,
32}
33impl AgentMaintenanceBinding {
34    /// Requires 1–128 unique tenants and all four exact standard event schemas.
35    /// Sorting is deterministic; duplicates fail closed rather than weighting work.
36    pub fn new(
37        store: PostgresStore,
38        schemas: JsonSchemaRegistry,
39        mut tenants: Vec<TenantId>,
40        options: AgentMaintenanceMutationOptions,
41    ) -> Result<Self, AgentMaintenanceError> {
42        if tenants.is_empty() || tenants.len() > 128 {
43            return Err(AgentMaintenanceError::InvalidTenants);
44        }
45        tenants.sort_by(|a, b| a.as_str().cmp(b.as_str()));
46        if tenants.windows(2).any(|pair| pair[0] == pair[1]) {
47            return Err(AgentMaintenanceError::InvalidTenants);
48        }
49        Ok(Self {
50            deadline: DurableAgentDeadlineReconciler::new(
51                store.clone(),
52                schemas.clone(),
53                options.lifecycle,
54            )
55            .map_err(|_| AgentMaintenanceError::SchemaUnavailable)?,
56            child: DurableChildReconciler::new(store.clone(), schemas.clone(), options.child)
57                .map_err(|_| AgentMaintenanceError::SchemaUnavailable)?,
58            join: DurableChildJoinPublisher::new(store.clone(), schemas.clone(), options.child)
59                .map_err(|_| AgentMaintenanceError::SchemaUnavailable)?,
60            close: DurableRunFailureCloser::new(store.clone(), schemas, options.lifecycle)
61                .map_err(|_| AgentMaintenanceError::SchemaUnavailable)?,
62            store,
63            tenants,
64        })
65    }
66    pub(super) async fn check(&self) -> Result<(), AgentMaintenanceError> {
67        self.store
68            .verify_schema()
69            .await
70            .map_err(|_| AgentMaintenanceError::Unavailable)
71    }
72    pub(super) fn rotation(&self) -> Vec<Progress> {
73        self.tenants
74            .iter()
75            .flat_map(|tenant| {
76                [
77                    Progress::Deadline(tenant.clone(), None),
78                    Progress::Child(tenant.clone(), None),
79                    Progress::Join(tenant.clone(), None),
80                    Progress::Close(tenant.clone(), None),
81                ]
82            })
83            .collect()
84    }
85    pub(super) async fn tick(
86        &self,
87        progress: &mut Progress,
88        signal: CancellationSignal,
89    ) -> Result<AgentMaintenanceJobReport, StoreError> {
90        // Each returned cursor advances past item errors, and resets at exhaustion.
91        // A discovery error leaves the old cursor intact; restart starts at None.
92        let (items, failures) = match progress {
93            Progress::Deadline(tenant, cursor) => {
94                let tick = self
95                    .deadline
96                    .tick(tenant.clone(), cursor.clone(), signal)
97                    .await?;
98                *cursor = Some(tick.cursor().clone());
99                (
100                    tick.items().len(),
101                    tick.items()
102                        .iter()
103                        .filter(|item| item.result().is_err())
104                        .count(),
105                )
106            }
107            Progress::Child(tenant, cursor) => {
108                let tick = self
109                    .child
110                    .tick(tenant.clone(), cursor.as_deref().cloned(), signal)
111                    .await?;
112                *cursor = Some(Box::new(tick.cursor().clone()));
113                (
114                    tick.items().len(),
115                    tick.items()
116                        .iter()
117                        .filter(|item| item.result().is_err())
118                        .count(),
119                )
120            }
121            Progress::Join(tenant, cursor) => {
122                let tick = self
123                    .join
124                    .tick(tenant.clone(), cursor.clone(), signal)
125                    .await?;
126                *cursor = Some(tick.cursor().clone());
127                (
128                    tick.items().len(),
129                    tick.items()
130                        .iter()
131                        .filter(|item| item.result().is_err())
132                        .count(),
133                )
134            }
135            Progress::Close(tenant, cursor) => {
136                let tick = self
137                    .close
138                    .tick(tenant.clone(), cursor.clone(), signal)
139                    .await?;
140                *cursor = Some(tick.cursor().clone());
141                (
142                    tick.items().len(),
143                    tick.items()
144                        .iter()
145                        .filter(|item| item.result().is_err())
146                        .count(),
147                )
148            }
149        };
150        Ok(AgentMaintenanceJobReport {
151            completed_ticks: 1,
152            items: items as u64,
153            item_failures: failures as u64,
154        })
155    }
156}
157pub(super) enum Progress {
158    Deadline(TenantId, Option<AgentDeadlineSweepCursor>),
159    Child(TenantId, Option<Box<ChildReconciliationCursor>>),
160    Join(TenantId, Option<ChildJoinPublicationCursor>),
161    Close(TenantId, Option<RunFailureCloseSweepCursor>),
162}
163impl Progress {
164    pub(super) const fn job(&self) -> AgentMaintenanceJob {
165        match self {
166            Self::Deadline(..) => AgentMaintenanceJob::Deadline,
167            Self::Child(..) => AgentMaintenanceJob::Child,
168            Self::Join(..) => AgentMaintenanceJob::Join,
169            Self::Close(..) => AgentMaintenanceJob::FailureClose,
170        }
171    }
172}