Skip to main content

euv_cli/update_server/
impl.rs

1use super::*;
2
3/// Production defaults for `UpdateServerConfig`.
4impl Default for UpdateServerConfig {
5    /// Returns balanced defaults for the read-only Hyperlane update server.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default update server configuration.
10    fn default() -> Self {
11        Self {
12            store_root: PathBuf::from(STORE_DIR_STATE),
13            host: DEFAULT_UPDATE_SERVER_HOST.to_string(),
14            port: DEFAULT_UPDATE_SERVER_PORT,
15            heartbeat_ms: DEFAULT_UPDATE_HEARTBEAT_MS,
16            retry_ms: 3_000,
17            replay_capacity: DEFAULT_UPDATE_EVENT_LOG_CAP,
18            watch_poll_ms: DEFAULT_UPDATE_WATCH_POLL_MS,
19            max_artifact_bytes: DEFAULT_MAX_ARTIFACT_BYTES,
20            once: false,
21        }
22    }
23}
24
25/// Accessor helper on `PublishReport`.
26impl PublishReport {
27    /// Returns the historical release sequence targeted when this publish is a rollback.
28    ///
29    /// # Returns
30    ///
31    /// - `Option<u64>` - Rollback source release sequence, if any.
32    #[must_use]
33    pub fn rollback_of_seq(&self) -> Option<u64> {
34        let Self { rollback_of, .. } = *self;
35        rollback_of
36    }
37}
38
39/// Automatic lockfile release on `UpdateWriterLockGuard` drop.
40impl Drop for UpdateWriterLockGuard {
41    /// Removes the local filesystem writer lock file cleanly.
42    fn drop(&mut self) {
43        let Self { lock_path } = self;
44        let _: io::Result<()> = fs::remove_file(lock_path);
45    }
46}
47
48/// Atomic local filesystem storage, staging, monotonic publishing, rollback, and status operations on `UpdateStore`.
49impl UpdateStore {
50    /// Initializes all required local filesystem store directories (`staging/`, `blobs/sha256/`, `releases/`, `channels/`, `state/events/`).
51    ///
52    /// # Returns
53    ///
54    /// - `io::Result<()>` - Directory creation outcome.
55    pub fn init_layout(&self) -> io::Result<()> {
56        let root: &Path = self.get_root();
57        fs::create_dir_all(root.join(STORE_DIR_STAGING))?;
58        fs::create_dir_all(root.join(STORE_DIR_BLOBS).join(STORE_DIR_SHA256))?;
59        fs::create_dir_all(root.join(STORE_DIR_RELEASES))?;
60        fs::create_dir_all(root.join(STORE_DIR_CHANNELS))?;
61        fs::create_dir_all(root.join(STORE_DIR_STATE).join(STORE_DIR_EVENTS))?;
62        Ok(())
63    }
64
65    /// Acquires the exclusive local filesystem writer lock at `state/writer.lock` with bounded retry backoff.
66    ///
67    /// # Returns
68    ///
69    /// - `io::Result<UpdateWriterLockGuard>` - RAII lock guard released on drop.
70    pub(crate) fn acquire_writer_lock(&self) -> io::Result<UpdateWriterLockGuard> {
71        self.init_layout()?;
72        let lock_path: PathBuf = self
73            .get_root()
74            .join(STORE_DIR_STATE)
75            .join(STORE_WRITER_LOCK_FILE);
76        for _ in 0..200 {
77            match OpenOptions::new()
78                .write(true)
79                .create_new(true)
80                .open(&lock_path)
81            {
82                Ok(mut file) => {
83                    let payload: String = format!("pid={}\n", process::id());
84                    let _: io::Result<()> = file.write_all(payload.as_bytes());
85                    let _: io::Result<()> = file.sync_all();
86                    return Ok(UpdateWriterLockGuard { lock_path });
87                }
88                Err(err) if err.kind() == ErrorKind::AlreadyExists => {
89                    thread::sleep(Duration::from_millis(10));
90                }
91                Err(err) => return Err(err),
92            }
93        }
94        Err(Error::new(ErrorKind::TimedOut, ERR_WRITER_LOCK_TIMEOUT))
95    }
96
97    /// Returns the canonical path for an immutable blob in `blobs/sha256/<sha256>`.
98    ///
99    /// # Arguments
100    ///
101    /// - `&str` - 64-character lowercase SHA-256 hex digest.
102    ///
103    /// # Returns
104    ///
105    /// - `io::Result<PathBuf>` - Validated blob path inside the store.
106    pub fn blob_path(&self, sha256: &str) -> io::Result<PathBuf> {
107        if !is_valid_sha256_hex(sha256) {
108            return Err(Error::new(
109                ErrorKind::InvalidInput,
110                format!("{ERR_BLOB_INTEGRITY}: invalid sha256 `{sha256}`"),
111            ));
112        }
113        Ok(self
114            .get_root()
115            .join(STORE_DIR_BLOBS)
116            .join(STORE_DIR_SHA256)
117            .join(sha256))
118    }
119
120    /// Stages a draft release manifest and its referenced blobs into `staging/<stage_id>/` after verifying SHA-256 integrity.
121    ///
122    /// # Arguments
123    ///
124    /// - `&str` - Logical project identifier.
125    /// - `&str` - Channel name.
126    /// - `&str` - Unique staging directory name.
127    /// - `&ReleaseManifest` - Draft release manifest describing artifacts and routes.
128    /// - `&Path` - Directory containing source blobs named `<sha256>` or `<module_id>@<version>`.
129    ///
130    /// # Returns
131    ///
132    /// - `io::Result<StageReport>` - Staging verification summary.
133    pub fn stage_release(
134        &self,
135        project: &str,
136        channel: &str,
137        stage_id: &str,
138        manifest: &ReleaseManifest,
139        blobs_dir: &Path,
140    ) -> io::Result<StageReport> {
141        validate_store_identifier(project)?;
142        validate_store_identifier(channel)?;
143        validate_store_identifier(stage_id)?;
144        let _lock: UpdateWriterLockGuard = self.acquire_writer_lock()?;
145        let stage_dir: PathBuf = self.get_root().join(STORE_DIR_STAGING).join(stage_id);
146        let stage_blobs_dir: PathBuf = stage_dir.join(STORE_DIR_BLOBS);
147        fs::create_dir_all(&stage_blobs_dir)?;
148        let mut staged_manifest: ReleaseManifest = manifest.clone();
149        staged_manifest
150            .set_project(project.to_string())
151            .set_channel(channel.to_string());
152        if staged_manifest.get_manifest_schema() == 0 {
153            staged_manifest.set_manifest_schema(DYNAMIC_MANIFEST_SCHEMA_V1);
154        }
155        if staged_manifest.get_track().is_empty() {
156            let track: String = default_track_for(
157                staged_manifest.get_min_host_abi().max(DYNAMIC_HOST_ABI_V1),
158                staged_manifest.get_delivery_mode(),
159            );
160            staged_manifest.set_track(track);
161        }
162        let max_bytes: u64 = self.get_max_artifact_bytes();
163        let mut blob_count: usize = 0;
164        let mut total_bytes: u64 = 0;
165        for (art_key, artifact) in staged_manifest.get_artifacts().iter() {
166            let sha: &str = artifact.get_sha256().as_str();
167            if !is_valid_sha256_hex(sha) {
168                return Err(Error::new(
169                    ErrorKind::InvalidData,
170                    format!("{ERR_BLOB_INTEGRITY}: {art_key}"),
171                ));
172            }
173            let by_sha: PathBuf = blobs_dir.join(sha);
174            let by_key: PathBuf = blobs_dir.join(art_key);
175            let existing_store_blob: PathBuf = self.blob_path(sha)?;
176            let src_path: PathBuf = if by_sha.is_file() {
177                by_sha
178            } else if by_key.is_file() {
179                by_key
180            } else if existing_store_blob.is_file() {
181                existing_store_blob
182            } else {
183                return Err(Error::new(
184                    ErrorKind::NotFound,
185                    format!("{ERR_BLOB_INTEGRITY}: missing `{sha}` for `{art_key}`"),
186                ));
187            };
188            let bytes: Vec<u8> = fs::read(&src_path)?;
189            if max_bytes > 0 && (bytes.len() as u64) > max_bytes {
190                return Err(Error::new(
191                    ErrorKind::InvalidData,
192                    format!("{ERR_BLOB_INTEGRITY}: `{art_key}` exceeds max_artifact_bytes"),
193                ));
194            }
195            let computed: String = sha256_hex(&bytes);
196            if !constant_time_eq(computed.as_bytes(), sha.as_bytes()) {
197                return Err(Error::new(
198                    ErrorKind::InvalidData,
199                    format!("{ERR_BLOB_INTEGRITY}: expected {sha}, got {computed}"),
200                ));
201            }
202            atomic_write_synced(&stage_blobs_dir.join(sha), &bytes)?;
203            blob_count += 1;
204            total_bytes = total_bytes.saturating_add(bytes.len() as u64);
205        }
206        let manifest_json: String = match to_string_pretty(&staged_manifest) {
207            Ok(encoded) => encoded,
208            Err(err) => return Err(Error::other(err.to_string())),
209        };
210        atomic_write_synced(
211            &stage_dir.join(STORE_STAGED_MANIFEST_FILE),
212            manifest_json.as_bytes(),
213        )?;
214        Ok(StageReport::new(
215            stage_id.to_string(),
216            project.to_string(),
217            channel.to_string(),
218            blob_count,
219            total_bytes,
220        ))
221    }
222
223    /// Publishes a previously staged release atomically with monotonic sequencing, signing, and event log append.
224    ///
225    /// # Arguments
226    ///
227    /// - `&str` - Logical project identifier.
228    /// - `&str` - Release channel name.
229    /// - `&str` - Staged directory name inside `staging/`.
230    /// - `&[u8]` - Offline signing secret key bytes (never persisted in server config or store).
231    ///
232    /// # Returns
233    ///
234    /// - `io::Result<PublishReport>` - Atomic publish summary.
235    pub fn publish_stage(
236        &self,
237        project: &str,
238        channel: &str,
239        stage_id: &str,
240        signing_key: &[u8],
241    ) -> io::Result<PublishReport> {
242        validate_store_identifier(project)?;
243        validate_store_identifier(channel)?;
244        validate_store_identifier(stage_id)?;
245        if signing_key.is_empty() {
246            return Err(Error::new(ErrorKind::InvalidInput, ERR_EMPTY_SIGNING_KEY));
247        }
248        let stage_dir: PathBuf = self.get_root().join(STORE_DIR_STAGING).join(stage_id);
249        let manifest_path: PathBuf = stage_dir.join(STORE_STAGED_MANIFEST_FILE);
250        if !manifest_path.is_file() {
251            return Err(Error::new(
252                ErrorKind::NotFound,
253                format!("{ERR_STAGE_NOT_FOUND}: {stage_id}"),
254            ));
255        }
256        let raw_manifest: String = fs::read_to_string(&manifest_path)?;
257        let mut manifest: ReleaseManifest = match from_str::<ReleaseManifest>(&raw_manifest) {
258            Ok(parsed) => parsed,
259            Err(err) => return Err(Error::new(ErrorKind::InvalidData, err.to_string())),
260        };
261        manifest
262            .set_project(project.to_string())
263            .set_channel(channel.to_string());
264        let stage_blobs_dir: PathBuf = stage_dir.join(STORE_DIR_BLOBS);
265        let mut blobs: BTreeMap<String, Vec<u8>> = BTreeMap::new();
266        for artifact in manifest.get_artifacts().values() {
267            let sha: &str = artifact.get_sha256().as_str();
268            let staged_path: PathBuf = stage_blobs_dir.join(sha);
269            let existing_path: PathBuf = self.blob_path(sha)?;
270            let src: PathBuf = if staged_path.is_file() {
271                staged_path
272            } else if existing_path.is_file() {
273                existing_path
274            } else {
275                return Err(Error::new(
276                    ErrorKind::NotFound,
277                    format!("{ERR_BLOB_INTEGRITY}: {sha}"),
278                ));
279            };
280            let bytes: Vec<u8> = fs::read(&src)?;
281            let _: Option<Vec<u8>> = blobs.insert(sha.to_string(), bytes);
282        }
283        self.publish_direct(manifest, &blobs, signing_key)
284    }
285
286    /// Atomically verifies, promotes blobs, signs with a strictly monotonic sequence, swaps the channel pointer, and records an event.
287    ///
288    /// # Arguments
289    ///
290    /// - `ReleaseManifest` - Target release manifest.
291    /// - `&BTreeMap<String, Vec<u8>>` - Raw blob bytes keyed by SHA-256 hex digest (may omit blobs already stored).
292    /// - `&[u8]` - Signing secret key bytes.
293    ///
294    /// # Returns
295    ///
296    /// - `io::Result<PublishReport>` - Atomic publish summary.
297    pub fn publish_direct(
298        &self,
299        mut manifest: ReleaseManifest,
300        blobs: &BTreeMap<String, Vec<u8>>,
301        signing_key: &[u8],
302    ) -> io::Result<PublishReport> {
303        let project: String = manifest.get_project().clone();
304        let channel: String = manifest.get_channel().clone();
305        validate_store_identifier(&project)?;
306        validate_store_identifier(&channel)?;
307        if signing_key.is_empty() {
308            return Err(Error::new(ErrorKind::InvalidInput, ERR_EMPTY_SIGNING_KEY));
309        }
310        let _lock: UpdateWriterLockGuard = self.acquire_writer_lock()?;
311        if manifest.get_manifest_schema() == 0 {
312            manifest.set_manifest_schema(DYNAMIC_MANIFEST_SCHEMA_V1);
313        }
314        if manifest.get_track().is_empty() {
315            let track: String = default_track_for(
316                manifest.get_min_host_abi().max(DYNAMIC_HOST_ABI_V1),
317                manifest.get_delivery_mode(),
318            );
319            manifest.set_track(track);
320        }
321        validate_store_identifier(manifest.get_track())?;
322        let current_ptr: Option<ChannelPointer> = self.read_channel_pointer(&project, &channel)?;
323        let from_seq: u64 = current_ptr
324            .as_ref()
325            .map(ChannelPointer::get_active_release_seq)
326            .unwrap_or(0);
327        let prev_manifest: Option<ReleaseManifest> = if from_seq > 0 {
328            self.read_release_manifest(&project, &channel, from_seq)?
329        } else {
330            None
331        };
332        let next_seq: u64 = if manifest.get_release_seq() > from_seq {
333            manifest.get_release_seq()
334        } else {
335            from_seq.saturating_add(1)
336        };
337        manifest
338            .set_release_seq(next_seq)
339            .set_created_at_unix(current_unix_secs());
340        let max_bytes: u64 = self.get_max_artifact_bytes();
341        let mut blobs_written: usize = 0;
342        for (art_key, artifact) in manifest.get_artifacts().iter() {
343            let sha: &str = artifact.get_sha256().as_str();
344            let dst: PathBuf = self.blob_path(sha)?;
345            if dst.is_file() {
346                let existing: Vec<u8> = fs::read(&dst)?;
347                let actual: String = sha256_hex(&existing);
348                if !constant_time_eq(actual.as_bytes(), sha.as_bytes()) {
349                    return Err(Error::new(
350                        ErrorKind::InvalidData,
351                        format!("{ERR_BLOB_INTEGRITY}: corrupt stored blob {sha}"),
352                    ));
353                }
354                continue;
355            }
356            let Some(bytes) = blobs.get(sha) else {
357                return Err(Error::new(
358                    ErrorKind::NotFound,
359                    format!("{ERR_BLOB_INTEGRITY}: missing `{sha}` for `{art_key}`"),
360                ));
361            };
362            if max_bytes > 0 && (bytes.len() as u64) > max_bytes {
363                return Err(Error::new(
364                    ErrorKind::InvalidData,
365                    format!("{ERR_BLOB_INTEGRITY}: `{art_key}` exceeds max_artifact_bytes"),
366                ));
367            }
368            let actual: String = sha256_hex(bytes);
369            if !constant_time_eq(actual.as_bytes(), sha.as_bytes()) {
370                return Err(Error::new(
371                    ErrorKind::InvalidData,
372                    format!("{ERR_BLOB_INTEGRITY}: expected {sha}, got {actual}"),
373                ));
374            }
375            atomic_write_synced(&dst, bytes)?;
376            blobs_written += 1;
377        }
378        let host_caps: Vec<String> = manifest.get_required_capabilities().clone();
379        let mut all_caps: Vec<String> = host_caps;
380        for art in manifest.get_artifacts().values() {
381            for cap in art.get_required_capabilities().iter() {
382                if !all_caps.contains(cap) {
383                    all_caps.push(cap.clone());
384                }
385            }
386        }
387        let check_abi: u32 = manifest.get_min_host_abi().max(DYNAMIC_HOST_ABI_V1);
388        manifest
389            .validate_for_host(
390                check_abi,
391                &all_caps,
392                manifest.get_delivery_mode(),
393                max_bytes,
394            )
395            .map_err(|err: DynamicReleaseError| {
396                Error::new(ErrorKind::InvalidData, err.to_string())
397            })?;
398        let _: &mut ReleaseManifest = manifest
399            .sign(signing_key)
400            .map_err(|err: DynamicReleaseError| Error::other(err.to_string()))?;
401        let manifest_sha256: String = manifest
402            .manifest_sha256()
403            .map_err(|err: DynamicReleaseError| Error::other(err.to_string()))?;
404        let release_path: PathBuf = self.release_manifest_path(&project, &channel, next_seq);
405        let manifest_json: String = match to_string_pretty(&manifest) {
406            Ok(encoded) => encoded,
407            Err(err) => return Err(Error::other(err.to_string())),
408        };
409        atomic_write_synced(&release_path, manifest_json.as_bytes())?;
410        let affected_routes: Vec<String> = manifest.affected_routes_since(prev_manifest.as_ref());
411        let mut activated_event: ReleaseActivatedEvent = ReleaseActivatedEvent::new(
412            DYNAMIC_EVENT_SCHEMA_V1,
413            project.clone(),
414            channel.clone(),
415            manifest.get_track().clone(),
416            from_seq,
417            next_seq,
418            manifest_sha256.clone(),
419        );
420        let _: &mut ReleaseActivatedEvent =
421            activated_event.set_affected_routes(affected_routes.clone());
422        self.append_bounded_event(
423            &project,
424            &channel,
425            StoredReleaseEvent::new(next_seq, activated_event),
426        )?;
427        let pointer: ChannelPointer = ChannelPointer::new(
428            project.clone(),
429            channel.clone(),
430            manifest.get_track().clone(),
431            next_seq,
432            manifest_sha256.clone(),
433            current_unix_secs(),
434        );
435        let ptr_json: String = match to_string_pretty(&pointer) {
436            Ok(encoded) => encoded,
437            Err(err) => return Err(Error::other(err.to_string())),
438        };
439        let track_ptr_path: PathBuf = self
440            .get_root()
441            .join(STORE_DIR_CHANNELS)
442            .join(&project)
443            .join(&channel)
444            .join(STORE_DIR_TRACKS)
445            .join(format!("{}{EXT_JSON_DOT}", manifest.get_track()));
446        atomic_write_synced(&track_ptr_path, ptr_json.as_bytes())?;
447        let active_ptr_path: PathBuf = self.channel_pointer_path(&project, &channel);
448        atomic_write_synced(&active_ptr_path, ptr_json.as_bytes())?;
449        let mut report: PublishReport = PublishReport::new(
450            project,
451            channel,
452            manifest.get_track().clone(),
453            from_seq,
454            next_seq,
455            manifest_sha256,
456        );
457        report
458            .set_rollback_of(manifest.rollback_of_seq())
459            .set_affected_routes(affected_routes)
460            .set_blobs_written(blobs_written);
461        Ok(report)
462    }
463
464    /// Executes a monotonic rollback by signing a NEW release sequence pointing back to `target_release_seq`'s blobs (Sec 11.3).
465    ///
466    /// # Arguments
467    ///
468    /// - `&str` - Logical project identifier.
469    /// - `&str` - Release channel name.
470    /// - `u64` - Historical release sequence whose blobs and route graphs should be restored.
471    /// - `&[u8]` - Offline signing secret key bytes.
472    ///
473    /// # Returns
474    ///
475    /// - `io::Result<PublishReport>` - Report containing the NEW monotonic `to_release` and `rollback_of`.
476    pub fn rollback_release(
477        &self,
478        project: &str,
479        channel: &str,
480        target_release_seq: u64,
481        signing_key: &[u8],
482    ) -> io::Result<PublishReport> {
483        validate_store_identifier(project)?;
484        validate_store_identifier(channel)?;
485        let Some(mut historical) =
486            self.read_release_manifest(project, channel, target_release_seq)?
487        else {
488            return Err(Error::new(
489                ErrorKind::NotFound,
490                format!("{ERR_ROLLBACK_TARGET_MISSING}: seq={target_release_seq}"),
491            ));
492        };
493        historical.set_release_seq(0);
494        historical.set_rollback_of(Some(target_release_seq));
495        historical.set_signature(String::new());
496        let empty_blobs: BTreeMap<String, Vec<u8>> = BTreeMap::new();
497        self.publish_direct(historical, &empty_blobs, signing_key)
498    }
499
500    /// Reads the active channel pointer for `(project, channel)` if published.
501    ///
502    /// # Arguments
503    ///
504    /// - `&str` - Project identifier.
505    /// - `&str` - Channel name.
506    ///
507    /// # Returns
508    ///
509    /// - `io::Result<Option<ChannelPointer>>` - Active pointer or `None`.
510    pub fn read_channel_pointer(
511        &self,
512        project: &str,
513        channel: &str,
514    ) -> io::Result<Option<ChannelPointer>> {
515        validate_store_identifier(project)?;
516        validate_store_identifier(channel)?;
517        let path: PathBuf = self.channel_pointer_path(project, channel);
518        if !path.is_file() {
519            return Ok(None);
520        }
521        let raw: String = fs::read_to_string(&path)?;
522        let ptr: ChannelPointer = match from_str::<ChannelPointer>(&raw) {
523            Ok(parsed) => parsed,
524            Err(err) => return Err(Error::new(ErrorKind::InvalidData, err.to_string())),
525        };
526        Ok(Some(ptr))
527    }
528
529    /// Reads an immutable signed release manifest for `(project, channel, release_seq)`.
530    ///
531    /// # Arguments
532    ///
533    /// - `&str` - Project identifier.
534    /// - `&str` - Channel name.
535    /// - `u64` - Release sequence number.
536    ///
537    /// # Returns
538    ///
539    /// - `io::Result<Option<ReleaseManifest>>` - Signed manifest or `None`.
540    pub fn read_release_manifest(
541        &self,
542        project: &str,
543        channel: &str,
544        release_seq: u64,
545    ) -> io::Result<Option<ReleaseManifest>> {
546        validate_store_identifier(project)?;
547        validate_store_identifier(channel)?;
548        let path: PathBuf = self.release_manifest_path(project, channel, release_seq);
549        if !path.is_file() {
550            return Ok(None);
551        }
552        let raw: String = fs::read_to_string(&path)?;
553        let manifest: ReleaseManifest = match from_str::<ReleaseManifest>(&raw) {
554            Ok(parsed) => parsed,
555            Err(err) => return Err(Error::new(ErrorKind::InvalidData, err.to_string())),
556        };
557        Ok(Some(manifest))
558    }
559
560    /// Negotiates and selects a compatible signed manifest for `(project, channel)` matching protocol, ABI, delivery mode, and optional track.
561    ///
562    /// # Arguments
563    ///
564    /// - `&str` - Project identifier.
565    /// - `&str` - Channel name.
566    /// - `&ClientNegotiation` - Client compatibility declaration.
567    ///
568    /// # Returns
569    ///
570    /// - `io::Result<Result<ReleaseManifest, String>>` - Compatible manifest, incompatibility reason, or I/O error.
571    pub fn read_compatible_manifest(
572        &self,
573        project: &str,
574        channel: &str,
575        negotiation: &ClientNegotiation,
576    ) -> io::Result<Result<ReleaseManifest, String>> {
577        validate_store_identifier(project)?;
578        validate_store_identifier(channel)?;
579        if negotiation.get_protocol_version() != DYNAMIC_PROTOCOL_VERSION_V1 {
580            return Ok(Err(format!(
581                "{ERR_NO_COMPATIBLE_RELEASE}: unsupported protocol v{}",
582                negotiation.get_protocol_version()
583            )));
584        }
585        let mut candidate_seqs: Vec<u64> = Vec::new();
586        let tracks_dir: PathBuf = self
587            .get_root()
588            .join(STORE_DIR_CHANNELS)
589            .join(project)
590            .join(channel)
591            .join(STORE_DIR_TRACKS);
592        if let Some(pref_track) = negotiation.preferred_track_str() {
593            validate_store_identifier(pref_track)?;
594            let track_path: PathBuf = tracks_dir.join(format!("{pref_track}{EXT_JSON_DOT}"));
595            if track_path.is_file()
596                && let Ok(raw) = fs::read_to_string(&track_path)
597                && let Ok(ptr) = from_str::<ChannelPointer>(&raw)
598            {
599                candidate_seqs.push(ptr.get_active_release_seq());
600            }
601        }
602        let inferred_track: String =
603            default_track_for(negotiation.get_host_abi(), negotiation.get_delivery_mode());
604        let inferred_path: PathBuf = tracks_dir.join(format!("{inferred_track}{EXT_JSON_DOT}"));
605        if inferred_path.is_file()
606            && let Ok(raw) = fs::read_to_string(&inferred_path)
607            && let Ok(ptr) = from_str::<ChannelPointer>(&raw)
608            && !candidate_seqs.contains(&ptr.get_active_release_seq())
609        {
610            candidate_seqs.push(ptr.get_active_release_seq());
611        }
612        if let Some(active_ptr) = self.read_channel_pointer(project, channel)?
613            && !candidate_seqs.contains(&active_ptr.get_active_release_seq())
614        {
615            candidate_seqs.push(active_ptr.get_active_release_seq());
616        }
617        if candidate_seqs.is_empty() {
618            return Err(Error::new(
619                ErrorKind::NotFound,
620                format!("no active release for {project}/{channel}"),
621            ));
622        }
623        for seq in candidate_seqs.into_iter() {
624            if let Some(manifest) = self.read_release_manifest(project, channel, seq)? {
625                let abi_ok: bool = negotiation.get_host_abi() >= manifest.get_min_host_abi()
626                    && negotiation.get_host_abi() <= manifest.get_max_host_abi();
627                let mode_ok: bool = !(negotiation.get_delivery_mode()
628                    == DeliveryChannelMode::DeclarativeData
629                    && manifest.get_delivery_mode() == DeliveryChannelMode::WasmComponent);
630                if abi_ok && mode_ok {
631                    return Ok(Ok(manifest));
632                }
633            }
634        }
635        Ok(Err(ERR_NO_COMPATIBLE_RELEASE.to_string()))
636    }
637
638    /// Reads an immutable content-addressed blob by its validated SHA-256 digest.
639    ///
640    /// # Arguments
641    ///
642    /// - `&str` - 64-character lowercase SHA-256 hex digest.
643    ///
644    /// # Returns
645    ///
646    /// - `io::Result<Option<Vec<u8>>>` - Blob bytes if present, or `None`.
647    pub fn read_blob(&self, sha256: &str) -> io::Result<Option<Vec<u8>>> {
648        let path: PathBuf = self.blob_path(sha256)?;
649        if !path.is_file() {
650            return Ok(None);
651        }
652        let bytes: Vec<u8> = fs::read(&path)?;
653        Ok(Some(bytes))
654    }
655
656    /// Reads bounded persisted release events strictly newer than `after_event_id`.
657    ///
658    /// # Arguments
659    ///
660    /// - `&str` - Project identifier.
661    /// - `&str` - Channel name.
662    /// - `u64` - Exclusive cursor (`0` returns all retained events).
663    ///
664    /// # Returns
665    ///
666    /// - `io::Result<Vec<StoredReleaseEvent>>` - Ordered release events newer than `after_event_id`.
667    pub fn read_events_after(
668        &self,
669        project: &str,
670        channel: &str,
671        after_event_id: u64,
672    ) -> io::Result<Vec<StoredReleaseEvent>> {
673        validate_store_identifier(project)?;
674        validate_store_identifier(channel)?;
675        let path: PathBuf = self.event_log_path(project, channel);
676        if !path.is_file() {
677            return Ok(Vec::new());
678        }
679        let raw: String = fs::read_to_string(&path)?;
680        let mut out: Vec<StoredReleaseEvent> = Vec::new();
681        for line in raw.lines() {
682            let trimmed: &str = line.trim();
683            if trimmed.is_empty() {
684                continue;
685            }
686            if let Ok(rec) = from_str::<StoredReleaseEvent>(trimmed)
687                && rec.get_event_id() > after_event_id
688            {
689                out.push(rec);
690            }
691        }
692        Ok(out)
693    }
694
695    /// Lists all active `ChannelPointer` records currently persisted beneath `channels/`.
696    ///
697    /// # Returns
698    ///
699    /// - `io::Result<Vec<ChannelPointer>>` - All active pointers in deterministic order.
700    pub fn list_active_pointers(&self) -> io::Result<Vec<ChannelPointer>> {
701        let channels_root: PathBuf = self.get_root().join(STORE_DIR_CHANNELS);
702        if !channels_root.is_dir() {
703            return Ok(Vec::new());
704        }
705        let mut pointers: Vec<ChannelPointer> = Vec::new();
706        for proj_entry_res in fs::read_dir(&channels_root)? {
707            let proj_entry: DirEntry = proj_entry_res?;
708            if !proj_entry.path().is_dir() {
709                continue;
710            }
711            for chan_entry_res in fs::read_dir(proj_entry.path())? {
712                let chan_entry: DirEntry = chan_entry_res?;
713                let active_file: PathBuf = chan_entry.path().join(STORE_ACTIVE_POINTER_FILE);
714                if active_file.is_file()
715                    && let Ok(raw) = fs::read_to_string(&active_file)
716                    && let Ok(ptr) = from_str::<ChannelPointer>(&raw)
717                {
718                    pointers.push(ptr);
719                }
720            }
721        }
722        pointers.sort_by(|a: &ChannelPointer, b: &ChannelPointer| {
723            a.get_project()
724                .cmp(b.get_project())
725                .then_with(|| a.get_channel().cmp(b.get_channel()))
726        });
727        Ok(pointers)
728    }
729
730    /// Collects a structured status report across all blobs and channels (optionally filtered).
731    ///
732    /// # Arguments
733    ///
734    /// - `Option<&str>` - Optional project filter.
735    /// - `Option<&str>` - Optional channel filter.
736    ///
737    /// # Returns
738    ///
739    /// - `io::Result<UpdateStoreStatus>` - Complete store status summary.
740    pub fn status(
741        &self,
742        project_filter: Option<&str>,
743        channel_filter: Option<&str>,
744    ) -> io::Result<UpdateStoreStatus> {
745        let blobs_dir: PathBuf = self.get_root().join(STORE_DIR_BLOBS).join(STORE_DIR_SHA256);
746        let mut blob_count: usize = 0;
747        let mut blob_total_bytes: u64 = 0;
748        if blobs_dir.is_dir() {
749            for entry_res in fs::read_dir(&blobs_dir)? {
750                let entry: DirEntry = entry_res?;
751                if entry.path().is_file()
752                    && let Ok(meta) = entry.metadata()
753                {
754                    blob_count += 1;
755                    blob_total_bytes = blob_total_bytes.saturating_add(meta.len());
756                }
757            }
758        }
759        let pointers: Vec<ChannelPointer> = self.list_active_pointers()?;
760        let mut channels: Vec<ChannelStatusEntry> = Vec::new();
761        for ptr in pointers.into_iter() {
762            if let Some(pf) = project_filter
763                && ptr.get_project() != pf
764            {
765                continue;
766            }
767            if let Some(cf) = channel_filter
768                && ptr.get_channel() != cf
769            {
770                continue;
771            }
772            let rel_dir: PathBuf = self
773                .get_root()
774                .join(STORE_DIR_RELEASES)
775                .join(ptr.get_project())
776                .join(ptr.get_channel());
777            let mut release_count: usize = 0;
778            if rel_dir.is_dir() {
779                for entry_res in fs::read_dir(&rel_dir)? {
780                    let entry: DirEntry = entry_res?;
781                    if entry.path().is_file() {
782                        release_count += 1;
783                    }
784                }
785            }
786            let event_count: usize = self
787                .read_events_after(ptr.get_project(), ptr.get_channel(), 0)?
788                .len();
789            channels.push(ChannelStatusEntry::new(
790                ptr.get_project().clone(),
791                ptr.get_channel().clone(),
792                ptr,
793                release_count,
794                event_count,
795            ));
796        }
797        Ok(UpdateStoreStatus::new(
798            self.get_root().display().to_string(),
799            blob_count,
800            blob_total_bytes,
801            channels,
802        ))
803    }
804
805    /// Appends one `StoredReleaseEvent` to the channel's bounded rotating JSONL history log.
806    ///
807    /// # Arguments
808    ///
809    /// - `&str` - Project identifier.
810    /// - `&str` - Channel name.
811    /// - `StoredReleaseEvent` - New event record.
812    ///
813    /// # Returns
814    ///
815    /// - `io::Result<()>` - Persistence outcome.
816    fn append_bounded_event(
817        &self,
818        project: &str,
819        channel: &str,
820        record: StoredReleaseEvent,
821    ) -> io::Result<()> {
822        let mut existing: Vec<StoredReleaseEvent> = self.read_events_after(project, channel, 0)?;
823        existing.push(record);
824        if existing.len() > DEFAULT_UPDATE_EVENT_LOG_CAP {
825            let drain_count: usize = existing.len() - DEFAULT_UPDATE_EVENT_LOG_CAP;
826            let _: Vec<StoredReleaseEvent> = existing.drain(..drain_count).collect();
827        }
828        let mut buf: String = String::new();
829        for item in existing.iter() {
830            let line: String = match to_string(item) {
831                Ok(encoded) => encoded,
832                Err(err) => return Err(Error::other(err.to_string())),
833            };
834            buf.push_str(&line);
835            buf.push('\n');
836        }
837        let path: PathBuf = self.event_log_path(project, channel);
838        atomic_write_synced(&path, buf.as_bytes())
839    }
840
841    /// Builds the active pointer file path for `(project, channel)`.
842    ///
843    /// # Arguments
844    ///
845    /// - `&str` - Project identifier.
846    /// - `&str` - Channel name.
847    ///
848    /// # Returns
849    ///
850    /// - `PathBuf` - Path to `channels/<project>/<channel>/active.json`.
851    #[must_use]
852    fn channel_pointer_path(&self, project: &str, channel: &str) -> PathBuf {
853        self.get_root()
854            .join(STORE_DIR_CHANNELS)
855            .join(project)
856            .join(channel)
857            .join(STORE_ACTIVE_POINTER_FILE)
858    }
859
860    /// Builds the immutable release manifest path for `(project, channel, release_seq)`.
861    ///
862    /// # Arguments
863    ///
864    /// - `&str` - Project identifier.
865    /// - `&str` - Channel name.
866    /// - `u64` - Release sequence number.
867    ///
868    /// # Returns
869    ///
870    /// - `PathBuf` - Path to `releases/<project>/<channel>/<release_seq>.json`.
871    #[must_use]
872    fn release_manifest_path(&self, project: &str, channel: &str, release_seq: u64) -> PathBuf {
873        self.get_root()
874            .join(STORE_DIR_RELEASES)
875            .join(project)
876            .join(channel)
877            .join(format!("{release_seq}{EXT_JSON_DOT}"))
878    }
879
880    /// Builds the bounded JSONL event log path for `(project, channel)`.
881    ///
882    /// # Arguments
883    ///
884    /// - `&str` - Project identifier.
885    /// - `&str` - Channel name.
886    ///
887    /// # Returns
888    ///
889    /// - `PathBuf` - Path to `state/events/<project>/<channel>.jsonl`.
890    #[must_use]
891    fn event_log_path(&self, project: &str, channel: &str) -> PathBuf {
892        self.get_root()
893            .join(STORE_DIR_STATE)
894            .join(STORE_DIR_EVENTS)
895            .join(project)
896            .join(format!("{channel}{EXT_JSONL_DOT}"))
897    }
898}
899
900/// Shared state management for the Hyperlane update server.
901#[cfg(feature = "update-server")]
902impl UpdateServerState {
903    /// Creates a new `UpdateServerState` wrapping `store` and a fresh `SseHub`.
904    ///
905    /// # Arguments
906    ///
907    /// - `UpdateStore` - Local atomic filesystem update store.
908    /// - `SseConfig` - Hyperlane SSE heartbeat, retry, and replay configuration.
909    ///
910    /// # Returns
911    ///
912    /// - `Self` - Shared server state ready for route registration.
913    #[must_use]
914    pub fn new(store: UpdateStore, sse_config: SseConfig) -> Self {
915        let sse_hub: SseHub = SseHub::new(sse_config.clone());
916        Self {
917            store,
918            sse_hub,
919            sse_config,
920            dispatched_seqs: Arc::new(Mutex::new(HashMap::new())),
921            running: Arc::new(AtomicBool::new(true)),
922        }
923    }
924
925    /// Returns a reference to the backing `UpdateStore`.
926    ///
927    /// # Returns
928    ///
929    /// - `&UpdateStore` - Update store reference.
930    #[must_use]
931    pub fn store(&self) -> &UpdateStore {
932        let Self { store, .. } = self;
933        store
934    }
935
936    /// Returns a reference to the shared Hyperlane `SseHub`.
937    ///
938    /// # Returns
939    ///
940    /// - `&SseHub` - Shared SSE pub/sub hub.
941    #[must_use]
942    pub fn sse_hub(&self) -> &SseHub {
943        let Self { sse_hub, .. } = self;
944        sse_hub
945    }
946
947    /// Returns a reference to the SSE configuration.
948    ///
949    /// # Returns
950    ///
951    /// - `&SseConfig` - Active SSE config.
952    #[must_use]
953    pub fn sse_config(&self) -> &SseConfig {
954        let Self { sse_config, .. } = self;
955        sse_config
956    }
957
958    /// Returns whether the background pointer watcher should continue running.
959    ///
960    /// # Returns
961    ///
962    /// - `bool` - `true` while active.
963    #[must_use]
964    pub fn is_running(&self) -> bool {
965        let Self { running, .. } = self;
966        running.load(Ordering::Acquire)
967    }
968
969    /// Signals the background pointer watcher to stop cleanly.
970    pub fn stop(&self) {
971        let Self { running, .. } = self;
972        running.store(false, Ordering::Release);
973    }
974
975    /// Scans filesystem channel pointers and bounded event logs, publishing each new monotonic sequence ONCE to `SseHub`.
976    pub fn sync_store_events_to_sse(&self) {
977        let Self {
978            store,
979            sse_hub,
980            dispatched_seqs,
981            ..
982        } = self;
983        let Ok(pointers) = store.list_active_pointers() else {
984            return;
985        };
986        for ptr in pointers.into_iter() {
987            let key: (String, String) = (ptr.get_project().clone(), ptr.get_channel().clone());
988            let last_sent: u64 = dispatched_seqs
989                .lock()
990                .ok()
991                .and_then(|g: MutexGuard<'_, HashMap<(String, String), u64>>| g.get(&key).copied())
992                .unwrap_or(0);
993            if ptr.get_active_release_seq() <= last_sent {
994                continue;
995            }
996            let Ok(events) = store.read_events_after(&key.0, &key.1, last_sent) else {
997                continue;
998            };
999            let topic: String = sse_topic_for_channel(&key.0, &key.1);
1000            let mut max_dispatched: u64 = last_sent;
1001            for rec in events.into_iter() {
1002                if let Ok(json) = to_string(rec.get_event()) {
1003                    let sse_ev: SseEvent = SseEvent::new(json)
1004                        .with_id(rec.get_event_id().to_string())
1005                        .with_event(SSE_EVENT_RELEASE_ACTIVATED);
1006                    let _: Result<u64, SseError> = sse_hub.publish(topic.as_str(), sse_ev);
1007                    if rec.get_event_id() > max_dispatched {
1008                        max_dispatched = rec.get_event_id();
1009                    }
1010                }
1011            }
1012            if max_dispatched > last_sent
1013                && let Ok(mut guard) = dispatched_seqs.lock()
1014            {
1015                let _: Option<u64> = guard.insert(key, max_dispatched);
1016            }
1017        }
1018    }
1019}
1020
1021/// Lifecycle control methods on `UpdateServerHandle`.
1022#[cfg(feature = "update-server")]
1023impl UpdateServerHandle {
1024    /// Returns the bound `SocketAddr` of the running Hyperlane update server.
1025    ///
1026    /// # Returns
1027    ///
1028    /// - `SocketAddr` - Bound address.
1029    #[must_use]
1030    pub fn address(&self) -> SocketAddr {
1031        let Self { address, .. } = *self;
1032        address
1033    }
1034
1035    /// Returns the base HTTP URL (`http://host:port`) of this server.
1036    ///
1037    /// # Returns
1038    ///
1039    /// - `String` - Base HTTP URL.
1040    #[must_use]
1041    pub fn url(&self) -> String {
1042        format!("http://{}", self.address())
1043    }
1044
1045    /// Returns a reference to the backing `UpdateStore`.
1046    ///
1047    /// # Returns
1048    ///
1049    /// - `&UpdateStore` - Update store reference.
1050    #[must_use]
1051    pub fn store(&self) -> &UpdateStore {
1052        let Self { state, .. } = self;
1053        state.store()
1054    }
1055
1056    /// Returns whether this server handle is currently active.
1057    ///
1058    /// # Returns
1059    ///
1060    /// - `bool` - `true` while active.
1061    #[must_use]
1062    pub fn is_running(&self) -> bool {
1063        let Self { state, .. } = self;
1064        state.is_running()
1065    }
1066
1067    /// Builds a machine-readable `UpdateServerReport` describing the active server endpoints.
1068    ///
1069    /// # Arguments
1070    ///
1071    /// - `bool` - Whether `--once` smoke mode was requested.
1072    ///
1073    /// # Returns
1074    ///
1075    /// - `UpdateServerReport` - Structured server report.
1076    #[must_use]
1077    pub fn report(&self, once: bool) -> UpdateServerReport {
1078        UpdateServerReport::new(
1079            self.store().get_root().display().to_string(),
1080            self.url(),
1081            UPDATE_ROUTE_MANIFEST.to_string(),
1082            UPDATE_ROUTE_BLOB.to_string(),
1083            UPDATE_ROUTE_EVENTS.to_string(),
1084            once,
1085        )
1086    }
1087
1088    /// Gracefully shuts down the Hyperlane server, pointer watcher, and Tokio runtime.
1089    pub fn shutdown(&mut self) {
1090        let Self {
1091            address,
1092            state,
1093            control,
1094            runtime,
1095        } = self;
1096        state.stop();
1097        unregister_server_state_for_addr(*address);
1098        if let (Some(ctrl), Some(rt)) = (control.take(), runtime.take()) {
1099            rt.block_on(async move {
1100                ctrl.shutdown().await;
1101            });
1102            rt.shutdown_timeout(Duration::from_millis(500));
1103        } else if let Some(rt) = runtime.take() {
1104            rt.shutdown_timeout(Duration::from_millis(500));
1105        }
1106    }
1107}
1108
1109/// Automatic server cleanup when `UpdateServerHandle` is dropped.
1110#[cfg(feature = "update-server")]
1111impl Drop for UpdateServerHandle {
1112    /// Stops the Hyperlane listener and reclaims resources cleanly.
1113    fn drop(&mut self) {
1114        self.shutdown();
1115    }
1116}
1117
1118/// Hyperlane `ServerHook` serving `GET /v1/projects/{project}/channels/{channel}/manifest`.
1119#[cfg(feature = "update-server")]
1120impl ServerHook for ManifestRouteHook {
1121    /// Constructs a stateless `ManifestRouteHook`.
1122    ///
1123    /// # Arguments
1124    ///
1125    /// - `&mut Stream` - Incoming client stream.
1126    /// - `&mut Context` - Active request context.
1127    ///
1128    /// # Returns
1129    ///
1130    /// - `Self` - Hook instance.
1131    async fn new(_: &mut Stream, _: &mut Context) -> Self {
1132        Self
1133    }
1134
1135    /// Serves the protocol/ABI-negotiated signed `ReleaseManifest` JSON (read-only `GET`/`HEAD`).
1136    ///
1137    /// # Arguments
1138    ///
1139    /// - `&mut Stream` - Client stream.
1140    /// - `&mut Context` - Hyperlane context.
1141    ///
1142    /// # Returns
1143    ///
1144    /// - `Status` - Request lifecycle status.
1145    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
1146        let method_ok: bool = {
1147            let method: &Method = ctx.get_request().get_method();
1148            method.is_get() || method.is_head()
1149        };
1150        if !method_ok {
1151            return send_hyperlane_bytes(
1152                stream,
1153                ctx,
1154                405,
1155                UPDATE_MIME_JSON,
1156                ERR_BODY_METHOD_NOT_ALLOWED.as_bytes().to_vec(),
1157            )
1158            .await;
1159        }
1160        let Some(state) = resolve_server_state(stream) else {
1161            return send_hyperlane_bytes(
1162                stream,
1163                ctx,
1164                503,
1165                UPDATE_MIME_JSON,
1166                ERR_BODY_UNCONFIGURED.as_bytes().to_vec(),
1167            )
1168            .await;
1169        };
1170        let Some(project) = ctx.try_get_route_param(ROUTE_PARAM_PROJECT) else {
1171            return send_hyperlane_bytes(
1172                stream,
1173                ctx,
1174                400,
1175                UPDATE_MIME_JSON,
1176                ERR_BODY_BAD_REQUEST.as_bytes().to_vec(),
1177            )
1178            .await;
1179        };
1180        let Some(channel) = ctx.try_get_route_param(ROUTE_PARAM_CHANNEL) else {
1181            return send_hyperlane_bytes(
1182                stream,
1183                ctx,
1184                400,
1185                UPDATE_MIME_JSON,
1186                ERR_BODY_BAD_REQUEST.as_bytes().to_vec(),
1187            )
1188            .await;
1189        };
1190        let protocol: u32 = ctx
1191            .get_request()
1192            .try_get_query_front(QUERY_KEY_PROTOCOL)
1193            .and_then(|v: String| v.parse::<u32>().ok())
1194            .unwrap_or(DYNAMIC_PROTOCOL_VERSION_V1);
1195        let host_abi: u32 = ctx
1196            .get_request()
1197            .try_get_query_front(QUERY_KEY_ABI)
1198            .and_then(|v: String| v.parse::<u32>().ok())
1199            .unwrap_or(DYNAMIC_HOST_ABI_V1);
1200        let mode_raw: Option<String> = ctx.get_request().try_get_query_front(QUERY_KEY_MODE);
1201        let mode: DeliveryChannelMode = parse_delivery_mode_token(mode_raw.as_deref());
1202        let mut neg: ClientNegotiation = ClientNegotiation::new(protocol, host_abi, mode);
1203        if let Some(track) = ctx.get_request().try_get_query_front(QUERY_KEY_TRACK)
1204            && !track.is_empty()
1205        {
1206            neg = neg.with_preferred_track(track);
1207        }
1208        match state
1209            .store()
1210            .read_compatible_manifest(&project, &channel, &neg)
1211        {
1212            Ok(Ok(manifest)) => {
1213                let etag: String = manifest.manifest_sha256().unwrap_or_default();
1214                let body: Vec<u8> = to_vec(&manifest).unwrap_or_default();
1215                ctx.get_mut_response()
1216                    .set_header(CACHE_CONTROL, UPDATE_CACHE_NO_CACHE)
1217                    .set_header(UPDATE_HDR_ETAG, format!("\"{etag}\""));
1218                send_hyperlane_bytes(stream, ctx, 200, UPDATE_MIME_JSON, body).await
1219            }
1220            Ok(Err(reason)) => {
1221                let payload: String =
1222                    format!("{{\"error\":\"incompatible\",\"detail\":\"{reason}\"}}");
1223                send_hyperlane_bytes(stream, ctx, 409, UPDATE_MIME_JSON, payload.into_bytes()).await
1224            }
1225            Err(err) if err.kind() == ErrorKind::NotFound => {
1226                send_hyperlane_bytes(
1227                    stream,
1228                    ctx,
1229                    404,
1230                    UPDATE_MIME_JSON,
1231                    ERR_BODY_NOT_FOUND.as_bytes().to_vec(),
1232                )
1233                .await
1234            }
1235            Err(_) => {
1236                send_hyperlane_bytes(
1237                    stream,
1238                    ctx,
1239                    400,
1240                    UPDATE_MIME_JSON,
1241                    ERR_BODY_BAD_REQUEST.as_bytes().to_vec(),
1242                )
1243                .await
1244            }
1245        }
1246    }
1247}
1248
1249/// Hyperlane `ServerHook` serving immutable content-addressed blobs at `GET /v1/blobs/{sha256}` with Range resume support.
1250#[cfg(feature = "update-server")]
1251impl ServerHook for BlobRouteHook {
1252    /// Constructs a stateless `BlobRouteHook`.
1253    ///
1254    /// # Arguments
1255    ///
1256    /// - `&mut Stream` - Incoming client stream.
1257    /// - `&mut Context` - Active request context.
1258    ///
1259    /// # Returns
1260    ///
1261    /// - `Self` - Hook instance.
1262    async fn new(_: &mut Stream, _: &mut Context) -> Self {
1263        Self
1264    }
1265
1266    /// Serves immutable verified blobs with HTTP `Range` (`206 Partial Content`) and immutable caching headers.
1267    ///
1268    /// # Arguments
1269    ///
1270    /// - `&mut Stream` - Client stream.
1271    /// - `&mut Context` - Hyperlane context.
1272    ///
1273    /// # Returns
1274    ///
1275    /// - `Status` - Request lifecycle status.
1276    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
1277        let method_ok: bool = {
1278            let method: &Method = ctx.get_request().get_method();
1279            method.is_get() || method.is_head()
1280        };
1281        if !method_ok {
1282            return send_hyperlane_bytes(
1283                stream,
1284                ctx,
1285                405,
1286                UPDATE_MIME_JSON,
1287                ERR_BODY_METHOD_NOT_ALLOWED.as_bytes().to_vec(),
1288            )
1289            .await;
1290        }
1291        let Some(state) = resolve_server_state(stream) else {
1292            return send_hyperlane_bytes(
1293                stream,
1294                ctx,
1295                503,
1296                UPDATE_MIME_JSON,
1297                ERR_BODY_UNCONFIGURED.as_bytes().to_vec(),
1298            )
1299            .await;
1300        };
1301        let Some(sha256) = ctx.try_get_route_param(ROUTE_PARAM_SHA256) else {
1302            return send_hyperlane_bytes(
1303                stream,
1304                ctx,
1305                400,
1306                UPDATE_MIME_JSON,
1307                ERR_BODY_BAD_REQUEST.as_bytes().to_vec(),
1308            )
1309            .await;
1310        };
1311        if !is_valid_sha256_hex(&sha256) {
1312            return send_hyperlane_bytes(
1313                stream,
1314                ctx,
1315                400,
1316                UPDATE_MIME_JSON,
1317                ERR_BODY_BAD_REQUEST.as_bytes().to_vec(),
1318            )
1319            .await;
1320        }
1321        let blob_bytes: Vec<u8> = match state.store().read_blob(&sha256) {
1322            Ok(Some(bytes)) => bytes,
1323            Ok(None) => {
1324                return send_hyperlane_bytes(
1325                    stream,
1326                    ctx,
1327                    404,
1328                    UPDATE_MIME_JSON,
1329                    ERR_BODY_NOT_FOUND.as_bytes().to_vec(),
1330                )
1331                .await;
1332            }
1333            Err(_) => {
1334                return send_hyperlane_bytes(
1335                    stream,
1336                    ctx,
1337                    400,
1338                    UPDATE_MIME_JSON,
1339                    ERR_BODY_BAD_REQUEST.as_bytes().to_vec(),
1340                )
1341                .await;
1342            }
1343        };
1344        let range_hdr: Option<String> = ctx
1345            .get_request()
1346            .try_get_header_front(UPDATE_HDR_RANGE_LOWER);
1347        let total_len: usize = blob_bytes.len();
1348        ctx.get_mut_response()
1349            .set_header(CACHE_CONTROL, UPDATE_CACHE_IMMUTABLE)
1350            .set_header(UPDATE_HDR_ETAG, format!("\"{sha256}\""))
1351            .set_header(UPDATE_HDR_ACCEPT_RANGES, UPDATE_HDR_BYTES);
1352        match parse_http_byte_range(range_hdr.as_deref(), total_len) {
1353            ByteRangeSpec::Full => {
1354                send_hyperlane_bytes(stream, ctx, 200, UPDATE_MIME_OCTET, blob_bytes).await
1355            }
1356            ByteRangeSpec::Slice { start, end } => {
1357                let slice: Vec<u8> = blob_bytes[start..=end].to_vec();
1358                ctx.get_mut_response().set_header(
1359                    UPDATE_HDR_CONTENT_RANGE,
1360                    format!("bytes {start}-{end}/{total_len}"),
1361                );
1362                send_hyperlane_bytes(stream, ctx, 206, UPDATE_MIME_OCTET, slice).await
1363            }
1364            ByteRangeSpec::Invalid => {
1365                ctx.get_mut_response()
1366                    .set_header(UPDATE_HDR_CONTENT_RANGE, format!("bytes */{total_len}"));
1367                send_hyperlane_bytes(
1368                    stream,
1369                    ctx,
1370                    416,
1371                    UPDATE_MIME_JSON,
1372                    ERR_BODY_RANGE_INVALID.as_bytes().to_vec(),
1373                )
1374                .await
1375            }
1376        }
1377    }
1378}
1379
1380/// Hyperlane `ServerHook` streaming minimal `release.activated` SSE notifications with `Last-Event-ID` replay.
1381#[cfg(feature = "update-server")]
1382impl ServerHook for EventsRouteHook {
1383    /// Constructs a stateless `EventsRouteHook`.
1384    ///
1385    /// # Arguments
1386    ///
1387    /// - `&mut Stream` - Incoming client stream.
1388    /// - `&mut Context` - Active request context.
1389    ///
1390    /// # Returns
1391    ///
1392    /// - `Self` - Hook instance.
1393    async fn new(_: &mut Stream, _: &mut Context) -> Self {
1394        Self
1395    }
1396
1397    /// Streams `release.activated` SSE frames via `hyperlane-plugin-sse`, supporting `Last-Event-ID` bounded replay and heartbeats.
1398    ///
1399    /// # Arguments
1400    ///
1401    /// - `&mut Stream` - Long-lived SSE stream.
1402    /// - `&mut Context` - Hyperlane request context.
1403    ///
1404    /// # Returns
1405    ///
1406    /// - `Status` - `Status::Reject` after stream closes to prevent duplicate response writes.
1407    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
1408        if !ctx.get_request().get_method().is_get() {
1409            return send_hyperlane_bytes(
1410                stream,
1411                ctx,
1412                405,
1413                UPDATE_MIME_JSON,
1414                ERR_BODY_METHOD_NOT_ALLOWED.as_bytes().to_vec(),
1415            )
1416            .await;
1417        }
1418        let Some(state) = resolve_server_state(stream) else {
1419            return send_hyperlane_bytes(
1420                stream,
1421                ctx,
1422                503,
1423                UPDATE_MIME_JSON,
1424                ERR_BODY_UNCONFIGURED.as_bytes().to_vec(),
1425            )
1426            .await;
1427        };
1428        let Some(project) = ctx.try_get_route_param(ROUTE_PARAM_PROJECT) else {
1429            return send_hyperlane_bytes(
1430                stream,
1431                ctx,
1432                400,
1433                UPDATE_MIME_JSON,
1434                ERR_BODY_BAD_REQUEST.as_bytes().to_vec(),
1435            )
1436            .await;
1437        };
1438        let Some(channel) = ctx.try_get_route_param(ROUTE_PARAM_CHANNEL) else {
1439            return send_hyperlane_bytes(
1440                stream,
1441                ctx,
1442                400,
1443                UPDATE_MIME_JSON,
1444                ERR_BODY_BAD_REQUEST.as_bytes().to_vec(),
1445            )
1446            .await;
1447        };
1448        if validate_store_identifier(&project).is_err()
1449            || validate_store_identifier(&channel).is_err()
1450        {
1451            return send_hyperlane_bytes(
1452                stream,
1453                ctx,
1454                400,
1455                UPDATE_MIME_JSON,
1456                ERR_BODY_BAD_REQUEST.as_bytes().to_vec(),
1457            )
1458            .await;
1459        }
1460        state.sync_store_events_to_sse();
1461        let last_event_id: Option<String> = ctx
1462            .get_request()
1463            .try_get_header_front(UPDATE_HDR_LAST_EVENT_ID_LOWER)
1464            .or_else(|| {
1465                ctx.get_request()
1466                    .try_get_query_front(QUERY_KEY_LAST_EVENT_ID)
1467            });
1468        let topic: String = sse_topic_for_channel(&project, &channel);
1469        let Ok(subscription) = state.sse_hub().subscribe(topic.as_str(), None) else {
1470            return send_hyperlane_bytes(
1471                stream,
1472                ctx,
1473                503,
1474                UPDATE_MIME_JSON,
1475                ERR_BODY_UNCONFIGURED.as_bytes().to_vec(),
1476            )
1477            .await;
1478        };
1479        let replay_events: Vec<StoredReleaseEvent> = match last_event_id
1480            .as_deref()
1481            .and_then(|raw: &str| raw.trim().parse::<u64>().ok())
1482        {
1483            Some(cursor) => state
1484                .store()
1485                .read_events_after(&project, &channel, cursor)
1486                .unwrap_or_default(),
1487            None => Vec::new(),
1488        };
1489        let _: Result<(), SseError> =
1490            serve_release_sse_stream(stream, ctx, replay_events, subscription, state.sse_config())
1491                .await;
1492        stream.set_closed(true);
1493        Status::Reject
1494    }
1495}