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
//! Direct-daemon identity semantics for an application-owned endpoint.
//!
//! The implementation delegates frozen v1 framing, probe validation, and
//! sidecar encoding to the private process substrate. This module owns the
//! public vocabulary and deliberately does not choose endpoint names, product
//! protocol identifiers, or daemon lifecycle policy.
use std::fmt;
use std::path::Path;
use running_process::backend_identity as backend;
/// An application-selected daemon endpoint.
///
/// Both strings are retained verbatim. In particular, this facade never
/// converts a namespaced address into a filesystem path (or vice versa).
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct DaemonEndpoint {
namespace: String,
address: String,
}
impl DaemonEndpoint {
/// Record an endpoint chosen by the application.
pub fn new(namespace: impl Into<String>, address: impl Into<String>) -> Self {
Self {
namespace: namespace.into(),
address: address.into(),
}
}
/// Return the application-owned namespace verbatim.
pub fn namespace(&self) -> &str {
&self.namespace
}
/// Return the application-owned address verbatim.
pub fn address(&self) -> &str {
&self.address
}
}
/// A normalized identity for a daemon already bound to an endpoint.
///
/// It is suitable for durable sidecars and for proving that an endpoint still
/// serves precisely this process. The cryptographic fields have fixed width
/// so callers cannot accidentally accept a truncated digest.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DaemonIdentity {
inner: backend::DaemonProcess,
}
/// Digest material captured for a newly constructed daemon identity.
///
/// The default remains [`Self::LegacyCompatible`]. Applications with an
/// established zero-filled legacy probe field can choose [`Self::Blake3Only`]
/// to preserve that fixed wire contract and avoid a second executable read.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum DaemonIdentityHashPolicy {
/// Compute BLAKE3 and the historical SHA-256 compatibility digest.
#[default]
LegacyCompatible,
/// Compute BLAKE3 only and retain a zero-filled legacy digest.
Blake3Only,
}
impl DaemonIdentityHashPolicy {
fn into_backend(self) -> backend::DaemonIdentityHashPolicy {
match self {
Self::LegacyCompatible => backend::DaemonIdentityHashPolicy::LegacyCompatible,
Self::Blake3Only => backend::DaemonIdentityHashPolicy::Blake3Only,
}
}
}
impl DaemonIdentity {
/// Construct the identity of this process after its final endpoint has
/// been selected.
pub fn current_process(
endpoint: DaemonEndpoint,
idle_timeout_secs: Option<u32>,
) -> Result<Self, DaemonIdentityError> {
Self::current_process_with_hash_policy(
endpoint,
idle_timeout_secs,
DaemonIdentityHashPolicy::LegacyCompatible,
)
}
/// Construct the identity of this process with an explicit legacy-digest
/// policy.
pub fn current_process_with_hash_policy(
endpoint: DaemonEndpoint,
idle_timeout_secs: Option<u32>,
hash_policy: DaemonIdentityHashPolicy,
) -> Result<Self, DaemonIdentityError> {
backend::DaemonProcess::current_process_with_hash_policy(
endpoint.into_backend(),
idle_timeout_secs,
hash_policy.into_backend(),
)
.map(Self::from_backend)
.map_err(DaemonIdentityError::current_process)
}
/// Operating-system process identifier captured in this identity.
pub fn pid(&self) -> u32 {
self.inner.pid
}
/// Executable path captured in this identity.
pub fn executable_path(&self) -> &Path {
&self.inner.exe_path
}
/// BLAKE3 digest of the executable captured in this identity.
pub fn blake3_digest(&self) -> &[u8; 32] {
&self.inner.exe_hash
}
/// SHA-256 digest retained for compatibility with stable v1 probes.
pub fn legacy_sha256_digest(&self) -> &[u8; 32] {
&self.inner.legacy_exe_sha256
}
/// Host boot identity captured when the daemon started.
pub fn boot_id(&self) -> &str {
&self.inner.boot_id
}
/// Endpoint supplied when this identity was constructed or decoded.
pub fn endpoint(&self) -> DaemonEndpoint {
DaemonEndpoint::from_backend(&self.inner.ipc_endpoint)
}
/// Unix timestamp, in milliseconds, captured when the daemon started.
pub fn started_at_unix_ms(&self) -> u64 {
self.inner.started_at_unix_ms
}
/// Idle timeout advertised by the daemon, if it has one.
pub fn idle_timeout_secs(&self) -> Option<u32> {
self.inner.idle_timeout_secs
}
/// Persist this identity atomically as an adjacent JSON sidecar.
///
/// JSON is only the human-facing durable sidecar format. It is not a
/// daemon control-plane or IPC fallback.
pub fn write_sidecar(&self, path: impl AsRef<Path>) -> std::io::Result<()> {
backend::write_daemon_identity_file(path.as_ref(), &self.inner)
}
/// Read an identity sidecar tolerantly.
///
/// Missing or malformed sidecars return `None`, allowing callers to fall
/// back to their normal application-owned discovery path.
pub fn read_sidecar(path: impl AsRef<Path>) -> Option<Self> {
backend::read_daemon_identity_file(path.as_ref()).map(Self::from_backend)
}
/// Read an identity sidecar while retaining I/O and decoding failures.
pub fn try_read_sidecar(path: impl AsRef<Path>) -> std::io::Result<Option<Self>> {
backend::try_read_daemon_identity_file(path.as_ref())
.map(|identity| identity.map(Self::from_backend))
}
/// Remove an identity sidecar as a best-effort clean-shutdown operation.
pub fn remove_sidecar(path: impl AsRef<Path>) {
backend::remove_daemon_identity_file(path.as_ref());
}
/// Prove, without occupying an async worker, that this identity still
/// serves its recorded endpoint.
///
/// A successful probe performs the substrate's single existing endpoint
/// connection and nonce round trip. It does not construct a client,
/// derive another endpoint, or add a product-protocol exchange.
pub async fn probe_same_endpoint(&self) -> ProbeSameEndpoint {
let endpoint = self.inner.ipc_endpoint.clone();
let expected = self.inner.clone();
match crate::async_engine::launch_blocking(move || {
backend::BackendHandle::probe(&endpoint, &expected).is_some()
})
.await
{
Ok(true) => ProbeSameEndpoint::Current,
Ok(false) | Err(_) => ProbeSameEndpoint::NotCurrent,
}
}
fn from_backend(inner: backend::DaemonProcess) -> Self {
Self { inner }
}
}
/// Failure while collecting the identity of the current process.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DaemonIdentityError {
detail: String,
}
impl DaemonIdentityError {
fn current_process(error: backend::IdentityError) -> Self {
Self {
detail: error.to_string(),
}
}
}
impl fmt::Display for DaemonIdentityError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.detail)
}
}
impl std::error::Error for DaemonIdentityError {}
/// Result of an endpoint identity probe.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ProbeSameEndpoint {
/// The endpoint accepted the frozen nonce proof and returned this identity.
Current,
/// The endpoint was unavailable, stale, or did not prove this identity.
NotCurrent,
}
/// Application classification of the leading bytes of its legacy wire.
///
/// The caller provides this before the facade parses the v1 envelope, so an
/// application legacy header beginning with `0x01` remains application-owned.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LegacyPrefix {
/// The bytes belong to the application's legacy wire.
Legacy,
/// The bytes do not belong to the application's legacy wire.
NotLegacy,
/// More bytes are required before the application can decide.
NeedMoreBytes,
}
/// A facade-owned responder for identity probes and product payload envelopes.
///
/// It is sans-I/O: an application's accept loop retains its stream and buffer,
/// calls [`Self::poll`], writes a returned probe reply verbatim, and advances
/// its buffer only by the returned `consumed` count.
#[derive(Clone, Debug)]
pub struct ProbeResponder {
daemon: backend::DaemonProcess,
served_payload_protocols: Vec<u32>,
}
impl ProbeResponder {
/// Create a responder for an existing daemon endpoint.
///
/// Product protocol identifiers are supplied by the application; this
/// facade neither defines nor negotiates them.
pub fn new(
daemon: DaemonIdentity,
served_payload_protocols: impl IntoIterator<Item = u32>,
) -> Self {
Self {
daemon: daemon.inner,
served_payload_protocols: served_payload_protocols.into_iter().collect(),
}
}
/// Return a copy of the identity this responder proves.
pub fn identity(&self) -> DaemonIdentity {
DaemonIdentity::from_backend(self.daemon.clone())
}
/// Classify the front of a buffered application connection.
///
/// The supplied [`LegacyPrefix`] is honored before every v1 frame check,
/// preserving legacy-first behavior and the exact consumed-byte contract.
pub fn poll(
&self,
buffered: &[u8],
legacy_prefix: LegacyPrefix,
) -> Result<ProbeMuxResult, DaemonMuxError> {
let mux = backend::BackendEndpointMux::new(
self.daemon.clone(),
&self.served_payload_protocols,
move |_| legacy_prefix.into_backend(),
);
match mux.poll(buffered).map_err(DaemonMuxError::from_backend)? {
backend::MuxPoll::NeedMoreBytes => Ok(ProbeMuxResult::NeedMoreBytes),
backend::MuxPoll::Legacy => Ok(ProbeMuxResult::Legacy),
backend::MuxPoll::ProbeAnswered { reply, consumed } => {
Ok(ProbeMuxResult::ProbeReply { reply, consumed })
}
backend::MuxPoll::Payload { frame, consumed } => Ok(ProbeMuxResult::ProductFrame {
frame: ProductFrame::from_backend(frame),
consumed,
}),
}
}
}
/// A product-owned v1 envelope delivered by [`ProbeResponder`].
///
/// `kind` and `payload_encoding` intentionally remain their raw numeric
/// discriminants. This preserves unknown future values for the application
/// instead of normalizing them through an implementation enum.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProductFrame {
/// Frozen envelope version carried by the decoded frame.
pub envelope_version: u32,
/// Raw frame-kind discriminant.
pub kind: i32,
/// Application-owned product payload protocol identifier.
pub payload_protocol: u32,
/// Opaque product request or response bytes.
pub payload: Vec<u8>,
/// Correlation identifier preserved from the incoming frame.
pub request_id: u64,
/// Raw payload-encoding discriminant.
pub payload_encoding: i32,
/// Optional absolute deadline value preserved from the incoming frame.
pub deadline_unix_ms: u64,
/// W3C trace parent preserved from the incoming frame.
pub traceparent: String,
/// W3C trace state preserved from the incoming frame.
pub tracestate: String,
}
impl ProductFrame {
fn from_backend(frame: backend::Frame) -> Self {
Self {
envelope_version: frame.envelope_version,
kind: frame.kind,
payload_protocol: frame.payload_protocol,
payload: frame.payload,
request_id: frame.request_id,
payload_encoding: frame.payload_encoding,
deadline_unix_ms: frame.deadline_unix_ms,
traceparent: frame.traceparent,
tracestate: frame.tracestate,
}
}
}
/// Verdict returned by [`ProbeResponder::poll`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ProbeMuxResult {
/// The buffer cannot yet be classified or decoded. Consume no bytes.
NeedMoreBytes,
/// The buffer belongs to application legacy wire. Consume no bytes.
Legacy,
/// A frozen v1 nonce probe was answered.
ProbeReply {
/// Complete v1 wire bytes to write back verbatim.
reply: Vec<u8>,
/// Count of request bytes to consume from the input buffer.
consumed: usize,
},
/// A complete application product frame was decoded.
ProductFrame {
/// Product fields preserved without protocol interpretation.
frame: ProductFrame,
/// Count of frame bytes to consume from the input buffer.
consumed: usize,
},
}
/// Connection-fatal mux failures represented without backend error types.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum DaemonMuxError {
/// The leading framing byte is not the frozen v1 version.
#[error("unsupported daemon frame version {received}; expected {expected}")]
UnsupportedFrameVersion {
/// Byte received at the start of the frame.
received: u8,
/// Frozen v1 framing byte expected by this facade.
expected: u8,
},
/// The claimed v1 frame body exceeds the 16 MiB maximum.
#[error("daemon frame body {body_length} exceeds maximum {maximum}")]
FrameTooLarge {
/// Body length declared in the v1 little-endian header.
body_length: usize,
/// Maximum accepted body length.
maximum: usize,
},
/// The frame body is not a valid v1 envelope.
#[error("malformed daemon frame")]
MalformedFrame,
/// A reserved identity probe did not meet the frozen probe contract.
#[error("malformed daemon identity probe")]
MalformedProbe,
/// A first-party control protocol reached a direct daemon endpoint.
#[error("unexpected first-party payload protocol {payload_protocol:#06X}")]
UnexpectedFirstPartyPayload {
/// Reserved protocol identifier received on this endpoint.
payload_protocol: u32,
},
/// The endpoint has no handler for this product protocol identifier.
#[error("unserved product payload protocol {payload_protocol:#06X}")]
UnservedProductProtocol {
/// Application-owned protocol identifier with no configured handler.
payload_protocol: u32,
},
}
impl DaemonMuxError {
fn from_backend(error: backend::MuxError) -> Self {
match error {
backend::MuxError::Framing(backend::FramingError::UnsupportedFramingVersion {
got,
expected,
}) => Self::UnsupportedFrameVersion {
received: got,
expected,
},
backend::MuxError::Framing(backend::FramingError::FrameTooLarge {
body_length,
cap,
}) => Self::FrameTooLarge {
body_length,
maximum: cap,
},
backend::MuxError::Framing(_) => Self::MalformedFrame,
backend::MuxError::MalformedProbe(_) => Self::MalformedProbe,
backend::MuxError::UnexpectedFirstPartyFrame { payload_protocol } => {
Self::UnexpectedFirstPartyPayload { payload_protocol }
}
backend::MuxError::UnservedPayloadProtocol { payload_protocol } => {
Self::UnservedProductProtocol { payload_protocol }
}
}
}
}
impl DaemonEndpoint {
fn from_backend(endpoint: &backend::Endpoint) -> Self {
Self {
namespace: endpoint.namespace_id.clone(),
address: endpoint.path.clone(),
}
}
fn into_backend(self) -> backend::Endpoint {
backend::Endpoint {
namespace_id: self.namespace,
path: self.address,
}
}
}
impl LegacyPrefix {
fn into_backend(self) -> backend::LegacyClassification {
match self {
Self::Legacy => backend::LegacyClassification::Legacy,
Self::NotLegacy => backend::LegacyClassification::NotLegacy,
Self::NeedMoreBytes => backend::LegacyClassification::NeedMoreBytes,
}
}
}