Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
221 changes: 221 additions & 0 deletions napi/src/connection.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
// Copyright (c) 2026 Databricks, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Opaque `Connection` wrapper around the kernel's `Session`.
//!
//! The kernel collapses ADBC's `Database` + `Connection` into a single
//! `Session`. We keep the wrapper name `Connection` on the JS side
//! because that matches the existing Node driver's mental model.
//!
//! - `Connection.executeStatement(sql)` — builds a kernel `Statement`,
//! sets the SQL, awaits `execute()`, and wraps the result in a
//! JS-visible `Statement` opaque handle. Catalog / schema /
//! sessionConf are session-level (`openSession` options) — the SEA
//! wire protocol carries them on `CreateSession`, not per-statement.
//! - `Connection.close()` — explicit async close. Drop schedules a
//! fire-and-forget close on the captured runtime handle if explicit
//! close was never called.

use std::sync::Arc;
use tokio::sync::Mutex;

use databricks_sql_kernel::{Error as KernelError, Session};

use crate::error::napi_err_from_kernel;
use crate::runtime;
use crate::statement::Statement;
use crate::util::guarded;

/// Closed-state error builder. Mirrors `statement::statement_closed_err`
/// — route through the kernel envelope so the TS reviver mints a typed
/// `KernelError(code='InvalidStatementHandle')`. Single source of truth
/// for `executeStatement` on a closed Connection.
fn connection_closed_err() -> napi::Error {
napi_err_from_kernel(
KernelError::invalid_statement_handle().message("connection already closed"),
)
}

/// Opaque connection handle wrapping a kernel `Session`.
///
/// `inner` is `Arc<Mutex<Option<Session>>>` so:
/// - the Drop impl can clone the `Arc` and `.take()` the session on a
/// background tokio task without holding `&mut self` (which Drop is
/// forbidden from doing across an `await`),
/// - `close()` can `.take()` the session to consume it for the kernel's
/// move-by-value `Session::close(self)` signature.
///
/// **Current concurrency shape** — `executeStatement` holds
/// `inner.lock()` across `stmt.execute().await`, so two concurrent
/// `Promise.all([executeStatement(q1), executeStatement(q2)])` calls
/// on the same Connection serialise even though the kernel transport
/// supports concurrent statements per session, and `close()` blocks
/// behind any in-flight execute. The kernel's `Session::statement()`
/// is `&self`-callable, so the right shape is `Arc<Session>` with
/// concurrent execute paths; that lands in the follow-up lock-shape
/// refactor — see
/// `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`.
#[napi]
pub struct Connection {
pub(crate) inner: Arc<Mutex<Option<Session>>>,
/// Server-issued session id. Cached at construction; readable
/// even after `close()` so JS-side log lines can correlate
/// against kernel / server logs which key on the same id.
pub(crate) session_id: String,
}

#[napi]
impl Connection {
/// Server-issued session id. Cached at construction; readable
/// even after `close()` so JS-side log lines can correlate
/// against kernel / server logs which key on the same id.
#[napi(getter)]
pub fn session_id(&self) -> &str {
&self.session_id
}

/// Execute a SQL statement and return a Statement handle that
/// streams batches via `fetchNextBatch()`.
///
/// No per-statement options: catalog / schema / sessionConf are
/// session-level (`openSession`).
#[napi]
pub async fn execute_statement(&self, sql: String) -> napi::Result<Statement> {
let inner = Arc::clone(&self.inner);
guarded(async move {
let guard = inner.lock().await;
let session = guard.as_ref().ok_or_else(connection_closed_err)?;

let mut stmt = session.statement();
stmt.spec().sql(sql);

let executed = stmt.execute().await.map_err(napi_err_from_kernel)?;
// Pass the parent kernel `Statement` into the JS wrapper.
// Dropping it here would invalidate the executed handle
// via the shared ValidityFlag — see `StatementInner` docs
// in `statement.rs` for the rationale.
Ok(Statement::from_executed(stmt, executed))
})
.await
}

/// Explicit close. Awaits the server-side `DeleteSession` so the
/// JS caller can observe failures (auth revoked mid-session,
/// warehouse stopped, network error). Idempotent — a second call
/// on an already-closed connection returns `Ok`.
///
/// **Errors are terminal from the JS side.** The kernel session
/// handle is consumed (`take()`) BEFORE the wire `DeleteSession`
/// runs, because `Session::close` takes `self` by value. On `Err`,
/// the napi `inner` is already `None`, so a JS-side retry sees a
/// closed connection and returns `Ok(())` without re-attempting
/// the wire call. The kernel's own `Drop` fire-and-forget retry
/// runs once in the background — the JS caller can log the error
/// but cannot drive a retry. If you need retry-on-failure
/// semantics for `DeleteSession`, layer them above this method.
#[napi]
pub async fn close(&self) -> napi::Result<()> {
let inner = Arc::clone(&self.inner);
guarded(async move {
let session = {
let mut guard = inner.lock().await;
guard.take()
};
let Some(session) = session else {
return Ok(());
};
session.close().await.map_err(napi_err_from_kernel)
})
.await
}
}

impl Drop for Connection {
fn drop(&mut self) {
// Best-effort cleanup: schedule a drop of the kernel handle on
// the captured tokio runtime. JS callers who need a
// guaranteed `DeleteSession` round-trip must call `close()`
// explicitly — `Drop` cannot `.await` and cannot surface
// failures, and the spawned task is subject to the runtime's
// lifetime. If process exit tears down the runtime before the
// task runs, the handle is dropped without a wire close; the
// server reclaims the session on its idle-timeout schedule.
let Some(handle) = runtime::try_get_handle() else {
// No async entry point ever ran — there's nothing to close.
return;
};
let inner = Arc::clone(&self.inner);
handle.spawn(async move {
// Drop the session value on the runtime. The kernel's
// `SessionInner::Drop` spawns a fire-and-forget
// `delete_session` against its own captured handle, so
// dropping inside a tokio context is sufficient cleanup.
let _taken = {
let mut guard = inner.lock().await;
guard.take()
};
});
}
}

#[cfg(test)]
mod tests {
use super::*;

// The closed-state error shape pins the TS adapter's reviver
// contract — a future maintainer who switches back to raw
// `napi::Error::new(Status::InvalidArg, "...")` will break this
// test instead of silently breaking the adapter.

fn assert_invalid_statement_handle_envelope(err: &napi::Error) {
let msg = err.reason.as_str();
assert!(
msg.starts_with(crate::error::ERROR_SENTINEL),
"expected envelope-sentinel-prefixed error, got: {msg}",
);
assert!(
msg.contains(r#""code":"InvalidStatementHandle""#),
"envelope payload missing InvalidStatementHandle code: {msg}",
);
}

#[test]
fn connection_closed_err_carries_invalid_statement_handle_envelope() {
let err = connection_closed_err();
assert_invalid_statement_handle_envelope(&err);
assert!(
err.reason.contains("connection already closed"),
"closed-state error must carry the human message: {}",
err.reason,
);
}

#[test]
fn connection_closed_err_status_collapses_to_invalid_arg() {
let err = connection_closed_err();
assert_eq!(err.status, napi::Status::InvalidArg);
}

#[test]
fn session_id_is_cached_and_survives_close() {
// The cached id is stored on the wrapper, not on the kernel
// Session — so even after close() takes the session out of
// `inner`, the getter still returns the original id.
let conn = Connection {
inner: Arc::new(Mutex::new(None)), // "already closed"
session_id: "session-survives-close".to_owned(),
};
assert_eq!(conn.session_id(), "session-survives-close");
}
}
126 changes: 126 additions & 0 deletions napi/src/database.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
// Copyright (c) 2026 Databricks, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! `openSession()` — the binding's session-construction entry point.
//!
//! The kernel collapses ADBC's `Database` + `Connection` into a single
//! `Session`. The TS adapter layer reconstructs a `DBSQLClient` /
//! `Database` wrapper on top of this binding, so the napi surface itself
//! stays flat: one free function, one opaque `Connection` class.
//!
//! A free function (not a static method on a wrapper class) because
//! there is no kernel-side `Database` state to hold — everything
//! meaningful lives on `Session`. A `Database` wrapper class with no
//! fields would add a JS object allocation per session for no benefit.

use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::Mutex;

use databricks_sql_kernel::{AuthConfig, DefaultOpts, Session};

use crate::connection::Connection;
use crate::error::napi_err_from_kernel;
use crate::runtime;
use crate::util::guarded;

/// JS-visible options for opening a Databricks SQL session over PAT.
/// `token` is required.
///
/// Catalog / schema / sessionConf are applied once at session creation
/// and remain in effect for every statement run on the resulting
/// `Connection`. The SEA wire protocol carries them on
/// `CreateSession`, not on `ExecuteStatement` — so there is no
/// per-statement override path on this binding.
#[allow(
dead_code,
reason = "exported via napi macro codegen; not called from Rust"
)]
#[napi(object)]
pub struct ConnectionOptions {
/// Workspace host, e.g. `adb-…azuredatabricks.net`. The kernel
/// normalises this — bare hostnames get `https://` prepended.
pub host_name: String,
/// JDBC-style HTTP path, e.g. `/sql/1.0/warehouses/abc123`. The
/// kernel parses out the warehouse id.
pub http_path: String,
/// Personal access token. Must be non-empty (the kernel rejects
/// empty PATs at session construction).
pub token: String,
/// Default catalog for statements executed on this session.
/// Routed through the kernel's `DefaultOpts` and onto the SEA
/// `CreateSession.catalog` wire field.
pub catalog: Option<String>,
/// Default schema for statements executed on this session.
/// Routed through the kernel's `DefaultOpts` and onto the SEA
/// `CreateSession.schema` wire field.
pub schema: Option<String>,
/// Server-bound session conf (Spark conf, `ANSI_MODE`, `TIMEZONE`,
/// query-tag presets, …). Forwarded verbatim to SEA
/// `session_confs`. Unknown keys are rejected server-side.
pub session_conf: Option<HashMap<String, String>>,
}

/// Open a Databricks SQL session over PAT auth and return an opaque
/// `Connection` wrapping the kernel `Session`.
///
/// The JS-visible name is `openSession` (napi-rs converts snake_case
/// to camelCase for free functions).
#[allow(
dead_code,
reason = "exported via napi macro codegen; not called from Rust"
)]
#[napi]
pub async fn open_session(options: ConnectionOptions) -> napi::Result<Connection> {
guarded(async move {
// Cache the napi-rs tokio Handle on the very first async call
// so Drop impls (which run on the V8 GC thread, outside any
// tokio context) can still `spawn` cleanup tasks onto the
// runtime that's driving this future.
let _ = runtime::get_handle();

// SessionConfig is `#[non_exhaustive]` — go through the
// builder, which is the only public path that constructs it.
// `http_path()` is the convenience setter that maps a bare
// hostname + `/sql/1.0/warehouses/{id}` path into the kernel's
// `ConnectionConfig`.
let mut builder = Session::builder()
.http_path(options.host_name, options.http_path)
.auth(AuthConfig::Pat {
token: options.token,
});
// Only wire `DefaultOpts` when at least one of catalog / schema
// was provided; otherwise leave the config's `defaults` field
// `None` so the kernel can distinguish "no defaults" from
// "empty defaults" if that distinction ever becomes meaningful.
// `DefaultOpts` is `#[non_exhaustive]` — must construct via
// `default()` and mutate fields.
if options.catalog.is_some() || options.schema.is_some() {
let mut defaults = DefaultOpts::default();
defaults.catalog = options.catalog;
defaults.schema = options.schema;
builder = builder.defaults(defaults);
}
if let Some(conf) = options.session_conf {
builder = builder.session_conf(conf);
}
let session = builder.open().await.map_err(napi_err_from_kernel)?;
let session_id = session.session_id().to_owned();
Ok(Connection {
inner: Arc::new(Mutex::new(Some(session))),
session_id,
})
})
.await
}
15 changes: 10 additions & 5 deletions napi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,12 @@
//! `databricks-sea-native` — napi-rs binding crate for the Databricks
//! SQL Node.js driver's SEA (Statement Execution API) path.
//!
//! **Skeleton commit.** This commit lands the crate's infrastructure:
//! Cargo manifest, build script, error envelope formatter, tokio
//! runtime helper, `tracing` logger bridge, and shared utilities.
//! The actual `#[napi]` classes (`Database`, `Connection`, `Statement`,
//! `ResultStream`) are added in the follow-up commit.
//! Surface: `openSession()` (free function) → `Connection` (opaque
//! class with `executeStatement` / `close` / `sessionId`) →
//! `Statement` (opaque class with `fetchNextBatch` / `schema` /
//! `cancel` / `close` / `statementId`). Results cross the FFI as
//! Arrow IPC bytes (`ArrowBatch` / `ArrowSchema` POJOs in
//! `result.rs`); the TS adapter decodes them via `apache-arrow`.

#![deny(unsafe_op_in_unsafe_fn)]
// Skeleton-PR state: every `pub(crate)` item in this crate (error
Expand All @@ -38,9 +39,13 @@
#[macro_use]
extern crate napi_derive;

pub(crate) mod connection;
pub(crate) mod database;
pub(crate) mod error;
pub(crate) mod logger;
pub(crate) mod result;
pub(crate) mod runtime;
pub(crate) mod statement;
pub(crate) mod util;

/// Returns the native binding's crate version (`CARGO_PKG_VERSION`).
Expand Down
Loading