rings-node 1.0.0-pre.6

Rings is a browser-native, structured peer-to-peer network: browser tabs and native daemons find each other by DID and talk over WebRTC, routed by a Chord DHT.
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
//! Browser mail reception through retained IndexedDB stores and the exported JavaScript API.
//!
//! Descriptor publication uses two connected browser peers and awaits their registration
//! readiness events. The other tests use a singleton overlay, whose local placements still
//! produce owner store reports. No test needs an external STUN server or a second browser
//! process. Two providers sharing one storage name model tabs holding distinct delegatee keys
//! for the same DID.
//!
//! Law: with a live recipient task, a poll after delivery is a processing barrier; its own
//! counters do not identify which poll processed the mail. Assertions inspect the resulting
//! inbox, notifications, and retained records instead.

use std::collections::BTreeMap;

use futures::channel::mpsc;
use futures::FutureExt;
use futures::StreamExt;
use js_sys::Array;
use js_sys::Function;
use js_sys::Reflect;
use js_sys::Uint8Array;
use rings_core::delegation::DelegateeKey;
use rings_core::ecc::SecretKey;
use rings_core::storage::idb::IdbStorage;
use rings_core::storage::KvStorageInterface;
use rings_core::storage::RecordAuthority;
use rings_core::utils::js_value;
use wasm_bindgen::closure::Closure;
use wasm_bindgen::JsCast;
use wasm_bindgen::JsValue;
use wasm_bindgen_futures::JsFuture;
use wasm_bindgen_test::wasm_bindgen_test;

use super::provider_did;
use super::with_hang_guard;
use super::TEST_HANG_GUARD;
use crate::error::Error;
use crate::mail::descriptor::MailRecipient;
use crate::mail::gateway::MailDrop;
use crate::mail::gateway::MailGateway;
use crate::mail::recipient::KvInbox;
use crate::mail::recipient::Recipient;
use crate::mail::recipient::RecipientError;
use crate::mail::recipient::RecipientRecord;
use crate::mail::recipient::StoredMail;
use crate::mail::recipient::DEFAULT_MAIL_POLL_INTERVAL;
use crate::processor::ProcessorConfig;
use crate::provider::browser::provider::mail::BrowserMailError;
use crate::provider::browser::provider::mail::MAIL_STORAGE_ROWS;
use crate::provider::browser::BrowserMailOptions;
use crate::provider::browser::ProviderListener;
use crate::provider::Provider;
use crate::tests::TEST_ICE_SERVERS;

/// A raw message whose stable Message-ID identifies every randomized resend in these tests.
const MESSAGE: &[u8] = b"Message-ID: <browser-mail@example.org>\r\n\r\nBrowser inbox.\r\n";

/// A different message whose deduplication key requires another inbox row.
const SECOND_MESSAGE: &[u8] =
    b"Message-ID: <browser-mail-second@example.org>\r\n\r\nNext mail.\r\n";

/// A recipient whose inbox and records have independently bounded retained IndexedDB stores.
type RetainedRecipient = Recipient<KvInbox<IdbStorage>, IdbStorage>;

/// A JavaScript callback and its buffered notifications; no notification needs an inbox scan.
struct MailNotifications {
    /// The Rust closure kept alive for the duration of its provider's callback registration.
    callback: Closure<dyn Fn(String)>,
    /// The ordered identifiers delivered by the callback.
    received: mpsc::UnboundedReceiver<String>,
}

impl MailNotifications {
    /// Install the notification channel before a provider starts its first poll.
    fn new() -> Self {
        let (sender, received) = mpsc::unbounded();
        let callback = Closure::new(move |identifier: String| {
            sender.unbounded_send(identifier).unwrap();
        });
        Self { callback, received }
    }

    /// The JavaScript function handle for this log, sharing the same live closure.
    fn function(&self) -> Function {
        self.callback.as_ref().unchecked_ref::<Function>().clone()
    }

    /// Await one filed identifier, including one delivered before this future was created.
    async fn next(&mut self) -> String {
        self.received.next().await.unwrap()
    }

    /// Assert that completed polls have produced no unconsumed notification.
    fn assert_empty(&mut self) {
        assert!(self.received.next().now_or_never().is_none());
    }
}

/// A browser configuration with a fresh delegatee key for the account `identity`.
fn configuration(identity: &SecretKey) -> ProcessorConfig {
    let delegatee_key = DelegateeKey::new_with_seckey(identity).unwrap();
    ProcessorConfig::new(0, TEST_ICE_SERVERS.to_owned(), delegatee_key, 200).dht_virtual_nodes(0)
}

/// A storage namespace isolated from every other browser test run.
fn storage_name() -> String {
    format!("rings-browser-mail-test-{}", uuid::Uuid::new_v4())
}

/// The recipient named by a configuration, used to preseed mail before receiving is enabled.
fn recipient_of(config: &ProcessorConfig) -> MailRecipient {
    let delegatee_key = config.delegatee_key();
    MailRecipient {
        did: delegatee_key.delegator_did(),
        encryption_key: delegatee_key.delegatee_public_key(),
    }
}

/// A gateway using the provider's overlay and its ordinary reported-write path.
fn gateway(provider: &Provider) -> MailGateway {
    MailGateway::new(provider.mail_processor_for_test())
}

/// Connect a listening provider to a second browser peer and await both registration events.
/// Law: readiness requires a publish that began with an admitted edge, so a singleton cannot
/// witness it. The first admission wakes each listener's early publish, and owner reports
/// resolve readiness before the caller performs its one descriptor lookup.
async fn connect_registration_peer(provider: &Provider) -> (Provider, ProviderListener) {
    let peer = Provider::new_browser_provider_with_storage(
        configuration(&SecretKey::random()),
        storage_name(),
    )
    .await
    .unwrap();
    let peer_listener = peer.listen();
    JsFuture::from(peer_listener.started()).await.unwrap();
    let processor = provider.mail_processor_for_test();
    let peer_processor = peer.mail_processor_for_test();
    let offer = processor
        .swarm
        .create_offer(peer_processor.did())
        .await
        .unwrap();
    let answer = peer_processor
        .swarm
        .answer_offer(offer)
        .await
        .unwrap()
        .answer()
        .expect("the peer holds no competing offer, so it answers");
    processor.swarm.accept_answer(answer).await.unwrap();
    provider.registrations_published().await;
    peer.registrations_published().await;
    (peer, peer_listener)
}

/// Read the inbox through the exported promise API, preserving each returned JavaScript row.
async fn listed_mail(provider: &Provider) -> Vec<JsValue> {
    let value = JsFuture::from(provider.list_mail()).await.unwrap();
    assert!(Array::is_array(&value));
    Array::from(&value).iter().collect()
}

/// Read one named property from a row returned to JavaScript.
fn property(value: &JsValue, name: &str) -> JsValue {
    Reflect::get(value, &JsValue::from_str(name)).unwrap()
}

/// Assert that a JavaScript row preserves the mail id, raw RFC 5322 bytes and filing time.
fn assert_message(row: &JsValue, identifier: &str) {
    assert_eq!(property(row, "id").as_string().unwrap(), identifier);
    let message = property(row, "message").dyn_into::<Uint8Array>().unwrap();
    assert_eq!(message.to_vec(), MESSAGE);
    let filed_at_ms = property(row, "filed_at_ms");
    assert!(filed_at_ms.is_bigint());
    assert!(js_value::deserialize::<u128>(filed_at_ms).unwrap() > 0);
}

/// Snapshot retained records under the same row budget and authority as the provider.
async fn recipient_records(storage_name: &str) -> BTreeMap<String, RecipientRecord> {
    let store = IdbStorage::new_with_cap_name_and_authority(
        MAIL_STORAGE_ROWS,
        &format!("{storage_name}/mail-records"),
        RecordAuthority::Retained,
    )
    .await
    .unwrap();
    let records: Vec<(String, RecipientRecord)> = store.get_all().await.unwrap();
    records.into_iter().collect()
}

/// Snapshot shared filing records. Law: a duplicate preserves their keys and timestamps,
/// while opening records may grow as other ciphertexts or delegatee keys are observed.
async fn filed_records(storage_name: &str) -> BTreeMap<String, RecipientRecord> {
    recipient_records(storage_name)
        .await
        .into_iter()
        .filter(|(_, record)| matches!(record, RecipientRecord::Filed { .. }))
        .collect()
}

/// Close the node while its listener and mail poller are live; both must finish before return.
async fn close_listening_provider(provider: Provider, listener: ProviderListener) {
    provider.close().await.unwrap();
    JsFuture::from(listener.task()).await.unwrap();
}

/// Law: only a valid custom heartbeat schedule can cross the JavaScript options boundary.
#[wasm_bindgen_test]
fn test_mail_options_validate_the_heartbeat_schedule() {
    assert!(BrowserMailOptions::new(None, None).is_ok());
    assert!(BrowserMailOptions::new(Some(10_000), Some(40_000)).is_ok());
    assert!(BrowserMailOptions::new(Some(90_000), Some(30_000)).is_err());
    assert!(BrowserMailOptions::new(Some(300_000), Some(600_000)).is_err());
}

/// Law: construction opts into the listener's descriptor heartbeat; existing constructors do not.
#[wasm_bindgen_test]
async fn test_mail_descriptor_is_published_only_when_enabled() {
    with_hang_guard(
        "test_mail_descriptor_is_published_only_when_enabled",
        TEST_HANG_GUARD,
        async {
            let config = configuration(&SecretKey::random());
            let provider = Provider::new_browser_provider_with_storage(config, storage_name())
                .await
                .unwrap();
            let listener = provider.listen();
            JsFuture::from(listener.started()).await.unwrap();
            let (peer, peer_listener) = connect_registration_peer(&provider).await;
            assert_eq!(
                gateway(&peer)
                    .recipient(provider_did(&provider))
                    .await
                    .unwrap(),
                None
            );
            close_listening_provider(provider, listener).await;
            close_listening_provider(peer, peer_listener).await;

            let config = configuration(&SecretKey::random());
            let expected = recipient_of(&config);
            let provider = Provider::new_browser_provider_with_mail(
                config,
                storage_name(),
                BrowserMailOptions::default(),
                None,
            )
            .await
            .unwrap();
            let listener = provider.listen();
            JsFuture::from(listener.started()).await.unwrap();
            let (peer, peer_listener) = connect_registration_peer(&provider).await;
            assert_eq!(
                gateway(&peer).recipient(expected.did).await.unwrap(),
                Some(expected)
            );
            close_listening_provider(provider, listener).await;
            close_listening_provider(peer, peer_listener).await;
        },
    )
    .await;
}

/// Seed a reported gateway delivery while the inbox is disabled, so only the enabled
/// provider's automatic startup poll can produce the first notification.
async fn seed_pending_mail(config: ProcessorConfig, storage_name: String) -> String {
    let recipient = recipient_of(&config);
    let provider = Provider::new_browser_provider_with_storage(config, storage_name)
        .await
        .unwrap();
    let identifier = gateway(&provider)
        .deliver(&recipient, MESSAGE)
        .await
        .unwrap()
        .to_string();
    provider.close().await.unwrap();
    identifier
}

/// Assert JavaScript list and read expose exactly the one expected inbox entry.
async fn assert_single_message(provider: &Provider, identifier: &str) {
    let listed = listed_mail(provider).await;
    assert_eq!(listed.len(), 1);
    assert_message(listed.first().unwrap(), identifier);
    let read = JsFuture::from(provider.read_mail(identifier.to_owned()))
        .await
        .unwrap();
    assert_message(&read, identifier);
}

/// Law: automatic reception notifies after filing, and both the inbox and deduplication
/// records survive a close and a reload with a new delegatee key.
#[wasm_bindgen_test]
async fn test_mail_startup_notification_restart_deduplication_and_removal() {
    with_hang_guard(
        "test_mail_startup_notification_restart_deduplication_and_removal",
        TEST_HANG_GUARD,
        async {
            let identity = SecretKey::random();
            let config = configuration(&identity);
            let storage_name = storage_name();
            let identifier = seed_pending_mail(config.clone(), storage_name.clone()).await;
            let mut notifications = MailNotifications::new();
            let provider = Provider::new_browser_provider_with_mail(
                config,
                storage_name.clone(),
                BrowserMailOptions::default(),
                Some(notifications.function()),
            )
            .await
            .unwrap();
            assert_eq!(notifications.next().await, identifier);
            provider.poll_mail_for_test().await.unwrap();
            assert_single_message(&provider, &identifier).await;
            notifications.assert_empty();
            let before = recipient_records(&storage_name).await;
            assert!(before
                .values()
                .any(|record| matches!(record, RecipientRecord::Filed { .. })));
            assert!(before
                .values()
                .any(|record| matches!(record, RecipientRecord::Opened { .. })));
            provider.close().await.unwrap();

            let reloaded_config = configuration(&identity);
            let current_recipient = recipient_of(&reloaded_config);
            let provider = Provider::new_browser_provider_with_mail(
                reloaded_config,
                storage_name.clone(),
                BrowserMailOptions::default(),
                Some(notifications.function()),
            )
            .await
            .unwrap();
            provider.poll_mail_for_test().await.unwrap();
            assert_single_message(&provider, &identifier).await;
            let after = recipient_records(&storage_name).await;
            assert!(before
                .iter()
                .all(|(name, record)| after.get(name) == Some(record)));
            let filed_before_resend = filed_records(&storage_name).await;
            assert_eq!(filed_before_resend.len(), 1);
            gateway(&provider)
                .deliver(&current_recipient, MESSAGE)
                .await
                .unwrap();
            provider.poll_mail_for_test().await.unwrap();
            assert_single_message(&provider, &identifier).await;
            notifications.assert_empty();
            assert_eq!(filed_records(&storage_name).await, filed_before_resend);

            JsFuture::from(provider.remove_mail(identifier.clone()))
                .await
                .unwrap();
            assert!(listed_mail(&provider).await.is_empty());
            assert!(JsFuture::from(provider.read_mail(identifier))
                .await
                .unwrap()
                .is_null());
            gateway(&provider)
                .deliver(&current_recipient, MESSAGE)
                .await
                .unwrap();
            provider.poll_mail_for_test().await.unwrap();
            assert!(listed_mail(&provider).await.is_empty());
            notifications.assert_empty();
            assert_eq!(filed_records(&storage_name).await, filed_before_resend);
            provider.close().await.unwrap();
        },
    )
    .await;
}

/// Law: a tab's unreadable verdict cannot hide mail from the tab holding its key, while a
/// filed Message-ID deduplicates resends under either key in the shared stores.
#[wasm_bindgen_test]
async fn test_mail_two_tabs_scope_unreadable_records_and_share_filed_records() {
    with_hang_guard(
        "test_mail_two_tabs_scope_unreadable_records_and_share_filed_records",
        TEST_HANG_GUARD,
        async {
            let identity = SecretKey::random();
            let first_config = configuration(&identity);
            let second_config = configuration(&identity);
            let first_recipient = recipient_of(&first_config);
            let second_recipient = recipient_of(&second_config);
            assert_eq!(first_recipient.did, second_recipient.did);
            assert_ne!(
                first_recipient.encryption_key,
                second_recipient.encryption_key
            );
            let storage_name = storage_name();
            let mut first_notifications = MailNotifications::new();
            let first = Provider::new_browser_provider_with_mail(
                first_config.clone(),
                storage_name.clone(),
                BrowserMailOptions::default(),
                Some(first_notifications.function()),
            )
            .await
            .unwrap();
            first.poll_mail_for_test().await.unwrap();
            let identifier = gateway(&first)
                .deliver(&second_recipient, MESSAGE)
                .await
                .unwrap()
                .to_string();
            first.poll_mail_for_test().await.unwrap();
            assert!(listed_mail(&first).await.is_empty());
            first_notifications.assert_empty();
            let unreadable_records = recipient_records(&storage_name).await;
            assert!(unreadable_records
                .values()
                .any(|record| matches!(record, RecipientRecord::Opened { .. })));
            assert!(filed_records(&storage_name).await.is_empty());

            let mut second_notifications = MailNotifications::new();
            let locked_attempt = Provider::new_browser_provider_with_mail(
                second_config.clone(),
                storage_name.clone(),
                BrowserMailOptions::default(),
                Some(second_notifications.function()),
            )
            .await;
            assert!(
                matches!(
                    &locked_attempt,
                    Err(BrowserMailError::Provider(Error::BrowserStorageLocked(locked)))
                        if locked == &storage_name
                ),
                "expected BrowserStorageLocked({storage_name:?}), got {}",
                locked_attempt
                    .err()
                    .map_or_else(|| "Ok(Provider)".to_owned(), |error| error.to_string())
            );
            first.close().await.unwrap();

            let second = Provider::new_browser_provider_with_mail(
                second_config,
                storage_name.clone(),
                BrowserMailOptions::default(),
                Some(second_notifications.function()),
            )
            .await
            .unwrap();
            assert_eq!(second_notifications.next().await, identifier);
            second.poll_mail_for_test().await.unwrap();
            assert_single_message(&second, &identifier).await;
            first_notifications.assert_empty();
            second_notifications.assert_empty();
            let filed_before_resend = filed_records(&storage_name).await;
            assert_eq!(filed_before_resend.len(), 1);
            gateway(&second)
                .deliver(&first_recipient, MESSAGE)
                .await
                .unwrap();
            second.close().await.unwrap();

            let first = Provider::new_browser_provider_with_mail(
                first_config,
                storage_name.clone(),
                BrowserMailOptions::default(),
                Some(first_notifications.function()),
            )
            .await
            .unwrap();
            first.poll_mail_for_test().await.unwrap();
            assert_single_message(&first, &identifier).await;
            first_notifications.assert_empty();
            second_notifications.assert_empty();
            assert_eq!(filed_records(&storage_name).await, filed_before_resend);
            first.close().await.unwrap();
        },
    )
    .await;
}

/// Law: an embedder callback that throws cannot prevent a filed mail from being remembered.
#[wasm_bindgen_test]
async fn test_mail_throwing_callback_preserves_filing_and_deduplication() {
    with_hang_guard(
        "test_mail_throwing_callback_preserves_filing_and_deduplication",
        TEST_HANG_GUARD,
        async {
            let config = configuration(&SecretKey::random());
            let recipient = recipient_of(&config);
            let storage_name = storage_name();
            let identifier = seed_pending_mail(config.clone(), storage_name.clone()).await;
            let notifications = Array::new();
            let callback = Function::new_with_args(
                "id",
                "this.push(id); throw new Error('mail callback failed');",
            )
            .bind0(&notifications);
            let provider = Provider::new_browser_provider_with_mail(
                config,
                storage_name.clone(),
                BrowserMailOptions::default(),
                Some(callback),
            )
            .await
            .unwrap();
            provider.poll_mail_for_test().await.unwrap();
            assert_single_message(&provider, &identifier).await;
            assert_eq!(notifications.length(), 1);
            assert_eq!(
                notifications.get(0).as_string().as_deref(),
                Some(identifier.as_str())
            );
            let filed_before_resend = filed_records(&storage_name).await;
            assert_eq!(filed_before_resend.len(), 1);
            gateway(&provider)
                .deliver(&recipient, MESSAGE)
                .await
                .unwrap();
            provider.poll_mail_for_test().await.unwrap();
            assert_single_message(&provider, &identifier).await;
            assert_eq!(notifications.length(), 1);
            assert_eq!(filed_records(&storage_name).await, filed_before_resend);
            provider.close().await.unwrap();
        },
    )
    .await;
}

/// Open a recipient with small explicit budgets, exercising the provider's retained-storage
/// law without filling its production capacity with thousands of messages.
async fn bounded_recipient(
    provider: &Provider,
    storage_name: &str,
    inbox_rows: u32,
    record_rows: u32,
) -> RetainedRecipient {
    let inbox = IdbStorage::new_with_cap_name_and_authority(
        inbox_rows,
        &format!("{storage_name}/mail-inbox"),
        RecordAuthority::Retained,
    )
    .await
    .unwrap();
    let records = IdbStorage::new_with_cap_name_and_authority(
        record_rows,
        &format!("{storage_name}/mail-records"),
        RecordAuthority::Retained,
    )
    .await
    .unwrap();
    Recipient::start(
        provider.mail_processor_for_test(),
        KvInbox::new(inbox),
        records,
        DEFAULT_MAIL_POLL_INTERVAL,
    )
    .unwrap()
}

/// Snapshot every filed message, including its timestamp, so a rewrite is observable.
async fn retained_messages(recipient: &RetainedRecipient) -> BTreeMap<String, StoredMail> {
    recipient
        .inbox()
        .store()
        .get_all()
        .await
        .unwrap()
        .into_iter()
        .collect()
}

/// Law: a full inbox fails its poll without eviction, and the pending mail is retried once
/// the embedder removes a filed message to make room.
#[wasm_bindgen_test]
async fn test_mail_full_inbox_preserves_filed_mail_and_retries_pending_mail() {
    with_hang_guard(
        "test_mail_full_inbox_preserves_filed_mail_and_retries_pending_mail",
        TEST_HANG_GUARD,
        async {
            let config = configuration(&SecretKey::random());
            let target = recipient_of(&config);
            let storage_name = storage_name();
            let provider =
                Provider::new_browser_provider_with_storage(config, storage_name.clone())
                    .await
                    .unwrap();
            let recipient = bounded_recipient(&provider, &storage_name, 1, 8).await;
            let first_identifier = gateway(&provider).deliver(&target, MESSAGE).await.unwrap();
            assert_eq!(recipient.poll().await.unwrap().filed, 1);
            let before = retained_messages(&recipient).await;
            gateway(&provider)
                .deliver(&target, SECOND_MESSAGE)
                .await
                .unwrap();
            assert!(matches!(
                recipient.poll().await,
                Err(RecipientError::Inbox(
                    rings_core::error::Error::StorageBudgetExhausted { .. }
                ))
            ));
            assert_eq!(retained_messages(&recipient).await, before);
            <IdbStorage as KvStorageInterface<StoredMail>>::remove(
                recipient.inbox().store(),
                &format!("mail-{first_identifier}"),
            )
            .await
            .unwrap();
            assert_eq!(recipient.poll().await.unwrap().filed, 1);
            let after = retained_messages(&recipient).await;
            assert_eq!(after.len(), 1);
            assert_eq!(after.values().next().unwrap().message, SECOND_MESSAGE);
            drop(recipient);
            provider.close().await.unwrap();
        },
    )
    .await;
}

/// Law: a full records store fails the poll after filing without evicting its filed
/// Message-ID; repeated polls preserve the inbox row instead of filing it again.
#[wasm_bindgen_test]
async fn test_mail_full_records_preserves_filed_mail_and_deduplication() {
    with_hang_guard(
        "test_mail_full_records_preserves_filed_mail_and_deduplication",
        TEST_HANG_GUARD,
        async {
            let config = configuration(&SecretKey::random());
            let target = recipient_of(&config);
            let storage_name = storage_name();
            let provider =
                Provider::new_browser_provider_with_storage(config, storage_name.clone())
                    .await
                    .unwrap();
            let recipient = bounded_recipient(&provider, &storage_name, 4, 1).await;
            gateway(&provider).deliver(&target, MESSAGE).await.unwrap();
            assert!(matches!(
                recipient.poll().await,
                Err(RecipientError::Records(
                    rings_core::error::Error::StorageBudgetExhausted { .. }
                ))
            ));
            let before = retained_messages(&recipient).await;
            assert_eq!(before.len(), 1);
            for _ in 0..2 {
                assert!(matches!(
                    recipient.poll().await,
                    Err(RecipientError::Records(
                        rings_core::error::Error::StorageBudgetExhausted { .. }
                    ))
                ));
                assert_eq!(retained_messages(&recipient).await, before);
            }
            let records = recipient_records(&storage_name).await;
            assert_eq!(records.len(), 1);
            assert!(matches!(
                records.values().next(),
                Some(RecipientRecord::Filed { .. })
            ));
            drop(recipient);
            provider.close().await.unwrap();
        },
    )
    .await;
}