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.
Files changed (89) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +168 -2
  3. package/bin/create-lathe.js +88 -0
  4. package/dist/framework.lock +115 -0
  5. package/dist/package/crates/instrument/Cargo.lock +415 -0
  6. package/dist/package/crates/instrument/Cargo.toml +27 -0
  7. package/dist/package/crates/instrument/examples/instrument.rs +73 -0
  8. package/dist/package/crates/instrument/src/client.rs +128 -0
  9. package/dist/package/crates/instrument/src/lib.rs +32 -0
  10. package/dist/package/crates/instrument/src/logging.rs +109 -0
  11. package/dist/package/crates/instrument/src/protocol.rs +49 -0
  12. package/dist/package/crates/instrument/src/registry.rs +166 -0
  13. package/dist/package/crates/instrument/src/selftest.rs +375 -0
  14. package/dist/package/crates/instrument/src/server.rs +363 -0
  15. package/dist/package/crates/instrument/tests/command_log.rs +60 -0
  16. package/dist/package/crates/instrument/tests/erreurs.rs +167 -0
  17. package/dist/package/crates/instrument/tests/round_trip.rs +230 -0
  18. package/dist/package/crates/instrument/tests/selftest_fail.rs +25 -0
  19. package/dist/package/crates/instrument/tests/selftest_pass.rs +24 -0
  20. package/dist/package/crates/instrument/tests/selftest_temps.rs +43 -0
  21. package/dist/package/crates/instrument/tests/support/mod.rs +58 -0
  22. package/dist/package/pi/context/journal-de-lot.md +24 -0
  23. package/dist/package/pi/context/tech-skill.md +19 -0
  24. package/dist/package/pi/context/ticket-closed.md +18 -0
  25. package/dist/package/scripts/framework.py +1384 -0
  26. package/dist/package/scripts/gates.py +1158 -0
  27. package/dist/package/scripts/setup.py +251 -0
  28. package/dist/package/skills/bootstrap/SKILL.md +110 -0
  29. package/dist/package/skills/documentation/SKILL.md +110 -0
  30. package/dist/package/skills/documentation/references/agents-md.md +70 -0
  31. package/dist/package/skills/documentation/references/corpus.md +112 -0
  32. package/dist/package/skills/journal/SKILL.md +81 -0
  33. package/dist/package/skills/journal/references/entry.md +172 -0
  34. package/dist/package/skills/lathe/SKILL.md +185 -0
  35. package/dist/package/skills/lathe/evals/routing.md +231 -0
  36. package/dist/package/skills/lathe/references/install.md +161 -0
  37. package/dist/package/skills/lathe/references/invariants.md +31 -0
  38. package/dist/package/skills/mutants/SKILL.md +88 -0
  39. package/dist/package/skills/mutants/references/cargo-mutants.md +176 -0
  40. package/dist/package/skills/mutants/references/triage.md +88 -0
  41. package/dist/package/skills/optimize/SKILL.md +87 -0
  42. package/dist/package/skills/optimize/references/codspeed.md +126 -0
  43. package/dist/package/skills/probe/SKILL.md +82 -0
  44. package/dist/package/skills/probe/references/wait-and-read.md +53 -0
  45. package/dist/package/skills/replicate-ui/SKILL.md +64 -0
  46. package/dist/package/skills/rust/SKILL.md +147 -0
  47. package/dist/package/skills/rust/references/errors.md +63 -0
  48. package/dist/package/skills/rust/references/unsafe.md +65 -0
  49. package/dist/package/skills/scaffold/SKILL.md +78 -0
  50. package/dist/package/skills/scaffold/profiles/rust-cli/.cargo/config.toml +2 -0
  51. package/dist/package/skills/scaffold/profiles/rust-cli/AGENTS.md +22 -0
  52. package/dist/package/skills/scaffold/profiles/rust-cli/Cargo.lock +7 -0
  53. package/dist/package/skills/scaffold/profiles/rust-cli/Cargo.toml +17 -0
  54. package/dist/package/skills/scaffold/profiles/rust-cli/README.md +15 -0
  55. package/dist/package/skills/scaffold/profiles/rust-cli/deny.toml +14 -0
  56. package/dist/package/skills/scaffold/profiles/rust-cli/rustfmt.toml +2 -0
  57. package/dist/package/skills/scaffold/profiles/rust-cli/src/main.rs +38 -0
  58. package/dist/package/skills/scaffold/profiles/rust-cli/tests/cli.rs +27 -0
  59. package/dist/package/skills/scaffold/profiles/rust-library/.cargo/config.toml +2 -0
  60. package/dist/package/skills/scaffold/profiles/rust-library/AGENTS.md +21 -0
  61. package/dist/package/skills/scaffold/profiles/rust-library/Cargo.lock +7 -0
  62. package/dist/package/skills/scaffold/profiles/rust-library/Cargo.toml +18 -0
  63. package/dist/package/skills/scaffold/profiles/rust-library/README.md +15 -0
  64. package/dist/package/skills/scaffold/profiles/rust-library/deny.toml +14 -0
  65. package/dist/package/skills/scaffold/profiles/rust-library/rustfmt.toml +2 -0
  66. package/dist/package/skills/scaffold/profiles/rust-library/src/lib.rs +25 -0
  67. package/dist/package/skills/scaffold/profiles/rust-native-desktop/.cargo/config.toml +2 -0
  68. package/dist/package/skills/scaffold/profiles/rust-native-desktop/AGENTS.md +23 -0
  69. package/dist/package/skills/scaffold/profiles/rust-native-desktop/Cargo.lock +9252 -0
  70. package/dist/package/skills/scaffold/profiles/rust-native-desktop/Cargo.toml +24 -0
  71. package/dist/package/skills/scaffold/profiles/rust-native-desktop/README.md +15 -0
  72. package/dist/package/skills/scaffold/profiles/rust-native-desktop/deny.toml +35 -0
  73. package/dist/package/skills/scaffold/profiles/rust-native-desktop/rustfmt.toml +2 -0
  74. package/dist/package/skills/scaffold/profiles/rust-native-desktop/src/main.rs +74 -0
  75. package/dist/package/skills/scaffold/references/gates.md +29 -0
  76. package/dist/package/skills/scaffold/references/profiles.md +36 -0
  77. package/dist/package/skills/update/SKILL.md +115 -0
  78. package/dist/package/skills/verify-visual/SKILL.md +82 -0
  79. package/dist/package/skills/verify-visual/references/baseline.md +46 -0
  80. package/dist/package/skills/visual-loop/SKILL.md +72 -0
  81. package/dist/package/workflows/batch-to-review.md +41 -0
  82. package/dist/package/workflows/framework-improvement.md +38 -0
  83. package/dist/package/workflows/hard-bug.md +37 -0
  84. package/dist/package/workflows/new-rust-cli.md +33 -0
  85. package/dist/package/workflows/new-rust-desktop-app.md +41 -0
  86. package/dist/package/workflows/new-rust-library.md +34 -0
  87. package/dist/package/workflows/performance-work.md +41 -0
  88. package/dist/package/workflows/ui-change.md +40 -0
  89. package/package.json +33 -4
@@ -0,0 +1,363 @@
1
+ use std::{
2
+ fmt,
3
+ io::{self, BufRead, BufReader, Write},
4
+ path::{Path, PathBuf},
5
+ sync::{
6
+ Arc,
7
+ atomic::{AtomicBool, Ordering},
8
+ },
9
+ thread::{self, JoinHandle},
10
+ time::{Duration, Instant},
11
+ };
12
+
13
+ use interprocess::local_socket::{ListenerNonblockingMode, ListenerOptions, prelude::*};
14
+
15
+ use crate::{
16
+ protocol::{Request, Response},
17
+ registry::Instrument,
18
+ };
19
+
20
+ /// Chemin du socket Unix ou nom de named pipe, lu par l'exemple et par
21
+ /// l'application hôte.
22
+ pub const SOCKET_PATH_ENV: &str = "APP_SOCKET";
23
+
24
+ /// Un socket Unix tient dans environ 103 octets de chemin, en comptant le zéro
25
+ /// final. On garde une marge explicite à 100 octets et on refuse au-delà avec
26
+ /// un message qui nomme la limite, plutôt que de laisser l'OS tronquer le nom.
27
+ pub const MAX_SOCKET_PATH_BYTES: usize = 100;
28
+
29
+ const ACCEPT_POLL: Duration = Duration::from_millis(10);
30
+ /// Un client qui se connecte puis se tait est libéré : le serveur ne peut pas
31
+ /// être immobilisé par une connexion inactive.
32
+ const CONNECTION_IDLE_TIMEOUT: Duration = Duration::from_millis(1_000);
33
+
34
+ #[derive(Debug, Clone, PartialEq, Eq)]
35
+ pub enum PathError {
36
+ Empty,
37
+ TooLong { bytes: usize, limit: usize },
38
+ }
39
+
40
+ impl fmt::Display for PathError {
41
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
42
+ match self {
43
+ Self::Empty => write!(formatter, "le chemin du socket est vide"),
44
+ Self::TooLong { bytes, limit } => write!(
45
+ formatter,
46
+ "chemin de socket trop long: {bytes} octets (limite {limit})"
47
+ ),
48
+ }
49
+ }
50
+ }
51
+
52
+ impl std::error::Error for PathError {}
53
+
54
+ /// Vérifie les deux limites que l'OS ne signale pas clairement : un chemin vide
55
+ /// et un chemin au-delà de la taille d'un `sockaddr_un`.
56
+ pub fn validate_socket_path(path: &Path) -> Result<(), PathError> {
57
+ if path.as_os_str().is_empty() {
58
+ return Err(PathError::Empty);
59
+ }
60
+ let bytes = path.as_os_str().as_encoded_bytes().len();
61
+ if bytes > MAX_SOCKET_PATH_BYTES {
62
+ return Err(PathError::TooLong {
63
+ bytes,
64
+ limit: MAX_SOCKET_PATH_BYTES,
65
+ });
66
+ }
67
+ Ok(())
68
+ }
69
+
70
+ #[cfg(unix)]
71
+ pub(crate) fn socket_name(path: &Path) -> io::Result<interprocess::local_socket::Name<'_>> {
72
+ path.to_fs_name::<interprocess::local_socket::GenericFilePath>()
73
+ }
74
+
75
+ /// Sur Windows, un « chemin » de socket est un nom de named pipe : l'API
76
+ /// namespaced préfixe `\\.\pipe\` et n'utilise que le dernier composant. Le
77
+ /// client et le serveur appliquent la même règle, donc ils se retrouvent.
78
+ #[cfg(windows)]
79
+ pub(crate) fn socket_name(path: &Path) -> io::Result<interprocess::local_socket::Name<'_>> {
80
+ let name = path
81
+ .file_name()
82
+ .filter(|name| !name.is_empty())
83
+ .unwrap_or_else(|| path.as_os_str());
84
+ name.to_ns_name::<interprocess::local_socket::GenericNamespaced>()
85
+ }
86
+
87
+ #[derive(Debug)]
88
+ pub enum ServerError {
89
+ Path(PathError),
90
+ Name { path: PathBuf, source: io::Error },
91
+ Bind { path: PathBuf, source: io::Error },
92
+ Permissions { path: PathBuf, source: io::Error },
93
+ Spawn { source: io::Error },
94
+ }
95
+
96
+ impl fmt::Display for ServerError {
97
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
98
+ match self {
99
+ Self::Path(error) => error.fmt(formatter),
100
+ Self::Name { path, source } => write!(
101
+ formatter,
102
+ "nom de socket invalide pour « {} »: {source}",
103
+ path.display()
104
+ ),
105
+ Self::Bind { path, source } => write!(
106
+ formatter,
107
+ "liaison du socket « {} » impossible: {source}",
108
+ path.display()
109
+ ),
110
+ Self::Permissions { path, source } => write!(
111
+ formatter,
112
+ "chmod 0600 sur « {} » impossible: {source}",
113
+ path.display()
114
+ ),
115
+ Self::Spawn { source } => {
116
+ write!(
117
+ formatter,
118
+ "démarrage du thread serveur impossible: {source}"
119
+ )
120
+ }
121
+ }
122
+ }
123
+ }
124
+
125
+ impl std::error::Error for ServerError {
126
+ fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
127
+ match self {
128
+ Self::Path(error) => Some(error),
129
+ Self::Name { source, .. }
130
+ | Self::Bind { source, .. }
131
+ | Self::Permissions { source, .. }
132
+ | Self::Spawn { source } => Some(source),
133
+ }
134
+ }
135
+ }
136
+
137
+ /// Serveur possédé : le socket est lié avant le retour de `start`, et le thread
138
+ /// d'acceptation s'arrête avec `shutdown` ou avec le `Drop`.
139
+ pub struct Server {
140
+ path: PathBuf,
141
+ shutdown: Arc<AtomicBool>,
142
+ thread: Option<JoinHandle<()>>,
143
+ }
144
+
145
+ impl Server {
146
+ pub fn start(instrument: Instrument, path: impl Into<PathBuf>) -> Result<Self, ServerError> {
147
+ let path = path.into();
148
+ validate_socket_path(&path).map_err(ServerError::Path)?;
149
+
150
+ let name = socket_name(&path).map_err(|source| ServerError::Name {
151
+ path: path.clone(),
152
+ source,
153
+ })?;
154
+ let listener = ListenerOptions::new()
155
+ .name(name)
156
+ .nonblocking(ListenerNonblockingMode::Accept)
157
+ .create_sync()
158
+ .map_err(|source| ServerError::Bind {
159
+ path: path.clone(),
160
+ source,
161
+ })?;
162
+
163
+ #[cfg(unix)]
164
+ set_socket_permissions(&path)?;
165
+
166
+ let shutdown = Arc::new(AtomicBool::new(false));
167
+ let flag = Arc::clone(&shutdown);
168
+ let instrument = Arc::new(instrument);
169
+ let thread = thread::Builder::new()
170
+ .name("instrument-server".to_owned())
171
+ .spawn(move || accept_loop(&listener, &instrument, &flag))
172
+ .map_err(|source| ServerError::Spawn { source })?;
173
+
174
+ Ok(Self {
175
+ path,
176
+ shutdown,
177
+ thread: Some(thread),
178
+ })
179
+ }
180
+
181
+ pub fn path(&self) -> &Path {
182
+ &self.path
183
+ }
184
+
185
+ /// Arrête l'acceptation de nouvelles connexions et attend la fin du thread.
186
+ /// La connexion en cours est libérée par son propre timeout.
187
+ pub fn shutdown(&mut self) {
188
+ self.shutdown.store(true, Ordering::Release);
189
+ if let Some(thread) = self.thread.take()
190
+ && thread.join().is_err()
191
+ {
192
+ tracing::error!("thread serveur terminé sur un panic");
193
+ }
194
+ }
195
+
196
+ /// Attend la fin du serveur. Utilisé par un binaire qui sert jusqu'à son
197
+ /// arrêt ; une interface graphique préfère `shutdown` depuis son thread.
198
+ pub fn wait(mut self) {
199
+ if let Some(thread) = self.thread.take()
200
+ && thread.join().is_err()
201
+ {
202
+ tracing::error!("thread serveur terminé sur un panic");
203
+ }
204
+ }
205
+ }
206
+
207
+ impl Drop for Server {
208
+ fn drop(&mut self) {
209
+ self.shutdown();
210
+ }
211
+ }
212
+
213
+ #[cfg(unix)]
214
+ fn set_socket_permissions(path: &Path) -> Result<(), ServerError> {
215
+ use std::os::unix::fs::PermissionsExt;
216
+
217
+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).map_err(|source| {
218
+ ServerError::Permissions {
219
+ path: path.to_path_buf(),
220
+ source,
221
+ }
222
+ })
223
+ }
224
+
225
+ /// Ce qu'une erreur d'acceptation signifie pour la boucle : une file vide se
226
+ /// repolle, toute autre erreur arrête le serveur. La décision est une fonction
227
+ /// pure, pour qu'un test la vérifie sans socket ni horloge.
228
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
229
+ enum AcceptAction {
230
+ Wait,
231
+ Stop,
232
+ }
233
+
234
+ fn accept_action(kind: io::ErrorKind) -> AcceptAction {
235
+ if kind == io::ErrorKind::WouldBlock {
236
+ AcceptAction::Wait
237
+ } else {
238
+ AcceptAction::Stop
239
+ }
240
+ }
241
+
242
+ // Les connexions sont traitées l'une après l'autre : c'est un canal de
243
+ // diagnostic, pas un serveur généraliste, et l'inactivité d'un client est
244
+ // bornée par `CONNECTION_IDLE_TIMEOUT`.
245
+ fn accept_loop(listener: &LocalSocketListener, instrument: &Instrument, shutdown: &AtomicBool) {
246
+ while !shutdown.load(Ordering::Acquire) {
247
+ match listener.accept() {
248
+ Ok(stream) => {
249
+ if let Err(error) = serve_connection(stream, instrument) {
250
+ tracing::warn!(%error, "connexion interrompue");
251
+ }
252
+ }
253
+ Err(error) => match accept_action(error.kind()) {
254
+ AcceptAction::Wait => thread::sleep(ACCEPT_POLL),
255
+ AcceptAction::Stop => {
256
+ tracing::error!(%error, "accept impossible, serveur arrêté");
257
+ break;
258
+ }
259
+ },
260
+ }
261
+ }
262
+ }
263
+
264
+ fn serve_connection(stream: LocalSocketStream, instrument: &Instrument) -> io::Result<()> {
265
+ // Le listener est en accept non bloquant. Sur macOS, le socket accepté
266
+ // hérite de O_NONBLOCK (contrairement à Linux): on le remet explicitement
267
+ // en bloquant pour que les timeouts de lecture soient honorés.
268
+ stream.set_nonblocking(false)?;
269
+ stream.set_recv_timeout(Some(CONNECTION_IDLE_TIMEOUT))?;
270
+ stream.set_send_timeout(Some(CONNECTION_IDLE_TIMEOUT))?;
271
+ let mut stream = BufReader::new(stream);
272
+
273
+ loop {
274
+ let mut line = String::new();
275
+ match stream.read_line(&mut line) {
276
+ Ok(0) => return Ok(()),
277
+ Ok(_) => {}
278
+ Err(error) => return on_read_error(error),
279
+ }
280
+
281
+ let request = match serde_json::from_str::<Request>(&line) {
282
+ Ok(request) => request,
283
+ Err(error) => {
284
+ let response = Response::failure(format!("requête JSON invalide: {error}"));
285
+ write_response(&mut stream, &response)?;
286
+ continue;
287
+ }
288
+ };
289
+
290
+ let started = Instant::now();
291
+ let response = match instrument.invoke(&request.command, request.params) {
292
+ Ok(data) => Response::success(data),
293
+ Err(message) => Response::failure(message),
294
+ };
295
+ tracing::info!(
296
+ command = %request.command,
297
+ ok = response.ok,
298
+ elapsed_ms = started.elapsed().as_millis() as u64,
299
+ "commande traitée"
300
+ );
301
+ write_response(&mut stream, &response)?;
302
+ }
303
+ }
304
+
305
+ fn write_response(
306
+ stream: &mut BufReader<LocalSocketStream>,
307
+ response: &Response,
308
+ ) -> io::Result<()> {
309
+ let body = serde_json::to_string(response).map_err(io::Error::other)?;
310
+ let inner = stream.get_mut();
311
+ inner.write_all(body.as_bytes())?;
312
+ inner.write_all(b"\n")?;
313
+ inner.flush()
314
+ }
315
+
316
+ fn is_timeout(error: &io::Error) -> bool {
317
+ matches!(
318
+ error.kind(),
319
+ io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut
320
+ )
321
+ }
322
+
323
+ /// Une lecture qui expire ferme la connexion sans bruit : le client s'est tu et
324
+ /// son inactivité est déjà bornée. Toute autre erreur de transport remonte, pour
325
+ /// être journalisée par la boucle d'acceptation.
326
+ fn on_read_error(error: io::Error) -> io::Result<()> {
327
+ if is_timeout(&error) {
328
+ Ok(())
329
+ } else {
330
+ Err(error)
331
+ }
332
+ }
333
+
334
+ #[cfg(test)]
335
+ mod tests {
336
+ use super::*;
337
+
338
+ #[test]
339
+ fn une_file_vide_se_polle_et_une_erreur_arrete_le_serveur() {
340
+ assert_eq!(accept_action(io::ErrorKind::WouldBlock), AcceptAction::Wait);
341
+ assert_eq!(
342
+ accept_action(io::ErrorKind::ConnectionReset),
343
+ AcceptAction::Stop
344
+ );
345
+ assert_eq!(
346
+ accept_action(io::ErrorKind::PermissionDenied),
347
+ AcceptAction::Stop
348
+ );
349
+ }
350
+
351
+ #[test]
352
+ fn une_erreur_de_delai_ferme_la_connexion() {
353
+ assert!(on_read_error(io::Error::from(io::ErrorKind::WouldBlock)).is_ok());
354
+ assert!(on_read_error(io::Error::from(io::ErrorKind::TimedOut)).is_ok());
355
+ }
356
+
357
+ #[test]
358
+ fn une_erreur_de_transport_remonte() {
359
+ let error = on_read_error(io::Error::from(io::ErrorKind::ConnectionReset))
360
+ .expect_err("une erreur de transport ne doit pas être avalée");
361
+ assert_eq!(error.kind(), io::ErrorKind::ConnectionReset);
362
+ }
363
+ }
@@ -0,0 +1,60 @@
1
+ mod support;
2
+
3
+ use std::{fs, time::Duration};
4
+
5
+ use instrument::{Client, Instrument, Server, logging};
6
+ use serde_json::{Value, json};
7
+ use support::TempDir;
8
+ use tracing_subscriber::filter::LevelFilter;
9
+
10
+ #[test]
11
+ fn chaque_commande_ecrit_une_ligne_json_dans_app_log() {
12
+ let temp = TempDir::new("in-log").expect("répertoire temporaire");
13
+ let socket = temp.socket();
14
+ let log_path = temp.path().join("app.log");
15
+
16
+ let guard = logging::init(&log_path, LevelFilter::INFO).expect("journalisation");
17
+
18
+ let mut instrument = Instrument::new();
19
+ instrument
20
+ .command("echo", |params| Ok(json!({ "echo": params })))
21
+ .expect("enregistrement de echo");
22
+ let mut server = Server::start(instrument, &socket).expect("démarrage du serveur");
23
+
24
+ let mut client = Client::connect(&socket, Duration::from_secs(1)).expect("connexion");
25
+ client.call("state", Value::Null).expect("état");
26
+ client
27
+ .call("action", json!({ "key": "a", "value": 1 }))
28
+ .expect("action");
29
+ client.call("echo", json!({ "x": 1 })).expect("echo");
30
+
31
+ drop(client);
32
+ server.shutdown();
33
+ // Déposer la garde vide la file d'écriture avant de lire le fichier.
34
+ drop(guard);
35
+
36
+ let content = fs::read_to_string(&log_path).expect("lecture du fichier de log");
37
+ let mut commands = Vec::new();
38
+ for line in content.lines() {
39
+ let value: Value = serde_json::from_str(line).expect("chaque ligne est un objet JSON");
40
+ let fields = value
41
+ .get("fields")
42
+ .expect("ligne JSON avec un objet 'fields'");
43
+ let command = fields
44
+ .get("command")
45
+ .and_then(Value::as_str)
46
+ .unwrap_or_else(|| panic!("ligne sans champ 'command': {line}"));
47
+ assert_eq!(
48
+ fields.get("ok").and_then(Value::as_bool),
49
+ Some(true),
50
+ "commande non marquée ok: {line}"
51
+ );
52
+ commands.push(command.to_owned());
53
+ }
54
+
55
+ assert_eq!(
56
+ commands,
57
+ ["state", "action", "echo"],
58
+ "une ligne par commande, dans l'ordre: {content}"
59
+ );
60
+ }
@@ -0,0 +1,167 @@
1
+ //! Les erreurs publiques expliquent leur cause : un message vide ou une chaîne
2
+ //! de cause absente rendent un refus indébogable pour l'appelant.
3
+
4
+ use std::{error::Error, io, path::PathBuf};
5
+
6
+ use instrument::{
7
+ ClientError, Instrument, RegistryError, ServerError, logging::LoggingError, server::PathError,
8
+ };
9
+ use serde_json::Value;
10
+
11
+ #[test]
12
+ fn les_messages_du_client_nomment_la_cause() {
13
+ let cases = [
14
+ (ClientError::Timeout, "délai"),
15
+ (
16
+ ClientError::Remote("refus explicite".to_owned()),
17
+ "refus explicite",
18
+ ),
19
+ (ClientError::Protocol("json cassé".to_owned()), "json cassé"),
20
+ (
21
+ ClientError::Connect(io::Error::other("socket absent")),
22
+ "socket absent",
23
+ ),
24
+ (
25
+ ClientError::Io(io::Error::other("tuyau cassé")),
26
+ "tuyau cassé",
27
+ ),
28
+ (ClientError::Path(PathError::Empty), "vide"),
29
+ ];
30
+
31
+ for (error, expected) in cases {
32
+ let message = error.to_string();
33
+ assert!(
34
+ message.contains(expected),
35
+ "message « {message} » sans « {expected} »"
36
+ );
37
+ }
38
+ }
39
+
40
+ #[test]
41
+ fn une_erreur_client_expose_sa_cause() {
42
+ assert!(
43
+ ClientError::Connect(io::Error::other("socket absent"))
44
+ .source()
45
+ .is_some(),
46
+ "une erreur de connexion doit garder sa cause"
47
+ );
48
+ assert!(
49
+ ClientError::Io(io::Error::other("tuyau cassé"))
50
+ .source()
51
+ .is_some(),
52
+ "une erreur d'échange doit garder sa cause"
53
+ );
54
+ assert!(
55
+ ClientError::Path(PathError::Empty).source().is_some(),
56
+ "un chemin refusé doit garder sa cause"
57
+ );
58
+ assert!(
59
+ ClientError::Timeout.source().is_none(),
60
+ "un délai n'a pas de cause système"
61
+ );
62
+ }
63
+
64
+ #[test]
65
+ fn les_messages_de_journalisation_nomment_la_cause() {
66
+ let cases = [
67
+ (LoggingError::MissingPath, "APP_LOG"),
68
+ (
69
+ LoggingError::Open {
70
+ path: PathBuf::from("/tmp/absent/app.log"),
71
+ source: io::Error::other("refus"),
72
+ },
73
+ "/tmp/absent/app.log",
74
+ ),
75
+ (LoggingError::InvalidLevel("bavard".to_owned()), "bavard"),
76
+ (
77
+ LoggingError::Install("abonné déjà posé".to_owned()),
78
+ "abonné déjà posé",
79
+ ),
80
+ ];
81
+
82
+ for (error, expected) in cases {
83
+ let message = error.to_string();
84
+ assert!(
85
+ message.contains(expected),
86
+ "message « {message} » sans « {expected} »"
87
+ );
88
+ }
89
+ }
90
+
91
+ #[test]
92
+ fn une_erreur_de_journalisation_expose_sa_cause() {
93
+ let open = LoggingError::Open {
94
+ path: PathBuf::from("/tmp/absent/app.log"),
95
+ source: io::Error::other("refus"),
96
+ };
97
+ assert!(
98
+ open.source().is_some(),
99
+ "une ouverture impossible doit garder sa cause"
100
+ );
101
+ assert!(
102
+ LoggingError::MissingPath.source().is_none(),
103
+ "une variable absente n'a pas de cause système"
104
+ );
105
+ }
106
+
107
+ #[test]
108
+ fn les_refus_d_enregistrement_nomment_la_commande() {
109
+ let mut instrument = Instrument::new();
110
+
111
+ match instrument.command("", |_| Ok(Value::Null)) {
112
+ Err(error) => {
113
+ assert_eq!(error, RegistryError::EmptyName);
114
+ assert!(error.to_string().contains("vide"), "message: {error}");
115
+ }
116
+ Ok(_) => panic!("un nom vide doit être refusé"),
117
+ }
118
+
119
+ match instrument.command("list", |_| Ok(Value::Null)) {
120
+ Err(error) => {
121
+ assert_eq!(error, RegistryError::Reserved("list".to_owned()));
122
+ assert!(error.to_string().contains("list"), "message: {error}");
123
+ }
124
+ Ok(_) => panic!("un nom du protocole doit être refusé"),
125
+ }
126
+
127
+ instrument
128
+ .command("echo", |_| Ok(Value::Null))
129
+ .expect("premier enregistrement de echo");
130
+
131
+ match instrument.command("echo", |_| Ok(Value::Null)) {
132
+ Err(error) => {
133
+ assert_eq!(error, RegistryError::Duplicate("echo".to_owned()));
134
+ assert!(error.to_string().contains("echo"), "message: {error}");
135
+ }
136
+ Ok(_) => panic!("un doublon doit être refusé"),
137
+ }
138
+ }
139
+
140
+ #[test]
141
+ fn un_refus_de_serveur_expose_sa_cause() {
142
+ let bind = ServerError::Bind {
143
+ path: PathBuf::from("/tmp/in-bind/s"),
144
+ source: io::Error::other("adresse déjà utilisée"),
145
+ };
146
+ assert!(
147
+ bind.source().is_some(),
148
+ "une liaison impossible doit garder sa cause"
149
+ );
150
+ assert!(
151
+ bind.to_string().contains("/tmp/in-bind/s"),
152
+ "message: {bind}"
153
+ );
154
+
155
+ let spawn = ServerError::Spawn {
156
+ source: io::Error::other("thread refusé"),
157
+ };
158
+ assert!(
159
+ spawn.source().is_some(),
160
+ "un démarrage impossible doit garder sa cause"
161
+ );
162
+
163
+ assert!(
164
+ ServerError::Path(PathError::Empty).source().is_some(),
165
+ "un chemin refusé doit garder sa cause"
166
+ );
167
+ }