sim-lib-server 0.1.8

SIM workspace package for sim lib server.
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
use sim_cookbook::{EmbeddedDir, RecipeCard, RecipeStore, next, ordered_cards, view};
use sim_kernel::{Cx, Result};
use sim_lib_cookbook::{
    LifecycleAction, LoadableLibList, SeededLibCatalog, projected_recipe_store,
    run_lifecycle_action, run_recipe_with_loadable_libs,
};

use crate::cookbook_web_json::{
    render_error_json, render_index_json, render_recipe_json, render_run_json, render_search_json,
};

const JSON: &str = "application/json; charset=utf-8";
const HTML: &str = "text/html; charset=utf-8";

/// Cookbook state exposed by the WebUI route and JSON API.
pub struct CookbookWebState {
    directory: LoadableLibList,
    diagnostics: Vec<String>,
    extra_books: Vec<EmbeddedDir>,
}

impl CookbookWebState {
    /// Build a WebUI state from the crate-shipped loadable-lib directory.
    pub fn seeded() -> Result<Self> {
        Ok(Self::from_loadable_libs(
            SeededLibCatalog::loadable_libs(),
            Vec::new(),
        ))
    }

    /// Build a WebUI state from the seeded directory plus host-injected books.
    ///
    /// Host-injected books cover facade-level descriptor recipes that are above
    /// `sim-lib-cookbook` in the dependency graph. They are projected on each
    /// request after the dynamic loadable-lib directory reflects the live `Cx`.
    pub fn seeded_with_books(extra: &[(&str, EmbeddedDir)]) -> Result<Self> {
        let mut state = Self::seeded()?;
        state.extra_books = extra.iter().map(|(_, recipes)| *recipes).collect();
        Ok(state)
    }

    /// Build a WebUI state from an effective loadable-lib directory.
    pub fn from_loadable_libs(directory: LoadableLibList, diagnostics: Vec<String>) -> Self {
        Self {
            directory,
            diagnostics,
            extra_books: Vec::new(),
        }
    }

    /// Build an empty WebUI state for tests and no-recipes deployments.
    pub fn empty() -> Self {
        Self::from_loadable_libs(LoadableLibList::new(Vec::new()), Vec::new())
    }

    /// Project a fresh cookbook store from the current runtime context.
    pub fn store(&self, cx: &Cx) -> Result<RecipeStore> {
        let mut store = projected_recipe_store(cx, &self.directory)?;
        for recipes in &self.extra_books {
            let _ = store.register_book(recipes);
        }
        Ok(store)
    }

    /// Route one cookbook WebUI request.
    ///
    /// `target` is an HTTP request target such as `/api/cookbook?q=x`. The run
    /// endpoint requires a runtime context because it executes the same
    /// `sim-lib-cookbook` recipe runner used by the runtime ops and CLI.
    pub fn handle_request(
        &self,
        method: &str,
        target: &str,
        cx: Option<&mut Cx>,
    ) -> CookbookWebResponse {
        let (path, query) = split_target(target);
        match (method, path) {
            ("GET", "/cookbook") => {
                let Some(cx) = cx else {
                    return CookbookWebResponse::server_error(
                        "cookbook page requires a runtime context",
                    );
                };
                let store = match self.store(cx) {
                    Ok(store) => store,
                    Err(err) => return CookbookWebResponse::server_error(err.to_string()),
                };
                let selected = query.and_then(|q| query_value(q, "recipe"));
                CookbookWebResponse::html(render_page(&store, selected.as_deref()))
            }
            ("GET", "/api/cookbook") => {
                let Some(cx) = cx else {
                    return CookbookWebResponse::server_error(
                        "cookbook index requires a runtime context",
                    );
                };
                match self.store(cx) {
                    Ok(store) => {
                        CookbookWebResponse::json(render_index_json(cx, &store, &self.diagnostics))
                    }
                    Err(err) => CookbookWebResponse::server_error(err.to_string()),
                }
            }
            ("GET", "/api/cookbook/search") => {
                let Some(cx) = cx else {
                    return CookbookWebResponse::server_error(
                        "cookbook search requires a runtime context",
                    );
                };
                let q = query
                    .and_then(|query| query_value(query, "q"))
                    .unwrap_or_default();
                match self.store(cx) {
                    Ok(store) => CookbookWebResponse::json(render_search_json(cx, &store, &q)),
                    Err(err) => CookbookWebResponse::server_error(err.to_string()),
                }
            }
            ("POST", path)
                if path.starts_with("/api/cookbook/recipe/") && path.ends_with("/run") =>
            {
                let start = "/api/cookbook/recipe/".len();
                let end = path.len() - "/run".len();
                let raw_id = &path[start..end];
                let Some(cx) = cx else {
                    return CookbookWebResponse::server_error(
                        "cookbook run endpoint requires a runtime context",
                    );
                };
                let store = match self.store(cx) {
                    Ok(store) => store,
                    Err(err) => return CookbookWebResponse::server_error(err.to_string()),
                };
                let id = match decode_component(raw_id, false) {
                    Ok(id) => id,
                    Err(err) => return response_for_resolve_error(err),
                };
                let card = match resolve_recipe(&store, &id) {
                    Ok(card) => card.clone(),
                    Err(err) => {
                        if let Some((action, lib)) = stale_lifecycle_id(&self.directory, &id) {
                            let run = run_lifecycle_action(cx, &self.directory, action, lib, &id);
                            return CookbookWebResponse::json(render_run_json(&run));
                        }
                        return response_for_resolve_error(err);
                    }
                };
                match run_recipe_with_loadable_libs(cx, &self.directory, &card) {
                    Ok(run) => CookbookWebResponse::json(render_run_json(&run)),
                    Err(err) => CookbookWebResponse::server_error(err.to_string()),
                }
            }
            (_, path) if path.starts_with("/api/cookbook/recipe/") && path.ends_with("/run") => {
                CookbookWebResponse::method_not_allowed()
            }
            ("GET", path) if path.starts_with("/api/cookbook/recipe/") => {
                let Some(cx) = cx else {
                    return CookbookWebResponse::server_error(
                        "cookbook detail requires a runtime context",
                    );
                };
                let store = match self.store(cx) {
                    Ok(store) => store,
                    Err(err) => return CookbookWebResponse::server_error(err.to_string()),
                };
                let raw_id = &path["/api/cookbook/recipe/".len()..];
                match decode_component(raw_id, false).and_then(|id| resolve_recipe(&store, &id)) {
                    Ok(card) => CookbookWebResponse::json(render_recipe_json(cx, &store, card)),
                    Err(err) => response_for_resolve_error(err),
                }
            }
            (_, "/api/cookbook") | (_, "/api/cookbook/search") | (_, "/cookbook") => {
                CookbookWebResponse::method_not_allowed()
            }
            (_, path) if path.starts_with("/api/cookbook/recipe/") => {
                CookbookWebResponse::method_not_allowed()
            }
            _ => CookbookWebResponse::not_found("unknown cookbook route"),
        }
    }
}

/// Minimal HTTP response model for cookbook route adapters.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CookbookWebResponse {
    /// HTTP status code.
    pub status: u16,
    /// Response `Content-Type`.
    pub content_type: &'static str,
    /// UTF-8 response body.
    pub body: String,
}

impl CookbookWebResponse {
    fn html(body: String) -> Self {
        Self {
            status: 200,
            content_type: HTML,
            body,
        }
    }

    fn json(body: String) -> Self {
        Self {
            status: 200,
            content_type: JSON,
            body,
        }
    }

    fn not_found(message: impl AsRef<str>) -> Self {
        Self::error(404, message)
    }

    fn method_not_allowed() -> Self {
        Self::error(405, "method not allowed")
    }

    fn server_error(message: impl AsRef<str>) -> Self {
        Self::error(500, message)
    }

    fn error(status: u16, message: impl AsRef<str>) -> Self {
        Self {
            status,
            content_type: JSON,
            body: render_error_json(message.as_ref()),
        }
    }
}

#[derive(Debug, PartialEq, Eq)]
enum ResolveError {
    Unknown(String),
    Ambiguous(String),
    BadRequest(String),
}

fn response_for_resolve_error(err: ResolveError) -> CookbookWebResponse {
    match err {
        ResolveError::Unknown(message) => CookbookWebResponse::not_found(message),
        ResolveError::Ambiguous(message) | ResolveError::BadRequest(message) => {
            CookbookWebResponse::error(400, message)
        }
    }
}

fn stale_lifecycle_id<'a>(
    directory: &'a LoadableLibList,
    id: &str,
) -> Option<(LifecycleAction, &'a str)> {
    let (action, lib) = if let Some(lib) = id.strip_prefix("cookbook/load/") {
        (LifecycleAction::Load, lib)
    } else if let Some(lib) = id.strip_suffix("/cookbook-lifecycle/unload") {
        (LifecycleAction::Unload, lib)
    } else {
        return None;
    };
    directory
        .entry(lib)
        .map(|entry| (action, entry.id.as_str()))
}

fn resolve_recipe<'a>(
    store: &'a RecipeStore,
    id: &str,
) -> std::result::Result<&'a RecipeCard, ResolveError> {
    if id.trim().is_empty() {
        return Err(ResolveError::BadRequest(
            "cookbook recipe id must not be empty".to_owned(),
        ));
    }
    if let Some(card) = store.card(id) {
        return Ok(card);
    }
    let suffix = format!("/{id}");
    let candidates: Vec<&RecipeCard> = ordered_cards(store)
        .into_iter()
        .filter(|card| card.id.ends_with(&suffix))
        .collect();
    match candidates.as_slice() {
        [card] => Ok(*card),
        [] => Err(ResolveError::Unknown(format!("unknown recipe {id}"))),
        many => Err(ResolveError::Ambiguous(format!(
            "ambiguous recipe {id}: {}",
            many.iter()
                .map(|card| card.id.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        ))),
    }
}

fn render_page(store: &RecipeStore, selected: Option<&str>) -> String {
    let selected_card = selected
        .and_then(|id| resolve_recipe(store, id).ok())
        .or_else(|| ordered_cards(store).first().copied());
    let selected_id = selected_card.map(|card| card.id.as_str());
    let mut out = String::from(
        r#"<!DOCTYPE html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>SIM Cookbook</title><link rel="stylesheet" href="/styles/theme.css" /></head><body><nav class="top-nav"><a href="/">Shell</a><a href="/cookbook" aria-current="page">Cookbook</a></nav><main class="cookbook-shell">"#,
    );
    out.push_str(r#"<aside class="cookbook-rail"><input type="search" aria-label="Search recipes" placeholder="Search" /><nav class="cookbook-tree">"#);
    if store.is_empty() {
        out.push_str(r#"<p class="empty-state">No recipes loaded.</p>"#);
    } else {
        render_tree_html(&mut out, store, selected_id);
    }
    out.push_str(r#"</nav></aside><section class="cookbook-main">"#);
    match selected_card {
        Some(card) => render_recipe_html(&mut out, store, card),
        None => out.push_str(r#"<h1>Cookbook</h1><p class="empty-state">No recipes loaded.</p>"#),
    }
    out.push_str("</section></main></body></html>");
    out
}

fn render_tree_html(out: &mut String, store: &RecipeStore, selected: Option<&str>) {
    for book in view(store).books {
        out.push_str("<section><h2>");
        push_html(out, &book.title);
        out.push_str("</h2>");
        for chapter in book.chapters {
            out.push_str("<div><h3>");
            push_html(out, &chapter.title);
            out.push_str("</h3><ul>");
            for recipe in chapter.recipes {
                let active = selected == Some(recipe.id.as_str());
                out.push_str("<li><a href=\"/cookbook?recipe=");
                push_attr(out, &recipe.id);
                out.push('"');
                if active {
                    out.push_str(" aria-current=\"page\" class=\"selected\"");
                }
                out.push('>');
                push_html(out, &recipe.title);
                out.push_str("</a></li>");
            }
            out.push_str("</ul></div>");
        }
        out.push_str("</section>");
    }
}

fn render_recipe_html(out: &mut String, store: &RecipeStore, card: &RecipeCard) {
    out.push_str("<h1>");
    push_html(out, &card.title);
    out.push_str("</h1><div class=\"purpose\">");
    push_purpose_html(out, &card.purpose);
    out.push_str("</div><div class=\"recipe-actions\"><button type=\"button\">Copy</button><button type=\"button\">Run</button></div><pre><code>");
    push_html(out, &String::from_utf8_lossy(&card.setup));
    out.push_str("</code></pre><section class=\"results-panel\" aria-live=\"polite\">Run this recipe to see pass/fail data.</section><footer>");
    if let Some(next) = next(store, &card.id) {
        out.push_str("<a href=\"/cookbook?recipe=");
        push_attr(out, &next.id);
        out.push_str("\">Next recipe -&gt;</a>");
    } else {
        out.push_str("<span>No next recipe.</span>");
    }
    out.push_str("</footer>");
}

fn split_target(target: &str) -> (&str, Option<&str>) {
    match target.split_once('?') {
        Some((path, query)) => (path, Some(query)),
        None => (target, None),
    }
}

fn query_value(query: &str, key: &str) -> Option<String> {
    query.split('&').find_map(|pair| {
        let (name, value) = pair.split_once('=').unwrap_or((pair, ""));
        (name == key).then(|| decode_component(value, true).unwrap_or_default())
    })
}

fn decode_component(raw: &str, plus_is_space: bool) -> std::result::Result<String, ResolveError> {
    let bytes = raw.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'%' if i + 2 < bytes.len() => {
                let hi = hex(bytes[i + 1]);
                let lo = hex(bytes[i + 2]);
                match (hi, lo) {
                    (Some(hi), Some(lo)) => out.push((hi << 4) | lo),
                    _ => {
                        return Err(ResolveError::BadRequest(
                            "invalid percent escape in cookbook route".to_owned(),
                        ));
                    }
                }
                i += 3;
            }
            b'%' => {
                return Err(ResolveError::BadRequest(
                    "truncated percent escape in cookbook route".to_owned(),
                ));
            }
            b'+' if plus_is_space => {
                out.push(b' ');
                i += 1;
            }
            byte => {
                out.push(byte);
                i += 1;
            }
        }
    }
    String::from_utf8(out).map_err(|err| ResolveError::BadRequest(err.to_string()))
}

fn hex(byte: u8) -> Option<u8> {
    match byte {
        b'0'..=b'9' => Some(byte - b'0'),
        b'a'..=b'f' => Some(byte - b'a' + 10),
        b'A'..=b'F' => Some(byte - b'A' + 10),
        _ => None,
    }
}

fn push_purpose_html(out: &mut String, purpose: &str) {
    let mut wrote = false;
    let mut open_p = false;
    for raw in purpose.lines() {
        let line = raw.trim();
        if line.is_empty() {
            if open_p {
                out.push_str("</p>");
                open_p = false;
            }
            continue;
        }
        if let Some(title) = line.strip_prefix("# ") {
            if open_p {
                out.push_str("</p>");
                open_p = false;
            }
            out.push_str("<h2>");
            push_html(out, title);
            out.push_str("</h2>");
        } else {
            if !open_p {
                out.push_str("<p>");
                open_p = true;
            } else {
                out.push(' ');
            }
            push_html(out, line);
        }
        wrote = true;
    }
    if open_p {
        out.push_str("</p>");
    }
    if !wrote {
        out.push_str("<p>No purpose provided.</p>");
    }
}

fn push_html(out: &mut String, text: &str) {
    for ch in text.chars() {
        match ch {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#39;"),
            ch => out.push(ch),
        }
    }
}

fn push_attr(out: &mut String, text: &str) {
    push_html(out, text);
}