ironflow-store 2.36.2

Storage abstraction and implementations for ironflow run tracking
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
//! In-memory [`ApprovalDelegationStore`] implementation.

use std::cmp::Reverse;

use chrono::Utc;
use uuid::Uuid;

use crate::approval_delegation_store::ApprovalDelegationStore;
use crate::entities::{ApprovalDelegation, DelegationFilter, NewApprovalDelegation, Page};
use crate::error::StoreError;
use crate::memory::InMemoryStore;
use crate::store::StoreFuture;

impl ApprovalDelegationStore for InMemoryStore {
    fn create_delegation(&self, req: NewApprovalDelegation) -> StoreFuture<'_, ApprovalDelegation> {
        Box::pin(async move {
            let delegation = ApprovalDelegation {
                id: Uuid::now_v7(),
                from_user_id: req.from_user_id,
                to_user_id: req.to_user_id,
                valid_from: req.valid_from,
                valid_until: req.valid_until,
                workflow_filter: req.workflow_filter,
                created_at: Utc::now(),
            };
            let mut state = self.state.write().await;
            state
                .approval_delegations
                .insert(delegation.id, delegation.clone());
            Ok(delegation)
        })
    }

    fn find_delegation_by_id(&self, id: Uuid) -> StoreFuture<'_, Option<ApprovalDelegation>> {
        Box::pin(async move {
            let state = self.state.read().await;
            Ok(state.approval_delegations.get(&id).cloned())
        })
    }

    fn list_active_delegations(
        &self,
        filter: DelegationFilter,
        page: u32,
        per_page: u32,
    ) -> StoreFuture<'_, Page<ApprovalDelegation>> {
        Box::pin(async move {
            let now = Utc::now();
            let state = self.state.read().await;
            let mut items: Vec<_> = state
                .approval_delegations
                .values()
                .filter(|d| d.is_active_at(now))
                .filter(|d| filter.from_user_id.is_none_or(|id| d.from_user_id == id))
                .filter(|d| filter.to_user_id.is_none_or(|id| d.to_user_id == id))
                .filter(|d| {
                    filter
                        .involving_user_id
                        .is_none_or(|id| d.from_user_id == id || d.to_user_id == id)
                })
                .cloned()
                .collect();
            items.sort_by_key(|d| Reverse(d.created_at));

            let total = items.len() as u64;
            let offset = (page.saturating_sub(1) as usize) * (per_page as usize);
            let items = items
                .into_iter()
                .skip(offset)
                .take(per_page as usize)
                .collect();

            Ok(Page {
                items,
                total,
                page,
                per_page,
            })
        })
    }

    fn find_active_delegation(
        &self,
        from_user_id: Uuid,
        to_user_id: Uuid,
        workflow_name: &str,
    ) -> StoreFuture<'_, Option<ApprovalDelegation>> {
        let workflow_name = workflow_name.to_string();
        Box::pin(async move {
            let now = Utc::now();
            let state = self.state.read().await;
            Ok(state
                .approval_delegations
                .values()
                .filter(|d| d.from_user_id == from_user_id && d.to_user_id == to_user_id)
                .filter(|d| d.is_active_at(now) && d.matches_workflow(&workflow_name))
                .max_by_key(|d| d.created_at)
                .cloned())
        })
    }

    fn delete_delegation(&self, id: Uuid) -> StoreFuture<'_, ()> {
        Box::pin(async move {
            let mut state = self.state.write().await;
            state
                .approval_delegations
                .remove(&id)
                .ok_or(StoreError::DelegationNotFound(id))?;
            Ok(())
        })
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use chrono::TimeDelta;
    use tokio::time::sleep;

    use super::*;

    fn new_delegation(from: Uuid, to: Uuid) -> NewApprovalDelegation {
        let now = Utc::now();
        NewApprovalDelegation {
            from_user_id: from,
            to_user_id: to,
            valid_from: now - TimeDelta::hours(1),
            valid_until: now + TimeDelta::hours(1),
            workflow_filter: None,
        }
    }

    #[tokio::test]
    async fn create_and_find() {
        let store = InMemoryStore::new();
        let (alice, bob) = (Uuid::now_v7(), Uuid::now_v7());

        let created = store
            .create_delegation(NewApprovalDelegation {
                workflow_filter: Some("deploy-*".to_string()),
                ..new_delegation(alice, bob)
            })
            .await
            .expect("create");

        assert_eq!(created.from_user_id, alice);
        assert_eq!(created.to_user_id, bob);
        assert_eq!(created.workflow_filter.as_deref(), Some("deploy-*"));

        let found = store
            .find_delegation_by_id(created.id)
            .await
            .expect("find")
            .expect("some");
        assert_eq!(found.id, created.id);
    }

    #[tokio::test]
    async fn list_skips_expired_and_future_rows() {
        let store = InMemoryStore::new();
        let (alice, bob) = (Uuid::now_v7(), Uuid::now_v7());
        let now = Utc::now();

        let active = store
            .create_delegation(new_delegation(alice, bob))
            .await
            .expect("create active");
        store
            .create_delegation(NewApprovalDelegation {
                valid_from: now - TimeDelta::days(2),
                valid_until: now - TimeDelta::days(1),
                ..new_delegation(alice, bob)
            })
            .await
            .expect("create expired");
        store
            .create_delegation(NewApprovalDelegation {
                valid_from: now + TimeDelta::days(1),
                valid_until: now + TimeDelta::days(2),
                ..new_delegation(alice, bob)
            })
            .await
            .expect("create future");

        let listed = store
            .list_active_delegations(DelegationFilter::default(), 1, 100)
            .await
            .expect("list")
            .items;
        assert_eq!(listed.len(), 1);
        assert_eq!(listed[0].id, active.id);
    }

    #[tokio::test]
    async fn list_filters_by_delegate_and_by_delegator() {
        let store = InMemoryStore::new();
        let (alice, bob, carol) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());

        let to_bob = store
            .create_delegation(new_delegation(alice, bob))
            .await
            .expect("create");
        let to_carol = store
            .create_delegation(new_delegation(alice, carol))
            .await
            .expect("create");
        let from_carol = store
            .create_delegation(new_delegation(carol, bob))
            .await
            .expect("create");

        let received_by_bob = store
            .list_active_delegations(
                DelegationFilter {
                    to_user_id: Some(bob),
                    ..DelegationFilter::default()
                },
                1,
                100,
            )
            .await
            .expect("list")
            .items;
        let ids: Vec<_> = received_by_bob.iter().map(|d| d.id).collect();
        assert_eq!(received_by_bob.len(), 2);
        assert!(ids.contains(&to_bob.id));
        assert!(ids.contains(&from_carol.id));

        let granted_by_alice = store
            .list_active_delegations(
                DelegationFilter {
                    from_user_id: Some(alice),
                    ..DelegationFilter::default()
                },
                1,
                100,
            )
            .await
            .expect("list")
            .items;
        let ids: Vec<_> = granted_by_alice.iter().map(|d| d.id).collect();
        assert_eq!(granted_by_alice.len(), 2);
        assert!(ids.contains(&to_bob.id));
        assert!(ids.contains(&to_carol.id));
    }

    #[tokio::test]
    async fn list_returns_the_newest_delegation_first() {
        let store = InMemoryStore::new();
        let (alice, bob, carol) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());

        let first = store
            .create_delegation(new_delegation(alice, bob))
            .await
            .expect("create");
        // `created_at` is stamped by the store, so the two rows need a real gap
        // for the ordering assertion to mean anything.
        sleep(Duration::from_millis(5)).await;
        let second = store
            .create_delegation(new_delegation(alice, carol))
            .await
            .expect("create");

        let listed = store
            .list_active_delegations(DelegationFilter::default(), 1, 100)
            .await
            .expect("list")
            .items;
        assert_eq!(listed[0].id, second.id);
        assert_eq!(listed[1].id, first.id);
    }

    #[tokio::test]
    async fn list_filters_by_involved_user_on_either_side() {
        let store = InMemoryStore::new();
        let (alice, bob, carol) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());

        let granted = store
            .create_delegation(new_delegation(alice, bob))
            .await
            .expect("create");
        let received = store
            .create_delegation(new_delegation(carol, alice))
            .await
            .expect("create");
        store
            .create_delegation(new_delegation(bob, carol))
            .await
            .expect("create");

        let page = store
            .list_active_delegations(
                DelegationFilter {
                    involving_user_id: Some(alice),
                    ..DelegationFilter::default()
                },
                1,
                100,
            )
            .await
            .expect("list");
        let ids: Vec<_> = page.items.iter().map(|d| d.id).collect();
        assert_eq!(page.total, 2);
        assert!(ids.contains(&granted.id));
        assert!(ids.contains(&received.id));
    }

    #[tokio::test]
    async fn list_paginates_and_reports_the_total() {
        let store = InMemoryStore::new();
        let alice = Uuid::now_v7();
        for _ in 0..5 {
            store
                .create_delegation(new_delegation(alice, Uuid::now_v7()))
                .await
                .expect("create");
        }

        let first = store
            .list_active_delegations(DelegationFilter::default(), 1, 2)
            .await
            .expect("list");
        assert_eq!(first.items.len(), 2);
        assert_eq!(first.total, 5);
        assert_eq!(first.page, 1);
        assert_eq!(first.per_page, 2);

        let last = store
            .list_active_delegations(DelegationFilter::default(), 3, 2)
            .await
            .expect("list");
        assert_eq!(last.items.len(), 1);

        let past_the_end = store
            .list_active_delegations(DelegationFilter::default(), 4, 2)
            .await
            .expect("list");
        assert!(past_the_end.items.is_empty());
    }

    #[tokio::test]
    async fn find_active_delegation_matches_pair_and_workflow() {
        let store = InMemoryStore::new();
        let (alice, bob, carol) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());

        let deploy = store
            .create_delegation(NewApprovalDelegation {
                workflow_filter: Some("deploy-*".to_string()),
                ..new_delegation(alice, bob)
            })
            .await
            .expect("create");

        let found = store
            .find_active_delegation(alice, bob, "deploy-api")
            .await
            .expect("find");
        assert_eq!(found.map(|d| d.id), Some(deploy.id));

        let other_workflow = store
            .find_active_delegation(alice, bob, "billing")
            .await
            .expect("find");
        assert!(other_workflow.is_none());

        let reversed = store
            .find_active_delegation(bob, alice, "deploy-api")
            .await
            .expect("find");
        assert!(reversed.is_none());

        let other_delegate = store
            .find_active_delegation(alice, carol, "deploy-api")
            .await
            .expect("find");
        assert!(other_delegate.is_none());
    }

    #[tokio::test]
    async fn find_active_delegation_ignores_expired_rows() {
        let store = InMemoryStore::new();
        let (alice, bob) = (Uuid::now_v7(), Uuid::now_v7());
        let now = Utc::now();

        store
            .create_delegation(NewApprovalDelegation {
                valid_from: now - TimeDelta::days(2),
                valid_until: now - TimeDelta::days(1),
                ..new_delegation(alice, bob)
            })
            .await
            .expect("create expired");

        let found = store
            .find_active_delegation(alice, bob, "deploy")
            .await
            .expect("find");
        assert!(found.is_none());
    }

    #[tokio::test]
    async fn delete_removes_the_row() {
        let store = InMemoryStore::new();
        let created = store
            .create_delegation(new_delegation(Uuid::now_v7(), Uuid::now_v7()))
            .await
            .expect("create");

        store.delete_delegation(created.id).await.expect("delete");

        let found = store
            .find_delegation_by_id(created.id)
            .await
            .expect("find delegation");
        assert!(found.is_none());
    }

    #[tokio::test]
    async fn delete_unknown_id_is_not_found() {
        let store = InMemoryStore::new();
        let err = store.delete_delegation(Uuid::now_v7()).await.unwrap_err();
        assert!(matches!(err, StoreError::DelegationNotFound(_)));
    }
}