Codex commited on
Commit
9ff3744
·
1 Parent(s): 6fd92d8

feat: add backup zip download endpoint

Browse files
Files changed (2) hide show
  1. app.py +36 -0
  2. tests/test_app_downloads.py +51 -0
app.py CHANGED
@@ -7,7 +7,9 @@ import os
7
  import shlex
8
  import subprocess
9
  import time
 
10
  from collections import deque
 
11
  from pathlib import Path
12
  from urllib.parse import parse_qs, quote, unquote
13
  from wsgiref.simple_server import make_server
@@ -16,6 +18,7 @@ from http import cookies
16
  from common import (
17
  APP_DIR,
18
  STATIC_DIR,
 
19
  CLEANER_LOG_PATH,
20
  WEB_LOG_PATH,
21
  REPORT_DIR,
@@ -464,6 +467,37 @@ def handle_report_download(environ, start_response):
464
  )
465
 
466
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
467
  def handle_save_config(environ, start_response):
468
  require_auth(environ)
469
  if environ.get('REQUEST_METHOD') != 'POST':
@@ -553,6 +587,8 @@ def application(environ, start_response):
553
  return handle_report_detail(environ, start_response)
554
  if path == '/CLIProxyAPI-cleaner/api/report/download':
555
  return handle_report_download(environ, start_response)
 
 
556
  if path == '/CLIProxyAPI-cleaner/api/config/save':
557
  return handle_save_config(environ, start_response)
558
  if path == '/CLIProxyAPI-cleaner/api/service/start':
 
7
  import shlex
8
  import subprocess
9
  import time
10
+ import zipfile
11
  from collections import deque
12
+ from datetime import datetime, timezone
13
  from pathlib import Path
14
  from urllib.parse import parse_qs, quote, unquote
15
  from wsgiref.simple_server import make_server
 
18
  from common import (
19
  APP_DIR,
20
  STATIC_DIR,
21
+ BACKUP_DIR,
22
  CLEANER_LOG_PATH,
23
  WEB_LOG_PATH,
24
  REPORT_DIR,
 
467
  )
468
 
469
 
470
+ def build_backup_archive() -> Path:
471
+ BACKUP_DIR.mkdir(parents=True, exist_ok=True)
472
+ files = [path for path in BACKUP_DIR.rglob('*') if path.is_file()]
473
+ if not files:
474
+ raise AppError('backup_not_found', 'no backups available', '404 Not Found')
475
+
476
+ archive_root = BACKUP_DIR.parent / '.tmp-downloads'
477
+ archive_root.mkdir(parents=True, exist_ok=True)
478
+ archive_path = archive_root / f'cliproxyapi-backups-{datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")}.zip'
479
+ if archive_path.exists():
480
+ archive_path.unlink()
481
+ with zipfile.ZipFile(archive_path, 'w', compression=zipfile.ZIP_DEFLATED) as zf:
482
+ for path in files:
483
+ zf.write(path, arcname=path.relative_to(BACKUP_DIR).as_posix())
484
+ return archive_path
485
+
486
+
487
+ def handle_backups_download(environ, start_response):
488
+ require_auth(environ)
489
+ archive_path = build_backup_archive()
490
+ try:
491
+ return file_response(
492
+ start_response,
493
+ archive_path.read_bytes(),
494
+ filename=archive_path.name,
495
+ content_type='application/zip',
496
+ )
497
+ finally:
498
+ archive_path.unlink(missing_ok=True)
499
+
500
+
501
  def handle_save_config(environ, start_response):
502
  require_auth(environ)
503
  if environ.get('REQUEST_METHOD') != 'POST':
 
587
  return handle_report_detail(environ, start_response)
588
  if path == '/CLIProxyAPI-cleaner/api/report/download':
589
  return handle_report_download(environ, start_response)
590
+ if path == '/CLIProxyAPI-cleaner/api/backups/download':
591
+ return handle_backups_download(environ, start_response)
592
  if path == '/CLIProxyAPI-cleaner/api/config/save':
593
  return handle_save_config(environ, start_response)
594
  if path == '/CLIProxyAPI-cleaner/api/service/start':
tests/test_app_downloads.py CHANGED
@@ -5,6 +5,7 @@ import shutil
5
  import sys
6
  import unittest
7
  import uuid
 
8
  from pathlib import Path
9
 
10
 
@@ -19,6 +20,7 @@ SPEC.loader.exec_module(app)
19
  class TestAppDownloads(unittest.TestCase):
20
  def setUp(self):
21
  self.original_report_dir = app.REPORT_DIR
 
22
  self.original_require_auth = app.require_auth
23
  self.original_ensure_app_dirs = app.ensure_app_dirs
24
  self.original_load_config = app.load_config
@@ -27,12 +29,16 @@ class TestAppDownloads(unittest.TestCase):
27
  self.tmp.mkdir()
28
  self.addCleanup(shutil.rmtree, self.tmp, ignore_errors=True)
29
  app.REPORT_DIR = self.tmp
 
 
30
  app.require_auth = lambda environ: ("token", {"ip": "127.0.0.1"})
31
  app.ensure_app_dirs = lambda: None
32
  app.load_config = lambda: {"allowed_hosts": ["localhost"]}
33
 
34
  def tearDown(self):
35
  app.REPORT_DIR = self.original_report_dir
 
 
36
  app.require_auth = self.original_require_auth
37
  app.ensure_app_dirs = self.original_ensure_app_dirs
38
  app.load_config = self.original_load_config
@@ -109,6 +115,51 @@ class TestAppDownloads(unittest.TestCase):
109
  self.assertEqual(name, detail["name"])
110
  self.assertEqual(payload, detail["data"])
111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
  if __name__ == "__main__":
114
  unittest.main()
 
5
  import sys
6
  import unittest
7
  import uuid
8
+ import zipfile
9
  from pathlib import Path
10
 
11
 
 
20
  class TestAppDownloads(unittest.TestCase):
21
  def setUp(self):
22
  self.original_report_dir = app.REPORT_DIR
23
+ self.original_backup_dir = getattr(app, "BACKUP_DIR", None)
24
  self.original_require_auth = app.require_auth
25
  self.original_ensure_app_dirs = app.ensure_app_dirs
26
  self.original_load_config = app.load_config
 
29
  self.tmp.mkdir()
30
  self.addCleanup(shutil.rmtree, self.tmp, ignore_errors=True)
31
  app.REPORT_DIR = self.tmp
32
+ app.BACKUP_DIR = self.tmp / "backups"
33
+ app.BACKUP_DIR.mkdir()
34
  app.require_auth = lambda environ: ("token", {"ip": "127.0.0.1"})
35
  app.ensure_app_dirs = lambda: None
36
  app.load_config = lambda: {"allowed_hosts": ["localhost"]}
37
 
38
  def tearDown(self):
39
  app.REPORT_DIR = self.original_report_dir
40
+ if self.original_backup_dir is not None:
41
+ app.BACKUP_DIR = self.original_backup_dir
42
  app.require_auth = self.original_require_auth
43
  app.ensure_app_dirs = self.original_ensure_app_dirs
44
  app.load_config = self.original_load_config
 
115
  self.assertEqual(name, detail["name"])
116
  self.assertEqual(payload, detail["data"])
117
 
118
+ def test_handle_backups_download_errors_when_backup_root_is_empty(self):
119
+ captured, start_response = self._start_response()
120
+ environ = {
121
+ "REQUEST_METHOD": "GET",
122
+ "QUERY_STRING": "",
123
+ "wsgi.input": io.BytesIO(b""),
124
+ }
125
+
126
+ response = app.application(
127
+ {**environ, "PATH_INFO": "/CLIProxyAPI-cleaner/api/backups/download", "HTTP_HOST": "localhost"},
128
+ start_response,
129
+ )
130
+ body = json.loads(b"".join(response).decode("utf-8"))
131
+
132
+ self.assertEqual("404 Not Found", captured["status"])
133
+ self.assertFalse(body["ok"])
134
+ self.assertEqual("backup_not_found", body["error"])
135
+
136
+ def test_handle_backups_download_returns_zip_with_relative_paths(self):
137
+ backup_file = app.BACKUP_DIR / "20260416T130853Z" / "delete-401" / "demo.json"
138
+ backup_file.parent.mkdir(parents=True)
139
+ backup_file.write_text('{"ok": true}\n', encoding="utf-8")
140
+ captured, start_response = self._start_response()
141
+ environ = {
142
+ "REQUEST_METHOD": "GET",
143
+ "QUERY_STRING": "",
144
+ "wsgi.input": io.BytesIO(b""),
145
+ }
146
+
147
+ body = b"".join(
148
+ app.handle_backups_download(
149
+ environ,
150
+ start_response,
151
+ )
152
+ )
153
+
154
+ self.assertEqual("200 OK", captured["status"])
155
+ header_map = dict(captured["headers"])
156
+ self.assertEqual("application/zip", header_map["Content-Type"])
157
+ self.assertIn(".zip", header_map["Content-Disposition"])
158
+ archive_path = self.tmp / "assert-backups.zip"
159
+ archive_path.write_bytes(body)
160
+ with zipfile.ZipFile(archive_path) as zf:
161
+ self.assertIn("20260416T130853Z/delete-401/demo.json", zf.namelist())
162
+
163
 
164
  if __name__ == "__main__":
165
  unittest.main()