theater 0.3.12

A WebAssembly actor system for AI agents
Documentation
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//! # Actor Handle
//!
//! This module provides the `ActorHandle` type, which serves as the primary interface
//! for interacting with actors in the Theater system.

use anyhow::Result;

use tokio::sync::{mpsc, oneshot};
use tokio::time::timeout;
use tracing::error;

use crate::actor::types::{
    ActorError, ActorOperation, WasiHttpResponse, DEFAULT_OPERATION_TIMEOUT,
};
use crate::chain::ChainEvent;
use crate::metrics::ActorMetrics;
use crate::pack_bridge::{self, InterfaceHash, Value};

use super::types::{ActorControl, ActorInfo};

/// # ActorHandle
///
/// A handle to an actor in the Theater system, providing methods to interact with the actor.
///
/// ## Purpose
///
/// ActorHandle provides a high-level interface for communicating with actors, managing their
/// lifecycle, and accessing their state and events. It encapsulates the details of message
/// passing and synchronization between the caller and the actor's execution environment.
#[derive(Clone, Debug)]
pub struct ActorHandle {
    operation_tx: mpsc::Sender<ActorOperation>,
    info_tx: mpsc::Sender<ActorInfo>,
    control_tx: mpsc::Sender<ActorControl>,
}

impl ActorHandle {
    /// Creates a new ActorHandle with the given operation channel.
    ///
    /// ## Parameters
    ///
    /// * `operation_tx` - The sender side of a channel used to send operations to the actor.
    ///
    /// ## Returns
    ///
    /// A new ActorHandle instance.
    pub fn new(
        operation_tx: mpsc::Sender<ActorOperation>,
        info_tx: mpsc::Sender<ActorInfo>,
        control_tx: mpsc::Sender<ActorControl>,
    ) -> Self {
        Self {
            operation_tx,
            info_tx,
            control_tx,
        }
    }

    /// Calls a function on the actor with Pack-native Value params and return.
    ///
    /// ## Parameters
    ///
    /// * `name` - The name of the function to call on the actor.
    /// * `params` - The parameters as a Pack `Value` (preserves structured type info).
    ///
    /// ## Returns
    ///
    /// * `Ok(Value)` - The return value from the function call as a Pack `Value`.
    /// * `Err(ActorError)` - An error occurred during the function call.
    pub async fn call_function(&self, name: String, params: Value) -> Result<Value, ActorError> {
        let (tx, rx) = oneshot::channel();

        let params_bytes = pack_bridge::encode_value(&params).map_err(|e| {
            error!("Failed to encode params: {}", e);
            ActorError::SerializationError
        })?;

        self.operation_tx
            .send(ActorOperation::CallFunctionPack {
                name,
                params: params_bytes,
                response_tx: tx,
            })
            .await
            .map_err(|e| {
                error!("Failed to send operation: {}", e);
                ActorError::ChannelClosed
            })?;

        match timeout(DEFAULT_OPERATION_TIMEOUT, rx).await {
            Ok(result) => match result {
                Ok(inner) => {
                    let result_bytes = inner?;
                    pack_bridge::decode_value(&result_bytes).map_err(|e| {
                        error!("Failed to decode result: {}", e);
                        ActorError::SerializationError
                    })
                }
                Err(e) => {
                    error!("Channel closed while waiting for response: {:?}", e);
                    Err(ActorError::ChannelClosed)
                }
            },
            Err(_) => {
                error!("Operation timed out after {:?}", DEFAULT_OPERATION_TIMEOUT);
                Err(ActorError::OperationTimeout(
                    DEFAULT_OPERATION_TIMEOUT.as_secs(),
                ))
            }
        }
    }

    /// Call a function with pre-encoded Pack ABI params, discarding the return value.
    ///
    /// Routes through `CallFunctionPack` which decodes the Pack ABI bytes back to
    /// a structured Value before passing to the wasm module.
    pub async fn call_function_pack_void(
        &self,
        name: String,
        params: Vec<u8>,
    ) -> Result<(), ActorError> {
        let (tx, rx) = oneshot::channel();

        self.operation_tx
            .send(ActorOperation::CallFunctionPack {
                name: name.clone(),
                params,
                response_tx: tx,
            })
            .await
            .map_err(|e| {
                error!("Failed to send operation: {}", e);
                ActorError::ChannelClosed
            })?;

        match timeout(DEFAULT_OPERATION_TIMEOUT, rx).await {
            Ok(result) => match result {
                Ok(inner_result) => match inner_result {
                    Ok(_) => Ok(()),
                    Err(e) => {
                        error!("Function call '{}' failed: {:?}", name, e);
                        Err(e)
                    }
                },
                Err(_) => {
                    error!("Channel closed while waiting for function call '{}'", name);
                    Err(ActorError::ChannelClosed)
                }
            },
            Err(_) => {
                error!("Operation timed out after {:?}", DEFAULT_OPERATION_TIMEOUT);
                Err(ActorError::OperationTimeout(
                    DEFAULT_OPERATION_TIMEOUT.as_secs(),
                ))
            }
        }
    }

    /// Handle a WASI HTTP incoming request.
    ///
    /// ## Purpose
    ///
    /// This method handles an incoming HTTP request by creating WASI HTTP resources
    /// in the actor's store and calling the actor's exported `wasi:http/incoming-handler.handle`
    /// function.
    ///
    /// ## Parameters
    ///
    /// * `method` - HTTP method (GET, POST, etc.)
    /// * `scheme` - URL scheme (http, https, etc.)
    /// * `authority` - Authority component (host:port)
    /// * `path_with_query` - Path with optional query string
    /// * `headers` - Request headers as (name, value) pairs
    /// * `body` - Request body bytes
    ///
    /// ## Returns
    ///
    /// * `Ok(WasiHttpResponse)` - The HTTP response from the actor
    /// * `Err(ActorError)` - An error occurred during request handling
    pub async fn handle_wasi_http_request(
        &self,
        method: String,
        scheme: Option<String>,
        authority: Option<String>,
        path_with_query: Option<String>,
        headers: Vec<(String, Vec<u8>)>,
        body: Vec<u8>,
    ) -> Result<WasiHttpResponse, ActorError> {
        let (tx, rx) = oneshot::channel();

        self.operation_tx
            .send(ActorOperation::HandleWasiHttpRequest {
                method,
                scheme,
                authority,
                path_with_query,
                headers,
                body,
                response_tx: tx,
            })
            .await
            .map_err(|e| {
                error!("Failed to send HandleWasiHttpRequest operation: {}", e);
                ActorError::ChannelClosed
            })?;

        match timeout(DEFAULT_OPERATION_TIMEOUT, rx).await {
            Ok(result) => match result {
                Ok(result) => result,
                Err(e) => {
                    error!("Channel closed while waiting for HTTP response: {:?}", e);
                    Err(ActorError::ChannelClosed)
                }
            },
            Err(_) => {
                error!(
                    "HTTP request timed out after {:?}",
                    DEFAULT_OPERATION_TIMEOUT
                );
                Err(ActorError::OperationTimeout(
                    DEFAULT_OPERATION_TIMEOUT.as_secs(),
                ))
            }
        }
    }

    /// Retrieves the current state of the actor.
    ///
    /// ## Purpose
    ///
    /// This method allows access to the actor's current state, which is useful for
    /// inspecting the actor's internal data or for backup purposes.
    ///
    /// ## Returns
    ///
    /// * `Ok(Value)` - The actor's current state as a Value.
    /// * `Err(ActorError)` - An error occurred while retrieving the state.
    pub async fn get_state(&self) -> Result<Value, ActorError> {
        let (tx, rx) = oneshot::channel();

        self.info_tx
            .send(ActorInfo::GetState { response_tx: tx })
            .await
            .map_err(|e| {
                error!("Failed to send GetState operation: {}", e);
                ActorError::ChannelClosed
            })?;

        match timeout(DEFAULT_OPERATION_TIMEOUT, rx).await {
            Ok(result) => result.map_err(|e| {
                error!(
                    "Channel closed while waiting for GetState response: {:?}",
                    e
                );
                ActorError::ChannelClosed
            })?,
            Err(_) => {
                error!(
                    "GetState operation timed out after {:?}",
                    DEFAULT_OPERATION_TIMEOUT
                );
                Err(ActorError::OperationTimeout(
                    DEFAULT_OPERATION_TIMEOUT.as_secs(),
                ))
            }
        }
    }

    /// Retrieves the event chain for the actor.
    ///
    /// ## Purpose
    ///
    /// This method returns the history of state changes for the actor,
    /// which is useful for auditing, debugging, or reconstructing the actor's state evolution.
    ///
    /// ## Returns
    ///
    /// * `Ok(Vec<ChainEvent>)` - The event chain containing the history of state changes.
    /// * `Err(ActorError)` - An error occurred while retrieving the chain.
    pub async fn get_chain(&self) -> Result<Vec<ChainEvent>, ActorError> {
        let (tx, rx) = oneshot::channel();

        self.info_tx
            .send(ActorInfo::GetChain { response_tx: tx })
            .await
            .map_err(|e| {
                error!("Failed to send GetChain operation: {}", e);
                ActorError::ChannelClosed
            })?;

        match timeout(DEFAULT_OPERATION_TIMEOUT, rx).await {
            Ok(result) => result.map_err(|e| {
                error!(
                    "Channel closed while waiting for GetChain response: {:?}",
                    e
                );
                ActorError::ChannelClosed
            })?,
            Err(_) => {
                error!(
                    "GetChain operation timed out after {:?}",
                    DEFAULT_OPERATION_TIMEOUT
                );
                Err(ActorError::OperationTimeout(
                    DEFAULT_OPERATION_TIMEOUT.as_secs(),
                ))
            }
        }
    }

    /// Retrieves performance metrics for the actor.
    ///
    /// ## Purpose
    ///
    /// This method provides access to performance metrics for the actor, which is useful
    /// for monitoring, debugging, and performance analysis.
    ///
    /// ## Returns
    ///
    /// * `Ok(ActorMetrics)` - The current metrics for the actor.
    /// * `Err(ActorError)` - An error occurred while retrieving the metrics.
    pub async fn get_metrics(&self) -> Result<ActorMetrics, ActorError> {
        let (tx, rx) = oneshot::channel();

        self.info_tx
            .send(ActorInfo::GetMetrics { response_tx: tx })
            .await
            .map_err(|e| {
                error!("Failed to send GetMetrics operation: {}", e);
                ActorError::ChannelClosed
            })?;

        match timeout(DEFAULT_OPERATION_TIMEOUT, rx).await {
            Ok(result) => result.map_err(|e| {
                error!(
                    "Channel closed while waiting for GetMetrics response: {:?}",
                    e
                );
                ActorError::ChannelClosed
            })?,
            Err(_) => {
                error!(
                    "GetMetrics operation timed out after {:?}",
                    DEFAULT_OPERATION_TIMEOUT
                );
                Err(ActorError::OperationTimeout(
                    DEFAULT_OPERATION_TIMEOUT.as_secs(),
                ))
            }
        }
    }

    /// Initiates an orderly shutdown of the actor.
    ///
    /// ## Purpose
    ///
    /// This method requests that the actor shut down gracefully, allowing it to
    /// complete any in-progress operations and perform any necessary cleanup.
    ///
    /// ## Returns
    ///
    /// * `Ok(())` - The actor was successfully shut down.
    /// * `Err(ActorError)` - An error occurred during the shutdown process.
    pub async fn shutdown(&self) -> Result<(), ActorError> {
        let (tx, rx) = oneshot::channel();

        self.control_tx
            .send(ActorControl::Shutdown { response_tx: tx })
            .await
            .map_err(|e| {
                error!("Failed to send Shutdown operation: {}", e);
                ActorError::ChannelClosed
            })?;

        match timeout(DEFAULT_OPERATION_TIMEOUT, rx).await {
            Ok(result) => result.map_err(|e| {
                error!(
                    "Channel closed while waiting for Shutdown response: {:?}",
                    e
                );
                ActorError::ChannelClosed
            })?,
            Err(_) => {
                error!(
                    "Shutdown operation timed out after {:?}",
                    DEFAULT_OPERATION_TIMEOUT
                );
                Err(ActorError::OperationTimeout(
                    DEFAULT_OPERATION_TIMEOUT.as_secs(),
                ))
            }
        }
    }

    /// Retrieves the interface hashes for all exported interfaces.
    ///
    /// ## Purpose
    ///
    /// This method queries the actor's Pack metadata to get the interface hashes
    /// for all exported interfaces. These hashes can be used for O(1) compatibility
    /// checking between actors.
    ///
    /// ## Returns
    ///
    /// * `Ok(Vec<InterfaceHash>)` - The list of exported interface hashes.
    /// * `Err(ActorError)` - An error occurred while retrieving the hashes.
    pub async fn get_export_hashes(&self) -> Result<Vec<InterfaceHash>, ActorError> {
        let (tx, rx) = oneshot::channel();

        self.info_tx
            .send(ActorInfo::GetExportHashes { response_tx: tx })
            .await
            .map_err(|e| {
                error!("Failed to send GetExportHashes operation: {}", e);
                ActorError::ChannelClosed
            })?;

        match timeout(DEFAULT_OPERATION_TIMEOUT, rx).await {
            Ok(result) => result.map_err(|e| {
                error!(
                    "Channel closed while waiting for GetExportHashes response: {:?}",
                    e
                );
                ActorError::ChannelClosed
            })?,
            Err(_) => {
                error!(
                    "GetExportHashes operation timed out after {:?}",
                    DEFAULT_OPERATION_TIMEOUT
                );
                Err(ActorError::OperationTimeout(
                    DEFAULT_OPERATION_TIMEOUT.as_secs(),
                ))
            }
        }
    }
}