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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
use super::*;
/// Human-readable diagnostic formatting for `DynamicReleaseError`.
impl fmt::Display for DynamicReleaseError {
/// Formats `self` into a human-readable diagnostic message.
///
/// # Arguments
///
/// - `&mut Formatter<'_>` - Destination text formatter.
///
/// # Returns
///
/// - `fmt::Result` - Formatting outcome.
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidSignature(msg) => write!(f, "invalid release signature: {msg}"),
Self::AbiIncompatible {
host_abi,
min_abi,
max_abi,
} => write!(
f,
"incompatible host ABI {host_abi} (required {min_abi}..={max_abi})"
),
Self::UnsupportedDeliveryMode { allowed, incoming } => write!(
f,
"delivery mode {incoming:?} is not permitted under policy {allowed:?}"
),
Self::MissingCapability(cap) => write!(f, "missing required host capability: {cap}"),
Self::BrokenDependencyClosure(msg) => {
write!(f, "broken release dependency closure: {msg}")
}
Self::HashMismatch { expected, actual } => {
write!(f, "sha256 mismatch: expected {expected}, actual {actual}")
}
Self::NonMonotonicRelease { current, incoming } => write!(
f,
"{ERR_NON_MONOTONIC_RELEASE}: current={current}, incoming={incoming}"
),
Self::BlobMissing(sha) => write!(f, "content-addressed blob not found: {sha}"),
Self::RouteNotFound(route) => write!(f, "route not declared in manifest: {route}"),
Self::InterfaceMismatch {
expected_interface,
actual_interface,
} => write!(
f,
"component interface mismatch: expected {expected_interface}, actual {actual_interface}"
),
Self::StateMigrationFailed(msg) => write!(f, "state migration failed: {msg}"),
Self::UnsafeSwapPoint(reason) => {
write!(f, "swap deferred at unsafe boundary: {reason}")
}
Self::StateCatchUpConflict {
base_revision,
live_revision,
} => write!(
f,
"state delta catch-up conflict from rev {base_revision} to rev {live_revision}"
),
Self::ProtocolIncompatible(msg) => write!(f, "protocol incompatible: {msg}"),
Self::NetworkError(msg) => write!(f, "update network error: {msg}"),
Self::StorageError(msg) => write!(f, "update storage error: {msg}"),
}
}
}
/// Standard error trait marker for `DynamicReleaseError`.
impl Error for DynamicReleaseError {}
/// Helper methods on `BlobArtifact`.
impl BlobArtifact {
/// Returns the canonical `"<module_id>@<version>"` artifact key.
///
/// # Returns
///
/// - `String` - Artifact lookup key.
#[must_use]
pub fn artifact_key(&self) -> String {
format_artifact_key(self.get_module_id(), self.get_version())
}
/// Configures interface contract metadata and host ABI range on this artifact.
///
/// # Arguments
///
/// - `&str` - Compile-time interface identifier.
/// - `u32` - Interface version number.
/// - `u32` - Local state schema version number.
/// - `u32` - Minimum host ABI version.
/// - `u32` - Maximum host ABI version.
///
/// # Returns
///
/// - `Self` - Updated artifact descriptor.
#[must_use]
pub fn with_contract(
mut self,
interface_id: &str,
interface_version: u32,
state_schema_version: u32,
min_host_abi: u32,
max_host_abi: u32,
) -> Self {
self.set_interface_id(interface_id.to_string())
.set_interface_version(interface_version)
.set_state_schema_version(state_schema_version)
.set_min_host_abi(min_host_abi)
.set_max_host_abi(max_host_abi);
self
}
/// Appends a pinned transitive dependency key (`"module_id@version"`).
///
/// # Arguments
///
/// - `String` - Pinned dependency artifact key.
///
/// # Returns
///
/// - `Self` - Updated artifact descriptor.
#[must_use]
pub fn with_dependency(mut self, dep_key: String) -> Self {
self.get_mut_dependencies().push(dep_key);
self
}
/// Sets the logical entrypoint symbol on this artifact.
///
/// # Arguments
///
/// - `String` - Entrypoint symbol name.
///
/// # Returns
///
/// - `Self` - Updated artifact descriptor.
#[must_use]
pub fn with_entrypoint(mut self, entrypoint: String) -> Self {
self.set_entrypoint(entrypoint);
self
}
/// Appends a required host capability string to this artifact.
///
/// # Arguments
///
/// - `String` - Capability identifier.
///
/// # Returns
///
/// - `Self` - Updated artifact descriptor.
#[must_use]
pub fn with_capability(mut self, capability: String) -> Self {
self.get_mut_required_capabilities().push(capability);
self
}
}
/// Builder helpers on `RouteManifest`.
impl RouteManifest {
/// Pins a logical slot key to an exact artifact key (`"module_id@version"`).
///
/// # Arguments
///
/// - `String` - Logical slot identifier.
/// - `String` - Exact pinned artifact key.
///
/// # Returns
///
/// - `Self` - Updated route manifest.
#[must_use]
pub fn with_slot(mut self, slot_key: String, artifact_key: String) -> Self {
let _: Option<String> = self.get_mut_slot_bindings().insert(slot_key, artifact_key);
self
}
/// Populates `transitive_hashes` directly from `artifacts`.
///
/// # Arguments
///
/// - `&BTreeMap<String, BlobArtifact>` - Release artifact table.
///
/// # Returns
///
/// - `Result<&mut Self, DynamicReleaseError>` - Updated route manifest or closure error.
pub fn seal_transitive_hashes(
&mut self,
artifacts: &BTreeMap<String, BlobArtifact>,
) -> Result<&mut Self, DynamicReleaseError> {
let hashes: BTreeSet<String> = compute_route_transitive_hashes(self, artifacts)?;
self.set_transitive_hashes(hashes);
Ok(self)
}
}
/// Signing, verification, closure validation, and diff helpers on `ReleaseManifest`.
impl ReleaseManifest {
/// Returns the optional prior release sequence targeted by a monotonic rollback.
///
/// # Returns
///
/// - `Option<u64>` - Prior release sequence if this release is a rollback.
#[must_use]
pub fn rollback_of_seq(&self) -> Option<u64> {
let Self { rollback_of, .. } = *self;
rollback_of
}
/// Inserts an artifact into the manifest artifact table keyed by `"module_id@version"`.
///
/// # Arguments
///
/// - `BlobArtifact` - Artifact metadata entry.
///
/// # Returns
///
/// - `&mut Self` - Mutable manifest reference for chaining.
pub fn insert_artifact(&mut self, artifact: BlobArtifact) -> &mut Self {
let key: String = artifact.artifact_key();
let _: Option<BlobArtifact> = self.get_mut_artifacts().insert(key, artifact);
self
}
/// Inserts a route manifest after normalizing its route path and computing its transitive hash closure.
///
/// # Arguments
///
/// - `RouteManifest` - Route manifest to seal and register.
///
/// # Returns
///
/// - `Result<&mut Self, DynamicReleaseError>` - Mutable manifest reference or closure error.
pub fn insert_route(
&mut self,
mut route: RouteManifest,
) -> Result<&mut Self, DynamicReleaseError> {
let normalized: String = normalize_dynamic_route(route.get_route());
route.set_route(normalized.clone());
let hashes: BTreeSet<String> =
compute_route_transitive_hashes(&route, self.get_artifacts())?;
route.set_transitive_hashes(hashes);
let _: Option<RouteManifest> = self.get_mut_routes().insert(normalized, route);
Ok(self)
}
/// Produces deterministic canonical JSON bytes over the manifest with `signature` cleared.
///
/// # Returns
///
/// - `Result<Vec<u8>, DynamicReleaseError>` - Canonical UTF-8 JSON bytes for signing and hashing.
pub fn canonical_signing_bytes(&self) -> Result<Vec<u8>, DynamicReleaseError> {
let mut unsigned: Self = self.clone();
unsigned.set_signature(String::new());
match to_string(&unsigned) {
Ok(json) => Ok(json.into_bytes()),
Err(err) => Err(DynamicReleaseError::StorageError(format!(
"{ERR_MANIFEST_SERIALIZE}: {err}"
))),
}
}
/// Computes the SHA-256 hex digest of the signed manifest JSON.
///
/// # Returns
///
/// - `Result<String, DynamicReleaseError>` - 64-character SHA-256 hex digest.
pub fn manifest_sha256(&self) -> Result<String, DynamicReleaseError> {
let json: String = match to_string(self) {
Ok(encoded) => encoded,
Err(err) => {
return Err(DynamicReleaseError::StorageError(format!(
"{ERR_MANIFEST_SERIALIZE}: {err}"
)));
}
};
Ok(sha256_hex(json.as_bytes()))
}
/// Signs the release manifest in place using HMAC-SHA256.
///
/// # Arguments
///
/// - `&[u8]` - Signing secret key bytes.
///
/// # Returns
///
/// - `Result<&mut Self, DynamicReleaseError>` - Signed manifest reference.
pub fn sign(&mut self, signing_key: &[u8]) -> Result<&mut Self, DynamicReleaseError> {
let payload: Vec<u8> = self.canonical_signing_bytes()?;
let sig: String = sign_release_payload(&payload, signing_key);
self.set_signature(sig);
Ok(self)
}
/// Verifies the manifest HMAC-SHA256 signature in constant time against `verify_key`.
///
/// # Arguments
///
/// - `&[u8]` - Trusted verification key bytes.
///
/// # Returns
///
/// - `Result<(), DynamicReleaseError>` - `Ok(())` when authentic, or `InvalidSignature`.
pub fn verify_signature(&self, verify_key: &[u8]) -> Result<(), DynamicReleaseError> {
let payload: Vec<u8> = self.canonical_signing_bytes()?;
if verify_release_signature(&payload, self.get_signature(), verify_key) {
Ok(())
} else {
Err(DynamicReleaseError::InvalidSignature(
ERR_INVALID_SIGNATURE.to_string(),
))
}
}
/// Validates protocol schema, delivery mode, ABI bounds, host capabilities, size ceiling, and full transitive dependency closure.
///
/// # Arguments
///
/// - `u32` - Running host ABI version.
/// - `&[String]` - Capabilities supported by the host runtime.
/// - `DeliveryChannelMode` - Delivery mode permitted by the current distribution channel.
/// - `u64` - Maximum allowed size in bytes for any individual artifact (`0` disables cap).
///
/// # Returns
///
/// - `Result<(), DynamicReleaseError>` - `Ok(())` when the complete graph is valid and compatible.
pub fn validate_for_host(
&self,
host_abi: u32,
host_capabilities: &[String],
allowed_mode: DeliveryChannelMode,
max_artifact_bytes: u64,
) -> Result<(), DynamicReleaseError> {
if self.get_manifest_schema() != DYNAMIC_MANIFEST_SCHEMA_V1 {
return Err(DynamicReleaseError::ProtocolIncompatible(format!(
"unsupported manifest schema v{}",
self.get_manifest_schema()
)));
}
if allowed_mode == DeliveryChannelMode::DeclarativeData
&& self.get_delivery_mode() == DeliveryChannelMode::WasmComponent
{
return Err(DynamicReleaseError::UnsupportedDeliveryMode {
allowed: allowed_mode,
incoming: self.get_delivery_mode(),
});
}
if host_abi < self.get_min_host_abi() || host_abi > self.get_max_host_abi() {
return Err(DynamicReleaseError::AbiIncompatible {
host_abi,
min_abi: self.get_min_host_abi(),
max_abi: self.get_max_host_abi(),
});
}
for cap in self.get_required_capabilities().iter() {
if !host_capabilities.iter().any(|c: &String| c == cap) {
return Err(DynamicReleaseError::MissingCapability(cap.clone()));
}
}
for (key, artifact) in self.get_artifacts().iter() {
if !is_valid_sha256_hex(artifact.get_sha256()) {
return Err(DynamicReleaseError::BrokenDependencyClosure(format!(
"{ERR_INVALID_HASH_FORMAT}: {key}"
)));
}
if max_artifact_bytes > 0 && artifact.get_size_bytes() > max_artifact_bytes {
return Err(DynamicReleaseError::BrokenDependencyClosure(format!(
"{ERR_ARTIFACT_TOO_LARGE}: {key} ({} > {max_artifact_bytes})",
artifact.get_size_bytes()
)));
}
if allowed_mode == DeliveryChannelMode::DeclarativeData
&& artifact.get_kind() == ArtifactKind::WasmComponent
{
return Err(DynamicReleaseError::UnsupportedDeliveryMode {
allowed: allowed_mode,
incoming: DeliveryChannelMode::WasmComponent,
});
}
if artifact.get_min_host_abi() > 0
&& (host_abi < artifact.get_min_host_abi()
|| (artifact.get_max_host_abi() > 0 && host_abi > artifact.get_max_host_abi()))
{
return Err(DynamicReleaseError::AbiIncompatible {
host_abi,
min_abi: artifact.get_min_host_abi(),
max_abi: artifact.get_max_host_abi(),
});
}
for cap in artifact.get_required_capabilities().iter() {
if !host_capabilities.iter().any(|c: &String| c == cap) {
return Err(DynamicReleaseError::MissingCapability(cap.clone()));
}
}
}
for (route_key, route_manifest) in self.get_routes().iter() {
let computed: BTreeSet<String> =
compute_route_transitive_hashes(route_manifest, self.get_artifacts())?;
if route_manifest.get_transitive_hashes() != &computed {
return Err(DynamicReleaseError::BrokenDependencyClosure(format!(
"{ERR_INCOMPLETE_HASH_CLOSURE}: {route_key}"
)));
}
}
Ok(())
}
/// Returns the sorted unique list of SHA-256 digests referenced by this manifest.
///
/// # Returns
///
/// - `BTreeSet<String>` - All artifact SHA-256 digests in this release.
#[must_use]
pub fn all_blob_hashes(&self) -> BTreeSet<String> {
self.get_artifacts()
.values()
.map(|art: &BlobArtifact| art.get_sha256().clone())
.collect()
}
/// Computes the incremental hash diff of blobs absent from `cached_hashes`.
///
/// # Arguments
///
/// - `&HashSet<String>` - Verified SHA-256 digests already present locally.
///
/// # Returns
///
/// - `Vec<String>` - Sorted SHA-256 digests that must be fetched.
#[must_use]
pub fn missing_blob_hashes(&self, cached_hashes: &HashSet<String>) -> Vec<String> {
self.all_blob_hashes()
.into_iter()
.filter(|sha: &String| !cached_hashes.contains(sha))
.collect()
}
/// Computes which routes changed their pinned entry module, slot bindings, or transitive hashes relative to `previous`.
///
/// # Arguments
///
/// - `Option<&Self>` - Previous active release manifest, if any.
///
/// # Returns
///
/// - `Vec<String>` - Sorted route paths whose pinned dependency graph changed.
#[must_use]
pub fn affected_routes_since(&self, previous: Option<&Self>) -> Vec<String> {
let Some(prev) = previous else {
return self.get_routes().keys().cloned().collect();
};
let mut changed: Vec<String> = Vec::new();
for (route_path, next_route) in self.get_routes().iter() {
match prev.get_routes().get(route_path) {
Some(prev_route) if prev_route == next_route => {}
_ => changed.push(route_path.clone()),
}
}
for prev_route_path in prev.get_routes().keys() {
if !self.get_routes().contains_key(prev_route_path) {
changed.push(prev_route_path.clone());
}
}
changed.sort();
changed
}
}
/// Builder helpers on `ClientNegotiation`.
impl ClientNegotiation {
/// Returns the optional preferred compatibility track name.
///
/// # Returns
///
/// - `Option<&str>` - Preferred track name if specified.
#[must_use]
pub fn preferred_track_str(&self) -> Option<&str> {
let Self {
preferred_track, ..
} = self;
preferred_track.as_deref()
}
/// Attaches a preferred track name to this negotiation descriptor.
///
/// # Arguments
///
/// - `String` - Compatibility track identifier.
///
/// # Returns
///
/// - `Self` - Updated negotiation descriptor.
#[must_use]
pub fn with_preferred_track(mut self, track: String) -> Self {
self.set_preferred_track(Some(track));
self
}
/// Attaches host capabilities to this negotiation descriptor.
///
/// # Arguments
///
/// - `Vec<String>` - Capability names exposed by the host.
///
/// # Returns
///
/// - `Self` - Updated negotiation descriptor.
#[must_use]
pub fn with_capabilities(mut self, capabilities: Vec<String>) -> Self {
self.set_capabilities(capabilities);
self
}
}