aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / spark-mail-rs / src / cortex_sync.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | use crate::models::EmailMessage; |
| 17 | use aien_localhttp::Client; |
| 18 | use serde_json::json; |
| 19 | use std::fs; |
| 20 | use std::path::PathBuf; |
| 21 | use std::time::Duration; |
| 22 | |
| 23 | #[derive(Clone, Debug)] |
| 24 | pub struct CortexSync { |
| 25 | cortex_url: String, |
| 26 | client: Client, |
| 27 | /// Tests only: read the token from here instead of ~/.config/cortex/token. |
| 28 | token_path_override: Option<PathBuf>, |
| 29 | } |
| 30 | |
| 31 | impl CortexSync { |
| 32 | pub fn new(cortex_url: Option<&str>) -> Self { |
| 33 | let url = cortex_url.unwrap_or("http://127.0.0.1:18080").to_string(); |
| 34 | let client = Client::builder().timeout(Duration::from_secs(3)).build(); |
| 35 | Self { |
| 36 | cortex_url: url, |
| 37 | client, |
| 38 | token_path_override: None, |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | fn get_cortex_token(&self) -> String { |
| 43 | let token_path = match &self.token_path_override { |
| 44 | Some(path) => path.clone(), |
| 45 | None => std::env::var("HOME") |
| 46 | .or_else(|_| std::env::var("USERPROFILE")) |
| 47 | .map(PathBuf::from) |
| 48 | .unwrap_or_else(|_| PathBuf::from(".")) |
| 49 | .join(".config/cortex/token"), |
| 50 | }; |
| 51 | if token_path.exists() { |
| 52 | fs::read_to_string(&token_path) |
| 53 | .unwrap_or_default() |
| 54 | .trim() |
| 55 | .to_string() |
| 56 | } else { |
| 57 | String::new() |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | pub async fn check_health(&self) -> bool { |
| 62 | self.client |
| 63 | .get(format!("{}/health", self.cortex_url)) |
| 64 | .timeout(Duration::from_millis(500)) |
| 65 | .send() |
| 66 | .await |
| 67 | .map(|r| r.status().is_success()) |
| 68 | .unwrap_or(false) |
| 69 | } |
| 70 | |
| 71 | pub async fn commit_mail(&self, msg: &EmailMessage) -> Result<(), String> { |
| 72 | let token = self.get_cortex_token(); |
| 73 | let body = if msg.untrusted { |
| 74 | crate::effect::render_untrusted_body(&msg.body) |
| 75 | } else { |
| 76 | msg.body.clone() |
| 77 | }; |
| 78 | let formatted_content = format!( |
| 79 | "From: {}\nTo: {}\nSubject: {}\nDate: {}\nFolder: {}\n\n{}", |
| 80 | msg.from, |
| 81 | msg.to.join(", "), |
| 82 | msg.subject, |
| 83 | msg.received_at, |
| 84 | msg.folder, |
| 85 | body |
| 86 | ); |
| 87 | |
| 88 | let payload = json!({ |
| 89 | "kind": "entity", |
| 90 | "value": { |
| 91 | "canonicalName": format!("mail:{}", msg.id), |
| 92 | "entityType": "correspondence", |
| 93 | "content": formatted_content, |
| 94 | "metadata": { |
| 95 | "mail_id": msg.id, |
| 96 | "subject": msg.subject, |
| 97 | "from": msg.from, |
| 98 | "to": msg.to, |
| 99 | "folder": msg.folder, |
| 100 | "received_at": msg.received_at, |
| 101 | "untrusted": msg.untrusted, |
| 102 | "tool_calls": [], |
| 103 | "instructions": null |
| 104 | }, |
| 105 | "space": "atlas-memory" |
| 106 | } |
| 107 | }); |
| 108 | |
| 109 | let mut req = self |
| 110 | .client |
| 111 | .post(format!("{}/api/cortex/write", self.cortex_url)) |
| 112 | .header("Content-Type", "application/json"); |
| 113 | |
| 114 | if !token.is_empty() { |
| 115 | req = req.header("Authorization", format!("Bearer {}", token)); |
| 116 | } |
| 117 | |
| 118 | let resp = req |
| 119 | .json(&payload) |
| 120 | .send() |
| 121 | .await |
| 122 | .map_err(|e| format!("Cortex connection failed: {}", e))?; |
| 123 | |
| 124 | if resp.status().is_success() { |
| 125 | Ok(()) |
| 126 | } else { |
| 127 | Err(format!("Cortex write returned HTTP {}", resp.status())) |
| 128 | } |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | #[cfg(test)] |
| 133 | mod tests { |
| 134 | use super::*; |
| 135 | use aien_localhttp::test_server::{closed_port, response, serve_once, serve_silent}; |
| 136 | use std::collections::HashMap; |
| 137 | |
| 138 | fn sync_with_token(base: &str, token: Option<&str>) -> (CortexSync, PathBuf) { |
| 139 | let path = |
| 140 | std::env::temp_dir().join(format!("spark-mail-cortex-token-{}", uuid::Uuid::new_v4())); |
| 141 | if let Some(token) = token { |
| 142 | fs::write(&path, token).unwrap(); |
| 143 | } |
| 144 | let mut sync = CortexSync::new(Some(base)); |
| 145 | sync.token_path_override = Some(path.clone()); |
| 146 | (sync, path) |
| 147 | } |
| 148 | |
| 149 | fn message() -> EmailMessage { |
| 150 | EmailMessage { |
| 151 | id: "m1".into(), |
| 152 | from: "a@example.test".into(), |
| 153 | to: vec!["b@example.test".into()], |
| 154 | subject: "Hi".into(), |
| 155 | body: "hello".into(), |
| 156 | headers: HashMap::new(), |
| 157 | received_at: "2026-10-15T00:00:00Z".into(), |
| 158 | folder: "INBOX".into(), |
| 159 | cortex_indexed: false, |
| 160 | untrusted: false, |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | #[tokio::test] |
| 165 | async fn check_health_is_true_only_for_2xx() { |
| 166 | let (base, server) = serve_once(response("200 OK", "text/plain", "ok")).await; |
| 167 | assert!(CortexSync::new(Some(&base)).check_health().await); |
| 168 | assert!( |
| 169 | server |
| 170 | .await |
| 171 | .unwrap() |
| 172 | .starts_with("GET /health HTTP/1.1\r\n") |
| 173 | ); |
| 174 | |
| 175 | let (base, _server) = |
| 176 | serve_once(response("503 Service Unavailable", "text/plain", "")).await; |
| 177 | assert!(!CortexSync::new(Some(&base)).check_health().await); |
| 178 | assert!( |
| 179 | !CortexSync::new(Some(&closed_port().await)) |
| 180 | .check_health() |
| 181 | .await |
| 182 | ); |
| 183 | assert!( |
| 184 | !CortexSync::new(Some("https://127.0.0.1:1")) |
| 185 | .check_health() |
| 186 | .await |
| 187 | ); |
| 188 | } |
| 189 | |
| 190 | #[tokio::test] |
| 191 | async fn check_health_gives_up_after_500_ms() { |
| 192 | let (base, _server) = serve_silent().await; |
| 193 | let started = std::time::Instant::now(); |
| 194 | assert!(!CortexSync::new(Some(&base)).check_health().await); |
| 195 | assert!(started.elapsed() < Duration::from_secs(2)); |
| 196 | } |
| 197 | |
| 198 | #[tokio::test] |
| 199 | async fn commit_mail_sends_the_same_request_with_bearer_token() { |
| 200 | let (base, server) = serve_once(response("200 OK", "application/json", "{}")).await; |
| 201 | let (sync, path) = sync_with_token(&base, Some("tok\n")); |
| 202 | sync.commit_mail(&message()).await.unwrap(); |
| 203 | let _ = fs::remove_file(&path); |
| 204 | let request = server.await.unwrap(); |
| 205 | assert!( |
| 206 | request.starts_with("POST /api/cortex/write HTTP/1.1\r\n"), |
| 207 | "{request}" |
| 208 | ); |
| 209 | assert!( |
| 210 | request.contains("\r\nAuthorization: Bearer tok\r\n"), |
| 211 | "{request}" |
| 212 | ); |
| 213 | assert_eq!(request.matches("Content-Type: application/json").count(), 1); |
| 214 | let body: serde_json::Value = |
| 215 | serde_json::from_str(request.split("\r\n\r\n").nth(1).unwrap()).unwrap(); |
| 216 | assert_eq!(body["kind"], "entity"); |
| 217 | assert_eq!(body["value"]["canonicalName"], "mail:m1"); |
| 218 | assert_eq!(body["value"]["entityType"], "correspondence"); |
| 219 | assert_eq!(body["value"]["metadata"]["untrusted"], false); |
| 220 | } |
| 221 | |
| 222 | #[tokio::test] |
| 223 | async fn commit_mail_without_token_sends_no_authorization() { |
| 224 | let (base, server) = serve_once(response("200 OK", "application/json", "{}")).await; |
| 225 | let (sync, _path) = sync_with_token(&base, None); |
| 226 | sync.commit_mail(&message()).await.unwrap(); |
| 227 | let request = server.await.unwrap(); |
| 228 | assert!( |
| 229 | !request.to_ascii_lowercase().contains("authorization:"), |
| 230 | "{request}" |
| 231 | ); |
| 232 | } |
| 233 | |
| 234 | #[tokio::test] |
| 235 | async fn commit_mail_reports_error_status_and_transport_failures() { |
| 236 | let (base, _server) = |
| 237 | serve_once(response("500 Internal Server Error", "text/plain", "")).await; |
| 238 | let (sync, _path) = sync_with_token(&base, None); |
| 239 | assert_eq!( |
| 240 | sync.commit_mail(&message()).await.unwrap_err(), |
| 241 | "Cortex write returned HTTP 500 Internal Server Error" |
| 242 | ); |
| 243 | |
| 244 | let (sync, _path) = sync_with_token(&closed_port().await, None); |
| 245 | let err = sync.commit_mail(&message()).await.unwrap_err(); |
| 246 | assert!(err.starts_with("Cortex connection failed: "), "{err}"); |
| 247 | |
| 248 | let (sync, _path) = sync_with_token("https://127.0.0.1:1", None); |
| 249 | let err = sync.commit_mail(&message()).await.unwrap_err(); |
| 250 | assert!(err.contains("https is refused"), "{err}"); |
| 251 | } |
| 252 | } |