11use std:: ops:: Deref ;
22use std:: thread:: JoinHandle ;
3+ use std:: time:: Duration ;
34
45use bytes:: Bytes ;
56use openworkers_runtime:: FetchInit ;
7+ use openworkers_runtime:: RuntimeLimits ;
68use openworkers_runtime:: Script ;
79use openworkers_runtime:: Task ;
810use openworkers_runtime:: Worker ;
@@ -11,6 +13,9 @@ use crate::store::WorkerData;
1113
1214type ResTx = tokio:: sync:: oneshot:: Sender < http_v02:: Response < Bytes > > ;
1315
16+ // Default timeout for fetch events
17+ const FETCH_TIMEOUT_MS : u64 = 64_000 ; // 64 seconds
18+
1419pub fn run_fetch (
1520 worker : WorkerData ,
1621 req : http_v02:: Request < Bytes > ,
@@ -31,7 +36,14 @@ pub fn run_fetch(
3136
3237 let tasks = local. spawn_local ( async move {
3338 log:: debug!( "create worker" ) ;
34- let mut worker = match Worker :: new ( script, Some ( log_tx) ) . await {
39+
40+ let limits = RuntimeLimits {
41+ max_cpu_time_ms : 100 , // 100ms CPU time for fetch tasks
42+ max_wall_clock_time_ms : 60_000 , // 60s total time for fetch tasks
43+ ..Default :: default ( )
44+ } ;
45+
46+ let mut worker = match Worker :: new ( script, Some ( log_tx) , Some ( limits) ) . await {
3547 Ok ( worker) => worker,
3648 Err ( err) => {
3749 log:: error!( "failed to create worker: {err}" ) ;
@@ -50,10 +62,18 @@ pub fn run_fetch(
5062
5163 let task = Task :: Fetch ( Some ( FetchInit :: new ( req, res_tx) ) ) ;
5264
53- log:: debug!( "exec fetch task" ) ;
54- match worker. exec ( task) . await {
55- Ok ( ( ) ) => log:: debug!( "exec completed" ) ,
56- Err ( err) => log:: error!( "exec did not complete: {err}" ) ,
65+ log:: debug!( "exec fetch task with {}ms timeout" , FETCH_TIMEOUT_MS ) ;
66+
67+ // Wrap execution with timeout
68+ let timeout_duration = Duration :: from_millis ( FETCH_TIMEOUT_MS ) ;
69+ match tokio:: time:: timeout ( timeout_duration, worker. exec ( task) ) . await {
70+ Ok ( Ok ( ( ) ) ) => log:: debug!( "exec completed" ) ,
71+ Ok ( Err ( err) ) => log:: error!( "exec did not complete: {err}" ) ,
72+ Err ( _) => {
73+ log:: error!( "exec timeout after {}ms" , FETCH_TIMEOUT_MS ) ;
74+ // Note: Worker may have already sent a response via FetchInit
75+ // If no response was sent, res_tx will be dropped and client gets an error
76+ }
5777 }
5878 } ) ;
5979
0 commit comments