fuel-telemetry 0.1.1

A tracing library to implement Fuel telemetry
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
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
pub mod errors;
pub mod file_watcher;
pub mod process_watcher;
pub mod systeminfo_watcher;
pub mod telemetry_formatter;
pub mod telemetry_layer;

pub use errors::{into_fatal, into_recoverable, TelemetryError, WatcherError};
pub use fuel_telemetry_macros::{new, new_with_watchers, new_with_watchers_and_init};
pub use telemetry_formatter::TelemetryFormatter;
pub use telemetry_layer::TelemetryLayer;
pub use tracing::{debug, error, event, info, span, trace, warn, Level};
pub use tracing_appender::non_blocking::WorkerGuard;

pub mod prelude {
    pub use crate::{
        debug, debug_telemetry, error, error_telemetry, event, info, info_telemetry, span,
        span_telemetry, trace, trace_telemetry, warn, warn_telemetry, Level, TelemetryLayer,
    };
}

// Re-export tracing so proc_macros can use them
pub use tracing as __reexport_tracing;
pub use tracing_subscriber as __reexport_tracing_subscriber;
pub use tracing_subscriber::filter::EnvFilter as __reexport_EnvFilter;
pub use tracing_subscriber::prelude::__tracing_subscriber_SubscriberExt as __reexport_tracing_subscriber_SubscriberExt;
pub use tracing_subscriber::util::SubscriberInitExt as __reexport_SubscriberInitExt;
pub use tracing_subscriber::Layer as __reexport_Layer;

use dirs::home_dir;
use libc::{c_int, c_long};
use nix::{
    errno::Errno,
    fcntl::{Flock, FlockArg},
    sys::stat,
    unistd::{
        chdir, close, dup2, fork, getpid, pipe, read, setsid, sysconf, write, ForkResult, Pid,
        SysconfVar,
    },
};
use std::{
    env::{current_exe, var, var_os},
    fs::{create_dir_all, File, OpenOptions},
    io::{stderr, stdout, Write},
    os::fd::{AsRawFd, OwnedFd},
    path::{Path, PathBuf},
    process::exit,
    sync::LazyLock,
};

// We need to close all file descriptors in `daemonise()`, but need to skip the
// first three (0 = STDIN, 1 = STDOUT, 2 = STDERR) as we deal with stdio later
const FIRST_NON_STDIO_FD: i32 = 3;

// The lowest maximum file descriptor across Legacy Linux and MacOS
const MIN_OPEN_MAX: i32 = 1024;

// Result type for the crate
pub type Result<T> = std::result::Result<T, TelemetryError>;

// Result type from Watchers
pub type WatcherResult<T> = std::result::Result<T, WatcherError>;

//
// Crate static configuration
//

/// A helper struct to get environment variables with a default value
pub struct EnvSetting {
    /// The name of the environment variable
    name: &'static str,
    /// The default value of the environment variable
    default: &'static str,
}

impl EnvSetting {
    /// Creates a new `EnvSetting`
    ///
    /// This function creates a new `EnvSetting` with the given name and default value.
    ///
    /// ```rust
    /// use fuel_telemetry::EnvSetting;
    ///
    /// let env_setting = EnvSetting::new("FUELUP_HOME", ".fuelup");
    /// ```
    pub fn new(name: &'static str, default: &'static str) -> Self {
        Self { name, default }
    }

    /// Gets the environment variable with a default value
    ///
    /// This function gets the environment variable with a default value.
    ///
    /// ```rust
    /// use fuel_telemetry::EnvSetting;
    ///
    /// let env_setting = EnvSetting::new("FUELUP_HOME", ".fuelup");
    /// let fuelup_home = env_setting.get();
    /// ```
    pub fn get(&self) -> String {
        var(self.name).unwrap_or_else(|_| self.default.to_string())
    }
}

/// Telemetry's global configuration
///
/// This struct contains the configuration for telemetry, to be used here and
/// within its underlying modules.
pub struct TelemetryConfig {
    // The path to the fuelup tmp directory
    fuelup_tmp: String,
    // The path to the fuelup log directory
    fuelup_log: String,
}

/// Get the global telemetry configuration
///
/// This function returns the global `'static` telemetry configuration.
///
/// ```rust
/// use fuel_telemetry::telemetry_config;
///
/// let telemetry_config = telemetry_config();
/// ```
pub fn telemetry_config() -> Result<&'static TelemetryConfig> {
    // Note: because we are using LazyLock, we cannot mock this function
    // using helpers as they cannot be evaluated as non-const.
    pub static TELEMETRY_CONFIG: LazyLock<Result<TelemetryConfig>> = LazyLock::new(|| {
        let fuelup_home_env = EnvSetting {
            name: "FUELUP_HOME",
            default: ".fuelup",
        };

        let fuelup_tmp_env = EnvSetting {
            name: "FUELUP_TMP",
            default: "tmp",
        };

        let fuelup_log_env = EnvSetting {
            name: "FUELUP_LOG",
            default: "log",
        };

        // Tries to set the fuelup home directory from the environment, falling
        // back to the $HOME/.fuelup
        let fuelup_home = var_os(fuelup_home_env.name)
            .map(PathBuf::from)
            .or_else(|| home_dir().map(|dir| dir.join(fuelup_home_env.default)))
            .ok_or(TelemetryError::UnreachableHomeDir)?
            .into_os_string()
            .into_string()
            .map_err(|e| TelemetryError::InvalidHomeDir(e.to_string_lossy().into()))?;

        // Tries to set the fuelup tmp directory from the environment, falling
        // back to $FUELUP_HOME/tmp
        let fuelup_tmp = var_os(fuelup_tmp_env.name)
            .unwrap_or_else(|| {
                PathBuf::from(fuelup_home.clone())
                    .join(fuelup_tmp_env.default)
                    .into_os_string()
            })
            .into_string()
            .map_err(|e| TelemetryError::InvalidTmpDir(e.to_string_lossy().into()))?;

        // Tries to set the fuelup log directory from the environment, falling
        // back to $FUELUP_HOME/log
        let fuelup_log = var_os(fuelup_log_env.name)
            .unwrap_or_else(|| {
                PathBuf::from(fuelup_home.clone())
                    .join(fuelup_log_env.default)
                    .into_os_string()
            })
            .into_string()
            .map_err(|e| TelemetryError::InvalidLogDir(e.to_string_lossy().into()))?;

        // Create the fuelup tmp and log directories if they don't exist
        create_dir_all(&fuelup_tmp)?;
        create_dir_all(&fuelup_log)?;

        Ok(TelemetryConfig {
            fuelup_tmp,
            fuelup_log,
        })
    });

    TELEMETRY_CONFIG
        .as_ref()
        .map_err(|e| TelemetryError::InvalidConfig(e.to_string()))
}

//
// Convenience Macros
//

/// Enter a temporary `Span`, then generates an `Event` with telemetry enabled
///
/// Note: The `Span` name is currently hardcoded to "auto" as `tracing::span!`
/// requires the name to be `const` as internally it is evaluated as a static,
/// however getting the caller's function name in statics is experimental.
///
/// ```rust
/// use fuel_telemetry::prelude::*;
///
/// span_telemetry!(Level::INFO, "This event will be sent to InfluxDB");
/// ```
#[macro_export]
macro_rules! span_telemetry {
    ($level:expr, $($arg:tt)*) => {
        $crate::__reexport_tracing::span!($level, "auto", telemetry = true).in_scope(|| {
            $crate::__reexport_tracing::event!($level, $($arg)*)
        })
    }
}

/// Generate an `ERROR` telemetry `Event`
///
/// ```rust
/// use fuel_telemetry::prelude::*;
///
/// error_telemetry!("This error event will be sent to InfluxDB");
/// ```
#[macro_export]
macro_rules! error_telemetry {
    ($($arg:tt)*) => {{
        span_telemetry!($crate::__reexport_tracing::Level::ERROR, $($arg)*);
    }}
}

/// Generate a `WARN` telemetry `Event`
///
/// ```rust
/// use fuel_telemetry::prelude::*;
///
/// warn_telemetry!("This warn event will be sent to InfluxDB");
/// ```
#[macro_export]
macro_rules! warn_telemetry {
    ($($arg:tt)*) => {{
        span_telemetry!($crate::__reexport_tracing::Level::WARN, $($arg)*);
    }}
}

/// Generate an `INFO` telemetry `Event`
///
/// ```rust
/// use fuel_telemetry::prelude::*;
///
/// info_telemetry!("This info event will be sent to InfluxDB");
/// ```
#[macro_export]
macro_rules! info_telemetry {
    ($($arg:tt)*) => {{
        span_telemetry!($crate::__reexport_tracing::Level::INFO, $($arg)*);
    }}
}

/// Generate a `DEBUG` telemetry `Event`
///
/// ```rust
/// use fuel_telemetry::prelude::*;
///
/// debug_telemetry!("This debug event will be sent to InfluxDB");
/// ```
#[macro_export]
macro_rules! debug_telemetry {
    ($($arg:tt)*) => {{
        span_telemetry!($crate::__reexport_tracing::Level::DEBUG, $($arg)*);
    }}
}

/// Generate a `TRACE` telemetry `Event`
///
/// ```rust
/// use fuel_telemetry::prelude::*;
///
/// trace_telemetry!("This trace event will be sent to InfluxDB");
/// ```
#[macro_export]
macro_rules! trace_telemetry {
    ($($arg:tt)*) => {{
        span_telemetry!($crate::__reexport_tracing::Level::TRACE, $($arg)*);
    }}
}

/// Helper function to get the current process' binary filename
pub fn get_process_name() -> String {
    let mut exe_name = String::from("unknown");

    if let Ok(exe) = current_exe() {
        if let Some(name) = exe.file_name() {
            if let Some(name_str) = name.to_str() {
                exe_name = name_str.to_string().replace(':', "_");
            }
        }
    }

    exe_name
}

/// Enforce a singleton by taking an advisory lock on a file
///
/// This function takes an advisory lock on a file, and if another process has
/// already locked the file, it will exit the current process.
pub(crate) fn enforce_singleton(filename: &Path) -> Result<Flock<File>> {
    enforce_singleton_with_helpers(filename, &mut DefaultEnforceSingletonHelpers)
}

fn enforce_singleton_with_helpers(
    filename: &Path,
    helpers: &mut impl EnforceSingletonHelpers,
) -> Result<Flock<File>> {
    let lockfile = helpers.open(filename)?;

    let lock = match helpers.lock(lockfile) {
        Ok(lock) => lock,
        Err((_, Errno::EWOULDBLOCK)) => {
            // Silently exit as another process has already locked the file
            helpers.exit(0);
        }
        Err((_, e)) => return Err(TelemetryError::from(e)),
    };

    Ok(lock)
}

trait EnforceSingletonHelpers {
    fn open(&self, filename: &Path) -> std::result::Result<File, std::io::Error> {
        OpenOptions::new().create(true).append(true).open(filename)
    }

    fn lock(&self, file: File) -> std::result::Result<Flock<File>, (File, Errno)> {
        Flock::lock(file, FlockArg::LockExclusiveNonblock)
    }

    fn exit(&self, status: i32) -> ! {
        exit(status)
    }
}

struct DefaultEnforceSingletonHelpers;
impl EnforceSingletonHelpers for DefaultEnforceSingletonHelpers {}

/// Daemonise the current process
///
/// This function forks and has the parent immediately return. The forked off
/// child then follows the common "double-fork" method of daemonising.
pub(crate) fn daemonise(log_filename: &PathBuf) -> WatcherResult<Option<Pid>> {
    let mut helpers = DefaultDaemoniseHelpers;
    daemonise_with_helpers(log_filename, &mut helpers)
}

fn daemonise_with_helpers(
    log_filename: &PathBuf,
    helpers: &mut impl DaemoniseHelpers,
) -> WatcherResult<Option<Pid>> {
    // All errors before the first fork() are recoverable from the caller,
    // meaning that the error occured within the same process and should be
    // ignored by the caller so that it can continue

    helpers.flush(&mut stdout()).map_err(into_recoverable)?;
    helpers.flush(&mut stderr()).map_err(into_recoverable)?;

    let (read_fd, write_fd) = helpers.pipe().map_err(into_recoverable)?;

    // Return if we are the parent
    if helpers.fork().map_err(into_recoverable)?.is_parent() {
        drop(write_fd);

        let mut pid_bytes = [0u8; std::mem::size_of::<Pid>()];
        helpers
            .read_pipe(read_fd, &mut pid_bytes)
            .map_err(into_recoverable)?;

        return Ok(Some(Pid::from_raw(i32::from_ne_bytes(pid_bytes))));
    };

    drop(read_fd);

    // From here on, we are no longer the original process, so the caller should
    // treat errors as fatal. This means that on error the process should exit
    // immediately as there should not be two identical flows of execution

    // To prevent us from becoming a zombie when we die, we fork then kill the
    // parent so that we are immediately inherited by init/systemd. Doing so, we
    // are guaranteed to be reaped on exit.
    //
    // Also, doing this guarantees that we are not the group leader, which is
    // required to create a new session (i.e setsid() will fail otherwise)
    if helpers.fork().map_err(into_fatal)?.is_parent() {
        drop(write_fd);
        exit(0);
    }

    // Creating a new session means we won't receive signals to the original
    // group or session (e.g. hitting CTRL-C to break a command pipeline)
    helpers.setsid().map_err(into_fatal)?;

    // As session leader, we now fork then follow the child again to guarantee
    // we cannot re-acquire a terminal
    if helpers.fork().map_err(into_fatal)?.is_parent() {
        drop(write_fd);
        exit(0);
    }

    let pid = getpid();
    helpers.write_pipe(write_fd, pid).map_err(into_fatal)?;

    // Setup stdio to write errors to the logfile while discarding any IO to
    // the controlling terminal
    let fuelup_tmp = helpers
        .telemetry_config()
        .map_err(into_fatal)?
        .fuelup_tmp
        .clone();

    helpers.setup_stdio(
        Path::new(&fuelup_tmp)
            .join(log_filename)
            .to_str()
            .ok_or(TelemetryError::InvalidLogFile(
                fuelup_tmp.clone(),
                log_filename.clone(),
            ))
            .map_err(into_fatal)?,
    )?;

    // The current working directory needs to be set to root so that we don't
    // prevent any unmounting of the filesystem leading up to the directory we
    // started in
    helpers.chdir(Path::new("/")).map_err(into_fatal)?;

    // We close all file descriptors since any currently opened were inherited
    // from the parent process which we don't care about. Not doing so leaks
    // open file descriptors which could lead to exhaustion.
    let max_fd = helpers
        .sysconf(SysconfVar::OPEN_MAX)
        .map_err(into_fatal)?
        .unwrap_or(MIN_OPEN_MAX.into()) as i32;

    for fd in FIRST_NON_STDIO_FD..=max_fd {
        match helpers.close(fd) {
            Ok(()) | Err(Errno::EBADF) => {}
            Err(e) => Err(into_fatal(e))?,
        }
    }

    // Clear the umask so that files we create aren't too permission-restricive
    stat::umask(stat::Mode::empty());

    Ok(None)
}

trait DaemoniseHelpers {
    fn flush<T: Write + std::os::fd::AsRawFd>(
        &mut self,
        stream: &mut T,
    ) -> std::result::Result<(), std::io::Error> {
        stream.flush()
    }

    fn pipe(&mut self) -> nix::Result<(OwnedFd, OwnedFd)> {
        pipe()
    }

    fn read_pipe(&mut self, read_fd: OwnedFd, pid_bytes: &mut [u8]) -> nix::Result<usize> {
        read(read_fd.as_raw_fd(), pid_bytes)
    }

    fn fork(&mut self) -> nix::Result<ForkResult> {
        unsafe { fork() }
    }

    fn setsid(&self) -> nix::Result<Pid> {
        setsid()
    }

    fn write_pipe(&mut self, write_fd: OwnedFd, pid: Pid) -> nix::Result<usize> {
        write(write_fd, &pid.as_raw().to_ne_bytes())
    }

    fn telemetry_config(&mut self) -> Result<&'static TelemetryConfig> {
        telemetry_config()
    }

    fn setup_stdio(&self, log_filename: &str) -> std::result::Result<(), TelemetryError> {
        setup_stdio(log_filename)
    }

    fn chdir(&self, path: &Path) -> nix::Result<()> {
        chdir(path)
    }

    fn sysconf(&self, var: SysconfVar) -> nix::Result<Option<c_long>> {
        sysconf(var)
    }

    fn close(&self, fd: c_int) -> nix::Result<()> {
        close(fd)
    }
}

struct DefaultDaemoniseHelpers;
impl DaemoniseHelpers for DefaultDaemoniseHelpers {}

trait SetupStdioHelpers {
    fn create_append(&self, log_filename: &str) -> std::result::Result<File, std::io::Error> {
        OpenOptions::new()
            .create(true)
            .append(true)
            .open(log_filename)
    }

    fn dup2(&mut self, fd: c_int, fd2: c_int) -> std::result::Result<c_int, nix::errno::Errno> {
        dup2(fd, fd2)
    }

    fn read_write(&self, path: &str) -> std::result::Result<File, std::io::Error> {
        OpenOptions::new().read(true).write(true).open(path)
    }
}

struct DefaultSetupStdioHelpers;
impl SetupStdioHelpers for DefaultSetupStdioHelpers {}

/// Setup stdio for the process
///
/// This function redirects stderr to its logfile while discarding any IO to the
/// controlling terminal.
pub(crate) fn setup_stdio(log_filename: &str) -> std::result::Result<(), TelemetryError> {
    let mut helpers = DefaultSetupStdioHelpers;
    setup_stdio_with_helpers(log_filename, &mut helpers)
}

fn setup_stdio_with_helpers(
    log_filename: &str,
    helpers: &mut impl SetupStdioHelpers,
) -> std::result::Result<(), TelemetryError> {
    let log_file = helpers.create_append(log_filename)?;

    // Redirect stderr to the logfile
    helpers.dup2(log_file.as_raw_fd(), 2)?;

    // Get a filehandle to /dev/null
    let dev_null = helpers.read_write("/dev/null")?;

    // Redirect stdin, stdout to /dev/null
    helpers.dup2(dev_null.as_raw_fd(), 0)?;
    helpers.dup2(dev_null.as_raw_fd(), 1)?;

    Ok(())
}

#[cfg(test)]
fn setup_fuelup_home() {
    let tmp_dir = std::env::temp_dir().join(format!("fuelup-test-{}", uuid::Uuid::new_v4()));
    std::fs::create_dir_all(&tmp_dir).unwrap();
    std::env::set_var("FUELUP_HOME", tmp_dir.to_str().unwrap());
}

#[cfg(test)]
mod env_setting {
    use super::*;
    use std::env::set_var;

    #[test]
    fn unset() {
        let env_setting = EnvSetting::new("does_not_exist", "default_value");
        assert_eq!(env_setting.get(), "default_value");
    }

    #[test]
    fn set() {
        set_var("existing_variable", "existing_value");

        let env_setting = EnvSetting::new("existing_variable", "default_value");
        assert_eq!(env_setting.get(), "existing_value");
    }
}

#[cfg(test)]
mod telemetry_config {
    use super::*;
    use rusty_fork::rusty_fork_test;
    use std::{env::set_var, path::Path};

    rusty_fork_test! {
        #[test]
        fn fuelup_all_unset() {
            let telemetry_config = telemetry_config().unwrap();
            let fuelup_home = home_dir().unwrap();

            assert_eq!(
                telemetry_config.fuelup_tmp,
                fuelup_home.join(".fuelup/tmp").to_str().unwrap()
            );

            assert_eq!(
                telemetry_config.fuelup_log,
                fuelup_home.join(".fuelup/log").to_str().unwrap()
            );

            assert!(Path::new(&telemetry_config.fuelup_tmp).is_dir());
            assert!(Path::new(&telemetry_config.fuelup_log).is_dir());
        }

        #[test]
        fn fuelup_home_set() {
            setup_fuelup_home();

            let tempdir = var("FUELUP_HOME").unwrap();
            let telemetry_config = telemetry_config().unwrap();

            assert_eq!(telemetry_config.fuelup_tmp, format!("{}/tmp", tempdir));
            assert_eq!(telemetry_config.fuelup_log, format!("{}/log", tempdir));

            assert!(Path::new(&telemetry_config.fuelup_tmp).is_dir());
            assert!(Path::new(&telemetry_config.fuelup_log).is_dir());
        }

        #[test]
        fn fuelup_tmp_set() {
            let tmpdir = std::env::temp_dir().join(format!("fuelup-test-{}", uuid::Uuid::new_v4()));
            set_var("FUELUP_TMP", tmpdir.to_str().unwrap());
            std::fs::create_dir_all(&tmpdir).unwrap();

            let telemetry_config = telemetry_config().unwrap();

            assert_eq!(telemetry_config.fuelup_tmp, tmpdir.to_str().unwrap());

            assert_eq!(
                telemetry_config.fuelup_log,
                home_dir().unwrap().join(".fuelup/log").to_str().unwrap()
            );

            assert!(Path::new(&telemetry_config.fuelup_tmp).is_dir());
            assert!(Path::new(&telemetry_config.fuelup_log).is_dir());
        }

        #[test]
        fn fuelup_log_set() {
            let tmpdir = std::env::temp_dir().join(format!("fuelup-test-{}", uuid::Uuid::new_v4()));
            std::fs::create_dir_all(&tmpdir).unwrap();
            set_var("FUELUP_LOG", tmpdir.to_str().unwrap());

            let telemetry_config = telemetry_config().unwrap();

            assert_eq!(
                telemetry_config.fuelup_tmp,
                home_dir().unwrap().join(".fuelup/tmp").to_str().unwrap()
            );

            assert_eq!(telemetry_config.fuelup_log, tmpdir.to_str().unwrap());

            assert!(Path::new(&telemetry_config.fuelup_tmp).is_dir());
            assert!(Path::new(&telemetry_config.fuelup_log).is_dir());
        }
    }
}

#[cfg(test)]
mod enforce_singleton {
    use super::*;
    use nix::unistd::ForkResult;
    use rusty_fork::rusty_fork_test;
    use std::os::fd::OwnedFd;

    fn setup_lockfile() -> PathBuf {
        let lockfile = format!("{}/test.lock", telemetry_config().unwrap().fuelup_tmp);

        File::create(&lockfile).unwrap();
        PathBuf::from(lockfile)
    }

    rusty_fork_test! {
        #[test]
        fn lockfile_open_failed() {
            struct LockfileOpenFailed;

            impl EnforceSingletonHelpers for LockfileOpenFailed {
                fn open(&self, _filename: &Path) -> std::result::Result<File, std::io::Error> {
                    Err(std::io::Error::new(
                        std::io::ErrorKind::NotFound,
                        "Mock error",
                    ))
                }
            }

            assert_eq!(
                enforce_singleton_with_helpers(Path::new("test.lock"), &mut LockfileOpenFailed)
                    .err(),
                Some(TelemetryError::IO("Mock error".to_string()))
            );
        }

        #[test]
        fn flock_ewouldblock() {
            setup_fuelup_home();
            let lockfile = setup_lockfile();

            struct FlockEWouldblock {
                write_fd: OwnedFd,
            }

            impl EnforceSingletonHelpers for FlockEWouldblock {
                fn lock(&self, file: File) -> std::result::Result<Flock<File>, (File, Errno)> {
                    Err((file, Errno::EWOULDBLOCK))
                }

                fn exit(&self, _status: i32) -> ! {
                    // Test we exited at the expected code path
                    let pid = getpid();
                    write(&self.write_fd, &pid.as_raw().to_ne_bytes()).unwrap();

                    exit(0);
                }
            }

            let (read_fd, write_fd) = pipe().unwrap();

            match unsafe { fork() }.unwrap() {
                ForkResult::Parent { child } => {
                    drop(write_fd);

                    let mut pid_bytes = [0u8; std::mem::size_of::<Pid>()];
                    read(read_fd.as_raw_fd(), &mut pid_bytes).unwrap();

                    assert_eq!(pid_bytes, child.as_raw().to_ne_bytes());
                }
                ForkResult::Child => {
                    drop(read_fd);

                    let mut flock_ewouldblock = FlockEWouldblock { write_fd };

                    enforce_singleton_with_helpers(&lockfile, &mut flock_ewouldblock).unwrap();

                    // Fallback exit, which rusty_fork will catch
                    exit(99);
                }
            }
        }

        #[test]
        fn flock_other_error() {
            setup_fuelup_home();
            let lockfile = setup_lockfile();

            struct FlockOtherError;

            impl EnforceSingletonHelpers for FlockOtherError {
                fn lock(&self, file: File) -> std::result::Result<Flock<File>, (File, Errno)> {
                    Err((file, Errno::EOWNERDEAD))
                }
            }

            let result = enforce_singleton_with_helpers(&lockfile, &mut FlockOtherError);

            let expected = TelemetryError::Nix(Errno::EOWNERDEAD.to_string());
            assert_eq!(result.err(), Some(expected));
        }
    }
}

#[cfg(test)]
mod daemonise {
    use super::*;
    use nix::{
        errno::Errno,
        sys::wait::{waitpid, WaitStatus},
        unistd::ForkResult,
    };
    use rusty_fork::rusty_fork_test;
    use std::io::{Error, ErrorKind, Result, Write};

    rusty_fork_test! {
        #[test]
        fn stdout_flush_failed() {
            setup_fuelup_home();

            struct StdoutFlushFailed;

            impl DaemoniseHelpers for StdoutFlushFailed {
                fn flush<T: Write + std::os::fd::AsRawFd>(&mut self, stream: &mut T) -> Result<()> {
                    assert_eq!(stream.as_raw_fd(), 1);
                    Err(Error::new(ErrorKind::Other, "Error flushing stdout"))
                }
            }

            let result = daemonise_with_helpers(&PathBuf::from("test.log"), &mut StdoutFlushFailed);
            assert!(matches!(result, Err(WatcherError::Recoverable(_))));
        }

        #[test]
        fn stderr_flush_failed() {
            setup_fuelup_home();

            #[derive(Default)]
            struct StderrFlushFailed {
                call_counter: usize,
            }

            impl DaemoniseHelpers for StderrFlushFailed {
                fn flush<T: Write + std::os::fd::AsRawFd>(&mut self, stream: &mut T) -> Result<()> {
                    self.call_counter += 1;

                    if self.call_counter == 1 {
                        Ok(())
                    } else {
                        assert_eq!(stream.as_raw_fd(), 2);
                        Err(Error::new(ErrorKind::Other, "Error flushing stderr"))
                    }
                }
            }

            let result = daemonise_with_helpers(
                &PathBuf::from("test.log"),
                &mut StderrFlushFailed::default(),
            );

            assert!(matches!(result, Err(WatcherError::Recoverable(_))));
        }

        #[test]
        fn pipe_failed() {
            setup_fuelup_home();

            struct PipeFailed;

            impl DaemoniseHelpers for PipeFailed {
                fn pipe(&mut self) -> nix::Result<(OwnedFd, OwnedFd)> {
                    Err(Errno::EOWNERDEAD)
                }
            }

            let result = daemonise_with_helpers(&PathBuf::from("test.log"), &mut PipeFailed);
            let expected_error = TelemetryError::Nix(Errno::EOWNERDEAD.to_string());

            assert_eq!(
                result.err(),
                Some(WatcherError::Recoverable(expected_error))
            );
        }

        #[test]
        fn first_fork_failed() {
            setup_fuelup_home();

            struct FirstForkFailed;

            impl DaemoniseHelpers for FirstForkFailed {
                fn fork(&mut self) -> nix::Result<ForkResult> {
                    Err(Errno::EOWNERDEAD)
                }
            }

            assert_eq!(
                daemonise_with_helpers(&PathBuf::from("test.log"), &mut FirstForkFailed),
                Err(WatcherError::Recoverable(TelemetryError::Nix(
                    Errno::EOWNERDEAD.to_string()
                )))
            );
        }

        #[test]
        fn first_fork_is_parent() {
            setup_fuelup_home();

            struct FirstForkIsParent;

            impl DaemoniseHelpers for FirstForkIsParent {
                fn fork(&mut self) -> nix::Result<ForkResult> {
                    Ok(ForkResult::Parent {
                        child: Pid::from_raw(1),
                    })
                }
            }

            let result = daemonise_with_helpers(&PathBuf::from("test.log"), &mut FirstForkIsParent);
            assert!(matches!(result, Ok(Some(_))));
        }

        #[test]
        fn second_fork_failed() {
            setup_fuelup_home();

            #[derive(Default)]
            struct SecondForkFailed {
                call_counter: usize,
            }

            impl DaemoniseHelpers for SecondForkFailed {
                fn fork(&mut self) -> nix::Result<ForkResult> {
                    self.call_counter += 1;

                    if self.call_counter == 2 {
                        Err(Errno::EOWNERDEAD)
                    } else {
                        Ok(ForkResult::Child)
                    }
                }
            }

            let result = daemonise_with_helpers(
                &PathBuf::from("test.log"),
                &mut SecondForkFailed::default(),
            );

            assert!(matches!(result, Err(WatcherError::Fatal(_))));
        }

        #[test]
        fn second_fork_is_parent() {
            setup_fuelup_home();

            #[derive(Default)]
            struct SecondForkIsParent {
                call_counter: usize,
            }

            impl DaemoniseHelpers for SecondForkIsParent {
                fn fork(&mut self) -> nix::Result<ForkResult> {
                    self.call_counter += 1;

                    if self.call_counter == 2 {
                        Ok(ForkResult::Parent {
                            child: Pid::from_raw(1),
                        })
                    } else {
                        Ok(ForkResult::Child)
                    }
                }
            }

            // We ourselves fork so that we can `waitpid` on the function
            match unsafe { fork() }.unwrap() {
                ForkResult::Parent { child } => match waitpid(child, None).unwrap() {
                    WaitStatus::Exited(_, code) => {
                        assert_eq!(code, 0);
                    }
                    _ => panic!("Child did not exit normally"),
                },
                ForkResult::Child => {
                    let _ = daemonise_with_helpers(
                        &PathBuf::from("test.log"),
                        &mut SecondForkIsParent::default(),
                    );

                    // Fallback exit
                    exit(99);
                }
            }
        }

        #[test]
        fn setsid_failed() {
            setup_fuelup_home();

            struct SetsidFailed;

            impl DaemoniseHelpers for SetsidFailed {
                fn setsid(&self) -> nix::Result<Pid> {
                    Err(Errno::EOWNERDEAD)
                }

                // Need to become the child so we don't return as the parent
                fn fork(&mut self) -> nix::Result<ForkResult> {
                    Ok(ForkResult::Child)
                }
            }

            let result = daemonise_with_helpers(&PathBuf::from("test.log"), &mut SetsidFailed);

            let expected_error = TelemetryError::Nix(Errno::EOWNERDEAD.to_string());
            assert_eq!(result.err(), Some(WatcherError::Fatal(expected_error)));
        }

        #[test]
        fn third_fork_failed() {
            setup_fuelup_home();

            #[derive(Default)]
            struct ThirdForkFailed {
                call_counter: usize,
            }

            impl DaemoniseHelpers for ThirdForkFailed {
                fn fork(&mut self) -> nix::Result<ForkResult> {
                    self.call_counter += 1;

                    if self.call_counter == 3 {
                        Err(Errno::EOWNERDEAD)
                    } else {
                        Ok(ForkResult::Child)
                    }
                }
            }

            let result =
                daemonise_with_helpers(&PathBuf::from("test.log"), &mut ThirdForkFailed::default());

            let expected_error = TelemetryError::Nix(Errno::EOWNERDEAD.to_string());
            assert_eq!(result.err(), Some(WatcherError::Fatal(expected_error)));
        }

        #[test]
        fn third_fork_is_parent() {
            setup_fuelup_home();

            #[derive(Default)]
            struct ThirdForkIsParent {
                call_counter: usize,
            }

            impl DaemoniseHelpers for ThirdForkIsParent {
                fn fork(&mut self) -> nix::Result<ForkResult> {
                    self.call_counter += 1;

                    if self.call_counter == 3 {
                        Ok(ForkResult::Parent {
                            child: Pid::from_raw(1),
                        })
                    } else {
                        Ok(ForkResult::Child)
                    }
                }
            }

            // We ourselves fork so that we can `waitpid` on the function
            match unsafe { fork() }.unwrap() {
                ForkResult::Parent { child } => match waitpid(child, None).unwrap() {
                    WaitStatus::Exited(_, code) => {
                        assert_eq!(code, 0);
                    }
                    _ => panic!("Child did not exit normally"),
                },
                ForkResult::Child => {
                    let _ = daemonise_with_helpers(
                        &PathBuf::from("test.log"),
                        &mut ThirdForkIsParent::default(),
                    );

                    // Fallback exit
                    exit(99);
                }
            }
        }

        #[test]
        fn write_pipe_failed() {
            setup_fuelup_home();

            struct WritePipeFailed;

            impl DaemoniseHelpers for WritePipeFailed {
                fn write_pipe(&mut self, _write_fd: OwnedFd, _pid: Pid) -> nix::Result<usize> {
                    Err(Errno::EOWNERDEAD)
                }

                fn fork(&mut self) -> nix::Result<ForkResult> {
                    Ok(ForkResult::Child)
                }
            }

            let result = daemonise_with_helpers(&PathBuf::from("test.log"), &mut WritePipeFailed);

            let expected_error = TelemetryError::Nix(Errno::EOWNERDEAD.to_string());
            assert_eq!(result.err(), Some(WatcherError::Fatal(expected_error)));
        }

        #[test]
        fn telemetry_config_failed() {
            setup_fuelup_home();

            struct TelemetryConfigFailed;

            impl DaemoniseHelpers for TelemetryConfigFailed {
                fn telemetry_config(
                    &mut self,
                ) -> std::result::Result<&'static TelemetryConfig, errors::TelemetryError>
                {
                    Err(TelemetryError::Mock)
                }

                fn fork(&mut self) -> nix::Result<ForkResult> {
                    // We want to continue as the child process, so flip the fork result
                    // and return the original parent as the child
                    let original_parent = getpid();

                    match unsafe { fork() }.unwrap() {
                        ForkResult::Parent { child: _child } => Ok(ForkResult::Child),
                        ForkResult::Child => Ok(ForkResult::Parent {
                            child: original_parent,
                        }),
                    }
                }
            }

            if let Err(e) =
                daemonise_with_helpers(&PathBuf::from("test.log"), &mut TelemetryConfigFailed)
            {
                assert_eq!(e, WatcherError::Fatal(TelemetryError::Mock));
            }
        }

        #[test]
        fn setup_stdio_failed() {
            setup_fuelup_home();

            struct SetupStdioFailed;

            impl DaemoniseHelpers for SetupStdioFailed {
                fn setup_stdio(
                    &self,
                    _log_filename: &str,
                ) -> std::result::Result<(), TelemetryError> {
                    Err(TelemetryError::IO("Error setting up stdio".to_string()))
                }

                fn fork(&mut self) -> nix::Result<ForkResult> {
                    // We want to continue as the child process, so flip the fork result
                    // and return the original parent as the child
                    let original_parent = getpid();

                    match unsafe { fork() }.unwrap() {
                        ForkResult::Parent { child: _child } => Ok(ForkResult::Child),
                        ForkResult::Child => Ok(ForkResult::Parent {
                            child: original_parent,
                        }),
                    }
                }
            }

            if let Err(e) =
                daemonise_with_helpers(&PathBuf::from("test.log"), &mut SetupStdioFailed)
            {
                let expected_error = TelemetryError::IO("Error setting up stdio".to_string());
                assert_eq!(e, WatcherError::Fatal(expected_error));
            }
        }

        #[test]
        fn join_failed() {
            setup_fuelup_home();

            struct JoinFailed;

            impl DaemoniseHelpers for JoinFailed {
                fn telemetry_config(
                    &mut self,
                ) -> std::result::Result<&'static TelemetryConfig, errors::TelemetryError>
                {
                    pub static _TELEMETRY_CONFIG: LazyLock<Result<TelemetryConfig>> =
                        LazyLock::new(|| {
                            Ok(TelemetryConfig {
                                // Use invalid UTF-8 to trigger the error
                                fuelup_tmp: unsafe { String::from_utf8_unchecked(vec![0xFF]) },
                                fuelup_log: "".to_string(),
                            })
                        });

                    _TELEMETRY_CONFIG.as_ref().map_err(|_| {
                        TelemetryError::InvalidConfig("Error getting telemetry config".to_string())
                    })
                }

                fn setup_stdio(
                    &self,
                    _log_filename: &str,
                ) -> std::result::Result<(), TelemetryError> {
                    Ok(())
                }

                fn fork(&mut self) -> nix::Result<ForkResult> {
                    // We want to continue as the child process, so flip the fork result
                    // and return the original parent as the child
                    let original_parent = getpid();

                    match unsafe { fork() }.unwrap() {
                        ForkResult::Parent { child: _child } => Ok(ForkResult::Child),
                        ForkResult::Child => Ok(ForkResult::Parent {
                            child: original_parent,
                        }),
                    }
                }
            }

            if let Err(e) = daemonise_with_helpers(&PathBuf::from("test.log"), &mut JoinFailed) {
                assert!(matches!(
                    e,
                    WatcherError::Fatal(TelemetryError::InvalidLogFile(_, _))
                ));
            }
        }

        #[test]
        fn chdir_failed() {
            setup_fuelup_home();

            struct ChdirFailed;

            impl DaemoniseHelpers for ChdirFailed {
                fn chdir(&self, _path: &Path) -> nix::Result<()> {
                    Err(Errno::EOWNERDEAD)
                }

                fn setup_stdio(
                    &self,
                    _log_filename: &str,
                ) -> std::result::Result<(), TelemetryError> {
                    Ok(())
                }

                fn fork(&mut self) -> nix::Result<ForkResult> {
                    // We want to continue as the child process, so flip the fork result
                    // and return the original parent as the child
                    let original_parent = getpid();

                    match unsafe { fork() }.unwrap() {
                        ForkResult::Parent { child: _child } => Ok(ForkResult::Child),
                        ForkResult::Child => Ok(ForkResult::Parent {
                            child: original_parent,
                        }),
                    }
                }
            }

            if let Err(e) = daemonise_with_helpers(&PathBuf::from("test.log"), &mut ChdirFailed) {
                assert_eq!(
                    e,
                    WatcherError::Fatal(TelemetryError::Nix(Errno::EOWNERDEAD.to_string()))
                );
            }
        }

        #[test]
        fn sysconf_failed() {
            setup_fuelup_home();

            struct SysconfFailed;

            impl DaemoniseHelpers for SysconfFailed {
                fn sysconf(&self, _var: SysconfVar) -> nix::Result<Option<c_long>> {
                    Err(Errno::EOWNERDEAD)
                }

                fn setup_stdio(
                    &self,
                    _log_filename: &str,
                ) -> std::result::Result<(), TelemetryError> {
                    Ok(())
                }

                fn fork(&mut self) -> nix::Result<ForkResult> {
                    // We want to continue as the child process, so flip the fork result
                    // and return the original parent as the child
                    let original_parent = getpid();

                    match unsafe { fork() }.unwrap() {
                        ForkResult::Parent { child: _child } => Ok(ForkResult::Child),
                        ForkResult::Child => Ok(ForkResult::Parent {
                            child: original_parent,
                        }),
                    }
                }
            }

            if let Err(e) = daemonise_with_helpers(&PathBuf::from("test.log"), &mut SysconfFailed) {
                assert_eq!(
                    e,
                    WatcherError::Fatal(TelemetryError::Nix(Errno::EOWNERDEAD.to_string()))
                );
            }
        }

        #[test]
        fn close_failed_with_ebadf() {
            setup_fuelup_home();

            struct CloseFailed;

            impl DaemoniseHelpers for CloseFailed {
                fn close(&self, _fd: c_int) -> nix::Result<()> {
                    Err(Errno::EBADF)
                }

                fn setup_stdio(
                    &self,
                    _log_filename: &str,
                ) -> std::result::Result<(), TelemetryError> {
                    Ok(())
                }

                fn fork(&mut self) -> nix::Result<ForkResult> {
                    // We want to continue as the child process, so flip the fork result
                    // and return the original parent as the child
                    let original_parent = getpid();

                    match unsafe { fork() }.unwrap() {
                        ForkResult::Parent { child: _child } => Ok(ForkResult::Child),
                        ForkResult::Child => Ok(ForkResult::Parent {
                            child: original_parent,
                        }),
                    }
                }
            }

            if let Err(e) = daemonise_with_helpers(&PathBuf::from("test.log"), &mut CloseFailed) {
                assert_eq!(
                    e,
                    WatcherError::Fatal(TelemetryError::Nix(Errno::EBADF.to_string()))
                );
            }
        }

        #[test]
        fn close_failed_with_other_error() {
            setup_fuelup_home();

            struct CloseFailed;

            impl DaemoniseHelpers for CloseFailed {
                fn close(&self, _fd: c_int) -> nix::Result<()> {
                    Err(Errno::EOWNERDEAD)
                }

                fn setup_stdio(
                    &self,
                    _log_filename: &str,
                ) -> std::result::Result<(), TelemetryError> {
                    Ok(())
                }

                fn fork(&mut self) -> nix::Result<ForkResult> {
                    // We want to continue as the child process, so flip the fork result
                    // and return the original parent as the child
                    let original_parent = getpid();

                    match unsafe { fork() }.unwrap() {
                        ForkResult::Parent { child: _child } => Ok(ForkResult::Child),
                        ForkResult::Child => Ok(ForkResult::Parent {
                            child: original_parent,
                        }),
                    }
                }
            }

            if let Err(e) = daemonise_with_helpers(&PathBuf::from("test.log"), &mut CloseFailed) {
                assert_eq!(
                    e,
                    WatcherError::Fatal(TelemetryError::Nix(Errno::EOWNERDEAD.to_string()))
                );
            }
        }

        #[test]
        fn ok() {
            setup_fuelup_home();

            struct AOk;

            impl DaemoniseHelpers for AOk {
                fn setup_stdio(
                    &self,
                    _log_filename: &str,
                ) -> std::result::Result<(), TelemetryError> {
                    Ok(())
                }

                fn fork(&mut self) -> nix::Result<ForkResult> {
                    // We want to continue as the child process, so flip the fork result
                    // and return the original parent as the child
                    let original_parent = getpid();

                    match unsafe { fork() }.unwrap() {
                        ForkResult::Parent { child: _child } => Ok(ForkResult::Child),
                        ForkResult::Child => Ok(ForkResult::Parent {
                            child: original_parent,
                        }),
                    }
                }
            }

            let parent_pid = getpid();
            let result = daemonise_with_helpers(&PathBuf::from("test.log"), &mut AOk);

            // We only care about the point of view from the parent (with flipped fork result)
            if getpid() == parent_pid {
                assert_eq!(result, Ok(None));
            }
        }
    }
}

#[cfg(test)]
mod setup_stdio {
    use super::*;
    use rusty_fork::rusty_fork_test;

    rusty_fork_test! {
        #[test]
        fn create_append_failed() {
            setup_fuelup_home();

            struct CreateAppendFailed;

            impl SetupStdioHelpers for CreateAppendFailed {
                fn create_append(
                    &self,
                    _log_filename: &str,
                ) -> std::result::Result<File, std::io::Error> {
                    Err(std::io::Error::new(
                        std::io::ErrorKind::Other,
                        "Error creating append",
                    ))
                }
            }

            let result = setup_stdio_with_helpers(
                &format!("{}/test.log", telemetry_config().unwrap().fuelup_log),
                &mut CreateAppendFailed,
            );

            assert!(matches!(result, Err(TelemetryError::IO(_))));
        }

        #[test]
        fn first_dup2_failed() {
            setup_fuelup_home();

            struct FirstDup2Failed;

            impl SetupStdioHelpers for FirstDup2Failed {
                fn dup2(
                    &mut self,
                    _fd: c_int,
                    fd2: c_int,
                ) -> std::result::Result<c_int, nix::errno::Errno> {
                    assert_eq!(fd2, 2);
                    Err(nix::errno::Errno::EOWNERDEAD)
                }
            }

            let result = setup_stdio_with_helpers(
                &format!("{}/test.log", telemetry_config().unwrap().fuelup_log),
                &mut FirstDup2Failed,
            );

            assert!(matches!(result, Err(TelemetryError::Nix(_))));
        }

        #[test]
        fn read_write_failed() {
            setup_fuelup_home();

            struct ReadWriteFailed;

            impl SetupStdioHelpers for ReadWriteFailed {
                fn read_write(&self, _path: &str) -> std::result::Result<File, std::io::Error> {
                    Err(std::io::Error::new(
                        std::io::ErrorKind::Other,
                        "Error reading write",
                    ))
                }
            }

            let result = setup_stdio_with_helpers(
                &format!("{}/test.log", telemetry_config().unwrap().fuelup_log),
                &mut ReadWriteFailed,
            );

            assert!(matches!(result, Err(TelemetryError::IO(_))));
        }

        #[test]
        fn second_dup2_failed() {
            setup_fuelup_home();

            #[derive(Default)]
            struct SecondDup2Failed {
                call_counter: usize,
            }

            impl SetupStdioHelpers for SecondDup2Failed {
                fn dup2(
                    &mut self,
                    _fd: c_int,
                    fd2: c_int,
                ) -> std::result::Result<c_int, nix::errno::Errno> {
                    self.call_counter += 1;

                    if self.call_counter == 2 {
                        assert_eq!(fd2, 0);
                        Err(nix::errno::Errno::EOWNERDEAD)
                    } else {
                        Ok(0)
                    }
                }
            }

            let result = setup_stdio_with_helpers(
                &format!("{}/test.log", telemetry_config().unwrap().fuelup_log),
                &mut SecondDup2Failed::default(),
            );

            assert!(matches!(result, Err(TelemetryError::Nix(_))));
        }

        #[test]
        fn third_dup2_failed() {
            setup_fuelup_home();

            #[derive(Default)]
            struct ThirdDup2Failed {
                call_counter: usize,
            }

            impl SetupStdioHelpers for ThirdDup2Failed {
                fn dup2(
                    &mut self,
                    _fd: c_int,
                    fd2: c_int,
                ) -> std::result::Result<c_int, nix::errno::Errno> {
                    self.call_counter += 1;

                    if self.call_counter == 3 {
                        assert_eq!(fd2, 1);
                        Err(nix::errno::Errno::EOWNERDEAD)
                    } else {
                        Ok(0)
                    }
                }
            }

            let result = setup_stdio_with_helpers(
                &format!("{}/test.log", telemetry_config().unwrap().fuelup_log),
                &mut ThirdDup2Failed::default(),
            );

            assert!(matches!(result, Err(TelemetryError::Nix(_))));
        }

        #[test]
        fn ok() {
            setup_fuelup_home();

            let result = setup_stdio_with_helpers(
                &format!("{}/test.log", telemetry_config().unwrap().fuelup_log),
                &mut DefaultSetupStdioHelpers,
            );

            assert!(matches!(result, Ok(())));
        }
    }
}