rari 0.13.6

rari: Runtime Accelerated Rendering Infrastructure - A high-performance React Server Components framework powered by Rust
Documentation
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
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
use crate::error::RariError;
use crate::runtime::module_loader::RariModuleLoader;
use crate::runtime::runtime_factory::constants::*;
use crate::runtime::runtime_factory::executor::{execute_script, execute_script_for_streaming};
use crate::runtime::runtime_factory::interface::{AsyncBatchResult, JsRuntimeInterface};
use crate::runtime::runtime_factory::runtime_builder::create_deno_runtime;
use crate::runtime::runtime_factory::v8_utils::get_module_namespace_as_json;
use deno_core::{ModuleSpecifier, PollEventLoopOptions};
use rustc_hash::FxHashMap;
use serde_json::Value as JsonValue;
use std::future::Future;
use std::pin::Pin;
use tokio::sync::{mpsc, oneshot};

type ScriptBatchItem = (String, String, oneshot::Sender<Result<JsonValue, RariError>>);
type BatchResultSender = mpsc::UnboundedSender<(usize, Result<JsonValue, RariError>)>;
type PendingScript = (
    oneshot::Sender<Result<JsonValue, RariError>>,
    String,
    Option<deno_core::v8::Global<deno_core::v8::Value>>,
);

struct PendingBatch {
    senders: Vec<Option<oneshot::Sender<Result<JsonValue, RariError>>>>,
    names: Vec<String>,
    sent: Vec<bool>,
    remaining: usize,
    start: std::time::Instant,
    timeout: std::time::Duration,
    batch_id: u64,
}

enum JsRequest {
    ExecuteScript {
        script_name: String,
        script_code: String,
        result_tx: oneshot::Sender<Result<JsonValue, RariError>>,
    },
    ExecuteScriptBatch {
        scripts: Vec<(String, String)>,
        result_tx: BatchResultSender,
    },
    ExecuteScriptForStreaming {
        script_name: String,
        script_code: String,
        result_tx: oneshot::Sender<Result<JsonValue, RariError>>,
        chunk_sender: mpsc::Sender<Result<Vec<u8>, String>>,
    },
    AddModuleToLoader {
        component_id: String,
        result_tx: oneshot::Sender<Result<(), RariError>>,
    },
    LoadEsModule {
        component_id: String,
        result_tx: oneshot::Sender<Result<deno_core::ModuleId, RariError>>,
    },
    EvaluateModule {
        module_id: deno_core::ModuleId,
        result_tx: oneshot::Sender<Result<JsonValue, RariError>>,
    },
    GetModuleNamespace {
        module_id: deno_core::ModuleId,
        result_tx: oneshot::Sender<Result<JsonValue, RariError>>,
    },
    AddModuleToLoaderOnly {
        specifier: String,
        code: String,
        result_tx: oneshot::Sender<Result<(), RariError>>,
    },
    ClearModuleLoaderCaches {
        component_id: String,
        result_tx: oneshot::Sender<Result<(), RariError>>,
    },
    SetRequestContext {
        request_context: std::sync::Arc<crate::server::middleware::request_context::RequestContext>,
        result_tx: oneshot::Sender<Result<(), RariError>>,
    },
    ClearRequestContext {
        result_tx: oneshot::Sender<Result<(), RariError>>,
    },
    ClearRequestContextIfMatches {
        expected_context:
            std::sync::Arc<crate::server::middleware::request_context::RequestContext>,
        result_tx: oneshot::Sender<Result<(), RariError>>,
    },
}

pub struct DenoRuntime {
    request_sender: mpsc::Sender<JsRequest>,
}

impl DenoRuntime {
    pub fn new(env_vars: Option<FxHashMap<String, String>>) -> Self {
        let (request_sender, mut request_receiver) = mpsc::channel(CHANNEL_CAPACITY);

        std::thread::spawn(move || {
            let runtime = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .expect("Failed to create Tokio runtime");

            runtime.block_on(async {
                loop {
                    let (mut deno_runtime, module_loader) =
                        match create_deno_runtime(env_vars.clone()) {
                            Ok(rt) => rt,
                            Err(_) => {
                                tokio::time::sleep(std::time::Duration::from_millis(
                                    RUNTIME_RESTART_DELAY_MS,
                                ))
                                .await;
                                continue;
                            }
                        };

                    let mut continue_processing = true;
                    let mut pending_batches: Vec<PendingBatch> = Vec::new();
                    let mut batch_id_counter: u64 = 0;

                    while continue_processing {
                        if !pending_batches.is_empty() {
                            tokio::select! {
                                biased;
                                request = request_receiver.recv() => {
                                    match request {
                                        Some(req) => {
                                            let result = handle_js_request(
                                                req,
                                                &mut deno_runtime,
                                                &module_loader,
                                                &mut continue_processing,
                                                &mut pending_batches,
                                                &mut batch_id_counter,
                                            ).await;
                                            if let Err(e) = result {
                                                eprintln!("[rari] Error processing request: {e}");
                                                break;
                                            }
                                        }
                                        None => {
                                            continue_processing = false;
                                        }
                                    }
                                }
                                event_loop_result = tokio::time::timeout(
                                    std::time::Duration::from_millis(50),
                                    crate::runtime::runtime_factory::v8_utils::run_event_loop_with_error_handling(
                                        &mut deno_runtime, "concurrent batch"
                                    ),
                                ) => {
                                    if let Ok(Err(e)) = event_loop_result {
                                        eprintln!("[rari] Event loop error: {e}");
                                        if is_runtime_restart_needed(&e) {
                                            for batch in pending_batches.drain(..) {
                                                for sender in batch.senders.into_iter().flatten() {
                                                    let _ = sender.send(Err(create_graceful_error()));
                                                }
                                            }
                                            break;
                                        }
                                    }
                                }
                            }

                            check_pending_batches(&mut deno_runtime, &mut pending_batches);
                            pending_batches.retain(|b| b.remaining > 0 && b.start.elapsed() < b.timeout);
                        } else {
                            match request_receiver.recv().await {
                                Some(req) => {
                                    let result = handle_js_request(
                                        req,
                                        &mut deno_runtime,
                                        &module_loader,
                                        &mut continue_processing,
                                        &mut pending_batches,
                                        &mut batch_id_counter,
                                    ).await;
                                    if let Err(e) = result {
                                        eprintln!("[rari] Error processing request: {e}");
                                        break;
                                    }
                                }
                                None => {
                                    continue_processing = false;
                                }
                            }
                        }

                        let _ = tokio::time::timeout(
                            std::time::Duration::from_millis(10),
                            deno_runtime.run_event_loop(PollEventLoopOptions::default()),
                        ).await;
                    }

                    println!("[rari] Restarting JS runtime due to error or forced restart");
                    tokio::time::sleep(std::time::Duration::from_millis(
                        RUNTIME_QUICK_RESTART_DELAY_MS,
                    ))
                    .await;
                }
            });
        });

        Self { request_sender }
    }
}

async fn handle_load_es_module(
    deno_runtime: &mut deno_core::JsRuntime,
    module_loader: &std::rc::Rc<RariModuleLoader>,
    component_id: &str,
    result_tx: oneshot::Sender<Result<deno_core::ModuleId, RariError>>,
) -> Result<(), RariError> {
    let specifier_opt = module_loader.get_component_specifier(component_id);

    if let Some(specifier_str) = specifier_opt {
        let is_hmr_update = module_loader.is_hmr_module(&specifier_str);

        match ModuleSpecifier::parse(&specifier_str) {
            Ok(module_specifier) => {
                let module_load_result = if is_hmr_update {
                    if let Some(versioned_specifier) =
                        module_loader.get_versioned_specifier(component_id)
                    {
                        match ModuleSpecifier::parse(&versioned_specifier) {
                            Ok(versioned_module_specifier) => {
                                deno_runtime.load_side_es_module(&versioned_module_specifier).await
                            }
                            Err(_) => deno_runtime.load_side_es_module(&module_specifier).await,
                        }
                    } else {
                        deno_runtime.load_side_es_module(&module_specifier).await
                    }
                } else {
                    deno_runtime.load_side_es_module(&module_specifier).await
                };

                let module_load_result = module_load_result.map_err(|e| {
                    RariError::js_execution(format!(
                        "Failed to load module '{component_id}' (specifier: '{module_specifier}'): {e}"
                    ))
                });

                let _ = result_tx.send(module_load_result);
            }
            Err(e) => {
                let err_msg = format!(
                    "Invalid module specifier string '{specifier_str}' for component '{component_id}': {e}"
                );
                eprintln!("[rari] {err_msg}");
                let _ = result_tx.send(Err(RariError::js_execution(err_msg)));
            }
        }
    } else {
        let err_msg = format!("Component specifier not found for LoadEsModule: {component_id}");
        eprintln!("[rari] {err_msg}");
        let _ = result_tx.send(Err(RariError::js_execution(err_msg)));
    }
    Ok::<(), RariError>(())
}

async fn handle_evaluate_module(
    deno_runtime: &mut deno_core::JsRuntime,
    module_loader: &std::rc::Rc<RariModuleLoader>,
    module_id: deno_core::ModuleId,
    result_tx: oneshot::Sender<Result<JsonValue, RariError>>,
    continue_processing: &mut bool,
) -> Result<(), RariError> {
    let module_registered = module_loader.is_already_evaluated(&module_id.to_string());

    let result = if module_registered {
        match get_module_namespace_as_json(deno_runtime, module_id) {
            Ok(json_result) => Ok(json_result),
            Err(_) => Ok(create_already_evaluated_response("get_module_namespace")),
        }
    } else {
        match deno_runtime.mod_evaluate(module_id).await {
            Ok(_) => {
                module_loader.mark_module_evaluated(&module_id.to_string());
                get_module_namespace_as_json(deno_runtime, module_id)
            }
            Err(e) => {
                if e.to_string().contains(MODULE_ALREADY_EVALUATED_ERROR) {
                    module_loader.mark_module_evaluated(&module_id.to_string());

                    match get_module_namespace_as_json(deno_runtime, module_id) {
                        Ok(json_result) => Ok(json_result),
                        Err(_) => Ok(create_already_evaluated_response("get_module_namespace")),
                    }
                } else {
                    Err(RariError::js_execution(format!(
                        "Failed to evaluate module {module_id}: {e}"
                    )))
                }
            }
        }
    };

    if let Err(e) = &result
        && is_critical_error(e)
    {
        println!("[rari] Critical error detected in module evaluation: {e}");
        *continue_processing = false;
    }

    let _ = result_tx.send(result);
    Ok::<(), RariError>(())
}

async fn handle_get_module_namespace(
    deno_runtime: &mut deno_core::JsRuntime,
    module_loader: &std::rc::Rc<RariModuleLoader>,
    module_id: deno_core::ModuleId,
    result_tx: oneshot::Sender<Result<JsonValue, RariError>>,
) -> Result<(), RariError> {
    let module_evaluated = module_loader.is_already_evaluated(&module_id.to_string());

    if module_evaluated {
        let json_result =
            get_module_namespace_as_json(deno_runtime, module_id as deno_core::ModuleId);
        let _ = result_tx.send(json_result);
    } else {
        match deno_runtime.mod_evaluate(module_id as deno_core::ModuleId).await {
            Ok(_) => {
                module_loader.mark_module_evaluated(&module_id.to_string());
                let json_result =
                    get_module_namespace_as_json(deno_runtime, module_id as deno_core::ModuleId);
                let _ = result_tx.send(json_result);
            }
            Err(e) => {
                if e.to_string().contains(MODULE_ALREADY_EVALUATED_ERROR) {
                    module_loader.mark_module_evaluated(&module_id.to_string());
                    let json_result = get_module_namespace_as_json(
                        deno_runtime,
                        module_id as deno_core::ModuleId,
                    );
                    let _ = result_tx.send(json_result);
                } else {
                    let _ = result_tx.send(Err(RariError::js_execution(format!(
                        "Failed to evaluate module: {e}"
                    ))));
                }
            }
        }
    }
    Ok::<(), RariError>(())
}

async fn handle_js_request(
    request: JsRequest,
    deno_runtime: &mut deno_core::JsRuntime,
    module_loader: &std::rc::Rc<RariModuleLoader>,
    continue_processing: &mut bool,
    pending_batches: &mut Vec<PendingBatch>,
    batch_id_counter: &mut u64,
) -> Result<(), RariError> {
    match request {
        JsRequest::ExecuteScript { script_name, script_code, result_tx } => {
            let result =
                execute_script(deno_runtime, module_loader, &script_name, &script_code).await;
            if let Err(e) = &result
                && is_runtime_restart_needed(e)
            {
                let _ = result_tx.send(Err(create_graceful_error()));
                return Err(RariError::internal("Runtime restart needed".to_string()));
            }
            let _ = result_tx.send(result);
        }
        JsRequest::ExecuteScriptBatch { scripts, result_tx } => {
            let batch: Vec<ScriptBatchItem> = scripts
                .into_iter()
                .enumerate()
                .map(|(i, (name, code))| {
                    let (tx, rx) = oneshot::channel::<Result<JsonValue, RariError>>();
                    let result_tx_clone = result_tx.clone();
                    tokio::spawn(async move {
                        let result = rx.await.unwrap_or_else(|_| Err(create_graceful_error()));
                        let _ = result_tx_clone.send((i, result));
                    });
                    (name, code, tx)
                })
                .collect();

            if let Some(pending_batch) =
                setup_concurrent_batch(deno_runtime, batch, batch_id_counter).await
            {
                pending_batches.push(pending_batch);
            }
        }
        JsRequest::ExecuteScriptForStreaming {
            script_name,
            script_code,
            result_tx,
            chunk_sender,
        } => {
            let sender_for_op_state = chunk_sender.clone();
            deno_runtime.op_state().borrow_mut().put(crate::runtime::ops::StreamOpState {
                chunk_sender: Some(sender_for_op_state),
                current_stream_id: None,
                row_counter: 0,
            });
            let result = execute_script_for_streaming(
                deno_runtime,
                module_loader,
                &script_name,
                &script_code,
                chunk_sender,
            )
            .await;
            let _ = result_tx.send(result.map(|_| JsonValue::Null));
        }
        JsRequest::AddModuleToLoader { component_id, result_tx } => {
            let specifier_opt = module_loader.get_component_specifier(&component_id);
            if specifier_opt.is_some() {
                let _ = result_tx.send(Ok(()));
            } else {
                let _ = result_tx.send(Err(RariError::js_execution(format!(
                    "Component specifier not found in loader for AddModuleToLoader: {component_id}"
                ))));
            }
        }
        JsRequest::LoadEsModule { component_id, result_tx } => {
            handle_load_es_module(deno_runtime, module_loader, &component_id, result_tx).await?;
        }
        JsRequest::EvaluateModule { module_id, result_tx } => {
            handle_evaluate_module(
                deno_runtime,
                module_loader,
                module_id,
                result_tx,
                continue_processing,
            )
            .await?;
        }
        JsRequest::GetModuleNamespace { module_id, result_tx } => {
            handle_get_module_namespace(deno_runtime, module_loader, module_id, result_tx).await?;
        }
        JsRequest::AddModuleToLoaderOnly { specifier, code, result_tx } => {
            module_loader.set_module_code(specifier.clone(), code.clone());
            let component_id = extract_component_id_from_specifier(&specifier);
            let is_hmr_specifier = specifier.contains("/rari_hmr/");
            let existing_specifier =
                module_loader.component_specifiers.get(&component_id).map(|entry| entry.clone());
            let has_existing_hmr_mapping = existing_specifier
                .as_ref()
                .map(|spec| spec.contains("/rari_hmr/"))
                .unwrap_or(false);
            if is_hmr_specifier || !has_existing_hmr_mapping {
                module_loader.component_specifiers.insert(component_id.clone(), specifier.clone());
            }
            let _ = result_tx.send(Ok(()));
        }
        JsRequest::ClearModuleLoaderCaches { component_id, result_tx } => {
            module_loader.clear_component_caches(&component_id);
            let _ = result_tx.send(Ok(()));
        }
        JsRequest::SetRequestContext { request_context, result_tx } => {
            deno_runtime.op_state().borrow_mut().put(request_context);
            let _ = result_tx.send(Ok(()));
        }
        JsRequest::ClearRequestContext { result_tx } => {
            deno_runtime.op_state().borrow_mut().try_take::<std::sync::Arc<crate::server::middleware::request_context::RequestContext>>();
            let _ = result_tx.send(Ok(()));
        }
        JsRequest::ClearRequestContextIfMatches { expected_context, result_tx } => {
            let should_clear = {
                let op_state = deno_runtime.op_state();
                let borrowed = op_state.borrow();
                if let Some(current_context) = borrowed.try_borrow::<std::sync::Arc<crate::server::middleware::request_context::RequestContext>>() {
                    std::sync::Arc::ptr_eq(current_context, &expected_context)
                } else {
                    false
                }
            };

            if should_clear {
                deno_runtime.op_state().borrow_mut().try_take::<std::sync::Arc<crate::server::middleware::request_context::RequestContext>>();
            }
            let _ = result_tx.send(Ok(()));
        }
    }
    Ok(())
}

async fn setup_concurrent_batch(
    deno_runtime: &mut deno_core::JsRuntime,
    batch: Vec<ScriptBatchItem>,
    batch_id_counter: &mut u64,
) -> Option<PendingBatch> {
    use crate::with_scope;

    *batch_id_counter += 1;
    let batch_id = *batch_id_counter;

    let mut pending: Vec<PendingScript> = Vec::with_capacity(batch.len());

    for (script_name, script_code, tx) in batch {
        match deno_runtime.execute_script(script_name.clone(), script_code.clone()) {
            Ok(v8_val) => {
                let slot_key = format!("__rari_b{}_{}__", batch_id, pending.len());
                let store_result = with_scope!(deno_runtime, |scope| {
                    let local_val = deno_core::v8::Local::new(scope, &v8_val);
                    let context = scope.get_current_context();
                    let global = context.global(scope);
                    if let Some(key_str) = deno_core::v8::String::new(scope, &slot_key) {
                        global.set(scope, key_str.into(), local_val);
                        Ok::<(), RariError>(())
                    } else {
                        Err(RariError::internal("Failed to create V8 key string".to_string()))
                    }
                });
                if store_result.is_err() {
                    let _ = tx.send(Err(RariError::internal(
                        "Failed to store V8 value in global slot".to_string(),
                    )));
                } else {
                    pending.push((tx, script_name, Some(v8_val)));
                }
            }
            Err(e) => {
                let err = RariError::js_execution(format!(
                    "Failed to execute script '{}': {}",
                    script_name, e
                ));
                let _ = tx.send(Err(err));
            }
        }
    }

    if pending.is_empty() {
        return None;
    }

    let promise_timeout_ms: u64 = std::env::var("RARI_PROMISE_RESOLUTION_TIMEOUT_MS")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(5000);

    let mut sent = vec![false; pending.len()];
    let mut remaining = pending.len();

    let (mut senders, names): (Vec<_>, Vec<_>) =
        pending.into_iter().map(|(tx, name, _)| (Some(tx), name)).unzip();

    for (i, sent_item) in sent.iter_mut().enumerate().take(senders.len()) {
        let slot_key = format!("__rari_b{}_{}__", batch_id, i);
        let setup = format!(
            r#"(function() {{
                if (!globalThis['~rari_concurrent']) globalThis['~rari_concurrent'] = {{}};
                const val = globalThis['{}'];
                if (val && typeof val.then === 'function') {{
                    globalThis['~rari_concurrent']['{}'] = {{ done: false, result: null, error: null }};
                    val.then(function(r) {{
                        globalThis['~rari_concurrent']['{}'] = {{ done: true, result: r, error: null }};
                    }}).catch(function(e) {{
                        globalThis['~rari_concurrent']['{}'] = {{ done: true, result: null, error: String(e) }};
                    }});
                }} else {{
                    globalThis['~rari_concurrent']['{}'] = {{ done: true, result: val, error: null }};
                }}
            }})()"#,
            slot_key, slot_key, slot_key, slot_key, slot_key
        );
        if let Err(e) = deno_runtime.execute_script(format!("setup_concurrent_{i}"), setup) {
            eprintln!("[rari] Failed to setup concurrent tracking for slot {i}: {e}");
            let cleanup = format!("delete globalThis['{}']", slot_key);
            let _ = deno_runtime.execute_script(format!("cleanup_setup_{i}"), cleanup);

            *sent_item = true;

            remaining = remaining.saturating_sub(1);

            if let Some(sender) = senders[i].take() {
                let _ = sender.send(Err(RariError::internal(format!(
                    "Failed to setup concurrent tracking: {e}"
                ))));
            }
        }
    }

    Some(PendingBatch {
        senders,
        names,
        sent,
        remaining,
        start: std::time::Instant::now(),
        timeout: std::time::Duration::from_millis(promise_timeout_ms),
        batch_id,
    })
}

fn check_pending_batches(
    deno_runtime: &mut deno_core::JsRuntime,
    pending_batches: &mut [PendingBatch],
) {
    use crate::runtime::runtime_factory::v8_utils::v8_to_json;
    use crate::with_scope;

    for batch in pending_batches.iter_mut() {
        for i in 0..batch.sent.len() {
            if batch.sent[i] {
                continue;
            }

            let slot_key = format!("__rari_b{}_{}__", batch.batch_id, i);
            let check = format!(
                r#"(function() {{
                    const e = globalThis['~rari_concurrent'] && globalThis['~rari_concurrent']['{}'];
                    return e && e.done ? e : null;
                }})()"#,
                slot_key
            );

            let check_result = deno_runtime.execute_script(format!("check_slot_{i}"), check);

            if let Err(e) = check_result {
                let cleanup = format!(
                    r#"(function() {{
                        if (globalThis['~rari_concurrent'] && globalThis['~rari_concurrent']['{}']) {{
                            delete globalThis['~rari_concurrent']['{}'];
                        }}
                        if (globalThis['{}']) {{
                            delete globalThis['{}'];
                        }}
                    }})()"#,
                    slot_key, slot_key, slot_key, slot_key
                );
                let _ = deno_runtime.execute_script(format!("cleanup_check_error_{i}"), cleanup);

                if let Some(tx) = batch.senders[i].take() {
                    let _ = tx.send(Err(RariError::js_execution(format!(
                        "Failed to check status for '{}': {}",
                        batch.names[i], e
                    ))));
                }
                batch.sent[i] = true;
                batch.remaining -= 1;
                continue;
            }

            let check_value = check_result.expect("check_result is Ok after error check");
            let is_done = with_scope!(deno_runtime, |scope| {
                let local = deno_core::v8::Local::new(scope, check_value);
                !local.is_null_or_undefined()
            });

            if is_done {
                let extract = format!(
                    r#"(function() {{
                        const entry = globalThis['~rari_concurrent']['{}'];
                        delete globalThis['~rari_concurrent']['{}'];
                        delete globalThis['{}'];
                        return {{
                            ok: entry.error === null,
                            value: entry.result,
                            error: entry.error
                        }};
                    }})()"#,
                    slot_key, slot_key, slot_key
                );
                let result = match deno_runtime
                    .execute_script(format!("extract_concurrent_{i}"), extract)
                {
                    Ok(extracted) => {
                        let json_result = with_scope!(deno_runtime, |scope| {
                            let local = deno_core::v8::Local::new(scope, extracted);
                            v8_to_json(scope, local)
                        });
                        match json_result {
                            Ok(JsonValue::Object(obj)) => {
                                if matches!(obj.get("ok"), Some(JsonValue::Bool(false))) {
                                    Err(RariError::js_execution(
                                        obj.get("error")
                                            .and_then(JsonValue::as_str)
                                            .unwrap_or("Unknown concurrent error")
                                            .to_string(),
                                    ))
                                } else {
                                    Ok(obj.get("value").cloned().unwrap_or(JsonValue::Null))
                                }
                            }
                            Ok(_) => {
                                let cleanup = format!(
                                    r#"(function() {{
                                            if (globalThis['~rari_concurrent'] && globalThis['~rari_concurrent']['{}']) {{
                                                delete globalThis['~rari_concurrent']['{}'];
                                            }}
                                            if (globalThis['{}']) {{
                                                delete globalThis['{}'];
                                            }}
                                        }})()"#,
                                    slot_key, slot_key, slot_key, slot_key
                                );
                                let _ = deno_runtime
                                    .execute_script(format!("cleanup_extract_shape_{i}"), cleanup);
                                Err(RariError::internal(
                                    "Concurrent extraction wrapper was not an object".to_string(),
                                ))
                            }
                            Err(e) => {
                                let cleanup = format!(
                                    r#"(function() {{
                                            if (globalThis['~rari_concurrent'] && globalThis['~rari_concurrent']['{}']) {{
                                                delete globalThis['~rari_concurrent']['{}'];
                                            }}
                                            if (globalThis['{}']) {{
                                                delete globalThis['{}'];
                                            }}
                                        }})()"#,
                                    slot_key, slot_key, slot_key, slot_key
                                );
                                let _ = deno_runtime
                                    .execute_script(format!("cleanup_extract_json_{i}"), cleanup);
                                Err(e)
                            }
                        }
                    }
                    Err(e) => {
                        let cleanup = format!(
                            r#"(function() {{
                                    if (globalThis['~rari_concurrent'] && globalThis['~rari_concurrent']['{}']) {{
                                        delete globalThis['~rari_concurrent']['{}'];
                                    }}
                                    if (globalThis['{}']) {{
                                        delete globalThis['{}'];
                                    }}
                                }})()"#,
                            slot_key, slot_key, slot_key, slot_key
                        );
                        let _ = deno_runtime
                            .execute_script(format!("cleanup_extract_error_{i}"), cleanup);
                        Err(RariError::js_execution(format!(
                            "Failed to extract result for '{}': {}",
                            batch.names[i], e
                        )))
                    }
                };

                if let Some(tx) = batch.senders[i].take() {
                    let _ = tx.send(result);
                }
                batch.sent[i] = true;
                batch.remaining -= 1;
            }
        }

        if batch.start.elapsed() >= batch.timeout {
            for i in 0..batch.sent.len() {
                if !batch.sent[i] {
                    let slot_key = format!("__rari_b{}_{}__", batch.batch_id, i);
                    let cleanup = format!(
                        r#"(function() {{
                            if (globalThis['~rari_concurrent'] && globalThis['~rari_concurrent']['{}']) {{
                                delete globalThis['~rari_concurrent']['{}'];
                            }}
                            if (globalThis['{}']) {{
                                delete globalThis['{}'];
                            }}
                        }})()"#,
                        slot_key, slot_key, slot_key, slot_key
                    );
                    let _ = deno_runtime.execute_script(format!("cleanup_timeout_{i}"), cleanup);

                    if let Some(tx) = batch.senders[i].take() {
                        let _ = tx.send(Err(RariError::timeout(format!(
                            "Promise timed out for '{}'",
                            batch.names[i]
                        ))));
                    }
                    batch.sent[i] = true;
                    batch.remaining -= 1;
                }
            }
        }
    }
}

fn extract_component_id_from_specifier(specifier: &str) -> String {
    if let Some(server_idx) = specifier.rfind("/server/") {
        let after_server = &specifier[server_idx + 8..];
        after_server.split('?').next().unwrap_or(after_server).trim_end_matches(".js").to_string()
    } else if let Some(component_idx) = specifier.rfind("/rari_component/") {
        let after_component = &specifier[component_idx + 16..];
        after_component
            .split('?')
            .next()
            .unwrap_or(after_component)
            .trim_end_matches(".js")
            .to_string()
    } else if let Some(hmr_idx) = specifier.rfind("/rari_hmr/server/") {
        let after_hmr = &specifier[hmr_idx + 17..];
        after_hmr.split('?').next().unwrap_or(after_hmr).trim_end_matches(".js").to_string()
    } else {
        specifier
            .split('/')
            .next_back()
            .unwrap_or(specifier)
            .split('?')
            .next()
            .unwrap_or(specifier)
            .trim_end_matches(".js")
            .to_string()
    }
}

impl JsRuntimeInterface for DenoRuntime {
    fn execute_script(
        &self,
        script_name: String,
        script_code: String,
    ) -> Pin<Box<dyn Future<Output = Result<JsonValue, RariError>> + Send>> {
        let request_sender = self.request_sender.clone();

        Box::pin(async move {
            let (response_sender, response_receiver) = oneshot::channel();

            request_sender
                .send(JsRequest::ExecuteScript {
                    script_name,
                    script_code,
                    result_tx: response_sender,
                })
                .await
                .map_err(|_| RariError::js_runtime(JS_EXECUTOR_CHANNEL_CLOSED_ERROR.to_string()))?;

            response_receiver
                .await
                .map_err(|_| RariError::js_runtime(JS_EXECUTOR_FAILED_ERROR.to_string()))?
        })
    }

    fn execute_script_batch(&self, scripts: Vec<(String, String)>) -> AsyncBatchResult {
        let request_sender = self.request_sender.clone();

        Box::pin(async move {
            let (result_tx, result_rx) = mpsc::unbounded_channel();
            let script_count = scripts.len();

            if request_sender
                .send(JsRequest::ExecuteScriptBatch { scripts, result_tx })
                .await
                .is_err()
            {
                let (err_tx, err_rx) = mpsc::unbounded_channel();
                for i in 0..script_count {
                    let _ = err_tx.send((
                        i,
                        Err(RariError::js_runtime(JS_EXECUTOR_CHANNEL_CLOSED_ERROR.to_string())),
                    ));
                }
                return err_rx;
            }

            result_rx
        })
    }

    fn execute_function(
        &self,
        function_name: &str,
        args: Vec<JsonValue>,
    ) -> Pin<Box<dyn Future<Output = Result<JsonValue, RariError>> + Send + 'static>> {
        let request_sender = self.request_sender.clone();
        let function_name = function_name.to_string();

        Box::pin(async move {
            let args_json = serde_json::to_string(&args)
                .map_err(|e| RariError::js_runtime(format!("Failed to serialize args: {e}")))?;

            let unique_id = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos();

            let args_base64 = base64::Engine::encode(
                &base64::engine::general_purpose::STANDARD,
                args_json.as_bytes(),
            );

            let script = format!(
                r#"
                (function() {{
                    const argsBase64 = "{}";
                    const argsBinary = atob(argsBase64);
                    const argsBytes = new Uint8Array(argsBinary.length);
                    for (let i = 0; i < argsBinary.length; i++) {{
                        argsBytes[i] = argsBinary.charCodeAt(i);
                    }}
                    const argsJson = new TextDecoder('utf-8').decode(argsBytes);
                    const args = JSON.parse(argsJson);

                    if (typeof globalThis["{}"] !== 'function') {{
                        throw new Error("Function not found: {}");
                    }}

                    return globalThis["{}"](...args);
                }})();
                "#,
                args_base64, function_name, function_name, function_name
            );

            let (response_sender, response_receiver) = oneshot::channel();

            request_sender
                .send(JsRequest::ExecuteScript {
                    script_name: format!("exec_func_{}_{}.js", function_name, unique_id),
                    script_code: script,
                    result_tx: response_sender,
                })
                .await
                .map_err(|_| RariError::js_runtime(JS_EXECUTOR_CHANNEL_CLOSED_ERROR.to_string()))?;

            response_receiver
                .await
                .map_err(|_| RariError::js_runtime(JS_EXECUTOR_FAILED_ERROR.to_string()))?
        })
    }

    fn execute_script_for_streaming(
        &self,
        script_name: String,
        script_code: String,
        chunk_sender: mpsc::Sender<Result<Vec<u8>, String>>,
    ) -> Pin<Box<dyn Future<Output = Result<(), RariError>> + Send>> {
        let request_sender = self.request_sender.clone();

        Box::pin(async move {
            let (response_sender, response_receiver) = oneshot::channel();

            request_sender
                .send(JsRequest::ExecuteScriptForStreaming {
                    script_name,
                    script_code,
                    result_tx: response_sender,
                    chunk_sender,
                })
                .await
                .map_err(|_| RariError::js_runtime(JS_EXECUTOR_CHANNEL_CLOSED_ERROR.to_string()))?;

            response_receiver
                .await
                .map_err(|_| RariError::js_runtime(JS_EXECUTOR_FAILED_ERROR.to_string()))?
                .map(|_| ())
        })
    }

    fn add_module_to_loader(
        &self,
        specifier: &str,
    ) -> Pin<Box<dyn Future<Output = Result<(), RariError>> + Send>> {
        let request_sender = self.request_sender.clone();
        let specifier = specifier.to_string();

        Box::pin(async move {
            let (response_sender, response_receiver) = oneshot::channel();

            request_sender
                .send(JsRequest::AddModuleToLoader {
                    component_id: specifier,
                    result_tx: response_sender,
                })
                .await
                .map_err(|_| RariError::js_runtime(JS_EXECUTOR_CHANNEL_CLOSED_ERROR.to_string()))?;

            response_receiver
                .await
                .map_err(|_| RariError::js_runtime(JS_EXECUTOR_FAILED_ERROR.to_string()))?
        })
    }

    fn load_es_module(
        &self,
        specifier: &str,
    ) -> Pin<Box<dyn Future<Output = Result<deno_core::ModuleId, RariError>> + Send>> {
        let request_sender = self.request_sender.clone();
        let specifier = specifier.to_string();

        Box::pin(async move {
            let (response_sender, response_receiver) = oneshot::channel();

            request_sender
                .send(JsRequest::LoadEsModule {
                    component_id: specifier,
                    result_tx: response_sender,
                })
                .await
                .map_err(|_| RariError::js_runtime(JS_EXECUTOR_CHANNEL_CLOSED_ERROR.to_string()))?;

            response_receiver
                .await
                .map_err(|_| RariError::js_runtime(JS_EXECUTOR_FAILED_ERROR.to_string()))?
        })
    }

    fn evaluate_module(
        &self,
        module_id: deno_core::ModuleId,
    ) -> Pin<Box<dyn Future<Output = Result<JsonValue, RariError>> + Send>> {
        let request_sender = self.request_sender.clone();

        Box::pin(async move {
            let (response_sender, response_receiver) = oneshot::channel();

            request_sender
                .send(JsRequest::EvaluateModule { module_id, result_tx: response_sender })
                .await
                .map_err(|_| RariError::js_runtime(JS_EXECUTOR_CHANNEL_CLOSED_ERROR.to_string()))?;

            response_receiver
                .await
                .map_err(|_| RariError::js_runtime(JS_EXECUTOR_FAILED_ERROR.to_string()))?
        })
    }

    fn get_module_namespace(
        &self,
        module_id: deno_core::ModuleId,
    ) -> Pin<Box<dyn Future<Output = Result<JsonValue, RariError>> + Send>> {
        let request_sender = self.request_sender.clone();

        Box::pin(async move {
            let (response_sender, response_receiver) = oneshot::channel();

            request_sender
                .send(JsRequest::GetModuleNamespace { module_id, result_tx: response_sender })
                .await
                .map_err(|_| RariError::js_runtime(JS_EXECUTOR_CHANNEL_CLOSED_ERROR.to_string()))?;

            response_receiver
                .await
                .map_err(|_| RariError::js_runtime(JS_EXECUTOR_FAILED_ERROR.to_string()))?
        })
    }

    fn add_module_to_loader_only(
        &self,
        specifier: &str,
        code: String,
    ) -> Pin<Box<dyn Future<Output = Result<(), RariError>> + Send>> {
        let request_sender = self.request_sender.clone();
        let specifier_str = specifier.to_string();

        Box::pin(async move {
            let (response_sender, response_receiver) = oneshot::channel();
            request_sender
                .send(JsRequest::AddModuleToLoaderOnly {
                    specifier: specifier_str,
                    code,
                    result_tx: response_sender,
                })
                .await
                .map_err(|_| {
                    RariError::js_runtime(
                        "JS executor channel closed (add_module_only)".to_string(),
                    )
                })?;
            response_receiver.await.map_err(|_| {
                RariError::js_runtime("JS executor failed to respond (add_module_only)".to_string())
            })?
        })
    }

    fn clear_module_loader_caches(
        &self,
        component_id: &str,
    ) -> Pin<Box<dyn Future<Output = Result<(), RariError>> + Send>> {
        let request_sender = self.request_sender.clone();
        let component_id_str = component_id.to_string();

        Box::pin(async move {
            let (response_sender, response_receiver) = oneshot::channel();
            request_sender
                .send(JsRequest::ClearModuleLoaderCaches {
                    component_id: component_id_str,
                    result_tx: response_sender,
                })
                .await
                .map_err(|_| {
                    RariError::js_runtime("JS executor channel closed (clear_caches)".to_string())
                })?;
            response_receiver.await.map_err(|_| {
                RariError::js_runtime("JS executor failed to respond (clear_caches)".to_string())
            })?
        })
    }

    fn set_request_context(
        &self,
        request_context: std::sync::Arc<crate::server::middleware::request_context::RequestContext>,
    ) -> Pin<Box<dyn Future<Output = Result<(), RariError>> + Send>> {
        let request_sender = self.request_sender.clone();

        Box::pin(async move {
            let (response_sender, response_receiver) = oneshot::channel();
            request_sender
                .send(JsRequest::SetRequestContext { request_context, result_tx: response_sender })
                .await
                .map_err(|_| {
                    RariError::js_runtime(
                        "JS executor channel closed (set_request_context)".to_string(),
                    )
                })?;
            response_receiver.await.map_err(|_| {
                RariError::js_runtime(
                    "JS executor failed to respond (set_request_context)".to_string(),
                )
            })?
        })
    }

    fn clear_request_context(&self) -> Pin<Box<dyn Future<Output = Result<(), RariError>> + Send>> {
        let request_sender = self.request_sender.clone();

        Box::pin(async move {
            let (response_sender, response_receiver) = oneshot::channel();
            request_sender
                .send(JsRequest::ClearRequestContext { result_tx: response_sender })
                .await
                .map_err(|_| {
                    RariError::js_runtime(
                        "JS executor channel closed (clear_request_context)".to_string(),
                    )
                })?;
            response_receiver.await.map_err(|_| {
                RariError::js_runtime(
                    "JS executor failed to respond (clear_request_context)".to_string(),
                )
            })?
        })
    }

    fn clear_request_context_if_matches(
        &self,
        expected_context: std::sync::Arc<
            crate::server::middleware::request_context::RequestContext,
        >,
    ) -> Pin<Box<dyn Future<Output = Result<(), RariError>> + Send>> {
        let request_sender = self.request_sender.clone();

        Box::pin(async move {
            let (response_sender, response_receiver) = oneshot::channel();
            request_sender
                .send(JsRequest::ClearRequestContextIfMatches {
                    expected_context,
                    result_tx: response_sender,
                })
                .await
                .map_err(|_| {
                    RariError::js_runtime(
                        "JS executor channel closed (clear_request_context_if_matches)".to_string(),
                    )
                })?;
            response_receiver.await.map_err(|_| {
                RariError::js_runtime(
                    "JS executor failed to respond (clear_request_context_if_matches)".to_string(),
                )
            })?
        })
    }
}