Skip to content
Merged
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
197 changes: 197 additions & 0 deletions .github/scripts/check-napi-loader-drift.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
#!/usr/bin/env bash
# Drift guard for the committed napi loader.
#
# napi/index.js + napi/index.d.ts are GENERATED by `@napi-rs/cli@2.18.4`
# from the `#[napi]` surface in napi/src/. We commit them because the
# release workflow uses `@napi-rs/cli@3`, which doesn't emit the loader.
# This is the only mechanism keeping them in sync — there is no
# `cargo build` step that would catch staleness.
#
# This script catches the most common drift class: a contributor adds a
# new top-level `#[napi]` function or class in napi/src/ and forgets to
# regenerate the loader. It parses the Rust source for top-level
# `#[napi]` items, parses the loader's destructure / module.exports,
# and fails CI if the symbol sets diverge.
#
# Scope:
# - Detects: missing exports for new `#[napi]` top-level fn / class /
# enum (with js_name override honored).
# - Does NOT detect: formatting drift in index.d.ts, type-only changes
# in `#[napi(object)]` shapes, or signature changes to existing
# functions. A full regenerate-and-diff (the reviewer's preferred
# shape) would catch those, but it requires an npm proxy that this
# repo doesn't yet have on the protected runners.
#
# Run from repo root.

set -euo pipefail

cd "$(git rev-parse --show-toplevel)"

# ──────────────────────────────────────────────────────────────────
# Collect the expected surface from napi/src/**.rs.
#
# Rules (matching @napi-rs/cli@2.18.4 behavior):
# - `#[napi]` on a top-level `pub fn` / `pub async fn` / `pub struct`
# / `pub enum` exports under the item name (snake_case → camelCase
# conversion happens for fns; classes / enums keep their name).
# - `#[napi(js_name = "...")]` overrides the JS name.
# - `#[napi(object)]` / `#[napi(string_enum)]` items are emitted as
# TypeScript interfaces / const enums; for index.js they only
# matter if they're classes — strict objects/string_enums don't
# appear in the runtime destructure. We collect them separately
# for the .d.ts check.
# - Methods inside `impl` blocks (`#[napi]` inside a `#[napi] impl`)
# are NOT separate exports; the parent class covers them.
# - Items inside `#[napi]\nimpl Foo` blocks have a column-indented
# `#[napi]` attribute (column 4+). Top-level items live at column 0.
# ──────────────────────────────────────────────────────────────────

# Parse top-level Rust items: read each .rs file, find `#[napi...]`
# attributes that start at column 0 (top-level), and look at the next
# `pub ...` declaration on the next non-blank line. Emits TSV:
# kind<TAB>js_name
collect_rust_surface() {
python3 - <<'PY'
import re
import sys
from pathlib import Path

js_name_re = re.compile(r'js_name\s*=\s*"([^"]+)"')
ATTR_RE = re.compile(r'^#\[napi(?:\(([^)]*)\))?\]$')
ITEM_RE = re.compile(
r'^pub\s+(?:async\s+)?(?:fn\s+(\w+)|struct\s+(\w+)|enum\s+(\w+))'
)

def snake_to_camel(s: str) -> str:
parts = s.split("_")
return parts[0] + "".join(p.title() for p in parts[1:])

for path in sorted(Path("napi/src").rglob("*.rs")):
lines = path.read_text().splitlines()
i = 0
while i < len(lines):
line = lines[i]
# Only top-level attributes (column 0).
m = ATTR_RE.match(line)
if not m:
i += 1
continue
attr_args = m.group(1) or ""
# Find the next pub item — skip blank lines, comments, and
# other attribute lines (e.g. `#[derive(...)]`, `#[serde(...)]`
# that often sit between the `#[napi]` attribute and the item).
j = i + 1
while j < len(lines):
stripped = lines[j].lstrip()
if (
not lines[j].strip()
or stripped.startswith("//")
or stripped.startswith("/*")
or stripped.startswith("*")
or stripped.startswith("#[")
):
j += 1
continue
break
if j >= len(lines):
i += 1
continue
# The pub item must also be column 0 (top-level).
next_line = lines[j]
if next_line.startswith(" ") or next_line.startswith("\t"):
i += 1
continue
im = ITEM_RE.match(next_line)
if not im:
# Could be `impl Foo` — skip (methods are exported via
# the parent class).
i += 1
continue
fn_name, struct_name, enum_name = im.groups()
name = fn_name or struct_name or enum_name
# Determine the JS name.
js_match = js_name_re.search(attr_args)
if js_match:
js_name = js_match.group(1)
elif fn_name:
js_name = snake_to_camel(name)
else:
js_name = name # classes/enums keep their PascalCase name
if "object" in attr_args:
kind = "object"
elif "string_enum" in attr_args:
kind = "string_enum"
elif fn_name:
kind = "fn"
elif struct_name:
kind = "class"
else:
kind = "enum"
print(f"{kind}\t{js_name}")
i = j + 1
PY
}

# ──────────────────────────────────────────────────────────────────
# Collect the actual destructured exports from napi/index.js.
# Pattern: `const { A, B, C } = nativeBinding`
# ──────────────────────────────────────────────────────────────────
collect_loader_exports() {
python3 - <<'PY'
import re
from pathlib import Path

src = Path("napi/index.js").read_text()
# Find `const { ... } = nativeBinding`
m = re.search(r"const\s*\{\s*([^}]*)\s*\}\s*=\s*nativeBinding", src)
if not m:
raise SystemExit("ERROR: could not find `const { ... } = nativeBinding` destructure in napi/index.js")
names = [n.strip() for n in m.group(1).split(",") if n.strip()]
for n in names:
print(n)
PY
}

# ──────────────────────────────────────────────────────────────────
# Compare. Anything in the expected set (fn / class) that isn't in the
# loader is a drift error. Reverse — names in the loader not in the
# Rust source — is also a drift error (something was removed).
# `object` and `string_enum` items aren't in the runtime destructure;
# they're checked separately against index.d.ts below.
# ──────────────────────────────────────────────────────────────────

EXPECTED_RUNTIME=$(collect_rust_surface | awk -F'\t' '$1 == "fn" || $1 == "class" || $1 == "enum" || $1 == "string_enum" {print $2}' | sort -u)
ACTUAL_RUNTIME=$(collect_loader_exports | sort -u)

missing=$(comm -23 <(echo "$EXPECTED_RUNTIME") <(echo "$ACTUAL_RUNTIME"))
extra=$(comm -13 <(echo "$EXPECTED_RUNTIME") <(echo "$ACTUAL_RUNTIME"))

fail=0
if [[ -n "$missing" ]]; then
echo "::error::napi loader is missing exports for these #[napi] symbols:" >&2
echo "$missing" | sed 's/^/ - /' >&2
fail=1
fi
if [[ -n "$extra" ]]; then
echo "::error::napi loader exports symbols that no longer exist in napi/src/:" >&2
echo "$extra" | sed 's/^/ - /' >&2
fail=1
fi

if [[ $fail -eq 1 ]]; then
cat >&2 <<EOF

To fix, regenerate the loader and recommit:

cd napi && npx --yes @napi-rs/cli@2.18.4 build --platform \\
--js-package-name @databricks/databricks-sql-kernel --release
git add napi/index.js napi/index.d.ts && git commit --amend --no-edit

See napi/.gitignore for the full regen procedure note.
EOF
exit 1
fi

count=$(printf '%s\n' "$EXPECTED_RUNTIME" | grep -c .)
echo "napi loader is in sync with #[napi] surface (${count} symbols)."
22 changes: 22 additions & 0 deletions .github/workflows/napi-checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,28 @@ jobs:
# secrets — purely cdylib + rlib in-tree tests.
run: cargo test --locked

# Drift guard for the committed loader (napi/index.js +
# napi/index.d.ts). PR #146 review feedback: nothing in CI
# detects when a contributor adds a top-level `#[napi]` symbol
# without recommitting the generated loader, and that already
# happened once (3 logger exports went missing in #146 before
# this check landed).
#
# This is a SURFACE audit, not a full regenerate-and-diff —
# parses napi/src/**.rs for top-level `#[napi]` items and
# compares against the destructured names in napi/index.js.
# Catches the "new export missing" bug class without needing
# an npm proxy on the protected runner (which doesn't yet
# exist; see .github/actions/setup-jfrog/action.yml — npm
# support is a "future" item). When npm-via-JFrog lands, this
# step should be replaced with the full reviewer-preferred
# form: `npx --yes @napi-rs/cli@2.18.4 build --platform ...`
# then `git diff --exit-code -- napi/index.js napi/index.d.ts`.
# Tracked in the PR #146 discussion.
- name: Check napi loader is in sync with #[napi] surface
working-directory: ${{ github.workspace }}
run: bash .github/scripts/check-napi-loader-drift.sh

# Release-profile build verifies the cdylib actually links with
# the production profile knobs (lto=true, codegen-units=1,
# strip="debuginfo"). The lto=true link is the slow part (~4 min
Expand Down
16 changes: 14 additions & 2 deletions napi/.gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
target/
index.node
*.node
index.d.ts
index.js

# Created transiently when running `napi build` to regenerate the
# committed loader (see the index.js note below). Never committed.
node_modules/

# index.js (the napi-rs multi-platform loader) and index.d.ts are
# COMMITTED, not ignored: they are generated by `@napi-rs/cli@2.18.4`
# but the release workflow runs `@napi-rs/cli@3`, which no longer
# emits index.js. Committing the generated loader decouples the
# published umbrella from the CLI version. Regenerate + recommit
# whenever the `#[napi]` API surface in napi/src/ changes. See
# `napi/README.md` for the exact incantation and the CI drift guard
# (`.github/scripts/check-napi-loader-drift.sh`) that catches the
# "forgot to regen" mistake.
94 changes: 94 additions & 0 deletions napi/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# `@databricks/databricks-sql-kernel` (napi binding)

Node.js binding over the Databricks SQL Kernel Rust crate. Published to
npm as [`@databricks/databricks-sql-kernel`](https://www.npmjs.com/package/@databricks/databricks-sql-kernel),
the umbrella loader that re-exports the per-platform native packages.

The binding itself lives under `src/`; its public TypeScript surface is
declared in `index.d.ts`.

---

## Building

The cdylib is built by the napi-rs CLI. The published umbrella ships
both a generated multi-platform loader (`index.js`) and its type
declarations (`index.d.ts`) — both files are **committed**, not
`.gitignore`d, because the publish workflow uses `@napi-rs/cli@3`
which no longer emits the loader.

### Regenerating the committed loader

Whenever the `#[napi]` surface in `napi/src/` changes (new function,
new class, new `string_enum`, new `#[napi(object)]` shape) you MUST
regenerate the loader and recommit both files:

```bash
cd napi
npx --yes @napi-rs/cli@2.18.4 build --platform \
--js-package-name @databricks/databricks-sql-kernel --release
git add napi/index.js napi/index.d.ts
git commit -s --amend --no-edit # or a fresh commit; up to you
```

The version pin (`@2.18.4`) is load-bearing — a bare `napi build`
resolves to `@napi-rs/cli@3`, which produces a different artifact
shape and breaks consumers. Always cite the pinned form.

The per-target list emitted in `index.js` (18 triples covering
`linux-{x64,arm64}-{gnu,musl}` + `darwin-{x64,arm64,universal}` +
`win32-{x64,arm64,ia32}` + `android-{arm64,arm-eabi}` + freebsd) is
the napi-rs default matrix; it does NOT track the `napi.targets` list
in `package.json` (that's a publish-time concern). So the only thing
that should force a regeneration is a change to the `#[napi]` surface
in Rust.

### CI drift guard

`.github/workflows/napi-checks.yml` runs
`.github/scripts/check-napi-loader-drift.sh` on every PR that touches
`napi/**`. The script parses napi/src/**.rs for top-level `#[napi]`
items and compares against the destructured names in `napi/index.js`,
failing CI if a contributor adds a new `#[napi]` symbol without
recommitting the regenerated loader.

The guard is a **surface audit**, not a full regenerate-and-diff: it
catches the "new export missing from loader" bug class (which already
occurred once, see PR #146) but doesn't catch formatting drift in
`index.d.ts` or signature changes to existing functions. A full
`napx napi build` + `git diff --exit-code` step would catch those too
but currently needs an npm proxy on the protected runner (npm support
in `setup-jfrog` is a "future" item per the action docs). When that
lands, swap the drift script for the full regenerate-and-diff.

---

## Per-platform native packages

The umbrella `package.json` declares `napi.targets` covering the eight
triples we publish. The release workflow
(`peco-databricks-sql-kernel-nodejs.yml` in
`databricks/secure-public-registry-releases-eng`) builds each per-target
package and publishes them as
`@databricks/databricks-sql-kernel-<triple>` (e.g.
`@databricks/databricks-sql-kernel-linux-x64-gnu`). The umbrella's
loader `require()`s the matching package at runtime via
`optionalDependencies` wiring (set up by the same workflow).

Consumers do NOT install the per-platform packages directly — they
`npm install @databricks/databricks-sql-kernel` and let npm resolve the
matching `optionalDependencies` entry for their platform.

---

## Changelogs

- `napi/CHANGELOG.md` — released versions of the npm package.
- `napi/NEXT_CHANGELOG.md` — unreleased changes staged for the next
release.
- `napi/release-notes.txt` — human-readable summary, mirrors the
format the jdbc driver uses.

The Rust crate (`../CHANGELOG.md`) and Python wheel
(`../pyo3/CHANGELOG.md`) ship on independent cadences; entries for
this napi binding go ONLY in this directory's files.
Loading
Loading