link-cli 3.4.0

A CLI tool and reusable library for links manipulation backed by a LiNo-notation doublet storage engine.
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
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
//! Link CLI - A command-line tool for links manipulation
//!
//! This is the Rust implementation of the link-cli tool, providing
//! similar functionality to the C# version.

mod cli_migrations;
mod cli_transaction;

use anyhow::{anyhow, bail, Result};
use link_cli::cli::{Cli, CliCommand};
use link_cli::import_lino_file_with_max_depth;
use link_cli::protocol::ipc;
use link_cli::protocol::{
    export_store_file, import_store_file, AcceptedProtocols, BinaryLinoOptions, BinaryLinoProtocol,
    LinksClient, LinksServer, LinksSessions, LinoProtocol, ServerOptions, TextLinoProtocol,
};
use link_cli::store_lock::{self, StoreLock, StoreLockKind, StoreLockOptions};
use link_cli::{
    make_triggers_database_filename, open_transitions_journal, CommitMode,
    FileTransactionsDecorator, FileTransitionLog, FileVersionControlDecorator, LinkError,
    LinksTokenTable, LockMode, LogRetentionPolicy, NamedTypeLinks, NamedTypesDecorator,
    PermissionPolicy, PermissionsDecorator, PersistentTransformationDecorator,
    PersistentTransformationKind, QueryProcessor, TriggerStore, UndoableLinksDecorator,
};
use std::path::PathBuf;

fn main() -> Result<()> {
    let cli = match Cli::parse()? {
        CliCommand::Run(cli) => *cli,
        CliCommand::Help => {
            Cli::print_help();
            return Ok(());
        }
        CliCommand::Version => {
            println!("{}", Cli::version_text());
            return Ok(());
        }
    };

    if cli.trigger_command_count() > 1 {
        bail!("Only one of --always, --once, or --never can be used at a time.");
    }

    if cli.serve.is_some() && cli.connect.is_some() {
        bail!("--serve and --connect cannot be used together.");
    }
    if cli_migrations::requested(&cli) && (cli.forward.is_some() || cli.connect.is_some()) {
        bail!("Migration options apply to local stores.");
    }
    if cli.trace {
        ipc::set_trace(true);
    }
    if let Some(target) = &cli.forward {
        return run_relay(&cli, target);
    }
    if let Some(address) = &cli.connect {
        if cli.indexed_lookups {
            bail!("--indexed-lookups applies to local stores; enable it on the server.");
        }
        return run_client(&cli, address);
    }

    let commit_mode = parse_commit_mode(cli.commit_mode.as_deref())?;
    let retention_policy = parse_retention(cli.retention.as_deref())?;
    let lock_options = StoreLockOptions {
        trace: cli.trace,
        ..StoreLockOptions::parse(cli.lock.as_deref(), cli.lock_timeout.as_deref())?
    };
    let stores = store_lock::lock_order(locked_stores(&cli));
    if cli.lock_status {
        print!("{}", store_lock::lock_status(&stores));
        return Ok(());
    }
    // Held until the stores are saved: the whole read-modify-write (#194).
    let mode = lock_mode(&cli);
    let mut lock = StoreLock::acquire(&stores, mode, &lock_options)?;
    if mode == LockMode::Shared && cli_migrations::enabled(&cli) {
        drop(lock);
        lock = StoreLock::acquire(&stores, LockMode::Exclusive, &lock_options)?;
    }
    let _lock = lock;
    if cli_migrations::enabled(&cli) && lock_options.kind == StoreLockKind::None {
        bail!("Migrations require a store lock.");
    }
    let migrations = cli_migrations::Migrations::load(&cli)?;
    let versioned = cli.vc_requested()
        || (migrations.is_some()
            && FileVersionControlDecorator::make_version_control_database_filename(&cli.db)
                .exists());
    if versioned {
        run_with_vc(&cli, commit_mode, retention_policy, migrations.as_ref())
    } else if cli.transactions_requested() || migrations.is_some() {
        run_with_transactions(&cli, commit_mode, retention_policy, migrations.as_ref())
    } else {
        run_bare(&cli)
    }
}

/// The store files this run may save: the database (whose lock covers its
/// default side stores, `<db>.*.links` and the `<db>.transitions.log` journal)
/// and every side store named explicitly.
fn locked_stores(cli: &Cli) -> Vec<PathBuf> {
    let mut stores = vec![PathBuf::from(&cli.db)];
    let side = [&cli.transactions_file, &cli.vc_file, &cli.triggers_file];
    stores.extend(side.into_iter().flatten().map(PathBuf::from));
    let sources = [&cli.tokens, &cli.permissions];
    stores.extend(
        sources
            .into_iter()
            .flatten()
            .map(|source| source.trim())
            .filter(|source| !source.is_empty() && *source != "self")
            .map(PathBuf::from),
    );
    stores
}

/// Read-only runs share the lock; anything that may write takes it alone,
/// and so does a first run on a store that does not exist yet, since opening
/// it creates its files.
fn lock_mode(cli: &Cli) -> LockMode {
    let query = cli.query.as_deref().or(cli.query_arg.as_deref());
    let read_only = std::path::Path::new(&cli.db).exists()
        && query.is_none_or(str::is_empty)
        && cli.lino_input.is_none()
        && cli.binary_input.is_none()
        && cli.trigger_command_count() == 0
        && cli.serve.is_none()
        && cli.grant_token.is_none()
        && cli.revoke_token.is_none()
        && !cli.transactions_requested()
        && !cli_migrations::enabled(cli);
    if read_only {
        LockMode::Shared
    } else {
        LockMode::Exclusive
    }
}

fn parse_commit_mode(raw: Option<&str>) -> Result<CommitMode> {
    match raw.map(|s| s.trim()).filter(|s| !s.is_empty()) {
        None => Ok(CommitMode::Sync),
        Some(value) if value.eq_ignore_ascii_case("sync") => Ok(CommitMode::Sync),
        Some(value) if value.eq_ignore_ascii_case("async") => Ok(CommitMode::Async),
        Some(other) => bail!("Invalid --commit-mode value '{other}'. Use 'sync' or 'async'."),
    }
}

fn parse_retention(raw: Option<&str>) -> Result<LogRetentionPolicy> {
    match raw.map(|s| s.trim()).filter(|s| !s.is_empty()) {
        None => Ok(LogRetentionPolicy::Infinite),
        Some(value) => LogRetentionPolicy::parse(value)
            .map_err(|e| anyhow!("Invalid --retention value '{value}': {e}")),
    }
}

fn open_named_storage(path: impl AsRef<std::path::Path>, cli: &Cli) -> Result<NamedTypesDecorator> {
    let storage = NamedTypesDecorator::new(path, cli.trace)?;
    Ok(if cli.indexed_lookups || cli.graphql {
        storage.with_indexed_lookups()
    } else {
        storage
    })
}

/// The append-only transitions journal: `--transactions-file` when given,
/// `<db>.transitions.log` otherwise. A legacy links-backed journal is
/// imported once (issue #195).
fn open_journal(cli: &Cli) -> Result<FileTransitionLog> {
    let explicit = cli.transactions_file.as_deref().map(std::path::Path::new);
    Ok(open_transitions_journal(
        std::path::Path::new(&cli.db),
        explicit,
        cli.trace,
    )?)
}

fn run_bare(cli: &Cli) -> Result<()> {
    let mut storage = open_named_storage(&cli.db, cli)?;
    finish(cli, &mut storage)
}

/// Resolved path of the trigger sidecar store: `--triggers-file` when given,
/// `<db>.triggers.links` otherwise.
fn triggers_path(cli: &Cli) -> PathBuf {
    cli.triggers_file
        .clone()
        .map(PathBuf::from)
        .unwrap_or_else(|| make_triggers_database_filename(&cli.db))
}

/// Mirrors `persistentTransformationsEnabled` in the C# tool: any explicit flag
/// turns the layer on, and so does an already existing trigger store, so that
/// triggers stored by an earlier invocation keep firing without repeating
/// `--triggers`.
fn persistent_transformations_enabled(cli: &Cli) -> bool {
    cli.persistent_transformations_requested() || triggers_path(cli).exists()
}

/// Runs the query pipeline over `storage`, wrapping it in a
/// [`PersistentTransformationDecorator`] first when triggers are enabled.
///
/// The wrap happens here rather than in the three entry paths so that the
/// decorator always sits *outermost* — above the transactions and
/// version-control layers — exactly like in the C# tool, where every replayed
/// substitution is journalled like any other write.
fn finish<S>(cli: &Cli, storage: &mut S) -> Result<()>
where
    S: NamedTypeLinks,
{
    if !persistent_transformations_enabled(cli) {
        return run(cli, storage, |_, _, _| Ok(false));
    }

    let trigger_store = if cli.embed_triggers {
        TriggerStore::Embedded
    } else {
        TriggerStore::sidecar(triggers_path(cli), cli.trace)?
    };
    let mut storage = PersistentTransformationDecorator::new(storage, trigger_store, cli.trace)
        .with_auto_create_missing_references(cli.auto_create_missing_references);
    run(cli, &mut storage, run_trigger_command)
}

/// The store a `--tokens` or `--permissions` value names: the data itself
/// (`self`, `None` here) or a links file of its own.
fn open_side_store(cli: &Cli, source: &str) -> Result<Option<NamedTypesDecorator>> {
    if source == "self" {
        Ok(None)
    } else {
        Ok(Some(open_named_storage(source, cli)?))
    }
}

/// `--subject`: a link index, or the name of a link.
fn resolve_subject<S: NamedTypeLinks>(cli: &Cli, storage: &mut S) -> Result<u32> {
    let Some(text) = cli
        .subject
        .as_deref()
        .map(str::trim)
        .filter(|text| !text.is_empty())
    else {
        return Ok(0);
    };
    if text.bytes().all(|byte| byte.is_ascii_digit()) {
        if let Ok(subject) = text.parse::<u32>() {
            return Ok(subject);
        }
    }
    match storage.get_by_name(text)? {
        Some(subject) if subject != 0 => Ok(subject),
        _ => bail!("Unknown subject '{text}'."),
    }
}

/// Runs the invocation over `storage`: the token commands, the server, or
/// the query pipeline, as the subject sees the store when `--permissions`
/// is given (issue #149).
fn run<S, F>(cli: &Cli, storage: &mut S, trigger_stage: F) -> Result<()>
where
    S: NamedTypeLinks,
    F: FnOnce(&Cli, &mut S, Option<&str>) -> Result<bool>,
{
    let subject = resolve_subject(cli, storage)?;
    let tokens_source = cli
        .tokens
        .as_deref()
        .map(str::trim)
        .filter(|source| !source.is_empty());
    let tokens = match tokens_source {
        Some(source) => Some(open_side_store(cli, source)?),
        None if cli.grant_token.is_some() || cli.revoke_token.is_some() => {
            bail!("--grant-token and --revoke-token need --tokens.")
        }
        None => None,
    };
    let policy = match cli
        .permissions
        .as_deref()
        .map(str::trim)
        .filter(|source| !source.is_empty())
    {
        Some(source) => {
            if cli.trigger_command_count() > 0 {
                // Triggers run below the view, as the store itself.
                bail!("--always, --once and --never cannot be used with --permissions.");
            }
            Some(match open_side_store(cli, source)? {
                None => PermissionPolicy::in_data(storage)?,
                Some(rules) => PermissionPolicy::with_rules(storage, Box::new(rules))?,
            })
        }
        None => None,
    };

    if cli.grant_token.is_some() || cli.revoke_token.is_some() {
        // `tokens` is `Some` here: the check above bails otherwise.
        return run_tokens(cli, storage, tokens.flatten(), subject);
    }
    if let (Some(address), true) = (&cli.serve, cli.graphql) {
        return run_graphql_server(cli, address, storage, policy);
    }
    if cli.serve.is_some() {
        return run_server(cli, storage, policy, subject, tokens);
    }
    match policy {
        None => run_query_pipeline_with(cli, storage, trigger_stage)?,
        Some(policy) => run_permitted_query(cli, storage, policy, subject)?,
    }
    storage.save()?;
    Ok(())
}

/// `--grant-token` and `--revoke-token`: writes the token table of
/// `--tokens`, in `tokens` or in the data when `None`.
fn run_tokens<S: NamedTypeLinks>(
    cli: &Cli,
    storage: &mut S,
    tokens: Option<NamedTypesDecorator>,
    subject: u32,
) -> Result<()> {
    if cli.grant_token.is_some() && subject == 0 {
        bail!("--grant-token needs a --subject.");
    }
    match tokens {
        Some(mut tokens) => {
            write_tokens(cli, &mut tokens, subject)?;
            tokens.save()?;
        }
        None => write_tokens(cli, &mut *storage, subject)?,
    }
    // The data holds the points the token table names, even with a
    // table of its own.
    storage.save()?;
    Ok(())
}

fn write_tokens<T: NamedTypeLinks>(cli: &Cli, tokens: T, subject: u32) -> Result<()> {
    let mut table = LinksTokenTable::new(tokens);
    if let Some(token) = &cli.grant_token {
        let link = table.grant(token, subject)?;
        println!("Token granted to subject {subject}: {link}");
    }
    if let Some(token) = &cli.revoke_token {
        if table.revoke(token)? {
            println!("Token revoked.");
        } else {
            println!("Unknown token.");
        }
    }
    Ok(())
}

/// The query pipeline as `subject` sees the store. The query is atomic: a
/// failed one is undone whole, even where the store changed links the
/// subject cannot see.
fn run_permitted_query<S: NamedTypeLinks>(
    cli: &Cli,
    storage: &mut S,
    policy: PermissionPolicy,
    subject: u32,
) -> Result<()> {
    let mut view = PermissionsDecorator::new(UndoableLinksDecorator::new(storage), policy, subject);
    view.inner_mut().begin();
    match run_query_pipeline(cli, &mut view) {
        Ok(()) => {
            view.inner_mut().commit();
            Ok(())
        }
        Err(error) => {
            view.inner_mut().rollback()?;
            if error.downcast_ref::<LinkError>().is_some() {
                Err(error)
            } else {
                Err(LinkError::QueryError(format!("{error:#}")).into())
            }
        }
    }
}

/// Handles `--always`, `--once` and `--never`.
///
/// Returns `true` when the command was terminal, i.e. the query was consumed as
/// a trigger definition and must not also be executed against the database.
fn run_trigger_command<S>(
    cli: &Cli,
    storage: &mut PersistentTransformationDecorator<S>,
    query: Option<&str>,
) -> Result<bool>
where
    S: NamedTypeLinks,
{
    if cli.trigger_command_count() == 0 {
        return Ok(false);
    }

    let query = query.filter(|query| !query.trim().is_empty());
    let Some(query) = query else {
        bail!("--always, --once, and --never require a query.");
    };

    if cli.always || cli.once {
        let kind = if cli.always {
            PersistentTransformationKind::Always
        } else {
            PersistentTransformationKind::Once
        };
        let root = storage.store_trigger(kind, query)?;
        println!("{kind} persistent transformation trigger stored: {root}");
    } else {
        let removed = storage.remove_triggers(query)?;
        println!("Persistent transformation triggers removed: {removed}");
    }

    Ok(true)
}

fn run_with_transactions(
    cli: &Cli,
    commit_mode: CommitMode,
    retention_policy: LogRetentionPolicy,
    migrations: Option<&cli_migrations::Migrations>,
) -> Result<()> {
    let data_links = open_named_storage(&cli.db, cli)?;
    let log_links = open_journal(cli)?;
    let mut tx = FileTransactionsDecorator::new(
        data_links,
        log_links,
        retention_policy,
        commit_mode,
        cli.trace,
    )?;

    if let Some(migrations) = migrations {
        if migrations.run(cli, &mut tx)? {
            return Ok(());
        }
    }
    if cli.show_log {
        for transition in tx.log() {
            println!(
                "{}\t{}\t{:?}\t{:032x}\t({},{},{}) -> ({},{},{})",
                transition.sequence,
                transition.timestamp_ms,
                transition.kind,
                transition.transaction_id,
                transition.before.index,
                transition.before.source,
                transition.before.target,
                transition.after.index,
                transition.after.source,
                transition.after.target,
            );
        }
        tx.save()?;
        return Ok(());
    }

    cli_transaction::finish(cli, &mut tx)
}

fn run_with_vc(
    cli: &Cli,
    commit_mode: CommitMode,
    retention_policy: LogRetentionPolicy,
    migrations: Option<&cli_migrations::Migrations>,
) -> Result<()> {
    let data_links = open_named_storage(&cli.db, cli)?;
    let log_links = open_journal(cli)?;
    let tx = FileTransactionsDecorator::new(
        data_links,
        log_links,
        retention_policy,
        commit_mode,
        cli.trace,
    )?;
    let vc_path = cli
        .vc_file
        .clone()
        .map(std::path::PathBuf::from)
        .unwrap_or_else(|| {
            FileVersionControlDecorator::make_version_control_database_filename(&cli.db)
        });
    let vc_links = open_named_storage(&vc_path, cli)?;
    let mut vc = FileVersionControlDecorator::new(tx, vc_links, cli.trace)?;

    if let Some(migrations) = migrations {
        if migrations.run(cli, &mut vc)? {
            return Ok(());
        }
    }
    // 1) --checkout (resolves seq or tag).
    if let Some(checkout_point) = cli.checkout.as_deref() {
        let seq = resolve_sequence(&vc, checkout_point)
            .ok_or_else(|| anyhow!("Unknown checkout point '{checkout_point}'."))?;
        vc.checkout(seq)?;
        if cli.trace {
            println!("Checked out seq {seq} on branch '{}'.", vc.current_branch());
        }
    }

    // 2) --branch [--branch-from] (creates if missing, then switches).
    if let Some(branch_name) = cli.branch.as_deref() {
        let exists = vc.list_branches().iter().any(|b| b.name == branch_name);
        if !exists {
            vc.branch(branch_name, cli.branch_from)?;
            if cli.trace {
                println!("Created branch '{branch_name}'.");
            }
        }
        vc.switch_branch(branch_name)?;
        if cli.trace {
            println!("Switched to branch '{branch_name}'.");
        }
    }

    // 3) --tag.
    if let Some(tag_spec) = cli.tag.as_deref() {
        let (name, seq) = match tag_spec.find('=') {
            None => (tag_spec.to_string(), None),
            // Preserve existing aliases before trying delimiters in the name:
            // alias=release=0 may refer to the complete existing tag release=0.
            Some(eq) => tag_spec
                .match_indices('=')
                .find_map(|(separator, _)| {
                    resolve_sequence(&vc, &tag_spec[separator + 1..])
                        .map(|resolved| (tag_spec[..separator].to_string(), Some(resolved)))
                })
                .ok_or_else(|| anyhow!("Unknown tag point '{}'.", &tag_spec[eq + 1..]))?,
        };
        vc.tag(&name, seq)?;
        if cli.trace {
            let resolved = seq.unwrap_or_else(|| vc.current_sequence());
            println!("Tagged '{name}' at seq {resolved}.");
        }
    }

    // 4) --list-branches / --list-tags (terminal).
    if cli.list_branches {
        let current = vc.current_branch().to_string();
        for info in vc.list_branches() {
            let marker = if info.name == current { "*" } else { " " };
            let parent = info.parent.clone().unwrap_or_else(|| "-".to_string());
            println!(
                "{} {}\tparent={}\tfork={}\thead={}",
                marker, info.name, parent, info.fork_seq, info.head
            );
        }
        vc.save()?;
        return Ok(());
    }

    if cli.list_tags {
        for (name, seq) in vc.list_tags() {
            println!("{name}\t{seq}");
        }
        vc.save()?;
        return Ok(());
    }

    // 5) --log.
    if cli.show_log {
        for transition in vc.transactions().log() {
            println!(
                "{}\t{}\t{:?}\t{:032x}\t({},{},{}) -> ({},{},{})",
                transition.sequence,
                transition.timestamp_ms,
                transition.kind,
                transition.transaction_id,
                transition.before.index,
                transition.before.source,
                transition.before.target,
                transition.after.index,
                transition.after.source,
                transition.after.target,
            );
        }
        vc.save()?;
        return Ok(());
    }

    cli_transaction::finish(cli, &mut vc)
}

fn resolve_sequence(vc: &FileVersionControlDecorator, point: &str) -> Option<i64> {
    let trimmed = point.trim();
    if trimmed.is_empty() {
        return None;
    }
    if let Ok(direct) = trimmed.parse::<i64>() {
        return Some(direct);
    }
    vc.try_get_tag(trimmed)
}

fn run_query_pipeline<S>(cli: &Cli, storage: &mut S) -> Result<()>
where
    S: NamedTypeLinks,
{
    run_query_pipeline_with(cli, storage, |_, _, _| Ok(false))
}

/// The query pipeline, with a hook that may consume the query before it reaches
/// the [`QueryProcessor`].
///
/// `trigger_stage` runs where the C# tool runs its trigger commands: after
/// `--structure`, so `clink --structure` keeps working unchanged, and before
/// the query is processed, so `--always '…'` stores the query instead of
/// applying it. Returning `true` ends the run after the LiNo output is written.
fn run_query_pipeline_with<S, F>(cli: &Cli, storage: &mut S, trigger_stage: F) -> Result<()>
where
    S: NamedTypeLinks,
    F: FnOnce(&Cli, &mut S, Option<&str>) -> Result<bool>,
{
    if cli.before {
        storage.print_all_lino()?;
    }

    import_inputs(cli, storage)?;

    if let Some(link_id) = cli.structure {
        let structure_formatted = storage.format_structure(link_id)?;
        println!("{structure_formatted}");
        export_outputs(cli, storage)?;
        return Ok(());
    }

    let effective_query = cli.query.as_deref().or(cli.query_arg.as_deref());

    if trigger_stage(cli, storage, effective_query)? {
        export_outputs(cli, storage)?;
        return Ok(());
    }

    let mut changes_list = Vec::new();

    if let Some(query) = effective_query {
        if !query.is_empty() {
            let processor = QueryProcessor::new(cli.trace)
                .with_auto_create_missing_references(cli.auto_create_missing_references);
            changes_list = processor.process_query(storage, query)?;
        }
    }

    if cli.changes && !changes_list.is_empty() {
        for (before_link, after_link) in &changes_list {
            storage.print_change_lino(before_link, after_link)?;
        }
    }

    if cli.after {
        storage.print_all_lino()?;
    }

    export_outputs(cli, storage)?;

    Ok(())
}

/// Imports the store archive of `--import-binary`, then the LiNo file of
/// `--in`.
fn import_inputs<S: NamedTypeLinks>(cli: &Cli, storage: &mut S) -> Result<()> {
    if let Some(input_path) = &cli.binary_input {
        import_store_file(storage, input_path)?;
    }
    if let Some(input_path) = &cli.lino_input {
        import_lino_file_with_max_depth(storage, input_path, cli.lino_input_max_depth)?;
    }
    Ok(())
}

/// Writes the whole store to the LiNo file of `--out` and the store archive
/// of `--export-binary`.
fn export_outputs<S: NamedTypeLinks>(cli: &Cli, storage: &mut S) -> Result<()> {
    if let Some(output_path) = &cli.lino_output {
        storage.write_lino_output(output_path)?;
    }
    if let Some(output_path) = &cli.binary_output {
        export_store_file(storage, output_path)?;
    }
    Ok(())
}

/// The binary options selected by `--external-references`, `--arity` and
/// `--packed-widths`.
fn binary_options(cli: &Cli) -> BinaryLinoOptions {
    BinaryLinoOptions::default()
        .with_external_references(cli.external_references)
        .with_arity(cli.arity)
        .with_packed_widths(cli.packed_widths)
}

/// `--connect`: sends the query to a server and prints the reply.
///
/// Any binary option implies `--protocol binary`.
fn run_client(cli: &Cli, address: &str) -> Result<()> {
    let options = binary_options(cli);
    let protocol: Box<dyn LinoProtocol> = match cli.protocol.as_deref().map(str::trim) {
        None if options == BinaryLinoOptions::default() => Box::new(TextLinoProtocol::new()),
        None => Box::new(BinaryLinoProtocol::with_options(options)),
        Some(name) if name.eq_ignore_ascii_case("text") => {
            if options != BinaryLinoOptions::default() {
                bail!("Binary protocol options require --protocol binary.");
            }
            Box::new(TextLinoProtocol::new())
        }
        Some(name) if name.eq_ignore_ascii_case("binary") => {
            Box::new(BinaryLinoProtocol::with_options(options))
        }
        Some(other) => bail!("Invalid --protocol value '{other}'. Use 'text' or 'binary'."),
    };
    let query = cli.query.as_deref().or(cli.query_arg.as_deref());
    let mut client = LinksClient::connect_endpoint(address, protocol)?;
    if let Some(token) = &cli.token {
        client.authenticate(token)?;
    }
    let reply = client.query_text(query.unwrap_or_default())?;
    if !reply.is_empty() {
        println!("{reply}");
    }
    Ok(())
}

/// `--serve`: serves `storage` until the process is stopped.
///
/// With `policy` every connection sees the store as its subject does: the
/// one of `--subject` until `(auth: token)` finds another in the token
/// table of `--tokens` (`tokens`, or the data when `None`).
fn run_graphql_server<S>(
    cli: &Cli,
    address: &str,
    storage: &mut S,
    policy: Option<PermissionPolicy>,
) -> Result<()>
where
    S: NamedTypeLinks,
{
    use link_cli::graphql::{DeepStore, GraphqlServer, Json, Settings};
    if !cli.serve_also.is_empty() {
        bail!("--graphql serves HTTP on one TCP address; give --serve once.");
    }
    let endpoint = ipc::Endpoint::parse(address)?;
    if endpoint.kind() != "tcp" {
        bail!(
            "--graphql serves HTTP over TCP only, not over `{}:`.",
            endpoint.kind()
        );
    }
    let address = endpoint.address();
    let mut store = DeepStore::open(&mut *storage, policy)?;
    for file in &cli.deep_packages {
        let text = std::fs::read_to_string(file)?;
        let rows = Json::parse(&text).map_err(|error| anyhow::anyhow!("{file}: {error}"))?;
        store.load_package(&rows)?;
    }
    let secret = match &cli.jwt_secret {
        Some(secret) => secret.clone().into_bytes(),
        None => Settings::random_secret(),
    };
    let settings = Settings::new(secret, cli.graphql_admin_secret.clone());
    let server = GraphqlServer::bind(address)?;
    let stop = server.shutdown_handle()?;
    ctrlc::set_handler(move || stop.shutdown())?;
    println!("clink GraphQL server listening on {}", server.local_addr()?);
    std::io::Write::flush(&mut std::io::stdout())?;
    server.serve(&mut store, settings)?;
    drop(store);
    storage.save()?;
    Ok(())
}

fn run_server<S>(
    cli: &Cli,
    storage: &mut S,
    policy: Option<PermissionPolicy>,
    subject: u32,
    tokens: Option<Option<NamedTypesDecorator>>,
) -> Result<()>
where
    S: NamedTypeLinks,
{
    if cli.query.is_some() || cli.query_arg.is_some() {
        bail!("--serve does not take a query; send queries with --connect.");
    }
    let accept = match cli.protocol.as_deref().map(str::trim) {
        None => AcceptedProtocols::Any,
        Some(name) if name.eq_ignore_ascii_case("any") => AcceptedProtocols::Any,
        Some(name) if name.eq_ignore_ascii_case("text") => AcceptedProtocols::Text,
        Some(name) if name.eq_ignore_ascii_case("binary") => AcceptedProtocols::Binary,
        Some(other) => {
            bail!("Invalid --protocol value '{other}'. Use 'any', 'text' or 'binary'.")
        }
    };
    let options = ServerOptions {
        trace: cli.trace,
        auto_create_missing_references: cli.auto_create_missing_references,
        accept,
        triplets: cli.triplets,
        ..ServerOptions::default()
    };
    let sessions = match policy {
        Some(policy) => LinksSessions::with_permissions(&mut *storage, policy),
        None => LinksSessions::new(&mut *storage),
    };
    let mut sessions = sessions
        .with_subject(subject)
        .with_auto_create_missing_references(cli.auto_create_missing_references);
    sessions = match tokens {
        None => sessions,
        Some(None) => sessions
            .with_authenticator(|store, token| LinksTokenTable::new(store).authenticate(token)),
        Some(Some(mut tokens)) => sessions.with_authenticator(move |_, token| {
            LinksTokenTable::new(&mut tokens).authenticate(token)
        }),
    };
    let server = LinksServer::listen_all(&cli.serve_endpoints(), options)?;
    let stop = server.shutdown_handle()?;
    ctrlc::set_handler(move || stop.shutdown())?;
    print_banner(&server.endpoints())?;
    server.serve_sessions(&mut sessions)?;
    drop(sessions);
    storage.save()?;
    Ok(())
}

/// `--serve A --forward B`: relays every connection accepted on the
/// `--serve` endpoints, byte for byte, to a new connection to `B`; no
/// database is opened, so relays stack any transports in either protocol.
fn run_relay(cli: &Cli, target: &str) -> Result<()> {
    if cli.serve.is_none() {
        bail!("--forward relays the connections of --serve; give --serve as well.");
    }
    if cli.query.is_some() || cli.query_arg.is_some() {
        bail!("--forward does not take a query; send queries with --connect.");
    }
    if cli.graphql {
        bail!("--forward and --graphql cannot be used together.");
    }
    let target = ipc::Endpoint::parse(target)?;
    let mut listener = ipc::listen_all(&cli.serve_endpoints())?;
    let close = listener.closer();
    ctrlc::set_handler(move || close())?;
    print_banner(&listener.endpoints())?;
    if cli.trace {
        eprintln!("clink: forwarding to {target}");
    }
    ipc::relay(&mut *listener, &target)?;
    Ok(())
}

/// Prints `clink server listening on ENDPOINT` once per endpoint: on
/// standard output, or on standard error when one endpoint is `stdio`,
/// whose standard output carries the protocol.
fn print_banner(endpoints: &[String]) -> Result<()> {
    let stdio = endpoints
        .iter()
        .any(|endpoint| ipc::Endpoint::parse(endpoint).is_ok_and(|e| e.kind() == "stdio"));
    for endpoint in endpoints {
        if stdio {
            eprintln!("clink server listening on {endpoint}");
        } else {
            println!("clink server listening on {endpoint}");
        }
    }
    std::io::Write::flush(&mut std::io::stdout())?;
    Ok(())
}