Spaces:
Running

File size: 4,385 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Event inbox, webhook endpoints and schedules (all tenant-scoped, RLS forced).



Every piece of work enters through the ``events`` table. The unique

``(tenant_id, dedupe_key)`` constraint is the one durable door: a redelivered webhook,

a double-clicked button or a replayed schedule slot inserts nothing the second time.

"""

from __future__ import annotations

import uuid
from datetime import datetime

from sqlalchemy import Boolean, DateTime, Integer, String, Text, UniqueConstraint, func
from sqlalchemy.dialects.postgresql import JSONB, UUID
from sqlalchemy.orm import Mapped, mapped_column

from core.db.base import Base, TenantMixin, TimestampMixin, new_id

# received -> processing -> processed | dead   (dead -> received on manual retry)
EVENT_STATUSES = ("received", "processing", "processed", "dead")


class InboxEvent(TenantMixin, Base):
    __tablename__ = "events"
    __table_args__ = (
        UniqueConstraint("tenant_id", "dedupe_key", name="uq_events_tenant_dedupe_key"),
    )

    id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=new_id)
    type: Mapped[str] = mapped_column(String(200), nullable=False)
    source: Mapped[str] = mapped_column(String(30), nullable=False)
    text: Mapped[str | None] = mapped_column(Text, nullable=True)  # untrusted unless ``trusted``
    trusted: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
    payload: Mapped[dict] = mapped_column(JSONB, nullable=False, default=dict)
    dedupe_key: Mapped[str] = mapped_column(String(300), nullable=False)
    status: Mapped[str] = mapped_column(String(20), nullable=False, default="received", index=True)
    attempts: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
    last_error: Mapped[str | None] = mapped_column(Text, nullable=True)
    run_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True)
    thread_id: Mapped[str | None] = mapped_column(String(200), nullable=True)
    received_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now(), nullable=False
    )
    processed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)


class WebhookEndpoint(TenantMixin, TimestampMixin, Base):
    """An inbound webhook URL ``/webhooks/<source>/<token>``.



    ``token`` is public (it is in the URL) and starts with the tenant id, so the API can

    bind the tenant before reading the row under RLS. ``secret`` verifies signatures

    (Shopify app secret, Meta app secret, or a generic HMAC key) and is never returned

    after creation. ``verify_token`` answers Meta's GET subscription handshake.

    """

    __tablename__ = "webhook_endpoints"

    id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=new_id)
    source: Mapped[str] = mapped_column(String(30), nullable=False)  # shopify|whatsapp|generic
    token: Mapped[str] = mapped_column(String(200), nullable=False, unique=True)
    secret: Mapped[str] = mapped_column(String(500), nullable=False)
    verify_token: Mapped[str | None] = mapped_column(String(200), nullable=True)
    enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)


class Schedule(TenantMixin, TimestampMixin, Base):
    """A cron trigger that emits ``schedule.tick``-style events, at most once per slot."""

    __tablename__ = "schedules"
    __table_args__ = (UniqueConstraint("tenant_id", "name", name="uq_schedules_tenant_name"),)

    id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=new_id)
    name: Mapped[str] = mapped_column(String(200), nullable=False)
    cron: Mapped[str] = mapped_column(String(100), nullable=False)
    timezone: Mapped[str] = mapped_column(String(64), nullable=False, default="Asia/Karachi")
    event_type: Mapped[str] = mapped_column(String(200), nullable=False, default="schedule.tick")
    payload: Mapped[dict] = mapped_column(JSONB, nullable=False, default=dict)
    enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
    next_run_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), nullable=True, index=True
    )
    last_run_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)