2022-11-09 06:06:29 +00:00
|
|
|
import datetime
|
2022-11-12 05:02:43 +00:00
|
|
|
import pprint
|
2022-11-10 05:29:33 +00:00
|
|
|
import traceback
|
2022-12-05 17:38:37 +00:00
|
|
|
from typing import ClassVar, cast
|
2022-11-09 06:06:29 +00:00
|
|
|
|
|
|
|
from asgiref.sync import sync_to_async
|
|
|
|
from django.db import models, transaction
|
|
|
|
from django.utils import timezone
|
|
|
|
from django.utils.functional import classproperty
|
|
|
|
|
2022-11-20 21:20:28 +00:00
|
|
|
from core import exceptions
|
2022-11-10 06:48:31 +00:00
|
|
|
from stator.graph import State, StateGraph
|
2022-11-09 06:06:29 +00:00
|
|
|
|
|
|
|
|
|
|
|
class StateField(models.CharField):
|
|
|
|
"""
|
|
|
|
A special field that automatically gets choices from a state graph
|
|
|
|
"""
|
|
|
|
|
2022-12-05 17:38:37 +00:00
|
|
|
def __init__(self, graph: type[StateGraph], **kwargs):
|
2022-11-09 06:06:29 +00:00
|
|
|
# Sensible default for state length
|
|
|
|
kwargs.setdefault("max_length", 100)
|
|
|
|
# Add choices and initial
|
|
|
|
self.graph = graph
|
|
|
|
kwargs["choices"] = self.graph.choices
|
|
|
|
kwargs["default"] = self.graph.initial_state.name
|
|
|
|
super().__init__(**kwargs)
|
|
|
|
|
|
|
|
def deconstruct(self):
|
|
|
|
name, path, args, kwargs = super().deconstruct()
|
|
|
|
kwargs["graph"] = self.graph
|
|
|
|
return name, path, args, kwargs
|
|
|
|
|
|
|
|
def get_prep_value(self, value):
|
|
|
|
if isinstance(value, State):
|
|
|
|
return value.name
|
|
|
|
return value
|
|
|
|
|
|
|
|
|
|
|
|
class StatorModel(models.Model):
|
|
|
|
"""
|
|
|
|
A model base class that has a state machine backing it, with tasks to work
|
|
|
|
out when to move the state to the next one.
|
|
|
|
|
|
|
|
You need to provide a "state" field as an instance of StateField on the
|
|
|
|
concrete model yourself.
|
|
|
|
"""
|
|
|
|
|
2022-11-12 06:04:43 +00:00
|
|
|
# If this row is up for transition attempts (which it always is on creation!)
|
|
|
|
state_ready = models.BooleanField(default=True)
|
2022-11-10 05:29:33 +00:00
|
|
|
|
2022-11-09 06:06:29 +00:00
|
|
|
# When the state last actually changed, or the date of instance creation
|
|
|
|
state_changed = models.DateTimeField(auto_now_add=True)
|
|
|
|
|
|
|
|
# When the last state change for the current state was attempted
|
|
|
|
# (and not successful, as this is cleared on transition)
|
|
|
|
state_attempted = models.DateTimeField(blank=True, null=True)
|
|
|
|
|
2022-11-10 05:29:33 +00:00
|
|
|
# If a lock is out on this row, when it is locked until
|
|
|
|
# (we don't identify the lock owner, as there's no heartbeats)
|
|
|
|
state_locked_until = models.DateTimeField(null=True, blank=True)
|
|
|
|
|
|
|
|
# Collection of subclasses of us
|
2022-12-05 17:38:37 +00:00
|
|
|
subclasses: ClassVar[list[type["StatorModel"]]] = []
|
2022-11-10 05:29:33 +00:00
|
|
|
|
2022-11-09 06:06:29 +00:00
|
|
|
class Meta:
|
|
|
|
abstract = True
|
|
|
|
|
2022-11-10 05:29:33 +00:00
|
|
|
def __init_subclass__(cls) -> None:
|
|
|
|
if cls is not StatorModel:
|
|
|
|
cls.subclasses.append(cls)
|
|
|
|
|
|
|
|
@classproperty
|
2022-12-05 17:38:37 +00:00
|
|
|
def state_graph(cls) -> type[StateGraph]:
|
2022-11-10 05:29:33 +00:00
|
|
|
return cls._meta.get_field("state").graph
|
|
|
|
|
2022-11-28 00:05:31 +00:00
|
|
|
@property
|
|
|
|
def state_age(self) -> int:
|
|
|
|
return (timezone.now() - self.state_changed).total_seconds()
|
|
|
|
|
2022-11-09 06:06:29 +00:00
|
|
|
@classmethod
|
2022-11-10 05:29:33 +00:00
|
|
|
async def atransition_schedule_due(cls, now=None) -> models.QuerySet:
|
2022-11-09 06:06:29 +00:00
|
|
|
"""
|
|
|
|
Finds instances of this model that need to run and schedule them.
|
|
|
|
"""
|
|
|
|
q = models.Q()
|
2022-11-10 05:29:33 +00:00
|
|
|
for state in cls.state_graph.states.values():
|
|
|
|
state = cast(State, state)
|
2022-11-11 06:42:43 +00:00
|
|
|
if not state.externally_progressed:
|
2022-11-10 05:29:33 +00:00
|
|
|
q = q | models.Q(
|
|
|
|
(
|
|
|
|
models.Q(
|
|
|
|
state_attempted__lte=timezone.now()
|
2022-11-10 06:48:31 +00:00
|
|
|
- datetime.timedelta(
|
|
|
|
seconds=cast(float, state.try_interval)
|
|
|
|
)
|
2022-11-10 05:29:33 +00:00
|
|
|
)
|
|
|
|
| models.Q(state_attempted__isnull=True)
|
|
|
|
),
|
|
|
|
state=state.name,
|
|
|
|
)
|
|
|
|
await cls.objects.filter(q).aupdate(state_ready=True)
|
2022-11-09 06:06:29 +00:00
|
|
|
|
2022-11-10 05:29:33 +00:00
|
|
|
@classmethod
|
|
|
|
def transition_get_with_lock(
|
|
|
|
cls, number: int, lock_expiry: datetime.datetime
|
2022-12-05 17:38:37 +00:00
|
|
|
) -> list["StatorModel"]:
|
2022-11-10 05:29:33 +00:00
|
|
|
"""
|
|
|
|
Returns up to `number` tasks for execution, having locked them.
|
|
|
|
"""
|
|
|
|
with transaction.atomic():
|
|
|
|
selected = list(
|
2022-11-16 01:30:30 +00:00
|
|
|
cls.objects.filter(
|
|
|
|
state_locked_until__isnull=True,
|
|
|
|
state_ready=True,
|
|
|
|
state__in=cls.state_graph.automatic_states,
|
|
|
|
)[:number].select_for_update()
|
2022-11-10 05:29:33 +00:00
|
|
|
)
|
|
|
|
cls.objects.filter(pk__in=[i.pk for i in selected]).update(
|
2022-11-10 06:48:31 +00:00
|
|
|
state_locked_until=lock_expiry
|
2022-11-10 05:29:33 +00:00
|
|
|
)
|
|
|
|
return selected
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
async def atransition_get_with_lock(
|
|
|
|
cls, number: int, lock_expiry: datetime.datetime
|
2022-12-05 17:38:37 +00:00
|
|
|
) -> list["StatorModel"]:
|
2022-11-10 05:29:33 +00:00
|
|
|
return await sync_to_async(cls.transition_get_with_lock)(number, lock_expiry)
|
2022-11-09 06:06:29 +00:00
|
|
|
|
2022-11-10 05:29:33 +00:00
|
|
|
@classmethod
|
|
|
|
async def atransition_clean_locks(cls):
|
|
|
|
await cls.objects.filter(state_locked_until__lte=timezone.now()).aupdate(
|
|
|
|
state_locked_until=None
|
|
|
|
)
|
|
|
|
|
|
|
|
def transition_schedule(self):
|
2022-11-09 06:06:29 +00:00
|
|
|
"""
|
|
|
|
Adds this instance to the queue to get its state transition attempted.
|
|
|
|
|
|
|
|
The scheduler will call this, but you can also call it directly if you
|
|
|
|
know it'll be ready and want to lower latency.
|
|
|
|
"""
|
2022-11-10 05:29:33 +00:00
|
|
|
self.state_ready = True
|
|
|
|
self.save()
|
2022-11-09 06:06:29 +00:00
|
|
|
|
2022-12-05 17:38:37 +00:00
|
|
|
async def atransition_attempt(self) -> State | None:
|
2022-11-09 06:06:29 +00:00
|
|
|
"""
|
|
|
|
Attempts to transition the current state by running its handler(s).
|
|
|
|
"""
|
2022-11-11 06:42:43 +00:00
|
|
|
current_state = self.state_graph.states[self.state]
|
|
|
|
# If it's a manual progression state don't even try
|
|
|
|
# We shouldn't really be here in this case, but it could be a race condition
|
|
|
|
if current_state.externally_progressed:
|
2022-11-16 01:30:30 +00:00
|
|
|
print(
|
|
|
|
f"Warning: trying to progress externally progressed state {self.state}!"
|
|
|
|
)
|
2022-11-11 06:42:43 +00:00
|
|
|
return None
|
2022-11-10 06:48:31 +00:00
|
|
|
try:
|
2022-11-11 06:42:43 +00:00
|
|
|
next_state = await current_state.handler(self)
|
2022-11-10 06:48:31 +00:00
|
|
|
except BaseException as e:
|
|
|
|
await StatorError.acreate_from_instance(self, e)
|
2022-11-20 21:20:28 +00:00
|
|
|
await exceptions.acapture_exception(e)
|
2022-11-10 06:48:31 +00:00
|
|
|
traceback.print_exc()
|
|
|
|
else:
|
|
|
|
if next_state:
|
2022-11-11 06:42:43 +00:00
|
|
|
# Ensure it's a State object
|
|
|
|
if isinstance(next_state, str):
|
|
|
|
next_state = self.state_graph.states[next_state]
|
|
|
|
# Ensure it's a child
|
|
|
|
if next_state not in current_state.children:
|
|
|
|
raise ValueError(
|
|
|
|
f"Cannot transition from {current_state} to {next_state} - not a declared transition"
|
|
|
|
)
|
2022-11-10 06:48:31 +00:00
|
|
|
await self.atransition_perform(next_state)
|
|
|
|
return next_state
|
2022-11-09 06:06:29 +00:00
|
|
|
await self.__class__.objects.filter(pk=self.pk).aupdate(
|
2022-11-10 05:29:33 +00:00
|
|
|
state_attempted=timezone.now(),
|
|
|
|
state_locked_until=None,
|
|
|
|
state_ready=False,
|
2022-11-09 06:06:29 +00:00
|
|
|
)
|
2022-11-10 06:48:31 +00:00
|
|
|
return None
|
2022-11-09 06:06:29 +00:00
|
|
|
|
2022-12-05 17:38:37 +00:00
|
|
|
def transition_perform(self, state: State | str):
|
2022-11-09 06:06:29 +00:00
|
|
|
"""
|
2022-11-10 05:29:33 +00:00
|
|
|
Transitions the instance to the given state name, forcibly.
|
2022-11-09 06:06:29 +00:00
|
|
|
"""
|
2022-11-10 06:48:31 +00:00
|
|
|
if isinstance(state, State):
|
|
|
|
state = state.name
|
|
|
|
if state not in self.state_graph.states:
|
|
|
|
raise ValueError(f"Invalid state {state}")
|
2022-11-28 00:05:31 +00:00
|
|
|
# See if it's ready immediately (if not, delay until first try_interval)
|
|
|
|
if self.state_graph.states[state].attempt_immediately:
|
|
|
|
self.__class__.objects.filter(pk=self.pk).update(
|
|
|
|
state=state,
|
|
|
|
state_changed=timezone.now(),
|
|
|
|
state_attempted=None,
|
|
|
|
state_locked_until=None,
|
|
|
|
state_ready=True,
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
self.__class__.objects.filter(pk=self.pk).update(
|
|
|
|
state=state,
|
|
|
|
state_changed=timezone.now(),
|
|
|
|
state_attempted=timezone.now(),
|
|
|
|
state_locked_until=None,
|
|
|
|
state_ready=False,
|
|
|
|
)
|
2022-11-09 06:06:29 +00:00
|
|
|
|
2022-11-10 05:29:33 +00:00
|
|
|
atransition_perform = sync_to_async(transition_perform)
|
2022-11-09 06:06:29 +00:00
|
|
|
|
|
|
|
|
2022-11-10 05:29:33 +00:00
|
|
|
class StatorError(models.Model):
|
|
|
|
"""
|
|
|
|
Tracks any errors running the transitions.
|
|
|
|
Meant to be cleaned out regularly. Should probably be a log.
|
2022-11-09 06:06:29 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
# appname.modelname (lowercased) label for the model this represents
|
|
|
|
model_label = models.CharField(max_length=200)
|
|
|
|
|
|
|
|
# The primary key of that model (probably int or str)
|
|
|
|
instance_pk = models.CharField(max_length=200)
|
|
|
|
|
2022-11-10 06:48:31 +00:00
|
|
|
# The state we were on
|
|
|
|
state = models.CharField(max_length=200)
|
2022-11-09 06:06:29 +00:00
|
|
|
|
2022-11-10 05:29:33 +00:00
|
|
|
# When it happened
|
|
|
|
date = models.DateTimeField(auto_now_add=True)
|
2022-11-09 06:06:29 +00:00
|
|
|
|
2022-11-10 05:29:33 +00:00
|
|
|
# Error name
|
|
|
|
error = models.TextField()
|
2022-11-09 06:06:29 +00:00
|
|
|
|
2022-11-10 05:29:33 +00:00
|
|
|
# Error details
|
|
|
|
error_details = models.TextField(blank=True, null=True)
|
2022-11-09 06:06:29 +00:00
|
|
|
|
|
|
|
@classmethod
|
2022-11-10 05:29:33 +00:00
|
|
|
async def acreate_from_instance(
|
|
|
|
cls,
|
|
|
|
instance: StatorModel,
|
2022-12-05 17:38:37 +00:00
|
|
|
exception: BaseException | None = None,
|
2022-11-10 05:29:33 +00:00
|
|
|
):
|
2022-11-12 05:02:43 +00:00
|
|
|
detail = traceback.format_exc()
|
|
|
|
if exception and len(exception.args) > 1:
|
|
|
|
detail += "\n\n" + "\n\n".join(
|
|
|
|
pprint.pformat(arg) for arg in exception.args
|
|
|
|
)
|
|
|
|
|
2022-11-10 05:29:33 +00:00
|
|
|
return await cls.objects.acreate(
|
|
|
|
model_label=instance._meta.label_lower,
|
|
|
|
instance_pk=str(instance.pk),
|
2022-11-10 06:48:31 +00:00
|
|
|
state=instance.state,
|
2022-11-10 05:29:33 +00:00
|
|
|
error=str(exception),
|
2022-11-12 05:02:43 +00:00
|
|
|
error_details=detail,
|
2022-11-09 06:06:29 +00:00
|
|
|
)
|