troll 0.3.1

The port manager that guards the bridge: permanent claims, expiring leases, and a live view of who listens where.
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
use std::{
    fmt, fs,
    io::{self, Read, Write},
    path::{Component, Path},
};

use clap::error::ErrorKind;
use serde::{
    Deserialize, Deserializer, Serialize,
    de::{self, IgnoredAny, MapAccess, Visitor},
};
use serde_json::Value;
use time::OffsetDateTime;
use troll_core::{
    ClaimRequest, Permanent, Role,
    legacy::{Candidate, ClaimIdentity, Input, LeaseRangeClaim, Report, Source},
};

use crate::{
    error::{CliError, ErrorOutput},
    output::{self, SCHEMA},
};

use super::{Context, registry};

const MAX_LEGACY_FILE_BYTES: u64 = 1024 * 1024;

#[derive(Serialize)]
struct ImportOutput<'a> {
    schema: u32,
    #[serde(flatten)]
    report: Report<'a>,
    summary: Summary,
}

#[derive(Serialize)]
struct Summary {
    permanent_candidates: usize,
    dead_claims: usize,
    live_lease_range_claims: usize,
    unknown_lease_range_claims: usize,
    unparseable: usize,
    conflicts: usize,
    already_registered: usize,
    skipped: usize,
}

impl Summary {
    fn new(report: &Report<'_>) -> Self {
        Self {
            permanent_candidates: report.permanent_candidates.len(),
            dead_claims: report.dead_claims.len(),
            live_lease_range_claims: report.live_lease_range_claims.len(),
            unknown_lease_range_claims: report.unknown_lease_range_claims.len(),
            unparseable: report.unparseable.len(),
            conflicts: report.conflicts.len(),
            already_registered: report.already_registered.len(),
            skipped: report.skipped.len(),
        }
    }
}

#[derive(Serialize)]
struct ApplyOutput {
    schema: u32,
    written: Vec<Permanent>,
}

pub(super) fn run(context: &Context, dir: &Path, apply: bool, json: bool) -> Result<i32, CliError> {
    let dir = dir
        .canonicalize()
        .map_err(|err| path_error("open legacy directory", dir, err))?;
    require_separate_registry(&dir, &context.config.registry_home)?;
    let input = read_folder(&dir)?;
    let snapshot = context.store.load()?;
    let report = input.classify(
        &snapshot,
        &context.config.policy.lease_range,
        &context.probe,
        &context.probe,
        |pid| context.probe.process_start_time(pid),
    );
    let result = ImportOutput {
        schema: SCHEMA,
        summary: Summary::new(&report),
        report,
    };

    output::write(json, &result, |out| write_report(out, &result))?;
    if !apply {
        return Ok(0);
    }

    match apply_candidates(context, result.report.permanent_candidates) {
        Ok(written) if json => output::stderr_json(&ApplyOutput {
            schema: SCHEMA,
            written,
        }),
        Ok(written) => {
            let mut out = io::stdout().lock();
            writeln!(out, "Imported {} permanent claim(s).", written.len())?;
            for entry in written {
                writeln!(
                    out,
                    "  {} ({}) for {} · {}",
                    entry.port, entry.bind, entry.project, entry.service
                )?;
            }
        }
        Err(error) if json => {
            // The report has already been emitted. Keep stdout a single JSON document.
            let (kind, code) = error.kind_and_code();
            output::stderr_json(&ErrorOutput::new(kind, &error.to_string(), code));
            return Ok(i32::from(code));
        }
        Err(error) => return Err(error),
    }
    Ok(0)
}

fn read_folder(dir: &Path) -> Result<Input, CliError> {
    let entries = dir
        .read_dir()
        .and_then(|entries| entries.collect::<Result<Vec<_>, _>>())
        .map_err(|err| path_error("read legacy directory", dir, err))?;
    let mut entries = entries;
    entries.sort_by_key(fs::DirEntry::file_name);

    let mut input = Input::default();
    for entry in entries {
        let name = entry.file_name();
        let file = name
            .to_str()
            .map_or_else(|| format!("{name:?}"), str::to_owned);
        if file.eq_ignore_ascii_case("README.md") {
            input.skip(&file, "legacy convention document");
            continue;
        }
        match entry.file_type() {
            Ok(kind) if kind.is_dir() => continue,
            Ok(kind) if kind.is_file() => {}
            Ok(_) => {
                input.file_error(&file, "expected a regular file");
                continue;
            }
            Err(error) => {
                input.file_error(&file, format!("could not inspect file: {error}"));
                continue;
            }
        }

        let path = entry.path();
        let extension = path
            .extension()
            .and_then(|ext| ext.to_str())
            .map(str::to_ascii_lowercase);
        let extension = extension.as_deref();
        if !matches!(extension, Some("toml" | "md" | "json")) {
            input.file_error(&file, "unsupported legacy file extension");
            continue;
        }
        let text = match read_legacy_file(&entry) {
            Ok(Some(text)) => text,
            Ok(None) => {
                input.file_error(
                    &file,
                    format!("file larger than {MAX_LEGACY_FILE_BYTES} bytes"),
                );
                continue;
            }
            Err(error) => {
                input.file_error(&file, format!("could not read file: {error}"));
                continue;
            }
        };
        match extension {
            Some("toml") => input.parse_toml(&file, &text),
            Some("md") => input.parse_markdown(&file, &text),
            Some("json") if text.trim_start().starts_with('{') => match serde_json::from_str(&text)
            {
                Ok(record) => input.json_record(&file, record),
                Err(error) => input.json_record_error(
                    &file,
                    format!("invalid JSON claim: {error}"),
                    serde_json::from_str(&text)
                        .ok()
                        .or_else(|| recover_json_identity(&text)),
                ),
            },
            Some("json") => input.file_error(&file, "expected a JSON claim object"),
            _ => unreachable!("extension was checked before reading"),
        }
    }
    Ok(input)
}

fn recover_json_identity(text: &str) -> Option<ClaimIdentity> {
    // A regular JSON object map would silently keep only the last value for
    // each key. Keep every release marker and require exactly one port key.
    #[derive(Default)]
    struct Fields {
        port: Option<Value>,
        statuses: Vec<String>,
    }

    struct FieldsVisitor;

    impl<'de> Visitor<'de> for FieldsVisitor {
        type Value = Fields;

        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            formatter.write_str("a JSON claim object")
        }

        fn visit_map<M: MapAccess<'de>>(self, mut map: M) -> Result<Fields, M::Error> {
            let mut fields = Fields::default();
            while let Some(key) = map.next_key::<String>()? {
                match key.as_str() {
                    "port" if fields.port.is_some() => {
                        return Err(de::Error::duplicate_field("port"));
                    }
                    "port" => fields.port = Some(map.next_value()?),
                    "status" | "state" => {
                        if let Value::String(status) = map.next_value()? {
                            fields.statuses.push(status);
                        }
                    }
                    _ => {
                        map.next_value::<IgnoredAny>()?;
                    }
                }
            }
            Ok(fields)
        }
    }

    impl<'de> Deserialize<'de> for Fields {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            deserializer.deserialize_map(FieldsVisitor)
        }
    }

    let fields: Fields = serde_json::from_str(text).ok()?;
    let port = fields.port?.as_u64()?.try_into().ok()?;
    Some(ClaimIdentity::recovered_from_port(
        port,
        fields.statuses.iter().map(String::as_str),
    ))
}

fn read_legacy_file(entry: &fs::DirEntry) -> io::Result<Option<String>> {
    if entry.metadata()?.len() > MAX_LEGACY_FILE_BYTES {
        return Ok(None);
    }

    read_legacy_text(fs::File::open(entry.path())?)
}

fn read_legacy_text(reader: impl Read) -> io::Result<Option<String>> {
    let mut bytes = Vec::new();
    reader
        .take(MAX_LEGACY_FILE_BYTES + 1)
        .read_to_end(&mut bytes)?;
    if bytes.len() as u64 > MAX_LEGACY_FILE_BYTES {
        return Ok(None);
    }
    String::from_utf8(bytes).map(Some).map_err(|_| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            "stream did not contain valid UTF-8",
        )
    })
}

fn require_separate_registry(source: &Path, home: &Path) -> Result<(), CliError> {
    // Resolve symlink aliases, even when only the registry's ancestor exists.
    for ancestor in home.ancestors() {
        let resolved = match ancestor.canonicalize() {
            Ok(path) => path,
            Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
            Err(error) => return Err(path_error("resolve registry home", home, error)),
        };
        if resolved.starts_with(source) {
            return Err(CliError::Usage(clap::Error::raw(
                ErrorKind::ValueValidation,
                "the registry home must be outside the legacy directory",
            )));
        }
        let suffix = home.strip_prefix(ancestor).expect("ancestor is a prefix");
        if suffix.components().any(|part| part == Component::ParentDir) {
            return Err(CliError::Usage(clap::Error::raw(
                ErrorKind::ValueValidation,
                "the unresolved part of the registry home must not contain '..'",
            )));
        }
        break;
    }
    Ok(())
}

fn path_error(operation: &'static str, path: &Path, error: io::Error) -> CliError {
    CliError::SetupIo(operation, path.to_owned(), error)
}

pub(crate) fn apply_candidates(
    context: &Context,
    candidates: Vec<Candidate>,
) -> Result<Vec<Permanent>, CliError> {
    if candidates.is_empty() {
        return Ok(Vec::new());
    }
    let today = OffsetDateTime::now_utc().date();
    let claimed_by = registry::holder();
    let requests = candidates
        .into_iter()
        .map(|candidate| {
            (
                ClaimRequest {
                    port: candidate.port,
                    bind: Some(candidate.bind),
                    project: candidate.project,
                    service: candidate.service,
                    claimed_by: claimed_by.clone(),
                    role: candidate.role,
                    container: candidate
                        .container
                        .filter(|_| candidate.role == Role::Service),
                    used_by: None,
                    web: None,
                    component: None,
                },
                candidate.claimed.unwrap_or(today),
            )
        })
        .collect();
    context.ensure_registry_home()?;
    Ok(troll_core::claim_batch(&context.store, requests)?)
}

fn write_report(out: &mut dyn Write, output: &ImportOutput<'_>) -> Result<(), CliError> {
    let ImportOutput {
        report, summary, ..
    } = output;
    writeln!(
        out,
        "Permanent candidates ({})",
        summary.permanent_candidates
    )?;
    for entry in &report.permanent_candidates {
        write_candidate(out, "  ", entry)?;
    }
    writeln!(out, "Dead claims ({})", summary.dead_claims)?;
    for entry in &report.dead_claims {
        write_source(out, "  ", &entry.source)?;
        writeln!(
            out,
            "port {} for {:?} · {:?} · {:?}",
            entry.port, entry.project, entry.reason, entry.source_text
        )?;
    }
    writeln!(
        out,
        "Live listeners in the lease range ({})",
        summary.live_lease_range_claims
    )?;
    for entry in &report.live_lease_range_claims {
        write_lease_range_claim(out, entry)?;
        writeln!(out)?;
    }
    writeln!(
        out,
        "Unknown listener state in the lease range ({})",
        summary.unknown_lease_range_claims
    )?;
    for entry in &report.unknown_lease_range_claims {
        write_lease_range_claim(out, &entry.claim)?;
        writeln!(out, " · {:?}", entry.listener_check_error)?;
    }
    writeln!(out, "Unparseable ({})", summary.unparseable)?;
    for entry in &report.unparseable {
        write_source(out, "  ", &entry.source)?;
        writeln!(out, "{:?}", entry.reason)?;
    }
    writeln!(out, "Conflicts ({})", summary.conflicts)?;
    for conflict in &report.conflicts {
        writeln!(out, "  Port {} · {}", conflict.port, conflict.reason)?;
        for entry in &conflict.candidates {
            write_candidate(out, "    ", entry)?;
        }
        for entry in &conflict.invalid_claimants {
            write_source(out, "    ", &entry.source)?;
            writeln!(out, "Invalid claim · {:?}", entry.reason)?;
        }
        for entry in &conflict.registry {
            if let Some(service) = entry.service {
                writeln!(
                    out,
                    "    Registry · {} · {:?} · {service:?}",
                    entry.bind, entry.project
                )?;
            } else {
                writeln!(
                    out,
                    "    Registry lease · {} · {:?}",
                    entry.bind, entry.project
                )?;
            }
        }
    }
    writeln!(out, "Already registered ({})", summary.already_registered)?;
    for entry in &report.already_registered {
        write_candidate(out, "  ", entry)?;
    }
    writeln!(out, "Skipped ({})", summary.skipped)?;
    for entry in &report.skipped {
        write_source(out, "  ", &entry.source)?;
        writeln!(out, "{}", entry.reason)?;
    }
    Ok(())
}

fn write_candidate(out: &mut dyn Write, indent: &str, entry: &Candidate) -> io::Result<()> {
    write_source(out, indent, &entry.source)?;
    let role = match entry.role {
        Role::App => "app",
        Role::Service => "service",
    };
    write!(
        out,
        "{} ({}) · {:?} · {:?} · {role}",
        entry.port, entry.bind, entry.project, entry.service,
    )?;
    if let Some(date) = entry.claimed {
        write!(out, " · claimed {date}")?;
    }
    if let Some(container) = &entry.container {
        write!(out, " · container {container:?}")?;
    }
    if let Some(error) = &entry.process_check_error {
        write!(out, " · process check ({error:?})")?;
    } else if let Some(process) = entry.process {
        write!(out, " · PID {} live", process.pid)?;
    }
    writeln!(out, " · source text {:?}", entry.source_text)
}

fn write_lease_range_claim(out: &mut dyn Write, claim: &LeaseRangeClaim) -> io::Result<()> {
    write_source(out, "  ", &claim.source)?;
    write!(out, "port {} for {:?}", claim.port, claim.project)
}

fn write_source(out: &mut dyn Write, indent: &str, source: &Source) -> io::Result<()> {
    write!(out, "{indent}{:?}", source.file)?;
    if let Some(line) = source.line {
        write!(out, " line {line}")?;
    }
    if let Some(section) = &source.section {
        write!(out, " section {section:?}")?;
    }
    if let Some(entry) = source.entry {
        write!(out, " entry {entry}")?;
    }
    write!(out, " · ")
}

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

    #[test]
    fn bounded_legacy_reader_stops_after_the_first_excess_byte() {
        let mut reader = io::repeat(b'x').take(MAX_LEGACY_FILE_BYTES + 2);

        assert!(read_legacy_text(&mut reader).unwrap().is_none());
        assert_eq!(reader.limit(), 1);
    }
}