neo4j 0.2.0

Bolt driver for Neo4j.
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
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
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
// Copyright Rouven Bauer
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

pub(crate) mod bookmarks;
pub(crate) mod config;
pub(crate) mod retry;

use atomic_refcell::AtomicRefCell;
use std::borrow::Borrow;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt::{Debug, Formatter};
use std::marker::PhantomData;
use std::ops::Deref;
use std::rc::Rc;
use std::result::Result as StdResult;
use std::sync::{Arc, OnceLock};

use log::{debug, info};

use super::config::auth::AuthToken;
use super::home_db_cache::{HomeDbCache, HomeDbCacheKey};
use super::io::bolt::message_parameters::{
    BeginParameters, RunParameters, TelemetryAPI, TelemetryParameters,
};
use super::io::bolt::{BoltMeta, ResponseCallbacks};
use super::io::{AcquireConfig, Pool, PooledBolt, UpdateRtArgs, UpdateRtDb};
use super::record_stream::{ErrorPropagator, RecordStream, SharedErrorPropagator};
use super::transaction::{Transaction, TransactionTimeout};
use super::{EagerResult, ReducedDriverConfig, RoutingControl};
use crate::driver::io::SessionAuth;
use crate::error_::{Neo4jError, Result};
use crate::time::Instant;
use crate::transaction::InnerTransaction;
use crate::value::{ValueReceive, ValueSend};
use bookmarks::{bookmark_managers, BookmarkManager, Bookmarks};
use config::InternalSessionConfig;
pub use config::SessionConfig;
use retry::RetryPolicy;

// imports for docs
#[allow(unused)]
use super::Driver;

/// A session is a container for a series of transactions.
///
/// Sessions, besides being a configuration container, automatically provide
/// [causal chaining](crate#causal-consistency), which means that each transaction can read the
/// results of any previous transaction in the same session.
/// If you need to establish a causal chain between two sessions, you can pass bookmarks manually
/// either by using [`Session::last_bookmarks()`] or by sharing [`BookmarkManager`] instance between
/// sessions (see [`SessionConfig::with_bookmark_manager()`]).
///
/// There are two ways to run a transaction inside a session:
///  * [`Session::transaction()`] runs a normal transaction managed by the client.
///  * [`Session::auto_commit()`] will leave transaction management up to the server.
///    This mode is necessary for certain types of queries that manage their own transactions.
///    Such as `CALL {...} IN TRANSACTION`.
///    This has the big drawback, that the client can easily end up in situations where it's unclear
///    whether a transaction has been committed or not.
///    The only guarantee given is that the transaction has been successfully committed once all
///    results have been consumed.
///
/// See also [`Driver::session()`].
#[derive(Debug)]
pub struct Session<'driver> {
    config: InternalSessionConfig,
    pool: &'driver Pool,
    home_db_cache: Arc<HomeDbCache>,
    driver_config: &'driver ReducedDriverConfig,
    target_db: Arc<AtomicRefCell<SessionTargetDb>>,
    home_db_cache_key: OnceLock<HomeDbCacheKey>,
    session_bookmarks: SessionBookmarks,
    current_acquisition_deadline: Option<Instant>,
}

impl<'driver> Session<'driver> {
    pub(super) fn new(
        config: InternalSessionConfig,
        pool: &'driver Pool,
        home_db_cache: Arc<HomeDbCache>,
        driver_config: &'driver ReducedDriverConfig,
    ) -> Self {
        let bookmarks = config.config.bookmarks.clone();
        let manager = config.config.as_ref().bookmark_manager.clone();
        let target_db = Arc::new(AtomicRefCell::new(SessionTargetDb::new_init(
            config.config.database.clone(),
        )));
        Session {
            config,
            pool,
            home_db_cache,
            driver_config,
            target_db,
            home_db_cache_key: Default::default(),
            session_bookmarks: SessionBookmarks::new(bookmarks, manager),
            current_acquisition_deadline: None,
        }
    }

    /// Prepare a transaction that will leave transaction management up to the server.
    ///
    /// This mode is necessary for certain types of queries that manage their own transactions.
    /// Such as `CALL {...} IN TRANSACTION`.
    /// This has the big drawback, that the client can easily end up in situations where it's unclear
    /// whether a transaction has been committed or not.
    /// The only guarantee given is that the transaction has been successfully committed once all
    /// results have been consumed.
    ///
    /// Use the returned [`AutoCommitBuilder`] to configure the transaction and run it.
    pub fn auto_commit<'session, Q: AsRef<str>>(
        &'session mut self,
        query: Q,
    ) -> AutoCommitBuilder<
        'driver,
        'session,
        Q,
        DefaultParamKey,
        DefaultParam,
        DefaultMetaKey,
        DefaultMeta,
        DefaultReceiver,
    > {
        AutoCommitBuilder::new(self, query)
    }

    fn auto_commit_run<
        'session,
        Q: AsRef<str>,
        KP: Borrow<str> + Debug,
        P: Borrow<HashMap<KP, ValueSend>>,
        KM: Borrow<str> + Debug,
        M: Borrow<HashMap<KM, ValueSend>>,
        R,
        FRes: FnOnce(&mut RecordStream) -> Result<R>,
    >(
        &'session mut self,
        builder: AutoCommitBuilder<'driver, 'session, Q, KP, P, KM, M, FRes>,
    ) -> Result<R> {
        let mut connection = self.acquire_connection(builder.mode)?;
        connection.telemetry(
            TelemetryParameters::new(TelemetryAPI::AutoCommit),
            ResponseCallbacks::new(),
        )?;
        let mut record_stream = RecordStream::new(
            Rc::new(RefCell::new(connection)),
            self.fetch_size(),
            true,
            None,
        );
        let target_db = AtomicRefCell::borrow(&self.target_db).as_db();
        let res = record_stream
            .run(
                RunParameters::new_auto_commit_run(
                    builder.query.as_ref(),
                    Some(builder.param.borrow()),
                    Some(&*self.session_bookmarks.get_bookmarks_for_work()?),
                    builder.timeout.raw(),
                    Some(builder.meta.borrow()),
                    builder.mode.as_protocol_str(),
                    target_db.as_deref().map(String::as_str),
                    self.config
                        .config
                        .as_ref()
                        .impersonated_user
                        .as_ref()
                        .map(|imp| imp.as_str()),
                    &self.config.config.notification_filter,
                ),
                Some(Box::new(self.make_db_meta_resolution_cb())),
            )
            .and_then(|_| (builder.receiver)(&mut record_stream));
        let res = match res {
            Ok(r) => {
                record_stream.consume()?;
                Ok(r)
            }
            Err(e) => {
                let _ = record_stream.consume();
                Err(e)
            }
        };
        let bookmark = record_stream.into_bookmark();
        if let Some(bookmark) = bookmark {
            self.session_bookmarks.update_bookmarks(bookmark)?;
        }
        res
    }

    /// Prepare a transaction.
    ///
    /// Use the returned [`TransactionBuilder`] to configure the transaction and run it.
    pub fn transaction<'session>(
        &'session mut self,
    ) -> TransactionBuilder<'driver, 'session, DefaultMetaKey, DefaultMeta> {
        TransactionBuilder::new(self)
    }

    fn transaction_run<
        'session,
        KM: Borrow<str> + Debug,
        M: Borrow<HashMap<KM, ValueSend>>,
        R,
        FTx: for<'tx> FnOnce(Transaction<'driver, 'tx>) -> Result<R>,
    >(
        &'session mut self,
        builder: &TransactionBuilder<'driver, 'session, KM, M>,
        receiver: FTx,
    ) -> Result<R> {
        let mut connection = self.acquire_connection(builder.mode)?;
        let error_propagator = SharedErrorPropagator::default();

        if let Some(api) = *builder.api.deref().borrow() {
            connection.telemetry(TelemetryParameters::new(api), {
                let api = Arc::clone(&builder.api);
                ResponseCallbacks::new()
                    .with_on_success(move |_meta| {
                        // Once a TELEMETRY message made it successfully to the server, we can
                        // stop trying to send it again.
                        api.borrow_mut().take();
                        Ok(())
                    })
                    .with_on_failure(ErrorPropagator::make_on_error_cb(Arc::clone(
                        &error_propagator,
                    )))
            })?;
        }
        let mut tx =
            InnerTransaction::new(connection, self.fetch_size(), Arc::clone(&error_propagator));
        let bookmarks = &*self.session_bookmarks.get_bookmarks_for_work()?;
        let parameters = BeginParameters::new(
            Some(bookmarks),
            builder.timeout.raw(),
            Some(builder.meta.borrow()),
            builder.mode.as_protocol_str(),
            AtomicRefCell::borrow(&self.target_db).as_db(),
            self.config
                .config
                .impersonated_user
                .as_ref()
                .map(|imp| imp.as_str()),
            &self.config.config.notification_filter,
        );

        tx.begin(
            parameters,
            self.config.eager_begin,
            ResponseCallbacks::new()
                .with_on_success({
                    let db_cb = self.make_db_meta_resolution_cb();
                    move |mut meta| {
                        db_cb(&mut meta);
                        Ok(())
                    }
                })
                .with_on_failure(ErrorPropagator::make_on_error_cb(error_propagator)),
        )?;
        let res = receiver(Transaction::new(&mut tx));
        let res = match res {
            Ok(_) => {
                tx.close()?;
                res
            }
            Err(_) => {
                if let Err(e) = tx.close() {
                    info!(
                        "while propagating user code error: \
                        ignored tx.close() error in transaction_run: {}",
                        e
                    )
                }
                res
            }
        };
        let bookmark = tx.into_bookmark();
        if let Some(bookmark) = bookmark {
            self.session_bookmarks.update_bookmarks(bookmark)?;
        }
        res
    }

    fn resolve_db(&mut self) -> Result<()> {
        let mut target_db = AtomicRefCell::borrow_mut(&self.target_db);
        if target_db.pinned
            || target_db
                .target
                .as_ref()
                .map(|t| !t.guess)
                .unwrap_or_default()
            || !self.pool.is_routing()
        {
            debug!(
                "Targeting fixed db: {:?}",
                target_db.target.as_ref().map(|t| t.db.as_str())
            );
            target_db.pinned = true;
            return Ok(());
        }
        if self.pool.ssr_enabled() {
            if let Some(cached_db) = self.home_db_cache.get(self.home_db_cache_key()) {
                debug!("Targeting cached home db: {:?}", cached_db.as_str());
                *target_db = SessionTargetDb::new_guess(cached_db);
                return Ok(());
            }
        }
        drop(target_db);

        self.resolve_db_forced()
    }

    fn resolve_db_forced(&mut self) -> Result<()> {
        debug!("Resolving home db");
        self.pool
            .resolve_home_db(UpdateRtArgs {
                db: None,
                bookmarks: Some(&*self.session_bookmarks.get_bookmarks_for_work()?),
                imp_user: self
                    .config
                    .config
                    .impersonated_user
                    .as_ref()
                    .map(|imp| imp.as_str()),
                session_auth: self.session_auth(),
                deadline: self.current_acquisition_deadline,
                idle_time_before_connection_test: self.config.idle_time_before_connection_test,
                db_resolution_cb: Some(&self.make_db_resolution_cb()),
            })
            .map(|_| ())
    }

    fn make_db_meta_resolution_cb(&self) -> impl Fn(&mut BoltMeta) + Send + Sync + 'static {
        let base_cb = self.make_db_resolution_cb();
        move |meta| {
            let db = match meta.remove("db") {
                Some(ValueReceive::String(db)) => Some(Arc::new(db)),
                _ => None,
            };
            base_cb(db);
        }
    }

    fn make_db_resolution_cb_if_needed(
        &self,
    ) -> Option<impl Fn(Option<Arc<String>>) + Send + Sync + 'static> {
        if !self.pool.is_routing() {
            return None;
        }
        {
            let target_db = AtomicRefCell::borrow(&self.target_db);
            if target_db.pinned || !target_db.target.as_ref().map(|t| t.guess).unwrap_or(true) {
                return None;
            }
        };
        Some(self.make_db_resolution_cb())
    }

    fn make_db_resolution_cb(&self) -> impl Fn(Option<Arc<String>>) + Send + Sync + 'static {
        let cache = Arc::clone(&self.home_db_cache);
        let target_db = Arc::clone(&self.target_db);
        let key = self.home_db_cache_key().clone();
        move |db| {
            if let Some(db) = db.as_ref() {
                cache.update(key.clone(), Arc::clone(db));
            }
            {
                let mut target_db = AtomicRefCell::borrow_mut(&target_db);
                if !target_db.pinned {
                    debug!("Pinning db: {:?}", db.as_ref().map(|d| d.as_str()));
                    *target_db = SessionTargetDb::new_pinned(db);
                }
            }
        }
    }

    fn home_db_cache_key(&self) -> &HomeDbCacheKey {
        self.home_db_cache_key.get_or_init(|| {
            HomeDbCacheKey::new(
                self.config.config.impersonated_user.as_ref(),
                self.config.config.auth.as_ref(),
            )
        })
    }

    pub(super) fn acquire_connection(
        &mut self,
        mode: RoutingControl,
    ) -> Result<PooledBolt<'driver>> {
        self.acquire_connection_args(mode, AcquireArgs::default())
    }

    fn acquire_connection_args(
        &mut self,
        mode: RoutingControl,
        args: AcquireArgs,
    ) -> Result<PooledBolt<'driver>> {
        self.current_acquisition_deadline = self.pool.config.connection_acquisition_deadline();
        self.resolve_db()?;
        let bookmarks = self.session_bookmarks.get_bookmarks_for_work()?;
        let target = AtomicRefCell::borrow(&self.target_db).target.clone();
        let connection = self.no_resolve_acquire_connection(
            mode,
            Some(&*bookmarks),
            target.as_ref(),
            args.session_auth.unwrap_or_else(|| self.session_auth()),
        )?;
        if target.as_ref().map(|t| t.guess).unwrap_or_default() && !connection.ssr_enabled() {
            debug!(
                "Used db cached, received connection without SSR => \
                    returning connection and falling back to explicit db resolution"
            );
            drop(connection);
            self.resolve_db_forced()?;
            let target = AtomicRefCell::borrow(&self.target_db).target.clone();
            self.no_resolve_acquire_connection(
                mode,
                Some(&*bookmarks),
                target.as_ref(),
                args.session_auth.unwrap_or_else(|| self.session_auth()),
            )
        } else {
            Ok(connection)
        }
    }

    fn no_resolve_acquire_connection(
        &self,
        mode: RoutingControl,
        bookmarks: Option<&Bookmarks>,
        db: Option<&UpdateRtDb>,
        session_auth: SessionAuth,
    ) -> Result<PooledBolt<'driver>> {
        self.pool.acquire(AcquireConfig {
            mode,
            update_rt_args: UpdateRtArgs {
                db,
                bookmarks,
                imp_user: self
                    .config
                    .config
                    .impersonated_user
                    .as_ref()
                    .map(|imp| imp.as_str()),
                session_auth,
                deadline: self.current_acquisition_deadline,
                idle_time_before_connection_test: self.config.idle_time_before_connection_test,
                db_resolution_cb: self
                    .make_db_resolution_cb_if_needed()
                    .as_ref()
                    .map(|cb| cb as _),
            },
        })
    }

    pub(super) fn verify_authentication(&mut self, auth: &Arc<AuthToken>) -> Result<bool> {
        match self.forced_auth(auth) {
            Ok(_) => Ok(true),
            Err(err) => match &err {
                Neo4jError::ServerError { error } => match error.code() {
                    "Neo.ClientError.Security.CredentialsExpired"
                    | "Neo.ClientError.Security.Forbidden"
                    | "Neo.ClientError.Security.TokenExpired"
                    | "Neo.ClientError.Security.Unauthorized" => Ok(false),
                    _ => Err(err),
                },
                Neo4jError::Disconnect { .. }
                | Neo4jError::InvalidConfig { .. }
                | Neo4jError::Timeout { .. }
                | Neo4jError::UserCallback { .. }
                | Neo4jError::ProtocolError { .. } => Err(err),
            },
        }
    }

    fn forced_auth(&mut self, auth: &Arc<AuthToken>) -> Result<()> {
        let args = AcquireArgs {
            session_auth: Some(SessionAuth::Forced(auth)),
        };
        let mut connection = self.acquire_connection_args(RoutingControl::Read, args)?;
        connection.write_all(None)?;
        connection.read_all(None)
    }

    /// Get the bookmarks last received by the session or the ones it was initialized with.
    ///
    /// This can be used to [causally chain](crate#causal-consistency) together sessions.
    ///
    /// # Example
    /// ```
    /// use std::sync::Arc;
    ///
    /// use neo4j::driver::{Driver, RoutingControl};
    /// use neo4j::session::SessionConfig;
    ///
    /// # use doc_test_utils::get_driver;
    ///
    /// # doc_test_utils::db_exclusive(|| {
    /// let db = Arc::new(String::from("neo4j")); // always specify the database name, if possible
    /// let driver: Driver = get_driver();
    /// let mut session1 = driver.session(SessionConfig::new().with_database(Arc::clone(&db)));
    /// // do work with session1, e.g.,
    /// session1.auto_commit("CREATE (n:Node)").run().unwrap();
    ///
    /// let bookmarks = session1.last_bookmarks();
    /// let mut session2 = driver.session(
    ///     SessionConfig::new()
    ///         .with_bookmarks(bookmarks)
    ///         .with_database(Arc::clone(&db)),
    /// );
    /// // now session2 will see the results of the transaction in session1
    /// let mut result = session2
    ///     .auto_commit("MATCH (n:Node) RETURN count(n)")
    ///     .with_routing_control(RoutingControl::Read)
    ///     .run()
    ///     .unwrap();
    /// assert_eq!(result.into_scalar().unwrap().try_into_int().unwrap(), 1);
    /// # });
    /// ```
    #[inline]
    pub fn last_bookmarks(&self) -> Arc<Bookmarks> {
        self.session_bookmarks.get_current_bookmarks()
    }

    #[inline]
    fn fetch_size(&self) -> i64 {
        self.config
            .config
            .as_ref()
            .fetch_size
            .unwrap_or(self.driver_config.fetch_size)
    }

    #[inline]
    fn session_auth(&self) -> SessionAuth {
        match &self.config.config.auth {
            Some(auth) => SessionAuth::Reauth(auth),
            None => SessionAuth::None,
        }
    }
}

/// Builder type to prepare an auto-commit transaction.
///
/// Use [`Session::auto_commit()`] for creating one and call [`AutoCommitBuilder::run()`]
/// to execute the auto-commit transaction when you're done configuring it.
pub struct AutoCommitBuilder<'driver, 'session, Q, KP, P, KM, M, FRes> {
    session: Option<&'session mut Session<'driver>>,
    query: Q,
    _kp: PhantomData<KP>,
    param: P,
    _km: PhantomData<KM>,
    meta: M,
    timeout: TransactionTimeout,
    mode: RoutingControl,
    receiver: FRes,
}

pub(crate) fn default_receiver(res: &mut RecordStream) -> Result<EagerResult> {
    res.try_as_eager_result().map(|r| {
        r.expect("default receiver does not consume stream before turning it into an eager result")
    })
}

pub(crate) type DefaultReceiver = fn(&mut RecordStream) -> Result<EagerResult>;
pub(crate) type DefaultParamKey = String;
pub(crate) type DefaultParam = HashMap<DefaultParamKey, ValueSend>;
pub(crate) type DefaultMetaKey = String;
pub(crate) type DefaultMeta = HashMap<DefaultMetaKey, ValueSend>;

impl<'driver, 'session, Q: AsRef<str>>
    AutoCommitBuilder<
        'driver,
        'session,
        Q,
        DefaultParamKey,
        DefaultParam,
        DefaultMetaKey,
        DefaultMeta,
        DefaultReceiver,
    >
{
    fn new(session: &'session mut Session<'driver>, query: Q) -> Self {
        Self {
            session: Some(session),
            query,
            _kp: PhantomData,
            param: Default::default(),
            _km: PhantomData,
            meta: Default::default(),
            timeout: Default::default(),
            mode: RoutingControl::Write,
            receiver: default_receiver,
        }
    }
}

impl<
        'driver,
        'session,
        Q: AsRef<str>,
        KP: Borrow<str> + Debug,
        P: Borrow<HashMap<KP, ValueSend>>,
        KM: Borrow<str> + Debug,
        M: Borrow<HashMap<KM, ValueSend>>,
        R,
        FRes: FnOnce(&mut RecordStream) -> Result<R>,
    > AutoCommitBuilder<'driver, 'session, Q, KP, P, KM, M, FRes>
{
    /// Configure query parameters.
    ///
    /// # Example
    /// ```
    /// use neo4j::{value_map, ValueReceive};
    ///
    /// # doc_test_utils::db_exclusive(|| {
    /// # let driver = doc_test_utils::get_driver();
    /// # let mut session = doc_test_utils::get_session(&driver);
    /// let mut result = session
    ///     .auto_commit("CREATE (n:Node {id: $id}) RETURN n")
    ///     .with_parameters(value_map!({"id": 1}))
    ///     .run()
    ///     .unwrap();
    /// let mut node = result.into_scalar().unwrap().try_into_node().unwrap();
    /// assert_eq!(node.properties.remove("id").unwrap(), ValueReceive::Integer(1));
    /// # });
    /// ```
    ///
    /// Always prefer this over query string manipulation to avoid injection vulnerabilities and to
    /// allow the server to cache the query plan.
    #[inline]
    pub fn with_parameters<KP_: Borrow<str> + Debug, P_: Borrow<HashMap<KP_, ValueSend>>>(
        self,
        param: P_,
    ) -> AutoCommitBuilder<'driver, 'session, Q, KP_, P_, KM, M, FRes> {
        let Self {
            session,
            query,
            _kp: _,
            param: _,
            _km,
            meta,
            timeout,
            mode,
            receiver,
        } = self;
        AutoCommitBuilder {
            session,
            query,
            _kp: PhantomData,
            param,
            _km,
            meta,
            timeout,
            mode,
            receiver,
        }
    }

    /// Configure the query to not use any parameters.
    ///
    /// This is the *default*.
    #[inline]
    pub fn without_parameters(
        self,
    ) -> AutoCommitBuilder<'driver, 'session, Q, DefaultParamKey, DefaultParam, KM, M, FRes> {
        let Self {
            session,
            query,
            _kp: _,
            param: _,
            _km,
            meta,
            timeout,
            mode,
            receiver,
        } = self;
        AutoCommitBuilder {
            session,
            query,
            _kp: PhantomData,
            param: Default::default(),
            _km,
            meta,
            timeout,
            mode,
            receiver,
        }
    }

    /// Attach transaction metadata to the query.
    ///
    /// See [`TransactionBuilder::with_transaction_meta()`] for more information.
    ///
    /// # Example
    /// ```
    /// use neo4j::value_map;
    ///
    /// # let driver = doc_test_utils::get_driver();
    /// # let mut session = doc_test_utils::get_session(&driver);
    /// let result = session
    ///    .auto_commit("MATCH (n:Node) RETURN n")
    ///    .with_transaction_meta(value_map!({"key": "value"}))
    ///    .run()
    ///    .unwrap();
    /// ```
    #[inline]
    pub fn with_transaction_meta<KM_: Borrow<str> + Debug, M_: Borrow<HashMap<KM_, ValueSend>>>(
        self,
        meta: M_,
    ) -> AutoCommitBuilder<'driver, 'session, Q, KP, P, KM_, M_, FRes> {
        let Self {
            session,
            query,
            _kp,
            param,
            _km: _,
            meta: _,
            timeout,
            mode,
            receiver,
        } = self;
        AutoCommitBuilder {
            session,
            query,
            _kp,
            param,
            _km: PhantomData,
            meta,
            timeout,
            mode,
            receiver,
        }
    }

    /// Configure the query to not use any transaction metadata.
    ///
    /// This is the *default*.
    #[inline]
    pub fn without_transaction_meta(
        self,
    ) -> AutoCommitBuilder<'driver, 'session, Q, KP, P, DefaultMetaKey, DefaultMeta, FRes> {
        let Self {
            session,
            query,
            _kp,
            param,
            _km: _,
            meta: _,
            timeout,
            mode,
            receiver,
        } = self;
        AutoCommitBuilder {
            session,
            query,
            _kp,
            param,
            _km: PhantomData,
            meta: Default::default(),
            timeout,
            mode,
            receiver,
        }
    }

    /// Instruct the server to abort the transaction after the given timeout.
    ///
    /// See [`TransactionTimeout`] for options.
    #[inline]
    pub fn with_transaction_timeout(mut self, timeout: TransactionTimeout) -> Self {
        self.timeout = timeout;
        self
    }

    /// Specify whether the query should be send to a reader or writer in the cluster.
    ///
    /// See [`TransactionBuilder::with_routing_control()`] for more information.
    #[inline]
    pub fn with_routing_control(mut self, mode: RoutingControl) -> Self {
        self.mode = mode;
        self
    }

    /// Specify a custom receiver to handle the result stream.
    ///
    /// By default ([`AutoCommitBuilder::with_default_receiver()`]), the result stream will be
    /// collected into memory and returned as [`EagerResult`].
    ///
    /// # Example
    /// ```
    /// use neo4j::driver::record_stream::RecordStream;
    /// use neo4j::driver::Record;
    ///
    /// # let driver = doc_test_utils::get_driver();
    /// # let mut session = doc_test_utils::get_session(&driver);
    /// let sum = session
    ///     .auto_commit("UNWIND range(1, 3) AS x RETURN x")
    ///     .with_receiver(|stream: &mut RecordStream| {
    ///         let mut sum = 0;
    ///         for result in stream {
    ///             let mut record: Record = result?;
    ///             sum += record.into_values().next().unwrap().try_into_int().unwrap();
    ///         }
    ///         Ok(sum)
    ///     })
    ///     .run()
    ///     .unwrap();
    ///
    /// assert_eq!(sum, 6);
    /// ```
    #[inline]
    pub fn with_receiver<R_, FRes_: FnOnce(&mut RecordStream) -> Result<R_>>(
        self,
        receiver: FRes_,
    ) -> AutoCommitBuilder<'driver, 'session, Q, KP, P, KM, M, FRes_> {
        let Self {
            session,
            query,
            _kp,
            param,
            _km,
            meta,
            timeout,
            mode,
            receiver: _,
        } = self;
        AutoCommitBuilder {
            session,
            query,
            _kp,
            param,
            _km,
            meta,
            timeout,
            mode,
            receiver,
        }
    }

    /// Set the receiver back to the default, which will collect the result stream into memory and
    /// return it as [`EagerResult`].
    #[inline]
    pub fn with_default_receiver(
        self,
    ) -> AutoCommitBuilder<'driver, 'session, Q, KP, P, KM, M, DefaultReceiver> {
        let Self {
            session,
            query,
            _kp,
            param,
            _km,
            meta,
            timeout,
            mode,
            receiver: _,
        } = self;
        AutoCommitBuilder {
            session,
            query,
            _kp,
            param,
            _km,
            meta,
            timeout,
            mode,
            receiver: default_receiver,
        }
    }

    /// Run the query and return the result.
    pub fn run(mut self) -> Result<R> {
        let session = self.session.take().unwrap();
        session.auto_commit_run(self)
    }
}

impl<
        Q: AsRef<str>,
        KP: Borrow<str> + Debug,
        P: Borrow<HashMap<KP, ValueSend>>,
        KM: Borrow<str> + Debug,
        M: Borrow<HashMap<KM, ValueSend>>,
        FRes,
    > Debug for AutoCommitBuilder<'_, '_, Q, KP, P, KM, M, FRes>
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AutoCommitBuilder")
            .field(
                "session",
                &match self.session {
                    None => "None",
                    Some(_) => "Some(...)",
                },
            )
            .field("query", &self.query.as_ref())
            .field("param", &self.param.borrow())
            .field("meta", &self.meta.borrow())
            .field("timeout", &self.timeout)
            .field("mode", &self.mode)
            .field("receiver", &"...")
            .finish()
    }
}

/// Builder type to prepare a transaction.
///
/// Use [`Session::transaction()`] for creating one and call [`TransactionBuilder::run()`]
/// to execute the transaction when you're done configuring it.
pub struct TransactionBuilder<'driver, 'session, KM, M> {
    session: Option<&'session mut Session<'driver>>,
    _km: PhantomData<KM>,
    meta: M,
    timeout: TransactionTimeout,
    mode: RoutingControl,
    api: Arc<AtomicRefCell<Option<TelemetryAPI>>>,
}

impl<'driver, 'session> TransactionBuilder<'driver, 'session, DefaultMetaKey, DefaultMeta> {
    fn new(session: &'session mut Session<'driver>) -> Self {
        Self {
            session: Some(session),
            _km: PhantomData,
            meta: Default::default(),
            timeout: Default::default(),
            mode: RoutingControl::Write,
            api: Default::default(),
        }
    }
}

impl<'driver, 'session, KM: Borrow<str> + Debug, M: Borrow<HashMap<KM, ValueSend>>>
    TransactionBuilder<'driver, 'session, KM, M>
{
    /// Attach transaction metadata to the transaction.
    ///
    /// Transaction metadata will be logged in the server's `query.log` and is accessible through
    /// querying `SHOW TRANSACTIONS YIELD *`.
    /// Metadata can also manually be set via the `dbms.setTXMetaData` procedure.
    ///
    /// # Example
    /// ```
    /// # use neo4j::driver::EagerResult;
    /// use neo4j::transaction::Transaction;
    /// # use neo4j::Result;
    /// use neo4j::value_map;
    ///
    /// # let driver = doc_test_utils::get_driver();
    /// # let mut session = doc_test_utils::get_session(&driver);
    ///
    /// let result = session
    ///     .transaction()
    ///     .with_transaction_meta(value_map!({"key": "value"}))
    ///     .run(|tx: Transaction| {
    ///         // ...
    ///         # tx.query("MATCH (n:Node) RETURN n").run()?.try_as_eager_result()?;
    ///         # tx.commit()
    ///     })
    ///     .unwrap();
    /// ```
    #[inline]
    pub fn with_transaction_meta<KM_: Borrow<str> + Debug, M_: Borrow<HashMap<KM_, ValueSend>>>(
        self,
        meta: M_,
    ) -> TransactionBuilder<'driver, 'session, KM_, M_> {
        let Self {
            session,
            _km: _,
            meta: _,
            timeout,
            mode,
            api,
        } = self;
        TransactionBuilder {
            session,
            _km: PhantomData,
            meta,
            timeout,
            mode,
            api,
        }
    }

    /// Configure the transaction to not use any transaction metadata (this is default).
    #[inline]
    pub fn without_transaction_meta(
        self,
    ) -> TransactionBuilder<'driver, 'session, DefaultMetaKey, DefaultMeta> {
        let Self {
            session,
            _km: _,
            meta: _,
            timeout,
            mode,
            api,
        } = self;
        TransactionBuilder {
            session,
            _km: PhantomData,
            meta: Default::default(),
            timeout,
            mode,
            api,
        }
    }

    /// Instruct the server to abort the transaction after the given timeout.
    ///
    /// See [`TransactionTimeout`] for options.
    #[inline]
    pub fn with_transaction_timeout(mut self, timeout: TransactionTimeout) -> Self {
        self.timeout = timeout;
        self
    }

    /// Specify whether the query should be send to a reader or writer in the cluster.
    ///
    /// Writers (*default*), can handle reads and writes.
    /// However, when running read-only queries, it's more efficient to send them to a reader to
    /// avoid overloading the writer.
    ///
    /// **Writers** are also known as **leaders** or **primaries**.  
    /// **Readers** are also known as **followers** or **secondaries** as well as
    /// **read replicas** or **tertiaries**.
    #[inline]
    pub fn with_routing_control(mut self, mode: RoutingControl) -> Self {
        self.mode = mode;
        self
    }

    #[inline]
    pub(crate) fn with_api_overwrite(mut self, api: Option<TelemetryAPI>) -> Self {
        self.api = Arc::new(AtomicRefCell::new(api));
        self
    }

    /// Run the transaction. The work to be done is specified by the given `receiver`.
    ///
    /// The `receiver` will be called with a [`Transaction`] that can be used to execute queries,
    /// and control the transaction (commit, rollback, ...).
    ///
    /// Especially when running against a clustered or cloud-hosted DBMS, it's recommended to use
    /// [`TransactionBuilder::run_with_retry()`] over this method because many intermittent errors
    /// can occur in such cases (e.g., leader switches, connections killed by load balancers, ...).
    ///
    /// # Example
    /// ```
    /// use std::sync::Arc;
    ///
    /// use neo4j::driver::EagerResult;
    /// use neo4j::transaction::Transaction;
    /// use neo4j::Result;
    /// use neo4j::{value_map, ValueReceive};
    ///
    /// # use doc_test_utils::get_session;
    /// #
    /// # doc_test_utils::db_exclusive(|| {
    /// # let driver = doc_test_utils::get_driver();
    /// #
    /// // always specify the database name, if possible
    /// let database = Arc::new(String::from("neo4j"));
    ///
    /// // populate database
    /// driver
    ///     .execute_query("UNWIND range(1, 3) AS x CREATE (n:Actor {fame: x})")
    ///     .with_database(Arc::clone(&database))
    ///     .run()
    ///     .unwrap();
    ///
    /// let total_fame = get_session(&driver)
    ///     .transaction()
    ///     .run(|tx: Transaction| {
    ///         let actors = tx.query("MATCH (n:Actor) RETURN n").run()?;
    ///         let mut total_fame = 0;
    ///         for result in actors {
    ///             let mut record = result?;
    ///             let mut actor = record.into_values().next().unwrap().try_into_node().unwrap();
    ///             let fame: ValueReceive = actor.properties.remove("fame").unwrap();
    ///             let fame: i64 = fame.try_into_int().unwrap();
    ///             total_fame += fame * 2;
    ///             // increase everyone's fame!
    ///             tx.query("MATCH (n:Actor) WHERE id(n) = $id SET n.fame = $fame")
    ///                 .with_parameters(value_map!({"id": actor.id, "fame": fame * 2}))
    ///                 .run()?;
    ///             // ...
    ///             // NOTE: this is just for demonstration purposes, in reality you would
    ///             //       do this in a single query and save many round trips to the server:
    ///             //       MATCH (n:Actor) SET n.fame = n.fame * 2
    ///         }
    ///         // now attempt commit the whole transaction
    ///         tx.commit()?;
    ///         // to roll it back, you can either call `tx.rollback()` or `drop` the Transaction
    ///         Ok(total_fame) // return any value you want from the transaction
    ///     })
    ///     .unwrap();
    ///
    /// assert_eq!(total_fame, 12);
    /// let db_total_fame = driver
    ///     .execute_query("MATCH (n:Actor) RETURN sum(n.fame) AS total_fame")
    ///     .with_database(Arc::clone(&database))
    ///     .run()
    ///     .unwrap()
    ///     .into_scalar()
    ///     .unwrap();
    /// assert_eq!(db_total_fame, ValueReceive::Integer(total_fame));
    /// # });
    /// ```
    pub fn run<R>(mut self, receiver: impl FnOnce(Transaction) -> Result<R>) -> Result<R> {
        self.api
            .borrow_mut()
            .get_or_insert(TelemetryAPI::UnmanagedTx);
        let session = self.session.take().unwrap();
        session.transaction_run(&self, receiver)
    }

    /// Run the transaction with a retry policy.
    ///
    /// This is pretty much the same as [`TransactionBuilder::run()`], except that the `receiver`
    /// will be retried if it returns an error deemed retryable by the given `retry_policy`.
    ///
    /// See also [`RetryPolicy`].
    pub fn run_with_retry<R, P: RetryPolicy>(
        mut self,
        retry_policy: P,
        mut receiver: impl FnMut(Transaction) -> Result<R>,
    ) -> StdResult<R, P::Error> {
        self.api.borrow_mut().get_or_insert(TelemetryAPI::TxFunc);
        let session = self.session.take().unwrap();
        retry_policy.execute(|| session.transaction_run(&self, &mut receiver))
    }
}

impl<KM, M: Debug> Debug for TransactionBuilder<'_, '_, KM, M> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TransactionBuilder")
            .field(
                "session",
                &match self.session {
                    None => "None",
                    Some(_) => "Some(...)",
                },
            )
            .field("meta", &self.meta)
            .field("timeout", &self.timeout)
            .field("mode", &self.mode)
            .finish()
    }
}

#[derive(Debug)]
enum SessionBookmarks {
    Unmanaged {
        bookmarks: Arc<Bookmarks>,
    },
    ManagedInit {
        bookmarks: Arc<Bookmarks>,
        manager: Arc<dyn BookmarkManager>,
    },
    ManagedGet {
        bookmarks: Arc<Bookmarks>,
        previous_bookmarks: Arc<Bookmarks>,
        manager: Arc<dyn BookmarkManager>,
    },
    ManagedUpdated {
        bookmarks: Arc<Bookmarks>,
        previous_bookmarks: Arc<Bookmarks>,
        manager: Arc<dyn BookmarkManager>,
    },
}

impl SessionBookmarks {
    fn new(bookmarks: Option<Arc<Bookmarks>>, manager: Option<Arc<dyn BookmarkManager>>) -> Self {
        match manager {
            None => Self::Unmanaged {
                bookmarks: bookmarks.unwrap_or_default(),
            },
            Some(manager) => Self::ManagedInit {
                bookmarks: bookmarks.unwrap_or_default(),
                manager,
            },
        }
    }

    fn get_current_bookmarks(&self) -> Arc<Bookmarks> {
        match &self {
            Self::Unmanaged { bookmarks }
            | Self::ManagedInit { bookmarks, .. }
            | Self::ManagedGet { bookmarks, .. }
            | Self::ManagedUpdated { bookmarks, .. } => Arc::clone(bookmarks),
        }
    }

    fn get_bookmarks_for_work(&mut self) -> Result<Arc<Bookmarks>> {
        match self {
            Self::Unmanaged { bookmarks } => Ok(Arc::clone(bookmarks)),
            Self::ManagedInit { bookmarks, manager }
            | Self::ManagedGet {
                bookmarks, manager, ..
            } => {
                let manager_bookmarks = bookmark_managers::get_bookmarks(&**manager)?;
                let previous_bookmarks = Arc::new(&*manager_bookmarks + &**bookmarks);
                *self = Self::ManagedGet {
                    bookmarks: Arc::clone(bookmarks),
                    previous_bookmarks: Arc::clone(&previous_bookmarks),
                    manager: Arc::clone(manager),
                };
                Ok(previous_bookmarks)
            }
            Self::ManagedUpdated {
                manager,
                previous_bookmarks,
                ..
            } => {
                *previous_bookmarks = bookmark_managers::get_bookmarks(&**manager)?;
                Ok(Arc::clone(previous_bookmarks))
            }
        }
    }

    fn update_bookmarks(&mut self, bookmark: String) -> Result<()> {
        match self {
            SessionBookmarks::Unmanaged { bookmarks } => {
                *bookmarks = Arc::new(Bookmarks::from_raw([bookmark]));
            }
            SessionBookmarks::ManagedInit { .. } => {
                panic!("Cannot update bookmarks before first get")
            }
            SessionBookmarks::ManagedGet {
                bookmarks,
                previous_bookmarks,
                manager,
            } => {
                *bookmarks = Arc::new(Bookmarks::from_raw([bookmark]));
                bookmark_managers::update_bookmarks(
                    &**manager,
                    Arc::clone(previous_bookmarks),
                    Arc::clone(bookmarks),
                )?;
                *self = Self::ManagedUpdated {
                    bookmarks: Arc::clone(bookmarks),
                    previous_bookmarks: Arc::clone(previous_bookmarks),
                    manager: Arc::clone(manager),
                };
            }
            SessionBookmarks::ManagedUpdated {
                bookmarks,
                previous_bookmarks,
                manager,
            } => {
                *bookmarks = Arc::new(Bookmarks::from_raw([bookmark]));
                bookmark_managers::update_bookmarks(
                    &**manager,
                    Arc::clone(previous_bookmarks),
                    Arc::clone(bookmarks),
                )?;
            }
        }
        Ok(())
    }
}

#[derive(Debug, Default)]
struct AcquireArgs<'a> {
    session_auth: Option<SessionAuth<'a>>,
}

#[derive(Debug, Default)]
struct SessionTargetDb {
    target: Option<UpdateRtDb>,
    pinned: bool,
}

impl SessionTargetDb {
    fn new_init(target: Option<Arc<String>>) -> Self {
        Self {
            target: target.map(|db| UpdateRtDb { db, guess: false }),
            pinned: false,
        }
    }

    fn new_guess(db: Arc<String>) -> Self {
        Self {
            target: Some(UpdateRtDb { db, guess: true }),
            pinned: false,
        }
    }

    fn new_pinned(target: Option<Arc<String>>) -> Self {
        Self {
            target: target.map(|db| UpdateRtDb { db, guess: false }),
            pinned: true,
        }
    }

    fn as_db(&self) -> Option<Arc<String>> {
        if self.pinned || self.target.as_ref().map(|t| !t.guess).unwrap_or_default() {
            self.target.as_ref().map(|t| Arc::clone(&t.db))
        } else {
            None
        }
    }
}