authentik.lib.sync.models

 1from datetime import datetime
 2from uuid import uuid4
 3
 4from django.db import models
 5from django_dramatiq_postgres.models import TaskState
 6from dramatiq.broker import get_broker
 7from dramatiq.message import Message
 8
 9from authentik.lib.models import InternallyManagedMixin
10from authentik.tasks.models import Task, TaskStatus
11
12
13class SyncStatus(models.TextChoices):
14    RUNNING = TaskStatus.RUNNING
15    ERROR = TaskStatus.ERROR
16    WARNING = TaskStatus.WARNING
17    DONE = TaskStatus.DONE
18
19
20class Sync(InternallyManagedMixin, models.Model):
21    uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
22
23    # Must be defined by subclasses with a through model
24    # tasks = models.ManyToManyField(Task, related_name="+")
25    tasks: models.ManyToManyField
26
27    started_at = models.DateTimeField(auto_now_add=True)
28
29    class Meta:
30        abstract = True
31
32    @classmethod
33    def cleanup(cls) -> int:
34        count = cls.objects.filter(tasks__count=0).delete()[0]
35        count += cls.objects.exclude(pk__in=cls.objects.order_by("-started_at")[:20]).delete()[0]
36        return count
37
38    @property
39    def done(self) -> bool:
40        return not any(
41            state not in (TaskState.DONE, TaskState.REJECTED)
42            for state in self.tasks.values_list("state", flat=True)
43        )
44
45    @property
46    def finished_at(self) -> datetime | None:
47        last_task = self.tasks.order_by("-mtime").first()
48        if last_task:
49            return last_task.mtime
50        return None
51
52    @property
53    def status(self) -> SyncStatus:
54        states = self.tasks.values_list("aggregated_status", flat=True)
55        if any(
56            state
57            in (
58                TaskStatus.WAITING_FOR_DEPENDENCIES,
59                TaskStatus.QUEUED,
60                TaskStatus.CONSUMED,
61                TaskStatus.PREPROCESS,
62                TaskStatus.RUNNING,
63                TaskStatus.POSTPROCESS,
64            )
65            for state in states
66        ):
67            return SyncStatus.RUNNING
68        if any(
69            state
70            in (
71                TaskStatus.REJECTED,
72                TaskStatus.ERROR,
73            )
74            for state in states
75        ):
76            return SyncStatus.ERROR
77        if any(state == TaskStatus.WARNING for state in states):
78            return SyncStatus.WARNING
79        return SyncStatus.DONE
80
81    def enqueue(self, messages: list[Message], existing_tasks_as_dependencies: bool = True) -> None:
82        broker = get_broker()
83        if existing_tasks_as_dependencies:
84            dependencies = self.tasks.values_list("pk", flat=True)
85            for message in messages:
86                message.options.setdefault("dependencies", []).extend(dependencies)
87        new_tasks: list[Task] = []
88        for message in messages:
89            new_message = broker.enqueue(message)
90            new_tasks.append(new_message.options["task"])
91        self.tasks.add(*new_tasks)
class SyncStatus(django.db.models.enums.TextChoices):
14class SyncStatus(models.TextChoices):
15    RUNNING = TaskStatus.RUNNING
16    ERROR = TaskStatus.ERROR
17    WARNING = TaskStatus.WARNING
18    DONE = TaskStatus.DONE

Class for creating enumerated string choices.

RUNNING = SyncStatus.RUNNING
WARNING = SyncStatus.WARNING
class Sync(authentik.lib.models.InternallyManagedMixin, django.db.models.base.Model):
21class Sync(InternallyManagedMixin, models.Model):
22    uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
23
24    # Must be defined by subclasses with a through model
25    # tasks = models.ManyToManyField(Task, related_name="+")
26    tasks: models.ManyToManyField
27
28    started_at = models.DateTimeField(auto_now_add=True)
29
30    class Meta:
31        abstract = True
32
33    @classmethod
34    def cleanup(cls) -> int:
35        count = cls.objects.filter(tasks__count=0).delete()[0]
36        count += cls.objects.exclude(pk__in=cls.objects.order_by("-started_at")[:20]).delete()[0]
37        return count
38
39    @property
40    def done(self) -> bool:
41        return not any(
42            state not in (TaskState.DONE, TaskState.REJECTED)
43            for state in self.tasks.values_list("state", flat=True)
44        )
45
46    @property
47    def finished_at(self) -> datetime | None:
48        last_task = self.tasks.order_by("-mtime").first()
49        if last_task:
50            return last_task.mtime
51        return None
52
53    @property
54    def status(self) -> SyncStatus:
55        states = self.tasks.values_list("aggregated_status", flat=True)
56        if any(
57            state
58            in (
59                TaskStatus.WAITING_FOR_DEPENDENCIES,
60                TaskStatus.QUEUED,
61                TaskStatus.CONSUMED,
62                TaskStatus.PREPROCESS,
63                TaskStatus.RUNNING,
64                TaskStatus.POSTPROCESS,
65            )
66            for state in states
67        ):
68            return SyncStatus.RUNNING
69        if any(
70            state
71            in (
72                TaskStatus.REJECTED,
73                TaskStatus.ERROR,
74            )
75            for state in states
76        ):
77            return SyncStatus.ERROR
78        if any(state == TaskStatus.WARNING for state in states):
79            return SyncStatus.WARNING
80        return SyncStatus.DONE
81
82    def enqueue(self, messages: list[Message], existing_tasks_as_dependencies: bool = True) -> None:
83        broker = get_broker()
84        if existing_tasks_as_dependencies:
85            dependencies = self.tasks.values_list("pk", flat=True)
86            for message in messages:
87                message.options.setdefault("dependencies", []).extend(dependencies)
88        new_tasks: list[Task] = []
89        for message in messages:
90            new_message = broker.enqueue(message)
91            new_tasks.append(new_message.options["task"])
92        self.tasks.add(*new_tasks)

Mixin for models that should _not_ be manageable via blueprint.

def uuid(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

tasks: django.db.models.fields.related.ManyToManyField
def started_at(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

@classmethod
def cleanup(cls) -> int:
33    @classmethod
34    def cleanup(cls) -> int:
35        count = cls.objects.filter(tasks__count=0).delete()[0]
36        count += cls.objects.exclude(pk__in=cls.objects.order_by("-started_at")[:20]).delete()[0]
37        return count
done: bool
39    @property
40    def done(self) -> bool:
41        return not any(
42            state not in (TaskState.DONE, TaskState.REJECTED)
43            for state in self.tasks.values_list("state", flat=True)
44        )
finished_at: datetime.datetime | None
46    @property
47    def finished_at(self) -> datetime | None:
48        last_task = self.tasks.order_by("-mtime").first()
49        if last_task:
50            return last_task.mtime
51        return None
status: SyncStatus
53    @property
54    def status(self) -> SyncStatus:
55        states = self.tasks.values_list("aggregated_status", flat=True)
56        if any(
57            state
58            in (
59                TaskStatus.WAITING_FOR_DEPENDENCIES,
60                TaskStatus.QUEUED,
61                TaskStatus.CONSUMED,
62                TaskStatus.PREPROCESS,
63                TaskStatus.RUNNING,
64                TaskStatus.POSTPROCESS,
65            )
66            for state in states
67        ):
68            return SyncStatus.RUNNING
69        if any(
70            state
71            in (
72                TaskStatus.REJECTED,
73                TaskStatus.ERROR,
74            )
75            for state in states
76        ):
77            return SyncStatus.ERROR
78        if any(state == TaskStatus.WARNING for state in states):
79            return SyncStatus.WARNING
80        return SyncStatus.DONE
def enqueue( self, messages: list[dramatiq.message.Message], existing_tasks_as_dependencies: bool = True) -> None:
82    def enqueue(self, messages: list[Message], existing_tasks_as_dependencies: bool = True) -> None:
83        broker = get_broker()
84        if existing_tasks_as_dependencies:
85            dependencies = self.tasks.values_list("pk", flat=True)
86            for message in messages:
87                message.options.setdefault("dependencies", []).extend(dependencies)
88        new_tasks: list[Task] = []
89        for message in messages:
90            new_message = broker.enqueue(message)
91            new_tasks.append(new_message.options["task"])
92        self.tasks.add(*new_tasks)
def get_next_by_started_at(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_previous_by_started_at(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

class Sync.Meta:
30    class Meta:
31        abstract = True
abstract = False