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.
- continuum_task_server_bundle/__init__.py +1 -0
- continuum_task_server_bundle/daytona/__init__.py +4 -0
- continuum_task_server_bundle/daytona/common.py +534 -0
- continuum_task_server_bundle/daytona/create_sandbox.py +166 -0
- continuum_task_server_bundle/daytona/dispatch.py +125 -0
- continuum_task_server_bundle/daytona/execute_sandbox.py +243 -0
- continuum_task_server_bundle/daytona/filesystem.py +330 -0
- continuum_task_server_bundle/daytona/fs_edit.py +127 -0
- continuum_task_server_bundle/daytona/git_ops.py +585 -0
- continuum_task_server_bundle/daytona/github_app.py +207 -0
- continuum_task_server_bundle/daytona/manage_sandbox.py +104 -0
- continuum_task_server_bundle/daytona/plugin.py +18 -0
- continuum_task_server_bundle/daytona/s3_transfer.py +207 -0
- continuum_task_server_bundle/discord/__init__.py +4 -0
- continuum_task_server_bundle/discord/attachment_registry_db.py +127 -0
- continuum_task_server_bundle/discord/attachment_resolve.py +213 -0
- continuum_task_server_bundle/discord/await_cleanup.py +105 -0
- continuum_task_server_bundle/discord/discord_ready.py +39 -0
- continuum_task_server_bundle/discord/message_await_apply.py +143 -0
- continuum_task_server_bundle/discord/message_await_db.py +197 -0
- continuum_task_server_bundle/discord/message_await_inbound.py +54 -0
- continuum_task_server_bundle/discord/message_await_logic.py +133 -0
- continuum_task_server_bundle/discord/message_await_poller.py +122 -0
- continuum_task_server_bundle/discord/message_chunking.py +45 -0
- continuum_task_server_bundle/discord/methods.py +408 -0
- continuum_task_server_bundle/discord/plugin.py +105 -0
- continuum_task_server_bundle/discord/reaction_await_apply.py +238 -0
- continuum_task_server_bundle/discord/reaction_await_db.py +174 -0
- continuum_task_server_bundle/discord/reaction_await_inbound.py +47 -0
- continuum_task_server_bundle/discord/reaction_await_logic.py +118 -0
- continuum_task_server_bundle/discord/reaction_await_poller.py +131 -0
- continuum_task_server_bundle/discord/s3_attachment_config.py +25 -0
- continuum_task_server_bundle/discord/s3_message_attachments.py +139 -0
- continuum_task_server_bundle/discord/sql/001_message_awaits.sql +112 -0
- continuum_task_server_bundle/discord/sql/002_reaction_awaits.sql +61 -0
- continuum_task_server_bundle/github/__init__.py +4 -0
- continuum_task_server_bundle/github/awaits/__init__.py +1 -0
- continuum_task_server_bundle/github/awaits/apply.py +92 -0
- continuum_task_server_bundle/github/awaits/cleanup.py +94 -0
- continuum_task_server_bundle/github/awaits/db.py +220 -0
- continuum_task_server_bundle/github/awaits/evaluators.py +325 -0
- continuum_task_server_bundle/github/awaits/fetch.py +192 -0
- continuum_task_server_bundle/github/awaits/poller.py +82 -0
- continuum_task_server_bundle/github/awaits/register.py +37 -0
- continuum_task_server_bundle/github/ci_status.py +70 -0
- continuum_task_server_bundle/github/comment_normalize.py +76 -0
- continuum_task_server_bundle/github/errors.py +52 -0
- continuum_task_server_bundle/github/github_app.py +291 -0
- continuum_task_server_bundle/github/github_http.py +377 -0
- continuum_task_server_bundle/github/methods/__init__.py +90 -0
- continuum_task_server_bundle/github/methods/_common.py +183 -0
- continuum_task_server_bundle/github/methods/awaits.py +107 -0
- continuum_task_server_bundle/github/methods/ci.py +158 -0
- continuum_task_server_bundle/github/methods/comments.py +214 -0
- continuum_task_server_bundle/github/methods/credentials.py +59 -0
- continuum_task_server_bundle/github/methods/issues.py +131 -0
- continuum_task_server_bundle/github/methods/pulls.py +329 -0
- continuum_task_server_bundle/github/methods/repos.py +424 -0
- continuum_task_server_bundle/github/methods/search.py +109 -0
- continuum_task_server_bundle/github/plugin.py +91 -0
- continuum_task_server_bundle/github/sql/001_github_awaits.sql +65 -0
- continuum_task_server_bundle/github/webhook_server.py +126 -0
- continuum_task_server_bundle/jira/__init__.py +4 -0
- continuum_task_server_bundle/jira/await_poller.py +236 -0
- continuum_task_server_bundle/jira/await_store.py +271 -0
- continuum_task_server_bundle/jira/config.py +68 -0
- continuum_task_server_bundle/jira/jira_client.py +382 -0
- continuum_task_server_bundle/jira/methods.py +246 -0
- continuum_task_server_bundle/jira/plugin.py +86 -0
- continuum_task_server_bundle/jira/sql/001_jira_issue_comment_waits.sql +19 -0
- continuum_task_server_bundle/jira/webhook.py +70 -0
- continuum_task_server_bundle/openrouter/__init__.py +4 -0
- continuum_task_server_bundle/openrouter/chat_service.py +1037 -0
- continuum_task_server_bundle/openrouter/chat_store.py +849 -0
- continuum_task_server_bundle/openrouter/environment.py +29 -0
- continuum_task_server_bundle/openrouter/handler.py +59 -0
- continuum_task_server_bundle/openrouter/image_context.py +207 -0
- continuum_task_server_bundle/openrouter/openrouter_client.py +324 -0
- continuum_task_server_bundle/openrouter/plugin.py +37 -0
- continuum_task_server_bundle/openrouter/prompt_projection.py +417 -0
- continuum_task_server_bundle/openrouter/sql/chat.sql +50 -0
- continuum_task_server_bundle/openrouter/sql/migrate_prune_then_chunk_v1.sql +11 -0
- continuum_task_server_bundle/roblox/__init__.py +4 -0
- continuum_task_server_bundle/roblox/open_cloud.py +335 -0
- continuum_task_server_bundle/roblox/plugin.py +30 -0
- continuum_task_server_bundle/roblox/storage_s3.py +55 -0
- continuum_task_server_bundle-1.0.0.dist-info/METADATA +109 -0
- continuum_task_server_bundle-1.0.0.dist-info/RECORD +90 -0
- continuum_task_server_bundle-1.0.0.dist-info/WHEEL +5 -0
- continuum_task_server_bundle-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Optional GitHub webhook receiver.
|
|
2
|
+
|
|
3
|
+
Verifies ``X-Hub-Signature-256`` and marks matching awaits due immediately.
|
|
4
|
+
The poller still decides when a queue item completes. If ``GITHUB_WEBHOOK_SECRET``
|
|
5
|
+
is unset the receiver is not started; polling alone still works.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import hmac
|
|
12
|
+
import json
|
|
13
|
+
import logging
|
|
14
|
+
import threading
|
|
15
|
+
from os import getenv
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
import uvicorn
|
|
19
|
+
from starlette.applications import Starlette
|
|
20
|
+
from starlette.requests import Request
|
|
21
|
+
from starlette.responses import Response
|
|
22
|
+
from starlette.routing import Route
|
|
23
|
+
|
|
24
|
+
import continuum_task_server_bundle.github.awaits.db as db
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def webhook_enabled() -> bool:
|
|
29
|
+
return bool(getenv("GITHUB_WEBHOOK_SECRET"))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def verify_signature(body: bytes, header: str | None, secret: str) -> bool:
|
|
33
|
+
"""Constant-time check of ``sha256=<hex>`` against the raw body."""
|
|
34
|
+
if not secret or not header or not header.startswith("sha256="):
|
|
35
|
+
return False
|
|
36
|
+
digest = hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
|
|
37
|
+
expected = "sha256=" + digest
|
|
38
|
+
return hmac.compare_digest(expected, header)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def targets_for_event(event: str, payload: dict[str, Any]) -> list[dict[str, Any]]:
|
|
42
|
+
"""Map a webhook to bump specs: repo plus number and/or head sha."""
|
|
43
|
+
repo = _repo(payload)
|
|
44
|
+
if not repo:
|
|
45
|
+
return []
|
|
46
|
+
if event == "issue_comment":
|
|
47
|
+
number = (payload.get("issue") or {}).get("number")
|
|
48
|
+
return [{"repo_full_name": repo, "number": number}] if number is not None else []
|
|
49
|
+
if event in ("pull_request_review", "pull_request_review_comment", "pull_request"):
|
|
50
|
+
pull = payload.get("pull_request") or {}
|
|
51
|
+
number = payload.get("number")
|
|
52
|
+
if number is None:
|
|
53
|
+
number = pull.get("number")
|
|
54
|
+
return [{"repo_full_name": repo, "number": number}] if number is not None else []
|
|
55
|
+
if event == "check_run":
|
|
56
|
+
sha = (payload.get("check_run") or {}).get("head_sha")
|
|
57
|
+
return [{"repo_full_name": repo, "head_sha": sha}] if sha else []
|
|
58
|
+
if event == "check_suite":
|
|
59
|
+
sha = (payload.get("check_suite") or {}).get("head_sha")
|
|
60
|
+
return [{"repo_full_name": repo, "head_sha": sha}] if sha else []
|
|
61
|
+
if event == "status":
|
|
62
|
+
sha = payload.get("sha")
|
|
63
|
+
return [{"repo_full_name": repo, "head_sha": sha}] if sha else []
|
|
64
|
+
if event == "workflow_run":
|
|
65
|
+
sha = (payload.get("workflow_run") or {}).get("head_sha")
|
|
66
|
+
return [{"repo_full_name": repo, "head_sha": sha}] if sha else []
|
|
67
|
+
return []
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
async def github_webhook(request: Request) -> Response:
|
|
71
|
+
body = await request.body()
|
|
72
|
+
secret = getenv("GITHUB_WEBHOOK_SECRET") or ""
|
|
73
|
+
if not verify_signature(body, request.headers.get("x-hub-signature-256"), secret):
|
|
74
|
+
return Response("invalid signature", status_code=401)
|
|
75
|
+
event = request.headers.get("x-github-event") or ""
|
|
76
|
+
if event == "ping":
|
|
77
|
+
return Response(status_code=202)
|
|
78
|
+
try:
|
|
79
|
+
payload = json.loads(body) if body else {}
|
|
80
|
+
except json.JSONDecodeError:
|
|
81
|
+
return Response("invalid json", status_code=400)
|
|
82
|
+
if not isinstance(payload, dict):
|
|
83
|
+
return Response("invalid json", status_code=400)
|
|
84
|
+
try:
|
|
85
|
+
for spec in targets_for_event(event, payload):
|
|
86
|
+
db.bump_matching(**spec)
|
|
87
|
+
except Exception:
|
|
88
|
+
logger.exception("webhook bump failed for %s", event)
|
|
89
|
+
return Response(status_code=500)
|
|
90
|
+
return Response(status_code=202)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
webhook_app = Starlette(routes=[Route("/github/webhook", github_webhook, methods=["POST"])])
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def serve_webhook() -> None:
|
|
97
|
+
port = int(getenv("GITHUB_WEBHOOK_PORT", getenv("WEBHOOK_PORT", "8088")))
|
|
98
|
+
host = getenv("GITHUB_WEBHOOK_HOST", getenv("WEBHOOK_HOST", "0.0.0.0"))
|
|
99
|
+
config = uvicorn.Config(webhook_app, host=host, port=port, log_level="info")
|
|
100
|
+
server = uvicorn.Server(config)
|
|
101
|
+
server.install_signal_handlers = False
|
|
102
|
+
logger.info("GitHub webhook receiver listening on %s:%s", host, port)
|
|
103
|
+
server.run()
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def serve_webhook_until(stop_event: threading.Event) -> None:
|
|
107
|
+
port = int(getenv("GITHUB_WEBHOOK_PORT", getenv("WEBHOOK_PORT", "8088")))
|
|
108
|
+
host = getenv("GITHUB_WEBHOOK_HOST", getenv("WEBHOOK_HOST", "0.0.0.0"))
|
|
109
|
+
config = uvicorn.Config(webhook_app, host=host, port=port, log_level="info")
|
|
110
|
+
server = uvicorn.Server(config)
|
|
111
|
+
server.install_signal_handlers = False
|
|
112
|
+
|
|
113
|
+
def _watch() -> None:
|
|
114
|
+
stop_event.wait()
|
|
115
|
+
server.should_exit = True
|
|
116
|
+
|
|
117
|
+
threading.Thread(target=_watch, name="github-webhook-stop", daemon=True).start()
|
|
118
|
+
logger.info("GitHub webhook receiver listening on %s:%s", host, port)
|
|
119
|
+
server.run()
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _repo(payload: dict[str, Any]) -> str | None:
|
|
123
|
+
full = (payload.get("repository") or {}).get("full_name")
|
|
124
|
+
if not full or not isinstance(full, str) or "/" not in full:
|
|
125
|
+
return None
|
|
126
|
+
return full.strip().lower()
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
"""Background reconciliation for durable Jira issue-comment waits."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
from datetime import datetime, timezone
|
|
9
|
+
from typing import Any
|
|
10
|
+
from uuid import UUID
|
|
11
|
+
|
|
12
|
+
from continuum_task_server import TaskServer, TaskStatus
|
|
13
|
+
from continuum_task_server.exceptions import (
|
|
14
|
+
ContinuumError,
|
|
15
|
+
ForbiddenError,
|
|
16
|
+
NotFoundError,
|
|
17
|
+
RateLimitError,
|
|
18
|
+
ServerError,
|
|
19
|
+
TransportError,
|
|
20
|
+
UnauthorizedError,
|
|
21
|
+
)
|
|
22
|
+
from continuum_task_server.models import QueueItem
|
|
23
|
+
|
|
24
|
+
from continuum_task_server_bundle.jira.await_store import AwaitStore
|
|
25
|
+
from continuum_task_server_bundle.jira.config import Settings
|
|
26
|
+
from continuum_task_server_bundle.jira.jira_client import JiraApiError, JiraClient
|
|
27
|
+
from continuum_task_server_bundle.jira.methods import _poll_jira_for_comment, _transient_jira_error
|
|
28
|
+
|
|
29
|
+
logger = logging.getLogger(__name__)
|
|
30
|
+
|
|
31
|
+
_TRANSIENT_HEARTBEAT_ERRORS = (
|
|
32
|
+
UnauthorizedError,
|
|
33
|
+
ForbiddenError,
|
|
34
|
+
RateLimitError,
|
|
35
|
+
ServerError,
|
|
36
|
+
TransportError,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def heartbeat_claim_or_drop(
|
|
41
|
+
server: TaskServer, await_store: AwaitStore, queue_item_id: UUID
|
|
42
|
+
) -> bool:
|
|
43
|
+
"""Heartbeat a queue item; discard its wait if it is no longer runnable."""
|
|
44
|
+
claim = _active_claim(server, queue_item_id)
|
|
45
|
+
token = None if claim is None else getattr(claim, "claim_token", None)
|
|
46
|
+
latest: QueueItem | None = None
|
|
47
|
+
try:
|
|
48
|
+
latest = server.client.queue.heartbeat(queue_item_id, claim_token=token)
|
|
49
|
+
except ContinuumError as error:
|
|
50
|
+
if isinstance(error, _TRANSIENT_HEARTBEAT_ERRORS):
|
|
51
|
+
logger.warning("heartbeat failed for Jira wait %s: %s", queue_item_id, error)
|
|
52
|
+
return True
|
|
53
|
+
logger.info("heartbeat failed for Jira wait %s: %s", queue_item_id, error)
|
|
54
|
+
try:
|
|
55
|
+
latest = server.client.queue.get_by_id(queue_item_id)
|
|
56
|
+
except NotFoundError:
|
|
57
|
+
_drop_wait(await_store, queue_item_id, claim, reason="not found")
|
|
58
|
+
return False
|
|
59
|
+
except ContinuumError as get_error:
|
|
60
|
+
logger.warning("queue lookup failed for Jira wait %s: %s", queue_item_id, get_error)
|
|
61
|
+
return True
|
|
62
|
+
|
|
63
|
+
if latest is None:
|
|
64
|
+
_drop_wait(await_store, queue_item_id, claim, reason="empty heartbeat")
|
|
65
|
+
return False
|
|
66
|
+
|
|
67
|
+
control = latest.control_request
|
|
68
|
+
if latest.task_status is not TaskStatus.STARTED or (control is not None and control != ""):
|
|
69
|
+
_drop_wait(
|
|
70
|
+
await_store,
|
|
71
|
+
queue_item_id,
|
|
72
|
+
claim,
|
|
73
|
+
reason=f"status={latest.task_status} control={control!r}",
|
|
74
|
+
)
|
|
75
|
+
return False
|
|
76
|
+
return True
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _active_claim(server: TaskServer, queue_item_id: UUID) -> Any:
|
|
80
|
+
active = getattr(server, "_active", None)
|
|
81
|
+
if not isinstance(active, dict):
|
|
82
|
+
return None
|
|
83
|
+
return active.get(queue_item_id)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _drop_wait(await_store: AwaitStore, queue_item_id: UUID, claim: Any, *, reason: str) -> None:
|
|
87
|
+
logger.info("Jira wait %s is no longer runnable (%s); deleting its row", queue_item_id, reason)
|
|
88
|
+
await_store.delete_wait(queue_item_id)
|
|
89
|
+
completed = getattr(claim, "completed", None)
|
|
90
|
+
if claim is None or (completed is not None and completed.is_set()):
|
|
91
|
+
return
|
|
92
|
+
signal = getattr(claim, "signal_control", None)
|
|
93
|
+
if callable(signal):
|
|
94
|
+
signal()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _deadline(value: Any) -> datetime:
|
|
98
|
+
if isinstance(value, str):
|
|
99
|
+
value = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
100
|
+
if not isinstance(value, datetime):
|
|
101
|
+
raise ValueError("Jira wait row is missing a valid deadline")
|
|
102
|
+
return value.replace(tzinfo=timezone.utc) if value.tzinfo is None else value
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def process_awaits_tick(
|
|
106
|
+
server: TaskServer,
|
|
107
|
+
jira: JiraClient,
|
|
108
|
+
await_store: AwaitStore,
|
|
109
|
+
settings: Settings,
|
|
110
|
+
*,
|
|
111
|
+
last_jira_poll_at: dict[str, float] | None = None,
|
|
112
|
+
monotonic_now: float | None = None,
|
|
113
|
+
utc_now: datetime | None = None,
|
|
114
|
+
) -> None:
|
|
115
|
+
"""Heartbeat waits, expire them, poll Jira if needed, and dispatch results."""
|
|
116
|
+
last_jira_poll_at = last_jira_poll_at if last_jira_poll_at is not None else {}
|
|
117
|
+
monotonic_now = time.monotonic() if monotonic_now is None else monotonic_now
|
|
118
|
+
utc_now = utc_now or datetime.now(timezone.utc)
|
|
119
|
+
|
|
120
|
+
try:
|
|
121
|
+
active_rows = await_store.list_active_waits()
|
|
122
|
+
except Exception:
|
|
123
|
+
logger.exception("listing active Jira waits failed")
|
|
124
|
+
return
|
|
125
|
+
|
|
126
|
+
poll_intervals_by_issue: dict[str, float] = {}
|
|
127
|
+
for row in active_rows:
|
|
128
|
+
queue_item_id = UUID(str(row["queue_item_id"]))
|
|
129
|
+
if not heartbeat_claim_or_drop(server, await_store, queue_item_id):
|
|
130
|
+
continue
|
|
131
|
+
|
|
132
|
+
try:
|
|
133
|
+
deadline = _deadline(row.get("deadline_at"))
|
|
134
|
+
except (TypeError, ValueError):
|
|
135
|
+
logger.exception("invalid deadline on Jira wait %s", queue_item_id)
|
|
136
|
+
await_store.finish_wait(
|
|
137
|
+
queue_item_id,
|
|
138
|
+
status="completed",
|
|
139
|
+
result={"success": False, "error": "invalid_wait_deadline"},
|
|
140
|
+
)
|
|
141
|
+
continue
|
|
142
|
+
|
|
143
|
+
if utc_now >= deadline:
|
|
144
|
+
await_store.finish_wait(
|
|
145
|
+
queue_item_id,
|
|
146
|
+
status="timed_out",
|
|
147
|
+
result={"success": True, "timed_out": True, "issue_key": row["issue_key"]},
|
|
148
|
+
)
|
|
149
|
+
continue
|
|
150
|
+
|
|
151
|
+
issue_key = str(row["issue_key"])
|
|
152
|
+
filters = row.get("filters") or {}
|
|
153
|
+
try:
|
|
154
|
+
interval = float(filters.get("poll_interval_seconds", settings.database_poll_seconds))
|
|
155
|
+
except (TypeError, ValueError):
|
|
156
|
+
interval = settings.database_poll_seconds
|
|
157
|
+
interval = min(60.0, max(0.25, interval))
|
|
158
|
+
current = poll_intervals_by_issue.get(issue_key)
|
|
159
|
+
poll_intervals_by_issue[issue_key] = interval if current is None else min(current, interval)
|
|
160
|
+
|
|
161
|
+
# Forget idle issue keys so a future wait polls immediately.
|
|
162
|
+
for issue_key in list(last_jira_poll_at):
|
|
163
|
+
if issue_key not in poll_intervals_by_issue:
|
|
164
|
+
del last_jira_poll_at[issue_key]
|
|
165
|
+
|
|
166
|
+
if not settings.webhook_secret:
|
|
167
|
+
for issue_key, interval in poll_intervals_by_issue.items():
|
|
168
|
+
last_poll = last_jira_poll_at.get(issue_key)
|
|
169
|
+
if last_poll is not None and monotonic_now - last_poll < interval:
|
|
170
|
+
continue
|
|
171
|
+
# Advance the schedule even on transient failures to avoid a hot retry loop.
|
|
172
|
+
last_jira_poll_at[issue_key] = monotonic_now
|
|
173
|
+
try:
|
|
174
|
+
_poll_jira_for_comment(jira, await_store, issue_key)
|
|
175
|
+
except JiraApiError as error:
|
|
176
|
+
if _transient_jira_error(error):
|
|
177
|
+
logger.warning("Jira await poll for %s will retry: HTTP %s", issue_key, error.status_code)
|
|
178
|
+
continue
|
|
179
|
+
logger.warning("Jira await poll for %s failed: %s", issue_key, error)
|
|
180
|
+
await_store.fail_issue_waits(issue_key, error=str(error))
|
|
181
|
+
except Exception:
|
|
182
|
+
logger.exception("Jira await poll for %s failed; will retry", issue_key)
|
|
183
|
+
|
|
184
|
+
try:
|
|
185
|
+
terminal_rows = await_store.list_terminal_waits()
|
|
186
|
+
except Exception:
|
|
187
|
+
logger.exception("listing terminal Jira waits failed")
|
|
188
|
+
return
|
|
189
|
+
|
|
190
|
+
for row in terminal_rows:
|
|
191
|
+
queue_item_id = UUID(str(row["queue_item_id"]))
|
|
192
|
+
if row.get("status") == "cancelled":
|
|
193
|
+
await_store.delete_wait(queue_item_id)
|
|
194
|
+
continue
|
|
195
|
+
if not heartbeat_claim_or_drop(server, await_store, queue_item_id):
|
|
196
|
+
continue
|
|
197
|
+
result = row.get("result_json")
|
|
198
|
+
if not isinstance(result, dict):
|
|
199
|
+
result = {"success": False, "error": "missing_wait_result"}
|
|
200
|
+
try:
|
|
201
|
+
server.complete_queue_item(queue_item_id, output_data=result)
|
|
202
|
+
except ContinuumError as error:
|
|
203
|
+
# Keep the row for retry. If completion actually succeeded before a
|
|
204
|
+
# transport error, the next heartbeat observes the terminal item.
|
|
205
|
+
logger.error("completing Jira wait %s failed: %s", queue_item_id, error)
|
|
206
|
+
continue
|
|
207
|
+
except Exception:
|
|
208
|
+
logger.exception("completing Jira wait %s failed", queue_item_id)
|
|
209
|
+
continue
|
|
210
|
+
await_store.delete_wait(queue_item_id)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def run_await_poller(
|
|
214
|
+
server: TaskServer,
|
|
215
|
+
jira: JiraClient,
|
|
216
|
+
await_store: AwaitStore,
|
|
217
|
+
settings: Settings,
|
|
218
|
+
stop_event: threading.Event,
|
|
219
|
+
*,
|
|
220
|
+
idle_seconds: float = 1.0,
|
|
221
|
+
) -> None:
|
|
222
|
+
"""Run the reconciler until shutdown; no wait occupies a task-handler slot."""
|
|
223
|
+
last_jira_poll_at: dict[str, float] = {}
|
|
224
|
+
while not stop_event.wait(timeout=idle_seconds):
|
|
225
|
+
try:
|
|
226
|
+
process_awaits_tick(
|
|
227
|
+
server,
|
|
228
|
+
jira,
|
|
229
|
+
await_store,
|
|
230
|
+
settings,
|
|
231
|
+
last_jira_poll_at=last_jira_poll_at,
|
|
232
|
+
)
|
|
233
|
+
except Exception:
|
|
234
|
+
# A transient persistence or queue API failure must not permanently
|
|
235
|
+
# stop the reconciler; the next tick retries any remaining rows.
|
|
236
|
+
logger.exception("Jira await reconciliation tick failed")
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
"""Non-destructive Postgres persistence for durable Jira issue-comment waits."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import datetime, timedelta, timezone
|
|
6
|
+
from typing import Any
|
|
7
|
+
from uuid import UUID
|
|
8
|
+
|
|
9
|
+
import psycopg
|
|
10
|
+
from psycopg.rows import dict_row
|
|
11
|
+
from psycopg.types.json import Jsonb
|
|
12
|
+
|
|
13
|
+
from continuum_task_server_bundle.jira.jira_client import adf_to_plain_text, mention_account_ids
|
|
14
|
+
|
|
15
|
+
SCHEMA_SQL = """
|
|
16
|
+
CREATE TABLE IF NOT EXISTS jira_issue_comment_waits (
|
|
17
|
+
queue_item_id UUID PRIMARY KEY,
|
|
18
|
+
issue_key TEXT NOT NULL,
|
|
19
|
+
status TEXT NOT NULL DEFAULT 'active'
|
|
20
|
+
CHECK (status IN ('active', 'completed', 'timed_out', 'cancelled')),
|
|
21
|
+
registered_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
22
|
+
deadline_at TIMESTAMPTZ NOT NULL,
|
|
23
|
+
filters JSONB NOT NULL DEFAULT '{}'::jsonb,
|
|
24
|
+
result_json JSONB,
|
|
25
|
+
matched_comment_id TEXT,
|
|
26
|
+
completed_at TIMESTAMPTZ,
|
|
27
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
28
|
+
);
|
|
29
|
+
CREATE INDEX IF NOT EXISTS jira_issue_comment_waits_active_issue_idx
|
|
30
|
+
ON jira_issue_comment_waits (issue_key, registered_at)
|
|
31
|
+
WHERE status = 'active';
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class AwaitStore:
|
|
36
|
+
def __init__(self, database_url: str) -> None:
|
|
37
|
+
if not database_url:
|
|
38
|
+
raise ValueError("DATABASE_URL is required for Jira await methods")
|
|
39
|
+
self._database_url = database_url
|
|
40
|
+
|
|
41
|
+
def _connect(self):
|
|
42
|
+
return psycopg.connect(self._database_url, row_factory=dict_row)
|
|
43
|
+
|
|
44
|
+
def ensure_schema(self) -> None:
|
|
45
|
+
"""Create the await table/index if missing; never drops or resets data."""
|
|
46
|
+
with self._connect() as connection:
|
|
47
|
+
# Separate statements keep psycopg's prepared-statement behavior portable.
|
|
48
|
+
connection.execute(SCHEMA_SQL.split(";\nCREATE INDEX", maxsplit=1)[0])
|
|
49
|
+
connection.execute(
|
|
50
|
+
"""
|
|
51
|
+
CREATE INDEX IF NOT EXISTS jira_issue_comment_waits_active_issue_idx
|
|
52
|
+
ON jira_issue_comment_waits (issue_key, registered_at)
|
|
53
|
+
WHERE status = 'active'
|
|
54
|
+
"""
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
def register_wait(
|
|
58
|
+
self,
|
|
59
|
+
*,
|
|
60
|
+
queue_item_id: str | UUID,
|
|
61
|
+
issue_key: str,
|
|
62
|
+
timeout_seconds: float,
|
|
63
|
+
filters: dict[str, Any],
|
|
64
|
+
) -> dict[str, Any]:
|
|
65
|
+
now = datetime.now(timezone.utc)
|
|
66
|
+
deadline = now + timedelta(seconds=timeout_seconds)
|
|
67
|
+
with self._connect() as connection:
|
|
68
|
+
connection.execute(
|
|
69
|
+
"""
|
|
70
|
+
INSERT INTO jira_issue_comment_waits
|
|
71
|
+
(queue_item_id, issue_key, deadline_at, filters)
|
|
72
|
+
VALUES (%s, %s, %s, %s)
|
|
73
|
+
ON CONFLICT (queue_item_id) DO NOTHING
|
|
74
|
+
""",
|
|
75
|
+
(str(queue_item_id), issue_key, deadline, Jsonb(filters)),
|
|
76
|
+
)
|
|
77
|
+
row = connection.execute(
|
|
78
|
+
"SELECT * FROM jira_issue_comment_waits WHERE queue_item_id = %s",
|
|
79
|
+
(str(queue_item_id),),
|
|
80
|
+
).fetchone()
|
|
81
|
+
if row is None:
|
|
82
|
+
raise RuntimeError("Could not create or retrieve Jira comment wait")
|
|
83
|
+
return dict(row)
|
|
84
|
+
|
|
85
|
+
def get_wait(self, queue_item_id: str | UUID) -> dict[str, Any] | None:
|
|
86
|
+
with self._connect() as connection:
|
|
87
|
+
row = connection.execute(
|
|
88
|
+
"SELECT * FROM jira_issue_comment_waits WHERE queue_item_id = %s",
|
|
89
|
+
(str(queue_item_id),),
|
|
90
|
+
).fetchone()
|
|
91
|
+
return dict(row) if row else None
|
|
92
|
+
|
|
93
|
+
def list_active_waits(self) -> list[dict[str, Any]]:
|
|
94
|
+
"""Return active waits for heartbeat, timeout, and optional Jira polling."""
|
|
95
|
+
with self._connect() as connection:
|
|
96
|
+
rows = connection.execute(
|
|
97
|
+
"""
|
|
98
|
+
SELECT queue_item_id, issue_key, deadline_at, filters
|
|
99
|
+
FROM jira_issue_comment_waits
|
|
100
|
+
WHERE status = 'active'
|
|
101
|
+
ORDER BY registered_at
|
|
102
|
+
"""
|
|
103
|
+
).fetchall()
|
|
104
|
+
return [dict(row) for row in rows]
|
|
105
|
+
|
|
106
|
+
def list_terminal_waits(self) -> list[dict[str, Any]]:
|
|
107
|
+
"""Return results that the background reconciler still needs to deliver."""
|
|
108
|
+
with self._connect() as connection:
|
|
109
|
+
rows = connection.execute(
|
|
110
|
+
"""
|
|
111
|
+
SELECT queue_item_id, status, result_json
|
|
112
|
+
FROM jira_issue_comment_waits
|
|
113
|
+
WHERE status IN ('completed', 'timed_out', 'cancelled')
|
|
114
|
+
ORDER BY completed_at, registered_at
|
|
115
|
+
"""
|
|
116
|
+
).fetchall()
|
|
117
|
+
return [dict(row) for row in rows]
|
|
118
|
+
|
|
119
|
+
def delete_wait(self, queue_item_id: str | UUID) -> None:
|
|
120
|
+
"""Remove a wait after its queue item is completed or cancelled."""
|
|
121
|
+
with self._connect() as connection:
|
|
122
|
+
connection.execute(
|
|
123
|
+
"DELETE FROM jira_issue_comment_waits WHERE queue_item_id = %s",
|
|
124
|
+
(str(queue_item_id),),
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
def finish_wait(
|
|
128
|
+
self,
|
|
129
|
+
queue_item_id: str | UUID,
|
|
130
|
+
*,
|
|
131
|
+
status: str,
|
|
132
|
+
result: dict[str, Any],
|
|
133
|
+
comment_id: str | None = None,
|
|
134
|
+
) -> bool:
|
|
135
|
+
if status not in {"completed", "timed_out", "cancelled"}:
|
|
136
|
+
raise ValueError("Invalid terminal wait status")
|
|
137
|
+
with self._connect() as connection:
|
|
138
|
+
row = connection.execute(
|
|
139
|
+
"""
|
|
140
|
+
UPDATE jira_issue_comment_waits
|
|
141
|
+
SET status = %s,
|
|
142
|
+
result_json = %s,
|
|
143
|
+
matched_comment_id = %s,
|
|
144
|
+
completed_at = now(),
|
|
145
|
+
updated_at = now()
|
|
146
|
+
WHERE queue_item_id = %s AND status = 'active'
|
|
147
|
+
RETURNING queue_item_id
|
|
148
|
+
""",
|
|
149
|
+
(status, Jsonb(result), comment_id, str(queue_item_id)),
|
|
150
|
+
).fetchone()
|
|
151
|
+
return row is not None
|
|
152
|
+
|
|
153
|
+
def complete_for_comment(
|
|
154
|
+
self,
|
|
155
|
+
*,
|
|
156
|
+
issue_key: str,
|
|
157
|
+
comment: dict[str, Any],
|
|
158
|
+
) -> list[str]:
|
|
159
|
+
"""Complete each matching active waiter exactly once; return queue IDs."""
|
|
160
|
+
comment_id = str(comment.get("id") or "")
|
|
161
|
+
author = comment.get("author") or {}
|
|
162
|
+
author_id = str(author.get("accountId") or "") or None
|
|
163
|
+
body = comment.get("body")
|
|
164
|
+
created = _parse_timestamp(comment.get("created")) or datetime.now(timezone.utc)
|
|
165
|
+
comment_mentions = mention_account_ids(body)
|
|
166
|
+
comment_text = adf_to_plain_text(body).strip()
|
|
167
|
+
result = {
|
|
168
|
+
"success": True,
|
|
169
|
+
"timed_out": False,
|
|
170
|
+
"issue_key": issue_key,
|
|
171
|
+
"comment": {
|
|
172
|
+
"comment_id": comment_id,
|
|
173
|
+
"author_account_id": author_id,
|
|
174
|
+
"body_text": comment_text,
|
|
175
|
+
"body_adf": body,
|
|
176
|
+
"created": comment.get("created"),
|
|
177
|
+
},
|
|
178
|
+
}
|
|
179
|
+
completed: list[str] = []
|
|
180
|
+
with self._connect() as connection:
|
|
181
|
+
rows = connection.execute(
|
|
182
|
+
"""
|
|
183
|
+
SELECT queue_item_id, filters
|
|
184
|
+
FROM jira_issue_comment_waits
|
|
185
|
+
WHERE issue_key = %s AND status = 'active' AND registered_at <= %s
|
|
186
|
+
FOR UPDATE
|
|
187
|
+
""",
|
|
188
|
+
(issue_key, created),
|
|
189
|
+
).fetchall()
|
|
190
|
+
for row in rows:
|
|
191
|
+
filters = row.get("filters") or {}
|
|
192
|
+
ignored = {str(value) for value in filters.get("ignore_comment_ids", [])}
|
|
193
|
+
if comment_id and comment_id in ignored:
|
|
194
|
+
continue
|
|
195
|
+
if filters.get("author_account_id") and author_id != str(filters["author_account_id"]):
|
|
196
|
+
continue
|
|
197
|
+
if filters.get("exclude_author_account_id") and author_id == str(filters["exclude_author_account_id"]):
|
|
198
|
+
continue
|
|
199
|
+
mentioned_account_id = filters.get("mention_account_id")
|
|
200
|
+
if mentioned_account_id and str(mentioned_account_id) not in comment_mentions:
|
|
201
|
+
continue
|
|
202
|
+
if filters.get("contains_text") and str(filters["contains_text"]).casefold() not in comment_text.casefold():
|
|
203
|
+
continue
|
|
204
|
+
row_id = str(row["queue_item_id"])
|
|
205
|
+
updated = connection.execute(
|
|
206
|
+
"""
|
|
207
|
+
UPDATE jira_issue_comment_waits
|
|
208
|
+
SET status = 'completed', result_json = %s,
|
|
209
|
+
matched_comment_id = %s, completed_at = now(), updated_at = now()
|
|
210
|
+
WHERE queue_item_id = %s AND status = 'active'
|
|
211
|
+
RETURNING queue_item_id
|
|
212
|
+
""",
|
|
213
|
+
(Jsonb(result), comment_id or None, row_id),
|
|
214
|
+
).fetchone()
|
|
215
|
+
if updated:
|
|
216
|
+
completed.append(row_id)
|
|
217
|
+
return completed
|
|
218
|
+
|
|
219
|
+
def finish_issue_waits(self, issue_key: str, *, end_reason: str) -> list[str]:
|
|
220
|
+
result = {
|
|
221
|
+
"success": True,
|
|
222
|
+
"timed_out": False,
|
|
223
|
+
"end_reason": end_reason,
|
|
224
|
+
"issue_key": issue_key,
|
|
225
|
+
}
|
|
226
|
+
with self._connect() as connection:
|
|
227
|
+
rows = connection.execute(
|
|
228
|
+
"""
|
|
229
|
+
UPDATE jira_issue_comment_waits
|
|
230
|
+
SET status = 'completed', result_json = %s,
|
|
231
|
+
completed_at = now(), updated_at = now()
|
|
232
|
+
WHERE issue_key = %s AND status = 'active'
|
|
233
|
+
RETURNING queue_item_id
|
|
234
|
+
""",
|
|
235
|
+
(Jsonb(result), issue_key),
|
|
236
|
+
).fetchall()
|
|
237
|
+
return [str(row["queue_item_id"]) for row in rows]
|
|
238
|
+
|
|
239
|
+
def fail_issue_waits(self, issue_key: str, *, error: str) -> list[str]:
|
|
240
|
+
result = {"success": False, "issue_key": issue_key, "error": error}
|
|
241
|
+
with self._connect() as connection:
|
|
242
|
+
rows = connection.execute(
|
|
243
|
+
"""
|
|
244
|
+
UPDATE jira_issue_comment_waits
|
|
245
|
+
SET status = 'completed', result_json = %s,
|
|
246
|
+
completed_at = now(), updated_at = now()
|
|
247
|
+
WHERE issue_key = %s AND status = 'active'
|
|
248
|
+
RETURNING queue_item_id
|
|
249
|
+
""",
|
|
250
|
+
(Jsonb(result), issue_key),
|
|
251
|
+
).fetchall()
|
|
252
|
+
return [str(row["queue_item_id"]) for row in rows]
|
|
253
|
+
|
|
254
|
+
def cancel_wait(self, queue_item_id: str | UUID) -> None:
|
|
255
|
+
self.finish_wait(
|
|
256
|
+
queue_item_id,
|
|
257
|
+
status="cancelled",
|
|
258
|
+
result={"success": False, "cancelled": True},
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _parse_timestamp(value: Any) -> datetime | None:
|
|
263
|
+
if not value:
|
|
264
|
+
return None
|
|
265
|
+
if isinstance(value, datetime):
|
|
266
|
+
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
|
|
267
|
+
try:
|
|
268
|
+
parsed = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
|
|
269
|
+
except ValueError:
|
|
270
|
+
return None
|
|
271
|
+
return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
|