3
3
import logging
4
4
import multiprocessing
5
5
import os
6
+ import platform
6
7
import sys
7
8
import tempfile
8
9
import traceback
37
38
_TEST_DB_FILE : Optional [Path ] = None
38
39
_TEST_LOCK : Optional [multiprocessing .Lock ] = None
39
40
_PROCESS_EXECUTOR : Optional [concurrent .futures .ProcessPoolExecutor ] = None
41
+ _MP_CONTEXT = None
40
42
41
43
42
44
class DependencyInjectionError (RuntimeError ):
@@ -63,6 +65,24 @@ def lifespan_config() -> AppConfig:
63
65
return cast (AppConfig , _CONFIG )
64
66
65
67
68
+ def mp_context_enter (** __ ):
69
+ global _MP_CONTEXT
70
+ platform_system = platform .system ()
71
+ if platform_system == "Darwin" :
72
+ ctx = "spawn"
73
+ elif platform_system == "Linux" :
74
+ ctx = "fork"
75
+ else :
76
+ raise ValueError (f"Unsupported OS: { platform_system } " )
77
+ _MP_CONTEXT = multiprocessing .get_context (ctx )
78
+
79
+
80
+ def lifespan_mp_context ():
81
+ if _MP_CONTEXT is None :
82
+ raise DependencyInjectionError ("multiprocessing context" )
83
+ return _MP_CONTEXT
84
+
85
+
66
86
async def neo4j_driver_enter (** __ ):
67
87
global _NEO4J_DRIVER
68
88
_NEO4J_DRIVER = lifespan_config ().to_neo4j_driver ()
@@ -164,7 +184,7 @@ def process_executor_enter(**_):
164
184
worker_ids = [f"worker-{ process_id } -{ i } " for i in range (n_workers )]
165
185
_PROCESS_EXECUTOR = concurrent .futures .ProcessPoolExecutor ( # pylint: disable=unnecessary-dunder-call
166
186
max_workers = n_workers ,
167
- mp_context = multiprocessing . get_context ( "spawn" ),
187
+ mp_context = lifespan_mp_context ( ),
168
188
).__enter__ ()
169
189
kwargs = dict ()
170
190
worker_cls = config .to_worker_cls ()
@@ -261,6 +281,7 @@ def lifespan_event_publisher() -> EventPublisher:
261
281
("neo4j driver creation" , neo4j_driver_enter , neo4j_driver_exit ),
262
282
("neo4j project registry creation" , create_project_registry_db_enter , None ),
263
283
("ES client creation" , es_client_enter , es_client_exit ),
284
+ (None , mp_context_enter , None ),
264
285
(None , test_process_manager_enter , test_process_manager_exit ),
265
286
(None , test_db_path_enter , test_db_path_exit ),
266
287
(None , _test_lock_enter , None ),
0 commit comments