Skip to content
File

Blob: src/rust/worker/error.rs

rust108 lines
1// Copyright (c) 2026 Cloudflare, Inc.
2// Licensed under the Apache 2.0 license found in the LICENSE file or at:
3// https://opensource.org/licenses/Apache-2.0
4 
5use std::pin::Pin;
6use std::time::SystemTime;
7 
8use cxx::KjError;
9use kj::http::ConnectResponse;
10use kj::http::ConnectSettings;
11use kj::http::HeadersRef;
12use kj::http::Method;
13use kj::http::ServiceResponse;
14use kj::io::AsyncInputStream;
15use kj::io::AsyncIoStream;
16 
17use crate::AlarmResult;
18use crate::Interface;
19use crate::ScheduledResult;
20use crate::ffi::Wrapper;
21 
22#[cxx::bridge(namespace = "workerd::rust::worker")]
23pub mod bridge {
24 extern "Rust" {
25 type Wrapper = crate::ffi::Wrapper;
26 
27 #[expect(
28 clippy::unnecessary_box_returns,
29 reason = "c++ expects heap-allocation"
30 )]
31 fn new_error_worker(message: &str) -> Box<Wrapper>;
32 }
33}
34 
35/// Worker that returns errors for all methods.
36pub struct Worker {
37 message: String,
38}
39 
40impl Worker {
41 pub fn new(message: String) -> Self {
42 Self { message }
43 }
44 
45 fn error(&self, file: &str, line: u32) -> KjError {
46 KjError::new(
47 cxx::KjExceptionType::Failed,
48 format!("jsg.Error: {}", self.message),
49 )
50 .with_location(file.to_owned(), line)
51 }
52}
53 
54#[async_trait::async_trait(?Send)]
55impl kj::http::Service for Worker {
56 async fn request<'a>(
57 &'a mut self,
58 _method: Method,
59 _url: &'a [u8],
60 _headers: HeadersRef<'a>,
61 _request_body: Pin<&'a mut AsyncInputStream>,
62 _response: ServiceResponse<'a>,
63 ) -> crate::Result<()> {
64 Err(self.error(file!(), line!()))
65 }
66 
67 async fn connect<'a>(
68 &'a mut self,
69 _host: &'a [u8],
70 _headers: HeadersRef<'a>,
71 _connection: Pin<&'a mut AsyncIoStream>,
72 _response: ConnectResponse<'a>,
73 _settings: ConnectSettings<'a>,
74 ) -> crate::Result<()> {
75 Err(self.error(file!(), line!()))
76 }
77}
78 
79#[async_trait::async_trait(?Send)]
80impl Interface for Worker {
81 async fn run_scheduled(
82 &mut self,
83 _scheduled_time: &SystemTime,
84 _cron: &str,
85 ) -> crate::Result<ScheduledResult> {
86 Err(self.error(file!(), line!()))
87 }
88 
89 async fn run_alarm(
90 &mut self,
91 _scheduled_time: &SystemTime,
92 _retry_count: u32,
93 ) -> crate::Result<AlarmResult> {
94 Err(self.error(file!(), line!()))
95 }
96 
97 async fn custom_event(
98 &mut self,
99 _event: Pin<&mut crate::CustomEvent>,
100 ) -> crate::Result<crate::CustomEventResult> {
101 Err(self.error(file!(), line!()))
102 }
103}
104 
105pub fn new_error_worker(message: &str) -> Box<Wrapper> {
106 Worker::new(message.to_owned()).into_ffi()
107}