Skip to main content

DevelopmentNodeEnvironment_MicrosoftVSCodeDependency_22NodeVersion_Bundle_Clean_Debug_ElectronProfile_EsbuildCompiler_Mountain/RPC/CocoonService/TreeView/
EnqueueTreeViewEmit.rs

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