-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathpy_callback.c
More file actions
4268 lines (3726 loc) · 147 KB
/
py_callback.c
File metadata and controls
4268 lines (3726 loc) · 147 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2026 Benoit Chesneau
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file py_callback.c
* @brief Erlang callback support and asyncio integration
* @author Benoit Chesneau
*
* @ingroup cb
*
* This module implements bidirectional calling between Python and Erlang,
* enabling Python code to invoke Erlang functions and await their results.
*
* @par Features
*
* - **erlang module**: Python module providing `erlang.call()` and `erlang.func()`
* - **Suspension/Resume**: Reentrant callbacks without blocking dirty schedulers
* - **Asyncio support**: Background event loop for async Python operations
*
* @par Suspension Mechanism
*
* When Python calls `erlang.call('func', args)`:
*
* ```
* ┌────────────┐ ┌─────────────┐ ┌──────────────┐
* │ Python │ raises │ Executor │ returns │ Erlang │
* │ Code │ ──────> │ Catches │ ──────> │ Callback │
* └────────────┘ Suspend │ Exception │ suspend └──────────────┘
* └─────────────┘ │ │
* │ │ result
* ┌─────────────┐ │ │
* │ Resume │ <──────────────┘
* │ Replay │
* └─────────────┘
* │
* v
* ┌────────────┐
* │ Continue │
* │ Python │
* └────────────┘
* ```
*
* @par Why Suspension?
*
* Without suspension, Python calling Erlang would block a dirty scheduler
* while waiting for the Erlang callback to complete. With suspension:
*
* 1. Dirty scheduler is released immediately
* 2. Erlang callback runs on normal scheduler
* 3. Result is stored, Python is replayed on dirty scheduler
*
* @par The 'erlang' Python Module
*
* Provides two calling syntaxes:
*
* ```python
* # Explicit call
* result = erlang.call('my_function', arg1, arg2)
*
* # Attribute-style call (via __getattr__)
* result = erlang.my_function(arg1, arg2)
* ```
*
* @par Thread Safety
*
* - Thread-local storage tracks current worker and suspended state
* - Async event loop runs in dedicated thread
* - Pending futures queue protected by mutex
*
* @note This file is included from py_nif.c (single compilation unit)
*/
/* ============================================================================
* Cached Python Function References
*
* Cache frequently-used Python functions to avoid repeated module import
* and attribute lookup overhead on every callback.
* ============================================================================ */
/** @brief Cached reference to ast.literal_eval function */
static PyObject *g_ast_literal_eval = NULL;
/**
* @brief Initialize cached Python function references
*
* Called during module initialization. Must be called with GIL held.
*/
static void init_callback_cache(void) {
if (g_ast_literal_eval == NULL) {
PyObject *ast_mod = PyImport_ImportModule("ast");
if (ast_mod != NULL) {
g_ast_literal_eval = PyObject_GetAttrString(ast_mod, "literal_eval");
Py_DECREF(ast_mod);
}
if (g_ast_literal_eval == NULL) {
PyErr_Clear(); /* Non-fatal if unavailable */
}
}
}
/**
* @brief Cleanup cached Python function references
*
* Called during module cleanup. Must be called with GIL held.
*/
static void cleanup_callback_cache(void) {
Py_XDECREF(g_ast_literal_eval);
g_ast_literal_eval = NULL;
}
/**
* Get the ProcessError exception class from the current interpreter's erlang module.
* This ensures the correct class is used in subinterpreter contexts where each
* interpreter has its own erlang module with its own ProcessError class.
*/
static PyObject *get_current_process_error(void) {
PyObject *erlang_module = PyImport_ImportModule("erlang");
if (erlang_module == NULL) {
PyErr_Clear();
return ProcessErrorException; /* Fallback to global */
}
PyObject *exc_class = PyObject_GetAttrString(erlang_module, "ProcessError");
Py_DECREF(erlang_module);
if (exc_class == NULL) {
PyErr_Clear();
return ProcessErrorException; /* Fallback to global */
}
/* Note: Returns new reference, but PyErr_SetString expects borrowed.
* We decref here and rely on the module keeping it alive. */
Py_DECREF(exc_class);
return exc_class;
}
/* ============================================================================
* Callback Name Registry
*
* Maintains a C-side registry of registered callback function names.
* This allows erlang_module_getattr to only return ErlangFunction wrappers
* for actually registered functions, preventing introspection issues with
* libraries like torch that probe module attributes.
* ============================================================================ */
/**
* @def CALLBACK_REGISTRY_BUCKETS
* @brief Number of hash buckets for the callback registry
*/
#define CALLBACK_REGISTRY_BUCKETS 64
/**
* @struct callback_name_entry_t
* @brief Entry in the callback name registry hash table
*/
typedef struct callback_name_entry {
char *name; /**< Callback name (owned) */
size_t name_len; /**< Length of name */
struct callback_name_entry *next; /**< Next entry in bucket chain */
} callback_name_entry_t;
/** @brief Hash table buckets for callback registry */
static callback_name_entry_t *g_callback_registry[CALLBACK_REGISTRY_BUCKETS] = {NULL};
/** @brief Mutex protecting the callback registry */
static pthread_mutex_t g_callback_registry_mutex = PTHREAD_MUTEX_INITIALIZER;
/**
* @brief Simple hash function for callback names
*/
static unsigned int callback_name_hash(const char *name, size_t len) {
unsigned int hash = 5381;
for (size_t i = 0; i < len; i++) {
hash = ((hash << 5) + hash) + (unsigned char)name[i];
}
return hash % CALLBACK_REGISTRY_BUCKETS;
}
/**
* @brief Check if a callback name is registered
*
* Thread-safe lookup in the callback registry.
*
* @param name Callback name to check
* @param len Length of name
* @return true if registered, false otherwise
*/
static bool is_callback_registered(const char *name, size_t len) {
unsigned int bucket = callback_name_hash(name, len);
bool found = false;
pthread_mutex_lock(&g_callback_registry_mutex);
callback_name_entry_t *entry = g_callback_registry[bucket];
while (entry != NULL) {
if (entry->name_len == len && memcmp(entry->name, name, len) == 0) {
found = true;
break;
}
entry = entry->next;
}
pthread_mutex_unlock(&g_callback_registry_mutex);
return found;
}
/**
* @brief Register a callback name
*
* Thread-safe addition to the callback registry.
*
* @param name Callback name to register
* @param len Length of name
* @return 0 on success, -1 on failure
*/
static int register_callback_name(const char *name, size_t len) {
/* Check if already registered */
if (is_callback_registered(name, len)) {
return 0; /* Already registered, success */
}
/* Allocate new entry */
callback_name_entry_t *entry = enif_alloc(sizeof(callback_name_entry_t));
if (entry == NULL) {
return -1;
}
entry->name = enif_alloc(len + 1);
if (entry->name == NULL) {
enif_free(entry);
return -1;
}
memcpy(entry->name, name, len);
entry->name[len] = '\0';
entry->name_len = len;
unsigned int bucket = callback_name_hash(name, len);
pthread_mutex_lock(&g_callback_registry_mutex);
entry->next = g_callback_registry[bucket];
g_callback_registry[bucket] = entry;
pthread_mutex_unlock(&g_callback_registry_mutex);
return 0;
}
/**
* @brief Unregister a callback name
*
* Thread-safe removal from the callback registry.
*
* @param name Callback name to unregister
* @param len Length of name
*/
static void unregister_callback_name(const char *name, size_t len) {
unsigned int bucket = callback_name_hash(name, len);
pthread_mutex_lock(&g_callback_registry_mutex);
callback_name_entry_t **pp = &g_callback_registry[bucket];
while (*pp != NULL) {
callback_name_entry_t *entry = *pp;
if (entry->name_len == len && memcmp(entry->name, name, len) == 0) {
*pp = entry->next;
enif_free(entry->name);
enif_free(entry);
break;
}
pp = &entry->next;
}
pthread_mutex_unlock(&g_callback_registry_mutex);
}
/**
* @brief Clean up the callback registry
*
* Frees all entries. Called during NIF unload.
*/
static void cleanup_callback_registry(void) {
pthread_mutex_lock(&g_callback_registry_mutex);
for (int i = 0; i < CALLBACK_REGISTRY_BUCKETS; i++) {
callback_name_entry_t *entry = g_callback_registry[i];
while (entry != NULL) {
callback_name_entry_t *next = entry->next;
enif_free(entry->name);
enif_free(entry);
entry = next;
}
g_callback_registry[i] = NULL;
}
pthread_mutex_unlock(&g_callback_registry_mutex);
}
/* ============================================================================
* Suspended state management
* ============================================================================ */
/**
* Source type for suspended state creation.
* Indicates whether the source is a request or an existing suspended state.
*/
typedef enum {
SUSPENDED_SOURCE_REQUEST, /* Source is py_request_t */
SUSPENDED_SOURCE_EXISTING /* Source is suspended_state_t */
} suspended_source_type_t;
/**
* Source union for suspended state creation.
* Contains pointers to either request or existing suspended state.
*/
typedef struct {
suspended_source_type_t type;
union {
py_request_t *req; /* For SUSPENDED_SOURCE_REQUEST */
suspended_state_t *existing; /* For SUSPENDED_SOURCE_EXISTING */
} data;
} suspended_source_t;
/**
* Internal cleanup helper for suspended state creation failure.
*/
static void cleanup_suspended_state_partial(suspended_state_t *state, PyObject *callback_args) {
if (state->orig_env != NULL) {
enif_free_env(state->orig_env);
}
if (state->callback_args != NULL) {
Py_DECREF(state->callback_args);
} else if (callback_args != NULL) {
Py_DECREF(callback_args);
}
if (state->callback_func_name != NULL) {
enif_free(state->callback_func_name);
}
enif_release_resource(state);
}
/**
* Create a suspended state resource from exception args.
* Args tuple format: (callback_id, func_name, args)
*
* This unified function handles both:
* - Creating from a request (initial suspension)
* - Creating from an existing suspended state (nested suspension during replay)
*
* @param env NIF environment
* @param exc_args Exception args tuple from erlang.call()
* @param source Source of original request data
* @return suspended_state_t* or NULL on error
*/
static suspended_state_t *create_suspended_state_ex(
ErlNifEnv *env, PyObject *exc_args, const suspended_source_t *source) {
(void)env; /* Only needed for future extensions */
if (!PyTuple_Check(exc_args) || PyTuple_Size(exc_args) != 3) {
return NULL;
}
PyObject *callback_id_obj = PyTuple_GetItem(exc_args, 0);
PyObject *func_name_obj = PyTuple_GetItem(exc_args, 1);
PyObject *callback_args = PyTuple_GetItem(exc_args, 2);
if (!PyLong_Check(callback_id_obj) || !PyUnicode_Check(func_name_obj)) {
return NULL;
}
/* Allocate the suspended state resource */
suspended_state_t *state = enif_alloc_resource(
SUSPENDED_STATE_RESOURCE_TYPE, sizeof(suspended_state_t));
if (state == NULL) {
return NULL;
}
/* Initialize the state */
memset(state, 0, sizeof(suspended_state_t));
/* Set worker based on source type */
if (source->type == SUSPENDED_SOURCE_REQUEST) {
state->worker = tl_current_worker;
} else {
state->worker = source->data.existing->worker;
}
state->callback_id = PyLong_AsUnsignedLongLong(callback_id_obj);
/* Copy callback function name */
Py_ssize_t len;
const char *func_name = PyUnicode_AsUTF8AndSize(func_name_obj, &len);
if (func_name == NULL) {
enif_release_resource(state);
return NULL;
}
state->callback_func_name = enif_alloc(len + 1);
if (state->callback_func_name == NULL) {
enif_release_resource(state);
return NULL;
}
memcpy(state->callback_func_name, func_name, len);
state->callback_func_name[len] = '\0';
state->callback_func_len = len;
/* Store reference to callback args */
Py_INCREF(callback_args);
state->callback_args = callback_args;
/* Get request type and timeout based on source */
int request_type;
unsigned long timeout_ms;
if (source->type == SUSPENDED_SOURCE_REQUEST) {
request_type = source->data.req->type;
timeout_ms = source->data.req->timeout_ms;
} else {
request_type = source->data.existing->request_type;
timeout_ms = source->data.existing->orig_timeout_ms;
}
state->request_type = request_type;
state->orig_timeout_ms = timeout_ms;
/* Create environment to hold copied terms */
state->orig_env = enif_alloc_env();
if (state->orig_env == NULL) {
cleanup_suspended_state_partial(state, NULL);
return NULL;
}
/* Copy request-specific data based on source type and request type */
if (request_type == PY_REQ_CALL) {
ErlNifBinary *src_module, *src_func;
ERL_NIF_TERM src_args, src_kwargs;
ErlNifEnv *src_env;
if (source->type == SUSPENDED_SOURCE_REQUEST) {
src_module = &source->data.req->module_bin;
src_func = &source->data.req->func_bin;
src_args = source->data.req->args_term;
src_kwargs = source->data.req->kwargs_term;
src_env = source->data.req->env;
} else {
src_module = &source->data.existing->orig_module;
src_func = &source->data.existing->orig_func;
src_args = source->data.existing->orig_args;
src_kwargs = source->data.existing->orig_kwargs;
src_env = source->data.existing->orig_env;
}
/* Copy module binary */
if (!enif_alloc_binary(src_module->size, &state->orig_module)) {
cleanup_suspended_state_partial(state, NULL);
return NULL;
}
memcpy(state->orig_module.data, src_module->data, src_module->size);
/* Copy function binary */
if (!enif_alloc_binary(src_func->size, &state->orig_func)) {
enif_release_binary(&state->orig_module);
cleanup_suspended_state_partial(state, NULL);
return NULL;
}
memcpy(state->orig_func.data, src_func->data, src_func->size);
/* Copy args and kwargs to our environment */
state->orig_args = enif_make_copy(state->orig_env, src_args);
state->orig_kwargs = enif_make_copy(state->orig_env, src_kwargs);
(void)src_env; /* Used implicitly by enif_make_copy */
} else if (request_type == PY_REQ_EVAL) {
ErlNifBinary *src_code;
ERL_NIF_TERM src_locals;
ErlNifEnv *src_env;
if (source->type == SUSPENDED_SOURCE_REQUEST) {
src_code = &source->data.req->code_bin;
src_locals = source->data.req->locals_term;
src_env = source->data.req->env;
} else {
src_code = &source->data.existing->orig_code;
src_locals = source->data.existing->orig_locals;
src_env = source->data.existing->orig_env;
}
/* Copy code binary */
if (!enif_alloc_binary(src_code->size, &state->orig_code)) {
cleanup_suspended_state_partial(state, NULL);
return NULL;
}
memcpy(state->orig_code.data, src_code->data, src_code->size);
/* Copy locals */
state->orig_locals = enif_make_copy(state->orig_env, src_locals);
(void)src_env; /* Used implicitly by enif_make_copy */
}
/* Initialize synchronization primitives */
pthread_mutex_init(&state->mutex, NULL);
pthread_cond_init(&state->cond, NULL);
state->result_data = NULL;
state->result_len = 0;
state->has_result = false;
state->is_error = false;
return state;
}
/**
* Create a suspended state resource from a request.
* Wrapper for create_suspended_state_ex for initial suspension.
*/
static suspended_state_t *create_suspended_state(ErlNifEnv *env, PyObject *exc_args,
py_request_t *req) {
suspended_source_t source = {
.type = SUSPENDED_SOURCE_REQUEST,
.data.req = req
};
return create_suspended_state_ex(env, exc_args, &source);
}
/**
* Create a new suspended state from an existing one (for nested suspensions).
* Wrapper for create_suspended_state_ex for nested suspension during replay.
*/
static suspended_state_t *create_suspended_state_from_existing(
ErlNifEnv *env, PyObject *exc_args, suspended_state_t *existing) {
suspended_source_t source = {
.type = SUSPENDED_SOURCE_EXISTING,
.data.existing = existing
};
return create_suspended_state_ex(env, exc_args, &source);
}
/**
* Build exception args tuple from thread-local pending callback state.
*
* This helper extracts the common pattern of building the exc_args tuple
* (callback_id, func_name, args) from thread-local storage.
*
* @return PyObject* tuple on success, NULL on failure
* @note On failure, tl_pending_callback is cleared
* @note Caller must Py_DECREF the returned tuple when done
*/
static PyObject *build_pending_callback_exc_args(void) {
PyObject *exc_args = PyTuple_New(3);
if (exc_args == NULL) {
tl_pending_callback = false;
Py_CLEAR(tl_pending_args);
return NULL;
}
PyObject *callback_id_obj = PyLong_FromUnsignedLongLong(tl_pending_callback_id);
PyObject *func_name_obj = PyUnicode_FromStringAndSize(
tl_pending_func_name, tl_pending_func_name_len);
if (callback_id_obj == NULL || func_name_obj == NULL) {
Py_XDECREF(callback_id_obj);
Py_XDECREF(func_name_obj);
Py_DECREF(exc_args);
tl_pending_callback = false;
Py_CLEAR(tl_pending_args);
return NULL;
}
PyTuple_SET_ITEM(exc_args, 0, callback_id_obj);
PyTuple_SET_ITEM(exc_args, 1, func_name_obj);
Py_INCREF(tl_pending_args); /* Tuple takes ownership */
PyTuple_SET_ITEM(exc_args, 2, tl_pending_args);
return exc_args;
}
/**
* Build the {suspended, ...} result term from a suspended state.
*
* Common helper for creating the suspension result after a callback
* is detected during Python execution.
*
* @param env NIF environment
* @param suspended Suspended state (resource will be released)
* @return ERL_NIF_TERM {suspended, CallbackId, StateRef, {FuncName, Args}}
* @note Clears tl_pending_callback
*/
static ERL_NIF_TERM build_suspended_result(ErlNifEnv *env, suspended_state_t *suspended) {
ERL_NIF_TERM state_ref = enif_make_resource(env, suspended);
enif_release_resource(suspended);
ERL_NIF_TERM callback_id_term = enif_make_uint64(env, tl_pending_callback_id);
ERL_NIF_TERM func_name_term;
unsigned char *fn_buf = enif_make_new_binary(env, tl_pending_func_name_len, &func_name_term);
memcpy(fn_buf, tl_pending_func_name, tl_pending_func_name_len);
ERL_NIF_TERM args_term = py_to_term(env, tl_pending_args);
tl_pending_callback = false;
Py_CLEAR(tl_pending_args);
return enif_make_tuple4(env,
ATOM_SUSPENDED,
callback_id_term,
state_ref,
enif_make_tuple2(env, func_name_term, args_term));
}
/* ============================================================================
* Context suspension helpers (for process-per-context architecture)
*
* These functions handle suspension/resume for py_context_t-based execution.
* Unlike worker suspension, context suspension doesn't use mutex or condvar -
* the context process handles callbacks inline via recursive receive.
* ============================================================================ */
/**
* Create a suspended context state for a py:call.
*
* Called when Python code in a context calls erlang.call() and suspension
* is required. Captures all state needed to resume after callback completes.
*
* @param env NIF environment
* @param ctx Context executing the Python code
* @param module_bin Original module binary
* @param func_bin Original function binary
* @param args_term Original args term
* @param kwargs_term Original kwargs term
* @return suspended_context_state_t* or NULL on error
*/
static suspended_context_state_t *create_suspended_context_state_for_call(
ErlNifEnv *env,
py_context_t *ctx,
ErlNifBinary *module_bin,
ErlNifBinary *func_bin,
ERL_NIF_TERM args_term,
ERL_NIF_TERM kwargs_term) {
/* Allocate the suspended context state resource */
suspended_context_state_t *state = enif_alloc_resource(
PY_CONTEXT_SUSPENDED_RESOURCE_TYPE, sizeof(suspended_context_state_t));
if (state == NULL) {
return NULL;
}
/* Initialize to zero */
memset(state, 0, sizeof(suspended_context_state_t));
state->ctx = ctx;
enif_keep_resource(ctx); /* Keep ctx alive while suspended state exists */
state->callback_id = tl_pending_callback_id;
state->request_type = PY_REQ_CALL;
/* Copy callback function name */
state->callback_func_name = enif_alloc(tl_pending_func_name_len + 1);
if (state->callback_func_name == NULL) {
enif_release_resource(state);
return NULL;
}
memcpy(state->callback_func_name, tl_pending_func_name, tl_pending_func_name_len);
state->callback_func_name[tl_pending_func_name_len] = '\0';
state->callback_func_len = tl_pending_func_name_len;
/* Store callback args reference */
Py_INCREF(tl_pending_args);
state->callback_args = tl_pending_args;
/* Create environment to hold copied terms */
state->orig_env = enif_alloc_env();
if (state->orig_env == NULL) {
Py_DECREF(state->callback_args);
enif_free(state->callback_func_name);
enif_release_resource(state);
return NULL;
}
/* Copy module binary */
if (!enif_alloc_binary(module_bin->size, &state->orig_module)) {
enif_free_env(state->orig_env);
Py_DECREF(state->callback_args);
enif_free(state->callback_func_name);
enif_release_resource(state);
return NULL;
}
memcpy(state->orig_module.data, module_bin->data, module_bin->size);
/* Copy function binary */
if (!enif_alloc_binary(func_bin->size, &state->orig_func)) {
enif_release_binary(&state->orig_module);
enif_free_env(state->orig_env);
Py_DECREF(state->callback_args);
enif_free(state->callback_func_name);
enif_release_resource(state);
return NULL;
}
memcpy(state->orig_func.data, func_bin->data, func_bin->size);
/* Copy args and kwargs to our environment */
state->orig_args = enif_make_copy(state->orig_env, args_term);
state->orig_kwargs = enif_make_copy(state->orig_env, kwargs_term);
atomic_fetch_add(&g_counters.suspended_created, 1);
return state;
}
/**
* Create a suspended context state for a py:eval.
*
* Called when Python code in a context calls erlang.call() during eval
* and suspension is required.
*
* @param env NIF environment
* @param ctx Context executing the Python code
* @param code_bin Original code binary
* @param locals_term Original locals term
* @return suspended_context_state_t* or NULL on error
*/
static suspended_context_state_t *create_suspended_context_state_for_eval(
ErlNifEnv *env,
py_context_t *ctx,
ErlNifBinary *code_bin,
ERL_NIF_TERM locals_term) {
(void)env;
/* Allocate the suspended context state resource */
suspended_context_state_t *state = enif_alloc_resource(
PY_CONTEXT_SUSPENDED_RESOURCE_TYPE, sizeof(suspended_context_state_t));
if (state == NULL) {
return NULL;
}
/* Initialize to zero */
memset(state, 0, sizeof(suspended_context_state_t));
state->ctx = ctx;
enif_keep_resource(ctx); /* Keep ctx alive while suspended state exists */
state->callback_id = tl_pending_callback_id;
state->request_type = PY_REQ_EVAL;
/* Copy callback function name */
state->callback_func_name = enif_alloc(tl_pending_func_name_len + 1);
if (state->callback_func_name == NULL) {
enif_release_resource(state);
return NULL;
}
memcpy(state->callback_func_name, tl_pending_func_name, tl_pending_func_name_len);
state->callback_func_name[tl_pending_func_name_len] = '\0';
state->callback_func_len = tl_pending_func_name_len;
/* Store callback args reference */
Py_INCREF(tl_pending_args);
state->callback_args = tl_pending_args;
/* Create environment to hold copied terms */
state->orig_env = enif_alloc_env();
if (state->orig_env == NULL) {
Py_DECREF(state->callback_args);
enif_free(state->callback_func_name);
enif_release_resource(state);
return NULL;
}
/* Copy code binary */
if (!enif_alloc_binary(code_bin->size, &state->orig_code)) {
enif_free_env(state->orig_env);
Py_DECREF(state->callback_args);
enif_free(state->callback_func_name);
enif_release_resource(state);
return NULL;
}
memcpy(state->orig_code.data, code_bin->data, code_bin->size);
/* Copy locals to our environment */
state->orig_locals = enif_make_copy(state->orig_env, locals_term);
atomic_fetch_add(&g_counters.suspended_created, 1);
return state;
}
/**
* Build the {suspended, ...} result term from a suspended context state.
*
* @param env NIF environment
* @param suspended Suspended context state (resource will be released)
* @return ERL_NIF_TERM {suspended, CallbackId, StateRef, {FuncName, Args}}
* @note Clears tl_pending_callback
*/
static ERL_NIF_TERM build_suspended_context_result(ErlNifEnv *env, suspended_context_state_t *suspended) {
ERL_NIF_TERM state_ref = enif_make_resource(env, suspended);
enif_release_resource(suspended);
ERL_NIF_TERM callback_id_term = enif_make_uint64(env, tl_pending_callback_id);
ERL_NIF_TERM func_name_term;
unsigned char *fn_buf = enif_make_new_binary(env, tl_pending_func_name_len, &func_name_term);
memcpy(fn_buf, tl_pending_func_name, tl_pending_func_name_len);
ERL_NIF_TERM args_term = py_to_term(env, tl_pending_args);
tl_pending_callback = false;
Py_CLEAR(tl_pending_args);
return enif_make_tuple4(env,
ATOM_SUSPENDED,
callback_id_term,
state_ref,
enif_make_tuple2(env, func_name_term, args_term));
}
/**
* Copy accumulated callback results from parent state to nested state.
*
* When a sequential callback occurs during replay, the nested suspended state
* needs to include all callback results from the parent PLUS the current result.
* This function copies parent's callback_results array and adds the parent's
* current result (result_data) to the end.
*
* @param nested The nested suspended state being created
* @param parent The parent suspended state (current tl_current_context_suspended)
* @return 0 on success, -1 on memory allocation failure
*/
static int copy_callback_results_to_nested(suspended_context_state_t *nested,
suspended_context_state_t *parent) {
if (parent == NULL) {
/* No parent state - nothing to copy */
return 0;
}
/*
* Calculate total results needed: parent's array + parent's current result.
*
* IMPORTANT: We check result_data != NULL instead of has_result because
* has_result may have been set to false when the result was consumed
* during replay, but the result data is still valid and needs to be
* copied to the nested state for subsequent replays.
*/
size_t total_results = parent->num_callback_results;
bool has_current_result = (parent->result_data != NULL && parent->result_len > 0);
if (has_current_result) {
total_results += 1;
}
if (total_results == 0) {
/* No results to copy */
return 0;
}
/* Allocate results array */
nested->callback_results = enif_alloc(total_results * sizeof(nested->callback_results[0]));
if (nested->callback_results == NULL) {
return -1;
}
nested->callback_results_capacity = total_results;
nested->num_callback_results = total_results;
nested->callback_result_index = 0;
/* Copy parent's accumulated results */
for (size_t i = 0; i < parent->num_callback_results; i++) {
size_t len = parent->callback_results[i].len;
nested->callback_results[i].data = enif_alloc(len);
if (nested->callback_results[i].data == NULL) {
/* Cleanup on failure */
for (size_t j = 0; j < i; j++) {
enif_free(nested->callback_results[j].data);
}
enif_free(nested->callback_results);
nested->callback_results = NULL;
nested->num_callback_results = 0;
nested->callback_results_capacity = 0;
return -1;
}
memcpy(nested->callback_results[i].data, parent->callback_results[i].data, len);
nested->callback_results[i].len = len;
}
/* Add parent's current result (result_data) as the last element */
if (has_current_result) {
size_t idx = parent->num_callback_results;
nested->callback_results[idx].data = enif_alloc(parent->result_len);
if (nested->callback_results[idx].data == NULL) {
/* Cleanup on failure */
for (size_t j = 0; j < idx; j++) {
enif_free(nested->callback_results[j].data);
}
enif_free(nested->callback_results);
nested->callback_results = NULL;
nested->num_callback_results = 0;
nested->callback_results_capacity = 0;
return -1;
}
memcpy(nested->callback_results[idx].data, parent->result_data, parent->result_len);
nested->callback_results[idx].len = parent->result_len;
}
return 0;
}
/**
* Helper to convert __etf__:base64 strings to Python objects.
* Used for encoding pids and references in callback responses.
* Returns a NEW reference on success, NULL with exception on error.
*/
static PyObject *decode_etf_string(const char *str, Py_ssize_t len) {
/* Check for __etf__: prefix (8 chars) */
const char *prefix = "__etf__:";
size_t prefix_len = 8;
if (len <= (Py_ssize_t)prefix_len || strncmp(str, prefix, prefix_len) != 0) {
return NULL; /* Not an ETF string */
}
/* Extract base64 portion */
const char *b64_data = str + prefix_len;
size_t b64_len = len - prefix_len;
/* Import base64 module and decode */
PyObject *base64_mod = PyImport_ImportModule("base64");
if (base64_mod == NULL) {
PyErr_Clear();
return NULL;
}
PyObject *b64decode = PyObject_GetAttrString(base64_mod, "b64decode");
Py_DECREF(base64_mod);
if (b64decode == NULL) {
PyErr_Clear();
return NULL;
}
PyObject *b64_str = PyUnicode_FromStringAndSize(b64_data, b64_len);
if (b64_str == NULL) {
Py_DECREF(b64decode);
PyErr_Clear();
return NULL;
}
PyObject *decoded = PyObject_CallFunctionObjArgs(b64decode, b64_str, NULL);
Py_DECREF(b64decode);
Py_DECREF(b64_str);
if (decoded == NULL) {
PyErr_Clear();
return NULL;
}
/* Get the binary data */
char *bin_data;
Py_ssize_t bin_len;
if (PyBytes_AsStringAndSize(decoded, &bin_data, &bin_len) < 0) {
Py_DECREF(decoded);
PyErr_Clear();
return NULL;
}
/* Create a temporary NIF environment to decode the term */
ErlNifEnv *tmp_env = enif_alloc_env();
if (tmp_env == NULL) {
Py_DECREF(decoded);
return NULL;
}
/* Decode the ETF binary to an Erlang term */
ERL_NIF_TERM term;
if (enif_binary_to_term(tmp_env, (unsigned char *)bin_data, bin_len, &term, 0) == 0) {
/* Decoding failed */
enif_free_env(tmp_env);
Py_DECREF(decoded);
return NULL;
}
Py_DECREF(decoded);
/* Convert the term to a Python object */
PyObject *result = term_to_py(tmp_env, term);
enif_free_env(tmp_env);
return result;
}
/**
* Recursively convert __etf__:base64 strings in a Python object.
* Handles nested tuples, lists, and dicts.
* Returns a NEW reference with ETF strings converted, or the original object
* with its refcount incremented if no conversion was needed.