diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 77ce10b..58df9d0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -74,6 +74,7 @@ netcdf4-wasm/ │ ├── netcdf-worker.ts # Web Worker implementation │ ├── netcdf4-wasm.d.ts # TypeScript declarations │ ├── netcdf4.ts # Main NetCDF4 class +│ ├── operations.ts # Operations shared by the main thread and the worker │ ├── types.ts # Type definitions │ ├── variable.ts # Variable class │ └── wasm-module.ts # WASM module loader diff --git a/src/netcdf-worker.ts b/src/netcdf-worker.ts index 665b3bc..07afe2d 100644 --- a/src/netcdf-worker.ts +++ b/src/netcdf-worker.ts @@ -1,5 +1,4 @@ -import { NC_CONSTANTS } from "./constants.js"; -import * as NCGet from "./netcdf-getters.js"; +import { isOperationName, runOperation } from "./operations.js"; import { checkRangeSupport, createRemoteFileNode, @@ -94,169 +93,10 @@ self.onmessage = async (e: MessageEvent) => { // Only report read errors raised by this request if (remoteFile) remoteFile.lastError = undefined; - let result; - - switch (type) { - case "open": { - const openResult = mod.nc_open(data.path, data.modeValue); - if (openResult.result !== NC_CONSTANTS.NC_NOERR) { - throw new Error("nc_open failed: " + openResult.result); - } - result = openResult.ncid as number; - break; - } - - case "close": { - const closeResult = mod.nc_close(data.ncid); - if (closeResult !== NC_CONSTANTS.NC_NOERR) { - throw new Error("Failed to close file"); - } - result = closeResult; - break; - } - - // ---- Globals ---- - case "getGlobalAttributes": - result = NCGet.getGlobalAttributes( - mod, - data.ncid, - data.groupPath, - ); - break; - - case "getFullMetadata": - result = NCGet.getFullMetadata(mod, data.ncid, data.groupPath); - break; - - // ---- Dims ---- - case "getDimCount": - result = NCGet.getDimCount(mod, data.ncid); - break; - - case "getDimIDs": - result = Array.from(NCGet.getDimIDs(mod, data.ncid)); - break; - - case "getDim": - result = NCGet.getDim(mod, data.ncid, data.dimid); - break; - - case "getDims": - result = NCGet.getDims(mod, data.ncid, data.groupPath); - break; - - // ---- Vars ---- - case "getGroupVariables": - // console.log('Worker: getGroupVariables', data.ncid); - result = NCGet.getGroupVariables( - mod, - data.ncid, - data.groupPath, - ); - break; - - case "getVarIDs": - result = Array.from(NCGet.getVarIDs(mod, data.ncid)); - break; - - case "getVarCount": - result = NCGet.getVarCount(mod, data.ncid); - break; - - case "getAttributeName": - result = NCGet.getAttributeName( - mod, - data.ncid, - data.varid, - data.attId, - ); - break; - - case "getVariableInfo": - result = NCGet.getVariableInfo( - mod, - data.ncid, - data.variable, - data.groupPath, - ); - break; - - case "getAttributeValues": - result = NCGet.getAttributeValues( - mod, - data.ncid, - data.varid, - data.attname, - ); - break; - - case "getVariableArrayWithSelection": - result = NCGet.getVariableArrayWithSelection( - mod, - data.ncid, - data.variable, - data.selection, - data.groupPath, - data.options, - ); - break; - - // ---- Arrays ---- - case "getVariableArray": - result = NCGet.getVariableArray( - mod, - data.ncid, - data.variable, - data.groupPath, - ); - break; - - case "getSlicedVariableArray": - result = NCGet.getSlicedVariableArray( - mod, - data.ncid, - data.variable, - data.start, - data.count, - data.groupPath, - ); - break; - - // ---- Groups ---- - case "getGroups": - result = NCGet.getGroups(mod, data.ncid); - break; - - case "getGroupsRecursive": - result = NCGet.getGroupsRecursive(mod, data.ncid); - break; - - case "getGroupNCID": - result = NCGet.getGroupNCID(mod, data.ncid, data.groupPath); - break; - - case "getGroupName": - result = NCGet.getGroupName(mod, data.ncid); - break; - - case "getGroupPath": - result = NCGet.getGroupPath(mod, data.ncid); - break; - case "getCompleteHierarchy": - result = NCGet.getCompleteHierarchy( - mod, - data.ncid, - data.groupPath, - ); - break; - - case "getVariables": - result = NCGet.getVariables(mod, data.ncid); - break; - - default: - throw new Error(`Unknown message type: ${type}`); + if (!isOperationName(type)) { + throw new Error(`Unknown message type: ${type}`); } + const result = runOperation(mod, type, data.args); self.postMessage({ id, success: true, result }); } catch (err: any) { diff --git a/src/netcdf4.ts b/src/netcdf4.ts index 624cc5d..7d13ac6 100644 --- a/src/netcdf4.ts +++ b/src/netcdf4.ts @@ -2,7 +2,12 @@ import { NC_CONSTANTS } from "./constants.js"; import { Group } from "./group.js"; -import * as NCGet from "./netcdf-getters.js"; +import { + type OperationArgs, + type OperationName, + type OperationResult, + runOperation, +} from "./operations.js"; import type { DimSelection } from "./slice.js"; import type { DatasetOptions, @@ -250,7 +255,7 @@ export class NetCDF4 extends Group { this.mode === "r" ? NC_CONSTANTS.NC_NOWRITE : NC_CONSTANTS.NC_WRITE; - this.ncid = await this.callWorker("open", { + this.ncid = await this.run("open", { path: this.filename, modeValue, }); @@ -356,21 +361,9 @@ export class NetCDF4 extends Group { // Low-level NetCDF operations (used by Group methods) async openFile(path: string, mode: "r" | "w" | "a" = "r"): Promise { - const module = this.getModule(); const modeValue = - mode === "r" - ? NC_CONSTANTS.NC_NOWRITE - : mode === "w" - ? NC_CONSTANTS.NC_WRITE - : NC_CONSTANTS.NC_WRITE; - - const result = module.nc_open(path, modeValue); - if (result.result !== NC_CONSTANTS.NC_NOERR) { - throw new Error( - `Failed to open NetCDF file: ${path} (error: ${result.result})`, - ); - } - return result.ncid; + mode === "r" ? NC_CONSTANTS.NC_NOWRITE : NC_CONSTANTS.NC_WRITE; + return this.run("open", { path, modeValue }); } async createFile( @@ -388,31 +381,23 @@ export class NetCDF4 extends Group { } async closeFile(ncid: number): Promise { - if (this.worker) { - await this.callWorker("close"); - } else { - const module = this.module; - if (!module) - throw new Error( - "Failed to load module. Ensure module is initialized before calling methods", - ); - - const result = module.nc_close(ncid); - if (result !== NC_CONSTANTS.NC_NOERR) { - throw new Error( - `Failed to close NetCDF file with ID: ${ncid} (error: ${result})`, - ); - } - } + await this.run("close", { ncid }); } private requestId = 0; - private async callWorker(type: string, payload: any = {}): Promise { + // Run an operation from operations.ts: in the worker if there is one, + // otherwise on this thread. ncid defaults to the dataset's own. + private async run( + name: K, + args: Omit, "ncid"> & { ncid?: number }, + ): Promise> { + const fullArgs = { ncid: this.ncid, ...args } as OperationArgs; if (this.workerError) throw this.workerError; - if (!this.worker) throw new Error("Worker not initialized"); - - return this.requestWorker({ type, ncid: this.ncid, ...payload }); + if (this.worker) { + return this.requestWorker({ type: name, args: fullArgs }); + } + return runOperation(this.getModule(), name, fullArgs); } // Post a message to the worker and wait for the reply carrying the same id. @@ -487,151 +472,60 @@ export class NetCDF4 extends Group { async getGlobalAttributes( groupPath?: string, ): Promise> { - if (this.worker) { - return this.callWorker("getGlobalAttributes", { groupPath }); - } else { - // Main thread path is already synchronous (or could be wrapped in Promise.resolve) - return NCGet.getGlobalAttributes( - this.module as NetCDF4Module, - this.ncid, - groupPath, - ); - } + return this.run("getGlobalAttributes", { groupPath }); } async getFullMetadata(groupPath?: string): Promise[]> { - if (this.worker) { - return this.callWorker("getFullMetadata", { groupPath }); - } else { - // Main thread path is already synchronous (or could be wrapped in Promise.resolve) - return NCGet.getFullMetadata( - this.module as NetCDF4Module, - this.ncid, - groupPath, - ); - } + return this.run("getFullMetadata", { groupPath }); } async getAttributeValues(varid: number, attname: string): Promise { - if (this.worker) { - return this.callWorker("getAttributeValues", { varid, attname }); - } else { - // Main thread path is already synchronous (or could be wrapped in Promise.resolve) - return NCGet.getAttributeValues( - this.module as NetCDF4Module, - this.ncid, - varid, - attname, - ); - } + return this.run("getAttributeValues", { varid, attname }); } async getDimCount(ncid: number = this.ncid): Promise { - if (this.worker) { - return this.callWorker("getDimCount", { ncid }); - } else { - // Main thread path is already synchronous (or could be wrapped in Promise.resolve) - return NCGet.getDimCount(this.module as NetCDF4Module, ncid); - } + return this.run("getDimCount", { ncid }); } async getGroupVariables(groupPath?: string): Promise> { - if (this.worker) { - return this.callWorker("getGroupVariables", { groupPath }); - } else { - // Main thread path is already synchronous (or could be wrapped in Promise.resolve) - return NCGet.getGroupVariables( - this.module as NetCDF4Module, - this.ncid, - groupPath, - ); - } + return this.run("getGroupVariables", { groupPath }); } async getVarIDs(ncid: number = this.ncid): Promise { - if (this.worker) { - return this.callWorker("getVarIDs", { ncid }); - } else { - // Main thread path is already synchronous (or could be wrapped in Promise.resolve) - return NCGet.getVarIDs(this.module as NetCDF4Module, ncid); - } + return this.run("getVarIDs", { ncid }); } async getDimIDs(ncid: number = this.ncid): Promise { - if (this.worker) { - return this.callWorker("getDimIDs", { ncid }); - } else { - // Main thread path is already synchronous (or could be wrapped in Promise.resolve) - return NCGet.getDimIDs(this.module as NetCDF4Module, ncid); - } + return this.run("getDimIDs", { ncid }); } async getDim( dimid: number, ncid: number = this.ncid, ): Promise> { - if (this.worker) { - return this.callWorker("getDim", { dimid, ncid }); - } else { - // Main thread path is already synchronous (or could be wrapped in Promise.resolve) - return NCGet.getDim(this.module as NetCDF4Module, ncid, dimid); - } + return this.run("getDim", { dimid, ncid }); } async getDims(groupPath?: string): Promise> { - if (this.worker) { - return this.callWorker("getDims", { groupPath }); - } else { - // Main thread path is already synchronous (or could be wrapped in Promise.resolve) - return NCGet.getDims( - this.module as NetCDF4Module, - this.ncid, - groupPath, - ); - } + return this.run("getDims", { groupPath }); } async getVarCount(ncid: number = this.ncid): Promise { - if (this.worker) { - return this.callWorker("getVarCount", { ncid }); - } else { - // Main thread path is already synchronous (or could be wrapped in Promise.resolve) - return NCGet.getVarCount(this.module as NetCDF4Module, ncid); - } + return this.run("getVarCount", { ncid }); } async getAttributeName( varid: number, attId: number, ): Promise { - if (this.worker) { - return this.callWorker("getAttributeName", { varid, attId }); - } else { - // Main thread path is already synchronous (or could be wrapped in Promise.resolve) - return NCGet.getAttributeName( - this.module as NetCDF4Module, - this.ncid, - varid, - attId, - ); - } + return this.run("getAttributeName", { varid, attId }); } async getVariableInfo( variable: number | string, groupPath?: string, ): Promise> { - if (this.worker) { - return this.callWorker("getVariableInfo", { variable, groupPath }); - } else { - // Main thread path is already synchronous (or could be wrapped in Promise.resolve) - return NCGet.getVariableInfo( - this.module as NetCDF4Module, - this.ncid, - variable, - groupPath, - ); - } + return this.run("getVariableInfo", { variable, groupPath }); } async getVariableArray( @@ -650,17 +544,7 @@ export class NetCDF4 extends Group { | BigUint64Array | string[] > { - if (this.worker) { - return this.callWorker("getVariableArray", { variable, groupPath }); - } else { - // Main thread path is already synchronous (or could be wrapped in Promise.resolve) - return NCGet.getVariableArray( - this.module as NetCDF4Module, - this.ncid, - variable, - groupPath, - ); - } + return this.run("getVariableArray", { variable, groupPath }); } async getSlicedVariableArray( @@ -681,24 +565,12 @@ export class NetCDF4 extends Group { | BigUint64Array | string[] > { - if (this.worker) { - return this.callWorker("getSlicedVariableArray", { - variable, - start, - count, - groupPath, - }); - } else { - // Main thread path is already synchronous (or could be wrapped in Promise.resolve) - return NCGet.getSlicedVariableArray( - this.module as NetCDF4Module, - this.ncid, - variable, - start, - count, - groupPath, - ); - } + return this.run("getSlicedVariableArray", { + variable, + start, + count, + groupPath, + }); } /** @@ -742,71 +614,35 @@ export class NetCDF4 extends Group { | BigUint64Array | string[] > { - if (this.worker) { - return this.callWorker("getVariableArrayWithSelection", { - ncid: this.ncid, - variable, - selection, - groupPath, - options, - }); - } else { - return NCGet.getVariableArrayWithSelection( - this.module as NetCDF4Module, - this.ncid, - variable, - selection, - groupPath, - options, - ); - } + return this.run("getVariableArrayWithSelection", { + variable, + selection, + groupPath, + options, + }); } // Group functions async getGroups(ncid: number = this.ncid): Promise> { - if (this.worker) { - return this.callWorker("getGroups", { ncid }); - } else { - return NCGet.getGroups(this.module as NetCDF4Module, ncid); - } + return this.run("getGroups", { ncid }); } async getGroupsRecursive( ncid: number = this.ncid, ): Promise> { - if (this.worker) { - return this.callWorker("getGroupsRecursive", { ncid }); - } else { - return NCGet.getGroupsRecursive(this.module as NetCDF4Module, ncid); - } + return this.run("getGroupsRecursive", { ncid }); } async getGroupNCID(groupPath: string): Promise { - if (this.worker) { - return this.callWorker("getGroupNCID", { groupPath }); - } else { - return NCGet.getGroupNCID( - this.module as NetCDF4Module, - this.ncid, - groupPath, - ); - } + return this.run("getGroupNCID", { groupPath }); } async getGroupName(ncid: number = this.ncid): Promise { - if (this.worker) { - return this.callWorker("getGroupName", { ncid }); - } else { - return NCGet.getGroupName(this.module as NetCDF4Module, ncid); - } + return this.run("getGroupName", { ncid }); } async getGroupPath(ncid: number = this.ncid): Promise { - if (this.worker) { - return this.callWorker("getGroupPath", { ncid }); - } else { - return NCGet.getGroupPath(this.module as NetCDF4Module, ncid); - } + return this.run("getGroupPath", { ncid }); } async defineDimension( @@ -978,15 +814,7 @@ export class NetCDF4 extends Group { async getCompleteHierarchy( groupPath?: string, ): Promise> { - if (this.worker) { - return this.callWorker("getCompleteHierarchy", { groupPath }); - } else { - return NCGet.getCompleteHierarchy( - this.module as NetCDF4Module, - this.ncid, - groupPath, - ); - } + return this.run("getCompleteHierarchy", { groupPath }); } /** @@ -994,11 +822,7 @@ export class NetCDF4 extends Group { * Returns a flat dictionary with full path keys like "/group1/var1" */ async getVariables(): Promise> { - if (this.worker) { - return this.callWorker("getVariables"); - } else { - return NCGet.getVariables(this.module as NetCDF4Module, this.ncid); - } + return this.run("getVariables", {}); } } diff --git a/src/operations.ts b/src/operations.ts new file mode 100644 index 0000000..b00181b --- /dev/null +++ b/src/operations.ts @@ -0,0 +1,161 @@ +// Every operation a dataset can run on its WASM module, defined once. +// NetCDF4 calls them directly on the main thread and sends them by name to +// netcdf-worker otherwise, so both paths run the same code. + +import { NC_CONSTANTS } from "./constants.js"; +import * as NCGet from "./netcdf-getters.js"; +import type { DimSelection } from "./slice.js"; +import type { NetCDF4Module } from "./types.js"; + +// Arguments of an operation: the ncid it runs on, plus its own +type Args = { ncid: number } & T; +type GroupArgs = Args<{ groupPath?: string }>; +type VariableArgs = Args<{ variable: number | string; groupPath?: string }>; + +export const operations = { + open: ( + module: NetCDF4Module, + { path, modeValue }: Args<{ path: string; modeValue: number }>, + ) => { + const result = module.nc_open(path, modeValue); + if (result.result !== NC_CONSTANTS.NC_NOERR) { + throw new Error( + `Failed to open NetCDF file: ${path} (error: ${result.result})`, + ); + } + return result.ncid; + }, + + close: (module: NetCDF4Module, { ncid }: Args) => { + const result = module.nc_close(ncid); + if (result !== NC_CONSTANTS.NC_NOERR) { + throw new Error( + `Failed to close NetCDF file with ID: ${ncid} (error: ${result})`, + ); + } + }, + + // ---- Globals ---- + getGlobalAttributes: (module: NetCDF4Module, a: GroupArgs) => + NCGet.getGlobalAttributes(module, a.ncid, a.groupPath), + + getFullMetadata: (module: NetCDF4Module, a: GroupArgs) => + NCGet.getFullMetadata(module, a.ncid, a.groupPath), + + // ---- Dims ---- + getDimCount: (module: NetCDF4Module, a: Args) => + NCGet.getDimCount(module, a.ncid), + + getDimIDs: (module: NetCDF4Module, a: Args) => + NCGet.getDimIDs(module, a.ncid), + + getDim: (module: NetCDF4Module, a: Args<{ dimid: number }>) => + NCGet.getDim(module, a.ncid, a.dimid), + + getDims: (module: NetCDF4Module, a: GroupArgs) => + NCGet.getDims(module, a.ncid, a.groupPath), + + // ---- Vars ---- + getGroupVariables: (module: NetCDF4Module, a: GroupArgs) => + NCGet.getGroupVariables(module, a.ncid, a.groupPath), + + getVarIDs: (module: NetCDF4Module, a: Args) => + NCGet.getVarIDs(module, a.ncid), + + getVarCount: (module: NetCDF4Module, a: Args) => + NCGet.getVarCount(module, a.ncid), + + getAttributeName: ( + module: NetCDF4Module, + a: Args<{ varid: number; attId: number }>, + ) => NCGet.getAttributeName(module, a.ncid, a.varid, a.attId), + + getAttributeValues: ( + module: NetCDF4Module, + a: Args<{ varid: number; attname: string }>, + ) => NCGet.getAttributeValues(module, a.ncid, a.varid, a.attname), + + getVariableInfo: (module: NetCDF4Module, a: VariableArgs) => + NCGet.getVariableInfo(module, a.ncid, a.variable, a.groupPath), + + // ---- Arrays ---- + getVariableArray: (module: NetCDF4Module, a: VariableArgs) => + NCGet.getVariableArray(module, a.ncid, a.variable, a.groupPath), + + getSlicedVariableArray: ( + module: NetCDF4Module, + a: VariableArgs & { start: number[]; count: number[] }, + ) => + NCGet.getSlicedVariableArray( + module, + a.ncid, + a.variable, + a.start, + a.count, + a.groupPath, + ), + + getVariableArrayWithSelection: ( + module: NetCDF4Module, + a: VariableArgs & { + selection: DimSelection[]; + options?: { convertEnumsToNames?: boolean }; + }, + ) => + NCGet.getVariableArrayWithSelection( + module, + a.ncid, + a.variable, + a.selection, + a.groupPath, + a.options, + ), + + // ---- Groups ---- + getGroups: (module: NetCDF4Module, a: Args) => + NCGet.getGroups(module, a.ncid), + + getGroupsRecursive: (module: NetCDF4Module, a: Args) => + NCGet.getGroupsRecursive(module, a.ncid), + + getGroupNCID: (module: NetCDF4Module, a: Args<{ groupPath: string }>) => + NCGet.getGroupNCID(module, a.ncid, a.groupPath), + + getGroupName: (module: NetCDF4Module, a: Args) => + NCGet.getGroupName(module, a.ncid), + + getGroupPath: (module: NetCDF4Module, a: Args) => + NCGet.getGroupPath(module, a.ncid), + + getCompleteHierarchy: (module: NetCDF4Module, a: GroupArgs) => + NCGet.getCompleteHierarchy(module, a.ncid, a.groupPath), + + getVariables: (module: NetCDF4Module, a: Args) => + NCGet.getVariables(module, a.ncid), +}; + +export type OperationName = keyof typeof operations; +export type OperationArgs = Parameters< + (typeof operations)[K] +>[1]; +export type OperationResult = ReturnType< + (typeof operations)[K] +>; + +export function isOperationName(name: unknown): name is OperationName { + return typeof name === "string" && Object.hasOwn(operations, name); +} + +// Run an operation by name. The cast is needed because TypeScript cannot +// relate the arguments of operations[name] to a generic name. +export function runOperation( + module: NetCDF4Module, + name: K, + args: OperationArgs, +): OperationResult { + const operation = operations[name] as ( + module: NetCDF4Module, + args: OperationArgs, + ) => OperationResult; + return operation(module, args); +} diff --git a/tests/README.md b/tests/README.md index 9685376..228c054 100644 --- a/tests/README.md +++ b/tests/README.md @@ -12,8 +12,10 @@ npm test # or test:watch, test:coverage - `unit/`: code that needs no WASM module: slicing, range requests and the block cache (with a fake `XMLHttpRequest`/`fetch`), and the worker - handshake (with a fake `Worker`). The worker path itself is not covered: - it needs a browser for `Worker` and `WORKERFS`. + handshake (with a fake `Worker`). The worker runs the same operations + (`src/operations.ts`) as the main thread, so `wasm/` covers them; only the + message passing and `WORKERFS` mounting are not covered, as they need a + browser. - `wasm/`: reads the fixtures through the WASM module, and writes new files. - `setup.ts`: lets the browser-only module run in Node. It stubs `window`, serves the `.wasm` binary through `fetch`, and compiles it once per test