snip-sync 0.2.0

gRPC sync server for snp snippet manager
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
#![allow(clippy::uninlined_format_args)]

use clap::Parser;
use snip_sync::cli::{Cli, Command, StartupCommand};
use std::net::{SocketAddr, ToSocketAddrs};
use std::time::Duration;

mod update;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cli = Cli::parse();

    match cli.command {
        None | Some(Command::Serve) => serve()?,
        Some(Command::Init {
            force_cert,
            skip_cert,
        }) => cmd_init(force_cert, skip_cert)?,
        Some(Command::Cert { force, out_dir }) => {
            snip_sync::cert::generate_dev_certs(force, out_dir)?
        }
        Some(Command::Edit) => cmd_edit()?,
        Some(Command::Stop { force }) => cmd_stop(force)?,
        Some(Command::Restart { force }) => cmd_restart(force)?,
        Some(Command::Startup { command }) => match command {
            StartupCommand::Install { method } => {
                snip_sync::startup::install(method, &std::env::current_exe()?)?
            }
            StartupCommand::Instructions { method } => {
                snip_sync::startup::instructions(method, &std::env::current_exe()?)?
            }
            StartupCommand::Uninstall => snip_sync::startup::uninstall(&std::env::current_exe()?)?,
        },
        Some(Command::Update { dry_run, locked }) => update::run(dry_run, locked)?,
        Some(Command::SelfReplace {
            candidate,
            destination,
            restart,
            managed_restart,
        }) => update::run_self_replace_helper(&candidate, &destination, restart, managed_restart)?,
        Some(Command::Croncheck { verbose }) => cmd_croncheck(verbose)?,
        Some(Command::Paths { json }) => cmd_paths(json)?,
        Some(Command::Completions { shell }) => cmd_completions(shell),
        Some(Command::Version) => println!("snip-sync {}", env!("CARGO_PKG_VERSION")),
    }

    Ok(())
}

fn serve() -> Result<(), Box<dyn std::error::Error>> {
    tracing_subscriber::fmt().with_target(false).init();

    let env = |name: &str| std::env::var(name).ok();
    let tls_enabled = snip_sync::parse_bool_env(&env, "TLS_ENABLED")?.unwrap_or(false);
    let allow_http = snip_sync::parse_bool_env(&env, "SNIP_SYNC_ALLOW_HTTP")?.unwrap_or(false);

    tracing::info!("Starting snip-sync server v{}", env!("CARGO_PKG_VERSION"));

    if tls_enabled {
        tracing::warn!(
            "TLS_ENABLED acknowledges TLS termination by an upstream reverse proxy; snip-sync itself still serves plaintext gRPC and HTTP."
        );
    } else {
        if allow_http {
            tracing::warn!(
                "Serving plaintext gRPC and HTTP for local development. For production, put a \
                 TLS-terminating reverse proxy in front of snip-sync."
            );
        } else {
            tracing::error!(
                "snip-sync does not terminate TLS. Put a TLS-terminating reverse proxy in front \
                 of it and set TLS_ENABLED=true, or set SNIP_SYNC_ALLOW_HTTP=true for local development."
            );
            return Err(
                "TLS termination is required for production. Set TLS_ENABLED=true when a reverse proxy terminates TLS, or set SNIP_SYNC_ALLOW_HTTP=true for local development"
                    .into(),
            );
        }
    }

    snip_sync::bootstrap::ensure_layout()?;
    snip_sync::bootstrap::ensure_config_file()?;
    let config = snip_sync::Config::load()?;
    let grpc_addr = resolve_socket_addr(&config.grpc_host, config.grpc_port)?;
    let http_addr = resolve_socket_addr(&config.http_host, config.http_port)?;
    snip_sync::startup::validate_transport_policy(
        tls_enabled,
        allow_http,
        grpc_addr.ip().is_loopback(),
        http_addr.ip().is_loopback(),
    )?;

    // Acquire the kernel-backed server singleton lock. This is the
    // authoritative mutual-exclusion barrier; its identity metadata is for
    // diagnostics and stop/restart ownership checks.
    let state_dir = snip_sync::paths::state_dir();
    let _server_lock = match snip_sync::server_lock::ServerLock::try_acquire(&state_dir) {
        Ok(guard) => guard,
        Err(snip_sync::server_lock::ServerLockError::Busy { owner }) => {
            return Err(format!(
                "snip-sync server already running{}",
                owner
                    .map(|o| format!(" (pid={})", o.pid))
                    .unwrap_or_default()
            )
            .into());
        }
        Err(snip_sync::server_lock::ServerLockError::UnsupportedPlatform) => {
            return Err("snip-sync server lock is not supported on this platform".into());
        }
        Err(snip_sync::server_lock::ServerLockError::Io(e)) => {
            return Err(format!("Failed to acquire server lock: {e}").into());
        }
    };

    let rt = tokio::runtime::Runtime::new()?;
    // The kernel lock owns the current server identity for the lifetime of
    // the process. Older PID files are never created by new servers.
    rt.block_on(serve_inner(config))
}

async fn serve_inner(config: snip_sync::Config) -> Result<(), Box<dyn std::error::Error>> {
    use snip_proto::snippet_sync_server::SnippetSyncServer;
    use snip_sync::{AppState, Database, Metrics, PremadeManager, RateLimiter, SnipSyncService};
    use std::sync::Arc;
    use std::time::Duration;

    let db = Arc::new(Database::connect(&config.db_path, config.db_max_connections).await?);
    tracing::info!("Database initialized at {}", config.db_path);

    match db.migrate_plaintext_api_keys().await {
        Ok(count) if count > 0 => tracing::info!("Migrated {} API keys to hashed format", count),
        Ok(_) => tracing::debug!("No plaintext API keys to migrate"),
        Err(e) => {
            tracing::error!(
                "API key migration failed: {}. Halting startup to prevent auth lockout.",
                e
            );
            return Err(e.into());
        }
    }

    match db.migrate_snippet_visible_at().await {
        Ok(true) => {
            tracing::info!("Migrated snippets table: added the visible_at delta-cursor column")
        }
        Ok(false) => tracing::debug!("snippets table already has the visible_at column"),
        Err(e) => {
            tracing::error!(
                "visible_at migration failed: {}. Halting startup to keep the delta cursor consistent.",
                e
            );
            return Err(e.into());
        }
    }

    let grpc_addr = resolve_socket_addr(&config.grpc_host, config.grpc_port)?;
    let http_addr = resolve_socket_addr(&config.http_host, config.http_port)?;

    // Bind both listeners before spawning either service. This makes port and
    // address errors fail the command immediately instead of leaving a
    // half-started server running with a misleading successful exit.
    let grpc_listener = tokio::net::TcpListener::bind(grpc_addr).await?;
    let http_listener = tokio::net::TcpListener::bind(http_addr).await?;

    tracing::info!("gRPC server listening on {}", grpc_addr);
    tracing::info!("HTTP server listening on {}", http_addr);

    let rate_limiter = Arc::new(RateLimiter::new());
    let cors_allowed_origins = config.cors_allowed_origins.clone();

    tracing::info!(
        "Input validation config: max_command={}, max_encrypted_payload={}, max_description={}, max_tags={}, max_tag_length={}, request_timeout={}s",
        config.max_command_length,
        config.max_encrypted_payload_length,
        config.max_description_length,
        config.max_tags,
        config.max_tag_length,
        config.request_timeout_secs
    );

    let timeout = Duration::from_secs(config.request_timeout_secs);

    let metrics = match Metrics::new() {
        Ok(m) => m,
        Err(e) => {
            tracing::error!(
                "Failed to create metrics: {}. Metrics will be unavailable.",
                e
            );
            Metrics::fallback()
        }
    };

    if config.metrics_username.is_some() && config.metrics_password.is_some() {
        tracing::info!("Metrics endpoint enabled with authentication");
    } else if config.metrics_username.is_some() || config.metrics_password.is_some() {
        tracing::warn!(
            "Metrics endpoint disabled: both METRICS_USERNAME and METRICS_PASSWORD must be set (only one provided)"
        );
    } else {
        tracing::warn!("Metrics endpoint disabled: METRICS_USERNAME and METRICS_PASSWORD not set");
    }

    let premade_manager = PremadeManager::new(config.premade_dir.clone());
    if premade_manager.is_empty() {
        tracing::warn!(
            "No premade libraries found in {}",
            config.premade_dir.display()
        );
    } else {
        tracing::info!(
            "Premade libraries loaded from {}",
            config.premade_dir.display()
        );
    }

    let state = AppState {
        config: config.clone(),
        metrics: metrics.clone(),
        db: db.clone(),
        // One limiter for both listeners: the HTTP leaf's metrics-failure
        // budget shares this structure and its `MAX_ENTRIES` bound.
        rate_limiter: rate_limiter.clone(),
    };

    let grpc_max_message_size = config.grpc_max_message_size;

    let grpc_service = SnipSyncService {
        db: db.clone(),
        rate_limiter: rate_limiter.clone(),
        config,
        metrics,
        premade_manager,
        #[cfg(feature = "test-helpers")]
        captured_auth_header: Arc::new(std::sync::Mutex::new(None)),
        #[cfg(feature = "test-helpers")]
        test_observer: None,
        #[cfg(feature = "test-helpers")]
        push_fail_after: Arc::new(std::sync::atomic::AtomicU32::new(u32::MAX)),
        #[cfg(feature = "test-helpers")]
        push_fail_counter: Arc::new(std::sync::atomic::AtomicU32::new(0)),
    };

    let cors_allow_all =
        snip_sync::parse_bool_env(&|name| std::env::var(name).ok(), "CORS_ALLOW_ALL")?
            .unwrap_or(false);

    let loopback_bind = http_addr.ip().is_loopback();
    let cors_allow_all = if cors_allow_all && !loopback_bind {
        tracing::warn!(
            "CORS_ALLOW_ALL=true ignored: HTTP server bound to {} (non-loopback). \
             Set CORS_ALLOW_ALL only on loopback-bound servers.",
            http_addr
        );
        false
    } else {
        cors_allow_all
    };

    if cors_allow_all {
        tracing::info!("CORS: allowing all origins (CORS_ALLOW_ALL=true)");
    } else if cors_allowed_origins.is_empty() {
        tracing::warn!(
            "CORS: no origins configured. Cross-origin requests will be blocked. \
             Set CORS_ALLOWED_ORIGINS to allow specific origins, or CORS_ALLOW_ALL=true for permissive CORS."
        );
    } else {
        tracing::info!("CORS allowed origins: {:?}", cors_allowed_origins);
    }
    let http_service = snip_sync::http::service(
        state,
        snip_sync::http::CorsPolicy {
            allow_all: cors_allow_all,
            allowed_origins: cors_allowed_origins,
        },
    );

    // Start HTTP only after both listeners have been pre-bound, and before
    // spawning gRPC so a runtime startup error cannot leave gRPC detached.
    let http_runtime = eggserve_server::RuntimeConfig::builder()
        .bind(http_addr)
        .disable_connection_total_timeout()
        .graceful_shutdown_timeout(timeout)
        .build()?;
    let http_server = eggserve_server::Server::builder()
        .runtime(http_runtime)
        .from_listener(http_listener)
        .build()?
        .start_with_service(http_service)
        .await?;
    let (http_control, http_completion) = http_server.into_parts();
    tracing::info!("HTTP server listening on http://{}", http_addr);

    // Create a single broadcast shutdown signal. Both services receive
    // a clone of the receiver; the orchestrator sends exactly once.
    let (shutdown_tx, _) = tokio::sync::broadcast::channel::<()>(1);

    let grpc_shutdown_rx = shutdown_tx.subscribe();
    // No "listening" log after this expression: that point is only reached
    // once `serve_with_incoming_shutdown` has already terminated, so a log
    // there would emit a startup line at shutdown time on every run. The
    // bind-time log above (right after pre-binding both listeners) is the
    // real startup signal.
    let grpc_handle = tokio::spawn(async move {
        let incoming = tokio_stream::wrappers::TcpListenerStream::new(grpc_listener);
        tonic::transport::Server::builder()
            .timeout(timeout)
            .add_service(
                SnippetSyncServer::new(grpc_service)
                    .max_decoding_message_size(grpc_max_message_size as usize)
                    .max_encoding_message_size(grpc_max_message_size as usize),
            )
            .serve_with_incoming_shutdown(incoming, async move {
                let mut rx = grpc_shutdown_rx;
                let _ = rx.recv().await;
                tracing::info!("Shutdown signal received, stopping gRPC server...");
            })
            .await
    });

    // Wait for the first terminal event: a process signal, or an
    // unexpected service failure. The normal-operation wait has no
    // arbitrary lifetime timeout.
    //
    // On Unix we also listen for SIGTERM so that `snip-sync stop`
    // triggers the same graceful shutdown path as Ctrl-C.
    #[cfg(unix)]
    let mut sigterm_stream =
        tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
            .map_err(|e| format!("Failed to register SIGTERM handler: {e}"))?;

    #[cfg(unix)]
    let sigterm_fut = sigterm_stream.recv();
    #[cfg(not(unix))]
    let sigterm_fut = std::future::pending::<()>();

    // Build the shutdown signal future based on platform.
    #[cfg(unix)]
    let shutdown_signal = async {
        tokio::select! {
            biased;
            _ = tokio::signal::ctrl_c() => {
                tracing::info!("Ctrl-C received, initiating shutdown");
            }
            _ = sigterm_fut => {
                tracing::info!("SIGTERM received, initiating shutdown");
            }
        }
    };
    #[cfg(not(unix))]
    let shutdown_signal = async {
        let _ = tokio::signal::ctrl_c().await;
        tracing::info!("Ctrl-C received, initiating shutdown");
    };

    tokio::pin!(shutdown_signal);

    let outcome = snip_sync::orchestration::run_eggserve_services_until_shutdown(
        shutdown_signal.as_mut(),
        grpc_handle,
        http_control,
        http_completion,
        shutdown_tx,
        timeout,
    )
    .await;

    tracing::info!("Server shutdown complete");

    outcome.ensure_clean_requested_shutdown()?;

    Ok(())
}

fn cmd_init(force_cert: bool, skip_cert: bool) -> Result<(), Box<dyn std::error::Error>> {
    snip_sync::bootstrap::ensure_layout()?;
    snip_sync::bootstrap::ensure_config_file()?;
    if !skip_cert {
        snip_sync::cert::generate_dev_certs(force_cert, None)?;
    }
    println!("Initialization complete.");
    Ok(())
}

fn cmd_edit() -> Result<(), Box<dyn std::error::Error>> {
    snip_sync::bootstrap::ensure_layout()?;
    snip_sync::bootstrap::ensure_config_file()?;
    let config_path = snip_sync::paths::config_path();
    snip_sync::editor::open_in_editor(&config_path)?;
    Ok(())
}

fn cmd_stop(force: bool) -> Result<(), Box<dyn std::error::Error>> {
    let state_dir = snip_sync::paths::state_dir();
    match snip_sync::server_lock::ServerLock::try_acquire(&state_dir) {
        Err(snip_sync::server_lock::ServerLockError::Busy { owner: Some(owner) }) => {
            stop_owner(owner, force)
        }
        Err(snip_sync::server_lock::ServerLockError::Busy { owner: None }) => {
            Err("The server lock is busy but contains no usable owner metadata.".into())
        }
        Err(e) => Err(format!("Failed to inspect server lock: {e}").into()),
        Ok(guard) => {
            drop(guard);
            stop_legacy(force)
        }
    }
}

fn stop_owner(
    owner: snip_sync::server_lock::ServerLockIdentity,
    force: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    let pid = owner.pid;
    let identity_matches = snip_sync::process::is_running(pid)
        && owner
            .start_token
            .as_ref()
            .and_then(|expected| {
                snip_sync::process::get_process_start_token(pid).map(|actual| actual == *expected)
            })
            .unwrap_or(true);
    if !identity_matches {
        return Err(
            format!("Server lock owner PID {pid} is no longer the recorded process.").into(),
        );
    }
    #[cfg(unix)]
    if !force && !snip_sync::process::validate_process_name(pid) {
        eprintln!("Warning: PID {pid} does not appear to be a snip-sync process.");
        eprintln!("Use --force to stop it anyway.");
        return Err("Refusing to stop non-snip-sync process".into());
    }

    #[cfg(windows)]
    {
        let _ = force;
        println!("Terminating recorded server process {pid}...");
        snip_sync::process::terminate_process(pid, Duration::from_secs(10))?;
        return match snip_sync::server_lock::ServerLock::try_acquire(&snip_sync::paths::state_dir())
        {
            Ok(_guard) => {
                println!("Server stopped.");
                Ok(())
            }
            Err(snip_sync::server_lock::ServerLockError::Busy { .. }) => {
                println!("A replacement server has already started.");
                Ok(())
            }
            Err(error) => Err(format!("Failed to acquire server lock: {error}").into()),
        };
    }

    #[cfg(not(any(unix, windows)))]
    {
        let _ = (pid, force);
        return Err("Stop is not supported on this platform.".into());
    }

    #[cfg(unix)]
    {
        let signal_pid = i32::try_from(pid).map_err(|_| format!("PID {pid} is out of range"))?;
        println!("Sending SIGTERM to process {pid}...");
        unsafe { libc::kill(signal_pid, libc::SIGTERM) };
        let exit_result = snip_sync::process::wait_for_exit(pid, Duration::from_secs(10));
        if let Err(error) = &exit_result {
            eprintln!("Warning: {error}");
            if !force {
                return Err(error.clone().into());
            }
            println!("Sending SIGKILL...");
            unsafe { libc::kill(signal_pid, libc::SIGKILL) };
            let _ = snip_sync::process::wait_for_exit(pid, Duration::from_secs(5));
        }

        match snip_sync::server_lock::ServerLock::try_acquire(&snip_sync::paths::state_dir()) {
            Ok(_guard) => {
                if exit_result.is_ok() {
                    println!("Server stopped.");
                } else {
                    println!("Server killed.");
                }
                Ok(())
            }
            Err(snip_sync::server_lock::ServerLockError::Busy { .. }) => {
                println!("A replacement server has already started.");
                Ok(())
            }
            Err(error) => Err(format!("Failed to acquire server lock: {error}").into()),
        }
    }
}

fn stop_legacy(force: bool) -> Result<(), Box<dyn std::error::Error>> {
    let state_dir = snip_sync::paths::state_dir();
    let expected = snip_sync::process::parse_pid_file(&snip_sync::paths::pid_path());
    let pid = match &expected {
        snip_sync::process::ParsedPidFile::Structured(record) => record.pid,
        snip_sync::process::ParsedPidFile::LegacyPid(pid) => *pid,
        snip_sync::process::ParsedPidFile::Empty => {
            return Err("No usable PID file found. Is the server running?".into());
        }
        snip_sync::process::ParsedPidFile::Malformed(message) => {
            return Err(format!("PID file is malformed: {message}. Remove or replace it.").into());
        }
    };

    #[cfg(not(unix))]
    if matches!(expected, snip_sync::process::ParsedPidFile::LegacyPid(_)) {
        eprintln!("Stop is only supported on Unix systems.");
        return Err("Unsupported platform".into());
    }

    let structured_matches = match &expected {
        snip_sync::process::ParsedPidFile::Structured(record) => {
            snip_sync::process::record_still_matches(record)
        }
        snip_sync::process::ParsedPidFile::LegacyPid(pid) => snip_sync::process::is_running(*pid),
        _ => false,
    };

    if !structured_matches {
        println!(
            "Process {} is not running (or its identity no longer matches the PID file). Cleaning up stale PID file.",
            pid
        );
        match snip_sync::server_lock::ServerLock::try_acquire(&state_dir) {
            Ok(_guard) => {
                snip_sync::process::remove_pid_if_unchanged(&expected);
                Ok(())
            }
            Err(snip_sync::server_lock::ServerLockError::Busy { .. }) => Ok(()),
            Err(e) => Err(format!("Failed to acquire server lock: {e}").into()),
        }
    } else if !force && !snip_sync::process::validate_process_name(pid) {
        eprintln!(
            "Warning: PID {} does not appear to be a snip-sync process.",
            pid
        );
        eprintln!("Use --force to stop it anyway.");
        Err("Refusing to stop non-snip-sync process".into())
    } else {
        #[cfg(not(unix))]
        {
            let _ = expected;
            eprintln!("Stop is only supported on Unix systems.");
            return Err("Unsupported platform".into());
        }

        #[cfg(unix)]
        {
            let signal_pid =
                i32::try_from(pid).map_err(|_| format!("PID {pid} is out of range"))?;
            println!("Sending SIGTERM to process {}...", pid);
            unsafe { libc::kill(signal_pid, libc::SIGTERM) };

            let exit_result =
                snip_sync::process::wait_for_exit(pid, std::time::Duration::from_secs(10));
            if let Err(ref e) = exit_result {
                eprintln!("Warning: {}", e);
                if !force {
                    return Err(exit_result.unwrap_err().into());
                }
                println!("Sending SIGKILL...");
                unsafe { libc::kill(signal_pid, libc::SIGKILL) };
                let _ = snip_sync::process::wait_for_exit(pid, std::time::Duration::from_secs(5));
            }

            // Acquire the server singleton lock before unlinking the
            // PID record. If a new server has already started, the lock
            // is busy and we leave its PID file alone.
            match snip_sync::server_lock::ServerLock::try_acquire(&state_dir) {
                Ok(_guard) => {
                    // Re-verify the on-disk record still identifies the process we
                    // just stopped before removing it. Legacy records compare by PID.
                    snip_sync::process::remove_pid_if_unchanged(&expected);
                    if exit_result.is_ok() {
                        println!("Server stopped.");
                    } else {
                        println!("Server killed.");
                    }
                    Ok(())
                }
                Err(snip_sync::server_lock::ServerLockError::Busy { .. }) => {
                    println!(
                        "A replacement server has already started; leaving its PID file in place."
                    );
                    Ok(())
                }
                Err(e) => Err(format!("Failed to acquire server lock: {e}").into()),
            }
        }
    }
}

fn cmd_restart(force: bool) -> Result<(), Box<dyn std::error::Error>> {
    if snip_sync::startup::restart_if_managed(&std::env::current_exe()?, force)? {
        return Ok(());
    }
    let state_dir = snip_sync::paths::state_dir();
    if let Err(snip_sync::server_lock::ServerLockError::Busy { owner: Some(owner) }) =
        snip_sync::server_lock::ServerLock::try_acquire(&state_dir)
    {
        println!("Stopping existing server (PID {})...", owner.pid);
        cmd_stop(force)?;
    } else {
        match snip_sync::process::parse_pid_file(&snip_sync::paths::pid_path()) {
            snip_sync::process::ParsedPidFile::Structured(record)
                if snip_sync::process::record_still_matches(&record) =>
            {
                println!("Stopping existing server (PID {})...", record.pid);
                cmd_stop(force)?;
            }
            snip_sync::process::ParsedPidFile::LegacyPid(pid) => {
                println!("Stopping existing server (PID {pid})...");
                cmd_stop(force)?;
            }
            snip_sync::process::ParsedPidFile::Malformed(message) => {
                return Err(
                    format!("PID file is malformed: {message}. Remove or replace it.").into(),
                );
            }
            snip_sync::process::ParsedPidFile::Empty
            | snip_sync::process::ParsedPidFile::Structured(_) => {
                println!("No running server found.");
            }
        }
    }
    println!("Starting server...");
    serve()
}

fn resolve_socket_addr(host: &str, port: u16) -> Result<SocketAddr, Box<dyn std::error::Error>> {
    let host = host.trim();
    let address = if host.contains(':') && !host.starts_with('[') {
        format!("[{host}]:{port}")
    } else {
        format!("{host}:{port}")
    };
    address
        .to_socket_addrs()?
        .next()
        .ok_or_else(|| format!("Could not resolve {address}").into())
}

fn cmd_croncheck(verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    snip_sync::bootstrap::ensure_layout()?;
    snip_sync::bootstrap::ensure_config_file()?;
    let lock_path = snip_sync::paths::state_dir().join("croncheck.lock");
    let _lock = match snip_sync::process::try_lock(&lock_path)? {
        Some(lock) => lock,
        None => {
            if verbose {
                println!("Another croncheck is already running; skipping this check.");
            }
            return Ok(());
        }
    };

    let config = snip_sync::Config::load()?;

    if snip_sync::startup::check_health(&config.http_host, config.http_port) {
        if verbose {
            println!(
                "Server is healthy on {}:{}",
                config.http_host, config.http_port
            );
        } else {
            println!("ok");
        }
        return Ok(());
    }

    if verbose {
        println!(
            "Server is unhealthy or not running on {}:{}.",
            config.http_host, config.http_port
        );
        println!("Starting detached server...");
    }

    let child = std::process::Command::new(std::env::current_exe()?)
        .arg("serve")
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
        .map_err(|e| format!("Failed to spawn server: {}", e))?;

    if verbose {
        println!("Spawned server process (PID {}).", child.id());
    }

    // Wait briefly for the server to come up. A failed health check is an
    // error: cron callers must be able to alert instead of receiving a false
    // success when `serve` exits during startup.
    for _ in 0..20 {
        std::thread::sleep(std::time::Duration::from_millis(250));
        if snip_sync::startup::check_health(&config.http_host, config.http_port) {
            if verbose {
                println!("Server started successfully.");
            }
            println!("ok");
            return Ok(());
        }
    }

    Err("Server did not become healthy within 5 seconds; inspect the service logs".into())
}

fn cmd_paths(json: bool) -> Result<(), Box<dyn std::error::Error>> {
    let paths = snip_sync::paths::Paths::resolve();
    if json {
        let map = serde_json::json!({
            "config_dir": paths.config_dir,
            "config_path": paths.config_path,
            "data_dir": paths.data_dir,
            "state_dir": paths.state_dir,
            "cert_dir": paths.cert_dir,
            "pid_path": paths.pid_path,
            "db_path": paths.db_path,
            "premade_dir": paths.premade_dir,
        });
        println!("{}", serde_json::to_string_pretty(&map)?);
    } else {
        paths.print();
    }
    Ok(())
}

fn cmd_completions(shell: clap_complete::Shell) {
    let mut cmd = <Cli as clap::CommandFactory>::command();
    let bin_name = "snip-sync".to_string();
    clap_complete::generate(shell, &mut cmd, bin_name, &mut std::io::stdout());
}