fix(datastore): alert on open sessions without silent deckeln, support stop by ID
This commit is contained in:
@@ -387,9 +387,9 @@ class DatastoreEngine:
|
||||
}
|
||||
return None
|
||||
|
||||
def _auto_close_stale_sleep_sessions(self, subject: str, current_start_dt: datetime.datetime) -> List[str]:
|
||||
"""Auto-closes open sleep sessions that started >10h ago or on a prior calendar day."""
|
||||
open_sessions = self.con.execute(
|
||||
def _get_open_sleep_sessions(self, subject: str, exclude_id: Optional[str] = None) -> List[Dict[str, Any]]:
|
||||
"""Finds open sleep sessions (end IS NULL) for subject, sorted chronologically."""
|
||||
rows = self.con.execute(
|
||||
"""
|
||||
SELECT id, start, payload, note
|
||||
FROM events
|
||||
@@ -398,46 +398,17 @@ class DatastoreEngine:
|
||||
""",
|
||||
[subject],
|
||||
).fetchall()
|
||||
|
||||
closed_ids = []
|
||||
for o_id, o_start, o_payload, o_note in open_sessions:
|
||||
o_start_dt = datetime.datetime.fromisoformat(str(o_start).replace("Z", "+00:00")).astimezone(BERLIN_TZ)
|
||||
diff_hours = (current_start_dt - o_start_dt).total_seconds() / 3600.0
|
||||
|
||||
# Stale if open for >= 10 hours or started on an earlier day
|
||||
if diff_hours >= 10.0 or (current_start_dt.date() > o_start_dt.date() and current_start_dt.hour >= 6):
|
||||
if o_start_dt.hour >= 17:
|
||||
next_day = o_start_dt.date() + datetime.timedelta(days=1)
|
||||
auto_end_dt = datetime.datetime.combine(next_day, datetime.time(7, 0), tzinfo=BERLIN_TZ)
|
||||
if auto_end_dt > current_start_dt:
|
||||
auto_end_dt = current_start_dt
|
||||
else:
|
||||
auto_end_dt = o_start_dt + datetime.timedelta(minutes=45)
|
||||
if auto_end_dt > current_start_dt:
|
||||
auto_end_dt = current_start_dt
|
||||
|
||||
auto_end_iso = auto_end_dt.isoformat()
|
||||
now_iso = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
note_suffix = "Auto-beendet (vergessenes Aufwachen)"
|
||||
updated_note = f"{o_note} | {note_suffix}" if o_note else note_suffix
|
||||
|
||||
self.con.execute(
|
||||
"""
|
||||
UPDATE events
|
||||
SET "end" = ?, estimated = true, note = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
""",
|
||||
[auto_end_iso, updated_note, now_iso, o_id],
|
||||
)
|
||||
self._update_jsonl_record("sleep", o_id, {
|
||||
"end": auto_end_iso,
|
||||
"estimated": True,
|
||||
"note": updated_note,
|
||||
"updated_at": now_iso,
|
||||
})
|
||||
closed_ids.append(o_id)
|
||||
logger.info(f"Auto-closed stale open sleep session {o_id} for {subject} at {auto_end_iso}")
|
||||
return closed_ids
|
||||
results = []
|
||||
for r in rows:
|
||||
if exclude_id and r[0] == exclude_id:
|
||||
continue
|
||||
results.append({
|
||||
"id": r[0],
|
||||
"start": str(r[1]),
|
||||
"payload": json.loads(r[2]) if isinstance(r[2], str) else (r[2] or {}),
|
||||
"note": r[3],
|
||||
})
|
||||
return results
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Event Operations
|
||||
@@ -501,19 +472,23 @@ class DatastoreEngine:
|
||||
"feedback": feedback,
|
||||
}
|
||||
|
||||
# Validation and stale cleanup for sleep sessions
|
||||
# Check open sleep sessions (notice on every log, never silently deckeln!)
|
||||
open_warning = None
|
||||
if kind == "sleep.session":
|
||||
self._auto_close_stale_sleep_sessions(subject, start_dt)
|
||||
if end_iso is None:
|
||||
# Check if there is still an active (non-stale) open session for this subject
|
||||
open_sessions = self.con.execute(
|
||||
"SELECT id, start FROM events WHERE kind = 'sleep.session' AND subject = ? AND \"end\" IS NULL AND deleted_at IS NULL",
|
||||
[subject],
|
||||
).fetchall()
|
||||
if open_sessions:
|
||||
raise ValueError(
|
||||
f"Subject '{subject}' already has an open sleep session ({open_sessions[0][0]} started at {open_sessions[0][1]}). Please stop it first."
|
||||
)
|
||||
open_sessions = self._get_open_sleep_sessions(subject)
|
||||
if open_sessions:
|
||||
first_open = open_sessions[0]
|
||||
o_start_dt = datetime.datetime.fromisoformat(str(first_open["start"]).replace("Z", "+00:00")).astimezone(BERLIN_TZ)
|
||||
open_warning = f"Vorheriges Schlaf-Event ({first_open['id']} ab {o_start_dt.strftime('%d.%m. %H:%M Uhr')}) ist noch offen! Bitte Aufwachzeit nachreichen."
|
||||
|
||||
# If adding a new open interval (end is None)
|
||||
if end_iso is None:
|
||||
# If existing open session is recent (< 8 hours on same calendar day) and not allow_duplicate, prevent accidental duplicate live nap
|
||||
diff_hours = (start_dt - o_start_dt).total_seconds() / 3600.0
|
||||
if diff_hours < 8.0 and start_dt.date() == o_start_dt.date() and not allow_duplicate:
|
||||
raise ValueError(
|
||||
f"Subject '{subject}' hat bereits ein aktives Schlaf-Event ({first_open['id']} gestartet um {o_start_dt.strftime('%H:%M Uhr')}). Bitte beende es zuerst."
|
||||
)
|
||||
|
||||
record = {
|
||||
"id": event_id,
|
||||
@@ -572,6 +547,12 @@ class DatastoreEngine:
|
||||
|
||||
# Fetch computed feedback
|
||||
feedback = self._get_event_feedback(kind, subject, start_dt.date())
|
||||
if open_warning:
|
||||
feedback["open_session_warning"] = open_warning
|
||||
if "day_total_formatted" in feedback and open_warning not in feedback["day_total_formatted"]:
|
||||
feedback["day_total_formatted"] += f"\n{open_warning}"
|
||||
elif "day_total_formatted" not in feedback:
|
||||
feedback["day_total_formatted"] = open_warning
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
@@ -584,22 +565,33 @@ class DatastoreEngine:
|
||||
kind: str,
|
||||
subject: str,
|
||||
end_time: Optional[str] = None,
|
||||
event_id: Optional[str] = None,
|
||||
actor: Optional[str] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""Finds the open event (end IS NULL) for kind and subject, and closes it."""
|
||||
row = self.con.execute(
|
||||
"""
|
||||
SELECT id, start FROM events
|
||||
WHERE kind = ? AND subject = ? AND "end" IS NULL AND deleted_at IS NULL
|
||||
ORDER BY start DESC LIMIT 1
|
||||
""",
|
||||
[kind, subject],
|
||||
).fetchone()
|
||||
if event_id:
|
||||
row = self.con.execute(
|
||||
"""
|
||||
SELECT id, start FROM events
|
||||
WHERE id = ? AND kind = ? AND subject = ? AND "end" IS NULL AND deleted_at IS NULL
|
||||
""",
|
||||
[event_id, kind, subject],
|
||||
).fetchone()
|
||||
if not row:
|
||||
raise ValueError(f"No open event with id='{event_id}' found for kind='{kind}' and subject='{subject}'")
|
||||
else:
|
||||
row = self.con.execute(
|
||||
"""
|
||||
SELECT id, start FROM events
|
||||
WHERE kind = ? AND subject = ? AND "end" IS NULL AND deleted_at IS NULL
|
||||
ORDER BY start DESC LIMIT 1
|
||||
""",
|
||||
[kind, subject],
|
||||
).fetchone()
|
||||
if not row:
|
||||
raise ValueError(f"No open event found for kind='{kind}' and subject='{subject}'")
|
||||
|
||||
if not row:
|
||||
raise ValueError(f"No open event found for kind='{kind}' and subject='{subject}'")
|
||||
|
||||
event_id, start_str = row[0], str(row[1])
|
||||
resolved_event_id, start_str = row[0], str(row[1])
|
||||
now_dt = datetime.datetime.now(datetime.timezone.utc)
|
||||
if end_time:
|
||||
end_dt = datetime.datetime.fromisoformat(end_time)
|
||||
@@ -618,12 +610,12 @@ class DatastoreEngine:
|
||||
SET "end" = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
""",
|
||||
[end_iso, now_iso, event_id],
|
||||
[end_iso, now_iso, resolved_event_id],
|
||||
)
|
||||
|
||||
# Update in JSONL
|
||||
domain = kind.split(".")[0]
|
||||
self._update_jsonl_record(domain, event_id, {"end": end_iso, "updated_at": now_iso})
|
||||
self._update_jsonl_record(domain, resolved_event_id, {"end": end_iso, "updated_at": now_iso})
|
||||
|
||||
# Calculate duration
|
||||
start_dt = datetime.datetime.fromisoformat(start_str.replace("Z", "+00:00"))
|
||||
@@ -631,7 +623,7 @@ class DatastoreEngine:
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"event_id": event_id,
|
||||
"event_id": resolved_event_id,
|
||||
"kind": kind,
|
||||
"subject": subject,
|
||||
"start": start_str,
|
||||
@@ -1117,6 +1109,7 @@ def run_cli():
|
||||
p_stop.add_argument("kind", nargs="?", default=None, help="e.g. sleep.session")
|
||||
p_stop.add_argument("--kind", dest="kind_flag", help="e.g. sleep.session")
|
||||
p_stop.add_argument("--subject", required=True, help="mila, moritz")
|
||||
p_stop.add_argument("--id", dest="event_id", help="Specific event ID to close")
|
||||
p_stop.add_argument("--end", help="ISO end time (defaults to now)")
|
||||
|
||||
# Query
|
||||
@@ -1166,7 +1159,7 @@ def run_cli():
|
||||
kind = args.kind or args.kind_flag
|
||||
if not kind:
|
||||
parser.error("the 'stop' command requires 'kind' (positional or via --kind)")
|
||||
res = engine.stop_event(kind=kind, subject=args.subject, end_time=args.end)
|
||||
res = engine.stop_event(kind=kind, subject=args.subject, end_time=args.end, event_id=getattr(args, "event_id", None))
|
||||
print(json.dumps(res, indent=2, ensure_ascii=False))
|
||||
elif args.command == "query":
|
||||
res = engine.query(args.sql)
|
||||
|
||||
Reference in New Issue
Block a user