@node-ctypes/python 0.1.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/runtime.js CHANGED
@@ -4,7 +4,7 @@ import { addressof, byref, memmove, array, EXTERNAL_BUFFERS, c_char_p, c_void_p,
4
4
  import { API, MIN_PYTHON, Py_file_input, Py_eval_input, METH_VARARGS, METH_KEYWORDS, PyMethodDef, TYPES } from "./native.js";
5
5
  import { PythonBootstrap } from "./bootstrap.js";
6
6
  import { PythonScheduler } from "./scheduler.js";
7
- import { PythonPlatform } from "./platform.js";
7
+ import { PythonPlatform, lineWriter } from "./platform.js";
8
8
  import { PythonConversions } from "./conversions.js";
9
9
  import { PythonBuffers } from "./buffers.js";
10
10
  import { PythonExecutor } from "./executor.js";
@@ -24,6 +24,11 @@ class ProxyStates extends WeakMap {
24
24
  }
25
25
  }
26
26
  const DONE = Symbol("done");
27
+ // SharedArrayBuffer is not defined where the page is not cross-origin isolated
28
+ // (e.g. an Electron renderer): only an ArrayBuffer can be passed there.
29
+ function isArrayBuffer(value) {
30
+ return value instanceof ArrayBuffer || (typeof SharedArrayBuffer === "function" && value instanceof SharedArrayBuffer);
31
+ }
27
32
  function isThenable(value) {
28
33
  return value !== null && (typeof value === "object" || typeof value === "function") && typeof Reflect.get(value, "then") === "function";
29
34
  }
@@ -58,6 +63,7 @@ export class Python {
58
63
  #state = "initializing";
59
64
  #ownsInterpreter = false;
60
65
  #executor;
66
+ #operations = new Map(); // executor operation names as Python str (#operationName)
61
67
  #pending = new Set();
62
68
  #closing = null;
63
69
  #callControls = new WeakMap();
@@ -126,8 +132,8 @@ export class Python {
126
132
  * @param {string} [options.executable] - Python interpreter whose library and environment are used (default: $PYTHON, python3, python, py)
127
133
  * @param {string} [options.library] - Explicit path of the Python shared library (default: $PYTHON_LIBRARY); same version as the interpreter
128
134
  * @param {boolean} [options.stdin=true] - false: Python does not read the process stdin (sys.stdin is None), left to Node.js
129
- * @param {"inherit"|"node"|Function} [options.stdout="inherit"] - sys.stdout: the process stdout ("inherit"), process.stdout of Node.js, in order with console.log ("node"), or a function receiving the text
130
- * @param {"inherit"|"node"|Function} [options.stderr="inherit"] - sys.stderr, as stdout
135
+ * @param {"inherit"|"node"|"console"|Function} [options.stdout="inherit"] - sys.stdout: the process stdout ("inherit"), process.stdout of Node.js, in order with console.log ("node"), whole lines to console.log ("console", e.g. DevTools in an Electron renderer), or a function receiving the text
136
+ * @param {"inherit"|"node"|"console"|Function} [options.stderr="inherit"] - sys.stderr, as stdout ("console": console.error)
131
137
  * @param {boolean} [options.synchronousCallbacks=false] - serve native callbacks during interruptible synchronous Python waits
132
138
  * @param {number} [options.switchInterval=5] - GIL switch interval in milliseconds (sys.setswitchinterval), as in CPython; a smaller value (0.5) keeps the Node.js event loop responsive while Python threads run CPU-bound code, at the cost of slower contended Python threads
133
139
  * @returns {Promise<Python>}
@@ -172,8 +178,8 @@ export class Python {
172
178
  throw new TypeError("options.nativeObjects has been removed: native objects are always enabled; use options.synchronousCallbacks for interruptible synchronous waits");
173
179
  const { executable, library = process.env.PYTHON_LIBRARY, stdin = true, stdout = "inherit", stderr = "inherit", synchronousCallbacks = false, switchInterval = 5 } = options;
174
180
  for (const [name, value] of Object.entries({ stdout, stderr })) {
175
- if (value !== "inherit" && value !== "node" && typeof value !== "function")
176
- throw new TypeError(`options.${name} must be "inherit", "node" or a function`);
181
+ if (value !== "inherit" && value !== "node" && value !== "console" && typeof value !== "function")
182
+ throw new TypeError(`options.${name} must be "inherit", "node", "console" or a function`);
177
183
  }
178
184
  if (typeof synchronousCallbacks !== "boolean")
179
185
  throw new TypeError("options.synchronousCallbacks must be a boolean");
@@ -268,7 +274,7 @@ export class Python {
268
274
  if (setHome)
269
275
  delete process.env.PYTHONHOME;
270
276
  }
271
- this.#executor = this.#withGIL(() => new PythonExecutor(this.#api, (ptr) => this.#check(ptr), (fn) => this.#withGIL(fn, true), (outcome) => this.#consumeOutcome(outcome)));
277
+ this.#executor = this.#withGIL(() => new PythonExecutor(this.#api, (ptr) => this.#check(ptr), (fn) => this.#withGIL(fn, true)));
272
278
  for (const name of [
273
279
  "threading",
274
280
  "types",
@@ -382,6 +388,11 @@ export class Python {
382
388
  const target = streams[name];
383
389
  if (target === "inherit")
384
390
  continue;
391
+ if (target === "console") {
392
+ const lines = lineWriter(name === "stdout" ? (line) => console.log(line) : (line) => console.error(line));
393
+ this.#platform.redirect(name, lines.write, lines.flush);
394
+ continue;
395
+ }
385
396
  const write = target === "node" ? (text) => void process[name].write(text) : (text) => void target(text);
386
397
  this.#platform.redirect(name, write);
387
398
  }
@@ -664,6 +675,9 @@ export class Python {
664
675
  this.#withGIL(() => {
665
676
  this.#drain();
666
677
  this.#nativeObjects?.releaseType();
678
+ for (const name of this.#operations.values())
679
+ this.#api.Py_DecRef(name);
680
+ this.#operations.clear();
667
681
  }, true);
668
682
  }
669
683
  catch (error) {
@@ -761,56 +775,70 @@ export class Python {
761
775
  }
762
776
  }
763
777
  async #nativeCall(name, args, control) {
764
- const { request, task } = this.#withGIL(() => {
765
- const request = this.#filled(this.#api.PyTuple_New(args.length + 1), (tuple) => {
766
- this.#status(this.#api.PyTuple_SetItem(tuple, 0, this.#toPy(name)));
767
- args.forEach((value, i) => {
768
- const pointerArgument = name === "ExecuteSource" ? i === 2 : API[name][1][i] === c_void_p;
769
- const ptr = pointerArgument && value !== null ? this.#check(typeof value === "bigint" ? value : null) : this.#toPy(value);
770
- if (pointerArgument && value !== null)
771
- this.#api.Py_IncRef(ptr);
772
- this.#status(this.#api.PyTuple_SetItem(tuple, i + 1, ptr));
773
- });
774
- });
778
+ const request = this.#withGIL(() => this.#request(name, args), true);
779
+ let outcome;
780
+ try {
781
+ outcome = await this.#submit(request, control);
782
+ }
783
+ catch (error) {
784
+ this.#withGIL(() => this.#api.Py_DecRef(request), true);
785
+ throw error;
786
+ }
787
+ return this.#withGIL(() => {
775
788
  try {
776
- const task = this.#executor.callAsync(request, control);
777
- if (control?.aborted)
778
- control.cancel?.();
779
- return { request, task };
789
+ return this.#consumeOutcome(outcome);
780
790
  }
781
- catch (error) {
791
+ finally {
782
792
  this.#api.Py_DecRef(request);
783
- throw error;
784
793
  }
785
794
  }, true);
786
- try {
787
- const outcome = await task;
788
- return this.#withGIL(() => this.#consumeOutcome(outcome), true);
789
- }
790
- finally {
791
- this.#withGIL(() => this.#api.Py_DecRef(request), true);
792
- }
795
+ }
796
+ /** The executor request `(operation, ...args)` (GIL held; new reference). */
797
+ #request(name, args) {
798
+ return this.#filled(this.#api.PyTuple_New(args.length + 1), (tuple) => {
799
+ this.#status(this.#api.PyTuple_SetItem(tuple, 0, this.#operationName(name)));
800
+ args.forEach((value, i) => {
801
+ const pointerArgument = name === "ExecuteSource" ? i === 2 : API[name][1][i] === c_void_p;
802
+ const ptr = pointerArgument && value !== null ? this.#check(typeof value === "bigint" ? value : null) : this.#toPy(value);
803
+ if (pointerArgument && value !== null)
804
+ this.#api.Py_IncRef(ptr);
805
+ this.#status(this.#api.PyTuple_SetItem(tuple, i + 1, ptr));
806
+ });
807
+ });
808
+ }
809
+ /**
810
+ * Submit `request` after releasing the GIL: the executor thread can take it
811
+ * at once. The caller still owns `request` (also when this throws).
812
+ */
813
+ #submit(request, control) {
814
+ const task = this.#executor.callAsync(request, control);
815
+ if (control?.aborted)
816
+ control.cancel?.();
817
+ return task;
793
818
  }
794
819
  #consumeOutcome(outcome) {
795
- return this.#using(this.#check(outcome), (outcome) => {
796
- if (this.#api.PyTuple_Size(outcome) !== 2n)
797
- throw new Error("Python executor returned an invalid outcome");
798
- const success = this.#status(this.#api.PyObject_IsTrue(this.#api.PyTuple_GetItem(outcome, 0)));
799
- const value = this.#check(this.#api.PyTuple_GetItem(outcome, 1));
800
- this.#api.Py_IncRef(value);
801
- if (success)
802
- return value;
803
- if (!this.#registry) {
804
- try {
805
- throw new Error(`Python startup failed: ${this.#take(this.#api.PyObject_Str(value))}`);
806
- }
807
- finally {
808
- this.#api.Py_DecRef(value);
809
- }
820
+ if ("value" in outcome)
821
+ return outcome.value;
822
+ const { error } = outcome;
823
+ if (!this.#registry) {
824
+ try {
825
+ throw new Error(`Python startup failed: ${this.#take(this.#api.PyObject_Str(error))}`);
810
826
  }
811
- this.#api.PyErr_SetRaisedException(value);
812
- throw this.#fetchError();
813
- });
827
+ finally {
828
+ this.#api.Py_DecRef(error);
829
+ }
830
+ }
831
+ // Steals the reference.
832
+ this.#api.PyErr_SetRaisedException(error);
833
+ throw this.#fetchError();
834
+ }
835
+ /** The executor operation's name as a Python str, converted once (new reference). */
836
+ #operationName(name) {
837
+ let cached = this.#operations.get(name);
838
+ if (cached === undefined)
839
+ this.#operations.set(name, (cached = this.#toPy(name)));
840
+ this.#api.Py_IncRef(cached);
841
+ return cached;
814
842
  }
815
843
  #track(work) {
816
844
  if (this.#state !== "running")
@@ -1071,7 +1099,7 @@ export class Python {
1071
1099
  }
1072
1100
  if (value instanceof Uint8Array && !(value instanceof Uint8ClampedArray))
1073
1101
  return this.#check(api.PyBytes_FromStringAndSize(Buffer.from(value.buffer, value.byteOffset, value.byteLength), value.byteLength));
1074
- if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer || value instanceof SharedArrayBuffer)
1102
+ if (ArrayBuffer.isView(value) || isArrayBuffer(value))
1075
1103
  return this.#memoryview(value);
1076
1104
  if (typeof value !== "object")
1077
1105
  throw new TypeError(`Cannot convert a JavaScript ${typeof value} to Python`);
@@ -1113,7 +1141,7 @@ export class Python {
1113
1141
  }
1114
1142
  /** byReference(value) → new reference. */
1115
1143
  #reference(value) {
1116
- if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer || value instanceof SharedArrayBuffer)
1144
+ if (ArrayBuffer.isView(value) || isArrayBuffer(value))
1117
1145
  return this.#memoryview(value);
1118
1146
  if (value === null || typeof value !== "object" || this.#states.has(value))
1119
1147
  return this.#toPy(value);
@@ -1149,7 +1177,7 @@ export class Python {
1149
1177
  }
1150
1178
  /** memoryview sharing the memory of a typed array / ArrayBuffer / DataView (new reference). */
1151
1179
  #memoryview(value) {
1152
- const view = value instanceof ArrayBuffer || value instanceof SharedArrayBuffer ? new Uint8Array(value) : value;
1180
+ const view = isArrayBuffer(value) ? new Uint8Array(value) : value;
1153
1181
  const bytes = Buffer.from(view.buffer, view.byteOffset, view.byteLength);
1154
1182
  const format = FORMATS[view.constructor.name] ?? "B"; // DataView: bytes
1155
1183
  const address = bytes.length ? addressof(bytes) : 0n;
@@ -1478,27 +1506,41 @@ export class Python {
1478
1506
  #callAsync(target, args, keep = false) {
1479
1507
  const control = { aborted: false };
1480
1508
  const promise = this.#track(async () => {
1481
- const held = this.#withGIL(() => {
1482
- const callable = this.#toPy(target);
1483
- const values = args.at(-1) instanceof Kwargs ? args.slice(0, -1) : args;
1484
- const pointers = [callable];
1509
+ // The GIL twice: arguments and request before the executor, outcome,
1510
+ // result and releases after it.
1511
+ const held = [];
1512
+ const request = this.#withGIL(() => {
1485
1513
  try {
1486
- const tuple = this.#filled(this.#api.PyTuple_New(values.length), (tuple) => values.forEach((value, i) => this.#status(this.#api.PyTuple_SetItem(tuple, i, this.#toPy(value)))));
1487
- pointers.push(tuple);
1514
+ held.push(this.#toPy(target));
1515
+ const values = args.at(-1) instanceof Kwargs ? args.slice(0, -1) : args;
1516
+ held.push(this.#filled(this.#api.PyTuple_New(values.length), (tuple) => values.forEach((value, i) => this.#status(this.#api.PyTuple_SetItem(tuple, i, this.#toPy(value))))));
1488
1517
  const last = args.at(-1);
1489
- const keywords = last instanceof Kwargs ? this.#toPy(last.values) : null;
1490
- pointers.push(keywords);
1491
- return pointers;
1518
+ held.push(last instanceof Kwargs ? this.#toPy(last.values) : null);
1519
+ return this.#request("PyObject_Call", held);
1492
1520
  }
1493
1521
  catch (error) {
1494
- for (const ptr of pointers)
1522
+ for (const ptr of held)
1495
1523
  this.#api.Py_DecRef(ptr);
1496
1524
  throw error;
1497
1525
  }
1498
1526
  });
1527
+ const release = () => {
1528
+ this.#api.Py_DecRef(request);
1529
+ for (const ptr of held)
1530
+ this.#api.Py_DecRef(ptr);
1531
+ this.#drain();
1532
+ };
1533
+ let outcome;
1499
1534
  try {
1500
- const result = await this.#nativeCall("PyObject_Call", held, control);
1501
- return this.#withGIL(() => {
1535
+ outcome = await this.#submit(request, control);
1536
+ }
1537
+ catch (error) {
1538
+ this.#withGIL(release, true);
1539
+ throw error;
1540
+ }
1541
+ return this.#withGIL(() => {
1542
+ try {
1543
+ const result = this.#consumeOutcome(outcome);
1502
1544
  let value = keep ? this.#wrap(this.#check(result), true) : this.#take(result, true);
1503
1545
  if (this.#states.has(value) && this.#scheduler.isAwaitable(value)) {
1504
1546
  const awaitable = value;
@@ -1508,15 +1550,11 @@ export class Python {
1508
1550
  this.#states.get(awaitable).future?.cancel();
1509
1551
  }
1510
1552
  return { value };
1511
- });
1512
- }
1513
- finally {
1514
- this.#withGIL(() => {
1515
- for (const ptr of held)
1516
- this.#api.Py_DecRef(ptr);
1517
- this.#drain();
1518
- });
1519
- }
1553
+ }
1554
+ finally {
1555
+ release();
1556
+ }
1557
+ }, true);
1520
1558
  }).then(({ value }) => value);
1521
1559
  this.#callControls.set(promise, control);
1522
1560
  return promise;
package/dist/types.d.ts CHANGED
@@ -25,7 +25,7 @@ type Float16ArrayIfAvailable = typeof globalThis extends {
25
25
  Float16Array: abstract new (...args: never) => infer T;
26
26
  } ? T : never;
27
27
  export type PythonTypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float16ArrayIfAvailable | Float32Array | Float64Array | BigInt64Array | BigUint64Array;
28
- export type OutputTarget = "inherit" | "node" | ((text: string) => unknown);
28
+ export type OutputTarget = "inherit" | "node" | "console" | ((text: string) => unknown);
29
29
  export interface StreamOptions {
30
30
  stdin: boolean;
31
31
  stdout: OutputTarget;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@node-ctypes/python",
3
- "version": "0.1.1",
3
+ "version": "0.2.1",
4
4
  "description": "Typed embedded CPython for Node.js, powered by node-ctypes",
5
5
  "author": "Damiano Mazzella",
6
6
  "license": "MIT",
@@ -54,7 +54,7 @@
54
54
  "prepublishOnly": "npm test"
55
55
  },
56
56
  "dependencies": {
57
- "node-ctypes": "^2.10.0"
57
+ "node-ctypes": "^2.12.2"
58
58
  },
59
59
  "devDependencies": {
60
60
  "@types/node": "^26.6.6",