freenet 0.2.43

Freenet core software
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
//! Tests for the Op Request Mediator crash and recovery scenarios.
//!
//! These tests verify:
//! - Graceful handling of executor drops
//! - Stale request cleanup
//! - Channel closure behavior
//! - Capacity limits and backpressure

use crate::config::GlobalExecutor;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::Duration;

use tokio::sync::{mpsc, oneshot};
use tokio::time::timeout;

use crate::contract::executor::{OpRequestError, OpRequestReceiver, OpRequestSender};
use crate::message::Transaction;
use crate::operations::OpEnum;
use crate::operations::get::GetMsg;

// =============================================================================
// Test Helper: Simplified Mediator for Unit Testing
// =============================================================================

/// A simplified mediator that mirrors the real mediator's core behavior.
/// Used for testing without requiring the full event loop infrastructure.
struct TestMediator {
    op_request_rx: OpRequestReceiver,
    to_event_loop_tx: mpsc::Sender<Transaction>,
    from_event_loop_rx: mpsc::Receiver<OpEnum>,
    pending:
        std::collections::HashMap<Transaction, oneshot::Sender<Result<OpEnum, OpRequestError>>>,
    max_pending: usize,
}

impl TestMediator {
    fn new(
        op_request_rx: OpRequestReceiver,
        to_event_loop_tx: mpsc::Sender<Transaction>,
        from_event_loop_rx: mpsc::Receiver<OpEnum>,
    ) -> Self {
        Self {
            op_request_rx,
            to_event_loop_tx,
            from_event_loop_rx,
            pending: std::collections::HashMap::new(),
            max_pending: 100, // Lower limit for testing
        }
    }

    async fn process_one_request(&mut self) -> bool {
        tokio::select! {
            Some((tx, response_tx)) = self.op_request_rx.recv() => {
                // Check capacity
                if self.pending.len() >= self.max_pending {
                    drop(response_tx.send(Err(OpRequestError::Failed(
                        "mediator at capacity".to_string()
                    ))));
                    return true;
                }

                // Store pending and forward to event loop
                self.pending.insert(tx, response_tx);
                if self.to_event_loop_tx.send(tx).await.is_err() {
                    if let Some(pending) = self.pending.remove(&tx) {
                        drop(pending.send(Err(OpRequestError::ChannelClosed)));
                    }
                }
                true
            }
            Some(op_result) = self.from_event_loop_rx.recv() => {
                let tx = *op_result.id();
                if let Some(pending) = self.pending.remove(&tx) {
                    drop(pending.send(Ok(op_result)));
                }
                true
            }
            else => false
        }
    }

    fn pending_count(&self) -> usize {
        self.pending.len()
    }
}

// =============================================================================
// Channel Creation Helper
// =============================================================================

fn create_test_channels() -> (
    OpRequestSender,
    OpRequestReceiver,
    mpsc::Sender<Transaction>,
    mpsc::Receiver<Transaction>,
    mpsc::Sender<OpEnum>,
    mpsc::Receiver<OpEnum>,
) {
    let (op_tx, op_rx) = mpsc::channel(100);
    let (to_el_tx, to_el_rx) = mpsc::channel(100);
    let (from_el_tx, from_el_rx) = mpsc::channel(100);
    (op_tx, op_rx, to_el_tx, to_el_rx, from_el_tx, from_el_rx)
}

// =============================================================================
// Executor Drop Recovery Tests
// =============================================================================

#[tokio::test]
async fn test_executor_drops_before_response() {
    let (op_tx, op_rx, to_el_tx, _to_el_rx, _from_el_tx, from_el_rx) = create_test_channels();
    let mut mediator = TestMediator::new(op_rx, to_el_tx, from_el_rx);

    let tx = Transaction::new::<GetMsg>();

    // Send request but drop the response receiver immediately
    let (response_tx, response_rx) = oneshot::channel();
    op_tx.send((tx, response_tx)).await.unwrap();
    drop(response_rx); // Simulate executor dropping before response

    // Mediator should process the request without panicking
    mediator.process_one_request().await;
    assert_eq!(mediator.pending_count(), 1);
}

#[tokio::test]
async fn test_multiple_executors_drop_independently() {
    let (op_tx, op_rx, to_el_tx, _to_el_rx, _from_el_tx, from_el_rx) = create_test_channels();
    let mut mediator = TestMediator::new(op_rx, to_el_tx, from_el_rx);

    let dropped = Arc::new(AtomicU32::new(0));

    // Send multiple requests, some will be dropped
    for i in 0..5 {
        let tx = Transaction::new::<GetMsg>();
        let (response_tx, response_rx) = oneshot::channel();
        op_tx.send((tx, response_tx)).await.unwrap();

        // Drop odd-numbered requests
        if i % 2 == 1 {
            drop(response_rx);
            dropped.fetch_add(1, Ordering::SeqCst);
        } else {
            // Keep even ones alive briefly then drop
            GlobalExecutor::spawn(async move {
                tokio::time::sleep(Duration::from_millis(100)).await;
                drop(response_rx);
            });
        }
    }

    // Process all requests
    for _ in 0..5 {
        mediator.process_one_request().await;
    }

    // All should be pending (mediator doesn't know about drops until it tries to respond)
    assert_eq!(mediator.pending_count(), 5);
}

// =============================================================================
// Stale Request Cleanup Tests
// =============================================================================

#[tokio::test]
async fn test_stale_requests_identified() {
    use std::time::Instant;

    let mut pending: std::collections::HashMap<
        Transaction,
        (oneshot::Sender<Result<OpEnum, OpRequestError>>, Instant),
    > = std::collections::HashMap::new();

    // Add some requests with different ages
    for i in 0..5 {
        let tx = Transaction::new::<GetMsg>();
        let (response_tx, _response_rx) = oneshot::channel();

        // Simulate different creation times
        let created_at = Instant::now() - Duration::from_secs(i * 60);
        pending.insert(tx, (response_tx, created_at));
    }

    // Find stale requests (older than 2 minutes)
    let threshold = Duration::from_secs(120);
    let stale: Vec<_> = pending
        .iter()
        .filter(|(_, (_, created))| created.elapsed() > threshold)
        .map(|(tx, _)| *tx)
        .collect();

    // Requests 2, 3, 4 should be stale (120s, 180s, 240s old)
    assert_eq!(stale.len(), 3);
}

#[tokio::test]
async fn test_stale_cleanup_notifies_waiters() {
    let (response_tx, response_rx) = oneshot::channel::<Result<OpEnum, OpRequestError>>();

    // Simulate stale cleanup notification
    drop(response_tx.send(Err(OpRequestError::Failed(
        "request exceeded stale threshold".to_string(),
    ))));

    // Waiter should receive the error
    let result = response_rx.await.unwrap();
    assert!(matches!(result, Err(OpRequestError::Failed(msg)) if msg.contains("stale")));
}

// =============================================================================
// Channel Closure Tests
// =============================================================================

#[tokio::test]
async fn test_event_loop_channel_closes() {
    let (op_tx, op_rx, to_el_tx, _to_el_rx, _from_el_tx, from_el_rx) = create_test_channels();

    // Drop the event loop receiver to simulate event loop crash
    drop(_to_el_rx);

    let mut mediator = TestMediator::new(op_rx, to_el_tx, from_el_rx);

    let tx = Transaction::new::<GetMsg>();
    let (response_tx, response_rx) = oneshot::channel();
    op_tx.send((tx, response_tx)).await.unwrap();

    // Process request - should fail to forward
    mediator.process_one_request().await;

    // Waiter should receive channel closed error
    let result = timeout(Duration::from_millis(100), response_rx).await;
    assert!(result.is_ok());
    let response = result.unwrap().unwrap();
    assert!(matches!(response, Err(OpRequestError::ChannelClosed)));
}

#[tokio::test]
async fn test_all_senders_dropped_mediator_exits() {
    let (op_tx, op_rx, to_el_tx, _to_el_rx, _from_el_tx, from_el_rx) = create_test_channels();
    let mut mediator = TestMediator::new(op_rx, to_el_tx, from_el_rx);

    // Drop all senders
    drop(op_tx);
    drop(_from_el_tx);

    // Mediator should detect closure and return false
    let still_running = mediator.process_one_request().await;
    assert!(!still_running);
}

// =============================================================================
// Capacity and Backpressure Tests
// =============================================================================

#[tokio::test]
async fn test_mediator_rejects_at_capacity() {
    let (op_tx, op_rx, to_el_tx, _to_el_rx, _from_el_tx, from_el_rx) = create_test_channels();
    let mut mediator = TestMediator::new(op_rx, to_el_tx, from_el_rx);
    mediator.max_pending = 5; // Low limit for testing

    // Fill up to capacity
    let mut receivers = Vec::new();
    for _ in 0..5 {
        let tx = Transaction::new::<GetMsg>();
        let (response_tx, response_rx) = oneshot::channel();
        op_tx.send((tx, response_tx)).await.unwrap();
        receivers.push(response_rx);
        mediator.process_one_request().await;
    }

    assert_eq!(mediator.pending_count(), 5);

    // Next request should be rejected
    let tx = Transaction::new::<GetMsg>();
    let (response_tx, response_rx) = oneshot::channel();
    op_tx.send((tx, response_tx)).await.unwrap();
    mediator.process_one_request().await;

    // Check that over-capacity request was rejected
    let result = timeout(Duration::from_millis(100), response_rx).await;
    assert!(result.is_ok());
    let response = result.unwrap().unwrap();
    assert!(matches!(response, Err(OpRequestError::Failed(msg)) if msg.contains("capacity")));

    // Pending count should still be 5 (rejected request not added)
    assert_eq!(mediator.pending_count(), 5);
}

#[tokio::test]
async fn test_capacity_recovers_after_responses() {
    let (op_tx, op_rx, to_el_tx, to_el_rx, _from_el_tx, from_el_rx) = create_test_channels();
    let mut mediator = TestMediator::new(op_rx, to_el_tx, from_el_rx);
    mediator.max_pending = 3;

    // Fill to capacity
    let mut transactions = Vec::new();
    for _ in 0..3 {
        let tx = Transaction::new::<GetMsg>();
        let (response_tx, _response_rx) = oneshot::channel();
        op_tx.send((tx, response_tx)).await.unwrap();
        transactions.push(tx);
        mediator.process_one_request().await;
    }

    assert_eq!(mediator.pending_count(), 3);

    // Simulate event loop responses for 2 requests
    // In the real mediator, we'd need to create proper OpEnum responses
    // For this test, we verify the pending count decreases

    // Drop event loop receiver to prevent blocking
    drop(to_el_rx);

    // Verify mediator was at capacity
    assert_eq!(mediator.pending_count(), 3);
}

// =============================================================================
// Response Routing Tests
// =============================================================================

#[tokio::test]
async fn test_response_routed_to_correct_executor() {
    // This test verifies that responses are correctly matched to their requests
    let mut pending: std::collections::HashMap<
        Transaction,
        oneshot::Sender<Result<OpEnum, OpRequestError>>,
    > = std::collections::HashMap::new();

    // Create 3 pending requests
    let mut receivers = Vec::new();
    let mut transactions = Vec::new();
    for _ in 0..3 {
        let tx = Transaction::new::<GetMsg>();
        let (response_tx, response_rx) = oneshot::channel();
        pending.insert(tx, response_tx);
        receivers.push(response_rx);
        transactions.push(tx);
    }

    // "Respond" to the middle one
    let target_tx = transactions[1];
    if let Some(sender) = pending.remove(&target_tx) {
        drop(sender.send(Err(OpRequestError::Failed("test response".to_string()))));
    }

    // Only middle receiver should have a response
    for (i, rx) in receivers.into_iter().enumerate() {
        let result = timeout(Duration::from_millis(10), rx).await;
        if i == 1 {
            assert!(result.is_ok(), "Middle request should have response");
        } else {
            assert!(result.is_err(), "Other requests should timeout");
        }
    }
}

#[tokio::test]
async fn test_unknown_response_handled_gracefully() {
    let (op_tx, op_rx, to_el_tx, _to_el_rx, _from_el_tx, from_el_rx) = create_test_channels();
    let mut mediator = TestMediator::new(op_rx, to_el_tx, from_el_rx);

    // Send a response for a transaction that was never registered
    // This simulates a race condition where the executor timed out before the response arrived
    let unknown_tx = Transaction::new::<GetMsg>();

    // We can't easily create a fake OpEnum, but we can verify the mediator
    // handles the case where pending.remove returns None

    // First, register a real request
    let real_tx = Transaction::new::<GetMsg>();
    let (response_tx, _response_rx) = oneshot::channel();
    op_tx.send((real_tx, response_tx)).await.unwrap();
    mediator.process_one_request().await;

    // Verify unknown transaction is not in pending
    assert!(!mediator.pending.contains_key(&unknown_tx));

    // The real implementation logs a warning for unknown transactions
    // but doesn't panic or crash
}

// =============================================================================
// Timeout Behavior Tests
// =============================================================================

#[tokio::test]
async fn test_executor_timeout_handling() {
    let (op_tx, op_rx, to_el_tx, _to_el_rx, _from_el_tx, from_el_rx) = create_test_channels();
    let mut mediator = TestMediator::new(op_rx, to_el_tx, from_el_rx);

    let tx = Transaction::new::<GetMsg>();
    let (response_tx, response_rx) = oneshot::channel();
    op_tx.send((tx, response_tx)).await.unwrap();
    mediator.process_one_request().await;

    // Executor times out waiting for response
    let result = timeout(Duration::from_millis(50), response_rx).await;
    assert!(result.is_err(), "Should timeout waiting for response");

    // Request is still pending in mediator
    assert_eq!(mediator.pending_count(), 1);

    // Mediator doesn't know about timeout until cleanup runs
}

#[tokio::test]
async fn test_concurrent_requests_independent_timeouts() {
    let (op_tx, op_rx, to_el_tx, _to_el_rx, _from_el_tx, from_el_rx) = create_test_channels();
    let mut mediator = TestMediator::new(op_rx, to_el_tx, from_el_rx);

    // Send multiple requests
    let mut receivers = Vec::new();
    for _ in 0..5 {
        let tx = Transaction::new::<GetMsg>();
        let (response_tx, response_rx) = oneshot::channel();
        op_tx.send((tx, response_tx)).await.unwrap();
        receivers.push(response_rx);
        mediator.process_one_request().await;
    }

    // All should timeout independently
    for rx in receivers {
        let result = timeout(Duration::from_millis(10), rx).await;
        assert!(result.is_err(), "Each request should timeout independently");
    }

    // All still pending
    assert_eq!(mediator.pending_count(), 5);
}