Remove manual log targets ()

This commit is contained in:
Rushmore Mushambi 2023-07-04 23:02:10 +02:00 committed by GitHub
parent 17455a4c24
commit 20ee2f1dc6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
28 changed files with 128 additions and 215 deletions

View file

@ -71,9 +71,6 @@ use tokio::io::AsyncWrite;
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
use tokio::io::AsyncWriteExt; use tokio::io::AsyncWriteExt;
#[cfg(not(target_arch = "wasm32"))]
const LOG: &str = "surrealdb::api::engine::local";
/// In-memory database /// In-memory database
/// ///
/// # Examples /// # Examples
@ -528,7 +525,7 @@ async fn router(
chn: channel::Sender<Vec<u8>>, chn: channel::Sender<Vec<u8>>,
) -> std::result::Result<(), crate::Error> { ) -> std::result::Result<(), crate::Error> {
kvs.export(ns, db, chn).await.map_err(|error| { kvs.export(ns, db, chn).await.map_err(|error| {
error!(target: LOG, "{error}"); error!("{error}");
crate::Error::Db(error) crate::Error::Db(error)
}) })
} }

View file

@ -55,7 +55,6 @@ use tokio_util::compat::FuturesAsyncReadCompatExt;
use url::Url; use url::Url;
const SQL_PATH: &str = "sql"; const SQL_PATH: &str = "sql";
const LOG: &str = "surrealdb::engine::remote::http";
/// The HTTP scheme used to connect to `http://` endpoints /// The HTTP scheme used to connect to `http://` endpoints
#[derive(Debug)] #[derive(Debug)]
@ -167,7 +166,7 @@ async fn submit_auth(request: RequestBuilder) -> Result<Value> {
} }
async fn query(request: RequestBuilder) -> Result<QueryResponse> { async fn query(request: RequestBuilder) -> Result<QueryResponse> {
info!(target: LOG, "{request:?}"); info!("{request:?}");
let response = request.send().await?.error_for_status()?; let response = request.send().await?.error_for_status()?;
let bytes = response.bytes().await?; let bytes = response.bytes().await?;
let responses = deserialize::<Vec<HttpQueryResponse>>(&bytes).map_err(|error| { let responses = deserialize::<Vec<HttpQueryResponse>>(&bytes).map_err(|error| {

View file

@ -1,5 +1,4 @@
use super::Client; use super::Client;
use super::LOG;
use crate::api::conn::Connection; use crate::api::conn::Connection;
use crate::api::conn::DbResponse; use crate::api::conn::DbResponse;
use crate::api::conn::Method; use crate::api::conn::Method;
@ -68,7 +67,7 @@ impl Connection for Client {
) -> Pin<Box<dyn Future<Output = Result<Receiver<Result<DbResponse>>>> + Send + Sync + 'r>> { ) -> Pin<Box<dyn Future<Output = Result<Receiver<Result<DbResponse>>>> + Send + Sync + 'r>> {
Box::pin(async move { Box::pin(async move {
let (sender, receiver) = flume::bounded(1); let (sender, receiver) = flume::bounded(1);
trace!(target: LOG, "{param:?}"); trace!("{param:?}");
let route = Route { let route = Route {
request: (0, self.method, param), request: (0, self.method, param),
response: sender, response: sender,

View file

@ -36,7 +36,6 @@ use wasmtimer::tokio::Interval;
pub(crate) const PATH: &str = "rpc"; pub(crate) const PATH: &str = "rpc";
const PING_INTERVAL: Duration = Duration::from_secs(5); const PING_INTERVAL: Duration = Duration::from_secs(5);
const PING_METHOD: &str = "ping"; const PING_METHOD: &str = "ping";
const LOG: &str = "surrealdb::engine::remote::ws";
/// The WS scheme used to connect to `ws://` endpoints /// The WS scheme used to connect to `ws://` endpoints
#[derive(Debug)] #[derive(Debug)]

View file

@ -1,4 +1,3 @@
use super::LOG;
use super::PATH; use super::PATH;
use crate::api::conn::Connection; use crate::api::conn::Connection;
use crate::api::conn::DbResponse; use crate::api::conn::DbResponse;
@ -243,7 +242,7 @@ pub(crate) fn router(
request.insert("params".to_owned(), params.into()); request.insert("params".to_owned(), params.into());
} }
let payload = Value::from(request); let payload = Value::from(request);
trace!(target: LOG, "Request {payload}"); trace!("Request {payload}");
Message::Binary(payload.into()) Message::Binary(payload.into())
}; };
if let Method::Authenticate if let Method::Authenticate
@ -268,7 +267,7 @@ pub(crate) fn router(
.await .await
.is_err() .is_err()
{ {
trace!(target: LOG, "Receiver dropped"); trace!("Receiver dropped");
} }
} }
} }
@ -276,7 +275,7 @@ pub(crate) fn router(
Err(error) => { Err(error) => {
let error = Error::Ws(error.to_string()); let error = Error::Ws(error.to_string());
if response.into_send_async(Err(error.into())).await.is_err() { if response.into_send_async(Err(error.into())).await.is_err() {
trace!(target: LOG, "Receiver dropped"); trace!("Receiver dropped");
} }
break; break;
} }
@ -288,7 +287,7 @@ pub(crate) fn router(
Ok(message) => match Response::try_from(&message) { Ok(message) => match Response::try_from(&message) {
Ok(option) => { Ok(option) => {
if let Some(response) = option { if let Some(response) = option {
trace!(target: LOG, "{response:?}"); trace!("{response:?}");
if let Some(Ok(id)) = if let Some(Ok(id)) =
response.id.map(Value::coerce_to_i64) response.id.map(Value::coerce_to_i64)
{ {
@ -327,10 +326,7 @@ pub(crate) fn router(
} }
} else { } else {
// Unfortunately, we don't know which response failed to deserialize // Unfortunately, we don't know which response failed to deserialize
warn!( warn!("Failed to deserialise message; {error:?}");
target: LOG,
"Failed to deserialise message; {error:?}"
);
} }
} }
} }
@ -338,13 +334,10 @@ pub(crate) fn router(
Err(error) => { Err(error) => {
match error { match error {
WsError::ConnectionClosed => { WsError::ConnectionClosed => {
trace!( trace!("Connection successfully closed on the server");
target: LOG,
"Connection successfully closed on the server"
);
} }
error => { error => {
trace!(target: LOG, "{error}"); trace!("{error}");
} }
} }
break; break;
@ -354,9 +347,9 @@ pub(crate) fn router(
Either::Ping => { Either::Ping => {
// only ping if we haven't talked to the server recently // only ping if we haven't talked to the server recently
if last_activity.elapsed() >= PING_INTERVAL { if last_activity.elapsed() >= PING_INTERVAL {
trace!(target: LOG, "Pinging the server"); trace!("Pinging the server");
if let Err(error) = socket_sink.send(ping.clone()).await { if let Err(error) = socket_sink.send(ping.clone()).await {
trace!(target: LOG, "failed to ping the server; {error:?}"); trace!("failed to ping the server; {error:?}");
break; break;
} }
} }
@ -369,13 +362,13 @@ pub(crate) fn router(
} }
'reconnect: loop { 'reconnect: loop {
trace!(target: LOG, "Reconnecting..."); trace!("Reconnecting...");
match connect(&url, Some(config), maybe_connector.clone()).await { match connect(&url, Some(config), maybe_connector.clone()).await {
Ok(s) => { Ok(s) => {
socket = s; socket = s;
for (_, message) in &replay { for (_, message) in &replay {
if let Err(error) = socket.send(message.clone()).await { if let Err(error) = socket.send(message.clone()).await {
trace!(target: LOG, "{error}"); trace!("{error}");
time::sleep(time::Duration::from_secs(1)).await; time::sleep(time::Duration::from_secs(1)).await;
continue 'reconnect; continue 'reconnect;
} }
@ -389,18 +382,18 @@ pub(crate) fn router(
vec![key.as_str().into(), value.clone()].into(), vec![key.as_str().into(), value.clone()].into(),
); );
let payload = Value::from(request); let payload = Value::from(request);
trace!(target: LOG, "Request {payload}"); trace!("Request {payload}");
if let Err(error) = socket.send(Message::Binary(payload.into())).await { if let Err(error) = socket.send(Message::Binary(payload.into())).await {
trace!(target: LOG, "{error}"); trace!("{error}");
time::sleep(time::Duration::from_secs(1)).await; time::sleep(time::Duration::from_secs(1)).await;
continue 'reconnect; continue 'reconnect;
} }
} }
trace!(target: LOG, "Reconnected successfully"); trace!("Reconnected successfully");
break; break;
} }
Err(error) => { Err(error) => {
trace!(target: LOG, "Failed to reconnect; {error}"); trace!("Failed to reconnect; {error}");
time::sleep(time::Duration::from_secs(1)).await; time::sleep(time::Duration::from_secs(1)).await;
} }
} }
@ -413,7 +406,7 @@ impl Response {
fn try_from(message: &Message) -> Result<Option<Self>> { fn try_from(message: &Message) -> Result<Option<Self>> {
match message { match message {
Message::Text(text) => { Message::Text(text) => {
trace!(target: LOG, "Received an unexpected text message; {text}"); trace!("Received an unexpected text message; {text}");
Ok(None) Ok(None)
} }
Message::Binary(binary) => deserialize(binary).map(Some).map_err(|error| { Message::Binary(binary) => deserialize(binary).map(Some).map_err(|error| {
@ -424,19 +417,19 @@ impl Response {
.into() .into()
}), }),
Message::Ping(..) => { Message::Ping(..) => {
trace!(target: LOG, "Received a ping from the server"); trace!("Received a ping from the server");
Ok(None) Ok(None)
} }
Message::Pong(..) => { Message::Pong(..) => {
trace!(target: LOG, "Received a pong from the server"); trace!("Received a pong from the server");
Ok(None) Ok(None)
} }
Message::Frame(..) => { Message::Frame(..) => {
trace!(target: LOG, "Received an unexpected raw frame"); trace!("Received an unexpected raw frame");
Ok(None) Ok(None)
} }
Message::Close(..) => { Message::Close(..) => {
trace!(target: LOG, "Received an unexpected close message"); trace!("Received an unexpected close message");
Ok(None) Ok(None)
} }
} }
@ -450,9 +443,9 @@ impl Drop for Socket {
if let Some(mut conn) = mem::take(&mut self.0) { if let Some(mut conn) = mem::take(&mut self.0) {
futures::executor::block_on(async move { futures::executor::block_on(async move {
match conn.borrow_mut().close().await { match conn.borrow_mut().close().await {
Ok(..) => trace!(target: LOG, "Connection closed successfully"), Ok(..) => trace!("Connection closed successfully"),
Err(error) => { Err(error) => {
trace!(target: LOG, "Failed to close database connection; {error}") trace!("Failed to close database connection; {error}")
} }
} }
}); });

View file

@ -1,4 +1,3 @@
use super::LOG;
use super::PATH; use super::PATH;
use crate::api::conn::Connection; use crate::api::conn::Connection;
use crate::api::conn::DbResponse; use crate::api::conn::DbResponse;
@ -216,7 +215,7 @@ pub(crate) fn router(
request.insert("params".to_owned(), params.into()); request.insert("params".to_owned(), params.into());
} }
let payload = Value::from(request); let payload = Value::from(request);
trace!(target: LOG, "Request {payload}"); trace!("Request {payload}");
Message::Binary(payload.into()) Message::Binary(payload.into())
}; };
if let Method::Authenticate if let Method::Authenticate
@ -241,7 +240,7 @@ pub(crate) fn router(
.await .await
.is_err() .is_err()
{ {
trace!(target: LOG, "Receiver dropped"); trace!("Receiver dropped");
} }
} }
} }
@ -249,7 +248,7 @@ pub(crate) fn router(
Err(error) => { Err(error) => {
let error = Error::Ws(error.to_string()); let error = Error::Ws(error.to_string());
if response.into_send_async(Err(error.into())).await.is_err() { if response.into_send_async(Err(error.into())).await.is_err() {
trace!(target: LOG, "Receiver dropped"); trace!("Receiver dropped");
} }
break; break;
} }
@ -260,7 +259,7 @@ pub(crate) fn router(
match Response::try_from(&message) { match Response::try_from(&message) {
Ok(option) => { Ok(option) => {
if let Some(response) = option { if let Some(response) = option {
trace!(target: LOG, "{response:?}"); trace!("{response:?}");
if let Some(Ok(id)) = response.id.map(Value::coerce_to_i64) { if let Some(Ok(id)) = response.id.map(Value::coerce_to_i64) {
if let Some((_method, sender)) = routes.remove(&id) { if let Some((_method, sender)) = routes.remove(&id) {
let _res = sender let _res = sender
@ -290,10 +289,7 @@ pub(crate) fn router(
} }
} else { } else {
// Unfortunately, we don't know which response failed to deserialize // Unfortunately, we don't know which response failed to deserialize
warn!( warn!("Failed to deserialise message; {error:?}");
target: LOG,
"Failed to deserialise message; {error:?}"
);
} }
} }
} }
@ -301,14 +297,14 @@ pub(crate) fn router(
} }
Either::Event(event) => match event { Either::Event(event) => match event {
WsEvent::Error => { WsEvent::Error => {
trace!(target: LOG, "connection errored"); trace!("connection errored");
break; break;
} }
WsEvent::WsErr(error) => { WsEvent::WsErr(error) => {
trace!(target: LOG, "{error}"); trace!("{error}");
} }
WsEvent::Closed(..) => { WsEvent::Closed(..) => {
trace!(target: LOG, "connection closed"); trace!("connection closed");
break; break;
} }
_ => {} _ => {}
@ -316,9 +312,9 @@ pub(crate) fn router(
Either::Ping => { Either::Ping => {
// only ping if we haven't talked to the server recently // only ping if we haven't talked to the server recently
if last_activity.elapsed() >= PING_INTERVAL { if last_activity.elapsed() >= PING_INTERVAL {
trace!(target: LOG, "Pinging the server"); trace!("Pinging the server");
if let Err(error) = socket_sink.send(ping.clone()).await { if let Err(error) = socket_sink.send(ping.clone()).await {
trace!(target: LOG, "failed to ping the server; {error:?}"); trace!("failed to ping the server; {error:?}");
break; break;
} }
} }
@ -330,7 +326,7 @@ pub(crate) fn router(
} }
'reconnect: loop { 'reconnect: loop {
trace!(target: LOG, "Reconnecting..."); trace!("Reconnecting...");
match WsMeta::connect(&address.endpoint, None).await { match WsMeta::connect(&address.endpoint, None).await {
Ok((mut meta, stream)) => { Ok((mut meta, stream)) => {
socket = stream; socket = stream;
@ -342,7 +338,7 @@ pub(crate) fn router(
match result { match result {
Ok(events) => events, Ok(events) => events,
Err(error) => { Err(error) => {
trace!(target: LOG, "{error}"); trace!("{error}");
time::sleep(Duration::from_secs(1)).await; time::sleep(Duration::from_secs(1)).await;
continue 'reconnect; continue 'reconnect;
} }
@ -350,7 +346,7 @@ pub(crate) fn router(
}; };
for (_, message) in &replay { for (_, message) in &replay {
if let Err(error) = socket.send(message.clone()).await { if let Err(error) = socket.send(message.clone()).await {
trace!(target: LOG, "{error}"); trace!("{error}");
time::sleep(Duration::from_secs(1)).await; time::sleep(Duration::from_secs(1)).await;
continue 'reconnect; continue 'reconnect;
} }
@ -363,18 +359,18 @@ pub(crate) fn router(
vec![key.as_str().into(), value.clone()].into(), vec![key.as_str().into(), value.clone()].into(),
); );
let payload = Value::from(request); let payload = Value::from(request);
trace!(target: LOG, "Request {payload}"); trace!("Request {payload}");
if let Err(error) = socket.send(Message::Binary(payload.into())).await { if let Err(error) = socket.send(Message::Binary(payload.into())).await {
trace!(target: LOG, "{error}"); trace!("{error}");
time::sleep(Duration::from_secs(1)).await; time::sleep(Duration::from_secs(1)).await;
continue 'reconnect; continue 'reconnect;
} }
} }
trace!(target: LOG, "Reconnected successfully"); trace!("Reconnected successfully");
break; break;
} }
Err(error) => { Err(error) => {
trace!(target: LOG, "Failed to reconnect; {error}"); trace!("Failed to reconnect; {error}");
time::sleep(Duration::from_secs(1)).await; time::sleep(Duration::from_secs(1)).await;
} }
} }
@ -387,7 +383,7 @@ impl Response {
fn try_from(message: &Message) -> Result<Option<Self>> { fn try_from(message: &Message) -> Result<Option<Self>> {
match message { match message {
Message::Text(text) => { Message::Text(text) => {
trace!(target: LOG, "Received an unexpected text message; {text}"); trace!("Received an unexpected text message; {text}");
Ok(None) Ok(None)
} }
Message::Binary(binary) => deserialize(binary).map(Some).map_err(|error| { Message::Binary(binary) => deserialize(binary).map(Some).map_err(|error| {

View file

@ -31,7 +31,6 @@ use wasm_bindgen_futures::spawn_local as spawn;
pub type Result<T> = std::result::Result<T, crate::Error>; pub type Result<T> = std::result::Result<T, crate::Error>;
const SUPPORTED_VERSIONS: (&str, &str) = (">=1.0.0-beta.9, <2.0.0", "20230701.55918b7c"); const SUPPORTED_VERSIONS: (&str, &str) = (">=1.0.0-beta.9, <2.0.0", "20230701.55918b7c");
const LOG: &str = "surrealdb::api";
/// Connection trait implemented by supported engines /// Connection trait implemented by supported engines
pub trait Connection: conn::Connection {} pub trait Connection: conn::Connection {}
@ -153,13 +152,13 @@ where
Ok(version) => { Ok(version) => {
let server_build = &version.build; let server_build = &version.build;
if !req.matches(&version) { if !req.matches(&version) {
warn!(target: LOG, "server version `{version}` does not match the range supported by the client `{versions}`"); warn!("server version `{version}` does not match the range supported by the client `{versions}`");
} else if !server_build.is_empty() && server_build < &build_meta { } else if !server_build.is_empty() && server_build < &build_meta {
warn!(target: LOG, "server build `{server_build}` is older than the minimum supported build `{build_meta}`"); warn!("server build `{server_build}` is older than the minimum supported build `{build_meta}`");
} }
} }
Err(error) => { Err(error) => {
trace!(target: LOG, "failed to lookup the server version; {error:?}"); trace!("failed to lookup the server version; {error:?}");
} }
} }
}); });

View file

@ -5,7 +5,6 @@ use crate::dbs::Level;
use crate::dbs::Notification; use crate::dbs::Notification;
use crate::dbs::Options; use crate::dbs::Options;
use crate::dbs::Transaction; use crate::dbs::Transaction;
use crate::dbs::LOG;
use crate::dbs::{Auth, QueryType}; use crate::dbs::{Auth, QueryType};
use crate::err::Error; use crate::err::Error;
use crate::kvs::Datastore; use crate::kvs::Datastore;
@ -171,7 +170,7 @@ impl<'a> Executor<'a> {
// Process all statements in query // Process all statements in query
for stm in qry.into_iter() { for stm in qry.into_iter() {
// Log the statement // Log the statement
debug!(target: LOG, "Executing: {}", stm); debug!("Executing: {}", stm);
// Reset errors // Reset errors
if self.txn.is_none() { if self.txn.is_none() {
self.err = false; self.err = false;

View file

@ -2,7 +2,6 @@ use crate::ctx::Canceller;
use crate::ctx::Context; use crate::ctx::Context;
use crate::dbs::Options; use crate::dbs::Options;
use crate::dbs::Statement; use crate::dbs::Statement;
use crate::dbs::LOG;
use crate::doc::Document; use crate::doc::Document;
use crate::err::Error; use crate::err::Error;
use crate::idx::planner::plan::Plan; use crate::idx::planner::plan::Plan;
@ -78,7 +77,7 @@ impl Iterator {
stm: &Statement<'_>, stm: &Statement<'_>,
) -> Result<Value, Error> { ) -> Result<Value, Error> {
// Log the statement // Log the statement
trace!(target: LOG, "Iterating: {}", stm); trace!("Iterating: {}", stm);
// Enable context override // Enable context override
let mut run = Context::new(ctx); let mut run = Context::new(ctx);
self.run = run.add_cancel(); self.run = run.add_cancel();

View file

@ -36,5 +36,3 @@ pub mod cl;
#[cfg(test)] #[cfg(test)]
pub(crate) mod test; pub(crate) mod test;
pub(crate) const LOG: &str = "surrealdb::dbs";

View file

@ -3,55 +3,30 @@
#[allow(clippy::module_inception)] #[allow(clippy::module_inception)]
pub mod console { pub mod console {
// Specify the imports // Specify the imports
use crate::fnc::script::LOG;
use crate::sql::value::Value; use crate::sql::value::Value;
use js::prelude::Rest; use js::prelude::Rest;
/// Log the input values as INFO /// Log the input values as INFO
pub fn log(args: Rest<Value>) { pub fn log(args: Rest<Value>) {
info!( info!("{}", args.iter().map(|v| v.to_raw_string()).collect::<Vec<String>>().join(" "));
target: LOG,
"{}",
args.iter().map(|v| v.to_raw_string()).collect::<Vec<String>>().join(" ")
);
} }
/// Log the input values as INFO /// Log the input values as INFO
pub fn info(args: Rest<Value>) { pub fn info(args: Rest<Value>) {
info!( info!("{}", args.iter().map(|v| v.to_raw_string()).collect::<Vec<String>>().join(" "));
target: LOG,
"{}",
args.iter().map(|v| v.to_raw_string()).collect::<Vec<String>>().join(" ")
);
} }
/// Log the input values as WARN /// Log the input values as WARN
pub fn warn(args: Rest<Value>) { pub fn warn(args: Rest<Value>) {
warn!( warn!("{}", args.iter().map(|v| v.to_raw_string()).collect::<Vec<String>>().join(" "));
target: LOG,
"{}",
args.iter().map(|v| v.to_raw_string()).collect::<Vec<String>>().join(" ")
);
} }
/// Log the input values as ERROR /// Log the input values as ERROR
pub fn error(args: Rest<Value>) { pub fn error(args: Rest<Value>) {
error!( error!("{}", args.iter().map(|v| v.to_raw_string()).collect::<Vec<String>>().join(" "));
target: LOG,
"{}",
args.iter().map(|v| v.to_raw_string()).collect::<Vec<String>>().join(" ")
);
} }
/// Log the input values as DEBUG /// Log the input values as DEBUG
pub fn debug(args: Rest<Value>) { pub fn debug(args: Rest<Value>) {
debug!( debug!("{}", args.iter().map(|v| v.to_raw_string()).collect::<Vec<String>>().join(" "));
target: LOG,
"{}",
args.iter().map(|v| v.to_raw_string()).collect::<Vec<String>>().join(" ")
);
} }
/// Log the input values as TRACE /// Log the input values as TRACE
pub fn trace(args: Rest<Value>) { pub fn trace(args: Rest<Value>) {
trace!( trace!("{}", args.iter().map(|v| v.to_raw_string()).collect::<Vec<String>>().join(" "));
target: LOG,
"{}",
args.iter().map(|v| v.to_raw_string()).collect::<Vec<String>>().join(" ")
);
} }
} }

View file

@ -1,7 +1,5 @@
#![cfg(feature = "scripting")] #![cfg(feature = "scripting")]
const LOG: &str = "surrealdb::jsr";
pub use main::run; pub use main::run;
mod classes; mod classes;

View file

@ -6,5 +6,4 @@ pub mod signup;
pub mod token; pub mod token;
pub mod verify; pub mod verify;
pub const LOG: &str = "surrealdb::iam";
pub const TOKEN: &str = "Bearer "; pub const TOKEN: &str = "Bearer ";

View file

@ -2,7 +2,6 @@ use crate::dbs::Auth;
use crate::dbs::Session; use crate::dbs::Session;
use crate::err::Error; use crate::err::Error;
use crate::iam::token::Claims; use crate::iam::token::Claims;
use crate::iam::LOG;
use crate::iam::TOKEN; use crate::iam::TOKEN;
use crate::kvs::Datastore; use crate::kvs::Datastore;
use crate::sql::Algorithm; use crate::sql::Algorithm;
@ -81,7 +80,7 @@ static DUD: Lazy<Validation> = Lazy::new(|| {
pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Result<(), Error> { pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Result<(), Error> {
// Log the authentication type // Log the authentication type
trace!(target: LOG, "Attempting token authentication"); trace!("Attempting token authentication");
// Retrieve just the auth data // Retrieve just the auth data
let auth = auth.trim_start_matches(TOKEN).trim(); let auth = auth.trim_start_matches(TOKEN).trim();
// Decode the token without verifying // Decode the token without verifying
@ -91,14 +90,14 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
// Check if the auth token can be used // Check if the auth token can be used
if let Some(nbf) = token.claims.nbf { if let Some(nbf) = token.claims.nbf {
if nbf > Utc::now().timestamp() { if nbf > Utc::now().timestamp() {
trace!(target: LOG, "The 'nbf' field in the authentication token was invalid"); trace!("The 'nbf' field in the authentication token was invalid");
return Err(Error::InvalidAuth); return Err(Error::InvalidAuth);
} }
} }
// Check if the auth token has expired // Check if the auth token has expired
if let Some(exp) = token.claims.exp { if let Some(exp) = token.claims.exp {
if exp < Utc::now().timestamp() { if exp < Utc::now().timestamp() {
trace!(target: LOG, "The 'exp' field in the authentication token was invalid"); trace!("The 'exp' field in the authentication token was invalid");
return Err(Error::InvalidAuth); return Err(Error::InvalidAuth);
} }
} }
@ -114,7 +113,7 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
.. ..
} => { } => {
// Log the decoded authentication claims // Log the decoded authentication claims
trace!(target: LOG, "Authenticating to scope `{}` with token `{}`", sc, tk); trace!("Authenticating to scope `{}` with token `{}`", sc, tk);
// Create a new readonly transaction // Create a new readonly transaction
let mut tx = kvs.transaction(false, false).await?; let mut tx = kvs.transaction(false, false).await?;
// Parse the record id // Parse the record id
@ -128,7 +127,7 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
// Verify the token // Verify the token
decode::<Claims>(auth, &cf.0, &cf.1)?; decode::<Claims>(auth, &cf.0, &cf.1)?;
// Log the success // Log the success
debug!(target: LOG, "Authenticated to scope `{}` with token `{}`", sc, tk); debug!("Authenticated to scope `{}` with token `{}`", sc, tk);
// Set the session // Set the session
session.sd = Some(id); session.sd = Some(id);
session.tk = Some(value); session.tk = Some(value);
@ -147,7 +146,7 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
.. ..
} => { } => {
// Log the decoded authentication claims // Log the decoded authentication claims
trace!(target: LOG, "Authenticating to scope `{}`", sc); trace!("Authenticating to scope `{}`", sc);
// Create a new readonly transaction // Create a new readonly transaction
let mut tx = kvs.transaction(false, false).await?; let mut tx = kvs.transaction(false, false).await?;
// Parse the record id // Parse the record id
@ -158,7 +157,7 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
// Verify the token // Verify the token
decode::<Claims>(auth, &cf.0, &cf.1)?; decode::<Claims>(auth, &cf.0, &cf.1)?;
// Log the success // Log the success
debug!(target: LOG, "Authenticated to scope `{}`", sc); debug!("Authenticated to scope `{}`", sc);
// Set the session // Set the session
session.tk = Some(value); session.tk = Some(value);
session.ns = Some(ns.to_owned()); session.ns = Some(ns.to_owned());
@ -176,7 +175,7 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
.. ..
} => { } => {
// Log the decoded authentication claims // Log the decoded authentication claims
trace!(target: LOG, "Authenticating to database `{}` with token `{}`", db, tk); trace!("Authenticating to database `{}` with token `{}`", db, tk);
// Create a new readonly transaction // Create a new readonly transaction
let mut tx = kvs.transaction(false, false).await?; let mut tx = kvs.transaction(false, false).await?;
// Get the database token // Get the database token
@ -185,7 +184,7 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
// Verify the token // Verify the token
decode::<Claims>(auth, &cf.0, &cf.1)?; decode::<Claims>(auth, &cf.0, &cf.1)?;
// Log the success // Log the success
debug!(target: LOG, "Authenticated to database `{}` with token `{}`", db, tk); debug!("Authenticated to database `{}` with token `{}`", db, tk);
// Set the session // Set the session
session.tk = Some(value); session.tk = Some(value);
session.ns = Some(ns.to_owned()); session.ns = Some(ns.to_owned());
@ -201,7 +200,7 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
.. ..
} => { } => {
// Log the decoded authentication claims // Log the decoded authentication claims
trace!(target: LOG, "Authenticating to database `{}` with login `{}`", db, id); trace!("Authenticating to database `{}` with login `{}`", db, id);
// Create a new readonly transaction // Create a new readonly transaction
let mut tx = kvs.transaction(false, false).await?; let mut tx = kvs.transaction(false, false).await?;
// Get the database login // Get the database login
@ -210,7 +209,7 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
// Verify the token // Verify the token
decode::<Claims>(auth, &cf.0, &cf.1)?; decode::<Claims>(auth, &cf.0, &cf.1)?;
// Log the success // Log the success
debug!(target: LOG, "Authenticated to database `{}` with login `{}`", db, id); debug!("Authenticated to database `{}` with login `{}`", db, id);
// Set the session // Set the session
session.tk = Some(value); session.tk = Some(value);
session.ns = Some(ns.to_owned()); session.ns = Some(ns.to_owned());
@ -225,7 +224,7 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
.. ..
} => { } => {
// Log the decoded authentication claims // Log the decoded authentication claims
trace!(target: LOG, "Authenticating to namespace `{}` with token `{}`", ns, tk); trace!("Authenticating to namespace `{}` with token `{}`", ns, tk);
// Create a new readonly transaction // Create a new readonly transaction
let mut tx = kvs.transaction(false, false).await?; let mut tx = kvs.transaction(false, false).await?;
// Get the namespace token // Get the namespace token
@ -234,7 +233,7 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
// Verify the token // Verify the token
decode::<Claims>(auth, &cf.0, &cf.1)?; decode::<Claims>(auth, &cf.0, &cf.1)?;
// Log the success // Log the success
trace!(target: LOG, "Authenticated to namespace `{}` with token `{}`", ns, tk); trace!("Authenticated to namespace `{}` with token `{}`", ns, tk);
// Set the session // Set the session
session.tk = Some(value); session.tk = Some(value);
session.ns = Some(ns.to_owned()); session.ns = Some(ns.to_owned());
@ -248,7 +247,7 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
.. ..
} => { } => {
// Log the decoded authentication claims // Log the decoded authentication claims
trace!(target: LOG, "Authenticating to namespace `{}` with login `{}`", ns, id); trace!("Authenticating to namespace `{}` with login `{}`", ns, id);
// Create a new readonly transaction // Create a new readonly transaction
let mut tx = kvs.transaction(false, false).await?; let mut tx = kvs.transaction(false, false).await?;
// Get the namespace login // Get the namespace login
@ -257,7 +256,7 @@ pub async fn token(kvs: &Datastore, session: &mut Session, auth: String) -> Resu
// Verify the token // Verify the token
decode::<Claims>(auth, &cf.0, &cf.1)?; decode::<Claims>(auth, &cf.0, &cf.1)?;
// Log the success // Log the success
trace!(target: LOG, "Authenticated to namespace `{}` with login `{}`", ns, id); trace!("Authenticated to namespace `{}` with login `{}`", ns, id);
// Set the session // Set the session
session.tk = Some(value); session.tk = Some(value);
session.ns = Some(ns.to_owned()); session.ns = Some(ns.to_owned());

View file

@ -8,7 +8,6 @@ use crate::dbs::Response;
use crate::dbs::Session; use crate::dbs::Session;
use crate::dbs::Variables; use crate::dbs::Variables;
use crate::err::Error; use crate::err::Error;
use crate::kvs::LOG;
use crate::sql; use crate::sql;
use crate::sql::Query; use crate::sql::Query;
use crate::sql::Value; use crate::sql::Value;
@ -112,9 +111,9 @@ impl Datastore {
"memory" => { "memory" => {
#[cfg(feature = "kv-mem")] #[cfg(feature = "kv-mem")]
{ {
info!(target: LOG, "Starting kvs store in {}", path); info!("Starting kvs store in {}", path);
let v = super::mem::Datastore::new().await.map(Inner::Mem); let v = super::mem::Datastore::new().await.map(Inner::Mem);
info!(target: LOG, "Started kvs store in {}", path); info!("Started kvs store in {}", path);
v v
} }
#[cfg(not(feature = "kv-mem"))] #[cfg(not(feature = "kv-mem"))]
@ -124,11 +123,11 @@ impl Datastore {
s if s.starts_with("file:") => { s if s.starts_with("file:") => {
#[cfg(feature = "kv-rocksdb")] #[cfg(feature = "kv-rocksdb")]
{ {
info!(target: LOG, "Starting kvs store at {}", path); info!("Starting kvs store at {}", path);
let s = s.trim_start_matches("file://"); let s = s.trim_start_matches("file://");
let s = s.trim_start_matches("file:"); let s = s.trim_start_matches("file:");
let v = super::rocksdb::Datastore::new(s).await.map(Inner::RocksDB); let v = super::rocksdb::Datastore::new(s).await.map(Inner::RocksDB);
info!(target: LOG, "Started kvs store at {}", path); info!("Started kvs store at {}", path);
v v
} }
#[cfg(not(feature = "kv-rocksdb"))] #[cfg(not(feature = "kv-rocksdb"))]
@ -138,11 +137,11 @@ impl Datastore {
s if s.starts_with("rocksdb:") => { s if s.starts_with("rocksdb:") => {
#[cfg(feature = "kv-rocksdb")] #[cfg(feature = "kv-rocksdb")]
{ {
info!(target: LOG, "Starting kvs store at {}", path); info!("Starting kvs store at {}", path);
let s = s.trim_start_matches("rocksdb://"); let s = s.trim_start_matches("rocksdb://");
let s = s.trim_start_matches("rocksdb:"); let s = s.trim_start_matches("rocksdb:");
let v = super::rocksdb::Datastore::new(s).await.map(Inner::RocksDB); let v = super::rocksdb::Datastore::new(s).await.map(Inner::RocksDB);
info!(target: LOG, "Started kvs store at {}", path); info!("Started kvs store at {}", path);
v v
} }
#[cfg(not(feature = "kv-rocksdb"))] #[cfg(not(feature = "kv-rocksdb"))]
@ -152,11 +151,11 @@ impl Datastore {
s if s.starts_with("speedb:") => { s if s.starts_with("speedb:") => {
#[cfg(feature = "kv-speedb")] #[cfg(feature = "kv-speedb")]
{ {
info!(target: LOG, "Starting kvs store at {}", path); info!("Starting kvs store at {}", path);
let s = s.trim_start_matches("speedb://"); let s = s.trim_start_matches("speedb://");
let s = s.trim_start_matches("speedb:"); let s = s.trim_start_matches("speedb:");
let v = super::speedb::Datastore::new(s).await.map(Inner::SpeeDB); let v = super::speedb::Datastore::new(s).await.map(Inner::SpeeDB);
info!(target: LOG, "Started kvs store at {}", path); info!("Started kvs store at {}", path);
v v
} }
#[cfg(not(feature = "kv-speedb"))] #[cfg(not(feature = "kv-speedb"))]
@ -166,11 +165,11 @@ impl Datastore {
s if s.starts_with("indxdb:") => { s if s.starts_with("indxdb:") => {
#[cfg(feature = "kv-indxdb")] #[cfg(feature = "kv-indxdb")]
{ {
info!(target: LOG, "Starting kvs store at {}", path); info!("Starting kvs store at {}", path);
let s = s.trim_start_matches("indxdb://"); let s = s.trim_start_matches("indxdb://");
let s = s.trim_start_matches("indxdb:"); let s = s.trim_start_matches("indxdb:");
let v = super::indxdb::Datastore::new(s).await.map(Inner::IndxDB); let v = super::indxdb::Datastore::new(s).await.map(Inner::IndxDB);
info!(target: LOG, "Started kvs store at {}", path); info!("Started kvs store at {}", path);
v v
} }
#[cfg(not(feature = "kv-indxdb"))] #[cfg(not(feature = "kv-indxdb"))]
@ -180,11 +179,11 @@ impl Datastore {
s if s.starts_with("tikv:") => { s if s.starts_with("tikv:") => {
#[cfg(feature = "kv-tikv")] #[cfg(feature = "kv-tikv")]
{ {
info!(target: LOG, "Connecting to kvs store at {}", path); info!("Connecting to kvs store at {}", path);
let s = s.trim_start_matches("tikv://"); let s = s.trim_start_matches("tikv://");
let s = s.trim_start_matches("tikv:"); let s = s.trim_start_matches("tikv:");
let v = super::tikv::Datastore::new(s).await.map(Inner::TiKV); let v = super::tikv::Datastore::new(s).await.map(Inner::TiKV);
info!(target: LOG, "Connected to kvs store at {}", path); info!("Connected to kvs store at {}", path);
v v
} }
#[cfg(not(feature = "kv-tikv"))] #[cfg(not(feature = "kv-tikv"))]
@ -194,11 +193,11 @@ impl Datastore {
s if s.starts_with("fdb:") => { s if s.starts_with("fdb:") => {
#[cfg(feature = "kv-fdb")] #[cfg(feature = "kv-fdb")]
{ {
info!(target: LOG, "Connecting to kvs store at {}", path); info!("Connecting to kvs store at {}", path);
let s = s.trim_start_matches("fdb://"); let s = s.trim_start_matches("fdb://");
let s = s.trim_start_matches("fdb:"); let s = s.trim_start_matches("fdb:");
let v = super::fdb::Datastore::new(s).await.map(Inner::FoundationDB); let v = super::fdb::Datastore::new(s).await.map(Inner::FoundationDB);
info!(target: LOG, "Connected to kvs store at {}", path); info!("Connected to kvs store at {}", path);
v v
} }
#[cfg(not(feature = "kv-fdb"))] #[cfg(not(feature = "kv-fdb"))]
@ -206,7 +205,7 @@ impl Datastore {
} }
// The datastore path is not valid // The datastore path is not valid
_ => { _ => {
info!(target: LOG, "Unable to load the specified datastore {}", path); info!("Unable to load the specified datastore {}", path);
Err(Error::Ds("Unable to load the specified datastore".into())) Err(Error::Ds("Unable to load the specified datastore".into()))
} }
}; };

View file

@ -29,5 +29,3 @@ mod tests;
pub use self::ds::*; pub use self::ds::*;
pub use self::kv::*; pub use self::kv::*;
pub use self::tx::*; pub use self::tx::*;
pub(crate) const LOG: &str = "surrealdb::kvs";

View file

@ -35,9 +35,6 @@ use std::ops::Range;
use std::sync::Arc; use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
#[cfg(debug_assertions)]
const LOG: &str = "surrealdb::txn";
/// A set of undoable updates and requests against a dataset. /// A set of undoable updates and requests against a dataset.
#[allow(dead_code)] #[allow(dead_code)]
pub struct Transaction { pub struct Transaction {
@ -96,7 +93,7 @@ impl Transaction {
/// in a [`Error::TxFinished`] error. /// in a [`Error::TxFinished`] error.
pub async fn closed(&self) -> bool { pub async fn closed(&self) -> bool {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
trace!(target: LOG, "Closed"); trace!("Closed");
match self { match self {
#[cfg(feature = "kv-mem")] #[cfg(feature = "kv-mem")]
Transaction { Transaction {
@ -138,7 +135,7 @@ impl Transaction {
/// This reverses all changes made within the transaction. /// This reverses all changes made within the transaction.
pub async fn cancel(&mut self) -> Result<(), Error> { pub async fn cancel(&mut self) -> Result<(), Error> {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
trace!(target: LOG, "Cancel"); trace!("Cancel");
match self { match self {
#[cfg(feature = "kv-mem")] #[cfg(feature = "kv-mem")]
Transaction { Transaction {
@ -180,7 +177,7 @@ impl Transaction {
/// This attempts to commit all changes made within the transaction. /// This attempts to commit all changes made within the transaction.
pub async fn commit(&mut self) -> Result<(), Error> { pub async fn commit(&mut self) -> Result<(), Error> {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
trace!(target: LOG, "Commit"); trace!("Commit");
match self { match self {
#[cfg(feature = "kv-mem")] #[cfg(feature = "kv-mem")]
Transaction { Transaction {
@ -224,7 +221,7 @@ impl Transaction {
K: Into<Key> + Debug, K: Into<Key> + Debug,
{ {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
trace!(target: LOG, "Del {:?}", key); trace!("Del {:?}", key);
match self { match self {
#[cfg(feature = "kv-mem")] #[cfg(feature = "kv-mem")]
Transaction { Transaction {
@ -268,7 +265,7 @@ impl Transaction {
K: Into<Key> + Debug, K: Into<Key> + Debug,
{ {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
trace!(target: LOG, "Exi {:?}", key); trace!("Exi {:?}", key);
match self { match self {
#[cfg(feature = "kv-mem")] #[cfg(feature = "kv-mem")]
Transaction { Transaction {
@ -312,7 +309,7 @@ impl Transaction {
K: Into<Key> + Debug, K: Into<Key> + Debug,
{ {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
trace!(target: LOG, "Get {:?}", key); trace!("Get {:?}", key);
match self { match self {
#[cfg(feature = "kv-mem")] #[cfg(feature = "kv-mem")]
Transaction { Transaction {
@ -357,7 +354,7 @@ impl Transaction {
V: Into<Val> + Debug, V: Into<Val> + Debug,
{ {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
trace!(target: LOG, "Set {:?} => {:?}", key, val); trace!("Set {:?} => {:?}", key, val);
match self { match self {
#[cfg(feature = "kv-mem")] #[cfg(feature = "kv-mem")]
Transaction { Transaction {
@ -402,7 +399,7 @@ impl Transaction {
V: Into<Val> + Debug, V: Into<Val> + Debug,
{ {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
trace!(target: LOG, "Put {:?} => {:?}", key, val); trace!("Put {:?} => {:?}", key, val);
match self { match self {
#[cfg(feature = "kv-mem")] #[cfg(feature = "kv-mem")]
Transaction { Transaction {
@ -448,7 +445,7 @@ impl Transaction {
K: Into<Key> + Debug, K: Into<Key> + Debug,
{ {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
trace!(target: LOG, "Scan {:?} - {:?}", rng.start, rng.end); trace!("Scan {:?} - {:?}", rng.start, rng.end);
match self { match self {
#[cfg(feature = "kv-mem")] #[cfg(feature = "kv-mem")]
Transaction { Transaction {
@ -493,7 +490,7 @@ impl Transaction {
V: Into<Val> + Debug, V: Into<Val> + Debug,
{ {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
trace!(target: LOG, "Putc {:?} if {:?} => {:?}", key, chk, val); trace!("Putc {:?} if {:?} => {:?}", key, chk, val);
match self { match self {
#[cfg(feature = "kv-mem")] #[cfg(feature = "kv-mem")]
Transaction { Transaction {
@ -538,7 +535,7 @@ impl Transaction {
V: Into<Val> + Debug, V: Into<Val> + Debug,
{ {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
trace!(target: LOG, "Delc {:?} if {:?}", key, chk); trace!("Delc {:?} if {:?}", key, chk);
match self { match self {
#[cfg(feature = "kv-mem")] #[cfg(feature = "kv-mem")]
Transaction { Transaction {

View file

@ -1,7 +1,6 @@
use crate::cli::abstraction::{ use crate::cli::abstraction::{
AuthArguments, DatabaseConnectionArguments, DatabaseSelectionArguments, AuthArguments, DatabaseConnectionArguments, DatabaseSelectionArguments,
}; };
use crate::cli::LOG;
use crate::err::Error; use crate::err::Error;
use clap::Args; use clap::Args;
use surrealdb::engine::any::connect; use surrealdb::engine::any::connect;
@ -57,7 +56,7 @@ pub async fn init(
client.use_ns(ns).use_db(db).await?; client.use_ns(ns).use_db(db).await?;
// Export the data from the database // Export the data from the database
client.export(file).await?; client.export(file).await?;
info!(target: LOG, "The SQL file was exported successfully"); info!("The SQL file was exported successfully");
// Everything OK // Everything OK
Ok(()) Ok(())
} }

View file

@ -1,7 +1,6 @@
use crate::cli::abstraction::{ use crate::cli::abstraction::{
AuthArguments, DatabaseConnectionArguments, DatabaseSelectionArguments, AuthArguments, DatabaseConnectionArguments, DatabaseSelectionArguments,
}; };
use crate::cli::LOG;
use crate::err::Error; use crate::err::Error;
use clap::Args; use clap::Args;
use surrealdb::engine::any::connect; use surrealdb::engine::any::connect;
@ -55,7 +54,7 @@ pub async fn init(
client.use_ns(ns).use_db(db).await?; client.use_ns(ns).use_db(db).await?;
// Import the data into the database // Import the data into the database
client.import(file).await?; client.import(file).await?;
info!(target: LOG, "The SQL file was imported successfully"); info!("The SQL file was imported successfully");
// Everything OK // Everything OK
Ok(()) Ok(())
} }

View file

@ -25,8 +25,6 @@ use sql::SqlCommandArguments;
use start::StartCommandArguments; use start::StartCommandArguments;
use std::process::ExitCode; use std::process::ExitCode;
pub const LOG: &str = "surrealdb::cli";
const INFO: &str = " const INFO: &str = "
To get started using SurrealDB, and for guides on connecting to and building applications To get started using SurrealDB, and for guides on connecting to and building applications
on top of SurrealDB, check out the SurrealDB documentation (https://surrealdb.com/docs). on top of SurrealDB, check out the SurrealDB documentation (https://surrealdb.com/docs).
@ -88,7 +86,7 @@ pub async fn init() -> ExitCode {
Commands::IsReady(args) => isready::init(args).await, Commands::IsReady(args) => isready::init(args).await,
}; };
if let Err(e) = output { if let Err(e) = output {
error!(target: LOG, "{}", e); error!("{}", e);
ExitCode::FAILURE ExitCode::FAILURE
} else { } else {
ExitCode::SUCCESS ExitCode::SUCCESS

View file

@ -8,8 +8,6 @@ use surrealdb::kvs::Datastore;
pub static DB: OnceCell<Datastore> = OnceCell::new(); pub static DB: OnceCell<Datastore> = OnceCell::new();
const LOG: &str = "surrealdb::dbs";
#[derive(Args, Debug)] #[derive(Args, Debug)]
pub struct StartCommandDbsOptions { pub struct StartCommandDbsOptions {
#[arg(help = "The maximum duration of any query")] #[arg(help = "The maximum duration of any query")]
@ -27,8 +25,8 @@ pub async fn init(
let opt = CF.get().unwrap(); let opt = CF.get().unwrap();
// Log authentication options // Log authentication options
match opt.strict { match opt.strict {
true => info!(target: LOG, "Database strict mode is enabled"), true => info!("Database strict mode is enabled"),
false => info!(target: LOG, "Database strict mode is disabled"), false => info!("Database strict mode is disabled"),
}; };
// Parse and setup the desired kv datastore // Parse and setup the desired kv datastore
let dbs = Datastore::new(&opt.path).await?.query_timeout(query_timeout); let dbs = Datastore::new(&opt.path).await?.query_timeout(query_timeout);

5
src/env/mod.rs vendored
View file

@ -3,13 +3,10 @@ use crate::cnf::PKG_VERSION;
use crate::err::Error; use crate::err::Error;
use surrealdb::env::{arch, os}; use surrealdb::env::{arch, os};
#[cfg(feature = "has-storage")]
const LOG: &str = "surrealdb::env";
#[cfg(feature = "has-storage")] #[cfg(feature = "has-storage")]
pub async fn init() -> Result<(), Error> { pub async fn init() -> Result<(), Error> {
// Log version // Log version
info!(target: LOG, "Running {}", release()); info!("Running {}", release());
// All ok // All ok
Ok(()) Ok(())
} }

View file

@ -2,7 +2,6 @@ pub mod verify;
use crate::cli::CF; use crate::cli::CF;
use crate::err::Error; use crate::err::Error;
use surrealdb::iam::LOG;
pub const BASIC: &str = "Basic "; pub const BASIC: &str = "Basic ";
@ -12,10 +11,10 @@ pub async fn init() -> Result<(), Error> {
// Log authentication options // Log authentication options
match opt.pass { match opt.pass {
Some(_) => { Some(_) => {
info!(target: LOG, "Root authentication is enabled"); info!("Root authentication is enabled");
info!(target: LOG, "Root username is '{}'", opt.user); info!("Root username is '{}'", opt.user);
} }
None => info!(target: LOG, "Root authentication is disabled"), None => info!("Root authentication is disabled"),
}; };
// All ok // All ok
Ok(()) Ok(())

View file

@ -8,11 +8,10 @@ use std::sync::Arc;
use surrealdb::dbs::Auth; use surrealdb::dbs::Auth;
use surrealdb::dbs::Session; use surrealdb::dbs::Session;
use surrealdb::iam::base::{Engine, BASE64}; use surrealdb::iam::base::{Engine, BASE64};
use surrealdb::iam::LOG;
pub async fn basic(session: &mut Session, auth: String) -> Result<(), Error> { pub async fn basic(session: &mut Session, auth: String) -> Result<(), Error> {
// Log the authentication type // Log the authentication type
trace!(target: LOG, "Attempting basic authentication"); trace!("Attempting basic authentication");
// Retrieve just the auth data // Retrieve just the auth data
let auth = auth.trim_start_matches(BASIC).trim(); let auth = auth.trim_start_matches(BASIC).trim();
// Get a database reference // Get a database reference
@ -33,7 +32,7 @@ pub async fn basic(session: &mut Session, auth: String) -> Result<(), Error> {
if let Some(root) = &opts.pass { if let Some(root) = &opts.pass {
if user == opts.user && pass == root { if user == opts.user && pass == root {
// Log the authentication type // Log the authentication type
debug!(target: LOG, "Authenticated as super user"); debug!("Authenticated as super user");
// Store the authentication data // Store the authentication data
session.au = Arc::new(Auth::Kv); session.au = Arc::new(Auth::Kv);
return Ok(()); return Ok(());
@ -49,7 +48,7 @@ pub async fn basic(session: &mut Session, auth: String) -> Result<(), Error> {
let hash = PasswordHash::new(&nl.hash).unwrap(); let hash = PasswordHash::new(&nl.hash).unwrap();
if Argon2::default().verify_password(pass.as_ref(), &hash).is_ok() { if Argon2::default().verify_password(pass.as_ref(), &hash).is_ok() {
// Log the successful namespace authentication // Log the successful namespace authentication
debug!(target: LOG, "Authenticated as namespace user: {}", user); debug!("Authenticated as namespace user: {}", user);
// Store the authentication data // Store the authentication data
session.au = Arc::new(Auth::Ns(ns.to_owned())); session.au = Arc::new(Auth::Ns(ns.to_owned()));
return Ok(()); return Ok(());
@ -63,7 +62,7 @@ pub async fn basic(session: &mut Session, auth: String) -> Result<(), Error> {
let hash = PasswordHash::new(&dl.hash).unwrap(); let hash = PasswordHash::new(&dl.hash).unwrap();
if Argon2::default().verify_password(pass.as_ref(), &hash).is_ok() { if Argon2::default().verify_password(pass.as_ref(), &hash).is_ok() {
// Log the successful namespace authentication // Log the successful namespace authentication
debug!(target: LOG, "Authenticated as database user: {}", user); debug!("Authenticated as database user: {}", user);
// Store the authentication data // Store the authentication data
session.au = Arc::new(Auth::Db(ns.to_owned(), db.to_owned())); session.au = Arc::new(Auth::Db(ns.to_owned(), db.to_owned()));
return Ok(()); return Ok(());

View file

@ -13,12 +13,9 @@ impl<T: fmt::Display> fmt::Display for OptFmt<T> {
} }
} }
const NAME: &str = "surrealdb::net";
pub fn write() -> warp::filters::log::Log<impl Fn(warp::filters::log::Info) + Copy> { pub fn write() -> warp::filters::log::Log<impl Fn(warp::filters::log::Info) + Copy> {
warp::log::custom(|info| { warp::log::custom(|info| {
event!( event!(
target: NAME,
Level::INFO, Level::INFO,
"{} {} {} {:?} {} \"{}\" {:?}", "{} {} {} {:?} {} \"{}\" {:?}",
OptFmt(info.remote_addr()), OptFmt(info.remote_addr()),

View file

@ -24,8 +24,6 @@ use crate::cli::CF;
use crate::err::Error; use crate::err::Error;
use warp::Filter; use warp::Filter;
const LOG: &str = "surrealdb::net";
pub async fn init() -> Result<(), Error> { pub async fn init() -> Result<(), Error> {
// Setup web routes // Setup web routes
let net = index::config() let net = index::config()
@ -69,7 +67,7 @@ pub async fn init() -> Result<(), Error> {
// Get local copy of options // Get local copy of options
let opt = CF.get().unwrap(); let opt = CF.get().unwrap();
info!(target: LOG, "Starting web server on {}", &opt.bind); info!("Starting web server on {}", &opt.bind);
if let (Some(c), Some(k)) = (&opt.crt, &opt.key) { if let (Some(c), Some(k)) = (&opt.crt, &opt.key) {
// Bind the server to the desired port // Bind the server to the desired port
@ -80,27 +78,27 @@ pub async fn init() -> Result<(), Error> {
.bind_with_graceful_shutdown(opt.bind, async move { .bind_with_graceful_shutdown(opt.bind, async move {
// Capture the shutdown signals and log that the graceful shutdown has started // Capture the shutdown signals and log that the graceful shutdown has started
let result = signals::listen().await.expect("Failed to listen to shutdown signal"); let result = signals::listen().await.expect("Failed to listen to shutdown signal");
info!(target: LOG, "{} received. Start graceful shutdown...", result); info!("{} received. Start graceful shutdown...", result);
}); });
// Log the server startup status // Log the server startup status
info!(target: LOG, "Started web server on {}", &adr); info!("Started web server on {}", &adr);
// Run the server forever // Run the server forever
srv.await; srv.await;
// Log the server shutdown event // Log the server shutdown event
info!(target: LOG, "Shutdown complete. Bye!") info!("Shutdown complete. Bye!")
} else { } else {
// Bind the server to the desired port // Bind the server to the desired port
let (adr, srv) = warp::serve(net).bind_with_graceful_shutdown(opt.bind, async move { let (adr, srv) = warp::serve(net).bind_with_graceful_shutdown(opt.bind, async move {
// Capture the shutdown signals and log that the graceful shutdown has started // Capture the shutdown signals and log that the graceful shutdown has started
let result = signals::listen().await.expect("Failed to listen to shutdown signal"); let result = signals::listen().await.expect("Failed to listen to shutdown signal");
info!(target: LOG, "{} received. Start graceful shutdown...", result); info!("{} received. Start graceful shutdown...", result);
}); });
// Log the server startup status // Log the server startup status
info!(target: LOG, "Started web server on {}", &adr); info!("Started web server on {}", &adr);
// Run the server forever // Run the server forever
srv.await; srv.await;
// Log the server shutdown event // Log the server shutdown event
info!(target: LOG, "Shutdown complete. Bye!") info!("Shutdown complete. Bye!")
}; };
Ok(()) Ok(())

View file

@ -6,7 +6,6 @@ use crate::cnf::WEBSOCKET_PING_FREQUENCY;
use crate::dbs::DB; use crate::dbs::DB;
use crate::err::Error; use crate::err::Error;
use crate::net::session; use crate::net::session;
use crate::net::LOG;
use crate::rpc::args::Take; use crate::rpc::args::Take;
use crate::rpc::paths::{ID, METHOD, PARAMS}; use crate::rpc::paths::{ID, METHOD, PARAMS};
use crate::rpc::res; use crate::rpc::res;
@ -114,7 +113,7 @@ impl Rpc {
// Send the message to the client // Send the message to the client
if let Err(err) = wtx.send(res).await { if let Err(err) = wtx.send(res).await {
// Output the WebSocket error to the logs // Output the WebSocket error to the logs
trace!(target: LOG, "WebSocket error: {:?}", err); trace!("WebSocket error: {:?}", err);
// It's already failed, so ignore error // It's already failed, so ignore error
let _ = wtx.close().await; let _ = wtx.close().await;
// Exit out of the loop // Exit out of the loop
@ -127,7 +126,7 @@ impl Rpc {
tokio::task::spawn(async move { tokio::task::spawn(async move {
let rpc = moved_rpc; let rpc = moved_rpc;
while let Ok(v) = DB.get().unwrap().notifications().recv().await { while let Ok(v) = DB.get().unwrap().notifications().recv().await {
trace!(target: LOG, "Received notification: {:?}", v); trace!("Received notification: {:?}", v);
// Find which websocket the notification belongs to // Find which websocket the notification belongs to
match LIVE_QUERIES.read().await.get(&v.id) { match LIVE_QUERIES.read().await.get(&v.id) {
Some(ws_id) => { Some(ws_id) => {
@ -137,8 +136,8 @@ impl Rpc {
match ws_write.get(ws_id) { match ws_write.get(ws_id) {
None => { None => {
error!( error!(
target: LOG, "Tracked WebSocket {:?} not found for lq: {:?}",
"Tracked WebSocket {:?} not found for lq: {:?}", ws_id, &v.id ws_id, &v.id
); );
} }
Some(ws_sender) => { Some(ws_sender) => {
@ -146,7 +145,6 @@ impl Rpc {
.send(rpc.read().await.format.clone(), ws_sender.clone()) .send(rpc.read().await.format.clone(), ws_sender.clone())
.await; .await;
trace!( trace!(
target: LOG,
"Sent notification to WebSocket {:?} for lq: {:?}", "Sent notification to WebSocket {:?} for lq: {:?}",
ws_id, ws_id,
&v.id &v.id
@ -155,7 +153,7 @@ impl Rpc {
} }
} }
None => { None => {
error!(target: LOG, "Unknown websocket for live query: {:?}", v.id); error!("Unknown websocket for live query: {:?}", v.id);
} }
} }
} }
@ -187,7 +185,7 @@ impl Rpc {
// There was an error receiving the message // There was an error receiving the message
Err(err) => { Err(err) => {
// Output the WebSocket error to the logs // Output the WebSocket error to the logs
trace!(target: LOG, "WebSocket error: {:?}", err); trace!("WebSocket error: {:?}", err);
// Exit out of the loop // Exit out of the loop
break; break;
} }
@ -201,7 +199,7 @@ impl Rpc {
// Fetch the unique id of the WebSocket // Fetch the unique id of the WebSocket
let id = rpc.read().await.uuid; let id = rpc.read().await.uuid;
// Log that the WebSocket has connected // Log that the WebSocket has connected
trace!(target: LOG, "WebSocket {} connected", id); trace!("WebSocket {} connected", id);
// Store this WebSocket in the list of WebSockets // Store this WebSocket in the list of WebSockets
WEBSOCKETS.write().await.insert(id, chn); WEBSOCKETS.write().await.insert(id, chn);
} }
@ -210,7 +208,7 @@ impl Rpc {
// Fetch the unique id of the WebSocket // Fetch the unique id of the WebSocket
let id = rpc.read().await.uuid; let id = rpc.read().await.uuid;
// Log that the WebSocket has disconnected // Log that the WebSocket has disconnected
trace!(target: LOG, "WebSocket {} disconnected", id); trace!("WebSocket {} disconnected", id);
// Remove this WebSocket from the list of WebSockets // Remove this WebSocket from the list of WebSockets
WEBSOCKETS.write().await.remove(&id); WEBSOCKETS.write().await.remove(&id);
// Remove all live queries // Remove all live queries
@ -218,7 +216,7 @@ impl Rpc {
let mut live_query_to_gc: Vec<Uuid> = vec![]; let mut live_query_to_gc: Vec<Uuid> = vec![];
for (key, value) in locked_lq_map.iter() { for (key, value) in locked_lq_map.iter() {
if value == &id { if value == &id {
trace!(target: LOG, "Removing live query: {}", key); trace!("Removing live query: {}", key);
live_query_to_gc.push(*key); live_query_to_gc.push(*key);
} }
} }
@ -258,7 +256,7 @@ impl Rpc {
_ => return res::failure(None, Failure::INTERNAL_ERROR).send(out, chn).await, _ => return res::failure(None, Failure::INTERNAL_ERROR).send(out, chn).await,
}; };
// Log the received request // Log the received request
trace!(target: LOG, "RPC Received: {}", req); trace!("RPC Received: {}", req);
// Fetch the 'id' argument // Fetch the 'id' argument
let id = match req.pick(&*ID) { let id = match req.pick(&*ID) {
v if v.is_none() => None, v if v.is_none() => None,
@ -742,24 +740,14 @@ impl Rpc {
if let Ok(Value::Uuid(lqid)) = &res.result { if let Ok(Value::Uuid(lqid)) = &res.result {
// Match on Uuid type // Match on Uuid type
LIVE_QUERIES.write().await.insert(lqid.0, self.uuid); LIVE_QUERIES.write().await.insert(lqid.0, self.uuid);
trace!( trace!("Registered live query {} on websocket {}", lqid, self.uuid);
target: LOG,
"Registered live query {} on websocket {}",
lqid,
self.uuid
);
} }
} }
QueryType::Kill => { QueryType::Kill => {
if let Ok(Value::Uuid(lqid)) = &res.result { if let Ok(Value::Uuid(lqid)) = &res.result {
let ws_id = LIVE_QUERIES.write().await.remove(&lqid.0); let ws_id = LIVE_QUERIES.write().await.remove(&lqid.0);
if let Some(ws_id) = ws_id { if let Some(ws_id) = ws_id {
trace!( trace!("Unregistered live query {} on websocket {}", lqid, ws_id);
target: LOG,
"Unregistered live query {} on websocket {}",
lqid,
ws_id
);
} }
} }
} }

View file

@ -9,8 +9,6 @@ use surrealdb::sql::Value;
use tracing::instrument; use tracing::instrument;
use warp::ws::Message; use warp::ws::Message;
const LOG: &str = "surrealdb::rpc::res";
#[derive(Clone)] #[derive(Clone)]
pub enum Output { pub enum Output {
Json, // JSON Json, // JSON
@ -105,7 +103,7 @@ impl Response {
} }
}; };
let _ = chn.send(message).await; let _ = chn.send(message).await;
trace!(target: LOG, "Response sent"); trace!("Response sent");
} }
} }