use relate_core::{ArithmeticFailure, Error};
pub const SYNTAX_ERROR_CODE: &str = "Neo.ClientError.Statement.SyntaxError";
pub const PROCEDURE_NOT_FOUND_CODE: &str = "Neo.ClientError.Procedure.ProcedureNotFound";
pub const PARAMETER_MISSING_CODE: &str = "Neo.ClientError.Statement.ParameterMissing";
pub const DATABASE_NOT_FOUND_CODE: &str = "Neo.ClientError.Database.DatabaseNotFound";
pub const SEMANTIC_ERROR_CODE: &str = "Neo.ClientError.Statement.SemanticError";
pub const TYPE_ERROR_CODE: &str = "Neo.ClientError.Statement.TypeError";
pub const ARGUMENT_ERROR_CODE: &str = "Neo.ClientError.General.InvalidArguments";
pub const ARGUMENT_VALUE_ERROR_CODE: &str = "Neo.ClientError.Statement.ArgumentError";
pub const ARITHMETIC_ERROR_CODE: &str = "Neo.ClientError.Statement.ArithmeticError";
pub const CONSTRAINT_VALIDATION_FAILED_CODE: &str =
"Neo.ClientError.Schema.ConstraintValidationFailed";
pub const TRANSACTION_TIMED_OUT_CODE: &str = "Neo.ClientError.Transaction.TransactionTimedOut";
pub const OUTDATED_CODE: &str = "Neo.TransientError.Transaction.Outdated";
pub const TRANSACTION_OUT_OF_MEMORY_CODE: &str =
"Neo.ClientError.General.TransactionOutOfMemoryError";
pub const MEMORY_POOL_OUT_OF_MEMORY_CODE: &str =
"Neo.TransientError.General.MemoryPoolOutOfMemoryError";
pub const UNKNOWN_ERROR_CODE: &str = "Neo.DatabaseError.General.UnknownError";
pub const GQLSTATUS_GENERAL: &str = "42000";
pub const GQLSTATUS_SYNTAX: &str = "42N06";
const GQLSTATUS_PARAMETER_MISSING: &str = "42N02";
const GQLSTATUS_TYPE: &str = "22G03";
pub const GQLSTATUS_DATABASE_NOT_FOUND: &str = "42N00";
const GQLSTATUS_UNSUPPORTED_ADMINISTRATION_COMMAND: &str = "51N27";
const GQLSTATUS_WRITE_ON_READ_ONLY: &str = "42N18";
const GQLSTATUS_INTERNAL: &str = "50N42";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorStage {
Compile,
Runtime,
Internal,
}
impl ErrorStage {
pub fn as_str(self) -> &'static str {
match self {
ErrorStage::Compile => "compile",
ErrorStage::Runtime => "runtime",
ErrorStage::Internal => "internal",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ErrorInfo {
pub neo4j_code: &'static str,
pub gql_status: &'static str,
pub stage: ErrorStage,
pub retryable: bool,
}
pub fn client_message(e: &Error) -> std::borrow::Cow<'_, str> {
match error_info(e).stage {
ErrorStage::Compile | ErrorStage::Runtime => std::borrow::Cow::Owned(e.to_string()),
ErrorStage::Internal => std::borrow::Cow::Borrowed(INTERNAL_MESSAGE),
}
}
pub fn log_internal_original(e: &Error, boundary: &str) {
if let ErrorStage::Internal = error_info(e).stage {
eprintln!("{boundary} internal error: {e}");
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NestedErrorClass {
ConstraintVerificationFailed,
ArgumentError,
EntityNotFound,
ProcedureError,
SyntaxError,
SemanticError,
UnsupportedAdministrationCommand,
WriteOnReadOnlyAccessDatabase,
DatabaseNotFound,
TransactionError,
}
impl NestedErrorClass {
pub(crate) const ALL: [NestedErrorClass; 10] = [
NestedErrorClass::ConstraintVerificationFailed,
NestedErrorClass::ArgumentError,
NestedErrorClass::EntityNotFound,
NestedErrorClass::ProcedureError,
NestedErrorClass::SyntaxError,
NestedErrorClass::SemanticError,
NestedErrorClass::UnsupportedAdministrationCommand,
NestedErrorClass::WriteOnReadOnlyAccessDatabase,
NestedErrorClass::DatabaseNotFound,
NestedErrorClass::TransactionError,
];
pub fn as_str(self) -> &'static str {
match self {
NestedErrorClass::ConstraintVerificationFailed => "ConstraintVerificationFailed",
NestedErrorClass::ArgumentError => "ArgumentError",
NestedErrorClass::EntityNotFound => "EntityNotFound",
NestedErrorClass::ProcedureError => "ProcedureError",
NestedErrorClass::SyntaxError => "SyntaxError",
NestedErrorClass::SemanticError => "SemanticError",
NestedErrorClass::UnsupportedAdministrationCommand => {
"UnsupportedAdministrationCommand"
}
NestedErrorClass::WriteOnReadOnlyAccessDatabase => "WriteOnReadOnlyAccessDatabase",
NestedErrorClass::DatabaseNotFound => "DatabaseNotFound",
NestedErrorClass::TransactionError => "TransactionError",
}
}
}
pub fn nested_error_class(payload: &str) -> Option<NestedErrorClass> {
if payload.contains("ConstraintValidationFailed:")
|| payload.contains("ConstraintVerificationFailed:")
{
return Some(NestedErrorClass::ConstraintVerificationFailed);
}
let name = payload.split_once(':').map(|(name, _)| name.trim())?;
NestedErrorClass::ALL
.into_iter()
.find(|&class| class.as_str() == name)
}
fn stringly_gql_status(payload: &str, own: &'static str) -> &'static str {
match nested_error_class(payload) {
None => own,
Some(NestedErrorClass::DatabaseNotFound) => GQLSTATUS_DATABASE_NOT_FOUND,
Some(NestedErrorClass::UnsupportedAdministrationCommand) => {
GQLSTATUS_UNSUPPORTED_ADMINISTRATION_COMMAND
}
Some(NestedErrorClass::WriteOnReadOnlyAccessDatabase) => GQLSTATUS_WRITE_ON_READ_ONLY,
Some(NestedErrorClass::SyntaxError) => GQLSTATUS_SYNTAX,
Some(
NestedErrorClass::ConstraintVerificationFailed
| NestedErrorClass::ArgumentError
| NestedErrorClass::EntityNotFound
| NestedErrorClass::ProcedureError
| NestedErrorClass::SemanticError
| NestedErrorClass::TransactionError,
) => GQLSTATUS_GENERAL,
}
}
pub const INTERNAL_MESSAGE: &str = "internal error";
pub const INTERNAL_ERROR_INFO: ErrorInfo = ErrorInfo {
neo4j_code: UNKNOWN_ERROR_CODE,
gql_status: GQLSTATUS_INTERNAL,
stage: ErrorStage::Internal,
retryable: false,
};
pub fn error_info(e: &Error) -> ErrorInfo {
use ErrorStage::{Compile, Runtime};
match e {
Error::Syntax(payload) => ErrorInfo {
neo4j_code: SYNTAX_ERROR_CODE,
gql_status: stringly_gql_status(payload, GQLSTATUS_SYNTAX),
stage: Compile,
retryable: false,
},
Error::ProcedureNotFound { .. } => ErrorInfo {
neo4j_code: PROCEDURE_NOT_FOUND_CODE,
gql_status: GQLSTATUS_SYNTAX,
stage: Compile,
retryable: false,
},
Error::ParameterMissing(_) => ErrorInfo {
neo4j_code: PARAMETER_MISSING_CODE,
gql_status: GQLSTATUS_PARAMETER_MISSING,
stage: Compile,
retryable: false,
},
Error::DatabaseNotFound { .. } => ErrorInfo {
neo4j_code: DATABASE_NOT_FOUND_CODE,
gql_status: GQLSTATUS_DATABASE_NOT_FOUND,
stage: Compile,
retryable: false,
},
Error::ArgumentError(_) => ErrorInfo {
neo4j_code: ARGUMENT_ERROR_CODE,
gql_status: GQLSTATUS_GENERAL,
stage: Compile,
retryable: false,
},
Error::ArgumentValue { .. } => ErrorInfo {
neo4j_code: ARGUMENT_VALUE_ERROR_CODE,
gql_status: GQLSTATUS_GENERAL,
stage: Runtime,
retryable: false,
},
Error::Type(_) | Error::TypeError(_) | Error::InvalidArgumentType(_) => ErrorInfo {
neo4j_code: TYPE_ERROR_CODE,
gql_status: GQLSTATUS_TYPE,
stage: Runtime,
retryable: false,
},
Error::Arithmetic(ArithmeticFailure::DivisionByZero | ArithmeticFailure::ModuloByZero) => {
ErrorInfo {
neo4j_code: ARITHMETIC_ERROR_CODE,
gql_status: GQLSTATUS_TYPE,
stage: Runtime,
retryable: false,
}
}
Error::Arithmetic(ArithmeticFailure::RoundingNecessary) => ErrorInfo {
neo4j_code: ARITHMETIC_ERROR_CODE,
gql_status: GQLSTATUS_GENERAL,
stage: Runtime,
retryable: false,
},
Error::UniquenessViolation { .. } => ErrorInfo {
neo4j_code: CONSTRAINT_VALIDATION_FAILED_CODE,
gql_status: GQLSTATUS_GENERAL,
stage: Runtime,
retryable: false,
},
Error::Cancelled => ErrorInfo {
neo4j_code: TRANSACTION_TIMED_OUT_CODE,
gql_status: GQLSTATUS_GENERAL,
stage: Runtime,
retryable: false,
},
Error::Conflict => ErrorInfo {
neo4j_code: OUTDATED_CODE,
gql_status: GQLSTATUS_GENERAL,
stage: Runtime,
retryable: true,
},
Error::Capacity { .. } => ErrorInfo {
neo4j_code: TRANSACTION_OUT_OF_MEMORY_CODE,
gql_status: GQLSTATUS_GENERAL,
stage: Runtime,
retryable: false,
},
Error::ResourceLimit { retryable, .. } => ErrorInfo {
neo4j_code: if *retryable {
MEMORY_POOL_OUT_OF_MEMORY_CODE
} else {
TRANSACTION_OUT_OF_MEMORY_CODE
},
gql_status: GQLSTATUS_GENERAL,
stage: Runtime,
retryable: *retryable,
},
Error::Semantic(payload) | Error::Execution(payload) => ErrorInfo {
neo4j_code: SEMANTIC_ERROR_CODE,
gql_status: stringly_gql_status(payload, GQLSTATUS_GENERAL),
stage: Runtime,
retryable: false,
},
Error::Internal(_) => INTERNAL_ERROR_INFO,
Error::Storage(_) | Error::Io(_) | Error::Locked(_) => ErrorInfo {
gql_status: GQLSTATUS_GENERAL,
..INTERNAL_ERROR_INFO
},
}
}
#[cfg(test)]
mod tests {
use super::*;
use relate_core::ErrorKind;
use ErrorStage::{Compile, Internal, Runtime};
#[test]
fn internal_error_info_is_error_infos_internal_row() {
assert_eq!(
error_info(&Error::Internal(String::new())),
INTERNAL_ERROR_INFO
);
}
#[test]
fn every_engine_variant_carries_its_adr_0307_code_and_stage() {
let rows: Vec<(Error, &str, ErrorStage)> = vec![
(Error::syntax("parse error"), SYNTAX_ERROR_CODE, Compile),
(
Error::procedure_not_found("dbms.noSuchProc"),
PROCEDURE_NOT_FOUND_CODE,
Compile,
),
(
Error::parameters_missing(["p"]),
PARAMETER_MISSING_CODE,
Compile,
),
(
Error::database_not_found("nosuchdb"),
DATABASE_NOT_FOUND_CODE,
Compile,
),
(
Error::argument_error("bad options"),
ARGUMENT_ERROR_CODE,
Compile,
),
(
Error::argument_value_kind(ErrorKind::NumberOutOfRange, "range() step"),
ARGUMENT_VALUE_ERROR_CODE,
Runtime,
),
(Error::ty("expected number"), TYPE_ERROR_CODE, Runtime),
(Error::type_error("x"), TYPE_ERROR_CODE, Runtime),
(Error::invalid_argument_type("x"), TYPE_ERROR_CODE, Runtime),
(
Error::arithmetic(ArithmeticFailure::DivisionByZero),
ARITHMETIC_ERROR_CODE,
Runtime,
),
(
Error::arithmetic(ArithmeticFailure::ModuloByZero),
ARITHMETIC_ERROR_CODE,
Runtime,
),
(
Error::arithmetic(ArithmeticFailure::RoundingNecessary),
ARITHMETIC_ERROR_CODE,
Runtime,
),
(
Error::uniqueness_violation("p_id"),
CONSTRAINT_VALIDATION_FAILED_CODE,
Runtime,
),
(Error::cancelled(), TRANSACTION_TIMED_OUT_CODE, Runtime),
(Error::conflict(), OUTDATED_CODE, Runtime),
(
Error::capacity(7, 5),
TRANSACTION_OUT_OF_MEMORY_CODE,
Runtime,
),
(
Error::capacity_wal_payload(67_108_864, Error::WAL_PAYLOAD_CAP_BYTES),
TRANSACTION_OUT_OF_MEMORY_CODE,
Runtime,
),
(
Error::resource_limit(Error::CONCURRENT_LOGICAL_WORKSPACE_LIMIT, 16, true),
MEMORY_POOL_OUT_OF_MEMORY_CODE,
Runtime,
),
(
Error::resource_limit(Error::CONCURRENT_LOGICAL_WORKSPACE_LIMIT, 16, false),
TRANSACTION_OUT_OF_MEMORY_CODE,
Runtime,
),
(
Error::semantic("variable `n` not defined"),
SEMANTIC_ERROR_CODE,
Runtime,
),
(
Error::execution("node ID exhausted"),
SEMANTIC_ERROR_CODE,
Runtime,
),
(Error::internal("boom"), UNKNOWN_ERROR_CODE, Internal),
(Error::storage("/x"), UNKNOWN_ERROR_CODE, Internal),
(Error::io("os error 2"), UNKNOWN_ERROR_CODE, Internal),
(Error::Locked("/x".into()), UNKNOWN_ERROR_CODE, Internal),
];
for (e, code, stage) in rows {
let i = error_info(&e);
assert_eq!(i.neo4j_code, code, "{e}");
assert_eq!(i.stage, stage, "{e}");
}
}
#[test]
fn only_the_transient_classes_are_retryable() {
let retryable = [
Error::conflict(),
Error::resource_limit(Error::CONCURRENT_LOGICAL_WORKSPACE_LIMIT, 16, true),
];
let not_retryable = [
Error::syntax("x"),
Error::semantic("x"),
Error::argument_error("x"),
Error::parameter_missing("x"),
Error::database_not_found("x"),
Error::ty("x"),
Error::arithmetic(ArithmeticFailure::RoundingNecessary),
Error::uniqueness_violation("u"),
Error::cancelled(),
Error::capacity(7, 5),
Error::resource_limit(Error::CONCURRENT_LOGICAL_WORKSPACE_LIMIT, 16, false),
Error::execution("x"),
Error::internal("x"),
Error::storage("x"),
Error::io("x"),
Error::Locked("x".into()),
];
for e in &retryable {
let i = error_info(e);
assert!(i.retryable, "{e}");
}
for e in ¬_retryable {
let i = error_info(e);
assert!(!i.retryable, "{e}");
}
}
#[test]
fn gql_status_is_the_code_the_surfaces_emit_today() {
let rows: Vec<(Error, &str)> = vec![
(Error::syntax("bad query"), GQLSTATUS_SYNTAX),
(Error::syntax("ProcedureNotFound: dbms.x"), GQLSTATUS_SYNTAX),
(Error::procedure_not_found("dbms.x"), GQLSTATUS_SYNTAX),
(Error::parameter_missing("p"), GQLSTATUS_PARAMETER_MISSING),
(
Error::database_not_found("movies"),
GQLSTATUS_DATABASE_NOT_FOUND,
),
(
Error::argument_error("InvalidIndexConfig"),
GQLSTATUS_GENERAL,
),
(
Error::argument_value_kind(ErrorKind::NumberOutOfRange, "range() step"),
GQLSTATUS_GENERAL,
),
(Error::ty("x"), GQLSTATUS_TYPE),
(Error::type_error("x"), GQLSTATUS_TYPE),
(Error::invalid_argument_type("x"), GQLSTATUS_TYPE),
(
Error::arithmetic(ArithmeticFailure::DivisionByZero),
GQLSTATUS_TYPE,
),
(
Error::arithmetic(ArithmeticFailure::RoundingNecessary),
GQLSTATUS_GENERAL,
),
(Error::uniqueness_violation("u"), GQLSTATUS_GENERAL),
(Error::cancelled(), GQLSTATUS_GENERAL),
(Error::conflict(), GQLSTATUS_GENERAL),
(Error::capacity(7, 5), GQLSTATUS_GENERAL),
(
Error::resource_limit(Error::CONCURRENT_LOGICAL_WORKSPACE_LIMIT, 16, true),
GQLSTATUS_GENERAL,
),
(
Error::semantic("variable `n` not defined"),
GQLSTATUS_GENERAL,
),
(Error::execution("node ID exhausted"), GQLSTATUS_GENERAL),
(Error::internal("boom"), GQLSTATUS_INTERNAL),
(Error::storage("/x"), GQLSTATUS_GENERAL),
(Error::io("os error 2"), GQLSTATUS_GENERAL),
(Error::Locked("/x".into()), GQLSTATUS_GENERAL),
];
for (e, status) in rows {
let i = error_info(&e);
assert_eq!(i.gql_status, status, "{e}");
}
}
#[test]
fn a_nested_class_token_carries_its_own_gql_status() {
let rows: Vec<(Error, &str)> = vec![
(
Error::semantic("WriteOnReadOnlyAccessDatabase: No write operations are allowed"),
GQLSTATUS_WRITE_ON_READ_ONLY,
),
(
Error::semantic("UnsupportedAdministrationCommand: CREATE DATABASE foo"),
GQLSTATUS_UNSUPPORTED_ADMINISTRATION_COMMAND,
),
(
Error::semantic("DatabaseNotFound: Graph not found: movies"),
GQLSTATUS_DATABASE_NOT_FOUND,
),
(
Error::execution("ConstraintVerificationFailed: duplicate"),
GQLSTATUS_GENERAL,
),
(Error::syntax("ArgumentError: x"), GQLSTATUS_GENERAL),
(Error::semantic("SyntaxError: x"), GQLSTATUS_SYNTAX),
(
Error::execution("while running: InvalidArgumentType: q"),
GQLSTATUS_GENERAL,
),
(
Error::syntax("TypeError: not the typed class"),
GQLSTATUS_SYNTAX,
),
];
for (e, status) in rows {
let i = error_info(&e);
assert_eq!(i.gql_status, status, "{e}");
}
}
#[test]
fn nested_error_class_recovers_the_embedded_names() {
assert_eq!(
nested_error_class("ArgumentError: x"),
Some(NestedErrorClass::ArgumentError)
);
assert_eq!(
nested_error_class("outer context: ConstraintVerificationFailed: duplicate key"),
Some(NestedErrorClass::ConstraintVerificationFailed)
);
assert_eq!(
nested_error_class("outer: ConstraintValidationFailed: bad"),
Some(NestedErrorClass::ConstraintVerificationFailed)
);
assert_eq!(nested_error_class("no class here"), None);
assert_eq!(nested_error_class("nested ParameterMissing: p"), None);
assert_eq!(nested_error_class(""), None);
}
#[test]
fn every_nested_class_renders_its_embedded_token() {
for class in NestedErrorClass::ALL {
let token = class.as_str();
let scanned = nested_error_class(&format!("{token}: x"))
.unwrap_or_else(|| panic!("token {token} not recognized by the scan"));
assert_eq!(scanned.as_str(), token);
}
}
}