184 lines
6.6 KiB
Python
184 lines
6.6 KiB
Python
"""Machine-independent shift downtime from effective attribution intervals."""
|
|
|
|
from collections import defaultdict
|
|
from collections.abc import Iterable
|
|
from dataclasses import dataclass
|
|
from datetime import UTC, datetime
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class ShiftDowntimeEvent:
|
|
external_id: str
|
|
machine_id: str
|
|
source_start: datetime
|
|
source_end: datetime | None
|
|
reason_id: str | None
|
|
reason_name: str | None
|
|
reason_description: str | None
|
|
reason_group: str | None
|
|
category: str | None
|
|
comment: str | None
|
|
attributed_start: datetime | None = None
|
|
attributed_end: datetime | None = None
|
|
|
|
def __post_init__(self) -> None:
|
|
for name in ("external_id", "machine_id"):
|
|
value = getattr(self, name)
|
|
if not isinstance(value, str) or not value.strip() or "\x00" in value:
|
|
raise ValueError(f"{name} must be a non-empty string without NUL bytes")
|
|
_aware(self.source_start, "source_start")
|
|
for name in ("attributed_start", "attributed_end"):
|
|
value = getattr(self, name)
|
|
if value is not None:
|
|
_aware(value, name)
|
|
if self.source_end is not None:
|
|
_aware(self.source_end, "source_end")
|
|
if self.source_end.astimezone(UTC) < self.source_start.astimezone(UTC):
|
|
raise ValueError("source_end must not precede source_start")
|
|
for name in (
|
|
"reason_id",
|
|
"reason_name",
|
|
"reason_description",
|
|
"reason_group",
|
|
"category",
|
|
"comment",
|
|
):
|
|
value = getattr(self, name)
|
|
if value is not None and not isinstance(value, str):
|
|
raise ValueError(f"{name} must be a string or null")
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class ClippedShiftDowntimeEvent:
|
|
source: ShiftDowntimeEvent
|
|
start: datetime
|
|
end: datetime
|
|
duration_seconds: float
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class ShiftDowntimeReason:
|
|
reason_id: str | None
|
|
reason_name: str | None
|
|
reason_description: str | None
|
|
reason_group: str | None
|
|
category: str | None
|
|
duration_seconds: float
|
|
event_count: int
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class ShiftDowntimeSummary:
|
|
machine_id: str
|
|
start: datetime
|
|
end: datetime
|
|
shift_duration_seconds: float
|
|
total_downtime_seconds: float
|
|
non_downtime_seconds: float
|
|
events: tuple[ClippedShiftDowntimeEvent, ...]
|
|
reasons: tuple[ShiftDowntimeReason, ...]
|
|
|
|
|
|
def validate_downtime_window(*, machine_id: str, start: datetime, end: datetime) -> None:
|
|
if not isinstance(machine_id, str) or not machine_id.strip() or "\x00" in machine_id:
|
|
raise ValueError("machine_id must be a non-empty string without NUL bytes")
|
|
_aware(start, "start")
|
|
_aware(end, "end")
|
|
if end.astimezone(UTC) <= start.astimezone(UTC):
|
|
raise ValueError("end must follow start")
|
|
|
|
|
|
def aggregate_shift_downtime(
|
|
events: Iterable[ShiftDowntimeEvent], *, machine_id: str, start: datetime, end: datetime
|
|
) -> ShiftDowntimeSummary:
|
|
"""Clip effective intervals to [start, end); open events end at the shift end.
|
|
|
|
Total downtime is the union of intervals. Each reason also uses a union within
|
|
its full metadata group. Different reasons may overlap, so their durations need
|
|
not sum to total downtime. Non-downtime is a time complement, not measured output.
|
|
Attribution timestamps take precedence, falling back to raw source timestamps.
|
|
"""
|
|
validate_downtime_window(machine_id=machine_id, start=start, end=end)
|
|
lower, upper = start.astimezone(UTC), end.astimezone(UTC)
|
|
clipped = []
|
|
for event in events:
|
|
if event.machine_id != machine_id:
|
|
continue
|
|
effective_start = event.attributed_start or event.source_start
|
|
effective_end = (
|
|
event.attributed_end if event.attributed_end is not None else event.source_end
|
|
)
|
|
event_start = effective_start.astimezone(UTC)
|
|
event_end = upper if effective_end is None else effective_end.astimezone(UTC)
|
|
if event_start >= upper or event_end <= lower:
|
|
continue
|
|
clipped_start = start if event_start < lower else effective_start
|
|
clipped_end = end if effective_end is None or event_end > upper else effective_end
|
|
duration = (clipped_end.astimezone(UTC) - clipped_start.astimezone(UTC)).total_seconds()
|
|
if duration > 0:
|
|
clipped.append(ClippedShiftDowntimeEvent(event, clipped_start, clipped_end, duration))
|
|
clipped.sort(key=lambda value: (value.start.astimezone(UTC), value.source.external_id))
|
|
groups = defaultdict(list)
|
|
for value in clipped:
|
|
source = value.source
|
|
groups[
|
|
(
|
|
source.reason_id,
|
|
source.reason_name,
|
|
source.reason_description,
|
|
source.reason_group,
|
|
source.category,
|
|
)
|
|
].append(value)
|
|
reasons = [
|
|
ShiftDowntimeReason(*key, _union_seconds(values), len(values))
|
|
for key, values in groups.items()
|
|
]
|
|
reasons.sort(
|
|
key=lambda value: (
|
|
-value.duration_seconds,
|
|
tuple(
|
|
(field is not None, field or "")
|
|
for field in (
|
|
value.reason_id,
|
|
value.reason_name,
|
|
value.reason_description,
|
|
value.reason_group,
|
|
value.category,
|
|
)
|
|
),
|
|
)
|
|
)
|
|
shift_seconds = (upper - lower).total_seconds()
|
|
downtime_seconds = _union_seconds(clipped)
|
|
return ShiftDowntimeSummary(
|
|
machine_id=machine_id,
|
|
start=start,
|
|
end=end,
|
|
shift_duration_seconds=shift_seconds,
|
|
total_downtime_seconds=downtime_seconds,
|
|
non_downtime_seconds=max(0.0, shift_seconds - downtime_seconds),
|
|
events=tuple(clipped),
|
|
reasons=tuple(reasons),
|
|
)
|
|
|
|
|
|
def _union_seconds(events: Iterable[ClippedShiftDowntimeEvent]) -> float:
|
|
intervals = sorted((event.start.astimezone(UTC), event.end.astimezone(UTC)) for event in events)
|
|
if not intervals:
|
|
return 0.0
|
|
start, end = intervals[0]
|
|
total = 0.0
|
|
for next_start, next_end in intervals[1:]:
|
|
if next_start <= end:
|
|
end = max(end, next_end)
|
|
else:
|
|
total += (end - start).total_seconds()
|
|
start, end = next_start, next_end
|
|
return total + (end - start).total_seconds()
|
|
|
|
|
|
def _aware(value: datetime, name: str) -> None:
|
|
if not isinstance(value, datetime) or value.tzinfo is None or value.utcoffset() is None:
|
|
raise ValueError(f"{name} must be a timezone-aware datetime")
|