feat(transfer): add streaming cat, resumable Range downloads, and transfer deadlines

- Add O(1)-memory chunked Client.stream_request with total transfer deadline and premature-EOF detection
- Add pages cat --stream with incremental stdout output and end-of-stream SHA-256 verification
- Add pages get --resume with private 0600 staging, Range/If-Range/Content-Range checks, full re-hash before atomic no-clobber commit, and --max-bytes/--timeout
- Pre-check 1 MiB limit in pages put and update docs and unit tests
This commit is contained in:
Anya Tokugawa committed 2026-11-30 22:27:52 +09:00
1 parent a7ef59f8c0
commit 13a4416af9
4 files changed
+690 -32

No files matched your search

+367 -19
View File
@@ -9,6 +9,7 @@ import uuid
import base64
import contextlib
import difflib
import errno
import fcntl
import getpass
import hashlib
@@ -73,6 +74,24 @@ def address(value, cwd='/'):
return 'path:' + semantic(value, cwd)
CHUNK_SIZE = 65536
DEFAULT_TIMEOUT = 20
DEFAULT_DEADLINE = 300
DEFAULT_DOWNLOAD_LIMIT = 64 << 20
def _iter_stream(stream, expected_length, deadline, clock):
remaining = expected_length
while remaining > 0:
if clock() > deadline:
raise Failure('Transfer exceeded total time deadline; no automatic write retry was attempted.')
chunk = stream.read(min(CHUNK_SIZE, remaining))
if not chunk:
raise Failure('Local input ended before expected Content-Length.')
remaining -= len(chunk)
yield chunk
class NoRedirect(http.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None # Never forward credentials or turn a login HTML page into success.
@@ -92,9 +111,16 @@ class Client:
handlers.append(http.HTTPSHandler(context=context))
self.opener = http.build_opener(*handlers)
def request(self, route, method='GET', data=None, form=None, limit=4 << 20, etag=None, content_type=None, headers=None, expect_status=None):
def stream_request(self, route, method='GET', data=None, form=None, *,
limit=4 << 20, etag=None, content_type=None, headers=None,
expect_status=None, on_headers=None, on_chunk=None,
timeout=DEFAULT_TIMEOUT, deadline_seconds=DEFAULT_DEADLINE,
content_length=None, max_request_bytes=2 << 20, clock=time.monotonic):
if not route.startswith('/') or route.startswith('//'):
raise Failure('Invalid API route.')
if deadline_seconds <= 0 or timeout <= 0:
raise Failure('Transfer timeout and deadline must be positive.')
deadline = clock() + deadline_seconds
req_headers = {'Accept': 'application/json', 'User-Agent': 'pages-cli/' + VERSION}
if headers:
req_headers.update(headers)
@@ -104,22 +130,61 @@ class Client:
req_headers['Authorization'] = 'Bearer ' + self.token
body = None
if data is not None:
body = data if isinstance(data, bytes) else json.dumps(data, ensure_ascii=False).encode()
req_headers['Content-Type'] = content_type or 'application/json'
if hasattr(data, 'read'):
if not isinstance(content_length, int) or isinstance(content_length, bool) or content_length < 0:
raise Failure('Streaming upload requires a non-negative integer Content-Length.')
if max_request_bytes is not None and content_length > max_request_bytes:
raise Failure('Request exceeds the client upload limit.')
req_headers['Content-Type'] = content_type or 'application/octet-stream'
req_headers['Content-Length'] = str(content_length)
body = _iter_stream(data, content_length, deadline, clock)
else:
body = data if isinstance(data, bytes) else json.dumps(data, ensure_ascii=False).encode()
req_headers['Content-Type'] = content_type or 'application/json'
if max_request_bytes is not None and len(body) > max_request_bytes:
raise Failure('Request exceeds the 2 MiB client limit.')
if form is not None:
body = url.urlencode(form).encode()
req_headers['Content-Type'] = 'application/x-www-form-urlencoded'
if body is not None and len(body) > 2 << 20:
raise Failure('Request exceeds the 2 MiB client limit.')
if max_request_bytes is not None and len(body) > max_request_bytes:
raise Failure('Request exceeds the 2 MiB client limit.')
req = http.Request(self.base + route, body, req_headers, method=method)
try:
with self.opener.open(req, timeout=20) as response:
with self.opener.open(req, timeout=min(timeout, max(0.1, deadline - clock()))) as response:
if expect_status is not None and response.status != expect_status:
raise Failure('Unexpected HTTP status (%d).' % response.status, response.status)
raw = response.read(limit + 1)
if len(raw) > limit:
cl_header = (response.headers.get('Content-Length') or '').strip()
expected_cl = int(cl_header) if (method != 'HEAD' and cl_header.isdigit()) else None
if expected_cl is not None and limit is not None and expected_cl > limit:
raise Failure('Response exceeds client limit; use the browser for large files.')
return raw, response.headers
if on_headers is not None:
on_headers(response.status, response.headers)
buf = None if on_chunk is not None else bytearray()
total = 0
while True:
remaining_time = deadline - clock()
if remaining_time <= 0:
raise Failure('Transfer exceeded total time deadline; no automatic write retry was attempted.')
sock = getattr(getattr(getattr(response, 'fp', None), 'raw', None), '_sock', None)
if sock is not None and hasattr(sock, 'settimeout'):
try:
sock.settimeout(min(timeout, remaining_time))
except OSError:
pass
to_read = CHUNK_SIZE if limit is None else min(CHUNK_SIZE, (limit - total) + 1)
chunk = response.read(to_read)
if not chunk:
break
total += len(chunk)
if limit is not None and total > limit:
raise Failure('Response exceeds client limit; use the browser for large files.')
if on_chunk is not None:
on_chunk(chunk)
else:
buf.extend(chunk)
if expected_cl is not None and total != expected_cl:
raise Failure('Incomplete transfer: received %d of %d bytes.' % (total, expected_cl))
return (None if on_chunk is not None else bytes(buf)), response.headers
except urllib.error.HTTPError as e:
raw = e.read(65536)
e.close()
@@ -131,12 +196,17 @@ class Client:
payload = {}
messages = {303: 'Login redirect refused; log in again.', 401: 'Session expired or authentication required.', 403: 'Access denied.',
404: 'Not found or not readable.', 409: 'Conflict: remote revision changed.',
412: 'Conflict: remote item changed; reload before saving.', 422: 'Invalid fields; check dates, project and required settings.',
412: 'Conflict: remote item changed; reload before saving.', 416: 'Requested byte range is not satisfiable.',
422: 'Invalid fields; check dates, project and required settings.',
428: 'Precondition required by server.'}
raise Failure(messages.get(e.code, 'HTTP request failed (%d); redirects are not followed.' % e.code), e.code, payload) from None
except (urllib.error.URLError, TimeoutError, OSError):
raise Failure('Connection/TLS failure; no automatic write retry was attempted.') from None
def request(self, route, method='GET', data=None, form=None, limit=4 << 20, etag=None, content_type=None, headers=None, expect_status=None):
return self.stream_request(route, method=method, data=data, form=form, limit=limit, etag=etag,
content_type=content_type, headers=headers, expect_status=expect_status)
def json(self, route, **kwargs):
raw, headers = self.request(route, **kwargs)
if headers.get_content_type() != 'application/json':
@@ -227,14 +297,264 @@ class Client:
def listing(self, path, prefix=''):
return self.json('/_/api/v1/path-picker?' + url.urlencode({'path': path, 'mode': 'children', 'prefix': prefix}))
def raw(self, addr, method='GET'):
def raw(self, addr, method='GET', *, limit=DEFAULT_DOWNLOAD_LIMIT, deadline_seconds=DEFAULT_DEADLINE):
query = '' if self.lang == 'auto' else '?' + url.urlencode({'lang': self.lang})
raw, headers = self.request('/v/raw/' + url.quote(addr, safe='/:') + query, method=method, limit=64 << 20)
raw, headers = self.stream_request(
'/v/raw/' + url.quote(addr, safe='/:') + query, method=method,
limit=limit, deadline_seconds=deadline_seconds)
digest = headers.get('X-PagesWiki-Document-SHA256')
if method == 'GET' and (not digest or hashlib.sha256(raw).hexdigest() != digest):
raise Failure('Document SHA-256 mismatch.')
return raw, headers
def stream_raw(self, addr, on_chunk, *, on_headers=None, limit=DEFAULT_DOWNLOAD_LIMIT, deadline_seconds=DEFAULT_DEADLINE, clock=time.monotonic):
if limit <= 0 or deadline_seconds <= 0:
raise Failure('Download limit and deadline must be positive.')
query = '' if self.lang == 'auto' else '?' + url.urlencode({'lang': self.lang})
hasher = hashlib.sha256()
def handle_chunk(chunk):
hasher.update(chunk)
on_chunk(chunk)
_, headers = self.stream_request(
'/v/raw/' + url.quote(addr, safe='/:') + query, method='GET',
limit=limit, on_headers=on_headers, on_chunk=handle_chunk,
deadline_seconds=deadline_seconds, clock=clock)
digest = (headers.get('X-PagesWiki-Document-SHA256') or '').strip()
if not digest or hasher.hexdigest() != digest:
raise Failure('Document SHA-256 mismatch after streaming output; streamed bytes must not be trusted.')
return headers
@staticmethod
def _write_private_json_atomic(path, data):
tmp = path.parent / ('.pages-meta-' + secrets.token_hex(8) + '.tmp')
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
try:
with os.fdopen(fd, 'w', encoding='utf-8') as out:
out.write(json.dumps(data))
out.flush()
os.fsync(out.fileno())
os.replace(tmp, path)
finally:
if tmp.exists() or tmp.is_symlink():
tmp.unlink()
@staticmethod
def _hash_file(path):
hasher = hashlib.sha256()
with open(path, 'rb') as src:
while True:
chunk = src.read(CHUNK_SIZE)
if not chunk:
break
hasher.update(chunk)
return hasher.hexdigest()
@staticmethod
def _commit_no_clobber(src_path, dest):
try:
os.link(src_path, dest)
except OSError as e:
if e.errno == errno.EEXIST:
raise FileExistsError(errno.EEXIST, 'File exists', str(dest)) from None
if e.errno not in (errno.EXDEV, errno.EPERM, errno.EACCES, errno.ENOTSUP, errno.EINVAL):
raise
dst_fd = os.open(dest, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
copied = False
try:
with os.fdopen(dst_fd, 'wb') as dst_out, open(src_path, 'rb') as src_in:
while True:
chunk = src_in.read(CHUNK_SIZE)
if not chunk:
break
dst_out.write(chunk)
dst_out.flush()
os.fsync(dst_out.fileno())
copied = True
finally:
if not copied and dest.exists():
dest.unlink()
def download(self, addr, local, *, limit=DEFAULT_DOWNLOAD_LIMIT, deadline_seconds=DEFAULT_DEADLINE, resume=False, clock=time.monotonic):
if limit <= 0 or deadline_seconds <= 0:
raise Failure('Download limit and deadline must be positive.')
dest = Path(local)
if dest.exists() or dest.is_symlink():
raise FileExistsError(errno.EEXIST, 'File exists', str(dest))
if not dest.parent.is_dir():
raise Failure('Destination directory does not exist.')
query = '' if self.lang == 'auto' else '?' + url.urlencode({'lang': self.lang})
route = '/v/raw/' + url.quote(addr, safe='/:') + query
if not resume:
tmp_path = dest.parent / ('.pages-get-' + secrets.token_hex(8) + '.tmp')
fd = os.open(tmp_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
hasher = hashlib.sha256()
total = [0]
try:
with os.fdopen(fd, 'wb') as out:
def write_chunk(chunk):
hasher.update(chunk)
out.write(chunk)
total[0] += len(chunk)
_, headers = self.stream_request(
route, method='GET', limit=limit, on_chunk=write_chunk,
deadline_seconds=deadline_seconds, clock=clock)
out.flush()
os.fsync(out.fileno())
digest = (headers.get('X-PagesWiki-Document-SHA256') or '').strip()
if not digest or hasher.hexdigest() != digest:
raise Failure('Document SHA-256 mismatch.')
self._commit_no_clobber(tmp_path, dest)
return headers, total[0]
finally:
if tmp_path.exists() or tmp_path.is_symlink():
tmp_path.unlink()
part_path = dest.parent / ('.' + dest.name + '.pages-part')
meta_path = dest.parent / ('.' + dest.name + '.pages-part.json')
offset = 0
saved_meta = None
if part_path.exists() or part_path.is_symlink() or meta_path.exists() or meta_path.is_symlink():
if not part_path.exists() or not meta_path.exists():
raise Failure('Invalid or insecure partial download state; remove partial files before retrying.')
private_file(part_path)
private_file(meta_path)
try:
saved_meta = json.loads(meta_path.read_text(encoding='utf-8'))
except (ValueError, UnicodeError) as e:
raise Failure('Corrupt partial download metadata; remove partial files before retrying.') from e
if (not isinstance(saved_meta, dict)
or saved_meta.get('origin') != self.base
or saved_meta.get('address') != addr
or saved_meta.get('lang') != self.lang
or not isinstance(saved_meta.get('expected_sha256'), str)
or not re.fullmatch(r'[0-9a-f]{64}', saved_meta['expected_sha256'])
or not isinstance(saved_meta.get('total_bytes'), int)
or isinstance(saved_meta.get('total_bytes'), bool)
or saved_meta['total_bytes'] <= 0
or not isinstance(saved_meta.get('etag', ''), str)):
raise Failure('Invalid or mismatched partial download metadata; remove partial files before retrying.')
if saved_meta['total_bytes'] > limit:
raise Failure('Response exceeds client limit; use the browser for large files.')
actual = part_path.stat().st_size
if actual < 0 or actual > saved_meta['total_bytes']:
raise Failure('Partial download size is inconsistent with metadata; remove partial files before retrying.')
offset = actual
else:
fd = os.open(part_path, os.O_RDWR | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
os.close(fd)
if saved_meta is not None and offset == saved_meta['total_bytes'] and offset > 0:
if self._hash_file(part_path) != saved_meta['expected_sha256']:
for p in (part_path, meta_path):
if p.exists():
p.unlink()
raise Failure('Document SHA-256 mismatch.')
self._commit_no_clobber(part_path, dest)
for p in (part_path, meta_path):
if p.exists():
p.unlink()
return {'X-PagesWiki-Revision-UUID': saved_meta.get('revision_uuid', 'unknown'),
'X-PagesWiki-Document-SHA256': saved_meta['expected_sha256']}, offset
req_headers = {}
if offset > 0:
req_headers['Range'] = f'bytes={offset}-'
if saved_meta.get('etag'):
req_headers['If-Range'] = saved_meta['etag']
private_file(part_path)
fd = os.open(part_path, os.O_RDWR | os.O_NOFOLLOW)
resumed_206 = [False]
current_meta = [dict(saved_meta) if saved_meta else None]
received = [offset]
hasher = [hashlib.sha256()]
drop_partial = [False]
headers = None
with os.fdopen(fd, 'r+b') as out:
def on_headers(status, resp_headers):
resp_sha = (resp_headers.get('X-PagesWiki-Document-SHA256') or '').strip()
resp_etag = (resp_headers.get('ETag') or '').strip()
resp_rev = (resp_headers.get('X-PagesWiki-Revision-UUID') or '').strip()
if status == 206:
if offset == 0 or saved_meta is None:
raise Failure('Unexpected 206 Partial Content without a range request.', 206)
cr = (resp_headers.get('Content-Range') or '').strip()
m_cr = re.fullmatch(r'bytes (\d+)-(\d+)/(\d+)', cr)
if not m_cr:
raise Failure('Resume target returned invalid Content-Range; remove partial files to restart.', 412)
start, end, total_len = int(m_cr.group(1)), int(m_cr.group(2)), int(m_cr.group(3))
if (start != offset or end < start or total_len != saved_meta['total_bytes']
or total_len > limit or resp_sha != saved_meta['expected_sha256']):
raise Failure('Resume target changed or Content-Range mismatched; remove partial files to restart.', 412)
out.seek(offset)
out.truncate(offset)
resumed_206[0] = True
elif status == 200:
cl_h = (resp_headers.get('Content-Length') or '').strip()
total_len = int(cl_h) if cl_h.isdigit() else None
out.seek(0)
out.truncate(0)
received[0] = 0
resumed_206[0] = False
hasher[0] = hashlib.sha256()
current_meta[0] = {
'origin': self.base, 'address': addr, 'lang': self.lang,
'revision_uuid': resp_rev, 'expected_sha256': resp_sha,
'etag': resp_etag, 'total_bytes': total_len, 'received_bytes': 0,
}
if total_len is not None and resp_sha and re.fullmatch(r'[0-9a-f]{64}', resp_sha):
self._write_private_json_atomic(meta_path, current_meta[0])
else:
raise Failure('Unexpected HTTP status (%d).' % status, status)
def write_chunk(chunk):
if received[0] + len(chunk) > limit:
drop_partial[0] = True
raise Failure('Response exceeds client limit; use the browser for large files.')
out.write(chunk)
if not resumed_206[0]:
hasher[0].update(chunk)
received[0] += len(chunk)
try:
_, headers = self.stream_request(
route, method='GET', headers=req_headers, limit=limit,
on_headers=on_headers, on_chunk=write_chunk,
deadline_seconds=deadline_seconds, clock=clock)
out.flush()
os.fsync(out.fileno())
except (Failure, KeyboardInterrupt):
meta = current_meta[0]
if (not drop_partial[0] and received[0] > 0 and meta
and meta.get('expected_sha256') and re.fullmatch(r'[0-9a-f]{64}', meta['expected_sha256'])
and isinstance(meta.get('total_bytes'), int) and meta['total_bytes'] > 0):
try:
out.flush()
os.fsync(out.fileno())
except OSError:
pass
meta['received_bytes'] = received[0]
self._write_private_json_atomic(meta_path, meta)
print('Partial download retained (%d/%d bytes). Re-run with --resume to continue.' % (received[0], meta['total_bytes']), file=sys.stderr)
else:
for p in (part_path, meta_path):
if p.exists() or p.is_symlink():
p.unlink()
raise
final_digest = self._hash_file(part_path) if resumed_206[0] else hasher[0].hexdigest()
digest = (headers.get('X-PagesWiki-Document-SHA256') or '').strip()
if not digest or final_digest != digest:
for p in (part_path, meta_path):
if p.exists() or p.is_symlink():
p.unlink()
raise Failure('Document SHA-256 mismatch.')
self._commit_no_clobber(part_path, dest)
for p in (part_path, meta_path):
if p.exists() or p.is_symlink():
p.unlink()
return headers, received[0]
def snapshot(self, addr, lang=None):
if addr.startswith('rev:'):
raise Failure('Revision addresses are immutable; edit a path: or uuid: address.')
@@ -1067,7 +1387,14 @@ def execute(client, profile, words):
if command == 'edit':
p.add_argument('--format', choices=['auto', 'raw', 'markdown'], default='auto')
p.add_argument('--lang', help='auto edits the visible language (or creates as und with warning); an explicit tag selects or creates a language revision')
elif command == 'cat':
p.add_argument('--stream', action='store_true', help='Stream chunks directly to stdout and verify SHA-256 at end (exits non-zero if corrupt)')
p.add_argument('--max-bytes', type=int, default=DEFAULT_DOWNLOAD_LIMIT, help='Maximum transfer size in bytes (default: 64 MiB)')
p.add_argument('--timeout', type=int, default=DEFAULT_DEADLINE, help='Total transfer deadline in seconds (default: 300)')
p = sub.add_parser('get'); p.add_argument('path'); p.add_argument('local')
p.add_argument('--resume', action='store_true', help='Retain partial download pieces on interruption and resume via HTTP Range/If-Range')
p.add_argument('--max-bytes', type=int, default=DEFAULT_DOWNLOAD_LIMIT, help='Maximum download size in bytes (default: 64 MiB)')
p.add_argument('--timeout', type=int, default=DEFAULT_DEADLINE, help='Total transfer deadline in seconds (default: 300)')
p = sub.add_parser('put'); p.add_argument('local'); p.add_argument('path'); p.add_argument('--base', required=True)
p.add_argument('--format', choices=['raw', 'markdown'], default='raw')
p = sub.add_parser('recover', help='List, resume, or discard retained local edit drafts')
@@ -1116,19 +1443,40 @@ def execute(client, profile, words):
editing = Client(client.base, client.token, language(args.lang), insecure=client.insecure) if args.lang else client
editor(editing, addr, args.format)
elif cmd == 'put':
local_path = Path(args.local)
if local_path.exists() and local_path.stat().st_size > 1 << 20:
raise Failure('Text edit exceeds the 1 MiB client limit.')
state = client.snapshot(addr)
if not state['head_revision_uuid']:
raise Failure('No revision in the target language; use edit --lang to create a language revision.')
if state['head_revision_uuid'] != args.base: raise Failure('Conflict: supplied base is not the current language head.', 409)
text = Path(args.local).read_text(encoding='utf-8')
text = local_path.read_text(encoding='utf-8')
print('Revision:', safe_text(client.save(state, text, args.format == 'markdown')['revision_uuid']))
elif cmd == 'get':
if args.max_bytes <= 0 or args.timeout <= 0:
raise Failure('Download limit and timeout must be positive.')
headers, _ = client.download(addr, args.local, limit=args.max_bytes, deadline_seconds=args.timeout, resume=args.resume)
print('Revision:', safe_text(headers.get('X-PagesWiki-Revision-UUID', 'unknown')))
elif cmd == 'cat' and args.stream:
if args.max_bytes <= 0 or args.timeout <= 0:
raise Failure('Download limit and timeout must be positive.')
def check_stream_headers(status, headers):
if sys.stdout.isatty() and not (headers.get_content_type().startswith('text/') or headers.get_content_type() in ('application/json', 'application/xml')):
raise Failure('Binary document: use get or open.')
def write_stream_chunk(chunk):
if sys.stdout.isatty():
sys.stdout.write(safe_text(chunk.decode('utf-8', errors='replace')))
sys.stdout.flush()
else:
sys.stdout.buffer.write(chunk)
sys.stdout.buffer.flush()
client.stream_raw(addr, write_stream_chunk, on_headers=check_stream_headers, limit=args.max_bytes, deadline_seconds=args.timeout)
else:
raw, headers = client.raw(addr)
if cmd == 'get':
fd = os.open(args.local, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, 'wb') as out: out.write(raw)
print('Revision:', safe_text(headers.get('X-PagesWiki-Revision-UUID', 'unknown')))
elif cmd == 'cat' and not sys.stdout.isatty():
raw_kwargs = {'limit': args.max_bytes, 'deadline_seconds': args.timeout} if cmd == 'cat' else {}
if cmd == 'cat' and (args.max_bytes <= 0 or args.timeout <= 0):
raise Failure('Download limit and timeout must be positive.')
raw, headers = client.raw(addr, **raw_kwargs)
if cmd == 'cat' and not sys.stdout.isatty():
sys.stdout.buffer.write(raw)
else:
if not (headers.get_content_type().startswith('text/') or headers.get_content_type() in ('application/json', 'application/xml')):