Skip to content

Commit

Permalink
chore: make sure that we can use javascript as an entrypoint (#424)
Browse files Browse the repository at this point in the history
* chore: make sure that we can use js script as an entrypoint

* chore: add js flavored examples

* stamp: clippy
  • Loading branch information
nyannyacha authored Oct 7, 2024
1 parent 7c378e6 commit 5bd54ed
Show file tree
Hide file tree
Showing 8 changed files with 213 additions and 2 deletions.
2 changes: 2 additions & 0 deletions crates/base/test_cases/eszip-js/npm-supabase-js/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import { createClient } from "npm:@supabase/[email protected]";
Deno.serve((_req) => new Response(`${typeof createClient}`));
4 changes: 4 additions & 0 deletions crates/base/test_cases/eszip-js/serve-js/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Deno.serve(req => {
console.log(req.headers.get("content-type"));
return new Response("meow");
});
65 changes: 65 additions & 0 deletions crates/base/test_cases/main_eszip/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
console.log('main function started');

Deno.serve(async (req: Request) => {
console.log(req.url);
const url = new URL(req.url);
const { pathname } = url;
const path_parts = pathname.split("/");
const service_name = path_parts[1];
const maybeEszip = new Uint8Array(await req.arrayBuffer());

if (!service_name || service_name === "") {
const error = { msg: "missing function name in request" }
return new Response(
JSON.stringify(error),
{ status: 400, headers: { "Content-Type": "application/json" } },
)
}

const servicePath = `./test_cases/${service_name}`;
console.error(`serving the request with ${servicePath}`);

const createWorker = async () => {
const memoryLimitMb = 150;
const workerTimeoutMs = 10 * 60 * 1000;
const cpuTimeSoftLimitMs = 10 * 60 * 1000;
const cpuTimeHardLimitMs = 10 * 60 * 1000;
const noModuleCache = false;
const importMapPath = null;
const envVarsObj = Deno.env.toObject();
const envVars = Object.keys(envVarsObj).map(k => [k, envVarsObj[k]]);

return await EdgeRuntime.userWorkers.create({
servicePath,
memoryLimitMb,
workerTimeoutMs,
cpuTimeSoftLimitMs,
cpuTimeHardLimitMs,
noModuleCache,
importMapPath,
envVars,
maybeEszip
});
}

const callWorker = async () => {
try {
const worker = await createWorker();
return await worker.fetch(req);
} catch (e) {
console.error(e);

// if (e instanceof Deno.errors.WorkerRequestCancelled) {
// return await callWorker();
// }

const error = { msg: e.toString() }
return new Response(
JSON.stringify(error),
{ status: 500, headers: { "Content-Type": "application/json" } },
);
}
}

return callWorker();
})
10 changes: 10 additions & 0 deletions crates/base/test_cases/serve-declarative-style-js/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export default {
/**
* @param {Request} req
* @returns {void}
*/
fetch(req) {
console.log(req.headers.get("content-type"));
return new Response("meow");
}
}
4 changes: 4 additions & 0 deletions crates/base/test_cases/serve-js/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Deno.serve(req => {
console.log(req.headers.get("content-type"));
return new Response("meow");
});
116 changes: 114 additions & 2 deletions crates/base/tests/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ mod integration_test_helper;
use http_v02 as http;
use hyper_v014 as hyper;
use reqwest_v011 as reqwest;
use sb_graph::EszipPayloadKind;
use sb_graph::{emitter::EmitterFactory, generate_binary_eszip, EszipPayloadKind};

use std::{
borrow::Cow,
collections::HashMap,
io::{self, Cursor},
net::{IpAddr, Ipv4Addr, SocketAddr},
path::Path,
path::{Path, PathBuf},
sync::Arc,
time::Duration,
};
Expand Down Expand Up @@ -2388,6 +2388,118 @@ async fn test_should_render_detailed_failed_to_create_graph_error() {
}
}

#[tokio::test]
#[serial]
async fn test_js_entrypoint() {
{
integration_test!(
"./test_cases/main",
NON_SECURE_PORT,
"serve-js",
None,
None,
None,
None,
(|resp| async {
let resp = resp.unwrap();
assert_eq!(resp.status().as_u16(), 200);
let msg = resp.text().await.unwrap();
assert_eq!(msg, "meow");
}),
TerminationToken::new()
);
}

{
integration_test!(
"./test_cases/main",
NON_SECURE_PORT,
"serve-declarative-style-js",
None,
None,
None,
None,
(|resp| async {
let resp = resp.unwrap();
assert_eq!(resp.status().as_u16(), 200);
let msg = resp.text().await.unwrap();
assert_eq!(msg, "meow");
}),
TerminationToken::new()
);
}

let get_eszip_buf = |path: &'static str| async move {
generate_binary_eszip(
PathBuf::from(path),
#[allow(clippy::arc_with_non_send_sync)]
Arc::new(EmitterFactory::new()),
None,
None,
None,
)
.await
.unwrap()
.into_bytes()
};

{
let buf = get_eszip_buf("./test_cases/eszip-js/serve-js/index.js").await;
let client = Client::new();
let req = client
.request(
Method::POST,
format!("http://localhost:{}/meow", NON_SECURE_PORT),
)
.body(buf);

integration_test!(
"./test_cases/main_eszip",
NON_SECURE_PORT,
"",
None,
None,
Some(req),
None,
(|resp| async {
let resp = resp.unwrap();
assert_eq!(resp.status().as_u16(), 200);
let msg = resp.text().await.unwrap();
assert_eq!(msg, "meow");
}),
TerminationToken::new()
);
}

{
let buf = get_eszip_buf("./test_cases/eszip-js/npm-supabase-js/index.js").await;
let client = Client::new();
let req = client
.request(
Method::POST,
format!("http://localhost:{}/meow", NON_SECURE_PORT),
)
.body(buf);

integration_test!(
"./test_cases/main_eszip",
NON_SECURE_PORT,
"",
None,
None,
Some(req),
None,
(|resp| async {
let resp = resp.unwrap();
assert_eq!(resp.status().as_u16(), 200);
let msg = resp.text().await.unwrap();
assert_eq!(msg, "function");
}),
TerminationToken::new()
);
}
}

#[derive(Deserialize)]
struct ErrorResponsePayload {
msg: String,
Expand Down
10 changes: 10 additions & 0 deletions examples/serve-declarative-style-js/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export default {
/**
* @param {Request} req
* @returns {void}
*/
fetch(req) {
console.log(req.headers.get("content-type"));
return new Response("Hello, world");
}
}
4 changes: 4 additions & 0 deletions examples/serve-js/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Deno.serve(req => {
console.log(req.headers.get("content-type"));
return new Response("Hello, world");
});

0 comments on commit 5bd54ed

Please sign in to comment.