canic-host 0.109.8

Host-side App build, Fleet install, deployment, and release-set library for Canic workspaces
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
//! Module: install_root::fleet_install_session
//!
//! Responsibility: own the durable Fleet identity and install operation for one fresh install.
//! Does not own: Coordinator, Fleet Subnet Root, Store, Registry, or activation effects.
//! Boundary: typed-schema retries recover one immutable session before terminal catalog closure.

#[cfg(test)]
mod tests;

use crate::{
    durable_io::{
        BoundedRegularFileReadError, CanonicalJsonEncodeError, CanonicalJsonStyle,
        RegularFileLockError, RegularFileReadError, create_new_bytes_with_parents,
        encode_canonical_json, lock_regular_file_with_parents, read_optional_bounded_regular_bytes,
        read_optional_regular_bytes,
    },
    entropy::{EntropyError, random_bytes_32},
    release_build::{
        FinalizedReleaseBuild, ReleaseBuildPlanError, ReleaseBuildPlanState,
        load_finalized_release_build,
    },
};
use crate::{
    fleet_catalog::FleetCatalogEntryV1,
    install_root::fleet_component_provisioning_journal::{
        FleetComponentProvisioningTerminalEvidence, JOURNAL_SCHEMA_VERSION,
    },
};
use std::{
    io,
    path::{Path, PathBuf},
};

use canic_core::ids::{
    AppId, CanonicalNetworkId, FleetBinding, FleetId, FleetKey, FleetName, ReleaseBuildId,
};
use serde::{Deserialize, Serialize};
use thiserror::Error as ThisError;

const SESSION_FILE: &str = "session.json";
const SESSION_LOCK_FILE: &str = "session.lock";
const SESSION_SCHEMA_VERSION: u32 = 1;
const MAX_SESSION_BYTES: usize = 16_384;
const COMPLETION_FILE: &str = "completion.json";
const COMPLETION_LOCK_FILE: &str = "completion.lock";
const COMPLETION_SCHEMA_VERSION: u32 = 1;
const MAX_COMPLETION_BYTES: usize = 65_536;

///
/// FleetInstallSession
///
/// Immutable pre-effect identity shared by every journal in one fresh Fleet install.
///

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub(super) struct FleetInstallSession {
    pub schema_version: u32,
    pub fleet_name: FleetName,
    pub fleet: FleetBinding,
    pub release_build_id: ReleaseBuildId,
    pub release_build_plan_digest: [u8; 32],
    pub release_set_manifest_digest: [u8; 32],
    pub decision_release_build_id: Option<ReleaseBuildId>,
    pub fresh_fleet_plan_digest: String,
    pub operation_id: [u8; 32],
}

///
/// PlanFleetInstallSessionRequest
///
/// Exact finalized authority required before allocating or recovering a Fleet identity.
///

pub(super) struct PlanFleetInstallSessionRequest<'a> {
    pub root: &'a Path,
    pub canonical_network_id: CanonicalNetworkId,
    pub fleet_name: FleetName,
    pub app: AppId,
    pub finalized_release_build: &'a FinalizedReleaseBuild,
    pub decision_release_build_id: Option<ReleaseBuildId>,
    pub fresh_fleet_plan_digest: &'a str,
}

/// Exact plan/release authority retained for same-release install recovery.
pub(super) struct RecoveredFleetInstallAuthority {
    pub session: FleetInstallSession,
    pub finalized_release_build: FinalizedReleaseBuild,
    pub decision_release_build_id: Option<ReleaseBuildId>,
    pub fresh_fleet_plan_digest: String,
}

/// Bounded read-only identity for one authoritative incomplete Fleet install session.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RetainedFleetInstallSessionSummaryV1 {
    pub fleet_name: FleetName,
    pub app: AppId,
    pub release_build_id: ReleaseBuildId,
    pub fresh_fleet_plan_digest: String,
    pub operation_id: [u8; 32],
}

/// Exact terminal catalog evidence that permanently closes one fresh-install session.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
struct FleetInstallCompletionV1 {
    schema_version: u32,
    session_schema_version: u32,
    fleet_name: FleetName,
    fleet: FleetBinding,
    release_build_id: ReleaseBuildId,
    fresh_fleet_plan_digest: String,
    fleet_install_operation_id: [u8; 32],
    fleet_install_plan_digest: [u8; 32],
    component_journal_schema_version: u32,
    component_journal_sequence: u64,
    component_journal_digest: [u8; 32],
    component_provisioning_operation_id: [u8; 32],
    component_provisioning_plan_hash: [u8; 32],
    catalog_entry: FleetCatalogEntryV1,
    catalog_hash: [u8; 32],
}

pub(super) struct CloseFleetInstallSessionRequest<'a> {
    pub root: &'a Path,
    pub session: &'a FleetInstallSession,
    pub component_journal: &'a FleetComponentProvisioningTerminalEvidence,
}

///
/// FleetInstallSessionError
///
/// Typed failure while publishing or recovering immutable fresh-install identity.
///

#[derive(Debug, ThisError)]
pub(super) enum FleetInstallSessionError {
    #[error("Fleet install session already has different immutable authority: {path}")]
    ConflictingAuthority { path: PathBuf },

    #[error(
        "Fleet install session is complete and cannot re-enter fresh-install recovery: {path}; wait for and use a separately supported managed-upgrade workflow from the published Fleet baseline"
    )]
    Completed { path: PathBuf },

    #[error("failed to access Fleet install session {path}: {source}")]
    Io {
        path: PathBuf,
        #[source]
        source: io::Error,
    },

    #[error("invalid Fleet install session {path}: {reason}")]
    InvalidDocument { path: PathBuf, reason: String },

    #[error("Fleet install session is not a regular no-follow file: {path}")]
    UnsafeFile { path: PathBuf },

    #[error("Fleet install session lock is not a regular no-follow file: {path}")]
    UnsafeLock { path: PathBuf },

    #[error("cryptographic random source returned only {actual} of 32 required bytes")]
    ShortRandomRead { actual: usize },

    #[error(transparent)]
    ReleaseBuild(#[from] ReleaseBuildPlanError),
}

/// Inspect one exact Fleet identity without compiling current workspace configuration.
pub fn inspect_incomplete_fleet_install_session(
    root: &Path,
    canonical_network_id: CanonicalNetworkId,
    fleet_name: &FleetName,
) -> Result<Option<RetainedFleetInstallSessionSummaryV1>, Box<dyn std::error::Error>> {
    let path = session_path(root, canonical_network_id, fleet_name);
    let Some(session) = load_optional_session(&path)? else {
        return Ok(None);
    };
    let completion_path = path.with_file_name(COMPLETION_FILE);
    if let Some(completion) = load_optional_completion(&completion_path)? {
        validate_completion(&completion_path, &completion, &session)?;
        return Ok(None);
    }
    Ok(Some(RetainedFleetInstallSessionSummaryV1 {
        fleet_name: session.fleet_name,
        app: session.fleet.app,
        release_build_id: session.release_build_id,
        fresh_fleet_plan_digest: session.fresh_fleet_plan_digest,
        operation_id: session.operation_id,
    }))
}

/// Publish or recover the exact pre-effect identity for one fresh Fleet install.
pub(super) fn plan_fleet_install_session(
    request: PlanFleetInstallSessionRequest<'_>,
) -> Result<FleetInstallSession, FleetInstallSessionError> {
    let finalized = load_finalized_release_build(
        request.root,
        request.finalized_release_build.record.release_build_id,
    )?;
    if finalized.record != request.finalized_release_build.record
        || finalized.plan_hash != request.finalized_release_build.plan_hash
    {
        return Err(FleetInstallSessionError::ConflictingAuthority {
            path: request.finalized_release_build.path.clone(),
        });
    }
    let ReleaseBuildPlanState::Finalized {
        release_set_manifest_digest,
    } = finalized.record.state
    else {
        unreachable!("load_finalized_release_build admits only finalized records");
    };

    let path = session_path(
        request.root,
        request.canonical_network_id,
        &request.fleet_name,
    );
    let _lock = lock_session(&path)?;
    if let Some(session) = load_optional_session(&path)? {
        let completion_path = path.with_file_name(COMPLETION_FILE);
        if let Some(completion) = load_optional_completion(&completion_path)? {
            validate_completion(&completion_path, &completion, &session)?;
            return Err(FleetInstallSessionError::Completed {
                path: completion_path,
            });
        }
        if session_matches_request(
            &session,
            &request,
            finalized.plan_hash,
            release_set_manifest_digest,
        ) {
            return Ok(session);
        }
        return Err(FleetInstallSessionError::ConflictingAuthority { path });
    }

    let session = FleetInstallSession {
        schema_version: SESSION_SCHEMA_VERSION,
        fleet_name: request.fleet_name.clone(),
        fleet: FleetBinding {
            fleet: FleetKey {
                canonical_network_id: request.canonical_network_id,
                fleet_id: FleetId::from_generated_bytes(random_identity_bytes()?),
            },
            app: request.app.clone(),
        },
        release_build_id: finalized.record.release_build_id,
        release_build_plan_digest: finalized.plan_hash,
        release_set_manifest_digest,
        decision_release_build_id: request.decision_release_build_id,
        fresh_fleet_plan_digest: request.fresh_fleet_plan_digest.to_string(),
        operation_id: random_identity_bytes()?,
    };
    let bytes = encode_session(&path, &session)?;
    if let Err(source) = create_new_bytes_with_parents(&path, &bytes) {
        if source.kind() == io::ErrorKind::AlreadyExists {
            if let Some(observed) = load_optional_session(&path)?
                && session_matches_request(
                    &observed,
                    &request,
                    finalized.plan_hash,
                    release_set_manifest_digest,
                )
            {
                return Ok(observed);
            }
            return Err(FleetInstallSessionError::ConflictingAuthority { path });
        }
        return Err(FleetInstallSessionError::Io { path, source });
    }

    let observed = load_optional_session(&path)?.ok_or_else(|| {
        invalid(
            &path,
            "published Fleet install session could not be read back",
        )
    })?;
    if observed != session {
        return Err(invalid(
            &path,
            "published Fleet install session differs from planned authority",
        ));
    }
    Ok(observed)
}

/// Permanently close one fresh-install session after terminal Fleet catalog publication.
pub(super) fn close_fleet_install_session(
    request: CloseFleetInstallSessionRequest<'_>,
) -> Result<(), FleetInstallSessionError> {
    let journal = request.component_journal;
    let completion = FleetInstallCompletionV1 {
        schema_version: COMPLETION_SCHEMA_VERSION,
        session_schema_version: request.session.schema_version,
        fleet_name: request.session.fleet_name.clone(),
        fleet: request.session.fleet.clone(),
        release_build_id: request.session.release_build_id,
        fresh_fleet_plan_digest: request.session.fresh_fleet_plan_digest.clone(),
        fleet_install_operation_id: request.session.operation_id,
        fleet_install_plan_digest: journal.fleet_install_plan_digest,
        component_journal_schema_version: journal.schema_version,
        component_journal_sequence: journal.sequence,
        component_journal_digest: journal.journal_digest,
        component_provisioning_operation_id: journal.operation_id,
        component_provisioning_plan_hash: journal.plan_hash,
        catalog_entry: journal.catalog_entry.clone(),
        catalog_hash: journal.catalog_hash,
    };
    let path = completion_path(request.root, request.session);
    validate_completion(&path, &completion, request.session)?;
    let bytes = encode_completion(&path, &completion)?;
    let _lock = lock_completion(&path)?;
    match create_new_bytes_with_parents(&path, &bytes) {
        Ok(()) => {}
        Err(source) if source.kind() == io::ErrorKind::AlreadyExists => {
            let observed = load_optional_completion(&path)?.ok_or_else(|| {
                FleetInstallSessionError::ConflictingAuthority { path: path.clone() }
            })?;
            if observed != completion {
                return Err(FleetInstallSessionError::ConflictingAuthority { path });
            }
        }
        Err(source) => return Err(FleetInstallSessionError::Io { path, source }),
    }
    let durable = load_optional_completion(&path)?
        .ok_or_else(|| FleetInstallSessionError::ConflictingAuthority { path: path.clone() })?;
    if durable != completion {
        return Err(FleetInstallSessionError::ConflictingAuthority { path });
    }
    Ok(())
}

/// Recover the original decision binding plus finalized artifacts for exact resume.
pub(super) fn recover_fleet_install_session_authority(
    root: &Path,
    canonical_network_id: CanonicalNetworkId,
    fleet_name: &FleetName,
    app: &AppId,
) -> Result<Option<RecoveredFleetInstallAuthority>, FleetInstallSessionError> {
    let path = session_path(root, canonical_network_id, fleet_name);
    let _lock = lock_session(&path)?;
    inspect_fleet_install_session_authority_at_path(
        root,
        &path,
        canonical_network_id,
        fleet_name,
        app,
    )
}

/// Inspect exact retained install authority without creating a recovery lock or other file.
pub(super) fn inspect_fleet_install_session_authority(
    root: &Path,
    canonical_network_id: CanonicalNetworkId,
    fleet_name: &FleetName,
    app: &AppId,
) -> Result<Option<RecoveredFleetInstallAuthority>, FleetInstallSessionError> {
    let path = session_path(root, canonical_network_id, fleet_name);
    inspect_fleet_install_session_authority_at_path(
        root,
        &path,
        canonical_network_id,
        fleet_name,
        app,
    )
}

fn inspect_fleet_install_session_authority_at_path(
    root: &Path,
    path: &Path,
    canonical_network_id: CanonicalNetworkId,
    fleet_name: &FleetName,
    app: &AppId,
) -> Result<Option<RecoveredFleetInstallAuthority>, FleetInstallSessionError> {
    let Some(session) = load_optional_session(path)? else {
        return Ok(None);
    };
    if session.fleet_name != *fleet_name
        || session.fleet.fleet.canonical_network_id != canonical_network_id
        || session.fleet.app != *app
    {
        return Err(FleetInstallSessionError::ConflictingAuthority {
            path: path.to_path_buf(),
        });
    }
    let completion_path = path.with_file_name(COMPLETION_FILE);
    if let Some(completion) = load_optional_completion(&completion_path)? {
        validate_completion(&completion_path, &completion, &session)?;
        return Err(FleetInstallSessionError::Completed {
            path: completion_path,
        });
    }

    let finalized = load_finalized_release_build(root, session.release_build_id)?;
    let ReleaseBuildPlanState::Finalized {
        release_set_manifest_digest,
    } = finalized.record.state
    else {
        unreachable!("load_finalized_release_build admits only finalized records");
    };
    if session.release_build_plan_digest != finalized.plan_hash
        || session.release_set_manifest_digest != release_set_manifest_digest
    {
        return Err(invalid(
            path,
            "session release-build evidence differs from its finalized authority",
        ));
    }

    Ok(Some(RecoveredFleetInstallAuthority {
        finalized_release_build: finalized,
        decision_release_build_id: session.decision_release_build_id,
        fresh_fleet_plan_digest: session.fresh_fleet_plan_digest.clone(),
        session,
    }))
}

fn session_matches_request(
    session: &FleetInstallSession,
    request: &PlanFleetInstallSessionRequest<'_>,
    release_build_plan_digest: [u8; 32],
    release_set_manifest_digest: [u8; 32],
) -> bool {
    session.schema_version == SESSION_SCHEMA_VERSION
        && session.fleet_name == request.fleet_name
        && session.fleet.fleet.canonical_network_id == request.canonical_network_id
        && session.fleet.app == request.app
        && session.release_build_id == request.finalized_release_build.record.release_build_id
        && session.release_build_plan_digest == release_build_plan_digest
        && session.release_set_manifest_digest == release_set_manifest_digest
        && session.decision_release_build_id == request.decision_release_build_id
        && session.fresh_fleet_plan_digest == request.fresh_fleet_plan_digest
}

fn encode_session(
    path: &Path,
    session: &FleetInstallSession,
) -> Result<Vec<u8>, FleetInstallSessionError> {
    validate_session(path, session)?;
    let mut bytes = serde_json::to_vec_pretty(session)
        .map_err(|error| invalid(path, format!("could not encode JSON: {error}")))?;
    bytes.push(b'\n');
    if bytes.len() > MAX_SESSION_BYTES {
        return Err(invalid(path, "session exceeds its byte bound"));
    }
    Ok(bytes)
}

fn load_optional_session(
    path: &Path,
) -> Result<Option<FleetInstallSession>, FleetInstallSessionError> {
    let bytes = match read_optional_regular_bytes(path) {
        Ok(bytes) => bytes,
        Err(RegularFileReadError::NotRegular) => {
            return Err(FleetInstallSessionError::UnsafeFile {
                path: path.to_path_buf(),
            });
        }
        Err(RegularFileReadError::Io(source)) => {
            return Err(FleetInstallSessionError::Io {
                path: path.to_path_buf(),
                source,
            });
        }
    };
    let Some(bytes) = bytes else {
        return Ok(None);
    };
    if bytes.len() > MAX_SESSION_BYTES {
        return Err(invalid(path, "session exceeds its byte bound"));
    }
    let session = serde_json::from_slice::<FleetInstallSession>(&bytes)
        .map_err(|error| invalid(path, error.to_string()))?;
    validate_session(path, &session)?;
    if encode_session(path, &session)? != bytes {
        return Err(invalid(path, "JSON bytes are not canonical"));
    }
    Ok(Some(session))
}

fn validate_session(
    path: &Path,
    session: &FleetInstallSession,
) -> Result<(), FleetInstallSessionError> {
    if session.schema_version != SESSION_SCHEMA_VERSION {
        return Err(invalid(
            path,
            "unsupported session schema version; export with the matching Canic release before retrying",
        ));
    }
    if session.fleet_name.as_str().is_empty() {
        return Err(invalid(path, "Fleet name must not be empty"));
    }
    if session.operation_id == [0; 32] {
        return Err(invalid(path, "operation identity must not be zero"));
    }
    if !is_canonical_sha256(&session.fresh_fleet_plan_digest) {
        return Err(invalid(
            path,
            "fresh-Fleet plan digest must contain 64 lowercase hexadecimal characters",
        ));
    }
    if session
        .decision_release_build_id
        .is_some_and(|release_build_id| release_build_id != session.release_build_id)
    {
        return Err(invalid(
            path,
            "decision release build differs from finalized install release build",
        ));
    }
    Ok(())
}

fn is_canonical_sha256(value: &str) -> bool {
    value.len() == 64
        && value
            .bytes()
            .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
}

fn validate_completion(
    path: &Path,
    completion: &FleetInstallCompletionV1,
    session: &FleetInstallSession,
) -> Result<(), FleetInstallSessionError> {
    let entry = &completion.catalog_entry;
    let exact = completion.schema_version == COMPLETION_SCHEMA_VERSION
        && completion.session_schema_version == session.schema_version
        && completion.fleet_name == session.fleet_name
        && completion.fleet == session.fleet
        && completion.release_build_id == session.release_build_id
        && completion.fresh_fleet_plan_digest == session.fresh_fleet_plan_digest
        && completion.fleet_install_operation_id == session.operation_id
        && completion.fleet_install_plan_digest != [0; 32]
        && completion.component_journal_schema_version == JOURNAL_SCHEMA_VERSION
        && completion.component_journal_sequence > 0
        && completion.component_journal_digest != [0; 32]
        && completion.component_provisioning_operation_id != [0; 32]
        && completion.component_provisioning_plan_hash != [0; 32]
        && completion.catalog_hash != [0; 32]
        && entry.canonical_network_id == session.fleet.fleet.canonical_network_id
        && entry.fleet_id == session.fleet.fleet.fleet_id
        && entry.fleet_name == session.fleet_name
        && entry.app == session.fleet.app
        && entry.release_build_id == session.release_build_id;
    if !exact {
        return Err(invalid(
            path,
            "completion differs from the exact terminal session and catalog authority",
        ));
    }
    Ok(())
}

fn encode_completion(
    path: &Path,
    completion: &FleetInstallCompletionV1,
) -> Result<Vec<u8>, FleetInstallSessionError> {
    encode_canonical_json(
        completion,
        CanonicalJsonStyle::PrettyNewline,
        MAX_COMPLETION_BYTES,
    )
    .map_err(|error| match error {
        CanonicalJsonEncodeError::Serialization(error) => invalid(path, error.to_string()),
        CanonicalJsonEncodeError::TooLarge => invalid(path, "completion exceeds its byte bound"),
    })
}

fn load_optional_completion(
    path: &Path,
) -> Result<Option<FleetInstallCompletionV1>, FleetInstallSessionError> {
    let bytes = match read_optional_bounded_regular_bytes(path, MAX_COMPLETION_BYTES) {
        Ok(bytes) => bytes,
        Err(BoundedRegularFileReadError::TooLarge) => {
            return Err(invalid(path, "completion exceeds its byte bound"));
        }
        Err(BoundedRegularFileReadError::Read(RegularFileReadError::NotRegular)) => {
            return Err(FleetInstallSessionError::UnsafeFile {
                path: path.to_path_buf(),
            });
        }
        Err(BoundedRegularFileReadError::Read(RegularFileReadError::Io(source))) => {
            return Err(FleetInstallSessionError::Io {
                path: path.to_path_buf(),
                source,
            });
        }
        #[cfg(not(unix))]
        Err(BoundedRegularFileReadError::Read(RegularFileReadError::UnsupportedPlatform)) => {
            return Err(FleetInstallSessionError::Io {
                path: path.to_path_buf(),
                source: io::Error::new(
                    io::ErrorKind::Unsupported,
                    "Fleet install completion reads are unsupported",
                ),
            });
        }
    };
    let Some(bytes) = bytes else {
        return Ok(None);
    };
    let completion = serde_json::from_slice::<FleetInstallCompletionV1>(&bytes)
        .map_err(|error| invalid(path, error.to_string()))?;
    if encode_completion(path, &completion)? != bytes {
        return Err(invalid(path, "completion JSON bytes are not canonical"));
    }
    Ok(Some(completion))
}

fn session_path(
    root: &Path,
    canonical_network_id: CanonicalNetworkId,
    fleet_name: &FleetName,
) -> PathBuf {
    root.join(".canic")
        .join("recovery")
        .join("fleet-install-sessions")
        .join(canonical_network_id.to_string())
        .join(fleet_name.as_str())
        .join(SESSION_FILE)
}

fn completion_path(root: &Path, session: &FleetInstallSession) -> PathBuf {
    session_path(
        root,
        session.fleet.fleet.canonical_network_id,
        &session.fleet_name,
    )
    .with_file_name(COMPLETION_FILE)
}

fn lock_completion(path: &Path) -> Result<std::fs::File, FleetInstallSessionError> {
    let lock_path = path.with_file_name(COMPLETION_LOCK_FILE);
    lock_regular_file_with_parents(&lock_path).map_err(|error| match error {
        RegularFileLockError::NotRegular => FleetInstallSessionError::UnsafeLock {
            path: lock_path.clone(),
        },
        RegularFileLockError::Io(source) => FleetInstallSessionError::Io {
            path: lock_path.clone(),
            source,
        },
        #[cfg(windows)]
        RegularFileLockError::UnsupportedPlatform => FleetInstallSessionError::Io {
            path: lock_path,
            source: io::Error::new(
                io::ErrorKind::Unsupported,
                "Fleet install completion locking is unsupported on Windows",
            ),
        },
    })
}

fn lock_session(path: &Path) -> Result<std::fs::File, FleetInstallSessionError> {
    let lock_path = path.with_file_name(SESSION_LOCK_FILE);
    lock_regular_file_with_parents(&lock_path).map_err(|error| match error {
        RegularFileLockError::NotRegular => FleetInstallSessionError::UnsafeLock {
            path: lock_path.clone(),
        },
        RegularFileLockError::Io(source) => FleetInstallSessionError::Io {
            path: lock_path.clone(),
            source,
        },
        #[cfg(windows)]
        RegularFileLockError::UnsupportedPlatform => FleetInstallSessionError::Io {
            path: lock_path,
            source: io::Error::new(
                io::ErrorKind::Unsupported,
                "Fleet install session locking is unsupported on Windows",
            ),
        },
    })
}

fn random_identity_bytes() -> Result<[u8; 32], FleetInstallSessionError> {
    random_bytes_32().map_err(|error| match error {
        EntropyError::Io(source) => FleetInstallSessionError::Io {
            path: PathBuf::from("<operating-system entropy>"),
            source,
        },
        EntropyError::ShortRead { actual } => FleetInstallSessionError::ShortRandomRead { actual },
    })
}

fn invalid(path: &Path, reason: impl Into<String>) -> FleetInstallSessionError {
    FleetInstallSessionError::InvalidDocument {
        path: path.to_path_buf(),
        reason: reason.into(),
    }
}