lattice-common 2026.1.203

Shared types, configuration, and error handling for Lattice scheduler
Documentation
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
//! VAST storage service client.
//!
//! Implements the [`StorageService`] trait by communicating with the VAST
//! Management System REST API for data lifecycle operations.
//!
//! # VAST API Overview
//!
//! - **Catalog**: Namespace/path metadata, quota info, capacity
//!   - `GET /api/views/{path}` — view/quota details
//!   - `GET /api/capacity` — cluster capacity summary
//! - **Data Lifecycle**: Prefetch, tiering, QoS
//!   - `POST /api/nfs/prefetch` — prefetch data to hot tier (NVMe cache)
//!   - `PUT /api/qospolicies/{policy_id}` — set bandwidth floor for a path
//! - **Security**: Encrypted pools, secure wipe
//!   - `DELETE /api/views/{path}?wipe=true` — secure wipe of a path (zero-fill + crypto-erase)

use async_trait::async_trait;
use reqwest::Client;
use serde::{Deserialize, Serialize};

use crate::error::LatticeError;
use crate::traits::StorageService;

/// Configuration for connecting to a VAST storage cluster.
#[derive(Debug, Clone)]
pub struct VastConfig {
    /// Base URL for the VAST management API (e.g., "https://vast-mgmt.example.com")
    pub base_url: String,
    /// API username for authentication
    pub username: String,
    /// API password for authentication
    pub password: String,
    /// Request timeout in seconds
    pub timeout_secs: u64,
}

/// HTTP client for the VAST storage management system.
///
/// Provides concrete storage operations: data readiness checks (is data
/// on hot tier?), prefetch/staging, QoS floor bandwidth, and secure wipe
/// for sensitive workload teardown.
pub struct VastClient {
    http: Client,
    config: VastConfig,
}

impl VastClient {
    /// Create a new VAST client with the given configuration.
    pub fn new(config: VastConfig) -> Result<Self, LatticeError> {
        let http = Client::builder()
            .timeout(std::time::Duration::from_secs(config.timeout_secs))
            .build()
            .map_err(|e| LatticeError::Internal(format!("failed to build HTTP client: {e}")))?;

        Ok(Self { http, config })
    }

    /// Authenticate with VAST and return a session token.
    ///
    /// VAST uses basic auth for the initial request; the returned token
    /// is used for subsequent API calls.
    async fn authenticate(&self) -> Result<String, LatticeError> {
        let url = format!("{}/api/token", self.config.base_url);

        let resp = self
            .http
            .post(&url)
            .basic_auth(&self.config.username, Some(&self.config.password))
            .send()
            .await
            .map_err(|e| LatticeError::StorageError(format!("VAST auth request failed: {e}")))?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(LatticeError::StorageError(format!(
                "VAST auth returned {status}: {body}"
            )));
        }

        let token_resp: VastTokenResponse = resp
            .json()
            .await
            .map_err(|e| LatticeError::StorageError(format!("failed to parse token: {e}")))?;

        Ok(token_resp.access)
    }

    /// Query the VAST view for a given path to determine capacity and tier info.
    async fn get_view(&self, path: &str, token: &str) -> Result<VastViewResponse, LatticeError> {
        let encoded_path = path.trim_start_matches('/');
        let url = format!("{}/api/views/{encoded_path}", self.config.base_url);

        let resp = self
            .http
            .get(&url)
            .bearer_auth(token)
            .send()
            .await
            .map_err(|e| LatticeError::StorageError(format!("VAST view request failed: {e}")))?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(LatticeError::StorageError(format!(
                "VAST view returned {status}: {body}"
            )));
        }

        resp.json::<VastViewResponse>()
            .await
            .map_err(|e| LatticeError::StorageError(format!("failed to parse view: {e}")))
    }
}

#[async_trait]
impl StorageService for VastClient {
    async fn data_readiness(&self, source: &str) -> Result<f64, LatticeError> {
        let token = self.authenticate().await?;
        let view = self.get_view(source, &token).await?;

        // Readiness = fraction of data on hot tier (NVMe / SSD cache)
        if view.total_bytes == 0 {
            return Ok(1.0); // No data = fully ready
        }

        let readiness = view.hot_bytes as f64 / view.total_bytes as f64;
        Ok(readiness.clamp(0.0, 1.0))
    }

    async fn stage_data(&self, source: &str, target: &str) -> Result<(), LatticeError> {
        let token = self.authenticate().await?;

        let url = format!("{}/api/nfs/prefetch", self.config.base_url);

        let request = VastPrefetchRequest {
            path: source.to_string(),
            target_path: Some(target.to_string()),
            recursive: true,
        };

        let resp = self
            .http
            .post(&url)
            .bearer_auth(&token)
            .json(&request)
            .send()
            .await
            .map_err(|e| LatticeError::StorageError(format!("VAST prefetch failed: {e}")))?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(LatticeError::StorageError(format!(
                "VAST prefetch returned {status}: {body}"
            )));
        }

        tracing::info!(source = %source, target = %target, "initiated data prefetch via VAST");
        Ok(())
    }

    async fn set_qos(&self, path: &str, floor_gbps: f64) -> Result<(), LatticeError> {
        let token = self.authenticate().await?;

        let url = format!("{}/api/qospolicies", self.config.base_url);

        let request = VastQosPolicyRequest {
            name: format!("lattice-qos-{}", path.replace('/', "-").trim_matches('-')),
            path: path.to_string(),
            min_bandwidth_mbps: (floor_gbps * 1000.0) as u64,
        };

        let resp = self
            .http
            .post(&url)
            .bearer_auth(&token)
            .json(&request)
            .send()
            .await
            .map_err(|e| LatticeError::StorageError(format!("VAST QoS request failed: {e}")))?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(LatticeError::StorageError(format!(
                "VAST QoS returned {status}: {body}"
            )));
        }

        tracing::info!(path = %path, floor_gbps = %floor_gbps, "set QoS floor via VAST");
        Ok(())
    }

    async fn wipe_data(&self, path: &str) -> Result<(), LatticeError> {
        let token = self.authenticate().await?;

        let encoded_path = path.trim_start_matches('/');
        let url = format!(
            "{}/api/views/{encoded_path}?wipe=true",
            self.config.base_url
        );

        let resp = self
            .http
            .delete(&url)
            .bearer_auth(&token)
            .send()
            .await
            .map_err(|e| LatticeError::StorageError(format!("VAST wipe request failed: {e}")))?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(LatticeError::StorageError(format!(
                "VAST wipe returned {status}: {body}"
            )));
        }

        tracing::info!(path = %path, "initiated secure data wipe via VAST");
        Ok(())
    }
}

// ─── VAST API types ─────────────────────────────────────────

/// VAST token authentication response.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VastTokenResponse {
    pub access: String,
    pub refresh: Option<String>,
}

/// VAST view (namespace) info response.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VastViewResponse {
    pub path: String,
    /// Total bytes used in this view
    pub total_bytes: u64,
    /// Bytes on hot tier (NVMe/SSD cache)
    pub hot_bytes: u64,
    /// Bytes on warm/cold tier
    pub cold_bytes: u64,
    /// View quota in bytes (0 = unlimited)
    pub quota_bytes: u64,
}

/// VAST prefetch (staging) request.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VastPrefetchRequest {
    pub path: String,
    pub target_path: Option<String>,
    pub recursive: bool,
}

/// VAST QoS policy request.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VastQosPolicyRequest {
    pub name: String,
    pub path: String,
    pub min_bandwidth_mbps: u64,
}

// ─── Tests ──────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use wiremock::matchers::{method, path, path_regex, query_param};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    /// Helper to create a client pointing at a mock server and pre-mount auth.
    async fn mock_client_with_auth(server: &MockServer) -> VastClient {
        // Mount the token endpoint that all operations will call first
        Mock::given(method("POST"))
            .and(path("/api/token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "access": "mock-token-abc",
                "refresh": "mock-refresh-xyz"
            })))
            .mount(server)
            .await;

        let config = VastConfig {
            base_url: server.uri(),
            username: "admin".to_string(),
            password: "secret".to_string(),
            timeout_secs: 5,
        };
        VastClient::new(config).unwrap()
    }

    #[tokio::test]
    async fn data_readiness_returns_ratio_of_hot_to_total() {
        let server = MockServer::start().await;
        let client = mock_client_with_auth(&server).await;

        Mock::given(method("GET"))
            .and(path("/api/views/data/training"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "path": "/data/training",
                "total_bytes": 1000,
                "hot_bytes": 750,
                "cold_bytes": 250,
                "quota_bytes": 0
            })))
            .mount(&server)
            .await;

        let readiness = client.data_readiness("/data/training").await.unwrap();
        assert!((readiness - 0.75).abs() < f64::EPSILON);
    }

    #[tokio::test]
    async fn data_readiness_returns_one_for_empty_view() {
        let server = MockServer::start().await;
        let client = mock_client_with_auth(&server).await;

        Mock::given(method("GET"))
            .and(path("/api/views/empty"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "path": "/empty",
                "total_bytes": 0,
                "hot_bytes": 0,
                "cold_bytes": 0,
                "quota_bytes": 0
            })))
            .mount(&server)
            .await;

        let readiness = client.data_readiness("/empty").await.unwrap();
        assert!((readiness - 1.0).abs() < f64::EPSILON);
    }

    #[tokio::test]
    async fn data_readiness_clamps_to_zero_one() {
        let server = MockServer::start().await;
        let client = mock_client_with_auth(&server).await;

        Mock::given(method("GET"))
            .and(path("/api/views/data/all-cold"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "path": "/data/all-cold",
                "total_bytes": 5000,
                "hot_bytes": 0,
                "cold_bytes": 5000,
                "quota_bytes": 0
            })))
            .mount(&server)
            .await;

        let readiness = client.data_readiness("/data/all-cold").await.unwrap();
        assert!((readiness - 0.0).abs() < f64::EPSILON);
    }

    #[tokio::test]
    async fn stage_data_sends_prefetch_request() {
        let server = MockServer::start().await;
        let client = mock_client_with_auth(&server).await;

        Mock::given(method("POST"))
            .and(path("/api/nfs/prefetch"))
            .respond_with(ResponseTemplate::new(200))
            .expect(1)
            .mount(&server)
            .await;

        let result = client.stage_data("/data/input", "/scratch/staging").await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn set_qos_creates_policy() {
        let server = MockServer::start().await;
        let client = mock_client_with_auth(&server).await;

        Mock::given(method("POST"))
            .and(path("/api/qospolicies"))
            .respond_with(ResponseTemplate::new(200))
            .expect(1)
            .mount(&server)
            .await;

        let result = client.set_qos("/data/output", 10.0).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn wipe_data_sends_delete_with_wipe_param() {
        let server = MockServer::start().await;
        let client = mock_client_with_auth(&server).await;

        Mock::given(method("DELETE"))
            .and(path_regex(r"/api/views/.*"))
            .and(query_param("wipe", "true"))
            .respond_with(ResponseTemplate::new(200))
            .expect(1)
            .mount(&server)
            .await;

        let result = client.wipe_data("/sensitive/subject-123").await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn auth_failure_propagates_error() {
        let server = MockServer::start().await;

        // Override the default auth mock with a failing one
        Mock::given(method("POST"))
            .and(path("/api/token"))
            .respond_with(ResponseTemplate::new(401).set_body_string("unauthorized"))
            .mount(&server)
            .await;

        let config = VastConfig {
            base_url: server.uri(),
            username: "bad-user".to_string(),
            password: "bad-pass".to_string(),
            timeout_secs: 5,
        };
        let client = VastClient::new(config).unwrap();

        let result = client.data_readiness("/some/path").await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("401"));
    }

    #[tokio::test]
    async fn stage_data_handles_server_error() {
        let server = MockServer::start().await;
        let client = mock_client_with_auth(&server).await;

        Mock::given(method("POST"))
            .and(path("/api/nfs/prefetch"))
            .respond_with(ResponseTemplate::new(503).set_body_string("service unavailable"))
            .mount(&server)
            .await;

        let result = client.stage_data("/data/input", "/scratch/out").await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("503"));
    }
}