tauri_plugin_compmd/compmd.rs
1//! What the plugin keeps for the app: the bundle, its origin and the pack store.
2
3use std::sync::Arc;
4use std::time::Duration;
5
6use compmd_host::registry::{Client, DEFAULT_MAX_PACK_SIZE, Options, Proxy};
7use compmd_host::{Bundle, FetchedBy, Manifest, Refusal, Store, refused, respond};
8use tauri::http::{HeaderValue, Request, Response, StatusCode, header};
9
10/// The bundle the app serves, where, and the store of the packs it fetches, as the app's state (`app.compmd()`). The
11/// bundle and the store are shared, so the processor can keep them as its packs (`packs`).
12pub struct Compmd {
13 bundle: Option<Arc<Bundle>>,
14 origin: Option<String>,
15 store: Arc<dyn Store>,
16 /// The `registry/` proxy, when the bundle's configuration fetches registry packs through the host.
17 proxy: Option<Proxy>,
18}
19
20/// Why the scheme serves nothing without a bundle.
21const NO_BUNDLE: &str = "this app has no bundle: build it with @compmd/vite before the app";
22
23/// Where the proxy is served on the scheme.
24pub(crate) const REGISTRY: &str = "/registry/";
25
26/// How long one request to a registry may take, its body read whole.
27const TIMEOUT: Duration = Duration::from_secs(30);
28
29/// The proxy of `manifest`'s registries, when it fetches through the host (docs/tauri-plugin.md, decision 11).
30fn proxy_of(manifest: &Manifest) -> Option<Proxy> {
31 if manifest.fetch != FetchedBy::Host || manifest.registries.is_empty() {
32 return None;
33 }
34 let options = Options {
35 max_pack_size: manifest.max_pack_size.unwrap_or(DEFAULT_MAX_PACK_SIZE),
36 ..Options::new(manifest.registries.clone())
37 };
38 Some(Proxy::new(options, Client::new(TIMEOUT)))
39}
40
41impl Compmd {
42 /// The state of an app serving `bundle` at `origin`, with `store`.
43 pub(crate) fn new(
44 bundle: Option<Bundle>,
45 origin: Option<String>,
46 store: Arc<dyn Store>,
47 ) -> Self {
48 Self {
49 proxy: bundle
50 .as_ref()
51 .and_then(|bundle| proxy_of(bundle.manifest())),
52 bundle: bundle.map(Arc::new),
53 origin,
54 store,
55 }
56 }
57
58 /// The bundle, when the app's build embedded one.
59 #[must_use]
60 pub fn bundle(&self) -> Option<&Bundle> {
61 self.bundle.as_deref()
62 }
63
64 /// Where the bundle is served, as the page has it in `__COMPMD__`: `compmd://localhost`, or
65 /// `http://compmd.localhost` on Windows and Android.
66 #[must_use]
67 pub fn origin(&self) -> Option<&str> {
68 self.origin.as_deref()
69 }
70
71 /// The store of the packs the app fetches, in its data folder.
72 #[must_use]
73 pub fn store(&self) -> &dyn Store {
74 self.store.as_ref()
75 }
76
77 /// The answer to a webview's `request` on the scheme: under `registry/`, the proxy's, when the bundle fetches
78 /// through the host (it blocks on the registry, so the scheme answers it on a thread of its own); otherwise the
79 /// serving contract (`compmd-host`'s `respond`), or a `404` saying why when there is no bundle, with the
80 /// contract's refusal headers, so the page can read it.
81 #[must_use]
82 pub fn respond<B>(&self, request: &Request<B>) -> Response<Vec<u8>> {
83 let path = request.uri().path();
84 if let (Some(proxy), Some(origin), Some(rest)) =
85 (&self.proxy, &self.origin, path.strip_prefix(REGISTRY))
86 {
87 let mut answer = proxy.answer(rest, &format!("{origin}{REGISTRY}"));
88 // The app's page is on an origin of its own, and a pack's metadata and tarballs are public.
89 answer.headers_mut().insert(
90 header::ACCESS_CONTROL_ALLOW_ORIGIN,
91 HeaderValue::from_static("*"),
92 );
93 return answer;
94 }
95 self.bundle.as_ref().map_or_else(
96 || {
97 refused(Refusal {
98 status: StatusCode::NOT_FOUND,
99 why: NO_BUNDLE,
100 })
101 },
102 |bundle| respond(bundle, self.store(), request),
103 )
104 }
105
106 /// The processor's packs: the bundle's, then the store's, the same files the frames load, with the policy and
107 /// ambient packs the bundle's configuration made, which the processor is given too; none without a bundle.
108 ///
109 /// ```ignore
110 /// let packs = app.compmd().packs().expect("a bundle");
111 /// let (policy, ambient) = (packs.policy()?, packs.ambient());
112 /// let processor = Processor::new(path, text).parse(&ParseOptions::default()).resolve_with((), packs, &ambient, &policy);
113 /// ```
114 #[cfg(feature = "processor")]
115 #[must_use]
116 pub fn packs(&self) -> Option<compmd_host::HostPacks> {
117 let bundle = Arc::clone(self.bundle.as_ref()?);
118 Some(compmd_host::HostPacks::new(bundle, Arc::clone(&self.store)))
119 }
120}