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
//! Daemon management functionality for the kasl watch command.
//!
//! Provides comprehensive background process management for the kasl activity
//! monitoring system including spawning, signal handling, and graceful shutdown.
//!
//! ## Features
//!
//! - **Process Spawning**: Creates detached background processes for continuous monitoring
//! - **Signal Handling**: Responds to system signals for graceful shutdown and restart
//! - **PID Management**: Tracks running processes and prevents duplicate instances
//! - **Cross-Platform Support**: Handles platform differences between Unix and Windows
//! - **Resource Cleanup**: Ensures proper cleanup of database connections and system resources
//! - **Error Recovery**: Manages process failures and provides meaningful error messages
//!
//! ## Usage
//!
//! ```rust,no_run
//! # async fn f() -> anyhow::Result<()> {
//! use kasl::libs::daemon;
//!
//! daemon::spawn()?; // Start background monitoring
//! daemon::stop()?; // Stop background monitoring
//! daemon::run_with_signal_handling().await?; // Run with signal handling
//! # Ok(())
//! # }
//! ```
use crateConfig;
use crateDataStorage;
use crateMessage;
use crateMonitor;
use crate::;
use Result;
use Duration;
use ;
/// PID file name used for tracking the daemon process.
///
/// This constant defines the filename used to store the process ID of the
/// running daemon. The file is created in the application data directory
/// when the daemon starts and removed when it shuts down gracefully.
///
/// The PID file serves multiple purposes:
/// - **Process Tracking**: Allows the main process to find and communicate with the daemon
/// - **Duplicate Prevention**: Prevents multiple daemon instances from running simultaneously
/// - **Status Checking**: Enables status queries about the daemon's running state
/// - **Cleanup Detection**: Helps identify when the daemon terminates unexpectedly
const PID_FILE: &str = "kasl-watch.pid";
/// Runs the daemon with proper signal handling for graceful shutdown.
///
/// Sets up comprehensive signal handling and runs the activity monitor in a
/// controlled environment. Designed to be the main entry point for daemon operation.
///
/// # Returns
///
/// Returns `Ok(())` when the daemon shuts down cleanly, or an error if
/// initialization fails or a critical error occurs during operation.
///
/// - **Signal Handler Setup**: Platform signal APIs not available
/// - **Monitor Initialization**: Database connection or configuration errors
/// - **Runtime Errors**: Critical failures during monitoring operation
/// - **Cleanup Failures**: Unable to remove PID file or close resources
///
/// # Usage Context
///
/// This function is typically called from:
/// - Background daemon processes spawned by [`spawn()`]
/// - Foreground monitoring mode for debugging
/// - Test environments requiring controlled shutdown
pub async
/// The core logic that initializes and runs the activity monitor.
///
/// This function handles the complete lifecycle of the activity monitoring
/// system, from configuration loading through monitor initialization to
/// the main monitoring loop execution.
///
/// ## Initialization Process
///
/// 1. **Configuration Loading**: Reads monitor settings from the config file
/// 2. **Default Application**: Applies sensible defaults for missing configuration
/// 3. **Monitor Creation**: Initializes the monitor with the loaded configuration
/// 4. **Loop Execution**: Starts the continuous activity monitoring loop
///
/// ## Configuration Handling
///
/// The function uses a robust configuration loading strategy:
/// - **Primary Source**: User configuration file
/// - **Fallback**: Built-in default values
/// - **Validation**: Ensures configuration values are within valid ranges
/// - **Error Recovery**: Continues with defaults if configuration is invalid
///
/// ## Monitor Components
///
/// The initialized monitor includes:
/// - **Input Detection**: Keyboard and mouse activity tracking
/// - **Database Interface**: Connection to SQLite database for data storage
/// - **State Management**: Activity state tracking and transition logic
/// - **Timing Control**: Configurable polling intervals and thresholds
///
/// ## Error Propagation
///
/// This function properly propagates errors from:
/// - Configuration loading failures
/// - Database connection issues
/// - Monitor initialization problems
/// - Runtime monitoring errors
///
/// # Returns
///
/// Returns `Ok(())` when monitoring completes successfully, or an error
/// if any part of the initialization or execution process fails.
///
/// # Error Scenarios
///
/// - **Configuration Errors**: Invalid or corrupted configuration file
/// - **Database Errors**: Cannot connect to or initialize the SQLite database
/// - **Permission Errors**: Insufficient privileges for input device monitoring
/// - **Resource Errors**: System resource exhaustion or availability issues
///
/// # Usage Context
///
/// This function is called by:
/// - [`run_with_signal_handling()`] for daemon operation
/// - Foreground monitoring mode for interactive debugging
/// - Test environments for controlled monitoring scenarios
async
/// Spawns the application as a detached background process.
///
/// This function creates a new background process that runs independently
/// of the parent process. It handles platform-specific process creation,
/// PID file management, and ensures only one daemon instance runs at a time.
///
/// ## Process Management
///
/// 1. **Existing Process Check**: Verifies no daemon is already running
/// 2. **Process Termination**: Stops any existing daemon before starting new one
/// 3. **Process Creation**: Spawns new daemon with platform-specific flags
/// 4. **PID Recording**: Saves the new process ID for future management
/// 5. **Status Reporting**: Provides feedback about the spawning operation
///
/// ## Platform-Specific Spawning
///
/// ### Unix Systems
/// ```text
/// std::process::Command::new(current_exe)
/// .arg("--daemon-run")
/// .pre_exec(|| {
/// nix::unistd::setsid()?; // Create new session
/// Ok(())
/// })
/// .spawn()?;
/// ```
///
/// ### Windows
/// ```text
/// std::process::Command::new(current_exe)
/// .arg("--daemon-run")
/// .creation_flags(CREATE_NO_WINDOW) // Hide console window
/// .spawn()?;
/// ```
///
/// ## Duplicate Prevention
///
/// The function prevents multiple daemon instances by:
/// - Checking for existing PID files
/// - Validating that the process in the PID file is actually running
/// - Terminating stale processes before starting new ones
/// - Cleaning up orphaned PID files
///
/// ## Error Recovery
///
/// If stopping an existing daemon fails:
/// - Issues a warning but continues with spawning
/// - Removes stale PID files to prevent conflicts
/// - Allows a brief delay for process cleanup
/// - Proceeds with new daemon creation
///
/// # Returns
///
/// Returns `Ok(())` if the daemon was successfully spawned and the PID file
/// was created, or an error if the spawning process fails.
///
/// # Error Scenarios
///
/// - **Executable Not Found**: Cannot locate the current executable
/// - **Permission Denied**: Insufficient privileges for process creation
/// - **Resource Exhaustion**: System cannot create new processes
/// - **PID File Creation**: Cannot write PID file to application directory
/// - **Platform Unsupported**: Daemon mode not available on the current platform
///
/// # Usage Examples
///
/// ```rust,no_run
/// # fn main() -> anyhow::Result<()> {
/// use kasl::libs::daemon;
///
/// // Start background monitoring
/// daemon::spawn()?;
/// println!("Background monitoring started");
/// # Ok(())
/// # }
/// ```
///
/// # Security Considerations
///
/// - The spawned process runs with the same privileges as the parent
/// - PID files are created with user-readable permissions only
/// - No sensitive information is passed via command line arguments
/// - Process isolation is maintained through session separation (Unix)
/// Finds and stops the running daemon process.
///
/// This function provides a user-friendly interface for stopping the daemon
/// process. It handles cases where no daemon is running gracefully and
/// provides appropriate feedback to the user.
///
/// ## Operation Flow
///
/// 1. **Process Lookup**: Searches for running daemon using PID file
/// 2. **Termination**: Attempts to terminate the found process
/// 3. **Cleanup**: Removes PID file and other resources
/// 4. **Status Reporting**: Provides feedback about the operation result
///
/// ## Error Handling Strategy
///
/// This function uses a forgiving error handling approach:
/// - **Process Not Found**: Reports "not running" instead of error
/// - **Stale PID File**: Cleans up orphaned files without complaint
/// - **Permission Issues**: Reports specific error details
/// - **Cleanup Failures**: Continues operation, reports warnings
///
/// ## User Experience
///
/// The function prioritizes clear user communication:
/// - Success messages confirm the daemon was stopped
/// - "Not running" messages avoid unnecessary error reports
/// - Specific error messages help with troubleshooting
/// - Consistent behavior across multiple invocations
///
/// # Returns
///
/// Returns `Ok(())` in most cases, including when no daemon is running.
/// Only returns errors for serious system-level failures that require
/// user attention.
///
/// # Error Scenarios
///
/// - **Permission Denied**: Insufficient privileges to terminate the process
/// - **System Errors**: Platform-specific process management failures
/// - **Resource Issues**: System resource exhaustion during termination
///
/// # Usage Examples
///
/// ```rust,no_run
/// # fn main() -> anyhow::Result<()> {
/// use kasl::libs::daemon;
///
/// // Stop background monitoring
/// daemon::stop()?;
/// println!("Monitoring stopped");
/// # Ok(())
/// # }
/// ```
///
/// # Idempotent Operation
///
/// This function is safe to call multiple times and will not produce
/// errors if called when no daemon is running. This makes it suitable
/// for use in cleanup scripts and automated scenarios.
/// Checks if the daemon is currently running.
///
/// This function determines whether a daemon process is currently active by
/// checking for the existence and validity of the PID file and verifying
/// that the corresponding process is still running.
///
/// # Returns
///
/// Returns `true` if the daemon is running, `false` otherwise.
/// This function does not return errors - it treats any failure to
/// verify the daemon as "not running".
/// Checks if a process with the given PID is currently running.
///
/// This function uses platform-specific methods to verify if a process
/// exists and is running. It's used internally by daemon management
/// functions to validate process state.
///
/// # Arguments
///
/// * `pid` - The process ID to check
///
/// # Returns
///
/// Returns `true` if the process is running, `false` otherwise.
/// Internal function to stop the daemon, used by both stop and spawn.
///
/// This function performs the actual daemon termination logic without
/// the user-friendly error handling of the public [`stop()`] function.
/// It's used internally when precise error information is needed.
///
/// ## Termination Process
///
/// 1. **PID File Validation**: Checks that PID file exists and is readable
/// 2. **PID Parsing**: Validates that PID file contains a valid process ID
/// 3. **Process Termination**: Uses platform-specific termination methods
/// 4. **File Cleanup**: Removes PID file regardless of termination result
/// 5. **Result Validation**: Confirms the process was actually terminated
///
/// ## Error Propagation
///
/// Unlike the public interface, this function propagates all errors:
/// - **File Not Found**: PID file doesn't exist
/// - **Invalid Content**: PID file contains invalid data
/// - **Process Not Found**: Process ID is not running
/// - **Termination Failed**: Process couldn't be terminated
///
/// ## Cleanup Guarantee
///
/// The function guarantees PID file cleanup even if process termination
/// fails. This prevents stale PID files from interfering with future
/// daemon operations.
///
/// # Returns
///
/// Returns `Ok(())` if the daemon was successfully terminated, or an
/// error describing the specific failure encountered.
///
/// # Error Scenarios
///
/// - **No PID File**: Daemon is not running or PID file was removed
/// - **Invalid PID**: PID file contains corrupted or invalid data
/// - **Process Not Found**: Process ID does not correspond to running process
/// - **Termination Failed**: Process exists but couldn't be terminated
///
/// # Usage Context
///
/// This function is used internally by:
/// - [`stop()`] for user-initiated daemon termination
/// - [`spawn()`] for replacing existing daemon instances
/// - Test utilities for controlled daemon lifecycle management
/// Cross-platform process termination for Windows systems.
///
/// This function uses Windows-specific APIs to terminate a process by its
/// process ID. It handles Windows process management through the WinAPI
/// and provides detailed error information for troubleshooting.
///
/// ## Windows Process Management
///
/// The function uses these WinAPI functions:
/// - `OpenProcess()`: Opens a handle to the target process
/// - `TerminateProcess()`: Forcibly terminates the process
/// - `CloseHandle()`: Releases the process handle
/// - `GetLastError()`: Retrieves detailed error information
///
/// ## Error Handling
///
/// Windows-specific error codes are handled:
/// - **ERROR_INVALID_PARAMETER (87)**: Process doesn't exist
/// - **ACCESS_DENIED**: Insufficient privileges
/// - **INVALID_HANDLE**: Process handle creation failed
///
/// ## Termination Strategy
///
/// The function uses forceful termination (`TerminateProcess`) rather than
/// graceful shutdown signals. While less elegant than Unix signals, this
/// ensures reliable process termination on Windows systems.
///
/// ## Safety Considerations
///
/// - Process handles are properly closed to prevent resource leaks
/// - Error conditions are checked after each API call
/// - Brief delay allows for process cleanup before returning
///
/// # Arguments
///
/// * `pid` - The process ID of the target process to terminate
///
/// # Returns
///
/// Returns `Ok(true)` if the process was successfully terminated,
/// `Ok(false)` if the process doesn't exist, or an error if termination fails.
///
/// # Error Scenarios
///
/// - **Access Denied**: Insufficient privileges to terminate the process
/// - **Invalid Handle**: Cannot open process handle
/// - **Termination Failed**: Process exists but termination failed
///
/// # Platform Availability
///
/// This function is only available on Windows platforms and will not
/// compile on Unix-like systems.
/// Cross-platform process termination for Unix-like systems.
///
/// This function uses Unix command-line tools to terminate a process by its
/// process ID. It implements a graceful termination strategy that attempts
/// polite shutdown before resorting to forceful termination.
///
/// ## Termination Strategy
///
/// 1. **Process Validation**: Uses `ps` to verify the process exists
/// 2. **Graceful Termination**: Sends SIGTERM for clean shutdown
/// 3. **Wait Period**: Allows time for graceful shutdown (1 second)
/// 4. **Forced Termination**: Sends SIGKILL if graceful shutdown fails
/// 5. **Final Validation**: Confirms the process was terminated
///
/// ## Signal Handling
///
/// - **SIGTERM**: Requests graceful shutdown, allows cleanup
/// - **SIGKILL**: Forces immediate termination, no cleanup possible
///
/// ## Command Dependencies
///
/// This function requires standard Unix utilities:
/// - `ps`: Process status checking
/// - `kill`: Signal sending
///
/// These are available on virtually all Unix-like systems including
/// Linux, macOS, BSD variants, and Solaris.
///
/// ## Graceful Shutdown Benefits
///
/// The graceful termination approach provides several advantages:
/// - Allows proper cleanup of resources
/// - Enables database transaction completion
/// - Provides opportunity for state saving
/// - Reduces risk of data corruption
///
/// # Arguments
///
/// * `pid` - The process ID of the target process to terminate
///
/// # Returns
///
/// Returns `Ok(true)` if the process was successfully terminated,
/// `Ok(false)` if the process doesn't exist, or an error if termination fails.
///
/// # Error Scenarios
///
/// - **Process Not Found**: Process ID doesn't correspond to running process
/// - **Permission Denied**: Insufficient privileges to send signals
/// - **Command Failed**: `ps` or `kill` commands not available or failed
/// - **Persistent Process**: Process survives both SIGTERM and SIGKILL
///
/// # Platform Availability
///
/// This function is only available on Unix-like platforms and will not
/// compile on Windows systems.