Skip to main content

skenion_runtime/
sidecar.rs

1use serde::{Deserialize, Serialize};
2use skenion_contracts::{
3    RuntimeConnectionProfile, RuntimeConnectionProfileMode, RuntimeEndpointMetadata,
4    RuntimeEndpointProtocol, RuntimeOwnershipMode, RuntimeProcessMetadata,
5};
6
7use crate::{DiagnosticSeverity, RUNTIME_API_VERSION, RuntimeDiagnostic};
8
9#[derive(Debug, Clone)]
10pub struct RuntimeEndpointConfig {
11    pub host: String,
12    pub port: u16,
13    pub url: String,
14}
15
16impl RuntimeEndpointConfig {
17    pub fn new(host: String, port: u16) -> Self {
18        let url = format!("http://{host}:{port}");
19        Self { host, port, url }
20    }
21}
22
23#[derive(Debug, Clone, Serialize)]
24#[serde(rename_all = "camelCase")]
25pub struct RuntimeSidecarStartupResponse {
26    pub schema: &'static str,
27    pub schema_version: &'static str,
28    pub ok: bool,
29    pub runtime: RuntimeSidecarRuntimeInfo,
30    pub endpoint: RuntimeEndpointMetadata,
31    pub profile: RuntimeConnectionProfile,
32    pub default_session_id: String,
33    pub default_session_url: String,
34    pub health: RuntimeSidecarHealthInfo,
35    pub token: RuntimeSidecarTokenInfo,
36    pub shutdown: RuntimeSidecarShutdownInfo,
37    pub diagnostics: Vec<RuntimeDiagnostic>,
38}
39
40#[derive(Debug, Clone, Serialize)]
41#[serde(rename_all = "camelCase")]
42pub struct RuntimeSidecarRuntimeInfo {
43    pub name: &'static str,
44    pub version: &'static str,
45    pub api_version: &'static str,
46}
47
48#[derive(Debug, Clone, Serialize)]
49#[serde(rename_all = "camelCase")]
50pub struct RuntimeSidecarHealthInfo {
51    pub ok: bool,
52    pub url: String,
53}
54
55#[derive(Debug, Clone, Serialize)]
56#[serde(rename_all = "camelCase")]
57pub struct RuntimeSidecarHealthResponse {
58    pub schema: &'static str,
59    pub schema_version: &'static str,
60    pub ok: bool,
61    pub readiness: &'static str,
62    pub runtime: RuntimeSidecarRuntimeInfo,
63    pub endpoint: RuntimeEndpointMetadata,
64    pub profile: RuntimeConnectionProfile,
65    pub diagnostics: Vec<RuntimeDiagnostic>,
66}
67
68#[derive(Debug, Clone, Serialize)]
69#[serde(rename_all = "camelCase")]
70pub struct RuntimeSidecarTokenInfo {
71    pub required: bool,
72    pub header: &'static str,
73    #[serde(skip_serializing_if = "Option::is_none")]
74    pub token: Option<String>,
75}
76
77#[derive(Debug, Clone, Serialize)]
78#[serde(rename_all = "camelCase")]
79pub struct RuntimeSidecarShutdownInfo {
80    pub supported: bool,
81    pub method: &'static str,
82    pub url: String,
83    pub scope: &'static str,
84}
85
86#[derive(Debug, Clone, Deserialize)]
87#[serde(rename_all = "camelCase")]
88pub struct RuntimeSidecarShutdownRequest {
89    #[serde(default)]
90    pub reason: Option<String>,
91    #[serde(default)]
92    pub owner_window_id: Option<String>,
93}
94
95#[derive(Debug, Clone, Serialize)]
96#[serde(rename_all = "camelCase")]
97pub struct RuntimeSidecarShutdownResponse {
98    pub schema: &'static str,
99    pub schema_version: &'static str,
100    pub ok: bool,
101    pub accepted: bool,
102    pub action: &'static str,
103    pub scope: &'static str,
104    pub diagnostics: Vec<RuntimeDiagnostic>,
105}
106
107pub(crate) fn sidecar_startup_response(
108    endpoint_config: &RuntimeEndpointConfig,
109    default_session_id: &str,
110    started_at_wall_clock: &str,
111) -> RuntimeSidecarStartupResponse {
112    let endpoint = runtime_endpoint_metadata(endpoint_config);
113    RuntimeSidecarStartupResponse {
114        schema: "skenion.runtime.sidecar.startup",
115        schema_version: "0.1.0",
116        ok: true,
117        runtime: RuntimeSidecarRuntimeInfo {
118            name: "skenion-runtime",
119            version: env!("CARGO_PKG_VERSION"),
120            api_version: RUNTIME_API_VERSION,
121        },
122        endpoint: endpoint.clone(),
123        profile: runtime_connection_profile(endpoint_config, started_at_wall_clock),
124        default_session_id: default_session_id.to_owned(),
125        default_session_url: format!("{}/v0/sessions/{default_session_id}", endpoint.url),
126        health: RuntimeSidecarHealthInfo {
127            ok: true,
128            url: format!("{}/v0/sidecar/health", endpoint.url),
129        },
130        token: runtime_sidecar_token(),
131        shutdown: RuntimeSidecarShutdownInfo {
132            supported: true,
133            method: "POST",
134            url: format!("{}/v0/sidecar/shutdown", endpoint.url),
135            scope: "owned-child-only",
136        },
137        diagnostics: Vec::new(),
138    }
139}
140
141pub(crate) fn sidecar_health_response(
142    endpoint_config: &RuntimeEndpointConfig,
143    started_at_wall_clock: &str,
144) -> RuntimeSidecarHealthResponse {
145    RuntimeSidecarHealthResponse {
146        schema: "skenion.runtime.sidecar.health",
147        schema_version: "0.1.0",
148        ok: true,
149        readiness: "ready",
150        runtime: RuntimeSidecarRuntimeInfo {
151            name: "skenion-runtime",
152            version: env!("CARGO_PKG_VERSION"),
153            api_version: RUNTIME_API_VERSION,
154        },
155        endpoint: runtime_endpoint_metadata(endpoint_config),
156        profile: runtime_connection_profile(endpoint_config, started_at_wall_clock),
157        diagnostics: Vec::new(),
158    }
159}
160
161pub(crate) fn runtime_connection_profile(
162    endpoint_config: &RuntimeEndpointConfig,
163    started_at_wall_clock: &str,
164) -> RuntimeConnectionProfile {
165    RuntimeConnectionProfile {
166        mode: RuntimeConnectionProfileMode::LocalManaged,
167        ownership: RuntimeOwnershipMode::OwnedChild,
168        display_name: Some("Skenion Runtime local-managed sidecar".to_owned()),
169        endpoint: runtime_endpoint_metadata(endpoint_config),
170        process: Some(RuntimeProcessMetadata {
171            owned_by_host: true,
172            pid: Some(std::process::id()),
173            executable_path: std::env::current_exe()
174                .ok()
175                .map(|path| path.display().to_string()),
176            working_directory: std::env::current_dir()
177                .ok()
178                .map(|path| path.display().to_string()),
179            started_at: Some(started_at_wall_clock.to_owned()),
180            owner_window_id: None,
181            platform: Some(std::env::consts::OS.to_owned()),
182            arch: Some(std::env::consts::ARCH.to_owned()),
183        }),
184    }
185}
186
187fn runtime_endpoint_metadata(endpoint_config: &RuntimeEndpointConfig) -> RuntimeEndpointMetadata {
188    RuntimeEndpointMetadata {
189        url: endpoint_config.url.clone(),
190        canonical_url: Some(endpoint_config.url.clone()),
191        protocol: RuntimeEndpointProtocol::Http,
192        host: Some(endpoint_config.host.clone()),
193        port: Some(endpoint_config.port),
194        tls: Some(false),
195    }
196}
197
198fn runtime_sidecar_token() -> RuntimeSidecarTokenInfo {
199    runtime_sidecar_token_from_value(std::env::var("SKENION_RUNTIME_TOKEN").ok())
200}
201
202fn runtime_sidecar_token_from_value(token: Option<String>) -> RuntimeSidecarTokenInfo {
203    let token = match token {
204        Some(token) if !token.is_empty() => Some(token),
205        _ => None,
206    };
207    RuntimeSidecarTokenInfo {
208        required: token.is_some(),
209        header: "Authorization",
210        token,
211    }
212}
213
214pub(crate) fn sidecar_shutdown_response(body: &[u8]) -> RuntimeSidecarShutdownResponse {
215    let diagnostics = match sidecar_shutdown_request(body) {
216        Ok(request) => shutdown_request_diagnostics(request),
217        Err(error) => vec![RuntimeDiagnostic::error(format!(
218            "invalid sidecar shutdown request: {error}"
219        ))],
220    };
221    RuntimeSidecarShutdownResponse {
222        schema: "skenion.runtime.sidecar.shutdown",
223        schema_version: "0.1.0",
224        ok: diagnostics
225            .iter()
226            .all(|diagnostic| diagnostic.severity != DiagnosticSeverity::Error),
227        accepted: false,
228        action: "host-owned-process-stop-required",
229        scope: "owned-child-only",
230        diagnostics,
231    }
232}
233
234fn sidecar_shutdown_request(
235    body: &[u8],
236) -> Result<RuntimeSidecarShutdownRequest, serde_json::Error> {
237    if body.is_empty() {
238        return Ok(RuntimeSidecarShutdownRequest {
239            reason: None,
240            owner_window_id: None,
241        });
242    }
243    serde_json::from_slice(body)
244}
245
246fn shutdown_request_diagnostics(request: RuntimeSidecarShutdownRequest) -> Vec<RuntimeDiagnostic> {
247    let mut diagnostics = vec![RuntimeDiagnostic::warning(
248        "runtime shutdown is a structured primitive; the host must stop only its owned child process",
249    )];
250    if let Some(reason) = request.reason.filter(|reason| !reason.is_empty()) {
251        diagnostics.push(RuntimeDiagnostic {
252            severity: DiagnosticSeverity::Info,
253            message: format!("shutdown requested: {reason}"),
254            code: Some("sidecar.shutdown.reason".to_owned()),
255            details: request
256                .owner_window_id
257                .map(|owner_window_id| serde_json::json!({ "ownerWindowId": owner_window_id })),
258        });
259    }
260    diagnostics
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266
267    #[test]
268    fn startup_response_is_machine_readable() {
269        let endpoint = RuntimeEndpointConfig::new("127.0.0.1".to_owned(), 3761);
270        let response = sidecar_startup_response(&endpoint, "default", "unix-ms:1");
271
272        assert!(response.ok);
273        assert_eq!(response.endpoint.url, "http://127.0.0.1:3761");
274        assert_eq!(response.default_session_id, "default");
275        assert_eq!(
276            response.profile.mode,
277            RuntimeConnectionProfileMode::LocalManaged
278        );
279        assert_eq!(response.token.header, "Authorization");
280        assert_eq!(response.shutdown.scope, "owned-child-only");
281    }
282
283    #[test]
284    fn health_response_is_not_startup_handshake() {
285        let endpoint = RuntimeEndpointConfig::new("127.0.0.1".to_owned(), 3761);
286        let response = sidecar_health_response(&endpoint, "unix-ms:1");
287        let value = serde_json::to_value(&response).expect("health response should serialize");
288
289        assert!(response.ok);
290        assert_eq!(response.schema, "skenion.runtime.sidecar.health");
291        assert_eq!(response.readiness, "ready");
292        assert_eq!(response.runtime.version, env!("CARGO_PKG_VERSION"));
293        assert_eq!(response.endpoint.url, "http://127.0.0.1:3761");
294        assert!(value.get("token").is_none());
295        assert!(value.get("shutdown").is_none());
296        assert!(value.get("defaultSessionUrl").is_none());
297    }
298
299    #[test]
300    fn token_info_reports_present_token_without_environment_mutation() {
301        let present = runtime_sidecar_token_from_value(Some("test-token".to_owned()));
302        let empty = runtime_sidecar_token_from_value(Some(String::new()));
303
304        assert!(present.required);
305        assert_eq!(present.token.as_deref(), Some("test-token"));
306        assert!(!empty.required);
307        assert!(empty.token.is_none());
308    }
309
310    #[test]
311    fn shutdown_response_is_structured_without_killing_processes() {
312        let empty = sidecar_shutdown_response(&[]);
313        let reason = sidecar_shutdown_response(
314            br#"{ "reason": "window-close", "ownerWindowId": "window-1" }"#,
315        );
316        let invalid = sidecar_shutdown_response(b"{");
317
318        assert!(empty.ok);
319        assert!(!empty.accepted);
320        assert!(reason.ok);
321        assert_eq!(reason.diagnostics.len(), 2);
322        assert!(!invalid.ok);
323    }
324}