table-editor 0.3.0

A local HTTP server and browser bundle for editing a repository's JSONL tables
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
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
//! The server a repository's binary builds and runs.

use std::net::{Ipv4Addr, SocketAddr};
use std::thread;
use std::time::Duration;

use anyhow::{Result, anyhow};
use clap::{Args, Subcommand};
use tiny_http::Server as HttpServer;

use crate::context::Context;
use crate::launch::{self, Occupant};
use crate::routes;
use crate::table::{App, Front};

/// The bundle served when the repository does not supply its own.
///
/// The build script puts it here, from `assets/index.html` where that has been
/// built and from `assets/placeholder.html` where it has not, so that the crate
/// compiles in a checkout that has never run bun.
const DEFAULT_INDEX_HTML: &str = include_str!(concat!(env!("OUT_DIR"), "/index.html"));

/// Which of the two the build script found: `built` or `placeholder`. Only the
/// crate's own test reads it; what a consumer is served is the page itself, and
/// the placeholder says what it is.
#[cfg(test)]
const BUNDLE_KIND: &str = env!("TABLE_EDITOR_BUNDLE");

/// The marker set on the detached worker process so it serves rather than
/// re-spawning itself.
const DEFAULT_CHILD_ENV: &str = "TABLE_EDITOR_CHILD";

/// The subcommand that reaches [`Server::run`], used to re-invoke the binary as
/// a detached worker.
const DEFAULT_COMMAND: &str = "web";

/// The port bound when neither the repository nor the command line names one.
const DEFAULT_PORT: u16 = 8787;

/// The arguments the editor's subcommand takes. A repository whose subcommand
/// takes arguments of its own flattens this into its own `Args` struct.
#[derive(Debug, Args)]
#[command(args_conflicts_with_subcommands = true)]
pub struct ServerArgs {
    /// Subcommand. Omit to launch (or reuse) the server, the default.
    #[command(subcommand)]
    pub command: Option<ServerCommand>,

    /// Table or view to open by name. Defaults to the app's front page.
    pub table: Option<String>,

    /// Port to bind on 127.0.0.1. Defaults to the app's own port, so two
    /// editors on one machine do not collide.
    #[arg(long, global = true)]
    pub port: Option<u16>,

    /// Do not open a browser; just run the server.
    #[arg(long)]
    pub no_open: bool,

    /// Shut down any server already running on the port and start a fresh one
    /// (e.g. to pick up a newly built binary). Without this, an existing server
    /// for this app is reused.
    #[arg(long)]
    pub restart: bool,

    /// Development mode: serve only `/api` in the foreground (no embedded UI,
    /// no browser). Vite serves the UI and proxies `/api` here.
    #[arg(long)]
    pub api_only: bool,
}

impl ServerArgs {
    /// Put the consuming app's own defaults into the help for `table` and
    /// `--port`.
    ///
    /// The two arguments default to something only the [`Server`] knows: the
    /// app's front page and the port it was built with. Help, though, is
    /// rendered by clap before `run` is ever reached, so the text has to be
    /// rewritten on the way in. Build the command, hand it here, and parse
    /// from what comes back:
    ///
    /// ```no_run
    /// # use clap::{CommandFactory, FromArgMatches, Parser, Subcommand};
    /// # use table_editor::ServerArgs;
    /// # #[derive(Parser)]
    /// # struct Cli {
    /// #     #[command(subcommand)]
    /// #     command: Command,
    /// # }
    /// # #[derive(Subcommand)]
    /// # enum Command {
    /// #     Web(ServerArgs),
    /// # }
    /// let command = ServerArgs::augment_help(Cli::command(), "books", 8788);
    /// let cli = Cli::from_arg_matches(&command.get_matches())?;
    /// # Ok::<(), clap::Error>(())
    /// ```
    ///
    /// Where the arguments sit does not matter: the whole command tree is
    /// walked. A command is rewritten only where it holds both `table` and
    /// `port` and both still carry this crate's own help, which is what
    /// flattening [`ServerArgs`] leaves behind. A repository's own `--port`
    /// on some other subcommand keeps its own wording, and so does one whose
    /// help the repository has already rewritten. Nothing but the help
    /// changes.
    pub fn augment_help(
        command: clap::Command,
        default_page: &str,
        default_port: u16,
    ) -> clap::Command {
        let table = format!("Table or view to open by name. Defaults to {default_page}.");
        let port = format!("Port to bind on 127.0.0.1. Defaults to {default_port}.");
        rewrite_help(command, &table, &port)
    }
}

/// The help clap derives for this crate's own `table` and `port`, which is how
/// an argument flattened from [`ServerArgs`] is told from a repository's own.
fn crate_help() -> (String, String) {
    let reference = ServerArgs::augment_args(clap::Command::new("table-editor"));
    let of = |id: &str| {
        reference
            .get_arguments()
            .find(|arg| arg.get_id() == id)
            .and_then(|arg| arg.get_help())
            .map(ToString::to_string)
            .unwrap_or_default()
    };
    (of("table"), of("port"))
}

/// Rewrite the help of `table` and `--port` on every command in the tree that
/// holds both of them with this crate's own wording.
fn rewrite_help(command: clap::Command, table: &str, port: &str) -> clap::Command {
    let (crate_table, crate_port) = crate_help();

    let subcommands: Vec<String> = command
        .get_subcommands()
        .map(|sub| sub.get_name().to_string())
        .collect();

    let help_of = |command: &clap::Command, id: &str| -> Option<String> {
        command
            .get_arguments()
            .find(|arg| arg.get_id() == id)
            .and_then(|arg| arg.get_help())
            .map(ToString::to_string)
    };

    let mut command = command;
    let ours = help_of(&command, "table").as_deref() == Some(crate_table.as_str())
        && help_of(&command, "port").as_deref() == Some(crate_port.as_str());
    if ours {
        let (table, port) = (table.to_string(), port.to_string());
        command = command
            .mut_arg("table", |arg| arg.help(table))
            .mut_arg("port", |arg| arg.help(port));
    }

    for name in subcommands {
        command = command.mut_subcommand(name, |sub| rewrite_help(sub, table, port));
    }
    command
}

/// The first character of `name` that may not appear in a path segment, or
/// nothing where every character may.
///
/// A name is compared against a segment of the address, so it has to survive
/// the journey there and back unchanged. The unreserved set from RFC 3986 is
/// what does: anything else either means something to a URL or arrives
/// escaped and no longer matches what the app called it.
fn reserved_url_character(name: &str) -> Option<char> {
    name.chars()
        .find(|c| !(c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '~')))
}

/// The parameter keys a view may not use, because the address already means
/// something by them.
const RESERVED_PARAM_KEYS: [&str; 2] = ["view", "table"];

/// Whether a name is one file inside `Data/` rather than a path out of it.
fn is_bare_file_name(file: &str) -> bool {
    !file.is_empty()
        && file != "."
        && file != ".."
        && !file.contains(['/', '\\'])
        && !std::path::Path::new(file).is_absolute()
}

#[derive(Debug, Subcommand)]
pub enum ServerCommand {
    /// Stop a server left running on the port (e.g. a stale detached one).
    /// Idempotent: a no-op when nothing is listening.
    Stop,
}

/// The editor's HTTP server, configured for one repository.
pub struct Server {
    app: Box<dyn App>,
    index_html: &'static str,
    child_env: &'static str,
    command: &'static str,
    default_port: u16,
    worker_args: Vec<String>,
    before_launch: Option<Box<dyn Fn() + Send>>,
}

impl Server {
    /// Build a server for an app.
    ///
    /// Panics when a table takes one of the reserved names, because such a
    /// table is unreachable: the control endpoints and the `stop` subcommand
    /// are matched first. Panics, too, when a table's file is not a bare name,
    /// since every file is resolved against the one `Data/` directory. Panics
    /// when a table's rows link to a view the app does not serve, or with a
    /// parameter that view does not declare.
    pub fn new(app: impl App) -> Self {
        let app: Box<dyn App> = Box::new(app);
        for table in app.tables() {
            assert!(
                !routes::RESERVED_NAMES.contains(&table.route()),
                "table \"{}\" uses a reserved name; the editor reserves {}",
                table.route(),
                routes::RESERVED_NAMES.join(", ")
            );
            assert!(
                is_bare_file_name(table.data_file()),
                "table \"{}\" names the file \"{}\"; a table's file is a bare name inside Data/",
                table.route(),
                table.data_file()
            );
        }

        for table in app.tables() {
            if let Some(bad) = reserved_url_character(table.route()) {
                panic!(
                    "table \"{}\" has {bad:?} in its name; a name is part of an address, so it \
                     takes letters, digits, and - _ . ~ only",
                    table.route()
                );
            }
        }

        let tables: Vec<&'static str> = app.tables().iter().map(|t| t.route()).collect();
        let mut seen: Vec<&'static str> = Vec::new();
        for view in app.views() {
            let name = view.route();
            assert!(
                !routes::RESERVED_NAMES.contains(&name),
                "view \"{name}\" uses a reserved name; the editor reserves {}",
                routes::RESERVED_NAMES.join(", ")
            );
            if let Some(bad) = reserved_url_character(name) {
                panic!(
                    "view \"{name}\" has {bad:?} in its name; a name is part of an address, so \
                     it takes letters, digits, and - _ . ~ only"
                );
            }
            // A view and a table are told apart by the address that asks for
            // them, so two of one name would make `?view=` and `?table=` name
            // different things under one word.
            assert!(
                !tables.contains(&name),
                "view \"{name}\" has the same name as a table; each name belongs to one of them"
            );
            assert!(
                !seen.contains(&name),
                "two views are named \"{name}\"; each view takes a name of its own"
            );
            seen.push(name);

            // A parameter keyed `view` or `table` would be asking the address
            // a question it already answers. The keys a view declares do not
            // depend on the data behind them, so a context rooted anywhere
            // serves to ask what they are; a view that cannot answer without
            // its files goes unchecked rather than refusing to build.
            let ctx = Context::new(".");
            for key in view.param_keys(&ctx).unwrap_or_default() {
                assert!(
                    !RESERVED_PARAM_KEYS.contains(&key.as_str()),
                    "view \"{name}\" has a parameter keyed \"{key}\"; the address uses that word \
                     to say which page it is on"
                );
            }
        }

        // A row's link is an address into a view, built by the page from the
        // row. One naming a view this app does not serve, or a parameter that
        // view does not declare, would be a link on every row to a page that
        // does not answer it. The keys are asked for the way the check on
        // reserved keys asks, and a view that cannot say without its files
        // has its parameters left unchecked.
        for table in app.tables() {
            let Some(link) = table.row_link() else {
                continue;
            };
            let Some(view) = app.view(link.view()) else {
                panic!(
                    "table \"{}\" links its rows to the view \"{}\", which this app does not serve",
                    table.route(),
                    link.view()
                );
            };
            if let Ok(keys) = view.param_keys(&Context::new(".")) {
                for (param, _) in link.args() {
                    assert!(
                        keys.iter().any(|key| key == param),
                        "table \"{}\" links its rows to the view \"{}\" with the parameter \
                         \"{param}\", which that view does not declare",
                        table.route(),
                        link.view()
                    );
                }
            }
        }

        match app.front() {
            Front::FirstTable => {}
            Front::Table(name) => assert!(
                tables.contains(&name),
                "the front page names the table \"{name}\", which this app does not serve"
            ),
            Front::View(name) => assert!(
                seen.contains(&name),
                "the front page names the view \"{name}\", which this app does not serve"
            ),
        }

        Self {
            app,
            index_html: DEFAULT_INDEX_HTML,
            child_env: DEFAULT_CHILD_ENV,
            command: DEFAULT_COMMAND,
            default_port: DEFAULT_PORT,
            worker_args: Vec::new(),
            before_launch: None,
        }
    }

    /// Serve a bundle of the repository's own in place of the embedded one.
    pub fn index_html(mut self, html: &'static str) -> Self {
        self.index_html = html;
        self
    }

    /// The environment variable marking the detached worker process. A
    /// repository whose server is registered as a system service keeps its own
    /// name here, so the service entry does not have to change.
    pub fn child_env(mut self, var: &'static str) -> Self {
        self.child_env = var;
        self
    }

    /// The subcommand that reaches [`Server::run`], used when re-invoking the
    /// binary as a detached worker.
    pub fn command(mut self, command: &'static str) -> Self {
        self.command = command;
        self
    }

    /// The port to bind when the command line names none. Each app on a
    /// machine takes its own, so one editor never lands on another's port.
    pub fn default_port(mut self, port: u16) -> Self {
        self.default_port = port;
        self
    }

    /// Arguments to pass on to the detached worker, after the table and the
    /// port.
    ///
    /// The worker is a fresh invocation of this binary, and it is given only
    /// the table and the port, so a flag the user passed the parent does not
    /// reach it. A repository whose subcommand takes a flag the serving
    /// process needs—one naming a companion service, say—forwards it here.
    /// The worker inherits the environment either way, so a setting that
    /// already lives in a variable needs no forwarding.
    ///
    /// What is forwarded lands on the worker's command line, so each argument
    /// has to be one the editor's subcommand declares. It must be a flag and
    /// not a positional, because the table is the only positional that command
    /// line has—a forwarded positional is refused outright—and it must not
    /// repeat `--port` or the table, which are passed already. An argument
    /// that breaks these rules leaves the worker unable to parse its own
    /// command line, and the launch then fails with what the worker said.
    pub fn worker_args(mut self, args: impl IntoIterator<Item = String>) -> Self {
        self.worker_args = args.into_iter().collect();
        self
    }

    /// Work to do once, in the process the user invoked, before a server is
    /// started or reused: bringing up a companion service, say. It does not run
    /// in the detached worker.
    pub fn before_launch(mut self, f: impl Fn() + Send + 'static) -> Self {
        self.before_launch = Some(Box::new(f));
        self
    }

    pub fn run(self, args: ServerArgs) -> Result<()> {
        let port = self.port(&args);
        let app = self.app.name();

        if let Some(ServerCommand::Stop) = args.command {
            return launch::stop(port, app);
        }

        // The detached worker carries the marker; it binds and serves. Handle
        // it before `before_launch` so only the user-invoked parent runs that.
        if std::env::var_os(self.child_env).is_some() {
            return self.serve(port, args.api_only);
        }

        if let Some(f) = &self.before_launch {
            f();
        }

        // Dev mode serves the API in the foreground so logs and Ctrl-C work;
        // Vite owns the UI and proxies `/api` here.
        if args.api_only {
            return self.serve(port, args.api_only);
        }

        // What a repository forwards to the worker is settled here, before a
        // single packet goes anywhere: an argument that could never work is
        // that, whatever else happens to be on the port.
        launch::check_worker_args(&self.worker_args)?;

        let url = self.url(&args, port);
        let occupant = launch::occupant(port);

        if args.restart && launch::replaceable(&occupant, app) {
            // A server that names no app is replaced but never adopted, so an
            // upgrade can take its port back.
            if occupant == Occupant::Unnamed {
                println!("{app}: replacing a server on port {port} that does not name its app");
            }
            launch::request_shutdown(port);
            launch::wait_until_down(port)?;
        } else if launch::serves(&occupant, app) {
            self.open_if_wanted(&args, &url);
            println!("{app}: re-using server at {url}");
            return Ok(());
        } else if occupant != Occupant::Vacant {
            let doing = if args.restart {
                "not replacing it"
            } else {
                "not starting a second one"
            };
            return Err(launch::occupied(port, &occupant, app, doing));
        }

        // Launch a detached copy of ourselves and wait until it is serving, so
        // the parent can return (this supports binding the command to a
        // double-click shortcut) and the browser never races an unbound port.
        let mut worker = launch::spawn_detached(
            self.command,
            self.child_env,
            args.table.as_deref(),
            port,
            &self.worker_args,
        )?;
        launch::wait_until_up(port, app, &mut worker)?;
        self.open_if_wanted(&args, &url);
        println!("{app}: serving at {url}");
        Ok(())
    }

    /// The port to use: the one named on the command line, or the app's own.
    fn port(&self, args: &ServerArgs) -> u16 {
        args.port.unwrap_or(self.default_port)
    }

    /// Bind the port and serve until the process is shut down (by a signal or
    /// by `POST /api/shutdown`).
    fn serve(&self, port: u16, api_only: bool) -> Result<()> {
        let addr = SocketAddr::from((Ipv4Addr::LOCALHOST, port));
        let server = bind_with_retry(addr)?;

        for request in server.incoming_requests() {
            if let Err(e) = routes::handle(request, self.app.as_ref(), self.index_html, api_only) {
                eprintln!("request error: {e}");
            }
        }
        Ok(())
    }

    /// Where to point the browser.
    ///
    /// A name on the command line opens that page, whether the app serves it
    /// as a table or as a view. With no name, an app that declares a front
    /// page is opened bare, so that page decides; an app that declares none is
    /// opened on its first table by name, because a repository serving a
    /// bundle of its own may read `?table=` and know nothing of front pages.
    fn url(&self, args: &ServerArgs, port: u16) -> String {
        let base = format!("http://127.0.0.1:{port}/");
        match args.table.as_deref() {
            Some(name) if self.app.view(name).is_some() => format!("{base}?view={name}"),
            Some(name) => format!("{base}?table={name}"),
            None => match self.app.front() {
                Front::FirstTable => match self.app.tables().first() {
                    Some(table) => format!("{base}?table={}", table.route()),
                    None => base,
                },
                _ => base,
            },
        }
    }

    fn open_if_wanted(&self, args: &ServerArgs, url: &str) {
        if args.no_open {
            return;
        }
        if let Err(e) = launch::open_browser(url) {
            eprintln!("could not open browser: {e}");
        }
    }
}

/// Bind, retrying briefly: after a `--restart` the previous server's socket can
/// linger for a moment before the OS frees the port.
fn bind_with_retry(addr: SocketAddr) -> Result<HttpServer> {
    let mut last_err = None;
    for _ in 0..20 {
        match HttpServer::http(addr) {
            Ok(server) => return Ok(server),
            Err(e) => {
                last_err = Some(e.to_string());
                thread::sleep(Duration::from_millis(100));
            }
        }
    }
    Err(anyhow!(
        "could not bind {}: {}",
        addr,
        last_err.unwrap_or_else(|| "unknown error".to_string())
    ))
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};

    use clap::{CommandFactory, Parser};

    use super::*;
    use crate::context::Context;
    use crate::error::ApiError;
    use crate::error::ValidationError;
    use crate::fixture::{Clashing, Library, Straying};
    use crate::schema::{Column, RowLink, Schema};
    use crate::table::TableLogic;
    use crate::table::{App, Table};
    use crate::view::{Param, View, ViewArgs, ViewData, ViewLogic};

    /// A binary that takes the editor's arguments unchanged.
    #[derive(Parser)]
    #[command(name = "library")]
    struct Cli {
        #[command(subcommand)]
        command: Command,
    }

    #[derive(Subcommand)]
    enum Command {
        Web(ServerArgs),
    }

    /// A binary that adds arguments of its own, the way a repository with a
    /// companion service does.
    #[derive(Parser)]
    #[command(name = "archive")]
    struct HostCli {
        #[command(subcommand)]
        command: HostCommand,
    }

    #[derive(Subcommand)]
    enum HostCommand {
        Web(WebArgs),
        /// A companion service of the repository's own, with a port of its own.
        ServeSpeech(SpeechArgs),
    }

    #[derive(Args)]
    struct WebArgs {
        #[command(flatten)]
        server: ServerArgs,

        #[arg(long)]
        no_service: bool,
    }

    #[derive(Args)]
    struct SpeechArgs {
        /// Port the speech service listens on. Defaults to 8765.
        #[arg(long)]
        port: Option<u16>,
    }

    fn parse(argv: &[&str]) -> ServerArgs {
        match Cli::parse_from(argv).command {
            Command::Web(args) => args,
        }
    }

    /// An app of one table and whatever views a test hands it.
    struct WithViews(Vec<&'static dyn View>);

    impl App for WithViews {
        fn name(&self) -> &str {
            "WithViews"
        }
        fn tables(&self) -> Vec<&dyn Table> {
            vec![&crate::fixture::Books]
        }
        fn views(&self) -> Vec<&dyn View> {
            self.0.clone()
        }
    }

    fn host_web(argv: &[&str]) -> WebArgs {
        match HostCli::parse_from(argv).command {
            HostCommand::Web(args) => args,
            HostCommand::ServeSpeech(_) => panic!("the web subcommand"),
        }
    }

    fn help_of(command: &mut clap::Command, subcommand: &str) -> String {
        command
            .find_subcommand_mut(subcommand)
            .unwrap_or_else(|| panic!("the {subcommand} subcommand"))
            .render_help()
            .to_string()
    }

    #[test]
    fn table_and_port_are_unset_when_unstated() {
        let args = parse(&["library", "web"]);
        assert!(args.table.is_none());
        assert!(args.port.is_none());
        assert!(!args.no_open);
    }

    #[test]
    fn a_named_table_and_flags_parse() {
        let args = parse(&["library", "web", "books", "--no-open", "--port", "9000"]);
        assert_eq!(args.table.as_deref(), Some("books"));
        assert_eq!(args.port, Some(9000));
        assert!(args.no_open);
    }

    #[test]
    fn stop_takes_the_port_as_a_global() {
        let args = parse(&["library", "web", "stop", "--port", "9000"]);
        assert!(matches!(args.command, Some(ServerCommand::Stop)));
        assert_eq!(args.port, Some(9000));
    }

    #[test]
    fn flattening_keeps_both_halves_of_the_arguments() {
        let args = host_web(&["archive", "web", "books", "--no-service", "--port", "9000"]);
        assert!(args.no_service);
        assert_eq!(args.server.table.as_deref(), Some("books"));
        assert_eq!(args.server.port, Some(9000));
    }

    #[test]
    fn flattening_keeps_the_stop_subcommand() {
        let args = host_web(&["archive", "web", "stop", "--port", "9000"]);
        assert!(matches!(args.server.command, Some(ServerCommand::Stop)));
        assert_eq!(args.server.port, Some(9000));
    }

    #[test]
    fn an_unstated_port_falls_back_to_the_apps_own() {
        let server = Server::new(Library::new()).default_port(8788);
        assert_eq!(server.port(&parse(&["library", "web"])), 8788);
        assert_eq!(
            server.port(&parse(&["library", "web", "--port", "9000"])),
            9000
        );
    }

    #[test]
    fn the_default_port_is_8787_until_an_app_names_its_own() {
        let server = Server::new(Library::new());
        assert_eq!(server.port(&parse(&["library", "web"])), 8787);
    }

    #[test]
    fn url_opens_the_first_table_when_the_app_declares_no_front_page() {
        // Named rather than left bare, because a repository serving a bundle
        // of its own may read `?table=` and know nothing of front pages.
        struct Plainly(crate::fixture::Books);
        impl App for Plainly {
            fn name(&self) -> &str {
                "Plainly"
            }
            fn tables(&self) -> Vec<&dyn Table> {
                vec![&self.0]
            }
        }

        let server = Server::new(Plainly(crate::fixture::Books));
        let args = parse(&["library", "web"]);
        assert_eq!(
            server.url(&args, server.port(&args)),
            "http://127.0.0.1:8787/?table=books"
        );
    }

    #[test]
    fn url_names_the_table_and_port() {
        let server = Server::new(Library::new());
        let args = parse(&["library", "web", "genres", "--port", "8788"]);
        assert_eq!(
            server.url(&args, server.port(&args)),
            "http://127.0.0.1:8788/?table=genres"
        );
    }

    #[test]
    fn url_names_nothing_when_nothing_was_named() {
        // The app's front page decides what a bare address opens, and the
        // browser resolves it, so the launcher does not have to know.
        let server = Server::new(Library::new());
        let args = parse(&["library", "web"]);
        assert_eq!(
            server.url(&args, server.port(&args)),
            "http://127.0.0.1:8787/"
        );
    }

    #[test]
    fn url_names_a_view_the_app_serves_as_a_view() {
        let server = Server::new(Library::new());
        let args = parse(&["library", "web", "on-loan"]);
        assert_eq!(
            server.url(&args, server.port(&args)),
            "http://127.0.0.1:8787/?view=on-loan"
        );
    }

    #[test]
    fn builders_override_the_defaults() {
        let server = Server::new(Library::new())
            .index_html("<!doctype html><title>Library</title>")
            .child_env("LIBRARY_WEB_CHILD")
            .command("edit")
            .default_port(8790)
            .worker_args(["--no-service".to_string()]);
        assert_eq!(server.index_html, "<!doctype html><title>Library</title>");
        assert_eq!(server.child_env, "LIBRARY_WEB_CHILD");
        assert_eq!(server.command, "edit");
        assert_eq!(server.default_port, 8790);
        assert_eq!(server.worker_args, ["--no-service"]);
    }

    #[test]
    fn the_worker_is_started_with_what_the_app_forwards() {
        let server = Server::new(Library::new())
            .command("edit")
            .worker_args(["--no-service".to_string()]);
        assert_eq!(
            launch::worker_argv(server.command, Some("books"), 8790, &server.worker_args).unwrap(),
            ["edit", "books", "--port", "8790", "--no-service"]
        );
    }

    #[test]
    fn help_states_the_apps_own_defaults() {
        let mut command = ServerArgs::augment_help(Cli::command(), "books", 8788);
        let help = help_of(&mut command, "web");

        assert!(help.contains("Defaults to books."), "{help}");
        assert!(help.contains("Defaults to 8788."), "{help}");
    }

    #[test]
    fn help_reaches_arguments_a_repository_has_flattened_into_its_own() {
        let mut command = ServerArgs::augment_help(HostCli::command(), "books", 8788);
        let help = help_of(&mut command, "web");

        assert!(help.contains("Defaults to books."), "{help}");
        assert!(help.contains("Defaults to 8788."), "{help}");
        // The repository's own arguments are left as they were.
        assert!(help.contains("--no-service"), "{help}");
    }

    #[test]
    fn a_repositorys_own_port_keeps_its_own_help() {
        let mut command = ServerArgs::augment_help(HostCli::command(), "books", 8788);
        let help = help_of(&mut command, "serve-speech");

        // Clap drops the full stop a doc comment ends in; the point is that
        // this is still the repository's own sentence.
        assert!(
            help.contains("Port the speech service listens on"),
            "{help}"
        );
        assert!(help.contains("Defaults to 8765"), "{help}");
        assert!(!help.contains("Defaults to 8788"), "{help}");
        assert!(!help.contains("127.0.0.1"), "{help}");
    }

    #[test]
    fn help_a_repository_has_already_written_is_left_alone() {
        let command = Cli::command().mut_subcommand("web", |web| {
            web.mut_arg("port", |arg| arg.help("Port for the editor. Ask Ada."))
        });
        let mut command = ServerArgs::augment_help(command, "books", 8788);
        let help = help_of(&mut command, "web");

        assert!(help.contains("Ask Ada."), "{help}");
        assert!(!help.contains("Defaults to 8788."), "{help}");
        // Both arguments are judged together, so the table is left as it was.
        assert!(!help.contains("Defaults to books."), "{help}");
    }

    #[test]
    fn a_command_without_the_editors_arguments_is_left_alone() {
        let command = ServerArgs::augment_help(clap::Command::new("bare"), "books", 8788);
        assert_eq!(command.get_name(), "bare");
        assert_eq!(command.get_arguments().count(), 0);
    }

    #[test]
    fn a_worker_argument_that_cannot_work_is_refused_whatever_is_on_the_port() {
        // Something else is listening, so a launch that probed the port first
        // would complain about the port. The argument is the complaint,
        // because it is settled before anything is asked of the network.
        let listener = std::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
        let port = listener.local_addr().unwrap().port().to_string();

        let failure = Server::new(Library::new())
            .worker_args(["books".to_string()])
            .run(parse(&["library", "web", "--no-open", "--port", &port]))
            .expect_err("a positional cannot be forwarded to the worker");

        assert!(failure.to_string().contains("not a flag"), "{failure}");
    }

    #[test]
    #[should_panic(expected = "reserved name")]
    fn a_table_may_not_take_a_reserved_name() {
        let _ = Server::new(Clashing::new());
    }

    #[test]
    #[should_panic(expected = "reserved name")]
    fn a_view_may_not_take_a_reserved_name() {
        struct Reserved;
        impl ViewLogic for Reserved {
            fn name(&self) -> &'static str {
                "health"
            }
            fn title(&self) -> &'static str {
                "Health"
            }
            fn render(&self, _args: &ViewArgs, _ctx: &Context) -> Result<ViewData, ApiError> {
                Ok(ViewData::new())
            }
        }
        let _ = Server::new(WithViews(vec![&Reserved]));
    }

    #[test]
    #[should_panic(expected = "same name as a table")]
    fn a_view_may_not_take_a_tables_name() {
        struct Books;
        impl ViewLogic for Books {
            fn name(&self) -> &'static str {
                "books"
            }
            fn title(&self) -> &'static str {
                "Books"
            }
            fn render(&self, _args: &ViewArgs, _ctx: &Context) -> Result<ViewData, ApiError> {
                Ok(ViewData::new())
            }
        }
        let _ = Server::new(WithViews(vec![&Books]));
    }

    #[test]
    #[should_panic(expected = "two views are named")]
    fn two_views_may_not_share_a_name() {
        let _ = Server::new(WithViews(vec![
            &crate::fixture::Shelf,
            &crate::fixture::Shelf,
        ]));
    }

    #[test]
    #[should_panic(expected = "front page names the view")]
    fn the_front_page_may_not_name_a_view_the_app_does_not_serve() {
        struct Missing;
        impl App for Missing {
            fn name(&self) -> &str {
                "Missing"
            }
            fn tables(&self) -> Vec<&dyn Table> {
                vec![&crate::fixture::Books]
            }
            fn front(&self) -> Front {
                Front::View("nowhere")
            }
        }
        let _ = Server::new(Missing);
    }

    #[test]
    #[should_panic(expected = "front page names the table")]
    fn the_front_page_may_not_name_a_table_the_app_does_not_serve() {
        struct Missing;
        impl App for Missing {
            fn name(&self) -> &str {
                "Missing"
            }
            fn tables(&self) -> Vec<&dyn Table> {
                vec![&crate::fixture::Books]
            }
            fn front(&self) -> Front {
                Front::Table("nowhere")
            }
        }
        let _ = Server::new(Missing);
    }

    #[test]
    #[should_panic(expected = "the address uses that word to say which page it is on")]
    fn a_parameter_may_not_be_keyed_for_the_address_itself() {
        struct Hijack;
        impl ViewLogic for Hijack {
            fn name(&self) -> &'static str {
                "hijack"
            }
            fn title(&self) -> &'static str {
                "Hijack"
            }
            fn params(&self, _ctx: &Context, _asked: &ViewArgs) -> Result<Vec<Param>, ApiError> {
                Ok(vec![Param::string("view", "View")])
            }
            fn render(&self, _args: &ViewArgs, _ctx: &Context) -> Result<ViewData, ApiError> {
                Ok(ViewData::new())
            }
        }
        let _ = Server::new(WithViews(vec![&Hijack]));
    }

    #[test]
    #[should_panic(expected = "the address uses that word to say which page it is on")]
    fn a_parameter_may_not_be_keyed_for_a_table_either() {
        struct Hijack;
        impl ViewLogic for Hijack {
            fn name(&self) -> &'static str {
                "hijack"
            }
            fn title(&self) -> &'static str {
                "Hijack"
            }
            fn params(&self, _ctx: &Context, _asked: &ViewArgs) -> Result<Vec<Param>, ApiError> {
                Ok(vec![Param::select("table", "Table", ["books"])])
            }
            fn render(&self, _args: &ViewArgs, _ctx: &Context) -> Result<ViewData, ApiError> {
                Ok(ViewData::new())
            }
        }
        let _ = Server::new(WithViews(vec![&Hijack]));
    }

    /// A table whose rows link into the fixture's `on-loan` view, or into
    /// whatever view and parameter a test names instead.
    struct Linked {
        view: &'static str,
        param: &'static str,
    }

    impl TableLogic for Linked {
        type Row = crate::fixture::Genre;

        fn name(&self) -> &'static str {
            "linked"
        }
        fn file(&self) -> &'static str {
            "Linked.jsonl"
        }
        fn title(&self) -> &'static str {
            "Linked"
        }
        fn schema(&self, _ctx: &Context) -> Result<Schema, ApiError> {
            Ok(Schema::new([Column::string("genre", "Genre")]))
        }
        fn validate(
            &self,
            _rows: &[crate::fixture::Genre],
            _ctx: &Context,
        ) -> Result<Vec<ValidationError>, ApiError> {
            Ok(Vec::new())
        }
        fn link(&self) -> Option<RowLink> {
            Some(RowLink::new(self.view).arg(self.param, "genre"))
        }
    }

    /// A view that cannot say what its parameters are without its files.
    struct Unreadable;

    impl ViewLogic for Unreadable {
        fn name(&self) -> &'static str {
            "unreadable"
        }
        fn title(&self) -> &'static str {
            "Unreadable"
        }
        fn params(&self, ctx: &Context, _asked: &ViewArgs) -> Result<Vec<Param>, ApiError> {
            let _: Vec<crate::fixture::Genre> = ctx.rows("Nowhere.jsonl")?;
            Ok(Vec::new())
        }
        fn render(&self, _args: &ViewArgs, _ctx: &Context) -> Result<ViewData, ApiError> {
            Ok(ViewData::new())
        }
    }

    struct WithLink(Linked);

    impl App for WithLink {
        fn name(&self) -> &str {
            "WithLink"
        }
        fn tables(&self) -> Vec<&dyn Table> {
            vec![&self.0]
        }
        fn views(&self) -> Vec<&dyn View> {
            vec![&crate::fixture::OnLoan, &Unreadable]
        }
    }

    #[test]
    fn a_row_may_link_to_a_view_by_a_parameter_it_declares() {
        let _ = Server::new(WithLink(Linked {
            view: "on-loan",
            param: "genre",
        }));
    }

    #[test]
    fn a_view_that_cannot_list_its_parameters_leaves_them_unchecked() {
        let _ = Server::new(WithLink(Linked {
            view: "unreadable",
            param: "codename",
        }));
    }

    #[test]
    #[should_panic(expected = "which this app does not serve")]
    fn a_row_may_not_link_to_a_view_the_app_does_not_serve() {
        let _ = Server::new(WithLink(Linked {
            view: "story",
            param: "genre",
        }));
    }

    #[test]
    #[should_panic(expected = "which that view does not declare")]
    fn a_row_may_not_link_by_a_parameter_the_view_does_not_declare() {
        let _ = Server::new(WithLink(Linked {
            view: "on-loan",
            param: "codename",
        }));
    }

    #[test]
    #[should_panic(expected = "takes letters, digits")]
    fn a_view_name_may_not_carry_a_character_an_address_reserves() {
        struct Spaced;
        impl ViewLogic for Spaced {
            fn name(&self) -> &'static str {
                "on loan"
            }
            fn title(&self) -> &'static str {
                "On loan"
            }
            fn render(&self, _args: &ViewArgs, _ctx: &Context) -> Result<ViewData, ApiError> {
                Ok(ViewData::new())
            }
        }
        let _ = Server::new(WithViews(vec![&Spaced]));
    }

    #[test]
    fn a_name_is_made_of_what_an_address_carries_unchanged() {
        assert_eq!(reserved_url_character("on-loan"), None);
        assert_eq!(reserved_url_character("books_2.0~a"), None);
        assert_eq!(reserved_url_character("on loan"), Some(' '));
        assert_eq!(reserved_url_character("on/loan"), Some('/'));
        assert_eq!(reserved_url_character("what?"), Some('?'));
        assert_eq!(reserved_url_character("a&b"), Some('&'));
        assert_eq!(reserved_url_character("café"), Some('é'));
    }

    #[test]
    fn an_app_that_serves_views_is_built_like_any_other() {
        let server = Server::new(Library::new());
        assert_eq!(server.app.views().len(), 2);
        assert_eq!(server.app.front(), Front::View("on-loan"));
    }

    #[test]
    #[should_panic(expected = "bare name inside Data/")]
    fn a_tables_file_may_not_be_a_path() {
        let _ = Server::new(Straying::new());
    }

    #[test]
    fn a_bare_file_name_is_one_file_in_the_data_directory() {
        assert!(is_bare_file_name("Books.jsonl"));
        assert!(is_bare_file_name("books.with.dots.jsonl"));

        for stray in [
            "",
            ".",
            "..",
            "../Books.jsonl",
            "sub/Books.jsonl",
            r"sub\Books.jsonl",
            "/etc/passwd",
        ] {
            assert!(!is_bare_file_name(stray), "{stray}");
        }
    }

    #[test]
    fn the_server_can_be_moved_to_another_thread() {
        fn assert_send<T: Send>(_: &T) {}
        let server = Server::new(Library::new()).before_launch(|| {});
        assert_send(&server);
    }

    /// Whatever the build script found, the page is held to the standard for
    /// what it claims to be: a checkout that has never run bun is a legitimate
    /// state and passes here, and a checkout that has built the bundle is held
    /// to everything a released page must be.
    #[test]
    fn the_embedded_page_is_what_it_says_it_is() {
        assert!(DEFAULT_INDEX_HTML.starts_with("<!doctype html>"));
        match BUNDLE_KIND {
            "built" => {
                // One self-contained page: the element the editor mounts on,
                // and its script inlined rather than fetched.
                assert!(DEFAULT_INDEX_HTML.contains(r#"<div id="root">"#));
                assert!(!DEFAULT_INDEX_HTML.contains(r#"src="/src/main.tsx""#));
                assert!(
                    DEFAULT_INDEX_HTML.len() > 50_000,
                    "the bundle is {} bytes, which is too small to be the built editor",
                    DEFAULT_INDEX_HTML.len()
                );
            }
            "placeholder" => {
                // It says which file is missing, since that is the whole of
                // what it is for.
                assert!(DEFAULT_INDEX_HTML.contains("assets/index.html"));
                assert!(!DEFAULT_INDEX_HTML.contains(r#"<div id="root">"#));
            }
            other => panic!("the build script embedded a page of unknown kind {other:?}"),
        }
    }

    #[test]
    fn stop_does_not_run_before_launch() {
        let ran = Arc::new(AtomicUsize::new(0));
        let counter = Arc::clone(&ran);
        let server = Server::new(Library::new()).before_launch(move || {
            counter.fetch_add(1, Ordering::Relaxed);
        });

        // Port 1 is privileged and never has our server, so the stop is a no-op.
        server
            .run(parse(&["library", "web", "stop", "--port", "1"]))
            .unwrap();
        assert_eq!(ran.load(Ordering::Relaxed), 0);
    }
}