-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb_broker.py
More file actions
1588 lines (1454 loc) · 53.8 KB
/
Copy pathdb_broker.py
File metadata and controls
1588 lines (1454 loc) · 53.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import json
import os
import smtplib
import urllib.request
import hmac
import hashlib
import sqlite3
import threading
import time
from email.message import EmailMessage
from email.utils import formatdate
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
from typing import Any, Dict, Optional
BUNDLE_ROOT = Path(__file__).resolve().parent
DEFAULT_DB = BUNDLE_ROOT / "_system" / "db" / "db.sqlite"
DB_PATH = Path(os.environ.get("DB_BROKER_DB", str(DEFAULT_DB)))
HOST = os.environ.get("DB_BROKER_HOST", "127.0.0.1")
PORT = int(os.environ.get("DB_BROKER_PORT", "8799"))
_LOCK = threading.Lock()
_CONN: Optional[sqlite3.Connection] = None
_NOTIFY_STALE_SECS = 45
_NOTIFY_QUEUE_STABLE_SECS = 45
def _as_bool(val: object, default: bool = False) -> bool:
if isinstance(val, bool):
return val
if val is None:
return default
if isinstance(val, (int, float)):
return bool(val)
return str(val).strip().lower() in {"1", "true", "yes", "on"}
def _as_int(val: object, default: int) -> int:
try:
return int(val) # type: ignore[arg-type]
except (TypeError, ValueError):
return default
def _load_settings_map(conn: sqlite3.Connection) -> Dict[str, str]:
try:
cur = conn.cursor()
cur.execute("SELECT key, value FROM Setting;")
rows = cur.fetchall()
return {str(row[0]): str(row[1]) for row in rows or [] if row and row[0] is not None}
except Exception:
return {}
def _get_setting(conn: sqlite3.Connection, key: str) -> Optional[str]:
try:
cur = conn.cursor()
cur.execute("SELECT value FROM Setting WHERE key=?;", (key,))
row = cur.fetchone()
return str(row[0]) if row and row[0] is not None else None
except Exception:
return None
def _set_setting(conn: sqlite3.Connection, key: str, value: str) -> None:
try:
cur = conn.cursor()
cur.execute(
"INSERT INTO Setting (key, value, updatedAt) VALUES (?, ?, CURRENT_TIMESTAMP) "
"ON CONFLICT(key) DO UPDATE SET value=excluded.value, updatedAt=CURRENT_TIMESTAMP;",
(key, value),
)
conn.commit()
except Exception:
return
def _delete_setting(conn: sqlite3.Connection, key: str) -> None:
try:
cur = conn.cursor()
cur.execute("DELETE FROM Setting WHERE key=?;", (key,))
conn.commit()
except Exception:
return
def _notifications_enabled(settings: Dict[str, str]) -> bool:
return _as_bool(settings.get("notifications_enabled"), False)
def _email_channel_enabled(settings: Dict[str, str]) -> bool:
return _as_bool(settings.get("notify_channel_email"), False)
def _discord_channel_enabled(settings: Dict[str, str]) -> bool:
return _as_bool(settings.get("notify_channel_discord"), False)
def _slack_channel_enabled(settings: Dict[str, str]) -> bool:
return _as_bool(settings.get("notify_channel_slack"), False)
def _webhook_channel_enabled(settings: Dict[str, str]) -> bool:
return _as_bool(settings.get("notify_channel_webhook"), False)
def _email_ready(settings: Dict[str, str]) -> bool:
host = settings.get("smtp_host", "").strip()
smtp_from = settings.get("smtp_from", "").strip()
smtp_to = settings.get("smtp_to", "").strip()
port = _as_int(settings.get("smtp_port"), 0)
return bool(host and smtp_from and smtp_to and port > 0)
def _discord_ready(settings: Dict[str, str]) -> bool:
return bool(settings.get("discord_webhook_url", "").strip())
def _slack_ready(settings: Dict[str, str]) -> bool:
return bool(settings.get("slack_webhook_url", "").strip())
def _webhook_ready(settings: Dict[str, str]) -> bool:
return bool(settings.get("webhook_url", "").strip())
def _join_url(base: str, path: str) -> str:
if not path:
return ""
if path.startswith("http://") or path.startswith("https://"):
return path
if not base:
return path
if path.startswith("/"):
return f"{base.rstrip('/')}{path}"
return f"{base.rstrip('/')}/{path}"
def _post_json(
url: str,
payload: Dict[str, object],
timeout: int = 5,
retries: int = 2,
headers: Optional[Dict[str, str]] = None,
) -> None:
data = json.dumps(payload).encode("utf-8")
hdrs = {
"Content-Type": "application/json",
"User-Agent": "FrameForge-Notifier/1.0",
}
if headers:
hdrs.update(headers)
req = urllib.request.Request(
url,
data=data,
headers=hdrs,
method="POST",
)
last_exc: Optional[Exception] = None
for _ in range(retries + 1):
try:
with urllib.request.urlopen(req, timeout=timeout):
return
except Exception as exc:
last_exc = exc
if last_exc:
raise last_exc
def _send_discord(settings: Dict[str, str], payload: Dict[str, object]) -> None:
url = settings.get("discord_webhook_url", "").strip()
if not url:
return
_post_json(url, payload)
def _send_slack(settings: Dict[str, str], payload: Dict[str, object]) -> None:
url = settings.get("slack_webhook_url", "").strip()
if not url:
return
_post_json(url, payload)
def _sign_webhook(secret: str, body: bytes) -> str:
return hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest()
def _send_webhook(settings: Dict[str, str], payload: Dict[str, object]) -> None:
url = settings.get("webhook_url", "").strip()
if not url:
return
secret = str(settings.get("webhook_secret", "") or "").strip()
headers = {}
if secret:
body = json.dumps(payload).encode("utf-8")
headers["X-FrameForge-Signature"] = _sign_webhook(secret, body)
headers["X-FrameForge-Signature-Alg"] = "sha256"
_post_json(url, payload, headers=headers)
return
_post_json(url, payload)
def _event_enabled(settings: Dict[str, str], event_key: str) -> bool:
return _as_bool(settings.get(event_key), False)
def _smtp_password(settings: Dict[str, str]) -> str:
env_override = os.environ.get("FRAMEFORGE_SMTP_PASS") or os.environ.get("SMTP_PASS")
return env_override if env_override is not None else str(settings.get("smtp_pass", ""))
def _reserve_notification(
conn: sqlite3.Connection,
*,
run_id: str,
notif_type: str,
status: str,
payload_hash: str,
) -> bool:
cur = conn.cursor()
cur.execute(
"""
INSERT INTO NotificationLog (runId, type, status, payloadHash)
VALUES (?, ?, ?, ?)
ON CONFLICT(runId, type, status, payloadHash) DO NOTHING;
""",
(run_id, notif_type, status, payload_hash),
)
conn.commit()
return cur.rowcount > 0
def _release_notification(
conn: sqlite3.Connection,
*,
run_id: str,
notif_type: str,
status: str,
payload_hash: str,
) -> None:
cur = conn.cursor()
cur.execute(
"DELETE FROM NotificationLog WHERE runId=? AND type=? AND status=? AND payloadHash=?;",
(run_id, notif_type, status, payload_hash),
)
conn.commit()
def _send_email(settings: Dict[str, str], subject: str, body: str, html: Optional[str] = None) -> None:
host = settings.get("smtp_host", "").strip()
if not host:
return
port = _as_int(settings.get("smtp_port"), 0)
if port <= 0:
return
smtp_user = settings.get("smtp_user", "").strip()
smtp_pass = _smtp_password(settings).strip()
smtp_from = settings.get("smtp_from", "").strip()
smtp_to = settings.get("smtp_to", "").strip()
if not smtp_from or not smtp_to:
return
use_tls = _as_bool(settings.get("smtp_tls"), False)
use_ssl = _as_bool(settings.get("smtp_ssl"), False)
msg = EmailMessage()
msg["Subject"] = subject
msg["From"] = smtp_from
msg["To"] = smtp_to
msg["Date"] = formatdate(localtime=True)
msg.set_content(body)
if html:
msg.add_alternative(html, subtype="html")
timeout = 5
if use_ssl:
with smtplib.SMTP_SSL(host, port, timeout=timeout) as server:
if smtp_user:
server.login(smtp_user, smtp_pass)
server.send_message(msg)
return
with smtplib.SMTP(host, port, timeout=timeout) as server:
server.ehlo()
if use_tls:
server.starttls()
server.ehlo()
if smtp_user:
server.login(smtp_user, smtp_pass)
server.send_message(msg)
def _is_failed_status(status: str) -> bool:
return status == "failed" or status.startswith("failed_")
def _format_ts(val: object) -> str:
return str(val) if val else "n/a"
def _html_escape(text: str) -> str:
return (
text.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace('"', """)
.replace("'", "'")
)
def _render_run_email_html(
*,
header: str,
run_id: str,
run_name: str,
status: str,
last_step: str,
created_at: str,
started_at: str,
finished_at: str,
dataset_url: str,
lora_url: str,
error: str,
instance_label: str,
instance_url: str,
) -> str:
def _row(label: str, value: str) -> str:
return (
f"<tr><td style='padding:6px 10px;color:#8fa2b8;'>{_html_escape(label)}</td>"
f"<td style='padding:6px 10px;color:#f5f7fb;'>{_html_escape(value)}</td></tr>"
)
downloads = ""
if dataset_url or lora_url:
rows = ""
if dataset_url:
rows += _row("Dataset", dataset_url)
if lora_url:
rows += _row("LoRA", lora_url)
downloads = f"""
<div style="margin-top:16px;padding:12px;border-radius:10px;background:#0f1622;border:1px solid #1c2a3a;">
<div style="font-weight:700;color:#8fd3ff;margin-bottom:6px;">Downloads</div>
<table style="width:100%;border-collapse:collapse;">{rows}</table>
</div>
"""
error_block = ""
if error:
error_block = f"""
<div style="margin-top:16px;padding:12px;border-radius:10px;background:#221416;border:1px solid #3a1c20;color:#ffb3a8;">
<div style="font-weight:700;margin-bottom:6px;">Error</div>
<div style="white-space:pre-wrap;">{_html_escape(error)}</div>
</div>
"""
instance_line = (
f"<a href='{_html_escape(instance_url)}' style='color:#8fd3ff;text-decoration:none;'>"
f"{_html_escape(instance_url)}</a>"
if instance_url
else ""
)
return f"""
<html>
<body style="margin:0;padding:0;background:#0b0f14;font-family:Arial,sans-serif;color:#f5f7fb;">
<div style="max-width:640px;margin:0 auto;padding:24px;">
<div style="padding:18px 20px;border-radius:16px;background:linear-gradient(180deg,#141a22,#0f141b);border:1px solid #1d2a38;">
<table role="presentation" style="width:100%;border-collapse:collapse;">
<tr>
<td style="width:28px;vertical-align:middle;">
<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="0 0 100 100" role="img" aria-label="FrameForge">
<path fill="#d58c3f" d="M64.6 12.8l5.4 9.3c3.1-0.3 6.3-0.3 9.4 0l5.4-9.3 11.3 6.5-5.4 9.3c2.2 2.2 4.1 4.6 5.7 7.3l10.7-2.1 3.3 12.7-10.7 2.1c0.3 3.1 0.3 6.3 0 9.4l10.7 2.1-3.3 12.7-10.7-2.1c-1.6 2.7-3.5 5.1-5.7 7.3l5.4 9.3-11.3 6.5-5.4-9.3c-3.1 0.3-6.3 0.3-9.4 0l-5.4 9.3-11.3-6.5 5.4-9.3c-2.2-2.2-4.1-4.6-5.7-7.3l-10.7 2.1-3.3-12.7 10.7-2.1c-0.3-3.1-0.3-6.3 0-9.4l-10.7-2.1 3.3-12.7 10.7 2.1c1.6-2.7 3.5-5.1 5.7-7.3l-5.4-9.3 11.3-6.5 5.4 9.3c3.1-0.3 6.3-0.3 9.4 0l5.4-9.3 11.3 6.5zM50 35c-8.3 0-15 6.7-15 15s6.7 15 15 15 15-6.7 15-15-6.7-15-15-15z"/>
</svg>
</td>
<td style="padding-left:10px;vertical-align:middle;">
<div style="font-size:18px;font-weight:700;letter-spacing:0.4px;">FrameForge</div>
<div style="margin-top:2px;font-size:11px;letter-spacing:1px;color:#8fa2b8;text-transform:uppercase;">automate. refine. deliver.</div>
</td>
</tr>
</table>
<div style="margin-top:10px;font-size:15px;color:#8fd3ff;">{_html_escape(header)}</div>
</div>
<div style="margin-top:16px;padding:18px;border-radius:16px;background:#111720;border:1px solid #1c2a3a;">
<table style="width:100%;border-collapse:collapse;">
{_row("Run", run_id)}
{_row("Name", run_name)}
{_row("Status", status)}
{_row("Last step", last_step)}
{_row("Created", created_at)}
{_row("Started", started_at)}
{_row("Finished", finished_at)}
</table>
{downloads}
{error_block}
</div>
<div style="margin-top:16px;color:#8fa2b8;font-size:12px;">
<div>{_html_escape(instance_label)}</div>
<div>{instance_line}</div>
</div>
</div>
</body>
</html>
"""
def _render_queue_email_html(
*,
queue_mode: str,
instance_label: str,
instance_url: str,
) -> str:
instance_line = (
f"<a href='{_html_escape(instance_url)}' style='color:#8fd3ff;text-decoration:none;'>"
f"{_html_escape(instance_url)}</a>"
if instance_url
else ""
)
return f"""
<html>
<body style="margin:0;padding:0;background:#0b0f14;font-family:Arial,sans-serif;color:#f5f7fb;">
<div style="max-width:640px;margin:0 auto;padding:24px;">
<div style="padding:18px 20px;border-radius:16px;background:linear-gradient(180deg,#141a22,#0f141b);border:1px solid #1d2a38;">
<table role="presentation" style="width:100%;border-collapse:collapse;">
<tr>
<td style="width:28px;vertical-align:middle;">
<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="0 0 100 100" role="img" aria-label="FrameForge">
<path fill="#d58c3f" d="M64.6 12.8l5.4 9.3c3.1-0.3 6.3-0.3 9.4 0l5.4-9.3 11.3 6.5-5.4 9.3c2.2 2.2 4.1 4.6 5.7 7.3l10.7-2.1 3.3 12.7-10.7 2.1c0.3 3.1 0.3 6.3 0 9.4l10.7 2.1-3.3 12.7-10.7-2.1c-1.6 2.7-3.5 5.1-5.7 7.3l5.4 9.3-11.3 6.5-5.4-9.3c-3.1 0.3-6.3 0.3-9.4 0l-5.4 9.3-11.3-6.5 5.4-9.3c-2.2-2.2-4.1-4.6-5.7-7.3l-10.7 2.1-3.3-12.7 10.7-2.1c-0.3-3.1-0.3-6.3 0-9.4l-10.7-2.1 3.3-12.7 10.7 2.1c1.6-2.7 3.5-5.1 5.7-7.3l-5.4-9.3 11.3-6.5 5.4 9.3c3.1-0.3 6.3-0.3 9.4 0l5.4-9.3 11.3 6.5zM50 35c-8.3 0-15 6.7-15 15s6.7 15 15 15 15-6.7 15-15-6.7-15-15-15z"/>
</svg>
</td>
<td style="padding-left:10px;vertical-align:middle;">
<div style="font-size:18px;font-weight:700;letter-spacing:0.4px;">FrameForge</div>
<div style="margin-top:2px;font-size:11px;letter-spacing:1px;color:#8fa2b8;text-transform:uppercase;">automate. refine. deliver.</div>
</td>
</tr>
</table>
<div style="margin-top:10px;font-size:15px;color:#8fd3ff;">Queue drained</div>
</div>
<div style="margin-top:16px;padding:18px;border-radius:16px;background:#111720;border:1px solid #1c2a3a;">
<div style="margin-bottom:10px;color:#c8d2df;">All workers are idle and no runs are active.</div>
<table style="width:100%;border-collapse:collapse;">
<tr><td style="padding:6px 10px;color:#8fa2b8;">Queue mode</td><td style="padding:6px 10px;color:#f5f7fb;">{_html_escape(queue_mode)}</td></tr>
</table>
</div>
<div style="margin-top:16px;color:#8fa2b8;font-size:12px;">
<div>{_html_escape(instance_label)}</div>
<div>{instance_line}</div>
</div>
</div>
</body>
</html>
"""
def _log_notification_error(
conn: sqlite3.Connection,
run_id: Optional[str],
message: str,
detail: str,
) -> None:
try:
cur = conn.cursor()
cur.execute(
"""
INSERT INTO ErrorLog (
runId, component, stage, step, errorType, errorCode, errorMessage, errorDetail, createdAt
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP);
""",
(
run_id,
"notifications",
"notify",
"notify",
"notification_error",
"notify_failed",
message,
detail,
),
)
conn.commit()
except Exception:
return
def _fetch_run_for_notification(conn: sqlite3.Connection, run_id_db: int) -> Optional[Dict[str, object]]:
cur = conn.cursor()
cur.execute(
"""
SELECT runId, runName, status, lastStep, error, createdAt, startedAt, finishedAt,
datasetDownload, loraDownload
FROM Run WHERE id=?;
""",
(run_id_db,),
)
row = cur.fetchone()
if not row:
return None
return {
"runId": row[0],
"runName": row[1],
"status": row[2],
"lastStep": row[3],
"error": row[4],
"createdAt": row[5],
"startedAt": row[6],
"finishedAt": row[7],
"datasetDownload": row[8],
"loraDownload": row[9],
}
def _queue_finish_token(conn: sqlite3.Connection) -> str:
cur = conn.cursor()
cur.execute("SELECT MAX(finishedAt) FROM Run WHERE finishedAt IS NOT NULL;")
row = cur.fetchone()
return str(row[0]) if row and row[0] is not None else "empty"
def _workers_idle(conn: sqlite3.Connection) -> bool:
cur = conn.cursor()
cur.execute(
"SELECT role, state, heartbeat FROM WorkerStatus WHERE role IN ('initiator', 'orchestrator', 'finisher');"
)
rows = cur.fetchall() or []
roles = {row[0]: {"state": row[1], "heartbeat": row[2]} for row in rows if row and row[0]}
for role in ("initiator", "orchestrator", "finisher"):
info = roles.get(role)
if not info:
return False
state = str(info.get("state") or "").lower()
if state not in {"idle", "ok"}:
return False
heartbeat = info.get("heartbeat")
if heartbeat is None:
return False
try:
age = time.time() - float(heartbeat)
except (TypeError, ValueError):
return False
if age > _NOTIFY_STALE_SECS:
return False
return True
def _active_run_count(conn: sqlite3.Connection) -> int:
active_statuses = (
"queued",
"queued_initiated",
"running",
"manual_tagging",
"ready_to_train",
"ready_for_finish",
)
placeholders = ",".join("?" for _ in active_statuses)
cur = conn.cursor()
cur.execute(f"SELECT COUNT(*) FROM Run WHERE status IN ({placeholders});", active_statuses)
row = cur.fetchone()
return int(row[0] or 0) if row else 0
def _maybe_notify_queue_finish(conn: sqlite3.Connection, settings: Dict[str, str]) -> None:
if not _notifications_enabled(settings):
return
email_ready = _email_channel_enabled(settings) and _email_ready(settings)
discord_ready = _discord_channel_enabled(settings) and _discord_ready(settings)
slack_ready = _slack_channel_enabled(settings) and _slack_ready(settings)
webhook_ready = _webhook_channel_enabled(settings) and _webhook_ready(settings)
if not (email_ready or discord_ready or slack_ready or webhook_ready):
return
if not _event_enabled(settings, "notify_queue_finish"):
return
if _active_run_count(conn) > 0:
_delete_setting(conn, "queue_finish_candidate_since")
return
if not _workers_idle(conn):
_delete_setting(conn, "queue_finish_candidate_since")
return
now = time.time()
candidate = _get_setting(conn, "queue_finish_candidate_since")
if not candidate:
_set_setting(conn, "queue_finish_candidate_since", str(int(now)))
return
try:
since = float(candidate)
except (TypeError, ValueError):
_set_setting(conn, "queue_finish_candidate_since", str(int(now)))
return
if now - since < _NOTIFY_QUEUE_STABLE_SECS:
return
payload_hash = _queue_finish_token(conn)
run_id = "queue"
notif_type = "queue_finish"
status = "queue_drain"
if not _reserve_notification(conn, run_id=run_id, notif_type=notif_type, status=status, payload_hash=payload_hash):
return
queue_mode = settings.get("queue_mode") or "running"
subject = "FrameForge: Queue is empty"
instance_label = settings.get("instance_label", "")
instance_url = settings.get("instance_url", "")
body_lines = [
"Hello,",
"",
"The queue is fully drained and all workers are idle.",
"",
"Queue",
"- Pending runs: 0",
f"- Queue mode: {queue_mode}",
"",
"Workers",
"- Initiator: idle/ok",
"- Orchestrator: idle/ok",
"- Finisher: idle/ok",
"",
"Instance",
f"- {instance_label}",
]
if instance_url:
body_lines.append(f"- {instance_url}")
body_lines.extend(
[
"",
"Thanks,",
"FrameForge",
]
)
body = "\n".join(body_lines)
success = False
if email_ready:
try:
html = _render_queue_email_html(
queue_mode=queue_mode,
instance_label=instance_label,
instance_url=instance_url,
)
_send_email(settings, subject, body, html)
success = True
except Exception as exc:
_log_notification_error(conn, None, "queue finish email failed", str(exc))
if discord_ready:
try:
fields = [
{"name": "Queue mode", "value": queue_mode, "inline": True},
]
if instance_label:
fields.append({"name": "Instance", "value": instance_label, "inline": True})
if instance_url:
fields.append({"name": "Open", "value": instance_url, "inline": False})
embed = {
"title": "FrameForge • Queue drained",
"description": "All workers are idle and no runs are active.",
"color": 0x2DB4FF,
"fields": fields,
}
_send_discord(settings, {"embeds": [embed]})
success = True
except Exception as exc:
_log_notification_error(conn, None, "queue finish discord failed", str(exc))
if slack_ready:
try:
text = "\n".join(
[
"FrameForge: Queue drained",
"All workers are idle and no runs are active.",
f"Queue mode: {queue_mode}",
f"Instance: {instance_label}" if instance_label else "",
instance_url or "",
]
).strip()
fields = [
{"type": "mrkdwn", "text": f"*Queue mode:* {queue_mode}"},
]
if instance_label:
fields.append({"type": "mrkdwn", "text": f"*Instance:* {instance_label}"})
blocks = [
{"type": "header", "text": {"type": "plain_text", "text": "FrameForge • Queue drained"}},
{"type": "section", "text": {"type": "mrkdwn", "text": "All workers are idle and no runs are active."}},
{"type": "section", "fields": fields},
]
if instance_url:
blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": f"*Open:* {instance_url}"}})
payload = {
"attachments": [
{
"color": "#2DB4FF",
"fallback": "FrameForge • Queue drained",
"blocks": blocks,
}
],
}
_send_slack(settings, payload)
success = True
except Exception as exc:
_log_notification_error(conn, None, "queue finish slack failed", str(exc))
if webhook_ready:
try:
payload = {
"type": "queue_finish",
"queue_count": 0,
"queue_mode": queue_mode,
"instance_label": instance_label,
"instance_url": instance_url,
}
_send_webhook(settings, payload)
success = True
except Exception as exc:
_log_notification_error(conn, None, "queue finish webhook failed", str(exc))
if success:
_delete_setting(conn, "queue_finish_candidate_since")
else:
_release_notification(conn, run_id=run_id, notif_type=notif_type, status=status, payload_hash=payload_hash)
def _maybe_notify_run_status(conn: sqlite3.Connection, run_id_db: int, status: str) -> None:
settings = _load_settings_map(conn)
if not _notifications_enabled(settings):
return
email_ready = _email_channel_enabled(settings) and _email_ready(settings)
discord_ready = _discord_channel_enabled(settings) and _discord_ready(settings)
slack_ready = _slack_channel_enabled(settings) and _slack_ready(settings)
webhook_ready = _webhook_channel_enabled(settings) and _webhook_ready(settings)
if not (email_ready or discord_ready or slack_ready or webhook_ready):
return
notif_type = None
event_key = None
if status == "done":
notif_type = "job_finish"
event_key = "notify_job_finish"
elif _is_failed_status(status):
notif_type = "job_failed"
event_key = "notify_job_failed"
if not notif_type or not event_key or not _event_enabled(settings, event_key):
return
run = _fetch_run_for_notification(conn, run_id_db)
if not run:
return
run_id = str(run.get("runId") or run_id_db)
payload_hash = f"{notif_type}:{run_id}:{status}"
if not _reserve_notification(conn, run_id=run_id, notif_type=notif_type, status=status, payload_hash=payload_hash):
return
subject = f"FrameForge: Run {run_id} {'finished' if notif_type == 'job_finish' else 'failed'}"
instance_label = settings.get("instance_label", "")
instance_url = settings.get("instance_url", "")
body_lines = [
"Hello,",
"",
"Your FrameForge run has completed successfully."
if notif_type == "job_finish"
else "Your FrameForge run needs attention. It did not complete successfully.",
"",
"Run",
f"- ID: {run_id}",
f"- Name: {run.get('runName') or ''}",
f"- Status: {run.get('status') or status}",
f"- Last step: {run.get('lastStep') or ''}",
f"- Created: {_format_ts(run.get('createdAt'))}",
f"- Started: {_format_ts(run.get('startedAt'))}",
f"- Finished: {_format_ts(run.get('finishedAt'))}",
]
if notif_type == "job_finish":
body_lines.extend(
[
"",
"Downloads",
f"- Dataset: {run.get('datasetDownload') or ''}",
f"- LoRA: {run.get('loraDownload') or ''}",
]
)
else:
body_lines.extend(
[
"",
"Error",
f"- {run.get('error') or ''}",
]
)
body_lines.extend(
[
"",
"Instance",
f"- {instance_label}",
]
)
if instance_url:
body_lines.append(f"- {instance_url}")
body_lines.extend(
[
"",
"Thanks,",
"FrameForge",
]
)
body = "\n".join(body_lines)
success = False
if email_ready:
try:
html = _render_run_email_html(
header="Run finished" if notif_type == "job_finish" else "Run failed",
run_id=run_id,
run_name=str(run.get("runName") or ""),
status=str(run.get("status") or status),
last_step=str(run.get("lastStep") or ""),
created_at=_format_ts(run.get("createdAt")),
started_at=_format_ts(run.get("startedAt")),
finished_at=_format_ts(run.get("finishedAt")),
dataset_url=str(run.get("datasetDownload") or ""),
lora_url=str(run.get("loraDownload") or ""),
error=str(run.get("error") or ""),
instance_label=instance_label,
instance_url=instance_url,
)
_send_email(settings, subject, body, html)
success = True
except Exception as exc:
_log_notification_error(conn, run_id, "run email failed", str(exc))
if discord_ready:
try:
base_url = str(settings.get("instance_url", "") or "").strip()
dataset_url = _join_url(base_url, str(run.get("datasetDownload") or ""))
lora_url = _join_url(base_url, str(run.get("loraDownload") or ""))
header = "Run finished" if notif_type == "job_finish" else "Run failed"
status_label = str(run.get("status") or status)
color = 0x4FE18A if notif_type == "job_finish" else 0xFF6B57
fields = [
{"name": "Run", "value": run_id, "inline": True},
{"name": "Status", "value": status_label, "inline": True},
{"name": "Name", "value": str(run.get("runName") or ""), "inline": False},
]
if notif_type == "job_finish":
if dataset_url:
fields.append({"name": "Dataset", "value": dataset_url, "inline": False})
if lora_url:
fields.append({"name": "LoRA", "value": lora_url, "inline": False})
else:
fields.append({"name": "Error", "value": str(run.get("error") or ""), "inline": False})
if instance_label:
fields.append({"name": "Instance", "value": instance_label, "inline": True})
if instance_url:
fields.append({"name": "Open", "value": instance_url, "inline": False})
embed = {
"title": f"FrameForge • {header}",
"color": color,
"fields": fields,
}
_send_discord(settings, {"embeds": [embed]})
success = True
except Exception as exc:
_log_notification_error(conn, run_id, "run discord failed", str(exc))
if slack_ready:
try:
base_url = str(settings.get("instance_url", "") or "").strip()
dataset_url = _join_url(base_url, str(run.get("datasetDownload") or ""))
lora_url = _join_url(base_url, str(run.get("loraDownload") or ""))
status_label = str(run.get("status") or status)
header = f"Run {'finished' if notif_type == 'job_finish' else 'failed'}"
text_lines = [
f"FrameForge: {header}",
f"Run: {run_id}",
f"Name: {run.get('runName') or ''}",
f"Status: {status_label}",
]
if notif_type == "job_finish":
if dataset_url:
text_lines.append(f"Dataset: {dataset_url}")
if lora_url:
text_lines.append(f"LoRA: {lora_url}")
else:
text_lines.append(f"Error: {run.get('error') or ''}")
if instance_label:
text_lines.append(f"Instance: {instance_label}")
if instance_url:
text_lines.append(instance_url)
fields = [
{"type": "mrkdwn", "text": f"*Run:* {run_id}"},
{"type": "mrkdwn", "text": f"*Status:* {status_label}"},
{"type": "mrkdwn", "text": f"*Name:* {run.get('runName') or ''}"},
]
blocks = [
{"type": "header", "text": {"type": "plain_text", "text": f"FrameForge • {header}"}},
{"type": "section", "fields": fields},
]
if notif_type == "job_finish":
if dataset_url:
blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": f"*Dataset:* {dataset_url}"}})
if lora_url:
blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": f"*LoRA:* {lora_url}"}})
else:
blocks.append(
{"type": "section", "text": {"type": "mrkdwn", "text": f"*Error:* {run.get('error') or ''}"}}
)
if instance_label:
blocks.append({"type": "context", "elements": [{"type": "mrkdwn", "text": f"{instance_label}"}]})
if instance_url:
blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": f"*Open:* {instance_url}"}})
payload = {
"attachments": [
{
"color": "#4FE18A" if notif_type == "job_finish" else "#FF6B57",
"fallback": f"FrameForge • {header}",
"blocks": blocks,
}
],
}
_send_slack(settings, payload)
success = True
except Exception as exc:
_log_notification_error(conn, run_id, "run slack failed", str(exc))
if webhook_ready:
try:
base_url = str(settings.get("instance_url", "") or "").strip()
dataset_url = _join_url(base_url, str(run.get("datasetDownload") or ""))
lora_url = _join_url(base_url, str(run.get("loraDownload") or ""))
payload = {
"type": notif_type,
"run_id": run_id,
"run_name": run.get("runName") or "",
"status": run.get("status") or status,
"last_step": run.get("lastStep") or "",
"error": run.get("error") or "",
"created_at": _format_ts(run.get("createdAt")),
"started_at": _format_ts(run.get("startedAt")),
"finished_at": _format_ts(run.get("finishedAt")),
"dataset_url": dataset_url,
"lora_url": lora_url,
"instance_label": instance_label,
"instance_url": instance_url,
}
_send_webhook(settings, payload)
success = True
except Exception as exc:
_log_notification_error(conn, run_id, "run webhook failed", str(exc))
if success:
_maybe_notify_queue_finish(conn, settings)
else:
_release_notification(conn, run_id=run_id, notif_type=notif_type, status=status, payload_hash=payload_hash)
def _pid_alive(pid: int) -> bool:
try:
os.kill(pid, 0)
return True
except OSError:
return False
def _conn() -> sqlite3.Connection:
global _CONN
if _CONN is None:
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
_CONN = sqlite3.connect(str(DB_PATH), check_same_thread=False)
_CONN.row_factory = sqlite3.Row
_CONN.execute("PRAGMA journal_mode=WAL;")
_CONN.execute("PRAGMA synchronous=NORMAL;")
_CONN.execute("PRAGMA busy_timeout=5000;")
_CONN.execute("PRAGMA temp_store=MEMORY;")
_ensure_tables(_CONN)
return _CONN
def _ensure_tables(conn: sqlite3.Connection) -> None:
cur = conn.cursor()
cur.execute(
"""
CREATE TABLE IF NOT EXISTS TrainProfile (
id INTEGER PRIMARY KEY,
name TEXT UNIQUE NOT NULL,
label TEXT,
settings TEXT NOT NULL,
isDefault BOOLEAN DEFAULT 0,
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP
);
"""
)
cur.execute(
"""
CREATE TABLE IF NOT EXISTS RunPlan (
runId TEXT NOT NULL,
step TEXT NOT NULL,
status TEXT NOT NULL,
meta TEXT,
updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (runId, step)
);
"""
)
cur.execute(
"""
CREATE TABLE IF NOT EXISTS TrainProgress (
runId TEXT PRIMARY KEY,
epoch INTEGER,
epochTotal INTEGER,
step INTEGER,
stepTotal INTEGER,
raw TEXT,
updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP
);
"""
)
cur.execute(
"""
CREATE TABLE IF NOT EXISTS WorkerStatus (
role TEXT PRIMARY KEY,
pid INTEGER,
state TEXT,
runId TEXT,
message TEXT,
heartbeat INTEGER
);
"""
)
cur.execute(
"""