cloacina 0.6.1

A Rust library for resilient task execution and orchestration.
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
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
/*
 *  Copyright 2025-2026 Colliery Software
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

//! Integration tests for multi-tenant functionality

mod postgres_multi_tenant_tests {
    use cloacina::context::Context;
    use cloacina::dal::DAL;
    use cloacina::database::universal_types::UniversalUuid;
    use cloacina::executor::WorkflowExecutor;
    use cloacina::runner::DefaultRunner;
    use cloacina::*;
    use serde_json::Value;
    use std::env;
    use std::sync::Arc;

    /// Simple task that marks its tenant in the context
    #[task(id = "tenant_marker_task", dependencies = [])]
    async fn tenant_marker_task(context: &mut Context<Value>) -> Result<(), TaskError> {
        // Just mark that we executed
        context.insert("executed", Value::Bool(true))?;
        Ok(())
    }

    /// Helper to create a workflow and register it on a scoped runtime
    fn setup_tenant_workflow(tenant_schema: &str, runtime: &cloacina::Runtime) -> Workflow {
        let workflow_name = format!("isolation_test_{}", tenant_schema);

        let workflow = Workflow::builder(&workflow_name)
            .tenant(tenant_schema)
            .description("Test workflow for multi-tenant isolation")
            .add_task(Arc::new(tenant_marker_task_task()))
            .unwrap()
            .build()
            .unwrap();

        // Register task on scoped runtime
        let namespace = TaskNamespace::new(
            workflow.tenant(),
            workflow.package(),
            workflow.name(),
            "tenant_marker_task",
        );
        let task = Arc::new(tenant_marker_task_task());
        runtime.register_task(namespace, move || task.clone());

        // Register workflow on scoped runtime
        runtime.register_workflow(workflow.name().to_string(), {
            let workflow = workflow.clone();
            move || workflow.clone()
        });

        workflow
    }

    /// Test that schema-based multi-tenancy provides complete data isolation
    #[tokio::test]
    async fn test_schema_isolation() -> Result<(), Box<dyn std::error::Error>> {
        let database_url = env::var("DATABASE_URL").unwrap_or_else(|_| {
            "postgresql://cloacina:cloacina@localhost:5432/cloacina".to_string()
        });

        // Setup workflows BEFORE creating runners (runtime snapshot must capture them)
        let runtime = cloacina::Runtime::new();
        let workflow_a = setup_tenant_workflow("tenant_iso_a", &runtime);
        let workflow_b = setup_tenant_workflow("tenant_iso_b", &runtime);

        // Create two runners with different schemas sharing the same runtime
        let runner_a = DefaultRunner::builder()
            .database_url(&database_url)
            .schema("tenant_iso_a")
            .runtime(runtime.clone())
            .build()
            .await?;
        let runner_b = DefaultRunner::builder()
            .database_url(&database_url)
            .schema("tenant_iso_b")
            .runtime(runtime)
            .build()
            .await?;

        // Execute workflow in tenant A
        let context_a = Context::new();
        let execution_a = runner_a.execute_async(workflow_a.name(), context_a).await?;
        let execution_a_id = execution_a.execution_id;

        // Wait for execution to complete
        execution_a.wait_for_completion().await?;

        // Get DALs for each tenant to verify isolation
        let dal_a = DAL::new(runner_a.database().clone());
        let dal_b = DAL::new(runner_b.database().clone());

        // Verify tenant A can see their execution
        let executions_a = dal_a.workflow_execution().list_recent(100).await?;
        assert!(
            executions_a
                .iter()
                .any(|e| e.id == UniversalUuid(execution_a_id)),
            "Tenant A should see their own execution"
        );

        // Verify tenant B cannot see tenant A's execution (isolation)
        let executions_b = dal_b.workflow_execution().list_recent(100).await?;
        assert!(
            !executions_b
                .iter()
                .any(|e| e.id == UniversalUuid(execution_a_id)),
            "Tenant B should NOT see tenant A's execution - isolation violated!"
        );

        // Now execute in tenant B
        let context_b = Context::new();
        let execution_b = runner_b.execute_async(workflow_b.name(), context_b).await?;
        let execution_b_id = execution_b.execution_id;

        // Wait for execution to complete
        execution_b.wait_for_completion().await?;

        // Refresh execution lists
        let executions_a = dal_a.workflow_execution().list_recent(100).await?;
        let executions_b = dal_b.workflow_execution().list_recent(100).await?;

        // Verify tenant A still only sees their execution
        assert!(
            executions_a
                .iter()
                .any(|e| e.id == UniversalUuid(execution_a_id)),
            "Tenant A should still see their own execution"
        );
        assert!(
            !executions_a
                .iter()
                .any(|e| e.id == UniversalUuid(execution_b_id)),
            "Tenant A should NOT see tenant B's execution"
        );

        // Verify tenant B only sees their execution
        assert!(
            executions_b
                .iter()
                .any(|e| e.id == UniversalUuid(execution_b_id)),
            "Tenant B should see their own execution"
        );
        assert!(
            !executions_b
                .iter()
                .any(|e| e.id == UniversalUuid(execution_a_id)),
            "Tenant B should NOT see tenant A's execution"
        );

        // Shutdown executors
        runner_a.shutdown().await?;
        runner_b.shutdown().await?;

        Ok(())
    }

    /// Test that the same workflow can execute independently in different tenants
    #[tokio::test]
    async fn test_independent_execution() -> Result<(), Box<dyn std::error::Error>> {
        let database_url = env::var("DATABASE_URL").unwrap_or_else(|_| {
            "postgresql://cloacina:cloacina@localhost:5432/cloacina".to_string()
        });

        // Setup workflows BEFORE creating runners
        let runtime = cloacina::Runtime::new();
        let workflow_a = setup_tenant_workflow("tenant_indep_a", &runtime);
        let workflow_b = setup_tenant_workflow("tenant_indep_b", &runtime);

        // Create two runners with different schemas sharing the same runtime
        let runner_a = DefaultRunner::builder()
            .database_url(&database_url)
            .schema("tenant_indep_a")
            .runtime(runtime.clone())
            .build()
            .await?;
        let runner_b = DefaultRunner::builder()
            .database_url(&database_url)
            .schema("tenant_indep_b")
            .runtime(runtime)
            .build()
            .await?;

        // Execute in both tenants simultaneously
        let context_a = Context::new();
        let context_b = Context::new();

        let (execution_a, execution_b) = tokio::join!(
            runner_a.execute_async(workflow_a.name(), context_a),
            runner_b.execute_async(workflow_b.name(), context_b)
        );

        let execution_a = execution_a?;
        let execution_b = execution_b?;
        let execution_a_id = execution_a.execution_id;
        let execution_b_id = execution_b.execution_id;

        // Verify both executions have different IDs
        assert_ne!(
            execution_a_id, execution_b_id,
            "Each tenant should have unique execution IDs"
        );

        // Wait for executions to complete
        let (result_a, result_b) = tokio::join!(
            execution_a.wait_for_completion(),
            execution_b.wait_for_completion()
        );
        result_a?;
        result_b?;

        // Verify each tenant has exactly one execution
        let dal_a = DAL::new(runner_a.database().clone());
        let dal_b = DAL::new(runner_b.database().clone());

        let executions_a = dal_a.workflow_execution().list_recent(100).await?;
        let executions_b = dal_b.workflow_execution().list_recent(100).await?;

        // Each tenant should have their workflow execution
        let tenant_a_workflows: Vec<_> = executions_a
            .iter()
            .filter(|e| e.workflow_name.contains("tenant_indep_a"))
            .collect();
        let tenant_b_workflows: Vec<_> = executions_b
            .iter()
            .filter(|e| e.workflow_name.contains("tenant_indep_b"))
            .collect();

        assert!(
            !tenant_a_workflows.is_empty(),
            "Tenant A should have executions"
        );
        assert!(
            !tenant_b_workflows.is_empty(),
            "Tenant B should have executions"
        );

        // Shutdown
        runner_a.shutdown().await?;
        runner_b.shutdown().await?;

        Ok(())
    }

    /// Test that invalid schema names are rejected
    #[tokio::test]
    async fn test_invalid_schema_names() {
        let database_url = "postgresql://cloacina:cloacina@localhost:5432/cloacina";

        // Test schema name with hyphens (should fail)
        let result = DefaultRunner::with_schema(database_url, "tenant-123").await;
        assert!(result.is_err());

        // Test schema name with spaces (should fail)
        let result = DefaultRunner::with_schema(database_url, "tenant 123").await;
        assert!(result.is_err());

        // Test schema name with special characters (should fail)
        let result = DefaultRunner::with_schema(database_url, "tenant@123").await;
        assert!(result.is_err());

        // Test valid schema name (should succeed)
        let database_url = env::var("DATABASE_URL").unwrap_or_else(|_| database_url.to_string());
        let result = DefaultRunner::with_schema(&database_url, "tenant_123").await;
        if let Ok(executor) = result {
            let _ = executor.shutdown().await;
        }
    }

    /// Test that schema isolation is only supported for PostgreSQL
    #[tokio::test]
    async fn test_sqlite_schema_rejection() {
        let result = DefaultRunner::builder()
            .database_url("sqlite://test.db")
            .schema("tenant_123")
            .build()
            .await;

        assert!(matches!(
            result,
            Err(WorkflowExecutionError::Configuration { .. })
        ));
    }

    /// Test builder pattern for multi-tenant setup
    #[tokio::test]
    async fn test_builder_pattern() -> Result<(), Box<dyn std::error::Error>> {
        let database_url = env::var("DATABASE_URL").unwrap_or_else(|_| {
            "postgresql://cloacina:cloacina@localhost:5432/cloacina".to_string()
        });

        let executor = DefaultRunner::builder()
            .database_url(&database_url)
            .schema("tenant_builder_test")
            .build()
            .await?;

        executor.shutdown().await?;
        Ok(())
    }
}

mod sqlite_multi_tenant_tests {
    use cloacina::context::Context;
    use cloacina::dal::DAL;
    use cloacina::database::universal_types::UniversalUuid;
    use cloacina::executor::WorkflowExecutor;
    use cloacina::runner::DefaultRunner;
    use cloacina::*;
    use serde_json::Value;
    use std::sync::Arc;

    /// Simple task for SQLite tests
    #[task(id = "sqlite_tenant_task", dependencies = [])]
    async fn sqlite_tenant_task(context: &mut Context<Value>) -> Result<(), TaskError> {
        context.insert("sqlite_executed", Value::Bool(true))?;
        Ok(())
    }

    /// Helper to create a workflow and register it on a scoped runtime
    fn setup_sqlite_workflow(db_name: &str, runtime: &cloacina::Runtime) -> Workflow {
        let workflow_name = format!("sqlite_isolation_{}", db_name);

        let workflow = Workflow::builder(&workflow_name)
            .description("Test workflow for SQLite multi-tenant isolation")
            .add_task(Arc::new(sqlite_tenant_task_task()))
            .unwrap()
            .build()
            .unwrap();

        let namespace = TaskNamespace::new(
            workflow.tenant(),
            workflow.package(),
            workflow.name(),
            "sqlite_tenant_task",
        );
        let task = Arc::new(sqlite_tenant_task_task());
        runtime.register_task(namespace, move || task.clone());

        runtime.register_workflow(workflow.name().to_string(), {
            let workflow = workflow.clone();
            move || workflow.clone()
        });

        workflow
    }

    /// Test that SQLite multi-tenancy works with separate database files
    #[tokio::test]
    async fn test_sqlite_file_isolation() -> Result<(), Box<dyn std::error::Error>> {
        let tmp = tempfile::TempDir::new()?;
        let db_a = tmp.path().join("tenant_a.db");
        let db_b = tmp.path().join("tenant_b.db");

        // Setup workflows BEFORE creating runners
        let runtime = cloacina::Runtime::new();
        let workflow_a = setup_sqlite_workflow("a", &runtime);
        let workflow_b = setup_sqlite_workflow("b", &runtime);

        // Create two executors with different database files
        let url_a = format!("sqlite://{}", db_a.display());
        let url_b = format!("sqlite://{}", db_b.display());
        let runner_a = DefaultRunner::builder()
            .database_url(&url_a)
            .runtime(runtime.clone())
            .build()
            .await?;
        let runner_b = DefaultRunner::builder()
            .database_url(&url_b)
            .runtime(runtime)
            .build()
            .await?;

        // Execute workflow in tenant A
        let context_a = Context::new();
        let execution_a = runner_a.execute_async(workflow_a.name(), context_a).await?;
        let execution_a_id = execution_a.execution_id;

        // Wait for execution to complete
        execution_a.wait_for_completion().await?;

        // Get DALs
        let dal_a = DAL::new(runner_a.database().clone());
        let dal_b = DAL::new(runner_b.database().clone());

        // Verify tenant A sees their execution
        let executions_a = dal_a.workflow_execution().list_recent(100).await?;
        assert!(
            executions_a
                .iter()
                .any(|e| e.id == UniversalUuid(execution_a_id)),
            "Tenant A should see their own execution"
        );

        // Verify tenant B has no executions (separate database file = isolation)
        let executions_b = dal_b.workflow_execution().list_recent(100).await?;
        assert!(
            !executions_b
                .iter()
                .any(|e| e.id == UniversalUuid(execution_a_id)),
            "Tenant B should NOT see tenant A's execution - file isolation"
        );

        // Execute in tenant B
        let context_b = Context::new();
        let execution_b = runner_b.execute_async(workflow_b.name(), context_b).await?;
        let execution_b_id = execution_b.execution_id;

        // Wait for execution to complete
        execution_b.wait_for_completion().await?;

        // Verify isolation after both execute
        let executions_a = dal_a.workflow_execution().list_recent(100).await?;
        let executions_b = dal_b.workflow_execution().list_recent(100).await?;

        // Tenant A only sees A's execution
        assert!(executions_a
            .iter()
            .any(|e| e.id == UniversalUuid(execution_a_id)));
        assert!(!executions_a
            .iter()
            .any(|e| e.id == UniversalUuid(execution_b_id)));

        // Tenant B only sees B's execution
        assert!(executions_b
            .iter()
            .any(|e| e.id == UniversalUuid(execution_b_id)));
        assert!(!executions_b
            .iter()
            .any(|e| e.id == UniversalUuid(execution_a_id)));

        // Shutdown executors
        runner_a.shutdown().await?;
        runner_b.shutdown().await?;

        Ok(())
    }

    /// Test that SQLite creates separate database files
    #[tokio::test]
    async fn test_sqlite_separate_files() -> Result<(), Box<dyn std::error::Error>> {
        let tmp = tempfile::TempDir::new()?;
        let db_file = tmp.path().join("test_sep.db");

        let executor = DefaultRunner::new(&format!("sqlite://{}", db_file.display())).await?;

        // Verify the file was created
        assert!(db_file.exists(), "Database file should be created");

        executor.shutdown().await?;

        // TempDir cleanup is automatic
        Ok(())
    }
}