@node-ctypes/python 0.2.0 → 0.3.0

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.
@@ -5,6 +5,12 @@ export declare function nextCompletionToken(previous: number, pending: ReadonlyM
5
5
  export interface Cancellable {
6
6
  cancel?: () => void;
7
7
  }
8
+ /** A request's result (new reference), or the exception it raised (new reference). */
9
+ export type Outcome = {
10
+ readonly value: bigint;
11
+ } | {
12
+ readonly error: bigint;
13
+ };
8
14
  /**
9
15
  * Python requests run in order on a node-ctypes Executor thread (no libuv
10
16
  * worker waits for them). Each request is a call of a Python ctypes callback
@@ -13,7 +19,7 @@ export interface Cancellable {
13
19
  export declare class PythonExecutor {
14
20
  #private;
15
21
  constructor(api: PythonLibrary, check: (ptr: Pointer) => bigint, withGIL: <T>(fn: () => T) => T);
16
- callAsync(request: Pointer, control?: Cancellable): Promise<Pointer>;
22
+ callAsync(request: Pointer, control?: Cancellable): Promise<Outcome>;
17
23
  close(): Promise<void>;
18
24
  abandon(): void;
19
25
  }
package/dist/executor.js CHANGED
@@ -10,7 +10,7 @@ export function nextCompletionToken(previous, pending) {
10
10
  } while (pending.has(token));
11
11
  return token;
12
12
  }
13
- const HELPERS = ["_cancel", "_discard", "_cancelled_outcome"];
13
+ const HELPERS = ["_cancel", "_discard", "_take_failure", "_cancelled_failure"];
14
14
  const SOURCE = `
15
15
  import ctypes
16
16
  import importlib
@@ -33,6 +33,8 @@ _ident = None
33
33
  _current = None
34
34
  _interrupted = False
35
35
  _cancelled = set()
36
+ # Exceptions of failed requests, by token, until the host takes them.
37
+ _failures = {}
36
38
 
37
39
  def _execute(request):
38
40
  operation, *args = request
@@ -67,7 +69,10 @@ def _settle():
67
69
  try:
68
70
  with _lock:
69
71
  _current = None
70
- _clear_async(_ident, None)
72
+ # Only an injected abort can be pending: _cancel injects under
73
+ # this lock, while this request is _current.
74
+ if _interrupted:
75
+ _clear_async(_ident, None)
71
76
  return
72
77
  except _base_error:
73
78
  # An abort that landed after the operation completed. It can land
@@ -95,20 +100,25 @@ def _discard(token):
95
100
  with _lock:
96
101
  _cancelled.discard(token)
97
102
 
98
- def _cancelled_outcome():
99
- return (False, _interrupt())
103
+ def _take_failure(token):
104
+ return _failures.pop(token)
105
+
106
+ def _cancelled_failure():
107
+ return _interrupt()
100
108
 
101
109
  def _entry(request, token):
102
110
  # Runs on the executor thread; ctypes takes the GIL around the callback.
103
- # The outcome is returned as a new reference, owned by the host.
111
+ # The value is returned as a new reference, owned by the host; a failure
112
+ # returns NULL and keeps its exception for _take_failure.
104
113
  global _ident
105
114
  _ident = _get_ident()
106
115
  try:
107
- outcome = (True, _run(request, token))
116
+ value = _run(request, token)
108
117
  except _base_error as error:
109
- outcome = (False, error)
110
- _incref(outcome)
111
- return id(outcome)
118
+ _failures[token] = error
119
+ return None
120
+ _incref(value)
121
+ return id(value)
112
122
 
113
123
  _entry_callback = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.py_object, ctypes.c_int)(_entry)
114
124
  _entry_address = ctypes.cast(_entry_callback, ctypes.c_void_p).value
@@ -202,34 +212,48 @@ export class PythonExecutor {
202
212
  if (!this.#executor._cancel(job, CANCELLED))
203
213
  this.#tokenHelper("_cancel", token);
204
214
  };
205
- const settled = task
206
- .then((outcome) => {
207
- if (cancelled)
208
- this.#tokenHelper("_discard", token);
209
- return outcome;
210
- }, (error) => {
211
- if (error === CANCELLED)
212
- return this.#withGIL(() => this.#call("_cancelled_outcome"));
213
- throw error;
214
- })
215
- .finally(() => {
215
+ // One reaction (no finally: it would add two steps to every request).
216
+ const done = () => {
216
217
  if (control)
217
218
  control.cancel = undefined;
218
219
  this.#pending.delete(token);
219
- });
220
- this.#pending.set(token, settled);
221
- return settled;
222
- }
223
- #tokenHelper(name, token) {
224
- this.#withGIL(() => {
225
- const id = this.#check(this.#api.PyLong_FromLongLong(token));
220
+ };
221
+ const settled = task.then((value) => {
222
+ try {
223
+ if (cancelled)
224
+ this.#tokenHelper("_discard", token);
225
+ if (value !== null)
226
+ return { value };
227
+ return { error: this.#withGIL(() => this.#withToken(token, (id) => this.#call("_take_failure", [id]))) };
228
+ }
229
+ finally {
230
+ done();
231
+ }
232
+ }, (error) => {
226
233
  try {
227
- this.#api.Py_DecRef(this.#call(name, [id]));
234
+ if (error === CANCELLED)
235
+ return { error: this.#withGIL(() => this.#call("_cancelled_failure")) };
236
+ throw error;
228
237
  }
229
238
  finally {
230
- this.#api.Py_DecRef(id);
239
+ done();
231
240
  }
232
241
  });
242
+ this.#pending.set(token, settled);
243
+ return settled;
244
+ }
245
+ #tokenHelper(name, token) {
246
+ this.#withGIL(() => this.#api.Py_DecRef(this.#withToken(token, (id) => this.#call(name, [id]))));
247
+ }
248
+ /** `use` with the token as a Python int (GIL held). */
249
+ #withToken(token, use) {
250
+ const id = this.#check(this.#api.PyLong_FromLongLong(token));
251
+ try {
252
+ return use(id);
253
+ }
254
+ finally {
255
+ this.#api.Py_DecRef(id);
256
+ }
233
257
  }
234
258
  #call(name, args = []) {
235
259
  const helper = this.#helpers.get(name);
package/dist/runtime.js CHANGED
@@ -63,6 +63,7 @@ export class Python {
63
63
  #state = "initializing";
64
64
  #ownsInterpreter = false;
65
65
  #executor;
66
+ #operations = new Map(); // executor operation names as Python str (#operationName)
66
67
  #pending = new Set();
67
68
  #closing = null;
68
69
  #callControls = new WeakMap();
@@ -674,6 +675,9 @@ export class Python {
674
675
  this.#withGIL(() => {
675
676
  this.#drain();
676
677
  this.#nativeObjects?.releaseType();
678
+ for (const name of this.#operations.values())
679
+ this.#api.Py_DecRef(name);
680
+ this.#operations.clear();
677
681
  }, true);
678
682
  }
679
683
  catch (error) {
@@ -771,8 +775,28 @@ export class Python {
771
775
  }
772
776
  }
773
777
  async #nativeCall(name, args, control) {
774
- const request = this.#withGIL(() => this.#filled(this.#api.PyTuple_New(args.length + 1), (tuple) => {
775
- this.#status(this.#api.PyTuple_SetItem(tuple, 0, this.#toPy(name)));
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(() => {
788
+ try {
789
+ return this.#consumeOutcome(outcome);
790
+ }
791
+ finally {
792
+ this.#api.Py_DecRef(request);
793
+ }
794
+ }, true);
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)));
776
800
  args.forEach((value, i) => {
777
801
  const pointerArgument = name === "ExecuteSource" ? i === 2 : API[name][1][i] === c_void_p;
778
802
  const ptr = pointerArgument && value !== null ? this.#check(typeof value === "bigint" ? value : null) : this.#toPy(value);
@@ -780,46 +804,41 @@ export class Python {
780
804
  this.#api.Py_IncRef(ptr);
781
805
  this.#status(this.#api.PyTuple_SetItem(tuple, i + 1, ptr));
782
806
  });
783
- }), true);
784
- // Submitted after releasing the GIL: the executor thread can take it at once.
785
- let task;
786
- try {
787
- task = this.#executor.callAsync(request, control);
788
- if (control?.aborted)
789
- control.cancel?.();
790
- }
791
- catch (error) {
792
- this.#withGIL(() => this.#api.Py_DecRef(request), true);
793
- throw error;
794
- }
795
- try {
796
- const outcome = await task;
797
- return this.#withGIL(() => this.#consumeOutcome(outcome), true);
798
- }
799
- finally {
800
- this.#withGIL(() => this.#api.Py_DecRef(request), true);
801
- }
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;
802
818
  }
803
819
  #consumeOutcome(outcome) {
804
- return this.#using(this.#check(outcome), (outcome) => {
805
- if (this.#api.PyTuple_Size(outcome) !== 2n)
806
- throw new Error("Python executor returned an invalid outcome");
807
- const success = this.#status(this.#api.PyObject_IsTrue(this.#api.PyTuple_GetItem(outcome, 0)));
808
- const value = this.#check(this.#api.PyTuple_GetItem(outcome, 1));
809
- this.#api.Py_IncRef(value);
810
- if (success)
811
- return value;
812
- if (!this.#registry) {
813
- try {
814
- throw new Error(`Python startup failed: ${this.#take(this.#api.PyObject_Str(value))}`);
815
- }
816
- finally {
817
- this.#api.Py_DecRef(value);
818
- }
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))}`);
819
826
  }
820
- this.#api.PyErr_SetRaisedException(value);
821
- throw this.#fetchError();
822
- });
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;
823
842
  }
824
843
  #track(work) {
825
844
  if (this.#state !== "running")
@@ -1487,27 +1506,41 @@ export class Python {
1487
1506
  #callAsync(target, args, keep = false) {
1488
1507
  const control = { aborted: false };
1489
1508
  const promise = this.#track(async () => {
1490
- const held = this.#withGIL(() => {
1491
- const callable = this.#toPy(target);
1492
- const values = args.at(-1) instanceof Kwargs ? args.slice(0, -1) : args;
1493
- 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(() => {
1494
1513
  try {
1495
- 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)))));
1496
- 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))))));
1497
1517
  const last = args.at(-1);
1498
- const keywords = last instanceof Kwargs ? this.#toPy(last.values) : null;
1499
- pointers.push(keywords);
1500
- return pointers;
1518
+ held.push(last instanceof Kwargs ? this.#toPy(last.values) : null);
1519
+ return this.#request("PyObject_Call", held);
1501
1520
  }
1502
1521
  catch (error) {
1503
- for (const ptr of pointers)
1522
+ for (const ptr of held)
1504
1523
  this.#api.Py_DecRef(ptr);
1505
1524
  throw error;
1506
1525
  }
1507
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;
1508
1534
  try {
1509
- const result = await this.#nativeCall("PyObject_Call", held, control);
1510
- 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);
1511
1544
  let value = keep ? this.#wrap(this.#check(result), true) : this.#take(result, true);
1512
1545
  if (this.#states.has(value) && this.#scheduler.isAwaitable(value)) {
1513
1546
  const awaitable = value;
@@ -1517,15 +1550,11 @@ export class Python {
1517
1550
  this.#states.get(awaitable).future?.cancel();
1518
1551
  }
1519
1552
  return { value };
1520
- });
1521
- }
1522
- finally {
1523
- this.#withGIL(() => {
1524
- for (const ptr of held)
1525
- this.#api.Py_DecRef(ptr);
1526
- this.#drain();
1527
- });
1528
- }
1553
+ }
1554
+ finally {
1555
+ release();
1556
+ }
1557
+ }, true);
1529
1558
  }).then(({ value }) => value);
1530
1559
  this.#callControls.set(promise, control);
1531
1560
  return promise;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@node-ctypes/python",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
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.12.2"
57
+ "node-ctypes": "^2.15.0"
58
58
  },
59
59
  "devDependencies": {
60
60
  "@types/node": "^26.6.6",