-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexport_api.py
More file actions
288 lines (245 loc) · 8.9 KB
/
Copy pathexport_api.py
File metadata and controls
288 lines (245 loc) · 8.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
"""Export endpoints -- bulk zip download and single-session md/json."""
import io
import json
import os
import zipfile
from datetime import datetime
from typing import Any
from flask import Blueprint, current_app, request, send_file
from api._flask_types import FlaskReturn, json_response
from api.error_codes import ErrorCode, error_response
from models.export import ExportStateDict
from utils.exclusion_rules import is_session_excluded
from utils.export_engine import (
EXPORT_ERRORS as _EXPORT_ERRORS,
ExportFailure,
ZipSink,
run_bulk_export,
)
from utils.export_state_store import (
EXPORT_STATE_FILE,
atomic_write_export_state,
export_state_lock,
load_export_state_from_disk,
)
from utils.json_exporter import session_to_json
from utils.jsonl_parser import parse_session
from utils.md_exporter import session_to_markdown
from utils.session_path import get_claude_projects_dir, list_projects, safe_join
from utils.session_stats import compute_stats
from utils.slugify import slugify
export_bp = Blueprint("export", __name__)
# Tests monkeypatch this path; keep in sync with utils.export_state_store.
_STATE_FILE = EXPORT_STATE_FILE
_EXPORT_WARNINGS_ZIP_NAME = "export-warnings.json"
_EXPORT_WARNINGS_HEADER_MAX_ENTRIES = 20
_EXPORT_WARNINGS_HEADER_MAX_BYTES = 8192
def _state_lock() -> Any:
return export_state_lock(_STATE_FILE)
def _load_state_from_disk() -> ExportStateDict:
return load_export_state_from_disk(_STATE_FILE)
def _atomic_write_state(state: ExportStateDict) -> None:
atomic_write_export_state(state, _STATE_FILE)
def _read_state() -> ExportStateDict:
with _state_lock():
return _load_state_from_disk()
def _serialize_export_failures(failures: list[ExportFailure]) -> list[dict[str, object]]:
return [
{
"session_id": item.session_id,
"code": str(item.code),
"message": item.message,
}
for item in failures
]
def _export_warnings_header_payload(
failures: list[ExportFailure],
) -> dict[str, object]:
"""Bounded summary for X-Export-Warnings; full list lives in export-warnings.json."""
entries = _serialize_export_failures(failures)
total = len(entries)
sample = entries[:_EXPORT_WARNINGS_HEADER_MAX_ENTRIES]
truncated = total > len(sample)
payload: dict[str, object] = {
"total_failures": total,
"truncated": truncated,
"failures": sample,
}
while (
len(json.dumps(payload, separators=(",", ":"))) > _EXPORT_WARNINGS_HEADER_MAX_BYTES
and len(sample) > 1
):
sample = sample[:-1]
truncated = True
payload = {"total_failures": total, "truncated": truncated, "failures": sample}
if len(json.dumps(payload, separators=(",", ":"))) > _EXPORT_WARNINGS_HEADER_MAX_BYTES:
payload = {"total_failures": total, "truncated": True, "failures": []}
return payload
def _write_state(sessions_map: dict[str, float], count: int) -> None:
"""Persist merge of *sessions_map* and update last-export metadata (*count* = this run only)."""
with _state_lock():
state = _load_state_from_disk()
state["lastExportTime"] = datetime.now().isoformat()
state["exportedCount"] = count
state.setdefault("sessions", {}).update(sessions_map)
_atomic_write_state(state)
@export_bp.route("/api/export/state")
def get_export_state() -> FlaskReturn:
state = _read_state()
n = state.get("exportedCount", 0)
return json_response(
{
"last_export_time": state.get("lastExportTime"),
# Sessions exported in the last completed bulk export (not a lifetime total).
"last_export_session_count": n,
}
)
@export_bp.route("/api/export", methods=["POST"])
def bulk_export() -> FlaskReturn:
body = request.get_json(silent=True)
if body is None:
body = {}
if not isinstance(body, dict):
return error_response(
ErrorCode.INVALID_REQUEST_BODY,
"Invalid request body",
400,
)
since = body.get("since", "all")
if since not in ("all", "last", "incremental"):
return error_response(
ErrorCode.INVALID_SINCE_MODE,
"Invalid since mode",
400,
since=since,
)
base = current_app.config.get("CLAUDE_PROJECTS_DIR") or get_claude_projects_dir()
projects = list_projects(base)
rules = current_app.config.get("EXCLUSION_RULES") or []
state = _read_state()
last_export_sessions: dict[str, float] = (
state.get("sessions", {}) if since == "incremental" else {}
)
buf = io.BytesIO()
def _on_export_error(sid: str, exc: Exception) -> None:
current_app.logger.warning("Failed to export %s: %s", sid[:10], exc)
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
result = run_bulk_export(
projects=projects,
since=since,
rules=rules,
last_export_sessions=last_export_sessions,
sink=ZipSink(zf),
fmt="md",
path_layout="api",
manifest_style="api",
on_export_error=_on_export_error,
)
if result.failures and result.exported_session_count > 0:
full_warnings = _serialize_export_failures(result.failures)
zf.writestr(
_EXPORT_WARNINGS_ZIP_NAME,
json.dumps(full_warnings, separators=(",", ":")) + "\n",
)
count = result.exported_session_count
new_sessions_map = result.new_sessions_map
latest_day = result.latest_day
failure_payload = _serialize_export_failures(result.failures)
if count == 0:
if result.failures:
return error_response(
ErrorCode.EXPORT_ALL_FAILED,
"All export candidates failed",
422,
since=since,
failures=failure_payload,
)
return error_response(
ErrorCode.EXPORT_NOTHING_TO_EXPORT,
"Nothing to export",
422,
since=since,
)
_write_state(new_sessions_map, count)
buf.seek(0)
date_tag = datetime.now().strftime("%Y-%m-%d")
if since == "last":
if latest_day is not None:
suffix = f"-last-{latest_day.strftime('%m-%d')}"
else:
suffix = "-last"
elif since == "incremental":
suffix = "-incremental"
else:
suffix = ""
resp = send_file(
buf,
mimetype="application/zip",
as_attachment=True,
download_name=f"claude-code-export{suffix}-{date_tag}.zip", # type: ignore[call-arg]
)
if result.failures:
resp.headers["X-Export-Warnings"] = json.dumps(
_export_warnings_header_payload(result.failures),
separators=(",", ":"),
)
return resp
@export_bp.route("/api/export/session/<path:project_name>/<session_id>")
def export_session(project_name: str, session_id: str) -> FlaskReturn:
base = current_app.config.get("CLAUDE_PROJECTS_DIR") or get_claude_projects_dir()
try:
filepath = safe_join(base, project_name, f"{session_id}.jsonl")
except ValueError:
return error_response(ErrorCode.INVALID_PATH, "Invalid path", 400)
if not os.path.isfile(filepath):
return error_response(
ErrorCode.SESSION_NOT_FOUND,
"Session not found",
404,
)
fmt = request.args.get("format", "md")
try:
session = parse_session(filepath)
except _EXPORT_ERRORS:
current_app.logger.exception("Failed to parse session %s for export", session_id)
return error_response(
ErrorCode.PARSE_ERROR,
"Failed to parse session",
500,
)
rules = current_app.config.get("EXCLUSION_RULES") or []
if is_session_excluded(rules, session, project_name):
return error_response(
ErrorCode.SESSION_NOT_FOUND,
"Session not found",
404,
)
try:
stats = compute_stats(session)
except _EXPORT_ERRORS:
current_app.logger.exception("Failed to compute stats for export %s", session_id)
return error_response(
ErrorCode.INTERNAL_ERROR,
"Failed to compute session stats",
500,
)
title_slug = slugify(session["title"], default="session")
if fmt == "json":
content = session_to_json(session, stats)
buf = io.BytesIO(content.encode("utf-8"))
buf.seek(0)
return send_file(
buf,
mimetype="application/json",
as_attachment=True,
download_name=f"{title_slug}.json", # type: ignore[call-arg]
)
md = session_to_markdown(session, stats)
buf = io.BytesIO(md.encode("utf-8"))
buf.seek(0)
return send_file(
buf,
mimetype="text/markdown",
as_attachment=True,
download_name=f"{title_slug}.md", # type: ignore[call-arg]
)