lenso-platform-module-remote 0.1.16

Remote module host support for the Lenso backend framework.
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
use axum::http::StatusCode;
use axum::{Json, Router, routing::post};
use platform_core::{
    EventHandlerRegistry, ExecutionContext, OutboxRelay, PLATFORM_MIGRATIONS, apply_migrations,
};
use platform_module_remote::{RemoteEventHandler, RemoteEventHostActionRunner, RemoteModuleConfig};
use platform_runtime::{
    FunctionDefinition, FunctionHandler, FunctionRegistry, RUNTIME_MIGRATIONS, RetryPolicy,
    RuntimeClient,
};
use platform_testing::TestDatabase;
use serde_json::{Value, json};
use std::sync::Arc;
use std::time::Duration;
use tokio::net::TcpListener;

#[tokio::test]
async fn outbox_relay_publishes_remote_event_handler_success() {
    let Some(db) = TestDatabase::create().await else {
        return;
    };
    apply_platform_migrations(&db).await;

    let remote = spawn_remote(event_success_router()).await;
    insert_outbox_event(&db.pool, "evt_remote_1", 3).await;

    let mut registry = EventHandlerRegistry::new();
    registry.register(Arc::new(remote_handler(&remote)));
    let relay = OutboxRelay::new(db.pool.clone(), "worker-remote");
    let count = relay
        .relay_once(&registry, 10)
        .await
        .expect("remote event handler should dispatch");

    assert_eq!(count, 1);
    assert_eq!(event_status(&db.pool, "evt_remote_1").await, "published");
    assert!(
        execution_log_bodies(&db.pool, "evt_remote_1")
            .await
            .contains(&"Outbox event published".to_owned())
    );

    db.cleanup().await;
}

#[tokio::test]
async fn outbox_relay_runs_remote_event_handler_enqueue_action() {
    let Some(db) = TestDatabase::create().await else {
        return;
    };
    apply_remote_event_stack_migrations(&db).await;

    let remote = spawn_remote(event_enqueue_action_router()).await;
    insert_outbox_event(&db.pool, "evt_remote_1", 3).await;

    let function_registry = Arc::new(remote_function_registry());
    let mut registry = EventHandlerRegistry::new();
    registry.register(Arc::new(remote_handler(&remote).with_host_action_runner(
        RemoteEventHostActionRunner::new(
            RuntimeClient::new(db.pool.clone()),
            function_registry,
            ["remote_crm.sync_contact.v1".to_owned()],
        ),
    )));
    let relay = OutboxRelay::new(db.pool.clone(), "worker-remote");
    let count = relay
        .relay_once(&registry, 10)
        .await
        .expect("remote event handler action should dispatch");

    assert_eq!(count, 1);
    assert_eq!(event_status(&db.pool, "evt_remote_1").await, "published");
    let run = function_run(&db.pool, "remote_crm.sync_contact.v1").await;
    assert_eq!(run.status, "pending");
    assert_eq!(run.max_attempts, 5);
    assert_eq!(run.correlation_id, "corr_remote_event_1");
    assert_eq!(run.input_json["contact_id"], "usr_1");
    assert_eq!(
        run.input_json["_lenso_runtime"]["causation_id"],
        "remote_event_handler:evt_remote_1:sync_contact_on_user_registered:0"
    );
    assert_eq!(run.actor["kind"], "user");
    assert_eq!(run.actor["user_id"], "usr_actor");

    db.cleanup().await;
}

#[tokio::test]
async fn outbox_relay_rejects_remote_event_handler_undeclared_enqueue_action() {
    let Some(db) = TestDatabase::create().await else {
        return;
    };
    apply_remote_event_stack_migrations(&db).await;

    let remote = spawn_remote(event_undeclared_enqueue_action_router()).await;
    insert_outbox_event(&db.pool, "evt_remote_1", 3).await;

    let function_registry = Arc::new(remote_function_registry());
    let mut registry = EventHandlerRegistry::new();
    registry.register(Arc::new(remote_handler(&remote).with_host_action_runner(
        RemoteEventHostActionRunner::new(
            RuntimeClient::new(db.pool.clone()),
            function_registry,
            ["remote_crm.sync_contact.v1".to_owned()],
        ),
    )));
    OutboxRelay::new(db.pool.clone(), "worker-remote")
        .relay_once(&registry, 10)
        .await
        .expect("relay should handle invalid remote event action");

    assert_eq!(
        event_status_and_attempts(&db.pool, "evt_remote_1").await,
        ("dead".to_owned(), 1)
    );
    assert_eq!(function_run_count(&db.pool).await, 0);

    db.cleanup().await;
}

#[tokio::test]
async fn outbox_relay_retries_remote_event_handler_failure() {
    let Some(db) = TestDatabase::create().await else {
        return;
    };
    apply_platform_migrations(&db).await;

    let remote = spawn_remote(event_retryable_failure_router()).await;
    insert_outbox_event(&db.pool, "evt_remote_1", 3).await;

    let mut registry = EventHandlerRegistry::new();
    registry.register(Arc::new(remote_handler(&remote)));
    OutboxRelay::new(db.pool.clone(), "worker-remote")
        .relay_once(&registry, 10)
        .await
        .expect("relay should handle remote event failure");

    assert_eq!(
        event_status_and_attempts(&db.pool, "evt_remote_1").await,
        ("failed".to_owned(), 1)
    );

    db.cleanup().await;
}

#[tokio::test]
async fn outbox_relay_marks_exhausted_remote_event_handler_dead() {
    let Some(db) = TestDatabase::create().await else {
        return;
    };
    apply_platform_migrations(&db).await;

    let remote = spawn_remote(event_retryable_failure_router()).await;
    insert_outbox_event(&db.pool, "evt_remote_1", 1).await;

    let mut registry = EventHandlerRegistry::new();
    registry.register(Arc::new(remote_handler(&remote)));
    OutboxRelay::new(db.pool.clone(), "worker-remote")
        .relay_once(&registry, 10)
        .await
        .expect("relay should handle remote event failure");

    assert_eq!(
        event_status_and_attempts(&db.pool, "evt_remote_1").await,
        ("dead".to_owned(), 1)
    );

    db.cleanup().await;
}

async fn spawn_remote(router: Router) -> String {
    let listener = TcpListener::bind(("127.0.0.1", 0))
        .await
        .expect("bind test server");
    let address = listener.local_addr().expect("test server address");
    tokio::spawn(async move {
        axum::serve(listener, router)
            .await
            .expect("test server should run");
    });
    format!("http://{address}")
}

fn event_success_router() -> Router {
    Router::new().route(
        "/events/handlers/sync_contact_on_user_registered/invoke",
        post(event_success),
    )
}

fn event_retryable_failure_router() -> Router {
    Router::new().route(
        "/events/handlers/sync_contact_on_user_registered/invoke",
        post(event_retryable_failure),
    )
}

fn event_enqueue_action_router() -> Router {
    Router::new().route(
        "/events/handlers/sync_contact_on_user_registered/invoke",
        post(event_enqueue_action),
    )
}

fn event_undeclared_enqueue_action_router() -> Router {
    Router::new().route(
        "/events/handlers/sync_contact_on_user_registered/invoke",
        post(event_undeclared_enqueue_action),
    )
}

fn remote_handler(base_url: &str) -> RemoteEventHandler {
    RemoteEventHandler::new(
        RemoteModuleConfig::new("remote-crm", base_url),
        "sync_contact_on_user_registered",
        "identity.user_registered.v1",
    )
    .expect("remote event handler")
}

fn remote_function_registry() -> FunctionRegistry {
    let mut registry = FunctionRegistry::default();
    registry.register(FunctionDefinition {
        name: "remote_crm.sync_contact.v1".to_owned(),
        version: 1,
        queue: "remote-crm".to_owned(),
        retry_policy: RetryPolicy::fixed(5, Duration::from_millis(250)),
        handler: Arc::new(NoopFunction),
    });
    registry
}

async fn event_success(Json(body): Json<Value>) -> Json<Value> {
    Json(json!({
        "accepted": true,
        "event_id": body["outbox_event_id"],
    }))
}

async fn event_enqueue_action(Json(body): Json<Value>) -> Json<Value> {
    Json(json!({
        "actions": [{
            "type": "enqueue_function",
            "function_name": "remote_crm.sync_contact.v1",
            "input": {
                "contact_id": body["aggregate_id"],
                "email": body["payload"]["email"]
            }
        }]
    }))
}

async fn event_undeclared_enqueue_action() -> Json<Value> {
    Json(json!({
        "actions": [{
            "type": "enqueue_function",
            "function_name": "identity.cleanup_expired_sessions.v1",
            "input": {}
        }]
    }))
}

async fn event_retryable_failure() -> (StatusCode, Json<Value>) {
    (
        StatusCode::SERVICE_UNAVAILABLE,
        Json(json!({
            "error": {
                "code": "external_dependency_failure",
                "message": "remote CRM event sink was unavailable",
                "retryable": true,
                "details": [{ "field": "upstream", "reason": "timeout" }]
            }
        })),
    )
}

async fn apply_platform_migrations(db: &TestDatabase) {
    apply_migrations(&db.pool, PLATFORM_MIGRATIONS)
        .await
        .expect("platform migrations should apply");
}

async fn apply_remote_event_stack_migrations(db: &TestDatabase) {
    apply_migrations(&db.pool, PLATFORM_MIGRATIONS)
        .await
        .expect("platform migrations should apply");
    apply_migrations(&db.pool, RUNTIME_MIGRATIONS)
        .await
        .expect("runtime migrations should apply");
}

async fn insert_outbox_event(pool: &platform_core::DbPool, id: &str, max_attempts: i32) {
    sqlx::query(
        r#"
        insert into platform.outbox (
            id,
            event_name,
            event_version,
            source_module,
            aggregate_type,
            aggregate_id,
            correlation_id,
            causation_id,
            occurred_at,
            payload,
            headers,
            max_attempts
        )
        values (
            $1,
            'identity.user_registered.v1',
            1,
            'identity',
            'user',
            'usr_1',
            'corr_remote_event_1',
            'httpreq_1',
            now(),
            $2,
            $3,
            $4
        )
        "#,
    )
    .bind(id)
    .bind(json!({
        "user_id": "usr_1",
        "email": "ada@example.com"
    }))
    .bind(json!({
        "actor": {
            "kind": "user",
            "user_id": "usr_actor",
            "scopes": []
        },
        "trace": {
            "trace_id": "trace_remote_event_1",
            "span_id": "span_remote_event_1",
            "baggage": []
        }
    }))
    .bind(max_attempts)
    .execute(pool)
    .await
    .expect("outbox event should insert");
}

async fn event_status(pool: &platform_core::DbPool, id: &str) -> String {
    sqlx::query_scalar("select status from platform.outbox where id = $1")
        .bind(id)
        .fetch_one(pool)
        .await
        .expect("event status should query")
}

async fn event_status_and_attempts(pool: &platform_core::DbPool, id: &str) -> (String, i32) {
    sqlx::query_as("select status, attempts from platform.outbox where id = $1")
        .bind(id)
        .fetch_one(pool)
        .await
        .expect("event status should query")
}

async fn execution_log_bodies(pool: &platform_core::DbPool, id: &str) -> Vec<String> {
    sqlx::query_scalar(
        r#"
        select body
        from platform.execution_logs
        where execution_id = $1
        order by occurred_at asc
        "#,
    )
    .bind(id)
    .fetch_all(pool)
    .await
    .expect("execution logs should query")
}

#[derive(Debug)]
struct NoopFunction;

#[async_trait::async_trait]
impl FunctionHandler for NoopFunction {
    async fn call(&self, _ctx: ExecutionContext, _input: Value) -> platform_core::AppResult<Value> {
        Ok(Value::Null)
    }
}

struct FunctionRunRow {
    status: String,
    max_attempts: i32,
    correlation_id: String,
    input_json: Value,
    actor: Value,
}

async fn function_run(pool: &platform_core::DbPool, function_name: &str) -> FunctionRunRow {
    let row: (String, i32, String, Value, Value) = sqlx::query_as(
        r#"
        select status, max_attempts, correlation_id, input_json, actor
        from runtime.function_runs
        where function_name = $1
        "#,
    )
    .bind(function_name)
    .fetch_one(pool)
    .await
    .expect("function run should query");

    FunctionRunRow {
        status: row.0,
        max_attempts: row.1,
        correlation_id: row.2,
        input_json: row.3,
        actor: row.4,
    }
}

async fn function_run_count(pool: &platform_core::DbPool) -> i64 {
    sqlx::query_scalar("select count(*) from runtime.function_runs")
        .fetch_one(pool)
        .await
        .expect("function run count should query")
}