acton_service/agents/messages.rs
1//! Agent message types for pool management
2//!
3//! These messages define the communication protocol between pool agents
4//! and other components in the system.
5//!
6//! All messages derive `Clone` and `Debug` to satisfy the `ActonMessage` trait
7//! requirements via blanket implementation.
8
9use acton_reactive::prelude::Request;
10
11/// Health status of a pool
12#[derive(Clone, Debug, Default, PartialEq, Eq)]
13pub enum HealthStatus {
14 /// Pool is healthy and operational
15 Healthy,
16 /// Pool is degraded but operational
17 Degraded,
18 /// Pool is unhealthy/disconnected
19 #[default]
20 Unhealthy,
21 /// Pool is in the process of connecting
22 Connecting,
23}
24
25/// Response containing aggregated health status from all pools
26#[derive(Clone, Debug, Default)]
27pub struct AggregatedHealthResponse {
28 /// Overall health status (unhealthy if any component is unhealthy)
29 pub overall_healthy: bool,
30 /// Individual pool health statuses
31 pub components: Vec<ComponentHealth>,
32}
33
34/// Health status of a single component/pool
35#[derive(Clone, Debug, Default)]
36pub struct ComponentHealth {
37 /// Component name (e.g., "database", "redis", "nats")
38 pub name: String,
39 /// Health status
40 pub status: HealthStatus,
41 /// Status message
42 pub message: String,
43}
44
45/// Ask a pool agent for its current connection health
46///
47/// Answers with whatever the agent knows right now, which for a pool that is
48/// still dialling is [`HealthStatus::Connecting`]. Use
49/// [`WaitForPoolReady`] to wait for the outcome instead of sampling it.
50#[derive(Clone, Debug, Default)]
51pub struct GetPoolHealth;
52
53impl Request for GetPoolHealth {
54 type Response = ComponentHealth;
55}
56
57/// Ask a pool agent to answer once its first connection attempt has settled
58///
59/// Pool agents dial on a spawned task and message themselves with the result,
60/// so that result is not in the mailbox yet when `spawn` returns — a plain
61/// [`GetPoolHealth`] ask right after startup races it and reports
62/// [`HealthStatus::Connecting`]. This request is parked by the agent until the
63/// attempt succeeds or fails, then answered with the resulting health. That
64/// makes "wait until the pool is up" a barrier rather than a guessed duration.
65#[derive(Clone, Debug, Default)]
66pub struct WaitForPoolReady;
67
68impl Request for WaitForPoolReady {
69 type Response = ComponentHealth;
70}
71
72// =============================================================================
73// Internal messages for pool connection state management
74// These are sent by spawned connection tasks back to the agent
75// =============================================================================
76
77/// Internal message sent when a database pool connects successfully
78#[cfg(feature = "database")]
79#[derive(Clone, Debug)]
80pub(crate) struct DatabasePoolConnected {
81 pub pool: sqlx::PgPool,
82}
83
84/// Internal message sent when a database pool connection fails
85#[cfg(feature = "database")]
86#[derive(Clone, Debug, Default)]
87pub(crate) struct DatabasePoolConnectionFailed {
88 pub error: String,
89}
90
91/// Internal message sent when the SQL Server pool connects successfully.
92#[cfg(feature = "mssql")]
93#[derive(Clone, Debug)]
94pub(crate) struct MssqlPoolConnected {
95 pub pool: crate::mssql::MssqlPool,
96}
97
98/// Internal message sent when the SQL Server pool connection fails.
99#[cfg(feature = "mssql")]
100#[derive(Clone, Debug, Default)]
101pub(crate) struct MssqlPoolConnectionFailed {
102 pub error: String,
103}
104
105/// Internal message sent when a Redis pool connects successfully
106#[cfg(feature = "cache")]
107#[derive(Clone, Debug)]
108pub(crate) struct RedisPoolConnected {
109 pub pool: deadpool_redis::Pool,
110}
111
112/// Internal message sent when a Redis pool connection fails
113#[cfg(feature = "cache")]
114#[derive(Clone, Debug, Default)]
115pub(crate) struct RedisPoolConnectionFailed {
116 pub error: String,
117}
118
119/// Internal message sent when a NATS client connects successfully
120#[cfg(feature = "events")]
121#[derive(Clone, Debug)]
122pub(crate) struct NatsClientConnected {
123 pub client: async_nats::Client,
124}
125
126/// Internal message sent when a NATS client connection fails
127#[cfg(feature = "events")]
128#[derive(Clone, Debug, Default)]
129pub(crate) struct NatsClientConnectionFailed {
130 pub error: String,
131}
132
133/// Internal message sent when a Turso database connects successfully
134#[cfg(feature = "turso")]
135#[derive(Clone, Debug)]
136pub(crate) struct TursoDbConnected {
137 pub db: std::sync::Arc<libsql::Database>,
138}
139
140/// Internal message sent when a Turso database connection fails
141#[cfg(feature = "turso")]
142#[derive(Clone, Debug, Default)]
143pub(crate) struct TursoDbConnectionFailed {
144 pub error: String,
145}
146
147/// Internal message sent when a SurrealDB client connects successfully
148#[cfg(feature = "surrealdb")]
149#[derive(Clone, Debug)]
150pub(crate) struct SurrealDbConnected {
151 pub client: std::sync::Arc<crate::surrealdb_backend::SurrealClient>,
152}
153
154/// Internal message sent when a SurrealDB client connection fails
155#[cfg(feature = "surrealdb")]
156#[derive(Clone, Debug, Default)]
157pub(crate) struct SurrealDbConnectionFailed {
158 pub error: String,
159}
160
161/// Internal message sent when a ClickHouse client connects successfully
162#[cfg(feature = "clickhouse")]
163#[derive(Clone)]
164pub(crate) struct ClickHouseClientConnected {
165 pub client: clickhouse::Client,
166}
167
168#[cfg(feature = "clickhouse")]
169impl std::fmt::Debug for ClickHouseClientConnected {
170 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171 f.debug_struct("ClickHouseClientConnected").finish()
172 }
173}
174
175/// Internal message sent when a ClickHouse client connection fails
176#[cfg(feature = "clickhouse")]
177#[derive(Clone, Debug, Default)]
178pub(crate) struct ClickHouseClientConnectionFailed {
179 pub error: String,
180}
181
182// =============================================================================
183// Background Worker Agent messages
184// =============================================================================
185
186/// Internal message: a task has been accepted and should be tracked
187///
188/// Sent before the task is spawned so the agent can never receive a
189/// [`TaskCompleted`] for an ID it has not registered.
190#[derive(Clone, Debug, Default)]
191pub(crate) struct RegisterTask {
192 /// The task ID being registered
193 pub task_id: String,
194 /// Token that cancels this task specifically
195 pub cancellation_token: tokio_util::sync::CancellationToken,
196}
197
198/// Internal message: a task reached a terminal state
199///
200/// Sent by the spawned task itself, so status has exactly one writer.
201#[derive(Clone, Debug, Default)]
202pub(crate) struct TaskCompleted {
203 /// The task ID that finished
204 pub task_id: String,
205 /// The status it finished in
206 pub status: super::background_worker::TaskStatus,
207}
208
209/// Message to cancel a running background task
210#[derive(Clone, Debug, Default)]
211pub struct CancelTask {
212 /// The task ID to cancel
213 pub task_id: String,
214}
215
216/// Message asking to be told when a task reaches a terminal state
217#[derive(Clone, Debug, Default)]
218pub struct WaitForTask {
219 /// The task ID to wait on
220 pub task_id: String,
221}
222
223/// Message to query the status of a specific task
224#[derive(Clone, Debug, Default)]
225pub struct GetTaskStatus {
226 /// The task ID to query
227 pub task_id: String,
228}
229
230/// Message to query the status of all tasks
231#[derive(Clone, Debug, Default)]
232pub struct GetAllTaskStatuses;
233
234/// Message asking the worker to drop records for tasks that have finished
235#[derive(Clone, Debug, Default)]
236pub struct CleanupFinishedTasks;
237
238/// Response containing task status information
239#[derive(Clone, Debug, Default)]
240pub struct TaskStatusResponse {
241 /// The task ID
242 pub task_id: String,
243 /// Current status of the task
244 pub status: super::background_worker::TaskStatus,
245}
246
247/// Lets callers read a single task's status with
248/// [`ask`](acton_reactive::prelude::ActorHandleInterface::ask). `None` means no
249/// such task is tracked, which is distinct from a task sitting in
250/// [`TaskStatus::Pending`](super::background_worker::TaskStatus::Pending).
251///
252/// ```rust,ignore
253/// let response = worker.handle().ask(GetTaskStatus { task_id: "job".into() }).await?;
254/// ```
255impl Request for GetTaskStatus {
256 type Response = Option<TaskStatusResponse>;
257}
258
259/// Lets callers read every tracked task's status with
260/// [`ask`](acton_reactive::prelude::ActorHandleInterface::ask).
261impl Request for GetAllTaskStatuses {
262 type Response = Vec<TaskStatusResponse>;
263}
264
265/// Resolves once the named task reaches a terminal state, or immediately with
266/// `None` if no such task is tracked. The agent parks the reply envelope until
267/// the task reports in, so callers wait rather than poll.
268impl Request for WaitForTask {
269 type Response = Option<TaskStatusResponse>;
270}
271
272/// Answers with the number of finished task records dropped.
273impl Request for CleanupFinishedTasks {
274 type Response = usize;
275}