create-lathe 0.0.0-stage → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +168 -2
- package/bin/create-lathe.js +88 -0
- package/dist/framework.lock +115 -0
- package/dist/package/crates/instrument/Cargo.lock +415 -0
- package/dist/package/crates/instrument/Cargo.toml +27 -0
- package/dist/package/crates/instrument/examples/instrument.rs +73 -0
- package/dist/package/crates/instrument/src/client.rs +128 -0
- package/dist/package/crates/instrument/src/lib.rs +32 -0
- package/dist/package/crates/instrument/src/logging.rs +109 -0
- package/dist/package/crates/instrument/src/protocol.rs +49 -0
- package/dist/package/crates/instrument/src/registry.rs +166 -0
- package/dist/package/crates/instrument/src/selftest.rs +375 -0
- package/dist/package/crates/instrument/src/server.rs +363 -0
- package/dist/package/crates/instrument/tests/command_log.rs +60 -0
- package/dist/package/crates/instrument/tests/erreurs.rs +167 -0
- package/dist/package/crates/instrument/tests/round_trip.rs +230 -0
- package/dist/package/crates/instrument/tests/selftest_fail.rs +25 -0
- package/dist/package/crates/instrument/tests/selftest_pass.rs +24 -0
- package/dist/package/crates/instrument/tests/selftest_temps.rs +43 -0
- package/dist/package/crates/instrument/tests/support/mod.rs +58 -0
- package/dist/package/pi/context/journal-de-lot.md +24 -0
- package/dist/package/pi/context/tech-skill.md +19 -0
- package/dist/package/pi/context/ticket-closed.md +18 -0
- package/dist/package/scripts/framework.py +1384 -0
- package/dist/package/scripts/gates.py +1158 -0
- package/dist/package/scripts/setup.py +251 -0
- package/dist/package/skills/bootstrap/SKILL.md +110 -0
- package/dist/package/skills/documentation/SKILL.md +110 -0
- package/dist/package/skills/documentation/references/agents-md.md +70 -0
- package/dist/package/skills/documentation/references/corpus.md +112 -0
- package/dist/package/skills/journal/SKILL.md +81 -0
- package/dist/package/skills/journal/references/entry.md +172 -0
- package/dist/package/skills/lathe/SKILL.md +185 -0
- package/dist/package/skills/lathe/evals/routing.md +231 -0
- package/dist/package/skills/lathe/references/install.md +161 -0
- package/dist/package/skills/lathe/references/invariants.md +31 -0
- package/dist/package/skills/mutants/SKILL.md +88 -0
- package/dist/package/skills/mutants/references/cargo-mutants.md +176 -0
- package/dist/package/skills/mutants/references/triage.md +88 -0
- package/dist/package/skills/optimize/SKILL.md +87 -0
- package/dist/package/skills/optimize/references/codspeed.md +126 -0
- package/dist/package/skills/probe/SKILL.md +82 -0
- package/dist/package/skills/probe/references/wait-and-read.md +53 -0
- package/dist/package/skills/replicate-ui/SKILL.md +64 -0
- package/dist/package/skills/rust/SKILL.md +147 -0
- package/dist/package/skills/rust/references/errors.md +63 -0
- package/dist/package/skills/rust/references/unsafe.md +65 -0
- package/dist/package/skills/scaffold/SKILL.md +78 -0
- package/dist/package/skills/scaffold/profiles/rust-cli/.cargo/config.toml +2 -0
- package/dist/package/skills/scaffold/profiles/rust-cli/AGENTS.md +22 -0
- package/dist/package/skills/scaffold/profiles/rust-cli/Cargo.lock +7 -0
- package/dist/package/skills/scaffold/profiles/rust-cli/Cargo.toml +17 -0
- package/dist/package/skills/scaffold/profiles/rust-cli/README.md +15 -0
- package/dist/package/skills/scaffold/profiles/rust-cli/deny.toml +14 -0
- package/dist/package/skills/scaffold/profiles/rust-cli/rustfmt.toml +2 -0
- package/dist/package/skills/scaffold/profiles/rust-cli/src/main.rs +38 -0
- package/dist/package/skills/scaffold/profiles/rust-cli/tests/cli.rs +27 -0
- package/dist/package/skills/scaffold/profiles/rust-library/.cargo/config.toml +2 -0
- package/dist/package/skills/scaffold/profiles/rust-library/AGENTS.md +21 -0
- package/dist/package/skills/scaffold/profiles/rust-library/Cargo.lock +7 -0
- package/dist/package/skills/scaffold/profiles/rust-library/Cargo.toml +18 -0
- package/dist/package/skills/scaffold/profiles/rust-library/README.md +15 -0
- package/dist/package/skills/scaffold/profiles/rust-library/deny.toml +14 -0
- package/dist/package/skills/scaffold/profiles/rust-library/rustfmt.toml +2 -0
- package/dist/package/skills/scaffold/profiles/rust-library/src/lib.rs +25 -0
- package/dist/package/skills/scaffold/profiles/rust-native-desktop/.cargo/config.toml +2 -0
- package/dist/package/skills/scaffold/profiles/rust-native-desktop/AGENTS.md +23 -0
- package/dist/package/skills/scaffold/profiles/rust-native-desktop/Cargo.lock +9252 -0
- package/dist/package/skills/scaffold/profiles/rust-native-desktop/Cargo.toml +24 -0
- package/dist/package/skills/scaffold/profiles/rust-native-desktop/README.md +15 -0
- package/dist/package/skills/scaffold/profiles/rust-native-desktop/deny.toml +35 -0
- package/dist/package/skills/scaffold/profiles/rust-native-desktop/rustfmt.toml +2 -0
- package/dist/package/skills/scaffold/profiles/rust-native-desktop/src/main.rs +74 -0
- package/dist/package/skills/scaffold/references/gates.md +29 -0
- package/dist/package/skills/scaffold/references/profiles.md +36 -0
- package/dist/package/skills/update/SKILL.md +115 -0
- package/dist/package/skills/verify-visual/SKILL.md +82 -0
- package/dist/package/skills/verify-visual/references/baseline.md +46 -0
- package/dist/package/skills/visual-loop/SKILL.md +72 -0
- package/dist/package/workflows/batch-to-review.md +41 -0
- package/dist/package/workflows/framework-improvement.md +38 -0
- package/dist/package/workflows/hard-bug.md +37 -0
- package/dist/package/workflows/new-rust-cli.md +33 -0
- package/dist/package/workflows/new-rust-desktop-app.md +41 -0
- package/dist/package/workflows/new-rust-library.md +34 -0
- package/dist/package/workflows/performance-work.md +41 -0
- package/dist/package/workflows/ui-change.md +40 -0
- package/package.json +33 -4
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
use std::{
|
|
2
|
+
fmt,
|
|
3
|
+
fs::OpenOptions,
|
|
4
|
+
io,
|
|
5
|
+
path::{Path, PathBuf},
|
|
6
|
+
str::FromStr,
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
use tracing_subscriber::{Layer, filter::LevelFilter, fmt as fmt_layer, layer::SubscriberExt};
|
|
10
|
+
|
|
11
|
+
/// Chemin du fichier JSON. Variable obligatoire : sans fichier, une application
|
|
12
|
+
/// GUI n'a aucun journal fiable.
|
|
13
|
+
pub const LOG_PATH_ENV: &str = "APP_LOG";
|
|
14
|
+
/// Niveau de journalisation optionnel (`error`, `warn`, `info`, `debug`,
|
|
15
|
+
/// `trace`, `off`). `info` par défaut.
|
|
16
|
+
pub const LOG_LEVEL_ENV: &str = "APP_LOG_LEVEL";
|
|
17
|
+
|
|
18
|
+
/// Garde le thread d'écriture vivant. Le déposer vide la file : c'est la raison
|
|
19
|
+
/// pour laquelle le binaire rend un code de sortie au lieu d'appeler
|
|
20
|
+
/// `std::process::exit`, qui peut perdre les derniers événements.
|
|
21
|
+
pub struct LoggingGuard {
|
|
22
|
+
_worker: tracing_appender::non_blocking::WorkerGuard,
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
#[derive(Debug)]
|
|
26
|
+
pub enum LoggingError {
|
|
27
|
+
MissingPath,
|
|
28
|
+
Open { path: PathBuf, source: io::Error },
|
|
29
|
+
InvalidLevel(String),
|
|
30
|
+
Install(String),
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
impl fmt::Display for LoggingError {
|
|
34
|
+
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
35
|
+
match self {
|
|
36
|
+
Self::MissingPath => write!(
|
|
37
|
+
formatter,
|
|
38
|
+
"{LOG_PATH_ENV} n'est pas défini: chemin du fichier de log requis"
|
|
39
|
+
),
|
|
40
|
+
Self::Open { path, source } => write!(
|
|
41
|
+
formatter,
|
|
42
|
+
"ouverture du fichier de log « {} » impossible: {source}",
|
|
43
|
+
path.display()
|
|
44
|
+
),
|
|
45
|
+
Self::InvalidLevel(level) => {
|
|
46
|
+
write!(formatter, "{LOG_LEVEL_ENV} invalide: « {level} »")
|
|
47
|
+
}
|
|
48
|
+
Self::Install(message) => {
|
|
49
|
+
write!(formatter, "abonné de traçage déjà installé: {message}")
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
impl std::error::Error for LoggingError {
|
|
56
|
+
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
|
57
|
+
match self {
|
|
58
|
+
Self::Open { source, .. } => Some(source),
|
|
59
|
+
Self::MissingPath | Self::InvalidLevel(_) | Self::Install(_) => None,
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/// Installe les deux couches : JSON vers le fichier `path`, humain compact vers
|
|
65
|
+
/// stderr. Le fichier est ouvert en ajout : une session n'efface pas la précédente.
|
|
66
|
+
/// stdout n'est jamais utilisé, et stderr n'est pas bufferisé : chaque ligne est
|
|
67
|
+
/// écrite immédiatement.
|
|
68
|
+
pub fn init(path: &Path, level: LevelFilter) -> Result<LoggingGuard, LoggingError> {
|
|
69
|
+
let file = OpenOptions::new()
|
|
70
|
+
.create(true)
|
|
71
|
+
.append(true)
|
|
72
|
+
.open(path)
|
|
73
|
+
.map_err(|source| LoggingError::Open {
|
|
74
|
+
path: path.to_path_buf(),
|
|
75
|
+
source,
|
|
76
|
+
})?;
|
|
77
|
+
let (writer, worker) = tracing_appender::non_blocking(file);
|
|
78
|
+
|
|
79
|
+
let file_layer = fmt_layer::layer()
|
|
80
|
+
.json()
|
|
81
|
+
.with_ansi(false)
|
|
82
|
+
.with_writer(writer)
|
|
83
|
+
.with_filter(level);
|
|
84
|
+
let stderr_layer = fmt_layer::layer()
|
|
85
|
+
.compact()
|
|
86
|
+
.with_ansi(false)
|
|
87
|
+
.with_writer(io::stderr)
|
|
88
|
+
.with_filter(level);
|
|
89
|
+
|
|
90
|
+
let subscriber = tracing_subscriber::registry()
|
|
91
|
+
.with(file_layer)
|
|
92
|
+
.with(stderr_layer);
|
|
93
|
+
tracing::subscriber::set_global_default(subscriber)
|
|
94
|
+
.map_err(|error| LoggingError::Install(error.to_string()))?;
|
|
95
|
+
|
|
96
|
+
Ok(LoggingGuard { _worker: worker })
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/// Lit `APP_LOG` et `APP_LOG_LEVEL`, puis installe les couches.
|
|
100
|
+
pub fn init_from_env() -> Result<LoggingGuard, LoggingError> {
|
|
101
|
+
let path = std::env::var_os(LOG_PATH_ENV).ok_or(LoggingError::MissingPath)?;
|
|
102
|
+
let level = match std::env::var(LOG_LEVEL_ENV) {
|
|
103
|
+
Ok(value) => {
|
|
104
|
+
LevelFilter::from_str(&value).map_err(|_| LoggingError::InvalidLevel(value))?
|
|
105
|
+
}
|
|
106
|
+
Err(_) => LevelFilter::INFO,
|
|
107
|
+
};
|
|
108
|
+
init(Path::new(&path), level)
|
|
109
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
use serde::{Deserialize, Serialize};
|
|
2
|
+
use serde_json::Value;
|
|
3
|
+
|
|
4
|
+
/// Une requête du protocole : le nom de la commande et ses paramètres.
|
|
5
|
+
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
6
|
+
pub struct Request {
|
|
7
|
+
pub command: String,
|
|
8
|
+
#[serde(default)]
|
|
9
|
+
pub params: Value,
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
impl Request {
|
|
13
|
+
pub fn new(command: impl Into<String>, params: Value) -> Self {
|
|
14
|
+
Self {
|
|
15
|
+
command: command.into(),
|
|
16
|
+
params,
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/// La réponse du protocole. `data` et `error` sont toujours présents, à `null`
|
|
22
|
+
/// quand ils ne s'appliquent pas : un client peut lire les deux champs sans
|
|
23
|
+
/// deviner la forme de l'objet.
|
|
24
|
+
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
25
|
+
pub struct Response {
|
|
26
|
+
pub ok: bool,
|
|
27
|
+
#[serde(default)]
|
|
28
|
+
pub data: Option<Value>,
|
|
29
|
+
#[serde(default)]
|
|
30
|
+
pub error: Option<String>,
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
impl Response {
|
|
34
|
+
pub fn success(data: Value) -> Self {
|
|
35
|
+
Self {
|
|
36
|
+
ok: true,
|
|
37
|
+
data: Some(data),
|
|
38
|
+
error: None,
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
pub fn failure(error: impl Into<String>) -> Self {
|
|
43
|
+
Self {
|
|
44
|
+
ok: false,
|
|
45
|
+
data: None,
|
|
46
|
+
error: Some(error.into()),
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
use std::{
|
|
2
|
+
collections::BTreeMap,
|
|
3
|
+
fmt,
|
|
4
|
+
sync::{Mutex, MutexGuard, PoisonError},
|
|
5
|
+
time::Duration,
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
use serde_json::{Value, json};
|
|
9
|
+
|
|
10
|
+
/// Signature d'une commande : elle reçoit les paramètres et rend une donnée ou
|
|
11
|
+
/// un message d'erreur destiné au client.
|
|
12
|
+
pub type Handler = Box<dyn Fn(Value) -> Result<Value, String> + Send + Sync>;
|
|
13
|
+
|
|
14
|
+
/// Les commandes du protocole, toujours disponibles et impossibles à écraser.
|
|
15
|
+
pub const PROTOCOL_COMMANDS: [&str; 4] = ["list", "state", "action", "wait"];
|
|
16
|
+
|
|
17
|
+
/// Plafond de `wait` : une commande ne peut pas immobiliser le serveur plus
|
|
18
|
+
/// longtemps que cette durée, même si le client demande davantage.
|
|
19
|
+
pub const MAX_WAIT_MS: u64 = 2_000;
|
|
20
|
+
|
|
21
|
+
#[derive(Debug, Default)]
|
|
22
|
+
struct State {
|
|
23
|
+
revision: u64,
|
|
24
|
+
values: BTreeMap<String, Value>,
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/// Registre de commandes et état partagé du serveur.
|
|
28
|
+
pub struct Instrument {
|
|
29
|
+
commands: BTreeMap<String, Handler>,
|
|
30
|
+
state: Mutex<State>,
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/// Refus d'enregistrement d'une commande.
|
|
34
|
+
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
35
|
+
pub enum RegistryError {
|
|
36
|
+
EmptyName,
|
|
37
|
+
Reserved(String),
|
|
38
|
+
Duplicate(String),
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
impl fmt::Display for RegistryError {
|
|
42
|
+
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
43
|
+
match self {
|
|
44
|
+
Self::EmptyName => write!(formatter, "le nom de commande ne peut pas être vide"),
|
|
45
|
+
Self::Reserved(name) => {
|
|
46
|
+
write!(formatter, "le nom « {name} » est réservé au protocole")
|
|
47
|
+
}
|
|
48
|
+
Self::Duplicate(name) => {
|
|
49
|
+
write!(formatter, "la commande « {name} » est déjà enregistrée")
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
impl std::error::Error for RegistryError {}
|
|
56
|
+
|
|
57
|
+
impl Instrument {
|
|
58
|
+
pub fn new() -> Self {
|
|
59
|
+
Self {
|
|
60
|
+
commands: BTreeMap::new(),
|
|
61
|
+
state: Mutex::new(State::default()),
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/// Enregistre une commande. Les noms du protocole et les doublons sont
|
|
66
|
+
/// refusés explicitement plutôt qu'écrasés en silence.
|
|
67
|
+
pub fn command<F>(
|
|
68
|
+
&mut self,
|
|
69
|
+
name: impl Into<String>,
|
|
70
|
+
handler: F,
|
|
71
|
+
) -> Result<&mut Self, RegistryError>
|
|
72
|
+
where
|
|
73
|
+
F: Fn(Value) -> Result<Value, String> + Send + Sync + 'static,
|
|
74
|
+
{
|
|
75
|
+
let name = name.into();
|
|
76
|
+
if name.trim().is_empty() {
|
|
77
|
+
return Err(RegistryError::EmptyName);
|
|
78
|
+
}
|
|
79
|
+
if PROTOCOL_COMMANDS.contains(&name.as_str()) {
|
|
80
|
+
return Err(RegistryError::Reserved(name));
|
|
81
|
+
}
|
|
82
|
+
if self.commands.contains_key(&name) {
|
|
83
|
+
return Err(RegistryError::Duplicate(name));
|
|
84
|
+
}
|
|
85
|
+
self.commands.insert(name, Box::new(handler));
|
|
86
|
+
Ok(self)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/// Exécute une commande et rend la donnée de réponse.
|
|
90
|
+
pub fn invoke(&self, command: &str, params: Value) -> Result<Value, String> {
|
|
91
|
+
match command {
|
|
92
|
+
"list" => Ok(json!({ "commands": self.command_names() })),
|
|
93
|
+
"state" => Ok(self.snapshot()),
|
|
94
|
+
"action" => self.action(params),
|
|
95
|
+
"wait" => wait(params),
|
|
96
|
+
_ => match self.commands.get(command) {
|
|
97
|
+
Some(handler) => handler(params),
|
|
98
|
+
None => Err(format!("commande inconnue: {command}")),
|
|
99
|
+
},
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
fn command_names(&self) -> Value {
|
|
104
|
+
let mut names: Vec<String> = PROTOCOL_COMMANDS
|
|
105
|
+
.iter()
|
|
106
|
+
.map(|name| (*name).to_owned())
|
|
107
|
+
.collect();
|
|
108
|
+
names.extend(self.commands.keys().cloned());
|
|
109
|
+
names.sort();
|
|
110
|
+
names.dedup();
|
|
111
|
+
Value::Array(names.into_iter().map(Value::String).collect())
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
fn snapshot(&self) -> Value {
|
|
115
|
+
let state = self.lock_state();
|
|
116
|
+
let values: serde_json::Map<String, Value> = state
|
|
117
|
+
.values
|
|
118
|
+
.iter()
|
|
119
|
+
.map(|(key, value)| (key.clone(), value.clone()))
|
|
120
|
+
.collect();
|
|
121
|
+
json!({ "revision": state.revision, "values": values })
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
fn action(&self, params: Value) -> Result<Value, String> {
|
|
125
|
+
let object = params
|
|
126
|
+
.as_object()
|
|
127
|
+
.ok_or("action: paramètres attendus sous forme d'objet")?;
|
|
128
|
+
let key = object
|
|
129
|
+
.get("key")
|
|
130
|
+
.and_then(Value::as_str)
|
|
131
|
+
.filter(|key| !key.is_empty())
|
|
132
|
+
.ok_or("action: 'key' doit être une chaîne non vide")?;
|
|
133
|
+
let value = object
|
|
134
|
+
.get("value")
|
|
135
|
+
.cloned()
|
|
136
|
+
.ok_or("action: 'value' est requis")?;
|
|
137
|
+
|
|
138
|
+
let mut state = self.lock_state();
|
|
139
|
+
state.revision = state.revision.saturating_add(1);
|
|
140
|
+
let revision = state.revision;
|
|
141
|
+
state.values.insert(key.to_owned(), value);
|
|
142
|
+
Ok(json!({ "revision": revision, "key": key }))
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/// Un empoisonnement du verrou viendrait d'un panic interne, pas d'une
|
|
146
|
+
/// entrée cliente : on reprend l'état plutôt que de paniquer à nouveau.
|
|
147
|
+
fn lock_state(&self) -> MutexGuard<'_, State> {
|
|
148
|
+
self.state.lock().unwrap_or_else(PoisonError::into_inner)
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
impl Default for Instrument {
|
|
153
|
+
fn default() -> Self {
|
|
154
|
+
Self::new()
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
fn wait(params: Value) -> Result<Value, String> {
|
|
159
|
+
let requested = params
|
|
160
|
+
.get("milliseconds")
|
|
161
|
+
.and_then(Value::as_u64)
|
|
162
|
+
.ok_or("wait: 'milliseconds' doit être un entier positif ou nul")?;
|
|
163
|
+
let waited = requested.min(MAX_WAIT_MS);
|
|
164
|
+
std::thread::sleep(Duration::from_millis(waited));
|
|
165
|
+
Ok(json!({ "requested_ms": requested, "waited_ms": waited }))
|
|
166
|
+
}
|
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
use std::{
|
|
2
|
+
io::{self},
|
|
3
|
+
path::PathBuf,
|
|
4
|
+
sync::atomic::{AtomicU64, Ordering},
|
|
5
|
+
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
use serde_json::{Value, json};
|
|
9
|
+
|
|
10
|
+
use crate::{
|
|
11
|
+
client::{Client, ClientError, DEFAULT_TIMEOUT},
|
|
12
|
+
registry::Instrument,
|
|
13
|
+
server::{PathError, Server, validate_socket_path},
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
|
|
17
|
+
|
|
18
|
+
/// Une assertion nommée : le nom reste stable, la raison est lisible par un
|
|
19
|
+
/// humain et par un script.
|
|
20
|
+
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
21
|
+
pub struct Outcome {
|
|
22
|
+
pub name: &'static str,
|
|
23
|
+
pub result: Result<(), String>,
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
#[derive(Debug, Clone, Default)]
|
|
27
|
+
pub struct SelftestOptions {
|
|
28
|
+
/// Nom d'assertion à faire échouer volontairement. Sert à prouver que le
|
|
29
|
+
/// rapport distingue PASS de FAIL et rend bien le code de sortie 1.
|
|
30
|
+
pub break_assertion: Option<String>,
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/// Exécute la suite sur un état temporaire : socket et registre neufs, répertoire
|
|
34
|
+
/// supprimé au retour. Aucun panic n'est utilisé comme mécanisme d'échec.
|
|
35
|
+
pub fn run(options: &SelftestOptions) -> Vec<Outcome> {
|
|
36
|
+
let mut checker = Checker {
|
|
37
|
+
outcomes: Vec::new(),
|
|
38
|
+
broken: options.break_assertion.clone(),
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
checker.check("socket-path-limit", || {
|
|
42
|
+
let limit = crate::server::MAX_SOCKET_PATH_BYTES;
|
|
43
|
+
let mut long = PathBuf::new();
|
|
44
|
+
long.push("a".repeat(limit + 20));
|
|
45
|
+
long.push("s");
|
|
46
|
+
// The expected number is computed here, not read back from the path buffer: a
|
|
47
|
+
// `validate_socket_path` that reported the wrong length would then fail instead of
|
|
48
|
+
// agreeing with itself (review finding 2026-11-29). 120 bytes of "a", one separator
|
|
49
|
+
// that `push` inserts, one "s" — measured, and the previous value was wrong by exactly
|
|
50
|
+
// the separator.
|
|
51
|
+
let bytes = limit + 20 + 1 + 1;
|
|
52
|
+
match validate_socket_path(&long) {
|
|
53
|
+
Err(PathError::TooLong {
|
|
54
|
+
bytes: seen,
|
|
55
|
+
limit: seen_limit,
|
|
56
|
+
}) if seen == bytes && seen_limit == limit => Ok(()),
|
|
57
|
+
other => Err(format!(
|
|
58
|
+
"chemin de {bytes} octets non refusé comme prévu: {other:?}"
|
|
59
|
+
)),
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
let temp = match TempDir::new("in") {
|
|
64
|
+
Ok(temp) => temp,
|
|
65
|
+
Err(error) => {
|
|
66
|
+
checker.fail(
|
|
67
|
+
"temp-dir",
|
|
68
|
+
format!("répertoire temporaire impossible: {error}"),
|
|
69
|
+
);
|
|
70
|
+
return checker.outcomes;
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
let socket = temp.path().join("s");
|
|
74
|
+
|
|
75
|
+
let mut instrument = Instrument::new();
|
|
76
|
+
checker.check("register-custom", || {
|
|
77
|
+
instrument
|
|
78
|
+
.command("echo", |params| Ok(json!({ "echo": params })))
|
|
79
|
+
.map(|_| ())
|
|
80
|
+
.map_err(|error| error.to_string())
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
let mut server = match Server::start(instrument, &socket) {
|
|
84
|
+
Ok(server) => {
|
|
85
|
+
checker.check("server-start", || Ok(()));
|
|
86
|
+
server
|
|
87
|
+
}
|
|
88
|
+
Err(error) => {
|
|
89
|
+
checker.fail("server-start", error.to_string());
|
|
90
|
+
return checker.outcomes;
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
#[cfg(unix)]
|
|
95
|
+
checker.check("socket-permissions", || {
|
|
96
|
+
use std::os::unix::fs::PermissionsExt;
|
|
97
|
+
|
|
98
|
+
let mode = std::fs::metadata(&socket)
|
|
99
|
+
.map_err(|error| format!("métadonnées du socket: {error}"))?
|
|
100
|
+
.permissions()
|
|
101
|
+
.mode()
|
|
102
|
+
& 0o777;
|
|
103
|
+
if mode == 0o600 {
|
|
104
|
+
Ok(())
|
|
105
|
+
} else {
|
|
106
|
+
Err(format!("mode {mode:o}, attendu 600"))
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
let mut client = match Client::connect(&socket, DEFAULT_TIMEOUT) {
|
|
111
|
+
Ok(client) => {
|
|
112
|
+
checker.check("client-connect", || Ok(()));
|
|
113
|
+
client
|
|
114
|
+
}
|
|
115
|
+
Err(error) => {
|
|
116
|
+
checker.fail("client-connect", error.to_string());
|
|
117
|
+
server.shutdown();
|
|
118
|
+
return checker.outcomes;
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
checker.check("list", || {
|
|
123
|
+
let data = client
|
|
124
|
+
.call("list", Value::Null)
|
|
125
|
+
.map_err(|error| error.to_string())?;
|
|
126
|
+
let commands = data
|
|
127
|
+
.get("commands")
|
|
128
|
+
.and_then(Value::as_array)
|
|
129
|
+
.ok_or("réponse sans tableau 'commands'")?;
|
|
130
|
+
match missing_command(commands, &["list", "state", "action", "wait", "echo"]) {
|
|
131
|
+
Some(name) => Err(format!("commande absente de list: {name}")),
|
|
132
|
+
None => Ok(()),
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
checker.check("state-initial", || {
|
|
137
|
+
let data = client
|
|
138
|
+
.call("state", Value::Null)
|
|
139
|
+
.map_err(|error| error.to_string())?;
|
|
140
|
+
if data.get("revision").and_then(Value::as_u64) != Some(0) {
|
|
141
|
+
return Err(format!("révision initiale inattendue: {data}"));
|
|
142
|
+
}
|
|
143
|
+
let values = data
|
|
144
|
+
.get("values")
|
|
145
|
+
.and_then(Value::as_object)
|
|
146
|
+
.ok_or("réponse sans objet 'values'")?;
|
|
147
|
+
if !values.is_empty() {
|
|
148
|
+
return Err(format!("état initial non vide: {data}"));
|
|
149
|
+
}
|
|
150
|
+
Ok(())
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
checker.check("action", || {
|
|
154
|
+
let data = client
|
|
155
|
+
.call("action", json!({ "key": "selftest", "value": { "n": 1 } }))
|
|
156
|
+
.map_err(|error| error.to_string())?;
|
|
157
|
+
if data.get("revision").and_then(Value::as_u64) != Some(1) {
|
|
158
|
+
return Err(format!("révision après action inattendue: {data}"));
|
|
159
|
+
}
|
|
160
|
+
Ok(())
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
checker.check("state-after-action", || {
|
|
164
|
+
let data = client
|
|
165
|
+
.call("state", Value::Null)
|
|
166
|
+
.map_err(|error| error.to_string())?;
|
|
167
|
+
let value = data
|
|
168
|
+
.get("values")
|
|
169
|
+
.and_then(|values| values.get("selftest"))
|
|
170
|
+
.and_then(|value| value.get("n"))
|
|
171
|
+
.and_then(Value::as_u64);
|
|
172
|
+
if value != Some(1) {
|
|
173
|
+
return Err(format!("valeur écrite absente de l'état: {data}"));
|
|
174
|
+
}
|
|
175
|
+
Ok(())
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
checker.check("custom-command", || {
|
|
179
|
+
let data = client
|
|
180
|
+
.call("echo", json!({ "x": 1 }))
|
|
181
|
+
.map_err(|error| error.to_string())?;
|
|
182
|
+
if data.get("echo") != Some(&json!({ "x": 1 })) {
|
|
183
|
+
return Err(format!("réponse de echo inattendue: {data}"));
|
|
184
|
+
}
|
|
185
|
+
Ok(())
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
checker.check("unknown-command", || {
|
|
189
|
+
match client.call("commande-qui-nexiste-pas", Value::Null) {
|
|
190
|
+
Err(ClientError::Remote(message)) if message.contains("inconnue") => Ok(()),
|
|
191
|
+
other => Err(format!("erreur inattendue: {other:?}")),
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
checker.check("invalid-params", || {
|
|
196
|
+
match client.call("action", json!({})) {
|
|
197
|
+
Err(ClientError::Remote(message)) if message.contains("key") => Ok(()),
|
|
198
|
+
other => Err(format!("erreur inattendue: {other:?}")),
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
checker.check("wait", || {
|
|
203
|
+
let started = Instant::now();
|
|
204
|
+
let data = client
|
|
205
|
+
.call("wait", json!({ "milliseconds": 5 }))
|
|
206
|
+
.map_err(|error| error.to_string())?;
|
|
207
|
+
if data.get("waited_ms").and_then(Value::as_u64) != Some(5) {
|
|
208
|
+
return Err(format!("attente rapportée inattendue: {data}"));
|
|
209
|
+
}
|
|
210
|
+
waited_within_bounds(started.elapsed())
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
checker.check("client-timeout", || {
|
|
214
|
+
let mut impatient = Client::connect(&socket, Duration::from_millis(100))
|
|
215
|
+
.map_err(|error| error.to_string())?;
|
|
216
|
+
let started = Instant::now();
|
|
217
|
+
match impatient.call("wait", json!({ "milliseconds": 400 })) {
|
|
218
|
+
Err(ClientError::Timeout) => client_timeout_within_bound(started.elapsed()),
|
|
219
|
+
other => Err(format!("l'attente n'a pas été interrompue: {other:?}")),
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
drop(client);
|
|
224
|
+
server.shutdown();
|
|
225
|
+
checker.check("socket-removed", || {
|
|
226
|
+
if socket.exists() {
|
|
227
|
+
Err(format!(
|
|
228
|
+
"le socket subsiste après arrêt: {}",
|
|
229
|
+
socket.display()
|
|
230
|
+
))
|
|
231
|
+
} else {
|
|
232
|
+
Ok(())
|
|
233
|
+
}
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
checker.outcomes
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/// La première commande attendue qui manque à `list`, s'il y en a une : la
|
|
240
|
+
/// recherche est isolée pour qu'un test la vérifie sans serveur.
|
|
241
|
+
fn missing_command<'a>(commands: &[Value], expected: &[&'a str]) -> Option<&'a str> {
|
|
242
|
+
expected.iter().copied().find(|name| {
|
|
243
|
+
!commands
|
|
244
|
+
.iter()
|
|
245
|
+
.any(|command| command.as_str() == Some(*name))
|
|
246
|
+
})
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/// Borne basse de l'attente mesurée : `wait` a été appelé pour 5 ms, donc en
|
|
250
|
+
/// dessous la commande a menti sur sa durée.
|
|
251
|
+
const MIN_WAITED: Duration = Duration::from_millis(5);
|
|
252
|
+
|
|
253
|
+
/// Plafond de l'attente mesurée, côté serveur comme côté client.
|
|
254
|
+
const MAX_WAITED: Duration = Duration::from_secs(1);
|
|
255
|
+
|
|
256
|
+
fn waited_within_bounds(elapsed: Duration) -> Result<(), String> {
|
|
257
|
+
if elapsed < MIN_WAITED {
|
|
258
|
+
return Err(format!("wait a rendu trop tôt: {elapsed:?}"));
|
|
259
|
+
}
|
|
260
|
+
if elapsed > MAX_WAITED {
|
|
261
|
+
return Err(format!("wait a dépassé son plafond: {elapsed:?}"));
|
|
262
|
+
}
|
|
263
|
+
Ok(())
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/// Le client devait couper l'attente bien avant son plafond : au-delà, c'est le
|
|
267
|
+
/// serveur qui a borné l'attente, pas le timeout du client.
|
|
268
|
+
fn client_timeout_within_bound(elapsed: Duration) -> Result<(), String> {
|
|
269
|
+
if elapsed > MAX_WAITED {
|
|
270
|
+
return Err("le timeout client n'a pas borné l'attente".to_owned());
|
|
271
|
+
}
|
|
272
|
+
Ok(())
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/// Imprime `PASS nom` ou `FAIL nom — raison`, une ligne par assertion. Rend
|
|
276
|
+
/// `true` seulement si toutes les assertions passent.
|
|
277
|
+
pub fn report(outcomes: &[Outcome], out: &mut dyn io::Write) -> bool {
|
|
278
|
+
let mut all_passed = true;
|
|
279
|
+
for outcome in outcomes {
|
|
280
|
+
let line = match &outcome.result {
|
|
281
|
+
Ok(()) => format!("PASS {}", outcome.name),
|
|
282
|
+
Err(reason) => {
|
|
283
|
+
all_passed = false;
|
|
284
|
+
format!("FAIL {} — {reason}", outcome.name)
|
|
285
|
+
}
|
|
286
|
+
};
|
|
287
|
+
if writeln!(out, "{line}").is_err() {
|
|
288
|
+
return false;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
all_passed
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
struct Checker {
|
|
295
|
+
outcomes: Vec<Outcome>,
|
|
296
|
+
broken: Option<String>,
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
impl Checker {
|
|
300
|
+
fn check(&mut self, name: &'static str, assertion: impl FnOnce() -> Result<(), String>) {
|
|
301
|
+
if self.broken.as_deref() == Some(name) {
|
|
302
|
+
self.fail(name, format!("échec injecté (--break {name})"));
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
self.outcomes.push(Outcome {
|
|
306
|
+
name,
|
|
307
|
+
result: assertion(),
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
fn fail(&mut self, name: &'static str, reason: impl Into<String>) {
|
|
312
|
+
self.outcomes.push(Outcome {
|
|
313
|
+
name,
|
|
314
|
+
result: Err(reason.into()),
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
struct TempDir {
|
|
320
|
+
path: PathBuf,
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
impl TempDir {
|
|
324
|
+
fn new(prefix: &str) -> io::Result<Self> {
|
|
325
|
+
let counter = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
|
|
326
|
+
let nanos = SystemTime::now()
|
|
327
|
+
.duration_since(UNIX_EPOCH)
|
|
328
|
+
.map(|duration| duration.as_nanos())
|
|
329
|
+
.unwrap_or(0);
|
|
330
|
+
let path =
|
|
331
|
+
std::env::temp_dir().join(format!("{prefix}-{}-{counter}-{nanos}", std::process::id()));
|
|
332
|
+
std::fs::create_dir(&path)?;
|
|
333
|
+
Ok(Self { path })
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
fn path(&self) -> &std::path::Path {
|
|
337
|
+
&self.path
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
impl Drop for TempDir {
|
|
342
|
+
fn drop(&mut self) {
|
|
343
|
+
let _ = std::fs::remove_dir_all(&self.path);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
#[cfg(test)]
|
|
348
|
+
mod tests {
|
|
349
|
+
use super::*;
|
|
350
|
+
|
|
351
|
+
#[test]
|
|
352
|
+
fn une_commande_absente_de_list_est_nommee() {
|
|
353
|
+
let commands = [json!("list"), json!("echo")];
|
|
354
|
+
assert_eq!(missing_command(&commands, &["list"]), None);
|
|
355
|
+
assert_eq!(missing_command(&commands, &["absent"]), Some("absent"));
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
#[test]
|
|
359
|
+
fn une_attente_trop_courte_ou_trop_longue_est_refusee() {
|
|
360
|
+
let too_early = MIN_WAITED - Duration::from_millis(1);
|
|
361
|
+
assert!(waited_within_bounds(too_early).is_err());
|
|
362
|
+
assert!(waited_within_bounds(MIN_WAITED).is_ok());
|
|
363
|
+
assert!(waited_within_bounds(MAX_WAITED).is_ok());
|
|
364
|
+
let too_late = MAX_WAITED + Duration::from_millis(1);
|
|
365
|
+
assert!(waited_within_bounds(too_late).is_err());
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
#[test]
|
|
369
|
+
fn un_timeout_client_au_dela_du_plafond_est_refuse() {
|
|
370
|
+
assert!(client_timeout_within_bound(Duration::from_millis(100)).is_ok());
|
|
371
|
+
assert!(client_timeout_within_bound(MAX_WAITED).is_ok());
|
|
372
|
+
let too_late = MAX_WAITED + Duration::from_nanos(1);
|
|
373
|
+
assert!(client_timeout_within_bound(too_late).is_err());
|
|
374
|
+
}
|
|
375
|
+
}
|