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
//! Shared application state for the control plane.
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use orca_core::config::{ClusterConfig, ServiceConfig};
use orca_core::runtime::{Runtime, WorkloadHandle};
use orca_core::types::{HealthState, Replicas, WorkloadStatus};
use crate::stats::ContainerStats;
use crate::webhook::WebhookStore;
pub use orca_proxy::{RouteTarget, SharedWasmTriggers, WasmTrigger};
/// Shared route table type, compatible with [`orca_proxy::run_proxy`].
pub type SharedRouteTable = Arc<RwLock<HashMap<String, Vec<RouteTarget>>>>;
/// Shared state for the control plane, accessible by the API server and reconciler.
pub struct AppState {
/// Cluster configuration.
pub cluster_config: ClusterConfig,
/// Container runtime (Docker).
pub container_runtime: Arc<dyn Runtime>,
/// Wasm runtime (wasmtime). Trait object to avoid coupling to concrete type.
pub wasm_runtime: Option<Arc<dyn Runtime>>,
/// Current service state, keyed by service name.
pub services: RwLock<HashMap<String, ServiceState>>,
/// Routing table for container workloads, shared with the reverse proxy.
pub route_table: SharedRouteTable,
/// Wasm HTTP triggers, shared with the reverse proxy.
pub wasm_triggers: SharedWasmTriggers,
/// Registered cluster nodes (M2 in-memory, will move to Raft store).
pub registered_nodes: RwLock<HashMap<u64, RegisteredNode>>,
/// Webhook configurations for push-triggered deploys.
pub webhooks: WebhookStore,
/// API bearer tokens for authentication (empty = allow all).
pub api_tokens: Vec<String>,
/// Pending commands for agent nodes, keyed by node_id.
/// Uses serde_json::Value to avoid circular dependency on orca-agent types.
pub pending_commands: RwLock<HashMap<u64, Vec<serde_json::Value>>>,
/// Deploy history for rollback support.
pub deploy_history: RwLock<crate::deploy_history::DeployHistory>,
/// ACME manager for hot cert provisioning (None if no TLS).
pub acme_manager: Option<orca_proxy::acme::AcmeManager>,
/// Dynamic cert resolver shared with the HTTPS listener.
pub cert_resolver: Option<orca_proxy::SharedCertResolver>,
/// Cached container stats, keyed by service name.
pub container_stats: RwLock<HashMap<String, ContainerStats>>,
/// Persistent cluster store (redb). None in tests without persistence.
pub store: Option<Arc<crate::store::ClusterStore>>,
/// WebSocket senders for connected agent nodes, keyed by node_id.
pub ws_agents: RwLock<HashMap<u64, crate::ws_handler::AgentSender>>,
/// Log stream listeners: request_id → (data, done) sender.
pub log_listeners: RwLock<HashMap<String, tokio::sync::mpsc::Sender<(String, bool)>>>,
/// Backup status listeners: request_id → report sender. Used by the
/// `/api/v1/cluster/backups` handler to collect reports dispatched in
/// parallel to every connected agent.
pub backup_listeners: RwLock<
HashMap<String, tokio::sync::mpsc::Sender<orca_core::ws_types::BackupStatusReportData>>,
>,
/// Network status listeners: request_id → report sender. Same pattern as
/// `backup_listeners`, used by the `/api/v1/cluster/networks` handler.
pub network_listeners: RwLock<
HashMap<String, tokio::sync::mpsc::Sender<orca_core::ws_types::NetworkStatusReportData>>,
>,
/// Last completed `BackupResult` per agent node, recorded as the result
/// arrives over WS. Surfaced alongside the snapshot listing so the
/// dashboard can show a node's last-failure message without having to
/// scrape logs. Master has its own field — its backups are subprocess-
/// driven, not WS-dispatched.
pub last_backup_results: RwLock<HashMap<u64, LastBackupResult>>,
/// Last completed master backup result, recorded when `run_master_backup`
/// finishes. Separate from `last_backup_results` because the master has
/// no `node_id` and runs its backups via subprocess rather than WS.
pub master_last_backup_result: RwLock<Option<LastBackupResult>>,
/// Recent webhook invocations, keyed by `service_name`. Bounded ring
/// buffer of the last 10 deliveries per webhook so the TUI can render a
/// history view without scraping logs. Lost on restart by design — this
/// is operator-visible recent activity, not durable audit.
pub webhook_invocations: RwLock<
HashMap<String, std::collections::VecDeque<orca_core::api_types::WebhookInvocation>>,
>,
/// Active exec sessions: session_id → output bytes sender (agent → CLI WS).
pub exec_sessions: RwLock<HashMap<String, tokio::sync::mpsc::Sender<Vec<u8>>>>,
/// Pending deploy result waiters: service_name → oneshot sender.
/// Inserted by queue_remote_deploy, resolved by ws_handler on DeployResult.
pub pending_deploys: RwLock<HashMap<String, tokio::sync::oneshot::Sender<Result<(), String>>>>,
}
pub use orca_core::api_types::LastBackupResult;
/// A node registered in the cluster.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RegisteredNode {
/// Node ID.
pub node_id: u64,
/// Node address (ip:port).
pub address: String,
/// Node labels.
pub labels: HashMap<String, String>,
/// Last heartbeat time.
pub last_heartbeat: chrono::DateTime<chrono::Utc>,
/// Whether the node is in drain mode (no new workloads scheduled).
#[serde(default)]
pub drain: bool,
/// Latest CPU / memory / disk / network sample reported in a heartbeat.
/// Populated for both the master (via its local collector) and joined
/// nodes (via their heartbeat body).
#[serde(default)]
pub cpu_percent: f64,
#[serde(default)]
pub memory_bytes: u64,
#[serde(default)]
pub memory_total: u64,
#[serde(default)]
pub disk_used: u64,
#[serde(default)]
pub disk_total: u64,
#[serde(default)]
pub net_rx: u64,
#[serde(default)]
pub net_tx: u64,
}
/// State of a deployed service.
#[derive(Debug)]
pub struct ServiceState {
/// The service configuration.
pub config: ServiceConfig,
/// Desired number of replicas.
pub desired_replicas: u32,
/// Running instances.
pub instances: Vec<InstanceState>,
}
/// State of a single workload instance (one replica).
#[derive(Debug)]
pub struct InstanceState {
/// Handle to the running workload.
pub handle: WorkloadHandle,
/// Current status.
pub status: WorkloadStatus,
/// Host port mapped to the container's primary port (containers only).
pub host_port: Option<u16>,
/// Container address on Docker network (ip:port) for direct proxy routing.
pub container_address: Option<String>,
/// Health check state.
pub health: HealthState,
/// Whether this instance is a canary (new version during canary deploy).
pub is_canary: bool,
/// When this instance was created (for initial_delay_secs).
pub started_at: std::time::Instant,
}
impl AppState {
/// Create with shared route table and Wasm triggers (for sharing with the proxy).
pub fn new(
cluster_config: ClusterConfig,
container_runtime: Arc<dyn Runtime>,
wasm_runtime: Option<Arc<dyn Runtime>>,
route_table: SharedRouteTable,
wasm_triggers: SharedWasmTriggers,
) -> Self {
let api_tokens = cluster_config.api_tokens.clone();
Self {
cluster_config,
container_runtime,
wasm_runtime,
services: RwLock::new(HashMap::new()),
route_table,
wasm_triggers,
registered_nodes: RwLock::new(HashMap::new()),
pending_commands: RwLock::new(HashMap::new()),
webhooks: crate::webhook::new_store(),
api_tokens,
deploy_history: RwLock::new(crate::deploy_history::DeployHistory::new()),
acme_manager: None,
cert_resolver: None,
container_stats: RwLock::new(HashMap::new()),
store: None,
ws_agents: RwLock::new(HashMap::new()),
log_listeners: RwLock::new(HashMap::new()),
backup_listeners: RwLock::new(HashMap::new()),
network_listeners: RwLock::new(HashMap::new()),
last_backup_results: RwLock::new(HashMap::new()),
master_last_backup_result: RwLock::new(None),
webhook_invocations: RwLock::new(HashMap::new()),
exec_sessions: RwLock::new(HashMap::new()),
pending_deploys: RwLock::new(HashMap::new()),
}
}
/// Set persistent store for service state.
pub fn with_store(mut self, store: Arc<crate::store::ClusterStore>) -> Self {
self.store = Some(store);
self
}
/// Set ACME manager and cert resolver for hot cert provisioning.
pub fn with_acme(
mut self,
manager: orca_proxy::acme::AcmeManager,
resolver: orca_proxy::SharedCertResolver,
) -> Self {
self.acme_manager = Some(manager);
self.cert_resolver = Some(resolver);
self
}
}
impl ServiceState {
/// Create from a service config.
pub fn from_config(config: ServiceConfig) -> Self {
let desired_replicas = match &config.replicas {
Replicas::Fixed(n) => *n,
Replicas::Auto => 1,
};
Self {
config,
desired_replicas,
instances: Vec::new(),
}
}
/// Count how many instances are currently running.
pub fn running_count(&self) -> u32 {
self.instances
.iter()
.filter(|i| i.status == WorkloadStatus::Running)
.count() as u32
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
use orca_core::config::ServiceConfig;
use orca_core::runtime::WorkloadHandle;
use orca_core::types::{Replicas, WorkloadStatus};
fn minimal_config(replicas: Replicas) -> ServiceConfig {
ServiceConfig {
name: "test-svc".to_string(),
project: None,
runtime: Default::default(),
image: Some("nginx:latest".to_string()),
module: None,
replicas,
port: Some(8080),
domain: None,
health: None,
readiness: None,
liveness: None,
env: HashMap::new(),
resources: None,
volume: None,
deploy: None,
placement: None,
network: None,
aliases: vec![],
mounts: vec![],
routes: vec![],
host_port: None,
triggers: Vec::new(),
assets: None,
build: None,
tls_cert: None,
tls_key: None,
internal: false,
depends_on: vec![],
cmd: vec![],
extra_ports: vec![],
strip_prefix: None,
pull_policy: Default::default(),
backup: None,
}
}
fn make_instance(status: WorkloadStatus) -> InstanceState {
InstanceState {
handle: WorkloadHandle {
runtime_id: "test-id".to_string(),
name: "test-instance".to_string(),
metadata: HashMap::new(),
},
status,
host_port: None,
container_address: None,
health: HealthState::Unknown,
is_canary: false,
started_at: std::time::Instant::now(),
}
}
#[test]
fn from_config_fixed_sets_desired_replicas() {
let state = ServiceState::from_config(minimal_config(Replicas::Fixed(3)));
assert_eq!(state.desired_replicas, 3);
}
#[test]
fn from_config_auto_defaults_to_one() {
let state = ServiceState::from_config(minimal_config(Replicas::Auto));
assert_eq!(state.desired_replicas, 1);
}
#[test]
fn running_count_with_mixed_statuses() {
let mut state = ServiceState::from_config(minimal_config(Replicas::Fixed(4)));
state.instances = vec![
make_instance(WorkloadStatus::Running),
make_instance(WorkloadStatus::Stopped),
make_instance(WorkloadStatus::Running),
make_instance(WorkloadStatus::Failed),
];
assert_eq!(state.running_count(), 2);
}
}