servlet 1.2.0

A small application runtime with an explicit operational contract
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
//! A live socket with stalled PostgreSQL replies must not strand pool capacity.
use super::{
    operations,
    support::{start, stop},
};
use servlet::{
    ecosystem::tokio,
    health::CheckPolicy,
    io::{self, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt},
    net::{TcpListener, TcpStream},
    sql::{PgConfig, PgLimits, PgOperations, PgReadiness, PgTls, query_scalar},
    sync::Notify,
    time::{Instant, sleep, timeout},
};
use std::{
    net::SocketAddr,
    sync::{
        Arc,
        atomic::{AtomicBool, AtomicUsize, Ordering},
    },
    time::Duration,
};
use tokio::task::JoinSet;

#[tokio::test]
#[ignore = "requires isolated PostgreSQL; python3 -B scripts/postgres_test.py"]
async fn stalled_readiness_replies_release_pool_capacity() {
    let (_proxy, config, stall) =
        loopback_proxy(|kind| matches!(kind, b'B' | b'P' | b'Q'), None).await;
    let config = config
        .with_limits(PgLimits {
            max_connections: 1,
            min_connections: 0,
            ..PgLimits::default()
        })
        .unwrap()
        .with_readiness(PgReadiness::Required(CheckPolicy {
            interval: Duration::from_millis(100),
            timeout: Duration::from_millis(500),
        }))
        .unwrap();

    let (running, pool) = start(config).await;
    let handle = running.handle();
    assert!(handle.is_ready());
    let original_pid: i32 = query_scalar("SELECT pg_backend_pid()")
        .fetch_one(&pool)
        .await
        .unwrap();
    assert_eq!(stall.accepted.load(Ordering::Relaxed), 1);

    stall.armed.store(true, Ordering::Relaxed);
    timeout(Duration::from_secs(5), async {
        while handle.is_ready() {
            sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .expect("the stalled probe should withdraw readiness");
    timeout(Duration::from_secs(5), async {
        while !handle.is_ready() {
            sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .expect("the pool should replace the interrupted connection and recover readiness");

    let replacement_pid: i32 = query_scalar("SELECT pg_backend_pid()")
        .fetch_one(&pool)
        .await
        .unwrap();
    assert_ne!(replacement_pid, original_pid);
    stop(running, pool).await;
}

#[tokio::test]
#[ignore = "requires isolated PostgreSQL; python3 -B scripts/postgres_test.py"]
async fn successful_operation_survives_recycle_timeout_and_pool_replaces_connection() {
    let (_proxy, config, stall) = loopback_proxy(|kind| kind == b'S', None).await;
    let config = config
        .with_limits(PgLimits {
            max_connections: 1,
            min_connections: 1,
            acquire_timeout: Duration::from_secs(1),
            ..PgLimits::default()
        })
        .unwrap()
        .with_readiness(PgReadiness::NotRequired)
        .unwrap();
    let (running, database, metrics) = operations::start_with_config("lookup", config).await;
    let original_pid = successful_query_with_stalled_return(&database, &stall).await;

    timeout(Duration::from_secs(3), async {
        while database.pool().num_idle() == 0 {
            sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .expect("the pool should discard the stalled return and replenish its minimum size");

    let replacement_pid: i32 = database
        .get("lookup")
        .unwrap()
        .run(Instant::now() + Duration::from_secs(2), |connection| {
            Box::pin(query_scalar("SELECT pg_backend_pid()").fetch_one(connection))
        })
        .await
        .unwrap();
    assert_ne!(replacement_pid, original_pid);
    assert_eq!(stall.accepted.load(Ordering::Relaxed), 2);
    operations::outcome(&metrics, "lookup", "ok", 2);
    operations::stop(running, database).await;
}

#[tokio::test]
#[ignore = "requires isolated PostgreSQL; python3 -B scripts/postgres_test.py"]
async fn timed_out_replacement_replenishes_minimum_without_replaying_the_operation() {
    let (_proxy, config, stall) = loopback_proxy(|kind| kind == b'S', Some(2)).await;
    let config = config
        .with_limits(PgLimits {
            max_connections: 1,
            min_connections: 1,
            acquire_timeout: Duration::from_millis(500),
            ..PgLimits::default()
        })
        .unwrap()
        .with_readiness(PgReadiness::NotRequired)
        .unwrap();
    let (running, database, metrics) = operations::start_with_config("lookup", config).await;
    let original_pid = successful_query_with_stalled_return(&database, &stall).await;

    timeout(Duration::from_secs(2), stall.replacement_started.notified())
        .await
        .expect("replenishment should open a replacement without demand from a query");
    timeout(
        Duration::from_millis(900),
        stall.replacement_closed.notified(),
    )
    .await
    .expect("the first stalled replacement should close at the acquisition deadline");
    timeout(Duration::from_secs(2), async {
        while database.pool().num_idle() == 0 {
            sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .expect("the minimum should recover after the replacement times out");

    let replacement_pid: i32 = query_scalar("SELECT pg_backend_pid()")
        .fetch_one(database.pool())
        .await
        .unwrap();
    assert_ne!(replacement_pid, original_pid);
    assert_eq!(stall.accepted.load(Ordering::Relaxed), 3);
    operations::outcome(&metrics, "lookup", "ok", 1);
    operations::stop(running, database).await;
}

#[tokio::test]
#[ignore = "requires isolated PostgreSQL; python3 -B scripts/postgres_test.py"]
async fn pool_shutdown_interrupts_a_stalled_replacement_handshake() {
    let (_proxy, config, stall) = loopback_proxy(|kind| kind == b'S', Some(2)).await;
    let config = config
        .with_limits(PgLimits {
            max_connections: 1,
            min_connections: 1,
            acquire_timeout: Duration::from_secs(2),
            ..PgLimits::default()
        })
        .unwrap()
        .with_readiness(PgReadiness::NotRequired)
        .unwrap();
    let (running, database, metrics) = operations::start_with_config("lookup", config).await;
    successful_query_with_stalled_return(&database, &stall).await;
    timeout(Duration::from_secs(4), stall.replacement_started.notified())
        .await
        .expect("replenishment should be inside the stalled handshake");

    operations::outcome(&metrics, "lookup", "ok", 1);
    operations::stop(running, database).await;
    timeout(Duration::from_secs(1), stall.replacement_closed.notified())
        .await
        .expect("pool cleanup should have released the replacement socket");
    assert_eq!(stall.accepted.load(Ordering::Relaxed), 2);
}

#[tokio::test]
#[ignore = "requires isolated PostgreSQL; python3 -B scripts/postgres_test.py"]
async fn a_healthy_idle_connection_remains_usable_during_replenishment() {
    let (_proxy, config, stall) = loopback_proxy(|_| false, Some(3)).await;
    let config = config
        .with_limits(PgLimits {
            max_connections: 2,
            min_connections: 2,
            acquire_timeout: Duration::from_secs(2),
            ..PgLimits::default()
        })
        .unwrap()
        .with_readiness(PgReadiness::NotRequired)
        .unwrap();
    let (running, pool) = start(config).await;
    timeout(Duration::from_secs(1), async {
        while pool.num_idle() != 2 {
            sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();
    drop(pool.try_acquire().unwrap().detach());
    timeout(Duration::from_secs(2), stall.replacement_started.notified())
        .await
        .expect("retiring a connection should trigger replenishment");

    let value: i32 = timeout(
        Duration::from_millis(500),
        query_scalar("SELECT 42").fetch_one(&pool),
    )
    .await
    .expect("a stalled replacement should not hold the remaining connection")
    .unwrap();
    assert_eq!(value, 42);
    stop(running, pool).await;
    timeout(Duration::from_secs(1), stall.replacement_closed.notified())
        .await
        .expect("pool cleanup should have released the replacement socket");
}

#[tokio::test]
#[ignore = "requires isolated PostgreSQL; python3 -B scripts/postgres_test.py"]
async fn pool_shutdown_interrupts_stalled_return_before_recycle_timeout() {
    let (_proxy, config, stall) = loopback_proxy(|kind| kind == b'S', None).await;
    let config = config
        .with_limits(PgLimits {
            max_connections: 1,
            min_connections: 0,
            acquire_timeout: Duration::from_secs(10),
            ..PgLimits::default()
        })
        .unwrap()
        .with_readiness(PgReadiness::NotRequired)
        .unwrap();
    let (running, database, metrics) = operations::start_with_config("lookup", config).await;
    successful_query_with_stalled_return(&database, &stall).await;
    operations::outcome(&metrics, "lookup", "ok", 1);
    operations::stop(running, database).await;
}

async fn successful_query_with_stalled_return(
    database: &PgOperations,
    stall: &Arc<ReplyStall>,
) -> i32 {
    let callback_stall = stall.clone();
    let pid = database
        .get("lookup")
        .unwrap()
        .run(Instant::now() + Duration::from_secs(2), move |connection| {
            Box::pin(async move {
                let pid: i32 = query_scalar("SELECT pg_backend_pid()")
                    .fetch_one(connection)
                    .await?;
                // The query completed. SQLx's separate return ping sends the next Sync.
                assert_eq!(callback_stall.accepted.load(Ordering::Relaxed), 1);
                callback_stall.armed.store(true, Ordering::Relaxed);
                Ok(pid)
            })
        })
        .await
        .unwrap();
    timeout(Duration::from_secs(2), stall.withheld.notified())
        .await
        .expect("the return ping should reach the local relay after the query succeeds");
    assert!(pid > 0);
    pid
}

#[derive(Default)]
struct ReplyStall {
    armed: AtomicBool,
    accepted: AtomicUsize,
    withheld: Notify,
    replacement_started: Notify,
    replacement_closed: Notify,
}

async fn loopback_proxy(
    stall_on: fn(u8) -> bool,
    stall_handshake: Option<usize>,
) -> (JoinSet<()>, PgConfig, Arc<ReplyStall>) {
    let mut url = url::Url::parse(&std::env::var("SERVLET_TEST_PG_URL").unwrap()).unwrap();
    let upstream = SocketAddr::new(
        url.host_str().unwrap().parse().unwrap(),
        url.port().unwrap(),
    );
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    url.set_port(Some(listener.local_addr().unwrap().port()))
        .unwrap();

    let config = PgConfig::new(url.as_str(), "postgres-stall")
        .unwrap()
        .with_tls(PgTls::PlaintextLoopback)
        .unwrap();
    let stall = Arc::new(ReplyStall::default());
    let mut proxy = JoinSet::new();
    proxy.spawn(serve(
        listener,
        upstream,
        stall_on,
        stall_handshake,
        stall.clone(),
    ));
    (proxy, config, stall)
}

async fn serve(
    listener: TcpListener,
    upstream: SocketAddr,
    stall_on: fn(u8) -> bool,
    stall_handshake: Option<usize>,
    stall: Arc<ReplyStall>,
) {
    let mut tunnels = JoinSet::new();
    loop {
        tokio::select! {
            result = listener.accept() => {
                let (mut client, _) = result.unwrap();
                let index = stall.accepted.fetch_add(1, Ordering::Relaxed) + 1;
                let stall = stall.clone();
                tunnels.spawn(async move {
                    if stall_handshake == Some(index) {
                        return stall_replacement_handshake(client, stall).await;
                    }
                    let mut server = TcpStream::connect(upstream).await?;
                    client.set_nodelay(true)?;
                    server.set_nodelay(true)?;
                    if index == 1 {
                        stall_first_connection(client, server, stall_on, stall).await
                    } else {
                        io::copy_bidirectional(&mut client, &mut server).await?;
                        Ok(())
                    }
                });
            }
            _ = tunnels.join_next(), if !tunnels.is_empty() => {}
        }
    }
}

async fn stall_replacement_handshake(
    mut client: TcpStream,
    stall: Arc<ReplyStall>,
) -> io::Result<()> {
    // Read the whole startup packet but never reply. The next socket reaches PostgreSQL.
    forward_packet(&mut client, &mut io::sink()).await?;
    stall.replacement_started.notify_one();
    io::copy(&mut client, &mut io::sink()).await?;
    stall.replacement_closed.notify_one();
    Ok(())
}

async fn stall_first_connection(
    mut client: TcpStream,
    mut server: TcpStream,
    stall_on: fn(u8) -> bool,
    stall: Arc<ReplyStall>,
) -> io::Result<()> {
    let (mut client_read, mut client_write) = client.split();
    let (mut server_read, mut server_write) = server.split();
    let stalled = AtomicBool::new(false);
    let requests = async {
        // The startup packet has only a length prefix. Later messages also have a type byte.
        forward_packet(&mut client_read, &mut server_write).await?;
        loop {
            let kind = client_read.read_u8().await?;
            if stall_on(kind)
                && stall.armed.load(Ordering::Relaxed)
                && !stalled.swap(true, Ordering::Relaxed)
            {
                stall.withheld.notify_one();
            }
            server_write.write_u8(kind).await?;
            forward_packet(&mut client_read, &mut server_write).await?;
        }
    };
    let replies = async {
        let mut bytes = [0; 8192];
        loop {
            let count = server_read.read(&mut bytes).await?;
            if count == 0 {
                return Ok(());
            }
            // Keep the TCP connection open while discarding replies.
            if !stalled.load(Ordering::Relaxed) {
                client_write.write_all(&bytes[..count]).await?;
            }
        }
    };
    tokio::select! {
        result = requests => result,
        result = replies => result,
    }
}

async fn forward_packet(
    read: &mut (impl AsyncRead + Unpin),
    write: &mut (impl AsyncWrite + Unpin),
) -> io::Result<()> {
    let length = read.read_u32().await?;
    write.write_u32(length).await?;
    io::copy(&mut read.take(u64::from(length) - 4), write).await?;
    Ok(())
}