Skip to main content

euv_cli/blender/
impl.rs

1use super::*;
2
3/// Canonical wire-label helpers for `BlenderAssetFormat`.
4impl BlenderAssetFormat {
5    /// Returns the lowercase canonical label for this 3D asset format.
6    ///
7    /// # Returns
8    ///
9    /// - `&'static str` - Lowercase format string (`blend`, `glb`, `gltf`, `euv3d`, or `obj`).
10    #[must_use]
11    pub const fn as_str(&self) -> &'static str {
12        match self {
13            Self::Blend => FORMAT_LABEL_BLEND,
14            Self::Glb => FORMAT_LABEL_GLB,
15            Self::Gltf => FORMAT_LABEL_GLTF,
16            Self::Euv3d => FORMAT_LABEL_EUV3D,
17            Self::Obj => FORMAT_LABEL_OBJ,
18        }
19    }
20}
21
22/// Canonical wire-label helpers for `BlenderBinarySource`.
23impl BlenderBinarySource {
24    /// Returns the canonical kebab-case label describing how the Blender binary was discovered.
25    ///
26    /// # Returns
27    ///
28    /// - `&'static str` - Binary source string.
29    #[must_use]
30    pub const fn as_str(&self) -> &'static str {
31        match self {
32            Self::CliFlag => SOURCE_LABEL_CLI_FLAG,
33            Self::EnvVar => SOURCE_LABEL_ENV_VAR,
34            Self::Path => SOURCE_LABEL_PATH,
35            Self::OsInstall => SOURCE_LABEL_OS_INSTALL,
36            Self::NotFound => SOURCE_LABEL_NOT_FOUND,
37        }
38    }
39}
40
41/// Sensible defaults for `BlenderDoctorConfig`.
42impl Default for BlenderDoctorConfig {
43    /// Returns default Blender doctor settings probing port `9876` and checking glTF exporter readiness.
44    ///
45    /// # Returns
46    ///
47    /// - `Self` - Default `BlenderDoctorConfig`.
48    fn default() -> Self {
49        Self {
50            blender_bin: None,
51            mcp_port: DEFAULT_BLENDER_MCP_PORT,
52            probe_gltf_exporter: true,
53        }
54    }
55}
56
57/// Sensible defaults for `BlenderImportConfig`.
58impl Default for BlenderImportConfig {
59    /// Returns default import settings targeting current directory with 4 QEM LODs, meshlets, and BVH4 enabled.
60    ///
61    /// # Returns
62    ///
63    /// - `Self` - Default `BlenderImportConfig`.
64    fn default() -> Self {
65        Self {
66            input: PathBuf::new(),
67            out_dir: PathBuf::from("."),
68            blender_bin: None,
69            bake: false,
70            lods: DEFAULT_BLENDER_BAKE_LODS,
71            build_meshlets: true,
72            bake_bvh4: true,
73            plan: false,
74        }
75    }
76}
77
78/// Sensible defaults for `BlenderBakeConfig`.
79impl Default for BlenderBakeConfig {
80    /// Returns default `.euv3d` bake settings with 4 QEM LODs, spatial meshlets, and SIMD BVH4 enabled.
81    ///
82    /// # Returns
83    ///
84    /// - `Self` - Default `BlenderBakeConfig`.
85    fn default() -> Self {
86        Self {
87            input: PathBuf::new(),
88            out_file: PathBuf::new(),
89            blender_bin: None,
90            lods: DEFAULT_BLENDER_BAKE_LODS,
91            build_meshlets: true,
92            bake_bvh4: true,
93            plan: false,
94        }
95    }
96}
97
98/// Sensible defaults for `BlenderLiveSyncConfig`.
99impl Default for BlenderLiveSyncConfig {
100    /// Returns default Live-Link HTTP+SSE daemon settings bound to `127.0.0.1:9877`.
101    ///
102    /// # Returns
103    ///
104    /// - `Self` - Default `BlenderLiveSyncConfig`.
105    fn default() -> Self {
106        Self {
107            host: DEFAULT_BLENDER_SYNC_HOST.to_string(),
108            port: DEFAULT_BLENDER_SYNC_PORT,
109            out_dir: None,
110            heartbeat_ms: DEFAULT_BLENDER_HEARTBEAT_MS,
111            replay_capacity: DEFAULT_BLENDER_EVENT_REPLAY_CAP,
112            max_asset_bytes: DEFAULT_BLENDER_MAX_ASSET_BYTES,
113            once: false,
114        }
115    }
116}
117
118/// Sensible defaults for `BlenderWatchConfig`.
119impl Default for BlenderWatchConfig {
120    /// Returns default watch + Live-Link configuration polling every `350ms` on port `9877`.
121    ///
122    /// # Returns
123    ///
124    /// - `Self` - Default `BlenderWatchConfig`.
125    fn default() -> Self {
126        Self {
127            path: PathBuf::from("."),
128            out_dir: PathBuf::from("."),
129            host: DEFAULT_BLENDER_SYNC_HOST.to_string(),
130            port: DEFAULT_BLENDER_SYNC_PORT,
131            blender_bin: None,
132            poll_ms: DEFAULT_BLENDER_WATCH_POLL_MS,
133            lods: DEFAULT_BLENDER_BAKE_LODS,
134            once: false,
135        }
136    }
137}
138
139/// Conversion helpers constructing `BlenderNativeBlendSummary` from `euv_core::BlendInspectionReport`.
140impl BlenderNativeBlendSummary {
141    /// Converts a pure-Rust `BlendInspectionReport` into a JSON-serializable CLI summary.
142    ///
143    /// # Arguments
144    ///
145    /// - `&BlendInspectionReport` - Core `.blend` inspection report.
146    ///
147    /// # Returns
148    ///
149    /// - `Self` - Serializable CLI summary.
150    #[must_use]
151    pub fn from_blend_report(report: &BlendInspectionReport) -> Self {
152        let compression: &str = match report.get_compression() {
153            BlendCompression::None => BLENDER_COMP_NONE,
154            BlendCompression::Gzip => BLENDER_COMP_GZIP,
155            BlendCompression::Zstd => BLENDER_COMP_ZSTD,
156        };
157        Self {
158            version: report.get_version_string().clone(),
159            pointer_size_bytes: report.get_pointer_size_bytes(),
160            is_little_endian: report.get_is_little_endian(),
161            is_large_header_v5: report.get_is_large_header_v5(),
162            compression: compression.to_string(),
163            block_count: report.get_block_count(),
164            dna_struct_count: report.get_dna_struct_count(),
165            scenes: report.get_scenes().clone(),
166            collections: report.get_collections().clone(),
167            objects: report.get_objects().clone(),
168            meshes: report.get_meshes().clone(),
169            materials: report.get_materials().clone(),
170            cameras: report.get_cameras().clone(),
171            lights: report.get_lights().clone(),
172            armatures: report.get_armatures().clone(),
173            actions: report.get_actions().clone(),
174            images: report.get_images().clone(),
175            node_trees: report.get_node_trees().clone(),
176            warnings: report.get_warnings().clone(),
177        }
178    }
179}
180
181/// Conversion helpers constructing `BlenderSceneSummary` from `euv_core::ImportedScene3D`.
182impl BlenderSceneSummary {
183    /// Builds a concise CLI inventory summary from an `ImportedScene3D`.
184    ///
185    /// # Arguments
186    ///
187    /// - `&ImportedScene3D` - Parsed glTF, GLB, `.euv3d`, or converted OBJ scene.
188    ///
189    /// # Returns
190    ///
191    /// - `Self` - Aggregated counts and asset names.
192    #[must_use]
193    pub fn from_imported_scene(scene: &ImportedScene3D) -> Self {
194        let mut total_vertices: usize = 0;
195        let mut total_triangles: usize = 0;
196        for mesh in scene.get_meshes().iter() {
197            total_vertices = total_vertices.saturating_add(mesh.get_vertices().len());
198            total_triangles = total_triangles.saturating_add(mesh.get_indices().len());
199        }
200        let collections: Vec<String> = scene
201            .get_scene_graph()
202            .get_collections()
203            .get_entries()
204            .iter()
205            .map(|entry: &CollectionEntry3D| entry.get_name().clone())
206            .collect();
207        let material_names: Vec<String> = scene
208            .get_materials()
209            .iter()
210            .map(|mat: &PrincipledMaterial3D| mat.get_name().clone())
211            .collect();
212        let animation_names: Vec<String> = scene
213            .get_animations()
214            .iter()
215            .map(|clip: &ImportedAnimationClip3D| clip.get_name().clone())
216            .collect();
217        Self {
218            name: scene.get_name().clone(),
219            generator: scene.get_generator().clone(),
220            node_count: scene.get_scene_graph().get_nodes().len(),
221            collections,
222            mesh_count: scene.get_meshes().len(),
223            total_vertices,
224            total_triangles,
225            material_count: scene.get_materials().len(),
226            material_names,
227            texture_count: scene.get_textures().len(),
228            skin_count: scene.get_skins().len(),
229            animation_count: scene.get_animations().len(),
230            animation_names,
231            camera_count: scene.get_cameras().len(),
232            light_count: scene.get_lights().len(),
233        }
234    }
235}
236
237/// Shared state management and SSE fan-out methods for `BlenderLiveSyncState`.
238#[cfg(feature = "update-server")]
239impl BlenderLiveSyncState {
240    /// Creates a new concurrent Live-Link state backed by a Hyperlane `SseHub`.
241    ///
242    /// # Arguments
243    ///
244    /// - `SseConfig` - SSE heartbeat, retry, and replay configuration.
245    /// - `Option<PathBuf>` - Optional directory mirroring hot-swapped binary assets to disk.
246    /// - `usize` - Maximum accepted binary asset payload size in bytes.
247    /// - `usize` - Maximum replay events retained in memory.
248    ///
249    /// # Returns
250    ///
251    /// - `Self` - Initialized Live-Link daemon state.
252    #[must_use]
253    pub fn new(
254        sse_config: SseConfig,
255        out_dir: Option<PathBuf>,
256        max_asset_bytes: usize,
257        replay_capacity: usize,
258    ) -> Self {
259        let sse_hub: SseHub = SseHub::new(sse_config.clone());
260        Self {
261            sse_hub,
262            sse_config,
263            out_dir,
264            max_asset_bytes: max_asset_bytes.max(1024),
265            replay_capacity: replay_capacity.clamp(8, 2048),
266            next_seq: AtomicU64::new(0),
267            delta_count: AtomicU64::new(0),
268            asset_count: AtomicU64::new(0),
269            event_log: Mutex::new(Vec::new()),
270            assets: RwLock::new(BTreeMap::new()),
271            latest_delta: RwLock::new(None),
272            running: AtomicBool::new(true),
273        }
274    }
275
276    /// Returns a reference to the shared Hyperlane `SseHub`.
277    ///
278    /// # Returns
279    ///
280    /// - `&SseHub` - Live-Link SSE pub/sub hub.
281    #[must_use]
282    pub fn sse_hub(&self) -> &SseHub {
283        let Self { sse_hub, .. } = self;
284        sse_hub
285    }
286
287    /// Returns the active SSE heartbeat and retry configuration.
288    ///
289    /// # Returns
290    ///
291    /// - `&SseConfig` - Active SSE configuration.
292    #[must_use]
293    pub fn sse_config(&self) -> &SseConfig {
294        let Self { sse_config, .. } = self;
295        sse_config
296    }
297
298    /// Returns the maximum permitted binary upload size in bytes.
299    ///
300    /// # Returns
301    ///
302    /// - `usize` - Maximum payload size in bytes.
303    #[must_use]
304    pub fn max_asset_bytes(&self) -> usize {
305        let Self {
306            max_asset_bytes, ..
307        } = *self;
308        max_asset_bytes
309    }
310
311    /// Returns whether the Live-Link daemon is still running.
312    ///
313    /// # Returns
314    ///
315    /// - `bool` - `true` while active.
316    #[must_use]
317    pub fn is_running(&self) -> bool {
318        let Self { running, .. } = self;
319        running.load(Ordering::Acquire)
320    }
321
322    /// Marks the Live-Link daemon as stopped.
323    pub fn stop(&self) {
324        let Self { running, .. } = self;
325        running.store(false, Ordering::Release);
326    }
327
328    /// Returns the latest monotonic event sequence number emitted so far.
329    ///
330    /// # Returns
331    ///
332    /// - `u64` - Latest sequence number (`0` before any events).
333    #[must_use]
334    pub fn latest_seq(&self) -> u64 {
335        let Self { next_seq, .. } = self;
336        next_seq.load(Ordering::Acquire)
337    }
338
339    /// Returns total JSON scene deltas accepted since startup.
340    ///
341    /// # Returns
342    ///
343    /// - `u64` - Delta counter.
344    #[must_use]
345    pub fn delta_count(&self) -> u64 {
346        let Self { delta_count, .. } = self;
347        delta_count.load(Ordering::Acquire)
348    }
349
350    /// Returns total binary asset hot-swaps accepted since startup.
351    ///
352    /// # Returns
353    ///
354    /// - `u64` - Asset hot-swap counter.
355    #[must_use]
356    pub fn asset_count(&self) -> u64 {
357        let Self { asset_count, .. } = self;
358        asset_count.load(Ordering::Acquire)
359    }
360
361    /// Returns sorted asset identifiers currently stored in memory.
362    ///
363    /// # Returns
364    ///
365    /// - `Vec<String>` - Cached asset identifiers.
366    #[must_use]
367    pub fn asset_ids(&self) -> Vec<String> {
368        let Self { assets, .. } = self;
369        assets
370            .read()
371            .ok()
372            .map(
373                |guard: RwLockReadGuard<'_, BTreeMap<String, BlenderStoredAsset>>| {
374                    guard.keys().cloned().collect()
375                },
376            )
377            .unwrap_or_default()
378    }
379
380    /// Retrieves a stored binary asset by identifier.
381    ///
382    /// # Arguments
383    ///
384    /// - `&str` - Sanitized asset identifier.
385    ///
386    /// # Returns
387    ///
388    /// - `Option<BlenderStoredAsset>` - Cloned asset entry if present.
389    #[must_use]
390    pub fn get_asset(&self, asset_id: &str) -> Option<BlenderStoredAsset> {
391        let Self { assets, .. } = self;
392        assets.read().ok().and_then(
393            |guard: RwLockReadGuard<'_, BTreeMap<String, BlenderStoredAsset>>| {
394                guard.get(asset_id).cloned()
395            },
396        )
397    }
398
399    /// Returns the most recent JSON delta payload received from Blender, if any.
400    ///
401    /// # Returns
402    ///
403    /// - `Option<BlenderLiveDeltaPayload>` - Latest delta payload.
404    #[must_use]
405    pub fn latest_delta(&self) -> Option<BlenderLiveDeltaPayload> {
406        let Self { latest_delta, .. } = self;
407        latest_delta
408            .read()
409            .ok()
410            .and_then(|guard: RwLockReadGuard<'_, Option<BlenderLiveDeltaPayload>>| guard.clone())
411    }
412
413    /// Returns buffered replay events strictly newer than `cursor`.
414    ///
415    /// # Arguments
416    ///
417    /// - `u64` - Last sequence number already observed by the SSE client.
418    ///
419    /// # Returns
420    ///
421    /// - `Vec<BlenderLiveEventRecord>` - Ordered replay event records.
422    #[must_use]
423    pub fn events_after(&self, cursor: u64) -> Vec<BlenderLiveEventRecord> {
424        let Self { event_log, .. } = self;
425        event_log
426            .lock()
427            .ok()
428            .map(|guard: MutexGuard<'_, Vec<BlenderLiveEventRecord>>| {
429                guard
430                    .iter()
431                    .filter(|rec: &&BlenderLiveEventRecord| rec.get_seq() > cursor)
432                    .cloned()
433                    .collect()
434            })
435            .unwrap_or_default()
436    }
437
438    /// Records a JSON scene delta, appends it to the replay log, and broadcasts a `blender.delta` SSE event.
439    ///
440    /// # Arguments
441    ///
442    /// - `BlenderLiveDeltaPayload` - Parsed Blender transform/camera/light/material/morph delta.
443    ///
444    /// # Returns
445    ///
446    /// - `io::Result<BlenderLiveEventRecord>` - Recorded SSE envelope.
447    pub fn record_delta(
448        &self,
449        payload: BlenderLiveDeltaPayload,
450    ) -> io::Result<BlenderLiveEventRecord> {
451        let Self {
452            sse_hub,
453            replay_capacity,
454            next_seq,
455            delta_count,
456            event_log,
457            latest_delta,
458            ..
459        } = self;
460        let seq: u64 = next_seq.fetch_add(1, Ordering::AcqRel) + 1;
461        let _: u64 = delta_count.fetch_add(1, Ordering::AcqRel);
462        if let Ok(mut guard) = latest_delta.write() {
463            *guard = Some(payload.clone());
464        }
465        let delta_json: String =
466            to_string(&payload).map_err(|err: serde_json::Error| Error::other(err.to_string()))?;
467        let wrapped_json: String =
468            format!("{{\"seq\":{seq},\"kind\":\"delta\",\"delta\":{delta_json}}}");
469        let record: BlenderLiveEventRecord = BlenderLiveEventRecord::new(
470            seq,
471            BlenderLiveEventKind::Delta,
472            BLENDER_SSE_EVENT_DELTA.to_string(),
473            wrapped_json.clone(),
474        );
475        if let Ok(mut log_guard) = event_log.lock() {
476            log_guard.push(record.clone());
477            if log_guard.len() > *replay_capacity {
478                let overflow: usize = log_guard.len() - *replay_capacity;
479                let _: Vec<BlenderLiveEventRecord> = log_guard.drain(0..overflow).collect();
480            }
481        }
482        let sse_event: SseEvent = SseEvent::new(wrapped_json)
483            .with_id(seq.to_string())
484            .with_event(BLENDER_SSE_EVENT_DELTA);
485        let _: Result<u64, SseError> = sse_hub.publish(BLENDER_LIVE_SSE_TOPIC, sse_event);
486        Ok(record)
487    }
488
489    /// Validates, caches, optionally persists, and broadcasts a hot-swapped binary `.glb` or `.euv3d` asset.
490    ///
491    /// # Arguments
492    ///
493    /// - `&str` - Sanitized asset identifier (`{id}`).
494    /// - `Vec<u8>` - Raw `.glb`, `.gltf`, or `.euv3d` binary payload.
495    ///
496    /// # Returns
497    ///
498    /// - `io::Result<BlenderLiveAssetNotice>` - Verified asset notice broadcast over SSE.
499    pub fn record_asset(
500        &self,
501        asset_id: &str,
502        bytes: Vec<u8>,
503    ) -> io::Result<BlenderLiveAssetNotice> {
504        let Self {
505            sse_hub,
506            out_dir,
507            max_asset_bytes,
508            replay_capacity,
509            next_seq,
510            asset_count,
511            event_log,
512            assets,
513            ..
514        } = self;
515        validate_blender_asset_id(asset_id)?;
516        if bytes.is_empty() {
517            return Err(Error::new(ErrorKind::InvalidInput, ERR_BLENDER_EMPTY_ASSET));
518        }
519        if bytes.len() > *max_asset_bytes {
520            return Err(Error::new(
521                ErrorKind::InvalidData,
522                BLENDER_ERR_PAYLOAD_TOO_LARGE,
523            ));
524        }
525        let (format, mesh_count, triangle_count): (BlenderAssetFormat, usize, usize) =
526            validate_live_asset_payload(&bytes)?;
527        let disk_path: Option<String> = if let Some(dir) = out_dir.as_ref() {
528            let ext: &str = format.as_str();
529            let target: PathBuf = dir.join(format!("{asset_id}.{ext}"));
530            atomic_write_synced(&target, &bytes)?;
531            Some(target.display().to_string())
532        } else {
533            None
534        };
535        let seq: u64 = next_seq.fetch_add(1, Ordering::AcqRel) + 1;
536        let _: u64 = asset_count.fetch_add(1, Ordering::AcqRel);
537        let sha256: String = sha256_hex(&bytes);
538        let notice: BlenderLiveAssetNotice = BlenderLiveAssetNotice {
539            seq,
540            asset_id: asset_id.to_string(),
541            format,
542            size_bytes: bytes.len(),
543            sha256,
544            mesh_count,
545            triangle_count,
546            asset_url: format!("/blender/asset/{asset_id}"),
547            disk_path,
548        };
549        if let Ok(mut map_guard) = assets.write() {
550            let _: Option<BlenderStoredAsset> = map_guard.insert(
551                asset_id.to_string(),
552                BlenderStoredAsset {
553                    notice: notice.clone(),
554                    bytes,
555                },
556            );
557        }
558        let notice_json: String =
559            to_string(&notice).map_err(|err: serde_json::Error| Error::other(err.to_string()))?;
560        let record: BlenderLiveEventRecord = BlenderLiveEventRecord::new(
561            seq,
562            BlenderLiveEventKind::Asset,
563            BLENDER_SSE_EVENT_ASSET.to_string(),
564            notice_json.clone(),
565        );
566        if let Ok(mut log_guard) = event_log.lock() {
567            log_guard.push(record);
568            if log_guard.len() > *replay_capacity {
569                let overflow: usize = log_guard.len() - *replay_capacity;
570                let _: Vec<BlenderLiveEventRecord> = log_guard.drain(0..overflow).collect();
571            }
572        }
573        let sse_event: SseEvent = SseEvent::new(notice_json)
574            .with_id(seq.to_string())
575            .with_event(BLENDER_SSE_EVENT_ASSET);
576        let _: Result<u64, SseError> = sse_hub.publish(BLENDER_LIVE_SSE_TOPIC, sse_event);
577        Ok(notice)
578    }
579
580    /// Builds a machine-readable status report for this Live-Link server bound at `base_url`.
581    ///
582    /// # Arguments
583    ///
584    /// - `&str` - Base HTTP URL (`http://host:port`).
585    /// - `bool` - Whether the command ran in `--once` smoke mode.
586    ///
587    /// # Returns
588    ///
589    /// - `BlenderLiveSyncReport` - Snapshot of routes, counters, and cached asset IDs.
590    #[must_use]
591    pub fn build_report(&self, base_url: &str, once: bool) -> BlenderLiveSyncReport {
592        BlenderLiveSyncReport {
593            url: base_url.to_string(),
594            delta_url: format!("{base_url}{BLENDER_ROUTE_DELTA}"),
595            asset_url: format!("{base_url}{BLENDER_ROUTE_ASSET}"),
596            events_url: format!("{base_url}{BLENDER_ROUTE_EVENTS}"),
597            status_url: format!("{base_url}{BLENDER_ROUTE_STATUS}"),
598            latest_seq: self.latest_seq(),
599            delta_count: self.delta_count(),
600            asset_count: self.asset_count(),
601            asset_ids: self.asset_ids(),
602            once,
603        }
604    }
605}
606
607/// Lifecycle control methods on `BlenderLiveSyncHandle`.
608#[cfg(feature = "update-server")]
609impl BlenderLiveSyncHandle {
610    /// Returns the concrete bound `SocketAddr` of the running Hyperlane Live-Link daemon.
611    ///
612    /// # Returns
613    ///
614    /// - `SocketAddr` - Bound TCP socket address.
615    #[must_use]
616    pub fn address(&self) -> SocketAddr {
617        let Self { address, .. } = *self;
618        address
619    }
620
621    /// Returns the base HTTP URL (`http://host:port`) of this Live-Link server.
622    ///
623    /// # Returns
624    ///
625    /// - `String` - Base HTTP URL.
626    #[must_use]
627    pub fn url(&self) -> String {
628        format!("http://{}", self.address())
629    }
630
631    /// Returns a reference to the shared `BlenderLiveSyncState`.
632    ///
633    /// # Returns
634    ///
635    /// - `&Arc<BlenderLiveSyncState>` - Shared Live-Link state.
636    #[must_use]
637    pub fn state(&self) -> &Arc<BlenderLiveSyncState> {
638        let Self { state, .. } = self;
639        state
640    }
641
642    /// Returns whether this Live-Link server is currently running.
643    ///
644    /// # Returns
645    ///
646    /// - `bool` - `true` while active.
647    #[must_use]
648    pub fn is_running(&self) -> bool {
649        let Self { state, .. } = self;
650        state.is_running()
651    }
652
653    /// Produces a machine-readable `BlenderLiveSyncReport` for this live server handle.
654    ///
655    /// # Arguments
656    ///
657    /// - `bool` - Whether this invocation runs in `--once` validation mode.
658    ///
659    /// # Returns
660    ///
661    /// - `BlenderLiveSyncReport` - Active Live-Link report.
662    #[must_use]
663    pub fn report(&self, once: bool) -> BlenderLiveSyncReport {
664        let base_url: String = self.url();
665        self.state().build_report(&base_url, once)
666    }
667
668    /// Cleanly stops the Hyperlane Live-Link listener, unregisters its address, and shuts down the Tokio runtime.
669    pub fn shutdown(&mut self) {
670        let Self {
671            address,
672            state,
673            control,
674            runtime,
675        } = self;
676        state.stop();
677        unregister_blender_live_sync_state(*address);
678        if let Some(ctrl) = control.take()
679            && let Some(rt) = runtime.as_ref()
680        {
681            rt.block_on(async move {
682                ctrl.shutdown().await;
683            });
684        }
685        if let Some(rt) = runtime.take() {
686            rt.shutdown_timeout(Duration::from_millis(250));
687        }
688    }
689}
690
691/// Automatic listener cleanup when `BlenderLiveSyncHandle` is dropped.
692#[cfg(feature = "update-server")]
693impl Drop for BlenderLiveSyncHandle {
694    /// Stops the Live-Link Hyperlane listener cleanly on drop.
695    fn drop(&mut self) {
696        self.shutdown();
697    }
698}
699
700/// Hyperlane `ServerHook` ingesting JSON scene deltas at `POST /blender/delta`.
701#[cfg(feature = "update-server")]
702impl ServerHook for BlenderDeltaRouteHook {
703    /// Constructs a stateless `BlenderDeltaRouteHook`.
704    ///
705    /// # Arguments
706    ///
707    /// - `&mut Stream` - Incoming client stream.
708    /// - `&mut Context` - Active Hyperlane request context.
709    ///
710    /// # Returns
711    ///
712    /// - `Self` - Hook instance.
713    async fn new(_: &mut Stream, _: &mut Context) -> Self {
714        Self
715    }
716
717    /// Validates incoming JSON delta payloads and broadcasts `blender.delta` SSE frames.
718    ///
719    /// # Arguments
720    ///
721    /// - `&mut Stream` - Active client stream.
722    /// - `&mut Context` - Active Hyperlane request context.
723    ///
724    /// # Returns
725    ///
726    /// - `Status` - Request lifecycle status.
727    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
728        if ctx.get_request().get_method().is_options() {
729            return send_hyperlane_bytes(stream, ctx, 204, BLENDER_MIME_JSON, Vec::new()).await;
730        }
731        if !ctx.get_request().get_method().is_post() {
732            return send_hyperlane_bytes(
733                stream,
734                ctx,
735                405,
736                BLENDER_MIME_JSON,
737                BLENDER_ERR_METHOD_NOT_ALLOWED.as_bytes().to_vec(),
738            )
739            .await;
740        }
741        let Some(state) = resolve_blender_live_sync_state(stream) else {
742            return send_hyperlane_bytes(
743                stream,
744                ctx,
745                503,
746                BLENDER_MIME_JSON,
747                BLENDER_ERR_UNCONFIGURED.as_bytes().to_vec(),
748            )
749            .await;
750        };
751        let raw_body: String = ctx.get_request().get_body_string();
752        let Ok(payload) = from_str::<BlenderLiveDeltaPayload>(&raw_body) else {
753            return send_hyperlane_bytes(
754                stream,
755                ctx,
756                400,
757                BLENDER_MIME_JSON,
758                BLENDER_ERR_BAD_REQUEST.as_bytes().to_vec(),
759            )
760            .await;
761        };
762        match state.record_delta(payload) {
763            Ok(rec) => {
764                let body: String = format!(
765                    "{{\"ok\":true,\"seq\":{},\"kind\":\"delta\"}}",
766                    rec.get_seq()
767                );
768                let _: &mut Response = ctx
769                    .get_mut_response()
770                    .set_header(CACHE_CONTROL, BLENDER_CACHE_NO_CACHE);
771                send_hyperlane_bytes(stream, ctx, 200, BLENDER_MIME_JSON, body.into_bytes()).await
772            }
773            Err(_) => {
774                send_hyperlane_bytes(
775                    stream,
776                    ctx,
777                    400,
778                    BLENDER_MIME_JSON,
779                    BLENDER_ERR_BAD_REQUEST.as_bytes().to_vec(),
780                )
781                .await
782            }
783        }
784    }
785}
786
787/// Hyperlane `ServerHook` handling binary `.glb`/`.euv3d` hot-swaps (`POST`) and fetches (`GET`/`HEAD`) at `/blender/asset/{id}`.
788#[cfg(feature = "update-server")]
789impl ServerHook for BlenderAssetRouteHook {
790    /// Constructs a stateless `BlenderAssetRouteHook`.
791    ///
792    /// # Arguments
793    ///
794    /// - `&mut Stream` - Incoming client stream.
795    /// - `&mut Context` - Active Hyperlane request context.
796    ///
797    /// # Returns
798    ///
799    /// - `Self` - Hook instance.
800    async fn new(_: &mut Stream, _: &mut Context) -> Self {
801        Self
802    }
803
804    /// Stores uploaded `.glb`/`.euv3d` binaries (`POST`) or serves the latest cached asset (`GET`/`HEAD`).
805    ///
806    /// # Arguments
807    ///
808    /// - `&mut Stream` - Active client stream.
809    /// - `&mut Context` - Active Hyperlane request context.
810    ///
811    /// # Returns
812    ///
813    /// - `Status` - Request lifecycle status.
814    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
815        if ctx.get_request().get_method().is_options() {
816            return send_hyperlane_bytes(stream, ctx, 204, BLENDER_MIME_JSON, Vec::new()).await;
817        }
818        let Some(state) = resolve_blender_live_sync_state(stream) else {
819            return send_hyperlane_bytes(
820                stream,
821                ctx,
822                503,
823                BLENDER_MIME_JSON,
824                BLENDER_ERR_UNCONFIGURED.as_bytes().to_vec(),
825            )
826            .await;
827        };
828        let Some(asset_id) = ctx.try_get_route_param(BLENDER_ROUTE_PARAM_ID) else {
829            return send_hyperlane_bytes(
830                stream,
831                ctx,
832                400,
833                BLENDER_MIME_JSON,
834                BLENDER_ERR_BAD_REQUEST.as_bytes().to_vec(),
835            )
836            .await;
837        };
838        if validate_blender_asset_id(&asset_id).is_err() {
839            return send_hyperlane_bytes(
840                stream,
841                ctx,
842                400,
843                BLENDER_MIME_JSON,
844                BLENDER_ERR_BAD_REQUEST.as_bytes().to_vec(),
845            )
846            .await;
847        }
848        if ctx.get_request().get_method().is_post() {
849            let body: Vec<u8> = ctx.get_request().get_body().clone();
850            if body.len() > state.max_asset_bytes() {
851                return send_hyperlane_bytes(
852                    stream,
853                    ctx,
854                    413,
855                    BLENDER_MIME_JSON,
856                    BLENDER_ERR_PAYLOAD_TOO_LARGE.as_bytes().to_vec(),
857                )
858                .await;
859            }
860            return match state.record_asset(&asset_id, body) {
861                Ok(notice) => {
862                    let encoded: Vec<u8> = to_vec(&notice).unwrap_or_default();
863                    let _: &mut Response = ctx
864                        .get_mut_response()
865                        .set_header(CACHE_CONTROL, BLENDER_CACHE_NO_CACHE);
866                    send_hyperlane_bytes(stream, ctx, 200, BLENDER_MIME_JSON, encoded).await
867                }
868                Err(_) => {
869                    send_hyperlane_bytes(
870                        stream,
871                        ctx,
872                        400,
873                        BLENDER_MIME_JSON,
874                        BLENDER_ERR_BAD_REQUEST.as_bytes().to_vec(),
875                    )
876                    .await
877                }
878            };
879        }
880        let is_read: bool = {
881            let method: &Method = ctx.get_request().get_method();
882            method.is_get() || method.is_head()
883        };
884        if !is_read {
885            return send_hyperlane_bytes(
886                stream,
887                ctx,
888                405,
889                BLENDER_MIME_JSON,
890                BLENDER_ERR_METHOD_NOT_ALLOWED.as_bytes().to_vec(),
891            )
892            .await;
893        }
894        let Some(stored) = state.get_asset(&asset_id) else {
895            return send_hyperlane_bytes(
896                stream,
897                ctx,
898                404,
899                BLENDER_MIME_JSON,
900                BLENDER_ERR_NOT_FOUND.as_bytes().to_vec(),
901            )
902            .await;
903        };
904        let mime: &str = match stored.get_notice().get_format() {
905            BlenderAssetFormat::Glb => BLENDER_MIME_GLB,
906            BlenderAssetFormat::Gltf => BLENDER_MIME_JSON,
907            _ => BLENDER_MIME_OCTET,
908        };
909        let etag: String = format!("\"{}\"", stored.get_notice().get_sha256());
910        let _: &mut Response = ctx
911            .get_mut_response()
912            .set_header(CACHE_CONTROL, BLENDER_CACHE_NO_CACHE)
913            .set_header(BLENDER_HDR_ETAG, etag);
914        send_hyperlane_bytes(stream, ctx, 200, mime, stored.get_bytes().clone()).await
915    }
916}
917
918/// Hyperlane `ServerHook` streaming `blender.delta` and `blender.asset` SSE events at `GET /blender/events`.
919#[cfg(feature = "update-server")]
920impl ServerHook for BlenderEventsRouteHook {
921    /// Constructs a stateless `BlenderEventsRouteHook`.
922    ///
923    /// # Arguments
924    ///
925    /// - `&mut Stream` - Incoming client stream.
926    /// - `&mut Context` - Active Hyperlane request context.
927    ///
928    /// # Returns
929    ///
930    /// - `Self` - Hook instance.
931    async fn new(_: &mut Stream, _: &mut Context) -> Self {
932        Self
933    }
934
935    /// Streams `Last-Event-ID` replay frames followed by live Blender Live-Link SSE notifications.
936    ///
937    /// # Arguments
938    ///
939    /// - `&mut Stream` - Long-lived client SSE stream.
940    /// - `&mut Context` - Active Hyperlane request context.
941    ///
942    /// # Returns
943    ///
944    /// - `Status` - `Status::Reject` after closing stream cleanly.
945    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
946        if ctx.get_request().get_method().is_options() {
947            return send_hyperlane_bytes(stream, ctx, 204, BLENDER_MIME_JSON, Vec::new()).await;
948        }
949        if !ctx.get_request().get_method().is_get() {
950            return send_hyperlane_bytes(
951                stream,
952                ctx,
953                405,
954                BLENDER_MIME_JSON,
955                BLENDER_ERR_METHOD_NOT_ALLOWED.as_bytes().to_vec(),
956            )
957            .await;
958        }
959        let Some(state) = resolve_blender_live_sync_state(stream) else {
960            return send_hyperlane_bytes(
961                stream,
962                ctx,
963                503,
964                BLENDER_MIME_JSON,
965                BLENDER_ERR_UNCONFIGURED.as_bytes().to_vec(),
966            )
967            .await;
968        };
969        let last_event_id: Option<String> = ctx
970            .get_request()
971            .try_get_header_front(BLENDER_HDR_LAST_EVENT_ID)
972            .or_else(|| {
973                ctx.get_request()
974                    .try_get_query_front(BLENDER_QUERY_LAST_EVENT_ID)
975            });
976        let Ok(subscription) = state.sse_hub().subscribe(BLENDER_LIVE_SSE_TOPIC, None) else {
977            return send_hyperlane_bytes(
978                stream,
979                ctx,
980                503,
981                BLENDER_MIME_JSON,
982                BLENDER_ERR_UNCONFIGURED.as_bytes().to_vec(),
983            )
984            .await;
985        };
986        let replay: Vec<BlenderLiveEventRecord> = match last_event_id
987            .as_deref()
988            .and_then(|raw: &str| raw.trim().parse::<u64>().ok())
989        {
990            Some(cursor) => state.events_after(cursor),
991            None => Vec::new(),
992        };
993        let _: Result<(), SseError> =
994            serve_blender_sse_stream(stream, ctx, replay, subscription, state.sse_config()).await;
995        stream.set_closed(true);
996        Status::Reject
997    }
998}
999
1000/// Hyperlane `ServerHook` serving JSON Live-Link status diagnostics at `GET /blender/status` and `GET /healthz`.
1001#[cfg(feature = "update-server")]
1002impl ServerHook for BlenderStatusRouteHook {
1003    /// Constructs a stateless `BlenderStatusRouteHook`.
1004    ///
1005    /// # Arguments
1006    ///
1007    /// - `&mut Stream` - Incoming client stream.
1008    /// - `&mut Context` - Active Hyperlane request context.
1009    ///
1010    /// # Returns
1011    ///
1012    /// - `Self` - Hook instance.
1013    async fn new(_: &mut Stream, _: &mut Context) -> Self {
1014        Self
1015    }
1016
1017    /// Serves a JSON snapshot of active Live-Link endpoints, event counters, and cached asset IDs.
1018    ///
1019    /// # Arguments
1020    ///
1021    /// - `&mut Stream` - Active client stream.
1022    /// - `&mut Context` - Active Hyperlane request context.
1023    ///
1024    /// # Returns
1025    ///
1026    /// - `Status` - Request lifecycle status.
1027    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
1028        if ctx.get_request().get_method().is_options() {
1029            return send_hyperlane_bytes(stream, ctx, 204, BLENDER_MIME_JSON, Vec::new()).await;
1030        }
1031        let method_ok: bool = {
1032            let method: &Method = ctx.get_request().get_method();
1033            method.is_get() || method.is_head()
1034        };
1035        if !method_ok {
1036            return send_hyperlane_bytes(
1037                stream,
1038                ctx,
1039                405,
1040                BLENDER_MIME_JSON,
1041                BLENDER_ERR_METHOD_NOT_ALLOWED.as_bytes().to_vec(),
1042            )
1043            .await;
1044        }
1045        let Some(state) = resolve_blender_live_sync_state(stream) else {
1046            return send_hyperlane_bytes(
1047                stream,
1048                ctx,
1049                503,
1050                BLENDER_MIME_JSON,
1051                BLENDER_ERR_UNCONFIGURED.as_bytes().to_vec(),
1052            )
1053            .await;
1054        };
1055        let base_url: String = stream
1056            .get_local_addr()
1057            .map(|addr: SocketAddr| format!("http://{addr}"))
1058            .unwrap_or_else(|_| {
1059                format!("http://{DEFAULT_BLENDER_SYNC_HOST}:{DEFAULT_BLENDER_SYNC_PORT}")
1060            });
1061        let report: BlenderLiveSyncReport = state.build_report(&base_url, false);
1062        let payload: Vec<u8> = to_vec(&report).unwrap_or_default();
1063        let _: &mut Response = ctx
1064            .get_mut_response()
1065            .set_header(CACHE_CONTROL, BLENDER_CACHE_NO_CACHE);
1066        send_hyperlane_bytes(stream, ctx, 200, BLENDER_MIME_JSON, payload).await
1067    }
1068}