vyuh 0.2.11

Vyuh web framework for Axum and SQLx with handler-first APIs
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
#![cfg(feature = "postgres")]

use sqlx::PgPool;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio::time::Duration;
use vyuh::Data;
use vyuh::emitters::{self, *};

async fn create_site(pool: PgPool) -> vyuh::Site {
    let conf = vyuh::SiteConf {
        log_init: false,
        logging: vyuh::logging::LoggingConf {
            env_prefix: None,
            rules: vec![],
        },
        ..vyuh::SiteConf::from_env().unwrap()
    };
    let parts: Vec<vyuh::bundles::BundlePart> = vec![];
    let bundle = vyuh::bundles::bundle(parts);
    vyuh::Site::test(conf, bundle, pool)
        .await
        .expect("Failed to create test site")
}

#[sqlx::test]
async fn test_periodic(pool: PgPool) -> Result<(), Box<dyn std::error::Error>> {
    #[derive(Clone, schemars::JsonSchema, serde::Serialize, serde::Deserialize)]
    struct Sample;

    let counter = Arc::new(AtomicUsize::new(0));
    let counter_clone = counter.clone();

    async fn handler(cnt: Arc<AtomicUsize>) -> Data<Sample> {
        cnt.fetch_add(1, Ordering::SeqCst);
        Data::new(Sample)
    }

    let site = create_site(pool).await;
    let emitter = emitters::periodic(
        move |emitters::IterCount(_it): emitters::IterCount| handler(counter_clone.clone()),
        emitters::PeriodicConf {
            interval: Duration::from_millis(100),
            target: emitters::EmitTarget::Signal,
        },
    )?;

    let mut registry = EmitterRegistry::new();
    registry.register(emitter)?;

    let task_site = site.clone();
    let engine = registry.create_engine();
    let run_handle = tokio::spawn(async move { engine.run(task_site).await });

    // Wait for periodic fires (3+ expected in 350ms with 100ms intervals)
    tokio::time::sleep(Duration::from_millis(350)).await;

    let fired_count = counter.load(Ordering::SeqCst);
    assert!(
        fired_count >= 3,
        "Expected at least 3 periodic fires, got {}",
        fired_count
    );

    site.shutdown_and_wait().await;
    let _ = tokio::time::timeout(Duration::from_millis(100), run_handle).await;
    Ok(())
}

#[sqlx::test]
async fn test_pgnotify_trailing_debounce_uses_last_payload(
    pool: PgPool,
) -> Result<(), Box<dyn std::error::Error>> {
    #[derive(Clone, schemars::JsonSchema, serde::Serialize, serde::Deserialize)]
    struct NotifyData {
        raw: String,
    }

    let counter = Arc::new(AtomicUsize::new(0));
    let payloads = Arc::new(Mutex::new(Vec::new()));
    let counter_clone = counter.clone();
    let payloads_clone = payloads.clone();

    let site = create_site(pool.clone()).await;
    let emitter = emitters::pgnotify(
        move |payload: Data<String>| {
            let cnt = counter_clone.clone();
            let seen = payloads_clone.clone();
            async move {
                cnt.fetch_add(1, Ordering::SeqCst);
                seen.lock().unwrap().push(payload.to_string());
                Data::new(NotifyData {
                    raw: payload.to_string(),
                })
            }
        },
        emitters::PgNotifyConf {
            channel: "test_trailing_debounce".to_string(),
            target: emitters::EmitTarget::Signal,
            debounce: Some(emitters::DebounceConf {
                window: Duration::from_millis(100),
                mode: emitters::DebounceMode::Trailing,
            }),
        },
    )?;

    let mut registry = EmitterRegistry::new();
    registry.register(emitter)?;

    let task_site = site.clone();
    let engine = registry.create_engine();
    let run_handle = tokio::spawn(async move { engine.run(task_site).await });

    tokio::time::sleep(Duration::from_millis(100)).await;
    site.db()
        .send_pgnotify("test_trailing_debounce", "first")
        .await?;
    site.db()
        .send_pgnotify("test_trailing_debounce", "middle")
        .await?;
    site.db()
        .send_pgnotify("test_trailing_debounce", "last")
        .await?;
    tokio::time::sleep(Duration::from_millis(250)).await;

    assert_eq!(counter.load(Ordering::SeqCst), 1);
    assert_eq!(payloads.lock().unwrap().as_slice(), ["last"]);

    site.shutdown_and_wait().await;
    let _ = tokio::time::timeout(Duration::from_millis(100), run_handle).await;
    Ok(())
}

#[sqlx::test]
async fn test_pgnotify_leading_trailing_debounce_emits_first_and_last(
    pool: PgPool,
) -> Result<(), Box<dyn std::error::Error>> {
    #[derive(Clone, schemars::JsonSchema, serde::Serialize, serde::Deserialize)]
    struct NotifyData {
        raw: String,
    }

    let counter = Arc::new(AtomicUsize::new(0));
    let payloads = Arc::new(Mutex::new(Vec::new()));
    let counter_clone = counter.clone();
    let payloads_clone = payloads.clone();

    let site = create_site(pool.clone()).await;
    let emitter = emitters::pgnotify(
        move |payload: Data<String>| {
            let cnt = counter_clone.clone();
            let seen = payloads_clone.clone();
            async move {
                cnt.fetch_add(1, Ordering::SeqCst);
                seen.lock().unwrap().push(payload.to_string());
                Data::new(NotifyData {
                    raw: payload.to_string(),
                })
            }
        },
        emitters::PgNotifyConf {
            channel: "test_leading_trailing_debounce".to_string(),
            target: emitters::EmitTarget::Signal,
            debounce: Some(emitters::DebounceConf {
                window: Duration::from_millis(100),
                mode: emitters::DebounceMode::LeadingAndTrailing,
            }),
        },
    )?;

    let mut registry = EmitterRegistry::new();
    registry.register(emitter)?;

    let task_site = site.clone();
    let engine = registry.create_engine();
    let run_handle = tokio::spawn(async move { engine.run(task_site).await });

    tokio::time::sleep(Duration::from_millis(100)).await;
    site.db()
        .send_pgnotify("test_leading_trailing_debounce", "first")
        .await?;
    site.db()
        .send_pgnotify("test_leading_trailing_debounce", "middle")
        .await?;
    site.db()
        .send_pgnotify("test_leading_trailing_debounce", "last")
        .await?;
    tokio::time::sleep(Duration::from_millis(250)).await;

    assert_eq!(counter.load(Ordering::SeqCst), 2);
    assert_eq!(payloads.lock().unwrap().as_slice(), ["first", "last"]);

    site.shutdown_and_wait().await;
    let _ = tokio::time::timeout(Duration::from_millis(100), run_handle).await;
    Ok(())
}

#[sqlx::test]
async fn test_pgnotify_slow_handler_does_not_block_other_notifications(
    pool: PgPool,
) -> Result<(), Box<dyn std::error::Error>> {
    #[derive(Clone, schemars::JsonSchema, serde::Serialize, serde::Deserialize)]
    struct SlowData;

    #[derive(Clone, schemars::JsonSchema, serde::Serialize, serde::Deserialize)]
    struct FastData;

    let slow_counter = Arc::new(AtomicUsize::new(0));
    let fast_counter = Arc::new(AtomicUsize::new(0));
    let slow_counter_clone = slow_counter.clone();
    let fast_counter_clone = fast_counter.clone();

    let site = create_site(pool.clone()).await;
    let slow = emitters::pgnotify(
        move |_payload: Data<String>| {
            let cnt = slow_counter_clone.clone();
            async move {
                tokio::time::sleep(Duration::from_millis(300)).await;
                cnt.fetch_add(1, Ordering::SeqCst);
                Data::new(SlowData)
            }
        },
        emitters::PgNotifyConf {
            channel: "test_slow_pgnotify".to_string(),
            target: emitters::EmitTarget::Signal,
            debounce: None,
        },
    )?;
    let fast = emitters::pgnotify(
        move |_payload: Data<String>| {
            let cnt = fast_counter_clone.clone();
            async move {
                cnt.fetch_add(1, Ordering::SeqCst);
                Data::new(FastData)
            }
        },
        emitters::PgNotifyConf {
            channel: "test_fast_pgnotify".to_string(),
            target: emitters::EmitTarget::Signal,
            debounce: None,
        },
    )?;

    let mut registry = EmitterRegistry::new();
    registry.register(slow)?;
    registry.register(fast)?;

    let task_site = site.clone();
    let engine = registry.create_engine();
    let run_handle = tokio::spawn(async move { engine.run(task_site).await });

    tokio::time::sleep(Duration::from_millis(100)).await;
    site.db()
        .send_pgnotify("test_slow_pgnotify", "slow")
        .await?;
    tokio::time::sleep(Duration::from_millis(25)).await;
    site.db()
        .send_pgnotify("test_fast_pgnotify", "fast")
        .await?;

    assert!(
        wait_for_count(&fast_counter, 1, Duration::from_millis(150)).await,
        "fast pgnotify handler was blocked by slow handler"
    );
    assert_eq!(slow_counter.load(Ordering::SeqCst), 0);
    assert!(wait_for_count(&slow_counter, 1, Duration::from_millis(400)).await);

    site.shutdown_and_wait().await;
    let _ = tokio::time::timeout(Duration::from_millis(100), run_handle).await;
    Ok(())
}

#[sqlx::test]
async fn test_cron(pool: PgPool) -> Result<(), Box<dyn std::error::Error>> {
    #[derive(Clone, schemars::JsonSchema, serde::Serialize, serde::Deserialize)]
    struct CronData;

    let counter = Arc::new(AtomicUsize::new(0));
    let counter_clone = counter.clone();

    async fn handler(cnt: Arc<AtomicUsize>) -> Data<CronData> {
        cnt.fetch_add(1, Ordering::SeqCst);
        Data::new(CronData)
    }

    let site = create_site(pool).await;
    let emitter = emitters::cron(
        move || handler(counter_clone.clone()),
        emitters::CronConf {
            expr: "* * * * * *".into(), // Every second
            target: emitters::EmitTarget::Signal,
        },
    )?;

    let mut registry = EmitterRegistry::new();
    registry.register(emitter)?;

    let task_site = site.clone();
    let engine = registry.create_engine();
    let run_handle = tokio::spawn(async move { engine.run(task_site).await });

    // Wait for cron fires (2+ expected in 2.5 seconds)
    tokio::time::sleep(Duration::from_millis(2500)).await;

    let fired_count = counter.load(Ordering::SeqCst);
    assert!(
        fired_count >= 2,
        "Expected at least 2 cron fires, got {}",
        fired_count
    );

    site.shutdown_and_wait().await;
    let _ = tokio::time::timeout(Duration::from_millis(100), run_handle).await;
    Ok(())
}

async fn wait_for_count(counter: &AtomicUsize, expected: usize, timeout: Duration) -> bool {
    let start = tokio::time::Instant::now();
    while start.elapsed() < timeout {
        if counter.load(Ordering::SeqCst) >= expected {
            return true;
        }
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
    counter.load(Ordering::SeqCst) >= expected
}

#[sqlx::test]
async fn test_pgnotify_debounce_still_postpones_periodic_fallback(
    pool: PgPool,
) -> Result<(), Box<dyn std::error::Error>> {
    #[derive(Clone, schemars::JsonSchema, serde::Serialize, serde::Deserialize)]
    struct NotifyData;

    let periodic_counter = Arc::new(AtomicUsize::new(0));
    let pgnotify_counter = Arc::new(AtomicUsize::new(0));
    let periodic_counter_clone = periodic_counter.clone();
    let pgnotify_counter_clone = pgnotify_counter.clone();

    let site = create_site(pool.clone()).await;
    let periodic = emitters::periodic(
        move || {
            let cnt = periodic_counter_clone.clone();
            async move {
                cnt.fetch_add(1, Ordering::SeqCst);
                Data::new(NotifyData)
            }
        },
        emitters::PeriodicConf {
            interval: Duration::from_millis(200),
            target: emitters::EmitTarget::Signal,
        },
    )?;
    let pgnotify = emitters::pgnotify(
        move |_payload: Data<String>| {
            let cnt = pgnotify_counter_clone.clone();
            async move {
                cnt.fetch_add(1, Ordering::SeqCst);
                Data::new(NotifyData)
            }
        },
        emitters::PgNotifyConf {
            channel: "test_debounce_periodic_fallback".to_string(),
            target: emitters::EmitTarget::Signal,
            debounce: Some(emitters::DebounceConf {
                window: Duration::from_millis(100),
                mode: emitters::DebounceMode::Trailing,
            }),
        },
    )?;

    let mut registry = EmitterRegistry::new();
    registry.register(periodic)?;
    registry.register(pgnotify)?;

    let task_site = site.clone();
    let engine = registry.create_engine();
    let run_handle = tokio::spawn(async move { engine.run(task_site).await });

    assert!(wait_for_count(&periodic_counter, 1, Duration::from_millis(250)).await);
    let initial_periodic_count = periodic_counter.load(Ordering::SeqCst);

    site.db()
        .send_pgnotify("test_debounce_periodic_fallback", "first")
        .await?;
    tokio::time::sleep(Duration::from_millis(60)).await;
    site.db()
        .send_pgnotify("test_debounce_periodic_fallback", "middle")
        .await?;
    tokio::time::sleep(Duration::from_millis(60)).await;
    site.db()
        .send_pgnotify("test_debounce_periodic_fallback", "last")
        .await?;

    tokio::time::sleep(Duration::from_millis(100)).await;
    assert_eq!(
        periodic_counter.load(Ordering::SeqCst),
        initial_periodic_count,
        "periodic fallback fired during an active pgnotify burst"
    );
    assert!(wait_for_count(&pgnotify_counter, 1, Duration::from_millis(250)).await);
    assert!(
        wait_for_count(
            &periodic_counter,
            initial_periodic_count + 1,
            Duration::from_millis(350),
        )
        .await
    );

    site.shutdown_and_wait().await;
    let _ = tokio::time::timeout(Duration::from_millis(100), run_handle).await;
    Ok(())
}

#[sqlx::test]
async fn test_pgnotify(pool: PgPool) -> Result<(), Box<dyn std::error::Error>> {
    #[derive(Clone, schemars::JsonSchema, serde::Serialize, serde::Deserialize)]
    struct NotifyData;

    let counter = Arc::new(AtomicUsize::new(0));
    let counter_clone = counter.clone();

    let site = create_site(pool.clone()).await;
    let emitter = emitters::pgnotify(
        move |_s: Data<String>| {
            let cnt = counter_clone.clone();
            async move {
                cnt.fetch_add(1, Ordering::SeqCst);
                Data::new(NotifyData)
            }
        },
        emitters::PgNotifyConf {
            channel: "test_channel".to_string(),
            target: emitters::EmitTarget::Signal,
            debounce: None,
        },
    )?;

    let mut registry = EmitterRegistry::new();
    registry.register(emitter)?;

    let task_site = site.clone();
    let engine = registry.create_engine();
    let run_handle = tokio::spawn(async move { engine.run(task_site).await });

    // Wait for notifications to be processed
    tokio::time::sleep(Duration::from_millis(100)).await;

    for _ in 0..3 {
        site.db().send_pgnotify("test_channel", "").await.unwrap();
    }
    tokio::time::sleep(Duration::from_millis(100)).await;

    let fired_count = counter.load(Ordering::SeqCst);
    assert!(
        fired_count >= 3,
        "Expected at least 3 pgnotify fires, got {}",
        fired_count
    );

    site.shutdown_and_wait().await;
    let _ = tokio::time::timeout(Duration::from_millis(100), run_handle).await;
    Ok(())
}