Skip to main content

surrealdb_engine_api/
lib.rs

1//! The service-provider interface between the SurrealDB Rust SDK and the
2//! engines it drives.
3//!
4//! An engine owns a datastore or a connection to one, and serves
5//! [`SurrealEngine`] to the SDK. Some run as a task the SDK hands a [`Route`]
6//! per request, answering on the route's response channel; session lifetime
7//! travels alongside on a separate [`SessionId`] channel either way. This crate
8//! holds exactly the types that cross that boundary, so an engine can live in
9//! its own crate without the SDK depending on it, or on anything it in turn
10//! depends on.
11//!
12//! # Stability
13//!
14//! This is an internal interface between crates released together. It carries
15//! no stability guarantee and may change in any release, including a patch
16//! release. Depend on it only if you implement an engine; application code
17//! should use the [`surrealdb`](https://docs.rs/surrealdb) crate.
18
19// TODO: Remove once this crate no longer needs it; see `absolute_paths` in the workspace lints.
20#![allow(clippy::absolute_paths)]
21
22use std::borrow::Cow;
23use std::fmt::Debug;
24use std::future::Future;
25use std::path::PathBuf;
26use std::pin::Pin;
27
28use async_channel::Sender;
29pub use surrealdb_rpc::QUERY_STREAM_BUFFER;
30pub use surrealdb_rpc::export::Config as DbExportConfig;
31use surrealdb_rpc::{QueryResult, QueryStreamItem, Token, items_for_result};
32use surrealdb_types::{
33	Array, ConnectionError, Error, NotFoundError, Notification, Object, SurrealValue, Value,
34	Variables,
35};
36use uuid::Uuid;
37
38pub mod session;
39
40pub use session::{Established, SessionEntry, SessionRegistry};
41
42/// A future boxed for storage behind a trait object, as
43/// [`SurrealEngine`]'s methods require.
44///
45/// `Send` but deliberately not `Sync`: an engine may await a future from a
46/// client library that is not itself `Sync` (tonic's are not), and requiring
47/// `Sync` here would rule those engines out entirely. Nothing polls one of
48/// these from two threads at once, so `Sync` buys nothing.
49pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
50
51/// A request travelling from the SDK to an engine, tagged with the session it
52/// belongs to.
53#[derive(Debug)]
54pub struct RequestData {
55	/// The operation the engine should perform.
56	pub command: Command,
57	/// The session the command runs under.
58	pub session_id: Uuid,
59}
60
61/// A request paired with the channel its response must be sent on.
62#[derive(Debug)]
63pub struct Route {
64	/// The request to execute.
65	pub request: RequestData,
66	/// Where the engine sends the outcome. Exactly one message is expected.
67	pub response: Sender<Result<Vec<QueryResult>, Error>>,
68}
69
70/// A session-lifetime event. Engines keep per-session state (the authenticated
71/// session, its variables, its live queries), and these events tell them when
72/// to create, copy and discard it.
73#[derive(Debug, Clone, Copy)]
74pub enum SessionId {
75	/// A new session was opened.
76	Initial(Uuid),
77	/// A session was cloned; `new` starts as a copy of `old`.
78	Clone {
79		/// The session being copied.
80		old: Uuid,
81		/// The session receiving the copy.
82		new: Uuid,
83	},
84	/// A session was dropped and its state can be released.
85	Drop(Uuid),
86}
87
88/// Why a route could not be matched to a session.
89#[derive(Debug, Clone)]
90pub enum SessionError {
91	/// No state is registered for the session the route targets.
92	NotFound(Uuid),
93	/// The remote end reported a session failure.
94	Remote(String),
95}
96
97impl From<SessionError> for Error {
98	fn from(error: SessionError) -> Self {
99		session_error_to_error(error)
100	}
101}
102
103/// Convert a session error into the error type the SDK surfaces to callers.
104pub fn session_error_to_error(e: SessionError) -> Error {
105	match e {
106		SessionError::NotFound(id) => Error::not_found(
107			format!("Session not found: {id}"),
108			NotFoundError::Session {
109				id: Some(id.to_string()),
110			},
111		),
112		SessionError::Remote(msg) => Error::internal(msg),
113	}
114}
115
116/// The mode of a read-only transaction opened with `begin`: a snapshot no older
117/// than `max_staleness`, and whether to refuse a current read when no snapshot
118/// meets the bound.
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120pub struct ReadOnlyBegin {
121	pub max_staleness: std::time::Duration,
122	pub strict: bool,
123}
124
125/// The isolation level of a transaction opened with `begin`. Omitted, a
126/// transaction is `Snapshot`.
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128pub enum IsolationLevel {
129	/// The conflict set is the transaction's writes.
130	Snapshot,
131	/// The conflict set is the transaction's writes and everything it read.
132	Serializable,
133}
134
135/// The options object a `begin` call carries on the wire:
136/// `{ isolation, read_only: { max_staleness, strict } }`, or `None` when the
137/// call asks for neither.
138pub fn begin_options(
139	read_only: Option<ReadOnlyBegin>,
140	isolation: Option<IsolationLevel>,
141) -> Option<Value> {
142	if read_only.is_none() && isolation.is_none() {
143		return None;
144	}
145	let mut options = Object::new();
146	if let Some(isolation) = isolation {
147		options.insert(
148			"isolation",
149			match isolation {
150				IsolationLevel::Snapshot => "snapshot",
151				IsolationLevel::Serializable => "serializable",
152			},
153		);
154	}
155	if let Some(read_only) = read_only {
156		let mut entry = Object::new();
157		entry.insert("max_staleness", surrealdb_types::Duration::from(read_only.max_staleness));
158		entry.insert("strict", read_only.strict);
159		options.insert("read_only", Value::Object(entry));
160	}
161	Some(Value::Object(options))
162}
163
164/// A transaction an engine opened: its id and, for a read-only one, the
165/// description of the snapshot it reads (`position`, `age`, `stale`).
166#[derive(Debug, Clone)]
167pub struct OpenedTransaction {
168	pub id: Uuid,
169	pub snapshot: Option<Value>,
170	/// Whether the server answered with an object, which a server that
171	/// understood the call's options always does. A bare id means the options
172	/// were ignored.
173	pub options_acknowledged: bool,
174}
175
176impl OpenedTransaction {
177	/// Reads the answer of a `begin` call: a bare transaction id, or an object
178	/// holding the id and the snapshot of a read-only transaction.
179	pub fn from_reply(reply: Value) -> Result<Self, Error> {
180		match reply {
181			Value::Uuid(id) => Ok(Self {
182				id: id.into_inner(),
183				snapshot: None,
184				options_acknowledged: false,
185			}),
186			Value::Object(mut reply) => {
187				let Some(Value::Uuid(id)) = reply.remove("id") else {
188					return Err(Error::internal(
189						"Begin did not return a transaction id".to_string(),
190					));
191				};
192				Ok(Self {
193					id: id.into_inner(),
194					snapshot: reply.remove("snapshot"),
195					options_acknowledged: true,
196				})
197			}
198			other @ Value::None
199			| other @ Value::Null
200			| other @ Value::Bool(_)
201			| other @ Value::Number(_)
202			| other @ Value::String(_)
203			| other @ Value::Bytes(_)
204			| other @ Value::Duration(_)
205			| other @ Value::Datetime(_)
206			| other @ Value::Date(_)
207			| other @ Value::Time(_)
208			| other @ Value::Timestamp(_)
209			| other @ Value::Interval(_)
210			| other @ Value::Geometry(_)
211			| other @ Value::Table(_)
212			| other @ Value::RecordId(_)
213			| other @ Value::File(_)
214			| other @ Value::Range(_)
215			| other @ Value::Regex(_)
216			| other @ Value::Array(_)
217			| other @ Value::Set(_) => {
218				Err(Error::internal(format!("Begin returned an unexpected value: {other:?}")))
219			}
220		}
221	}
222}
223
224/// The operations an engine can be asked to perform.
225#[derive(Debug, Clone)]
226pub enum Command {
227	/// Select the namespace and/or database for the session.
228	Use {
229		/// The namespace to use, or `None` to leave it unchanged.
230		namespace: Option<String>,
231		/// The database to use, or `None` to leave it unchanged.
232		database: Option<String>,
233	},
234	/// Sign up as a record user and authenticate the session.
235	Signup {
236		/// The signup credentials.
237		credentials: Object,
238	},
239	/// Sign in and authenticate the session.
240	Signin {
241		/// The signin credentials.
242		credentials: Object,
243	},
244	/// Authenticate the session with an existing token.
245	Authenticate {
246		/// The token to authenticate with.
247		token: Token,
248	},
249	/// Exchange a refresh token for a fresh token pair.
250	Refresh {
251		/// The token carrying the refresh token.
252		token: Token,
253	},
254	/// Drop the session's authentication.
255	Invalidate,
256	/// Begin a manual transaction, read-only when `read_only` is set.
257	Begin {
258		read_only: Option<ReadOnlyBegin>,
259		isolation: Option<IsolationLevel>,
260	},
261	/// Cancel a manual transaction.
262	Rollback {
263		/// The transaction to cancel.
264		txn: Uuid,
265	},
266	/// Commit a manual transaction.
267	Commit {
268		/// The transaction to commit.
269		txn: Uuid,
270	},
271	/// Invalidate a refresh token so it can no longer be redeemed.
272	Revoke {
273		/// The token carrying the refresh token.
274		token: Token,
275	},
276	/// Execute a query, optionally inside a manual transaction.
277	Query {
278		/// The transaction to run in, or `None` for an implicit one.
279		txn: Option<Uuid>,
280		/// The query text.
281		query: Cow<'static, str>,
282		/// The variables bound for this query only.
283		variables: Variables,
284	},
285	/// Export the database to a file.
286	ExportFile {
287		/// The file to write.
288		path: PathBuf,
289		/// What to include in the export.
290		config: Option<DbExportConfig>,
291	},
292	/// Export the database to a channel.
293	ExportBytes {
294		/// Where the export is streamed.
295		bytes: Sender<Result<Vec<u8>, Error>>,
296		/// What to include in the export.
297		config: Option<DbExportConfig>,
298	},
299	/// Import a database export from a file.
300	ImportFile {
301		/// The file to read.
302		path: PathBuf,
303	},
304	/// Check that the engine is reachable.
305	Health,
306	/// Report the database version.
307	Version,
308	/// Set a session variable.
309	Set {
310		/// The variable name.
311		key: String,
312		/// The value to bind, or `Value::None` to remove it.
313		value: Value,
314	},
315	/// Remove a session variable.
316	Unset {
317		/// The variable name.
318		key: String,
319	},
320	/// Register the channel a live query's notifications are delivered on.
321	SubscribeLive {
322		/// The live query.
323		uuid: Uuid,
324		/// Where notifications are delivered.
325		notification_sender: Sender<Result<Notification, Error>>,
326	},
327	/// Kill a live query.
328	Kill {
329		/// The live query.
330		uuid: Uuid,
331	},
332	/// Adopt an existing remote session.
333	Attach {
334		/// The session to adopt.
335		session_id: Uuid,
336	},
337	/// Release a remote session without ending it.
338	Detach {
339		/// The session to release.
340		session_id: Uuid,
341	},
342	/// Call a function or a machine learning model.
343	Run {
344		/// The function or model name.
345		name: String,
346		/// The model version, if any.
347		version: Option<String>,
348		/// The arguments to pass.
349		args: Array,
350	},
351}
352
353/// Which session, and which explicit transaction, a request applies to.
354///
355/// Mirrors the `RequestContext` every request carries in the SurrealDB
356/// network protocol, minus the fields the SDK does not populate: an engine
357/// applies its own configured timeouts rather than being told them per call.
358#[derive(Debug, Clone, Copy)]
359pub struct EngineContext {
360	/// The session the request runs under.
361	pub session: Uuid,
362	/// The explicit transaction to run in, or `None` for an implicit one.
363	///
364	/// Only meaningful on [`SurrealEngine::query`]; the transaction-lifecycle
365	/// methods take the transaction they act on as an explicit argument.
366	pub transaction: Option<Uuid>,
367}
368
369impl EngineContext {
370	/// A context for a request outside any explicit transaction.
371	pub fn new(session: Uuid) -> Self {
372		Self {
373			session,
374			transaction: None,
375		}
376	}
377
378	/// A context for a request inside the given explicit transaction.
379	pub fn with_transaction(session: Uuid, transaction: Option<Uuid>) -> Self {
380		Self {
381			session,
382			transaction,
383		}
384	}
385}
386
387/// A boxed engine result.
388pub type EngineFuture<'a, T> = BoxFuture<'a, Result<T, Error>>;
389
390/// Answers a streaming caller from an engine's buffered `query`.
391///
392/// The caller sees the same items either way, just all at once. This is the
393/// right answer for any engine whose transport cannot carry results before the
394/// query ends -- which is most of them.
395fn buffered_query_stream<'a, E>(
396	engine: &'a E,
397	ctx: EngineContext,
398	query: Cow<'static, str>,
399	variables: Variables,
400	items: Sender<QueryStreamItem>,
401) -> EngineFuture<'a, ()>
402where
403	E: SurrealEngine + ?Sized,
404{
405	Box::pin(async move {
406		for (index, result) in engine.query(ctx, query, variables).await?.into_iter().enumerate() {
407			for item in items_for_result(index, result) {
408				// A receiver that has gone away wants no more items, and there
409				// is nothing else to do with them.
410				if items.send(item).await.is_err() {
411					return Ok(());
412				}
413			}
414		}
415		Ok(())
416	})
417}
418
419/// The interface every SurrealDB engine implements, and the only thing the
420/// Rust SDK calls to reach a database.
421///
422/// One method per operation, each taking and returning the types that
423/// operation actually deals in, so no engine has to encode a result into a
424/// generic [`Value`] purely for the SDK to take it apart again. An embedded
425/// engine hands its own values straight back; a remote engine converts once,
426/// from its wire format.
427///
428/// Methods for capabilities an engine may not have -- live queries, export
429/// and import -- default to reporting that they are unsupported, so an engine
430/// implements only what it serves. The SDK gates most of these on
431/// `ExtraFeatures` before calling, so the default is a backstop rather than
432/// the usual path.
433///
434/// # Stability
435///
436/// This is an internal interface between crates released together. It carries
437/// no stability guarantee and may change in any release, including a patch
438/// release.
439pub trait SurrealEngine: Debug + Send + Sync + 'static {
440	// ------------------------------------------------------------------
441	// Queries
442	// ------------------------------------------------------------------
443
444	/// Executes SurrealQL, returning one result per statement, in order.
445	fn query(
446		&self,
447		ctx: EngineContext,
448		query: Cow<'static, str>,
449		variables: Variables,
450	) -> EngineFuture<'_, Vec<QueryResult>>;
451
452	/// Executes SurrealQL, sending results into `items` as they are produced.
453	///
454	/// The returned future is the execution: drive it while draining `items`,
455	/// and treat the channel closing as "no more results" rather than as
456	/// success, since a failure that belongs to no single statement is reported
457	/// by the future.
458	///
459	/// The default answers from [`Self::query`] and replays the finished
460	/// results, which is what an engine whose transport cannot carry
461	/// incremental results should do — the caller sees the same items either
462	/// way, just all at once. Overriding it is worthwhile only where results
463	/// can actually reach the caller before the query ends.
464	///
465	/// Rows are provisional until their statement's
466	/// [`Finished`](QueryStreamItem::Finished) item arrives; see
467	/// [`QueryStreamItem`].
468	fn query_stream(
469		&self,
470		ctx: EngineContext,
471		query: Cow<'static, str>,
472		variables: Variables,
473		items: Sender<QueryStreamItem>,
474	) -> EngineFuture<'_, ()> {
475		buffered_query_stream(self, ctx, query, variables, items)
476	}
477
478	/// Calls a function, or a machine learning model when `version` is set.
479	fn run(
480		&self,
481		ctx: EngineContext,
482		name: String,
483		version: Option<String>,
484		args: Array,
485	) -> EngineFuture<'_, Value>;
486
487	// ------------------------------------------------------------------
488	// Session state
489	// ------------------------------------------------------------------
490
491	/// Selects the namespace and/or database, returning the resulting
492	/// selection. `None` for either argument leaves that one unchanged.
493	fn use_ns_db(
494		&self,
495		ctx: EngineContext,
496		namespace: Option<String>,
497		database: Option<String>,
498	) -> EngineFuture<'_, (Option<String>, Option<String>)>;
499
500	/// Binds a session variable.
501	fn set(&self, ctx: EngineContext, key: String, value: Value) -> EngineFuture<'_, ()>;
502
503	/// Removes a session variable.
504	fn unset(&self, ctx: EngineContext, key: String) -> EngineFuture<'_, ()>;
505
506	// ------------------------------------------------------------------
507	// Authentication
508	// ------------------------------------------------------------------
509
510	/// Registers a record user and authenticates the session as them.
511	fn signup(&self, ctx: EngineContext, credentials: Object) -> EngineFuture<'_, Token>;
512
513	/// Authenticates the session with credentials.
514	fn signin(&self, ctx: EngineContext, credentials: Object) -> EngineFuture<'_, Token>;
515
516	/// Authenticates the session with an existing token, returning the token
517	/// now in effect.
518	///
519	/// A server may hand back a token of its own rather than the one it was
520	/// given, so the result is what the session is authenticated with -- not
521	/// necessarily the argument.
522	fn authenticate(&self, ctx: EngineContext, token: Token) -> EngineFuture<'_, Token>;
523
524	/// Exchanges a refresh token for a fresh token pair.
525	fn refresh(&self, ctx: EngineContext, token: Token) -> EngineFuture<'_, Token>;
526
527	/// Invalidates a refresh token so it can no longer be redeemed.
528	fn revoke(&self, ctx: EngineContext, token: Token) -> EngineFuture<'_, ()>;
529
530	/// Drops the session's authentication.
531	fn invalidate(&self, ctx: EngineContext) -> EngineFuture<'_, ()>;
532
533	// ------------------------------------------------------------------
534	// Transactions
535	// ------------------------------------------------------------------
536
537	/// Opens an explicit transaction, returning its id and, when `read_only` is
538	/// set, the snapshot it reads.
539	fn begin(
540		&self,
541		ctx: EngineContext,
542		read_only: Option<ReadOnlyBegin>,
543		isolation: Option<IsolationLevel>,
544	) -> EngineFuture<'_, OpenedTransaction>;
545
546	/// Commits an explicit transaction.
547	fn commit(&self, ctx: EngineContext, txn: Uuid) -> EngineFuture<'_, ()>;
548
549	/// Cancels an explicit transaction.
550	fn rollback(&self, ctx: EngineContext, txn: Uuid) -> EngineFuture<'_, ()>;
551
552	// ------------------------------------------------------------------
553	// Connection
554	// ------------------------------------------------------------------
555
556	/// Checks that the engine is reachable.
557	fn health(&self, ctx: EngineContext) -> EngineFuture<'_, ()>;
558
559	/// Reports the database version, as the server spells it (for example
560	/// `surrealdb-3.0.0`).
561	fn version(&self, ctx: EngineContext) -> EngineFuture<'_, String>;
562
563	/// Resolves once the engine has stopped: for an embedded engine, its
564	/// datastore has shut down and its background tasks no longer hold it, so
565	/// dropping the engine releases the storage. A failure to shut the
566	/// datastore down is reported to the first caller.
567	///
568	/// The caller has by then ended every session, which is what stops an
569	/// embedded engine; this only waits for that to finish. The default
570	/// returns immediately, which is right for an engine whose resources
571	/// belong to something else, such as a connection to a remote server.
572	fn shutdown(&self) -> EngineFuture<'_, ()> {
573		Box::pin(async { Ok(()) })
574	}
575
576	// ------------------------------------------------------------------
577	// Live queries
578	// ------------------------------------------------------------------
579
580	/// Registers the channel a live query's notifications are delivered on.
581	fn subscribe_live(
582		&self,
583		_ctx: EngineContext,
584		_uuid: Uuid,
585		_notifications: Sender<Result<Notification, Error>>,
586	) -> EngineFuture<'_, ()> {
587		Box::pin(async { Err(unsupported("Live queries")) })
588	}
589
590	/// Kills a live query.
591	fn kill(&self, _ctx: EngineContext, _uuid: Uuid) -> EngineFuture<'_, ()> {
592		Box::pin(async { Err(unsupported("Live queries")) })
593	}
594
595	// ------------------------------------------------------------------
596	// Export and import
597	// ------------------------------------------------------------------
598
599	/// Exports the database to a file.
600	fn export_file(
601		&self,
602		_ctx: EngineContext,
603		_path: PathBuf,
604		_config: Option<DbExportConfig>,
605	) -> EngineFuture<'_, ()> {
606		Box::pin(async { Err(unsupported("Export")) })
607	}
608
609	/// Exports the database, streaming it to a channel.
610	fn export_bytes(
611		&self,
612		_ctx: EngineContext,
613		_bytes: Sender<Result<Vec<u8>, Error>>,
614		_config: Option<DbExportConfig>,
615	) -> EngineFuture<'_, ()> {
616		Box::pin(async { Err(unsupported("Export")) })
617	}
618
619	/// Imports a database export from a file.
620	fn import_file(&self, _ctx: EngineContext, _path: PathBuf) -> EngineFuture<'_, ()> {
621		Box::pin(async { Err(unsupported("Import")) })
622	}
623}
624
625/// The error an engine reports for an operation it does not serve.
626fn unsupported(what: &str) -> Error {
627	Error::configuration(format!("{what} is not supported by this engine"), None)
628}
629
630/// Flattens the results of an operation that runs a single statement into the
631/// one value it produced.
632///
633/// An empty reply reads as [`Value::None`]: an operation with no result may
634/// answer with either, and both mean the same thing. Anything longer than one
635/// result is a bug in the engine rather than something to report to the user.
636pub fn single_result(mut results: Vec<QueryResult>) -> Result<Value, Error> {
637	match results.len() {
638		0 => Ok(Value::None),
639		1 => results.remove(0).result,
640		_ => Err(Error::internal("expected the database to return one or no results".to_string())),
641	}
642}
643
644/// A [`SurrealEngine`] that drives an engine which consumes [`Route`]s.
645///
646/// The WebSocket and HTTP engines each run a task that reads `Route`s off a
647/// channel and answers on the response channel a `Route` carries -- the
648/// channel is also their session replay log, so a reconnection can rebuild
649/// what the connection had established. This adapter is the whole of what it
650/// takes to expose one of them through [`SurrealEngine`]: it turns each typed
651/// call back into the [`Command`] that task already understands, and unwraps
652/// the single response into the type the method promises.
653///
654/// [`Command`] is therefore an implementation detail of those two engines, not
655/// part of the interface: an engine with no route channel -- the embedded and
656/// gRPC ones -- never constructs a `Command` at all.
657#[derive(Debug, Clone)]
658pub struct RouteChannelEngine {
659	sender: Sender<Route>,
660}
661
662impl RouteChannelEngine {
663	/// Wraps a route sender as a [`SurrealEngine`].
664	pub fn new(sender: Sender<Route>) -> Self {
665		Self {
666			sender,
667		}
668	}
669
670	/// Sends one command and awaits its single response, flattening the
671	/// engine's `Vec<QueryResult>` reply into the one value these
672	/// non-`query` operations return.
673	///
674	/// An empty reply reads as [`Value::None`]: the route protocol lets an
675	/// engine answer a no-result operation with either an empty vector or a
676	/// single `Value::None`, and both mean the same thing.
677	async fn value(&self, command: Command, session: Uuid) -> Result<Value, Error> {
678		single_result(self.results(command, session).await?)
679	}
680
681	/// Sends one command and awaits its single response.
682	async fn results(&self, command: Command, session: Uuid) -> Result<Vec<QueryResult>, Error> {
683		let (response, receiver) = async_channel::bounded(1);
684		let route = Route {
685			request: RequestData {
686				command,
687				session_id: session,
688			},
689			response,
690		};
691		// Both failure modes mean the engine task is gone, which callers
692		// distinguish from a database error with `Error::is_connection()` to
693		// decide whether reconnecting is worth trying.
694		self.sender.send(route).await.map_err(|e| {
695			Error::connection(
696				format!("Failed to send command: {e}"),
697				ConnectionError::ConnectionFailed,
698			)
699		})?;
700		receiver.recv().await.map_err(|_| {
701			Error::connection(
702				"The engine dropped the request without answering".to_string(),
703				ConnectionError::ConnectionFailed,
704			)
705		})?
706	}
707
708	/// Sends one command whose response carries nothing of interest.
709	async fn unit(&self, command: Command, session: Uuid) -> Result<(), Error> {
710		match self.value(command, session).await? {
711			Value::None | Value::Null => Ok(()),
712			Value::Array(array) if array.is_empty() => Ok(()),
713			Value::Bool(_)
714			| Value::Number(_)
715			| Value::String(_)
716			| Value::Bytes(_)
717			| Value::Duration(_)
718			| Value::Datetime(_)
719			| Value::Date(_)
720			| Value::Time(_)
721			| Value::Timestamp(_)
722			| Value::Interval(_)
723			| Value::Uuid(_)
724			| Value::Geometry(_)
725			| Value::Table(_)
726			| Value::RecordId(_)
727			| Value::File(_)
728			| Value::Range(_)
729			| Value::Regex(_)
730			| Value::Array(_)
731			| Value::Object(_)
732			| Value::Set(_) => Err(Error::internal("expected the database to return nothing".to_string())),
733		}
734	}
735}
736
737/// Converts the value an engine returns for signin/signup/refresh into a
738/// [`Token`].
739///
740/// These engines answer with the token's wire form (a bare string, or an
741/// object carrying `token` and `refresh`), which is exactly what `Token`
742/// deserialises from.
743fn value_to_token(value: Value) -> Result<Token, Error> {
744	// signin/signup answers historically arrive wrapped in a single-element
745	// array from some engines; unwrap that before converting.
746	let value = match value {
747		Value::Array(array) if array.len() == 1 => {
748			array.into_iter().next().expect("array has exactly one element")
749		}
750		value @ Value::None
751		| value @ Value::Null
752		| value @ Value::Bool(_)
753		| value @ Value::Number(_)
754		| value @ Value::String(_)
755		| value @ Value::Bytes(_)
756		| value @ Value::Duration(_)
757		| value @ Value::Datetime(_)
758		| value @ Value::Date(_)
759		| value @ Value::Time(_)
760		| value @ Value::Timestamp(_)
761		| value @ Value::Interval(_)
762		| value @ Value::Uuid(_)
763		| value @ Value::Geometry(_)
764		| value @ Value::Table(_)
765		| value @ Value::RecordId(_)
766		| value @ Value::File(_)
767		| value @ Value::Range(_)
768		| value @ Value::Regex(_)
769		| value @ Value::Array(_)
770		| value @ Value::Object(_)
771		| value @ Value::Set(_) => value,
772	};
773	Token::from_value(value)
774}
775
776impl SurrealEngine for RouteChannelEngine {
777	fn query(
778		&self,
779		ctx: EngineContext,
780		query: Cow<'static, str>,
781		variables: Variables,
782	) -> EngineFuture<'_, Vec<QueryResult>> {
783		Box::pin(self.results(
784			Command::Query {
785				txn: ctx.transaction,
786				query,
787				variables,
788			},
789			ctx.session,
790		))
791	}
792
793	fn run(
794		&self,
795		ctx: EngineContext,
796		name: String,
797		version: Option<String>,
798		args: Array,
799	) -> EngineFuture<'_, Value> {
800		Box::pin(self.value(
801			Command::Run {
802				name,
803				version,
804				args,
805			},
806			ctx.session,
807		))
808	}
809
810	fn use_ns_db(
811		&self,
812		ctx: EngineContext,
813		namespace: Option<String>,
814		database: Option<String>,
815	) -> EngineFuture<'_, (Option<String>, Option<String>)> {
816		Box::pin(async move {
817			let value = self
818				.value(
819					Command::Use {
820						namespace,
821						database,
822					},
823					ctx.session,
824				)
825				.await?;
826			// Engines that predate reporting the resulting selection answer
827			// with something other than an object; report "unknown" rather
828			// than failing, as the SDK has always done.
829			let Value::Object(object) = value else {
830				return Ok((None, None));
831			};
832			let read = |key: &str| object.get(key).and_then(|v| v.as_string()).map(String::from);
833			Ok((read("namespace"), read("database")))
834		})
835	}
836
837	fn set(&self, ctx: EngineContext, key: String, value: Value) -> EngineFuture<'_, ()> {
838		Box::pin(self.unit(
839			Command::Set {
840				key,
841				value,
842			},
843			ctx.session,
844		))
845	}
846
847	fn unset(&self, ctx: EngineContext, key: String) -> EngineFuture<'_, ()> {
848		Box::pin(self.unit(
849			Command::Unset {
850				key,
851			},
852			ctx.session,
853		))
854	}
855
856	fn signup(&self, ctx: EngineContext, credentials: Object) -> EngineFuture<'_, Token> {
857		Box::pin(async move {
858			let value = self
859				.value(
860					Command::Signup {
861						credentials,
862					},
863					ctx.session,
864				)
865				.await?;
866			value_to_token(value)
867		})
868	}
869
870	fn signin(&self, ctx: EngineContext, credentials: Object) -> EngineFuture<'_, Token> {
871		Box::pin(async move {
872			let value = self
873				.value(
874					Command::Signin {
875						credentials,
876					},
877					ctx.session,
878				)
879				.await?;
880			value_to_token(value)
881		})
882	}
883
884	fn authenticate(&self, ctx: EngineContext, token: Token) -> EngineFuture<'_, Token> {
885		Box::pin(async move {
886			let value = self
887				.value(
888					Command::Authenticate {
889						token,
890					},
891					ctx.session,
892				)
893				.await?;
894			value_to_token(value)
895		})
896	}
897
898	fn refresh(&self, ctx: EngineContext, token: Token) -> EngineFuture<'_, Token> {
899		Box::pin(async move {
900			let value = self
901				.value(
902					Command::Refresh {
903						token,
904					},
905					ctx.session,
906				)
907				.await?;
908			value_to_token(value)
909		})
910	}
911
912	fn revoke(&self, ctx: EngineContext, token: Token) -> EngineFuture<'_, ()> {
913		Box::pin(self.unit(
914			Command::Revoke {
915				token,
916			},
917			ctx.session,
918		))
919	}
920
921	fn invalidate(&self, ctx: EngineContext) -> EngineFuture<'_, ()> {
922		Box::pin(self.unit(Command::Invalidate, ctx.session))
923	}
924
925	fn begin(
926		&self,
927		ctx: EngineContext,
928		read_only: Option<ReadOnlyBegin>,
929		isolation: Option<IsolationLevel>,
930	) -> EngineFuture<'_, OpenedTransaction> {
931		Box::pin(async move {
932			let reply = self
933				.value(
934					Command::Begin {
935						read_only,
936						isolation,
937					},
938					ctx.session,
939				)
940				.await?;
941			let opened = OpenedTransaction::from_reply(reply)?;
942			// A server that predates the options ignores them and answers with
943			// a bare id for an ordinary transaction. A transaction that is not
944			// the one asked for is released and refused, not handed back: a
945			// read-only or serializable request must never be quietly weaker.
946			if (read_only.is_some() || isolation.is_some()) && !opened.options_acknowledged {
947				let _ = self.rollback(ctx, opened.id).await;
948				return Err(Error::validation(
949					"The server did not honour the transaction options; it may not support them"
950						.to_string(),
951					None,
952				));
953			}
954			Ok(opened)
955		})
956	}
957
958	fn commit(&self, ctx: EngineContext, txn: Uuid) -> EngineFuture<'_, ()> {
959		Box::pin(async move {
960			self.value(
961				Command::Commit {
962					txn,
963				},
964				ctx.session,
965			)
966			.await?;
967			Ok(())
968		})
969	}
970
971	fn rollback(&self, ctx: EngineContext, txn: Uuid) -> EngineFuture<'_, ()> {
972		Box::pin(async move {
973			self.value(
974				Command::Rollback {
975					txn,
976				},
977				ctx.session,
978			)
979			.await?;
980			Ok(())
981		})
982	}
983
984	fn health(&self, ctx: EngineContext) -> EngineFuture<'_, ()> {
985		Box::pin(self.unit(Command::Health, ctx.session))
986	}
987
988	fn version(&self, ctx: EngineContext) -> EngineFuture<'_, String> {
989		Box::pin(async move {
990			let value = self.value(Command::Version, ctx.session).await?;
991			value.into_string().map_err(|e| Error::internal(e.to_string()))
992		})
993	}
994
995	fn subscribe_live(
996		&self,
997		ctx: EngineContext,
998		uuid: Uuid,
999		notifications: Sender<Result<Notification, Error>>,
1000	) -> EngineFuture<'_, ()> {
1001		Box::pin(self.unit(
1002			Command::SubscribeLive {
1003				uuid,
1004				notification_sender: notifications,
1005			},
1006			ctx.session,
1007		))
1008	}
1009
1010	fn kill(&self, ctx: EngineContext, uuid: Uuid) -> EngineFuture<'_, ()> {
1011		Box::pin(self.unit(
1012			Command::Kill {
1013				uuid,
1014			},
1015			ctx.session,
1016		))
1017	}
1018
1019	fn export_file(
1020		&self,
1021		ctx: EngineContext,
1022		path: PathBuf,
1023		config: Option<DbExportConfig>,
1024	) -> EngineFuture<'_, ()> {
1025		Box::pin(self.unit(
1026			Command::ExportFile {
1027				path,
1028				config,
1029			},
1030			ctx.session,
1031		))
1032	}
1033
1034	fn export_bytes(
1035		&self,
1036		ctx: EngineContext,
1037		bytes: Sender<Result<Vec<u8>, Error>>,
1038		config: Option<DbExportConfig>,
1039	) -> EngineFuture<'_, ()> {
1040		Box::pin(self.unit(
1041			Command::ExportBytes {
1042				bytes,
1043				config,
1044			},
1045			ctx.session,
1046		))
1047	}
1048
1049	fn import_file(&self, ctx: EngineContext, path: PathBuf) -> EngineFuture<'_, ()> {
1050		Box::pin(self.unit(
1051			Command::ImportFile {
1052				path,
1053			},
1054			ctx.session,
1055		))
1056	}
1057}
1058
1059#[cfg(test)]
1060mod tests {
1061	use surrealdb_types::Value;
1062
1063	use super::*;
1064
1065	/// The buffered adaptation produces the same items a streaming engine
1066	/// would, so a caller cannot tell which one answered.
1067	#[tokio::test]
1068	async fn the_buffered_adaptation_produces_the_same_items() {
1069		let (sender, routes) = async_channel::bounded(1);
1070		let engine = RouteChannelEngine::new(sender);
1071		let (items, received) = async_channel::bounded(8);
1072		let stream = engine.query_stream(
1073			EngineContext::new(Uuid::nil()),
1074			Cow::Borrowed("SELECT * FROM thing"),
1075			Variables::default(),
1076			items,
1077		);
1078		let serve = async {
1079			let route = routes.recv().await.expect("a route");
1080			let _ = route
1081				.response
1082				.send(Ok(vec![QueryResult {
1083					time: std::time::Duration::ZERO,
1084					result: Ok(Value::Array(vec![Value::Bool(true)].into())),
1085					query_type: surrealdb_rpc::QueryType::Other,
1086				}]))
1087				.await;
1088		};
1089		let (outcome, ()) = futures::future::join(stream, serve).await;
1090		outcome.expect("the engine answered");
1091
1092		let mut items = Vec::new();
1093		while let Ok(item) = received.try_recv() {
1094			items.push(item);
1095		}
1096		assert!(matches!(items[0], QueryStreamItem::Rows { .. }), "a list becomes rows");
1097		assert!(
1098			matches!(
1099				items[1],
1100				QueryStreamItem::Finished {
1101					error: None,
1102					..
1103				}
1104			),
1105			"and the statement is terminated"
1106		);
1107		assert_eq!(items.len(), 2);
1108	}
1109}