|
| 1 | +use swimos::{ |
| 2 | + agent::{ |
| 3 | + agent_lifecycle::HandlerContext, agent_model::AgentModel, event_handler::EventHandler, |
| 4 | + lanes::ValueLane, lifecycle, projections, AgentLaneModel, |
| 5 | + }, |
| 6 | + route::RoutePattern, |
| 7 | + server::{Server, ServerBuilder, ServerHandle}, |
| 8 | +}; |
| 9 | + |
| 10 | +use std::{error::Error, time::Duration}; |
| 11 | +use swimos::agent::event_handler::HandlerActionExt; |
| 12 | +use swimos::agent::lanes::CommandLane; |
| 13 | +use swimos_form::Form; |
| 14 | + |
| 15 | +// Note how as this is a custom type we need to derive `Form` for it. |
| 16 | +// For most types, simply adding the derive attribute will suffice. |
| 17 | +#[derive(Debug, Form, Copy, Clone)] |
| 18 | +pub enum Operation { |
| 19 | + Add(i32), |
| 20 | + Sub(i32), |
| 21 | +} |
| 22 | + |
| 23 | +#[derive(AgentLaneModel)] |
| 24 | +#[projections] |
| 25 | +pub struct ExampleAgent { |
| 26 | + state: ValueLane<i32>, |
| 27 | + exec: CommandLane<Operation>, |
| 28 | +} |
| 29 | + |
| 30 | +#[derive(Clone)] |
| 31 | +pub struct ExampleLifecycle; |
| 32 | + |
| 33 | +#[lifecycle(ExampleAgent)] |
| 34 | +impl ExampleLifecycle { |
| 35 | + // Handler invoked when the agent starts. |
| 36 | + #[on_start] |
| 37 | + pub fn on_start( |
| 38 | + &self, |
| 39 | + context: HandlerContext<ExampleAgent>, |
| 40 | + ) -> impl EventHandler<ExampleAgent> { |
| 41 | + context.effect(|| println!("Starting agent.")) |
| 42 | + } |
| 43 | + |
| 44 | + // Handler invoked when the agent is about to stop. |
| 45 | + #[on_stop] |
| 46 | + pub fn on_stop( |
| 47 | + &self, |
| 48 | + context: HandlerContext<ExampleAgent>, |
| 49 | + ) -> impl EventHandler<ExampleAgent> { |
| 50 | + context.effect(|| println!("Stopping agent.")) |
| 51 | + } |
| 52 | + |
| 53 | + // Handler invoked after the state of 'lane' has changed. |
| 54 | + #[on_event(state)] |
| 55 | + pub fn on_event( |
| 56 | + &self, |
| 57 | + context: HandlerContext<ExampleAgent>, |
| 58 | + value: &i32, |
| 59 | + ) -> impl EventHandler<ExampleAgent> { |
| 60 | + let n = *value; |
| 61 | + // EventHandler::effect accepts a FnOnce() |
| 62 | + // which runs a side effect. |
| 63 | + context.effect(move || { |
| 64 | + println!("Setting value to: {}", n); |
| 65 | + }) |
| 66 | + } |
| 67 | + |
| 68 | + #[on_command(exec)] |
| 69 | + pub fn on_command( |
| 70 | + &self, |
| 71 | + context: HandlerContext<ExampleAgent>, |
| 72 | + // Notice a reference to the deserialized command envelope is provided. |
| 73 | + operation: &Operation, |
| 74 | + ) -> impl EventHandler<ExampleAgent> { |
| 75 | + let operation = *operation; |
| 76 | + context |
| 77 | + // Get the current state of our `state` lane. |
| 78 | + .get_value(ExampleAgent::STATE) |
| 79 | + .and_then(move |state| { |
| 80 | + // Calculate the new state. |
| 81 | + let new_state = match operation { |
| 82 | + Operation::Add(val) => state + val, |
| 83 | + Operation::Sub(val) => state - val, |
| 84 | + }; |
| 85 | + // Return a event handler which updates the state of the `state` lane. |
| 86 | + context.set_value(ExampleAgent::STATE, new_state) |
| 87 | + }) |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | +#[tokio::main] |
| 92 | +async fn main() -> Result<(), Box<dyn Error + Send + Sync>> { |
| 93 | + // Create a dynamic route for our agents. |
| 94 | + let route = RoutePattern::parse_str("/example/:id")?; |
| 95 | + // Create an agent model which contains the factory for creating the agent as well |
| 96 | + // as the lifecycle which will be run. |
| 97 | + let agent = AgentModel::new(ExampleAgent::default, ExampleLifecycle.into_lifecycle()); |
| 98 | + |
| 99 | + // Create a server builder. |
| 100 | + let server = ServerBuilder::with_plane_name("Plane") |
| 101 | + // Bind to port 8080 |
| 102 | + .set_bind_addr("127.0.0.1:8080".parse().unwrap()) |
| 103 | + // For this guide, ensure agents timeout fairly quickly. |
| 104 | + // An agent will timeout after they have received no new updates |
| 105 | + // for this configured period of time. |
| 106 | + .update_config(|config| { |
| 107 | + config.agent_runtime.inactive_timeout = Duration::from_secs(20); |
| 108 | + }) |
| 109 | + // Register the agent against the route. |
| 110 | + .add_route(route, agent) |
| 111 | + .build() |
| 112 | + // Building the server may fail if many routes are registered and some |
| 113 | + // are ambiguous. |
| 114 | + .await?; |
| 115 | + |
| 116 | + // Run the server. A tuple of the server's runtime |
| 117 | + // future and a handle to the runtime is returned. |
| 118 | + let (task, handle) = server.run(); |
| 119 | + // Watch for ctrl+c signals |
| 120 | + let shutdown = manage_handle(handle); |
| 121 | + |
| 122 | + // Join on the server and ctrl+c futures. |
| 123 | + let (_, result) = tokio::join!(shutdown, task); |
| 124 | + |
| 125 | + result?; |
| 126 | + println!("Server stopped successfully."); |
| 127 | + Ok(()) |
| 128 | +} |
| 129 | + |
| 130 | +// Utility function for awaiting a stop signal in the terminal. |
| 131 | +async fn manage_handle(mut handle: ServerHandle) { |
| 132 | + tokio::signal::ctrl_c() |
| 133 | + .await |
| 134 | + .expect("Failed to register interrupt handler."); |
| 135 | + |
| 136 | + println!("Stopping server."); |
| 137 | + handle.stop(); |
| 138 | +} |
0 commit comments