lean-rs-worker 0.1.2

Worker-process boundary for lean-rs host workloads.
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
//! Import-set planning for worker-pool execution.
//!
//! The planner groups module work into stable worker session batches. It does
//! not choose workers, run commands, or define downstream cache semantics.

use std::collections::BTreeMap;
use std::fmt;
use std::path::PathBuf;

use lean_toolchain::{
    LeanLakeProjectModules, LeanModuleDescriptor, LeanModuleDiscoveryDiagnostic, LeanModuleDiscoveryOptions,
    LeanModuleSetFingerprint, ToolchainFingerprint, discover_lake_modules, lake_target_declared,
};
use serde_json::Value;

use crate::capability::LeanWorkerCapabilityBuilder;
use crate::pool::{LeanWorkerRestartPolicyClass, LeanWorkerSessionKey};
use crate::session::LeanWorkerCapabilityMetadata;
use crate::supervisor::LeanWorkerRestartPolicy;

/// Capability and session requirements used to plan worker batches.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LeanWorkerImportPlanConfig {
    project_root: PathBuf,
    package: String,
    lib_name: String,
    source_roots: Option<Vec<String>>,
    base_imports: Vec<String>,
    metadata_expectation: Option<LeanWorkerPlanMetadataExpectation>,
    restart_policy: Option<LeanWorkerRestartPolicy>,
}

impl LeanWorkerImportPlanConfig {
    /// Create planner configuration for a Lake capability target.
    #[must_use]
    pub fn new(project_root: impl Into<PathBuf>, package: impl Into<String>, lib_name: impl Into<String>) -> Self {
        Self {
            project_root: project_root.into(),
            package: package.into(),
            lib_name: lib_name.into(),
            source_roots: None,
            base_imports: Vec::new(),
            metadata_expectation: None,
            restart_policy: None,
        }
    }

    /// Restrict discovery to these source roots.
    #[must_use]
    pub fn source_roots(mut self, roots: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.source_roots = Some(roots.into_iter().map(Into::into).collect());
        self
    }

    /// Add imports required by every planned session batch.
    #[must_use]
    pub fn base_imports(mut self, imports: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.base_imports = imports.into_iter().map(Into::into).collect();
        self
    }

    /// Validate metadata before a worker batch is used.
    #[must_use]
    pub fn validate_metadata(mut self, export: impl Into<String>, request: Value) -> Self {
        self.metadata_expectation = Some(LeanWorkerPlanMetadataExpectation {
            export: export.into(),
            request,
            expected: None,
        });
        self
    }

    /// Require exact generic capability metadata before a worker batch is used.
    #[must_use]
    pub fn expect_metadata(
        mut self,
        export: impl Into<String>,
        request: Value,
        expected: LeanWorkerCapabilityMetadata,
    ) -> Self {
        self.metadata_expectation = Some(LeanWorkerPlanMetadataExpectation {
            export: export.into(),
            request,
            expected: Some(expected),
        });
        self
    }

    /// Use a worker restart policy for builders derived from planned batches.
    #[must_use]
    pub fn restart_policy(mut self, policy: LeanWorkerRestartPolicy) -> Self {
        self.restart_policy = Some(policy);
        self
    }
}

/// Metadata expectation carried into planned session keys.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LeanWorkerPlanMetadataExpectation {
    pub export: String,
    pub request: Value,
    pub expected: Option<LeanWorkerCapabilityMetadata>,
}

/// One module-sized unit of planned worker work.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LeanWorkerModuleWork {
    pub module: String,
    pub path: PathBuf,
    pub source_root: String,
    pub imports: Vec<String>,
}

impl LeanWorkerModuleWork {
    /// Create one module work item with explicit imports.
    #[must_use]
    pub fn new(
        module: impl Into<String>,
        path: impl Into<PathBuf>,
        source_root: impl Into<String>,
        imports: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        Self {
            module: module.into(),
            path: path.into(),
            source_root: source_root.into(),
            imports: imports.into_iter().map(Into::into).collect(),
        }
    }

    fn from_descriptor(descriptor: &LeanModuleDescriptor, imports: &[String]) -> Self {
        Self {
            module: descriptor.module.clone(),
            path: descriptor.path.clone(),
            source_root: descriptor.source_root.clone(),
            imports: imports.to_vec(),
        }
    }
}

/// One stable pool-execution batch.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LeanWorkerPlannedBatch {
    pub session_key: LeanWorkerSessionKey,
    pub project_root: PathBuf,
    pub package: String,
    pub lib_name: String,
    pub source_root: String,
    pub imports: Vec<String>,
    pub modules: Vec<LeanWorkerModuleWork>,
    pub fingerprint: LeanWorkerBatchFingerprint,
    metadata_expectation: Option<LeanWorkerPlanMetadataExpectation>,
    restart_policy: Option<LeanWorkerRestartPolicy>,
}

impl LeanWorkerPlannedBatch {
    /// Create a capability builder for this batch.
    ///
    /// The caller may still add packaging-specific details such as an explicit
    /// worker executable. The batch supplies the stable session material.
    #[must_use]
    pub fn capability_builder(&self) -> LeanWorkerCapabilityBuilder {
        let mut builder = LeanWorkerCapabilityBuilder::new(
            self.project_root.clone(),
            self.package.clone(),
            self.lib_name.clone(),
            self.imports.clone(),
        );
        if let Some(policy) = &self.restart_policy {
            builder = builder.restart_policy(policy.clone());
        }
        if let Some(expectation) = &self.metadata_expectation {
            builder = match &expectation.expected {
                Some(expected) => builder.expect_metadata(
                    expectation.export.clone(),
                    expectation.request.clone(),
                    expected.clone(),
                ),
                None => builder.validate_metadata(expectation.export.clone(), expectation.request.clone()),
            };
        }
        builder
    }
}

/// Stable cache-key-relevant facts for a planned batch.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LeanWorkerBatchFingerprint {
    pub toolchain: ToolchainFingerprint,
    pub source_set: LeanModuleSetFingerprint,
    pub batch_key: String,
}

/// Import planning diagnostics.
#[non_exhaustive]
#[derive(Debug)]
pub enum LeanWorkerImportPlanError {
    ModuleDiscovery { diagnostic: LeanModuleDiscoveryDiagnostic },
    InvalidModuleName { module: String, reason: String },
    UnresolvedCapabilityTarget { project_root: PathBuf, target_name: String },
}

impl fmt::Display for LeanWorkerImportPlanError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ModuleDiscovery { diagnostic } => write!(f, "{diagnostic}"),
            Self::InvalidModuleName { module, reason } => {
                write!(f, "lean-rs-worker: invalid module `{module}` in import plan: {reason}")
            }
            Self::UnresolvedCapabilityTarget {
                project_root,
                target_name,
            } => {
                write!(
                    f,
                    "lean-rs-worker: capability target `{target_name}` is not declared in {}",
                    project_root.display()
                )
            }
        }
    }
}

impl std::error::Error for LeanWorkerImportPlanError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::ModuleDiscovery { diagnostic } => Some(diagnostic),
            Self::InvalidModuleName { .. } | Self::UnresolvedCapabilityTarget { .. } => None,
        }
    }
}

/// Planner for worker-pool import/session batches.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LeanWorkerImportPlanner {
    config: LeanWorkerImportPlanConfig,
}

impl LeanWorkerImportPlanner {
    /// Create a planner from capability/session requirements.
    #[must_use]
    pub fn new(config: LeanWorkerImportPlanConfig) -> Self {
        Self { config }
    }

    /// Discover a Lake project and return stable worker batches.
    ///
    /// # Errors
    ///
    /// Returns typed planning diagnostics for missing Lake roots, selected
    /// module roots, invalid module names, unsupported toolchains, or an
    /// unresolved capability target.
    pub fn plan_lake_project(&self) -> Result<Vec<LeanWorkerPlannedBatch>, LeanWorkerImportPlanError> {
        let mut options = LeanModuleDiscoveryOptions::new(&self.config.project_root);
        if let Some(roots) = &self.config.source_roots {
            options = options.selected_roots(roots.clone());
        }
        let discovered = discover_lake_modules(options)
            .map_err(|diagnostic| LeanWorkerImportPlanError::ModuleDiscovery { diagnostic })?;
        let target_declared = lake_target_declared(&discovered.project_root, &self.config.lib_name)
            .map_err(|diagnostic| LeanWorkerImportPlanError::ModuleDiscovery { diagnostic })?;
        if !target_declared {
            return Err(LeanWorkerImportPlanError::UnresolvedCapabilityTarget {
                project_root: discovered.project_root,
                target_name: self.config.lib_name.clone(),
            });
        }
        self.plan_discovered(&discovered)
    }

    /// Plan batches from already discovered module descriptors.
    ///
    /// # Errors
    ///
    /// Returns a typed error if a supplied module descriptor has an invalid
    /// module name.
    pub fn plan_discovered(
        &self,
        discovered: &LeanLakeProjectModules,
    ) -> Result<Vec<LeanWorkerPlannedBatch>, LeanWorkerImportPlanError> {
        let work = discovered
            .modules
            .iter()
            .map(|module| LeanWorkerModuleWork::from_descriptor(module, &self.config.base_imports));
        self.plan_work_items(work, &discovered.fingerprint)
    }

    /// Plan batches from caller-provided module work items.
    ///
    /// # Errors
    ///
    /// Returns a typed error if a supplied work item has an invalid module
    /// name.
    pub fn plan_work_items(
        &self,
        modules: impl IntoIterator<Item = LeanWorkerModuleWork>,
        source_set: &LeanModuleSetFingerprint,
    ) -> Result<Vec<LeanWorkerPlannedBatch>, LeanWorkerImportPlanError> {
        let mut groups = BTreeMap::<BatchGroupKey, Vec<LeanWorkerModuleWork>>::new();
        for module in modules {
            validate_module_name(&module.module)?;
            validate_module_name(&module.source_root)?;
            let key = BatchGroupKey {
                project_root: self.config.project_root.clone(),
                package: self.config.package.clone(),
                lib_name: self.config.lib_name.clone(),
                source_root: module.source_root.clone(),
                imports: module.imports.clone(),
                restart_policy_class: restart_policy_class(self.config.restart_policy.as_ref()),
            };
            groups.entry(key).or_default().push(module);
        }

        let mut batches = Vec::new();
        for (key, mut modules) in groups {
            modules.sort_by(|left, right| left.module.cmp(&right.module));
            let mut session_key = LeanWorkerSessionKey::new(
                key.project_root.clone(),
                key.package.clone(),
                key.lib_name.clone(),
                key.imports.clone(),
            )
            .restart_policy_class(key.restart_policy_class);
            if let Some(expectation) = &self.config.metadata_expectation {
                session_key = session_key.metadata_expectation(
                    expectation.export.clone(),
                    expectation.request.clone(),
                    expectation.expected.clone(),
                );
            }
            let batch_key = batch_key_string(&key, &modules);
            batches.push(LeanWorkerPlannedBatch {
                session_key,
                project_root: key.project_root,
                package: key.package,
                lib_name: key.lib_name,
                source_root: key.source_root,
                imports: key.imports,
                modules,
                fingerprint: LeanWorkerBatchFingerprint {
                    toolchain: source_set.toolchain.clone(),
                    source_set: source_set.clone(),
                    batch_key,
                },
                metadata_expectation: self.config.metadata_expectation.clone(),
                restart_policy: self.config.restart_policy.clone(),
            });
        }
        Ok(batches)
    }
}

#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
struct BatchGroupKey {
    project_root: PathBuf,
    package: String,
    lib_name: String,
    source_root: String,
    imports: Vec<String>,
    restart_policy_class: LeanWorkerRestartPolicyClass,
}

fn restart_policy_class(policy: Option<&LeanWorkerRestartPolicy>) -> LeanWorkerRestartPolicyClass {
    match policy {
        Some(policy) if policy == &LeanWorkerRestartPolicy::default() => LeanWorkerRestartPolicyClass::Default,
        Some(_policy) => LeanWorkerRestartPolicyClass::Custom,
        None => LeanWorkerRestartPolicyClass::Default,
    }
}

fn batch_key_string(key: &BatchGroupKey, modules: &[LeanWorkerModuleWork]) -> String {
    let module_list = modules
        .iter()
        .map(|module| module.module.as_str())
        .collect::<Vec<_>>()
        .join(",");
    format!(
        "project={};package={};lib={};source_root={};imports={};policy={:?};modules={module_list}",
        key.project_root.display(),
        key.package,
        key.lib_name,
        key.source_root,
        key.imports.join(","),
        key.restart_policy_class,
    )
}

fn validate_module_name(module: &str) -> Result<(), LeanWorkerImportPlanError> {
    if module.is_empty() {
        return Err(LeanWorkerImportPlanError::InvalidModuleName {
            module: module.to_owned(),
            reason: "module name is empty".to_owned(),
        });
    }
    for component in module.split('.') {
        if component.is_empty() {
            return Err(LeanWorkerImportPlanError::InvalidModuleName {
                module: module.to_owned(),
                reason: "module name contains an empty component".to_owned(),
            });
        }
        let mut chars = component.chars();
        let Some(first) = chars.next() else {
            return Err(LeanWorkerImportPlanError::InvalidModuleName {
                module: module.to_owned(),
                reason: "module name contains an empty component".to_owned(),
            });
        };
        if !(first == '_' || first.is_alphabetic()) {
            return Err(LeanWorkerImportPlanError::InvalidModuleName {
                module: module.to_owned(),
                reason: "module components must begin with a letter or underscore".to_owned(),
            });
        }
        if chars.any(|ch| !(ch == '_' || ch == '\'' || ch.is_alphanumeric())) {
            return Err(LeanWorkerImportPlanError::InvalidModuleName {
                module: module.to_owned(),
                reason: "module components may contain only letters, digits, underscores, or apostrophes".to_owned(),
            });
        }
    }
    Ok(())
}