Skip to main content

atmos/os_lib/web_engine/
dynamic_scripts.rs

1//! 動的 `<script>` の非同期フェッチおよびライフサイクル管理モジュール。
2//!
3//! JS によって動的に DOM へ追加された `<script>` を管理し、
4//! キャッシュヒット時は即時実行アクションを返し、
5//! 未キャッシュ時はバックグラウンドフェッチ要求を発行して描画スレッドをブロックさせず、
6//! キャッシュ到着時に順次実行アクションを生成する。
7
8extern crate alloc;
9
10use alloc::string::String;
11use alloc::vec::Vec;
12
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum DynamicScriptAction {
15    /// クラシック JS を実行する (idx, code)
16    EvalClassic { idx: usize, code: String },
17    /// ES モジュールを実行する (idx, specifier, code)
18    EvalModule { idx: usize, specifier: String, code: String },
19    /// 取得失敗により error イベントを発火する (idx)
20    DispatchError { idx: usize },
21}
22
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct DynamicScriptFetchRequest {
25    pub idx: usize,
26    pub url: String,
27    pub host: String,
28    pub path: String,
29    pub is_https: bool,
30    pub is_module: bool,
31}
32
33#[derive(Debug, Clone, PartialEq, Eq)]
34struct PendingFetch {
35    idx: usize,
36    url: String,
37    host: String,
38    path: String,
39    is_module: bool,
40    ordered: bool,
41}
42
43#[derive(Debug, Default)]
44pub struct DynamicScriptManager {
45    pending_fetches: Vec<PendingFetch>,
46}
47
48impl DynamicScriptManager {
49    pub fn new() -> Self {
50        Self {
51            pending_fetches: Vec::new(),
52        }
53    }
54
55    pub fn has_pending(&self) -> bool {
56        !self.pending_fetches.is_empty()
57    }
58
59    pub fn clear(&mut self) {
60        self.pending_fetches.clear();
61    }
62
63    /// スクリプト要素の追加を受け取り、即時実行アクションまたはフェッチ要求を返す(既定 `is_async = true`)。
64    pub fn process_script<F>(
65        &mut self,
66        idx: usize,
67        src: Option<&str>,
68        ty: &str,
69        text: &str,
70        page_url: &str,
71        cache_reader: F,
72    ) -> (Vec<DynamicScriptAction>, Option<DynamicScriptFetchRequest>)
73    where
74        F: Fn(&str, &str) -> Option<Vec<u8>>,
75    {
76        self.process_script_with_async(idx, src, ty, text, page_url, true, cache_reader)
77    }
78
79    /// `async` 属性(`true` = 到着順、`false` = 挿入順)を考慮してスクリプト要素の追加を処理する。
80    #[allow(clippy::too_many_arguments)]
81    pub fn process_script_with_async<F>(
82        &mut self,
83        idx: usize,
84        src: Option<&str>,
85        ty: &str,
86        text: &str,
87        page_url: &str,
88        is_async: bool,
89        cache_reader: F,
90    ) -> (Vec<DynamicScriptAction>, Option<DynamicScriptFetchRequest>)
91    where
92        F: Fn(&str, &str) -> Option<Vec<u8>>,
93    {
94        let ty_trimmed = ty.trim().to_ascii_lowercase();
95        let ty_essence = ty_trimmed.split(';').next().unwrap_or("").trim();
96        let is_module = ty_essence == "module";
97        let is_classic = ty_essence.is_empty()
98            || matches!(
99                ty_essence,
100                "text/javascript"
101                    | "application/javascript"
102                    | "application/x-javascript"
103                    | "text/ecmascript"
104                    | "application/ecmascript"
105            );
106
107        if !is_classic && !is_module {
108            return (Vec::new(), None);
109        }
110
111        match src {
112            Some(src_str) if !src_str.trim().is_empty() => {
113                let resolved = super::url_resolve::resolve_url(page_url, src_str.trim());
114                let (is_https, host, path) = super::url_resolve::split_target(
115                    &resolved,
116                    page_url.starts_with("https://"),
117                    "",
118                );
119                let ordered = !is_async;
120                let has_preceding_ordered =
121                    ordered && self.pending_fetches.iter().any(|p| p.ordered);
122
123                // キャッシュを確認(ただし先行する `async=false` の保留スクリプトがある場合は順序維持のため待機列へ積む)
124                let cached = cache_reader(&host, &path);
125                if !has_preceding_ordered {
126                    if let Some(cached_bytes) = cached {
127                        let code = String::from_utf8(cached_bytes).unwrap_or_else(|e| {
128                            String::from_utf8_lossy(&e.into_bytes()).into_owned()
129                        });
130                        let action = if is_module {
131                            DynamicScriptAction::EvalModule {
132                                idx,
133                                specifier: resolved,
134                                code,
135                            }
136                        } else {
137                            DynamicScriptAction::EvalClassic { idx, code }
138                        };
139                        return (alloc::vec![action], None);
140                    }
141                }
142                let fetch_req = if cached.is_some() {
143                    None
144                } else {
145                    Some(DynamicScriptFetchRequest {
146                        idx,
147                        url: resolved.clone(),
148                        host: host.clone(),
149                        path: path.clone(),
150                        is_https,
151                        is_module,
152                    })
153                };
154                self.pending_fetches.push(PendingFetch {
155                    idx,
156                    url: resolved,
157                    host,
158                    path,
159                    is_module,
160                    ordered,
161                });
162                (Vec::new(), fetch_req)
163            }
164            _ => {
165                // インラインスクリプト
166                if text.trim().is_empty() {
167                    (Vec::new(), None)
168                } else {
169                    let action = if is_module {
170                        DynamicScriptAction::EvalModule {
171                            idx,
172                            specifier: String::from("<inline-module>"),
173                            code: String::from(text),
174                        }
175                    } else {
176                        DynamicScriptAction::EvalClassic {
177                            idx,
178                            code: String::from(text),
179                        }
180                    };
181                    (alloc::vec![action], None)
182                }
183            }
184        }
185    }
186
187    /// 保留中のフェッチ要求をポーリングし、到着済みのスクリプトのアクションを返す。
188    /// `ordered`(`async = false`)のスクリプトは先行する `ordered` スクリプトがすべて完了するまで待機し、
189    /// `!ordered`(`async = true`)のスクリプトは到着次第すぐに返す。
190    pub fn poll_pending<F>(&mut self, cache_reader: F) -> Vec<DynamicScriptAction>
191    where
192        F: Fn(&str, &str) -> Option<Vec<u8>>,
193    {
194        if self.pending_fetches.is_empty() {
195            return Vec::new();
196        }
197
198        let mut actions = Vec::new();
199        let mut remaining = Vec::new();
200        let mut ordered_blocked = false;
201
202        for pending in self.pending_fetches.drain(..) {
203            if pending.ordered && ordered_blocked {
204                remaining.push(pending);
205                continue;
206            }
207            if let Some(cached_bytes) = cache_reader(&pending.host, &pending.path) {
208                let code = String::from_utf8(cached_bytes)
209                    .unwrap_or_else(|e| String::from_utf8_lossy(&e.into_bytes()).into_owned());
210                if pending.is_module {
211                    actions.push(DynamicScriptAction::EvalModule {
212                        idx: pending.idx,
213                        specifier: pending.url,
214                        code,
215                    });
216                } else {
217                    actions.push(DynamicScriptAction::EvalClassic {
218                        idx: pending.idx,
219                        code,
220                    });
221                }
222            } else {
223                if pending.ordered {
224                    ordered_blocked = true;
225                }
226                remaining.push(pending);
227            }
228        }
229
230        self.pending_fetches = remaining;
231        actions
232    }
233
234    /// 取得に失敗した保留中のスクリプトを外し、`error` を発火するアクションを返す。
235    /// これが無いと失敗した要素は永久に保留のまま残り、`load`/`error` のどちらも来ない。
236    pub fn take_failed<F>(&mut self, failed: F) -> Vec<DynamicScriptAction>
237    where
238        F: Fn(&str, &str) -> bool,
239    {
240        let mut actions = Vec::new();
241        self.pending_fetches.retain(|p| {
242            if failed(&p.host, &p.path) {
243                actions.push(DynamicScriptAction::DispatchError { idx: p.idx });
244                false
245            } else {
246                true
247            }
248        });
249        actions
250    }
251}