kcode-k1-rust-coding 0.2.2

Orchestrate per-user public K1 Rust coding operations
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
use kcode_k1_rust_cache::{CheckIdentity, LockGeneration, SourceGeneration, UserRustCache};
use kcode_k1_rust_package::{K1Dependency, LibraryFamily, LibraryId, SourcePackage};
use kcode_k1_rust_podman::{CommandDiagnostics, RustPodman, RustPodmanError, RustPodmanPaths};
use kcode_k1_rust_projection::{K1RustProjection, PublishOutcome, PublishStatus};
use kcode_k1_rust_registry::LocalRegistry;
use kcode_k1_transaction_id::TxId;
use std::collections::BTreeSet;
use std::error::Error;
use std::ffi::OsString;
use std::fmt::{Debug, Display, Formatter};
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::Arc;

type CodingResult<T> = Result<T, RustCodingError>;

pub trait RustPublishAuthorization {
    fn authorize_publish(&self, family: &LibraryFamily) -> Result<bool, String>;
}

#[derive(Clone, Debug)]
pub struct RustCodingConfigValues {
    pub schema_id: String,
    pub toolchain_policy: String,
    pub image: String,
    pub rust_toolchain: String,
    pub check_policy: String,
    pub target_triple: String,
    pub command_policy: String,
    pub podman_program: OsString,
}

#[derive(Clone, Debug)]
pub struct RustCodingConfig {
    values: RustCodingConfigValues,
}

impl RustCodingConfig {
    pub fn new(values: RustCodingConfigValues) -> CodingResult<Self> {
        let text = [
            &values.schema_id,
            &values.toolchain_policy,
            &values.image,
            &values.rust_toolchain,
            &values.check_policy,
            &values.target_triple,
            &values.command_policy,
        ];
        if text.iter().any(|value| value.is_empty()) || values.podman_program.is_empty() {
            return Err(RustCodingError::State(
                "Rust coding configuration values must be nonempty".into(),
            ));
        }
        Ok(Self { values })
    }
}

#[derive(Debug)]
pub enum CheckOutcome {
    Reused,
    Checked { diagnostics: CommandDiagnostics },
}

pub struct VerifiedCheck {
    identity: CheckIdentity,
}

#[derive(Debug)]
pub struct PublishResult {
    pub check: CheckOutcome,
    pub outcome: PublishOutcome,
}

#[derive(Debug)]
pub struct BinaryBuild {
    pub path: PathBuf,
    pub check: CheckOutcome,
    pub diagnostics: CommandDiagnostics,
}

#[derive(Debug)]
pub enum RustCodingError {
    State(String),
    Authorization(String),
    DependencyUnavailable {
        family: LibraryFamily,
        requirement: String,
    },
    PublishDenied,
    StaleCheck,
    Podman(RustPodmanError),
    AfterPublish {
        outcome: PublishOutcome,
        cause: Box<RustCodingError>,
    },
}

impl Display for RustCodingError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        Debug::fmt(self, formatter)
    }
}

impl Error for RustCodingError {}

pub struct K1RustCoding {
    config: RustCodingConfig,
    projection: Arc<K1RustProjection>,
    cache: UserRustCache,
    registry: LocalRegistry,
    podman: RustPodman,
}

impl K1RustCoding {
    pub fn open(
        cache_root: impl AsRef<Path>,
        user: TxId,
        config: RustCodingConfig,
        projection: Arc<K1RustProjection>,
    ) -> CodingResult<Self> {
        let values = &config.values;
        let cache = state_result(UserRustCache::open(
            cache_root,
            user,
            &values.schema_id,
            &values.toolchain_policy,
        ))?;
        let registry = state_result(LocalRegistry::open(cache.registry_root()))?;
        let podman = RustPodman::new(values.podman_program.clone(), values.image.clone())
            .map_err(RustCodingError::Podman)?;
        let value = Self {
            config,
            projection,
            cache,
            registry,
            podman,
        };
        value.ensure_config()?;
        Ok(value)
    }

    pub fn cache_epoch(&self) -> u64 {
        self.cache.epoch()
    }

    pub fn check(&mut self, package: &SourcePackage) -> CodingResult<CheckOutcome> {
        let (source, dependencies) = self.prepare_check(package)?;
        let family = package.id().family();
        if self
            .current_identity(family, source, &dependencies)?
            .is_some()
        {
            return Ok(CheckOutcome::Reused);
        }
        let (_, diagnostics) = self.run_check(family, source, &dependencies)?;
        Ok(CheckOutcome::Checked { diagnostics })
    }

    pub fn check_fresh(&mut self, package: &SourcePackage) -> CodingResult<VerifiedCheck> {
        let (source, dependencies) = self.prepare_check(package)?;
        let (identity, _) = self.run_check(package.id().family(), source, &dependencies)?;
        Ok(VerifiedCheck { identity })
    }

    pub fn current_check(
        &mut self,
        package: &SourcePackage,
    ) -> CodingResult<Option<VerifiedCheck>> {
        let (source, dependencies) = self.prepare_check(package)?;
        Ok(self
            .current_identity(package.id().family(), source, &dependencies)?
            .map(|identity| VerifiedCheck { identity }))
    }

    pub fn publish(
        &mut self,
        package: &SourcePackage,
        gate: &dyn RustPublishAuthorization,
    ) -> CodingResult<PublishResult> {
        let check = self.check(package)?;
        let outcome = self.publish_authorized(package, gate)?;
        Ok(PublishResult { check, outcome })
    }

    pub fn publish_checked(
        &mut self,
        package: &SourcePackage,
        verified: &VerifiedCheck,
        gate: &dyn RustPublishAuthorization,
    ) -> CodingResult<PublishOutcome> {
        let current = self.current_check(package)?;
        if current.as_ref().map(|value| &value.identity) != Some(&verified.identity) {
            return Err(RustCodingError::StaleCheck);
        }
        self.publish_authorized(package, gate)
    }

    pub fn build_binary(
        &mut self,
        package: &SourcePackage,
        binary: &str,
    ) -> CodingResult<BinaryBuild> {
        validate_binary(binary)?;
        let check = self.check(package)?;
        let id = package.id();
        let authority = id.family().authority().to_string();
        let version = id.version().to_string();
        let directory = ensure_directories(
            &self.cache.binaries_root(),
            &[&authority, id.family().logical_name(), &version],
        )?;
        let path = directory.join(binary);
        let diagnostics = self
            .podman
            .build_binary(&self.paths(id.family()), binary, &path)
            .map_err(RustCodingError::Podman)?;
        Ok(BinaryBuild {
            path,
            check,
            diagnostics,
        })
    }

    pub fn reset(&mut self) -> CodingResult<()> {
        let values = &self.config.values;
        state_result(
            self.cache
                .reset(&values.schema_id, &values.toolchain_policy),
        )?;
        self.registry = state_result(LocalRegistry::open(self.cache.registry_root()))?;
        self.ensure_config()
    }

    fn prepare_check(
        &mut self,
        package: &SourcePackage,
    ) -> CodingResult<(SourceGeneration, Vec<LibraryId>)> {
        let source = state_result(self.cache.materialize(package))?;
        let dependencies = self.resolve_dependencies(package)?;
        self.ensure_config()?;
        Ok((source, dependencies))
    }

    fn current_identity(
        &self,
        family: &LibraryFamily,
        source: SourceGeneration,
        dependencies: &[LibraryId],
    ) -> CodingResult<Option<CheckIdentity>> {
        let Some(lock) = state_result(self.cache.lock_generation(family))? else {
            return Ok(None);
        };
        let identity = self.identity(source, lock, dependencies);
        Ok(state_result(self.cache.has_check(family, &identity))?.then_some(identity))
    }

    fn run_check(
        &mut self,
        family: &LibraryFamily,
        source: SourceGeneration,
        dependencies: &[LibraryId],
    ) -> CodingResult<(CheckIdentity, CommandDiagnostics)> {
        let paths = self.paths(family);
        let diagnostics = self.podman.check(&paths).map_err(RustCodingError::Podman)?;
        let lock = state_result(
            self.cache
                .record_lock(family, &read_ordinary(&paths.workspace.join("Cargo.lock"))?),
        )?;
        let identity = self.identity(source, lock, dependencies);
        state_result(self.cache.record_check(family, &identity))?;
        Ok((identity, diagnostics))
    }

    fn publish_authorized(
        &self,
        package: &SourcePackage,
        gate: &dyn RustPublishAuthorization,
    ) -> CodingResult<PublishOutcome> {
        match gate.authorize_publish(package.id().family()) {
            Ok(true) => {}
            Ok(false) => return Err(RustCodingError::PublishDenied),
            Err(cause) => return Err(RustCodingError::Authorization(cause)),
        }
        let outcome = state_result(self.projection.publish(package))?;
        if outcome.status() != PublishStatus::Conflict
            && let Err(cause) = self.complete_publication(package)
        {
            return Err(RustCodingError::AfterPublish {
                outcome,
                cause: Box::new(cause),
            });
        }
        Ok(outcome)
    }

    fn resolve_dependencies(&mut self, package: &SourcePackage) -> CodingResult<Vec<LibraryId>> {
        let mut visiting = BTreeSet::new();
        let mut resolved = BTreeSet::new();
        for dependency in package.dependencies() {
            self.resolve(dependency, &mut visiting, &mut resolved)?;
        }
        Ok(resolved.into_iter().collect())
    }

    fn resolve(
        &mut self,
        dependency: &K1Dependency,
        visiting: &mut BTreeSet<LibraryId>,
        resolved: &mut BTreeSet<LibraryId>,
    ) -> CodingResult<()> {
        let package = state_result(
            self.projection
                .resolve(dependency.family(), dependency.requirement()),
        )?
        .ok_or_else(|| RustCodingError::DependencyUnavailable {
            family: dependency.family().clone(),
            requirement: dependency.requirement().to_string(),
        })?;
        let id = package.id().clone();
        if resolved.contains(&id) || !visiting.insert(id.clone()) {
            return Ok(());
        }
        let result = self.resolve_one(&package, visiting, resolved);
        visiting.remove(&id);
        if result.is_ok() {
            resolved.insert(id);
        }
        result
    }

    fn resolve_one(
        &mut self,
        package: &SourcePackage,
        visiting: &mut BTreeSet<LibraryId>,
        resolved: &mut BTreeSet<LibraryId>,
    ) -> CodingResult<()> {
        for dependency in package.dependencies() {
            self.resolve(dependency, visiting, resolved)?;
        }
        self.install(package)
    }

    fn install(&self, package: &SourcePackage) -> CodingResult<()> {
        state_result(self.registry.install(package)).map(|_| ())
    }

    fn complete_publication(&self, package: &SourcePackage) -> CodingResult<()> {
        self.install(package)?;
        self.ensure_config()
    }

    fn identity(
        &self,
        source: SourceGeneration,
        lock: LockGeneration,
        dependencies: &[LibraryId],
    ) -> CheckIdentity {
        let values = &self.config.values;
        CheckIdentity {
            source,
            lock,
            dependencies: dependencies.to_vec(),
            image_identity: values.image.clone(),
            rust_toolchain: values.rust_toolchain.clone(),
            check_policy: values.check_policy.clone(),
            target_triple: values.target_triple.clone(),
            command_policy: values.command_policy.clone(),
        }
    }

    fn paths(&self, family: &LibraryFamily) -> RustPodmanPaths {
        RustPodmanPaths::new(
            self.cache.workspace(family),
            self.cache.cargo_home(),
            self.cache.target_root(),
            self.cache.registry_root(),
            self.cache.cargo_home().join("config.toml"),
        )
    }

    fn ensure_config(&self) -> CodingResult<()> {
        write_config(
            &self.cache.cargo_home().join("config.toml"),
            self.registry.cargo_config().as_bytes(),
        )
    }
}

fn read_ordinary(path: &Path) -> CodingResult<Vec<u8>> {
    let metadata = fs::symlink_metadata(path).map_err(state)?;
    if metadata.file_type().is_symlink() || !metadata.is_file() {
        return Err(RustCodingError::State(format!(
            "not an ordinary nonsymlink file: {}",
            path.display()
        )));
    }
    fs::read(path).map_err(state)
}

fn write_config(path: &Path, bytes: &[u8]) -> CodingResult<()> {
    match fs::symlink_metadata(path) {
        Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_file() => {
            return Err(RustCodingError::State(format!(
                "Cargo configuration is not an ordinary nonsymlink file: {}",
                path.display()
            )));
        }
        Ok(_) if fs::read(path).map_err(state)? == bytes => return Ok(()),
        Ok(_) => {}
        Err(cause) if cause.kind() == std::io::ErrorKind::NotFound => {}
        Err(cause) => return Err(state(cause)),
    }
    let parent = path
        .parent()
        .ok_or_else(|| RustCodingError::State("Cargo configuration has no parent".into()))?;
    let stage = parent.join(format!(".config.toml.stage-{}", std::process::id()));
    match fs::symlink_metadata(&stage) {
        Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_file() => {
            return Err(RustCodingError::State(format!(
                "Cargo configuration stage is not an ordinary nonsymlink file: {}",
                stage.display()
            )));
        }
        Ok(_) => fs::remove_file(&stage).map_err(state)?,
        Err(cause) if cause.kind() == std::io::ErrorKind::NotFound => {}
        Err(cause) => return Err(state(cause)),
    }
    let result = (|| {
        let mut file = OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&stage)?;
        file.write_all(bytes)?;
        file.sync_all()?;
        fs::rename(&stage, path)
    })()
    .map_err(state);
    if result.is_err() {
        let _ = fs::remove_file(stage);
    }
    result
}

fn ensure_directories(root: &Path, names: &[&str]) -> CodingResult<PathBuf> {
    let mut path = root.to_path_buf();
    require_directory(&path)?;
    for name in names {
        path.push(name);
        match fs::create_dir(&path) {
            Ok(()) => {}
            Err(cause) if cause.kind() == std::io::ErrorKind::AlreadyExists => {
                require_directory(&path)?;
            }
            Err(cause) => return Err(state(cause)),
        }
    }
    Ok(path)
}

fn require_directory(path: &Path) -> CodingResult<()> {
    let metadata = fs::symlink_metadata(path).map_err(state)?;
    if metadata.file_type().is_symlink() || !metadata.is_dir() {
        return Err(RustCodingError::State(format!(
            "not an ordinary nonsymlink directory: {}",
            path.display()
        )));
    }
    Ok(())
}

fn validate_binary(value: &str) -> CodingResult<()> {
    let bytes = value.as_bytes();
    let alphanumeric = |byte: &u8| byte.is_ascii_lowercase() || byte.is_ascii_digit();
    let valid = (1..=250).contains(&bytes.len())
        && alphanumeric(&bytes[0])
        && alphanumeric(&bytes[bytes.len() - 1])
        && bytes.iter().all(|byte| alphanumeric(byte) || *byte == b'-')
        && !bytes.windows(2).any(|pair| pair == b"--");
    if valid {
        Ok(())
    } else {
        Err(RustCodingError::Podman(RustPodmanError::InvalidInput {
            field: "binary",
            reason: "must be lowercase kebab-case of length 1-250".into(),
        }))
    }
}

fn state(cause: impl Display) -> RustCodingError {
    RustCodingError::State(cause.to_string())
}

fn state_result<T>(result: Result<T, String>) -> CodingResult<T> {
    result.map_err(RustCodingError::State)
}