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
/*
* Copyright (C) 2022 Vaticle
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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
*
* http://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.
*/
use core::fmt;
use std::sync::{Arc, Mutex, RwLock};
use crossbeam::atomic::AtomicCell;
use log::warn;
use crate::{
common::{error::ConnectionError, info::SessionInfo, Result, SessionType, TransactionType},
Database, Options, Transaction,
};
type Callback = Box<dyn FnMut() + Send>;
pub struct Session {
database: Database,
server_session_info: RwLock<SessionInfo>,
session_type: SessionType,
is_open: Arc<AtomicCell<bool>>,
on_close: Arc<Mutex<Vec<Callback>>>,
on_reopen: Mutex<Vec<Callback>>,
}
impl fmt::Debug for Session {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Session")
.field("database", &self.database)
.field("session_type", &self.session_type)
.field("server_session_info", &self.server_session_info)
.field("is_open", &self.is_open)
.finish()
}
}
impl Drop for Session {
fn drop(&mut self) {
if let Err(err) = self.force_close() {
warn!("Error encountered while closing session: {}", err);
}
}
}
impl Session {
/// Opens a communication tunnel (session) to the given database with default options.
/// See [`Session::new_with_options`]
#[cfg_attr(feature = "sync", maybe_async::must_be_sync)]
pub async fn new(database: Database, session_type: SessionType) -> Result<Self> {
Self::new_with_options(database, session_type, Options::new()).await
}
/// Opens a communication tunnel (session) to the given database on the running TypeDB server.
///
/// # Arguments
///
/// * `database` -- The database with which the session connects
/// * `session_type` -- The type of session to be created (DATA or SCHEMA)
/// * `options` -- `TypeDBOptions` for the session
///
/// # Examples
///
/// ```rust
#[cfg_attr(feature = "sync", doc = "Session::new_with_options(database, session_type, options);")]
#[cfg_attr(not(feature = "sync"), doc = "Session::new_with_options(database, session_type, options).await;")]
/// ```
#[cfg_attr(feature = "sync", maybe_async::must_be_sync)]
pub async fn new_with_options(database: Database, session_type: SessionType, options: Options) -> Result<Self> {
let server_session_info = database
.run_failsafe(|database, _| async move {
database.connection().open_session(database.name().to_owned(), session_type, options).await
})
.await?;
let is_open = Arc::new(AtomicCell::new(true));
let on_close: Arc<Mutex<Vec<Callback>>> = Arc::new(Mutex::new(vec![Box::new({
let is_open = is_open.clone();
move || is_open.store(false)
})]));
register_persistent_on_close(&server_session_info, on_close.clone());
Ok(Self {
database,
session_type,
server_session_info: RwLock::new(server_session_info),
is_open,
on_close,
on_reopen: Mutex::default(),
})
}
/// Returns the name of the database of the session.
///
/// # Examples
///
/// ```rust
/// session.database_name();
/// ```
pub fn database_name(&self) -> &str {
self.database.name()
}
/// The current session’s type (SCHEMA or DATA)
pub fn type_(&self) -> SessionType {
self.session_type
}
/// Checks whether this session is open.
///
/// # Examples
///
/// ```rust
/// session.is_open();
/// ```
pub fn is_open(&self) -> bool {
self.is_open.load()
}
/// Closes the session. Before opening a new session, the session currently open should first be closed.
///
/// # Examples
///
/// ```rust
/// session.force_close();
/// ```
pub fn force_close(&self) -> Result {
if self.is_open.compare_exchange(true, false).is_ok() {
let session_info = self.server_session_info.write().unwrap();
let connection = self.database.connection().connection(&session_info.address).unwrap();
connection.close_session(session_info.session_id.clone())?;
}
Ok(())
}
/// Registers a callback function which will be executed when this session is closed.
///
/// # Arguments
///
/// * `function` -- The callback function.
///
/// # Examples
///
/// ```rust
/// session.on_close(function);
/// ```
pub fn on_close(&self, callback: impl FnMut() + Send + 'static) {
self.on_close.lock().unwrap().push(Box::new(callback));
}
fn on_server_session_close(&self, callback: impl FnOnce() + Send + 'static) {
let session_info = self.server_session_info.write().unwrap();
session_info.on_close_register_sink.send(Box::new(callback)).ok();
}
/// Registers a callback function which will be executed when this session is reopened.
/// A session may be closed if it times out, or loses the connection to the database.
/// In such situations, the session is reopened automatically when opening a new transaction.
///
/// # Arguments
///
/// * `function` -- The callback function.
///
/// # Examples
///
/// ```rust
/// session.on_reopen(function);
/// ```
pub fn on_reopen(&self, callback: impl FnMut() + Send + 'static) {
self.on_reopen.lock().unwrap().push(Box::new(callback));
}
fn reopened(&self) {
self.on_reopen.lock().unwrap().iter_mut().for_each(|callback| (callback)());
let session_info = self.server_session_info.write().unwrap();
register_persistent_on_close(&session_info, self.on_close.clone());
}
/// Opens a transaction to perform read or write queries on the database connected to the session.
/// See [`Session::transaction_with_options`]
#[cfg_attr(feature = "sync", maybe_async::must_be_sync)]
pub async fn transaction(&self, transaction_type: TransactionType) -> Result<Transaction<'_>> {
self.transaction_with_options(transaction_type, Options::new()).await
}
/// Opens a transaction to perform read or write queries on the database connected to the session.
///
/// # Arguments
///
/// * `transaction_type` -- The type of transaction to be created (READ or WRITE)
/// * `options` -- Options for the session
///
/// # Examples
///
/// ```rust
#[cfg_attr(feature = "sync", doc = "session.transaction_with_options(transaction_type, options);")]
#[cfg_attr(not(feature = "sync"), doc = "session.transaction_with_options(transaction_type, options).await;")]
/// ```
#[cfg_attr(feature = "sync", maybe_async::must_be_sync)]
pub async fn transaction_with_options(
&self,
transaction_type: TransactionType,
options: Options,
) -> Result<Transaction<'_>> {
if !self.is_open() {
return Err(ConnectionError::SessionIsClosed.into());
}
let SessionInfo { address, session_id, network_latency, .. } = self.server_session_info.read().unwrap().clone();
let server_connection = &self.database.connection().connection(&address)?;
let (transaction_stream, transaction_shutdown_sink) = match server_connection
.open_transaction(session_id.clone(), transaction_type, options, network_latency)
.await
{
Ok((transaction_stream, transaction_shutdown_sink)) => (transaction_stream, transaction_shutdown_sink),
Err(_err) => {
self.is_open.store(false);
server_connection.close_session(session_id).ok();
let (session_info, (transaction_stream, transaction_shutdown_sink)) = self
.database
.run_failsafe(|database, _| {
let session_type = self.session_type;
async move {
let connection = database.connection();
let database_name = database.name().to_owned();
let session_info = connection.open_session(database_name, session_type, options).await?;
Ok((
session_info.clone(),
connection
.open_transaction(
session_info.session_id,
transaction_type,
options,
session_info.network_latency,
)
.await?,
))
}
})
.await?;
*self.server_session_info.write().unwrap() = session_info;
self.is_open.store(true);
self.reopened();
(transaction_stream, transaction_shutdown_sink)
}
};
self.on_server_session_close(move || {
transaction_shutdown_sink.send(()).ok();
});
Ok(Transaction::new(transaction_stream))
}
}
fn register_persistent_on_close(server_session_info: &SessionInfo, callbacks: Arc<Mutex<Vec<Callback>>>) {
server_session_info
.on_close_register_sink
.send(Box::new(move || callbacks.lock().unwrap().iter_mut().for_each(|callback| (callback)())))
.ok();
}