├── .gitignore
├── LICENSE
├── README.md
├── backend
├── .gitignore
├── __init__.py
├── auth.py
├── data_models.py
├── database.py
├── main.py
├── register.py
├── server.default.config.json
├── server_config.py
└── ws.py
├── data
├── .gitignore
├── projects
│ └── .gitignore
└── readme.md
├── docs
├── dependencies.md
├── design.md
├── format.md
├── readme.ai
└── screenshots
│ └── project_view.png
├── logging_helper
├── __init__.py
├── formatter.py
├── print_colors.py
└── uvicorn_log.config.yaml
├── taskgraph
├── __init__.py
└── taskgraph.py
└── tests
├── .gitignore
├── draw_project.py
└── test_taskgraph.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # This project
2 | .vscode
3 | backup
4 |
5 |
6 | # Byte-compiled / optimized / DLL files
7 | __pycache__/
8 | *.py[cod]
9 | *$py.class
10 |
11 | # C extensions
12 | *.so
13 |
14 | # Distribution / packaging
15 | .Python
16 | build/
17 | develop-eggs/
18 | dist/
19 | downloads/
20 | eggs/
21 | .eggs/
22 | lib/
23 | lib64/
24 | parts/
25 | sdist/
26 | var/
27 | wheels/
28 | share/python-wheels/
29 | *.egg-info/
30 | .installed.cfg
31 | *.egg
32 | MANIFEST
33 |
34 | # PyInstaller
35 | # Usually these files are written by a python script from a template
36 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
37 | *.manifest
38 | *.spec
39 |
40 | # Installer logs
41 | pip-log.txt
42 | pip-delete-this-directory.txt
43 |
44 | # Unit test / coverage reports
45 | htmlcov/
46 | .tox/
47 | .nox/
48 | .coverage
49 | .coverage.*
50 | .cache
51 | nosetests.xml
52 | coverage.xml
53 | *.cover
54 | *.py,cover
55 | .hypothesis/
56 | .pytest_cache/
57 | cover/
58 |
59 | # Translations
60 | *.mo
61 | *.pot
62 |
63 | # Django stuff:
64 | *.log
65 | local_settings.py
66 | db.sqlite3
67 | db.sqlite3-journal
68 |
69 | # Flask stuff:
70 | instance/
71 | .webassets-cache
72 |
73 | # Scrapy stuff:
74 | .scrapy
75 |
76 | # Sphinx documentation
77 | docs/_build/
78 |
79 | # PyBuilder
80 | .pybuilder/
81 | target/
82 |
83 | # Jupyter Notebook
84 | .ipynb_checkpoints
85 |
86 | # IPython
87 | profile_default/
88 | ipython_config.py
89 |
90 | # pyenv
91 | # For a library or package, you might want to ignore these files since the code is
92 | # intended to run in multiple environments; otherwise, check them in:
93 | # .python-version
94 |
95 | # pipenv
96 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
97 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
98 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
99 | # install all needed dependencies.
100 | #Pipfile.lock
101 |
102 | # poetry
103 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
104 | # This is especially recommended for binary packages to ensure reproducibility, and is more
105 | # commonly ignored for libraries.
106 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
107 | #poetry.lock
108 |
109 | # pdm
110 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
111 | #pdm.lock
112 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
113 | # in version control.
114 | # https://pdm.fming.dev/#use-with-ide
115 | .pdm.toml
116 |
117 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
118 | __pypackages__/
119 |
120 | # Celery stuff
121 | celerybeat-schedule
122 | celerybeat.pid
123 |
124 | # SageMath parsed files
125 | *.sage.py
126 |
127 | # Environments
128 | .env
129 | .venv
130 | env/
131 | venv/
132 | ENV/
133 | env.bak/
134 | venv.bak/
135 |
136 | # Spyder project settings
137 | .spyderproject
138 | .spyproject
139 |
140 | # Rope project settings
141 | .ropeproject
142 |
143 | # mkdocs documentation
144 | /site
145 |
146 | # mypy
147 | .mypy_cache/
148 | .dmypy.json
149 | dmypy.json
150 |
151 | # Pyre type checker
152 | .pyre/
153 |
154 | # pytype static type analyzer
155 | .pytype/
156 |
157 | # Cython debug symbols
158 | cython_debug/
159 |
160 | # PyCharm
161 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
162 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
163 | # and can be added to the global gitignore or merged into this file. For a more nuclear
164 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
165 | #.idea/
166 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # TaskGraph
2 |
3 | **NOTE**: TaskGraph is in the early prototype stage. The design is still changing and the source code is under active development, thus the documentation may be inaccurate.
4 |
5 | TaskGraph is a simple application for personal project management.
6 | It utilizes some ideas from asynchronous programming, cooperative multitasking and git versioning to help you finish projects more efficiently.
7 |
8 | It is basically a todolist app with the following features:
9 |
10 | - Tasks are organized into Projects.
11 |
12 | - A project is mapped to a directed acyclic graph (DAG).
13 | - Tasks are nodes in the project DAG.
14 | - A task can depend on another task, the dependency is represented by edges in the DAG.
15 | - Tasks can be inserted or removed at any time.
16 | - A task can be breaked down into more tasks.
17 |
18 | - A Dispatcher tells you what to do now.
19 |
20 | - The dispatcher uses a eventloop to manage tasks.
21 | - When you finish the current task, you mark it as finished and ask the dispatcher for a list of available tasks and pick one to continue working.
22 | - You can leave the current task and mark it as interrupted at any time, if the current task requires to wait for some external event, for example waiting for package delivery or PCB manufacturing.
23 | - The dispatcher will automatically adds interrupted tasks back to available tasks for you to continue when received the required event.
24 |
25 | - Metadata can be attached to tasks.
26 |
27 | - File paths
28 | - Timeouts
29 | - Deadlines
30 | - Geo Locations
31 | - Images and Videos
32 | - Links
33 | - Any other string
34 | - Special metadata reserved: Name, Status
35 |
36 | - Actions can be attached to tasks.
37 |
38 | - Python scripts
39 | - Email reminder
40 | - WeChat reminder
41 |
42 | - Database is saved as text files for easy synchronization across devices.
43 | - Human readable
44 | - Standard formats
45 | - Export to various formats
46 |
47 | Screenshots:
48 |
49 | 
50 |
51 | ## Deployment
52 |
53 | TaskGraph is based on python and javascript, no installation is required.
54 | However, dependencies for python packages needs to be installed on the server side.
55 | Check docs/dependencies.md for a guide on how to install deps.
56 |
57 | To deploy the backend application, suppose that the python dependencies are installed in an anaconda environment called `taskgraph`, clone the project
58 |
59 | (base) $ git clone https://github.com/5A/taskgraph
60 | (base) $ cd taskgraph
61 |
62 | then in the root directory of this project, run
63 |
64 | (base) $ conda activate taskgraph
65 | (taskgraph) $ uvicorn backend.main:app --log-config logging_helper/uvicorn_log.config.yaml --host 0.0.0.0
66 |
67 | The frontend application is in the `taskgraph-vue-antd` directory, and can be served by any static content server application, such as nginx.
68 | For temporary testing, you can run the built-in python3 HTTP server
69 |
70 | (base) $ cd taskgraph-vue-antd/dist
71 | (base) $ python -m http.server
72 |
73 | then go to http://localhost:8000 to access the web GUI.
74 |
75 | If you happen to be a developer, you can also use the vite dev server
76 |
77 | $ cd taskgraph-vue-antd
78 | $ npm run dev
79 |
80 | then go to http://app.taskgraph.org:8080 to access the web GUI. (app.taskgraph.org is a convenient CNAME for 127.0.0.1 to make better use of your web browser localStorage)
81 |
82 | ## Testing
83 |
84 | To run the python unittests, do
85 |
86 | $ python -m unittest tests.test_taskgraph
87 |
--------------------------------------------------------------------------------
/backend/.gitignore:
--------------------------------------------------------------------------------
1 | # server.config.json and hardware.config.json are generated files containing secrets and run-time parameters
2 | # you can create these config files by copying *.default.config.json and filling the empty (secret) fields.
3 | server.config.json
4 | # config-new-user.json is autogenerated when running register.py to add new users.
5 | config-new-user.json
6 |
--------------------------------------------------------------------------------
/backend/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | """backend:
4 | This module provides a FastAPI server for communicating with
5 | taskgraph core.
6 | """
7 |
8 | __author__ = "Zhi Zi"
9 | __email__ = "x@zzi.io"
10 | __version__ = "20240301"
11 |
--------------------------------------------------------------------------------
/backend/auth.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | """auth.py:
4 | This module provide functions for password verification, token generation, token validation and user access level validation.
5 | """
6 |
7 | __author__ = "Zhi Zi"
8 | __email__ = "x@zzi.io"
9 | __version__ = "20231115"
10 |
11 | # std libs
12 | from datetime import datetime, timedelta
13 | from typing import Annotated
14 | # third-party libs
15 | from fastapi import Depends, HTTPException, status, WebSocketException
16 | from fastapi.encoders import jsonable_encoder
17 | from fastapi.security import OAuth2PasswordBearer
18 | from jose import JWTError, jwt
19 | from passlib.context import CryptContext
20 | from pydantic import BaseModel, UUID4
21 | # own package
22 | from .server_config import server_config, UserConfig, UserAccessLevel
23 |
24 |
25 | class Token(BaseModel):
26 | access_token: str
27 | token_type: str
28 |
29 |
30 | class TokenData(BaseModel):
31 | # Subject (required): we will use user id as sub to avoid username collision.
32 | sub: UUID4
33 | # Expires (required): integer timestamp, measured in the number of seconds since January 1 1970 UTC
34 | exp: datetime
35 | # Custom contents
36 | username: str
37 | access_level: UserAccessLevel
38 |
39 |
40 | class AccessLevelException(Exception):
41 | def __init__(self, detail):
42 | self.detail = detail
43 | super().__init__(self.detail)
44 |
45 |
46 | pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
47 | oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
48 |
49 |
50 | def try_authenticate(users: list[UserConfig], username: str, password: str) -> tuple[bool, UserConfig | None]:
51 | """
52 | Search user with given username in a given users list, then verify the password of the user.
53 | """
54 | for user in users:
55 | if username == user.username:
56 | if pwd_context.verify(password, user.hashed_password):
57 | return (True, user)
58 | else:
59 | # user found, but incorrect password
60 | return (False, user)
61 | # no such user
62 | return (False, None)
63 |
64 |
65 | def create_access_token(user: UserConfig, expires_delta: timedelta | None = None) -> str:
66 | """
67 | Creates encoded JSON Web Token from given data and expire delta.
68 | NOTE: This function uses current server time to calculate the expiration time, make sure the server time is correct!
69 | """
70 | to_encode = dict()
71 | to_encode["sub"] = user.id
72 | to_encode["username"] = user.username
73 | to_encode["access_level"] = user.access_level
74 | # jwt.encode only takes json encodable objects so convert before that.
75 | to_encode = jsonable_encoder(to_encode)
76 | jwt_config = server_config.auth.jwt
77 | if expires_delta is None:
78 | expire = datetime.utcnow() + timedelta(seconds=jwt_config.expire_seconds)
79 | else:
80 | expire = datetime.utcnow() + expires_delta
81 | to_encode.update({"exp": expire})
82 | encoded_jwt = jwt.encode(
83 | to_encode, key=jwt_config.secret, algorithm=jwt_config.algorithm)
84 | return encoded_jwt
85 |
86 |
87 | def validate_access_token(token: Annotated[str, Depends(oauth2_scheme)]) -> TokenData:
88 | """
89 | Validates a given JWT in HTTP header and returns the data encoded in the token.
90 | If validation is unsuccessful, raises HTTP 401 Unauthorized.
91 | This function depends on OAuth2 Password Bearer scheme so if you need to add authentication to an app path, simply
92 | add this function in the Depends() as follows:
93 |
94 | fn(..., token_data: Annotated[TokenData, Depends(validate_access_token)])
95 |
96 | NOTE: This function uses current server system time to validate expiration time, so make sure the system clock is
97 | accurate.
98 | """
99 | credentials_exception = HTTPException(
100 | status_code=status.HTTP_401_UNAUTHORIZED,
101 | detail="Invalid token",
102 | headers={"WWW-Authenticate": "Bearer"},
103 | )
104 | jwt_config = server_config.auth.jwt
105 | try:
106 | payload = jwt.decode(token, jwt_config.secret,
107 | algorithms=[jwt_config.algorithm])
108 | return TokenData(**payload)
109 | except JWTError:
110 | raise credentials_exception
111 |
112 |
113 | def validate_token_ws(token: str | None) -> TokenData:
114 | """
115 | Validates a given JWT and returns the data encoded in the token.
116 | If validation is unsuccessful, raises WebSocket 1008 Policy Violation.
117 | This function also accepts a None input, because it is common to use dict.get("token") to retrive token str from a
118 | dict, and if "token" is not in the dict then it returns None and should fail to validate.
119 |
120 | NOTE: this function is only for WebSocket authentication.
121 | """
122 | ws_credentials_exception = WebSocketException(
123 | code=status.WS_1008_POLICY_VIOLATION, reason="Invalid Token")
124 | jwt_config = server_config.auth.jwt
125 | if token is None:
126 | raise ws_credentials_exception
127 | try:
128 | payload = jwt.decode(token, jwt_config.secret,
129 | algorithms=[jwt_config.algorithm])
130 | return TokenData(**payload)
131 | except JWTError:
132 | raise ws_credentials_exception
133 |
134 |
135 | def check_access_level(level: UserAccessLevel, level_required: UserAccessLevel):
136 | if level < level_required:
137 | raise HTTPException(
138 | status_code=403, detail="User with access level '{}' is not allowed to perform this operation".format(level)
139 | )
140 |
141 |
142 | def check_access_level_ws(level: UserAccessLevel, level_required: UserAccessLevel):
143 | if level < level_required:
144 | raise AccessLevelException(
145 | detail="User with access level '{}' is not allowed to perform this operation".format(
146 | level)
147 | )
148 |
--------------------------------------------------------------------------------
/backend/data_models.py:
--------------------------------------------------------------------------------
1 | # std
2 | from typing import Optional
3 | # third party
4 | from pydantic import BaseModel, Field
5 | # this project
6 | from taskgraph import TaskStatus
7 |
8 |
9 | class ServerResourceNames(BaseModel):
10 | resources: list[str]
11 |
12 |
13 | class NewProjectData(BaseModel):
14 | name: Optional[str] = Field(
15 | None, description="Name of the new project, if not specified, empty string will be used."
16 | )
17 |
18 |
19 | class DeleteProjectData(BaseModel):
20 | uuid: str
21 |
22 |
23 | class ProjectOperationReport(BaseModel):
24 | id: str
25 | name: str
26 |
27 |
28 | class NewSubTaskData(BaseModel):
29 | parent: str
30 | name: Optional[str] = Field(
31 | None, description="Name of the new task, if not specified, the task will be created without a name"
32 | )
33 | detail: Optional[str] = Field(
34 | None, description="Detail of the new task, if not specified, the task will be created without a detail"
35 | )
36 |
37 |
38 | class NewSuperTaskData(BaseModel):
39 | child: str
40 | name: Optional[str] = Field(
41 | None, description="Name of the new task, if not specified, the task will be created without a name"
42 | )
43 | detail: Optional[str] = Field(
44 | None, description="Detail of the new task, if not specified, the task will be created without a detail"
45 | )
46 |
47 |
48 | class ModifyTaskData(BaseModel):
49 | uuid: str
50 | name: Optional[str] = Field(
51 | None, description="New name of the task. If not specified, no change to name is made"
52 | )
53 | detail: Optional[str] = Field(
54 | None, description="New detail of the task. If not specified, no change to detail is made"
55 | )
56 |
57 |
58 | class UpdateTaskStatusData(BaseModel):
59 | uuid: str
60 | status: TaskStatus
61 |
62 |
63 | class RemoveTaskData(BaseModel):
64 | uuid: str
65 |
66 |
67 | class AddDependenciesData(BaseModel):
68 | uuid: str
69 | dependencies: list[str]
70 |
71 |
72 | class RemoveDependencyData(BaseModel):
73 | uuid_sub_task: str
74 | uuid_super_task: str
75 |
76 |
77 | class SnoozeTaskData(BaseModel):
78 | uuid: str
79 | snooze_until: float
80 | reason: str
81 |
82 |
83 | class OpenIssueData(BaseModel):
84 | task_uuid: str
85 | title: str
86 | description: Optional[str] = None
87 |
88 |
89 | class CloseIssueData(BaseModel):
90 | task_uuid: str
91 | issue_uuid: str
92 | reason: Optional[str] = None
93 |
94 |
95 | class ModifyIssueData(BaseModel):
96 | task_uuid: str
97 | issue_uuid: str
98 | title: Optional[str] = None
99 | description: Optional[str] = None
100 |
101 |
102 | class ReopenIssueData(BaseModel):
103 | task_uuid: str
104 | issue_uuid: str
105 |
106 |
107 | class DeleteIssueData(BaseModel):
108 | task_uuid: str
109 | issue_uuid: str
110 |
111 |
112 | class RaiseIssueData(BaseModel):
113 | task_uuid: str
114 | issue_uuid: str
115 |
116 |
117 | class ModifyProjectData(BaseModel):
118 | add_sub_task: Optional[NewSubTaskData] = Field(
119 | None, description=""
120 | )
121 | add_super_task: Optional[NewSuperTaskData] = Field(
122 | None, description=""
123 | )
124 | modify_task: Optional[ModifyTaskData] = Field(
125 | None, description=""
126 | )
127 | update_task_status: Optional[UpdateTaskStatusData] = Field(
128 | None, description=""
129 | )
130 | remove_task: Optional[RemoveTaskData] = Field(
131 | None, description=""
132 | )
133 | add_dependencies: Optional[AddDependenciesData] = Field(
134 | None, description=""
135 | )
136 | remove_dependency: Optional[RemoveDependencyData] = Field(
137 | None, description=""
138 | )
139 | snooze_task: Optional[SnoozeTaskData] = Field(
140 | None, description=""
141 | )
142 | open_issue: Optional[OpenIssueData] = Field(
143 | None, description=""
144 | )
145 | close_issue: Optional[CloseIssueData] = Field(
146 | None, description=""
147 | )
148 | modify_issue: Optional[ModifyIssueData] = Field(
149 | None, description=""
150 | )
151 | reopen_issue: Optional[ReopenIssueData] = Field(
152 | None, description=""
153 | )
154 | delete_issue: Optional[DeleteIssueData] = Field(
155 | None, description=""
156 | )
157 | raise_issue: Optional[RaiseIssueData] = Field(
158 | None, description=""
159 | )
160 |
161 |
162 | class ModifyProjectReport(BaseModel):
163 | result: str
164 |
165 |
166 | class TasksLookupReport(BaseModel):
167 | result: dict
168 |
--------------------------------------------------------------------------------
/backend/database.py:
--------------------------------------------------------------------------------
1 | # std libs
2 | import os
3 | import logging
4 | import json
5 | import asyncio
6 | import time
7 | # local packages
8 | from taskgraph import TaskGraph, TaskGraphData, TaskGraphScheduler
9 |
10 | # this package
11 | from .server_config import DatabaseConfig
12 |
13 |
14 | lg = logging.getLogger(__name__)
15 |
16 |
17 | class TaskGraphDatabaseManager():
18 | def __init__(self, taskgraph: TaskGraph, scheduler: TaskGraphScheduler,
19 | database_config: DatabaseConfig) -> None:
20 | self.tg = taskgraph
21 | self.sch = scheduler
22 | self.cfg = database_config
23 | # this hash information is used to compare if the project data on disk is
24 | # the same as the one in memory, to see if it has been changed.
25 | self.project_hashes: dict[str, str] = dict()
26 | self.manager_running = False
27 | self.eloop = asyncio.get_event_loop()
28 |
29 | def start_scheduler(self):
30 | self.manager_running = True
31 | self.eloop.create_task(self.periodic_check())
32 |
33 | def stop_scheduler(self):
34 | self.manager_running = False
35 |
36 | async def periodic_check(self):
37 | """
38 | Checks local file changes, load changes into memory, and save database periodically.
39 | NOTE that this function eventually calls methods that modifies data of TaskGraph
40 | and data on the disk, be aware of data conflicts and data corruption.
41 | This is the asynchronous version, thus no mutex is needed.
42 | """
43 | t_next_autosave = time.time() + 3600
44 | while self.manager_running:
45 | # [TODO]: check local files for auto loading
46 | # ...
47 | if time.time() > t_next_autosave:
48 | # Save database files every hour (set check_hash=True to save changes only)
49 | self.save_database(check_hash=True)
50 | t_next_autosave = t_next_autosave + 3600
51 | # release control and come back to check every second
52 | await asyncio.sleep(1)
53 |
54 | def load_projects(self, tg_data: TaskGraphData):
55 | projects_loaded: int = 0
56 | for project_id in tg_data.projects:
57 | project_name = tg_data.projects[project_id].name
58 | lg.info("Loading project: {} ({})".format(
59 | project_name, project_id))
60 | project_db_path = self.cfg.root_path + \
61 | "projects/{}.json".format(project_id)
62 | if os.path.exists(project_db_path):
63 | self.tg.load_project_from_file(project_db_path, project_id)
64 | # if loaded successful, save its hash for later use
65 | project = self.tg.projects[project_id]
66 | self.project_hashes[project_id] = project.get_data_hash()
67 | projects_loaded += 1
68 | else:
69 | lg.error(
70 | "Cannot find database file for project {}!".format(project_id))
71 | lg.error("The DB item will be removed from project.json.")
72 | lg.info("Expected to load {} projects, {} projects actually loaded.".format(
73 | len(tg_data.projects), projects_loaded))
74 |
75 | def load_database(self):
76 | root_path = self.cfg.root_path
77 | projects_db_path = root_path + "projects.json"
78 | if os.path.exists(projects_db_path):
79 | lg.info("Database file found, loading projects.")
80 | with open(projects_db_path, 'rb') as f:
81 | r = f.read().decode("utf-8")
82 | r = json.loads(r)
83 | data = TaskGraphData(**r)
84 | self.load_projects(tg_data=data)
85 | else:
86 | lg.warning("No database file found!")
87 | lg.warning(
88 | "If this is a new installation of TaskGraph, this warning can be safely ignored.")
89 | lg.warning("Creating new database file at {}".format(
90 | projects_db_path))
91 | self.tg.serialize_to_file(projects_db_path)
92 |
93 | def save_project(self, project_id: str, check_hash: bool = False):
94 | project = self.tg.projects[project_id]
95 | if check_hash and (project_id in self.project_hashes):
96 | if project.get_data_hash() == self.project_hashes[project_id]:
97 | lg.debug("Project database file for {} not changed because the project has not been modified.".format(
98 | project_id))
99 | return
100 | lg.info("Purging project metadata for {} before saving".format(project_id))
101 | project.purge_metadata()
102 | project_db_path = self.cfg.root_path + \
103 | "projects/{}.json".format(project_id)
104 | if os.path.exists(project_db_path):
105 | lg.info("Overwriting project database file at {}".format(
106 | project_db_path))
107 | else:
108 | lg.warning("Creating new project database file at {}".format(
109 | project_db_path))
110 | project.serialize_to_file(project_db_path)
111 | # if saved successfully, save its hash
112 | self.project_hashes[project_id] = project.get_data_hash()
113 |
114 | def save_projects(self, check_hash: bool = False):
115 | for project_id in self.tg.projects:
116 | self.save_project(project_id=project_id, check_hash=check_hash)
117 |
118 | def save_database(self, check_hash: bool = False):
119 | projects_db_path = self.cfg.root_path + "projects.json"
120 | if os.path.exists(projects_db_path):
121 | lg.info("Overwriting projects database file.")
122 | else:
123 | lg.warning("Creating new database file at {}".format(
124 | projects_db_path))
125 | self.save_projects(check_hash=check_hash)
126 | self.tg.serialize_to_file(projects_db_path)
127 |
128 | def delete_project(self, project_id: str):
129 | self.tg.remove_project(project_id=project_id)
130 | # SECURITY NOTICE:
131 | # execute only if project_id is trustworthy.
132 | project_db_path = self.cfg.root_path + \
133 | "projects/{}.json".format(project_id)
134 | if os.path.exists(project_db_path):
135 | lg.warning("Deleting project database file at {}".format(
136 | project_db_path))
137 | os.remove(project_db_path)
138 | else:
139 | lg.warning("Did not find project database file {} when deleting project".format(
140 | project_db_path))
141 |
142 | def save_scheduler_database(self):
143 | scheduler_db_path = self.cfg.root_path + "scheduler.json"
144 | if os.path.exists(scheduler_db_path):
145 | lg.info("Overwriting scheduler database file.")
146 | else:
147 | lg.warning("Creating new scheduler database file at {}".format(
148 | scheduler_db_path))
149 | self.sch.serialize_to_file(scheduler_db_path)
150 |
151 | def load_scheduler_database(self):
152 | root_path = self.cfg.root_path
153 | scheduler_db_path = root_path + "scheduler.json"
154 | if os.path.exists(scheduler_db_path):
155 | self.sch.load_from_file(scheduler_db_path)
156 | else:
157 | lg.warning("No scheduler database file found!")
158 | lg.warning(
159 | "If this is a new installation of TaskGraph, this warning can be safely ignored.")
160 | lg.warning("Creating new scheduler database file at {}".format(
161 | scheduler_db_path))
162 | self.sch.serialize_to_file(scheduler_db_path)
163 |
--------------------------------------------------------------------------------
/backend/main.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | """main.py:
4 |
5 | """
6 |
7 | __author__ = "Zhi Zi"
8 | __email__ = "x@zzi.io"
9 | __version__ = "20240301"
10 |
11 | # std libs
12 | import logging
13 | from typing import Annotated
14 | from json import JSONDecodeError
15 | from contextlib import asynccontextmanager
16 | # third party libs
17 | from websockets.exceptions import ConnectionClosedOK
18 | from fastapi import Depends, FastAPI, HTTPException, status, WebSocket, WebSocketDisconnect, WebSocketException
19 | from fastapi.security import OAuth2PasswordRequestForm
20 | from fastapi.middleware.cors import CORSMiddleware
21 | from pydantic import ValidationError
22 | # local libraries
23 | from taskgraph import (
24 | TaskGraph, TaskGraphData,
25 | TaskGraphProjectData, TaskStatus, TaskGraphTaskMetadataItem,
26 | TaskGraphScheduler, TaskGraphEvents, EventTaskWakeUp
27 | )
28 | # this package
29 | from .server_config import server_config, UserAccessLevel
30 | from .auth import try_authenticate, create_access_token, validate_access_token, check_access_level
31 | from .auth import Token, TokenData, AccessLevelException
32 | from .ws import WebSocketConnectionManager
33 | from .database import TaskGraphDatabaseManager
34 | from .data_models import (
35 | ServerResourceNames,
36 | NewProjectData, DeleteProjectData, ProjectOperationReport,
37 | ModifyProjectData, ModifyProjectReport,
38 | TasksLookupReport
39 | )
40 |
41 | lg = logging.getLogger(__name__)
42 |
43 |
44 | ws_mgr = WebSocketConnectionManager()
45 | tg = TaskGraph()
46 | tg_sch = TaskGraphScheduler(taskgraph=tg)
47 | db_mgr = TaskGraphDatabaseManager(
48 | taskgraph=tg, scheduler=tg_sch,
49 | database_config=server_config.database)
50 |
51 |
52 | @asynccontextmanager
53 | async def lifespan(app: FastAPI):
54 | # Before application start, load database and scheduler
55 | lg.info("Loading data from database.")
56 | db_mgr.load_database()
57 | lg.info("Loading events remaining from last session.")
58 | db_mgr.load_scheduler_database()
59 | lg.info("Starting up scheduler...")
60 | tg_sch.start_scheduler()
61 | lg.info("Starting up database manager...")
62 | db_mgr.start_scheduler()
63 | yield
64 | # Clean up resources and save database to file
65 | lg.info("Stopping database manager...")
66 | db_mgr.stop_scheduler()
67 | lg.info("Stopping scheduler...")
68 | tg_sch.stop_scheduler()
69 | lg.info("Saving remaining events to database file")
70 | db_mgr.save_scheduler_database()
71 | lg.info("Saving projects data to database file ")
72 | # Explicitly set check_hash to False to force overwriting files at exit.
73 | # This is nonsense if everything goes right, but if something went wrong
74 | # this should be able to keep some data consistency at least.
75 | db_mgr.save_database(check_hash=False)
76 |
77 |
78 | app = FastAPI(lifespan=lifespan)
79 |
80 | app.add_middleware(
81 | CORSMiddleware,
82 | allow_origins=server_config.CORS.origins,
83 | allow_credentials=server_config.CORS.allow_credentials,
84 | allow_methods=server_config.CORS.allow_methods,
85 | allow_headers=server_config.CORS.allow_headers,
86 | )
87 |
88 |
89 | @app.get("/")
90 | async def get_resource_names() -> ServerResourceNames:
91 | r = [
92 | 'token',
93 | 'projects',
94 | 'ws(ws://)']
95 | return ServerResourceNames(resources=r)
96 |
97 |
98 | @app.post("/token")
99 | async def login_for_access_token(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]) -> Token:
100 | authenticate_result, user = try_authenticate(
101 | server_config.auth.users, form_data.username, form_data.password)
102 | if (authenticate_result is False) or (user is None):
103 | # don't tell the user if it is the username or the password that is wrong.
104 | raise HTTPException(
105 | status_code=status.HTTP_401_UNAUTHORIZED,
106 | detail="Incorrect username or password",
107 | headers={"WWW-Authenticate": "Bearer"},
108 | )
109 | # authentication successful, create token
110 | access_token = create_access_token(user=user)
111 | return Token(**{"access_token": access_token, "token_type": "bearer"})
112 |
113 |
114 | @app.get("/projects")
115 | async def get_project_list(token_data: Annotated[TokenData, Depends(validate_access_token)]) -> TaskGraphData:
116 | check_access_level(token_data.access_level, UserAccessLevel.readonly)
117 | return tg.get_data()
118 |
119 |
120 | @app.post("/projects")
121 | async def create_project(project_data: NewProjectData,
122 | token_data: Annotated[TokenData, Depends(validate_access_token)]) -> ProjectOperationReport:
123 | check_access_level(token_data.access_level, UserAccessLevel.standard)
124 | project_id = tg.new_project(name=project_data.name)
125 | project_name = tg.projects[project_id].name
126 | db_mgr.save_project(project_id=project_id)
127 | lg.info("Created new project \"{}\": {}".format(project_name, project_id))
128 | return ProjectOperationReport(id=project_id, name=project_name)
129 |
130 |
131 | @app.delete("/projects")
132 | async def delete_project(project_data: DeleteProjectData,
133 | token_data: Annotated[TokenData, Depends(validate_access_token)]) -> ProjectOperationReport:
134 | check_access_level(token_data.access_level, UserAccessLevel.standard)
135 | project_id = project_data.uuid
136 | project_name = tg.projects[project_id].name
137 | db_mgr.delete_project(project_id=project_id)
138 | lg.info("Deleted project \"{}\": {}".format(project_name, project_id))
139 | return ProjectOperationReport(id=project_id, name=project_name)
140 |
141 |
142 | @app.get("/projects/{project_uuid}", response_model=TaskGraphProjectData, response_model_exclude_none=True)
143 | async def read_project(project_uuid: str,
144 | token_data: Annotated[TokenData, Depends(validate_access_token)],
145 | format: str | None = None):
146 | check_access_level(token_data.access_level, UserAccessLevel.readonly)
147 | return tg.projects[project_uuid].get_data(dag_format=format)
148 |
149 |
150 | @app.post("/projects/{project_uuid}")
151 | async def modify_project(project_uuid: str, mod_data: ModifyProjectData,
152 | token_data: Annotated[TokenData, Depends(validate_access_token)]):
153 | check_access_level(token_data.access_level, UserAccessLevel.standard)
154 | proj = tg.projects[project_uuid]
155 | if mod_data.add_sub_task is not None:
156 | meta = TaskGraphTaskMetadataItem()
157 | if mod_data.add_sub_task.name is not None:
158 | meta.name = mod_data.add_sub_task.name
159 | if mod_data.add_sub_task.detail is not None:
160 | meta.detail = mod_data.add_sub_task.detail
161 | proj.add_sub_task(mod_data.add_sub_task.parent, meta=meta)
162 | if mod_data.add_super_task is not None:
163 | meta = TaskGraphTaskMetadataItem()
164 | if mod_data.add_super_task.name is not None:
165 | meta.name = mod_data.add_super_task.name
166 | if mod_data.add_super_task.detail is not None:
167 | meta.detail = mod_data.add_super_task.detail
168 | proj.add_super_task(mod_data.add_super_task.child, meta=meta)
169 | if mod_data.modify_task is not None:
170 | meta = TaskGraphTaskMetadataItem()
171 | if mod_data.modify_task.name is not None:
172 | meta.name = mod_data.modify_task.name
173 | if mod_data.modify_task.detail is not None:
174 | meta.detail = mod_data.modify_task.detail
175 | proj.modify_task_metadata(mod_data.modify_task.uuid, meta=meta)
176 | if mod_data.update_task_status is not None:
177 | data = mod_data.update_task_status
178 | if TaskStatus.done.value == data.status.value:
179 | proj.task_done(data.uuid)
180 | if mod_data.remove_task is not None:
181 | proj.remove_task(mod_data.remove_task.uuid)
182 | if mod_data.add_dependencies is not None:
183 | for uuid in mod_data.add_dependencies.dependencies:
184 | proj.add_dependency(mod_data.add_dependencies.uuid, uuid)
185 | if mod_data.remove_dependency is not None:
186 | proj.remove_dependency(
187 | task_uuid=mod_data.remove_dependency.uuid_super_task,
188 | dep_uuid=mod_data.remove_dependency.uuid_sub_task
189 | )
190 | if mod_data.snooze_task is not None:
191 | proj.task_snooze(mod_data.snooze_task.uuid,
192 | mod_data.snooze_task.snooze_until,
193 | mod_data.snooze_task.reason)
194 | tg_sch.schedule(mod_data.snooze_task.snooze_until,
195 | TaskGraphEvents.wake_up.value,
196 | EventTaskWakeUp(
197 | project_uuid=project_uuid,
198 | task_uuid=mod_data.snooze_task.uuid
199 | ))
200 | if mod_data.open_issue is not None:
201 | proj.task_open_issue(task_uuid=mod_data.open_issue.task_uuid,
202 | title=mod_data.open_issue.title,
203 | description=mod_data.open_issue.description)
204 | if mod_data.close_issue is not None:
205 | proj.task_close_issue(task_uuid=mod_data.close_issue.task_uuid,
206 | issue_uuid=mod_data.close_issue.issue_uuid,
207 | reason=mod_data.close_issue.reason)
208 | if mod_data.modify_issue is not None:
209 | proj.task_modify_issue(task_uuid=mod_data.modify_issue.task_uuid,
210 | issue_uuid=mod_data.modify_issue.issue_uuid,
211 | title=mod_data.modify_issue.title,
212 | description=mod_data.modify_issue.description)
213 | if mod_data.reopen_issue is not None:
214 | proj.task_reopen_issue(task_uuid=mod_data.reopen_issue.task_uuid,
215 | issue_uuid=mod_data.reopen_issue.issue_uuid)
216 | if mod_data.delete_issue is not None:
217 | proj.task_delete_issue(task_uuid=mod_data.delete_issue.task_uuid,
218 | issue_uuid=mod_data.delete_issue.issue_uuid)
219 | if mod_data.raise_issue is not None:
220 | proj.task_raise_issue(task_uuid=mod_data.raise_issue.task_uuid,
221 | issue_uuid=mod_data.raise_issue.issue_uuid)
222 |
223 | return ModifyProjectReport(result="OK")
224 |
225 |
226 | @app.get("/tasks/{status}", response_model_exclude_none=True)
227 | async def get_tasks_list_by_status(
228 | status: TaskStatus,
229 | token_data: Annotated[TokenData, Depends(validate_access_token)]) -> TasksLookupReport:
230 | check_access_level(token_data.access_level, UserAccessLevel.readonly)
231 | result = tg.get_tasks_by_status(status=status)
232 | return TasksLookupReport(result=result)
233 |
234 |
235 | @app.websocket("/ws")
236 | async def ws_endpoint(websocket: WebSocket):
237 | wsid = None
238 | try:
239 | wsid = await ws_mgr.connect(websocket)
240 | await ws_mgr.run(wsid)
241 | except (WebSocketDisconnect, ConnectionClosedOK) as e:
242 | # user disconnected from client side.
243 | lg.debug(
244 | "User disconnected from WebSocket connection, normal disconnection: {}".format(e))
245 | except JSONDecodeError:
246 | # user sent non-json message, probably wrong client, disconnect right away.
247 | raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
248 | except ValidationError:
249 | # user input lack required field or malformed, report error to user and disconnect right away.
250 | await websocket.send_json({"error": "Invalid Operation"})
251 | raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
252 | except AccessLevelException:
253 | # user input is legal and the user is good, but the user does not have the permission to perform the operation.
254 | await websocket.send_json({"error": "Insufficient Access Level"})
255 | raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
256 | finally:
257 | if wsid is None:
258 | lg.info(
259 | "Client disconnected from websocket before authentication and protocol initialization finish.")
260 | else:
261 | # clear websocket and application protocol stored in manager as well as its auth info.
262 | ws_mgr.disconnect(wsid)
263 |
--------------------------------------------------------------------------------
/backend/register.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | """register.py:
4 | This script helps you to register a new user into config.
5 | """
6 |
7 | __author__ = "Zhi Zi"
8 | __email__ = "x@zzi.io"
9 | __version__ = "20231009"
10 |
11 | # std libs
12 | import uuid
13 | import os
14 | # third-party libs
15 | from passlib.context import CryptContext
16 | # this package
17 | from server_config import dump_config_to_file, load_config_from_file, UserAccessLevel, UserConfig
18 |
19 |
20 | TEMP_CONFIG_PATH = os.path.join(
21 | os.path.dirname(__file__), 'config-new-user.json')
22 | pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
23 | temp_config = load_config_from_file()
24 |
25 |
26 | def validate_username(username: str) -> bool:
27 | """
28 | Validates if a username is usable
29 | """
30 | for user in temp_config.auth.users:
31 | if username == user.username:
32 | print("Username already taken, please use another username.")
33 | return False
34 | return True
35 |
36 |
37 | def get_access_level(access_level: str) -> UserAccessLevel | None:
38 | """
39 | Validates if an access_level is defined, if so, return the enum, if not, return None.
40 | """
41 | for e in UserAccessLevel:
42 | if access_level == str(e.value):
43 | return e
44 | print("Undefined access level, please input only listed values.")
45 | return None
46 |
47 |
48 | if __name__ == "__main__":
49 | print("Registering new user into server config, Ctrl-C to cancel.")
50 | print("========================================================")
51 |
52 | print("Please input the username. The username is used to login to the system to get authentication tokens.")
53 | username = input("Username:").strip()
54 | while validate_username(username) is False:
55 | username = input("Username:").strip()
56 |
57 | print("Please input the password. Note that the password will be echoed in terminal.")
58 | password = input("Password:").strip()
59 | hashed_password = pwd_context.hash(password)
60 |
61 | possible_access_levels: str = ", ".join([str(e.value) for e in UserAccessLevel])
62 | print("Please specify the access level of the new user, possible values are {}".format(
63 | possible_access_levels))
64 | print("These values corresponds to {}".format([e for e in UserAccessLevel]))
65 | access_level = get_access_level(input("Access Level:").strip())
66 | while access_level is None:
67 | access_level = get_access_level(input("Access Level:").strip())
68 |
69 | user_id = uuid.uuid4().__str__()
70 | new_user = UserConfig(id=user_id, username=username,
71 | hashed_password=hashed_password, access_level=access_level)
72 | print("Registering a new user with the following information: ")
73 | print(new_user.model_dump_json(indent=2))
74 | ans = input("Is this OK? [y]/n")
75 | if ans == 'y' or ans == '':
76 | temp_config.auth.users.append(new_user)
77 | dump_config_to_file(temp_config, TEMP_CONFIG_PATH)
78 | print("Dumped new config to {}.".format(TEMP_CONFIG_PATH))
79 | print("Check if the new config is correct and rename it to server.config.json if everything is OK.")
80 | else:
81 | print("Aborted.")
82 |
--------------------------------------------------------------------------------
/backend/server.default.config.json:
--------------------------------------------------------------------------------
1 | {
2 | "auth": {
3 | "users": [],
4 | "jwt": {
5 | "secret": "",
6 | "algorithm": "HS256",
7 | "expire_seconds": 604800
8 | }
9 | },
10 | "CORS": {
11 | "origins": [
12 | "http://dev.taskgraph.org:8080",
13 | "https://app.taskgraph.org",
14 | "http://localhost:8080",
15 | "http://127.0.0.1:8080"
16 | ],
17 | "allow_credentials": true,
18 | "allow_methods": ["*"],
19 | "allow_headers": ["*"]
20 | },
21 | "database" :{
22 | "root_path": "data/"
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/backend/server_config.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | """server_config.py:
4 | This module defines the data model of config file for the server of this application.
5 | It also provides methods to load config from config file, or dump config to a file.
6 | """
7 |
8 | __author__ = "Zhi Zi"
9 | __email__ = "x@zzi.io"
10 | __version__ = "20231115"
11 |
12 | # std libs
13 | import os
14 | import json
15 | from enum import Enum
16 | # third party libs
17 | from pydantic import BaseModel, UUID4
18 | # this package
19 |
20 | # meta params and defaults
21 | CONFIG_PATH = os.path.join(os.path.dirname(__file__), 'server.config.json')
22 |
23 |
24 | class UserAccessLevel(int, Enum):
25 | readonly = 1
26 | standard = 2
27 | advanced = 3
28 |
29 |
30 | class UserConfig(BaseModel):
31 | id: UUID4
32 | username: str
33 | hashed_password: str
34 | access_level: UserAccessLevel
35 |
36 |
37 | class JWTConfig(BaseModel):
38 | secret: str
39 | algorithm: str
40 | expire_seconds: int
41 |
42 |
43 | class AuthConfig(BaseModel):
44 | users: list[UserConfig]
45 | jwt: JWTConfig
46 |
47 |
48 | class CORSConfig(BaseModel):
49 | origins: list[str]
50 | allow_credentials: bool
51 | allow_methods: list[str]
52 | allow_headers: list[str]
53 |
54 | class DatabaseConfig(BaseModel):
55 | root_path: str
56 |
57 | class ApplicationConfig(BaseModel):
58 | auth: AuthConfig
59 | CORS: CORSConfig
60 | database: DatabaseConfig
61 |
62 |
63 | def load_config_from_file(config_path: str = CONFIG_PATH):
64 | with open(config_path, 'r') as f:
65 | r = json.load(f)
66 | return ApplicationConfig(**r)
67 |
68 |
69 | def dump_config_to_file(config: ApplicationConfig, config_path: str = CONFIG_PATH):
70 | with open(config_path, 'w+') as f:
71 | f.write(config.model_dump_json(indent=4))
72 |
73 |
74 | server_config = load_config_from_file()
75 |
--------------------------------------------------------------------------------
/backend/ws.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | """ws.py:
4 | Websocket connection manager, parser and authenticator.
5 | """
6 |
7 | __author__ = "Zhi Zi"
8 | __email__ = "x@zzi.io"
9 | __version__ = "20231205"
10 |
11 | # std libs
12 | import logging
13 | import asyncio
14 | # third-party libs
15 | from fastapi import WebSocket
16 | from websockets.exceptions import ConnectionClosedOK
17 | # own package
18 | from .auth import validate_token_ws, TokenData, check_access_level_ws, UserAccessLevel
19 |
20 | lg = logging.getLogger(__name__)
21 |
22 |
23 | class WSApplicationProtocol():
24 | """
25 | Application protocol defined on WebSocket connection.
26 | When connected to the websocket endpoint, the initialize method is called once.
27 | Then the run method is awaited.
28 | When disconnected, the stop method is called.
29 | """
30 |
31 | def __init__(self, websocket: WebSocket, access_level: UserAccessLevel = UserAccessLevel.readonly) -> None:
32 | self.websocket = websocket
33 | self.access_level = access_level
34 |
35 | def initialize(self):
36 | lg.debug(
37 | "User connected to WebSocket, new instance of WSApplication Protocol initialized.")
38 |
39 | async def run(self):
40 | while True:
41 | received = await self.websocket.receive_json()
42 | # check user priviledge satistied for this endpoint.
43 | check_access_level_ws(self.access_level,
44 | UserAccessLevel.standard)
45 | response = {"echo": received}
46 | if "id" in received:
47 | # if user specifies a id in command, then we response with the same id to indicate task finish.
48 | response["id"] = received["id"]
49 | await self.websocket.send_json(response)
50 |
51 | def stop(self):
52 | lg.debug(
53 | "User disconnected from WebSocket, WSApplicationProtocol instance shutdown.")
54 |
55 |
56 | class WSManagerItem():
57 | def __init__(self, websocket: WebSocket, protocol: WSApplicationProtocol, token: TokenData) -> None:
58 | self.websocket = websocket
59 | self.protocol = protocol
60 | self.token = token
61 |
62 |
63 | class WebSocketConnectionManager:
64 | def __init__(self):
65 | self.wsid_i = 0
66 | self.active_connections: dict[int, WSManagerItem] = {}
67 |
68 | async def connect(self, websocket: WebSocket) -> int:
69 | """
70 | Connect to a websocket and wait for authentication message.
71 | If authentication fails, closes connection with WebSocket 1008 Policy Violation
72 | If everything is OK, initializes the websocket application protocol, then
73 | returns internal id of the websocket, which can be used to access the websocket form
74 | outside the manager later.
75 | """
76 | # register at manager, but not authorized yet.
77 | await websocket.accept()
78 | # After connection established, the first message must be an authentication message.
79 | auth_data: dict = await websocket.receive_json()
80 | token_data = validate_token_ws(auth_data.get("token"))
81 | await websocket.send_json({"auth_result": "success"})
82 | # create application protocol instance if authentication is successful.
83 | proto = WSApplicationProtocol(
84 | websocket=websocket, access_level=token_data.access_level)
85 | proto.initialize()
86 | # register this websocket at manager active_connections KV storage.
87 | self.wsid_i += 1
88 | wsid = self.wsid_i
89 | self.active_connections[wsid] = WSManagerItem(
90 | websocket=websocket, protocol=proto, token=token_data)
91 | return wsid
92 |
93 | async def run(self, wsid: int):
94 | """
95 | Run the application protocol on the websocket connection specified by wsid.
96 | """
97 | await self.active_connections[wsid].protocol.run()
98 |
99 | def disconnect(self, wsid: int):
100 | """
101 | When a websocket closes, remove it from manager.
102 | Please note that this function is intended to be called when connection is closed.
103 | But this function does NOT close the connection.
104 | """
105 | if wsid in self.active_connections:
106 | self.active_connections[wsid].protocol.stop()
107 | self.active_connections.pop(wsid)
108 | else:
109 | lg.info(
110 | "Cannot disconnect ws:{} from manager because it is not connected to this manager.".format(wsid))
111 |
112 | async def broadcast(self, message: dict):
113 | """
114 | Send a message to all authenticated connections.
115 | [NOTE]: For async programs, it is possible that .connect or .disconnect is called while awaiting
116 | the broadcast, causing the size of .active_connections dict to change, resulting in a RuntimeError.
117 | To avoid such race conditions, we copy the dict just before iteration.
118 | """
119 | for wsid in list(self.active_connections.keys()).copy():
120 | if self.active_connections[wsid].token:
121 | # only send message to authenticated clients
122 | try:
123 | await self.active_connections[wsid].websocket.send_json(message)
124 | except ConnectionClosedOK:
125 | lg.warning(
126 | "Client {} closed connection to server while broadcasting, skipping this client".format(wsid))
127 |
128 |
--------------------------------------------------------------------------------
/data/.gitignore:
--------------------------------------------------------------------------------
1 | *.json
--------------------------------------------------------------------------------
/data/projects/.gitignore:
--------------------------------------------------------------------------------
1 | *.json
--------------------------------------------------------------------------------
/data/readme.md:
--------------------------------------------------------------------------------
1 | # Data
2 |
3 | This directory is where all database files are saved.
4 | The database files are human-readable and can also be manually edited with any text editor.
5 |
6 | If you are deploying the application with a static content server, do NOT expose this directory to public web! This directory should only be visible to the backend application and the administrator.
7 |
8 | `projects.json` holds information used by TaskGraph to identify what projects are to be loaded.
9 |
10 | `projects/xxxx-xxxx...xxx.json` holds data for each project.
11 |
12 | It is recommanded that a centralized server, for example a managed server/NAS to be used to synchronize your changes to all client devices.
13 | But for users who do not have a centralized server to store their data, the database files can be directly synchronized between multiple devices, with regular software like OneDrive, rsync or Syncthing.
14 | The backend server is able to automatically monitor the data directory for any changes made by other software/human editing.
15 | However, be aware that data inconsistency may occur if conficting changes are made simutanuously on different devices.
16 |
--------------------------------------------------------------------------------
/docs/dependencies.md:
--------------------------------------------------------------------------------
1 | # Dependencies
2 |
3 | This project depends on various open source projects.
4 |
5 | ## Python Dependencies
6 |
7 | To install dependencies, install the following packages with pip
8 |
9 | networkx[all]
10 | fastapi[all]
11 | python-jose[cryptography]
12 | passlib[bcrypt]
13 |
14 | ## JavaScript Dependencies
15 |
16 | To install dependencies, install the following packages with npm
17 |
18 | cytoscape
--------------------------------------------------------------------------------
/docs/design.md:
--------------------------------------------------------------------------------
1 | # Design of TaskGraph
2 |
3 |
--------------------------------------------------------------------------------
/docs/format.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/5A/taskgraph/a68ff9afe6542da1869ef22a8c5cd79f7fd59639/docs/format.md
--------------------------------------------------------------------------------
/docs/readme.ai:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/5A/taskgraph/a68ff9afe6542da1869ef22a8c5cd79f7fd59639/docs/readme.ai
--------------------------------------------------------------------------------
/docs/screenshots/project_view.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/5A/taskgraph/a68ff9afe6542da1869ef22a8c5cd79f7fd59639/docs/screenshots/project_view.png
--------------------------------------------------------------------------------
/logging_helper/__init__.py:
--------------------------------------------------------------------------------
1 |
2 | from .formatter import TestingLogFormatter, UvicornAccessFormatter, UvicornDefaultFormatter
3 |
--------------------------------------------------------------------------------
/logging_helper/formatter.py:
--------------------------------------------------------------------------------
1 |
2 | import logging
3 |
4 | class TestingLogFormatter(logging.Formatter):
5 | reset = "\x1b[0m"
6 | color_ascname = "\x1b[38;5;99m{}" + reset
7 | color_name = "\x1b[38;5;39m{}" + reset
8 | color_debug = "\x1b[38;5;11m{}" + reset
9 | color_info = "\x1b[38;5;15m{}" + reset
10 | color_warning = "\x1b[38;5;226m{}" + reset
11 | color_error = "\x1b[38;5;196m{}" + reset
12 | color_critical = "\x1b[38;5;201m{}" + reset
13 | color_threadName = "\x1b[38;5;82m{}" + reset
14 |
15 | fmt_asctime = color_ascname.format("[%(asctime)s]")
16 | fmt_name = color_name.format("[%(name)s]")
17 | fmt_threadName = color_threadName.format("[%(threadName)s]")
18 |
19 | fmt = fmt_asctime + fmt_name + fmt_threadName
20 |
21 | FORMATS = {
22 | logging.DEBUG: fmt + color_debug.format("[%(levelname)s] %(message)s"),
23 | logging.INFO: fmt + color_info.format("[%(levelname)s] %(message)s"),
24 | logging.WARNING: fmt + color_warning.format("[%(levelname)s] %(message)s"),
25 | logging.ERROR: fmt + color_error.format("[%(levelname)s] %(message)s"),
26 | logging.CRITICAL: fmt + color_critical.format("[%(levelname)s] %(message)s"),
27 | }
28 |
29 | def format(self, record):
30 | log_fmt = self.FORMATS.get(record.levelno)
31 | formatter = logging.Formatter(log_fmt)
32 | return formatter.format(record)
33 |
34 |
35 | class UvicornDefaultFormatter(logging.Formatter):
36 | reset = "\x1b[0m"
37 | color_ascname = "\x1b[38;5;99m{}" + reset
38 | color_name = "\x1b[38;5;39m{}" + reset
39 | color_debug = "\x1b[38;5;11m{}" + reset
40 | color_info = "\x1b[38;5;15m{}" + reset
41 | color_warning = "\x1b[38;5;226m{}" + reset
42 | color_error = "\x1b[38;5;196m{}" + reset
43 | color_critical = "\x1b[38;5;201m{}" + reset
44 | color_threadName = "\x1b[38;5;82m{}" + reset
45 |
46 | fmt_asctime = color_ascname.format("[%(asctime)s]")
47 | fmt_name = color_name.format("[%(name)s]")
48 | fmt_threadName = color_threadName.format("[%(threadName)s]")
49 |
50 | fmt = fmt_asctime + fmt_name + fmt_threadName
51 |
52 | FORMATS = {
53 | logging.DEBUG: fmt + color_debug.format("[%(levelname)s] %(message)s"),
54 | logging.INFO: fmt + color_info.format("[%(levelname)s] %(message)s"),
55 | logging.WARNING: fmt + color_warning.format("[%(levelname)s] %(message)s"),
56 | logging.ERROR: fmt + color_error.format("[%(levelname)s] %(message)s"),
57 | logging.CRITICAL: fmt + color_critical.format("[%(levelname)s] %(message)s"),
58 | }
59 |
60 | def format(self, record):
61 | log_fmt = self.FORMATS.get(record.levelno)
62 | formatter = logging.Formatter(log_fmt)
63 | return formatter.format(record)
64 |
65 |
66 | class UvicornAccessFormatter(logging.Formatter):
67 | reset = "\x1b[0m"
68 | color_ascname = "\x1b[38;5;99m{}" + reset
69 | color_name = "\x1b[38;5;39m{}" + reset
70 | color_debug = "\x1b[38;5;11m{}" + reset
71 | color_info = "\x1b[38;5;15m{}" + reset
72 | color_warning = "\x1b[38;5;226m{}" + reset
73 | color_error = "\x1b[38;5;196m{}" + reset
74 | color_critical = "\x1b[38;5;201m{}" + reset
75 | color_threadName = "\x1b[38;5;82m{}" + reset
76 |
77 | fmt_asctime = color_ascname.format("[%(asctime)s]")
78 | fmt_name = color_name.format("[%(name)s]")
79 | fmt_threadName = color_threadName.format("[%(threadName)s]")
80 |
81 | fmt = fmt_asctime + fmt_name + fmt_threadName
82 |
83 | FORMATS = {
84 | logging.DEBUG: fmt + color_debug.format("[%(levelname)s] %(message)s"),
85 | logging.INFO: fmt + color_info.format("[%(levelname)s] %(message)s"),
86 | logging.WARNING: fmt + color_warning.format("[%(levelname)s] %(message)s"),
87 | logging.ERROR: fmt + color_error.format("[%(levelname)s] %(message)s"),
88 | logging.CRITICAL: fmt + color_critical.format("[%(levelname)s] %(message)s"),
89 | }
90 |
91 | def format(self, record):
92 | log_fmt = self.FORMATS.get(record.levelno)
93 | formatter = logging.Formatter(log_fmt)
94 | return formatter.format(record)
--------------------------------------------------------------------------------
/logging_helper/print_colors.py:
--------------------------------------------------------------------------------
1 | print("Testing support for 8 colors mode")
2 |
3 | print("Regular:")
4 | test_color = "\x1b[{foreground};{background}m"
5 | reset = "\x1b[0m"
6 | foreground_codes = ["30", "31", "32", "33", "34", "35", "36", "37", "39"]
7 | background_codes = ["40", "41", "42", "43", "44", "45", "46", "47", "49"]
8 | for i in foreground_codes:
9 | for j in background_codes:
10 | colored_string = test_color.format(
11 | foreground=i, background=j) + "ESC[{};{}m".format(i, j) + reset
12 | print(colored_string, end=' ')
13 | print()
14 |
15 | print("Bold:")
16 | test_color = "\x1b[1;{foreground};{background}m"
17 | reset = "\x1b[0m"
18 | foreground_codes = ["30", "31", "32", "33", "34", "35", "36", "37", "39"]
19 | background_codes = ["40", "41", "42", "43", "44", "45", "46", "47", "49"]
20 | for i in foreground_codes:
21 | for j in background_codes:
22 | colored_string = test_color.format(
23 | foreground=i, background=j) + "ESC[{};{}m".format(i, j) + reset
24 | print(colored_string, end=' ')
25 | print()
26 |
27 | print("Dimmed:")
28 | test_color = "\x1b[2;{foreground};{background}m"
29 | reset = "\x1b[0m"
30 | foreground_codes = ["30", "31", "32", "33", "34", "35", "36", "37", "39"]
31 | background_codes = ["40", "41", "42", "43", "44", "45", "46", "47", "49"]
32 | for i in foreground_codes:
33 | for j in background_codes:
34 | colored_string = test_color.format(
35 | foreground=i, background=j) + "ESC[{};{}m".format(i, j) + reset
36 | print(colored_string, end=' ')
37 | print()
38 |
39 | print("Bright:")
40 | test_color = "\x1b[2;{foreground};{background}m"
41 | reset = "\x1b[0m"
42 | foreground_codes = ["90", "91", "92", "93", "94", "95", "96", "97"]
43 | background_codes = ["100", "101", "102", "103", "104", "105", "106", "107"]
44 | for i in foreground_codes:
45 | for j in background_codes:
46 | colored_string = test_color.format(
47 | foreground=i, background=j) + "ESC[{};{}m".format(i, j) + reset
48 | print(colored_string, end=' ')
49 | print()
50 |
51 | print("Bright on regular background:")
52 | test_color = "\x1b[2;{foreground};{background}m"
53 | reset = "\x1b[0m"
54 | foreground_codes = ["90", "91", "92", "93", "94", "95", "96", "97"]
55 | background_codes = ["40", "41", "42", "43", "44", "45", "46", "47", "49"]
56 | for i in foreground_codes:
57 | for j in background_codes:
58 | colored_string = test_color.format(
59 | foreground=i, background=j) + "ESC[{};{}m".format(i, j) + reset
60 | print(colored_string, end=' ')
61 | print()
62 |
63 |
64 | print("Testing support for 256-color mode")
65 |
66 | print("Default Background")
67 | test_color = "\x1b[38;5;{}m"
68 | reset = "\x1b[0m"
69 | for i in range(256):
70 | if i == 16:
71 | print()
72 | if (i-16) % 6 == 0:
73 | print()
74 | colored_string = test_color.format(i) + str(i).rjust(4) + reset
75 | print(colored_string, end='')
76 | print()
77 |
78 | print("White Background")
79 | test_color = "\x1b[38;5;{}m\x1b[48;5;15m"
80 | reset = "\x1b[0m"
81 | for i in range(256):
82 | if i == 16:
83 | print()
84 | if (i-16) % 6 == 0:
85 | print()
86 | colored_string = test_color.format(i) + str(i).rjust(4) + reset
87 | print(colored_string, end='')
88 | print()
89 |
90 | print("Testing support for RGB colors")
91 |
92 | test_foreground_color = "\x1b[38;2;{r};{g};{b}m"
93 | test_background_color = "\x1b[48;2;{r};{g};{b}m"
94 | reset = "\x1b[0m"
95 | for i in range(0, 256, 16):
96 | for j in range(0, 256, 16):
97 | colored_string = test_foreground_color.format(
98 | r=255, g=i, b=j) + "0xff{:02x}{:02x}".format(i, j).rjust(4) + reset
99 | print()
100 |
101 | test_foreground_color = "\x1b[38;2;{r};{g};{b}m"
102 | test_background_color = "\x1b[48;2;{r};{g};{b}m"
103 | reset = "\x1b[0m"
104 | for i in range(0, 256, 16):
105 | for j in range(0, 256, 16):
106 | colored_string = test_foreground_color.format(
107 | r=i, g=255, b=j) + "0x{:02x}ff{:02x}".format(i, j).rjust(4) + reset
108 | print()
109 |
110 | test_foreground_color = "\x1b[38;2;{r};{g};{b}m"
111 | test_background_color = "\x1b[48;2;{r};{g};{b}m"
112 | reset = "\x1b[0m"
113 | for i in range(0, 256, 16):
114 | for j in range(0, 256, 16):
115 | colored_string = test_foreground_color.format(
116 | r=i, g=j, b=255) + "0x{:02x}{:02x}ff".format(i, j).rjust(4) + reset
117 | print()
118 |
119 |
120 | print("Done testing")
--------------------------------------------------------------------------------
/logging_helper/uvicorn_log.config.yaml:
--------------------------------------------------------------------------------
1 | version: 1
2 | disable_existing_loggers: False
3 | formatters:
4 | default:
5 | "()": logging_helper.UvicornDefaultFormatter
6 | # format: '[%(asctime)s][%(name)s][%(levelname)s] %(message)s'
7 | # use_colors: yes
8 | access:
9 | "()": logging_helper.UvicornAccessFormatter
10 | # format: '[%(asctime)s][%(name)s][%(levelname)s] %(message)s'
11 | # use_colors: yes
12 | handlers:
13 | default:
14 | formatter: default
15 | class: logging.StreamHandler
16 | stream: ext://sys.stderr
17 | access:
18 | formatter: access
19 | class: logging.StreamHandler
20 | stream: ext://sys.stdout
21 | loggers:
22 | uvicorn.error:
23 | level: INFO
24 | handlers:
25 | - default
26 | propagate: no
27 | uvicorn.access:
28 | level: INFO
29 | handlers:
30 | - access
31 | propagate: no
32 | root:
33 | level: INFO
34 | handlers:
35 | - default
36 | propagate: no
--------------------------------------------------------------------------------
/taskgraph/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | """taskgraph:
4 | This package defines the data model and operations of taskgraph.
5 | """
6 |
7 | __author__ = "Zhi Zi"
8 | __email__ = "x@zzi.io"
9 | __version__ = "20240301"
10 |
11 | from .taskgraph import (
12 | TaskGraph, TaskGraphProject,
13 | TaskGraphData, TaskGraphProjectData,
14 | TaskStatus, TaskGraphTaskMetadataItem,
15 | TaskGraphScheduler, TaskGraphEvents,
16 | EventTaskWakeUp,
17 | )
18 |
--------------------------------------------------------------------------------
/taskgraph/taskgraph.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | """taskgraph.py:
4 | This module defines the data model and operations of taskgraph.
5 | """
6 |
7 | __author__ = "Zhi Zi"
8 | __email__ = "x@zzi.io"
9 | __version__ = "20240301"
10 |
11 | # std libs
12 | import json
13 | import time
14 | import heapq
15 | import asyncio
16 | import logging
17 | import hashlib
18 | from typing import Mapping, Optional, Tuple
19 | from enum import Enum
20 | # third party libs
21 | import uuid
22 | import networkx as nx
23 | from pydantic import BaseModel
24 |
25 | lg = logging.getLogger(__name__)
26 |
27 |
28 | class ProjectStatus(Enum):
29 | """
30 | Projects have multiple status:
31 | Done: marks that the project has been finished
32 | Active: the project still has tasks active
33 | Snoozed: the project has tasks not done, but all available tasks are snoozed
34 | """
35 | done = "Done"
36 | active = "Active"
37 | snoozed = "Snoozed"
38 |
39 |
40 | class TaskStatus(Enum):
41 | """
42 | Tasks have multiple status:
43 | Done: marks that task has been done
44 | Active: the task is currently under working
45 | Pending: the task is waiting for its dependency to be resolved
46 | Snoozed: the task is waiting for an appropriate time to start
47 | """
48 | done = "Done"
49 | active = "Active"
50 | pending = "Pending"
51 | snoozed = "Snoozed"
52 |
53 |
54 | class IssueStatus(Enum):
55 | """
56 | Issues have multiple status:
57 | Open: issue to be resolved
58 | Closed: issue finished or cannot be finished anymore
59 | """
60 | open = "Open"
61 | closed = "Closed"
62 |
63 |
64 | class TaskGraphIssue(BaseModel):
65 | """
66 | Stores issue item data
67 | """
68 | title: str
69 | status: str
70 | description: Optional[str] = None
71 | labels: Optional[list[str]] = None
72 | close_reason: Optional[str] = None
73 | time_close: Optional[float] = None # Timestamp, unit in seconds
74 | last_modify: Optional[float] = None # Timestamp, unit in seconds
75 |
76 |
77 | class TaskGraphTaskMetadataItem(BaseModel):
78 | """
79 | Stores any metadata attached to a given task(node)
80 | """
81 | name: Optional[str] = None
82 | detail: Optional[str] = None
83 | status: Optional[str] = None
84 | wake_after: Optional[float] = None # Timestamp, unit in seconds
85 | snooze_reason: Optional[str] = None
86 | remind_after: Optional[float] = None # Timestamp, unit in seconds
87 | last_modify: Optional[float] = None # Timestamp, unit in seconds
88 | time_done: Optional[float] = None # Timestamp, unit in seconds
89 | issues: Optional[dict[str, TaskGraphIssue]] = None
90 |
91 |
92 | class ProjectStatisticsData(BaseModel):
93 | active: int = 0
94 | snoozed: int = 0
95 | pending: int = 0
96 | done: int = 0
97 | unknown: int = 0
98 |
99 |
100 | class TaskGraphProjectData(BaseModel):
101 | name: str
102 | DAG: Mapping
103 | metadata: dict[str, TaskGraphTaskMetadataItem]
104 |
105 |
106 | class TaskGraphDataItem(BaseModel):
107 | name: str
108 | status: Optional[str] = None
109 |
110 |
111 | class TaskGraphData(BaseModel):
112 | # projects: dict[uuid -> {meta: data}]
113 | projects: dict[str, TaskGraphDataItem]
114 |
115 |
116 | class TaskGraphProject:
117 | def __init__(self, name: str | None = None) -> None:
118 | if name is not None:
119 | self.name = name
120 | else:
121 | self.name = ""
122 | self.dag = nx.DiGraph()
123 | self.metadata: dict[str, TaskGraphTaskMetadataItem] = dict()
124 | self.statistics: ProjectStatisticsData = ProjectStatisticsData()
125 | self.__add_root()
126 |
127 | def __add_root(self):
128 | self.task_root = uuid.uuid4().__str__()
129 | self.metadata[self.task_root] = TaskGraphTaskMetadataItem()
130 | self.metadata[self.task_root].name = "Finish"
131 | self.metadata[self.task_root].status = "Active"
132 | self.dag.add_node(self.task_root)
133 |
134 | def __check_snoozed(self, task_uuid: str) -> bool:
135 | meta = self.metadata[task_uuid]
136 | if TaskStatus.snoozed.value == meta.status:
137 | if meta.wake_after is None:
138 | # no wake_after time set, this should not happen
139 | raise ValueError(
140 | "No wake_after is set for snoozed task {}".format(task_uuid))
141 | elif time.time() > meta.wake_after:
142 | # it is time to wake
143 | return False
144 | else:
145 | # continue snooze
146 | return True
147 | else:
148 | # currently not snoozed
149 | return False
150 |
151 | def __check_reminder(self, task_uuid: str) -> bool:
152 | meta = self.metadata[task_uuid]
153 | if meta.remind_after is None:
154 | raise ValueError(
155 | "No remind_after is set for task {}".format(task_uuid))
156 | elif time.time() > meta.remind_after:
157 | # it is time to remind
158 | return True
159 | else:
160 | # do not remind yet
161 | return False
162 |
163 | def update_statistics(self):
164 | statistics = ProjectStatisticsData()
165 | for k, v in self.metadata.items():
166 | if v.status is None:
167 | statistics.unknown += 1
168 | elif TaskStatus.done.value == v.status:
169 | statistics.done += 1
170 | elif TaskStatus.active.value == v.status:
171 | statistics.active += 1
172 | elif TaskStatus.pending.value == v.status:
173 | statistics.pending += 1
174 | elif TaskStatus.snoozed.value == v.status:
175 | statistics.snoozed += 1
176 | else:
177 | statistics.unknown += 1
178 | self.statistics = statistics
179 |
180 | def resolve_dependency(self, task_uuid: str):
181 | """
182 | Analyzes status of a given task in the project DAG to resolve dependency
183 | """
184 | # rule -1: if the task is already removed, it cannot has a status
185 | # this should normally not happen, so a warning is emitted
186 | if task_uuid not in self.metadata:
187 | lg.warning(
188 | "Task {} does not exist in current project, thus asking to resolve its dependency failed and nothing is changed.".format(task_uuid))
189 | lg.warning(
190 | "This usually happens when an action is scheduled for the task, but the task is removed manually before the action get executed.")
191 | return
192 | # rule 0: if a task is done, it is done forever unless it is revived
193 | if TaskStatus.done.value == self.metadata[task_uuid].status:
194 | return
195 | # rule 1: if task is currently snoozed, it remains snoozed until time to wake up.
196 | if self.__check_snoozed(task_uuid):
197 | return
198 | # rule 2: else: if the task is not snoozed, and if all predecessors of the task are done,
199 | # then the task becomes active
200 | # rule 3: else: if the task is not snoozed, and it still has dependency not done, it is pending.
201 | all_dependency_resolved = True
202 | for node in self.dag.predecessors(task_uuid):
203 | if TaskStatus.done.value == self.metadata[node].status:
204 | pass
205 | else:
206 | all_dependency_resolved = False
207 | break
208 | if all_dependency_resolved:
209 | self.metadata[task_uuid].status = TaskStatus.active.value
210 | else:
211 | self.metadata[task_uuid].status = TaskStatus.pending.value
212 |
213 | def add_sub_task(self, parent: str, meta: TaskGraphTaskMetadataItem | None = None) -> str:
214 | """
215 | Adds a sub-task for a given parent task, marks the new task as active and
216 | the parent task as pending.
217 | """
218 | # create node for the task and record its metadata in project.metadata
219 | task_uuid = uuid.uuid4().__str__()
220 | if meta is not None:
221 | self.metadata[task_uuid] = meta
222 | else:
223 | self.metadata[task_uuid] = TaskGraphTaskMetadataItem()
224 | self.dag.add_node(task_uuid)
225 | # add dependency for the task, the parent task will depend on the new sub-task
226 | self.add_dependency(parent, dep=task_uuid)
227 | # mark status of tasks
228 | self.metadata[task_uuid].status = TaskStatus.active.value
229 | self.metadata[task_uuid].last_modify = time.time()
230 | return task_uuid
231 |
232 | def add_super_task(self, child: str, meta: TaskGraphTaskMetadataItem | None = None) -> str:
233 | """
234 | Adds a super-task for a given child task, marks the new task as pending.
235 | """
236 | # create node for the task and record its metadata in project.metadata,
237 | task_uuid = uuid.uuid4().__str__()
238 | if meta is not None:
239 | self.metadata[task_uuid] = meta
240 | else:
241 | self.metadata[task_uuid] = TaskGraphTaskMetadataItem()
242 | self.dag.add_node(task_uuid)
243 | # add dependency for the task, the new super-task will depend on the child task
244 | self.add_dependency(task_uuid, dep=child)
245 | self.metadata[task_uuid].last_modify = time.time()
246 | return task_uuid
247 |
248 | def modify_task_metadata(self, task_uuid: str, meta: TaskGraphTaskMetadataItem):
249 | """
250 | Modify several metadata for a single task all at once.
251 | Non-empty fields in meta are updated, while None-valued fields are ignored and not modified.
252 | """
253 | if task_uuid not in self.dag.nodes:
254 | raise ValueError(
255 | "Modifying non-existent task {}!".format(task_uuid))
256 | if meta.name is not None:
257 | self.metadata[task_uuid].name = meta.name
258 | if meta.detail is not None:
259 | self.metadata[task_uuid].detail = meta.detail
260 | if meta.status is not None:
261 | self.metadata[task_uuid].status = meta.status
262 | self.metadata[task_uuid].last_modify = time.time()
263 |
264 | def add_dependency(self, task_uuid: str, dep: str):
265 | """
266 | Adds an existing task as sub-task for a given parent task.
267 | Marks the parent task as pending.
268 | """
269 | dependency_uuid = uuid.uuid4().__str__()
270 | # [TODO] add metadata to dependency
271 | # self.dependency_metadata[dependency_uuid] = TaskGraphDependencyMetadataItem()
272 | self.dag.add_edge(dep, task_uuid, id=dependency_uuid)
273 | # mark status of task
274 | self.metadata[task_uuid].status = TaskStatus.pending.value
275 |
276 | def remove_dependency(self, task_uuid: str, dep_uuid: str):
277 | """
278 | Removes dep_uuid from task_uuid's dependency
279 | """
280 | dependency_uuid = self.dag.edges[dep_uuid, task_uuid]['id']
281 | # [TODO] remove dependency from dep meta
282 | # self.dependency_metadata.pop(dependency_uuid)
283 | self.dag.remove_edge(dep_uuid, task_uuid)
284 | self.resolve_dependency(task_uuid=task_uuid)
285 |
286 | def remove_task(self, task_uuid: str):
287 | """
288 | Removes a task, checks every super-task to see if its dependency has been resolved.
289 | """
290 | # save a list of successors before removing
291 | super_tasks = self.dag.successors(task_uuid)
292 | # remove the task
293 | self.dag.remove_node(task_uuid)
294 | self.metadata.pop(task_uuid)
295 | # resolve dependencies for super-tasks after the task is removed
296 | for node in super_tasks:
297 | self.resolve_dependency(task_uuid=node)
298 |
299 | def task_done(self, task_uuid: str):
300 | """
301 | Marks a task as done, resolving its children's dependency
302 | """
303 | self.metadata[task_uuid].status = TaskStatus.done.value
304 | self.metadata[task_uuid].time_done = time.time()
305 | for node in self.dag.successors(task_uuid):
306 | self.resolve_dependency(node)
307 |
308 | def task_snooze(self, task_uuid: str, snooze_until: float, reason: Optional[str] = None):
309 | """
310 | Marks a task as snoozed, removing it from active task list and do not resolve its
311 | children's dependency.
312 | Once snooze_until (timestamp) is passed, snoozed tasks will be re-set to active
313 | in the next analyze.
314 | """
315 | self.metadata[task_uuid].status = TaskStatus.snoozed.value
316 | self.metadata[task_uuid].wake_after = snooze_until
317 | self.metadata[task_uuid].snooze_reason = reason
318 |
319 | def task_add_reminder(self, task_uuid: str, remind_after: float):
320 | """
321 | Adds a reminder to a task.
322 | Once remind_after (timestamp) is passed, user defined action will be executed on task.
323 | """
324 | self.metadata[task_uuid].remind_after = remind_after
325 |
326 | def task_open_issue(self, task_uuid: str, title: str, description: Optional[str] = None) -> str:
327 | """
328 | Adds an issue to a task, optionally provides a description, default to no label.
329 | """
330 | task_meta = self.metadata[task_uuid]
331 | if task_meta.issues is None:
332 | # create issues metadata item if it does not exist yet
333 | task_meta.issues = dict()
334 | issue_uuid = uuid.uuid4().__str__()
335 | issue_last_modify = time.time()
336 | issue_data = TaskGraphIssue(
337 | title=title,
338 | status=IssueStatus.open.value,
339 | description=description,
340 | last_modify=issue_last_modify)
341 | task_meta.issues[issue_uuid] = issue_data
342 | return issue_uuid
343 |
344 | def task_close_issue(self, task_uuid: str, issue_uuid: str, reason: Optional[str] = None):
345 | """
346 | Closes an issue, optionally provides a reason.
347 | """
348 | task_meta = self.metadata[task_uuid]
349 | if task_meta.issues is None:
350 | raise ValueError(
351 | "No issues created for task {} yet!".format(task_uuid))
352 | if issue_uuid not in task_meta.issues:
353 | raise ValueError(
354 | "issue_uuid does not exist in list, already removed or not created yet.")
355 | task_meta.issues[issue_uuid].status = IssueStatus.closed.value
356 | task_meta.issues[issue_uuid].close_reason = reason
357 | task_meta.issues[issue_uuid].time_close = time.time()
358 |
359 | def task_modify_issue(self, task_uuid: str, issue_uuid: str,
360 | title: Optional[str] = None, description: Optional[str] = None):
361 | """
362 | Modify issue data (title, description)
363 | """
364 | task_meta = self.metadata[task_uuid]
365 | if task_meta.issues is None:
366 | raise ValueError(
367 | "No issues created for task {} yet!".format(task_uuid))
368 | if issue_uuid not in task_meta.issues:
369 | raise ValueError(
370 | "issue_uuid does not exist in list, already removed or not created yet.")
371 | if title is not None:
372 | task_meta.issues[issue_uuid].title = title
373 | if description is not None:
374 | task_meta.issues[issue_uuid].description = description
375 | task_meta.issues[issue_uuid].last_modify = time.time()
376 |
377 | def task_reopen_issue(self, task_uuid: str, issue_uuid: str):
378 | """
379 | Re-opens a closed issue.
380 | """
381 | task_meta = self.metadata[task_uuid]
382 | if task_meta.issues is None:
383 | raise ValueError(
384 | "No issues created for task {} yet!".format(task_uuid))
385 | if issue_uuid not in task_meta.issues:
386 | raise ValueError(
387 | "issue_uuid does not exist in list, already removed or not created yet.")
388 | task_meta.issues[issue_uuid].status = IssueStatus.open.value
389 |
390 | def task_delete_issue(self, task_uuid: str, issue_uuid: str):
391 | """
392 | Deletes an issue (Closed issues are still saved in database, deleted issues are gone forever)
393 | """
394 | task_meta = self.metadata[task_uuid]
395 | if task_meta.issues is None:
396 | raise ValueError(
397 | "No issues created for task {} yet!".format(task_uuid))
398 | task_meta.issues.pop(issue_uuid)
399 |
400 | def task_raise_issue(self, task_uuid: str, issue_uuid: str):
401 | """
402 | Raises an issue to a sub-task of current task
403 | (Converts issue to task)
404 | """
405 | task_meta = self.metadata[task_uuid]
406 | if task_meta.issues is None:
407 | raise ValueError(
408 | "No issues created for task {} yet!".format(task_uuid))
409 | if issue_uuid not in task_meta.issues:
410 | raise ValueError(
411 | "Issue does not exist in task!")
412 | issue = task_meta.issues[issue_uuid]
413 | # Add new sub-task, map data between issue and task
414 | sub_task_meta = TaskGraphTaskMetadataItem()
415 | sub_task_meta.name = issue.title
416 | sub_task_meta.detail = issue.description
417 | self.add_sub_task(task_uuid, meta=sub_task_meta)
418 | # Remove converted issue
419 | task_meta.issues.pop(issue_uuid)
420 |
421 | def get_tasks_by_status(self, status: TaskStatus = TaskStatus.active) -> dict[str, TaskGraphTaskMetadataItem]:
422 | tasks = dict(
423 | filter(
424 | lambda item: item[1].status == status.value,
425 | self.metadata.items()
426 | ))
427 | return tasks
428 |
429 | def get_data(self, dag_format: str | None = None) -> TaskGraphProjectData:
430 | if dag_format == "cytoscape":
431 | dag_data = nx.cytoscape_data(self.dag)
432 | else:
433 | # default data format
434 | dag_data = nx.node_link_data(self.dag)
435 | data_obj = TaskGraphProjectData(
436 | name=self.name,
437 | DAG=dag_data,
438 | metadata=self.metadata
439 | )
440 | return data_obj
441 |
442 | def serialize(self) -> str:
443 | data_obj = self.get_data()
444 | return data_obj.model_dump_json(indent=2, exclude_none=True)
445 |
446 | def serialize_to_file(self, path: str):
447 | with open(path, 'wb') as f:
448 | f.write(self.serialize().encode("utf-8"))
449 |
450 | def load(self, data: TaskGraphProjectData):
451 | self.name = data.name
452 | self.dag = nx.node_link_graph(data.DAG)
453 | self.metadata = data.metadata
454 |
455 | def load_from_file(self, path: str):
456 | with open(path, 'rb') as f:
457 | r = f.read().decode("utf-8")
458 | r = json.loads(r)
459 | data = TaskGraphProjectData(**r)
460 | return self.load(data)
461 |
462 | def purge_metadata(self):
463 | """
464 | Removes unused metadata items from .metadata, by looking at each task uuid
465 | """
466 | new_metadata: dict[str, TaskGraphTaskMetadataItem] = dict()
467 | for item in self.dag.nodes:
468 | if item in self.metadata:
469 | new_metadata[item] = self.metadata[item]
470 | self.metadata = new_metadata
471 |
472 | def get_data_hash(self):
473 | """
474 | Calculates a hash from current project data, if the hashes match, then the projects
475 | should be identical.
476 | This method provides a way to compare TaskGraphProject's, which is handy for detecting
477 | data changes or handling data migration.
478 | """
479 | return hashlib.sha256(self.serialize().encode('utf-8')).hexdigest()
480 |
481 |
482 | class TaskGraph:
483 | def __init__(self) -> None:
484 | self.projects: dict[str, TaskGraphProject] = dict()
485 |
486 | def new_project(self, name: str | None = None) -> str:
487 | proj_uuid = uuid.uuid4().__str__()
488 | proj = TaskGraphProject(name=name)
489 | self.projects[proj_uuid] = proj
490 | return proj_uuid
491 |
492 | def remove_project(self, project_id: str) -> TaskGraphProject:
493 | return self.projects.pop(project_id)
494 |
495 | def get_tasks_by_status(self, status: TaskStatus = TaskStatus.active):
496 | tasks = dict()
497 | for project_uuid in self.projects:
498 | proj = self.projects[project_uuid]
499 | tasks[project_uuid] = proj.get_tasks_by_status(status=status)
500 | return tasks
501 |
502 | def get_data(self) -> TaskGraphData:
503 | data = {}
504 | for project_id in self.projects:
505 | proj = self.projects[project_id]
506 | proj.update_statistics()
507 | status = ProjectStatus.done.value
508 | if proj.statistics.active > 0:
509 | # active task present, project is active
510 | status = ProjectStatus.active.value
511 | elif proj.statistics.snoozed > 0:
512 | # no active task, but at least 1 task is snoozed
513 | status = ProjectStatus.snoozed.value
514 | else:
515 | # no active or snoozed, project finished.
516 | pass
517 | data_obj = TaskGraphDataItem(
518 | name=proj.name,
519 | status=status
520 | )
521 | data[project_id] = data_obj
522 | return TaskGraphData(projects=data)
523 |
524 | def serialize(self) -> str:
525 | data_obj = self.get_data()
526 | return data_obj.model_dump_json(indent=2, exclude_none=True)
527 |
528 | def serialize_to_file(self, file_path: str):
529 | with open(file_path, 'wb') as f:
530 | f.write(self.serialize().encode("utf-8"))
531 |
532 | def load_project_from_file(self, file_path: str, project_id: str | None = None) -> str:
533 | proj = TaskGraphProject()
534 | proj.load_from_file(file_path)
535 | if project_id is not None:
536 | proj_uuid = project_id
537 | else:
538 | proj_uuid = uuid.uuid4().__str__()
539 | self.projects[proj_uuid] = proj
540 | return proj_uuid
541 |
542 |
543 | class TaskGraphEvents(Enum):
544 | wake_up = "wake_up"
545 |
546 |
547 | class EventTaskWakeUp(BaseModel):
548 | project_uuid: str
549 | task_uuid: str
550 |
551 |
552 | class TaskGraphSchedulerData(BaseModel):
553 | event_heap: list[Tuple[float, str, str]]
554 | event_map: dict[str, EventTaskWakeUp]
555 |
556 |
557 | class TaskGraphScheduler:
558 | def __init__(self, taskgraph: TaskGraph) -> None:
559 | """
560 | Scheduler of all TaskGraph events, regardless of task or project.
561 | event_heap: min heap used to sort events, stored as (timestamp, event_uuid, event_type)
562 | event_map: key-value storage to store additional event data, as {event_uuid: EventData}
563 | """
564 | self.tg = taskgraph
565 | self.event_heap: list[Tuple[float, str, str]] = []
566 | self.event_map: dict[str, EventTaskWakeUp] = dict()
567 | self.scheduler_running = False
568 | self.eloop = asyncio.get_event_loop()
569 |
570 | def start_scheduler(self):
571 | self.scheduler_running = True
572 | self.eloop.create_task(self.periodic_check())
573 |
574 | def stop_scheduler(self):
575 | self.scheduler_running = False
576 |
577 | def get_data(self) -> TaskGraphSchedulerData:
578 | data_obj = TaskGraphSchedulerData(
579 | event_heap=self.event_heap,
580 | event_map=self.event_map
581 | )
582 | return data_obj
583 |
584 | def serialize(self) -> str:
585 | data_obj = self.get_data()
586 | return data_obj.model_dump_json(indent=2, exclude_none=True)
587 |
588 | def serialize_to_file(self, file_path: str):
589 | with open(file_path, 'wb') as f:
590 | f.write(self.serialize().encode("utf-8"))
591 |
592 | def load(self, data: TaskGraphSchedulerData):
593 | self.event_heap = data.event_heap
594 | self.event_map = data.event_map
595 |
596 | def load_from_file(self, path: str):
597 | with open(path, 'rb') as f:
598 | r = f.read().decode("utf-8")
599 | r = json.loads(r)
600 | data = TaskGraphSchedulerData(**r)
601 | return self.load(data)
602 |
603 | def schedule(self, timestamp: float, event_type: str,
604 | event_data: EventTaskWakeUp):
605 | event_uuid = uuid.uuid4().__str__()
606 | heapq.heappush(self.event_heap, (timestamp, event_uuid, event_type))
607 | self.event_map[event_uuid] = event_data
608 |
609 | async def periodic_check(self):
610 | """
611 | Checks event heap constantly to trigger events.
612 | NOTE that this function eventually calls methods that modifies data of TaskGraph,
613 | be aware of data conflicts.
614 | This is the asynchronous version, thus no mutex is needed.
615 | """
616 | while self.scheduler_running:
617 | while (len(self.event_heap) > 0) and self.scheduler_running:
618 | # process all time-up events in a loop
619 | first_event = self.event_heap[0]
620 | t_event = first_event[0]
621 | if time.time() > t_event:
622 | # trig event and remove it from event heap / event map
623 | event_uuid = first_event[1]
624 | event_type = first_event[2]
625 | self.__process_event(
626 | event_uuid=event_uuid, event_type=event_type)
627 | heapq.heappop(self.event_heap)
628 | self.event_map.pop(event_uuid)
629 | else:
630 | # no more time-up event, go to outer loop and wait for nexts
631 | break
632 | # all data operation is done, hand out control for a short period of time
633 | # to avoid blocking the main thread for too long in case of too many events.
634 | await asyncio.sleep(0.1)
635 | # all time-up events processed,
636 | # release control and come back to check events every second
637 | await asyncio.sleep(1)
638 |
639 | def __process_event(self, event_uuid: str, event_type: str):
640 | if TaskGraphEvents.wake_up.value == event_type:
641 | event_data: EventTaskWakeUp = self.event_map[event_uuid]
642 | project_uuid = event_data.project_uuid
643 | task_uuid = event_data.task_uuid
644 | # we need to check if the project and the task still exist before
645 | # processing wake_up event
646 | if project_uuid not in self.tg.projects:
647 | lg.warning("When processing wake_up event for task {} for project {}, the project does not exist in current database. The project is probably removed before this action.".format(
648 | task_uuid, project_uuid))
649 | return
650 | target_project = self.tg.projects[project_uuid]
651 | if task_uuid not in target_project.metadata:
652 | lg.warning("When processing wake_up event for task {} in project {}, the task does not exist in the project. The task is probably removed before this action.".format(
653 | task_uuid, project_uuid))
654 | return
655 | # check dependency to determine if it should be pending or active.
656 | # resolve_dependency will check wake_after metadata attached to the
657 | # task again to determine if it is really time to wake up, because
658 | # the user may set another time to snooze until, and the previous
659 | # event did not get removed. (Which means EventWakeUp only tries to
660 | # wake up the task, but does not guarantee that the task get woke up)
661 | target_project.resolve_dependency(task_uuid=task_uuid)
662 |
--------------------------------------------------------------------------------
/tests/.gitignore:
--------------------------------------------------------------------------------
1 | # temporary files generated during testing
2 | test_taskgraph.json
3 | test_taskgraph_project.json
4 |
--------------------------------------------------------------------------------
/tests/draw_project.py:
--------------------------------------------------------------------------------
1 | import matplotlib.pyplot as plt
2 | import networkx as nx
3 |
4 | from taskgraph import TaskGraphProject
5 |
6 | proj = TaskGraphProject()
7 | task1 = proj.add_sub_task(proj.task_root)
8 | task2 = proj.add_sub_task(proj.task_root)
9 | task3 = proj.add_sub_task(proj.task_root)
10 | task4 = proj.add_sub_task(task1)
11 | task5 = proj.add_sub_task(task2)
12 | proj.add_dependency(task5, task1)
13 |
14 | for layer, nodes in enumerate(nx.topological_generations(proj.dag)):
15 | # `multipartite_layout` expects the layer as a node attribute, so add the
16 | # numeric layer value as a node attribute
17 | for node in nodes:
18 | proj.dag.nodes[node]["layer"] = layer
19 |
20 | # get lables
21 | node_labels = dict()
22 | for node in proj.dag.nodes:
23 | if "Name" in proj.metadata[node]:
24 | node_labels[node] = proj.metadata[node]["Name"]
25 | else:
26 | node_labels[node] = ""
27 |
28 | # Compute the multipartite_layout using the "layer" node attribute
29 | pos = nx.multipartite_layout(proj.dag, subset_key="layer")
30 |
31 | fig, ax = plt.subplots()
32 | nx.draw_networkx(proj.dag, pos=pos, ax=ax, labels=node_labels)
33 | ax.set_title("DAG layout in topological order")
34 | fig.tight_layout()
35 | plt.show()
36 |
--------------------------------------------------------------------------------
/tests/test_taskgraph.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | """test_taskgraph.py:
4 | Integration test for taskgraph core library
5 | """
6 |
7 | __author__ = "Zhi Zi"
8 | __email__ = "x@zzi.io"
9 | __version__ = "20240301"
10 |
11 | # std libs
12 | import unittest
13 | import logging
14 | import time
15 | import os
16 | # project packages
17 | from logging_helper import TestingLogFormatter
18 | # package to be tested
19 | from taskgraph import TaskGraphProject, TaskGraph
20 |
21 | # configure root logger to output all logs to stdout
22 | lg = logging.getLogger()
23 | lg.setLevel(logging.DEBUG)
24 | ch = logging.StreamHandler()
25 | ch.setLevel(logging.DEBUG)
26 | ch.setFormatter(TestingLogFormatter())
27 | lg.addHandler(ch)
28 |
29 | # configure logger for this module.
30 | lg = logging.getLogger(__name__)
31 |
32 | # setup temporary file path for testing
33 | TEMPORARY_FILE_PATH = os.path.dirname(__file__)
34 |
35 |
36 | class TestTaskGraph(unittest.TestCase):
37 | @classmethod
38 | def setUpClass(cls) -> None:
39 | lg.info("Test started")
40 | # cls.tg = TaskGraph()
41 |
42 | @classmethod
43 | def tearDownClass(cls):
44 | lg.info("Test ended.")
45 |
46 | def test_task_graph(self):
47 | lg.info("Testing TaskGraph Core Library")
48 | self.tg = TaskGraph()
49 | lg.info("Constructing a test project")
50 | proj1 = self.tg.new_project("Test Project")
51 | proj = self.tg.projects[proj1]
52 | task1 = proj.add_sub_task(proj.task_root)
53 | task2 = proj.add_sub_task(proj.task_root)
54 | task3 = proj.add_sub_task(proj.task_root)
55 | task4 = proj.add_sub_task(task1)
56 | task5 = proj.add_sub_task(task4)
57 | task6 = proj.add_sub_task(task2)
58 | proj.add_dependency(task6, dep=task3)
59 | lg.info("Saving project to temporary file")
60 | to_save = proj.serialize()
61 | lg.info(to_save)
62 | proj_save_path = os.path.join(TEMPORARY_FILE_PATH, "test_taskgraph_project.json")
63 | with open(proj_save_path, 'w') as f:
64 | f.write(to_save)
65 | lg.info("Loading back")
66 | proj = TaskGraphProject()
67 | proj.load_from_file(proj_save_path)
68 | lg.info("Loaded: ")
69 | lg.info(proj.serialize())
70 | lg.info("Testing project export")
71 | self.tg.new_project(name="Test Project 2")
72 | to_save = self.tg.serialize()
73 | lg.info((to_save))
74 | tg_save_path = os.path.join(TEMPORARY_FILE_PATH, "test_taskgraph.json")
75 | with open(tg_save_path, 'w') as f:
76 | f.write(to_save)
77 | lg.info("Testing load project from file")
78 | self.tg.load_project_from_file(proj_save_path)
79 | lg.info(self.tg.serialize())
80 |
81 |
82 |
--------------------------------------------------------------------------------