greggd 1.0.14

Lightweight Linux, macOS, and Windows metrics daemon that exposes a read-only JSON API for the gregg client.
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
//! Windows SCM service runtime and `WindowsServiceManager`.
//!
//! On Windows, `greggd` can run as a native Windows service managed by
//! the Service Control Manager (SCM). The service entry point is
//! `run_service`, which is invoked when the binary is launched by the
//! SCM with the `service` subcommand.
//!
//! The executable's hidden `service` command first enters the SCM dispatcher,
//! which invokes the generated `ServiceMain` callback. The callback runs the
//! service worker and keeps its selected config path in a process-local launch
//! context.
//!
//! The CLI `start`/`stop`/`restart` commands use `WindowsServiceManager` to
//! control the service through native APIs. `croncheck` is a
//! process-local watchdog that probes the TCP listener and spawns `run`
//! directly; it does not interact with the SCM.
//!
//! ## Architecture
//!
//! ```text
//! SCM ─── service_dispatcher ──→ ServiceMain ──→ run_with_shutdown() ──→ core daemon
//! CLI ─── WindowsServiceManager ──→ native service APIs
//! ```
//!
//! The service state machine is tested through an injectable
//! `ScmAdapter` trait, keeping deterministic unit tests independent
//! from the real SCM.

#[cfg(any(test, target_os = "windows"))]
use std::sync::{Arc, Mutex};

#[cfg(any(test, target_os = "windows"))]
use std::time::Duration;

#[cfg(any(test, target_os = "windows"))]
use tokio::sync::oneshot;

#[cfg(any(test, target_os = "windows"))]
use super::{ServiceError, ServiceManager, ServiceRegistration, ServiceState};

#[cfg(any(test, target_os = "windows"))]
use std::path::{Path, PathBuf};

#[cfg(target_os = "windows")]
use std::sync::OnceLock;

#[cfg(target_os = "windows")]
use windows_service::{define_windows_service, service_dispatcher};

/// Service name registered with the SCM.
pub const SERVICE_NAME: &str = "greggd";

/// Display name shown in the Windows Services console.
pub const SERVICE_DISPLAY_NAME: &str = "Gregg Metrics Daemon";

#[cfg(target_os = "windows")]
static SERVICE_LAUNCH_CONFIG: OnceLock<PathBuf> = OnceLock::new();

#[cfg(target_os = "windows")]
define_windows_service!(ffi_service_main, service_main);

/// Maximum time (ms) to wait for a state transition before reporting timeout.
#[cfg(any(test, target_os = "windows"))]
const STATE_TRANSITION_TIMEOUT_MS: u64 = 30_000;

/// Interval between state-transition polls.
#[cfg(any(test, target_os = "windows"))]
const STATE_POLL_INTERVAL_MS: u64 = 200;

// ── SCM adapter trait (available on Windows and in tests) ──────────────────

/// Adapter trait for SCM interaction. The production implementation wraps
/// `windows-service` FFI calls; test implementations provide deterministic
/// fake behavior.
#[cfg(any(test, target_os = "windows"))]
pub(crate) trait ScmAdapter: Send + Sync {
    /// Query the current service state from the SCM.
    fn query_state(&self) -> Result<ServiceState, ServiceError>;

    /// Query state and the registered executable image path.
    fn query_registration(&self) -> Result<ServiceRegistration, ServiceError>;

    /// Request the SCM to start the service.
    fn start_service(&self) -> Result<(), ServiceError>;

    /// Request the SCM to stop the service.
    fn stop_service(&self) -> Result<(), ServiceError>;

    /// Delete only this service's SCM registration.
    fn delete_service(&self) -> Result<(), ServiceError>;
}

/// Wait for the service to reach the target state, polling periodically.
///
/// Returns `Ok(())` when the target state is reached, or
/// `ServiceError::Timeout` if `STATE_TRANSITION_TIMEOUT_MS` elapses.
#[cfg(any(test, target_os = "windows"))]
fn wait_for_state(adapter: &dyn ScmAdapter, target: ServiceState) -> Result<(), ServiceError> {
    let deadline = Duration::from_millis(STATE_TRANSITION_TIMEOUT_MS);
    let poll = Duration::from_millis(STATE_POLL_INTERVAL_MS);
    let start = std::time::Instant::now();

    loop {
        let current = adapter.query_state()?;
        if current == target {
            return Ok(());
        }
        if start.elapsed() >= deadline {
            return Err(ServiceError::Timeout {
                waited_ms: STATE_TRANSITION_TIMEOUT_MS,
            });
        }
        std::thread::sleep(poll);
    }
}

// ── Production SCM adapter (Windows only) ─────────────────────────────────

/// Production SCM adapter using the `windows-service` crate.
///
/// # Safety
///
/// All FFI is delegated to the `windows-service` crate, which manages
/// handle lifetimes and error mapping internally.
#[cfg(target_os = "windows")]
pub(crate) struct NativeScmAdapter {
    service_name: String,
}

#[cfg(target_os = "windows")]
impl NativeScmAdapter {
    /// Create a new adapter for the given service name.
    #[must_use]
    pub fn new(service_name: impl Into<String>) -> Self {
        Self {
            service_name: service_name.into(),
        }
    }
}

#[cfg(target_os = "windows")]
impl ScmAdapter for NativeScmAdapter {
    fn query_state(&self) -> Result<ServiceState, ServiceError> {
        use windows_service::service_manager::{ServiceManager, ServiceManagerAccess};

        let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT)
            .map_err(|e| ServiceError::StateQueryFailed {
            source: std::io::Error::other(e),
        })?;

        let service = match manager.open_service(
            &self.service_name,
            windows_service::service::ServiceAccess::QUERY_STATUS,
        ) {
            Ok(service) => service,
            // A missing registration is a stable state, not a query
            // failure: stop/uninstall treat it as idempotent.
            Err(e) if is_missing_service(&e) => return Ok(ServiceState::NotInstalled),
            Err(e) => {
                return Err(ServiceError::StateQueryFailed {
                    source: std::io::Error::other(e),
                });
            }
        };

        let status = service
            .query_status()
            .map_err(|e| ServiceError::StateQueryFailed {
                source: std::io::Error::other(e),
            })?;

        Ok(map_service_state(status.current_state))
    }

    fn query_registration(&self) -> Result<ServiceRegistration, ServiceError> {
        use windows_service::service_manager::{ServiceManager, ServiceManagerAccess};

        let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT)
            .map_err(native_query_error)?;
        let service = match manager.open_service(
            &self.service_name,
            windows_service::service::ServiceAccess::QUERY_STATUS
                | windows_service::service::ServiceAccess::QUERY_CONFIG,
        ) {
            Ok(service) => service,
            Err(e) if is_missing_service(&e) => {
                return Ok(ServiceRegistration {
                    state: ServiceState::NotInstalled,
                    executable_path: None,
                });
            }
            Err(e) => return Err(native_query_error(e)),
        };
        let status = service.query_status().map_err(native_query_error)?;
        let config = service.query_config().map_err(native_query_error)?;
        let executable_path =
            parse_service_executable(&config.executable_path).ok_or_else(|| {
                ServiceError::StateQueryFailed {
                    source: std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "SCM executable command is ambiguous or has no absolute image path",
                    ),
                }
            })?;
        Ok(ServiceRegistration {
            state: map_service_state(status.current_state),
            executable_path: Some(executable_path),
        })
    }

    fn start_service(&self) -> Result<(), ServiceError> {
        use windows_service::service_manager::{ServiceManager, ServiceManagerAccess};

        let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT)
            .map_err(|e| ServiceError::ExecFailed {
            command: "ServiceManager::connect".into(),
            source: std::io::Error::other(e),
        })?;

        let service = manager
            .open_service(
                &self.service_name,
                windows_service::service::ServiceAccess::START,
            )
            .map_err(|e| ServiceError::ExecFailed {
                command: format!("open service `{}`", self.service_name),
                source: std::io::Error::other(e),
            })?;

        let args: [&str; 0] = [];
        service.start(&args).map_err(|e| ServiceError::ExecFailed {
            command: format!("start service `{}`", self.service_name),
            source: std::io::Error::other(e),
        })?;

        Ok(())
    }

    fn stop_service(&self) -> Result<(), ServiceError> {
        use windows_service::service_manager::{ServiceManager, ServiceManagerAccess};

        let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT)
            .map_err(|e| ServiceError::ExecFailed {
            command: "ServiceManager::connect".into(),
            source: std::io::Error::other(e),
        })?;

        let service = manager
            .open_service(
                &self.service_name,
                windows_service::service::ServiceAccess::STOP,
            )
            .map_err(|e| ServiceError::ExecFailed {
                command: format!("open service `{}`", self.service_name),
                source: std::io::Error::other(e),
            })?;

        service.stop().map_err(|e| ServiceError::ExecFailed {
            command: format!("stop service `{}`", self.service_name),
            source: std::io::Error::other(e),
        })?;

        Ok(())
    }

    fn delete_service(&self) -> Result<(), ServiceError> {
        use windows_service::service_manager::{ServiceManager, ServiceManagerAccess};

        let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT)
            .map_err(|e| ServiceError::ExecFailed {
            command: "ServiceManager::connect".into(),
            source: std::io::Error::other(e),
        })?;

        let service = match manager.open_service(
            &self.service_name,
            windows_service::service::ServiceAccess::DELETE,
        ) {
            Ok(service) => service,
            // Not registered: the uninstall goal is already met.
            Err(e) if is_missing_service(&e) => return Ok(()),
            Err(e) if is_access_denied_error(&e) => return Err(ServiceError::AccessDenied),
            Err(e) => {
                return Err(ServiceError::ExecFailed {
                    command: format!("open service `{}`", self.service_name),
                    source: std::io::Error::other(e),
                });
            }
        };

        match service.delete() {
            Ok(()) => Ok(()),
            // Already fully removed, or marked for delete pending stop:
            // either way there is no live registration left to own.
            Err(e) if is_missing_service(&e) || is_marked_for_delete(&e) => Ok(()),
            Err(e) if is_access_denied_error(&e) => Err(ServiceError::AccessDenied),
            Err(e) => Err(ServiceError::ExecFailed {
                command: format!("delete service `{}`", self.service_name),
                source: std::io::Error::other(e),
            }),
        }
    }
}

/// Extract the image path from the SCM `lpBinaryPathName` command line.
///
/// `windows-service` exposes the complete launch command through
/// `ServiceConfig::executable_path`; Gregg only accepts an unambiguous,
/// absolute image path for ownership decisions. Quoted paths may have
/// arguments. Unquoted paths are accepted only when they contain no
/// whitespace and no arguments, because an unquoted path with spaces cannot
/// be distinguished safely from its first token.
#[cfg(any(test, target_os = "windows"))]
fn parse_service_executable(command: &Path) -> Option<PathBuf> {
    let text = command.to_str()?.trim_start();
    let image = if let Some(quoted) = text.strip_prefix('"') {
        let end = quoted.find('"')?;
        let image = &quoted[..end];
        let remainder = &quoted[end + 1..];
        if !remainder.is_empty() && !remainder.chars().next()?.is_whitespace() {
            return None;
        }
        image
    } else {
        if text.chars().any(char::is_whitespace) {
            return None;
        }
        text
    };
    let path = PathBuf::from(image);
    path.is_absolute().then_some(path)
}

#[cfg(target_os = "windows")]
fn native_query_error(error: windows_service::Error) -> ServiceError {
    if is_access_denied_error(&error) {
        ServiceError::AccessDenied
    } else {
        ServiceError::StateQueryFailed {
            source: std::io::Error::other(error),
        }
    }
}

/// Win32 `ERROR_SERVICE_DOES_NOT_EXIST` (1060): no such SCM registration.
#[cfg(target_os = "windows")]
fn scm_raw_code(error: &windows_service::Error) -> Option<i32> {
    match error {
        windows_service::Error::Winapi(io) => io.raw_os_error(),
        _ => None,
    }
}

/// Classify a `windows-service` error as a missing registration (1060).
#[cfg(target_os = "windows")]
fn is_missing_service(error: &windows_service::Error) -> bool {
    scm_raw_code(error) == Some(1060)
}

/// Classify a `windows-service` error as access denied (5).
#[cfg(target_os = "windows")]
fn is_access_denied_error(error: &windows_service::Error) -> bool {
    if scm_raw_code(error) == Some(5) {
        return true;
    }
    let message = error.to_string().to_ascii_lowercase();
    message.contains("access is denied") || message.contains("access denied")
}

/// Classify a `windows-service` error as already marked for delete (1072).
#[cfg(target_os = "windows")]
fn is_marked_for_delete(error: &windows_service::Error) -> bool {
    scm_raw_code(error) == Some(1072)
}

/// Map `windows-service` `ServiceState` to our `ServiceState`.
#[cfg(target_os = "windows")]
fn map_service_state(state: windows_service::service::ServiceState) -> ServiceState {
    use windows_service::service::ServiceState as WsState;
    match state {
        WsState::StartPending => ServiceState::StartPending,
        WsState::Stopped => ServiceState::Stopped,
        WsState::StopPending => ServiceState::StopPending,
        WsState::Running | WsState::PausePending | WsState::Paused | WsState::ContinuePending => {
            ServiceState::Running
        }
    }
}

// ── SCM service entry point (Windows only) ────────────────────────────────

#[cfg(any(test, target_os = "windows"))]
type ShutdownSender = Arc<Mutex<Option<oneshot::Sender<&'static str>>>>;

#[cfg(any(test, target_os = "windows"))]
fn shutdown_channel() -> (ShutdownSender, oneshot::Receiver<&'static str>) {
    let (sender, receiver) = oneshot::channel();
    (Arc::new(Mutex::new(Some(sender))), receiver)
}

#[cfg(any(test, target_os = "windows"))]
fn send_shutdown(sender: &ShutdownSender, reason: &'static str) {
    if let Ok(mut sender) = sender.lock() {
        if let Some(sender) = sender.take() {
            let _ = sender.send(reason);
        }
    }
}

/// Connect the process to the SCM dispatcher and wait for its callback.
#[cfg(target_os = "windows")]
pub fn start_service_dispatcher(config_path: PathBuf) -> Result<(), Box<dyn std::error::Error>> {
    SERVICE_LAUNCH_CONFIG.set(config_path).map_err(|_| {
        Box::new(std::io::Error::new(
            std::io::ErrorKind::AlreadyExists,
            "Windows service launch context was already initialized",
        )) as Box<dyn std::error::Error>
    })?;

    service_dispatcher::start(SERVICE_NAME, ffi_service_main)
        .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)
}

#[cfg(target_os = "windows")]
fn service_main(_service_arguments: Vec<std::ffi::OsString>) {
    let result = SERVICE_LAUNCH_CONFIG
        .get()
        .ok_or_else(|| {
            Box::new(std::io::Error::other(
                "Windows service launch context is missing",
            )) as Box<dyn std::error::Error>
        })
        .and_then(|config_path| run_service_worker(config_path));

    if let Err(error) = result {
        tracing::error!(error = %error, "Windows service exited with an error");
    }
}

#[cfg(target_os = "windows")]
fn run_service_worker(config_path: &Path) -> Result<(), Box<dyn std::error::Error>> {
    use windows_service::service::ServiceState as WsState;
    use windows_service::service_control_handler;

    // The handler only sends into this one-shot signal. It never waits for the
    // daemon, so SCM callbacks remain nonblocking.
    let (shutdown_sender, shutdown_receiver) = shutdown_channel();
    let status_handle = service_control_handler::register(SERVICE_NAME, move |control| {
        handle_service_control(control, &shutdown_sender)
    })
    .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?;

    let result = (|| {
        update_status(
            status_handle,
            WsState::StartPending,
            0,
            Duration::from_secs(5),
        )
        .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?;

        let config = crate::config::Config::load(config_path)
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?;
        let collector =
            crate::collector::windows::WindowsCollector::new(Some(config.name.as_str()))
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?;
        let shutdown_future =
            async move { shutdown_receiver.await.unwrap_or("SCM_CHANNEL_CLOSED") };
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?;

        rt.block_on(crate::run::run_with_shutdown_on_ready(
            collector,
            config,
            shutdown_future,
            || {
                update_status(status_handle, WsState::Running, 0, Duration::from_secs(10))
                    .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)
            },
        ))
    })();

    let exit_code = u32::from(result.is_err());
    let _ = update_status(
        status_handle,
        WsState::Stopped,
        exit_code,
        Duration::from_secs(5),
    );
    result
}

#[cfg(target_os = "windows")]
fn handle_service_control(
    control: windows_service::service::ServiceControl,
    shutdown: &ShutdownSender,
) -> windows_service::service_control_handler::ServiceControlHandlerResult {
    use windows_service::service::ServiceControl;
    use windows_service::service_control_handler::ServiceControlHandlerResult;

    match control {
        ServiceControl::Stop => {
            send_shutdown(shutdown, "SCM_STOP");
            ServiceControlHandlerResult::NoError
        }
        ServiceControl::Shutdown => {
            send_shutdown(shutdown, "SCM_SHUTDOWN");
            ServiceControlHandlerResult::NoError
        }
        ServiceControl::Interrogate => ServiceControlHandlerResult::NoError,
        _ => ServiceControlHandlerResult::NotImplemented,
    }
}

/// Update the SCM service status.
#[cfg(target_os = "windows")]
fn update_status(
    status_handle: windows_service::service_control_handler::ServiceStatusHandle,
    state: windows_service::service::ServiceState,
    exit_code: u32,
    wait_hint: Duration,
) -> windows_service::Result<()> {
    use windows_service::service::{
        ServiceControlAccept, ServiceExitCode, ServiceStatus, ServiceType,
    };

    let status = ServiceStatus {
        service_type: ServiceType::OWN_PROCESS,
        current_state: state,
        controls_accepted: ServiceControlAccept::STOP | ServiceControlAccept::SHUTDOWN,
        exit_code: ServiceExitCode::Win32(exit_code),
        checkpoint: 0,
        wait_hint,
        process_id: None,
    };
    status_handle.set_service_status(status)
}

// ── WindowsServiceManager ─────────────────────────────────────────────────

/// Windows implementation of [`ServiceManager`] using native SCM APIs.
#[cfg(any(test, target_os = "windows"))]
pub struct WindowsServiceManager {
    adapter: Box<dyn ScmAdapter>,
}

#[cfg(any(test, target_os = "windows"))]
impl std::fmt::Debug for WindowsServiceManager {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WindowsServiceManager")
            .field("service", &SERVICE_NAME)
            .finish()
    }
}

#[cfg(any(test, target_os = "windows"))]
impl WindowsServiceManager {
    /// Create a production manager using the native SCM adapter.
    ///
    /// # Panics
    ///
    /// Panics if called on a non-Windows platform.
    #[must_use]
    pub fn production() -> Self {
        #[cfg(target_os = "windows")]
        {
            Self {
                adapter: Box::new(NativeScmAdapter::new(SERVICE_NAME)),
            }
        }
        #[cfg(not(target_os = "windows"))]
        {
            panic!("WindowsServiceManager::production() can only be called on Windows")
        }
    }

    /// Create a manager with a custom adapter (for testing).
    #[cfg(test)]
    #[must_use]
    pub(crate) fn with_adapter(adapter: Box<dyn ScmAdapter>) -> Self {
        Self { adapter }
    }
}

#[cfg(any(test, target_os = "windows"))]
impl ServiceManager for WindowsServiceManager {
    fn query_registration(&self) -> Result<ServiceRegistration, ServiceError> {
        self.adapter.query_registration()
    }

    fn start(&self) -> Result<(), ServiceError> {
        let state = self.adapter.query_state()?;

        match state {
            ServiceState::Running | ServiceState::StartPending => {
                // Already running or starting — idempotent.
                Ok(())
            }
            ServiceState::StopPending => {
                // Wait for stop to complete, then start.
                wait_for_state(&*self.adapter, ServiceState::Stopped)?;
                self.adapter.start_service()?;
                wait_for_state(&*self.adapter, ServiceState::Running)
            }
            ServiceState::Stopped | ServiceState::NotInstalled => {
                self.adapter.start_service()?;
                wait_for_state(&*self.adapter, ServiceState::Running)
            }
        }
    }

    fn stop(&self) -> Result<(), ServiceError> {
        let state = self.adapter.query_state()?;

        match state {
            ServiceState::Stopped | ServiceState::NotInstalled => {
                // Already stopped — idempotent.
                Ok(())
            }
            ServiceState::Running | ServiceState::StartPending => {
                self.adapter.stop_service()?;
                wait_for_state(&*self.adapter, ServiceState::Stopped)
            }
            ServiceState::StopPending => {
                // Already stopping — wait for it.
                wait_for_state(&*self.adapter, ServiceState::Stopped)
            }
        }
    }

    fn restart(&self) -> Result<(), ServiceError> {
        self.stop()?;
        self.start()
    }

    fn is_active(&self) -> Result<bool, ServiceError> {
        let state = self.adapter.query_state()?;
        Ok(state.is_active())
    }

    fn unregister(&self) -> Result<(), ServiceError> {
        // Resolve first so a missing registration is idempotent without
        // touching the SCM further.
        match self.adapter.query_state()? {
            ServiceState::NotInstalled => Ok(()),
            ServiceState::Stopped => self.adapter.delete_service(),
            ServiceState::Running | ServiceState::StartPending => {
                self.adapter.stop_service()?;
                wait_for_state(&*self.adapter, ServiceState::Stopped)?;
                self.adapter.delete_service()
            }
            ServiceState::StopPending => {
                wait_for_state(&*self.adapter, ServiceState::Stopped)?;
                self.adapter.delete_service()
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Arc, Mutex};

    /// Mock SCM adapter for deterministic tests.
    struct MockScmAdapter {
        state: Mutex<ServiceState>,
        start_error: Mutex<Option<ServiceError>>,
        stop_error: Mutex<Option<ServiceError>>,
        delete_error: Mutex<Option<ServiceError>>,
        query_error: Mutex<Option<ServiceError>>,
        /// When true, stop transitions straight to `Stopped` so
        /// unregister tests need no 30s timeout wait.
        immediate_stop: bool,
        calls: Mutex<Vec<&'static str>>,
    }

    impl MockScmAdapter {
        fn new(initial: ServiceState) -> Arc<Self> {
            Arc::new(Self {
                state: Mutex::new(initial),
                start_error: Mutex::new(None),
                stop_error: Mutex::new(None),
                delete_error: Mutex::new(None),
                query_error: Mutex::new(None),
                immediate_stop: false,
                calls: Mutex::new(Vec::new()),
            })
        }

        fn calls(&self) -> Vec<&'static str> {
            self.calls.lock().unwrap().clone()
        }
    }

    impl ScmAdapter for MockScmAdapter {
        fn query_state(&self) -> Result<ServiceState, ServiceError> {
            self.calls.lock().unwrap().push("query");
            if let Some(err) = self.query_error.lock().unwrap().take() {
                return Err(err);
            }
            Ok(*self.state.lock().unwrap())
        }

        fn query_registration(&self) -> Result<ServiceRegistration, ServiceError> {
            Ok(ServiceRegistration {
                state: self.query_state()?,
                executable_path: None,
            })
        }

        fn start_service(&self) -> Result<(), ServiceError> {
            self.calls.lock().unwrap().push("start");
            if let Some(err) = self.start_error.lock().unwrap().take() {
                return Err(err);
            }
            *self.state.lock().unwrap() = ServiceState::StartPending;
            Ok(())
        }

        fn stop_service(&self) -> Result<(), ServiceError> {
            self.calls.lock().unwrap().push("stop");
            if let Some(err) = self.stop_error.lock().unwrap().take() {
                return Err(err);
            }
            *self.state.lock().unwrap() = if self.immediate_stop {
                ServiceState::Stopped
            } else {
                ServiceState::StopPending
            };
            Ok(())
        }

        fn delete_service(&self) -> Result<(), ServiceError> {
            self.calls.lock().unwrap().push("delete");
            if let Some(err) = self.delete_error.lock().unwrap().take() {
                return Err(err);
            }
            *self.state.lock().unwrap() = ServiceState::NotInstalled;
            Ok(())
        }
    }

    /// Thin wrapper to make `MockScmAdapter` work with `Box<dyn ScmAdapter>`.
    struct MockScmAdapterWrapper(Arc<MockScmAdapter>);

    impl ScmAdapter for MockScmAdapterWrapper {
        fn query_state(&self) -> Result<ServiceState, ServiceError> {
            self.0.query_state()
        }
        fn query_registration(&self) -> Result<ServiceRegistration, ServiceError> {
            self.0.query_registration()
        }
        fn start_service(&self) -> Result<(), ServiceError> {
            self.0.start_service()
        }
        fn stop_service(&self) -> Result<(), ServiceError> {
            self.0.stop_service()
        }
        fn delete_service(&self) -> Result<(), ServiceError> {
            self.0.delete_service()
        }
    }

    fn manager_with_mock(
        mock: Arc<MockScmAdapter>,
    ) -> (WindowsServiceManager, Arc<MockScmAdapter>) {
        let mgr =
            WindowsServiceManager::with_adapter(Box::new(MockScmAdapterWrapper(Arc::clone(&mock))));
        (mgr, mock)
    }

    // --- State enum tests ---

    #[test]
    fn service_state_is_active() {
        assert!(ServiceState::Running.is_active());
        assert!(ServiceState::StartPending.is_active());
        assert!(!ServiceState::Stopped.is_active());
        assert!(!ServiceState::StopPending.is_active());
        assert!(!ServiceState::NotInstalled.is_active());
    }

    // --- Start tests ---

    #[test]
    fn start_when_running_is_idempotent() {
        let mock = MockScmAdapter::new(ServiceState::Running);
        let (mgr, mock_ref) = manager_with_mock(mock);

        assert!(mgr.start().is_ok());
        assert_eq!(mock_ref.calls(), vec!["query"]);
    }

    #[test]
    fn start_when_start_pending_is_idempotent() {
        let mock = MockScmAdapter::new(ServiceState::StartPending);
        let (mgr, mock_ref) = manager_with_mock(mock);

        assert!(mgr.start().is_ok());
        assert_eq!(mock_ref.calls(), vec!["query"]);
    }

    // --- Stop tests ---

    #[test]
    fn stop_when_stopped_is_idempotent() {
        let mock = MockScmAdapter::new(ServiceState::Stopped);
        let (mgr, mock_ref) = manager_with_mock(mock);

        assert!(mgr.stop().is_ok());
        assert_eq!(mock_ref.calls(), vec!["query"]);
    }

    #[test]
    fn stop_when_not_installed_is_idempotent() {
        let mock = MockScmAdapter::new(ServiceState::NotInstalled);
        let (mgr, mock_ref) = manager_with_mock(mock);

        assert!(mgr.stop().is_ok());
        assert_eq!(mock_ref.calls(), vec!["query"]);
    }

    #[test]
    fn stop_when_stop_pending_waits_then_times_out() {
        let mock = MockScmAdapter::new(ServiceState::StopPending);
        let (mgr, _mock_ref) = manager_with_mock(mock);

        let result = mgr.stop();
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), ServiceError::Timeout { .. }));
    }

    // --- Restart tests ---

    #[test]
    fn restart_when_stopped_queries_and_starts() {
        let mock = MockScmAdapter::new(ServiceState::Stopped);
        let (mgr, mock_ref) = manager_with_mock(mock);

        // restart() calls stop() (idempotent on Stopped), then start().
        // start() calls start_service() which sets StartPending, then
        // wait_for_state(Running) which will time out in the mock.
        let _ = mgr.restart();
        let calls = mock_ref.calls();
        // stop query + start query + start_service + wait queries
        assert!(calls.contains(&"start"));
    }

    #[test]
    fn restart_when_running_stops_then_attempts_start() {
        let mock = MockScmAdapter::new(ServiceState::Running);
        let (mgr, mock_ref) = manager_with_mock(mock);

        // restart() calls stop() which calls stop_service(), then
        // wait_for_state(Stopped) times out, so start() is never reached.
        let result = mgr.restart();
        let calls = mock_ref.calls();
        assert!(calls.contains(&"stop"));
        // stop timed out, so restart returns error
        assert!(result.is_err());
    }

    // --- is_active tests ---

    #[test]
    fn is_active_running_returns_true() {
        let mock = MockScmAdapter::new(ServiceState::Running);
        let (mgr, _mock_ref) = manager_with_mock(mock);
        assert!(mgr.is_active().unwrap());
    }

    #[test]
    fn is_active_stopped_returns_false() {
        let mock = MockScmAdapter::new(ServiceState::Stopped);
        let (mgr, _mock_ref) = manager_with_mock(mock);
        assert!(!mgr.is_active().unwrap());
    }

    #[test]
    fn is_active_not_installed_returns_false() {
        let mock = MockScmAdapter::new(ServiceState::NotInstalled);
        let (mgr, _mock_ref) = manager_with_mock(mock);
        assert!(!mgr.is_active().unwrap());
    }

    #[test]
    fn is_active_start_pending_returns_true() {
        let mock = MockScmAdapter::new(ServiceState::StartPending);
        let (mgr, _mock_ref) = manager_with_mock(mock);
        assert!(mgr.is_active().unwrap());
    }

    #[test]
    fn is_active_stop_pending_returns_false() {
        let mock = MockScmAdapter::new(ServiceState::StopPending);
        let (mgr, _mock_ref) = manager_with_mock(mock);
        assert!(!mgr.is_active().unwrap());
    }

    // --- Error propagation tests ---

    #[test]
    fn start_propagates_query_error() {
        let mock = MockScmAdapter::new(ServiceState::Stopped);
        mock.query_error
            .lock()
            .unwrap()
            .replace(ServiceError::AccessDenied);
        let (mgr, _mock_ref) = manager_with_mock(mock);

        let err = mgr.start().unwrap_err();
        assert!(matches!(err, ServiceError::AccessDenied));
    }

    #[test]
    fn stop_propagates_query_error() {
        let mock = MockScmAdapter::new(ServiceState::Running);
        mock.query_error
            .lock()
            .unwrap()
            .replace(ServiceError::AccessDenied);
        let (mgr, _mock_ref) = manager_with_mock(mock);

        let err = mgr.stop().unwrap_err();
        assert!(matches!(err, ServiceError::AccessDenied));
    }

    #[test]
    fn start_propagates_start_error() {
        let mock = MockScmAdapter::new(ServiceState::Stopped);
        mock.start_error
            .lock()
            .unwrap()
            .replace(ServiceError::AccessDenied);
        let (mgr, _mock_ref) = manager_with_mock(mock);

        let err = mgr.start().unwrap_err();
        assert!(matches!(err, ServiceError::AccessDenied));
    }

    #[test]
    fn stop_propagates_stop_error() {
        let mock = MockScmAdapter::new(ServiceState::Running);
        mock.stop_error
            .lock()
            .unwrap()
            .replace(ServiceError::AccessDenied);
        let (mgr, _mock_ref) = manager_with_mock(mock);

        let err = mgr.stop().unwrap_err();
        assert!(matches!(err, ServiceError::AccessDenied));
    }

    // --- Service identity tests ---

    #[test]
    fn service_name_is_stable() {
        assert_eq!(SERVICE_NAME, "greggd");
    }

    #[test]
    fn service_display_name_is_human_readable() {
        assert!(!SERVICE_DISPLAY_NAME.is_empty());
        assert!(!SERVICE_DISPLAY_NAME.contains('\n'));
    }

    #[cfg(target_os = "windows")]
    const SCM_TEST_IMAGE: &str = r"C:\Gregg\greggd.exe";
    #[cfg(not(target_os = "windows"))]
    const SCM_TEST_IMAGE: &str = "/opt/gregg/greggd";

    #[test]
    fn scm_command_parser_extracts_quoted_image() {
        let command = format!(r#""{SCM_TEST_IMAGE}" service --config "C:\Gregg\greggd.toml""#);
        assert_eq!(
            parse_service_executable(Path::new(&command)),
            Some(PathBuf::from(SCM_TEST_IMAGE))
        );
    }

    #[test]
    fn scm_command_parser_accepts_plain_image_without_arguments() {
        assert_eq!(
            parse_service_executable(Path::new(SCM_TEST_IMAGE)),
            Some(PathBuf::from(SCM_TEST_IMAGE))
        );
    }

    #[test]
    fn scm_command_parser_rejects_ambiguous_commands() {
        let unquoted = format!("{SCM_TEST_IMAGE} service");
        assert_eq!(parse_service_executable(Path::new(&unquoted)), None);
        let unterminated = format!(r#""{SCM_TEST_IMAGE} service"#);
        assert_eq!(parse_service_executable(Path::new(&unterminated)), None);
        assert_eq!(parse_service_executable(Path::new("greggd service")), None);
    }

    // --- Debug test ---

    #[test]
    fn unregister_when_not_installed_is_idempotent() {
        let mock = MockScmAdapter::new(ServiceState::NotInstalled);
        let (mgr, mock_ref) = manager_with_mock(mock);
        assert!(mgr.unregister().is_ok());
        assert_eq!(mock_ref.calls(), vec!["query"]);
    }

    #[test]
    fn unregister_when_stopped_deletes_without_stopping() {
        let mock = MockScmAdapter::new(ServiceState::Stopped);
        let (mgr, mock_ref) = manager_with_mock(mock);
        assert!(mgr.unregister().is_ok());
        assert_eq!(mock_ref.calls(), vec!["query", "delete"]);
        assert_eq!(*mock_ref.state.lock().unwrap(), ServiceState::NotInstalled);
    }

    #[test]
    fn unregister_when_running_stops_waits_then_deletes() {
        let mut mock = MockScmAdapter::new(ServiceState::Running);
        Arc::get_mut(&mut mock)
            .expect("single owner")
            .immediate_stop = true;
        let (mgr, mock_ref) = manager_with_mock(mock);
        assert!(mgr.unregister().is_ok());
        let calls = mock_ref.calls();
        assert!(
            calls.contains(&"stop"),
            "must stop before delete: {calls:?}"
        );
        assert!(calls.contains(&"delete"), "must delete: {calls:?}");
        assert!(
            calls.iter().position(|c| *c == "stop") < calls.iter().position(|c| *c == "delete"),
            "stop must precede delete: {calls:?}"
        );
        assert_eq!(*mock_ref.state.lock().unwrap(), ServiceState::NotInstalled);
    }

    #[test]
    fn unregister_propagates_access_denied_on_delete() {
        let mock = MockScmAdapter::new(ServiceState::Stopped);
        mock.delete_error
            .lock()
            .unwrap()
            .replace(ServiceError::AccessDenied);
        let (mgr, _mock_ref) = manager_with_mock(mock);
        let err = mgr.unregister().unwrap_err();
        assert!(matches!(err, ServiceError::AccessDenied));
    }

    #[test]
    fn unregister_propagates_query_error() {
        let mock = MockScmAdapter::new(ServiceState::Running);
        mock.query_error
            .lock()
            .unwrap()
            .replace(ServiceError::AccessDenied);
        let (mgr, mock_ref) = manager_with_mock(mock);
        let err = mgr.unregister().unwrap_err();
        assert!(matches!(err, ServiceError::AccessDenied));
        assert_eq!(mock_ref.calls(), vec!["query"]);
    }

    #[test]
    fn windows_service_manager_debug() {
        let mock = MockScmAdapter::new(ServiceState::Running);
        let (mgr, _mock_ref) = manager_with_mock(mock);
        let debug = format!("{mgr:?}");
        assert!(debug.contains("WindowsServiceManager"));
    }

    // --- Nonblocking SCM shutdown signal tests ---

    #[tokio::test]
    async fn stop_completes_the_async_shutdown_signal_once() {
        let (sender, receiver) = shutdown_channel();
        send_shutdown(&sender, "SCM_STOP");
        send_shutdown(&sender, "SCM_SHUTDOWN");
        assert_eq!(receiver.await, Ok("SCM_STOP"));
    }

    #[tokio::test]
    async fn shutdown_completes_the_async_shutdown_signal() {
        let (sender, receiver) = shutdown_channel();
        send_shutdown(&sender, "SCM_SHUTDOWN");
        assert_eq!(receiver.await, Ok("SCM_SHUTDOWN"));
    }

    #[tokio::test]
    async fn dropped_shutdown_sender_has_a_stable_reason() {
        let (sender, receiver) = shutdown_channel();
        drop(sender);
        assert_eq!(
            receiver.await.unwrap_or("SCM_CHANNEL_CLOSED"),
            "SCM_CHANNEL_CLOSED"
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn stop_control_maps_to_no_error_and_scm_stop() {
        use windows_service::service::ServiceControl;
        use windows_service::service_control_handler::ServiceControlHandlerResult;

        let (sender, mut receiver) = shutdown_channel();
        assert!(matches!(
            handle_service_control(ServiceControl::Stop, &sender),
            ServiceControlHandlerResult::NoError
        ));
        assert_eq!(receiver.try_recv(), Ok("SCM_STOP"));
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn shutdown_control_maps_to_no_error_and_scm_shutdown() {
        use windows_service::service::ServiceControl;
        use windows_service::service_control_handler::ServiceControlHandlerResult;

        let (sender, mut receiver) = shutdown_channel();
        assert!(matches!(
            handle_service_control(ServiceControl::Shutdown, &sender),
            ServiceControlHandlerResult::NoError
        ));
        assert_eq!(receiver.try_recv(), Ok("SCM_SHUTDOWN"));
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn interrogate_does_not_complete_shutdown() {
        use windows_service::service::ServiceControl;
        use windows_service::service_control_handler::ServiceControlHandlerResult;

        let (sender, mut receiver) = shutdown_channel();
        assert!(matches!(
            handle_service_control(ServiceControl::Interrogate, &sender),
            ServiceControlHandlerResult::NoError
        ));
        assert!(matches!(
            receiver.try_recv(),
            Err(tokio::sync::oneshot::error::TryRecvError::Empty)
        ));
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn unsupported_control_is_not_implemented_and_does_not_shutdown() {
        use windows_service::service::ServiceControl;
        use windows_service::service_control_handler::ServiceControlHandlerResult;

        let (sender, mut receiver) = shutdown_channel();
        assert!(matches!(
            handle_service_control(ServiceControl::Pause, &sender),
            ServiceControlHandlerResult::NotImplemented
        ));
        assert!(matches!(
            receiver.try_recv(),
            Err(tokio::sync::oneshot::error::TryRecvError::Empty)
        ));
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn duplicate_stop_and_shutdown_controls_preserve_first_reason() {
        use windows_service::service::ServiceControl;

        let (sender, mut receiver) = shutdown_channel();
        handle_service_control(ServiceControl::Stop, &sender);
        handle_service_control(ServiceControl::Shutdown, &sender);
        assert_eq!(receiver.try_recv(), Ok("SCM_STOP"));

        let (sender, mut receiver) = shutdown_channel();
        handle_service_control(ServiceControl::Shutdown, &sender);
        handle_service_control(ServiceControl::Stop, &sender);
        assert_eq!(receiver.try_recv(), Ok("SCM_SHUTDOWN"));
    }

    // --- ServiceError display tests ---

    #[test]
    fn service_error_access_denied_display() {
        let err = ServiceError::AccessDenied;
        let msg = format!("{err}");
        assert!(msg.contains("access denied"));
    }

    #[test]
    fn service_error_timeout_display() {
        let err = ServiceError::Timeout { waited_ms: 5000 };
        let msg = format!("{err}");
        assert!(msg.contains("5000"));
        assert!(msg.contains("timed out"));
    }

    // --- Exit code tests ---

    #[test]
    fn access_denied_maps_to_permission_denied() {
        let code = crate::cli::ExitCode::from(&ServiceError::AccessDenied);
        assert_eq!(code, crate::cli::ExitCode::PermissionDenied);
    }

    #[test]
    fn timeout_maps_to_service_error() {
        let code = crate::cli::ExitCode::from(&ServiceError::Timeout { waited_ms: 1000 });
        assert_eq!(code, crate::cli::ExitCode::ServiceError);
    }
}