Skip to content

Commit

Permalink
Implement a rough kv asset handler
Browse files Browse the repository at this point in the history
  • Loading branch information
SeokminHong committed Apr 30, 2022
1 parent 1611b68 commit 5c7051d
Show file tree
Hide file tree
Showing 12 changed files with 72 additions and 3 deletions.
18 changes: 17 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion worker-build/src/bundler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ pub fn bundle_worker(shim_src: String, mut dst: impl Write) -> Result<()> {
Config {
// In the future it could be nice for us to allow to have snippets that need wasm
// probably blocked on https://github.com/rustwasm/wasm-bindgen/issues/2375.
external_modules: vec!["./index_bg.wasm".into()],
external_modules: vec!["./index_bg.wasm".into(), "__STATIC_CONTENT_MANIFEST".into()],
..Default::default()
},
Box::new(NoopHook),
Expand Down
Binary file added worker-sandbox/bucket/test.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions worker-sandbox/bucket/test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Test text
3 changes: 3 additions & 0 deletions worker-sandbox/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -553,6 +553,9 @@ pub async fn main(req: Request, env: Env, _ctx: worker::Context) -> Result<Respo
let init_called = GLOBAL_STATE.load(Ordering::SeqCst);
Response::ok(init_called.to_string())
})
.get_async("/:sites", |req, ctx| async {
get_asset_from_kv(req, ctx).await
})
.or_else_any_method_async("/*catchall", |_, ctx| async move {
console_log!(
"[or_else_any_method_async] caught: {}",
Expand Down
3 changes: 3 additions & 0 deletions worker-sandbox/wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,6 @@ main = "./shim.mjs"
[[build.upload.rules]]
globs = ["**/*.wasm"]
type = "CompiledWasm"

[site]
bucket = "./bucket"
3 changes: 3 additions & 0 deletions worker-sys/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ description = "Low-level extern definitions / FFI bindings to the Cloudflare Wor
cfg-if = "1.0.0"
js-sys = "0.3.57"
wasm-bindgen = "0.2.80"
serde_json = "=1.0.79"
serde-wasm-bindgen = "=0.4.2"
once_cell = "1.10.0"

[dependencies.web-sys]
version = "0.3.57"
Expand Down
13 changes: 13 additions & 0 deletions worker-sys/src/asset_handler.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use std::collections::HashMap;

use once_cell::sync::Lazy;
use wasm_bindgen::prelude::*;

#[wasm_bindgen(module = "__STATIC_CONTENT_MANIFEST")]
extern "C" {
#[wasm_bindgen(js_name = "default")]
static MANIFEST_STR: String;
}

pub static ASSET_MANIFEST: Lazy<HashMap<&str, &str>> =
Lazy::new(|| serde_json::from_str(&MANIFEST_STR).unwrap_or_default());
2 changes: 2 additions & 0 deletions worker-sys/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#![allow(clippy::manual_non_exhaustive)]

pub mod abort;
pub mod asset_handler;
pub mod cf;
pub mod context;
pub mod durable_object;
Expand Down Expand Up @@ -59,6 +60,7 @@ pub mod prelude {
}

pub use abort::*;
pub use asset_handler::*;
pub use cf::Cf;
pub use context::Context;
pub use durable_object::*;
Expand Down
5 changes: 4 additions & 1 deletion worker/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,15 @@ readme = "../README.md"

[dependencies]
async-trait = "0.1.53"
chrono = { version = "0.4.19", default-features = false, features = ["wasmbind"] }
chrono = { version = "0.4.19", default-features = false, features = [
"wasmbind",
] }
chrono-tz = { version = "0.6.1", default-features = false }
futures = "0.3.21"
http = "0.2.6"
js-sys = "0.3.57"
matchit = "0.4.6"
mime_guess = "2.0.4"
pin-project = "1.0.10"
serde = { version = "1.0.136", features = ["derive"] }
serde_json = "1.0.79"
Expand Down
22 changes: 22 additions & 0 deletions worker/src/asset_handler.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use crate::request::Request;
use crate::response::Response;
use crate::{Headers, Result, RouteContext};
use worker_sys::ASSET_MANIFEST;

const ASSET_NAMESPACE: &str = "__STATIC_CONTENT";

pub async fn get_asset_from_kv<D>(req: Request, ctx: RouteContext<D>) -> Result<Response> {
let url = req.url()?;
let path = &url.path()[1..];
let mime = mime_guess::from_path(path).first_or_octet_stream();

let key = ASSET_MANIFEST.get(path).unwrap_or(&path);
let bytes = ctx.kv(ASSET_NAMESPACE)?.get(key).bytes().await?;
if let Some(bytes) = bytes {
let mut headers = Headers::new();
headers.set("content_type", &mime.to_string())?;
return Ok(Response::from_bytes(bytes)?.with_headers(headers));
}

Response::error("Not found", 404)
}
3 changes: 3 additions & 0 deletions worker/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#![allow(clippy::or_fun_call)]

mod abort;
mod asset_handler;
mod cf;
mod context;
mod cors;
Expand All @@ -28,6 +29,8 @@ use std::result::Result as StdResult;
pub type Result<T> = StdResult<T, error::Error>;

pub use crate::abort::*;
pub use crate::asset_handler::*;
//pub use crate::cache::Cache;
pub use crate::context::Context;
pub use crate::cors::Cors;
pub use crate::date::{Date, DateInit};
Expand Down

0 comments on commit 5c7051d

Please sign in to comment.