continuum-task-server-bundle 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. continuum_task_server_bundle/__init__.py +1 -0
  2. continuum_task_server_bundle/daytona/__init__.py +4 -0
  3. continuum_task_server_bundle/daytona/common.py +534 -0
  4. continuum_task_server_bundle/daytona/create_sandbox.py +166 -0
  5. continuum_task_server_bundle/daytona/dispatch.py +125 -0
  6. continuum_task_server_bundle/daytona/execute_sandbox.py +243 -0
  7. continuum_task_server_bundle/daytona/filesystem.py +330 -0
  8. continuum_task_server_bundle/daytona/fs_edit.py +127 -0
  9. continuum_task_server_bundle/daytona/git_ops.py +585 -0
  10. continuum_task_server_bundle/daytona/github_app.py +207 -0
  11. continuum_task_server_bundle/daytona/manage_sandbox.py +104 -0
  12. continuum_task_server_bundle/daytona/plugin.py +18 -0
  13. continuum_task_server_bundle/daytona/s3_transfer.py +207 -0
  14. continuum_task_server_bundle/discord/__init__.py +4 -0
  15. continuum_task_server_bundle/discord/attachment_registry_db.py +127 -0
  16. continuum_task_server_bundle/discord/attachment_resolve.py +213 -0
  17. continuum_task_server_bundle/discord/await_cleanup.py +105 -0
  18. continuum_task_server_bundle/discord/discord_ready.py +39 -0
  19. continuum_task_server_bundle/discord/message_await_apply.py +143 -0
  20. continuum_task_server_bundle/discord/message_await_db.py +197 -0
  21. continuum_task_server_bundle/discord/message_await_inbound.py +54 -0
  22. continuum_task_server_bundle/discord/message_await_logic.py +133 -0
  23. continuum_task_server_bundle/discord/message_await_poller.py +122 -0
  24. continuum_task_server_bundle/discord/message_chunking.py +45 -0
  25. continuum_task_server_bundle/discord/methods.py +408 -0
  26. continuum_task_server_bundle/discord/plugin.py +105 -0
  27. continuum_task_server_bundle/discord/reaction_await_apply.py +238 -0
  28. continuum_task_server_bundle/discord/reaction_await_db.py +174 -0
  29. continuum_task_server_bundle/discord/reaction_await_inbound.py +47 -0
  30. continuum_task_server_bundle/discord/reaction_await_logic.py +118 -0
  31. continuum_task_server_bundle/discord/reaction_await_poller.py +131 -0
  32. continuum_task_server_bundle/discord/s3_attachment_config.py +25 -0
  33. continuum_task_server_bundle/discord/s3_message_attachments.py +139 -0
  34. continuum_task_server_bundle/discord/sql/001_message_awaits.sql +112 -0
  35. continuum_task_server_bundle/discord/sql/002_reaction_awaits.sql +61 -0
  36. continuum_task_server_bundle/github/__init__.py +4 -0
  37. continuum_task_server_bundle/github/awaits/__init__.py +1 -0
  38. continuum_task_server_bundle/github/awaits/apply.py +92 -0
  39. continuum_task_server_bundle/github/awaits/cleanup.py +94 -0
  40. continuum_task_server_bundle/github/awaits/db.py +220 -0
  41. continuum_task_server_bundle/github/awaits/evaluators.py +325 -0
  42. continuum_task_server_bundle/github/awaits/fetch.py +192 -0
  43. continuum_task_server_bundle/github/awaits/poller.py +82 -0
  44. continuum_task_server_bundle/github/awaits/register.py +37 -0
  45. continuum_task_server_bundle/github/ci_status.py +70 -0
  46. continuum_task_server_bundle/github/comment_normalize.py +76 -0
  47. continuum_task_server_bundle/github/errors.py +52 -0
  48. continuum_task_server_bundle/github/github_app.py +291 -0
  49. continuum_task_server_bundle/github/github_http.py +377 -0
  50. continuum_task_server_bundle/github/methods/__init__.py +90 -0
  51. continuum_task_server_bundle/github/methods/_common.py +183 -0
  52. continuum_task_server_bundle/github/methods/awaits.py +107 -0
  53. continuum_task_server_bundle/github/methods/ci.py +158 -0
  54. continuum_task_server_bundle/github/methods/comments.py +214 -0
  55. continuum_task_server_bundle/github/methods/credentials.py +59 -0
  56. continuum_task_server_bundle/github/methods/issues.py +131 -0
  57. continuum_task_server_bundle/github/methods/pulls.py +329 -0
  58. continuum_task_server_bundle/github/methods/repos.py +424 -0
  59. continuum_task_server_bundle/github/methods/search.py +109 -0
  60. continuum_task_server_bundle/github/plugin.py +91 -0
  61. continuum_task_server_bundle/github/sql/001_github_awaits.sql +65 -0
  62. continuum_task_server_bundle/github/webhook_server.py +126 -0
  63. continuum_task_server_bundle/jira/__init__.py +4 -0
  64. continuum_task_server_bundle/jira/await_poller.py +236 -0
  65. continuum_task_server_bundle/jira/await_store.py +271 -0
  66. continuum_task_server_bundle/jira/config.py +68 -0
  67. continuum_task_server_bundle/jira/jira_client.py +382 -0
  68. continuum_task_server_bundle/jira/methods.py +246 -0
  69. continuum_task_server_bundle/jira/plugin.py +86 -0
  70. continuum_task_server_bundle/jira/sql/001_jira_issue_comment_waits.sql +19 -0
  71. continuum_task_server_bundle/jira/webhook.py +70 -0
  72. continuum_task_server_bundle/openrouter/__init__.py +4 -0
  73. continuum_task_server_bundle/openrouter/chat_service.py +1037 -0
  74. continuum_task_server_bundle/openrouter/chat_store.py +849 -0
  75. continuum_task_server_bundle/openrouter/environment.py +29 -0
  76. continuum_task_server_bundle/openrouter/handler.py +59 -0
  77. continuum_task_server_bundle/openrouter/image_context.py +207 -0
  78. continuum_task_server_bundle/openrouter/openrouter_client.py +324 -0
  79. continuum_task_server_bundle/openrouter/plugin.py +37 -0
  80. continuum_task_server_bundle/openrouter/prompt_projection.py +417 -0
  81. continuum_task_server_bundle/openrouter/sql/chat.sql +50 -0
  82. continuum_task_server_bundle/openrouter/sql/migrate_prune_then_chunk_v1.sql +11 -0
  83. continuum_task_server_bundle/roblox/__init__.py +4 -0
  84. continuum_task_server_bundle/roblox/open_cloud.py +335 -0
  85. continuum_task_server_bundle/roblox/plugin.py +30 -0
  86. continuum_task_server_bundle/roblox/storage_s3.py +55 -0
  87. continuum_task_server_bundle-1.0.0.dist-info/METADATA +109 -0
  88. continuum_task_server_bundle-1.0.0.dist-info/RECORD +90 -0
  89. continuum_task_server_bundle-1.0.0.dist-info/WHEEL +5 -0
  90. continuum_task_server_bundle-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,213 @@
1
+ """Resolve Discord attachments to S3 (optional; Continuum task method)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any
7
+ from uuid import UUID
8
+
9
+ import discord
10
+
11
+ import continuum_task_server_bundle.discord.attachment_registry_db as reg
12
+ import continuum_task_server_bundle.discord.message_await_db as mdb
13
+ import continuum_task_server_bundle.discord.s3_attachment_config as s3cfg
14
+ from continuum_task_server_bundle.discord.methods import _await_on_discord_client, get_message_container_by_ids
15
+
16
+
17
+ def _sanitize_filename(name: str) -> str:
18
+ return re.sub(r"[^a-zA-Z0-9._-]+", "_", name)[:200] or "file"
19
+
20
+
21
+ def _messageable(client: discord.Client, channel_id: int) -> discord.abc.Messageable:
22
+ ch = client.get_channel(channel_id)
23
+ if ch is None:
24
+ raise RuntimeError(
25
+ f"Discord channel or thread {channel_id} not found (check id and intents)"
26
+ )
27
+ return ch # type: ignore[return-value]
28
+
29
+
30
+ def _container_for_fetch(
31
+ client: discord.Client, data: dict[str, Any], *, fallback_channel_id: int
32
+ ) -> discord.abc.Messageable:
33
+ """If input has parent channel_id + thread_id, resolve thread; else fetch by channel/thread id."""
34
+ raw_thread = data.get("thread_id")
35
+ raw_channel = data.get("channel_id")
36
+ if raw_thread is not None and raw_channel is not None:
37
+ return get_message_container_by_ids(
38
+ client, int(raw_channel), int(raw_thread)
39
+ )
40
+ return _messageable(client, fallback_channel_id)
41
+
42
+
43
+ async def _read_attachment_bytes(att: discord.Attachment) -> bytes:
44
+ return await att.read()
45
+
46
+
47
+ def _find_attachment(
48
+ message: discord.Message, discord_attachment_id: int
49
+ ) -> discord.Attachment | None:
50
+ for a in message.attachments:
51
+ if int(a.id) == discord_attachment_id:
52
+ return a
53
+ return None
54
+
55
+
56
+ def resolve_attachment_to_s3(client: discord.Client, input_data: dict | None) -> dict[str, Any]:
57
+ """Archive a Discord attachment to S3; idempotent. Structured errors only (no raise)."""
58
+ data = input_data or {}
59
+ if not mdb.database_url():
60
+ return {"success": False, "error": "DATABASE_URL is not set"}
61
+ if not s3cfg.s3_configured():
62
+ return {
63
+ "success": False,
64
+ "error": "S3 not configured (set S3_ATTACHMENTS_BUCKET)",
65
+ }
66
+
67
+ row: dict[str, Any] | None = None
68
+ raw_ref = data.get("attachment_ref")
69
+
70
+ if raw_ref is not None:
71
+ try:
72
+ ref_uuid = UUID(str(raw_ref))
73
+ except (ValueError, TypeError):
74
+ return {"success": False, "error": "Invalid attachment_ref"}
75
+ row = reg.get_by_ref(attachment_ref=ref_uuid)
76
+ if row is None:
77
+ return {"success": False, "error": "Unknown attachment_ref"}
78
+ else:
79
+ da_raw = data.get("discord_attachment_id") or data.get("attachment_id")
80
+ if da_raw is None:
81
+ return {
82
+ "success": False,
83
+ "error": "Provide attachment_ref or channel_id, message_id, and discord_attachment_id",
84
+ }
85
+ try:
86
+ channel_id = int(data["channel_id"])
87
+ message_id = int(data["message_id"])
88
+ discord_attachment_id = int(da_raw)
89
+ except (KeyError, TypeError, ValueError):
90
+ return {
91
+ "success": False,
92
+ "error": "Provide attachment_ref or channel_id, message_id, and discord_attachment_id",
93
+ }
94
+
95
+ row = reg.get_by_triplet(
96
+ channel_id=channel_id,
97
+ message_id=message_id,
98
+ discord_attachment_id=discord_attachment_id,
99
+ )
100
+
101
+ if row is None:
102
+ try:
103
+ container = _container_for_fetch(
104
+ client, data, fallback_channel_id=channel_id
105
+ )
106
+ message = _await_on_discord_client(
107
+ client, container.fetch_message(message_id), timeout=60.0
108
+ )
109
+ except Exception as e:
110
+ return {"success": False, "error": f"Discord fetch failed: {e}"}
111
+
112
+ att = _find_attachment(message, discord_attachment_id)
113
+ if att is None:
114
+ return {"success": False, "error": "Attachment not found on message"}
115
+
116
+ ref = reg.ensure_attachment_ref(
117
+ channel_id=int(message.channel.id),
118
+ message_id=int(message.id),
119
+ discord_attachment_id=discord_attachment_id,
120
+ filename=att.filename or "",
121
+ size=int(att.size or 0),
122
+ content_type=att.content_type,
123
+ ephemeral=bool(att.ephemeral),
124
+ )
125
+ if ref is None:
126
+ return {"success": False, "error": "Failed to create registry row"}
127
+ row = reg.get_by_ref(attachment_ref=ref)
128
+ if row is None:
129
+ return {"success": False, "error": "Registry row not found after insert"}
130
+
131
+ if row is None:
132
+ return {"success": False, "error": "Registry row not found"}
133
+
134
+ existing_uri = row.get("s3_uri")
135
+ if existing_uri:
136
+ return {
137
+ "success": True,
138
+ "attachment_ref": str(row["id"]),
139
+ "s3_uri": existing_uri,
140
+ "s3_bucket": row.get("s3_bucket"),
141
+ "s3_key": row.get("s3_key"),
142
+ "cached": True,
143
+ }
144
+
145
+ registry_id = UUID(str(row["id"]))
146
+ channel_id = int(row["channel_id"])
147
+ message_id = int(row["message_id"])
148
+ discord_attachment_id = int(row["discord_attachment_id"])
149
+
150
+ try:
151
+ container = _container_for_fetch(client, data, fallback_channel_id=channel_id)
152
+ message = _await_on_discord_client(
153
+ client, container.fetch_message(message_id), timeout=60.0
154
+ )
155
+ except Exception as e:
156
+ return {"success": False, "error": f"Discord fetch failed: {e}"}
157
+
158
+ att = _find_attachment(message, discord_attachment_id)
159
+ if att is None:
160
+ return {"success": False, "error": "Attachment not found on message (re-fetch)"}
161
+
162
+ try:
163
+ body = _await_on_discord_client(
164
+ client, _read_attachment_bytes(att), timeout=120.0
165
+ )
166
+ except Exception as e:
167
+ return {"success": False, "error": f"Failed to read attachment: {e}"}
168
+
169
+ import boto3
170
+
171
+ bucket = s3cfg.s3_bucket()
172
+ assert bucket is not None
173
+ prefix = s3cfg.s3_prefix()
174
+ key = f"{prefix}{registry_id}/{_sanitize_filename(att.filename or 'file')}"
175
+ region = s3cfg.aws_region()
176
+ extra: dict[str, Any] = {}
177
+ if region:
178
+ extra["region_name"] = region
179
+ try:
180
+ s3 = boto3.client("s3", **extra)
181
+ ct = att.content_type or "application/octet-stream"
182
+ s3.put_object(Bucket=bucket, Key=key, Body=body, ContentType=ct)
183
+ except Exception as e:
184
+ return {"success": False, "error": f"S3 upload failed: {e}"}
185
+
186
+ s3_uri = f"s3://{bucket}/{key}"
187
+
188
+ if reg.try_set_s3_uri(
189
+ registry_id=registry_id,
190
+ s3_bucket=bucket,
191
+ s3_key=key,
192
+ s3_uri=s3_uri,
193
+ ):
194
+ return {
195
+ "success": True,
196
+ "attachment_ref": str(registry_id),
197
+ "s3_uri": s3_uri,
198
+ "s3_bucket": bucket,
199
+ "s3_key": key,
200
+ "cached": False,
201
+ }
202
+
203
+ row2 = reg.get_by_ref(attachment_ref=registry_id)
204
+ if row2 and row2.get("s3_uri"):
205
+ return {
206
+ "success": True,
207
+ "attachment_ref": str(registry_id),
208
+ "s3_uri": row2["s3_uri"],
209
+ "s3_bucket": row2.get("s3_bucket"),
210
+ "s3_key": row2.get("s3_key"),
211
+ "cached": True,
212
+ }
213
+ return {"success": False, "error": "Failed to persist S3 URI after upload"}
@@ -0,0 +1,105 @@
1
+ """Drop Postgres await rows when a Continuum queue item is no longer ours."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from typing import Any
7
+ from uuid import UUID
8
+
9
+ from continuum_task_server import TaskServer, TaskStatus
10
+ from continuum_task_server.exceptions import (
11
+ ContinuumError,
12
+ ForbiddenError,
13
+ NotFoundError,
14
+ RateLimitError,
15
+ ServerError,
16
+ TransportError,
17
+ UnauthorizedError,
18
+ )
19
+ from continuum_task_server.models import QueueItem
20
+
21
+ from continuum_task_server_bundle.discord import message_await_db
22
+ from continuum_task_server_bundle.discord import reaction_await_db
23
+ logger = logging.getLogger(__name__)
24
+
25
+ _TRANSIENT = (UnauthorizedError, ForbiddenError, RateLimitError, ServerError, TransportError)
26
+
27
+
28
+ def drop_await_rows(queue_item_id: UUID) -> None:
29
+ """Delete message_awaits and reaction_awaits rows for this queue item."""
30
+ if not message_await_db.database_url():
31
+ return
32
+ n_msg = 0
33
+ n_rxn = 0
34
+ try:
35
+ n_msg = message_await_db.delete_by_queue_item_id(queue_item_id)
36
+ except Exception:
37
+ logger.exception("delete message_awaits failed for %s", queue_item_id)
38
+ try:
39
+ n_rxn = reaction_await_db.delete_by_queue_item_id(queue_item_id)
40
+ except Exception:
41
+ logger.exception("delete reaction_awaits failed for %s", queue_item_id)
42
+ if n_msg or n_rxn:
43
+ logger.info(
44
+ "dropped await rows for %s (message=%s reaction=%s)",
45
+ queue_item_id,
46
+ n_msg,
47
+ n_rxn,
48
+ )
49
+
50
+
51
+ def heartbeat_claim_or_drop(server: TaskServer, queue_item_id: UUID) -> bool:
52
+ """Heartbeat the item; drop await rows unless it is still STARTED with no control.
53
+
54
+ Returns True if Discord polling should continue for this row.
55
+ """
56
+ claim = _active_claim(server, queue_item_id)
57
+ token = None if claim is None else getattr(claim, "claim_token", None)
58
+ latest: QueueItem | None = None
59
+ try:
60
+ latest = server.client.queue.heartbeat(queue_item_id, claim_token=token)
61
+ except ContinuumError as e:
62
+ if isinstance(e, _TRANSIENT):
63
+ logger.warning("heartbeat failed for %s: %s", queue_item_id, e)
64
+ return True
65
+ logger.info("heartbeat failed for %s: %s", queue_item_id, e)
66
+ try:
67
+ latest = server.client.queue.get_by_id(queue_item_id)
68
+ except NotFoundError:
69
+ _drop_and_release(queue_item_id, claim, reason="not found")
70
+ return False
71
+ except ContinuumError as e2:
72
+ logger.warning("get_by_id failed for %s: %s", queue_item_id, e2)
73
+ return True
74
+
75
+ if latest is None:
76
+ _drop_and_release(queue_item_id, claim, reason="empty heartbeat")
77
+ return False
78
+
79
+ control = latest.control_request
80
+ if latest.task_status is not TaskStatus.STARTED or (control is not None and control != ""):
81
+ _drop_and_release(
82
+ queue_item_id,
83
+ claim,
84
+ reason=f"status={latest.task_status} control={control!r}",
85
+ )
86
+ return False
87
+ return True
88
+
89
+
90
+ def _drop_and_release(queue_item_id: UUID, claim: Any, *, reason: str) -> None:
91
+ logger.info("queue item %s not runnable (%s); dropping await rows", queue_item_id, reason)
92
+ drop_await_rows(queue_item_id)
93
+ completed = getattr(claim, "completed", None)
94
+ if claim is None or (completed is not None and completed.is_set()):
95
+ return
96
+ signal = getattr(claim, "signal_control", None)
97
+ if callable(signal):
98
+ signal()
99
+
100
+
101
+ def _active_claim(server: TaskServer, queue_item_id: UUID) -> Any:
102
+ active = getattr(server, "_active", None)
103
+ if not isinstance(active, dict):
104
+ return None
105
+ return active.get(queue_item_id)
@@ -0,0 +1,39 @@
1
+ """Wait until the Discord gateway is connected and the client loop is running."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import time
7
+
8
+ import discord
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ def discord_usable(client: discord.Client) -> bool:
14
+ """True when the bot can use the gateway (channels in cache, loop accepting coroutines)."""
15
+ if not client.is_ready():
16
+ return False
17
+ loop = client.loop
18
+ if loop is None or not loop.is_running():
19
+ return False
20
+ return True
21
+
22
+
23
+ def wait_for_discord_ready(
24
+ client: discord.Client,
25
+ *,
26
+ timeout: float = 120.0,
27
+ poll_interval: float = 0.25,
28
+ ) -> None:
29
+ """Block until ``discord_usable`` or raise after ``timeout`` seconds."""
30
+ deadline = time.monotonic() + timeout
31
+ while time.monotonic() < deadline:
32
+ if discord_usable(client):
33
+ logger.info("Discord client ready (user=%s)", client.user)
34
+ return
35
+ time.sleep(poll_interval)
36
+ raise RuntimeError(
37
+ f"Discord client did not become ready within {timeout}s "
38
+ "(check DISCORD_TOKEN and network)"
39
+ )
@@ -0,0 +1,143 @@
1
+ """Transactional merge + Continuum completion for message_awaits.
2
+
3
+ Each call takes one Postgres transaction: ``SELECT ... FOR UPDATE`` on the row
4
+ (only ``status = 'active'``), merge in memory, then a single conditional ``UPDATE``.
5
+ Concurrent workers block on the same row or skip via claim-side ``SKIP LOCKED``;
6
+ they cannot apply lost updates to ``messages_json``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ from datetime import timedelta
13
+ from typing import Any
14
+ from uuid import UUID
15
+
16
+ import discord
17
+ from continuum_task_server import TaskServer
18
+ from continuum_task_server.exceptions import ContinuumError
19
+ from psycopg.types.json import Json
20
+
21
+ import continuum_task_server_bundle.discord.message_await_db as db
22
+ import continuum_task_server_bundle.discord.message_await_logic as logic
23
+ from continuum_task_server_bundle.discord.methods import message_to_dict
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+
28
+ def apply_new_discord_messages(
29
+ server: TaskServer,
30
+ row_id: UUID,
31
+ new_messages: list[discord.Message],
32
+ *,
33
+ heartbeat_after: bool = True,
34
+ client: discord.Client | None = None,
35
+ ) -> None:
36
+ """Merge new Discord messages into one await row under row lock; complete or persist.
37
+
38
+ ``new_messages`` may be empty (e.g. poll tick with no history) so timeout-only
39
+ completion still runs. If ``heartbeat_after`` is False, skip the post-commit
40
+ heartbeat (caller already heartbeats, e.g. the slow poller).
41
+ """
42
+
43
+ queue_item_id: UUID | None = None
44
+ completed_qid: UUID | None = None
45
+ completion_payload: dict[str, Any] | None = None
46
+
47
+ with db.connect() as conn:
48
+ with conn.transaction():
49
+ with conn.cursor() as cur:
50
+ cur.execute(
51
+ """
52
+ SELECT * FROM message_awaits
53
+ WHERE id = %s AND status = 'active'
54
+ FOR UPDATE
55
+ """,
56
+ (str(row_id),),
57
+ )
58
+ row = cur.fetchone()
59
+ if not row:
60
+ return
61
+
62
+ queue_item_id = row["queue_item_id"]
63
+ if isinstance(queue_item_id, str):
64
+ queue_item_id = UUID(queue_item_id)
65
+
66
+ accumulated = db.parse_messages_json(row.get("messages_json"))
67
+ msg_limit = int(row["message_limit"])
68
+ ignore_ids = logic.parse_ignore_message_ids(row)
69
+ ignore_own = logic.parse_ignore_own_bot_messages(row)
70
+ bot_uid = client.user.id if client and client.user else None
71
+ merged = logic.merge_messages(
72
+ accumulated,
73
+ new_messages,
74
+ message_limit=msg_limit,
75
+ message_to_dict=message_to_dict,
76
+ ignore_ids=ignore_ids,
77
+ ignore_own_bot=ignore_own,
78
+ bot_user_id=bot_uid,
79
+ )
80
+ last_at = logic.last_message_time(merged)
81
+ last_snowflake = logic.last_message_snowflake(merged)
82
+ now = db.utcnow()
83
+ should_complete, timed_out = logic.completion_decision(
84
+ merged=merged,
85
+ deadline_at=row["deadline_at"],
86
+ quiet_period_seconds=float(row["quiet_period_seconds"]),
87
+ now=now,
88
+ )
89
+
90
+ if should_complete:
91
+ cur.execute(
92
+ """
93
+ UPDATE message_awaits
94
+ SET status = 'completed', completed_at = now()
95
+ WHERE id = %s AND status = 'active'
96
+ RETURNING queue_item_id
97
+ """,
98
+ (str(row_id),),
99
+ )
100
+ done = cur.fetchone()
101
+ if done:
102
+ completed_qid = UUID(str(done["queue_item_id"]))
103
+ completion_payload = {
104
+ "success": True,
105
+ "messages": merged,
106
+ "timed_out": timed_out,
107
+ }
108
+ else:
109
+ poll_sec = float(row["poll_interval_seconds"])
110
+ quiet_sec = float(row["quiet_period_seconds"])
111
+ if len(merged) > 0 and quiet_sec > 0:
112
+ next_poll_at = now + timedelta(seconds=quiet_sec)
113
+ else:
114
+ next_poll_at = now + timedelta(seconds=poll_sec)
115
+ cur.execute(
116
+ """
117
+ UPDATE message_awaits
118
+ SET messages_json = %s,
119
+ last_message_snowflake = %s,
120
+ last_message_at = %s,
121
+ next_poll_at = %s
122
+ WHERE id = %s AND status = 'active'
123
+ """,
124
+ (
125
+ Json(merged),
126
+ last_snowflake,
127
+ last_at,
128
+ next_poll_at,
129
+ str(row_id),
130
+ ),
131
+ )
132
+
133
+ if heartbeat_after and queue_item_id is not None:
134
+ try:
135
+ server.client.queue.heartbeat(queue_item_id)
136
+ except ContinuumError as e:
137
+ logger.warning("heartbeat failed for %s: %s", queue_item_id, e)
138
+
139
+ if completed_qid is not None and completion_payload is not None:
140
+ try:
141
+ server.complete_queue_item(completed_qid, output_data=completion_payload)
142
+ except ContinuumError as e:
143
+ logger.error("complete_queue_item failed for %s: %s", completed_qid, e)
@@ -0,0 +1,197 @@
1
+ """PostgreSQL persistence for durable await_messages polling.
2
+
3
+ Concurrency (multiple worker processes against one database):
4
+
5
+ - ``claim_due_awaits`` uses ``FOR UPDATE SKIP LOCKED`` so only one poller claims a
6
+ given row per due time; others skip locked rows and pick different work.
7
+ - ``apply_new_discord_messages`` (see ``message_await_apply``) loads the row with
8
+ ``SELECT ... FOR UPDATE`` in one transaction, merges, then updates or completes
9
+ with ``WHERE status = 'active'`` so concurrent Discord events serialize per row.
10
+ - ``insert_message_await`` is a single ``INSERT ... ON CONFLICT DO NOTHING`` (atomic).
11
+ - ``mark_failed`` / completion inside ``apply`` use conditional ``UPDATE ... WHERE status = 'active'``
12
+ so only one writer wins terminal transitions.
13
+
14
+ Continuum HTTP calls (heartbeat, complete, fail) run **after** the DB transaction commits.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ from datetime import datetime, timedelta, timezone
21
+ from os import getenv
22
+ from typing import Any
23
+ from uuid import UUID
24
+
25
+ import psycopg
26
+ from psycopg.rows import dict_row
27
+ from psycopg.types.json import Json
28
+
29
+
30
+ def database_url() -> str | None:
31
+ url = getenv("DATABASE_URL")
32
+ return url if url else None
33
+
34
+
35
+ def connect():
36
+ url = database_url()
37
+ if not url:
38
+ raise RuntimeError("DATABASE_URL is not set")
39
+ return psycopg.connect(url, row_factory=dict_row)
40
+
41
+
42
+ def insert_message_await(
43
+ *,
44
+ queue_item_id: UUID,
45
+ channel_id: int,
46
+ thread_id: int | None,
47
+ after_message_id: int | None,
48
+ message_limit: int,
49
+ timeout_seconds: float,
50
+ poll_interval_seconds: float,
51
+ quiet_period_seconds: float,
52
+ ignore_message_ids: list[str],
53
+ ignore_own_bot_messages: bool,
54
+ ) -> bool:
55
+ """Insert a new await row. Returns True if inserted, False if queue_item_id already exists."""
56
+ deadline = timedelta(seconds=timeout_seconds)
57
+ with connect() as conn:
58
+ with conn.transaction():
59
+ with conn.cursor() as cur:
60
+ cur.execute(
61
+ """
62
+ INSERT INTO message_awaits (
63
+ queue_item_id,
64
+ channel_id,
65
+ thread_id,
66
+ after_message_id,
67
+ message_limit,
68
+ timeout_seconds,
69
+ poll_interval_seconds,
70
+ quiet_period_seconds,
71
+ deadline_at,
72
+ next_poll_at,
73
+ ignore_message_ids,
74
+ ignore_own_bot_messages
75
+ )
76
+ VALUES (
77
+ %s, %s, %s, %s, %s, %s, %s, %s,
78
+ now() + %s::interval,
79
+ now(),
80
+ %s,
81
+ %s
82
+ )
83
+ ON CONFLICT (queue_item_id) DO NOTHING
84
+ RETURNING id
85
+ """,
86
+ (
87
+ str(queue_item_id),
88
+ channel_id,
89
+ thread_id,
90
+ after_message_id,
91
+ message_limit,
92
+ timeout_seconds,
93
+ poll_interval_seconds,
94
+ quiet_period_seconds,
95
+ deadline,
96
+ Json(ignore_message_ids),
97
+ ignore_own_bot_messages,
98
+ ),
99
+ )
100
+ row = cur.fetchone()
101
+ return row is not None
102
+
103
+
104
+ def list_active_for_discord_channel(discord_channel_id: int) -> list[dict[str, Any]]:
105
+ """Active awaits listening on this Discord channel or thread id (message.channel.id)."""
106
+ with connect() as conn:
107
+ with conn.transaction():
108
+ with conn.cursor() as cur:
109
+ cur.execute(
110
+ """
111
+ SELECT * FROM message_awaits
112
+ WHERE status = 'active'
113
+ AND (
114
+ (thread_id IS NOT NULL AND thread_id = %(cid)s)
115
+ OR (thread_id IS NULL AND channel_id = %(cid)s)
116
+ )
117
+ """,
118
+ {"cid": discord_channel_id},
119
+ )
120
+ return list(cur.fetchall())
121
+
122
+
123
+ def claim_due_awaits(*, limit: int = 10) -> list[dict[str, Any]]:
124
+ """Atomically schedule next_poll_at and return rows due for a Discord poll."""
125
+ with connect() as conn:
126
+ with conn.transaction():
127
+ with conn.cursor() as cur:
128
+ cur.execute(
129
+ """
130
+ WITH picked AS (
131
+ SELECT id
132
+ FROM message_awaits
133
+ WHERE status = 'active' AND next_poll_at <= now()
134
+ ORDER BY next_poll_at
135
+ FOR UPDATE SKIP LOCKED
136
+ LIMIT %(lim)s
137
+ )
138
+ UPDATE message_awaits m
139
+ SET next_poll_at = now() + (m.poll_interval_seconds * INTERVAL '1 second')
140
+ FROM picked p
141
+ WHERE m.id = p.id AND m.status = 'active'
142
+ RETURNING m.*
143
+ """,
144
+ {"lim": limit},
145
+ )
146
+ return list(cur.fetchall())
147
+
148
+
149
+ def delete_by_queue_item_id(queue_item_id: UUID) -> int:
150
+ """Delete the await row for this queue item. Returns rows deleted (0 or 1)."""
151
+ with connect() as conn:
152
+ with conn.transaction():
153
+ with conn.cursor() as cur:
154
+ cur.execute(
155
+ """
156
+ DELETE FROM message_awaits
157
+ WHERE queue_item_id = %s
158
+ """,
159
+ (str(queue_item_id),),
160
+ )
161
+ return int(cur.rowcount or 0)
162
+
163
+
164
+ def mark_failed(*, row_id: UUID, error: dict[str, Any]) -> UUID | None:
165
+ """Set status failed if still active. Returns queue_item_id if updated."""
166
+ with connect() as conn:
167
+ with conn.transaction():
168
+ with conn.cursor() as cur:
169
+ cur.execute(
170
+ """
171
+ UPDATE message_awaits
172
+ SET status = 'failed',
173
+ completed_at = now(),
174
+ error_json = %s
175
+ WHERE id = %s AND status = 'active'
176
+ RETURNING queue_item_id
177
+ """,
178
+ (Json(error), str(row_id)),
179
+ )
180
+ one = cur.fetchone()
181
+ if not one:
182
+ return None
183
+ return UUID(str(one["queue_item_id"]))
184
+
185
+
186
+ def utcnow() -> datetime:
187
+ return datetime.now(timezone.utc)
188
+
189
+
190
+ def parse_messages_json(raw: Any) -> list[dict[str, Any]]:
191
+ if raw is None:
192
+ return []
193
+ if isinstance(raw, list):
194
+ return list(raw)
195
+ if isinstance(raw, str):
196
+ return json.loads(raw)
197
+ return list(raw)