Skip to content

Commit e71a7af

Browse files
committed
feat(feature-flags): add Node and Python typed getters
Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com>
1 parent e7a5e97 commit e71a7af

8 files changed

Lines changed: 485 additions & 14 deletions

File tree

‎napi/NEXT_CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,14 @@ layout, or npm publishing. Pure-kernel changes go in the root
1414

1515
### Added
1616

17+
- Add typed `Connection.featureFlag*()` getters backed by the kernel-owned
18+
workspace cache.
19+
1720
### Changed
1821

22+
- Use a non-empty `driverVersion` as the Node.js client identity for
23+
connector-service feature flags.
24+
1925
### Updated
2026

2127
### Fixed

‎napi/index.d.ts‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -324,8 +324,9 @@ export interface ConnectionOptions {
324324
*/
325325
driverName?: string
326326
/**
327-
* Driver version reported in telemetry system configuration. Omitted ⇒
328-
* kernel default.
327+
* Driver version reported in telemetry system configuration and used for
328+
* connector-service feature-flag evaluation. Omitted ⇒ kernel default and
329+
* no feature-flag request.
329330
*/
330331
driverVersion?: string
331332
/**
@@ -972,8 +973,20 @@ export declare class Connection {
972973
* Server-issued session id. Cached at construction; readable
973974
* even after `close()` so JS-side log lines can correlate
974975
* against kernel / server logs which key on the same id.
975-
*/
976+
*/
976977
get sessionId(): string
978+
/** Read and validate a Boolean feature flag. */
979+
featureFlagBool(name: string): Promise<boolean | null>
980+
/** Read and validate a signed 32-bit integer feature flag. */
981+
featureFlagInt32(name: string): Promise<number | null>
982+
/** Read and validate a signed 64-bit integer without precision loss. */
983+
featureFlagInt64(name: string): Promise<bigint | null>
984+
/** Read and validate a double-precision feature flag. */
985+
featureFlagDouble(name: string): Promise<number | null>
986+
/** Read and validate a string feature flag. */
987+
featureFlagString(name: string): Promise<string | null>
988+
/** Read and validate a string-list feature flag. */
989+
featureFlagStringList(name: string): Promise<Array<string> | null>
977990
/**
978991
* Execute a SQL statement and return a Statement handle that
979992
* streams batches via `fetchNextBatch()`.

‎napi/src/connection.rs‎

Lines changed: 135 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ use std::sync::Arc;
3232
use tokio::sync::Mutex;
3333

3434
use databricks_sql_kernel::{Error as KernelError, Session, TypedValue};
35+
use napi::bindgen_prelude::BigInt;
3536

3637
use crate::async_statement::AsyncStatement;
3738
use crate::error::napi_err_from_kernel;
@@ -273,6 +274,59 @@ impl Connection {
273274
&self.session_id
274275
}
275276

277+
/// Read and validate a Boolean feature flag. Missing, malformed, and
278+
/// unavailable flags return `null`.
279+
#[napi]
280+
pub async fn feature_flag_bool(&self, name: String) -> napi::Result<Option<bool>> {
281+
let guard = self.inner.lock().await;
282+
let session = guard.as_ref().ok_or_else(connection_closed_err)?;
283+
Ok(session.feature_flag_bool(&name).await)
284+
}
285+
286+
/// Read and validate a signed 32-bit integer feature flag.
287+
#[napi]
288+
pub async fn feature_flag_int32(&self, name: String) -> napi::Result<Option<i32>> {
289+
let guard = self.inner.lock().await;
290+
let session = guard.as_ref().ok_or_else(connection_closed_err)?;
291+
Ok(session.feature_flag_int32(&name).await)
292+
}
293+
294+
/// Read and validate a signed 64-bit integer feature flag as a JavaScript
295+
/// `bigint`, preserving the full SAFE int64 range.
296+
#[napi]
297+
pub async fn feature_flag_int64(&self, name: String) -> napi::Result<Option<BigInt>> {
298+
let guard = self.inner.lock().await;
299+
let session = guard.as_ref().ok_or_else(connection_closed_err)?;
300+
Ok(session.feature_flag_int64(&name).await.map(BigInt::from))
301+
}
302+
303+
/// Read and validate a double-precision feature flag.
304+
#[napi]
305+
pub async fn feature_flag_double(&self, name: String) -> napi::Result<Option<f64>> {
306+
let guard = self.inner.lock().await;
307+
let session = guard.as_ref().ok_or_else(connection_closed_err)?;
308+
Ok(session.feature_flag_double(&name).await)
309+
}
310+
311+
/// Read and validate a string feature flag.
312+
#[napi]
313+
pub async fn feature_flag_string(&self, name: String) -> napi::Result<Option<String>> {
314+
let guard = self.inner.lock().await;
315+
let session = guard.as_ref().ok_or_else(connection_closed_err)?;
316+
Ok(session.feature_flag_string(&name).await)
317+
}
318+
319+
/// Read and validate a string-list feature flag.
320+
#[napi]
321+
pub async fn feature_flag_string_list(
322+
&self,
323+
name: String,
324+
) -> napi::Result<Option<Vec<String>>> {
325+
let guard = self.inner.lock().await;
326+
let session = guard.as_ref().ok_or_else(connection_closed_err)?;
327+
Ok(session.feature_flag_string_list(&name).await)
328+
}
329+
276330
/// Execute a SQL statement and return a Statement handle that
277331
/// streams batches via `fetchNextBatch()`.
278332
///
@@ -651,7 +705,9 @@ impl Drop for Connection {
651705
#[cfg(test)]
652706
mod tests {
653707
use super::*;
654-
use databricks_sql_kernel::{AuthConfig, ConnectionConfig, ErrorCode};
708+
use databricks_sql_kernel::{
709+
AuthConfig, ClientIdentity, ClientType, ConnectionConfig, ErrorCode,
710+
};
655711
use serde_json::json;
656712
use wiremock::matchers::{method, path};
657713
use wiremock::{Mock, MockServer, ResponseTemplate};
@@ -702,6 +758,84 @@ mod tests {
702758
assert_eq!(conn.session_id(), "session-survives-close");
703759
}
704760

761+
#[tokio::test]
762+
async fn typed_feature_flags_use_shared_cache_and_reject_closed_connection() {
763+
let server = MockServer::start().await;
764+
Mock::given(method("GET"))
765+
.and(path(
766+
"/api/2.0/connector-service/feature-flags/NODEJS/napi-test",
767+
))
768+
.respond_with(ResponseTemplate::new(200).set_body_string(
769+
r#"{"flags":[{"name":"example.list","value":"[\"a\",\"b\"]"},{"name":"example.int64","value":"9223372036854775807"}],"ttl_seconds":300}"#,
770+
))
771+
.expect(1)
772+
.mount(&server)
773+
.await;
774+
Mock::given(method("POST"))
775+
.and(path("/api/2.0/sql/sessions"))
776+
.respond_with(
777+
ResponseTemplate::new(200).set_body_string(
778+
r#"{"session_id":"sess-napi-flags","warehouse_id":"test_wh"}"#,
779+
),
780+
)
781+
.expect(1)
782+
.mount(&server)
783+
.await;
784+
Mock::given(method("DELETE"))
785+
.and(path("/api/2.0/sql/sessions/sess-napi-flags"))
786+
.respond_with(ResponseTemplate::new(200))
787+
.expect(1)
788+
.mount(&server)
789+
.await;
790+
791+
let session = Session::builder()
792+
.connection(
793+
ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh")
794+
.expect("valid HTTP path"),
795+
)
796+
.auth(AuthConfig::Pat {
797+
token: "dapi_test_token".into(),
798+
identity_federation_client_id: None,
799+
})
800+
.client_identity(ClientIdentity::new(ClientType::NodeJs, "napi-test"))
801+
.open()
802+
.await
803+
.expect("session opens against mock server");
804+
let connection = Connection {
805+
session_id: session.session_id().to_owned(),
806+
inner: Arc::new(Mutex::new(Some(session))),
807+
};
808+
809+
assert_eq!(
810+
connection
811+
.feature_flag_string_list("example.list".to_owned())
812+
.await
813+
.unwrap(),
814+
Some(vec!["a".to_string(), "b".to_string()])
815+
);
816+
let int64 = connection
817+
.feature_flag_int64("example.int64".to_owned())
818+
.await
819+
.unwrap()
820+
.expect("int64 flag");
821+
assert_eq!(int64.get_i64(), (i64::MAX, true));
822+
assert_eq!(
823+
connection
824+
.feature_flag_bool("missing.flag".to_owned())
825+
.await
826+
.unwrap(),
827+
None
828+
);
829+
830+
connection.close().await.unwrap();
831+
let error = connection
832+
.feature_flag_bool("example.flag".to_owned())
833+
.await
834+
.unwrap_err();
835+
assert_invalid_statement_handle_envelope(&error);
836+
server.verify().await;
837+
}
838+
705839
#[tokio::test]
706840
async fn build_statement_forwards_raw_params_and_rejects_mixed_binding() {
707841
let server = MockServer::start().await;

‎napi/src/database.rs‎

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,9 @@ use napi::bindgen_prelude::Buffer;
3434
type Buffer = Vec<u8>;
3535

3636
use databricks_sql_kernel::{
37-
AuthConfig, DefaultOpts, DriverSystemConfiguration, Error as KernelError, HttpConfig,
38-
ProxyConfig, ResultConfig, Session, TelemetryConfig, TlsConfig, TokenCacheConfig,
37+
AuthConfig, ClientIdentity, ClientType, DefaultOpts, DriverSystemConfiguration,
38+
Error as KernelError, HttpConfig, ProxyConfig, ResultConfig, Session, TelemetryConfig,
39+
TlsConfig, TokenCacheConfig,
3940
};
4041

4142
/// NodeJS-driver-appropriate default for `pool_max_idle_per_host`.
@@ -234,8 +235,9 @@ pub struct ConnectionOptions {
234235
/// Driver name reported in telemetry system configuration. Omitted ⇒
235236
/// kernel default.
236237
pub driver_name: Option<String>,
237-
/// Driver version reported in telemetry system configuration. Omitted ⇒
238-
/// kernel default.
238+
/// Driver version reported in telemetry system configuration and used for
239+
/// connector-service feature-flag evaluation. Omitted ⇒ kernel default and
240+
/// no feature-flag request.
239241
pub driver_version: Option<String>,
240242
/// Runtime name reported in telemetry system configuration. Omitted ⇒
241243
/// kernel default.
@@ -763,6 +765,12 @@ fn build_driver_system_configuration(
763765
})
764766
}
765767

768+
fn build_client_identity(driver_version: Option<&str>) -> Option<ClientIdentity> {
769+
driver_version
770+
.filter(|version| !version.trim().is_empty())
771+
.map(|version| ClientIdentity::new(ClientType::NodeJs, version))
772+
}
773+
766774
/// Open a Databricks SQL session and return an opaque `Connection`
767775
/// wrapping the kernel `Session`. Authentication is selected by
768776
/// `options.auth_mode` (PAT / OAuth M2M / OAuth U2M) — see
@@ -798,6 +806,7 @@ pub async fn open_session(mut options: ConnectionOptions) -> napi::Result<Connec
798806
// `options` to avoid cloning the header strings.
799807
let http_config = build_http_config(&mut options);
800808
let telemetry_config = build_telemetry_config(&options)?;
809+
let client_identity = build_client_identity(options.driver_version.as_deref());
801810
let driver_system_configuration = build_driver_system_configuration(&options);
802811

803812
// SessionConfig is `#[non_exhaustive]` — go through the
@@ -847,6 +856,9 @@ pub async fn open_session(mut options: ConnectionOptions) -> napi::Result<Connec
847856
if let Some(system_configuration) = driver_system_configuration {
848857
builder = builder.driver_system_configuration(system_configuration);
849858
}
859+
if let Some(identity) = client_identity {
860+
builder = builder.client_identity(identity);
861+
}
850862
// Programmatic HTTP/HTTPS proxy. Only wire a `ProxyConfig` when a
851863
// proxy is supplied; otherwise leave it unset so the kernel keeps
852864
// reqwest's env-var behaviour (HTTPS_PROXY / NO_PROXY).
@@ -1699,4 +1711,15 @@ mod tests {
16991711
);
17001712
assert_eq!(system_configuration.process_name.as_deref(), Some("node"));
17011713
}
1714+
1715+
#[test]
1716+
fn driver_version_builds_node_client_identity() {
1717+
assert!(build_client_identity(None).is_none());
1718+
assert!(build_client_identity(Some("")).is_none());
1719+
assert!(build_client_identity(Some(" \t")).is_none());
1720+
1721+
let identity = build_client_identity(Some("1.2.3")).unwrap();
1722+
assert_eq!(identity.client_type(), ClientType::NodeJs);
1723+
assert_eq!(identity.version(), "1.2.3");
1724+
}
17021725
}

0 commit comments

Comments
 (0)