Skip to content
Open
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
1 change: 0 additions & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
version: "2"
run:
timeout: 5m
linters:
Expand Down
69 changes: 69 additions & 0 deletions AUDIT-ERROR-HANDLING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Audit: Error Handling & Logging

This audit reviews the error handling and logging practices of the Poindexter Go library, focusing on the core `kdtree.go` implementation and the `wasm/main.go` wrapper.

## Error Handling

### Exception Handling
- [x] **Are exceptions caught appropriately?**
- **Finding:** Yes. As a Go library, it doesn't use exceptions but instead returns `error` types. The code diligently checks for and propagates errors. For instance, `NewKDTree` returns an error for invalid input, and callers are expected to handle it.

- [x] **Generic catches hiding bugs?**
- **Finding:** No. The library defines specific, exported error variables (e.g., `ErrEmptyPoints`, `ErrDimMismatch`) in `kdtree.go`. This allows consumers to programmatically check for specific error conditions using `errors.Is`, which is a best practice.

- [x] **Error information leakage?**
- **Finding:** Previously, the WASM wrapper at `wasm/main.go` would return raw Go error strings to the JavaScript client. This has been **remediated** by introducing a structured `WasmError` type with a `code` and `message`, preventing the leakage of internal implementation details.

### Error Recovery
- [x] **Graceful degradation?**
- **Finding:** Yes. The `KDTree` constructor attempts to use the `gonum` backend if requested, but it gracefully falls back to the `linear` backend if the `gonum` build tag is not present or if the backend fails to initialize. This ensures the library remains functional even without the optimized backend.

- [ ] **Retry logic with backoff?**
- **Finding:** Not applicable. This is a computational library, not a networked service, so retry logic is not relevant.

- [ ] **Circuit breaker patterns?**
- **Finding:** Not applicable. This is not a networked service.

### User-Facing Errors
- [x] **Helpful without exposing internals?**
- **Finding:** Yes. The error messages are clear and actionable for developers (e.g., "inconsistent dimensionality in points") without revealing sensitive internal state.

- [x] **Consistent error format?**
- **Finding:** Yes. The Go API uses the standard `error` interface. The WASM API has been updated to use a consistent JSON structure for all errors: `{ "ok": false, "error": { "code": "...", "message": "..." } }`.

- [ ] **Localization support?**
- **Finding:** No. Error messages are in English. For a developer-facing library, this is generally acceptable and localization is not expected.

### API Errors
- [x] **Standard error response format?**
- **Finding:** Yes. As noted above, the WASM API now has a standardized JSON error format.

- [ ] **Appropriate HTTP status codes?**
- **Finding:** Not applicable. This is a WASM module, not an HTTP service.

- [x] **Error codes for clients?**
- **Finding:** Yes. The WASM API now includes standardized string-based error codes (e.g., `bad_request`, `not_found`), allowing clients to handle different error types programmatically.

## Logging

The library itself does not perform any logging, which is appropriate for its role. It returns errors to the calling application, which is then responsible for its own logging strategy. The library does include analytics and metrics collection (`kdtree_analytics.go`), but this is separate from logging and does not record any sensitive information.

### What is Logged
- [ ] Security events (auth, access)? - **N/A**
- [ ] Errors with context? - **N/A**
- [ ] Performance metrics? - **N/A** (collected, but not logged by the library)

### What Should NOT be Logged
- [ ] Passwords/tokens - **N/A**
- [ ] PII without consent - **N/A**
- [ ] Full credit card numbers - **N/A**

### Log Quality
- [ ] Structured logging (JSON)? - **N/A**
- [ ] Correlation IDs? - **N/A**
- [ ] Log levels used correctly? - **N/A**

### Log Security
- [ ] Injection-safe? - **N/A**
- [ ] Tamper-evident? - **N/A**
- [ ] Retention policy? - **N/A**
21 changes: 20 additions & 1 deletion npm/poindexter-wasm/PROJECT_README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,9 @@ Explore runnable examples in the repository:
- examples/kdtree_2d_ping_hop
- examples/kdtree_3d_ping_hop_geo
- examples/kdtree_4d_ping_hop_geo_score
- examples/dht_helpers (convenience wrappers for common DHT schemas)
- examples/wasm-browser (browser demo using the ESM loader)
- examples/wasm-browser-ts (TypeScript + Vite local demo)

### KDTree performance and notes
- Dual backend support: Linear (always available) and an optimized KD backend enabled when building with `-tags=gonum`. Linear is the default; with the `gonum` tag, the optimized backend becomes the default.
Expand Down Expand Up @@ -216,4 +218,21 @@ This project is licensed under the European Union Public Licence v1.2 (EUPL-1.2)

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.
Contributions are welcome! Please feel free to submit a Pull Request.


## Coverage

- CI produces coverage summaries as artifacts on every push/PR:
- Default job: `coverage-summary.md` (from `coverage.out`)
- Gonum-tag job: `coverage-summary-gonum.md` (from `coverage-gonum.out`)
- Locally, you can generate and inspect coverage with the Makefile:

```bash
make cover # runs tests with race + coverage and prints the total
make coverfunc # prints per-function coverage
make cover-kdtree # filters coverage to kdtree.go
make coverhtml # writes coverage.html for visual inspection
```

Note: CI also uploads raw coverage profiles as artifacts (`coverage.out`, `coverage-gonum.out`).
67 changes: 55 additions & 12 deletions npm/poindexter-wasm/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@
// await tree.insert({ id: 'a', coords: [0,0], value: 'A' });
// const res = await tree.nearest([0.1, 0.2]);

// --- Environment detection ---
const isBrowser = typeof window !== 'undefined';
const isNode = typeof process !== 'undefined' && process.versions != null && process.versions.node != null;

// --- Browser-specific helpers ---
async function loadScriptOnce(src) {
return new Promise((resolve, reject) => {
// If already present, resolve immediately
Expand All @@ -18,20 +23,44 @@ async function loadScriptOnce(src) {
});
}

// --- Loader logic ---
async function ensureWasmExec(url) {
if (typeof window !== 'undefined' && typeof window.Go === 'function') return;
await loadScriptOnce(url);
if (typeof window === 'undefined' || typeof window.Go !== 'function') {
throw new Error('wasm_exec.js did not define window.Go');
if (typeof globalThis.Go === 'function') return;

if (isBrowser) {
await loadScriptOnce(url);
} else if (isNode) {
const { fileURLToPath } = await import('url');
const wasmExecPath = fileURLToPath(url);
await import(wasmExecPath);
} else {
throw new Error(`Unsupported environment: cannot load ${url}`);
}

if (typeof globalThis.Go !== 'function') {
throw new Error('wasm_exec.js did not define globalThis.Go');
}
}

function unwrap(result) {
if (!result || typeof result !== 'object') throw new Error('bad result');
if (result.ok) return result.data;
throw new Error(result.error || 'unknown error');
if (!result || typeof result !== 'object') {
throw new Error(`bad/unexpected result type from WASM: ${typeof result}`);
}
if (result.ok) {
return result.data;
}
// Handle structured errors, which may be nested
const errorPayload = result.error || result;
if (errorPayload && typeof errorPayload === 'object') {
const err = new Error(errorPayload.message || 'unknown WASM error');
err.code = errorPayload.code;
throw err;
}
// Fallback for simple string errors
throw new Error(errorPayload || 'unknown WASM error');
}


function call(name, ...args) {
const fn = globalThis[name];
if (typeof fn !== 'function') throw new Error(`WASM function ${name} not found`);
Expand Down Expand Up @@ -65,18 +94,32 @@ export async function init(options = {}) {
} = options;

await ensureWasmExec(wasmExecURL);
const go = new window.Go();
const go = new globalThis.Go();

let result;
if (instantiateWasm) {
const source = await fetch(wasmURL).then(r => r.arrayBuffer());
let source;
if (isBrowser) {
source = await fetch(wasmURL).then(r => r.arrayBuffer());
} else {
const fs = await import('fs/promises');
const { fileURLToPath } = await import('url');
source = await fs.readFile(fileURLToPath(wasmURL));
}
const inst = await instantiateWasm(source, go.importObject);
result = { instance: inst };
} else if (WebAssembly.instantiateStreaming) {
} else if (isBrowser && WebAssembly.instantiateStreaming) {
result = await WebAssembly.instantiateStreaming(fetch(wasmURL), go.importObject);
} else {
const resp = await fetch(wasmURL);
const bytes = await resp.arrayBuffer();
let bytes;
if (isBrowser) {
const resp = await fetch(wasmURL);
bytes = await resp.arrayBuffer();
} else {
const fs = await import('fs/promises');
const { fileURLToPath } = await import('url');
bytes = await fs.readFile(fileURLToPath(wasmURL));
}
result = await WebAssembly.instantiate(bytes, go.importObject);
}

Expand Down
26 changes: 20 additions & 6 deletions npm/poindexter-wasm/smoke.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
import { init } from './loader.js';

(async function () {
let px;
try {
const px = await init({
// In CI, dist/ is placed at repo root via make wasm-build && make npm-pack
wasmURL: new URL('./dist/poindexter.wasm', import.meta.url).pathname,
wasmExecURL: new URL('./dist/wasm_exec.js', import.meta.url).pathname,
px = await init({
wasmURL: new URL('./dist/poindexter.wasm', import.meta.url).toString(),
wasmExecURL: new URL('./dist/wasm_exec.js', import.meta.url).toString(),
});
const ver = await px.version();
if (!ver || typeof ver !== 'string') throw new Error('version not string');
Expand All @@ -17,10 +17,24 @@ import { init } from './loader.js';
await tree.insert({ id: 'a', coords: [0, 0], value: 'A' });
await tree.insert({ id: 'b', coords: [1, 0], value: 'B' });
const nn = await tree.nearest([0.9, 0.1]);
if (!nn || !nn.id) throw new Error('nearest failed');
console.log('WASM smoke ok:', ver, 'nearest.id=', nn.id);
if (!nn || !nn.point || !nn.point.id) throw new Error('nearest failed');
console.log('WASM smoke ok:', ver, 'nearest.id=', nn.point.id);
} catch (err) {
console.error('WASM smoke failed:', err);
process.exit(1);
}

// Test error handling
try {
await px.newTree(0);
console.error('Expected error from newTree(0) but got none');
process.exit(1);
} catch (err) {
if (err.code === 'bad_request' && err.message.includes('dimension')) {
console.log('WASM error handling ok:', err.code);
} else {
console.error('WASM smoke failed: unexpected error format:', err);
process.exit(1);
}
}
})();
Loading
Loading