threaded-order 1.3.1__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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,147 @@
1
+ Metadata-Version: 2.4
2
+ Name: threaded-order
3
+ Version: 1.3.1
4
+ Summary: A lightweight framework for running functions concurrently across multiple threads while maintaining a defined execution order.
5
+ Author-email: Emilio Reyes <soda480@gmail.com>
6
+ Project-URL: Homepage, https://github.com/soda480/threaded-order
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Operating System :: OS Independent
9
+ Requires-Python: >=3.9
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Provides-Extra: dev
13
+ Requires-Dist: build; extra == "dev"
14
+ Requires-Dist: flake8; extra == "dev"
15
+ Requires-Dist: mock; extra == "dev"
16
+ Requires-Dist: radon; extra == "dev"
17
+ Requires-Dist: bandit; extra == "dev"
18
+ Requires-Dist: coverage; extra == "dev"
19
+ Requires-Dist: coverage-badge; extra == "dev"
20
+ Requires-Dist: twine; extra == "dev"
21
+ Dynamic: license-file
22
+
23
+ [![ci](https://github.com/soda480/threaded-order/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/soda480/threaded-order/actions/workflows/ci.yml)
24
+ [![PyPI version](https://badge.fury.io/py/threaded-order.svg)](https://badge.fury.io/py/threaded-order)
25
+
26
+ # threaded-order
27
+ A lightweight Python framework for running functions concurrently across multiple threads while maintaining defined execution order. It lets you declare dependencies between tasks—so some run only after others complete—without complex orchestration code.
28
+
29
+ Ideal for dependency-aware test execution, build pipelines, and automation workflows that benefit from controlled concurrency.
30
+
31
+ Key Features
32
+ * Concurrent task execution using Python threads
33
+ * Dependency graph automatically determines order
34
+ * Simple registration and decorator API
35
+ * Thread-safe logging, callbacks, and run summary
36
+ * Graceful shutdown on interrupt
37
+
38
+ ## Installation
39
+
40
+ ```
41
+ pip install threaded-order
42
+ ```
43
+
44
+ ### Simple Example
45
+
46
+ ![graph](https://github.com/soda480/threaded-order/blob/main/docs/images/graph.png?raw=true)
47
+
48
+ ```Python
49
+ from threaded_order import Scheduler, ThreadProxyLogger
50
+ import time
51
+ import random
52
+
53
+ s = Scheduler(workers=3, setup_logging=True)
54
+ logger = ThreadProxyLogger()
55
+
56
+ def run(name):
57
+ time.sleep(random.uniform(.5, 3.5))
58
+ logger.info(f'{name} completed')
59
+
60
+ @s.dregister()
61
+ def a(): run('a')
62
+
63
+ @s.dregister(after=['a'])
64
+ def b(): run('b')
65
+
66
+ @s.dregister(after=['a'])
67
+ def c(): run('c')
68
+
69
+ @s.dregister(after=['c'])
70
+ def d(): run('d')
71
+
72
+ @s.dregister(after=['c'])
73
+ def e(): run('e')
74
+
75
+ @s.dregister(after=['b', 'd'])
76
+ def f(): run('f')
77
+
78
+ if __name__ == '__main__':
79
+ s.on_scheduler_done(lambda s: print(f"Passed:{len(s['passed'])} Failed:{len(s['failed'])}"))
80
+ s.start()
81
+ ```
82
+
83
+ ![example4](https://github.com/soda480/threaded-order/blob/main/docs/images/example4.gif?raw=true)
84
+
85
+ ### ProgressBar Integration Example
86
+
87
+ Can be done by using the `on_task_done` callback. See [example5](https://github.com/soda480/threaded-order/blob/main/examples/example5.py)
88
+
89
+ ![example5](https://github.com/soda480/threaded-order/blob/main/docs/images/example5.gif?raw=true)
90
+
91
+
92
+ See examples in examples folder. To run examples, follow instructions below to build and run the Docker container then execute:
93
+
94
+ ## API Overview
95
+ `class Scheduler(workers=None, setup_logging=False, add_stream_handler=True)`
96
+
97
+ Runs registered callables across multiple threads while respecting declared dependencies.
98
+
99
+ ### Core Methods
100
+ | Method | Description |
101
+ | --- | --- |
102
+ | `register(obj, name, after=None)` | Register a callable for execution. after defines dependencies by name. |
103
+ | `dregister(after=None)` | Decorator variant of register() for inline task definitions. |
104
+ | `start()` | Start execution, respecting dependencies. Returns a summary dictionary. |
105
+
106
+ ### Callbacks
107
+
108
+ All are optional and run on the scheduler thread (never worker threads).
109
+
110
+ | Callback | When Fired | Signature |
111
+ | --- | --- | --- |
112
+ | `on_task_start(fn)` | Before a task starts | (name) |
113
+ | `on_task_done(fn)` | After a task finishes | (name, ok) |
114
+ | `on_scheduler_start(fn)` | Before scheduler starts running tasks | (meta) |
115
+ | `on_scheduler_done(fn)` | After all tasks complete | (summary) |
116
+
117
+ ### Interrupt Handling
118
+
119
+ Press Ctrl-C during execution to gracefully cancel outstanding work:
120
+ * Running tasks finish naturally or are marked as cancelled
121
+ * Remaining queued tasks are discarded
122
+ * Final summary reflects all results
123
+
124
+ ## Development
125
+
126
+ Clone the repository and ensure the latest version of Docker is installed on your development server.
127
+
128
+ Build the Docker image:
129
+ ```sh
130
+ docker image build \
131
+ -t threaded-order:latest .
132
+ ```
133
+
134
+ Run the Docker container:
135
+ ```sh
136
+ docker container run \
137
+ --rm \
138
+ -it \
139
+ -v $PWD:/code \
140
+ threaded-order:latest \
141
+ bash
142
+ ```
143
+
144
+ Execute the dev pipeline:
145
+ ```sh
146
+ make dev
147
+ ```
@@ -0,0 +1,125 @@
1
+ [![ci](https://github.com/soda480/threaded-order/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/soda480/threaded-order/actions/workflows/ci.yml)
2
+ [![PyPI version](https://badge.fury.io/py/threaded-order.svg)](https://badge.fury.io/py/threaded-order)
3
+
4
+ # threaded-order
5
+ A lightweight Python framework for running functions concurrently across multiple threads while maintaining defined execution order. It lets you declare dependencies between tasks—so some run only after others complete—without complex orchestration code.
6
+
7
+ Ideal for dependency-aware test execution, build pipelines, and automation workflows that benefit from controlled concurrency.
8
+
9
+ Key Features
10
+ * Concurrent task execution using Python threads
11
+ * Dependency graph automatically determines order
12
+ * Simple registration and decorator API
13
+ * Thread-safe logging, callbacks, and run summary
14
+ * Graceful shutdown on interrupt
15
+
16
+ ## Installation
17
+
18
+ ```
19
+ pip install threaded-order
20
+ ```
21
+
22
+ ### Simple Example
23
+
24
+ ![graph](https://github.com/soda480/threaded-order/blob/main/docs/images/graph.png?raw=true)
25
+
26
+ ```Python
27
+ from threaded_order import Scheduler, ThreadProxyLogger
28
+ import time
29
+ import random
30
+
31
+ s = Scheduler(workers=3, setup_logging=True)
32
+ logger = ThreadProxyLogger()
33
+
34
+ def run(name):
35
+ time.sleep(random.uniform(.5, 3.5))
36
+ logger.info(f'{name} completed')
37
+
38
+ @s.dregister()
39
+ def a(): run('a')
40
+
41
+ @s.dregister(after=['a'])
42
+ def b(): run('b')
43
+
44
+ @s.dregister(after=['a'])
45
+ def c(): run('c')
46
+
47
+ @s.dregister(after=['c'])
48
+ def d(): run('d')
49
+
50
+ @s.dregister(after=['c'])
51
+ def e(): run('e')
52
+
53
+ @s.dregister(after=['b', 'd'])
54
+ def f(): run('f')
55
+
56
+ if __name__ == '__main__':
57
+ s.on_scheduler_done(lambda s: print(f"Passed:{len(s['passed'])} Failed:{len(s['failed'])}"))
58
+ s.start()
59
+ ```
60
+
61
+ ![example4](https://github.com/soda480/threaded-order/blob/main/docs/images/example4.gif?raw=true)
62
+
63
+ ### ProgressBar Integration Example
64
+
65
+ Can be done by using the `on_task_done` callback. See [example5](https://github.com/soda480/threaded-order/blob/main/examples/example5.py)
66
+
67
+ ![example5](https://github.com/soda480/threaded-order/blob/main/docs/images/example5.gif?raw=true)
68
+
69
+
70
+ See examples in examples folder. To run examples, follow instructions below to build and run the Docker container then execute:
71
+
72
+ ## API Overview
73
+ `class Scheduler(workers=None, setup_logging=False, add_stream_handler=True)`
74
+
75
+ Runs registered callables across multiple threads while respecting declared dependencies.
76
+
77
+ ### Core Methods
78
+ | Method | Description |
79
+ | --- | --- |
80
+ | `register(obj, name, after=None)` | Register a callable for execution. after defines dependencies by name. |
81
+ | `dregister(after=None)` | Decorator variant of register() for inline task definitions. |
82
+ | `start()` | Start execution, respecting dependencies. Returns a summary dictionary. |
83
+
84
+ ### Callbacks
85
+
86
+ All are optional and run on the scheduler thread (never worker threads).
87
+
88
+ | Callback | When Fired | Signature |
89
+ | --- | --- | --- |
90
+ | `on_task_start(fn)` | Before a task starts | (name) |
91
+ | `on_task_done(fn)` | After a task finishes | (name, ok) |
92
+ | `on_scheduler_start(fn)` | Before scheduler starts running tasks | (meta) |
93
+ | `on_scheduler_done(fn)` | After all tasks complete | (summary) |
94
+
95
+ ### Interrupt Handling
96
+
97
+ Press Ctrl-C during execution to gracefully cancel outstanding work:
98
+ * Running tasks finish naturally or are marked as cancelled
99
+ * Remaining queued tasks are discarded
100
+ * Final summary reflects all results
101
+
102
+ ## Development
103
+
104
+ Clone the repository and ensure the latest version of Docker is installed on your development server.
105
+
106
+ Build the Docker image:
107
+ ```sh
108
+ docker image build \
109
+ -t threaded-order:latest .
110
+ ```
111
+
112
+ Run the Docker container:
113
+ ```sh
114
+ docker container run \
115
+ --rm \
116
+ -it \
117
+ -v $PWD:/code \
118
+ threaded-order:latest \
119
+ bash
120
+ ```
121
+
122
+ Execute the dev pipeline:
123
+ ```sh
124
+ make dev
125
+ ```
@@ -0,0 +1,41 @@
1
+ [project]
2
+ name = "threaded-order"
3
+ dynamic = ["version"]
4
+ authors = [
5
+ { name="Emilio Reyes", email="soda480@gmail.com" },
6
+ ]
7
+ description = "A lightweight framework for running functions concurrently across multiple threads while maintaining a defined execution order."
8
+ readme = "README.md"
9
+ requires-python = ">=3.9"
10
+ classifiers = [
11
+ "Programming Language :: Python :: 3",
12
+ "Operating System :: OS Independent",
13
+ ]
14
+
15
+ dependencies = [
16
+ ]
17
+
18
+ [tool.setuptools]
19
+ packages = ["threaded_order"]
20
+
21
+ [project.urls]
22
+ "Homepage" = "https://github.com/soda480/threaded-order"
23
+
24
+ [project.optional-dependencies]
25
+ dev = [
26
+ "build",
27
+ "flake8",
28
+ "mock",
29
+ "radon",
30
+ "bandit",
31
+ "coverage",
32
+ "coverage-badge",
33
+ "twine"
34
+ ]
35
+
36
+ [build-system]
37
+ requires = ["setuptools>=61.0"]
38
+ build-backend = "setuptools.build_meta"
39
+
40
+ [tool.setuptools.dynamic]
41
+ version = {attr = "threaded_order.__version__"}
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,32 @@
1
+ from importlib import metadata as _metadata
2
+ from os import getenv
3
+
4
+ __all__ = [
5
+ 'Scheduler',
6
+ 'DAGraph',
7
+ 'configure_logging',
8
+ 'ThreadProxyLogger',
9
+ '__version__']
10
+
11
+ def __getattr__(name):
12
+ if name == 'Scheduler':
13
+ from .scheduler import Scheduler
14
+ return Scheduler
15
+ if name == 'DAGraph':
16
+ from .graph import DAGraph
17
+ return DAGraph
18
+ if name == 'configure_logging':
19
+ from .logger import configure_logging
20
+ return configure_logging
21
+ if name == 'ThreadProxyLogger':
22
+ from .logger import ThreadProxyLogger
23
+ return ThreadProxyLogger
24
+ raise AttributeError(name)
25
+
26
+ try:
27
+ __version__ = _metadata.version(__name__)
28
+ except _metadata.PackageNotFoundError:
29
+ __version__ = '1.3.1'
30
+
31
+ if getenv('DEV'):
32
+ __version__ = f'{__version__}+dev'
@@ -0,0 +1,119 @@
1
+ import threading
2
+ import logging
3
+ from collections import defaultdict
4
+
5
+ def log_candidates(candidates, number):
6
+ """ log a debug message describing how many candidate nodes were found
7
+ """
8
+ logger = logging.getLogger(threading.current_thread().name)
9
+ count = len(candidates)
10
+ if not candidates:
11
+ message = 'but found no candidates eligible for submission'
12
+ else:
13
+ base = f"and found {count} candidate{'s' if count != 1 else ''} eligible for submission"
14
+ message = f"{base} {', '.join(candidates)}"
15
+ logger.debug(f'requested {number} {message}')
16
+
17
+ class DAGraph:
18
+
19
+ def __init__(self):
20
+ """ initialize an empty DAG with parent and child adjacency mappings
21
+ """
22
+ self._parents = defaultdict(list)
23
+ self._children = defaultdict(set)
24
+
25
+ def add(self, name, after=None):
26
+ """ add a new node with optional dependencies
27
+
28
+ All items in `after` must already exist in the DAG.
29
+ Raises ValueError if the node already exists, dependencies are unknown,
30
+ or the addition would introduce a cycle.
31
+ """
32
+ logger = logging.getLogger(threading.current_thread().name)
33
+ after = after or []
34
+ logger.debug(f'add {name} dependent on {after}')
35
+ if name in self._parents:
36
+ raise ValueError(f'{name} has already been added')
37
+ unknowns = [dep for dep in after if dep not in self._parents]
38
+ if unknowns:
39
+ raise ValueError(f'{name} depends on unknown {unknowns}')
40
+ self._parents[name] = []
41
+ for dep in after:
42
+ self._parents[name].append(dep)
43
+ self._children[dep].add(name)
44
+ if self._has_cycle():
45
+ # rollback this node to keep DAG consistent
46
+ for dep in after:
47
+ self._children[dep].discard(name)
48
+ self._parents.pop(name, None)
49
+ raise ValueError(f'adding {name} will create a cycle')
50
+
51
+ def remove(self, name):
52
+ """ remove a completed node and detach it from all dependent children
53
+
54
+ Cleans up parent and child relationships and drops the node completely
55
+ once it has no remaining edges.
56
+ """
57
+ logger = logging.getLogger(threading.current_thread().name)
58
+ for child in self._children.pop(name, ()):
59
+ logger.debug(f'removing {name} as a dependency from {child}')
60
+ try:
61
+ self._parents[child].remove(name)
62
+ except ValueError:
63
+ # defensive: graph might already be partially cleaned
64
+ pass
65
+
66
+ if name in self._parents and not self._parents[name]:
67
+ logger.debug(f'removing {name} from dependency graph')
68
+ self._parents.pop(name, None)
69
+
70
+ def ready(self, active=None):
71
+ """ return a list of nodes whose dependencies are satisfied and not active
72
+ """
73
+ if active is None:
74
+ active = set()
75
+ return [name for name, deps in self._parents.items() if not deps and name not in active]
76
+
77
+ def get_candidates(self, active, number, sort=True):
78
+ """ return up to `number` ready nodes, optionally sorted for stable scheduling
79
+
80
+ Also logs the candidate list for visibility.
81
+ """
82
+ candidates = self.ready(active)
83
+ if sort:
84
+ candidates = sorted(candidates)
85
+ log_candidates(candidates, number)
86
+ return candidates[:number]
87
+
88
+ def _has_cycle(self):
89
+ """ return True if DAGraph contains a cycle
90
+ """
91
+ visited = set()
92
+ stack = set()
93
+
94
+ def visit(node):
95
+ if node in stack:
96
+ return True
97
+ if node in visited:
98
+ return False
99
+ visited.add(node)
100
+ stack.add(node)
101
+ for neighbor in self._parents[node]:
102
+ if visit(neighbor):
103
+ return True
104
+ stack.remove(node)
105
+ return False
106
+ return any(visit(node) for node in self._parents)
107
+
108
+ def is_empty(self):
109
+ """ return True if the DAGraph has no nodes
110
+ """
111
+ return not self._parents and not self._children
112
+
113
+ def __repr__(self):
114
+ """ return a human-readable representation of the dependency graph
115
+ """
116
+ parents = '\n'.join(f'{n}: {self._parents[n]}' for n in sorted(self._parents))
117
+ children = '\n'.join(
118
+ f'{n}: {sorted(list(self._children[n]))}' for n in sorted(self._children))
119
+ return f'Parents:\n{parents}\nChildren:\n{children}'
@@ -0,0 +1,45 @@
1
+ import os
2
+ import sys
3
+ import threading
4
+ import logging
5
+
6
+ class ThreadProxyLogger:
7
+ def __getattr__(self, name):
8
+ return getattr(logging.getLogger(threading.current_thread().name), name)
9
+
10
+ def configure_logging(workers, prefix='thread', add_stream_handler=False):
11
+ if add_stream_handler:
12
+ shandler = logging.StreamHandler(sys.stderr)
13
+ shandler.setLevel(logging.INFO)
14
+ shandler.setFormatter(
15
+ logging.Formatter(
16
+ "%(asctime)s [%(threadName)s]: %(message)s", "%Y-%m-%d %H:%M:%S"))
17
+
18
+ root = logging.getLogger()
19
+ root.setLevel(logging.DEBUG)
20
+ root.handlers.clear()
21
+ root.addHandler(shandler)
22
+
23
+ base = os.path.splitext(os.path.basename(sys.argv[0]))[0]
24
+ formatter = logging.Formatter(
25
+ "%(asctime)s %(levelname)-5s [%(threadName)s] %(funcName)s: %(message)s",
26
+ "%Y-%m-%d %H:%M:%S")
27
+
28
+ def add_handler(name):
29
+ filename = f'{base}_{name}.log'
30
+ logger = logging.getLogger(name)
31
+ if not any(
32
+ isinstance(handler, logging.FileHandler)
33
+ and getattr(handler, 'baseFilename', '').endswith(filename)
34
+ for handler in logger.handlers
35
+ ):
36
+ fhandler = logging.FileHandler(filename, mode='a', encoding='utf-8')
37
+ fhandler.setLevel(logging.DEBUG)
38
+ fhandler.setFormatter(formatter)
39
+ logger.addHandler(fhandler)
40
+ logger.setLevel(logging.DEBUG)
41
+ return logger
42
+
43
+ add_handler(threading.current_thread().name)
44
+ for index in range(workers):
45
+ add_handler(f'{prefix}_{index}')
@@ -0,0 +1,341 @@
1
+ import os
2
+ import time
3
+ import queue
4
+ import threading
5
+ import logging
6
+ from collections import Counter
7
+ from concurrent.futures import ThreadPoolExecutor, CancelledError
8
+ from functools import wraps
9
+ from .graph import DAGraph
10
+ from .logger import configure_logging
11
+
12
+ class Scheduler:
13
+ """ run functions concurrently across multiple threads while maintaining a defined
14
+ execution order
15
+ """
16
+ max_workers = min(8, os.cpu_count())
17
+
18
+ def __init__(self, workers=max_workers, setup_logging=False, add_stream_handler=True):
19
+ """ initialize scheduler with thread pool size, logging, and callback placeholders
20
+ """
21
+ # number of concurrent worker threads in the pool
22
+ self._workers = workers
23
+ # task name → callable object to execute
24
+ self._run_map = {}
25
+ # direct acyclic graph
26
+ self._dagraph = DAGraph()
27
+ # protects access to _futures (shared by scheduler and worker threads)
28
+ self._lock = threading.Lock()
29
+ # currently running task names
30
+ self._active = set()
31
+ # future → task name mapping for cancellation and error recovery
32
+ self._futures = {}
33
+ # signals scheduler when all tasks have completed
34
+ self._completed = threading.Event()
35
+ # ThreadPoolExecutor instance (managed inside start())
36
+ self._executor = None
37
+ # thread-safe queue for passing start/done events from workers to scheduler
38
+ self._events = queue.Queue()
39
+ # wall-clock start time (UTC seconds)
40
+ self._started_wall = 0.0
41
+ # wall-clock finish time (UTC seconds)
42
+ self._finished_wall = 0.0
43
+ # monotonic clock start time (for precise duration measurement)
44
+ self._started_mono = 0.0
45
+ # monotonic clock finish time (for precise duration measurement)
46
+ self._finished_mono = 0.0
47
+ # list of task names that have run (in order of completion)
48
+ self._ran = []
49
+ # task name → result details (ok, error_type, error)
50
+ self._results = {}
51
+ # list of task names that failed
52
+ self._failed = []
53
+ # user callback fired when a task is about to start
54
+ self._on_task_start = None
55
+ # user callback fired when a task is running on thread
56
+ self._on_task_run = None
57
+ # user callback fired when a task completes
58
+ self._on_task_done = None
59
+ # user callback fired when the scheduler begins execution
60
+ self._on_scheduler_start = None
61
+ # user callback fired when the scheduler finishes all tasks
62
+ self._on_scheduler_done = None
63
+ self._prefix = 'thread'
64
+ if setup_logging:
65
+ configure_logging(workers, prefix=self._prefix, add_stream_handler=add_stream_handler)
66
+
67
+ def register(self, obj, name, after=None):
68
+ """ register a callable for execution, optionally dependent on other tasks
69
+ """
70
+ if not callable(obj):
71
+ raise ValueError('object must be callable')
72
+ self._dagraph.add(name, after=after)
73
+ self._run_map[name] = obj
74
+
75
+ def dregister(self, after=None):
76
+ """ decorator form of register() for convenient inline task definition
77
+ """
78
+ def decorator(function):
79
+ @wraps(function)
80
+ def wrapper(*args, **kwargs):
81
+ return function(*args, **kwargs)
82
+ # register at decoration time so start() can discover it
83
+ self.register(wrapper, function.__name__, after=after)
84
+ # keep a pointer to the original
85
+ wrapper.__original__ = function
86
+ return wrapper
87
+ return decorator
88
+
89
+ def _handle_event(self):
90
+ """ process queued task and scheduler events on the scheduler thread
91
+ """
92
+ logger = logging.getLogger(threading.current_thread().name)
93
+ while True:
94
+ try:
95
+ kind, payload = self._events.get_nowait()
96
+ except queue.Empty:
97
+ break
98
+
99
+ if kind == 'start':
100
+ name = payload
101
+ self._callback(self._on_task_start, name)
102
+
103
+ elif kind == 'run':
104
+ name, thread = payload
105
+ self._callback(self._on_task_run, name, thread)
106
+
107
+ elif kind == 'done':
108
+ name, ok, error_type, error = payload
109
+ logger.debug(f'removing {name!r} from active futures')
110
+ self._active.discard(name)
111
+ self._dagraph.remove(name)
112
+
113
+ self._ran.append(name)
114
+ self._results[name] = {
115
+ 'ok': ok,
116
+ 'error_type': error_type,
117
+ 'error': error
118
+ }
119
+ if not ok:
120
+ self._failed.append(name)
121
+
122
+ self._callback(self._on_task_done, name, ok)
123
+ # schedule next candidate
124
+ free = max(0, self._workers - len(self._active))
125
+ if free:
126
+ # keep pool full after dependency 'burst' - several tasks unblock at once
127
+ for cand in self._dagraph.get_candidates(self._active, free):
128
+ self._submit(cand)
129
+ if self._dagraph.is_empty() and not self._active:
130
+ logger.debug(
131
+ 'nothing more to run and no active futures remain - signaling all done')
132
+ self._completed.set()
133
+
134
+ def _build_summary(self):
135
+ """ assemble concise run summary from collected results and timings
136
+ """
137
+ ran = list(self._ran)
138
+ passed = [name for name, result in self._results.items() if result["ok"]]
139
+ failed = list(self._failed)
140
+ failures = {
141
+ name: {
142
+ 'error_type': self._results[name]['error_type'],
143
+ 'error': self._results[name]['error']
144
+ } for name in failed
145
+ }
146
+ failure_counts = Counter(
147
+ result['error_type'] for result in self._results.values() if not result['ok']
148
+ )
149
+ return {
150
+ 'ran': ran,
151
+ 'passed': passed,
152
+ 'failed': failed,
153
+ 'failures': failures,
154
+ 'failure_counts': dict(failure_counts),
155
+ 'started_at': self._started_wall,
156
+ 'finished_at': self._finished_wall,
157
+ 'duration': self._finished_mono - self._started_mono
158
+ }
159
+
160
+ def _handle_interrupt(self, logger):
161
+ """ cancel in-flight work, drain events, and mark remaining tasks as cancelled
162
+ """
163
+ logger.error('interrupt received; cancelling remaining tasks')
164
+
165
+ # cancel all futures we still track
166
+ with self._lock:
167
+ futures = list(self._futures.keys())
168
+ for future in futures:
169
+ try:
170
+ future.cancel()
171
+ except (CancelledError, RuntimeError) as exception:
172
+ logger.debug(f'cancel() ignored for completed future: {exception}')
173
+
174
+ # drain anything already completed and queued
175
+ self._handle_event()
176
+
177
+ # mark any still-active tasks as cancelled (these never emitted a 'done' event)
178
+ still_active = list(self._active)
179
+ self._active.clear()
180
+ for name in still_active:
181
+ # remove from graph so completion logic won't wait on them
182
+ self._dagraph.remove(name)
183
+ # record cancellation
184
+ self._ran.append(name)
185
+ self._results[name] = {
186
+ 'ok': False,
187
+ 'error_type': 'CancelledError',
188
+ 'error': 'cancelled'
189
+ }
190
+ self._failed.append(name)
191
+
192
+ # signal completion so the loop (if resumed) would exit
193
+ self._completed.set()
194
+
195
+ def start(self):
196
+ """ run all registered tasks respecting dependencies, collect results, and trigger callbacks
197
+ """
198
+ logger = logging.getLogger(threading.current_thread().name)
199
+ self._ran.clear()
200
+ self._results.clear()
201
+ self._failed.clear()
202
+ self._completed.clear()
203
+ self._futures.clear()
204
+
205
+ # drain any stale events
206
+ try:
207
+ while True:
208
+ self._events.get_nowait()
209
+ except queue.Empty:
210
+ pass
211
+
212
+ self._started_wall = time.time()
213
+ self._started_mono = time.perf_counter()
214
+ meta = {
215
+ 'total_tasks': len(self._run_map),
216
+ 'workers': self._workers,
217
+ 'started_at': self._started_wall
218
+ }
219
+ self._callback(self._on_scheduler_start, meta)
220
+
221
+ try:
222
+ with ThreadPoolExecutor(max_workers=self._workers,
223
+ thread_name_prefix=self._prefix) as executor:
224
+ self._executor = executor
225
+ logger.info(f'starting thread pool with {self._workers} threads')
226
+ # initial seeding
227
+ for name in self._dagraph.get_candidates(self._active, self._workers):
228
+ self._submit(name)
229
+
230
+ # main loop of scheduler thread
231
+ while not self._completed.wait(timeout=0.1):
232
+ self._handle_event()
233
+
234
+ # final drain
235
+ self._handle_event()
236
+ logger.info('all work completed')
237
+
238
+ except KeyboardInterrupt:
239
+ self._handle_interrupt(logger)
240
+
241
+ finally:
242
+ self._finished_wall = time.time()
243
+ self._finished_mono = time.perf_counter()
244
+ duration = self._finished_mono - self._started_mono
245
+ logger.info(f'duration: {duration:.2f}s')
246
+ summary = self._build_summary()
247
+ self._callback(self._on_scheduler_done, summary)
248
+ return summary
249
+
250
+ def _submit(self, name):
251
+ """ submit a ready task to the thread pool and queue its start event
252
+ """
253
+ logger = logging.getLogger(threading.current_thread().name)
254
+ logger.debug(f'submitting {name!r} to thread pool')
255
+
256
+ self._events.put(('start', name))
257
+
258
+ future = self._executor.submit(self._run, name)
259
+ logger.debug(f'adding {name} to active futures')
260
+ self._active.add(name)
261
+ with self._lock:
262
+ # track future to name
263
+ self._futures[future] = name
264
+ future.add_done_callback(self._done)
265
+
266
+ def _done(self, future):
267
+ """ enqueue a 'done' event for a finished Future
268
+ safely extracts the task result or synthesizes a failure if the Future raised
269
+ """
270
+ try:
271
+ payload = future.result()
272
+ except Exception as exception:
273
+ # worker failed before building payload - recover name and emit synthetic failure
274
+ name = self._futures.get(future, '<unknown>')
275
+ payload = (name, False, type(exception).__name__, str(exception))
276
+ finally:
277
+ # cleanup no matter what
278
+ with self._lock:
279
+ self._futures.pop(future, '<unknown>')
280
+ self._events.put(('done', payload))
281
+
282
+ def _run(self, name):
283
+ """ execute a task callable, capture errors, and return its result tuple
284
+ """
285
+ thread = threading.current_thread().name
286
+ logger = logging.getLogger(thread)
287
+ payload = (name, thread)
288
+ self._events.put(('run', payload))
289
+ logger.debug(f'run {name!r}')
290
+ ok = True
291
+ error_type = None
292
+ error = None
293
+ try:
294
+ self._run_map[name]()
295
+ except Exception as exception:
296
+ ok = False
297
+ error_type = type(exception).__name__
298
+ error = str(exception)
299
+ logger.error(f'{name!r} failed: {error_type}: {error}')
300
+ return (name, ok, error_type, error)
301
+
302
+ def _callback(self, callback, *args):
303
+ """ safely invoke a user callback, logging any exceptions raised
304
+ """
305
+ if not callback:
306
+ return
307
+ logger = logging.getLogger(threading.current_thread().name)
308
+ try:
309
+ if isinstance(callback, tuple):
310
+ function, user_args, user_kwargs = callback
311
+ function(*args, *user_args, **user_kwargs)
312
+ else:
313
+ callback(*args)
314
+ except Exception:
315
+ callback_name = getattr(callback, '__name__', callback)
316
+ logger.debug(f'callback {callback_name!r} failed', exc_info=True)
317
+
318
+ def on_task_start(self, function, *args, **kwargs):
319
+ """ register callback fired when a task is about to start
320
+ """
321
+ self._on_task_start = (function, args, kwargs)
322
+
323
+ def on_task_run(self, function, *args, **kwargs):
324
+ """ register callback fired when a task is running on thread
325
+ """
326
+ self._on_task_run = (function, args, kwargs)
327
+
328
+ def on_task_done(self, function, *args, **kwargs):
329
+ """ register callback fired when a task finishes execution
330
+ """
331
+ self._on_task_done = (function, args, kwargs)
332
+
333
+ def on_scheduler_start(self, function, *args, **kwargs):
334
+ """ register callback fired when the scheduler begins execution
335
+ """
336
+ self._on_scheduler_start = (function, args, kwargs)
337
+
338
+ def on_scheduler_done(self, function, *args, **kwargs):
339
+ """ register callback fired when the scheduler completes all tasks
340
+ """
341
+ self._on_scheduler_done = (function, args, kwargs)
@@ -0,0 +1,147 @@
1
+ Metadata-Version: 2.4
2
+ Name: threaded-order
3
+ Version: 1.3.1
4
+ Summary: A lightweight framework for running functions concurrently across multiple threads while maintaining a defined execution order.
5
+ Author-email: Emilio Reyes <soda480@gmail.com>
6
+ Project-URL: Homepage, https://github.com/soda480/threaded-order
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Operating System :: OS Independent
9
+ Requires-Python: >=3.9
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Provides-Extra: dev
13
+ Requires-Dist: build; extra == "dev"
14
+ Requires-Dist: flake8; extra == "dev"
15
+ Requires-Dist: mock; extra == "dev"
16
+ Requires-Dist: radon; extra == "dev"
17
+ Requires-Dist: bandit; extra == "dev"
18
+ Requires-Dist: coverage; extra == "dev"
19
+ Requires-Dist: coverage-badge; extra == "dev"
20
+ Requires-Dist: twine; extra == "dev"
21
+ Dynamic: license-file
22
+
23
+ [![ci](https://github.com/soda480/threaded-order/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/soda480/threaded-order/actions/workflows/ci.yml)
24
+ [![PyPI version](https://badge.fury.io/py/threaded-order.svg)](https://badge.fury.io/py/threaded-order)
25
+
26
+ # threaded-order
27
+ A lightweight Python framework for running functions concurrently across multiple threads while maintaining defined execution order. It lets you declare dependencies between tasks—so some run only after others complete—without complex orchestration code.
28
+
29
+ Ideal for dependency-aware test execution, build pipelines, and automation workflows that benefit from controlled concurrency.
30
+
31
+ Key Features
32
+ * Concurrent task execution using Python threads
33
+ * Dependency graph automatically determines order
34
+ * Simple registration and decorator API
35
+ * Thread-safe logging, callbacks, and run summary
36
+ * Graceful shutdown on interrupt
37
+
38
+ ## Installation
39
+
40
+ ```
41
+ pip install threaded-order
42
+ ```
43
+
44
+ ### Simple Example
45
+
46
+ ![graph](https://github.com/soda480/threaded-order/blob/main/docs/images/graph.png?raw=true)
47
+
48
+ ```Python
49
+ from threaded_order import Scheduler, ThreadProxyLogger
50
+ import time
51
+ import random
52
+
53
+ s = Scheduler(workers=3, setup_logging=True)
54
+ logger = ThreadProxyLogger()
55
+
56
+ def run(name):
57
+ time.sleep(random.uniform(.5, 3.5))
58
+ logger.info(f'{name} completed')
59
+
60
+ @s.dregister()
61
+ def a(): run('a')
62
+
63
+ @s.dregister(after=['a'])
64
+ def b(): run('b')
65
+
66
+ @s.dregister(after=['a'])
67
+ def c(): run('c')
68
+
69
+ @s.dregister(after=['c'])
70
+ def d(): run('d')
71
+
72
+ @s.dregister(after=['c'])
73
+ def e(): run('e')
74
+
75
+ @s.dregister(after=['b', 'd'])
76
+ def f(): run('f')
77
+
78
+ if __name__ == '__main__':
79
+ s.on_scheduler_done(lambda s: print(f"Passed:{len(s['passed'])} Failed:{len(s['failed'])}"))
80
+ s.start()
81
+ ```
82
+
83
+ ![example4](https://github.com/soda480/threaded-order/blob/main/docs/images/example4.gif?raw=true)
84
+
85
+ ### ProgressBar Integration Example
86
+
87
+ Can be done by using the `on_task_done` callback. See [example5](https://github.com/soda480/threaded-order/blob/main/examples/example5.py)
88
+
89
+ ![example5](https://github.com/soda480/threaded-order/blob/main/docs/images/example5.gif?raw=true)
90
+
91
+
92
+ See examples in examples folder. To run examples, follow instructions below to build and run the Docker container then execute:
93
+
94
+ ## API Overview
95
+ `class Scheduler(workers=None, setup_logging=False, add_stream_handler=True)`
96
+
97
+ Runs registered callables across multiple threads while respecting declared dependencies.
98
+
99
+ ### Core Methods
100
+ | Method | Description |
101
+ | --- | --- |
102
+ | `register(obj, name, after=None)` | Register a callable for execution. after defines dependencies by name. |
103
+ | `dregister(after=None)` | Decorator variant of register() for inline task definitions. |
104
+ | `start()` | Start execution, respecting dependencies. Returns a summary dictionary. |
105
+
106
+ ### Callbacks
107
+
108
+ All are optional and run on the scheduler thread (never worker threads).
109
+
110
+ | Callback | When Fired | Signature |
111
+ | --- | --- | --- |
112
+ | `on_task_start(fn)` | Before a task starts | (name) |
113
+ | `on_task_done(fn)` | After a task finishes | (name, ok) |
114
+ | `on_scheduler_start(fn)` | Before scheduler starts running tasks | (meta) |
115
+ | `on_scheduler_done(fn)` | After all tasks complete | (summary) |
116
+
117
+ ### Interrupt Handling
118
+
119
+ Press Ctrl-C during execution to gracefully cancel outstanding work:
120
+ * Running tasks finish naturally or are marked as cancelled
121
+ * Remaining queued tasks are discarded
122
+ * Final summary reflects all results
123
+
124
+ ## Development
125
+
126
+ Clone the repository and ensure the latest version of Docker is installed on your development server.
127
+
128
+ Build the Docker image:
129
+ ```sh
130
+ docker image build \
131
+ -t threaded-order:latest .
132
+ ```
133
+
134
+ Run the Docker container:
135
+ ```sh
136
+ docker container run \
137
+ --rm \
138
+ -it \
139
+ -v $PWD:/code \
140
+ threaded-order:latest \
141
+ bash
142
+ ```
143
+
144
+ Execute the dev pipeline:
145
+ ```sh
146
+ make dev
147
+ ```
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ threaded_order/__init__.py
5
+ threaded_order/graph.py
6
+ threaded_order/logger.py
7
+ threaded_order/scheduler.py
8
+ threaded_order.egg-info/PKG-INFO
9
+ threaded_order.egg-info/SOURCES.txt
10
+ threaded_order.egg-info/dependency_links.txt
11
+ threaded_order.egg-info/requires.txt
12
+ threaded_order.egg-info/top_level.txt
@@ -0,0 +1,10 @@
1
+
2
+ [dev]
3
+ build
4
+ flake8
5
+ mock
6
+ radon
7
+ bandit
8
+ coverage
9
+ coverage-badge
10
+ twine
@@ -0,0 +1 @@
1
+ threaded_order