lingxia-lxapp 0.6.5

LxApp (lightweight application) container and runtime for LingXia framework
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
use crate::bridge::{self, AppServiceCommand};
use crate::error::LxAppError;
use crate::lx;
use crate::lxapp::LxApp;
use crate::{error, info};

use rong::{JSContext, JSResult, JSRuntime, JSValue, RongJSError, Source, error::HostError};
use rong_console as console;
use rong_http as http;

use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex, mpsc};
use std::time::Duration;
use tokio::sync::oneshot;

#[path = "app.rs"]
mod app;
use crate::lifecycle::AppServiceEvent;

#[path = "event_bus.rs"]
pub(crate) mod event_bus;

#[path = "page.rs"]
mod page;
use crate::lifecycle::PageServiceEvent;
pub use page::PageSvc;

#[path = "plugin.rs"]
mod plugin;

#[path = "runtime_ctx.rs"]
mod runtime_ctx;
pub(crate) use runtime_ctx::set_app_svc_for_ctx;
use runtime_ctx::{register_app_ctx, remove_app_ctx, with_app_svc, with_page_svc_map};

/// Message type for LxApp service system
pub(crate) enum ServiceMessage {
    // Create a new AppService (JS runtime) for this LxApp instance
    CreateAppSvc {
        lxapp: Arc<LxApp>,
    },
    // Terminate AppService for this LxApp instance. ACK returned when cleanup completes.
    TerminateAppSvc {
        lxapp: Arc<LxApp>,
        ack_tx: mpsc::Sender<()>,
    },
    // Create a new page service
    CreatePage {
        lxapp: Arc<LxApp>,
        path: String,
        page_instance_id: Option<String>,
        ack_tx: oneshot::Sender<Result<(), String>>,
    },
    // Delete a page service (object-identity safe)
    TerminatePage {
        lxapp: Arc<LxApp>,
        path: String,
        page_instance_id: Option<String>,
    },
    // Call predefined AppService event (typed)
    CallAppSvcEvent {
        lxapp: Arc<LxApp>,
        event: AppServiceEvent,
        args: Option<String>,
    },
    // Call function of PageInstance service with different sources
    CallPageSvc {
        lxapp: Arc<LxApp>,
        path: String,
        page_instance_id: Option<String>,
        source: PageSvcSource,
    },
    // Call typed page event
    CallPageSvcEvent {
        lxapp: Arc<LxApp>,
        path: String,
        page_instance_id: Option<String>,
        event: PageServiceEvent,
        args: Option<String>,
    },
    // Native -> JS event dispatch via event bus (e.g., video context)
    DispatchAppBusEvent {
        lxapp: Arc<LxApp>,
        event: event_bus::AppBusEvent,
    },
    Eval {
        lxapp: Arc<LxApp>,
        script: String,
        tx: oneshot::Sender<Result<String, LxAppError>>,
    },
}

/// Enum representing different sources of PageInstance service calls
pub enum PageSvcSource {
    /// Call from view layer after the top-level bridge has parsed and routed it.
    Bridge {
        message: crate::bridge::AppServiceCommand,
    },
    /// Call from native layer with explicit function name and args
    Native {
        name: String,
        args: Option<String>, // JSON string of arguments
    },
}

pub(crate) struct WorkerService {
    pub(crate) svc: ServiceMessage,
}

// Handles a typed AppService event
async fn handle_app_service_event(
    worker_id: usize,
    ctx: &JSContext,
    appid: String,
    event: AppServiceEvent,
    args: Option<String>,
) {
    // Resolve AppSvc from registry via JSContext and clone it for use in this async handler.
    let svc = match with_app_svc(ctx, |svc| Ok(svc.clone())) {
        Ok(svc) => svc,
        Err(e) => {
            error!("[Worker {}] App service not loaded: {}", worker_id, e).with_appid(appid);
            return;
        }
    };

    if matches!(
        event,
        AppServiceEvent::OnLaunch
            | AppServiceEvent::OnShow
            | AppServiceEvent::OnHide
            | AppServiceEvent::OnUserCaptureScreen
    ) {
        if let Err(e) = svc.call_event(ctx, event, args.clone()).await {
            error!(
                "[Worker {}] App service event '{}' failed, Error: {}",
                worker_id, event, e
            )
            .with_appid(appid);
        }
    }
}

fn js_value_to_json_string(value: JSValue) -> Result<String, LxAppError> {
    if value.is_undefined() || value.is_null() {
        return Ok("null".to_string());
    }
    if value.is_boolean() {
        let value: bool = value.into_value().try_into().map_err(LxAppError::from)?;
        return Ok(if value { "true" } else { "false" }.to_string());
    }
    if value.is_number() {
        let value: f64 = value.into_value().try_into().map_err(LxAppError::from)?;
        let number = serde_json::Number::from_f64(value)
            .ok_or_else(|| LxAppError::Runtime("eval returned invalid number".to_string()))?;
        return Ok(number.to_string());
    }
    if value.is_string() {
        let value: String = value.into_value().try_into().map_err(LxAppError::from)?;
        return serde_json::to_string(&value).map_err(LxAppError::from);
    }
    if let Some(object) = value.into_object() {
        return object.to_json_string().map_err(LxAppError::from);
    }
    Ok("null".to_string())
}

fn eval_error_from_rong(ctx: &JSContext, error: RongJSError) -> LxAppError {
    if let Some(thrown) = error.thrown_value(ctx) {
        if thrown.is_string() {
            let value: Result<String, RongJSError> = thrown.into_value().try_into();
            if let Ok(value) = value {
                return LxAppError::RongJS(value);
            }
        } else if let Some(object) = thrown.into_object() {
            let name = object
                .get::<_, String>("name")
                .unwrap_or_else(|_| "Error".to_string());
            if let Ok(message) = object.get::<_, String>("message") {
                return LxAppError::RongJS(format!("{name}: {message}"));
            }
        }
    }
    LxAppError::from(error)
}

async fn eval_logic_script(ctx: &JSContext, script: &str) -> Result<String, LxAppError> {
    let expression_json = serde_json::to_string(script).map_err(LxAppError::from)?;
    let expression = format!(
        r#"(async () => {{
  return await eval({expression_json});
}})()"#
    );
    match ctx
        .eval_async::<JSValue>(Source::from_bytes(expression))
        .await
    {
        Ok(value) => return js_value_to_json_string(value),
        Err(expression_error) if script_may_be_function_body(script, &expression_error) => {
            let body = format!(
                r#"(async () => {{
{script}
}})()"#
            );
            let value = ctx
                .eval_async::<JSValue>(Source::from_bytes(body))
                .await
                .map_err(|body_error| eval_error_from_rong(ctx, body_error))?;
            js_value_to_json_string(value)
        }
        Err(expression_error) => Err(eval_error_from_rong(ctx, expression_error)),
    }
}

fn script_may_be_function_body(script: &str, expression_error: &RongJSError) -> bool {
    if !expression_error
        .to_string()
        .to_ascii_lowercase()
        .contains("syntax")
    {
        return false;
    }
    let trimmed = script.trim_start();
    trimmed.starts_with("return")
        || trimmed.starts_with("const ")
        || trimmed.starts_with("let ")
        || trimmed.starts_with("var ")
        || trimmed.starts_with("if ")
        || trimmed.starts_with("for ")
        || trimmed.starts_with("while ")
        || trimmed.starts_with("try ")
        || trimmed.contains(';')
}

// Handles a bridge-routed message that must enter the JS runtime worker.
async fn handle_bridge_source(
    page_svc: &PageSvc,
    message: AppServiceCommand,
) -> Result<(), LxAppError> {
    match message {
        AppServiceCommand::Ready => {
            page_svc.handle_bridge_ready().await;
            Ok(())
        }
        AppServiceCommand::StateSnapshot { id, scope } => {
            let bridge = page_svc.bridge();
            match page_svc.get_state_snapshot(scope.as_deref()).await {
                Ok(snapshot) => bridge.send_res_ok(page_svc, id, snapshot)?,
                Err(err) => bridge.send_res_err(
                    page_svc,
                    id,
                    bridge::BRIDGE_INTERNAL_ERROR,
                    Some(err.to_string()),
                    None,
                )?,
            }
            Ok(())
        }
        AppServiceCommand::Req {
            id,
            method,
            params_json,
            cancel_rx,
        } => {
            let bridge = page_svc.bridge();
            match page_svc
                .handle_req(&id, &method, params_json.as_deref(), cancel_rx)
                .await
            {
                Ok(json) => bridge.send_res_ok(page_svc, id, json)?,
                Err(err) => bridge.send_res_err(page_svc, id, &err.code, err.message, err.data)?,
            }
            Ok(())
        }
        AppServiceCommand::Notify {
            method,
            params_json,
        } => {
            page_svc
                .handle_notify(&method, params_json.as_deref())
                .await;
            Ok(())
        }
        AppServiceCommand::ChOpen {
            id,
            topic,
            params_json,
        } => {
            let bridge = page_svc.bridge();
            match page_svc
                .handle_ch_open(&id, &topic, params_json.as_deref())
                .await
            {
                Ok(()) => bridge.send_ch_ack_ok(page_svc, id)?,
                Err(err) => {
                    bridge.send_ch_ack_err(page_svc, id, &err.code, err.message, err.data)?
                }
            }
            Ok(())
        }
        AppServiceCommand::ChData { id, payload_json } => {
            if let Err(err) = page_svc.handle_ch_data(&id, &payload_json).await {
                error!("channel '{}' data handler failed: {}", id, err.code)
                    .with_appid(page_svc.page.appid())
                    .with_path(page_svc.page.path());
            }
            Ok(())
        }
        AppServiceCommand::ChClose { id, code, reason } => {
            page_svc
                .handle_ch_close(&id, code.as_deref(), reason.as_deref())
                .await;
            Ok(())
        }
        AppServiceCommand::StateAck { scope, rev } => {
            page_svc.handle_state_ack(scope, rev).await;
            Ok(())
        }
    }
}

// Handles a call from native code to a PageInstance service function
async fn handle_native_source(
    page_svc: &PageSvc,
    appid: String,
    name: String,
    args: Option<String>,
) {
    let ctx = page_svc.get_ctx();
    let page_svc_clone = page_svc.clone();
    let name_clone = name.clone();

    let task = async move {
        if let Err(e) = page_svc_clone
            .call_or_event_from_native(&ctx, &name, args.as_deref())
            .await
        {
            crate::error!("PageInstance service call '{}' failed: {}", name_clone, e)
                .with_appid(appid)
                .with_path(page_svc_clone.page.path());
        }
    };
    rong::spawn_local(task);
}

/// The core logic for a persistent worker task.
/// This function is a handler for messages received by the worker.
pub(crate) async fn lxapp_service_handler(
    worker_id: usize,
    runtime: JSRuntime,
    message: ServiceMessage,
    current_ctx: &mut Option<JSContext>,
) {
    match message {
        ServiceMessage::CreateAppSvc { lxapp } => {
            let ctx = runtime.context();

            // Register LxApp runtime context and bind identity to JSContext
            register_app_ctx(&runtime, &ctx, &lxapp);

            // register PageInstance, App and getApp function
            if let Err(e) = app::init(&ctx) {
                error!(
                    "[Worker {}] Failed to initialize App runtime: {}",
                    worker_id, e
                )
                .with_appid(lxapp.appid.clone());
                return;
            }
            if let Err(e) = page::init(&ctx) {
                error!(
                    "[Worker {}] Failed to initialize PageInstance runtime: {}",
                    worker_id, e
                )
                .with_appid(lxapp.appid.clone());
                return;
            }
            if let Err(e) = plugin::init(&ctx) {
                error!(
                    "[Worker {}] Failed to initialize Plugin runtime: {}",
                    worker_id, e
                )
                .with_appid(lxapp.appid.clone());
                return;
            }
            event_bus::init(&ctx);

            let app_ctx = LxAppCtx::new(lxapp.clone());

            console::set_trace_context(
                &ctx,
                console::ConsoleTraceContext {
                    namespace: Some(lxapp.appid.clone()),
                    scope: Some("appservice".to_string()),
                },
            );

            // Set network access guard to prevent unauthorized domain access
            http::set_network_access_guard(Box::new(app_ctx));

            let _ = rong_modules::init(&ctx);
            let _ = lx::init(&ctx);

            // Execute a closure with access to the list of registered extensions.
            crate::lx::extension::with_registered_extensions(|user_extensions| {
                info!(
                    "[Worker {}] Initializing {} user-registered extensions",
                    worker_id,
                    user_extensions.len()
                )
                .with_appid(lxapp.appid.clone());

                // Iterate through the list and initialize each extension.
                for (index, user_extension) in user_extensions.iter().enumerate() {
                    if let Err(e) = user_extension.init(&ctx) {
                        error!(
                            "[Worker {}] Failed to initialize user extension #{}: {}",
                            worker_id, index, e
                        )
                        .with_appid(lxapp.appid.clone());
                    }
                }
            });

            info!("[Worker {}] Created JS context", worker_id).with_appid(lxapp.appid.clone());

            match lxapp.logic_entry_source(&ctx).await {
                Ok(Some(js)) => match ctx.eval::<()>(js) {
                    Ok(_) => {
                        info!("[Worker {}] Successfully loaded logic JS", worker_id)
                            .with_appid(lxapp.appid.clone());
                    }
                    Err(e) => {
                        info!("[Worker {}] eval logic JS  failed: {}", worker_id, e)
                            .with_appid(lxapp.appid.clone());
                    }
                },
                Ok(None) => {
                    info!(
                        "[Worker {}] Logic disabled; skipping JS bootstrap",
                        worker_id
                    )
                    .with_appid(lxapp.appid.clone());
                }
                Err(e) => {
                    error!("[Worker {}] Failed to load logic source: {}", worker_id, e)
                        .with_appid(lxapp.appid.clone());
                }
            }

            *current_ctx = Some(ctx.clone());
        }
        ServiceMessage::TerminateAppSvc { lxapp, ack_tx } => {
            // Drop the JSContext directly to release all JS/PageSvc resources.
            if current_ctx.is_some() {
                if let Some(ctx) = current_ctx.as_ref() {
                    console::clear_trace_context(ctx);
                }
                *current_ctx = None;
                info!("[Worker {}] Removed LxApp context ", worker_id)
                    .with_appid(lxapp.appid.clone());
            }
            // Clear guards on app terminate so the previous LxAppCtx is dropped immediately.
            http::set_network_access_guard(Box::new(DenyAllNetworkAccessGuard));
            // Remove runtime context for this app so that all associated resources can be dropped.
            remove_app_ctx(&runtime, &lxapp.appid);
            // ACK back to the caller that cleanup is complete
            let _ = ack_tx.send(());
        }
        ServiceMessage::CreatePage {
            lxapp,
            path,
            page_instance_id,
            ack_tx,
        } => {
            let result = if let Some(ctx) = current_ctx.as_ref() {
                match PageSvc::create_in_ctx(ctx, &path, page_instance_id.as_deref()).await {
                    Ok(()) => Ok(()),
                    Err(e) => {
                        let msg = e.to_string();
                        error!("[Worker {}] create_in_ctx failed: {}", worker_id, e)
                            .with_appid(lxapp.appid.clone())
                            .with_path(&path);
                        Err(msg)
                    }
                }
            } else {
                let msg = "JS context not available".to_string();
                error!("[Worker {}] create_in_ctx: {}", worker_id, msg)
                    .with_appid(lxapp.appid.clone())
                    .with_path(&path);
                Err(msg)
            };
            let _ = ack_tx.send(result);
        }
        ServiceMessage::TerminatePage {
            lxapp,
            path,
            page_instance_id,
        } => {
            if let Some(ctx) = current_ctx.as_ref() {
                // Ensure this TerminatePage belongs to the same LxApp
                let same_app = LxApp::from_ctx(ctx)
                    .map(|ctx_app| ctx_app.session.id == lxapp.session.id)
                    .unwrap_or(false);
                if !same_app {
                    info!(
                        "[Worker {}] Ignored TerminatePage for different LxApp instance",
                        worker_id
                    )
                    .with_appid(lxapp.appid.clone())
                    .with_path(path.clone());
                    return;
                }

                // Prefer page instance identity. Multiple active PageSvc objects can share a path.
                let page_svc = with_page_svc_map(ctx, |page_svc_map| {
                    let mut page_svc_map = page_svc_map.borrow_mut();
                    let page_svc = match page_instance_id.as_deref() {
                        Some(id) => page_svc_map.remove(id),
                        None => page_svc_map.get(&path).cloned(),
                    };

                    if let Some(page_svc) = page_svc.as_ref() {
                        let instance_id = page_svc.get_page().instance_id_string();
                        page_svc_map.remove(instance_id.as_str());
                        if page_svc_map.get(&path).is_some_and(|candidate| {
                            candidate.get_page().instance_id_string() == instance_id
                        }) {
                            page_svc_map.remove(&path);
                        }
                    }
                    Ok(page_svc)
                })
                .unwrap_or(None);

                if page_svc.is_some() {
                    event_bus::clear_page(ctx, &path);

                    info!("[Worker {}] Removed page", worker_id)
                        .with_appid(lxapp.appid.clone())
                        .with_path(path);
                }
            }
        }
        ServiceMessage::CallAppSvcEvent { lxapp, event, args } => {
            if let Some(ctx) = current_ctx.as_ref() {
                // Ensure this event targets the same LxApp bound to ctx
                let same_app = LxApp::from_ctx(ctx)
                    .map(|ctx_app| ctx_app.session.id == lxapp.session.id)
                    .unwrap_or(false);
                if same_app {
                    // Don't block the worker message pump on user JS lifecycle handlers.
                    // If an app handler awaits network/IO, blocking here can starve bridge handshake
                    // and other view messages, causing "Handshake timeout" even when transport is OK.
                    let ctx = ctx.clone();
                    let appid = lxapp.appid.clone();
                    rong::spawn_local(async move {
                        handle_app_service_event(worker_id, &ctx, appid, event, args).await;
                    });
                }
            }
        }
        ServiceMessage::CallPageSvc {
            lxapp,
            path,
            page_instance_id,
            source,
        } => {
            if let Some(ctx) = current_ctx.as_ref() {
                match source {
                    PageSvcSource::Bridge { message } => {
                        let page_svc = with_page_svc_map(ctx, |page_svc_map| {
                            let page_svc_map = page_svc_map.borrow();
                            Ok(page_instance_id
                                .as_deref()
                                .and_then(|id| page_svc_map.get(id).cloned())
                                .or_else(|| page_svc_map.get(&path).cloned()))
                        })
                        .unwrap_or(None);

                        if let Some(page_svc) = page_svc {
                            if let Err(e) = handle_bridge_source(&page_svc, message).await {
                                error!("[Worker {}] Handle bridge message error: {}", worker_id, e)
                                    .with_appid(lxapp.appid.clone())
                                    .with_path(path.clone());
                            }
                        } else {
                            info!(
                                "[Worker {}] Dropping bridge message: page service not loaded",
                                worker_id
                            )
                            .with_appid(lxapp.appid.clone())
                            .with_path(path);
                        }
                    }
                    PageSvcSource::Native { name, args } => {
                        let page_svc = with_page_svc_map(ctx, |page_svc_map| {
                            let page_svc_map = page_svc_map.borrow();
                            Ok(page_instance_id
                                .as_deref()
                                .and_then(|id| page_svc_map.get(id).cloned())
                                .or_else(|| page_svc_map.get(&path).cloned()))
                        })
                        .unwrap_or(None);

                        if let Some(page_svc) = page_svc {
                            handle_native_source(&page_svc, lxapp.appid.clone(), name, args).await;
                        } else {
                            info!(
                                "[Worker {}] Dropping native call: page service not loaded",
                                worker_id
                            )
                            .with_appid(lxapp.appid.clone())
                            .with_path(path);
                        }
                    }
                }
            }
        }
        ServiceMessage::CallPageSvcEvent {
            lxapp,
            path,
            page_instance_id,
            event,
            args,
        } => {
            if let Some(ctx) = current_ctx.as_ref() {
                // Resolve PageSvc from registry
                let page_svc = with_page_svc_map(ctx, |page_svc_map| {
                    let page_svc_map = page_svc_map.borrow();
                    Ok(page_instance_id
                        .as_deref()
                        .and_then(|id| page_svc_map.get(id).cloned())
                        .or_else(|| page_svc_map.get(&path).cloned()))
                })
                .unwrap_or(None);

                if let Some(page_svc) = page_svc {
                    // Enqueue page event via PageSvc API (non-blocking)
                    if let Err(e) = page_svc.call_page_event(ctx, event, args.as_deref()).await {
                        error!(
                            "[Worker {}] PageInstance event '{}' failed: {}",
                            worker_id, event, e
                        )
                        .with_appid(lxapp.appid.clone())
                        .with_path(path);
                    }
                } else {
                    info!(
                        "[Worker {}] Dropping page event: page service not loaded",
                        worker_id
                    )
                    .with_appid(lxapp.appid.clone())
                    .with_path(path);
                }
            }
        }
        ServiceMessage::DispatchAppBusEvent { lxapp, event } => {
            if let Some(ctx) = current_ctx.as_ref() {
                let same_app = LxApp::from_ctx(ctx)
                    .map(|ctx_app| ctx_app.session.id == lxapp.session.id)
                    .unwrap_or(false);
                if same_app {
                    // Don't block the worker message pump on user JS event handlers. Like app/page
                    // lifecycle events, event bus handlers can await network/IO and would
                    // otherwise starve view messages (including handshake retries).
                    let ctx = ctx.clone();
                    let appid = lxapp.appid.clone();
                    rong::spawn_local(async move {
                        if let Err(e) = event_bus::dispatch_app_bus_event(&ctx, &event).await {
                            error!(
                                "[Worker {}] Dispatch app bus event failed: {}",
                                worker_id, e
                            )
                            .with_appid(appid);
                        }
                    });
                }
            }
        }
        ServiceMessage::Eval { lxapp, script, tx } => {
            let result = if let Some(ctx) = current_ctx.as_ref() {
                let same_app = LxApp::from_ctx(ctx)
                    .map(|ctx_app| ctx_app.session.id == lxapp.session.id)
                    .unwrap_or(false);
                if same_app {
                    eval_logic_script(ctx, &script).await
                } else {
                    Err(LxAppError::Runtime(format!(
                        "logic runtime is bound to a different lxapp than {}",
                        lxapp.appid
                    )))
                }
            } else {
                Err(LxAppError::Runtime(format!(
                    "logic runtime is not ready for {}",
                    lxapp.appid
                )))
            };
            let _ = tx.send(result);
        }
    }
}

/// Create a new mini-app service - enforces 1:1 appid->worker mapping
pub(crate) fn create_app_svc(
    lxapp: Arc<crate::lxapp::LxApp>,
    sender: &mpsc::Sender<ServiceMessage>,
    instance_assignments: &Arc<Mutex<HashMap<usize, usize>>>,
    free_workers: &Arc<Mutex<VecDeque<usize>>>,
) -> Result<(), LxAppError> {
    let appid = lxapp.appid.clone();

    // Establish instance mapping only once; if a mapping exists, reuse it (idempotent)
    let key = lxapp.as_ref() as *const _ as usize;
    {
        let assignments = instance_assignments.lock().unwrap();
        if assignments.contains_key(&key) {
            info!("Reusing existing worker for app {}", appid);
            return Ok(());
        }
    }

    // Check if we have free workers available
    let worker_id = {
        let mut free_workers_guard = free_workers.lock().unwrap();
        if free_workers_guard.is_empty() {
            return Err(LxAppError::ResourceExhausted(
                "No available workers for new mini-app".to_string(),
            ));
        }
        free_workers_guard.pop_front().unwrap()
    };

    // Establish instance mapping: LxApp ptr -> worker_id
    instance_assignments.lock().unwrap().insert(key, worker_id);

    // Send message to create the runtime in the dedicated worker
    if let Err(e) = sender.send(ServiceMessage::CreateAppSvc { lxapp }) {
        instance_assignments.lock().unwrap().remove(&key);
        free_workers.lock().unwrap().push_front(worker_id);
        return Err(e.into());
    }

    info!("Assigned dedicated worker {} to app {}", worker_id, appid);
    Ok(())
}

/// Terminate a mini-app service - breaks 1:1 mapping and returns worker to pool
pub(crate) fn terminate_app_svc(
    lxapp_arc: Arc<LxApp>,
    sender: &mpsc::Sender<ServiceMessage>,
    instance_assignments: &Arc<Mutex<HashMap<usize, usize>>>,
    free_workers: &Arc<Mutex<VecDeque<usize>>>,
) -> Result<(), LxAppError> {
    let appid = lxapp_arc.appid.clone();
    // Ensure mapping remains during terminate; get current worker_id via instance mapping
    let key = lxapp_arc.as_ref() as *const _ as usize;
    let worker_id_opt = instance_assignments.lock().unwrap().get(&key).copied();
    if worker_id_opt.is_none() {
        info!(
            "No active worker mapping for app {}; skipping terminate",
            appid
        );
        return Ok(());
    }

    // Set up ACK channel and send terminate to current worker
    let (tx, rx) = mpsc::channel();
    sender.send(ServiceMessage::TerminateAppSvc {
        lxapp: lxapp_arc,
        ack_tx: tx,
    })?;

    // Wait for ACK with timeout
    let acked = rx.recv_timeout(Duration::from_secs(3)).is_ok();
    if acked {
        info!("Terminate ACK received").with_appid(appid.clone());
    } else {
        error!("Terminate ACK timeout; forcing release").with_appid(appid.clone());
    }

    // Remove instance mapping and release the dedicated worker
    let worker_id_opt = instance_assignments.lock().unwrap().remove(&key);
    if let Some(worker_id) = worker_id_opt {
        free_workers.lock().unwrap().push_back(worker_id);
        info!("Released dedicated worker {} from app {}", worker_id, appid);
    }

    Ok(())
}

/// Wrapper for LxApp to implement external traits
#[derive(Clone)]
struct LxAppCtx {
    lxapp: Arc<LxApp>,
}

#[derive(Debug)]
struct DenyAllNetworkAccessGuard;

impl http::NetworkAccessGuard for DenyAllNetworkAccessGuard {
    fn check_access(&self, _domain: &str) -> JSResult<()> {
        Err(network_access_denied_error("network access is denied"))
    }
}

impl LxAppCtx {
    pub fn new(lxapp: Arc<LxApp>) -> Self {
        Self { lxapp }
    }
}

impl std::fmt::Debug for LxAppCtx {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LxAppCtx")
            .field("appid", &self.lxapp.appid)
            .finish()
    }
}

impl http::NetworkAccessGuard for LxAppCtx {
    /// Check if the mini app has access to the specified domain
    /// Returns Ok(()) if access is granted, Err with error message if denied
    fn check_access(&self, domain: &str) -> JSResult<()> {
        if self.lxapp.is_domain_allowed(domain) {
            Ok(())
        } else {
            Err(network_access_denied_error(format!(
                "domain '{domain}' is not allowed by lxapp security policy"
            )))
        }
    }
}

fn network_access_denied_error(detail: impl AsRef<str>) -> RongJSError {
    HostError::new(rong::error::E_PERMISSION_DENIED, "Permission denied")
        .with_data(rong::err_data!({ bizCode: (3000), detail: (detail.as_ref()) }))
        .into()
}