tailsurf-cli 0.2.0

Command line client for tail.surf live transcript streams
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
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
//! `tsf` command-line client for creating, writing, replaying, tailing, and managing Tailsurf streams.

use std::{
    collections::{BTreeMap, VecDeque},
    fs::OpenOptions,
    io::ErrorKind,
    path::{Path, PathBuf},
    process::{ExitCode, ExitStatus, Stdio},
    str::FromStr,
};

use axoupdater::AxoUpdater;
use bytes::{Buf, Bytes, BytesMut};
use clap::{Args, Parser, Subcommand, ValueEnum};
use eyre::{Context, ContextCompat, bail};
use secrecy::ExposeSecret;
use serde::Serialize;
use tailsurf::{
    AppendTicket, BearerToken, StreamId, TokenId, TokenPermissions, TsfClient, TsfProducer,
    WriteRecord, WriterId,
    protocol::{
        rest::{
            CreateStreamRequest, CreateStreamResponse, IssueTokenRequest, IssueTokenResponse,
            IssuedStreamToken, RequestedRetention, StreamInfoResponse, StreamTokenStatus,
            UpdateStreamRequest, Visibility,
        },
        ws::{
            ReadStart, ReadStreamOptions, WriteStreamOptions,
            frame::{MAX_RECORD_BYTES, PartHeader, RecordFormat},
        },
    },
    stream_url::{StreamLocator, stream_url},
    transcript::{DEFAULT_MAX_LOGICAL_RECORD_BYTES, LogicalTranscript, TranscriptRecord},
};
use tokio::{
    io::{AsyncRead, AsyncReadExt, AsyncWriteExt},
    process::Command as TokioCommand,
    sync::mpsc,
    time::{Duration, Instant, sleep_until},
};
use url::Url;

const INTERRUPT_EXIT_CODE: i32 = 130;
const RAW_LINGER: Duration = Duration::from_millis(10);

#[derive(Debug, Parser)]
#[command(name = "tsf")]
#[command(version, about = "Create, write, and read tail.surf streams")]
struct Cli {
    /// Tailsurf API origin.
    #[arg(
        long = "api-url",
        env = "TSF_API_URL",
        default_value = "https://tail.surf",
        global = true
    )]
    api_url: Url,
    /// Origin used when printing share URLs.
    #[arg(
        long = "web-url",
        env = "TSF_WEB_URL",
        default_value = "https://tail.surf",
        global = true
    )]
    web_url: Url,
    #[command(subcommand)]
    command: Command,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Create a stream and print its share links.
    New(NewArgs),
    /// Stream stdin or a command's output to a stream.
    Write(WriteArgs),
    /// Follow a stream, optionally starting from retained records.
    Tail(TailArgs),
    /// Print a bounded snapshot of retained records.
    Replay(ReplayArgs),
    /// Show current stream metadata.
    Info(InfoArgs),
    /// Permanently delete a stream.
    Delete(OwnerUrlArgs),
    /// Change stream visibility.
    Visibility(VisibilityArgs),
    /// Manage share links.
    Link(LinkArgs),
    /// Update an installation managed by the tail.surf installer.
    Update(UpdateArgs),
    /// Validate a stream URL without exposing its token.
    ParseUrl {
        /// Stream share URL.
        #[arg(value_name = "STREAM_URL")]
        url: String,
    },
}

#[derive(Debug, Args)]
struct UpdateArgs {
    /// Check whether an update is available without installing it.
    #[arg(long)]
    check: bool,
}

#[derive(Debug, Args)]
struct NewArgs {
    /// Allow anonymous reads.
    #[arg(long)]
    public: bool,
    /// Issue this link at creation instead of the default owner link. May be repeated.
    #[arg(long = "link", value_name = "ACCESS")]
    links: Vec<AccessArg>,
    #[arg(
        long,
        value_name = "DURATION",
        help = "Record retention, such as 6h, 7d, or infinite"
    )]
    retention: Option<RetentionArg>,
    /// Output format.
    #[arg(long, value_enum, default_value_t = OutputFormat::Text)]
    format: OutputFormat,
    /// Write the owner token secret to this file.
    #[arg(long = "owner-token-file", value_name = "PATH")]
    owner_token_file: Option<PathBuf>,
    /// Write the view token secret to this file.
    #[arg(long = "view-token-file", value_name = "PATH")]
    view_token_file: Option<PathBuf>,
    /// Write the write token secret to this file.
    #[arg(long = "write-token-file", value_name = "PATH")]
    write_token_file: Option<PathBuf>,
}

#[derive(Debug, Args)]
struct WriteArgs {
    /// Write-capable stream share URL. Required unless --new is set.
    #[arg(value_name = "STREAM_URL", conflicts_with = "new")]
    url: Option<String>,
    /// Create a private stream before writing.
    #[arg(long)]
    new: bool,
    /// Make the new stream publicly readable.
    #[arg(long)]
    public: bool,
    #[arg(
        long,
        value_name = "DURATION",
        help = "New-stream record retention, such as 6h, 7d, or infinite"
    )]
    retention: Option<RetentionArg>,
    /// Preserve input as arbitrary byte records instead of newline-delimited transcript records.
    #[arg(long)]
    raw: bool,
    /// Command to run. Its stdout and stderr are written to the stream.
    #[arg(last = true, value_name = "COMMAND")]
    command: Vec<String>,
}

#[derive(Debug, Args)]
struct TailArgs {
    /// Read-capable or public stream share URL.
    #[arg(value_name = "STREAM_URL")]
    url: String,
    /// Start this many retained records before the live tail.
    #[arg(short = 'n', long, conflicts_with_all = ["seq_num", "timestamp"])]
    tail_offset: Option<u64>,
    /// Start at this S2 sequence number.
    #[arg(long, conflicts_with = "timestamp")]
    seq_num: Option<u64>,
    /// Start at this Unix timestamp in milliseconds.
    #[arg(long, conflicts_with = "seq_num")]
    timestamp: Option<u64>,
    /// Stop after this many stored records instead of following forever.
    #[arg(long)]
    count: Option<u64>,
    /// Maximum assembled transcript record size.
    #[arg(long, value_name = "BYTES", default_value_t = DEFAULT_MAX_LOGICAL_RECORD_BYTES)]
    max_logical_record_bytes: usize,
}

#[derive(Debug, Args)]
struct ReplayArgs {
    /// Read-capable or public stream share URL.
    #[arg(value_name = "STREAM_URL")]
    url: String,
    /// Start at this S2 sequence number.
    #[arg(long, conflicts_with = "timestamp")]
    seq_num: Option<u64>,
    /// Start at this Unix timestamp in milliseconds.
    #[arg(long, conflicts_with = "seq_num")]
    timestamp: Option<u64>,
    /// Print at most this many stored records.
    #[arg(long)]
    count: Option<u64>,
    /// Maximum assembled transcript record size.
    #[arg(long, value_name = "BYTES", default_value_t = DEFAULT_MAX_LOGICAL_RECORD_BYTES)]
    max_logical_record_bytes: usize,
}

#[derive(Debug, Args)]
struct InfoArgs {
    /// Read-capable or public stream share URL.
    #[arg(value_name = "STREAM_URL")]
    url: String,
    /// Output format.
    #[arg(long, value_enum, default_value_t = OutputFormat::Text)]
    format: OutputFormat,
}

#[derive(Debug, Args)]
struct OwnerUrlArgs {
    /// Owner stream share URL.
    #[arg(value_name = "OWNER_URL")]
    url: String,
}

#[derive(Debug, Args)]
struct VisibilityArgs {
    /// Owner stream share URL.
    #[arg(value_name = "OWNER_URL")]
    url: String,
    /// New visibility.
    visibility: VisibilityArg,
    /// Output format.
    #[arg(long, value_enum, default_value_t = OutputFormat::Text)]
    format: OutputFormat,
}

#[derive(Debug, Args)]
struct LinkArgs {
    #[command(subcommand)]
    command: LinkCommand,
}

#[derive(Debug, Subcommand)]
enum LinkCommand {
    /// List link metadata without secrets.
    List(ListLinkArgs),
    /// Issue a share link and print it once.
    Issue(IssueLinkArgs),
    /// Revoke a link by its ID.
    Revoke(RevokeLinkArgs),
}

#[derive(Debug, Args)]
struct ListLinkArgs {
    /// Owner stream share URL.
    #[arg(value_name = "OWNER_URL")]
    url: String,
    /// Output format.
    #[arg(long, value_enum, default_value_t = OutputFormat::Text)]
    format: OutputFormat,
}

#[derive(Debug, Args)]
struct IssueLinkArgs {
    /// Owner stream share URL.
    #[arg(value_name = "OWNER_URL")]
    url: String,
    /// Access level: view, write, view+write, or owner.
    #[arg(long = "access", value_name = "ACCESS")]
    access: AccessArg,
    /// Expiry such as 1h, 7d, or never.
    #[arg(long, value_name = "EXPIRY", default_value = "never")]
    expires: ExpiresArg,
    /// Output format.
    #[arg(long, value_enum, default_value_t = OutputFormat::Text)]
    format: OutputFormat,
    /// Write the new token secret to this file.
    #[arg(long = "token-file", value_name = "PATH")]
    token_file: Option<PathBuf>,
}

#[derive(Debug, Args)]
struct RevokeLinkArgs {
    /// Owner stream share URL.
    #[arg(value_name = "OWNER_URL")]
    url: String,
    /// Link ID from `tsf link list`.
    #[arg(value_name = "LINK_ID")]
    token_id: TokenId,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
enum VisibilityArg {
    Private,
    Public,
}

impl From<VisibilityArg> for Visibility {
    fn from(value: VisibilityArg) -> Self {
        match value {
            VisibilityArg::Private => Self::Private,
            VisibilityArg::Public => Self::Public,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
enum OutputFormat {
    Text,
    Json,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum RetentionArg {
    Seconds(u64),
    Infinite,
}

impl FromStr for RetentionArg {
    type Err = String;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        if value.eq_ignore_ascii_case("infinite") {
            return Ok(Self::Infinite);
        }
        let duration = humantime::parse_duration(value)
            .map_err(|error| format!("invalid retention duration: {error}"))?;
        if duration.is_zero() {
            return Err("retention must be at least one second".to_owned());
        }
        if duration.subsec_nanos() != 0 {
            return Err("retention must be a whole number of seconds".to_owned());
        }
        Ok(Self::Seconds(duration.as_secs()))
    }
}

impl From<RetentionArg> for RequestedRetention {
    fn from(value: RetentionArg) -> Self {
        match value {
            RetentionArg::Seconds(seconds) => Self::Seconds(seconds),
            RetentionArg::Infinite => Self::Infinite,
        }
    }
}

#[derive(Clone, Copy, Debug)]
struct AccessArg(TokenPermissions);

impl FromStr for AccessArg {
    type Err = String;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let permissions = match value.to_ascii_lowercase().as_str() {
            "view" | "r" => TokenPermissions::read(),
            "write" | "w" => TokenPermissions::write(),
            "view+write" | "view-write" | "rw" => TokenPermissions::read_write(),
            "owner" | "o" => TokenPermissions::owner(),
            other => {
                return Err(format!(
                    "unknown access level {other:?}; use view, write, view+write, or owner"
                ));
            }
        };
        Ok(Self(permissions))
    }
}

#[derive(Clone, Copy, Debug)]
enum ExpiresArg {
    Never,
    In(Duration),
}

impl ExpiresArg {
    fn rfc3339(self) -> Option<String> {
        match self {
            Self::Never => None,
            Self::In(duration) => Some(
                humantime::format_rfc3339_seconds(std::time::SystemTime::now() + duration)
                    .to_string(),
            ),
        }
    }
}

impl FromStr for ExpiresArg {
    type Err = String;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        if value.eq_ignore_ascii_case("never") {
            return Ok(Self::Never);
        }
        let duration = humantime::parse_duration(value)
            .map_err(|error| format!("invalid expiry duration: {error}"))?;
        if duration.is_zero() {
            return Err("expiry must be at least one second".to_owned());
        }
        Ok(Self::In(duration))
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum WriteBuffering {
    Raw,
    Lines,
}

#[derive(Debug)]
struct WriterState {
    writer_id: WriterId,
    next_writer_seq: u64,
}

impl WriterState {
    fn new_random() -> Self {
        Self {
            writer_id: WriterId::new_random(),
            next_writer_seq: 0,
        }
    }

    fn writer_id(&self) -> WriterId {
        self.writer_id
    }

    fn appended(&self) -> u64 {
        self.next_writer_seq
    }

    fn reserve_writer_seq(&mut self) -> eyre::Result<u64> {
        let reserved = self.next_writer_seq;
        self.next_writer_seq = self
            .next_writer_seq
            .checked_add(1)
            .context("writer sequence overflowed")?;
        Ok(reserved)
    }
}

#[tokio::main]
async fn main() -> ExitCode {
    match run(Cli::parse()).await {
        Ok(()) => ExitCode::SUCCESS,
        Err(error) if is_broken_pipe(&error) => ExitCode::SUCCESS,
        Err(error) => {
            print_error(&error);
            ExitCode::FAILURE
        }
    }
}

async fn run(cli: Cli) -> eyre::Result<()> {
    match cli.command {
        Command::New(args) => new_stream(cli.api_url, cli.web_url, args).await,
        Command::Write(args) => write_stream(cli.api_url, cli.web_url, args).await,
        Command::Tail(args) => tail_stream(cli.api_url, args).await,
        Command::Replay(args) => replay_stream(cli.api_url, args).await,
        Command::Info(args) => stream_info(cli.api_url, args).await,
        Command::Delete(args) => delete_stream(cli.api_url, args).await,
        Command::Visibility(args) => update_visibility(cli.api_url, args).await,
        Command::Link(args) => link_command(cli.api_url, cli.web_url, args).await,
        Command::Update(args) => update_cli(args).await,
        Command::ParseUrl { url } => parse_url(&url),
    }
}

async fn update_cli(args: UpdateArgs) -> eyre::Result<()> {
    let mut updater = managed_updater()?;

    if args.check {
        if updater
            .is_update_needed()
            .await
            .context("failed to check for a tsf update")?
        {
            println!("An update is available. Run `tsf update` to install it.");
        } else {
            println!("tsf is up to date.");
        }
        return Ok(());
    }

    updater.enable_installer_output();
    match updater.run().await.context("failed to update tsf")? {
        Some(_) => eprintln!("Updated tsf."),
        None => eprintln!("tsf is already up to date."),
    }
    Ok(())
}

fn managed_updater() -> eyre::Result<AxoUpdater> {
    const OWNERSHIP_ERROR: &str = "this tsf installation is not managed by the tail.surf installer; update it with the package manager that installed it (Cargo: cargo install tailsurf-cli --locked)";

    let mut updater = AxoUpdater::new_for("tailsurf-cli");
    updater
        .load_receipt()
        .map_err(|_| eyre::eyre!(OWNERSHIP_ERROR))?;
    let owns_executable = updater
        .check_receipt_is_for_this_executable()
        .map_err(|_| eyre::eyre!(OWNERSHIP_ERROR))?;
    if !owns_executable {
        bail!(OWNERSHIP_ERROR);
    }
    Ok(updater)
}

fn is_broken_pipe(error: &eyre::Report) -> bool {
    error.chain().any(|source| {
        source
            .downcast_ref::<std::io::Error>()
            .is_some_and(|error| error.kind() == ErrorKind::BrokenPipe)
    })
}

fn print_error(error: &eyre::Report) {
    let mut chain = error.chain();
    if let Some(message) = chain.next() {
        eprintln!("error: {message}");
    }
    for cause in chain {
        eprintln!("  caused by: {cause}");
    }
}

async fn new_stream(api_url: Url, web_url: Url, args: NewArgs) -> eyre::Result<()> {
    let visibility = visibility_from_flags(args.public);
    let issue_tokens = if args.links.is_empty() {
        Some(new_default_links())
    } else {
        Some(args.links.iter().map(|access| access.0).collect())
    };

    let created = TsfClient::with_api_base_url(api_url)
        .create_stream(&CreateStreamRequest {
            visibility,
            retention_secs: args.retention.map(Into::into),
            issue_tokens,
        })
        .await
        .context("failed to create stream")?;
    write_token_files(&created.tokens, &args)?;
    print_created_stream(&web_url, &created, args.format, OutputTarget::Stdout)?;

    Ok(())
}

async fn write_stream(api_url: Url, web_url: Url, args: WriteArgs) -> eyre::Result<()> {
    validate_write_args(&args)?;
    let buffering = if args.raw {
        WriteBuffering::Raw
    } else {
        WriteBuffering::Lines
    };
    let command = args.command;
    let (stream_id, token, view_link) = if args.new {
        let visibility = visibility_from_flags(args.public);
        let created = TsfClient::with_api_base_url(api_url.clone())
            .create_stream(&CreateStreamRequest {
                visibility,
                retention_secs: args.retention.map(Into::into),
                issue_tokens: Some(write_new_default_links(visibility)),
            })
            .await
            .context("failed to create stream")?;
        print_created_stream(&web_url, &created, OutputFormat::Text, OutputTarget::Stderr)?;
        let token = created
            .tokens
            .iter()
            .find(|token| token.permissions.allows_write())
            .context("created stream did not include a write-capable link")?
            .token
            .clone();
        let view_link = if matches!(created.visibility, Visibility::Public) {
            Some(bare_stream_url(&web_url, &created.stream_id))
        } else {
            created
                .tokens
                .iter()
                .find(|issued| link_label(issued.permissions) == "view")
                .map(|issued| {
                    stream_url(
                        &web_url,
                        &created.stream_id,
                        issued.permissions,
                        &issued.token,
                    )
                })
        };
        (created.stream_id, token, view_link)
    } else {
        let url = args
            .url
            .context("write requires a stream URL unless --new is set")?;
        let locator = StreamLocator::parse(&url).context("invalid stream URL")?;
        let token = locator
            .token_with(TokenPermissions::allows_write)
            .context("URL does not grant write access")?
            .clone();
        (locator.stream_id, token, None)
    };

    if command.is_empty() {
        stream_stdin_to_writer(api_url, stream_id, token, buffering, view_link).await
    } else {
        stream_command_to_writer(api_url, stream_id, token, buffering, command, view_link).await
    }
}

fn print_write_summary(records: u64, view_link: Option<&Url>) {
    let noun = if records == 1 { "record" } else { "records" };
    match view_link {
        Some(url) => eprintln!("{records} {noun} durable · view {url}"),
        None => eprintln!("{records} {noun} durable"),
    }
}

fn validate_write_args(args: &WriteArgs) -> eyre::Result<()> {
    if args.new {
        return Ok(());
    }
    if args.public {
        bail!("--public requires --new");
    }
    if args.retention.is_some() {
        bail!("--retention requires --new");
    }
    if args.url.is_none() {
        bail!("write requires a stream URL unless --new is set");
    }
    Ok(())
}

async fn stream_stdin_to_writer(
    api_url: Url,
    stream_id: StreamId,
    token: BearerToken,
    buffering: WriteBuffering,
    view_link: Option<Url>,
) -> eyre::Result<()> {
    let client = TsfClient::with_api_base_url(api_url);
    let mut state = WriterState::new_random();
    let writer = client
        .connect_producer(WriteStreamOptions::with_stream_token(
            stream_id,
            state.writer_id(),
            &token,
        ))
        .await
        .context("failed to connect writer")?;

    let interrupted = match buffering {
        WriteBuffering::Raw => stream_raw_stdin_to_writer(&writer, &mut state).await,
        WriteBuffering::Lines => stream_lines_to_writer(&writer, &mut state).await,
    }?;
    writer.close().await.context("failed to close writer")?;
    print_write_summary(state.appended(), view_link.as_ref());
    if interrupted {
        exit_interrupted();
    }
    Ok(())
}

async fn stream_raw_stdin_to_writer(
    writer: &TsfProducer,
    state: &mut WriterState,
) -> eyre::Result<bool> {
    let mut stdin = tokio::io::stdin();
    let mut buffer = vec![0_u8; 16 * 1024];
    let mut appender = RawRecordAppender::new(RAW_LINGER);
    let mut session = WriterSession {
        writer,
        state,
        pending_tickets: VecDeque::new(),
    };
    let interrupted = loop {
        if let Some(deadline) = appender.deadline() {
            tokio::select! {
                byte_count = stdin.read(&mut buffer) => {
                    let byte_count = byte_count.context("failed to read stdin")?;
                    if byte_count == 0 {
                        break false;
                    }
                    appender.push_bytes(&mut session, &buffer[..byte_count]).await?;
                }
                _ = sleep_until(deadline) => {
                    appender.flush(&mut session).await?;
                }
                interrupt = tokio::signal::ctrl_c() => {
                    interrupt.context("failed to listen for interrupt signal")?;
                    break true;
                }
            }
        } else {
            let byte_count = tokio::select! {
                byte_count = stdin.read(&mut buffer) => byte_count.context("failed to read stdin")?,
                interrupt = tokio::signal::ctrl_c() => {
                    interrupt.context("failed to listen for interrupt signal")?;
                    break true;
                }
            };
            if byte_count == 0 {
                break false;
            }
            appender
                .push_bytes(&mut session, &buffer[..byte_count])
                .await?;
        };
    };
    appender.finish(&mut session).await?;
    session.finish().await?;

    Ok(interrupted)
}

async fn stream_lines_to_writer(
    writer: &TsfProducer,
    state: &mut WriterState,
) -> eyre::Result<bool> {
    let mut stdin = tokio::io::stdin();
    let mut read_buffer = vec![0_u8; 16 * 1024];
    let mut line_appender = LineRecordAppender::new();
    let mut session = WriterSession {
        writer,
        state,
        pending_tickets: VecDeque::new(),
    };

    let interrupted = loop {
        let byte_count = tokio::select! {
            byte_count = stdin.read(&mut read_buffer) => byte_count.context("failed to read stdin")?,
            interrupt = tokio::signal::ctrl_c() => {
                interrupt.context("failed to listen for interrupt signal")?;
                break true;
            }
        };
        if byte_count == 0 {
            break false;
        }

        line_appender
            .push_bytes(&mut session, &read_buffer[..byte_count])
            .await?;
    };

    line_appender.finish(&mut session).await?;
    session.finish().await?;

    Ok(interrupted)
}

async fn stream_command_to_writer(
    api_url: Url,
    stream_id: StreamId,
    token: BearerToken,
    buffering: WriteBuffering,
    command: Vec<String>,
    view_link: Option<Url>,
) -> eyre::Result<()> {
    let client = TsfClient::with_api_base_url(api_url);
    let mut state = WriterState::new_random();
    let writer = client
        .connect_producer(WriteStreamOptions::with_stream_token(
            stream_id,
            state.writer_id(),
            &token,
        ))
        .await
        .context("failed to connect writer")?;
    let outcome = {
        let mut session = WriterSession {
            writer: &writer,
            state: &mut state,
            pending_tickets: VecDeque::new(),
        };
        let outcome = stream_child_command_output(&mut session, buffering, command).await?;
        session.finish().await?;
        outcome
    };
    writer.close().await.context("failed to close writer")?;
    print_write_summary(state.appended(), view_link.as_ref());
    if outcome.interrupted {
        exit_interrupted();
    }
    if outcome.status.success() {
        Ok(())
    } else {
        exit_with_status(outcome.status)
    }
}

struct ChildCommandOutcome {
    status: ExitStatus,
    interrupted: bool,
}

async fn stream_child_command_output(
    session: &mut WriterSession<'_>,
    buffering: WriteBuffering,
    command: Vec<String>,
) -> eyre::Result<ChildCommandOutcome> {
    let program = command
        .first()
        .context("command mode requires a program after --")?;
    let mut child = TokioCommand::new(program)
        .args(&command[1..])
        .stdin(Stdio::inherit())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .with_context(|| format!("failed to spawn command {program:?}"))?;
    let stdout = child
        .stdout
        .take()
        .context("failed to capture child stdout")?;
    let stderr = child
        .stderr
        .take()
        .context("failed to capture child stderr")?;
    let (chunk_tx, mut chunk_rx) = mpsc::channel::<eyre::Result<Bytes>>(16);
    let stdout_task = tokio::spawn(read_child_pipe(stdout, chunk_tx.clone()));
    let stderr_task = tokio::spawn(read_child_pipe(stderr, chunk_tx));

    let stream_output = async {
        match buffering {
            WriteBuffering::Raw => stream_raw_chunks_to_writer(session, &mut chunk_rx).await?,
            WriteBuffering::Lines => {
                let mut line_appender = LineRecordAppender::new();
                while let Some(chunk) = chunk_rx.recv().await {
                    line_appender.push_bytes(session, &chunk?).await?;
                }
                line_appender.finish(session).await?;
            }
        }
        eyre::Result::<()>::Ok(())
    };
    tokio::pin!(stream_output);

    let (stream_result, interrupted) = tokio::select! {
        result = &mut stream_output => (result, false),
        interrupt = tokio::signal::ctrl_c() => {
            interrupt.context("failed to listen for interrupt signal")?;
            let _ = child.kill().await;
            (stream_output.await, true)
        }
    };

    if let Err(error) = stream_result {
        let _ = child.kill().await;
        stdout_task.abort();
        stderr_task.abort();
        let _ = stdout_task.await;
        let _ = stderr_task.await;
        return Err(error);
    }

    stdout_task.await.context("stdout reader task panicked")??;
    stderr_task.await.context("stderr reader task panicked")??;
    let status = child.wait().await.context("failed to wait for command")?;
    Ok(ChildCommandOutcome {
        status,
        interrupted,
    })
}

async fn read_child_pipe<R>(
    mut pipe: R,
    chunk_tx: mpsc::Sender<eyre::Result<Bytes>>,
) -> eyre::Result<()>
where
    R: AsyncRead + Unpin,
{
    let mut buffer = vec![0_u8; MAX_RECORD_BYTES];
    loop {
        let byte_count = pipe
            .read(&mut buffer)
            .await
            .context("failed to read command output")?;
        if byte_count == 0 {
            return Ok(());
        }
        if chunk_tx
            .send(Ok(Bytes::copy_from_slice(&buffer[..byte_count])))
            .await
            .is_err()
        {
            return Ok(());
        }
    }
}

struct RawRecordAppender {
    pending: BytesMut,
    deadline: Option<Instant>,
    linger: Duration,
}

impl RawRecordAppender {
    fn new(linger: Duration) -> Self {
        Self {
            pending: BytesMut::with_capacity(MAX_RECORD_BYTES),
            deadline: None,
            linger,
        }
    }

    fn deadline(&self) -> Option<Instant> {
        self.deadline
    }

    async fn push_bytes(
        &mut self,
        session: &mut WriterSession<'_>,
        mut bytes: &[u8],
    ) -> eyre::Result<()> {
        while !bytes.is_empty() {
            if self.pending.is_empty() {
                self.deadline = Some(Instant::now() + self.linger);
            }
            let available = MAX_RECORD_BYTES - self.pending.len();
            let take = available.min(bytes.len());
            self.pending.extend_from_slice(&bytes[..take]);
            bytes = &bytes[take..];
            if self.pending.len() == MAX_RECORD_BYTES {
                self.flush(session).await?;
            }
        }
        Ok(())
    }

    async fn flush(&mut self, session: &mut WriterSession<'_>) -> eyre::Result<()> {
        if self.pending.is_empty() {
            self.deadline = None;
            return Ok(());
        }
        let data = self.pending.split().freeze();
        self.deadline = None;
        session
            .append_physical_record(PartHeader::unsplit(), RecordFormat::Bytes, data)
            .await
    }

    async fn finish(&mut self, session: &mut WriterSession<'_>) -> eyre::Result<()> {
        self.flush(session).await
    }
}

async fn stream_raw_chunks_to_writer(
    session: &mut WriterSession<'_>,
    chunk_rx: &mut mpsc::Receiver<eyre::Result<Bytes>>,
) -> eyre::Result<()> {
    let mut appender = RawRecordAppender::new(RAW_LINGER);
    loop {
        if let Some(deadline) = appender.deadline() {
            tokio::select! {
                biased;
                chunk = chunk_rx.recv() => {
                    let Some(chunk) = chunk else {
                        break;
                    };
                    appender.push_bytes(session, &chunk?).await?;
                }
                _ = sleep_until(deadline) => {
                    appender.flush(session).await?;
                }
            }
        } else {
            let Some(chunk) = chunk_rx.recv().await else {
                break;
            };
            appender.push_bytes(session, &chunk?).await?;
        }
    }
    appender.finish(session).await
}

struct LineRecordAppender {
    pending: BytesMut,
    split_part_index: u32,
}

impl LineRecordAppender {
    fn new() -> Self {
        Self {
            pending: BytesMut::with_capacity(MAX_RECORD_BYTES),
            split_part_index: 0,
        }
    }

    async fn push_bytes(
        &mut self,
        session: &mut WriterSession<'_>,
        mut bytes: &[u8],
    ) -> eyre::Result<()> {
        while !bytes.is_empty() {
            if self.pending.len() == MAX_RECORD_BYTES {
                self.flush(session, false).await?;
            }

            let available = MAX_RECORD_BYTES - self.pending.len();
            let window_len = available.min(bytes.len());
            let window = &bytes[..window_len];
            let take = window
                .iter()
                .position(|byte| *byte == b'\n')
                .map_or(window_len, |index| index + 1);
            self.pending.extend_from_slice(&window[..take]);
            bytes = &bytes[take..];

            if self.pending.last() == Some(&b'\n') {
                self.flush(session, true).await?;
            }
        }
        Ok(())
    }

    async fn finish(&mut self, session: &mut WriterSession<'_>) -> eyre::Result<()> {
        if !self.pending.is_empty() {
            self.flush(session, true).await?;
        }
        Ok(())
    }

    async fn flush(&mut self, session: &mut WriterSession<'_>, is_final: bool) -> eyre::Result<()> {
        let data = self.pending.split().freeze();
        session
            .append_line_part(self.split_part_index, is_final, data)
            .await?;
        if is_final {
            self.split_part_index = 0;
        } else {
            self.split_part_index = self
                .split_part_index
                .checked_add(1)
                .context("line split part index overflowed")?;
        }
        Ok(())
    }
}

struct WriterSession<'a> {
    writer: &'a TsfProducer,
    state: &'a mut WriterState,
    pending_tickets: VecDeque<AppendTicket>,
}

impl WriterSession<'_> {
    async fn append_line_part(
        &mut self,
        part_index: u32,
        is_final: bool,
        data: Bytes,
    ) -> eyre::Result<()> {
        let part = if part_index == 0 && is_final {
            PartHeader::unsplit()
        } else {
            PartHeader::new(part_index, is_final).context("failed to encode split part")?
        };
        self.append_physical_record(part, RecordFormat::Transcript, data)
            .await
    }

    async fn append_physical_record(
        &mut self,
        part: PartHeader,
        format: RecordFormat,
        data: Bytes,
    ) -> eyre::Result<()> {
        let writer_seq_num = self
            .state
            .reserve_writer_seq()
            .context("failed to reserve writer sequence")?;
        let record = WriteRecord::new(writer_seq_num, part, format, data);
        let ticket = self
            .writer
            .submit(record)
            .await
            .context("failed to submit record")?;
        self.pending_tickets.push_back(ticket);
        self.drain_ready_tickets()
    }

    async fn finish(&mut self) -> eyre::Result<()> {
        while let Some(ticket) = self.pending_tickets.pop_front() {
            ticket.await.context("failed to append record")?;
        }
        Ok(())
    }

    fn drain_ready_tickets(&mut self) -> eyre::Result<()> {
        loop {
            let Some(result) = self
                .pending_tickets
                .front_mut()
                .and_then(AppendTicket::try_recv)
            else {
                return Ok(());
            };
            result.context("failed to append record")?;
            self.pending_tickets.pop_front();
        }
    }
}

async fn tail_stream(api_url: Url, args: TailArgs) -> eyre::Result<()> {
    ensure_single_selector(args.seq_num, args.timestamp)?;
    let locator = StreamLocator::parse(&args.url).context("invalid stream URL")?;
    let mut request = ReadStreamOptions::new(locator.stream_id);
    request.start = Some(if let Some(seq_num) = args.seq_num {
        ReadStart::SeqNum(seq_num)
    } else if let Some(timestamp) = args.timestamp {
        ReadStart::TimestampMs(timestamp)
    } else {
        ReadStart::TailOffset(args.tail_offset.unwrap_or_default())
    });
    request.count = args.count;
    if let Some(token) = locator.token_with(TokenPermissions::allows_read) {
        request = request.with_stream_token(token);
    }

    read_transcript(api_url, request, args.max_logical_record_bytes).await
}

async fn replay_stream(api_url: Url, args: ReplayArgs) -> eyre::Result<()> {
    ensure_single_selector(args.seq_num, args.timestamp)?;
    let locator = StreamLocator::parse(&args.url).context("invalid stream URL")?;
    if args.count == Some(0) {
        return Ok(());
    }
    let read_token = locator.token_with(TokenPermissions::allows_read);
    let read_client = if let Some(token) = read_token {
        TsfClient::with_api_base_url_and_rest_bearer_token(api_url.clone(), token.expose_secret())
    } else {
        TsfClient::with_api_base_url(api_url.clone())
    };
    let tail = read_client
        .get_stream_tail(&locator.stream_id)
        .await
        .context("failed to check stream tail")?;
    if tail.next_s2_seq_num == 0 {
        return Ok(());
    }

    let mut request = ReadStreamOptions::new(locator.stream_id);
    request.start = Some(if let Some(seq_num) = args.seq_num {
        ReadStart::SeqNum(seq_num)
    } else if let Some(timestamp) = args.timestamp {
        ReadStart::TimestampMs(timestamp)
    } else {
        ReadStart::SeqNum(0)
    });
    request.until = Some(tail.next_s2_seq_num - 1);
    request.count = args
        .count
        .or_else(|| replay_count_from_tail(&request, tail.next_s2_seq_num));
    if let Some(token) = read_token {
        request = request.with_stream_token(token);
    }

    read_transcript(api_url, request, args.max_logical_record_bytes).await
}

async fn stream_info(api_url: Url, args: InfoArgs) -> eyre::Result<()> {
    let locator = StreamLocator::parse(&args.url).context("invalid stream URL")?;
    let client = if let Some(token) = locator.token.as_ref() {
        TsfClient::with_api_base_url_and_rest_bearer_token(api_url, token.token.expose_secret())
    } else {
        TsfClient::with_api_base_url(api_url)
    };
    let stream = client
        .get_stream(&locator.stream_id)
        .await
        .context("failed to get stream")?;
    print_stream_info(&stream, args.format)
}

async fn delete_stream(api_url: Url, args: OwnerUrlArgs) -> eyre::Result<()> {
    let (client, locator) = owner_client_from_url(api_url, &args.url)?;
    client
        .delete_stream(&locator.stream_id)
        .await
        .context("failed to delete stream")?;
    Ok(())
}

async fn update_visibility(api_url: Url, args: VisibilityArgs) -> eyre::Result<()> {
    let (client, locator) = owner_client_from_url(api_url, &args.url)?;
    let stream = client
        .update_stream(
            &locator.stream_id,
            &UpdateStreamRequest {
                visibility: Some(args.visibility.into()),
            },
        )
        .await
        .context("failed to update stream visibility")?;
    print_stream_info(&stream, args.format)?;
    Ok(())
}

async fn link_command(api_url: Url, web_url: Url, args: LinkArgs) -> eyre::Result<()> {
    match args.command {
        LinkCommand::List(args) => list_links(api_url, args).await,
        LinkCommand::Issue(args) => issue_link(api_url, web_url, args).await,
        LinkCommand::Revoke(args) => revoke_link(api_url, args).await,
    }
}

async fn list_links(api_url: Url, args: ListLinkArgs) -> eyre::Result<()> {
    let (client, locator) = owner_client_from_url(api_url, &args.url)?;
    let response = client
        .list_tokens(&locator.stream_id)
        .await
        .context("failed to list links")?;
    match args.format {
        OutputFormat::Text => {
            for token in response.tokens {
                println!(
                    "{:<10}  {:<7}  expires {:<24}  id {}{}",
                    link_label(token.permissions),
                    token_status_label(token.status),
                    token.expires_at.as_deref().unwrap_or("never"),
                    token.token_id,
                    if token.is_current { "  (current)" } else { "" }
                );
            }
        }
        OutputFormat::Json => println!("{}", serde_json::to_string_pretty(&response)?),
    }
    Ok(())
}

fn token_status_label(status: StreamTokenStatus) -> &'static str {
    match status {
        StreamTokenStatus::Active => "active",
        StreamTokenStatus::Expired => "expired",
        StreamTokenStatus::Revoked => "revoked",
    }
}

async fn issue_link(api_url: Url, web_url: Url, args: IssueLinkArgs) -> eyre::Result<()> {
    let (client, locator) = owner_client_from_url(api_url, &args.url)?;
    let issued = client
        .issue_token(
            &locator.stream_id,
            &IssueTokenRequest {
                permissions: args.access.0,
                expires_at: args.expires.rfc3339(),
            },
        )
        .await
        .context("failed to issue link")?;
    if let Some(path) = &args.token_file {
        write_secret_file(path, issued.token.expose_secret())
            .with_context(|| format!("failed to write token file {}", path.display()))?;
    }
    print_issued_token(&web_url, &locator.stream_id, &issued, args.format)?;
    Ok(())
}

async fn revoke_link(api_url: Url, args: RevokeLinkArgs) -> eyre::Result<()> {
    let (client, locator) = owner_client_from_url(api_url, &args.url)?;
    client
        .revoke_token(&locator.stream_id, &args.token_id)
        .await
        .context("failed to revoke link")?;
    Ok(())
}

async fn read_transcript(
    api_url: Url,
    options: ReadStreamOptions,
    max_logical_record_bytes: usize,
) -> eyre::Result<()> {
    if options.count == Some(0) {
        return Ok(());
    }

    let client = TsfClient::with_api_base_url(api_url);
    let mut transcript = LogicalTranscript::with_max_logical_record_bytes(max_logical_record_bytes);
    let mut stdout = tokio::io::stdout();
    let mut reader = client
        .connect_reader(options)
        .await
        .context("failed to connect reader")?;

    while let Some(record) = tokio::select! {
        record = reader.next_record() => record.context("failed to read stream")?,
        interrupt = tokio::signal::ctrl_c() => {
            interrupt.context("failed to listen for interrupt signal")?;
            exit_interrupted();
        }
    } {
        let record = transcript
            .push_record(record)
            .context("failed to assemble transcript record")?;
        write_transcript_record(&mut stdout, record).await?;
    }

    Ok(())
}

async fn write_transcript_record(
    stdout: &mut tokio::io::Stdout,
    record: Option<TranscriptRecord>,
) -> eyre::Result<()> {
    if let Some(record) = record {
        write_transcript_data(stdout, record.data).await?;
    }
    Ok(())
}

async fn write_transcript_data(
    stdout: &mut tokio::io::Stdout,
    mut data: impl Buf,
) -> eyre::Result<()> {
    while data.has_remaining() {
        let chunk = data.chunk();
        let chunk_len = chunk.len();
        if chunk_len == 0 {
            bail!("transcript data returned an empty chunk before EOF");
        }
        stdout
            .write_all(chunk)
            .await
            .context("failed to write stdout")?;
        data.advance(chunk_len);
    }
    stdout.flush().await.context("failed to flush stdout")?;
    Ok(())
}

fn parse_url(url: &str) -> eyre::Result<()> {
    let locator = StreamLocator::parse(url).context("invalid stream URL")?;
    let output = ParsedUrlOutput {
        stream_id: locator.stream_id.to_string(),
        tokens: locator
            .token
            .iter()
            .map(|token| ParsedTokenOutput {
                permissions: token.permissions.to_string(),
                token_present: true,
            })
            .collect(),
    };

    println!("{}", serde_json::to_string_pretty(&output)?);
    Ok(())
}

fn owner_client_from_url(api_url: Url, url: &str) -> eyre::Result<(TsfClient, StreamLocator)> {
    let locator = StreamLocator::parse(url).context("invalid stream URL")?;
    let owner_token = locator
        .token_with(TokenPermissions::allows_owner)
        .context("URL does not grant owner access")?;
    let client =
        TsfClient::with_api_base_url_and_rest_bearer_token(api_url, owner_token.expose_secret());
    Ok((client, locator))
}

fn print_created_stream(
    web_url: &Url,
    created: &CreateStreamResponse,
    format: OutputFormat,
    target: OutputTarget,
) -> eyre::Result<()> {
    match format {
        OutputFormat::Text => {
            target.print_line(&format!(
                "Created {} stream {}",
                visibility_label(created.visibility),
                created.stream_id
            ));
            target.print_line(&format!(
                "Retention: {}",
                humanize_retention(created.retention_secs)
            ));
            let mut links = created
                .tokens
                .iter()
                .map(|issued| {
                    (
                        link_label(issued.permissions),
                        stream_url(
                            web_url,
                            &created.stream_id,
                            issued.permissions,
                            &issued.token,
                        ),
                        if issued.permissions.to_string() == "o" {
                            "  (keep private)"
                        } else {
                            ""
                        },
                    )
                })
                .collect::<Vec<_>>();
            if matches!(created.visibility, Visibility::Public) {
                links.push((
                    "view",
                    bare_stream_url(web_url, &created.stream_id),
                    "  (public)",
                ));
            }
            if !links.is_empty() {
                target.print_line("");
                links.sort_by_key(|(label, _, _)| link_rank(label));
                let width = links
                    .iter()
                    .map(|(label, _, _)| label.len())
                    .max()
                    .unwrap_or(0);
                for (label, url, suffix) in &links {
                    target.print_line(&format!("  {label:<width$}  {url}{suffix}"));
                }
                target.print_line("");
                target.print_line("Links are shown once.");
            }
        }
        OutputFormat::Json => {
            let output = CreatedStreamOutput {
                stream_id: created.stream_id.to_string(),
                visibility: visibility_label(created.visibility),
                retention_secs: created.retention_secs,
                urls: created
                    .tokens
                    .iter()
                    .map(|issued| {
                        (
                            issued.permissions.to_string(),
                            stream_url(
                                web_url,
                                &created.stream_id,
                                issued.permissions,
                                &issued.token,
                            )
                            .to_string(),
                        )
                    })
                    .collect(),
            };
            target.print_line(&serde_json::to_string_pretty(&output)?);
        }
    }
    Ok(())
}

fn print_stream_info(stream: &StreamInfoResponse, format: OutputFormat) -> eyre::Result<()> {
    match format {
        OutputFormat::Text => {
            println!("Stream {}", stream.stream_id);
            println!("Visibility: {}", visibility_label(stream.visibility));
            println!("State: {}", stream.state);
            println!("Retention: {}", humanize_retention(stream.retention_secs));
            println!("Active links: {}", stream.active_token_count);
        }
        OutputFormat::Json => {
            println!("{}", serde_json::to_string_pretty(stream)?);
        }
    }
    Ok(())
}

fn print_issued_token(
    web_url: &Url,
    stream_id: &StreamId,
    issued: &IssueTokenResponse,
    format: OutputFormat,
) -> eyre::Result<()> {
    let url = stream_url(web_url, stream_id, issued.permissions, &issued.token);
    match format {
        OutputFormat::Text => {
            println!("Issued {} link", link_label(issued.permissions));
            println!("  url  {url}");
            println!("  id   {}", issued.token_id);
            println!("Link is shown once. Revoke it with the id above.");
        }
        OutputFormat::Json => {
            let output = IssuedTokenOutput {
                token_id: issued.token_id.to_string(),
                permissions: issued.permissions.to_string(),
                token: issued.token.expose_secret().to_owned(),
                url: url.to_string(),
            };
            println!("{}", serde_json::to_string_pretty(&output)?);
        }
    }
    Ok(())
}

fn write_token_files(tokens: &[IssuedStreamToken], args: &NewArgs) -> eyre::Result<()> {
    write_token_file(
        &args.owner_token_file,
        tokens,
        TokenPermissions::allows_owner,
        "owner",
    )?;
    write_token_file(
        &args.view_token_file,
        tokens,
        TokenPermissions::allows_read,
        "view",
    )?;
    write_token_file(
        &args.write_token_file,
        tokens,
        TokenPermissions::allows_write,
        "write",
    )?;
    Ok(())
}

fn write_token_file(
    path: &Option<PathBuf>,
    tokens: &[IssuedStreamToken],
    allows: impl Fn(TokenPermissions) -> bool,
    label: &str,
) -> eyre::Result<()> {
    let Some(path) = path else {
        return Ok(());
    };
    let token = tokens
        .iter()
        .find(|token| allows(token.permissions))
        .with_context(|| format!("created stream did not include a {label} token"))?;
    write_secret_file(path, token.token.expose_secret())
        .with_context(|| format!("failed to write {label} token file {}", path.display()))?;
    Ok(())
}

fn write_secret_file(path: &Path, secret: &str) -> std::io::Result<()> {
    let mut options = OpenOptions::new();
    options.write(true).create(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt as _;

        options.mode(0o600);
    }
    let mut file = options.open(path)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt as _;

        file.set_permissions(std::fs::Permissions::from_mode(0o600))?;
    }
    file.set_len(0)?;
    std::io::Write::write_all(&mut file, secret.as_bytes())
}

fn new_default_links() -> Vec<TokenPermissions> {
    vec![TokenPermissions::owner()]
}

fn write_new_default_links(visibility: Visibility) -> Vec<TokenPermissions> {
    match visibility {
        Visibility::Private => vec![TokenPermissions::owner(), TokenPermissions::read()],
        Visibility::Public => vec![TokenPermissions::owner()],
    }
}

fn visibility_from_flags(public: bool) -> Visibility {
    if public {
        Visibility::Public
    } else {
        Visibility::Private
    }
}

fn visibility_label(visibility: Visibility) -> &'static str {
    match visibility {
        Visibility::Private => "private",
        Visibility::Public => "public",
    }
}

fn bare_stream_url(base_url: &Url, stream_id: &StreamId) -> Url {
    let mut url = base_url.clone();
    url.set_path(&format!("/s/{stream_id}"));
    url.set_query(None);
    url.set_fragment(None);
    url
}

fn link_label(permissions: TokenPermissions) -> &'static str {
    match permissions.to_string().as_str() {
        "o" => "owner",
        "r" => "view",
        "w" => "write",
        "rw" => "view+write",
        _ => "link",
    }
}

fn link_rank(label: &str) -> usize {
    match label {
        "view" => 0,
        "write" => 1,
        "view+write" => 2,
        "owner" => 3,
        _ => 4,
    }
}

fn humanize_retention(secs: u64) -> String {
    if secs == u64::MAX {
        return "infinite".to_owned();
    }
    const MINUTE: u64 = 60;
    const HOUR: u64 = 60 * MINUTE;
    const DAY: u64 = 24 * HOUR;
    let unit =
        |count: u64, name: &str| format!("{count} {name}{}", if count == 1 { "" } else { "s" });
    if secs >= DAY && secs.is_multiple_of(DAY) {
        return unit(secs / DAY, "day");
    }
    if secs >= HOUR && secs.is_multiple_of(HOUR) {
        return unit(secs / HOUR, "hour");
    }
    if secs >= MINUTE && secs.is_multiple_of(MINUTE) {
        return unit(secs / MINUTE, "minute");
    }
    unit(secs, "second")
}

fn ensure_single_selector(seq_num: Option<u64>, timestamp: Option<u64>) -> eyre::Result<()> {
    if seq_num.is_some() && timestamp.is_some() {
        bail!("only one of --seq-num or --timestamp can be set");
    }
    Ok(())
}

fn replay_count_from_tail(options: &ReadStreamOptions, next_s2_seq_num: u64) -> Option<u64> {
    match options.start {
        Some(ReadStart::SeqNum(seq_num)) => Some(next_s2_seq_num.saturating_sub(seq_num)),
        None => Some(next_s2_seq_num),
        Some(ReadStart::TimestampMs(_) | ReadStart::TailOffset(_)) => None,
    }
}

fn exit_with_status(status: ExitStatus) -> ! {
    std::process::exit(exit_code_from_status(status));
}

fn exit_interrupted() -> ! {
    std::process::exit(INTERRUPT_EXIT_CODE);
}

fn exit_code_from_status(status: ExitStatus) -> i32 {
    status.code().unwrap_or_else(|| {
        #[cfg(unix)]
        {
            use std::os::unix::process::ExitStatusExt;
            status.signal().map(|signal| 128 + signal).unwrap_or(1)
        }
        #[cfg(not(unix))]
        {
            1
        }
    })
}

#[derive(Clone, Copy)]
enum OutputTarget {
    Stdout,
    Stderr,
}

impl OutputTarget {
    fn print_line(self, line: &str) {
        match self {
            Self::Stdout => println!("{line}"),
            Self::Stderr => eprintln!("{line}"),
        }
    }
}

#[derive(Serialize)]
struct CreatedStreamOutput {
    stream_id: String,
    visibility: &'static str,
    retention_secs: u64,
    urls: BTreeMap<String, String>,
}

#[derive(Serialize)]
struct IssuedTokenOutput {
    token_id: String,
    permissions: String,
    token: String,
    url: String,
}

#[derive(Serialize)]
struct ParsedUrlOutput {
    stream_id: String,
    tokens: Vec<ParsedTokenOutput>,
}

#[derive(Serialize)]
struct ParsedTokenOutput {
    permissions: String,
    token_present: bool,
}

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

    #[test]
    fn classifies_wrapped_broken_pipes_only() {
        let broken_pipe: eyre::Report =
            std::io::Error::new(ErrorKind::BrokenPipe, "closed consumer").into();
        assert!(is_broken_pipe(
            &broken_pipe.wrap_err("failed to write stdout")
        ));

        let connection_reset: eyre::Report =
            std::io::Error::new(ErrorKind::ConnectionReset, "reset consumer").into();
        assert!(!is_broken_pipe(&connection_reset));
    }
}