Skip to content

Commit

Permalink
feat(tauri): add cache option (#13)
Browse files Browse the repository at this point in the history
## Summary

Add cache option for tauri plugin.

## Test Plan

Should pass CI.
  • Loading branch information
seokju-na authored Oct 27, 2024
1 parent 48b2d44 commit f912a24
Show file tree
Hide file tree
Showing 6 changed files with 112 additions and 17 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ bincode = "2.0.0-rc.3"
biome_console = "0.5.7"
bpaf = { version = "0.9.14", features = ["derive"] }
lz4_flex = "0.11.3"
mime_guess = "2.0.5"
napi = { version = "2.16.11", default-features = false, features = ["napi4", "async"] }
napi-build = "2.1.3"
napi-derive = "2.16.12"
Expand Down
5 changes: 5 additions & 0 deletions crates/webview-bundle-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ webview-bundle = { workspace = true }

async-trait = { workspace = true }
buildstructor = "0.5.4"
lru = { version = "0.12.5", optional = true }
mime_guess = { workspace = true }
tauri = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true }

[features]
cache-lru = ["dep:lru"]
61 changes: 61 additions & 0 deletions crates/webview-bundle-tauri/src/cache.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
use std::hash::Hash;
use webview_bundle::Bundle;

pub trait Cache<K: Hash + Eq, V> {
fn has(&self, key: &K) -> bool;
fn get(&mut self, key: &K) -> Option<&V>;
fn set(&mut self, key: K, value: V);
}

#[derive(Clone, Default)]
pub struct NoopCache;

impl Cache<String, Bundle> for NoopCache {
fn has(&self, _key: &String) -> bool {
false
}

fn get(&mut self, _key: &String) -> Option<&Bundle> {
None
}

fn set(&mut self, _key: String, _value: Bundle) {}
}

#[cfg(feature = "cache-lru")]
#[derive(Clone)]
pub struct LruCache<K: Hash + Eq, V> {
cache: lru::LruCache<K, V>,
}

#[cfg(feature = "cache-lru")]
impl<K: Hash + Eq, V> LruCache<K, V> {
pub fn new(size: usize) -> Self {
Self {
cache: lru::LruCache::<K, V>::new(
std::num::NonZeroUsize::new(size).expect("size is not non zero"),
),
}
}

pub fn unbounded() -> Self {
Self {
cache: lru::LruCache::<K, V>::unbounded(),
}
}
}

#[cfg(feature = "cache-lru")]
impl Cache<String, Bundle> for LruCache<String, Bundle> {
fn has(&self, key: &String) -> bool {
self.cache.contains(key)
}

fn get(&mut self, key: &String) -> Option<&Bundle> {
self.cache.get(key)
}

fn set(&mut self, key: String, value: Bundle) {
self.cache.put(key, value);
}
}
20 changes: 16 additions & 4 deletions crates/webview-bundle-tauri/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,32 @@
use crate::cache::Cache;
use crate::loader::Loader;
use webview_bundle::Bundle;

pub struct Config<L: Loader + Send + Sync> {
pub struct Config<L, C>
where
L: Loader + Send + Sync,
C: Cache<String, Bundle> + Send + Sync,
{
loader: L,
cache: C,
}

#[buildstructor::buildstructor]
impl<L> Config<L>
impl<L, C> Config<L, C>
where
L: Loader + Send + Sync,
C: Cache<String, Bundle> + Send + Sync,
{
#[builder]
pub fn new(loader: L) -> Self {
Self { loader }
pub fn new(loader: L, cache: C) -> Self {
Self { loader, cache }
}

pub fn loader(&self) -> &L {
&self.loader
}

pub fn cache(&self) -> &C {
&self.cache
}
}
33 changes: 22 additions & 11 deletions crates/webview-bundle-tauri/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
mod config;
mod error;
mod loader;
pub mod cache;
pub mod config;
pub mod error;
pub mod loader;

pub use config::Config;
pub use error::Error;
pub use loader::{FSLoader, Loader};
use crate::cache::Cache;
use crate::config::Config;
use crate::loader::Loader;
use std::path::Path;
use tauri::http::{Method, Response, Uri};
use tauri::plugin::{PluginApi, TauriPlugin};
use tauri::{plugin, AppHandle, Manager, Runtime};
use webview_bundle::Bundle;

pub fn init<R, L, F>(scheme: &'static str, config: F) -> TauriPlugin<R>
pub fn init<R, L, C, F>(scheme: &'static str, config: F) -> TauriPlugin<R>
where
R: Runtime,
L: Loader + Send + Sync + 'static,
F: FnOnce(&AppHandle<R>, PluginApi<R, ()>) -> Result<Config<L>, Box<dyn std::error::Error>>
C: Cache<String, Bundle> + Send + Sync + 'static,
F: FnOnce(&AppHandle<R>, PluginApi<R, ()>) -> Result<Config<L, C>, Box<dyn std::error::Error>>
+ Send
+ 'static,
{
Expand All @@ -33,13 +36,13 @@ where
let uri = request.uri().clone();
let app = ctx.app_handle().clone();
tauri::async_runtime::spawn(async move {
let config = app.state::<Config<L>>();
let config = app.state::<Config<L, C>>();
let bundle = config.loader().load(&uri).await.unwrap();
let filepath = uri_to_filepath(&uri);
let buf = bundle.read_file(filepath).unwrap();
let buf = bundle.read_file(&filepath).unwrap(); // TODO: handle file not found error
responder.respond(
Response::builder()
.header("content-type", "text/html")
.header("content-type", mime_types_from_filepath(&filepath))
.header("content-length", buf.len())
.status(200)
.body(buf)
Expand All @@ -61,3 +64,11 @@ fn uri_to_filepath(uri: &Uri) -> String {
}
[filepath, index_html].join("/")
}

fn mime_types_from_filepath(filepath: &String) -> String {
let guess = mime_guess::from_path(filepath);
guess
.first()
.map(|x| x.to_string())
.unwrap_or("text/plain".to_string())
}
9 changes: 7 additions & 2 deletions examples/tauri-simple/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use tauri::{Manager, WebviewUrl};
use webview_bundle_tauri::{Config, FSLoader};
use webview_bundle_tauri::cache::NoopCache;
use webview_bundle_tauri::config::Config;
use webview_bundle_tauri::loader::FSLoader;

fn main() {
tauri::Builder::default()
Expand All @@ -10,7 +12,10 @@ fn main() {
dir.pop();
dir.pop();
dir.push("examples/tauri-simple");
let config = Config::builder().loader(FSLoader::from_dir(dir)).build();
let config = Config::builder()
.cache(NoopCache::default())
.loader(FSLoader::from_dir(dir))
.build();
Ok(config)
}))
.setup(|app| {
Expand Down

0 comments on commit f912a24

Please sign in to comment.