Download nyarion/cli.py from PureOne/NYARION-FS-8.0-Transactional-Storage-Engine: direct link, hf CLI and curl.
- Browser
- Download file 8.14 kB
-
https://huggingface.co/datasets/PureOne/NYARION-FS-8.0-Transactional-Storage-Engine/resolve/main/nyarion/cli.py
- Command line
-
hf download hf://datasets/PureOne/NYARION-FS-8.0-Transactional-Storage-Engine/nyarion/cli.py
-
curl -L -o cli.py https://huggingface.co/datasets/PureOne/NYARION-FS-8.0-Transactional-Storage-Engine/resolve/main/nyarion/cli.py
8.14 kB
| """Command-line access to NYARION's POSIX regular-file image engine.""" | |
| from __future__ import annotations | |
| import argparse | |
| import base64 | |
| import hashlib | |
| import json | |
| import os | |
| from pathlib import Path | |
| import sys | |
| import pagefs | |
| from . import __version__ | |
| INPUT_LIMIT = 1024 * 1024 | |
| def _json(value): | |
| print(json.dumps(value, sort_keys=True, ensure_ascii=True, indent=2)) | |
| def _read(path, limit=INPUT_LIMIT): | |
| if path == '-': | |
| data = sys.stdin.buffer.read(limit + 1) | |
| else: | |
| with open(path, 'rb') as stream: | |
| data = stream.read(limit + 1) | |
| if len(data) > limit: | |
| raise ValueError(f'input exceeds {limit} byte command limit') | |
| return data | |
| def _write(path, data): | |
| """Exclusive creation keeps output paths from replacing an image or input.""" | |
| if path == '-': | |
| sys.stdout.buffer.write(data) | |
| sys.stdout.buffer.flush() | |
| return | |
| descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_NOFOLLOW', 0), 0o600) | |
| with os.fdopen(descriptor, 'wb') as stream: | |
| stream.write(data) | |
| stream.flush() | |
| os.fsync(stream.fileno()) | |
| def _pairs(items): | |
| obj = {} | |
| for key, value in items: | |
| if key in obj: | |
| raise ValueError(f'duplicate JSON key: {key!r}') | |
| obj[key] = value | |
| return obj | |
| def _transaction(path): | |
| try: | |
| obj = json.loads(_read(path).decode('utf8'), object_pairs_hook=_pairs, | |
| parse_constant=lambda value: (_ for _ in ()).throw(ValueError('invalid JSON constant'))) | |
| except (UnicodeError, RecursionError) as exc: | |
| raise ValueError('transaction must be bounded UTF-8 JSON') from exc | |
| if not isinstance(obj, dict) or set(obj) != {'token', 'changes'}: | |
| raise ValueError('transaction fields must be exactly token and changes') | |
| pagefs.token_key(obj['token']) | |
| changes = obj['changes'] | |
| if not isinstance(changes, dict) or not changes: | |
| raise ValueError('transaction changes must be a nonempty map') | |
| decoded = {} | |
| for key, entry in changes.items(): | |
| pagefs.path_key(key) | |
| if entry is None: | |
| decoded[key] = None | |
| elif isinstance(entry, dict) and set(entry) == {'base64'}: | |
| decoded[key] = pagefs.unb64(entry['base64']) | |
| else: | |
| raise ValueError('each change must be null or an object containing only base64') | |
| return decoded, obj['token'] | |
| def _snapshot(store): | |
| files = [] | |
| for path in store.files(): | |
| data = store.get(path) | |
| files.append({'path': path, 'base64': base64.b64encode(data).decode('ascii'), | |
| 'length': len(data), 'sha256': hashlib.sha256(data).hexdigest()}) | |
| # Receipt enumeration is a release-local export interface. Each value is | |
| # retrieved through the public query function after recovery validation. | |
| receipts = [{'token': token, **store.query(token)} for token in sorted(store._tokens)] | |
| body = {'export_format': 1, 'engine_format': pagefs.FORMAT, 'volume': store.volume, | |
| 'epoch': store.epoch, 'files': files, 'receipts': receipts} | |
| body['snapshot_sha256'] = hashlib.sha256(pagefs.canonical(body)).hexdigest() | |
| return body | |
| def parser(): | |
| result = argparse.ArgumentParser( | |
| prog='nyarion', | |
| description='NYARION regular-file storage engine. Requires Python 3 and POSIX; this is not a mounted filesystem.') | |
| result.add_argument('--version', action='version', version='NYARION ' + __version__) | |
| commands = result.add_subparsers(dest='command', required=True) | |
| init = commands.add_parser('init', help='exclusively create an empty image') | |
| init.add_argument('image') | |
| init.add_argument('--pool-blocks', type=int, default=pagefs.DEFAULT_POOL_BLOCKS, | |
| help='number of 4 KiB physical arena blocks, including replicas') | |
| put = commands.add_parser('put', help='durably replace one complete logical file value') | |
| put.add_argument('image'); put.add_argument('key'); put.add_argument('--token', required=True) | |
| data = put.add_mutually_exclusive_group(required=True) | |
| data.add_argument('--file', metavar='PATH', help='input bytes; - reads stdin') | |
| data.add_argument('--text', help='UTF-8 text value') | |
| get = commands.add_parser('get', help='read a logical value as raw bytes') | |
| get.add_argument('image'); get.add_argument('key') | |
| get.add_argument('--output', default='-', help='new output file; default is stdout') | |
| ls = commands.add_parser('ls', aliases=['list'], help='list logical keys as JSON') | |
| ls.add_argument('image') | |
| delete = commands.add_parser('delete', help='durably remove one logical key') | |
| delete.add_argument('image'); delete.add_argument('key'); delete.add_argument('--token', required=True) | |
| tx = commands.add_parser('transact', help='apply one atomic JSON transaction') | |
| tx.add_argument('image'); tx.add_argument('transaction', help='UTF-8 JSON path, or - for stdin') | |
| for command, help_text in ( | |
| ('checkpoint', 'materialize and publish the complete outstanding prefix'), | |
| ('inspect', 'inspect recovered metadata without repairing'), | |
| ('plan', 'show an exact checkpoint publication summary without writing'), | |
| ('verify', 'validate recovery and report a logical snapshot digest without repairing'), | |
| ('repair', 'open writable, restore available mirror redundancy, and inspect'), | |
| ): | |
| cmd = commands.add_parser(command, help=help_text); cmd.add_argument('image') | |
| query = commands.add_parser('query', help='query a durable retry receipt') | |
| query.add_argument('image'); query.add_argument('token') | |
| export = commands.add_parser('export', help='export bytes and receipt metadata as audit JSON') | |
| export.add_argument('image'); export.add_argument('--output', default='-', help='new output file; default is stdout') | |
| return result | |
| def main(argv=None): | |
| args = parser().parse_args(argv) | |
| try: | |
| command = args.command | |
| if command == 'init': | |
| with pagefs.PageStore.create(args.image, pool_blocks=args.pool_blocks) as store: | |
| _json(store.inspect()) | |
| return 0 | |
| if command == 'put': | |
| value = args.text.encode('utf8') if args.text is not None else _read(args.file) | |
| changes, token = {args.key: value}, args.token | |
| elif command == 'delete': | |
| changes, token = {args.key: None}, args.token | |
| elif command == 'transact': | |
| changes, token = _transaction(args.transaction) | |
| writable = command in ('put', 'delete', 'transact', 'checkpoint', 'repair') | |
| with pagefs.PageStore(args.image, writable=writable) as store: | |
| if command in ('put', 'delete', 'transact'): | |
| epoch = store.transact(changes, token) | |
| _json({'epoch': epoch, 'receipt': store.query(token)}) | |
| elif command == 'get': | |
| _write(args.output, store.get(args.key)) | |
| elif command in ('ls', 'list'): | |
| _json(store.files()) | |
| elif command == 'checkpoint': | |
| _json({'checkpoint_epoch': store.checkpoint(), 'state': store.inspect()}) | |
| elif command in ('inspect', 'repair'): | |
| _json(store.inspect()) | |
| elif command == 'plan': | |
| _json(store.checkpoint_plan()) | |
| elif command == 'query': | |
| _json(store.query(args.token)) | |
| elif command in ('verify', 'export'): | |
| snapshot = _snapshot(store) | |
| if command == 'export': | |
| _write(args.output, (json.dumps(snapshot, sort_keys=True, ensure_ascii=True, indent=2) + '\n').encode('ascii')) | |
| else: | |
| _json({'valid': True, 'epoch': store.epoch, 'files': len(snapshot['files']), | |
| 'receipts': len(snapshot['receipts']), 'snapshot_sha256': snapshot['snapshot_sha256']}) | |
| return 0 | |
| except (pagefs.StoreError, OSError, ValueError, TypeError) as exc: | |
| print('nyarion: ' + str(exc), file=sys.stderr) | |
| return 2 | |
| if __name__ == '__main__': | |
| raise SystemExit(main()) | |