From 400c6a209f9017674ec797578569d1a38ecaed7e Mon Sep 17 00:00:00 2001 From: Dmitrii Ubskii <18616863+dmitrii-ubskii@users.noreply.github.com> Date: Tue, 12 Nov 2024 11:51:54 +0000 Subject: [PATCH 1/4] update dependencies and commit generated manifests --- .gitignore | 1 - Cargo.toml | 5 + c/Cargo.toml | 39 +++++++ dependencies/vaticle/repositories.bzl | 8 +- rust/Cargo.toml | 144 +++++++++++++++++++++++++ rust/tests/behaviour/config/Cargo.toml | 16 +++ rust/tests/behaviour/steps/Cargo.toml | 74 +++++++++++++ tool/ide/rust/sync.sh | 2 +- 8 files changed, 283 insertions(+), 6 deletions(-) create mode 100644 Cargo.toml create mode 100644 c/Cargo.toml create mode 100644 rust/Cargo.toml create mode 100644 rust/tests/behaviour/config/Cargo.toml create mode 100644 rust/tests/behaviour/steps/Cargo.toml diff --git a/.gitignore b/.gitignore index 0609a1d10d..3d9246741a 100644 --- a/.gitignore +++ b/.gitignore @@ -96,7 +96,6 @@ venv # Cargo files # Cargo.lock -Cargo.toml # Temporary paket files for C# # paket-files/ diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000000..fb8e755a48 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,5 @@ + +[workspace] + resolver = "2" + members = ["rust", "rust/tests/behaviour/config", "rust/tests/behaviour/steps", "c"] + diff --git a/c/Cargo.toml b/c/Cargo.toml new file mode 100644 index 0000000000..06b1251f88 --- /dev/null +++ b/c/Cargo.toml @@ -0,0 +1,39 @@ + +# Generated by Vaticle Cargo sync tool. + +features = {} + +[package] + name = "typedb_driver_clib" + edition = "2021" + version = "0.0.0" + +[lib] + path = "src/lib.rs" + +[dependencies] + + [dependencies.env_logger] + features = ["auto-color", "color", "default", "humantime", "regex"] + version = "0.10.2" + default-features = false + + [dependencies.log] + features = ["kv", "kv_unstable", "std", "value-bag"] + version = "0.4.22" + default-features = false + + [dependencies.typedb-driver] + path = "../rust" + features = ["sync"] + + [dependencies.chrono] + features = ["alloc", "android-tzdata", "clock", "default", "iana-time-zone", "js-sys", "now", "oldtime", "serde", "std", "wasm-bindgen", "wasmbind", "winapi", "windows-targets"] + version = "0.4.38" + default-features = false + + [dependencies.itertools] + features = ["default", "use_alloc", "use_std"] + version = "0.10.5" + default-features = false + diff --git a/dependencies/vaticle/repositories.bzl b/dependencies/vaticle/repositories.bzl index f22a37a281..b73e1b9213 100644 --- a/dependencies/vaticle/repositories.bzl +++ b/dependencies/vaticle/repositories.bzl @@ -20,15 +20,15 @@ load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository") def vaticle_dependencies(): git_repository( name = "vaticle_dependencies", - remote = "https://github.com/typedb/dependencies", - commit = "2acdb27e8f0139e1535855328396654535472703", # sync-marker: do not remove this comment, this is used for sync-dependencies by @vaticle_dependencies + remote = "https://github.com/dmitrii-ubskii/dependencies", + commit = "b4d8e026b06e2ea0d7c461b1b09fba81111c8d76", # sync-marker: do not remove this comment, this is used for sync-dependencies by @vaticle_dependencies ) def vaticle_typedb_protocol(): git_repository( name = "vaticle_typedb_protocol", - remote = "https://github.com/typedb/typedb-protocol", - tag = "3.0.0-alpha-7", # sync-marker: do not remove this comment, this is used for sync-dependencies by @vaticle_typedb_protocol + remote = "https://github.com/dmitrii-ubskii/typedb-protocol", + commit = "71d7975a4617bb142015d27deaa3f8e886c00f0f", # sync-marker: do not remove this comment, this is used for sync-dependencies by @vaticle_typedb_protocol ) def vaticle_typedb_behaviour(): diff --git a/rust/Cargo.toml b/rust/Cargo.toml new file mode 100644 index 0000000000..6f14444efd --- /dev/null +++ b/rust/Cargo.toml @@ -0,0 +1,144 @@ + +# Generated by Vaticle Cargo sync tool. + + +[features] + default = [] + sync = [] + +[package] + name = "typedb-driver" + edition = "2021" + version = "0.0.0" + +[lib] + path = "src/lib.rs" + +[dev-dependencies] + + [dev-dependencies.smol] + features = [] + version = "1.3.0" + default-features = false + + [dev-dependencies.regex] + features = ["default", "perf", "perf-backtrack", "perf-cache", "perf-dfa", "perf-inline", "perf-literal", "perf-onepass", "std", "unicode", "unicode-age", "unicode-bool", "unicode-case", "unicode-gencat", "unicode-perl", "unicode-script", "unicode-segment"] + version = "1.10.6" + default-features = false + + [dev-dependencies.async-std] + features = ["alloc", "async-attributes", "async-channel", "async-global-executor", "async-io", "async-lock", "attributes", "crossbeam-utils", "default", "futures-channel", "futures-core", "futures-io", "futures-lite", "gloo-timers", "kv-log-macro", "log", "memchr", "once_cell", "pin-project-lite", "pin-utils", "slab", "std", "wasm-bindgen-futures"] + version = "1.13.0" + default-features = false + + [dev-dependencies.steps] + path = "../rust/tests/behaviour/steps" + features = [] + + [dev-dependencies.config] + path = "../rust/tests/behaviour/config" + features = ["bazel"] + + [dev-dependencies.serial_test] + features = ["async", "default", "futures", "log", "logging"] + version = "0.9.0" + default-features = false + + [dev-dependencies.serde_json] + features = ["alloc", "default", "indexmap", "preserve_order", "raw_value", "std"] + version = "1.0.128" + default-features = false + +[dependencies] + + [dependencies.tokio] + features = ["bytes", "default", "fs", "full", "io-std", "io-util", "libc", "macros", "mio", "net", "parking_lot", "process", "rt", "rt-multi-thread", "signal", "signal-hook-registry", "socket2", "sync", "time", "tokio-macros"] + version = "1.40.0" + default-features = false + + [dependencies.typedb-protocol] + features = [] + rev = "71d7975a4617bb142015d27deaa3f8e886c00f0f" + git = "https://github.com/typedb/typedb-protocol" + + [dependencies.log] + features = ["kv", "kv_unstable", "std", "value-bag"] + version = "0.4.22" + default-features = false + + [dependencies.tokio-stream] + features = ["default", "net", "time"] + version = "0.1.16" + default-features = false + + [dependencies.futures] + features = ["alloc", "async-await", "default", "executor", "futures-executor", "std", "thread-pool"] + version = "0.3.30" + default-features = false + + [dependencies.uuid] + features = ["default", "fast-rng", "rng", "serde", "std", "v4"] + version = "1.10.0" + default-features = false + + [dependencies.itertools] + features = ["default", "use_alloc", "use_std"] + version = "0.10.5" + default-features = false + + [dependencies.prost] + features = ["default", "derive", "prost-derive", "std"] + version = "0.13.3" + default-features = false + + [dependencies.chrono-tz] + features = ["case-insensitive", "default", "std"] + version = "0.9.0" + default-features = false + + [dependencies.tonic-types] + features = [] + version = "0.12.2" + default-features = false + + [dependencies.http] + features = ["default", "std"] + version = "1.1.0" + default-features = false + + [dependencies.maybe-async] + features = ["default"] + version = "0.2.10" + default-features = false + + [dependencies.tonic] + features = ["channel", "codegen", "default", "prost", "router", "server", "tls", "tls-native-roots", "tls-roots", "transport"] + version = "0.12.2" + default-features = false + + [dependencies.chrono] + features = ["alloc", "android-tzdata", "clock", "default", "iana-time-zone", "js-sys", "now", "oldtime", "serde", "std", "wasm-bindgen", "wasmbind", "winapi", "windows-targets"] + version = "0.4.38" + default-features = false + + [dependencies.crossbeam] + features = ["alloc", "crossbeam-channel", "crossbeam-deque", "crossbeam-epoch", "crossbeam-queue", "default", "std"] + version = "0.8.4" + default-features = false + +[[test]] + path = "tests/integration/core/example.rs" + name = "test_example" + +[[test]] + path = "tests/behaviour/connection/database.rs" + name = "test_database" + +[[test]] + path = "tests/behaviour/connection/transaction.rs" + name = "test_transaction" + +[[test]] + path = "tests/behaviour/driver/driver.rs" + name = "test_driver" + diff --git a/rust/tests/behaviour/config/Cargo.toml b/rust/tests/behaviour/config/Cargo.toml new file mode 100644 index 0000000000..016d847988 --- /dev/null +++ b/rust/tests/behaviour/config/Cargo.toml @@ -0,0 +1,16 @@ + +# Generated by Vaticle Cargo sync tool. + +dependencies = {} + +[features] + bazel = [] + +[package] + name = "config" + edition = "2021" + version = "0.0.0" + +[lib] + path = "lib.rs" + diff --git a/rust/tests/behaviour/steps/Cargo.toml b/rust/tests/behaviour/steps/Cargo.toml new file mode 100644 index 0000000000..0ebcb9b103 --- /dev/null +++ b/rust/tests/behaviour/steps/Cargo.toml @@ -0,0 +1,74 @@ + +# Generated by Vaticle Cargo sync tool. + +features = {} + +[package] + name = "steps" + edition = "2021" + version = "0.0.0" + +[lib] + path = "lib.rs" + +[dependencies] + + [dependencies.tokio] + features = ["bytes", "default", "fs", "full", "io-std", "io-util", "libc", "macros", "mio", "net", "parking_lot", "process", "rt", "rt-multi-thread", "signal", "signal-hook-registry", "socket2", "sync", "time", "tokio-macros"] + version = "1.40.0" + default-features = false + + [dependencies.smol] + features = [] + version = "1.3.0" + default-features = false + + [dependencies.regex] + features = ["default", "perf", "perf-backtrack", "perf-cache", "perf-dfa", "perf-inline", "perf-literal", "perf-onepass", "std", "unicode", "unicode-age", "unicode-bool", "unicode-case", "unicode-gencat", "unicode-perl", "unicode-script", "unicode-segment"] + version = "1.10.6" + default-features = false + + [dependencies.cucumber] + features = ["default", "macros"] + version = "0.19.1" + default-features = false + + [dependencies.async-std] + features = ["alloc", "async-attributes", "async-channel", "async-global-executor", "async-io", "async-lock", "attributes", "crossbeam-utils", "default", "futures-channel", "futures-core", "futures-io", "futures-lite", "gloo-timers", "kv-log-macro", "log", "memchr", "once_cell", "pin-project-lite", "pin-utils", "slab", "std", "wasm-bindgen-futures"] + version = "1.13.0" + default-features = false + + [dependencies.macro_rules_attribute] + features = ["default"] + version = "0.2.0" + default-features = false + + [dependencies.typedb-driver] + path = "../../../../rust" + features = [] + + [dependencies.futures] + features = ["alloc", "async-await", "default", "executor", "futures-executor", "std", "thread-pool"] + version = "0.3.30" + default-features = false + + [dependencies.chrono] + features = ["alloc", "android-tzdata", "clock", "default", "iana-time-zone", "js-sys", "now", "oldtime", "serde", "std", "wasm-bindgen", "wasmbind", "winapi", "windows-targets"] + version = "0.4.38" + default-features = false + + [dependencies.uuid] + features = ["default", "fast-rng", "rng", "serde", "std", "v4"] + version = "1.10.0" + default-features = false + + [dependencies.itertools] + features = ["default", "use_alloc", "use_std"] + version = "0.10.5" + default-features = false + + [dependencies.serde_json] + features = ["alloc", "default", "indexmap", "preserve_order", "raw_value", "std"] + version = "1.0.128" + default-features = false + diff --git a/tool/ide/rust/sync.sh b/tool/ide/rust/sync.sh index f9fae1b1ec..af7ce8bed8 100755 --- a/tool/ide/rust/sync.sh +++ b/tool/ide/rust/sync.sh @@ -16,4 +16,4 @@ # specific language governing permissions and limitations # under the License. -bazel run @vaticle_dependencies//tool/ide:rust_sync +bazel run @vaticle_dependencies//tool/ide:rust_sync -- @vaticle_typedb_driver_workspace_refs//:refs.json From ea10fb22f38465124ad86f94d0ca123011995e69 Mon Sep 17 00:00:00 2001 From: Dmitrii Ubskii <18616863+dmitrii-ubskii@users.noreply.github.com> Date: Wed, 13 Nov 2024 15:54:21 +0000 Subject: [PATCH 2/4] autofix --- c/Cargo.toml | 1 + c/src/answer.rs | 4 +-- c/src/concept/concept.rs | 24 +++++++-------- c/src/concept/mod.rs | 5 ++-- c/src/concept/thing.rs | 2 +- c/src/concept/type_.rs | 2 +- c/src/database.rs | 7 ++--- c/src/error.rs | 2 +- c/src/memory.rs | 4 +-- c/src/options.rs | 6 ---- c/src/transaction.rs | 5 ++-- c/src/user.rs | 9 ------ c/src/user_manager.rs | 10 ------- rust/Cargo.toml | 6 ++-- rust/src/answer/concept_document.rs | 9 ++---- rust/src/answer/concept_row.rs | 4 +-- rust/src/answer/mod.rs | 8 ++--- rust/src/common/error.rs | 29 ++++++++----------- rust/src/common/promise_sync.rs | 2 +- rust/src/concept/mod.rs | 21 +++++++------- rust/src/concept/value.rs | 5 ++-- rust/src/connection/network/proto/common.rs | 2 +- rust/src/connection/network/proto/concept.rs | 10 ++----- rust/src/connection/network/proto/message.rs | 6 +--- rust/src/connection/network/stub.rs | 6 ++-- .../network/transmitter/response_sink.rs | 5 ++-- .../network/transmitter/transaction.rs | 16 ++++------ rust/src/connection/transaction_stream.rs | 6 +--- rust/src/database/database.rs | 7 +---- rust/src/transaction.rs | 2 +- rust/src/user/user_manager.rs | 5 +--- 31 files changed, 83 insertions(+), 147 deletions(-) diff --git a/c/Cargo.toml b/c/Cargo.toml index 06b1251f88..a16de74f46 100644 --- a/c/Cargo.toml +++ b/c/Cargo.toml @@ -26,6 +26,7 @@ features = {} [dependencies.typedb-driver] path = "../rust" features = ["sync"] + default-features = false [dependencies.chrono] features = ["alloc", "android-tzdata", "clock", "default", "iana-time-zone", "js-sys", "now", "oldtime", "serde", "std", "wasm-bindgen", "wasmbind", "winapi", "windows-targets"] diff --git a/c/src/answer.rs b/c/src/answer.rs index 0f1638cf42..99df1f86db 100644 --- a/c/src/answer.rs +++ b/c/src/answer.rs @@ -39,7 +39,7 @@ pub struct QueryAnswerPromise(BoxPromise<'static, Result>); impl QueryAnswerPromise { pub fn new(promise: impl Promise<'static, Result>) -> Self { - Self(Box::new(|| Ok(promise.resolve()?))) + Self(Box::new(|| promise.resolve())) } } @@ -106,7 +106,7 @@ pub extern "C" fn concept_row_drop(concept_row: *mut ConceptRow) { /// Produces an Iterator over all String column names of the ConceptRow's header. #[no_mangle] pub extern "C" fn concept_row_get_column_names(concept_row: *const ConceptRow) -> *mut StringIterator { - release(StringIterator(CIterator(box_stream(borrow(concept_row).get_column_names().into_iter().cloned().map(Ok))))) + release(StringIterator(CIterator(box_stream(borrow(concept_row).get_column_names().iter().cloned().map(Ok))))) } /// Retrieve the executed query's type of the ConceptRow's header. diff --git a/c/src/concept/concept.rs b/c/src/concept/concept.rs index d277eab891..bf14dc8ac4 100644 --- a/c/src/concept/concept.rs +++ b/c/src/concept/concept.rs @@ -159,7 +159,7 @@ pub extern "C" fn string_and_opt_value_drop(string_and_opt_value: *mut StringAnd /// Otherwise, returns false. #[no_mangle] pub extern "C" fn attribute_type_is_untyped(attribute_type: *const Concept) -> bool { - matches!(borrow_as_attribute_type(attribute_type).value_type, None) + borrow_as_attribute_type(attribute_type).value_type.is_none() } /// Returns true if the attribute type is of type boolean. @@ -306,8 +306,8 @@ pub extern "C" fn value_is_struct(value: *const Concept) -> bool { /// If the value has another type, the error is set. #[no_mangle] pub extern "C" fn value_get_boolean(value: *const Concept) -> bool { - if let Value::Boolean(bool) = borrow_as_value(value) { - *bool + if let &Value::Boolean(bool) = borrow_as_value(value) { + bool } else { unreachable!("Attempting to unwrap a non-boolean {:?} as boolean", borrow_as_value(value)) } @@ -317,8 +317,8 @@ pub extern "C" fn value_get_boolean(value: *const Concept) -> bool { /// If the value has another type, the error is set. #[no_mangle] pub extern "C" fn value_get_long(value: *const Concept) -> i64 { - if let Value::Long(long) = borrow_as_value(value) { - *long + if let &Value::Long(long) = borrow_as_value(value) { + long } else { unreachable!("Attempting to unwrap a non-long {:?} as long", borrow_as_value(value)) } @@ -328,8 +328,8 @@ pub extern "C" fn value_get_long(value: *const Concept) -> i64 { /// If the value has another type, the error is set. #[no_mangle] pub extern "C" fn value_get_double(value: *const Concept) -> f64 { - if let Value::Double(double) = borrow_as_value(value) { - *double + if let &Value::Double(double) = borrow_as_value(value) { + double } else { unreachable!("Attempting to unwrap a non-double {:?} as double", borrow_as_value(value)) } @@ -339,8 +339,8 @@ pub extern "C" fn value_get_double(value: *const Concept) -> f64 { /// If the value has another type, the error is set. #[no_mangle] pub extern "C" fn value_get_decimal(value: *const Concept) -> Decimal { - if let Value::Decimal(decimal) = borrow_as_value(value) { - decimal.clone() + if let &Value::Decimal(decimal) = borrow_as_value(value) { + decimal } else { unreachable!("Attempting to unwrap a non-decimal {:?} as decimal", borrow_as_value(value)) } @@ -394,8 +394,8 @@ pub extern "C" fn value_get_datetime_tz(value: *const Concept) -> DatetimeAndTim /// If the value has another type, the error is set. #[no_mangle] pub extern "C" fn value_get_duration(value: *const Concept) -> Duration { - if let Value::Duration(duration) = borrow_as_value(value) { - duration.clone() + if let &Value::Duration(duration) = borrow_as_value(value) { + duration } else { unreachable!("Attempting to unwrap a non-duration {:?} as duration", borrow_as_value(value)) } @@ -483,7 +483,7 @@ pub extern "C" fn concept_is_role_type(concept: *const Concept) -> bool { /// Gets the 'label' of this Concept object. #[no_mangle] pub extern "C" fn concept_get_label(concept: *const Concept) -> *mut c_char { - release_string(borrow(concept).get_label().clone().to_owned()) + release_string(borrow(concept).get_label().to_owned()) } /// A string representation of this Concept object. diff --git a/c/src/concept/mod.rs b/c/src/concept/mod.rs index 9ce3a83d24..a64e4abefb 100644 --- a/c/src/concept/mod.rs +++ b/c/src/concept/mod.rs @@ -19,10 +19,9 @@ use std::ptr::addr_of_mut; -use itertools::Itertools; use typedb_driver::{ - answer::{ConceptDocument, ConceptRow, QueryAnswer, ValueGroup}, - concept::{Attribute, AttributeType, Concept, Entity, EntityType, Relation, RelationType, RoleType, Value}, + answer::{ConceptRow, ValueGroup}, + concept::Concept, BoxPromise, Promise, Result, }; diff --git a/c/src/concept/thing.rs b/c/src/concept/thing.rs index e6f5708137..8fb9f5a996 100644 --- a/c/src/concept/thing.rs +++ b/c/src/concept/thing.rs @@ -19,7 +19,7 @@ use std::{ffi::c_char, ptr::null_mut}; -use typedb_driver::concept::{Concept, Value}; +use typedb_driver::concept::Concept; use super::concept::{borrow_as_attribute, borrow_as_entity, borrow_as_relation}; use crate::memory::{release, release_string}; diff --git a/c/src/concept/type_.rs b/c/src/concept/type_.rs index 5f9cb05f0c..1ab89da17e 100644 --- a/c/src/concept/type_.rs +++ b/c/src/concept/type_.rs @@ -21,7 +21,7 @@ use std::ffi::c_char; use typedb_driver::concept::Concept; -use super::concept::{borrow_as_attribute_type, borrow_as_entity_type, borrow_as_relation_type, borrow_as_role_type}; +use super::concept::borrow_as_attribute_type; use crate::memory::release_string; /// Gets the string representation of the value type of this attribute type. diff --git a/c/src/database.rs b/c/src/database.rs index 76bc287940..37a6e61fcc 100644 --- a/c/src/database.rs +++ b/c/src/database.rs @@ -17,14 +17,13 @@ * under the License. */ -use std::{ffi::c_char, ptr::addr_of_mut, sync::Arc}; +use std::ffi::c_char; -use typedb_driver::{box_stream, info::ReplicaInfo, Database}; +use typedb_driver::Database; use super::{ error::{try_release_string, unwrap_void}, - iterator::{iterator_next, CIterator}, - memory::{borrow, borrow_mut, free, release, release_optional, release_string, take_ownership}, + memory::{borrow, release_string}, }; use crate::memory::{decrement_arc, take_arc}; diff --git a/c/src/error.rs b/c/src/error.rs index 57ed509aa4..8a9c51354b 100644 --- a/c/src/error.rs +++ b/c/src/error.rs @@ -31,7 +31,7 @@ use typedb_driver::{Error, Result}; use super::memory::{free, release_arc, release_optional, release_string}; thread_local! { - static LAST_ERROR: RefCell> = RefCell::new(None); + static LAST_ERROR: RefCell> = const { RefCell::new(None) }; } /// Enables logging in the TypeDB driver. diff --git a/c/src/memory.rs b/c/src/memory.rs index 18d8763b07..d38692d7b2 100644 --- a/c/src/memory.rs +++ b/c/src/memory.rs @@ -20,7 +20,7 @@ use std::{ cell::RefCell, ffi::{c_char, CStr, CString}, - ptr::{null, null_mut}, + ptr::null_mut, sync::Arc, }; @@ -28,7 +28,7 @@ use log::trace; use typedb_driver::Error; thread_local! { - static LAST_ERROR: RefCell> = RefCell::new(None); + static LAST_ERROR: RefCell> = const { RefCell::new(None) }; } pub(super) fn release(t: T) -> *mut T { diff --git a/c/src/options.rs b/c/src/options.rs index 8e17f2ffb8..dda157e991 100644 --- a/c/src/options.rs +++ b/c/src/options.rs @@ -17,12 +17,6 @@ * under the License. */ -use std::time::Duration; - -use typedb_driver::Options; - -use super::memory::{borrow, borrow_mut, free, release}; - // /// Produces a new TypeDBOptions object. // #[no_mangle] // pub extern "C" fn options_new() -> *mut Options { diff --git a/c/src/transaction.rs b/c/src/transaction.rs index 85bad0924c..6d9fcae83b 100644 --- a/c/src/transaction.rs +++ b/c/src/transaction.rs @@ -19,7 +19,7 @@ use std::{ffi::c_char, ptr::null_mut}; -use typedb_driver::{DatabaseManager, Error, Transaction, TransactionType, TypeDBDriver}; +use typedb_driver::{Error, Transaction, TransactionType, TypeDBDriver}; use super::memory::{borrow, borrow_mut, free, release, take_ownership}; use crate::{answer::QueryAnswerPromise, error::try_release, memory::string_view, promise::VoidPromise}; @@ -87,6 +87,5 @@ pub extern "C" fn transaction_on_close( callback_id: usize, callback: extern "C" fn(usize, *mut Error), ) { - borrow(txn) - .on_close(move |error| callback(callback_id, error.map(|err| release(err.into())).unwrap_or(null_mut()))); + borrow(txn).on_close(move |error| callback(callback_id, error.map(release).unwrap_or(null_mut()))); } diff --git a/c/src/user.rs b/c/src/user.rs index 4b32a1fe25..eaf93af430 100644 --- a/c/src/user.rs +++ b/c/src/user.rs @@ -17,15 +17,6 @@ * under the License. */ -use std::ffi::c_char; - -use typedb_driver::{User, UserManager}; - -use super::{ - error::unwrap_void, - memory::{borrow, free, release_string, string_view}, -}; - // /// Frees the native rust User object. // #[no_mangle] // pub extern "C" fn user_drop(user: *mut User) { diff --git a/c/src/user_manager.rs b/c/src/user_manager.rs index 39cd95bbd5..16fa6341b5 100644 --- a/c/src/user_manager.rs +++ b/c/src/user_manager.rs @@ -17,16 +17,6 @@ * under the License. */ -use std::{ffi::c_char, ptr::addr_of_mut}; - -use typedb_driver::{box_stream, TypeDBDriver, User, UserManager}; - -use super::{ - error::{try_release, try_release_optional, unwrap_or_default, unwrap_void}, - iterator::{iterator_next, CIterator}, - memory::{borrow, free, release, string_view}, -}; - // /// Creates a UserManager on the specified connection // #[no_mangle] // pub extern "C" fn user_manager_new(connection: *const TypeDBDriver) -> *mut UserManager { diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 6f14444efd..d98e5a5303 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -3,7 +3,6 @@ [features] - default = [] sync = [] [package] @@ -34,10 +33,12 @@ [dev-dependencies.steps] path = "../rust/tests/behaviour/steps" features = [] + default-features = false [dev-dependencies.config] path = "../rust/tests/behaviour/config" - features = ["bazel"] + features = [] + default-features = false [dev-dependencies.serial_test] features = ["async", "default", "futures", "log", "logging"] @@ -60,6 +61,7 @@ features = [] rev = "71d7975a4617bb142015d27deaa3f8e886c00f0f" git = "https://github.com/typedb/typedb-protocol" + default-features = false [dependencies.log] features = ["kv", "kv_unstable", "std", "value-bag"] diff --git a/rust/src/answer/concept_document.rs b/rust/src/answer/concept_document.rs index ca044d0851..5c68e1fb4f 100644 --- a/rust/src/answer/concept_document.rs +++ b/rust/src/answer/concept_document.rs @@ -17,14 +17,11 @@ * under the License. */ -use std::{borrow::Cow, collections::HashMap, fmt, fmt::Formatter, sync::Arc}; +use std::{borrow::Cow, collections::HashMap, sync::Arc}; -use chrono::DateTime; - -use super::{ConceptRow, QueryType, JSON}; +use super::{QueryType, JSON}; use crate::concept::{ - value::{Struct, TimeZone}, - Attribute, AttributeType, Concept, EntityType, Kind, RelationType, RoleType, Value, ValueType, + value::Struct, Attribute, AttributeType, Concept, EntityType, Kind, RelationType, RoleType, Value, ValueType, }; #[derive(Debug, PartialEq)] diff --git a/rust/src/answer/concept_row.rs b/rust/src/answer/concept_row.rs index a017d2e41e..ca4c61ca54 100644 --- a/rust/src/answer/concept_row.rs +++ b/rust/src/answer/concept_row.rs @@ -88,7 +88,7 @@ impl ConceptRow { /// concept_row.get(var_name) /// ``` pub fn get(&self, column_name: &str) -> Option<&Concept> { - self.header.get_index(column_name).map(|index| self.get_index(index)).flatten() + self.header.get_index(column_name).and_then(|index| self.get_index(index)) } /// Retrieves a concept for a given column index. Returns an empty optional if @@ -104,7 +104,7 @@ impl ConceptRow { /// concept_row.get_position(column_index) /// ``` pub fn get_index(&self, column_index: usize) -> Option<&Concept> { - self.row.get(column_index).map(|inner| inner.as_ref()).flatten() + self.row.get(column_index).and_then(|inner| inner.as_ref()) } /// Produces an iterator over all concepts in this `ConceptRow`, skipping empty results diff --git a/rust/src/answer/mod.rs b/rust/src/answer/mod.rs index 91f375227e..ff5fed6452 100644 --- a/rust/src/answer/mod.rs +++ b/rust/src/answer/mod.rs @@ -19,12 +19,10 @@ use std::{fmt, sync::Arc}; -use futures::{stream, StreamExt}; - pub use self::{concept_document::ConceptDocument, concept_row::ConceptRow, json::JSON, value_group::ValueGroup}; use crate::{ answer::{concept_document::ConceptDocumentHeader, concept_row::ConceptRowHeader}, - box_stream, BoxStream, Result, + BoxStream, Result, }; pub mod concept_document; @@ -47,8 +45,8 @@ impl QueryAnswer { /// query_answer.get_query_type() /// ``` pub fn get_query_type(&self) -> QueryType { - match &self { - QueryAnswer::Ok(query_type) => query_type.clone(), + match self { + &QueryAnswer::Ok(query_type) => query_type, QueryAnswer::ConceptRowStream(header, _) => header.query_type, QueryAnswer::ConceptDocumentStream(header, _) => header.query_type, } diff --git a/rust/src/common/error.rs b/rust/src/common/error.rs index 47585c6995..11a39a43b3 100644 --- a/rust/src/common/error.rs +++ b/rust/src/common/error.rs @@ -19,7 +19,6 @@ use std::{collections::HashSet, error::Error as StdError, fmt}; -use chrono::{MappedLocalTime, NaiveDateTime}; use itertools::Itertools; use tonic::{Code, Status}; use tonic_types::StatusExt; @@ -349,23 +348,19 @@ impl From for Error { } else { Self::from_message(status.message()) } + } else if status.code() == Code::Unavailable { + Self::parse_unavailable(status.message()) + } else if status.code() == Code::Unknown + || is_rst_stream(&status) + || status.code() == Code::InvalidArgument + || status.code() == Code::FailedPrecondition + || status.code() == Code::AlreadyExists + { + Self::Connection(ConnectionError::ServerConnectionFailedStatusError { error: status.message().to_owned() }) + } else if status.code() == Code::Unimplemented { + Self::Connection(ConnectionError::RPCMethodUnavailable { message: status.message().to_owned() }) } else { - if status.code() == Code::Unavailable { - Self::parse_unavailable(status.message()) - } else if status.code() == Code::Unknown - || is_rst_stream(&status) - || status.code() == Code::InvalidArgument - || status.code() == Code::FailedPrecondition - || status.code() == Code::AlreadyExists - { - Self::Connection(ConnectionError::ServerConnectionFailedStatusError { - error: status.message().to_owned(), - }) - } else if status.code() == Code::Unimplemented { - Self::Connection(ConnectionError::RPCMethodUnavailable { message: status.message().to_owned() }) - } else { - Self::from_message(status.message()) - } + Self::from_message(status.message()) } } } diff --git a/rust/src/common/promise_sync.rs b/rust/src/common/promise_sync.rs index 77ac37af54..8fcef189be 100644 --- a/rust/src/common/promise_sync.rs +++ b/rust/src/common/promise_sync.rs @@ -52,6 +52,6 @@ macro_rules! promisify { #[macro_export] macro_rules! resolve { ($promise:expr $(,)?) => { - $crate::common::Promise::resolve($promise) + ($promise)() }; } diff --git a/rust/src/concept/mod.rs b/rust/src/concept/mod.rs index 991d2f9d27..93cf368b66 100644 --- a/rust/src/concept/mod.rs +++ b/rust/src/concept/mod.rs @@ -20,7 +20,6 @@ use std::fmt::{Debug, Display, Formatter}; use chrono::{DateTime, NaiveDate, NaiveDateTime}; -use chrono_tz::Tz; pub use self::{ thing::{Attribute, Entity, Relation}, @@ -174,7 +173,7 @@ impl Concept { /// If this a boolean-valued Value, return the boolean value. /// Otherwise, return empty. pub fn get_boolean(&self) -> Option { - self.get_value().map(|value| value.get_boolean()).flatten() + self.get_value().and_then(|value| value.get_boolean()) } /// Get the long value of this concept, if it exists. @@ -182,7 +181,7 @@ impl Concept { /// If this a long-valued Value, return the long value. /// Otherwise, return empty. pub fn get_long(&self) -> Option { - self.get_value().map(|value| value.get_long()).flatten() + self.get_value().and_then(|value| value.get_long()) } /// Get the double value of this concept, if it exists. @@ -190,7 +189,7 @@ impl Concept { /// If this a double-valued Value, return the double value. /// Otherwise, return empty. pub fn get_double(&self) -> Option { - self.get_value().map(|value| value.get_double()).flatten() + self.get_value().and_then(|value| value.get_double()) } /// Get the fixed-decimal value of this concept, if it exists. @@ -198,7 +197,7 @@ impl Concept { /// If this a fixed-decimal valued Value, return the fixed-decimal value. /// Otherwise, return empty. pub fn get_decimal(&self) -> Option { - self.get_value().map(|value| value.get_decimal()).flatten() + self.get_value().and_then(|value| value.get_decimal()) } /// Get the string value of this concept, if it exists. @@ -206,7 +205,7 @@ impl Concept { /// If this a string-valued Value, return the string value. /// Otherwise, return empty. pub fn get_string(&self) -> Option<&str> { - self.get_value().map(|value| value.get_string()).flatten() + self.get_value().and_then(|value| value.get_string()) } /// Get the date value of this concept, if it exists. @@ -214,7 +213,7 @@ impl Concept { /// If this a date-valued Value, return the date value. /// Otherwise, return empty. pub fn get_date(&self) -> Option { - self.get_value().map(|value| value.get_date()).flatten() + self.get_value().and_then(|value| value.get_date()) } /// Get the datetime value of this concept, if it exists. @@ -222,7 +221,7 @@ impl Concept { /// If this a datetime-valued Value, return the datetime value. /// Otherwise, return empty. pub fn get_datetime(&self) -> Option { - self.get_value().map(|value| value.get_datetime()).flatten() + self.get_value().and_then(|value| value.get_datetime()) } /// Get the timezoned-datetime value of this concept, if it exists. @@ -230,7 +229,7 @@ impl Concept { /// If this a timezoned-datetime valued Value, return the timezoned-datetime value. /// Otherwise, return empty. pub fn get_datetime_tz(&self) -> Option> { - self.get_value().map(|value| value.get_datetime_tz()).flatten() + self.get_value().and_then(|value| value.get_datetime_tz()) } /// Get the duration value of this concept, if it exists. @@ -238,7 +237,7 @@ impl Concept { /// If this a duration-valued Value, return the duration value. /// Otherwise, return empty. pub fn get_duration(&self) -> Option { - self.get_value().map(|value| value.get_duration()).flatten() + self.get_value().and_then(|value| value.get_duration()) } /// Get the struct value of this concept, if it exists. @@ -246,7 +245,7 @@ impl Concept { /// If this a struct-valued Value, return the struct value. /// Otherwise, return empty. pub fn get_struct(&self) -> Option<&Struct> { - self.get_value().map(|value| value.get_struct()).flatten() + self.get_value().and_then(|value| value.get_struct()) } /// Get the category of this concept diff --git a/rust/src/concept/value.rs b/rust/src/concept/value.rs index 74c3353205..9ec5087dd7 100644 --- a/rust/src/concept/value.rs +++ b/rust/src/concept/value.rs @@ -18,7 +18,6 @@ */ use std::{ - borrow::Cow, collections::HashMap, fmt, ops::{Add, Neg, Sub}, @@ -28,7 +27,7 @@ use std::{ use chrono::{DateTime, FixedOffset, MappedLocalTime, NaiveDate, NaiveDateTime}; use chrono_tz::Tz; -use crate::{answer::JSON, Error}; +use crate::Error; /// Represents the type of primitive value is held by a Value or Attribute. #[derive(Clone, PartialEq, Eq)] @@ -68,7 +67,7 @@ impl ValueType { Self::Datetime => Self::DATETIME_STR, Self::DatetimeTZ => Self::DATETIME_TZ_STR, Self::Duration => Self::DURATION_STR, - Self::Struct(name) => &name, + Self::Struct(name) => name, } } } diff --git a/rust/src/connection/network/proto/common.rs b/rust/src/connection/network/proto/common.rs index 1031666c43..9ec716e5dc 100644 --- a/rust/src/connection/network/proto/common.rs +++ b/rust/src/connection/network/proto/common.rs @@ -17,7 +17,7 @@ * under the License. */ -use typedb_protocol::{query, transaction, Options as OptionsProto}; +use typedb_protocol::{transaction, Options as OptionsProto}; use super::{IntoProto, TryFromProto}; use crate::{answer::QueryType, error::ConnectionError, Options, Result, TransactionType}; diff --git a/rust/src/connection/network/proto/concept.rs b/rust/src/connection/network/proto/concept.rs index cbd3751e58..dca8c7f3a2 100644 --- a/rust/src/connection/network/proto/concept.rs +++ b/rust/src/connection/network/proto/concept.rs @@ -27,7 +27,6 @@ use typedb_protocol::{ concept, concept_document::{self, node::leaf::Leaf as LeafProto}, row_entry::Entry, - value, value::{datetime_tz::Timezone as TimezoneProto, Value as ValueProtoInner}, value_type::ValueType as ValueTypeProto, Attribute as AttributeProto, AttributeType as AttributeTypeProto, Concept as ConceptProto, @@ -231,24 +230,21 @@ impl TryFromProto for ValueType { impl TryFromProto for Entity { fn try_from_proto(proto: EntityProto) -> Result { let EntityProto { iid, entity_type } = proto; - Ok(Self { iid: iid.into(), type_: entity_type.map(|type_| EntityType::from_proto(type_)) }) + Ok(Self { iid: iid.into(), type_: entity_type.map(EntityType::from_proto) }) } } impl TryFromProto for Relation { fn try_from_proto(proto: RelationProto) -> Result { let RelationProto { iid, relation_type } = proto; - Ok(Self { iid: iid.into(), type_: relation_type.map(|type_| RelationType::from_proto(type_)) }) + Ok(Self { iid: iid.into(), type_: relation_type.map(RelationType::from_proto) }) } } impl TryFromProto for Attribute { fn try_from_proto(proto: AttributeProto) -> Result { let AttributeProto { iid, attribute_type, value } = proto; - let type_ = match attribute_type { - None => None, - Some(attribute_type) => Some(AttributeType::from_proto(attribute_type)), - }; + let type_ = attribute_type.map(AttributeType::from_proto); Ok(Self { iid: iid.into(), type_, diff --git a/rust/src/connection/network/proto/message.rs b/rust/src/connection/network/proto/message.rs index 985c46cb7a..8fee49df84 100644 --- a/rust/src/connection/network/proto/message.rs +++ b/rust/src/connection/network/proto/message.rs @@ -26,11 +26,7 @@ use uuid::Uuid; use super::{FromProto, IntoProto, TryFromProto, TryIntoProto}; use crate::{ - answer::{ - concept_document::{ConceptDocument, ConceptDocumentHeader}, - concept_row::ConceptRowHeader, - QueryType, - }, + answer::{concept_document::ConceptDocumentHeader, concept_row::ConceptRowHeader, QueryType}, common::{info::DatabaseInfo, RequestID, Result}, connection::message::{QueryRequest, QueryResponse, Request, Response, TransactionRequest, TransactionResponse}, error::{ConnectionError, InternalError, ServerError}, diff --git a/rust/src/connection/network/stub.rs b/rust/src/connection/network/stub.rs index 84b6e636e2..69a621cb7e 100644 --- a/rust/src/connection/network/stub.rs +++ b/rust/src/connection/network/stub.rs @@ -20,7 +20,7 @@ use std::sync::Arc; use futures::{future::BoxFuture, FutureExt, TryFutureExt}; -use log::{debug, trace, warn}; +use log::{debug, warn}; use tokio::sync::mpsc::{unbounded_channel as unbounded_async, UnboundedSender}; use tokio_stream::wrappers::UnboundedReceiverStream; use tonic::{Response, Status, Streaming}; @@ -82,7 +82,7 @@ impl RPCStub { } pub(super) async fn servers_all(&mut self, req: server_manager::all::Req) -> Result { - self.single(|this| Box::pin(this.grpc.servers_all(req.clone()))).await + self.single(|this| Box::pin(this.grpc.servers_all(req))).await } pub(super) async fn databases_contains( @@ -110,7 +110,7 @@ impl RPCStub { &mut self, req: database_manager::all::Req, ) -> Result { - self.single(|this| Box::pin(this.grpc.databases_all(req.clone()))).await + self.single(|this| Box::pin(this.grpc.databases_all(req))).await } pub(super) async fn database_delete(&mut self, req: database::delete::Req) -> Result { diff --git a/rust/src/connection/network/transmitter/response_sink.rs b/rust/src/connection/network/transmitter/response_sink.rs index 5b799e8e9a..9d88cba739 100644 --- a/rust/src/connection/network/transmitter/response_sink.rs +++ b/rust/src/connection/network/transmitter/response_sink.rs @@ -20,13 +20,12 @@ use std::{fmt, fmt::Formatter, sync::Arc}; use crossbeam::channel::Sender as SyncSender; -use itertools::Either; use log::{debug, error}; use tokio::sync::{mpsc::UnboundedSender, oneshot::Sender as AsyncOneshotSender}; use crate::{ common::{RequestID, Result}, - error::{ConnectionError, InternalError}, + error::InternalError, Error, }; @@ -39,7 +38,7 @@ pub(super) enum ResponseSink { } pub(super) struct ImmediateHandler { - pub(super) handler: Arc () + Sync + Send>, + pub(super) handler: Arc, } impl ImmediateHandler { diff --git a/rust/src/connection/network/transmitter/transaction.rs b/rust/src/connection/network/transmitter/transaction.rs index cfbae835cc..3bd1141ece 100644 --- a/rust/src/connection/network/transmitter/transaction.rs +++ b/rust/src/connection/network/transmitter/transaction.rs @@ -19,8 +19,6 @@ use std::{ collections::HashMap, - future::Future, - pin::Pin, sync::{Arc, RwLock}, time::Duration, }; @@ -29,8 +27,6 @@ use crossbeam::{atomic::AtomicCell, channel::Sender}; use futures::StreamExt; #[cfg(not(feature = "sync"))] use futures::TryStreamExt; -#[cfg(feature = "sync")] -use itertools::Itertools; use log::{debug, error}; use prost::Message; #[cfg(not(feature = "sync"))] @@ -38,14 +34,13 @@ use tokio::sync::oneshot::channel as oneshot; use tokio::{ select, sync::{ - mpsc::{error::SendError, unbounded_channel as unbounded_async, UnboundedReceiver, UnboundedSender}, + mpsc::{unbounded_channel as unbounded_async, UnboundedReceiver, UnboundedSender}, oneshot::{channel as oneshot_async, Sender as AsyncOneshotSender}, }, time::{sleep_until, Instant}, }; use tonic::Streaming; use typedb_protocol::transaction::{self, res_part::ResPart, server::Server, stream_signal::res_part::State}; -use uuid::Uuid; #[cfg(feature = "sync")] use super::oneshot_blocking as oneshot; @@ -58,10 +53,9 @@ use crate::{ Callback, Promise, RequestID, Result, }, connection::{ - message::{QueryResponse, Request, Response, TransactionRequest, TransactionResponse}, + message::{QueryResponse, TransactionRequest, TransactionResponse}, network::proto::{FromProto, IntoProto, TryFromProto}, runtime::BackgroundRuntime, - server_connection::LatencyTracker, }, Error, }; @@ -88,7 +82,7 @@ impl TransactionTransmitter { request_sink: UnboundedSender, response_source: Streaming, initial_request_id: RequestID, - initial_response_handler: Arc) -> () + Sync + Send>, + initial_response_handler: Arc) + Sync + Send>, ) -> Self { let callback_handler_sink = background_runtime.callback_handler_sink(); let (buffer_sink, buffer_source) = unbounded_async(); @@ -155,7 +149,7 @@ impl TransactionTransmitter { ) -> impl Promise<'static, Result> { if !self.is_open() { let error = self.error(); - return box_promise(|| Err(error.into())); + return box_promise(|| Err(error)); } let (res_sink, recv) = oneshot(); let send_result = self.request_sink.send((req, Some(ResponseSink::BlockingOneShot(res_sink)))); @@ -169,7 +163,7 @@ impl TransactionTransmitter { req: TransactionRequest, ) -> Result>> { if !self.is_open() { - return Err(self.error().into()); + return Err(self.error()); } let (res_part_sink, recv) = unbounded_async(); self.request_sink diff --git a/rust/src/connection/transaction_stream.rs b/rust/src/connection/transaction_stream.rs index c561841f6d..030dce055a 100644 --- a/rust/src/connection/transaction_stream.rs +++ b/rust/src/connection/transaction_stream.rs @@ -74,11 +74,7 @@ impl TransactionStream { let promise = self.transaction_transmitter.single(TransactionRequest::Commit); promisify! { let _this = self; // move into the promise so the stream isn't dropped until the promise is resolved - resolve!(promise).map(|_| { - () - }).map_err(|err| { - err - }) + resolve!(promise).map(|_| ()) } } diff --git a/rust/src/database/database.rs b/rust/src/database/database.rs index d0bdd761ba..1b58862b99 100644 --- a/rust/src/database/database.rs +++ b/rust/src/database/database.rs @@ -22,10 +22,7 @@ use std::future::Future; use std::{ collections::HashMap, fmt, - sync::{ - atomic::{AtomicU64, Ordering}, - Arc, RwLock, - }, + sync::{Arc, RwLock}, thread::sleep, time::Duration, }; @@ -41,9 +38,7 @@ use crate::{ Error, Result, }, connection::server_connection::ServerConnection, - driver::TypeDBDriver, error::InternalError, - Options, Transaction, TransactionType, }; /// A TypeDB database diff --git a/rust/src/transaction.rs b/rust/src/transaction.rs index 150e7a7541..38de695a96 100644 --- a/rust/src/transaction.rs +++ b/rust/src/transaction.rs @@ -17,7 +17,7 @@ * under the License. */ -use std::{fmt, marker::PhantomData, pin::Pin}; +use std::{fmt, pin::Pin}; use crate::{ answer::QueryAnswer, diff --git a/rust/src/user/user_manager.rs b/rust/src/user/user_manager.rs index 3bf28b94d4..09984575f2 100644 --- a/rust/src/user/user_manager.rs +++ b/rust/src/user/user_manager.rs @@ -20,10 +20,7 @@ #[cfg(not(feature = "sync"))] use std::future::Future; -use crate::{ - common::Result, connection::server_connection::ServerConnection, driver::TypeDBDriver, error::ConnectionError, - DatabaseManager, Error, User, -}; +use crate::{common::Result, connection::server_connection::ServerConnection, driver::TypeDBDriver, User}; /// Provides access to all user management methods. #[derive(Debug)] From 6c80d38f5b669a04193b0c1555042f8f208db814 Mon Sep 17 00:00:00 2001 From: Dmitrii Ubskii <18616863+dmitrii-ubskii@users.noreply.github.com> Date: Wed, 13 Nov 2024 16:00:11 +0000 Subject: [PATCH 3/4] switch behaviour tests to blocking (`sync`) driver mode --- rust/Cargo.toml | 19 ------- rust/tests/BUILD | 2 +- rust/tests/behaviour/steps/BUILD | 2 +- rust/tests/behaviour/steps/Cargo.toml | 3 +- .../behaviour/steps/connection/database.rs | 34 +++++------- rust/tests/behaviour/steps/connection/mod.rs | 12 ++--- .../behaviour/steps/connection/transaction.rs | 12 ++--- rust/tests/behaviour/steps/lib.rs | 53 ++++++++----------- rust/tests/behaviour/steps/params.rs | 4 +- rust/tests/behaviour/steps/query.rs | 31 +++++------ rust/tests/behaviour/steps/util.rs | 22 ++------ rust/tests/integration/core/BUILD | 34 ++++++------ 12 files changed, 86 insertions(+), 142 deletions(-) diff --git a/rust/Cargo.toml b/rust/Cargo.toml index d98e5a5303..85445bf9d3 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -15,21 +15,6 @@ [dev-dependencies] - [dev-dependencies.smol] - features = [] - version = "1.3.0" - default-features = false - - [dev-dependencies.regex] - features = ["default", "perf", "perf-backtrack", "perf-cache", "perf-dfa", "perf-inline", "perf-literal", "perf-onepass", "std", "unicode", "unicode-age", "unicode-bool", "unicode-case", "unicode-gencat", "unicode-perl", "unicode-script", "unicode-segment"] - version = "1.10.6" - default-features = false - - [dev-dependencies.async-std] - features = ["alloc", "async-attributes", "async-channel", "async-global-executor", "async-io", "async-lock", "attributes", "crossbeam-utils", "default", "futures-channel", "futures-core", "futures-io", "futures-lite", "gloo-timers", "kv-log-macro", "log", "memchr", "once_cell", "pin-project-lite", "pin-utils", "slab", "std", "wasm-bindgen-futures"] - version = "1.13.0" - default-features = false - [dev-dependencies.steps] path = "../rust/tests/behaviour/steps" features = [] @@ -128,10 +113,6 @@ version = "0.8.4" default-features = false -[[test]] - path = "tests/integration/core/example.rs" - name = "test_example" - [[test]] path = "tests/behaviour/connection/database.rs" name = "test_database" diff --git a/rust/tests/BUILD b/rust/tests/BUILD index 16d72feea7..432a0c5038 100644 --- a/rust/tests/BUILD +++ b/rust/tests/BUILD @@ -28,7 +28,7 @@ rustfmt_test( "//rust/tests/behaviour/connection:test_transaction", "//rust/tests/behaviour/driver:test_driver", - "//rust/tests/integration/core:test_example", +# "//rust/tests/integration/core:test_example", # "//rust/tests/integration/cloud:test_example", ], size = "small", diff --git a/rust/tests/behaviour/steps/BUILD b/rust/tests/behaviour/steps/BUILD index 03b47d98ad..0c134bca9f 100644 --- a/rust/tests/behaviour/steps/BUILD +++ b/rust/tests/behaviour/steps/BUILD @@ -25,7 +25,7 @@ rust_library( srcs = glob(["**/*.rs"]), crate_root = "lib.rs", deps = [ - "//rust:typedb_driver", + "//rust:typedb_driver_sync", "@crates//:async-std", "@crates//:chrono", "@crates//:cucumber", diff --git a/rust/tests/behaviour/steps/Cargo.toml b/rust/tests/behaviour/steps/Cargo.toml index 0ebcb9b103..64679d8329 100644 --- a/rust/tests/behaviour/steps/Cargo.toml +++ b/rust/tests/behaviour/steps/Cargo.toml @@ -45,7 +45,8 @@ features = {} [dependencies.typedb-driver] path = "../../../../rust" - features = [] + features = ["sync"] + default-features = false [dependencies.futures] features = ["alloc", "async-await", "default", "executor", "futures-executor", "std", "thread-pool"] diff --git a/rust/tests/behaviour/steps/connection/database.rs b/rust/tests/behaviour/steps/connection/database.rs index fe495313ab..ed5935dffa 100644 --- a/rust/tests/behaviour/steps/connection/database.rs +++ b/rust/tests/behaviour/steps/connection/database.rs @@ -19,19 +19,16 @@ use std::collections::HashSet; -use cucumber::{gherkin::Step, given, then, when}; -use futures::{ - future::{join_all, try_join_all}, - stream, StreamExt, TryFutureExt, -}; +use cucumber::gherkin::Step; +use futures::future::join_all; use macro_rules_attribute::apply; use tokio::time::sleep; -use typedb_driver::{Database, DatabaseManager, Result as TypeDBResult, TypeDBDriver}; +use typedb_driver::{Database, TypeDBDriver}; use crate::{assert_with_timeout, generic_step, params, util::iter_table, Context}; async fn create_database(driver: &TypeDBDriver, name: String, may_error: params::MayError) { - may_error.check(driver.databases().create(name).await); + may_error.check(driver.databases().create(name)); } #[apply(generic_step)] @@ -67,32 +64,30 @@ async fn connection_create_databases_in_parallel(context: &mut Context, step: &S #[apply(generic_step)] #[step(expr = "connection delete database: {word}{may_error}")] pub async fn connection_delete_database(context: &mut Context, name: String, may_error: params::MayError) { - may_error.check(context.driver.as_ref().unwrap().databases().get(name).and_then(Database::delete).await); + may_error.check(context.driver.as_ref().unwrap().databases().get(name).and_then(Database::delete)); } #[apply(generic_step)] #[step(expr = "connection delete database(s):")] async fn connection_delete_databases(context: &mut Context, step: &Step) { for name in iter_table(step) { - context.driver.as_ref().unwrap().databases().get(name).and_then(Database::delete).await.unwrap(); + context.driver.as_ref().unwrap().databases().get(name).and_then(Database::delete).unwrap(); } } #[apply(generic_step)] #[step(expr = "connection delete databases in parallel:")] async fn connection_delete_databases_in_parallel(context: &mut Context, step: &Step) { - try_join_all( - iter_table(step).map(|name| context.driver.as_ref().unwrap().databases().get(name).and_then(Database::delete)), - ) - .await - .unwrap(); + for name in iter_table(step) { + context.driver.as_ref().unwrap().databases().get(name).and_then(Database::delete).unwrap(); + } } #[apply(generic_step)] #[step(expr = "connection has database: {word}")] async fn connection_has_database(context: &mut Context, name: String) { assert_with_timeout!( - context.driver.as_ref().unwrap().databases().contains(name.clone()).await.unwrap(), + context.driver.as_ref().unwrap().databases().contains(name.clone()).unwrap(), "Connection doesn't contain database {name}.", ); } @@ -101,17 +96,14 @@ async fn connection_has_database(context: &mut Context, name: String) { #[step(expr = "connection has database(s):")] async fn connection_has_databases(context: &mut Context, step: &Step) { let names: HashSet = iter_table(step).map(|name| name.to_owned()).collect(); - assert_with_timeout!( - context.all_databases().await == names, - "Connection doesn't contain at least one of the databases.", - ); + assert_with_timeout!(context.all_databases() == names, "Connection doesn't contain at least one of the databases.",); } #[apply(generic_step)] #[step(expr = "connection does not have database: {word}")] async fn connection_does_not_have_database(context: &mut Context, name: String) { assert_with_timeout!( - !context.driver.as_ref().unwrap().databases().contains(name.clone()).await.unwrap(), + !context.driver.as_ref().unwrap().databases().contains(name.clone()).unwrap(), "Connection contains database {name}.", ); } @@ -120,7 +112,7 @@ async fn connection_does_not_have_database(context: &mut Context, name: String) #[step(expr = "connection does not have database(s):")] async fn connection_does_not_have_databases(context: &mut Context, step: &Step) { assert_with_timeout!( - stream::iter(iter_table(step)).all(|name| async { !context.all_databases().await.contains(name) }).await, + iter_table(step).all(|name| !context.all_databases().contains(name)), "Connection contains at least one of the databases.", ) } diff --git a/rust/tests/behaviour/steps/connection/mod.rs b/rust/tests/behaviour/steps/connection/mod.rs index 97a0e92edf..5b44bba7e9 100644 --- a/rust/tests/behaviour/steps/connection/mod.rs +++ b/rust/tests/behaviour/steps/connection/mod.rs @@ -17,12 +17,9 @@ * under the License. */ -use cucumber::{given, then, when}; use macro_rules_attribute::apply; -use tokio::time::sleep; -use typedb_driver::{Credential, TypeDBDriver}; -use crate::{assert_with_timeout, generic_step, params, params::check_boolean, Context}; +use crate::{generic_step, params, params::check_boolean, Context}; mod database; mod transaction; @@ -70,7 +67,8 @@ async fn connection_opens_with_a_wrong_host(context: &mut Context, may_error: pa .await } true => { - let updated_address = change_host(Context::DEFAULT_CLOUD_ADDRESSES.get(0).unwrap(), "surely-not-localhost"); + let updated_address = + change_host(Context::DEFAULT_CLOUD_ADDRESSES.first().unwrap(), "surely-not-localhost"); context .create_cloud_driver(&[&updated_address], Some(Context::ADMIN_USERNAME), Some(Context::ADMIN_PASSWORD)) .await @@ -92,7 +90,7 @@ async fn connection_opens_with_a_wrong_port(context: &mut Context, may_error: pa .await } true => { - let updated_address = change_port(Context::DEFAULT_CLOUD_ADDRESSES.get(0).unwrap(), "0"); + let updated_address = change_port(Context::DEFAULT_CLOUD_ADDRESSES.first().unwrap(), "0"); context .create_cloud_driver(&[&updated_address], Some(Context::ADMIN_USERNAME), Some(Context::ADMIN_PASSWORD)) .await @@ -109,7 +107,7 @@ async fn connection_has_been_opened(context: &mut Context, is_open: params::Bool #[apply(generic_step)] #[step(expr = r"connection has {int} database(s)")] async fn connection_has_count_databases(context: &mut Context, count: usize) { - assert_eq!(context.driver.as_ref().unwrap().databases().all().await.unwrap().len(), count); + assert_eq!(context.driver.as_ref().unwrap().databases().all().unwrap().len(), count); } #[apply(generic_step)] diff --git a/rust/tests/behaviour/steps/connection/transaction.rs b/rust/tests/behaviour/steps/connection/transaction.rs index 1f24bf27d5..13ac05cdfc 100644 --- a/rust/tests/behaviour/steps/connection/transaction.rs +++ b/rust/tests/behaviour/steps/connection/transaction.rs @@ -17,12 +17,12 @@ * under the License. */ -use std::{collections::VecDeque, time::Duration}; +use std::collections::VecDeque; -use cucumber::{gherkin::Step, given, then, when}; +use cucumber::gherkin::Step; use futures::{future::join_all, FutureExt}; use macro_rules_attribute::apply; -use typedb_driver::{Result as TypeDBResult, Transaction, TransactionType, TypeDBDriver}; +use typedb_driver::{resolve, Result as TypeDBResult, Transaction, TransactionType, TypeDBDriver}; use crate::{generic_step, params, params::check_boolean, util::iter_table, Context}; @@ -31,7 +31,7 @@ async fn open_transaction_for_database( database_name: impl AsRef, transaction_type: TransactionType, ) -> TypeDBResult { - driver.as_ref().unwrap().transaction(database_name, transaction_type).await + driver.as_ref().unwrap().transaction(database_name, transaction_type) } #[apply(generic_step)] @@ -100,7 +100,7 @@ pub async fn transactions_have_type(context: &mut Context, step: &Step) { #[apply(generic_step)] #[step(expr = "transaction commits{may_error}")] pub async fn transaction_commits(context: &mut Context, may_error: params::MayError) { - may_error.check(context.take_transaction().commit().await); + may_error.check(resolve!(context.take_transaction().commit())); } #[apply(generic_step)] @@ -112,5 +112,5 @@ pub async fn transaction_closes(context: &mut Context) { #[apply(generic_step)] #[step(expr = "transaction rollbacks{may_error}")] pub async fn transaction_rollbacks(context: &mut Context, may_error: params::MayError) { - may_error.check(context.transaction().rollback().await); + may_error.check(resolve!(context.transaction().rollback())); } diff --git a/rust/tests/behaviour/steps/lib.rs b/rust/tests/behaviour/steps/lib.rs index 03bfc9a4af..3f446cdbd0 100644 --- a/rust/tests/behaviour/steps/lib.rs +++ b/rust/tests/behaviour/steps/lib.rs @@ -21,8 +21,7 @@ #![deny(elided_lifetimes_in_paths)] use std::{ - collections::{HashMap, HashSet, VecDeque}, - env::VarError, + collections::{HashSet, VecDeque}, error::Error, fmt, fmt::Formatter, @@ -32,16 +31,14 @@ use std::{ use cucumber::{gherkin::Feature, StatsWriter, World}; use futures::{ - future::{try_join_all, Either}, + future::Either, stream::{self, StreamExt}, }; use itertools::Itertools; use tokio::time::{sleep, Duration}; use typedb_driver::{ - answer::{ConceptDocument, ConceptRow, QueryAnswer, QueryType, JSON}, - concept::Value, - BoxStream, Credential, Database, DatabaseManager, Options, Result as TypeDBResult, Transaction, TypeDBDriver, - UserManager, + answer::{ConceptDocument, ConceptRow, QueryAnswer, QueryType}, + BoxStream, Credential, Options, Result as TypeDBResult, Transaction, TypeDBDriver, }; use crate::params::QueryAnswerType; @@ -185,13 +182,12 @@ impl Context { Ok(()) } - pub async fn all_databases(&self) -> HashSet { + pub fn all_databases(&self) -> HashSet { self.driver .as_ref() .unwrap() .databases() .all() - .await .unwrap() .into_iter() .map(|db| db.name().to_owned()) @@ -203,9 +199,9 @@ impl Context { self.create_default_driver(Some(Self::ADMIN_USERNAME), Some(Self::ADMIN_PASSWORD)).await.unwrap(); } - try_join_all(self.driver.as_ref().unwrap().databases().all().await.unwrap().into_iter().map(|db| db.delete())) - .await - .unwrap(); + for db in self.driver.as_ref().unwrap().databases().all().unwrap() { + db.delete().unwrap() + } } pub async fn cleanup_transactions(&mut self) { @@ -215,24 +211,17 @@ impl Context { } pub async fn cleanup_users(&mut self) { - if self.driver.is_none() || !self.driver.as_ref().unwrap().is_open() { + let driver = self.driver.as_ref().unwrap(); + if self.driver.is_none() || !driver.is_open() { return; } - try_join_all( - self.driver - .as_ref() - .unwrap() - .users() - .all() - .await - .unwrap() - .into_iter() - .filter(|user| user.username != Context::ADMIN_USERNAME) - .map(|user| self.driver.as_ref().unwrap().users().delete(user.username)), - ) - .await - .ok(); + for user in driver.users().all().unwrap() { + if user.username == Context::ADMIN_USERNAME { + continue; + } + driver.users().delete(user.username).ok(); + } } pub async fn cleanup_answers(&mut self) { @@ -249,11 +238,11 @@ impl Context { } pub fn transaction_opt(&self) -> Option<&Transaction> { - self.transactions.get(0) + self.transactions.front() } pub fn transaction(&self) -> &Transaction { - self.transactions.get(0).unwrap() + self.transactions.front().unwrap() } pub fn take_transaction(&mut self) -> Transaction { @@ -308,7 +297,7 @@ impl Context { pub async fn unwrap_answer_into_rows(&mut self) { self.collected_rows = - Some(self.answer.take().unwrap().into_rows().map(|result| result.unwrap()).collect::>().await); + Some(self.answer.take().unwrap().into_rows().map(|result| result.unwrap()).collect::>()); } pub async fn unwrap_concurrent_answers_into_rows_streams(&mut self) { @@ -318,7 +307,7 @@ impl Context { pub async fn unwrap_answer_into_documents(&mut self) { self.collected_documents = - Some(self.answer.take().unwrap().into_documents().map(|result| result.unwrap()).collect::>().await); + Some(self.answer.take().unwrap().into_documents().map(|result| result.unwrap()).collect::>()); } pub async fn get_answer(&self) -> Option<&QueryAnswer> { @@ -381,7 +370,7 @@ impl Context { _password: Option<&str>, ) -> TypeDBResult { assert!(!self.is_cloud); - let driver = TypeDBDriver::new_core(address).await?; + let driver = TypeDBDriver::new_core(address)?; self.driver = Some(driver); Ok(()) } diff --git a/rust/tests/behaviour/steps/params.rs b/rust/tests/behaviour/steps/params.rs index 9efef00cdf..605662dbdc 100644 --- a/rust/tests/behaviour/steps/params.rs +++ b/rust/tests/behaviour/steps/params.rs @@ -17,7 +17,7 @@ * under the License. */ -use std::{borrow::Borrow, convert::Infallible, fmt, ops::Not, str::FromStr}; +use std::{borrow::Borrow, convert::Infallible, fmt, str::FromStr}; use chrono::{FixedOffset, NaiveDate, NaiveDateTime, NaiveTime}; use cucumber::Parameter; @@ -295,7 +295,7 @@ macro_rules! check_boolean { pub(crate) use check_boolean; use typedb_driver::concept::{ value::{Decimal, TimeZone}, - Concept, ConceptCategory, + Concept, }; impl FromStr for Boolean { diff --git a/rust/tests/behaviour/steps/query.rs b/rust/tests/behaviour/steps/query.rs index 4f387b31d8..b8960cee16 100644 --- a/rust/tests/behaviour/steps/query.rs +++ b/rust/tests/behaviour/steps/query.rs @@ -17,34 +17,31 @@ * under the License. */ -use std::{collections::VecDeque, ops::Index}; - -use cucumber::{gherkin::Step, given, then, when}; +use cucumber::gherkin::Step; use futures::{future::join_all, StreamExt, TryStreamExt}; use itertools::Itertools; use macro_rules_attribute::apply; use typedb_driver::{ - answer::{ConceptRow, QueryAnswer, JSON}, + answer::{ConceptRow, QueryAnswer}, concept::{AttributeType, Concept, ConceptCategory, EntityType, RelationType, Value, ValueType}, - Result as TypeDBResult, Transaction, + resolve, Result as TypeDBResult, Transaction, }; use crate::{ - assert_err, generic_step, params, + generic_step, params, params::check_boolean, - util, util::{iter_table, list_contains_json, parse_json}, BehaviourTestOptionalError, - BehaviourTestOptionalError::{InvalidValueCasting, VariableDoesNotExist}, + BehaviourTestOptionalError::InvalidValueCasting, Context, }; async fn run_query(transaction: &Transaction, query: impl AsRef) -> TypeDBResult { - transaction.query(query).await + resolve!(transaction.query(query)) } fn get_collected_column_names(concept_row: &ConceptRow) -> Vec { - concept_row.get_column_names().into_iter().cloned().collect() + concept_row.get_column_names().to_vec() } async fn get_answer_rows_var( @@ -280,7 +277,7 @@ pub async fn concurrently_process_rows_from_answers(context: &mut Context, count let mut rows = Vec::new(); for _ in 0..count { - if let Some(row) = stream.next().await { + if let Some(row) = stream.next() { rows.push(row.unwrap()); } else { failed = true; @@ -348,9 +345,9 @@ pub async fn answer_get_row_get_variable_as( may_error: params::MayError, ) { let concept = get_answer_rows_var(context, index, is_by_var_index, var).await.unwrap(); - may_error.check((|| { - kind.matches_concept(concept).then(|| ()).ok_or(BehaviourTestOptionalError::InvalidConceptConversion) - })()); + may_error.check({ + kind.matches_concept(concept).then_some(()).ok_or(BehaviourTestOptionalError::InvalidConceptConversion) + }); } #[apply(generic_step)] @@ -541,7 +538,7 @@ pub async fn answer_get_row_get_variable_get_specific_value( ) { let concept = get_answer_rows_var(context, index, is_by_var_index, var).await.unwrap(); check_concept_is_kind(concept, var_kind, params::Boolean::True); - let actual_value = concept.get_value().expect("Value is expected"); + let _actual_value = concept.get_value().expect("Value is expected"); let expected_value = value.into_typedb(value_type.value_type.clone()); match value_type.value_type { ValueType::Boolean => { @@ -630,8 +627,8 @@ pub async fn answer_get_row_get_variable_is_untyped( ) { let concept = get_answer_rows_var(context, index, is_by_var_index, var).await.unwrap(); check_concept_is_kind(concept, var_kind, params::Boolean::True); - check_boolean!(is_untyped, matches!(concept.get_value_type(), None)); - check_boolean!(is_untyped, matches!(concept.get_value_label(), None)); + check_boolean!(is_untyped, concept.get_value_type().is_none()); + check_boolean!(is_untyped, concept.get_value_label().is_none()); } #[apply(generic_step)] diff --git a/rust/tests/behaviour/steps/util.rs b/rust/tests/behaviour/steps/util.rs index e0bd3274e7..8d81d9ad91 100644 --- a/rust/tests/behaviour/steps/util.rs +++ b/rust/tests/behaviour/steps/util.rs @@ -20,29 +20,15 @@ use std::{ borrow::Cow, collections::{HashMap, HashSet}, - env, iter, mem, - path::{Path, PathBuf}, + env, }; -use chrono::{NaiveDate, NaiveDateTime, NaiveTime}; -use cucumber::{ - gherkin::{Feature, Step}, - given, then, when, StatsWriter, World, -}; -use futures::{ - future::{try_join_all, Either}, - stream::{self, StreamExt}, -}; -use itertools::Itertools; +use cucumber::gherkin::Step; use macro_rules_attribute::apply; use tokio::time::{sleep, Duration}; -use typedb_driver::{ - answer::{ConceptRow, JSON}, - concept::{Attribute, AttributeType, Concept, Entity, EntityType, Relation, RelationType, RoleType, Value}, - DatabaseManager, Error, Result as TypeDBResult, -}; +use typedb_driver::{answer::JSON, Result as TypeDBResult}; -use crate::{assert_with_timeout, generic_step, Context}; +use crate::{generic_step, Context}; pub fn iter_table(step: &Step) -> impl Iterator { step.table().unwrap().rows.iter().flatten().map(String::as_str) diff --git a/rust/tests/integration/core/BUILD b/rust/tests/integration/core/BUILD index 0d195e65a7..aa90d48739 100644 --- a/rust/tests/integration/core/BUILD +++ b/rust/tests/integration/core/BUILD @@ -25,23 +25,23 @@ exports_files( visibility = ["//rust:__subpackages__"], ) -rust_test( - name = "test_example", - srcs = glob(["example.rs"]), - deps = [ - "//rust:typedb_driver", - "@crates//:async-std", - "@crates//:chrono", - "@crates//:futures", - "@crates//:itertools", - "@crates//:regex", - "@crates//:serde_json", - "@crates//:serial_test", - "@crates//:smol", - "@crates//:tokio", - "@crates//:uuid", - ], -) +# rust_test( +# name = "test_example", +# srcs = glob(["example.rs"]), +# deps = [ +# "//rust:typedb_driver", +# "@crates//:async-std", +# "@crates//:chrono", +# "@crates//:futures", +# "@crates//:itertools", +# "@crates//:regex", +# "@crates//:serde_json", +# "@crates//:serial_test", +# "@crates//:smol", +# "@crates//:tokio", +# "@crates//:uuid", +# ], +# ) checkstyle_test( name = "checkstyle", From 8fb08caaf489b8cbfeece83a4fec32c351007c91 Mon Sep 17 00:00:00 2001 From: Dmitrii Ubskii <18616863+dmitrii-ubskii@users.noreply.github.com> Date: Wed, 13 Nov 2024 16:02:04 +0000 Subject: [PATCH 4/4] move `to_string()` impl to `Display` (which provides `to_string`) --- rust/src/common/error.rs | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/rust/src/common/error.rs b/rust/src/common/error.rs index 11a39a43b3..60499d53c1 100644 --- a/rust/src/common/error.rs +++ b/rust/src/common/error.rs @@ -214,19 +214,15 @@ impl ServerError { pub(crate) fn message(&self) -> String { self.to_string() } - - fn to_string(&self) -> String { - if self.stack_trace.is_empty() { - format!("[{}] {}. {}", self.error_code, self.error_domain, self.message) - } else { - format!("\n{}", self.stack_trace.join("\nCaused: ")) - } - } } impl fmt::Display for ServerError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.to_string()) + if self.stack_trace.is_empty() { + write!(f, "[{}] {}. {}", self.error_code, self.error_domain, self.message) + } else { + write!(f, "\n{}", self.stack_trace.join("\nCaused: ")) + } } }