mongodb 3.6.0

The official MongoDB driver for Rust
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
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
mod causal_consistency;

use std::{future::Future, sync::Arc, time::Duration};

use crate::bson::Document;
use futures::stream::StreamExt;

use crate::{
    bson::{doc, Bson},
    coll::options::CountOptions,
    error::Result,
    event::sdam::SdamEvent,
    options::{FindOptions, ReadConcern, ReadPreference, WriteConcern},
    sdam::ServerInfo,
    selection_criteria::SelectionCriteria,
    test::{
        get_client_options,
        get_primary,
        log_uncaptured,
        topology_is_standalone,
        util::event_buffer::EventBuffer,
        Event,
        EventClient,
    },
    Client,
    Collection,
};

/// Macro defining a closure that returns a future populated by an operation on the
/// provided client identifier.
macro_rules! client_op {
    ($client:ident, $body:expr) => {
        |$client| async move {
            $body.await.unwrap();
        }
    };
}

/// Macro defining a closure that returns a future populated by an operation on the
/// provided database identifier.
macro_rules! db_op {
    ($test_name:expr, $db:ident, $body:expr) => {
        |client| async move {
            let $db = client.database($test_name);
            $body.await.unwrap();
        }
    };
}

/// Macro defining a closure that returns a future populated by an operation on the
/// provided collection identifier.
macro_rules! collection_op {
    ($test_name:expr, $coll:ident, $body:expr) => {
        |client| async move {
            let $coll = client
                .database($test_name)
                .collection::<crate::bson::Document>($test_name);
            $body.await.unwrap();
        }
    };
}

/// Macro that runs the provided function with each operation that uses a session.
macro_rules! for_each_op {
    ($test_name:expr, $test_func:ident) => {{
        // collection operations
        $test_func(
            "insert",
            collection_op!($test_name, coll, coll.insert_one(doc! { "x": 1 })),
        )
        .await;
        $test_func(
            "insert",
            collection_op!($test_name, coll, coll.insert_many(vec![doc! { "x": 1 }])),
        )
        .await;
        $test_func(
            "update",
            collection_op!(
                $test_name,
                coll,
                coll.replace_one(doc! { "x": 1 }, doc! { "x": 2 })
            ),
        )
        .await;
        $test_func(
            "update",
            collection_op!(
                $test_name,
                coll,
                coll.update_one(doc! {}, doc! { "$inc": {"x": 5 } })
            ),
        )
        .await;
        $test_func(
            "update",
            collection_op!(
                $test_name,
                coll,
                coll.update_many(doc! {}, doc! { "$inc": {"x": 5 } })
            ),
        )
        .await;
        $test_func(
            "delete",
            collection_op!($test_name, coll, coll.delete_one(doc! { "x": 1 })),
        )
        .await;
        $test_func(
            "delete",
            collection_op!($test_name, coll, coll.delete_many(doc! { "x": 1 })),
        )
        .await;
        $test_func(
            "findAndModify",
            collection_op!($test_name, coll, coll.find_one_and_delete(doc! { "x": 1 })),
        )
        .await;
        $test_func(
            "findAndModify",
            collection_op!(
                $test_name,
                coll,
                coll.find_one_and_update(doc! {}, doc! { "$inc": { "x": 1 } })
            ),
        )
        .await;
        $test_func(
            "findAndModify",
            collection_op!(
                $test_name,
                coll,
                coll.find_one_and_replace(doc! {}, doc! {"x": 1})
            ),
        )
        .await;
        $test_func(
            "aggregate",
            collection_op!(
                $test_name,
                coll,
                coll.aggregate(vec![doc! { "$match": { "x": 1 } }])
            ),
        )
        .await;
        $test_func(
            "find",
            collection_op!($test_name, coll, coll.find(doc! { "x": 1 })),
        )
        .await;
        $test_func(
            "find",
            collection_op!($test_name, coll, coll.find_one(doc! { "x": 1 })),
        )
        .await;
        $test_func(
            "distinct",
            collection_op!($test_name, coll, coll.distinct("x", doc! {})),
        )
        .await;
        $test_func(
            "aggregate",
            collection_op!($test_name, coll, coll.count_documents(doc! {})),
        )
        .await;
        $test_func("drop", collection_op!($test_name, coll, coll.drop())).await;

        // db operations
        $test_func(
            "listCollections",
            db_op!($test_name, db, db.list_collections()),
        )
        .await;
        $test_func(
            "ping",
            db_op!($test_name, db, db.run_command(doc! { "ping":  1 })),
        )
        .await;
        $test_func(
            "create",
            db_op!($test_name, db, db.create_collection("sessionopcoll")),
        )
        .await;
        $test_func("dropDatabase", db_op!($test_name, db, db.drop())).await;

        // client operations
        $test_func("listDatabases", client_op!(client, client.list_databases())).await;
        $test_func(
            "listDatabases",
            client_op!(client, client.list_database_names()),
        )
        .await;
    }};
}

/// Prose test 1 from sessions spec.
/// This test also satisifies the `endSession` testing requirement of prose test 5.
#[tokio::test]
async fn pool_is_lifo() {
    if topology_is_standalone().await {
        return;
    }

    let client = Client::for_test().await;
    // Wait for the implicit sessions created in TestClient::new to be returned to the pool.
    tokio::time::sleep(Duration::from_millis(500)).await;

    let a = client.start_session().await.unwrap();
    let b = client.start_session().await.unwrap();

    let a_id = a.id().clone();
    let b_id = b.id().clone();

    // End both sessions, waiting after each to ensure the background task got scheduled
    // in the Drop impls.
    drop(a);
    tokio::time::sleep(Duration::from_millis(250)).await;

    drop(b);
    tokio::time::sleep(Duration::from_millis(250)).await;

    let s1 = client.start_session().await.unwrap();
    assert_eq!(s1.id(), &b_id);

    let s2 = client.start_session().await.unwrap();
    assert_eq!(s2.id(), &a_id);
}

/// Prose test 2 from sessions spec.
#[tokio::test]
#[function_name::named]
async fn cluster_time_in_commands() {
    if topology_is_standalone().await {
        log_uncaptured("skipping cluster_time_in_commands test due to standalone topology");
        return;
    }

    async fn cluster_time_test<F, G, R>(
        command_name: &str,
        client: &Client,
        event_buffer: &EventBuffer,
        operation: F,
    ) where
        F: Fn(Client) -> G,
        G: Future<Output = Result<R>>,
    {
        let mut event_stream = event_buffer.stream();

        operation(client.clone())
            .await
            .expect("operation should succeed");

        operation(client.clone())
            .await
            .expect("operation should succeed");

        let (first_command_started, first_command_succeeded) = event_stream
            .next_successful_command_execution(Duration::from_secs(5), command_name)
            .await
            .unwrap_or_else(|| {
                panic!("did not see command started and succeeded events for {command_name}")
            });

        assert!(first_command_started.command.get("$clusterTime").is_some());
        let response_cluster_time = first_command_succeeded
            .reply
            .get("$clusterTime")
            .expect("should get cluster time from command response");

        let (second_command_started, _) = event_stream
            .next_successful_command_execution(Duration::from_secs(5), command_name)
            .await
            .unwrap_or_else(|| {
                panic!("did not see command started and succeeded events for {command_name}")
            });

        assert_eq!(
            response_cluster_time,
            second_command_started
                .command
                .get("$clusterTime")
                .expect("second command should contain cluster time"),
            "cluster time not equal for {command_name}"
        );
    }

    let buffer = EventBuffer::new();
    let mut options = get_client_options().await.clone();
    options.heartbeat_freq = Some(Duration::from_secs(1000));
    options.command_event_handler = Some(buffer.handler());
    options.sdam_event_handler = Some(buffer.handler());

    // Ensure we only connect to one server so the monitor checks from other servers
    // don't affect the TopologyDescription's clusterTime value between commands.
    if options.load_balanced != Some(true) {
        options.direct_connection = Some(true);

        // Since we need to run an insert below, ensure the single host is a primary
        // if we're connected to a replica set.
        if let Some(primary) = get_primary().await {
            options.hosts = vec![primary];
        } else {
            options.hosts.drain(1..);
        }
    }

    let mut event_stream = buffer.stream();

    let client = Client::with_options(options).unwrap();

    // Wait for initial monitor check to complete and discover the server.
    event_stream
        .next_match(Duration::from_secs(5), |event| match event {
            Event::Sdam(SdamEvent::ServerDescriptionChanged(e)) => {
                !e.previous_description.server_type().is_available()
                    && e.new_description.server_type().is_available()
            }
            _ => false,
        })
        .await
        .expect("server should be discovered");

    // LoadBalanced topologies don't have monitors, so the client needs to get a clusterTime from
    // a command invocation.
    client
        .database("admin")
        .run_command(doc! { "ping": 1 })
        .await
        .unwrap();

    cluster_time_test("ping", &client, &buffer, |client| async move {
        client
            .database(function_name!())
            .run_command(doc! { "ping": 1 })
            .await
    })
    .await;

    cluster_time_test("aggregate", &client, &buffer, |client| async move {
        client
            .database(function_name!())
            .collection::<Document>(function_name!())
            .aggregate(vec![doc! { "$match": { "x": 1 } }])
            .await
    })
    .await;

    cluster_time_test("find", &client, &buffer, |client| async move {
        client
            .database(function_name!())
            .collection::<Document>(function_name!())
            .find(doc! {})
            .await
    })
    .await;

    cluster_time_test("insert", &client, &buffer, |client| async move {
        client
            .database(function_name!())
            .collection::<Document>(function_name!())
            .insert_one(doc! {})
            .await
    })
    .await;
}

/// Prose test 3 from sessions spec.
#[tokio::test]
#[function_name::named]
async fn session_usage() {
    if topology_is_standalone().await {
        return;
    }

    async fn session_usage_test<F, G>(command_name: &str, operation: F)
    where
        F: Fn(EventClient) -> G,
        G: Future<Output = ()>,
    {
        let client = Client::for_test().monitor_events().await;
        operation(client.clone()).await;
        let (command_started, _) = client.events.get_successful_command_execution(command_name);
        assert!(
            command_started.command.get("lsid").is_some(),
            "implicit session not passed to {command_name}"
        );
    }

    for_each_op!(function_name!(), session_usage_test)
}

/// Prose test 7 from sessions spec.
#[tokio::test]
#[function_name::named]
async fn implicit_session_returned_after_immediate_exhaust() {
    if topology_is_standalone().await {
        return;
    }

    let client = Client::for_test().monitor_events().await;

    let coll = client
        .init_db_and_coll(function_name!(), function_name!())
        .await;
    coll.insert_many(vec![doc! {}, doc! {}])
        .await
        .expect("insert should succeed");

    // wait for sessions to be returned to the pool and clear them out.
    tokio::time::sleep(Duration::from_millis(250)).await;
    client.clear_session_pool().await;

    let mut cursor = coll.find(doc! {}).await.expect("find should succeed");
    assert!(matches!(cursor.next().await, Some(Ok(_))));

    let (find_started, _) = client.events.get_successful_command_execution("find");
    let session_id = find_started
        .command
        .get("lsid")
        .expect("find should use implicit session")
        .as_document()
        .expect("session id should be a document");

    tokio::time::sleep(Duration::from_millis(250)).await;
    assert!(
        client.is_session_checked_in(session_id).await,
        "session not checked back in"
    );

    assert!(matches!(cursor.next().await, Some(Ok(_))));
}

/// Prose test 8 from sessions spec.
#[tokio::test]
#[function_name::named]
async fn implicit_session_returned_after_exhaust_by_get_more() {
    if topology_is_standalone().await {
        return;
    }

    let client = Client::for_test().monitor_events().await;
    let coll = client
        .init_db_and_coll(function_name!(), function_name!())
        .await;
    for _ in 0..5 {
        coll.insert_one(doc! {})
            .await
            .expect("insert should succeed");
    }

    // wait for sessions to be returned to the pool and clear them out.
    tokio::time::sleep(Duration::from_millis(250)).await;
    client.clear_session_pool().await;

    let mut cursor = coll
        .find(doc! {})
        .batch_size(3)
        .await
        .expect("find should succeed");

    for _ in 0..4 {
        assert!(matches!(cursor.next().await, Some(Ok(_))));
    }

    let (find_started, _) = client.events.get_successful_command_execution("find");

    let session_id = find_started
        .command
        .get("lsid")
        .expect("find should use implicit session")
        .as_document()
        .expect("session id should be a document");

    tokio::time::sleep(Duration::from_millis(250)).await;
    assert!(
        client.is_session_checked_in(session_id).await,
        "session not checked back in"
    );

    assert!(matches!(cursor.next().await, Some(Ok(_))));
}

/// Prose test 10 from sessions spec.
#[tokio::test]
#[function_name::named]
async fn find_and_getmore_share_session() {
    if topology_is_standalone().await {
        log_uncaptured(
            "skipping find_and_getmore_share_session due to unsupported topology: Standalone",
        );
        return;
    }

    let client = Client::for_test().monitor_events().await;

    let coll = client
        .init_db_and_coll(function_name!(), function_name!())
        .await;

    coll.insert_many(vec![doc! {}; 3])
        .write_concern(WriteConcern::majority())
        .await
        .unwrap();

    let read_preferences: Vec<ReadPreference> = vec![
        ReadPreference::Primary,
        ReadPreference::PrimaryPreferred {
            options: Default::default(),
        },
        ReadPreference::Secondary {
            options: Default::default(),
        },
        ReadPreference::SecondaryPreferred {
            options: Default::default(),
        },
        ReadPreference::Nearest {
            options: Default::default(),
        },
    ];

    async fn run_test(
        client: &EventClient,
        coll: &Collection<Document>,
        read_preference: ReadPreference,
    ) {
        client.events.clone().clear_cached_events();

        let options = FindOptions::builder()
            .batch_size(2)
            .selection_criteria(SelectionCriteria::ReadPreference(read_preference.clone()))
            .read_concern(ReadConcern::local())
            .build();

        // Loop until data is found to avoid racing with replication.
        let mut cursor;
        loop {
            cursor = coll
                .find(doc! {})
                .with_options(options.clone())
                .await
                .expect("find should succeed");
            if cursor.has_next() {
                break;
            }
        }

        for _ in 0..3 {
            cursor
                .next()
                .await
                .unwrap_or_else(|| {
                    panic!("should get result with read preference {read_preference:?}")
                })
                .unwrap_or_else(|e| {
                    panic!(
                        "result should not be error with read preference {read_preference:?}, but \
                         got {e:?}"
                    )
                });
        }

        let (find_started, _) = client.events.get_successful_command_execution("find");
        let session_id = find_started
            .command
            .get("lsid")
            .expect("find should use implicit session");
        assert!(session_id != &Bson::Null);

        let (command_started, _) = client.events.get_successful_command_execution("getMore");
        let getmore_session_id = command_started
            .command
            .get("lsid")
            .expect("count documents should use implicit session");
        assert_eq!(getmore_session_id, session_id);
    }

    let topology_description = client.topology_description();
    for (addr, server) in topology_description.servers {
        if !server.server_type.is_data_bearing() {
            continue;
        }

        let a = addr.clone();
        let rp = Arc::new(move |si: &ServerInfo| si.address() == &a);
        let options = CountOptions::builder()
            .selection_criteria(SelectionCriteria::Predicate(rp))
            .read_concern(ReadConcern::local())
            .build();

        while coll
            .count_documents(doc! {})
            .with_options(options.clone())
            .await
            .unwrap()
            != 3
        {}
    }

    for read_pref in read_preferences {
        run_test(&client, &coll, read_pref).await;
    }
}