GitHub Actions commited on
Commit
fffaeb4
·
1 Parent(s): b03fdde

Deploy from GitHub main

Browse files
.env.example CHANGED
@@ -28,5 +28,6 @@ WHATSAPP_VERIFY_TOKEN=choose-a-webhook-verify-token
28
  WHATSAPP_APP_SECRET=your-meta-app-secret
29
  WHATSAPP_ACCESS_TOKEN=your-whatsapp-cloud-api-token
30
  WHATSAPP_PHONE_NUMBER_ID=your-phone-number-id
 
31
 
32
  ADMIN_API_KEY=choose-a-long-random-admin-key
 
28
  WHATSAPP_APP_SECRET=your-meta-app-secret
29
  WHATSAPP_ACCESS_TOKEN=your-whatsapp-cloud-api-token
30
  WHATSAPP_PHONE_NUMBER_ID=your-phone-number-id
31
+ WHATSAPP_RETRY_INTERVAL_SECONDS=60
32
 
33
  ADMIN_API_KEY=choose-a-long-random-admin-key
app/config.py CHANGED
@@ -48,6 +48,7 @@ class Settings(BaseSettings):
48
  whatsapp_app_secret: str = Field(min_length=1)
49
  whatsapp_access_token: str = Field(min_length=1)
50
  whatsapp_phone_number_id: str = Field(min_length=1)
 
51
 
52
  admin_api_key: str = Field(min_length=1)
53
 
 
48
  whatsapp_app_secret: str = Field(min_length=1)
49
  whatsapp_access_token: str = Field(min_length=1)
50
  whatsapp_phone_number_id: str = Field(min_length=1)
51
+ whatsapp_retry_interval_seconds: int = Field(default=6, gt=0)
52
 
53
  admin_api_key: str = Field(min_length=1)
54
 
app/database/supabase.py CHANGED
@@ -1,5 +1,5 @@
1
  import logging
2
- from datetime import date, time
3
  from typing import Any
4
 
5
  from app.config import Settings
@@ -32,6 +32,158 @@ class SupabaseRepository:
32
  def __init__(self, client: Any) -> None:
33
  self.client = client
34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  async def upsert_customer(
36
  self,
37
  *,
 
1
  import logging
2
+ from datetime import UTC, date, datetime, time
3
  from typing import Any
4
 
5
  from app.config import Settings
 
32
  def __init__(self, client: Any) -> None:
33
  self.client = client
34
 
35
+ async def enqueue_whatsapp_message(
36
+ self,
37
+ *,
38
+ recipient: str,
39
+ payload: dict[str, Any],
40
+ ) -> dict[str, Any]:
41
+ now = datetime.now(UTC).isoformat()
42
+ response = await (
43
+ self.client.table("whatsapp_outbox")
44
+ .insert(
45
+ {
46
+ "recipient": recipient,
47
+ "payload": payload,
48
+ "status": "pending",
49
+ "next_attempt_at": now,
50
+ }
51
+ )
52
+ .select("*")
53
+ .execute()
54
+ )
55
+ data = _response_data(response)
56
+ return data[0] if isinstance(data, list) else data
57
+
58
+ async def get_oldest_active_whatsapp_message(self) -> dict[str, Any] | None:
59
+ response = await (
60
+ self.client.table("whatsapp_outbox")
61
+ .select("*")
62
+ .in_("status", ["pending", "sending"])
63
+ .order("created_at")
64
+ .order("id")
65
+ .limit(1)
66
+ .execute()
67
+ )
68
+ data = _response_data(response) or []
69
+ return data[0] if data else None
70
+
71
+ async def claim_whatsapp_message(
72
+ self,
73
+ message_id: str,
74
+ *,
75
+ ignore_retry_time: bool = False,
76
+ ) -> dict[str, Any] | None:
77
+ attempts_response = await (
78
+ self.client.table("whatsapp_outbox")
79
+ .select("attempts")
80
+ .eq("id", message_id)
81
+ .eq("status", "pending")
82
+ .maybe_single()
83
+ .execute()
84
+ )
85
+ row = _response_data(attempts_response)
86
+ if not row:
87
+ return None
88
+
89
+ now = datetime.now(UTC).isoformat()
90
+ update = (
91
+ self.client.table("whatsapp_outbox")
92
+ .update(
93
+ {
94
+ "status": "sending",
95
+ "attempts": int(row.get("attempts") or 0) + 1,
96
+ "last_attempt_at": now,
97
+ "locked_at": now,
98
+ "last_error": None,
99
+ }
100
+ )
101
+ .eq("id", message_id)
102
+ .eq("status", "pending")
103
+ )
104
+ if not ignore_retry_time:
105
+ update = update.lte("next_attempt_at", now)
106
+ response = await update.select("*").execute()
107
+ data = _response_data(response) or []
108
+ return data[0] if data else None
109
+
110
+ async def recover_stale_whatsapp_messages(
111
+ self,
112
+ *,
113
+ stale_before: datetime,
114
+ ) -> None:
115
+ now = datetime.now(UTC).isoformat()
116
+ await (
117
+ self.client.table("whatsapp_outbox")
118
+ .update(
119
+ {
120
+ "status": "pending",
121
+ "next_attempt_at": now,
122
+ "locked_at": None,
123
+ "last_error": "Recovered after an interrupted send attempt",
124
+ }
125
+ )
126
+ .eq("status", "sending")
127
+ .lt("locked_at", stale_before.isoformat())
128
+ .execute()
129
+ )
130
+
131
+ async def mark_whatsapp_message_sent(
132
+ self,
133
+ message_id: str,
134
+ *,
135
+ provider_response: dict[str, Any],
136
+ ) -> None:
137
+ await (
138
+ self.client.table("whatsapp_outbox")
139
+ .update(
140
+ {
141
+ "status": "sent",
142
+ "sent_at": datetime.now(UTC).isoformat(),
143
+ "locked_at": None,
144
+ "last_error": None,
145
+ "provider_response": provider_response,
146
+ }
147
+ )
148
+ .eq("id", message_id)
149
+ .execute()
150
+ )
151
+ provider_messages = provider_response.get("messages") or []
152
+ provider_message_id = (
153
+ provider_messages[0].get("id")
154
+ if provider_messages and isinstance(provider_messages[0], dict)
155
+ else None
156
+ )
157
+ if provider_message_id:
158
+ await (
159
+ self.client.table("messages")
160
+ .update({"whatsapp_message_id": provider_message_id})
161
+ .eq("metadata->>outbox_id", message_id)
162
+ .execute()
163
+ )
164
+
165
+ async def fail_whatsapp_message(
166
+ self,
167
+ message_id: str,
168
+ *,
169
+ error: str,
170
+ retryable: bool,
171
+ retry_at: datetime,
172
+ ) -> None:
173
+ await (
174
+ self.client.table("whatsapp_outbox")
175
+ .update(
176
+ {
177
+ "status": "pending" if retryable else "failed",
178
+ "next_attempt_at": retry_at.isoformat(),
179
+ "locked_at": None,
180
+ "last_error": error[:4000],
181
+ }
182
+ )
183
+ .eq("id", message_id)
184
+ .execute()
185
+ )
186
+
187
  async def upsert_customer(
188
  self,
189
  *,
app/main.py CHANGED
@@ -1,3 +1,4 @@
 
1
  from collections.abc import AsyncIterator
2
  from contextlib import asynccontextmanager
3
 
@@ -16,6 +17,7 @@ def create_app(
16
  ) -> FastAPI:
17
  @asynccontextmanager
18
  async def lifespan(app: FastAPI) -> AsyncIterator[None]:
 
19
  app.state.container = None
20
  app.state.container_init_error = None
21
 
@@ -41,7 +43,20 @@ def create_app(
41
  app.state.container = None
42
  app.state.container_init_error = str(exc)
43
 
44
- yield
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
  app = FastAPI(title="FALZH API", version="0.1.0", lifespan=lifespan)
47
  app.include_router(router)
 
1
+ import asyncio
2
  from collections.abc import AsyncIterator
3
  from contextlib import asynccontextmanager
4
 
 
17
  ) -> FastAPI:
18
  @asynccontextmanager
19
  async def lifespan(app: FastAPI) -> AsyncIterator[None]:
20
+ retry_worker: asyncio.Task[None] | None = None
21
  app.state.container = None
22
  app.state.container_init_error = None
23
 
 
43
  app.state.container = None
44
  app.state.container_init_error = str(exc)
45
 
46
+ whatsapp = getattr(app.state.container, "whatsapp", None)
47
+ run_retry_worker = getattr(whatsapp, "run_retry_worker", None)
48
+ if callable(run_retry_worker):
49
+ retry_worker = asyncio.create_task(run_retry_worker())
50
+
51
+ try:
52
+ yield
53
+ finally:
54
+ if retry_worker is not None:
55
+ retry_worker.cancel()
56
+ try:
57
+ await retry_worker
58
+ except asyncio.CancelledError:
59
+ pass
60
 
61
  app = FastAPI(title="FALZH API", version="0.1.0", lifespan=lifespan)
62
  app.include_router(router)
app/services/container.py CHANGED
@@ -8,6 +8,7 @@ from app.services.conversation_service import ConversationService
8
  from app.services.embedding_service import JinaEmbeddingService
9
  from app.services.group_message_service import GroupMessageService
10
  from app.whatsapp.client import WhatsAppClient
 
11
 
12
 
13
  @dataclass(slots=True)
@@ -15,7 +16,7 @@ class ServiceContainer:
15
  settings: Settings
16
  repository: SupabaseRepository
17
  embeddings: JinaEmbeddingService
18
- whatsapp: WhatsAppClient
19
  ai: LiteLLMOrchestration
20
  conversation: ConversationService
21
  group_message: GroupMessageService
@@ -26,7 +27,11 @@ class ServiceContainer:
26
  supabase_client = await create_supabase_client(settings)
27
  repository = SupabaseRepository(supabase_client)
28
  embeddings = JinaEmbeddingService(settings)
29
- whatsapp = WhatsAppClient(settings)
 
 
 
 
30
 
31
  ai = LiteLLMOrchestration(
32
  groq_api_key=settings.groq_api_key,
 
8
  from app.services.embedding_service import JinaEmbeddingService
9
  from app.services.group_message_service import GroupMessageService
10
  from app.whatsapp.client import WhatsAppClient
11
+ from app.whatsapp.outbox import WhatsAppOutbox
12
 
13
 
14
  @dataclass(slots=True)
 
16
  settings: Settings
17
  repository: SupabaseRepository
18
  embeddings: JinaEmbeddingService
19
+ whatsapp: WhatsAppOutbox
20
  ai: LiteLLMOrchestration
21
  conversation: ConversationService
22
  group_message: GroupMessageService
 
27
  supabase_client = await create_supabase_client(settings)
28
  repository = SupabaseRepository(supabase_client)
29
  embeddings = JinaEmbeddingService(settings)
30
+ whatsapp = WhatsAppOutbox(
31
+ repository=repository,
32
+ client=WhatsAppClient(settings),
33
+ retry_interval_seconds=settings.whatsapp_retry_interval_seconds,
34
+ )
35
 
36
  ai = LiteLLMOrchestration(
37
  groq_api_key=settings.groq_api_key,
app/tools/handlers.py CHANGED
@@ -23,7 +23,7 @@ from app.utils.departure import (
23
  trip_satisfies_departure_request,
24
  )
25
  from app.utils.emoji import count_emojis
26
- from app.whatsapp.client import WhatsAppClient, WhatsAppClientError
27
  from app.whatsapp.trip_selection import format_trip_card
28
 
29
 
@@ -33,7 +33,7 @@ class FalzhToolHandlers:
33
  *,
34
  repository: SupabaseRepository,
35
  embeddings: JinaEmbeddingService,
36
- whatsapp: WhatsAppClient,
37
  customer: dict[str, Any],
38
  remoteJid: str,
39
  embedding_model: str,
@@ -203,6 +203,17 @@ class FalzhToolHandlers:
203
  whatsapp_message_id=wam_id,
204
  metadata={"trip_id": trip_id, "type": "trip_card"},
205
  )
 
 
 
 
 
 
 
 
 
 
 
206
  except WhatsAppClientError:
207
  logger.warning("Failed to send trip card for trip %s", trip_id)
208
 
@@ -292,7 +303,7 @@ class FalzhToolHandlers:
292
 
293
  if is_registered and driver_recipient:
294
  try:
295
- await self.whatsapp.send_text(
296
  driver_recipient,
297
  _driver_notification_text(
298
  customer=self.customer,
@@ -301,7 +312,13 @@ class FalzhToolHandlers:
301
  notes=notes,
302
  ),
303
  )
304
- notification_status = "sent"
 
 
 
 
 
 
305
  except Exception as exc: # noqa: BLE001
306
  notification_status = "failed"
307
  notification_error = str(exc)
@@ -433,6 +450,17 @@ class FalzhToolHandlers:
433
  whatsapp_message_id=wam_id,
434
  metadata={"trip_id": trip_id, "type": "driver_trip_card"},
435
  )
 
 
 
 
 
 
 
 
 
 
 
436
  except WhatsAppClientError:
437
  logger.warning("Failed to send trip card for trip %s", trip_id)
438
 
@@ -707,6 +735,18 @@ class FalzhToolHandlers:
707
  whatsapp_message_id=wam_id,
708
  metadata={"trip_id": trip_id, "type": "driver_trip_card", "action": action_type},
709
  )
 
 
 
 
 
 
 
 
 
 
 
 
710
  except WhatsAppClientError:
711
  logger.warning("Failed to send trip card for trip %s", trip_id)
712
 
 
23
  trip_satisfies_departure_request,
24
  )
25
  from app.utils.emoji import count_emojis
26
+ from app.whatsapp.client import WhatsAppClientError, WhatsAppSender
27
  from app.whatsapp.trip_selection import format_trip_card
28
 
29
 
 
33
  *,
34
  repository: SupabaseRepository,
35
  embeddings: JinaEmbeddingService,
36
+ whatsapp: WhatsAppSender,
37
  customer: dict[str, Any],
38
  remoteJid: str,
39
  embedding_model: str,
 
203
  whatsapp_message_id=wam_id,
204
  metadata={"trip_id": trip_id, "type": "trip_card"},
205
  )
206
+ elif resp.get("outbox_id"):
207
+ await self.repository.create_message(
208
+ customer_id=str(self.customer["id"]),
209
+ sender_type="assistant",
210
+ message=card,
211
+ metadata={
212
+ "trip_id": trip_id,
213
+ "type": "trip_card",
214
+ "outbox_id": resp["outbox_id"],
215
+ },
216
+ )
217
  except WhatsAppClientError:
218
  logger.warning("Failed to send trip card for trip %s", trip_id)
219
 
 
303
 
304
  if is_registered and driver_recipient:
305
  try:
306
+ receipt = await self.whatsapp.send_text(
307
  driver_recipient,
308
  _driver_notification_text(
309
  customer=self.customer,
 
312
  notes=notes,
313
  ),
314
  )
315
+ if receipt.get("queued") or receipt.get("failed"):
316
+ notification_status = "failed"
317
+ notification_error = (
318
+ receipt.get("error") or "Notification queued for retry"
319
+ )
320
+ else:
321
+ notification_status = "sent"
322
  except Exception as exc: # noqa: BLE001
323
  notification_status = "failed"
324
  notification_error = str(exc)
 
450
  whatsapp_message_id=wam_id,
451
  metadata={"trip_id": trip_id, "type": "driver_trip_card"},
452
  )
453
+ elif resp.get("outbox_id"):
454
+ await self.repository.create_message(
455
+ customer_id=str(self.customer["id"]),
456
+ sender_type="assistant",
457
+ message=card,
458
+ metadata={
459
+ "trip_id": trip_id,
460
+ "type": "driver_trip_card",
461
+ "outbox_id": resp["outbox_id"],
462
+ },
463
+ )
464
  except WhatsAppClientError:
465
  logger.warning("Failed to send trip card for trip %s", trip_id)
466
 
 
735
  whatsapp_message_id=wam_id,
736
  metadata={"trip_id": trip_id, "type": "driver_trip_card", "action": action_type},
737
  )
738
+ elif resp.get("outbox_id"):
739
+ await self.repository.create_message(
740
+ customer_id=str(self.customer["id"]),
741
+ sender_type="assistant",
742
+ message=card,
743
+ metadata={
744
+ "trip_id": trip_id,
745
+ "type": "driver_trip_card",
746
+ "action": action_type,
747
+ "outbox_id": resp["outbox_id"],
748
+ },
749
+ )
750
  except WhatsAppClientError:
751
  logger.warning("Failed to send trip card for trip %s", trip_id)
752
 
app/whatsapp/client.py CHANGED
@@ -1,3 +1,5 @@
 
 
1
  import httpx
2
 
3
  from app.config import Settings
@@ -5,7 +7,26 @@ from app.utils.whatsapp_format import to_whatsapp_markup
5
 
6
 
7
  class WhatsAppClientError(RuntimeError):
8
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
 
11
  class WhatsAppClient:
@@ -18,61 +39,62 @@ class WhatsAppClient:
18
  base = self._settings.whatsapp_graph_url.rstrip("/")
19
  version = self._settings.whatsapp_api_version.strip("/")
20
  phone_number_id = self._settings.whatsapp_phone_number_id
21
- print(base)
22
  return f"{base}/{version}/{phone_number_id}/messages"
23
 
24
- async def send_text(self, remoteJid: str, text: str) -> dict:
25
- payload = {
26
  "messaging_product": "whatsapp",
27
  "recipient_type": "individual",
28
  "to": remoteJid,
29
  "type": "text",
30
  "text": {"preview_url": False, "body": to_whatsapp_markup(text)},
31
  }
32
- headers = {
33
- "Authorization": f"Bearer {self._settings.whatsapp_access_token}",
34
- "Content-Type": "application/json",
35
- }
36
-
37
- if self._client is not None:
38
- response = await self._client.post(self._messages_url, json=payload, headers=headers)
39
- else:
40
- async with httpx.AsyncClient(timeout=self._settings.request_timeout_seconds) as client:
41
- response = await client.post(self._messages_url, json=payload, headers=headers)
42
-
43
- if response.status_code >= 400:
44
- raise WhatsAppClientError(
45
- f"WhatsApp API failed with {response.status_code}: {response.text}"
46
- )
47
-
48
- return response.json()
49
 
50
- async def send_interactive_list(
51
  self,
52
  remoteJid: str,
53
  interactive: dict[str, Any],
54
- ) -> dict:
55
- payload = {
56
  "messaging_product": "whatsapp",
57
  "recipient_type": "individual",
58
  "to": remoteJid,
59
  "type": "interactive",
60
  "interactive": interactive,
61
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  headers = {
63
  "Authorization": f"Bearer {self._settings.whatsapp_access_token}",
64
  "Content-Type": "application/json",
65
  }
66
 
67
  if self._client is not None:
68
- response = await self._client.post(self._messages_url, json=payload, headers=headers)
 
 
 
 
69
  else:
70
  async with httpx.AsyncClient(timeout=self._settings.request_timeout_seconds) as client:
71
  response = await client.post(self._messages_url, json=payload, headers=headers)
72
 
73
  if response.status_code >= 400:
74
  raise WhatsAppClientError(
75
- f"WhatsApp API failed with {response.status_code}: {response.text}"
 
76
  )
77
 
78
  return response.json()
 
1
+ from typing import Any, Protocol
2
+
3
  import httpx
4
 
5
  from app.config import Settings
 
7
 
8
 
9
  class WhatsAppClientError(RuntimeError):
10
+ def __init__(self, message: str, *, status_code: int | None = None) -> None:
11
+ super().__init__(message)
12
+ self.status_code = status_code
13
+ self.retryable = (
14
+ status_code is None
15
+ or status_code in {408, 429}
16
+ or status_code >= 500
17
+ )
18
+
19
+
20
+ class WhatsAppSender(Protocol):
21
+ async def send_text(self, remoteJid: str, text: str) -> dict[str, Any]:
22
+ ...
23
+
24
+ async def send_interactive_list(
25
+ self,
26
+ remoteJid: str,
27
+ interactive: dict[str, Any],
28
+ ) -> dict[str, Any]:
29
+ ...
30
 
31
 
32
  class WhatsAppClient:
 
39
  base = self._settings.whatsapp_graph_url.rstrip("/")
40
  version = self._settings.whatsapp_api_version.strip("/")
41
  phone_number_id = self._settings.whatsapp_phone_number_id
 
42
  return f"{base}/{version}/{phone_number_id}/messages"
43
 
44
+ def build_text_payload(self, remoteJid: str, text: str) -> dict[str, Any]:
45
+ return {
46
  "messaging_product": "whatsapp",
47
  "recipient_type": "individual",
48
  "to": remoteJid,
49
  "type": "text",
50
  "text": {"preview_url": False, "body": to_whatsapp_markup(text)},
51
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
+ def build_interactive_list_payload(
54
  self,
55
  remoteJid: str,
56
  interactive: dict[str, Any],
57
+ ) -> dict[str, Any]:
58
+ return {
59
  "messaging_product": "whatsapp",
60
  "recipient_type": "individual",
61
  "to": remoteJid,
62
  "type": "interactive",
63
  "interactive": interactive,
64
  }
65
+
66
+ async def send_text(self, remoteJid: str, text: str) -> dict[str, Any]:
67
+ return await self.send_payload(self.build_text_payload(remoteJid, text))
68
+
69
+ async def send_interactive_list(
70
+ self,
71
+ remoteJid: str,
72
+ interactive: dict[str, Any],
73
+ ) -> dict[str, Any]:
74
+ return await self.send_payload(
75
+ self.build_interactive_list_payload(remoteJid, interactive)
76
+ )
77
+
78
+ async def send_payload(self, payload: dict[str, Any]) -> dict[str, Any]:
79
  headers = {
80
  "Authorization": f"Bearer {self._settings.whatsapp_access_token}",
81
  "Content-Type": "application/json",
82
  }
83
 
84
  if self._client is not None:
85
+ response = await self._client.post(
86
+ self._messages_url,
87
+ json=payload,
88
+ headers=headers,
89
+ )
90
  else:
91
  async with httpx.AsyncClient(timeout=self._settings.request_timeout_seconds) as client:
92
  response = await client.post(self._messages_url, json=payload, headers=headers)
93
 
94
  if response.status_code >= 400:
95
  raise WhatsAppClientError(
96
+ f"WhatsApp API failed with {response.status_code}: {response.text}",
97
+ status_code=response.status_code,
98
  )
99
 
100
  return response.json()
app/whatsapp/outbox.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import logging
3
+ from datetime import UTC, datetime, timedelta
4
+ from typing import Any
5
+
6
+ from app.database.supabase import SupabaseRepository
7
+ from app.whatsapp.client import WhatsAppClient, WhatsAppClientError
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ class WhatsAppOutbox:
13
+ def __init__(
14
+ self,
15
+ *,
16
+ repository: SupabaseRepository,
17
+ client: WhatsAppClient,
18
+ retry_interval_seconds: int,
19
+ ) -> None:
20
+ self.repository = repository
21
+ self.client = client
22
+ self.retry_interval_seconds = retry_interval_seconds
23
+
24
+ async def send_text(self, remoteJid: str, text: str) -> dict[str, Any]:
25
+ payload = self.client.build_text_payload(remoteJid, text)
26
+ return await self._enqueue_and_send(remoteJid, payload)
27
+
28
+ async def send_interactive_list(
29
+ self,
30
+ remoteJid: str,
31
+ interactive: dict[str, Any],
32
+ ) -> dict[str, Any]:
33
+ payload = self.client.build_interactive_list_payload(remoteJid, interactive)
34
+ return await self._enqueue_and_send(remoteJid, payload)
35
+
36
+ async def _enqueue_and_send(
37
+ self,
38
+ recipient: str,
39
+ payload: dict[str, Any],
40
+ ) -> dict[str, Any]:
41
+ row = await self.repository.enqueue_whatsapp_message(
42
+ recipient=recipient,
43
+ payload=payload,
44
+ )
45
+ oldest = await self.repository.get_oldest_active_whatsapp_message()
46
+ if not oldest or oldest.get("id") != row.get("id"):
47
+ return _queued_response(row)
48
+
49
+ claimed = await self.repository.claim_whatsapp_message(str(row["id"]))
50
+ if not claimed:
51
+ return _queued_response(row)
52
+
53
+ result = await self._deliver_claimed(claimed)
54
+ return result.get("response") or _queued_response(row)
55
+
56
+ async def run_retry_worker(self) -> None:
57
+ while True:
58
+ await asyncio.sleep(self.retry_interval_seconds)
59
+ try:
60
+ await self.retry_pending_messages()
61
+ except Exception:
62
+ logger.exception("WhatsApp outbox retry pass failed")
63
+
64
+ async def retry_pending_messages(self) -> int:
65
+ lease_seconds = max(self.retry_interval_seconds * 2, 30)
66
+ stale_before = datetime.now(UTC) - timedelta(seconds=lease_seconds)
67
+ await self.repository.recover_stale_whatsapp_messages(stale_before=stale_before)
68
+
69
+ oldest = await self.repository.get_oldest_active_whatsapp_message()
70
+ if not oldest or oldest.get("status") != "pending":
71
+ return 0
72
+ if _is_future(oldest.get("next_attempt_at")):
73
+ return 0
74
+
75
+ claimed = await self.repository.claim_whatsapp_message(str(oldest["id"]))
76
+ if not claimed:
77
+ return 0
78
+
79
+ sent = 0
80
+ result = await self._deliver_claimed(claimed)
81
+ sent += int(result["sent"])
82
+ if result["retryable"]:
83
+ return sent
84
+
85
+ while True:
86
+ next_message = await self.repository.get_oldest_active_whatsapp_message()
87
+ if not next_message or next_message.get("status") != "pending":
88
+ break
89
+
90
+ claimed = await self.repository.claim_whatsapp_message(
91
+ str(next_message["id"]),
92
+ ignore_retry_time=True,
93
+ )
94
+ if not claimed:
95
+ break
96
+
97
+ result = await self._deliver_claimed(claimed)
98
+ sent += int(result["sent"])
99
+ if result["retryable"]:
100
+ break
101
+
102
+ return sent
103
+
104
+ async def _deliver_claimed(self, row: dict[str, Any]) -> dict[str, Any]:
105
+ try:
106
+ response = await self.client.send_payload(row["payload"])
107
+ except Exception as exc: # noqa: BLE001
108
+ retryable = not isinstance(exc, WhatsAppClientError) or exc.retryable
109
+ retry_at = datetime.now(UTC) + timedelta(seconds=self.retry_interval_seconds)
110
+ await self.repository.fail_whatsapp_message(
111
+ str(row["id"]),
112
+ error=str(exc),
113
+ retryable=retryable,
114
+ retry_at=retry_at,
115
+ )
116
+ logger.warning(
117
+ "WhatsApp delivery failed for outbox message %s (retryable=%s): %s",
118
+ row["id"],
119
+ retryable,
120
+ exc,
121
+ )
122
+ return {
123
+ "sent": False,
124
+ "retryable": retryable,
125
+ "response": _queued_response(row, error=str(exc), retryable=retryable),
126
+ }
127
+
128
+ await self.repository.mark_whatsapp_message_sent(
129
+ str(row["id"]),
130
+ provider_response=response,
131
+ )
132
+ return {"sent": True, "retryable": False, "response": response}
133
+
134
+
135
+ def _queued_response(
136
+ row: dict[str, Any],
137
+ *,
138
+ error: str | None = None,
139
+ retryable: bool = True,
140
+ ) -> dict[str, Any]:
141
+ response: dict[str, Any] = {
142
+ "messages": [{}],
143
+ "queued": retryable,
144
+ "failed": not retryable,
145
+ "outbox_id": row.get("id"),
146
+ }
147
+ if error:
148
+ response["error"] = error
149
+ return response
150
+
151
+
152
+ def _is_future(value: Any) -> bool:
153
+ if not value:
154
+ return False
155
+ try:
156
+ scheduled = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
157
+ except ValueError:
158
+ return False
159
+ if scheduled.tzinfo is None:
160
+ scheduled = scheduled.replace(tzinfo=UTC)
161
+ return scheduled > datetime.now(UTC)
supabase/migrations/202610140001_whatsapp_outbox.sql ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ create table if not exists public.whatsapp_outbox (
2
+ id uuid primary key default gen_random_uuid(),
3
+ recipient text not null,
4
+ payload jsonb not null,
5
+ status text not null default 'pending'
6
+ check (status in ('pending', 'sending', 'sent', 'failed')),
7
+ attempts integer not null default 0 check (attempts >= 0),
8
+ next_attempt_at timestamptz not null default now(),
9
+ last_attempt_at timestamptz,
10
+ locked_at timestamptz,
11
+ sent_at timestamptz,
12
+ last_error text,
13
+ provider_response jsonb,
14
+ created_at timestamptz not null default now()
15
+ );
16
+
17
+ create index if not exists idx_whatsapp_outbox_queue
18
+ on public.whatsapp_outbox (created_at, id)
19
+ where status in ('pending', 'sending');
20
+
21
+ alter table public.whatsapp_outbox enable row level security;
22
+
23
+ grant all on table public.whatsapp_outbox to service_role;
supabase/migrations/public_schema.sql CHANGED
@@ -349,6 +349,28 @@ CREATE TABLE public.messages (
349
  );
350
 
351
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
352
  --
353
  -- Name: trip_selections; Type: TABLE; Schema: public; Owner: -
354
  --
@@ -574,6 +596,13 @@ CREATE INDEX idx_falzh_info_chunks_embedding ON public.falzh_info_chunks USING h
574
  CREATE INDEX idx_messages_customer_created_at ON public.messages USING btree (customer_id, created_at DESC);
575
 
576
 
 
 
 
 
 
 
 
577
  --
578
  -- Name: idx_trip_selections_customer; Type: INDEX; Schema: public; Owner: -
579
  --
@@ -764,6 +793,12 @@ ALTER TABLE public.falzh_info_chunks ENABLE ROW LEVEL SECURITY;
764
 
765
  ALTER TABLE public.messages ENABLE ROW LEVEL SECURITY;
766
 
 
 
 
 
 
 
767
  --
768
  -- Name: trip_selections; Type: ROW SECURITY; Schema: public; Owner: -
769
  --
 
349
  );
350
 
351
 
352
+ --
353
+ -- Name: whatsapp_outbox; Type: TABLE; Schema: public; Owner: -
354
+ --
355
+
356
+ CREATE TABLE public.whatsapp_outbox (
357
+ id uuid DEFAULT gen_random_uuid() NOT NULL,
358
+ recipient text NOT NULL,
359
+ payload jsonb NOT NULL,
360
+ status text DEFAULT 'pending'::text NOT NULL,
361
+ attempts integer DEFAULT 0 NOT NULL,
362
+ next_attempt_at timestamp with time zone DEFAULT now() NOT NULL,
363
+ last_attempt_at timestamp with time zone,
364
+ locked_at timestamp with time zone,
365
+ sent_at timestamp with time zone,
366
+ last_error text,
367
+ provider_response jsonb,
368
+ created_at timestamp with time zone DEFAULT now() NOT NULL,
369
+ CONSTRAINT whatsapp_outbox_status_check CHECK ((status = ANY (ARRAY['pending'::text, 'sending'::text, 'sent'::text, 'failed'::text]))),
370
+ CONSTRAINT whatsapp_outbox_attempts_check CHECK ((attempts >= 0))
371
+ );
372
+
373
+
374
  --
375
  -- Name: trip_selections; Type: TABLE; Schema: public; Owner: -
376
  --
 
596
  CREATE INDEX idx_messages_customer_created_at ON public.messages USING btree (customer_id, created_at DESC);
597
 
598
 
599
+ --
600
+ -- Name: idx_whatsapp_outbox_queue; Type: INDEX; Schema: public; Owner: -
601
+ --
602
+
603
+ CREATE INDEX idx_whatsapp_outbox_queue ON public.whatsapp_outbox USING btree (created_at, id) WHERE (status = ANY (ARRAY['pending'::text, 'sending'::text]));
604
+
605
+
606
  --
607
  -- Name: idx_trip_selections_customer; Type: INDEX; Schema: public; Owner: -
608
  --
 
793
 
794
  ALTER TABLE public.messages ENABLE ROW LEVEL SECURITY;
795
 
796
+ --
797
+ -- Name: whatsapp_outbox; Type: ROW SECURITY; Schema: public; Owner: -
798
+ --
799
+
800
+ ALTER TABLE public.whatsapp_outbox ENABLE ROW LEVEL SECURITY;
801
+
802
  --
803
  -- Name: trip_selections; Type: ROW SECURITY; Schema: public; Owner: -
804
  --