Skip to content

Commit 9cff703

Browse files
authored
Merge pull request supabase#136 from supabase/print-when-log-not-available
fix: print to stderr when logger is not available
2 parents d6556b2 + bc7e75a commit 9cff703

File tree

5 files changed

+85
-76
lines changed

5 files changed

+85
-76
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

crates/base/src/worker_ctx.rs

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -266,14 +266,20 @@ pub async fn create_worker(
266266
};
267267

268268
let end_time = get_thread_time()?;
269-
send_event_if_event_manager_available(
270-
events_msg_tx_clone.clone(),
271-
WorkerEvents::Log(LogEvent {
272-
msg: format!("CPU time used: {:?}ms", (end_time - start_time) / 1_000_000),
273-
level: LogLevel::Info,
274-
}),
275-
event_metadata_clone.clone(),
276-
);
269+
let cpu_time_msg =
270+
format!("CPU time used: {:?}ms", (end_time - start_time) / 1_000_000);
271+
if events_msg_tx_clone.is_some() {
272+
send_event_if_event_manager_available(
273+
events_msg_tx_clone.clone(),
274+
WorkerEvents::Log(LogEvent {
275+
msg: cpu_time_msg,
276+
level: LogLevel::Info,
277+
}),
278+
event_metadata_clone.clone(),
279+
);
280+
} else {
281+
error!("{}", cpu_time_msg);
282+
}
277283

278284
// remove the worker from pool
279285
if worker_key.is_some() {

crates/sb_workers/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,5 @@ deno_http.workspace = true
1919
hyper.workspace = true
2020
serde.workspace = true
2121
bytes.workspace = true
22+
log.workspace = true
2223
sb_worker_context = { version = "0.1.0", path = "../sb_worker_context" }

crates/sb_workers/lib.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ use deno_core::{
1212
use hyper::body::HttpBody;
1313
use hyper::header::{HeaderName, HeaderValue};
1414
use hyper::{Body, Request, Response};
15+
use log::error;
1516
use sb_worker_context::essentials::{
1617
CreateUserWorkerResult, UserWorkerMsgs, UserWorkerRuntimeOpts, WorkerContextInitOpts,
1718
WorkerRuntimeOpts,
@@ -158,7 +159,7 @@ pub fn op_user_worker_log(state: &mut OpState, msg: &str, is_err: bool) -> Resul
158159
metadata: event_metadata,
159160
})?;
160161
} else {
161-
println!("[{:?}] {}", level, msg);
162+
error!("[{:?}] {}", level, msg);
162163
}
163164
Ok(())
164165
}

examples/main/index.ts

Lines changed: 67 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -1,79 +1,79 @@
1-
import { serve } from 'https://deno.land/[email protected]/http/server.ts';
1+
import { serve } from "https://deno.land/[email protected]/http/server.ts";
22

3-
console.log('main function started');
3+
console.log("main function started");
44

55
serve(async (req: Request) => {
6-
const url = new URL(req.url);
7-
const { pathname } = url;
6+
const url = new URL(req.url);
7+
const { pathname } = url;
88

9-
// handle health checks
10-
if (pathname === '/_internal/health') {
11-
return new Response(
12-
JSON.stringify({ 'message': 'ok' }),
13-
{ status: 200, headers: { 'Content-Type': 'application/json' } },
14-
);
15-
}
9+
// handle health checks
10+
if (pathname === "/_internal/health") {
11+
return new Response(
12+
JSON.stringify({ "message": "ok" }),
13+
{ status: 200, headers: { "Content-Type": "application/json" } },
14+
);
15+
}
1616

17-
const path_parts = pathname.split('/');
18-
const service_name = path_parts[1];
17+
const path_parts = pathname.split("/");
18+
const service_name = path_parts[1];
1919

20-
if (!service_name || service_name === '') {
21-
const error = { msg: 'missing function name in request' };
22-
return new Response(
23-
JSON.stringify(error),
24-
{ status: 400, headers: { 'Content-Type': 'application/json' } },
25-
);
26-
}
20+
if (!service_name || service_name === "") {
21+
const error = { msg: "missing function name in request" };
22+
return new Response(
23+
JSON.stringify(error),
24+
{ status: 400, headers: { "Content-Type": "application/json" } },
25+
);
26+
}
2727

28-
const servicePath = `./examples/${service_name}`;
29-
console.error(`serving the request with ${servicePath}`);
28+
const servicePath = `./examples/${service_name}`;
29+
console.error(`serving the request with ${servicePath}`);
3030

31-
const createWorker = async () => {
32-
const memoryLimitMb = 150;
33-
const workerTimeoutMs = 10 * 1000;
34-
const noModuleCache = false;
35-
const customModuleRoot = null;
36-
// you can provide an import map inline
37-
// const inlineImportMap = {
38-
// imports: {
39-
// "std/": "https://deno.land/[email protected]/",
40-
// "cors": "./examples/_shared/cors.ts"
41-
// }
42-
// }
43-
// const importMapPath = `data:${encodeURIComponent(JSON.stringify(importMap))}?${encodeURIComponent('/home/deno/functions/test')}`;
44-
const importMapPath = null;
45-
const envVarsObj = Deno.env.toObject();
46-
const envVars = Object.keys(envVarsObj).map((k) => [k, envVarsObj[k]]);
47-
const forceCreate = false;
31+
const createWorker = async () => {
32+
const memoryLimitMb = 150;
33+
const workerTimeoutMs = 5 * 60 * 1000;
34+
const noModuleCache = false;
35+
const customModuleRoot = null;
36+
// you can provide an import map inline
37+
// const inlineImportMap = {
38+
// imports: {
39+
// "std/": "https://deno.land/[email protected]/",
40+
// "cors": "./examples/_shared/cors.ts"
41+
// }
42+
// }
43+
// const importMapPath = `data:${encodeURIComponent(JSON.stringify(importMap))}?${encodeURIComponent('/home/deno/functions/test')}`;
44+
const importMapPath = null;
45+
const envVarsObj = Deno.env.toObject();
46+
const envVars = Object.keys(envVarsObj).map((k) => [k, envVarsObj[k]]);
47+
const forceCreate = false;
4848

49-
return await EdgeRuntime.userWorkers.create({
50-
servicePath,
51-
memoryLimitMb,
52-
workerTimeoutMs,
53-
noModuleCache,
54-
importMapPath,
55-
envVars,
56-
forceCreate,
57-
customModuleRoot,
58-
});
59-
};
49+
return await EdgeRuntime.userWorkers.create({
50+
servicePath,
51+
memoryLimitMb,
52+
workerTimeoutMs,
53+
noModuleCache,
54+
importMapPath,
55+
envVars,
56+
forceCreate,
57+
customModuleRoot,
58+
});
59+
};
6060

61-
const callWorker = async () => {
62-
try {
63-
// If a worker for the given service path already exists,
64-
// it will be reused by default.
65-
// Update forceCreate option in createWorker to force create a new worker for each request.
66-
const worker = await createWorker();
67-
return await worker.fetch(req);
68-
} catch (e) {
69-
console.error(e);
70-
const error = { msg: e.toString() };
71-
return new Response(
72-
JSON.stringify(error),
73-
{ status: 500, headers: { 'Content-Type': 'application/json' } },
74-
);
75-
}
76-
};
61+
const callWorker = async () => {
62+
try {
63+
// If a worker for the given service path already exists,
64+
// it will be reused by default.
65+
// Update forceCreate option in createWorker to force create a new worker for each request.
66+
const worker = await createWorker();
67+
return await worker.fetch(req);
68+
} catch (e) {
69+
console.error(e);
70+
const error = { msg: e.toString() };
71+
return new Response(
72+
JSON.stringify(error),
73+
{ status: 500, headers: { "Content-Type": "application/json" } },
74+
);
75+
}
76+
};
7777

78-
return callWorker();
78+
return callWorker();
7979
});

0 commit comments

Comments
 (0)