boatramp 0.2.5

boatramp — self-hosted, streaming-first static site publishing (server + CLI in one binary)
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
//! The `function` subcommand — the FaaS **function** surface (PLAN-faas).
//!
//! FA-1 shipped the read view: list/show the derived site-scoped functions a site's
//! handlers/consumers/crons desugar to. FA-2 adds the write view for **top-level**
//! functions — `deploy` a component version, `rollback`, `alias`, and `rm` — each
//! carrying its own independent version line. `function invoke` lands in FA-3.

use boatramp_core::function::FunctionSummary;
use serde::Deserialize;

use crate::client;
use crate::config::ProjectConfig;

mod build;
mod scaffold;

use build::build_project;
use scaffold::init_project;
// `sanitize_crate_name` is exercised only by the unit tests below.
#[cfg(test)]
use scaffold::sanitize_crate_name;

/// A failure in the `function` subcommand.
#[derive(Debug, thiserror::Error)]
pub enum FunctionError {
    /// Resolving the target or a control-plane call failed.
    #[error(transparent)]
    Client(#[from] crate::client::ClientError),
    /// A control-plane HTTP request failed.
    #[error("control-plane request: {0}")]
    Http(#[from] reqwest::Error),
    /// Reading the invoke request body (a file or stdin) failed.
    #[error("reading request body: {0}")]
    Io(#[from] std::io::Error),
    /// `function trigger add` needs exactly one of `--cron` / `--queue` / `--blob`.
    #[error("specify exactly one of --cron, --queue, or --blob")]
    BadTrigger,
    /// `function init --lang` named an unknown template.
    #[error("unknown template language {0:?} (supported: rust, js, python)")]
    UnknownLang(String),
    /// `function init` target directory already exists.
    #[error("{0} already exists")]
    AlreadyExists(std::path::PathBuf),
    /// `function build` (the language's componentize invocation) failed.
    #[error("build failed (Rust: wasm32-wasip2 target; JS: node/npx; Python: uv/componentize-py)")]
    BuildFailed,
    /// `function build` produced no component `.wasm`.
    #[error("no component produced under target/wasm32-wasip2/release")]
    NoComponent,
    /// The local harness (`function test`/`dev`) failed to run the component.
    #[cfg(feature = "handlers")]
    #[error("running the component: {0}")]
    Harness(String),
    /// A `function test` assertion (status / body) failed.
    #[cfg(feature = "handlers")]
    #[error("function test assertion failed")]
    HarnessFailed,
}

type Result<T> = std::result::Result<T, FunctionError>;

/// `function` — inspect the functions a site runs.
#[derive(Debug, clap::Args)]
pub struct FunctionArgs {
    #[command(subcommand)]
    command: FunctionCommand,
}

#[derive(Debug, clap::Subcommand)]
enum FunctionCommand {
    /// List functions (optionally for one site).
    Ls {
        /// Only this site.
        #[arg(long)]
        site: Option<String>,
        /// Server base URL (overrides config/env).
        #[arg(long)]
        server: Option<String>,
    },
    /// Show one function by its `<site>/<name>`.
    Get {
        /// The `<site>/<name>` shown by `function ls`.
        name: String,
        /// Server base URL (overrides config/env).
        #[arg(long)]
        server: Option<String>,
    },
    /// Deploy a version of a top-level function from a component `.wasm`.
    Deploy {
        /// Function name.
        name: String,
        /// Path to the component `.wasm` (uploaded as a content-addressed blob).
        #[arg(long)]
        component: std::path::PathBuf,
        /// Execution substrate: `wasm` (default), `microvm`, or `container`.
        #[arg(long)]
        runtime: Option<String>,
        /// Enable a signed webhook: the host env var holding the HMAC-SHA256
        /// verifying secret (never the secret itself).
        #[arg(long)]
        webhook_secret_env: Option<String>,
        /// Server base URL.
        #[arg(long)]
        server: Option<String>,
    },
    /// Roll a function's active version back to `--to <version>`.
    Rollback {
        /// Function name.
        name: String,
        /// The version id to activate.
        #[arg(long)]
        to: String,
        /// Server base URL.
        #[arg(long)]
        server: Option<String>,
    },
    /// Point an alias label at a version.
    Alias {
        /// Function name.
        name: String,
        /// The alias label (e.g. `prod`, `staging`).
        label: String,
        /// The version id the alias points at.
        version: String,
        /// Server base URL.
        #[arg(long)]
        server: Option<String>,
    },
    /// Remove a top-level function.
    Rm {
        /// Function name.
        name: String,
        /// Server base URL.
        #[arg(long)]
        server: Option<String>,
    },
    /// Invoke a function. Reads the request body from `--data`, `--data-file`, or
    /// stdin; prints the function's response body.
    Invoke {
        /// Function name.
        name: String,
        /// Inline request body (mutually exclusive with `--data-file`).
        #[arg(long, conflicts_with = "data_file")]
        data: Option<String>,
        /// Read the request body from this file (`-` = stdin).
        #[arg(long)]
        data_file: Option<std::path::PathBuf>,
        /// Content type of the request body.
        #[arg(long)]
        content_type: Option<String>,
        /// Deliver asynchronously: enqueue + print the invocation id to poll.
        #[arg(long)]
        r#async: bool,
        /// Idempotency key — a repeat with the same key replays the first outcome.
        #[arg(long)]
        idempotency_key: Option<String>,
        /// Invoke a specific version/alias instead of the active version.
        #[arg(long)]
        version: Option<String>,
        /// Server base URL.
        #[arg(long)]
        server: Option<String>,
    },
    /// Show a durable (async) invocation's status/result by id.
    Invocation {
        /// Function name.
        name: String,
        /// The invocation id from `function invoke --async`.
        id: String,
        /// Server base URL.
        #[arg(long)]
        server: Option<String>,
    },
    /// Show a function's usage aggregate (invocations, duration, bytes).
    Usage {
        /// Function name.
        name: String,
        /// Server base URL.
        #[arg(long)]
        server: Option<String>,
    },
    /// Manage a function's scheduled / event triggers (cron, queue).
    Trigger(TriggerArgs),
    /// Scaffold a new function project from a language template.
    Init {
        /// Function/project name (also the Rust crate name).
        name: String,
        /// Language template: `rust` (default), `js`, or `python`.
        #[arg(long, default_value = "rust")]
        lang: String,
        /// Parent directory to create the project under (default: cwd).
        #[arg(long)]
        dir: Option<std::path::PathBuf>,
    },
    /// Build a function project to a `wasi:http` component (`cargo build
    /// --release --target wasm32-wasip2`). Prints the produced `.wasm` path.
    Build {
        /// The project directory (default: cwd).
        #[arg(long)]
        dir: Option<std::path::PathBuf>,
    },
    /// Run a component locally against one request and assert on the response
    /// (the local single-function harness).
    #[cfg(feature = "handlers")]
    Test {
        /// Path to the component `.wasm`.
        #[arg(long)]
        component: std::path::PathBuf,
        /// Request path (default `/`).
        #[arg(long, default_value = "/")]
        path: String,
        /// Request method (default `GET`).
        #[arg(long, default_value = "GET")]
        method: String,
        /// Inline request body.
        #[arg(long)]
        data: Option<String>,
        /// Request content type.
        #[arg(long)]
        content_type: Option<String>,
        /// Assert the response status equals this.
        #[arg(long)]
        expect_status: Option<u16>,
        /// Assert the response body contains this substring.
        #[arg(long)]
        expect_body: Option<String>,
    },
    /// Serve a component locally on an HTTP port (the local dev harness).
    #[cfg(feature = "handlers")]
    Dev {
        /// Path to the component `.wasm`.
        #[arg(long)]
        component: std::path::PathBuf,
        /// Port to listen on (127.0.0.1).
        #[arg(long, default_value = "8787")]
        port: u16,
    },
}

/// `function trigger` — cron + queue triggers the server dispatches.
#[derive(Debug, clap::Args)]
struct TriggerArgs {
    #[command(subcommand)]
    command: TriggerCommand,
}

#[derive(Debug, clap::Subcommand)]
enum TriggerCommand {
    /// Add/replace a trigger. Exactly one of `--cron` / `--queue` / `--blob`.
    Add {
        /// Function name.
        name: String,
        /// Trigger id (unique within the function).
        id: String,
        /// A cron schedule (`min hour dom month dow`) — a scheduled invoke.
        #[arg(long, conflicts_with_all = ["queue", "blob"])]
        cron: Option<String>,
        /// A queue topic — invoke the function per message on `fn/<name>/<topic>`.
        #[arg(long, conflicts_with = "blob")]
        queue: Option<String>,
        /// A blobstore prefix — invoke the function when an object under
        /// `fn/<name>/<prefix>` changes (needs a watch-capable storage backend).
        #[arg(long)]
        blob: Option<String>,
        /// Server base URL.
        #[arg(long)]
        server: Option<String>,
    },
    /// List a function's triggers.
    Ls {
        /// Function name.
        name: String,
        /// Server base URL.
        #[arg(long)]
        server: Option<String>,
    },
    /// Remove a trigger by id.
    Rm {
        /// Function name.
        name: String,
        /// Trigger id.
        id: String,
        /// Server base URL.
        #[arg(long)]
        server: Option<String>,
    },
}

/// A stored trigger as `/triggers` reports it (id + kind).
#[derive(Debug, Deserialize)]
struct TriggerView {
    id: String,
    kind: serde_json::Value,
}

/// The stored `Function` a mutating call (`deploy`/`rollback`) echoes back — the
/// full record, of which we only surface the name, active version, and runtime.
#[derive(Debug, Deserialize)]
struct StoredFunction {
    name: String,
    active: String,
    #[serde(default)]
    config: StoredConfig,
}

#[derive(Debug, Default, Deserialize)]
struct StoredConfig {
    #[serde(default)]
    runtime: String,
}

/// A durable invocation record as `/invoke` (async) and `/invocations/:id`
/// report it — the fields the CLI surfaces.
#[derive(Debug, Deserialize)]
struct InvocationRecord {
    id: String,
    status: String,
    #[serde(default)]
    attempts: u32,
    #[serde(default)]
    result: Option<InvocationResultView>,
}

#[derive(Debug, Deserialize)]
struct InvocationResultView {
    status: u16,
}

/// A function's usage aggregate as `/usage` reports it (FA-4).
#[derive(Debug, Default, Deserialize)]
struct UsageView {
    function: String,
    #[serde(default)]
    invocations: u64,
    #[serde(default)]
    successes: u64,
    #[serde(default)]
    failures: u64,
    #[serde(default)]
    duration_ms_total: u64,
    #[serde(default)]
    bytes_in_total: u64,
    #[serde(default)]
    bytes_out_total: u64,
}

/// Run the `function` subcommand.
pub async fn run(args: FunctionArgs, config: &ProjectConfig) -> Result<()> {
    // Honor `--project`: every function URL is scoped to the collection segment
    // (`functions` for default, else `projects/<proj>/functions`), so `--project` is
    // no longer silently dropped on the deploy/config path.
    let seg = client::project_seg(&client::resolve_project(config), "functions");
    match args.command {
        FunctionCommand::Ls { site, server } => {
            let funcs = fetch(server, site, config).await?;
            if funcs.is_empty() {
                println!("no functions");
                return Ok(());
            }
            for f in funcs {
                println!(
                    "{}  [{}]  {}  {}",
                    f.name,
                    f.runtime,
                    short(&f.version),
                    f.triggers.join(", ")
                );
            }
        }
        FunctionCommand::Get { name, server } => {
            let funcs = fetch(server, None, config).await?;
            match funcs.into_iter().find(|f| f.name == name) {
                Some(f) => {
                    println!("{}", f.name);
                    println!("  runtime: {}", f.runtime);
                    println!("  version: {}", f.version);
                    for t in &f.triggers {
                        println!("  trigger: {t}");
                    }
                }
                None => println!("no function {name:?}"),
            }
        }
        FunctionCommand::Deploy {
            name,
            component,
            runtime,
            webhook_secret_env,
            server,
        } => {
            let (server, http) = client::connect(server, config)?;
            let cp = client::ControlPlane::new(
                server.clone(),
                http.clone(),
                client::resolve_project(config),
            );
            // Upload the component first; the server rejects a deploy whose blob is
            // absent, so this is content-addressed staging, not a second round-trip.
            let hash = cp.put_file_blob(&component).await?;
            let mut cfg = serde_json::Map::new();
            if let Some(r) = &runtime {
                cfg.insert("runtime".to_string(), serde_json::json!(r));
            }
            if let Some(secret_env) = &webhook_secret_env {
                cfg.insert(
                    "webhook".to_string(),
                    serde_json::json!({ "secret_env": secret_env }),
                );
            }
            // Top-level functions carry their own version line (decision 3).
            let body = serde_json::json!({
                "component": hash,
                "config": serde_json::Value::Object(cfg),
                "lifecycle": "independent",
            });
            let f: StoredFunction = http
                .put(format!("{server}/api/{seg}/{name}"))
                .json(&body)
                .send()
                .await?
                .error_for_status()?
                .json()
                .await?;
            println!(
                "deployed {}  [{}]  {}",
                f.name,
                f.config.runtime,
                short(&f.active)
            );
        }
        FunctionCommand::Rollback { name, to, server } => {
            let (server, http) = client::connect(server, config)?;
            let f: StoredFunction = http
                .post(format!("{server}/api/{seg}/{name}/rollback"))
                .json(&serde_json::json!({ "to": to }))
                .send()
                .await?
                .error_for_status()?
                .json()
                .await?;
            println!("rolled {} back to {}", f.name, short(&f.active));
        }
        FunctionCommand::Alias {
            name,
            label,
            version,
            server,
        } => {
            let (server, http) = client::connect(server, config)?;
            http.put(format!("{server}/api/{seg}/{name}/aliases/{label}"))
                .json(&serde_json::json!({ "version": version }))
                .send()
                .await?
                .error_for_status()?;
            println!("aliased {name}:{label} -> {}", short(&version));
        }
        FunctionCommand::Rm { name, server } => {
            let (server, http) = client::connect(server, config)?;
            http.delete(format!("{server}/api/{seg}/{name}"))
                .send()
                .await?
                .error_for_status()?;
            println!("removed {name}");
        }
        FunctionCommand::Invoke {
            name,
            data,
            data_file,
            content_type,
            r#async,
            idempotency_key,
            version,
            server,
        } => {
            let (server, http) = client::connect(server, config)?;
            let body = read_invoke_body(data, data_file).await?;
            let mut qs: Vec<String> = Vec::new();
            if r#async {
                qs.push("mode=async".to_string());
            }
            if let Some(v) = &version {
                qs.push(format!("version={v}"));
            }
            let url = if qs.is_empty() {
                format!("{server}/api/{seg}/{name}/invoke")
            } else {
                format!("{server}/api/{seg}/{name}/invoke?{}", qs.join("&"))
            };
            let mut req = http.post(url).body(body);
            if let Some(ct) = &content_type {
                req = req.header("content-type", ct.as_str());
            }
            if let Some(key) = &idempotency_key {
                req = req.header("idempotency-key", key.as_str());
            }
            let resp = req.send().await?;
            let status = resp.status();
            let bytes = resp.bytes().await?;
            if r#async {
                // 202 + a JSON invocation record: surface the id to poll.
                match serde_json::from_slice::<InvocationRecord>(&bytes) {
                    Ok(inv) => println!("queued {} [{}]", inv.id, inv.status),
                    Err(_) => eprint!("{}", String::from_utf8_lossy(&bytes)),
                }
            } else {
                // Print the function's response body verbatim; note a non-success
                // status on stderr (a control-plane 404/401, or the guest's own).
                use std::io::Write;
                let _ = std::io::stdout().write_all(&bytes);
                if !status.is_success() {
                    eprintln!("invoke returned HTTP {}", status.as_u16());
                }
            }
        }
        FunctionCommand::Invocation { name, id, server } => {
            let (server, http) = client::connect(server, config)?;
            let inv: InvocationRecord = http
                .get(format!("{server}/api/{seg}/{name}/invocations/{id}"))
                .send()
                .await?
                .error_for_status()?
                .json()
                .await?;
            println!("{}  [{}]  attempts={}", inv.id, inv.status, inv.attempts);
            if let Some(result) = &inv.result {
                println!("  result: HTTP {}", result.status);
            }
        }
        FunctionCommand::Usage { name, server } => {
            let (server, http) = client::connect(server, config)?;
            let usage: UsageView = http
                .get(format!("{server}/api/{seg}/{name}/usage"))
                .send()
                .await?
                .error_for_status()?
                .json()
                .await?;
            println!("{}", usage.function);
            println!(
                "  invocations: {} ({} ok, {} failed)",
                usage.invocations, usage.successes, usage.failures
            );
            println!("  duration:    {} ms total", usage.duration_ms_total);
            println!(
                "  bytes:       {} in / {} out",
                usage.bytes_in_total, usage.bytes_out_total
            );
        }
        FunctionCommand::Trigger(args) => run_trigger(args, config).await?,
        FunctionCommand::Init { name, lang, dir } => init_project(&name, &lang, dir)?,
        FunctionCommand::Build { dir } => build_project(dir).await?,
        #[cfg(feature = "handlers")]
        FunctionCommand::Test {
            component,
            path,
            method,
            data,
            content_type,
            expect_status,
            expect_body,
        } => {
            harness::test_component(
                component,
                &path,
                &method,
                data,
                content_type,
                expect_status,
                expect_body,
            )
            .await?;
        }
        #[cfg(feature = "handlers")]
        FunctionCommand::Dev { component, port } => harness::dev_serve(component, port).await?,
    }
    Ok(())
}

/// Run the `function trigger` subcommand.
async fn run_trigger(args: TriggerArgs, config: &ProjectConfig) -> Result<()> {
    let seg = client::project_seg(&client::resolve_project(config), "functions");
    match args.command {
        TriggerCommand::Add {
            name,
            id,
            cron,
            queue,
            blob,
            server,
        } => {
            let (server, http) = client::connect(server, config)?;
            let kind = match (cron, queue, blob) {
                (Some(schedule), None, None) => {
                    serde_json::json!({ "type": "cron", "schedule": schedule })
                }
                (None, Some(topic), None) => {
                    serde_json::json!({ "type": "queue", "topic": topic })
                }
                (None, None, Some(prefix)) => {
                    serde_json::json!({ "type": "blob", "prefix": prefix })
                }
                _ => return Err(FunctionError::BadTrigger),
            };
            http.put(format!("{server}/api/{seg}/{name}/triggers/{id}"))
                .json(&kind)
                .send()
                .await?
                .error_for_status()?;
            println!("added trigger {name}/{id}");
        }
        TriggerCommand::Ls { name, server } => {
            let (server, http) = client::connect(server, config)?;
            let list: Vec<TriggerView> = http
                .get(format!("{server}/api/{seg}/{name}/triggers"))
                .send()
                .await?
                .error_for_status()?
                .json()
                .await?;
            if list.is_empty() {
                println!("no triggers");
                return Ok(());
            }
            for t in list {
                let kind = t.kind.get("type").and_then(|v| v.as_str()).unwrap_or("?");
                println!("{}  [{}]", t.id, kind);
            }
        }
        TriggerCommand::Rm { name, id, server } => {
            let (server, http) = client::connect(server, config)?;
            http.delete(format!("{server}/api/{seg}/{name}/triggers/{id}"))
                .send()
                .await?
                .error_for_status()?;
            println!("removed trigger {name}/{id}");
        }
    }
    Ok(())
}

/// Read the invoke request body: `--data` inline, `--data-file <path>` (`-` =
/// stdin), or empty when neither is given.
async fn read_invoke_body(
    data: Option<String>,
    data_file: Option<std::path::PathBuf>,
) -> Result<Vec<u8>> {
    if let Some(inline) = data {
        return Ok(inline.into_bytes());
    }
    let Some(path) = data_file else {
        return Ok(Vec::new());
    };
    if path.as_os_str() == "-" {
        use tokio::io::AsyncReadExt;
        let mut buf = Vec::new();
        tokio::io::stdin().read_to_end(&mut buf).await?;
        Ok(buf)
    } else {
        Ok(tokio::fs::read(&path).await?)
    }
}

/// The local single-function harness (FA-7): run a scaffolded component through
/// the engine in-process — `function test` (one request + asserts) and
/// `function dev` (a local HTTP server). Only the no-capability request path is
/// wired (the template's shape); capability-backed local testing is future.
#[cfg(feature = "handlers")]
mod harness {
    use super::{FunctionError, Result};
    use boatramp_handlers::{Bindings, HandlerEngine, Limits};
    use http_body_util::{BodyExt, Full};

    /// The engine's compile-cache key for a locally-run component (one per run).
    const LOCAL_HASH: &str = "function-local";

    /// Run `component` against one request; print the response and assert.
    #[allow(clippy::too_many_arguments)]
    pub(super) async fn test_component(
        component: std::path::PathBuf,
        path: &str,
        method: &str,
        data: Option<String>,
        content_type: Option<String>,
        expect_status: Option<u16>,
        expect_body: Option<String>,
    ) -> Result<()> {
        let wasm = tokio::fs::read(&component).await?;
        let engine = HandlerEngine::new(Limits::default(), 4).map_err(harness_err)?;
        let (status, body) = run_once(
            &engine,
            &wasm,
            method,
            path,
            content_type.as_deref(),
            data.unwrap_or_default().into_bytes(),
        )
        .await?;
        let text = String::from_utf8_lossy(&body);
        println!("HTTP {status}");
        print!("{text}");
        if !text.ends_with('\n') {
            println!();
        }

        let mut ok = true;
        if let Some(exp) = expect_status {
            if status != exp {
                eprintln!("FAIL: expected status {exp}, got {status}");
                ok = false;
            }
        }
        if let Some(sub) = &expect_body {
            if !text.contains(sub.as_str()) {
                eprintln!("FAIL: body does not contain {sub:?}");
                ok = false;
            }
        }
        if ok {
            println!("ok");
            Ok(())
        } else {
            Err(FunctionError::HarnessFailed)
        }
    }

    /// Serve `component` locally on `127.0.0.1:<port>` until interrupted. Each
    /// request runs the component; the response is buffered (fine for local dev).
    pub(super) async fn dev_serve(component: std::path::PathBuf, port: u16) -> Result<()> {
        use hyper::server::conn::http1;
        use hyper::service::service_fn;
        use hyper_util::rt::TokioIo;
        use std::sync::Arc;

        let wasm = Arc::new(tokio::fs::read(&component).await?);
        let engine = Arc::new(HandlerEngine::new(Limits::default(), 16).map_err(harness_err)?);
        let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await?;
        println!(
            "serving {} on http://127.0.0.1:{port}  (Ctrl-C to stop)",
            component.display()
        );

        loop {
            let (stream, _) = listener.accept().await?;
            let io = TokioIo::new(stream);
            let engine = engine.clone();
            let wasm = wasm.clone();
            tokio::spawn(async move {
                let service = service_fn(move |req: http::Request<hyper::body::Incoming>| {
                    let engine = engine.clone();
                    let wasm = wasm.clone();
                    async move {
                        let response = match engine
                            .serve(LOCAL_HASH, &wasm, req, Bindings::new("fn/local"))
                            .await
                        {
                            Ok(resp) => {
                                let (parts, body) = resp.into_parts();
                                let bytes = body
                                    .collect()
                                    .await
                                    .map(http_body_util::Collected::to_bytes)
                                    .unwrap_or_default();
                                http::Response::from_parts(parts, Full::new(bytes))
                            }
                            Err(err) => http::Response::builder()
                                .status(500)
                                .body(Full::new(bytes::Bytes::from(format!(
                                    "function error: {err:?}\n"
                                ))))
                                .unwrap(),
                        };
                        Ok::<_, std::convert::Infallible>(response)
                    }
                });
                let _ = http1::Builder::new().serve_connection(io, service).await;
            });
        }
    }

    /// Run one request through the engine → (status, body bytes).
    async fn run_once(
        engine: &HandlerEngine,
        wasm: &[u8],
        method: &str,
        path: &str,
        content_type: Option<&str>,
        body: Vec<u8>,
    ) -> Result<(u16, Vec<u8>)> {
        let mut builder = http::Request::builder()
            .method(method)
            .uri(format!("http://localhost{path}"));
        if let Some(ct) = content_type {
            builder = builder.header("content-type", ct);
        }
        let request = builder
            .body(Full::new(bytes::Bytes::from(body)))
            .map_err(harness_err)?;
        let response = engine
            .serve(LOCAL_HASH, wasm, request, Bindings::new("fn/local"))
            .await
            .map_err(|e| FunctionError::Harness(format!("{e:?}")))?;
        let status = response.status().as_u16();
        let bytes = response
            .into_body()
            .collect()
            .await
            .map_err(|e| FunctionError::Harness(format!("{e:?}")))?
            .to_bytes();
        Ok((status, bytes.to_vec()))
    }

    fn harness_err<E: std::fmt::Display>(err: E) -> FunctionError {
        FunctionError::Harness(err.to_string())
    }
}

/// Fetch the functions view (all sites, or one with `?site=`).
async fn fetch(
    server: Option<String>,
    site: Option<String>,
    config: &ProjectConfig,
) -> Result<Vec<FunctionSummary>> {
    let server = client::resolve_server(server, config)?;
    let http = client::http_client(client::token(config).as_deref());
    let seg = client::project_seg(&client::resolve_project(config), "functions");
    let url = match &site {
        Some(s) => format!("{server}/api/{seg}?site={s}"),
        None => format!("{server}/api/{seg}"),
    };
    Ok(http
        .get(url)
        .send()
        .await?
        .error_for_status()?
        .json()
        .await?)
}

/// Shorten a version id for display (drop the `sha256:` tag, keep 12 chars).
fn short(id: &str) -> &str {
    let id = id.strip_prefix("sha256:").unwrap_or(id);
    &id[..id.len().min(12)]
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn sanitizes_crate_names() {
        assert_eq!(sanitize_crate_name("My Cool Fn"), "my-cool-fn");
        assert_eq!(sanitize_crate_name("resize_images"), "resize-images");
        assert_eq!(sanitize_crate_name("  --Foo.Bar--  "), "foo-bar");
        assert_eq!(sanitize_crate_name("!!!"), "function");
    }

    #[test]
    fn init_scaffolds_a_buildable_tree() {
        let root = std::env::temp_dir().join(format!("boatramp-init-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        init_project("My Cool Fn", "rust", Some(root.clone())).unwrap();
        let proj = root.join("my-cool-fn");

        // The manifest is written (not the `.tmpl`), with the name substituted.
        let cargo = std::fs::read_to_string(proj.join("Cargo.toml")).unwrap();
        assert!(cargo.contains("name = \"my-cool-fn\""));
        assert!(!cargo.contains("BOATRAMP_FUNCTION_NAME"));
        assert!(!proj.join("Cargo.toml.tmpl").exists());
        // Source + the WIT closure came along, so `cargo build` would have them.
        assert!(proj.join("src/lib.rs").exists());
        assert!(proj.join("wit/handler.wit").exists());

        // Refuses an unknown language and an existing directory.
        assert!(matches!(
            init_project("x", "cobol", Some(root.clone())),
            Err(FunctionError::UnknownLang(_))
        ));
        assert!(matches!(
            init_project("My Cool Fn", "rust", Some(root.clone())),
            Err(FunctionError::AlreadyExists(_))
        ));

        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn init_scaffolds_a_js_tree() {
        let root = std::env::temp_dir().join(format!("boatramp-initjs-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        init_project("My JS Fn", "js", Some(root.clone())).unwrap();
        let proj = root.join("my-js-fn");

        // The manifest is written (not the `.tmpl`), name substituted.
        let pkg = std::fs::read_to_string(proj.join("package.json")).unwrap();
        assert!(pkg.contains("\"name\": \"my-js-fn\""));
        assert!(!pkg.contains("BOATRAMP_FUNCTION_NAME"));
        assert!(!proj.join("package.json.tmpl").exists());
        // Handler source + the WIT closure came along.
        assert!(proj.join("handler.js").exists());
        assert!(proj.join("wit/handler.wit").exists());
        // `javascript` is an accepted alias for `js`.
        assert!(init_project("Other", "javascript", Some(root.clone())).is_ok());

        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn init_scaffolds_a_python_tree() {
        let root = std::env::temp_dir().join(format!("boatramp-initpy-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        init_project("My Py Fn", "python", Some(root.clone())).unwrap();
        let proj = root.join("my-py-fn");

        let pyproject = std::fs::read_to_string(proj.join("pyproject.toml")).unwrap();
        assert!(pyproject.contains("name = \"my-py-fn\""));
        assert!(!pyproject.contains("BOATRAMP_FUNCTION_NAME"));
        assert!(!proj.join("pyproject.toml.tmpl").exists());
        assert!(proj.join("app.py").exists());
        assert!(proj.join("wit/handler.wit").exists());
        // `py` is an accepted alias.
        assert!(init_project("Other", "py", Some(root.clone())).is_ok());
        // An unknown language is still rejected.
        assert!(matches!(
            init_project("x", "ruby", Some(root.clone())),
            Err(FunctionError::UnknownLang(_))
        ));

        let _ = std::fs::remove_dir_all(&root);
    }

    /// The local harness runs a component through the engine: a matching assertion
    /// passes, a wrong one fails. Uses a prebuilt fixture (no `cargo build`), so
    /// it is fast; needs `--features handlers` (the engine).
    #[cfg(feature = "handlers")]
    #[tokio::test]
    async fn harness_runs_a_component_and_asserts() {
        const HTTP_200: &[u8] =
            include_bytes!("../../boatramp-handlers/tests/fixtures/http-200.wasm");
        let tmp =
            std::env::temp_dir().join(format!("boatramp-harness-{}.wasm", std::process::id()));
        std::fs::write(&tmp, HTTP_200).unwrap();

        // A matching status + body assertion passes.
        harness::test_component(
            tmp.clone(),
            "/",
            "GET",
            None,
            None,
            Some(200),
            Some("hello from boatramp".into()),
        )
        .await
        .unwrap();

        // A wrong status assertion fails.
        assert!(matches!(
            harness::test_component(tmp.clone(), "/", "GET", None, None, Some(404), None).await,
            Err(FunctionError::HarnessFailed)
        ));

        let _ = std::fs::remove_file(&tmp);
    }

    /// The scaffolded Rust template compiles to a real `wasi:http` component.
    /// `#[ignore]`d because it invokes `cargo build --target wasm32-wasip2` (slow +
    /// needs the wasm toolchain); run with `--ignored`, and wired into the flake
    /// check. Validates FA-7's init → build round-trip end to end.
    #[tokio::test]
    #[ignore = "compiles a wasm component; run with --ignored / in the flake check"]
    async fn init_then_build_produces_a_component() {
        let root = std::env::temp_dir().join(format!("boatramp-roundtrip-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        init_project("roundtrip demo", "rust", Some(root.clone())).unwrap();
        let proj = root.join("roundtrip-demo");
        build_project(Some(proj.clone())).await.unwrap();
        let wasm = proj.join("target/wasm32-wasip2/release/roundtrip_demo.wasm");
        assert!(wasm.exists(), "expected a built component at {wasm:?}");
        // A component starts with the wasm preamble + the component-model layer.
        let bytes = std::fs::read(&wasm).unwrap();
        assert_eq!(&bytes[..4], b"\0asm");
        let _ = std::fs::remove_dir_all(&root);
    }

    /// The scaffolded JS template compiles to a component via `jco componentize`.
    /// `#[ignore]`d because it fetches `jco` through `npx` (network) and runs
    /// StarlingMonkey (slow). Run with `--ignored` / `just function-roundtrip`.
    #[tokio::test]
    #[ignore = "runs jco via npx (network + slow); run with --ignored / in the flake check"]
    async fn init_then_build_js_produces_a_component() {
        let root =
            std::env::temp_dir().join(format!("boatramp-jsroundtrip-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        init_project("js roundtrip", "js", Some(root.clone())).unwrap();
        let proj = root.join("js-roundtrip");
        build_project(Some(proj.clone())).await.unwrap();
        let wasm = proj.join("js-roundtrip.wasm");
        assert!(wasm.exists(), "expected a built component at {wasm:?}");
        let bytes = std::fs::read(&wasm).unwrap();
        assert_eq!(&bytes[..4], b"\0asm");
        let _ = std::fs::remove_dir_all(&root);
    }

    /// The scaffolded Python template compiles to a component via `componentize-py`
    /// (run through `uvx`). `#[ignore]`d — fetches `componentize-py` (network) and
    /// runs CPython (slow). Run with `--ignored` / `just function-roundtrip-py`
    /// (needs `uv` from `nix develop`).
    #[tokio::test]
    #[ignore = "runs componentize-py via uvx (network + slow); run with --ignored"]
    async fn init_then_build_python_produces_a_component() {
        let root =
            std::env::temp_dir().join(format!("boatramp-pyroundtrip-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        init_project("py roundtrip", "python", Some(root.clone())).unwrap();
        let proj = root.join("py-roundtrip");
        build_project(Some(proj.clone())).await.unwrap();
        let wasm = proj.join("py-roundtrip.wasm");
        assert!(wasm.exists(), "expected a built component at {wasm:?}");
        let bytes = std::fs::read(&wasm).unwrap();
        assert_eq!(&bytes[..4], b"\0asm");
        let _ = std::fs::remove_dir_all(&root);
    }
}