Skip to main content

DevelopmentNodeEnvironment_MicrosoftVSCodeDependency_22NodeVersion_Bundle_Clean_Debug_ElectronProfile_EsbuildCompiler_Mountain/RPC/CocoonService/TreeView/
EnqueueTreeViewEmit.rs

1//! Coalesce 30+ Mountain → Sky `tree-view/create` emits at boot into a
2//! single batched payload per frame. Uses the channel-drain pattern: a
3//! long-lived flusher wakes on first item, drains immediately, sleeps one
4//! frame (16 ms), drains stragglers, then emits one `{ views: [...] }` batch.
5//! Zero spawns per call; sub-millisecond wake latency.
6
7use std::sync::OnceLock;
8
9use serde_json::{Value, json};
10use tauri::{AppHandle, Emitter};
11use tokio::sync::mpsc::{UnboundedSender, unbounded_channel};
12use CommonLibrary::IPC::SkyEvent::SkyEvent;
13
14use crate::dev_log;
15
16struct TreeViewChannel {
17	Sender:UnboundedSender<(AppHandle, Value)>,
18}
19
20static TV_CH:OnceLock<TreeViewChannel> = OnceLock::new();
21
22fn GetOrInitChannel(Handle:&AppHandle) -> &'static TreeViewChannel {
23	TV_CH.get_or_init(|| {
24		let (Tx, mut Rx) = unbounded_channel::<(AppHandle, Value)>();
25
26		let Channel = SkyEvent::TreeViewCreate.AsStr().to_string();
27
28		tokio::spawn(async move {
29			let mut Buf:Vec<(AppHandle, Value)> = Vec::with_capacity(64);
30
31			loop {
32				match Rx.recv().await {
33					None => break,
34					Some(Item) => Buf.push(Item),
35				}
36
37				Rx.recv_many(&mut Buf, 4096).await;
38
39				tokio::time::sleep(std::time::Duration::from_millis(16)).await;
40
41				Rx.recv_many(&mut Buf, 4096).await;
42
43				if Buf.is_empty() {
44					continue;
45				}
46
47				let Handle = Buf[0].0.clone();
48
49				let Views:Vec<Value> = Buf.drain(..).map(|(_, V)| V).collect();
50
51				let Count = Views.len();
52
53				match Handle.emit(&Channel, json!({ "views": Views })) {
54					Ok(()) => dev_log!("sky-emit", "[SkyEmit] ok channel={} batch={}", Channel, Count),
55					Err(E) => {
56						dev_log!("sky-emit", "[SkyEmit] fail channel={} batch={} error={}", Channel, Count, E)
57					},
58				}
59			}
60		});
61
62		TreeViewChannel { Sender:Tx }
63	})
64}
65
66pub fn Fn(Handle:&AppHandle, Payload:Value) {
67	let Ch = GetOrInitChannel(Handle);
68
69	let _ = Ch.Sender.send((Handle.clone(), Payload));
70}