outbox-pattern-processor 0.3.6

Library to make easier to dispatch your outbox-pattern data from database to SQS, SNS and/or HTTP(S) gateways
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
470
471
472
use aws_config::BehaviorVersion;
use aws_sdk_sns::operation::create_topic::CreateTopicOutput;
use aws_sdk_sqs::operation::create_queue::CreateQueueOutput;
use outbox_pattern_processor::aws::{SnsClient, SqsClient};
use outbox_pattern_processor::http_destination::HttpDestination;
use outbox_pattern_processor::outbox::Outbox;
use outbox_pattern_processor::outbox_destination::OutboxDestination;
use outbox_pattern_processor::outbox_resources::OutboxProcessorResources;
use outbox_pattern_processor::sns_destination::SnsDestination;
use outbox_pattern_processor::sqs_destination::SqsDestination;
use rand::Rng;
use serde_json::{json, Value};
use sqlx::postgres::{PgConnectOptions, PgPoolOptions};
use sqlx::types::chrono::{DateTime, Utc};
use sqlx::types::Json;
use sqlx::{Pool, Postgres};
use std::collections::HashMap;
use std::env;
use std::net::{SocketAddr, TcpListener};
use std::time::Duration;
use test_context::AsyncTestContext;
use uuid::Uuid;
use wiremock::matchers::{body_json_string, header, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

#[allow(dead_code)]
pub struct TestContext {
    pub resources: OutboxProcessorResources,
    mock_server: MockServer,
    pub gateway_uri: String,
    pub queue_url: String,
    pub topic_arn: String,
    pub postgres_pool: Pool<Postgres>,
}

impl AsyncTestContext for TestContext {
    async fn setup() -> Self {
        env::set_var("AWS_ACCESS_KEY_ID", "outbox-pattern-processor");
        env::set_var("AWS_SECRET_ACCESS_KEY", "outbox-pattern-processor");
        env::set_var("LOCAL_ENDPOINT", "http://localhost:4566");
        env::set_var("LOCAL_REGION", "us-east-1");

        let mock_server = Infrastructure::init_mock_server().await;

        let postgres_pool = Infrastructure::init_database().await;

        let aws_config = aws_config::load_defaults(BehaviorVersion::latest()).await;
        let sqs_client = SqsClient::new(&aws_config).await;
        let sns_client = SnsClient::new(&aws_config).await;

        let resources = OutboxProcessorResources::new(postgres_pool.clone(), Some(sqs_client), Some(sns_client));

        let gateway_uri = mock_server.uri();
        let queue_url = Infrastructure::init_sqs(&resources).await.queue_url.unwrap();
        let topic_arn = Infrastructure::init_sns(&resources).await.topic_arn.unwrap();

        Self {
            resources,
            mock_server,
            gateway_uri,
            queue_url,
            topic_arn,
            postgres_pool,
        }
    }
}

pub struct Infrastructure;

impl Infrastructure {
    async fn init_database() -> Pool<Postgres> {
        PgPoolOptions::new()
            .min_connections(1)
            .max_connections(10)
            .test_before_acquire(true)
            .connect_with(
                PgConnectOptions::new()
                    .host("localhost")
                    .database("local")
                    .username("local")
                    .password("local")
                    .port(5432)
                    .application_name("outbox-pattern-processor"),
            )
            .await
            .unwrap()
    }

    async fn init_sqs(resources: &OutboxProcessorResources) -> CreateQueueOutput {
        resources.sqs_client.clone().unwrap().client.create_queue().queue_name("queue").send().await.unwrap()
    }

    async fn init_sns(resources: &OutboxProcessorResources) -> CreateTopicOutput {
        resources.sns_client.clone().unwrap().client.create_topic().name("topic").send().await.unwrap()
    }

    async fn init_mock_server() -> MockServer {
        for _ in 1..10 {
            let port = rand::thread_rng().gen_range(51000..54000);
            let addr = SocketAddr::from(([0, 0, 0, 0], port));
            if let Ok(listener) = TcpListener::bind(addr) {
                return MockServer::builder().listener(listener).start().await;
            }
        }

        panic!("Failed to create mock server");
    }
}

pub struct DefaultData;

impl DefaultData {
    pub async fn create_default_http_outbox_success(ctx: &mut TestContext) -> Outbox {
        Self::create_outbox(
            ctx,
            None,
            None,
            vec![OutboxDestination::HttpDestination(HttpDestination {
                url: format!("{}/success", ctx.gateway_uri),
                headers: None,
                method: None,
            })],
            None,
            None,
            None,
        )
        .await
    }

    pub async fn create_default_scheduled(
        ctx: &mut TestContext,
        process_after: DateTime<Utc>,
    ) -> Outbox {
        Self::create_outbox(
            ctx,
            None,
            None,
            vec![OutboxDestination::HttpDestination(HttpDestination {
                url: format!("{}/success", ctx.gateway_uri),
                headers: None,
                method: None,
            })],
            None,
            None,
            Some(process_after),
        )
        .await
    }

    pub async fn create_default_http_outbox_failed(ctx: &mut TestContext) -> Outbox {
        Self::create_outbox(
            ctx,
            None,
            None,
            vec![OutboxDestination::HttpDestination(HttpDestination {
                url: format!("{}/failed", ctx.gateway_uri),
                headers: None,
                method: None,
            })],
            None,
            None,
            None,
        )
        .await
    }

    pub async fn create_http_outbox_success_with_partition_key(
        ctx: &mut TestContext,
        partition_key: Uuid,
    ) -> Outbox {
        Self::create_outbox(
            ctx,
            None,
            Some(partition_key),
            vec![OutboxDestination::HttpDestination(HttpDestination {
                url: format!("{}/success", ctx.gateway_uri),
                headers: None,
                method: None,
            })],
            None,
            None,
            None,
        )
        .await
    }

    pub async fn create_http_outbox_success(
        ctx: &mut TestContext,
        method: &str,
    ) -> Outbox {
        Self::create_outbox(
            ctx,
            None,
            None,
            vec![OutboxDestination::HttpDestination(HttpDestination {
                url: format!("{}/success", ctx.gateway_uri),
                headers: None,
                method: Some(method.to_string()),
            })],
            None,
            None,
            None,
        )
        .await
    }

    pub async fn create_http_outbox_with_headers(
        ctx: &mut TestContext,
        http_headers_map: HashMap<String, String>,
        outbox_headers_map: HashMap<String, String>,
    ) -> Outbox {
        Self::create_outbox(
            ctx,
            None,
            None,
            vec![OutboxDestination::HttpDestination(HttpDestination {
                url: format!("{}/success", ctx.gateway_uri),
                headers: Some(http_headers_map),
                method: None,
            })],
            Some(outbox_headers_map),
            None,
            None,
        )
        .await
    }

    pub async fn create_default_sqs_outbox_success(ctx: &mut TestContext) -> Outbox {
        Self::create_outbox(
            ctx,
            None,
            None,
            vec![OutboxDestination::SqsDestination(SqsDestination { queue_url: ctx.queue_url.clone() })],
            None,
            None,
            None,
        )
        .await
    }

    pub async fn create_default_sqs_outbox_failed(ctx: &mut TestContext) -> Outbox {
        Self::create_outbox(
            ctx,
            None,
            None,
            vec![OutboxDestination::SqsDestination(SqsDestination {
                queue_url: "https://invalid.queue.com".to_string(),
            })],
            None,
            None,
            None,
        )
        .await
    }

    pub async fn create_default_sns_outbox_success(ctx: &mut TestContext) -> Outbox {
        Self::create_outbox(
            ctx,
            None,
            None,
            vec![OutboxDestination::SnsDestination(SnsDestination { topic_arn: ctx.topic_arn.clone() })],
            None,
            None,
            None,
        )
        .await
    }

    pub async fn create_default_sns_outbox_failed(ctx: &mut TestContext) -> Outbox {
        Self::create_outbox(
            ctx,
            None,
            None,
            vec![OutboxDestination::SnsDestination(SnsDestination {
                topic_arn: "invalid::arn".to_string(),
            })],
            None,
            None,
            None,
        )
        .await
    }

    pub async fn create_outbox(
        ctx: &mut TestContext,
        idempotent_key: Option<Uuid>,
        partition_key: Option<Uuid>,
        destinations: Vec<OutboxDestination>,
        headers: Option<HashMap<String, String>>,
        payload: Option<String>,
        process_after: Option<DateTime<Utc>>,
    ) -> Outbox {
        let sql = r#"
        insert into outbox
            (idempotent_key, partition_key, destinations, headers, payload, process_after)
        values
            ($1, $2, $3, $4, $5, $6)
        returning *
        "#;

        sqlx::query_as(sql)
            .bind(idempotent_key.unwrap_or(Uuid::now_v7()))
            .bind(partition_key.unwrap_or(Uuid::now_v7()))
            .bind(Json(destinations))
            .bind(headers.map(|it| Some(Json(it))))
            .bind(payload.unwrap_or(json!({"foo":"bar"}).to_string()))
            .bind(process_after.unwrap_or(Utc::now()))
            .fetch_one(&ctx.resources.postgres_pool)
            .await
            .unwrap()
    }

    pub async fn find_all_outboxes(ctx: &mut TestContext) -> Vec<Outbox> {
        let sql = r#"
        select * 
        from outbox
        "#;

        sqlx::query_as(sql).fetch_all(&ctx.resources.postgres_pool).await.unwrap()
    }

    pub async fn find_all_outboxes_processed(ctx: &mut TestContext) -> Vec<Outbox> {
        let sql = r#"
        select *
        from outbox
        where processed_at is not null
        "#;

        sqlx::query_as(sql).fetch_all(&ctx.resources.postgres_pool).await.unwrap()
    }

    pub async fn create_lock(
        ctx: &mut TestContext,
        processed: bool,
    ) {
        let processed_at = if processed { "now()" } else { "null" };

        let sql = format!(
            "insert into outbox_lock (partition_key, lock_id, processing_until, processed_at) values ('{}', '{}', now(), {})",
            Uuid::now_v7(),
            Uuid::now_v7(),
            processed_at
        );

        let _ = sqlx::query(&sql).execute(&ctx.postgres_pool).await;
    }

    pub async fn create_cleaner_schedule(
        ctx: &mut TestContext,
        cron: &str,
    ) {
        let last_execution = Utc::now() - Duration::from_secs(2);
        let sql = "insert into outbox_cleaner_schedule (cron_expression, last_execution) values ($1, $2)";
        let _ = sqlx::query(&sql).bind(cron).bind(last_execution).execute(&ctx.postgres_pool).await;
    }

    pub async fn count_locks(ctx: &mut TestContext) -> i64 {
        let sql = r#"
        select count(1)
        from outbox_lock
        "#;

        let result = sqlx::query_scalar(sql).fetch_one(&ctx.postgres_pool).await;

        match result {
            Ok(Some(count)) => count,
            Ok(None) | Err(_) => 0,
        }
    }

    pub async fn count_processed_locks(ctx: &mut TestContext) -> i64 {
        let sql = r#"
        select count(1)
        from outbox_lock
        where processed_at is not null
        "#;

        let result = sqlx::query_scalar(sql).fetch_one(&ctx.postgres_pool).await;

        match result {
            Ok(Some(count)) => count,
            Ok(None) | Err(_) => 0,
        }
    }

    pub async fn count_not_processed_locks(ctx: &mut TestContext) -> i64 {
        let sql = r#"
        select count(1)
        from outbox_lock
        where processed_at is null
        "#;

        let result = sqlx::query_scalar(sql).fetch_one(&ctx.postgres_pool).await;

        match result {
            Ok(Some(count)) => count,
            Ok(None) | Err(_) => 0,
        }
    }

    pub async fn clear(ctx: &mut TestContext) {
        let _ = sqlx::query("delete from outbox").execute(&ctx.resources.postgres_pool).await;
        let _ = sqlx::query("delete from outbox_lock").execute(&ctx.resources.postgres_pool).await;
        let _ = sqlx::query("delete from outbox_cleaner_schedule").execute(&ctx.resources.postgres_pool).await;
    }
}

pub struct HttpGatewayMock;

impl HttpGatewayMock {
    pub async fn default_mock(
        ctx: &mut TestContext,
        outbox: &Outbox,
    ) {
        Self::mock(ctx, outbox, "POST", None, None).await;
    }

    pub async fn mock_put(
        ctx: &mut TestContext,
        outbox: &Outbox,
    ) {
        Self::mock(ctx, outbox, "PUT", None, None).await;
    }

    pub async fn mock_patch(
        ctx: &mut TestContext,
        outbox: &Outbox,
    ) {
        Self::mock(ctx, outbox, "PATCH", None, None).await;
    }

    pub async fn mock_with_headers(
        ctx: &mut TestContext,
        outbox: &Outbox,
        headers_map: HashMap<String, String>,
    ) {
        Self::mock(ctx, outbox, "POST", None, Some(headers_map)).await;
    }

    async fn mock(
        ctx: &mut TestContext,
        outbox: &Outbox,
        method_name: &str,
        payload: Option<Value>,
        headers_map: Option<HashMap<String, String>>,
    ) {
        let mut mock_builder = Mock::given(method(method_name)).and(body_json_string(payload.unwrap_or(json!({"foo":"bar"})).to_string()));

        match headers_map {
            None => {},
            Some(headers) => {
                for (key, value) in headers {
                    mock_builder = mock_builder.and(header(key.as_str(), value.as_str()));
                }
            },
        }

        mock_builder
            .and(header("x-idempotent-key", outbox.idempotent_key.to_string()))
            .and(path("/success"))
            .respond_with(ResponseTemplate::new(200))
            .mount(&ctx.mock_server)
            .await;

        Mock::given(method(method_name))
            .and(header("x-idempotent-key", outbox.idempotent_key.to_string()))
            .and(path("/failed"))
            .respond_with(ResponseTemplate::new(500))
            .mount(&ctx.mock_server)
            .await;
    }
}