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,207 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import re
|
|
4
|
+
import threading
|
|
5
|
+
import time
|
|
6
|
+
import urllib.error
|
|
7
|
+
import urllib.request
|
|
8
|
+
from datetime import datetime, timezone
|
|
9
|
+
|
|
10
|
+
import jwt
|
|
11
|
+
|
|
12
|
+
from continuum_task_server_bundle.daytona.common import HandlerError
|
|
13
|
+
|
|
14
|
+
_API = "https://api.github.com"
|
|
15
|
+
_USER_AGENT = "continuum-daytona-task-server"
|
|
16
|
+
_HTTPS_RE = re.compile(
|
|
17
|
+
r"^https://(?:[^@/\s]+@)?github\.com/"
|
|
18
|
+
r"(?P<owner>[A-Za-z0-9_.-]+)/(?P<repo>[A-Za-z0-9_.-]+?)(?:\.git)?/?$"
|
|
19
|
+
)
|
|
20
|
+
_SSH_RE = re.compile(
|
|
21
|
+
r"^git@github\.com:(?P<owner>[A-Za-z0-9_.-]+)/(?P<repo>[A-Za-z0-9_.-]+?)(?:\.git)?$"
|
|
22
|
+
)
|
|
23
|
+
_LOCK = threading.Lock()
|
|
24
|
+
_TOKEN_CACHE: dict[tuple[str, str], tuple[str, float]] = {}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def configured() -> bool:
|
|
28
|
+
return _app_id() is not None and _private_key() is not None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def require_configured() -> None:
|
|
32
|
+
if not configured():
|
|
33
|
+
raise HandlerError(
|
|
34
|
+
"GITHUB_APP_ID and GITHUB_APP_PRIVATE_KEY are required for git"
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def parse_github_repo(url: str) -> tuple[str, str]:
|
|
39
|
+
match = _HTTPS_RE.match(url.strip()) or _SSH_RE.match(url.strip())
|
|
40
|
+
if match is None:
|
|
41
|
+
raise HandlerError("git authentication only supports github.com repositories")
|
|
42
|
+
return match.group("owner"), match.group("repo")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def https_repo_url(url: str) -> str:
|
|
46
|
+
owner, repo = parse_github_repo(url)
|
|
47
|
+
return f"https://github.com/{owner}/{repo}.git"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def installation_token(owner: str, repo: str) -> str:
|
|
51
|
+
require_configured()
|
|
52
|
+
cache_key = (owner.lower(), repo.lower())
|
|
53
|
+
now = time.time()
|
|
54
|
+
with _LOCK:
|
|
55
|
+
cached = _TOKEN_CACHE.get(cache_key)
|
|
56
|
+
if cached is not None and cached[1] > now:
|
|
57
|
+
return cached[0]
|
|
58
|
+
app_jwt = _app_jwt()
|
|
59
|
+
installation = _github(
|
|
60
|
+
"GET",
|
|
61
|
+
f"/repos/{owner}/{repo}/installation",
|
|
62
|
+
app_jwt,
|
|
63
|
+
)
|
|
64
|
+
installation_id = installation.get("id")
|
|
65
|
+
if not isinstance(installation_id, int):
|
|
66
|
+
raise HandlerError(
|
|
67
|
+
f"GitHub did not return an installation for {owner}/{repo}",
|
|
68
|
+
"not_found",
|
|
69
|
+
)
|
|
70
|
+
minted = _github(
|
|
71
|
+
"POST",
|
|
72
|
+
f"/app/installations/{installation_id}/access_tokens",
|
|
73
|
+
app_jwt,
|
|
74
|
+
{"repositories": [repo]},
|
|
75
|
+
)
|
|
76
|
+
token = minted.get("token")
|
|
77
|
+
if not isinstance(token, str) or not token:
|
|
78
|
+
raise HandlerError("GitHub did not return an installation token", "internal_error")
|
|
79
|
+
expires_at = _expires_at(minted.get("expires_at"))
|
|
80
|
+
with _LOCK:
|
|
81
|
+
_TOKEN_CACHE[cache_key] = (token, expires_at)
|
|
82
|
+
return token
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def invalidate_token(owner: str, repo: str) -> None:
|
|
86
|
+
with _LOCK:
|
|
87
|
+
_TOKEN_CACHE.pop((owner.lower(), repo.lower()), None)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def clear_token_cache() -> None:
|
|
91
|
+
with _LOCK:
|
|
92
|
+
_TOKEN_CACHE.clear()
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _app_id() -> str | None:
|
|
96
|
+
value = os.getenv("GITHUB_APP_ID")
|
|
97
|
+
if value is None:
|
|
98
|
+
return None
|
|
99
|
+
stripped = value.strip()
|
|
100
|
+
return stripped or None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _private_key() -> str | None:
|
|
104
|
+
value = os.getenv("GITHUB_APP_PRIVATE_KEY")
|
|
105
|
+
if value is None:
|
|
106
|
+
return None
|
|
107
|
+
key = value.strip()
|
|
108
|
+
if len(key) >= 2 and key[0] == key[-1] and key[0] in {'"', "'"}:
|
|
109
|
+
key = key[1:-1]
|
|
110
|
+
key = key.replace("\\n", "\n").strip()
|
|
111
|
+
return key or None
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _app_jwt() -> str:
|
|
115
|
+
app_id = _app_id()
|
|
116
|
+
private_key = _private_key()
|
|
117
|
+
if app_id is None or private_key is None:
|
|
118
|
+
raise HandlerError(
|
|
119
|
+
"GITHUB_APP_ID and GITHUB_APP_PRIVATE_KEY are required for git"
|
|
120
|
+
)
|
|
121
|
+
now = int(time.time())
|
|
122
|
+
try:
|
|
123
|
+
token = jwt.encode(
|
|
124
|
+
{"iat": now - 60, "exp": now + 9 * 60, "iss": app_id},
|
|
125
|
+
private_key,
|
|
126
|
+
algorithm="RS256",
|
|
127
|
+
)
|
|
128
|
+
except Exception as exc:
|
|
129
|
+
raise HandlerError(
|
|
130
|
+
"GITHUB_APP_PRIVATE_KEY could not be used to sign a JWT"
|
|
131
|
+
) from exc
|
|
132
|
+
if isinstance(token, bytes):
|
|
133
|
+
return token.decode("ascii")
|
|
134
|
+
return token
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _github(method: str, path: str, app_jwt: str, body: dict | None = None) -> dict:
|
|
138
|
+
data = None if body is None else json.dumps(body).encode("utf-8")
|
|
139
|
+
headers = {
|
|
140
|
+
"Authorization": f"Bearer {app_jwt}",
|
|
141
|
+
"Accept": "application/vnd.github+json",
|
|
142
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
143
|
+
"User-Agent": _USER_AGENT,
|
|
144
|
+
}
|
|
145
|
+
if data is not None:
|
|
146
|
+
headers["Content-Type"] = "application/json"
|
|
147
|
+
request = urllib.request.Request(
|
|
148
|
+
f"{_API}{path}",
|
|
149
|
+
data=data,
|
|
150
|
+
method=method,
|
|
151
|
+
headers=headers,
|
|
152
|
+
)
|
|
153
|
+
try:
|
|
154
|
+
with urllib.request.urlopen(request, timeout=30) as response:
|
|
155
|
+
payload = json.loads(response.read().decode("utf-8"))
|
|
156
|
+
except urllib.error.HTTPError as exc:
|
|
157
|
+
try:
|
|
158
|
+
message = _github_error(exc)
|
|
159
|
+
code = _github_error_code(exc.code)
|
|
160
|
+
finally:
|
|
161
|
+
exc.close()
|
|
162
|
+
raise HandlerError(
|
|
163
|
+
f"GitHub API {method} {path} failed ({exc.code}): {message}",
|
|
164
|
+
code,
|
|
165
|
+
) from exc
|
|
166
|
+
except TimeoutError as exc:
|
|
167
|
+
raise HandlerError("GitHub API request timed out", "timeout") from exc
|
|
168
|
+
except urllib.error.URLError as exc:
|
|
169
|
+
raise HandlerError("GitHub API request failed", "internal_error") from exc
|
|
170
|
+
if not isinstance(payload, dict):
|
|
171
|
+
raise HandlerError("GitHub API returned an unexpected response", "internal_error")
|
|
172
|
+
return payload
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _github_error(exc: urllib.error.HTTPError) -> str:
|
|
176
|
+
try:
|
|
177
|
+
payload = json.loads(exc.read().decode("utf-8"))
|
|
178
|
+
except Exception:
|
|
179
|
+
return "request rejected"
|
|
180
|
+
if isinstance(payload, dict):
|
|
181
|
+
message = payload.get("message")
|
|
182
|
+
if isinstance(message, str) and message.strip():
|
|
183
|
+
return message.strip()[:300]
|
|
184
|
+
return "request rejected"
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _github_error_code(status: int) -> str:
|
|
188
|
+
if status == 404:
|
|
189
|
+
return "not_found"
|
|
190
|
+
if status in {401, 403}:
|
|
191
|
+
return "forbidden"
|
|
192
|
+
if status == 422:
|
|
193
|
+
return "validation_error"
|
|
194
|
+
if status == 429:
|
|
195
|
+
return "limit_exceeded"
|
|
196
|
+
return "internal_error"
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _expires_at(value) -> float:
|
|
200
|
+
if isinstance(value, str):
|
|
201
|
+
try:
|
|
202
|
+
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
203
|
+
except ValueError:
|
|
204
|
+
parsed = None
|
|
205
|
+
if parsed is not None:
|
|
206
|
+
return parsed.astimezone(timezone.utc).timestamp() - 60
|
|
207
|
+
return time.time() + 45 * 60
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
from daytona import Daytona
|
|
2
|
+
|
|
3
|
+
from continuum_task_server_bundle.daytona.common import (
|
|
4
|
+
HandlerError,
|
|
5
|
+
call_daytona,
|
|
6
|
+
ensure_started,
|
|
7
|
+
get_sandbox,
|
|
8
|
+
optional_bool,
|
|
9
|
+
optional_int,
|
|
10
|
+
refresh_sandbox,
|
|
11
|
+
request_timeout_for_sandbox,
|
|
12
|
+
require_sandbox_id,
|
|
13
|
+
resolve_timeout,
|
|
14
|
+
sandbox_state,
|
|
15
|
+
serialize_sandbox,
|
|
16
|
+
success,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def get_sandbox_info(daytona: Daytona, definition: dict, input_data: dict) -> dict:
|
|
21
|
+
sandbox = get_sandbox(daytona, require_sandbox_id(input_data))
|
|
22
|
+
return success(serialize_sandbox(sandbox))
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def start_sandbox(daytona: Daytona, definition: dict, input_data: dict) -> dict:
|
|
26
|
+
sandbox = get_sandbox(daytona, require_sandbox_id(input_data))
|
|
27
|
+
timeout = resolve_timeout(
|
|
28
|
+
input_data,
|
|
29
|
+
definition,
|
|
30
|
+
ceiling_key="max_lifecycle_timeout",
|
|
31
|
+
default=60,
|
|
32
|
+
)
|
|
33
|
+
call_daytona(lambda: ensure_started(sandbox, timeout), retry=False)
|
|
34
|
+
return success(serialize_sandbox(sandbox))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def stop_sandbox(daytona: Daytona, definition: dict, input_data: dict) -> dict:
|
|
38
|
+
sandbox = get_sandbox(daytona, require_sandbox_id(input_data))
|
|
39
|
+
timeout = resolve_timeout(
|
|
40
|
+
input_data,
|
|
41
|
+
definition,
|
|
42
|
+
ceiling_key="max_lifecycle_timeout",
|
|
43
|
+
default=60,
|
|
44
|
+
)
|
|
45
|
+
state = sandbox_state(sandbox)
|
|
46
|
+
if state not in {"stopped", "archived", "paused", "destroyed"}:
|
|
47
|
+
call_daytona(lambda: sandbox.stop(timeout=timeout), retry=False)
|
|
48
|
+
refresh_sandbox(sandbox)
|
|
49
|
+
return success(serialize_sandbox(sandbox))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def delete_sandbox(daytona: Daytona, definition: dict, input_data: dict) -> dict:
|
|
53
|
+
sandbox = get_sandbox(daytona, require_sandbox_id(input_data))
|
|
54
|
+
timeout = resolve_timeout(
|
|
55
|
+
input_data,
|
|
56
|
+
definition,
|
|
57
|
+
ceiling_key="max_lifecycle_timeout",
|
|
58
|
+
default=60,
|
|
59
|
+
)
|
|
60
|
+
wait = optional_bool(input_data, "wait")
|
|
61
|
+
if wait is None:
|
|
62
|
+
wait = optional_bool(definition, "wait") or False
|
|
63
|
+
call_daytona(
|
|
64
|
+
lambda: sandbox.delete(timeout=timeout, wait=wait),
|
|
65
|
+
retry=False,
|
|
66
|
+
)
|
|
67
|
+
return success(
|
|
68
|
+
{
|
|
69
|
+
"id": getattr(sandbox, "id", None),
|
|
70
|
+
"deleted": True,
|
|
71
|
+
"wait": wait,
|
|
72
|
+
}
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def get_preview_link(daytona: Daytona, definition: dict, input_data: dict) -> dict:
|
|
77
|
+
sandbox = get_sandbox(daytona, require_sandbox_id(input_data))
|
|
78
|
+
timeout = resolve_timeout(
|
|
79
|
+
input_data,
|
|
80
|
+
definition,
|
|
81
|
+
ceiling_key="max_lifecycle_timeout",
|
|
82
|
+
default=60,
|
|
83
|
+
)
|
|
84
|
+
call_daytona(lambda: ensure_started(sandbox, timeout), retry=False)
|
|
85
|
+
port = optional_int(input_data, "port", min_value=1, max_value=65535)
|
|
86
|
+
if port is None:
|
|
87
|
+
port = optional_int(definition, "port", min_value=1, max_value=65535)
|
|
88
|
+
if port is None:
|
|
89
|
+
raise HandlerError("port is required")
|
|
90
|
+
preview = call_daytona(
|
|
91
|
+
lambda: sandbox.get_preview_link(
|
|
92
|
+
port,
|
|
93
|
+
request_timeout=request_timeout_for_sandbox(sandbox),
|
|
94
|
+
),
|
|
95
|
+
retry=True,
|
|
96
|
+
)
|
|
97
|
+
return success(
|
|
98
|
+
{
|
|
99
|
+
"id": getattr(sandbox, "id", None),
|
|
100
|
+
"port": port,
|
|
101
|
+
"url": getattr(preview, "url", None),
|
|
102
|
+
"token": getattr(preview, "token", None),
|
|
103
|
+
}
|
|
104
|
+
)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Register Daytona task handling on an existing host."""
|
|
2
|
+
from os import getenv
|
|
3
|
+
|
|
4
|
+
from daytona import Daytona, DaytonaConfig
|
|
5
|
+
from .common import env_int
|
|
6
|
+
from .dispatch import dispatch
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def register_daytona(host, *, concurrency=None, client=None):
|
|
10
|
+
concurrency = env_int("DAYTONA_TASK_CONCURRENCY", 8) if concurrency is None else concurrency
|
|
11
|
+
daytona = client if client is not None else Daytona(DaytonaConfig(connection_pool_maxsize=250))
|
|
12
|
+
server = host.server
|
|
13
|
+
|
|
14
|
+
def handle(item):
|
|
15
|
+
version = server.client.task_items.versions.get_by_id(item.task_item_version_id)
|
|
16
|
+
return dispatch(daytona, version.item_definition_json or {}, item.input_data_json)
|
|
17
|
+
|
|
18
|
+
server.register("daytona", handle, concurrency=concurrency)
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import tempfile
|
|
3
|
+
from urllib.parse import unquote, urlparse
|
|
4
|
+
|
|
5
|
+
from botocore.exceptions import BotoCoreError, ClientError
|
|
6
|
+
from daytona import Daytona, DaytonaError
|
|
7
|
+
|
|
8
|
+
from continuum_task_server_bundle.daytona.common import (
|
|
9
|
+
HandlerError,
|
|
10
|
+
effective_limit,
|
|
11
|
+
get_running_sandbox,
|
|
12
|
+
map_daytona,
|
|
13
|
+
optional_str,
|
|
14
|
+
require_path,
|
|
15
|
+
success,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def s3_to_sandbox(daytona: Daytona, definition: dict, input_data: dict) -> dict:
|
|
20
|
+
sandbox = get_running_sandbox(daytona, input_data, definition)
|
|
21
|
+
path = require_path(input_data)
|
|
22
|
+
bucket, key = resolve_s3_location(input_data)
|
|
23
|
+
max_bytes = effective_limit(definition, "max_s3_bytes")
|
|
24
|
+
client = s3_client()
|
|
25
|
+
try:
|
|
26
|
+
head = client.head_object(Bucket=bucket, Key=key)
|
|
27
|
+
size = head.get("ContentLength")
|
|
28
|
+
if not isinstance(size, int):
|
|
29
|
+
raise HandlerError("S3 object size is unknown", "s3_error")
|
|
30
|
+
if size > max_bytes:
|
|
31
|
+
raise HandlerError(
|
|
32
|
+
f"S3 object is {size} bytes, which exceeds max_s3_bytes={max_bytes}",
|
|
33
|
+
"limit_exceeded",
|
|
34
|
+
)
|
|
35
|
+
obj = client.get_object(Bucket=bucket, Key=key)
|
|
36
|
+
sandbox.fs.upload_file_stream(obj["Body"], path)
|
|
37
|
+
except HandlerError:
|
|
38
|
+
raise
|
|
39
|
+
except DaytonaError as exc:
|
|
40
|
+
raise map_daytona(exc) from exc
|
|
41
|
+
except (ClientError, BotoCoreError) as exc:
|
|
42
|
+
raise map_boto(exc) from exc
|
|
43
|
+
return success(_transfer_result(bucket, key, path, size, "s3_to_sandbox"))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def sandbox_to_s3(daytona: Daytona, definition: dict, input_data: dict) -> dict:
|
|
47
|
+
sandbox = get_running_sandbox(daytona, input_data, definition)
|
|
48
|
+
path = require_path(input_data)
|
|
49
|
+
bucket, key = resolve_s3_location(input_data)
|
|
50
|
+
max_bytes = effective_limit(definition, "max_s3_bytes")
|
|
51
|
+
client = s3_client()
|
|
52
|
+
try:
|
|
53
|
+
info = sandbox.fs.get_file_info(path)
|
|
54
|
+
if getattr(info, "is_dir", False):
|
|
55
|
+
raise HandlerError("path is a directory")
|
|
56
|
+
size = getattr(info, "size", None)
|
|
57
|
+
if isinstance(size, int) and size > max_bytes:
|
|
58
|
+
raise HandlerError(
|
|
59
|
+
f"File is {size} bytes, which exceeds max_s3_bytes={max_bytes}",
|
|
60
|
+
"limit_exceeded",
|
|
61
|
+
)
|
|
62
|
+
written = 0
|
|
63
|
+
with tempfile.SpooledTemporaryFile(max_size=1024 * 1024) as tmp:
|
|
64
|
+
for chunk in sandbox.fs.download_file_stream(path):
|
|
65
|
+
if not chunk:
|
|
66
|
+
continue
|
|
67
|
+
written += len(chunk)
|
|
68
|
+
if written > max_bytes:
|
|
69
|
+
raise HandlerError(
|
|
70
|
+
f"Download exceeded max_s3_bytes={max_bytes}",
|
|
71
|
+
"limit_exceeded",
|
|
72
|
+
)
|
|
73
|
+
tmp.write(chunk)
|
|
74
|
+
tmp.seek(0)
|
|
75
|
+
client.upload_fileobj(tmp, bucket, key)
|
|
76
|
+
except HandlerError:
|
|
77
|
+
raise
|
|
78
|
+
except DaytonaError as exc:
|
|
79
|
+
raise map_daytona(exc) from exc
|
|
80
|
+
except (ClientError, BotoCoreError) as exc:
|
|
81
|
+
raise map_boto(exc) from exc
|
|
82
|
+
return success(
|
|
83
|
+
_transfer_result(
|
|
84
|
+
bucket,
|
|
85
|
+
key,
|
|
86
|
+
path,
|
|
87
|
+
written if not isinstance(size, int) else size,
|
|
88
|
+
"sandbox_to_s3",
|
|
89
|
+
)
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def s3_client():
|
|
94
|
+
import boto3
|
|
95
|
+
|
|
96
|
+
kwargs = {}
|
|
97
|
+
region = os.getenv("AWS_REGION") or os.getenv("AWS_DEFAULT_REGION")
|
|
98
|
+
endpoint = os.getenv("S3_ENDPOINT_URL")
|
|
99
|
+
if region:
|
|
100
|
+
kwargs["region_name"] = region
|
|
101
|
+
if endpoint:
|
|
102
|
+
kwargs["endpoint_url"] = endpoint
|
|
103
|
+
return boto3.client("s3", **kwargs)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _transfer_result(bucket: str, key: str, path: str, size: int, direction: str) -> dict:
|
|
107
|
+
return {
|
|
108
|
+
"bucket": bucket,
|
|
109
|
+
"key": key,
|
|
110
|
+
"s3_uri": f"s3://{bucket}/{key}",
|
|
111
|
+
"path": path,
|
|
112
|
+
"bytes": size,
|
|
113
|
+
"direction": direction,
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def resolve_s3_location(input_data: dict) -> tuple[str, str]:
|
|
118
|
+
allowed_bucket = configured_bucket()
|
|
119
|
+
s3_uri = optional_str(input_data, "s3_uri")
|
|
120
|
+
bucket = optional_str(input_data, "bucket")
|
|
121
|
+
key = optional_str(input_data, "key")
|
|
122
|
+
|
|
123
|
+
if s3_uri and (bucket or key):
|
|
124
|
+
raise HandlerError("Provide s3_uri or bucket/key, not both")
|
|
125
|
+
if s3_uri:
|
|
126
|
+
parsed_bucket, parsed_key = parse_s3_uri(s3_uri)
|
|
127
|
+
return confine_s3_location(parsed_bucket, parsed_key, allowed_bucket)
|
|
128
|
+
if bucket:
|
|
129
|
+
if key is None:
|
|
130
|
+
raise HandlerError("key is required when bucket is provided")
|
|
131
|
+
return confine_s3_location(bucket, normalize_relative_key(key), allowed_bucket)
|
|
132
|
+
if key is None:
|
|
133
|
+
raise HandlerError("s3_uri or key is required")
|
|
134
|
+
return confine_s3_location(
|
|
135
|
+
allowed_bucket,
|
|
136
|
+
join_s3_key(os.getenv("S3_PREFIX"), key),
|
|
137
|
+
allowed_bucket,
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def configured_bucket() -> str:
|
|
142
|
+
bucket = (os.getenv("S3_BUCKET") or "").strip()
|
|
143
|
+
if not bucket:
|
|
144
|
+
raise HandlerError("S3_BUCKET is not configured")
|
|
145
|
+
return bucket
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def configured_prefix() -> str | None:
|
|
149
|
+
raw = (os.getenv("S3_PREFIX") or "").strip().strip("/")
|
|
150
|
+
if not raw:
|
|
151
|
+
return None
|
|
152
|
+
return normalize_relative_key(raw)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def parse_s3_uri(uri: str) -> tuple[str, str]:
|
|
156
|
+
parsed = urlparse(uri.strip())
|
|
157
|
+
if parsed.scheme != "s3" or not parsed.netloc:
|
|
158
|
+
raise HandlerError("s3_uri must be s3://bucket/key")
|
|
159
|
+
if parsed.query or parsed.fragment or parsed.params:
|
|
160
|
+
raise HandlerError("s3_uri must not include query or fragment")
|
|
161
|
+
key = unquote(parsed.path.lstrip("/"))
|
|
162
|
+
if not key:
|
|
163
|
+
raise HandlerError("s3_uri must include an object key")
|
|
164
|
+
return parsed.netloc, normalize_relative_key(key)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def confine_s3_location(bucket: str, key: str, allowed_bucket: str) -> tuple[str, str]:
|
|
168
|
+
if bucket != allowed_bucket:
|
|
169
|
+
raise HandlerError("S3 bucket is not allowed", "forbidden")
|
|
170
|
+
prefix = configured_prefix()
|
|
171
|
+
if prefix and key != prefix and not key.startswith(f"{prefix}/"):
|
|
172
|
+
raise HandlerError("S3 key is outside the configured prefix", "forbidden")
|
|
173
|
+
return bucket, key
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def join_s3_key(prefix: str | None, relative_key: str) -> str:
|
|
177
|
+
key = normalize_relative_key(relative_key)
|
|
178
|
+
cleaned_prefix = (prefix or "").strip().strip("/")
|
|
179
|
+
if not cleaned_prefix:
|
|
180
|
+
return key
|
|
181
|
+
prefix_key = normalize_relative_key(cleaned_prefix)
|
|
182
|
+
return f"{prefix_key}/{key}"
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def normalize_relative_key(value: str) -> str:
|
|
186
|
+
key = (value or "").strip()
|
|
187
|
+
if not key:
|
|
188
|
+
raise HandlerError("key is required")
|
|
189
|
+
if key.startswith("/") or key.startswith("\\"):
|
|
190
|
+
raise HandlerError("S3 key must be relative")
|
|
191
|
+
if "\\" in key:
|
|
192
|
+
raise HandlerError("S3 key must use forward slashes")
|
|
193
|
+
parts = [part for part in key.split("/")]
|
|
194
|
+
if any(part in {"", ".", ".."} for part in parts):
|
|
195
|
+
raise HandlerError("S3 key must not contain empty, '.', or '..' segments")
|
|
196
|
+
return "/".join(parts)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def map_boto(exc: Exception) -> HandlerError:
|
|
200
|
+
if isinstance(exc, ClientError):
|
|
201
|
+
error = (exc.response or {}).get("Error") or {}
|
|
202
|
+
code = str(error.get("Code") or "")
|
|
203
|
+
message = str(error.get("Message") or code or "S3 request failed")
|
|
204
|
+
if code in {"404", "NoSuchKey", "NoSuchBucket", "NotFound", "404 Not Found"}:
|
|
205
|
+
return HandlerError("S3 object not found", "not_found")
|
|
206
|
+
return HandlerError(message, "s3_error")
|
|
207
|
+
return HandlerError(str(exc) or exc.__class__.__name__, "s3_error")
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Postgres registry for Discord attachments (stable refs + optional S3 metadata)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
from uuid import UUID
|
|
7
|
+
|
|
8
|
+
from continuum_task_server_bundle.discord.message_await_db import connect, database_url
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def ensure_attachment_ref(
|
|
12
|
+
*,
|
|
13
|
+
channel_id: int,
|
|
14
|
+
message_id: int,
|
|
15
|
+
discord_attachment_id: int,
|
|
16
|
+
filename: str,
|
|
17
|
+
size: int,
|
|
18
|
+
content_type: str | None,
|
|
19
|
+
ephemeral: bool,
|
|
20
|
+
) -> UUID | None:
|
|
21
|
+
"""Upsert registry row; return stable attachment_ref (id). None if DATABASE_URL unset."""
|
|
22
|
+
if not database_url():
|
|
23
|
+
return None
|
|
24
|
+
with connect() as conn:
|
|
25
|
+
with conn.transaction():
|
|
26
|
+
with conn.cursor() as cur:
|
|
27
|
+
cur.execute(
|
|
28
|
+
"""
|
|
29
|
+
INSERT INTO discord_attachment_registry (
|
|
30
|
+
channel_id,
|
|
31
|
+
message_id,
|
|
32
|
+
discord_attachment_id,
|
|
33
|
+
filename,
|
|
34
|
+
size,
|
|
35
|
+
content_type,
|
|
36
|
+
ephemeral
|
|
37
|
+
)
|
|
38
|
+
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
|
39
|
+
ON CONFLICT (channel_id, message_id, discord_attachment_id)
|
|
40
|
+
DO UPDATE SET
|
|
41
|
+
filename = EXCLUDED.filename,
|
|
42
|
+
size = EXCLUDED.size,
|
|
43
|
+
content_type = EXCLUDED.content_type,
|
|
44
|
+
ephemeral = EXCLUDED.ephemeral,
|
|
45
|
+
updated_at = now()
|
|
46
|
+
RETURNING id
|
|
47
|
+
""",
|
|
48
|
+
(
|
|
49
|
+
channel_id,
|
|
50
|
+
message_id,
|
|
51
|
+
discord_attachment_id,
|
|
52
|
+
filename,
|
|
53
|
+
size,
|
|
54
|
+
content_type,
|
|
55
|
+
ephemeral,
|
|
56
|
+
),
|
|
57
|
+
)
|
|
58
|
+
row = cur.fetchone()
|
|
59
|
+
if not row:
|
|
60
|
+
return None
|
|
61
|
+
return UUID(str(row["id"]))
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def get_by_ref(*, attachment_ref: UUID) -> dict[str, Any] | None:
|
|
65
|
+
if not database_url():
|
|
66
|
+
return None
|
|
67
|
+
with connect() as conn:
|
|
68
|
+
with conn.transaction():
|
|
69
|
+
with conn.cursor() as cur:
|
|
70
|
+
cur.execute(
|
|
71
|
+
"""
|
|
72
|
+
SELECT * FROM discord_attachment_registry
|
|
73
|
+
WHERE id = %s
|
|
74
|
+
""",
|
|
75
|
+
(str(attachment_ref),),
|
|
76
|
+
)
|
|
77
|
+
return cur.fetchone()
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def get_by_triplet(
|
|
81
|
+
*,
|
|
82
|
+
channel_id: int,
|
|
83
|
+
message_id: int,
|
|
84
|
+
discord_attachment_id: int,
|
|
85
|
+
) -> dict[str, Any] | None:
|
|
86
|
+
if not database_url():
|
|
87
|
+
return None
|
|
88
|
+
with connect() as conn:
|
|
89
|
+
with conn.transaction():
|
|
90
|
+
with conn.cursor() as cur:
|
|
91
|
+
cur.execute(
|
|
92
|
+
"""
|
|
93
|
+
SELECT * FROM discord_attachment_registry
|
|
94
|
+
WHERE channel_id = %s AND message_id = %s AND discord_attachment_id = %s
|
|
95
|
+
""",
|
|
96
|
+
(channel_id, message_id, discord_attachment_id),
|
|
97
|
+
)
|
|
98
|
+
return cur.fetchone()
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def try_set_s3_uri(
|
|
102
|
+
*,
|
|
103
|
+
registry_id: UUID,
|
|
104
|
+
s3_bucket: str,
|
|
105
|
+
s3_key: str,
|
|
106
|
+
s3_uri: str,
|
|
107
|
+
) -> bool:
|
|
108
|
+
"""Set S3 fields only if not already archived. Returns True if this call stored them."""
|
|
109
|
+
if not database_url():
|
|
110
|
+
return False
|
|
111
|
+
with connect() as conn:
|
|
112
|
+
with conn.transaction():
|
|
113
|
+
with conn.cursor() as cur:
|
|
114
|
+
cur.execute(
|
|
115
|
+
"""
|
|
116
|
+
UPDATE discord_attachment_registry
|
|
117
|
+
SET s3_bucket = %s,
|
|
118
|
+
s3_key = %s,
|
|
119
|
+
s3_uri = %s,
|
|
120
|
+
archived_at = now(),
|
|
121
|
+
updated_at = now()
|
|
122
|
+
WHERE id = %s AND s3_uri IS NULL
|
|
123
|
+
RETURNING id
|
|
124
|
+
""",
|
|
125
|
+
(s3_bucket, s3_key, s3_uri, str(registry_id)),
|
|
126
|
+
)
|
|
127
|
+
return cur.fetchone() is not None
|