aves-tyto 0.5.0

Specialized messaging domain for the Aves async application runtime
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
use std::path::{Path, PathBuf};

use thiserror::Error;
use turso::{Connection, Database, Error as TursoError, Row};

use aves::utils::database::{
    DatabaseError, MigrationRunner, connect_database, maintain_database, open_database_at_path,
};

use crate::migrations::MIGRATIONS;

/// Typed errors raised by the Tyto message store.
#[derive(Debug, Error)]
pub(super) enum StoreError {
    #[error(transparent)]
    Database(#[from] DatabaseError),
    #[error(transparent)]
    Turso(#[from] TursoError),
}

/// A persisted provider connection configuration.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(super) struct MessagingConnection {
    pub(super) id: String,
    pub(super) display_name: String,
    pub(super) provider_type: String,
    pub(super) credential_id: String,
    pub(super) transport_settings: String,
    pub(super) enabled: bool,
    pub(super) retention_seconds: i64,
}

/// A durable permission request, including its finalization/edit state.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(super) struct PermissionRequest {
    pub(super) request_id: String,
    pub(super) connection_id: String,
    pub(super) provider_message_id: Option<String>,
    pub(super) destination: String,
    pub(super) request_text: String,
    pub(super) expires_at: i64,
    pub(super) flow_execution_id: String,
    pub(super) flow_node_id: String,
    pub(super) status: String,
    pub(super) provider_receipt: Option<String>,
    pub(super) decided_at: Option<i64>,
    pub(super) outstanding_edit: bool,
}

/// Tyto's durable messaging database handle.
pub(super) struct MessageStore {
    database: Database,
    path: PathBuf,
}

impl MessageStore {
    /// Opens and migrates `config_dir/messages.db`.
    pub(super) async fn open(config_dir: &Path) -> Result<Self, StoreError> {
        let path = config_dir.join("messages.db");
        let database = open_database_at_path(path.clone()).await?;
        MigrationRunner::new("__peitho_migrations", MIGRATIONS)
            .apply(&database)
            .await?;
        Ok(Self { database, path })
    }

    async fn connection(&self) -> Result<Connection, StoreError> {
        Ok(connect_database(&self.database).await?)
    }

    /// Performs Aves database maintenance for the message store.
    pub(super) async fn maintain(&self) {
        maintain_database(&self.database, &self.path).await;
    }

    /// Lists all configured messaging connections.
    pub(super) async fn list_connections(&self) -> Result<Vec<MessagingConnection>, StoreError> {
        let connection = self.connection().await?;
        let mut rows = connection
            .query(include_str!("queries/list_connections.sql"), ())
            .await?;
        let mut result = Vec::new();
        while let Some(row) = rows.next().await? {
            result.push(Self::read_connection(&row)?);
        }
        Ok(result)
    }

    /// Loads one connection by its immutable identifier.
    pub(super) async fn get_connection(&self, id: &str) -> Result<Option<MessagingConnection>, StoreError> {
        let connection = self.connection().await?;
        let mut rows = connection
            .query(include_str!("queries/get_connection.sql"), (id,))
            .await?;
        Ok(rows
            .next()
            .await?
            .as_ref()
            .map(Self::read_connection)
            .transpose()?)
    }

    /// Inserts a new connection configuration.
    pub(super) async fn create_connection(&self, value: &MessagingConnection) -> Result<(), StoreError> {
        let connection = self.connection().await?;
        connection
            .execute(
                include_str!("queries/create_connection.sql"),
                (
                    value.id.as_str(),
                    value.display_name.as_str(),
                    value.provider_type.as_str(),
                    value.credential_id.as_str(),
                    value.transport_settings.as_str(),
                    i64::from(value.enabled),
                    value.retention_seconds,
                ),
            )
            .await?;
        Ok(())
    }

    /// Updates editable connection settings while preserving its identifier and enabled state.
    pub(super) async fn update_connection(&self, value: &MessagingConnection) -> Result<(), StoreError> {
        let connection = self.connection().await?;
        connection
            .execute(
                include_str!("queries/update_connection.sql"),
                (
                    value.id.as_str(),
                    value.display_name.as_str(),
                    value.provider_type.as_str(),
                    value.credential_id.as_str(),
                    value.transport_settings.as_str(),
                    value.retention_seconds,
                ),
            )
            .await?;
        Ok(())
    }

    /// Sets a connection's inbound-listener enabled state.
    pub(super) async fn set_enabled(&self, id: &str, enabled: bool) -> Result<(), StoreError> {
        let connection = self.connection().await?;
        connection
            .execute(
                include_str!("queries/set_connection_enabled.sql"),
                (id, i64::from(enabled)),
            )
            .await?;
        Ok(())
    }

    /// Deletes a connection configuration without deleting retained history.
    pub(super) async fn delete_connection(&self, id: &str) -> Result<(), StoreError> {
        let connection = self.connection().await?;
        connection
            .execute(include_str!("queries/delete_connection.sql"), (id,))
            .await?;
        Ok(())
    }

    /// Persists a permission request before provider delivery.
    pub(super) async fn insert_prepared(&self, request: &PermissionRequest) -> Result<(), StoreError> {
        let connection = self.connection().await?;
        connection
            .execute(
                include_str!("queries/insert_prepared.sql"),
                (
                    request.request_id.as_str(),
                    request.connection_id.as_str(),
                    request.destination.as_str(),
                    request.request_text.as_str(),
                    request.expires_at,
                    request.flow_execution_id.as_str(),
                    request.flow_node_id.as_str(),
                ),
            )
            .await?;
        Ok(())
    }

    /// Marks a prepared request pending; returns false if another durable transition already won.
    pub(super) async fn mark_pending(
        &self,
        request_id: &str,
        message_id: &str,
        receipt: &str,
    ) -> Result<bool, StoreError> {
        let connection = self.connection().await?;
        Ok(connection
            .execute(
                include_str!("queries/mark_pending.sql"),
                (request_id, message_id, receipt),
            )
            .await?
            == 1)
    }

    /// Attaches a provider message receipt without changing the request status.
    pub(super) async fn attach_provider_message(
        &self,
        request_id: &str,
        provider_message_id: &str,
        provider_receipt: &str,
    ) -> Result<bool, StoreError> {
        let connection = self.connection().await?;
        Ok(connection
            .execute(
                include_str!("queries/attach_provider_message.sql"),
                (request_id, provider_message_id, provider_receipt),
            )
            .await?
            == 1)
    }

    /// Atomically performs the first transition out of prepared/pending.
    pub(super) async fn finalize_atomic(
        &self,
        request_id: &str,
        status: &str,
        decided_at: i64,
        outstanding_edit: bool,
    ) -> Result<bool, StoreError> {
        let connection = self.connection().await?;
        Ok(connection
            .execute(
                include_str!("queries/finalize_atomic.sql"),
                (request_id, status, decided_at, i64::from(outstanding_edit)),
            )
            .await?
            == 1)
    }

    /// Clears the retry flag after a provider message edit succeeds.
    pub(super) async fn clear_outstanding_edit(&self, request_id: &str) -> Result<(), StoreError> {
        let connection = self.connection().await?;
        connection
            .execute(include_str!("queries/clear_outstanding_edit.sql"), (request_id,))
            .await?;
        Ok(())
    }

    /// Loads a permission request by its pre-send identity.
    pub(super) async fn get_permission_request(
        &self,
        request_id: &str,
    ) -> Result<Option<PermissionRequest>, StoreError> {
        let connection = self.connection().await?;
        let mut rows = connection
            .query(include_str!("queries/get_permission_request.sql"), (request_id,))
            .await?;
        Ok(rows
            .next()
            .await?
            .as_ref()
            .map(Self::read_permission_request)
            .transpose()?)
    }

    /// Loads one permission request by its Flow execution and node correlation.
    pub(super) async fn get_by_correlation(
        &self,
        flow_execution_id: &str,
        flow_node_id: &str,
    ) -> Result<Option<PermissionRequest>, StoreError> {
        let connection = self.connection().await?;
        let mut rows = connection
            .query(
                include_str!("queries/get_by_correlation.sql"),
                (flow_execution_id, flow_node_id),
            )
            .await?;
        Ok(rows
            .next()
            .await?
            .as_ref()
            .map(Self::read_permission_request)
            .transpose()?)
    }

    /// Scans expired unfinished requests and requests whose provider edit remains outstanding.
    pub(super) async fn scan_unfinished(&self, now: i64) -> Result<Vec<PermissionRequest>, StoreError> {
        let connection = self.connection().await?;
        let mut rows = connection
            .query(include_str!("queries/scan_unfinished.sql"), (now,))
            .await?;
        let mut result = Vec::new();
        while let Some(row) = rows.next().await? {
            result.push(Self::read_permission_request(&row)?);
        }
        Ok(result)
    }

    /// Scans finalized requests whose provider edit must be retried.
    pub(super) async fn scan_outstanding_edits(&self) -> Result<Vec<PermissionRequest>, StoreError> {
        let connection = self.connection().await?;
        let mut rows = connection
            .query(include_str!("queries/scan_outstanding_edits.sql"), ())
            .await?;
        let mut result = Vec::new();
        while let Some(row) = rows.next().await? {
            result.push(Self::read_permission_request(&row)?);
        }
        Ok(result)
    }

    /// Finalizes every unfinished request for a deleted connection without editing provider messages.
    pub(super) async fn mark_deleted_for_connection(&self, id: &str, now: i64) -> Result<u64, StoreError> {
        let connection = self.connection().await?;
        Ok(connection
            .execute(include_str!("queries/mark_deleted_for_connection.sql"), (id, now))
            .await?)
    }

    /// Inserts a raw inbound provider delivery and optional normalized projection.
    #[allow(clippy::too_many_arguments)]
    pub(super) async fn insert_inbound(
        &self,
        raw: &[u8],
        body: Option<&str>,
        metadata: Option<&str>,
        connection_id: &str,
        channel_id: Option<&str>,
        received_at: i64,
        retention_seconds: i64,
        expires_at: i64,
    ) -> Result<(), StoreError> {
        let connection = self.connection().await?;
        connection
            .execute(
                include_str!("queries/insert_inbound.sql"),
                (
                    raw,
                    body,
                    metadata,
                    connection_id,
                    channel_id,
                    received_at,
                    retention_seconds,
                    expires_at,
                ),
            )
            .await?;
        Ok(())
    }

    /// Inserts a raw permission callback independently of its arbitration outcome.
    #[allow(clippy::too_many_arguments)]
    pub(super) async fn insert_callback(
        &self,
        raw: &str,
        request_id: Option<&str>,
        action: Option<&str>,
        decided_at: Option<i64>,
        connection_id: Option<&str>,
        received_at: i64,
        retention_seconds: i64,
        expires_at: i64,
    ) -> Result<(), StoreError> {
        let connection = self.connection().await?;
        connection
            .execute(
                include_str!("queries/insert_callback.sql"),
                (
                    raw,
                    request_id,
                    action,
                    decided_at,
                    connection_id,
                    received_at,
                    retention_seconds,
                    expires_at,
                ),
            )
            .await?;
        Ok(())
    }

    /// Inserts an accepted outbound send; raw payload is deliberately SQL NULL.
    #[allow(clippy::too_many_arguments)]
    pub(super) async fn insert_accepted_send(
        &self,
        body: &str,
        metadata: Option<&str>,
        receipt: &str,
        connection_id: &str,
        received_at: i64,
        retention_seconds: i64,
        expires_at: i64,
    ) -> Result<(), StoreError> {
        let connection = self.connection().await?;
        connection
            .execute(
                include_str!("queries/insert_accepted_send.sql"),
                (
                    body,
                    metadata,
                    receipt,
                    connection_id,
                    received_at,
                    retention_seconds,
                    expires_at,
                ),
            )
            .await?;
        Ok(())
    }

    /// Prunes only inbound, callback, and accepted-send history under live/snapshot retention rules.
    pub(super) async fn prune_expired(&self, now: i64) -> Result<(), StoreError> {
        let connection = self.connection().await?;
        for query in [
            include_str!("queries/prune_expired.sql"),
            include_str!("queries/prune_callbacks.sql"),
            include_str!("queries/prune_accepted_sends.sql"),
        ] {
            connection.execute(query, (now,)).await?;
        }
        Ok(())
    }

    fn read_connection(row: &Row) -> Result<MessagingConnection, TursoError> {
        Ok(MessagingConnection {
            id: row.get(0)?,
            display_name: row.get(1)?,
            provider_type: row.get(2)?,
            credential_id: row.get(3)?,
            transport_settings: row.get(4)?,
            enabled: row.get::<i64>(5)? != 0,
            retention_seconds: row.get(6)?,
        })
    }

    fn read_permission_request(row: &Row) -> Result<PermissionRequest, TursoError> {
        Ok(PermissionRequest {
            request_id: row.get(0)?,
            connection_id: row.get(1)?,
            provider_message_id: row.get(2)?,
            destination: row.get(3)?,
            request_text: row.get(4)?,
            expires_at: row.get(5)?,
            flow_execution_id: row.get(6)?,
            flow_node_id: row.get(7)?,
            status: row.get(8)?,
            provider_receipt: row.get(9)?,
            decided_at: row.get(10)?,
            outstanding_edit: row.get::<i64>(11)? != 0,
        })
    }
}