| 1 |
# This Source Code Form is subject to the terms of the Mozilla Public |
| 2 |
# License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 |
# file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 4 |
|
| 5 |
from dataclasses import dataclass |
| 6 |
from typing import Dict |
| 7 |
|
| 8 |
from .graph import Graph |
| 9 |
from .task import Task |
| 10 |
|
| 11 |
|
| 12 |
@dataclass(frozen=True) |
| 13 |
class TaskGraph: |
| 14 |
""" |
| 15 |
Representation of a task graph. |
| 16 |
|
| 17 |
A task graph is a combination of a Graph and a dictionary of tasks indexed |
| 18 |
by label. TaskGraph instances should be treated as immutable. |
| 19 |
|
| 20 |
In the graph, tasks are said to "link to" their dependencies. Whereas |
| 21 |
tasks are "linked from" their dependents. |
| 22 |
""" |
| 23 |
|
| 24 |
tasks: Dict[str, Task] |
| 25 |
graph: Graph |
| 26 |
|
| 27 |
def __post_init__(self): |
| 28 |
assert set(self.tasks) == self.graph.nodes |
| 29 |
|
| 30 |
def for_each_task(self, f, *args, **kwargs): |
| 31 |
for task_label in self.graph.visit_postorder(): |
| 32 |
task = self.tasks[task_label] |
| 33 |
f(task, self, *args, **kwargs) |
| 34 |
|
| 35 |
def __getitem__(self, label): |
| 36 |
"Get a task by label" |
| 37 |
return self.tasks[label] |
| 38 |
|
| 39 |
def __contains__(self, label): |
| 40 |
return label in self.tasks |
| 41 |
|
| 42 |
def __iter__(self): |
| 43 |
"Iterate over tasks in undefined order" |
| 44 |
return iter(self.tasks.values()) # type: ignore |
| 45 |
|
| 46 |
def to_json(self): |
| 47 |
"Return a JSON-able object representing the task graph, as documented" |
| 48 |
named_links_dict = self.graph.named_links_dict() |
| 49 |
# this dictionary may be keyed by label or by taskid, so let's just call it 'key' |
| 50 |
tasks = {} |
| 51 |
for key in self.graph.visit_postorder(): |
| 52 |
tasks[key] = self.tasks[key].to_json() |
| 53 |
# overwrite dependencies with the information in the taskgraph's edges. |
| 54 |
tasks[key]["dependencies"] = named_links_dict.get(key, {}) |
| 55 |
return tasks |
| 56 |
|
| 57 |
@classmethod |
| 58 |
def from_json(cls, tasks_dict): |
| 59 |
""" |
| 60 |
This code is used to generate the a TaskGraph using a dictionary |
| 61 |
which is representative of the TaskGraph. |
| 62 |
""" |
| 63 |
tasks = {} |
| 64 |
edges = set() |
| 65 |
for key, value in tasks_dict.items(): |
| 66 |
tasks[key] = Task.from_json(value) |
| 67 |
if "task_id" in value: |
| 68 |
tasks[key].task_id = value["task_id"] |
| 69 |
for depname, dep in value["dependencies"].items(): |
| 70 |
edges.add((key, dep, depname)) |
| 71 |
task_graph = cls(tasks, Graph(set(tasks), edges)) # type: ignore |
| 72 |
return tasks, task_graph |