-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstate.rs
More file actions
416 lines (366 loc) · 13.1 KB
/
Copy pathstate.rs
File metadata and controls
416 lines (366 loc) · 13.1 KB
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
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use uuid::Uuid;
// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------
#[derive(Debug, Error)]
pub enum StateError {
#[error("failed to read state file {path}: {source}")]
ReadError {
path: PathBuf,
source: std::io::Error,
},
#[error("failed to write state file {path}: {source}")]
WriteError {
path: PathBuf,
source: std::io::Error,
},
#[error("failed to parse state file {path}: {source}")]
ParseError {
path: PathBuf,
source: serde_json::Error,
},
#[error("run \"{0}\" not found")]
RunNotFound(String),
}
// ---------------------------------------------------------------------------
// Run status
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RunStatus {
Starting,
Running,
/// A recovery cycle is in progress for one or more nodes.
Recovering,
Stopping,
Stopped,
Failed,
}
// ---------------------------------------------------------------------------
// Node status
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NodeStatus {
Pending,
Starting,
HealthChecking,
Healthy,
/// Liveness probe failed but recovery has not yet been exhausted.
Unhealthy,
Failed,
Stopped,
Skipped,
}
// ---------------------------------------------------------------------------
// Readiness phase tracking
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReadinessPhase {
pub phase: u8, // 1 = port, 2 = HTTPS
pub passed: bool,
pub last_error: Option<String>,
#[serde(with = "chrono::serde::ts_milliseconds_option")]
pub passed_at: Option<DateTime<Utc>>,
}
// ---------------------------------------------------------------------------
// Node state
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeState {
pub node_name: String,
pub variant: String,
pub status: NodeStatus,
pub pid: Option<u32>,
pub port: Option<u16>,
pub url: Option<String>,
pub outputs: HashMap<String, String>,
/// Readiness probe phase tracking (renamed from `health_phases` in v7).
#[serde(default, alias = "health_phases")]
pub readiness_phases: Vec<ReadinessPhase>,
/// Number of recovery attempts completed for this node.
#[serde(default)]
pub recovery_count: u32,
/// Current streak of consecutive liveness probe failures.
#[serde(default)]
pub consecutive_failures: u32,
/// Error message from the most recent liveness probe failure.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_liveness_error: Option<String>,
/// Output keys whose values are sensitive (encrypted at rest, masked in display).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub sensitive_keys: Vec<String>,
}
impl NodeState {
pub fn new(node_name: &str, variant: &str) -> Self {
Self {
node_name: node_name.to_owned(),
variant: variant.to_owned(),
status: NodeStatus::Pending,
pid: None,
port: None,
url: None,
outputs: HashMap::new(),
readiness_phases: Vec::new(),
recovery_count: 0,
consecutive_failures: 0,
last_liveness_error: None,
sensitive_keys: Vec::new(),
}
}
/// Encrypt sensitive output values in-place for storage at rest.
pub fn encrypt_sensitive_outputs(&mut self) {
for key in &self.sensitive_keys {
if let Some(value) = self.outputs.get(key) {
if !crate::sensitive::is_encrypted(value) {
let encrypted = crate::sensitive::encrypt_value(value);
self.outputs.insert(key.clone(), encrypted);
}
}
}
}
/// Decrypt sensitive output values in-place after loading from storage.
pub fn decrypt_sensitive_outputs(&mut self) {
for key in &self.sensitive_keys {
if let Some(value) = self.outputs.get(key) {
if crate::sensitive::is_encrypted(value) {
let decrypted = crate::sensitive::decrypt_value(value);
self.outputs.insert(key.clone(), decrypted);
}
}
}
}
/// Return a copy of outputs with sensitive values masked for display.
pub fn display_outputs(&self) -> HashMap<String, String> {
self.outputs
.iter()
.map(|(k, v)| {
if self.sensitive_keys.contains(k) {
(k.clone(), crate::sensitive::mask_value(v))
} else {
(k.clone(), v.clone())
}
})
.collect()
}
/// Output keys that, when all present, mark this node as a database a
/// client can connect to. User/password are optional and not required here.
pub const DATABASE_OUTPUT_KEYS: [&'static str; 3] = ["DB_HOST", "DB_PORT", "DB_NAME"];
/// True if this node exposes the outputs needed to build a database
/// connection URL. Shared by the `veld postico` command and the management
/// dashboard so both agree on what counts as a database node.
pub fn exposes_database(&self) -> bool {
Self::DATABASE_OUTPUT_KEYS
.iter()
.all(|k| self.outputs.contains_key(*k))
}
}
// ---------------------------------------------------------------------------
// Run state
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunState {
pub run_id: Uuid,
pub name: String,
pub project: String,
pub status: RunStatus,
pub nodes: HashMap<String, NodeState>,
/// Node keys in the order they were started (for reverse-order stop).
#[serde(default)]
pub execution_order: Vec<String>,
pub created_at: DateTime<Utc>,
pub stopped_at: Option<DateTime<Utc>>,
}
impl RunState {
pub fn new(name: &str, project: &str) -> Self {
Self {
run_id: Uuid::new_v4(),
name: name.to_owned(),
project: project.to_owned(),
status: RunStatus::Starting,
nodes: HashMap::new(),
execution_order: Vec::new(),
created_at: Utc::now(),
stopped_at: None,
}
}
/// Key for the node state map: `"node:variant"`.
pub fn node_key(node: &str, variant: &str) -> String {
format!("{node}:{variant}")
}
}
// ---------------------------------------------------------------------------
// Project state file (.veld/state.json)
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ProjectState {
pub runs: HashMap<String, RunState>,
}
impl ProjectState {
/// Load from the `.veld/state.json` file under `project_root`.
/// Sensitive output values are decrypted after loading.
pub fn load(project_root: &Path) -> Result<Self, StateError> {
let path = state_file_path(project_root);
if !path.exists() {
return Ok(Self::default());
}
let data = std::fs::read_to_string(&path).map_err(|e| StateError::ReadError {
path: path.clone(),
source: e,
})?;
let mut state: Self =
serde_json::from_str(&data).map_err(|e| StateError::ParseError { path, source: e })?;
// Decrypt sensitive outputs after loading.
for run in state.runs.values_mut() {
for node in run.nodes.values_mut() {
node.decrypt_sensitive_outputs();
}
}
Ok(state)
}
/// Persist to `.veld/state.json`.
/// Sensitive output values are encrypted before writing.
pub fn save(&self, project_root: &Path) -> Result<(), StateError> {
let path = state_file_path(project_root);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| StateError::WriteError {
path: path.clone(),
source: e,
})?;
}
// Clone and encrypt sensitive values before serializing.
let mut state_for_disk = self.clone();
for run in state_for_disk.runs.values_mut() {
for node in run.nodes.values_mut() {
node.encrypt_sensitive_outputs();
}
}
let data =
serde_json::to_string_pretty(&state_for_disk).expect("state serialization cannot fail");
atomic_write(&path, &data)
}
pub fn get_run(&self, name: &str) -> Option<&RunState> {
self.runs.get(name)
}
pub fn get_run_mut(&mut self, name: &str) -> Option<&mut RunState> {
self.runs.get_mut(name)
}
}
fn state_file_path(project_root: &Path) -> PathBuf {
project_root.join(".veld").join("state.json")
}
/// Write `data` to `path` atomically via a temp file + rename.
/// The temp file lives in the same directory so the rename never crosses
/// filesystem boundaries.
fn atomic_write(path: &Path, data: &str) -> Result<(), StateError> {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
let tmp_name = format!(
".{}.{}.{}.tmp",
path.file_name().unwrap_or_default().to_string_lossy(),
std::process::id(),
seq,
);
let tmp_path = path.with_file_name(tmp_name);
std::fs::write(&tmp_path, data).map_err(|e| StateError::WriteError {
path: tmp_path.clone(),
source: e,
})?;
std::fs::rename(&tmp_path, path).map_err(|e| {
let _ = std::fs::remove_file(&tmp_path);
StateError::WriteError {
path: path.to_path_buf(),
source: e,
}
})
}
// ---------------------------------------------------------------------------
// Global registry (~/Library/Application Support/veld/registry.json etc.)
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegistryEntry {
pub project_root: PathBuf,
pub project_name: String,
pub runs: HashMap<String, RegistryRunInfo>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegistryRunInfo {
pub run_id: Uuid,
pub name: String,
pub status: RunStatus,
pub urls: HashMap<String, String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GlobalRegistry {
pub projects: HashMap<String, RegistryEntry>,
}
impl GlobalRegistry {
pub fn registry_path() -> Option<PathBuf> {
dirs::data_dir().map(|d| d.join("veld").join("registry.json"))
}
pub fn load() -> Result<Self, StateError> {
let path = match Self::registry_path() {
Some(p) => p,
None => return Ok(Self::default()),
};
if !path.exists() {
return Ok(Self::default());
}
let data = std::fs::read_to_string(&path).map_err(|e| StateError::ReadError {
path: path.clone(),
source: e,
})?;
serde_json::from_str(&data).map_err(|e| StateError::ParseError { path, source: e })
}
pub fn save(&self) -> Result<(), StateError> {
let path = match Self::registry_path() {
Some(p) => p,
None => return Ok(()),
};
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| StateError::WriteError {
path: path.clone(),
source: e,
})?;
}
let data = serde_json::to_string_pretty(self).expect("registry serialization cannot fail");
atomic_write(&path, &data)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn node_with_outputs(pairs: &[(&str, &str)]) -> NodeState {
let mut ns = NodeState::new("database", "dblab");
ns.outputs = pairs
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
ns
}
#[test]
fn exposes_database_requires_all_keys() {
let ns = node_with_outputs(&[
("DB_HOST", "localhost"),
("DB_PORT", "5432"),
("DB_NAME", "app"),
]);
assert!(ns.exposes_database());
}
#[test]
fn exposes_database_false_when_a_key_is_missing() {
let ns = node_with_outputs(&[("DB_HOST", "localhost"), ("DB_PORT", "5432")]);
assert!(!ns.exposes_database());
}
#[test]
fn exposes_database_false_for_non_database_node() {
let ns = node_with_outputs(&[("PORT", "3000")]);
assert!(!ns.exposes_database());
}
}