flpit 0.4.2.dev10__tar.gz → 0.4.2.dev12__tar.gz
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.
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/PKG-INFO +27 -21
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/README.md +26 -20
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/pyproject.toml +1 -1
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/src/flpit/asyncio_bridge.py +306 -3
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/src/flpit/core/linq.py +16 -3
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/src/flpit/json/_msgspec.py +38 -2
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/src/flpit/json/_native.py +1 -1
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/src/flpit/task.py +218 -76
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/.gitignore +0 -0
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/LICENSE +0 -0
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/src/flp/__init__.py +0 -0
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/src/flpit/__init__.py +0 -0
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/src/flpit/channels.py +0 -0
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/src/flpit/concurrent.py +0 -0
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/src/flpit/core/__init__.py +0 -0
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/src/flpit/core/_grouping.py +0 -0
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/src/flpit/core/_index.py +0 -0
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/src/flpit/core/_join.py +0 -0
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/src/flpit/core/_lookup.py +0 -0
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/src/flpit/core/_zip.py +0 -0
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/src/flpit/core/async_linq.py +0 -0
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/src/flpit/core/comparers.py +0 -0
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/src/flpit/csv.py +0 -0
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/src/flpit/flp.py +0 -0
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/src/flpit/json/__init__.py +0 -0
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/src/flpit/json/_core.py +0 -0
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/src/flpit/py.typed +0 -0
- {flpit-0.4.2.dev10 → flpit-0.4.2.dev12}/src/flpit/threading.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: flpit
|
|
3
|
-
Version: 0.4.2.
|
|
3
|
+
Version: 0.4.2.dev12
|
|
4
4
|
Summary: Fluent LINQ for Python — flip your iterables
|
|
5
5
|
Project-URL: Homepage, https://github.com/riemar/flpit
|
|
6
6
|
Project-URL: Documentation, https://riemar.github.io/flpit/
|
|
@@ -153,7 +153,7 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
153
153
|
| │ ├── test_first.py | 8 |
|
|
154
154
|
| │ ├── test_first_or_default.py | 8 |
|
|
155
155
|
| │ ├── test_full_join.py | 11 |
|
|
156
|
-
| │ ├── test_group_by.py |
|
|
156
|
+
| │ ├── test_group_by.py | 6 |
|
|
157
157
|
| │ ├── test_group_join.py | 9 |
|
|
158
158
|
| │ ├── test_index.py | 8 |
|
|
159
159
|
| │ ├── test_intersect.py | 12 |
|
|
@@ -162,9 +162,9 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
162
162
|
| │ ├── test_last_or_default.py | 8 |
|
|
163
163
|
| │ ├── test_left_join.py | 10 |
|
|
164
164
|
| │ ├── test_max.py | 11 |
|
|
165
|
-
| │ ├── test_max_by.py |
|
|
165
|
+
| │ ├── test_max_by.py | 12 |
|
|
166
166
|
| │ ├── test_min.py | 11 |
|
|
167
|
-
| │ ├── test_min_by.py |
|
|
167
|
+
| │ ├── test_min_by.py | 12 |
|
|
168
168
|
| │ ├── test_of_type.py | 5 |
|
|
169
169
|
| │ ├── test_order_by.py | 18 |
|
|
170
170
|
| │ ├── test_prepend.py | 19 |
|
|
@@ -198,7 +198,7 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
198
198
|
| │ ├── test_rendezvous_channel.py | 104 |
|
|
199
199
|
| │ └── test_unbounded_channel.py | 338 |
|
|
200
200
|
| ├── concurrent/ | |
|
|
201
|
-
| │ ├── test_concurrent_bag.py |
|
|
201
|
+
| │ ├── test_concurrent_bag.py | 131 |
|
|
202
202
|
| │ ├── test_concurrent_dictionary.py | 56 |
|
|
203
203
|
| │ ├── test_concurrent_dictionary_generic.py | 1236 |
|
|
204
204
|
| │ ├── test_concurrent_queue.py | 130 |
|
|
@@ -214,7 +214,7 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
214
214
|
| │ ├── test_chunk.py | 22 |
|
|
215
215
|
| │ ├── test_concat.py | 64 |
|
|
216
216
|
| │ ├── test_contains.py | 108 |
|
|
217
|
-
| │ ├── test_count.py |
|
|
217
|
+
| │ ├── test_count.py | 64 |
|
|
218
218
|
| │ ├── test_default_if_empty.py | 37 |
|
|
219
219
|
| │ ├── test_distinct.py | 87 |
|
|
220
220
|
| │ ├── test_element_at.py | 43 |
|
|
@@ -222,7 +222,7 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
222
222
|
| │ ├── test_first.py | 29 |
|
|
223
223
|
| │ ├── test_first_or_default.py | 50 |
|
|
224
224
|
| │ ├── test_full_join.py | 37 |
|
|
225
|
-
| │ ├── test_generic_list.py |
|
|
225
|
+
| │ ├── test_generic_list.py | 87 |
|
|
226
226
|
| │ ├── test_group_by.py | 23 |
|
|
227
227
|
| │ ├── test_group_join.py | 53 |
|
|
228
228
|
| │ ├── test_index.py | 6 |
|
|
@@ -231,23 +231,23 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
231
231
|
| │ ├── test_last.py | 29 |
|
|
232
232
|
| │ ├── test_last_or_default.py | 45 |
|
|
233
233
|
| │ ├── test_left_join.py | 47 |
|
|
234
|
-
| │ ├── test_max.py |
|
|
235
|
-
| │ ├── test_min.py |
|
|
234
|
+
| │ ├── test_max.py | 1098 |
|
|
235
|
+
| │ ├── test_min.py | 966 |
|
|
236
236
|
| │ ├── test_of_type.py | 38 |
|
|
237
|
-
| │ ├── test_order_by.py |
|
|
238
|
-
| │ ├── test_order_descending_by.py |
|
|
237
|
+
| │ ├── test_order_by.py | 104 |
|
|
238
|
+
| │ ├── test_order_descending_by.py | 46 |
|
|
239
239
|
| │ ├── test_reverse.py | 35 |
|
|
240
|
-
| │ ├── test_select.py |
|
|
240
|
+
| │ ├── test_select.py | 143 |
|
|
241
241
|
| │ ├── test_select_many.py | 85 |
|
|
242
242
|
| │ ├── test_single.py | 34 |
|
|
243
243
|
| │ ├── test_single_or_default.py | 48 |
|
|
244
|
-
| │ ├── test_skip.py |
|
|
244
|
+
| │ ├── test_skip.py | 77 |
|
|
245
245
|
| │ ├── test_skip_last.py | 1221 |
|
|
246
|
-
| │ ├── test_sum.py |
|
|
247
|
-
| │ ├── test_take.py |
|
|
246
|
+
| │ ├── test_sum.py | 154 |
|
|
247
|
+
| │ ├── test_take.py | 73 |
|
|
248
248
|
| │ ├── test_take_last.py | 1221 |
|
|
249
|
-
| │ ├── test_then_by.py |
|
|
250
|
-
| │ ├── test_then_descending_by.py |
|
|
249
|
+
| │ ├── test_then_by.py | 38 |
|
|
250
|
+
| │ ├── test_then_descending_by.py | 32 |
|
|
251
251
|
| │ ├── test_to_dictionary.py | 32 |
|
|
252
252
|
| │ ├── test_to_list.py | 40 |
|
|
253
253
|
| │ ├── test_to_lookup.py | 26 |
|
|
@@ -255,20 +255,26 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
255
255
|
| │ ├── test_where.py | 76 |
|
|
256
256
|
| │ └── test_zip.py | 101 |
|
|
257
257
|
| ├── task/ | |
|
|
258
|
+
| │ ├── test_aggregate_exception.py | 1 |
|
|
258
259
|
| │ ├── test_cancellation.py | 69 |
|
|
259
|
-
| │ ├──
|
|
260
|
+
| │ ├── test_method_coverage.py | 30 |
|
|
261
|
+
| │ ├── test_method_coverage_when_all.py | 13 |
|
|
262
|
+
| │ ├── test_operation_canceled_exception.py | 0 |
|
|
263
|
+
| │ ├── test_task_canceled_exception.py | 1 |
|
|
264
|
+
| │ ├── test_task_completion_source.py | 25 |
|
|
265
|
+
| │ ├── test_task_completion_source_tresult.py | 5 |
|
|
260
266
|
| │ ├── test_task_continue_with.py | 15 |
|
|
261
267
|
| │ ├── test_task_continue_with_func_and_action.py | 16 |
|
|
262
268
|
| │ ├── test_task_continue_with_func_and_action_args.py | 20 |
|
|
263
269
|
| │ ├── test_task_factory.py | 3 |
|
|
264
|
-
| │ ├── test_task_rt.py |
|
|
265
|
-
| │ ├── test_task_rt_core.py |
|
|
270
|
+
| │ ├── test_task_rt.py | 7 |
|
|
271
|
+
| │ ├── test_task_rt_core.py | 32 |
|
|
266
272
|
| │ └── test_task_wait_all_any.py | 62 |
|
|
267
273
|
| └── threading/ | |
|
|
268
274
|
| ├── test_semaphore_slim.py | 39 |
|
|
269
275
|
| ├── test_semaphore_slim_cancellation.py | 4 |
|
|
270
276
|
| └── test_thread_local.py | 15 |
|
|
271
277
|
--------------------------------------------------------------------------------
|
|
272
|
-
| GRAND TOTALS |
|
|
278
|
+
| GRAND TOTALS | 10848 |
|
|
273
279
|
================================================================================
|
|
274
280
|
```
|
|
@@ -122,7 +122,7 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
122
122
|
| │ ├── test_first.py | 8 |
|
|
123
123
|
| │ ├── test_first_or_default.py | 8 |
|
|
124
124
|
| │ ├── test_full_join.py | 11 |
|
|
125
|
-
| │ ├── test_group_by.py |
|
|
125
|
+
| │ ├── test_group_by.py | 6 |
|
|
126
126
|
| │ ├── test_group_join.py | 9 |
|
|
127
127
|
| │ ├── test_index.py | 8 |
|
|
128
128
|
| │ ├── test_intersect.py | 12 |
|
|
@@ -131,9 +131,9 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
131
131
|
| │ ├── test_last_or_default.py | 8 |
|
|
132
132
|
| │ ├── test_left_join.py | 10 |
|
|
133
133
|
| │ ├── test_max.py | 11 |
|
|
134
|
-
| │ ├── test_max_by.py |
|
|
134
|
+
| │ ├── test_max_by.py | 12 |
|
|
135
135
|
| │ ├── test_min.py | 11 |
|
|
136
|
-
| │ ├── test_min_by.py |
|
|
136
|
+
| │ ├── test_min_by.py | 12 |
|
|
137
137
|
| │ ├── test_of_type.py | 5 |
|
|
138
138
|
| │ ├── test_order_by.py | 18 |
|
|
139
139
|
| │ ├── test_prepend.py | 19 |
|
|
@@ -167,7 +167,7 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
167
167
|
| │ ├── test_rendezvous_channel.py | 104 |
|
|
168
168
|
| │ └── test_unbounded_channel.py | 338 |
|
|
169
169
|
| ├── concurrent/ | |
|
|
170
|
-
| │ ├── test_concurrent_bag.py |
|
|
170
|
+
| │ ├── test_concurrent_bag.py | 131 |
|
|
171
171
|
| │ ├── test_concurrent_dictionary.py | 56 |
|
|
172
172
|
| │ ├── test_concurrent_dictionary_generic.py | 1236 |
|
|
173
173
|
| │ ├── test_concurrent_queue.py | 130 |
|
|
@@ -183,7 +183,7 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
183
183
|
| │ ├── test_chunk.py | 22 |
|
|
184
184
|
| │ ├── test_concat.py | 64 |
|
|
185
185
|
| │ ├── test_contains.py | 108 |
|
|
186
|
-
| │ ├── test_count.py |
|
|
186
|
+
| │ ├── test_count.py | 64 |
|
|
187
187
|
| │ ├── test_default_if_empty.py | 37 |
|
|
188
188
|
| │ ├── test_distinct.py | 87 |
|
|
189
189
|
| │ ├── test_element_at.py | 43 |
|
|
@@ -191,7 +191,7 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
191
191
|
| │ ├── test_first.py | 29 |
|
|
192
192
|
| │ ├── test_first_or_default.py | 50 |
|
|
193
193
|
| │ ├── test_full_join.py | 37 |
|
|
194
|
-
| │ ├── test_generic_list.py |
|
|
194
|
+
| │ ├── test_generic_list.py | 87 |
|
|
195
195
|
| │ ├── test_group_by.py | 23 |
|
|
196
196
|
| │ ├── test_group_join.py | 53 |
|
|
197
197
|
| │ ├── test_index.py | 6 |
|
|
@@ -200,23 +200,23 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
200
200
|
| │ ├── test_last.py | 29 |
|
|
201
201
|
| │ ├── test_last_or_default.py | 45 |
|
|
202
202
|
| │ ├── test_left_join.py | 47 |
|
|
203
|
-
| │ ├── test_max.py |
|
|
204
|
-
| │ ├── test_min.py |
|
|
203
|
+
| │ ├── test_max.py | 1098 |
|
|
204
|
+
| │ ├── test_min.py | 966 |
|
|
205
205
|
| │ ├── test_of_type.py | 38 |
|
|
206
|
-
| │ ├── test_order_by.py |
|
|
207
|
-
| │ ├── test_order_descending_by.py |
|
|
206
|
+
| │ ├── test_order_by.py | 104 |
|
|
207
|
+
| │ ├── test_order_descending_by.py | 46 |
|
|
208
208
|
| │ ├── test_reverse.py | 35 |
|
|
209
|
-
| │ ├── test_select.py |
|
|
209
|
+
| │ ├── test_select.py | 143 |
|
|
210
210
|
| │ ├── test_select_many.py | 85 |
|
|
211
211
|
| │ ├── test_single.py | 34 |
|
|
212
212
|
| │ ├── test_single_or_default.py | 48 |
|
|
213
|
-
| │ ├── test_skip.py |
|
|
213
|
+
| │ ├── test_skip.py | 77 |
|
|
214
214
|
| │ ├── test_skip_last.py | 1221 |
|
|
215
|
-
| │ ├── test_sum.py |
|
|
216
|
-
| │ ├── test_take.py |
|
|
215
|
+
| │ ├── test_sum.py | 154 |
|
|
216
|
+
| │ ├── test_take.py | 73 |
|
|
217
217
|
| │ ├── test_take_last.py | 1221 |
|
|
218
|
-
| │ ├── test_then_by.py |
|
|
219
|
-
| │ ├── test_then_descending_by.py |
|
|
218
|
+
| │ ├── test_then_by.py | 38 |
|
|
219
|
+
| │ ├── test_then_descending_by.py | 32 |
|
|
220
220
|
| │ ├── test_to_dictionary.py | 32 |
|
|
221
221
|
| │ ├── test_to_list.py | 40 |
|
|
222
222
|
| │ ├── test_to_lookup.py | 26 |
|
|
@@ -224,20 +224,26 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
224
224
|
| │ ├── test_where.py | 76 |
|
|
225
225
|
| │ └── test_zip.py | 101 |
|
|
226
226
|
| ├── task/ | |
|
|
227
|
+
| │ ├── test_aggregate_exception.py | 1 |
|
|
227
228
|
| │ ├── test_cancellation.py | 69 |
|
|
228
|
-
| │ ├──
|
|
229
|
+
| │ ├── test_method_coverage.py | 30 |
|
|
230
|
+
| │ ├── test_method_coverage_when_all.py | 13 |
|
|
231
|
+
| │ ├── test_operation_canceled_exception.py | 0 |
|
|
232
|
+
| │ ├── test_task_canceled_exception.py | 1 |
|
|
233
|
+
| │ ├── test_task_completion_source.py | 25 |
|
|
234
|
+
| │ ├── test_task_completion_source_tresult.py | 5 |
|
|
229
235
|
| │ ├── test_task_continue_with.py | 15 |
|
|
230
236
|
| │ ├── test_task_continue_with_func_and_action.py | 16 |
|
|
231
237
|
| │ ├── test_task_continue_with_func_and_action_args.py | 20 |
|
|
232
238
|
| │ ├── test_task_factory.py | 3 |
|
|
233
|
-
| │ ├── test_task_rt.py |
|
|
234
|
-
| │ ├── test_task_rt_core.py |
|
|
239
|
+
| │ ├── test_task_rt.py | 7 |
|
|
240
|
+
| │ ├── test_task_rt_core.py | 32 |
|
|
235
241
|
| │ └── test_task_wait_all_any.py | 62 |
|
|
236
242
|
| └── threading/ | |
|
|
237
243
|
| ├── test_semaphore_slim.py | 39 |
|
|
238
244
|
| ├── test_semaphore_slim_cancellation.py | 4 |
|
|
239
245
|
| └── test_thread_local.py | 15 |
|
|
240
246
|
--------------------------------------------------------------------------------
|
|
241
|
-
| GRAND TOTALS |
|
|
247
|
+
| GRAND TOTALS | 10848 |
|
|
242
248
|
================================================================================
|
|
243
249
|
```
|
|
@@ -23,7 +23,10 @@ calling more asyncio code stays on its loop), otherwise to the least busy of the
|
|
|
23
23
|
("power of two choices"). Loops are created on demand, up to ``configure(loops=...)``.
|
|
24
24
|
|
|
25
25
|
Loop-bound objects that should outlive one call (an ``httpx.AsyncClient``, an asyncpg pool)
|
|
26
|
-
|
|
26
|
+
are kept one per loop and closed with the loop. Register them with ``provide()`` and take them as
|
|
27
|
+
a ``Loop[T]`` parameter of an ``@asyncio_task`` function, or hold a ``PerLoop[T]`` in an object that
|
|
28
|
+
lives longer than a call (a singleton) and read ``.current`` on the loop. ``warm=True`` creates the
|
|
29
|
+
value on every pool loop before the loop takes work.
|
|
27
30
|
|
|
28
31
|
Strand loops drive asyncio's ``BaseEventLoop._run_once`` and replace two private hooks
|
|
29
32
|
(``_write_to_self``, the selector's wait); the thread backend needs none of that and is the
|
|
@@ -35,23 +38,25 @@ import asyncio
|
|
|
35
38
|
import atexit
|
|
36
39
|
import concurrent.futures
|
|
37
40
|
import contextvars
|
|
41
|
+
import inspect
|
|
38
42
|
import os
|
|
39
43
|
import random
|
|
40
44
|
import select
|
|
41
45
|
import selectors
|
|
42
46
|
import sys
|
|
43
47
|
import threading
|
|
48
|
+
import typing
|
|
44
49
|
import weakref
|
|
45
50
|
from asyncio import events
|
|
46
51
|
from collections import deque
|
|
47
52
|
from collections.abc import AsyncGenerator, Awaitable, Callable, Coroutine
|
|
48
|
-
from typing import Any, Generic, TypeVar, cast, override
|
|
53
|
+
from typing import Annotated, Any, Final, Generic, TypeAlias, TypeVar, cast, get_args, get_origin, override
|
|
49
54
|
|
|
50
55
|
from . import task as _task
|
|
51
56
|
from .task import CancellationToken, OperationCanceledError, Task, TaskCompletionSource
|
|
52
57
|
from .threading import ThreadPool
|
|
53
58
|
|
|
54
|
-
__all__ = ["LoopLocal", "configure", "run_asyncio", "shutdown"]
|
|
59
|
+
__all__ = ["Loop", "LoopLocal", "LoopStartError", "PerLoop", "configure", "injected", "provide", "run_asyncio", "shutdown"]
|
|
55
60
|
|
|
56
61
|
T = TypeVar("T")
|
|
57
62
|
|
|
@@ -380,6 +385,8 @@ class _LoopPool:
|
|
|
380
385
|
loop = self._new_loop()
|
|
381
386
|
loops.append(loop)
|
|
382
387
|
self.load[loop] = 1
|
|
388
|
+
# Queued before the caller queues its work, so the warm-up gate exists first.
|
|
389
|
+
loop.call_soon_threadsafe(_begin_warm, loop, self, None)
|
|
383
390
|
return loop
|
|
384
391
|
|
|
385
392
|
def release(self, loop: asyncio.AbstractEventLoop) -> None:
|
|
@@ -387,6 +394,25 @@ class _LoopPool:
|
|
|
387
394
|
if loop in self.load:
|
|
388
395
|
self.load[loop] -= 1
|
|
389
396
|
|
|
397
|
+
def retire(self, loop: asyncio.AbstractEventLoop) -> None:
|
|
398
|
+
"""Take ``loop`` out of service (its start failed) and close it once its work has ended."""
|
|
399
|
+
with self.lock:
|
|
400
|
+
if loop not in self.load:
|
|
401
|
+
return
|
|
402
|
+
self.loops.remove(loop)
|
|
403
|
+
del self.load[loop]
|
|
404
|
+
runner = next((r for r in self.threads if r.loop is loop), None)
|
|
405
|
+
if runner is not None:
|
|
406
|
+
self.threads.remove(runner)
|
|
407
|
+
|
|
408
|
+
def close(_state: Any) -> None:
|
|
409
|
+
_close_loop(loop, 1.0)
|
|
410
|
+
if runner is not None:
|
|
411
|
+
runner.stop()
|
|
412
|
+
runner.loop.close()
|
|
413
|
+
|
|
414
|
+
ThreadPool.queue(close, None)
|
|
415
|
+
|
|
390
416
|
def _new_loop(self) -> asyncio.AbstractEventLoop:
|
|
391
417
|
if self.backend == "strands":
|
|
392
418
|
if self.reactor is None:
|
|
@@ -576,6 +602,13 @@ def _start(loop: asyncio.AbstractEventLoop, pool: _LoopPool | None, coroutine: C
|
|
|
576
602
|
run = _Run(loop, pool, source, token)
|
|
577
603
|
if token is not None:
|
|
578
604
|
run.registration = token.register(run.on_cancel)
|
|
605
|
+
gate: asyncio.Task[None] | None = getattr(loop, _GATE, None)
|
|
606
|
+
if gate is not None:
|
|
607
|
+
if gate.done() and not gate.cancelled() and gate.exception() is None:
|
|
608
|
+
if getattr(loop, _GATE, None) is gate:
|
|
609
|
+
setattr(loop, _GATE, None)
|
|
610
|
+
else:
|
|
611
|
+
coroutine = _after_gate(gate, coroutine)
|
|
579
612
|
task = loop.create_task(coroutine, context=context)
|
|
580
613
|
run.task = task
|
|
581
614
|
task.add_done_callback(run.finish)
|
|
@@ -679,6 +712,276 @@ async def _dispose_loop_locals(loop: asyncio.AbstractEventLoop) -> None:
|
|
|
679
712
|
_task._LOG.exception("closing a LoopLocal value failed")
|
|
680
713
|
|
|
681
714
|
|
|
715
|
+
# ---------------------------------------------------------------------------
|
|
716
|
+
# PerLoop, provide() and Loop[T] parameters
|
|
717
|
+
# ---------------------------------------------------------------------------
|
|
718
|
+
|
|
719
|
+
class LoopStartError(RuntimeError):
|
|
720
|
+
"""A ``warm=True`` value could not be created on a new loop; the loop was taken out of service."""
|
|
721
|
+
|
|
722
|
+
|
|
723
|
+
#: Attribute of a pool loop holding the asyncio task that warms it (None once warm).
|
|
724
|
+
_GATE: Final = "_flpit_warm_gate"
|
|
725
|
+
_warm_per_loops: weakref.WeakSet[PerLoop[Any]] = weakref.WeakSet()
|
|
726
|
+
_warm_lock = threading.Lock()
|
|
727
|
+
|
|
728
|
+
|
|
729
|
+
def _begin_warm(loop: asyncio.AbstractEventLoop, pool: _LoopPool, per_loops: list[PerLoop[Any]] | None) -> None:
|
|
730
|
+
"""On ``loop``: start creating the warm values; work started meanwhile waits for them."""
|
|
731
|
+
if per_loops is None:
|
|
732
|
+
with _warm_lock:
|
|
733
|
+
per_loops = list(_warm_per_loops)
|
|
734
|
+
if not per_loops:
|
|
735
|
+
return
|
|
736
|
+
previous: asyncio.Task[None] | None = getattr(loop, _GATE, None)
|
|
737
|
+
setattr(loop, _GATE, loop.create_task(_warm(loop, pool, per_loops, previous)))
|
|
738
|
+
|
|
739
|
+
|
|
740
|
+
async def _warm(loop: asyncio.AbstractEventLoop, pool: _LoopPool, per_loops: list[PerLoop[Any]],
|
|
741
|
+
previous: asyncio.Task[None] | None) -> None:
|
|
742
|
+
if previous is not None:
|
|
743
|
+
await previous
|
|
744
|
+
for per_loop in per_loops:
|
|
745
|
+
if per_loop._closed:
|
|
746
|
+
continue
|
|
747
|
+
try:
|
|
748
|
+
await per_loop.get()
|
|
749
|
+
except Exception as error:
|
|
750
|
+
pool.retire(loop)
|
|
751
|
+
raise LoopStartError(f"creating the per-loop value {per_loop!r} on a new asyncio loop failed") from error
|
|
752
|
+
|
|
753
|
+
|
|
754
|
+
async def _after_gate(gate: asyncio.Task[None], coroutine: Coroutine[Any, Any, T]) -> T:
|
|
755
|
+
try:
|
|
756
|
+
await asyncio.shield(gate)
|
|
757
|
+
except BaseException:
|
|
758
|
+
coroutine.close()
|
|
759
|
+
raise
|
|
760
|
+
return await coroutine
|
|
761
|
+
|
|
762
|
+
|
|
763
|
+
class PerLoop(LoopLocal[T]):
|
|
764
|
+
"""One ``T`` per asyncio event loop, for objects that live longer than a call.
|
|
765
|
+
|
|
766
|
+
Hold a ``PerLoop`` where the object itself must not be held: a singleton built once cannot
|
|
767
|
+
keep a loop-bound client (it would use the client of the loop it was built on), but it can
|
|
768
|
+
keep the ``PerLoop`` and read ``current`` in each call:
|
|
769
|
+
|
|
770
|
+
```python
|
|
771
|
+
clients = PerLoop(lambda: httpx.AsyncClient(timeout=10), warm=True)
|
|
772
|
+
|
|
773
|
+
class GitHubApi:
|
|
774
|
+
def __init__(self, clients: PerLoop[httpx.AsyncClient]) -> None:
|
|
775
|
+
self._clients = clients
|
|
776
|
+
|
|
777
|
+
@asyncio_task
|
|
778
|
+
async def repo(self, name: str) -> dict:
|
|
779
|
+
return (await self._clients.current.get(f"/repos/{name}")).json()
|
|
780
|
+
```
|
|
781
|
+
|
|
782
|
+
``factory`` may be a plain function or an ``async def``. With ``warm=True`` the value is created
|
|
783
|
+
on each pool loop when the loop starts, before it takes work, so ``current`` never creates one
|
|
784
|
+
during a call; a factory that fails there fails the work waiting for that loop with
|
|
785
|
+
``LoopStartError`` and the loop is replaced. ``close()`` closes the values on every loop.
|
|
786
|
+
"""
|
|
787
|
+
|
|
788
|
+
def __init__(self, factory: Callable[[], T | Awaitable[T]], *, warm: bool = False) -> None:
|
|
789
|
+
super().__init__(factory)
|
|
790
|
+
self.warm = warm
|
|
791
|
+
self._closed = False
|
|
792
|
+
if warm:
|
|
793
|
+
with _warm_lock:
|
|
794
|
+
_warm_per_loops.add(self)
|
|
795
|
+
pool = _pool
|
|
796
|
+
if pool is not None:
|
|
797
|
+
with pool.lock:
|
|
798
|
+
loops = list(pool.loops)
|
|
799
|
+
only: list[PerLoop[Any]] = [self]
|
|
800
|
+
for loop in loops:
|
|
801
|
+
try:
|
|
802
|
+
loop.call_soon_threadsafe(_begin_warm, loop, pool, only)
|
|
803
|
+
except RuntimeError:
|
|
804
|
+
pass # closed meanwhile
|
|
805
|
+
|
|
806
|
+
@property
|
|
807
|
+
def current(self) -> T:
|
|
808
|
+
"""The value of the loop running on this thread; created now if it does not exist yet.
|
|
809
|
+
|
|
810
|
+
Raises ``RuntimeError`` outside asyncio code. An async factory cannot run here: with
|
|
811
|
+
``warm=True`` the value exists on every pool loop; elsewhere use ``await per_loop.get()``.
|
|
812
|
+
"""
|
|
813
|
+
if self._closed:
|
|
814
|
+
raise RuntimeError(f"{self!r} is closed")
|
|
815
|
+
loop = self._loop()
|
|
816
|
+
values = self._values
|
|
817
|
+
if loop in values:
|
|
818
|
+
return values[loop]
|
|
819
|
+
created = self._factory()
|
|
820
|
+
if asyncio.iscoroutine(created) or isinstance(created, asyncio.Future):
|
|
821
|
+
if asyncio.iscoroutine(created):
|
|
822
|
+
created.close()
|
|
823
|
+
raise RuntimeError(f"{self!r} has an async factory and no value on this loop yet: "
|
|
824
|
+
"create it with warm=True, or use 'await per_loop.get()'")
|
|
825
|
+
value = cast(T, created)
|
|
826
|
+
values[loop] = value
|
|
827
|
+
return value
|
|
828
|
+
|
|
829
|
+
@override
|
|
830
|
+
async def get(self) -> T:
|
|
831
|
+
if self._closed:
|
|
832
|
+
raise RuntimeError(f"{self!r} is closed")
|
|
833
|
+
return await super().get()
|
|
834
|
+
|
|
835
|
+
def close(self, timeout: float = 5.0) -> None:
|
|
836
|
+
"""Close the value of every loop (``aclose()`` or ``close()``, on its loop) and stop creating new ones."""
|
|
837
|
+
self._closed = True
|
|
838
|
+
with _warm_lock:
|
|
839
|
+
_warm_per_loops.discard(self)
|
|
840
|
+
with _providers_lock:
|
|
841
|
+
for service_type, registered in list(_providers.items()):
|
|
842
|
+
if registered is self:
|
|
843
|
+
del _providers[service_type]
|
|
844
|
+
running = events._get_running_loop()
|
|
845
|
+
pending: list[concurrent.futures.Future[None]] = []
|
|
846
|
+
for loop, value in list(self._values.items()):
|
|
847
|
+
self._values.pop(loop, None)
|
|
848
|
+
if loop.is_closed():
|
|
849
|
+
continue
|
|
850
|
+
if loop is running:
|
|
851
|
+
loop.create_task(_close_value(value)) # cannot wait for our own loop
|
|
852
|
+
continue
|
|
853
|
+
try:
|
|
854
|
+
pending.append(asyncio.run_coroutine_threadsafe(_close_value(value), loop))
|
|
855
|
+
except RuntimeError:
|
|
856
|
+
pass # the loop closed meanwhile
|
|
857
|
+
if pending:
|
|
858
|
+
done, _ = concurrent.futures.wait(pending, timeout=timeout)
|
|
859
|
+
for future in done:
|
|
860
|
+
if future.exception() is not None:
|
|
861
|
+
_task._LOG.error("closing a PerLoop value failed", exc_info=future.exception())
|
|
862
|
+
|
|
863
|
+
async def aclose(self) -> None:
|
|
864
|
+
"""``close()`` without blocking the awaiting coroutine's thread."""
|
|
865
|
+
await Task.run(self.close)
|
|
866
|
+
|
|
867
|
+
@override
|
|
868
|
+
def __repr__(self) -> str:
|
|
869
|
+
name = getattr(self._factory, "__qualname__", None) or repr(self._factory)
|
|
870
|
+
return f"PerLoop({name})"
|
|
871
|
+
|
|
872
|
+
|
|
873
|
+
class _LoopParameter:
|
|
874
|
+
__slots__ = ()
|
|
875
|
+
|
|
876
|
+
@override
|
|
877
|
+
def __repr__(self) -> str:
|
|
878
|
+
return "Loop"
|
|
879
|
+
|
|
880
|
+
|
|
881
|
+
_LOOP_PARAMETER: Final = _LoopParameter()
|
|
882
|
+
|
|
883
|
+
Loop: TypeAlias = Annotated[T, _LOOP_PARAMETER]
|
|
884
|
+
"""A parameter of an ``@asyncio_task`` function that receives the ``provide()``-d ``T`` of the loop the call runs on.
|
|
885
|
+
|
|
886
|
+
```python
|
|
887
|
+
asyncio_bridge.provide(httpx.AsyncClient, lambda: httpx.AsyncClient(timeout=10), warm=True)
|
|
888
|
+
|
|
889
|
+
@asyncio_task
|
|
890
|
+
async def fetch(url: str, client: Loop[httpx.AsyncClient] = injected) -> dict:
|
|
891
|
+
return (await client.get(url)).json()
|
|
892
|
+
|
|
893
|
+
data = await fetch("https://...")
|
|
894
|
+
```
|
|
895
|
+
|
|
896
|
+
The caller does not pass it (``= injected`` tells type checkers so); a value the caller does pass wins.
|
|
897
|
+
"""
|
|
898
|
+
|
|
899
|
+
|
|
900
|
+
class _Injected:
|
|
901
|
+
__slots__ = ()
|
|
902
|
+
|
|
903
|
+
@override
|
|
904
|
+
def __repr__(self) -> str:
|
|
905
|
+
return "injected"
|
|
906
|
+
|
|
907
|
+
|
|
908
|
+
injected: Final[Any] = _Injected()
|
|
909
|
+
"""Default for a ``Loop[T]`` parameter: the bridge fills it in, the caller does not pass it."""
|
|
910
|
+
|
|
911
|
+
_providers: dict[Any, PerLoop[Any]] = {}
|
|
912
|
+
_owned_providers: weakref.WeakSet[PerLoop[Any]] = weakref.WeakSet()
|
|
913
|
+
_providers_lock = threading.Lock()
|
|
914
|
+
|
|
915
|
+
|
|
916
|
+
def provide(service_type: type[T], source: Callable[[], T | Awaitable[T]] | PerLoop[T], *,
|
|
917
|
+
warm: bool = False) -> PerLoop[T]:
|
|
918
|
+
"""Make ``Loop[service_type]`` parameters of ``@asyncio_task`` functions receive one value per loop.
|
|
919
|
+
|
|
920
|
+
``source`` is a factory (plain or ``async def``; ``warm`` as for ``PerLoop``) or an existing
|
|
921
|
+
``PerLoop``, which stays the caller's to close. Providing a type again replaces the provider;
|
|
922
|
+
values created by a replaced factory are closed. Returns the ``PerLoop`` in use.
|
|
923
|
+
"""
|
|
924
|
+
if isinstance(source, PerLoop):
|
|
925
|
+
per_loop = cast(PerLoop[T], source)
|
|
926
|
+
else:
|
|
927
|
+
per_loop = PerLoop(source, warm=warm)
|
|
928
|
+
_owned_providers.add(per_loop)
|
|
929
|
+
with _providers_lock:
|
|
930
|
+
replaced = _providers.get(service_type)
|
|
931
|
+
_providers[service_type] = per_loop
|
|
932
|
+
if replaced is not None and replaced is not per_loop and replaced in _owned_providers:
|
|
933
|
+
ThreadPool.queue(lambda: replaced.close())
|
|
934
|
+
return per_loop
|
|
935
|
+
|
|
936
|
+
|
|
937
|
+
def _provider(service_type: Any) -> PerLoop[Any]:
|
|
938
|
+
per_loop = _providers.get(service_type)
|
|
939
|
+
if per_loop is None:
|
|
940
|
+
name = getattr(service_type, "__qualname__", repr(service_type))
|
|
941
|
+
raise LookupError(f"no per-loop value is provided for {name}: "
|
|
942
|
+
f"call asyncio_bridge.provide({name}, factory) at startup")
|
|
943
|
+
return per_loop
|
|
944
|
+
|
|
945
|
+
|
|
946
|
+
def _loop_parameters(function: Callable[..., Any]) -> tuple[inspect.Signature, tuple[tuple[str, Any], ...]] | None:
|
|
947
|
+
"""The signature and the ``Loop[T]`` parameters of ``function``, or None if it has none."""
|
|
948
|
+
try:
|
|
949
|
+
hints = typing.get_type_hints(function, include_extras=True)
|
|
950
|
+
except Exception as error:
|
|
951
|
+
raw = getattr(function, "__annotations__", {})
|
|
952
|
+
if not any("Loop[" in str(annotation) for annotation in raw.values()):
|
|
953
|
+
return None
|
|
954
|
+
raise TypeError(f"cannot read the annotations of {function.__qualname__} "
|
|
955
|
+
f"to find its Loop[...] parameters: {error}") from error
|
|
956
|
+
found = tuple(
|
|
957
|
+
(name, get_args(hint)[0]) for name, hint in hints.items()
|
|
958
|
+
if get_origin(hint) is Annotated and any(m is _LOOP_PARAMETER for m in hint.__metadata__)
|
|
959
|
+
)
|
|
960
|
+
return (inspect.signature(function), found) if found else None
|
|
961
|
+
|
|
962
|
+
|
|
963
|
+
def _call_asyncio_task(function: Callable[..., Awaitable[T]], args: tuple[Any, ...], kwargs: dict[str, Any],
|
|
964
|
+
token: CancellationToken | None, cache: list[Any]) -> Task[T]:
|
|
965
|
+
"""One call of an ``@asyncio_task`` function: fill its ``Loop[T]`` parameters on the loop, run it."""
|
|
966
|
+
if not cache:
|
|
967
|
+
cache.append(_loop_parameters(function))
|
|
968
|
+
plan = cache[0]
|
|
969
|
+
if plan is None:
|
|
970
|
+
return run_asyncio(function(*args, **kwargs), token=token)
|
|
971
|
+
signature, parameters = plan
|
|
972
|
+
bound = signature.bind_partial(*args, **kwargs) # wrong arguments fail here, in the caller
|
|
973
|
+
missing = [(name, service_type) for name, service_type in parameters
|
|
974
|
+
if bound.arguments.get(name, injected) is injected]
|
|
975
|
+
return run_asyncio(_with_loop_values(function, bound, missing), token=token)
|
|
976
|
+
|
|
977
|
+
|
|
978
|
+
async def _with_loop_values(function: Callable[..., Awaitable[T]], bound: inspect.BoundArguments,
|
|
979
|
+
missing: list[tuple[str, Any]]) -> T:
|
|
980
|
+
for name, service_type in missing:
|
|
981
|
+
bound.arguments[name] = await _provider(service_type).get()
|
|
982
|
+
return await function(*bound.args, **bound.kwargs)
|
|
983
|
+
|
|
984
|
+
|
|
682
985
|
# ---------------------------------------------------------------------------
|
|
683
986
|
# Lifecycle hooks
|
|
684
987
|
# ---------------------------------------------------------------------------
|