1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
mod service_protocol;
mod vm;

use std::borrow::Cow;
use std::time::Duration;

pub use vm::CoreVM;

#[derive(Debug, Eq, PartialEq)]
pub struct Header {
    pub key: Cow<'static, str>,
    pub value: Cow<'static, str>,
}

#[derive(Debug)]
pub struct ResponseHead {
    pub status_code: u16,
    pub headers: Vec<Header>,
}

#[derive(Debug, Clone, Copy, thiserror::Error)]
#[error("Suspended execution")]
pub struct SuspendedError;

#[derive(Debug, Clone, thiserror::Error)]
#[error("VM Error [{code}]: {message}. Description: {description}")]
pub struct VMError {
    pub code: u16,
    pub message: Cow<'static, str>,
    pub description: Cow<'static, str>,
}

impl VMError {
    pub fn new(code: impl Into<u16>, message: impl Into<Cow<'static, str>>) -> Self {
        VMError {
            code: code.into(),
            message: message.into(),
            description: Default::default(),
        }
    }
}

#[derive(Debug, Clone, thiserror::Error)]
pub enum SuspendedOrVMError {
    #[error(transparent)]
    Suspended(SuspendedError),
    #[error(transparent)]
    VM(VMError),
}

#[derive(Debug, Eq, PartialEq)]
pub struct Input {
    pub invocation_id: String,
    pub random_seed: u64,
    pub key: String,
    pub headers: Vec<Header>,
    pub input: Vec<u8>,
}

#[derive(Debug, Eq, PartialEq)]
pub struct Target {
    pub service: String,
    pub handler: String,
    pub key: Option<String>,
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct AsyncResultHandle(u32);

impl From<u32> for AsyncResultHandle {
    fn from(value: u32) -> Self {
        AsyncResultHandle(value)
    }
}

impl From<AsyncResultHandle> for u32 {
    fn from(value: AsyncResultHandle) -> Self {
        value.0
    }
}

#[derive(Debug, Eq, PartialEq)]
pub enum Value {
    // a void/None/undefined success
    Void,
    Success(Vec<u8>),
    Failure(Failure),
}

/// Terminal failure
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Failure {
    pub code: u16,
    pub message: String,
}

#[derive(Debug)]
pub enum RunEnterResult {
    Executed(NonEmptyValue),
    NotExecuted,
}

#[derive(Debug, Clone)]
pub enum NonEmptyValue {
    Success(Vec<u8>),
    Failure(Failure),
}

impl From<NonEmptyValue> for Value {
    fn from(value: NonEmptyValue) -> Self {
        match value {
            NonEmptyValue::Success(s) => Value::Success(s),
            NonEmptyValue::Failure(f) => Value::Failure(f),
        }
    }
}

#[derive(Debug, Eq, PartialEq)]
pub enum TakeOutputResult {
    Buffer(Vec<u8>),
    EOF,
}

pub type VMResult<T> = Result<T, VMError>;

pub trait VM: Sized {
    fn new(request_headers: Vec<(String, String)>) -> VMResult<Self>;

    fn get_response_head(&self) -> ResponseHead;

    // --- Input stream

    fn notify_input(&mut self, buffer: Vec<u8>);

    fn notify_input_closed(&mut self);

    // --- Errors

    fn notify_error(&mut self, message: Cow<'static, str>, description: Cow<'static, str>);

    // --- Output stream

    fn take_output(&mut self) -> TakeOutputResult;

    // --- Execution start waiting point

    fn is_ready_to_execute(&self) -> Result<bool, VMError>;

    // --- Async results

    fn notify_await_point(&mut self, handle: AsyncResultHandle);

    /// Ok(None) means the result is not ready.
    fn take_async_result(
        &mut self,
        handle: AsyncResultHandle,
    ) -> Result<Option<Value>, SuspendedOrVMError>;

    // --- Syscall(s)

    fn sys_input(&mut self) -> VMResult<Input>;

    fn sys_get_state(&mut self, key: String) -> VMResult<AsyncResultHandle>;

    // TODO sys_get_keys_state(&mut self)

    fn sys_set_state(&mut self, key: String, value: Vec<u8>) -> VMResult<()>;

    fn sys_clear_state(&mut self, key: String) -> VMResult<()>;

    fn sys_clear_all_state(&mut self) -> VMResult<()>;

    fn sys_sleep(&mut self, duration: Duration) -> VMResult<AsyncResultHandle>;

    fn sys_call(&mut self, target: Target, input: Vec<u8>) -> VMResult<AsyncResultHandle>;

    fn sys_send(&mut self, target: Target, input: Vec<u8>, delay: Option<Duration>)
        -> VMResult<()>;

    fn sys_awakeable(&mut self) -> VMResult<(String, AsyncResultHandle)>;

    fn sys_complete_awakeable(&mut self, id: String, value: NonEmptyValue) -> VMResult<()>;

    fn sys_get_promise(&mut self, key: String) -> VMResult<AsyncResultHandle>;

    fn sys_peek_promise(&mut self, key: String) -> VMResult<AsyncResultHandle>;

    fn sys_complete_promise(
        &mut self,
        key: String,
        value: NonEmptyValue,
    ) -> VMResult<AsyncResultHandle>;

    fn sys_run_enter(&mut self, name: String) -> VMResult<RunEnterResult>;

    fn sys_run_exit(&mut self, value: NonEmptyValue) -> VMResult<AsyncResultHandle>;

    fn sys_write_output(&mut self, value: NonEmptyValue) -> VMResult<()>;

    fn sys_end(&mut self) -> VMResult<()>;
}

// HOW TO USE THIS API
//
// pre_user_code:
//     while !vm.is_ready_to_execute() {
//         match io.read_input() {
//             buffer => vm.notify_input(buffer),
//             EOF => vm.notify_input_closed()
//         }
//     }
//
// sys_[something]:
//     try {
//         vm.sys_[something]()
//         io.write_out(vm.take_output())
//     } catch (e) {
//         log(e)
//         io.write_out(vm.take_output())
//         throw e
//     }
//
// await_restate_future:
//     vm.notify_await_point(handle);
//     loop {
//         // Result here can be value, not_ready, suspended, vm error
//         let result = vm.take_async_result(handle);
//         if result.is_not_ready() {
//             match await io.read_input() {
//                buffer => vm.notify_input(buffer),
//                EOF => vm.notify_input_closed()
//             }
//         }
//         return result
//     }
//
// post_user_code:
//     // Consume vm.take_output() until EOF
//     while buffer = vm.take_output() {
//         io.write_out(buffer)
//     }
//     io.close()

#[cfg(test)]
mod tests;