Repository navigation
feat(bindings): registry configuration, credential store, and license support - #551
Conversation
ad71956 to
c729d4e
Compare
73d9a2f to
6db8b63
Compare
6db8b63 to
09e7021
Compare
09e7021 to
b25a24a
Compare
b25a24a to
28ec55e
Compare
28ec55e to
4947055
Compare
4947055 to
64bc5b0
Compare
64bc5b0 to
b85ce53
Compare
b85ce53 to
3923dfe
Compare
|
Good call: they weren't running. 89c4cd6 adds Turning it on surfaced tests that assumed a native host:
Wasm run 41896020360 on 75b6940 is green, with both Go steps passing on ubuntu and macOS. |
| func LoadCredentials() error { | ||
| loaded.Do(func() { | ||
| creds, err := loadCreds() | ||
| credMu.Lock() | ||
| creds, err := loadCreds() | ||
| loadedCredentials, credentialErr = creds, err | ||
| credMu.Unlock() | ||
| }) | ||
| credMu.RLock() | ||
| defer credMu.RUnlock() | ||
| return credentialErr | ||
| } |
There was a problem hiding this comment.
Same **** that gosnowflake does (used to?) with locks: lock on read and lock on write. This is wrong. It's the classic CAS concept [1]. If you're reading credentials, checking if they are missing, doing something about it, and then writing, you should hold a lock through the whole process from beginning to end.
This not being handled correctly was how we ended up with one browser tab per process trying to connect to warehouses.
One optimization you can make [2] is to read without a full lock, in case it's empty, restart the process with a lock acquired, read again, if it's empty (still) start the process of acquiring credentials and then write. The decision to write has to always come from a read that was done during the lifetime of the same lock.
Also, don't lock file locks, use leases [3]. An auth process might go for too long. Before writing to the cache, it should check if the lease is still valid. If not, the operation fails, but that's fine. You allowed a concurrent process to succeed instead of hanging for too long.
[1] https://en.wikipedia.org/wiki/Compare-and-swap
[2] https://en.wikipedia.org/wiki/Double-checked_locking
[3] https://github.com/adbc-drivers/amazon/blob/main/go/auth/lease.go
There was a problem hiding this comment.
You're right about the part that mattered. Writes were already compare-and-swap: persistRefreshed takes the file lock, re-reads, and writes only if the stored entry still equals the one we started from. But the decision to refresh was made from an unlocked read, so N processes with the same expired token made N refreshes. I reproduced it: four processes against one store hit the token endpoint 4 times and ended up with 3 different tokens.
Fixed in d958f02, with double-checked locking as you describe:
- Take the credential file lock first.
- Re-read the store. If another process stored a different token meanwhile, use it, with no network call.
- Otherwise refresh while holding the lock, and write with the same CAS. The decision to write always comes from a read made under that lock.
The same four-process test now makes 1 request, and all four get the stored token.
On leases: fslock is an OS lock (flock / LockFileEx), so a crashed holder is released by the kernel, and no expiry file or renewal is needed for that case. A slow holder is the case it doesn't cover, and that's bounded:
- The holder: the refresh under the lock runs with
credentialLockTimeout(10s) as its deadline. - The waiters: one that can't get the lock within that refreshes on its own and doesn't write, since its decision didn't come from a read under the lock.
A stuck process therefore costs an extra refresh, never a hang. TestRefreshDoesNotWaitForeverOnAStuckHolder covers it.
One difference from the gosnowflake case: nothing on this path is interactive. Refresh is a single non-browser token request (API key or OAuth refresh_token), and the refresh token isn't rotated, so a duplicated refresh used to waste a request but couldn't invalidate anyone. Browser login only happens from dbc auth login.
… support Brings the language bindings up to the CLI's registry and auth handling, through internal/api, the C ABI, Rust, and npm-wasm: explicit registry lists (empty means zero registries everywhere; C registry.count), global config.toml and project dbc.toml, login/logout against dbc's credential store, credentialStore=none, license path/install, and validation of all registry and credential URLs through internal/registryurl. Deprecates auth.UpdateCreds and adds docs/guides/go_library.md. Rebuilt on the rebased stack as one commit; the previous history (68dca0d..fd6d066 plus merges) is preserved at pr551-backup.
Logout parsed registryURL with url.Parse and only required an absolute URL with a host, so ftp://registry.test removed the stored credential for registry.test. Use registryurl.Parse, as Login, injected credentials, and registry configuration do.
…time
On js/wasm, fslock only ordered callers inside one Go runtime, so separate
npm loadDbc({ worker: true }) clients (and separate Node processes) ran the
credential store's read-modify-write concurrently. A new concurrent-login
test in the npm suite corrupted credentials.toml in 3 of 3 runs.
The holder now also creates <lock>.js with O_EXCL and keeps its mtime fresh
while held; a marker idle for 30s is treated as left by a dead runtime and
removed. Without a filesystem (the browser build) the runtime token remains
the whole lock. Native flock/LockFileEx is unchanged and still not visible to
Node, so Wasm and the native CLI do not exclude each other.
acquireMarker ignored os.Remove's error and retried immediately, skipping the timeout, context, and poll wait, so a stale marker in an unwritable directory spun forever. Return the removal error instead; a marker refreshed between the two stats now waits like any live holder.
…t force - writeCreds truncated credentials.toml and re-encoded it in place, so a reader in another process (LoadCredentials takes no lock, and caches the result) could see an empty or partial file. Replace it atomically with internal/atomicfile instead. - InstallLicenseFromFile(force=false) checked for an existing license with os.Stat and then wrote with os.WriteFile, so concurrent installs could all succeed and overwrite each other. Create the file with O_EXCL instead. Both regressions have tests that failed before the change.
Windows refuses MoveFileEx over a file that another handle opened without FILE_SHARE_DELETE, which includes every os.Open. Since credential writes use atomicfile (078bcfc), a reader holding credentials.toml made AddCredential fail with "Access is denied."; TestCredentialWritesAreNeverObservedPartial failed on windows-latest. Retry ERROR_ACCESS_DENIED and ERROR_SHARING_VIOLATION with backoff for up to 2s, as cmd/go's robustio does. Driver manifest writes, which already used atomicfile, get the same fix.
With atomic credential writes, Windows CI's TestCredentialWritesAreNeverObservedPartial now failed on the reader side: os.Open returns ERROR_SHARING_VIOLATION while MoveFileEx holds the file to replace it, and a process whose LoadCredentials hit that window would cache the error. Add atomicfile.Open, which on Windows retries ERROR_SHARING_VIOLATION and ERROR_ACCESS_DENIED (delete pending) with the same bounded backoff as replace, and is os.Open elsewhere; a missing file still fails at once. Read credentials.toml through it.
On Unix, Go reads a copy of the environment taken when its runtime starts, and only its own os.Setenv updates it. A C, Rust, or Python host changes the environment through libc, so changes it made after libdbc loaded were ignored: e.g. Python setting os.environ["ADBC_DRIVER_PATH"] after import still installed to the user level (#548 review). config now reads the three variables through internal/hostenv, which defaults to os.LookupEnv; capi replaces it on Unix with libc getenv, so cgo stays in the C API build. Pure Go programs were already effectively live, and Windows reads the live process environment. The Rust default_location test now sets ADBC_DRIVER_PATH after startup instead of re-running itself, and fails against the previous libdbc.
Co-authored-by: Bryce Mecum <[email protected]>
Co-authored-by: Bryce Mecum <[email protected]>
Open used os.Open, which doesn't share delete access, so while a reader held the file MoveFileEx couldn't replace it. The writer's retry backs off up to 100ms, so a reader reopening in a loop could keep it out past the 2s window: TestCredentialWritesAreNeverObservedPartial failed on windows-latest with "atomicfile: replace ...credentials.toml: Access is denied". openForRead now opens with FILE_SHARE_READ|WRITE|DELETE. A replace renames over the open file, and the reader keeps the old contents, as on POSIX. It still retries the sharing errors of a replace in progress.
FILE_SHARE_DELETE on readers is not enough: MoveFileEx refuses to replace a file any handle has open (TestReplaceSucceedsWhileOpenHandleIsHeld failed with Access is denied after the 2s retry). Rename through os.Root, whose Windows Rename uses FILE_RENAME_POSIX_SEMANTICS where supported and falls back to a plain replacing rename elsewhere.
No CI job ran the js-tagged Go tests (fslock_js_test.go, paths_host_node_js_test.go, api_browser_js_test.go, splitlist_js_test.go): go.yml tests the host OS and wasm.yml only ran the npm smoke scripts. The Wasm workflow now runs scripts/test_go_js.sh, the Go tests of every module package the wasm build uses, as the browser and the Node (dbcnode) build, on Linux and macOS. Under js several tests assumed a native host: - Install tests found no package for "unknown_wasm64": the npm package sets the host platform first, so js test binaries now do too (internal/jstest). - config's generation-removal tests, one of which hung, assume pinned cleanup, which js deliberately lacks; they skip there, and a new test checks that js uninstall removes the registration but leaves the generation's files. - Multi-root Location tests skip on js, whose API takes one location. - TestProxyEnv re-runs itself as a subprocess, which js cannot start.
isolateUserState picked the config directory from runtime.GOOS, which is js under wasm, but the Node build follows the native host's layout, so on macOS TestNewClientRegistryConfigPrecedence wrote config.toml where the client never looks. Use internal.GetUserConfigPath, which the client calls.
Processes needing the same expired credential each refreshed it without a lock and only took the lock to write the result back, so N processes made N token requests (and N-1 writes were dropped by the compare-and-swap). RefreshAndPersist now takes the credential file lock first, re-reads the store, and uses a token another process stored meanwhile; only otherwise does it refresh, under the lock, and write. The hold is bounded: the refresh under the lock gets credentialLockTimeout, and a process that cannot get the lock in that time refreshes on its own without writing, so a stuck holder costs an extra refresh rather than a hang. TestConcurrentProcessesRefreshOnce starts four processes against one store: before, the token endpoint saw 4 requests and they got 3 different tokens; now it sees 1.
RefreshAndPersist waited for the credential file lock for up to credentialLockTimeout even when the caller's context was already done, and when the store turned out unreadable it refreshed while still holding the lock. The lock wait now uses fslock.AcquireContext and returns the context's error, and the unreadable-store fallback releases the lock before refreshing.
…eting Release deletes the lock file on Windows. While the delete runs, opening the file fails with ERROR_SHARING_VIOLATION, or ERROR_ACCESS_DENIED once it is pending deletion, and acquire treated that open error as fatal: a waiter failed within milliseconds instead of taking the lock. On windows-latest TestRegistrationNamespaceLockSerializesInstallCleanupAndCreateManifest failed this way in 7-17 of 300 runs. The open is now retried: sharing violations until the lock timeout, access denials for at most 250ms, since a lasting ERROR_ACCESS_DENIED is a permission failure that must still be reported promptly. With the fix the test passed 300 of 300 runs, twice.
Stacked on #549.
Brings the language bindings up to the CLI's registry and auth handling. Goes through
internal/api→ C ABI → Rust → npm-wasm.Registries
registries: [{url, name}](C:registry.<n>.url/registry.<n>.name) →dbc.WithRegistries. It is used as given, with no merging.config.tomlby default, like the CLI.registryConfig: "none"(C:registry_config=none) opts out. In the browser it is alwaysnone.projectFile(C:project_file) → theregistries/replace_defaultskeys from adbc.toml.baseURLor an explicit list overrides all configuration files, asDBC_BASE_URLdoes for the CLI.Credentials
login(credential)/logout(registryURL)(C:dbc_login,dbc_logout) store or remove token credentials in dbc's credential store.credentialnow applies only to its own host; other hosts fall back to stored credentials, matching what the header already documented.credentialStore: "none"(C:credential_store=none) disables stored-credential lookup.auth.AddCredential/RemoveCredentialre-read the credentials file before writing. Without this, a stale snapshot held by another worker or process dropped other entries on write. Test included.License
licensePath()/installLicense(path, {force})(C:dbc_license_path,dbc_install_license+DBC_LICENSE_FORCE).The C ABI goes from 13 to 17 exports; Rust bindings are regenerated. Node/Rust docs note that credential lookups in an already-running runtime don't see changes another runtime makes.
Testing
Go (including
-race ./auth), npm-wasm smoke and worker tests, Rust tests and clippy, bindgen drift check, and a throwaway C ABI smoke run against a local registry with an isolated credential store.