torzy 0.1.0

Minimal Tor-routed worker launcher library and CLI
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
//! Minimal Tor-routed worker launching.
//!
//! `torzy` starts one Tor SOCKS route per worker, prepares an isolated worker
//! workspace, and runs a caller-supplied shell command once per worker. The CLI
//! and library both call [`run`], so embedded and command-line behavior stay on
//! the same code path.
//!
//! The default command is intentionally local and quiet. Network checks are left
//! to the caller-supplied command.
//!
//! ```no_run
//! use torzy::{run, LaunchConfig};
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//!     let summary = run(
//!         LaunchConfig {
//!             envs: 5,
//!             command: "printf 'worker=%s ready\\n' \"$TOR_WORKER_ID\"".to_string(),
//!             ..LaunchConfig::default()
//!         },
//!         None,
//!     )
//!     .await?;
//!
//!     println!("{} workers succeeded", summary.succeeded);
//!     Ok(())
//! }
//! ```

use std::collections::{BTreeMap, HashSet};
use std::ffi::OsString;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use anyhow::{Context, Result, bail};
use serde::Serialize;
#[cfg(unix)]
use std::os::unix::process::CommandExt;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::{Child, Command};
use tokio::sync::{Semaphore, mpsc};
use tokio::time::{sleep, timeout};

/// Local default command used when no command is supplied.
pub const DEFAULT_COMMAND: &str = "printf 'torzy worker %s ready\\n' \"$TOR_WORKER_ID\"";

/// Configuration for one `torzy` run.
#[derive(Clone, Debug)]
pub struct LaunchConfig {
    /// Number of workers and Tor routes to prepare. Values below `1` become `1`.
    pub envs: usize,
    /// Shell command run once per worker through `/bin/sh -lc`.
    pub command: String,
    /// Explicit SOCKS routes, one per worker. Leave empty to auto-generate routes.
    pub tor_routes: Vec<String>,
    /// First SOCKS port used for auto-generated local routes.
    pub base_socks_port: u16,
    /// Per-worker timeout.
    pub timeout: Duration,
    /// Maximum workers running at once. Defaults to available CPU parallelism.
    pub max_concurrent: Option<usize>,
    /// Per-worker memory limit in MiB. `0` means unlimited.
    pub memory_limit_mb: u64,
    /// Root directory for runtime data. Defaults to a temporary directory.
    pub root_dir: Option<PathBuf>,
    /// Keep worker workspaces after completion.
    pub keep_workspaces: bool,
    /// Start and stop Tor instances automatically.
    pub manage_tor: bool,
    /// Tor executable path.
    pub tor_binary: String,
    /// Per-instance Tor bootstrap timeout.
    pub tor_timeout: Duration,
    /// Persistent Tor data directory. Defaults to runtime data under `root_dir`.
    pub tor_data_dir: Option<PathBuf>,
    /// Do not start Tor or run real commands; emit simulated success events.
    pub dry_run: bool,
    /// Export proxy environment variables to each worker.
    pub proxy_env: bool,
    /// Command working directory. Defaults to each isolated worker workspace.
    pub working_directory: Option<PathBuf>,
    /// Extra environment variables for workers.
    pub extra_env: BTreeMap<String, String>,
}

impl Default for LaunchConfig {
    fn default() -> Self {
        Self {
            envs: 5,
            command: DEFAULT_COMMAND.to_string(),
            tor_routes: Vec::new(),
            base_socks_port: 9050,
            timeout: Duration::from_secs(120),
            max_concurrent: None,
            memory_limit_mb: 0,
            root_dir: None,
            keep_workspaces: false,
            manage_tor: true,
            tor_binary: "tor".to_string(),
            tor_timeout: Duration::from_secs(90),
            tor_data_dir: None,
            dry_run: false,
            proxy_env: true,
            working_directory: None,
            extra_env: BTreeMap::new(),
        }
    }
}

/// Output stream that produced a worker line.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub enum StreamKind {
    /// Worker standard output.
    Stdout,
    /// Worker standard error.
    Stderr,
}

impl StreamKind {
    /// Stable lowercase label.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Stdout => "stdout",
            Self::Stderr => "stderr",
        }
    }
}

/// Final worker status.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub enum WorkerStatus {
    /// Worker exited successfully.
    Succeeded,
    /// Worker exited unsuccessfully or could not spawn.
    Failed,
    /// Worker exceeded its timeout.
    TimedOut,
    /// Worker was terminated by the launcher.
    Killed,
}

impl WorkerStatus {
    /// Stable lowercase label.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Succeeded => "succeeded",
            Self::Failed => "failed",
            Self::TimedOut => "timed_out",
            Self::Killed => "killed",
        }
    }
}

/// Runtime event emitted by [`run`].
#[derive(Clone, Debug)]
pub enum TorzyEvent {
    /// Tor process was started for a worker.
    TorStarted { id: usize },
    /// Tor bootstrap percentage advanced.
    TorBootstrap { id: usize, pct: u8 },
    /// Tor route is ready.
    TorReady { id: usize },
    /// Tor route failed to start or bootstrap.
    TorFailed { id: usize, detail: String },
    /// Managed Tor process was stopped.
    TorStopped { id: usize },
    /// All routes are ready and workers are launching.
    WorkersReady,
    /// Worker process was started.
    WorkerStarted { id: usize },
    /// Redacted worker output line.
    WorkerOutput {
        id: usize,
        stream: StreamKind,
        line: String,
    },
    /// Worker reached a terminal status.
    WorkerFinished {
        id: usize,
        status: WorkerStatus,
        exit_code: Option<i32>,
        detail: Option<String>,
    },
}

/// JSON-friendly worker summary.
#[derive(Clone, Debug, Serialize)]
pub struct WorkerSummary {
    /// Zero-based worker id.
    pub id: usize,
    /// Final status label.
    pub status: String,
    /// Process exit code when available.
    pub exit_code: Option<i32>,
    /// Redacted failure or timeout detail when available.
    pub detail: Option<String>,
    /// Worker runtime in milliseconds.
    pub duration_ms: u128,
}

/// JSON-friendly run summary that avoids command, route, path, and output data.
#[derive(Clone, Debug, Serialize)]
pub struct RunSummary {
    /// Start time as seconds since Unix epoch.
    pub started_at_unix: u64,
    /// End time as seconds since Unix epoch.
    pub ended_at_unix: u64,
    /// Number of configured workers.
    pub total_envs: usize,
    /// Maximum worker concurrency used for the run.
    pub max_concurrent: usize,
    /// Per-worker memory limit in MiB.
    pub memory_limit_mb: u64,
    /// Whether `torzy` managed Tor processes.
    pub managed_tor: bool,
    /// Whether this was a dry run.
    pub dry_run: bool,
    /// Whether proxy environment variables were exported to workers.
    pub proxy_env: bool,
    /// Workers that reached a terminal status.
    pub completed: usize,
    /// Workers that succeeded.
    pub succeeded: usize,
    /// Workers that failed.
    pub failed: usize,
    /// Workers that timed out.
    pub timed_out: usize,
    /// Workers killed by the launcher.
    pub killed: usize,
    /// Per-worker status summaries.
    pub workers: Vec<WorkerSummary>,
}

#[derive(Clone)]
struct WorkerConfig {
    id: usize,
    command: String,
    tor_route: String,
    timeout: Duration,
    root: PathBuf,
    workspace: PathBuf,
    working_directory: Option<PathBuf>,
    memory_limit_mb: u64,
    keep_workspace: bool,
    proxy_env: bool,
    extra_env: BTreeMap<String, String>,
}

struct ManagedTor {
    id: usize,
    child: Child,
}

/// Run the configured Tor-routed workers.
///
/// The optional event sender receives sanitized progress and worker output. The
/// returned summary intentionally omits commands, routes, filesystem paths, and
/// output lines.
pub async fn run(
    config: LaunchConfig,
    events: Option<mpsc::UnboundedSender<TorzyEvent>>,
) -> Result<RunSummary> {
    let envs = config.envs.max(1);
    let max_concurrent = config
        .max_concurrent
        .unwrap_or_else(|| {
            std::thread::available_parallelism()
                .map(|n| n.get())
                .unwrap_or(4)
        })
        .max(1);
    let tor_routes = routes_for_config(&config, envs)?;

    let started = Instant::now();
    let started_at_unix = unix_now();
    let root = config.root_dir.clone().unwrap_or_else(|| {
        std::env::temp_dir().join(format!("torzy-{started_at_unix}-{}", std::process::id()))
    });
    tokio::fs::create_dir_all(&root)
        .await
        .context("creating root directory")?;

    let mut tor_instances = if config.manage_tor && !config.dry_run {
        start_tor_instances(&config, &tor_routes, &root, &events).await?
    } else {
        Vec::new()
    };

    emit(&events, TorzyEvent::WorkersReady);

    let semaphore = Arc::new(Semaphore::new(max_concurrent));
    let mut handles = Vec::with_capacity(envs);
    for (id, tor_route) in tor_routes.iter().enumerate() {
        let workspace = root.join("workers").join(format!("worker-{id}"));
        let worker = WorkerConfig {
            id,
            command: config.command.clone(),
            tor_route: tor_route.clone(),
            timeout: config.timeout,
            root: root.clone(),
            workspace,
            working_directory: config.working_directory.clone(),
            memory_limit_mb: config.memory_limit_mb,
            keep_workspace: config.keep_workspaces,
            proxy_env: config.proxy_env,
            extra_env: config.extra_env.clone(),
        };
        let events = events.clone();
        let semaphore = semaphore.clone();
        let dry_run = config.dry_run;
        handles.push((
            id,
            tokio::spawn(async move { run_worker(worker, dry_run, semaphore, events).await }),
        ));
    }

    let mut workers = Vec::with_capacity(envs);
    for (id, handle) in handles {
        match handle.await {
            Ok(summary) => workers.push(summary),
            Err(error) => workers.push(WorkerSummary {
                id,
                status: WorkerStatus::Failed.as_str().to_string(),
                exit_code: None,
                detail: Some(redact_detail(&format!("worker task join error: {error}"))),
                duration_ms: 0,
            }),
        }
    }
    workers.sort_by_key(|worker| worker.id);

    stop_tor_instances(&mut tor_instances, &events).await;
    if !config.keep_workspaces && config.tor_data_dir.is_none() {
        let _ = tokio::fs::remove_dir_all(root.join("tor-data")).await;
    }

    let ended_at_unix = unix_now();
    Ok(build_summary(
        started_at_unix,
        ended_at_unix,
        &config,
        max_concurrent,
        workers,
        started,
    ))
}

/// Generate local SOCKS route strings from a base port.
pub fn generate_tor_routes(env_count: usize, base_socks_port: u16) -> Result<Vec<String>> {
    let mut routes = Vec::with_capacity(env_count.max(1));
    for id in 0..env_count.max(1) {
        let offset = u16::try_from(id).context("too many environments for SOCKS port range")?;
        let port = base_socks_port
            .checked_add(offset)
            .context("base SOCKS port plus environment count exceeds port range")?;
        routes.push(format!("socks5h://127.0.0.1:{port}"));
    }
    Ok(routes)
}

/// Validate that explicit routes are non-empty, unique, and match worker count.
pub fn validate_tor_routes(routes: &[String], env_count: usize) -> Result<()> {
    if routes.len() != env_count.max(1) {
        bail!(
            "got {} tor route(s), but env count is {}; provide exactly one route per worker",
            routes.len(),
            env_count.max(1),
        );
    }

    let mut unique = HashSet::new();
    for route in routes {
        if route.trim().is_empty() {
            bail!("tor routes cannot be empty");
        }
        if !unique.insert(route) {
            bail!("duplicate tor route provided");
        }
    }

    Ok(())
}

/// Expand command placeholders for a worker.
pub fn expand_command_template(
    raw: &str,
    tor_route: &str,
    worker_id: usize,
    root: &Path,
    workspace: &Path,
) -> String {
    raw.replace("{TOR_ROUTE}", tor_route)
        .replace("{TOR_WORKER_ID}", &worker_id.to_string())
        .replace("{WORKER_ID}", &worker_id.to_string())
        .replace("{TORZY_ROOT}", root.to_string_lossy().as_ref())
        .replace("{TORZY_WORKSPACE}", workspace.to_string_lossy().as_ref())
}

/// Redact route strings, runtime paths, and public network-address tokens.
pub fn redact_line(line: &str) -> String {
    redact_line_with_context(line, None, None)
}

fn routes_for_config(config: &LaunchConfig, envs: usize) -> Result<Vec<String>> {
    if config.tor_routes.is_empty() {
        generate_tor_routes(envs, config.base_socks_port)
    } else {
        validate_tor_routes(&config.tor_routes, envs)?;
        Ok(config.tor_routes.clone())
    }
}

async fn start_tor_instances(
    config: &LaunchConfig,
    routes: &[String],
    root: &Path,
    events: &Option<mpsc::UnboundedSender<TorzyEvent>>,
) -> Result<Vec<ManagedTor>> {
    let tor_data_root = config
        .tor_data_dir
        .clone()
        .unwrap_or_else(|| root.join("tor-data"));
    tokio::fs::create_dir_all(&tor_data_root)
        .await
        .context("creating tor data directory")?;

    let mut instances = Vec::with_capacity(routes.len());
    let mut boot_handles = Vec::with_capacity(routes.len());

    for (id, route) in routes.iter().enumerate() {
        let port = extract_port(route)?;
        let data_dir = tor_data_root.join(format!("tor-{port}"));
        tokio::fs::create_dir_all(&data_dir)
            .await
            .context("creating tor data directory")?;

        let empty_torrc = data_dir.join("torrc");
        tokio::fs::write(&empty_torrc, "")
            .await
            .context("writing empty torrc")?;

        let mut child = Command::new(&config.tor_binary)
            .arg("-f")
            .arg(&empty_torrc)
            .arg("--SocksPort")
            .arg(port.to_string())
            .arg("--DataDirectory")
            .arg(&data_dir)
            .arg("--PidFile")
            .arg(data_dir.join("tor.pid"))
            .arg("--Log")
            .arg("notice stderr")
            .stdout(Stdio::null())
            .stderr(Stdio::piped())
            .stdin(Stdio::null())
            .spawn()
            .with_context(|| "failed to start tor binary; install tor or pass --tor-binary")?;

        emit(events, TorzyEvent::TorStarted { id });
        let stderr = child
            .stderr
            .take()
            .context("managed tor process did not expose stderr")?;
        let events_for_reader = events.clone();
        boot_handles.push((
            id,
            tokio::spawn(async move { read_tor_bootstrap(id, stderr, events_for_reader).await }),
        ));
        instances.push(ManagedTor { id, child });
    }

    for (id, handle) in boot_handles {
        match timeout(config.tor_timeout, handle).await {
            Ok(Ok(Ok(()))) => {}
            Ok(Ok(Err(error))) => {
                let detail = redact_detail(&error.to_string());
                emit(&events, TorzyEvent::TorFailed { id, detail });
                stop_tor_instances(&mut instances, events).await;
                return Err(error);
            }
            Ok(Err(error)) => {
                let detail = redact_detail(&format!("tor bootstrap task failed: {error}"));
                emit(
                    &events,
                    TorzyEvent::TorFailed {
                        id,
                        detail: detail.clone(),
                    },
                );
                stop_tor_instances(&mut instances, events).await;
                bail!(detail);
            }
            Err(_) => {
                let detail = format!(
                    "tor did not bootstrap within {}s",
                    config.tor_timeout.as_secs()
                );
                emit(
                    &events,
                    TorzyEvent::TorFailed {
                        id,
                        detail: detail.clone(),
                    },
                );
                stop_tor_instances(&mut instances, events).await;
                bail!(detail);
            }
        }
    }

    Ok(instances)
}

async fn read_tor_bootstrap<R>(
    id: usize,
    source: R,
    events: Option<mpsc::UnboundedSender<TorzyEvent>>,
) -> Result<()>
where
    R: tokio::io::AsyncRead + Unpin,
{
    let reader = BufReader::new(source);
    let mut lines = reader.lines();
    let mut last_pct = 0;

    while let Some(line) = lines.next_line().await? {
        if let Some(pct) = parse_bootstrap_pct(&line) {
            if pct > last_pct {
                last_pct = pct;
                emit(&events, TorzyEvent::TorBootstrap { id, pct });
            }
            if pct >= 100 {
                emit(&events, TorzyEvent::TorReady { id });
                return Ok(());
            }
        }
    }

    bail!("tor exited before bootstrap completed")
}

async fn stop_tor_instances(
    instances: &mut [ManagedTor],
    events: &Option<mpsc::UnboundedSender<TorzyEvent>>,
) {
    for instance in instances {
        let _ = instance.child.kill().await;
        let _ = instance.child.wait().await;
        emit(events, TorzyEvent::TorStopped { id: instance.id });
    }
}

async fn run_worker(
    config: WorkerConfig,
    dry_run: bool,
    semaphore: Arc<Semaphore>,
    events: Option<mpsc::UnboundedSender<TorzyEvent>>,
) -> WorkerSummary {
    let _permit = semaphore.acquire().await.expect("semaphore closed");
    let started = Instant::now();

    if dry_run {
        emit(&events, TorzyEvent::WorkerStarted { id: config.id });
        for i in 0..3 {
            emit(
                &events,
                TorzyEvent::WorkerOutput {
                    id: config.id,
                    stream: StreamKind::Stdout,
                    line: format!("dry-run {i}: worker ready"),
                },
            );
            sleep(Duration::from_millis(40)).await;
        }
        emit(
            &events,
            TorzyEvent::WorkerFinished {
                id: config.id,
                status: WorkerStatus::Succeeded,
                exit_code: Some(0),
                detail: Some("dry run done".to_string()),
            },
        );
        return worker_summary(
            &config,
            WorkerStatus::Succeeded,
            Some(0),
            Some("dry run done".to_string()),
            started,
        );
    }

    if let Err(error) = prepare_worker_workspace(&config).await {
        let detail = redact_detail(&error.to_string());
        emit(
            &events,
            TorzyEvent::WorkerFinished {
                id: config.id,
                status: WorkerStatus::Failed,
                exit_code: None,
                detail: Some(detail.clone()),
            },
        );
        return worker_summary(&config, WorkerStatus::Failed, None, Some(detail), started);
    }

    let command = expand_command_template(
        &config.command,
        &config.tor_route,
        config.id,
        &config.root,
        &config.workspace,
    );
    let current_dir = config
        .working_directory
        .clone()
        .unwrap_or_else(|| config.workspace.clone());

    let cargo_home = config.workspace.join(".cargo");
    let cargo_target_dir = config.workspace.join("target");
    let worker_path = worker_path(&cargo_home);
    let mem_bytes = if config.memory_limit_mb > 0 {
        config.memory_limit_mb.saturating_mul(1024 * 1024)
    } else {
        0
    };

    let mut std_cmd = std::process::Command::new("/bin/sh");
    std_cmd
        .arg("-lc")
        .arg(&command)
        .current_dir(&current_dir)
        .env("HOME", &config.workspace)
        .env("TMPDIR", config.workspace.join(".tmp"))
        .env("CARGO_HOME", &cargo_home)
        .env("CARGO_TARGET_DIR", &cargo_target_dir)
        .env("PATH", worker_path)
        .env("TOR_WORKER_ID", config.id.to_string())
        .env("TOR_ROUTE", &config.tor_route)
        .env("TORZY_ROOT", &config.root)
        .env("TORZY_WORKSPACE", &config.workspace)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .stdin(Stdio::null());

    if config.proxy_env {
        for key in [
            "ALL_PROXY",
            "HTTPS_PROXY",
            "HTTP_PROXY",
            "all_proxy",
            "https_proxy",
            "http_proxy",
            "CARGO_HTTP_PROXY",
        ] {
            std_cmd.env(key, &config.tor_route);
        }
    }

    for (key, value) in &config.extra_env {
        std_cmd.env(key, value);
    }

    #[cfg(unix)]
    unsafe {
        std_cmd.pre_exec(move || {
            libc::setsid();
            if mem_bytes > 0 {
                let lim = libc::rlimit {
                    rlim_cur: mem_bytes as libc::rlim_t,
                    rlim_max: mem_bytes as libc::rlim_t,
                };
                libc::setrlimit(libc::RLIMIT_AS, &lim);
                libc::setrlimit(libc::RLIMIT_RSS, &lim);
            }
            libc::nice(19);
            Ok(())
        });
    }

    let mut child = match Command::from(std_cmd).spawn() {
        Ok(child) => child,
        Err(error) => {
            let detail = redact_detail(&format!("failed to spawn worker: {error}"));
            emit(
                &events,
                TorzyEvent::WorkerFinished {
                    id: config.id,
                    status: WorkerStatus::Failed,
                    exit_code: None,
                    detail: Some(detail.clone()),
                },
            );
            return worker_summary(&config, WorkerStatus::Failed, None, Some(detail), started);
        }
    };

    emit(&events, TorzyEvent::WorkerStarted { id: config.id });

    if let Some(stdout) = child.stdout.take() {
        tokio::spawn(capture_lines(
            config.id,
            StreamKind::Stdout,
            stdout,
            config.root.clone(),
            config.workspace.clone(),
            events.clone(),
        ));
    }
    if let Some(stderr) = child.stderr.take() {
        tokio::spawn(capture_lines(
            config.id,
            StreamKind::Stderr,
            stderr,
            config.root.clone(),
            config.workspace.clone(),
            events.clone(),
        ));
    }

    let (wait_result, timed_out) = tokio::select! {
        result = child.wait() => (result, false),
        _ = sleep(config.timeout) => {
            kill_worker(&mut child).await;
            (child.wait().await, true)
        }
    };

    let (status, exit_code, detail) = match wait_result {
        Ok(status) if timed_out => (
            WorkerStatus::TimedOut,
            status.code(),
            Some(format!("timed out at {}s", config.timeout.as_secs())),
        ),
        Ok(status) if status.success() => (WorkerStatus::Succeeded, status.code(), None),
        Ok(status) => (
            WorkerStatus::Failed,
            status.code(),
            Some(format!("exit code {}", status.code().unwrap_or(-1))),
        ),
        Err(error) => (
            WorkerStatus::Failed,
            None,
            Some(redact_detail(&format!("worker wait error: {error}"))),
        ),
    };

    emit(
        &events,
        TorzyEvent::WorkerFinished {
            id: config.id,
            status,
            exit_code,
            detail: detail.clone(),
        },
    );

    if !config.keep_workspace {
        let _ = tokio::fs::remove_dir_all(&config.workspace).await;
    }

    worker_summary(&config, status, exit_code, detail, started)
}

async fn prepare_worker_workspace(config: &WorkerConfig) -> Result<()> {
    for path in [
        config.workspace.clone(),
        config.workspace.join(".tmp"),
        config.workspace.join(".cargo"),
        config.workspace.join("target"),
    ] {
        tokio::fs::create_dir_all(&path)
            .await
            .context("creating worker directory")?;
    }
    Ok(())
}

async fn capture_lines<R>(
    id: usize,
    stream: StreamKind,
    source: R,
    root: PathBuf,
    workspace: PathBuf,
    events: Option<mpsc::UnboundedSender<TorzyEvent>>,
) where
    R: tokio::io::AsyncRead + Unpin,
{
    let reader = BufReader::new(source);
    let mut lines = reader.lines();

    while let Ok(Some(line)) = lines.next_line().await {
        let line = redact_line_with_context(&line, Some(&root), Some(&workspace));
        emit(&events, TorzyEvent::WorkerOutput { id, stream, line });
    }
}

async fn kill_worker(child: &mut Child) {
    #[cfg(unix)]
    if let Some(pid) = child.id() {
        let pgid = -(pid as i32);
        unsafe {
            libc::kill(pgid, libc::SIGTERM);
        }
        sleep(Duration::from_secs(3)).await;
        unsafe {
            libc::kill(pgid, libc::SIGKILL);
        }
    }

    let _ = child.kill().await;
}

fn worker_path(cargo_home: &Path) -> OsString {
    let mut entries = vec![cargo_home.join("bin")];
    if let Some(path) = std::env::var_os("PATH") {
        entries.extend(std::env::split_paths(&path));
    }
    std::env::join_paths(entries).unwrap_or_else(|_| OsString::new())
}

fn worker_summary(
    config: &WorkerConfig,
    status: WorkerStatus,
    exit_code: Option<i32>,
    detail: Option<String>,
    started: Instant,
) -> WorkerSummary {
    WorkerSummary {
        id: config.id,
        status: status.as_str().to_string(),
        exit_code,
        detail: detail.map(|value| redact_detail(&value)),
        duration_ms: started.elapsed().as_millis(),
    }
}

fn build_summary(
    started_at_unix: u64,
    ended_at_unix: u64,
    config: &LaunchConfig,
    max_concurrent: usize,
    workers: Vec<WorkerSummary>,
    _started: Instant,
) -> RunSummary {
    let mut succeeded = 0;
    let mut failed = 0;
    let mut timed_out = 0;
    let mut killed = 0;

    for worker in &workers {
        match worker.status.as_str() {
            "succeeded" => succeeded += 1,
            "timed_out" => timed_out += 1,
            "killed" => killed += 1,
            _ => failed += 1,
        }
    }

    RunSummary {
        started_at_unix,
        ended_at_unix,
        total_envs: workers.len(),
        max_concurrent,
        memory_limit_mb: config.memory_limit_mb,
        managed_tor: config.manage_tor,
        dry_run: config.dry_run,
        proxy_env: config.proxy_env,
        completed: workers.len(),
        succeeded,
        failed,
        timed_out,
        killed,
        workers,
    }
}

fn extract_port(route: &str) -> Result<u16> {
    route
        .rsplit(':')
        .next()
        .and_then(|value| value.parse::<u16>().ok())
        .with_context(|| "route does not end with a valid port")
}

fn parse_bootstrap_pct(line: &str) -> Option<u8> {
    let start = line.find("Bootstrapped ")? + "Bootstrapped ".len();
    let pct_end = line[start..].find('%')? + start;
    line[start..pct_end].trim().parse::<u8>().ok()
}

fn redact_detail(value: &str) -> String {
    redact_line(value)
}

fn redact_line_with_context(line: &str, root: Option<&Path>, workspace: Option<&Path>) -> String {
    let mut value = line.to_string();

    if let Some(workspace) = workspace {
        let workspace = workspace.to_string_lossy();
        if !workspace.is_empty() {
            value = value.replace(workspace.as_ref(), "[torzy-workspace]");
        }
    }
    if let Some(root) = root {
        let root = root.to_string_lossy();
        if !root.is_empty() {
            value = value.replace(root.as_ref(), "[torzy-root]");
        }
    }

    value
        .split_whitespace()
        .map(redact_token)
        .collect::<Vec<_>>()
        .join(" ")
}

fn redact_token(token: &str) -> String {
    let trimmed = token.trim_matches(|ch: char| {
        matches!(
            ch,
            ',' | ';' | ')' | '(' | '[' | ']' | '{' | '}' | '<' | '>' | '"' | '\''
        )
    });

    if trimmed.starts_with("socks5://") || trimmed.starts_with("socks5h://") {
        return token.replace(trimmed, "[tor-route]");
    }

    if should_redact_addr(trimmed) {
        return token.replace(trimmed, "[addr-redacted]");
    }

    token.to_string()
}

fn should_redact_addr(value: &str) -> bool {
    if let Ok(addr) = value.parse::<Ipv4Addr>() {
        return redact_v4(addr);
    }
    if let Ok(addr) = value.parse::<Ipv6Addr>() {
        return !addr.is_loopback() && !addr.is_unspecified();
    }
    false
}

fn redact_v4(addr: Ipv4Addr) -> bool {
    let octets = addr.octets();
    !(addr.is_loopback()
        || addr.is_private()
        || addr.is_link_local()
        || addr.is_unspecified()
        || addr.is_broadcast()
        || octets[0] >= 224)
}

fn unix_now() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

fn emit(events: &Option<mpsc::UnboundedSender<TorzyEvent>>, event: TorzyEvent) {
    if let Some(events) = events {
        let _ = events.send(event);
    }
}

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

    #[test]
    fn generates_routes_from_base_port() {
        assert_eq!(
            generate_tor_routes(3, 9100).unwrap(),
            vec![
                "socks5h://127.0.0.1:9100",
                "socks5h://127.0.0.1:9101",
                "socks5h://127.0.0.1:9102",
            ]
        );
    }

    #[test]
    fn rejects_duplicate_routes() {
        let routes = vec![
            "socks5h://127.0.0.1:9050".to_string(),
            "socks5h://127.0.0.1:9050".to_string(),
        ];
        assert!(validate_tor_routes(&routes, 2).is_err());
    }

    #[test]
    fn expands_command_template() {
        let command = expand_command_template(
            "route={TOR_ROUTE} id={TOR_WORKER_ID} root={TORZY_ROOT} work={TORZY_WORKSPACE}",
            "socks5h://127.0.0.1:9050",
            7,
            Path::new("/tmp/root"),
            Path::new("/tmp/root/workers/worker-7"),
        );
        assert_eq!(
            command,
            "route=socks5h://127.0.0.1:9050 id=7 root=/tmp/root work=/tmp/root/workers/worker-7"
        );
    }

    #[test]
    fn parses_tor_bootstrap_percentage() {
        assert_eq!(
            parse_bootstrap_pct("Bootstrapped 100% (done): Done"),
            Some(100)
        );
        assert_eq!(parse_bootstrap_pct("not bootstrap"), None);
    }

    #[test]
    fn redacts_sensitive_tokens() {
        assert_eq!(
            redact_line("route socks5h://127.0.0.1:9050 public 203.0.113.9 local 127.0.0.1"),
            "route [tor-route] public [addr-redacted] local 127.0.0.1"
        );
    }

    #[tokio::test]
    async fn dry_run_succeeds_without_tor() {
        let root = std::env::temp_dir().join(format!("torzy-test-{}", unix_now()));
        let summary = run(
            LaunchConfig {
                envs: 2,
                dry_run: true,
                manage_tor: false,
                root_dir: Some(root.clone()),
                max_concurrent: Some(2),
                ..LaunchConfig::default()
            },
            None,
        )
        .await
        .unwrap();

        assert_eq!(summary.total_envs, 2);
        assert_eq!(summary.succeeded, 2);
        assert_eq!(summary.workers[0].status, "succeeded");
        let _ = tokio::fs::remove_dir_all(root).await;
    }
}