stigmergy 0.1.0

stigmergy provides emergent agent behavior
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
//! Invariant operations for PostgreSQL database.
//!
//! This module provides functions for managing invariants in the PostgreSQL database
//! with automatic timestamp tracking for created_at and updated_at fields.

use chrono::{DateTime, Utc};
use sqlx::{Postgres, Transaction};

use crate::{DataStoreError, InvariantID};

/// Result type for database operations.
pub type SqlResult<T> = Result<T, DataStoreError>;

/// Represents an invariant with its metadata.
#[derive(Debug, Clone)]
pub struct InvariantRecord {
    /// The invariant identifier.
    pub invariant_id: InvariantID,
    /// The assertion expression as a string.
    pub asserts: String,
    /// When the invariant was created.
    pub created_at: DateTime<Utc>,
    /// When the invariant was last updated.
    pub updated_at: DateTime<Utc>,
}

/// Creates a new invariant in the database.
///
/// The `created_at` and `updated_at` timestamps are automatically set to the current time.
///
/// # Arguments
/// * `tx` - PostgreSQL transaction
/// * `invariant_id` - The invariant identifier to create
/// * `asserts` - The assertion expression as a string
///
/// # Returns
/// * `Ok(())` - Invariant created successfully
/// * `Err(DataStoreError::AlreadyExists)` - Invariant already exists
/// * `Err(DataStoreError::Internal)` - Database error
///
/// # Examples
/// ```no_run
/// # use stigmergy::{InvariantID, sql};
/// # use sqlx::PgPool;
/// # async fn example(pool: PgPool) -> Result<(), Box<dyn std::error::Error>> {
/// let invariant_id = InvariantID::new([1u8; 32]);
/// let mut tx = pool.begin().await?;
/// sql::invariants::create(&mut tx, &invariant_id, "x > 0 && y < 100").await?;
/// tx.commit().await?;
/// # Ok(())
/// # }
/// ```
pub async fn create(
    tx: &mut Transaction<'_, Postgres>,
    invariant_id: &InvariantID,
    asserts: &str,
) -> SqlResult<()> {
    let invariant_bytes = invariant_id.as_bytes();

    let result = sqlx::query!(
        r#"
        INSERT INTO invariants (invariant_id, asserts)
        VALUES ($1, $2)
        "#,
        invariant_bytes.as_slice(),
        asserts
    )
    .execute(&mut **tx)
    .await;

    match result {
        Ok(_) => Ok(()),
        Err(sqlx::Error::Database(db_err)) if db_err.is_unique_violation() => {
            Err(DataStoreError::AlreadyExists)
        }
        Err(e) => {
            eprintln!("Database error creating invariant: {}", e);
            Err(DataStoreError::Internal(e.to_string()))
        }
    }
}

/// Retrieves an invariant from the database.
///
/// # Arguments
/// * `tx` - PostgreSQL transaction
/// * `invariant_id` - The invariant to retrieve
///
/// # Returns
/// * `Ok(Some(InvariantRecord))` - Invariant found
/// * `Ok(None)` - Invariant not found
/// * `Err(DataStoreError::Internal)` - Database error
pub async fn get(
    tx: &mut Transaction<'_, Postgres>,
    invariant_id: &InvariantID,
) -> SqlResult<Option<InvariantRecord>> {
    let invariant_bytes = invariant_id.as_bytes();

    let result = sqlx::query!(
        r#"
        SELECT invariant_id, asserts, created_at, updated_at
        FROM invariants
        WHERE invariant_id = $1
        "#,
        invariant_bytes.as_slice()
    )
    .fetch_optional(&mut **tx)
    .await;

    match result {
        Ok(Some(row)) => {
            let invariant_bytes: [u8; 32] = row
                .invariant_id
                .try_into()
                .map_err(|_| DataStoreError::Internal("invalid invariant_id length".to_string()))?;

            Ok(Some(InvariantRecord {
                invariant_id: InvariantID::new(invariant_bytes),
                asserts: row.asserts,
                created_at: row.created_at,
                updated_at: row.updated_at,
            }))
        }
        Ok(None) => Ok(None),
        Err(e) => {
            eprintln!("Database error getting invariant: {}", e);
            Err(DataStoreError::Internal(e.to_string()))
        }
    }
}

/// Updates the assertion for an existing invariant.
///
/// # Arguments
/// * `tx` - PostgreSQL transaction
/// * `invariant_id` - The invariant to update
/// * `asserts` - The new assertion expression as a string
///
/// # Returns
/// * `Ok(true)` - Invariant existed and was updated
/// * `Ok(false)` - Invariant did not exist
/// * `Err(DataStoreError::Internal)` - Database error
pub async fn update(
    tx: &mut Transaction<'_, Postgres>,
    invariant_id: &InvariantID,
    asserts: &str,
) -> SqlResult<bool> {
    let invariant_bytes = invariant_id.as_bytes();

    let result = sqlx::query!(
        r#"
        UPDATE invariants
        SET asserts = $2, updated_at = CURRENT_TIMESTAMP
        WHERE invariant_id = $1
        "#,
        invariant_bytes.as_slice(),
        asserts
    )
    .execute(&mut **tx)
    .await;

    match result {
        Ok(result) => Ok(result.rows_affected() > 0),
        Err(e) => {
            eprintln!("Database error updating invariant: {}", e);
            Err(DataStoreError::Internal(e.to_string()))
        }
    }
}

/// Deletes an invariant from the database.
///
/// # Arguments
/// * `tx` - PostgreSQL transaction
/// * `invariant_id` - The invariant to delete
///
/// # Returns
/// * `Ok(true)` - Invariant existed and was deleted
/// * `Ok(false)` - Invariant did not exist
/// * `Err(DataStoreError::Internal)` - Database error
pub async fn delete(
    tx: &mut Transaction<'_, Postgres>,
    invariant_id: &InvariantID,
) -> SqlResult<bool> {
    let invariant_bytes = invariant_id.as_bytes();

    let result = sqlx::query!(
        r#"
        DELETE FROM invariants
        WHERE invariant_id = $1
        "#,
        invariant_bytes.as_slice()
    )
    .execute(&mut **tx)
    .await;

    match result {
        Ok(result) => Ok(result.rows_affected() > 0),
        Err(e) => {
            eprintln!("Database error deleting invariant: {}", e);
            Err(DataStoreError::Internal(e.to_string()))
        }
    }
}

/// Lists all invariants in the database.
///
/// # Arguments
/// * `tx` - PostgreSQL transaction
///
/// # Returns
/// * `Ok(Vec<InvariantRecord>)` - List of all invariants
/// * `Err(DataStoreError::Internal)` - Database error
pub async fn list(tx: &mut Transaction<'_, Postgres>) -> SqlResult<Vec<InvariantRecord>> {
    let result = sqlx::query!(
        r#"
        SELECT invariant_id, asserts, created_at, updated_at
        FROM invariants
        ORDER BY created_at ASC
        "#
    )
    .fetch_all(&mut **tx)
    .await;

    match result {
        Ok(rows) => {
            let mut invariants = Vec::new();
            for row in rows {
                let invariant_bytes: [u8; 32] = row.invariant_id.try_into().map_err(|_| {
                    DataStoreError::Internal("invalid invariant_id length".to_string())
                })?;
                invariants.push(InvariantRecord {
                    invariant_id: InvariantID::new(invariant_bytes),
                    asserts: row.asserts,
                    created_at: row.created_at,
                    updated_at: row.updated_at,
                });
            }
            Ok(invariants)
        }
        Err(e) => {
            eprintln!("Database error listing invariants: {}", e);
            Err(DataStoreError::Internal(e.to_string()))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn unique_invariant(test_name: &str) -> InvariantID {
        use std::time::{SystemTime, UNIX_EPOCH};
        let pid = std::process::id();
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_micros() as u64;

        let mut bytes = [0u8; 32];
        bytes[0..4].copy_from_slice(&pid.to_le_bytes());
        bytes[4..12].copy_from_slice(&now.to_le_bytes());

        let test_bytes = test_name.as_bytes();
        let copy_len = test_bytes.len().min(20);
        bytes[12..12 + copy_len].copy_from_slice(&test_bytes[..copy_len]);

        InvariantID::new(bytes)
    }

    #[tokio::test]
    async fn create_and_get() {
        let pool = super::super::tests::setup_test_db().await;
        let invariant_id = unique_invariant("create_and_get");
        let asserts = "x > 0 && y < 100";

        let db_before = sqlx::query_scalar::<_, DateTime<Utc>>("SELECT CURRENT_TIMESTAMP")
            .fetch_one(&pool)
            .await
            .unwrap();

        let mut tx = pool.begin().await.unwrap();
        create(&mut tx, &invariant_id, asserts).await.unwrap();
        tx.commit().await.unwrap();

        let db_after = sqlx::query_scalar::<_, DateTime<Utc>>("SELECT CURRENT_TIMESTAMP")
            .fetch_one(&pool)
            .await
            .unwrap();

        let mut tx = pool.begin().await.unwrap();
        let record = get(&mut tx, &invariant_id).await.unwrap();
        tx.commit().await.unwrap();
        assert!(record.is_some());
        let record = record.unwrap();
        assert_eq!(record.invariant_id, invariant_id);
        assert_eq!(record.asserts, asserts);
        assert!(record.created_at >= db_before);
        assert!(record.created_at <= db_after);
        assert!(record.updated_at >= db_before);
        assert!(record.updated_at <= db_after);
        assert_eq!(record.created_at, record.updated_at);
    }

    #[tokio::test]
    async fn create_duplicate_fails() {
        let pool = super::super::tests::setup_test_db().await;
        let invariant_id = unique_invariant("create_duplicate_fails");

        let mut tx = pool.begin().await.unwrap();
        create(&mut tx, &invariant_id, "x > 0").await.unwrap();
        tx.commit().await.unwrap();

        let mut tx = pool.begin().await.unwrap();
        let result = create(&mut tx, &invariant_id, "y > 0").await;
        assert!(matches!(result, Err(DataStoreError::AlreadyExists)));
    }

    #[tokio::test]
    async fn update_existing() {
        let pool = super::super::tests::setup_test_db().await;
        let invariant_id = unique_invariant("update_existing");

        let mut tx = pool.begin().await.unwrap();
        create(&mut tx, &invariant_id, "x > 0").await.unwrap();
        tx.commit().await.unwrap();

        let mut tx = pool.begin().await.unwrap();
        let record_before = get(&mut tx, &invariant_id).await.unwrap().unwrap();
        tx.commit().await.unwrap();
        assert_eq!(record_before.asserts, "x > 0");
        assert_eq!(record_before.created_at, record_before.updated_at);

        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

        let mut tx = pool.begin().await.unwrap();
        let updated = update(&mut tx, &invariant_id, "y < 100").await.unwrap();
        tx.commit().await.unwrap();
        assert!(updated);

        let mut tx = pool.begin().await.unwrap();
        let record_after = get(&mut tx, &invariant_id).await.unwrap().unwrap();
        tx.commit().await.unwrap();
        assert_eq!(record_after.asserts, "y < 100");
        assert_eq!(record_after.created_at, record_before.created_at);
        assert!(record_after.updated_at > record_before.updated_at);
    }

    #[tokio::test]
    async fn update_nonexistent() {
        let pool = super::super::tests::setup_test_db().await;
        let invariant_id = unique_invariant("update_nonexistent");

        let mut tx = pool.begin().await.unwrap();
        let updated = update(&mut tx, &invariant_id, "x > 0").await.unwrap();
        tx.commit().await.unwrap();
        assert!(!updated);
    }

    #[tokio::test]
    async fn delete_existing() {
        let pool = super::super::tests::setup_test_db().await;
        let invariant_id = unique_invariant("delete_existing");

        let mut tx = pool.begin().await.unwrap();
        create(&mut tx, &invariant_id, "x > 0").await.unwrap();
        tx.commit().await.unwrap();

        let mut tx = pool.begin().await.unwrap();
        let deleted = delete(&mut tx, &invariant_id).await.unwrap();
        tx.commit().await.unwrap();
        assert!(deleted);

        let mut tx = pool.begin().await.unwrap();
        let record = get(&mut tx, &invariant_id).await.unwrap();
        tx.commit().await.unwrap();
        assert!(record.is_none());
    }

    #[tokio::test]
    async fn delete_nonexistent() {
        let pool = super::super::tests::setup_test_db().await;
        let invariant_id = unique_invariant("delete_nonexistent");

        let mut tx = pool.begin().await.unwrap();
        let deleted = delete(&mut tx, &invariant_id).await.unwrap();
        tx.commit().await.unwrap();
        assert!(!deleted);
    }

    #[tokio::test]
    async fn list_multiple() {
        let pool = super::super::tests::setup_test_db().await;
        let invariant1 = unique_invariant("list_multiple_1");
        let invariant2 = unique_invariant("list_multiple_2");
        let invariant3 = unique_invariant("list_multiple_3");

        let mut tx = pool.begin().await.unwrap();
        create(&mut tx, &invariant1, "x > 0").await.unwrap();
        create(&mut tx, &invariant2, "y > 0").await.unwrap();
        create(&mut tx, &invariant3, "z > 0").await.unwrap();
        tx.commit().await.unwrap();

        let mut tx = pool.begin().await.unwrap();
        let invariants = list(&mut tx).await.unwrap();
        tx.commit().await.unwrap();
        let ids: Vec<_> = invariants.iter().map(|r| r.invariant_id).collect();
        assert!(ids.contains(&invariant1));
        assert!(ids.contains(&invariant2));
        assert!(ids.contains(&invariant3));
    }
}