rida-format 0.1.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.
- rida/__init__.py +870 -0
- rida/__main__.py +7 -0
- rida_format-0.1.0.dist-info/METADATA +218 -0
- rida_format-0.1.0.dist-info/RECORD +8 -0
- rida_format-0.1.0.dist-info/WHEEL +5 -0
- rida_format-0.1.0.dist-info/entry_points.txt +2 -0
- rida_format-0.1.0.dist-info/licenses/LICENSE +43 -0
- rida_format-0.1.0.dist-info/top_level.txt +1 -0
rida/__init__.py
ADDED
|
@@ -0,0 +1,870 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""RIDA 0.1 builder and reader library.
|
|
3
|
+
|
|
4
|
+
RIDA is a read-first, single-file format for a collection of JSON records.
|
|
5
|
+
The file contains UTF-8 JSON values plus a compact address catalog, so a local
|
|
6
|
+
or HTTP-range reader can retrieve one record field without reading all data.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import hashlib
|
|
13
|
+
import json
|
|
14
|
+
import lzma
|
|
15
|
+
import os
|
|
16
|
+
import struct
|
|
17
|
+
import sys
|
|
18
|
+
import tempfile
|
|
19
|
+
import urllib.error
|
|
20
|
+
import urllib.request
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any, BinaryIO, Callable
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
RIDA_MAGIC = b"RIDA0001"
|
|
27
|
+
RIDA_VERSION = 1
|
|
28
|
+
__version__ = "0.1.0"
|
|
29
|
+
# magic, version, header size, metadata length, catalog length, raw catalog
|
|
30
|
+
# length, data offset, data length, record count, catalog hash, data hash.
|
|
31
|
+
HEADER = struct.Struct(">8sIIIIQQQQ32s32s8x")
|
|
32
|
+
CATALOG_MAGIC = b"RDACAT01"
|
|
33
|
+
CATALOG_VERSION = 1
|
|
34
|
+
CATALOG_HEADER = struct.Struct(">8sIIQIIIQ")
|
|
35
|
+
MODE_DENSE = 1
|
|
36
|
+
MODE_SPARSE = 2
|
|
37
|
+
ProgressCallback = Callable[[str, int, int], None]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class RidaError(Exception):
|
|
41
|
+
"""Raised for an invalid RIDA file or unsupported source data."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
__all__ = [
|
|
45
|
+
"BuildPlan",
|
|
46
|
+
"BuildResult",
|
|
47
|
+
"Catalog",
|
|
48
|
+
"RidaError",
|
|
49
|
+
"RidaFile",
|
|
50
|
+
"RemoteRidaFile",
|
|
51
|
+
"__version__",
|
|
52
|
+
"build",
|
|
53
|
+
"build_rida",
|
|
54
|
+
"inspect_metadata",
|
|
55
|
+
"load_records",
|
|
56
|
+
"scan",
|
|
57
|
+
"scan_records",
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _compact_json(value: Any) -> bytes:
|
|
62
|
+
return json.dumps(value, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode("utf-8")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _encode_varint(value: int) -> bytes:
|
|
66
|
+
if value < 0:
|
|
67
|
+
raise RidaError("Cannot encode a negative RIDA value")
|
|
68
|
+
encoded = bytearray()
|
|
69
|
+
while value >= 0x80:
|
|
70
|
+
encoded.append((value & 0x7F) | 0x80)
|
|
71
|
+
value >>= 7
|
|
72
|
+
encoded.append(value)
|
|
73
|
+
return bytes(encoded)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _decode_varint(data: memoryview, position: int) -> tuple[int, int]:
|
|
77
|
+
value = 0
|
|
78
|
+
shift = 0
|
|
79
|
+
while position < len(data) and shift < 70:
|
|
80
|
+
byte = data[position]
|
|
81
|
+
position += 1
|
|
82
|
+
value |= (byte & 0x7F) << shift
|
|
83
|
+
if byte < 0x80:
|
|
84
|
+
return value, position
|
|
85
|
+
shift += 7
|
|
86
|
+
raise RidaError("Invalid variable-length value in RIDA catalog")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _varint_length(value: int) -> int:
|
|
90
|
+
return len(_encode_varint(value))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _report_progress(
|
|
94
|
+
progress: ProgressCallback | None, stage: str, completed: int, total: int
|
|
95
|
+
) -> None:
|
|
96
|
+
"""Report at most roughly 100 updates for a long stage.
|
|
97
|
+
|
|
98
|
+
The core has no opinion about a user interface. A desktop app can pass its
|
|
99
|
+
own callback; the CLI passes a small terminal renderer below.
|
|
100
|
+
"""
|
|
101
|
+
if progress is None:
|
|
102
|
+
return
|
|
103
|
+
interval = max(1, total // 100) if total else 1
|
|
104
|
+
if completed in (0, total) or completed % interval == 0:
|
|
105
|
+
progress(stage, completed, total)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _ordered_json_files(directory: Path) -> list[Path]:
|
|
109
|
+
files = list(directory.glob("*.json"))
|
|
110
|
+
if not files:
|
|
111
|
+
raise RidaError(f"No JSON files found in {directory}")
|
|
112
|
+
|
|
113
|
+
def order(path: Path) -> tuple[int, int | str, str]:
|
|
114
|
+
if path.stem.isdecimal():
|
|
115
|
+
return 0, int(path.stem), path.name.casefold()
|
|
116
|
+
return 1, path.stem.casefold(), path.name.casefold()
|
|
117
|
+
|
|
118
|
+
return sorted(files, key=order)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _load_json_file(path: Path, progress: ProgressCallback | None = None) -> Any:
|
|
122
|
+
"""Read one JSON file while reporting byte progress, then parse it."""
|
|
123
|
+
total_bytes = path.stat().st_size
|
|
124
|
+
loaded = bytearray()
|
|
125
|
+
_report_progress(progress, "Reading JSON bytes", 0, total_bytes)
|
|
126
|
+
with path.open("rb") as source:
|
|
127
|
+
while block := source.read(1024 * 1024):
|
|
128
|
+
loaded.extend(block)
|
|
129
|
+
_report_progress(progress, "Reading JSON bytes", len(loaded), total_bytes)
|
|
130
|
+
_report_progress(progress, "Parsing JSON", 0, 1)
|
|
131
|
+
value = json.loads(loaded)
|
|
132
|
+
_report_progress(progress, "Parsing JSON", 1, 1)
|
|
133
|
+
return value
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def load_records(
|
|
137
|
+
source: Path,
|
|
138
|
+
id_key: str | None = None,
|
|
139
|
+
progress: ProgressCallback | None = None,
|
|
140
|
+
) -> list[tuple[str, dict[str, Any]]]:
|
|
141
|
+
"""Load a mapping, an array with an ID field, or a folder of JSON records."""
|
|
142
|
+
records: list[tuple[str, dict[str, Any]]] = []
|
|
143
|
+
if source.is_dir():
|
|
144
|
+
paths = _ordered_json_files(source)
|
|
145
|
+
_report_progress(progress, "Loading JSON records", 0, len(paths))
|
|
146
|
+
for position, path in enumerate(paths, start=1):
|
|
147
|
+
value = json.loads(path.read_bytes())
|
|
148
|
+
if not isinstance(value, dict):
|
|
149
|
+
raise RidaError(f"Record file must contain a JSON object: {path}")
|
|
150
|
+
records.append((path.stem, value))
|
|
151
|
+
_report_progress(progress, "Loading JSON records", position, len(paths))
|
|
152
|
+
elif source.is_file():
|
|
153
|
+
value = _load_json_file(source, progress)
|
|
154
|
+
if isinstance(value, list):
|
|
155
|
+
if not id_key:
|
|
156
|
+
raise RidaError("A JSON array needs --id-key so RIDA can identify every record")
|
|
157
|
+
for position, record in enumerate(value, start=1):
|
|
158
|
+
if not isinstance(record, dict):
|
|
159
|
+
raise RidaError(f"Array item {position} is not a JSON object")
|
|
160
|
+
if id_key not in record or record[id_key] is None:
|
|
161
|
+
raise RidaError(f"Array item {position} has no usable {id_key!r} ID")
|
|
162
|
+
records.append((str(record[id_key]), record))
|
|
163
|
+
elif isinstance(value, dict):
|
|
164
|
+
for record_id, record in value.items():
|
|
165
|
+
if not isinstance(record, dict):
|
|
166
|
+
raise RidaError(
|
|
167
|
+
"A JSON object source must map record IDs to record objects; "
|
|
168
|
+
"use an array plus --id-key for another shape"
|
|
169
|
+
)
|
|
170
|
+
records.append((str(record_id), record))
|
|
171
|
+
else:
|
|
172
|
+
raise RidaError("RIDA source must be a JSON object, JSON array, or folder of JSON record files")
|
|
173
|
+
else:
|
|
174
|
+
raise RidaError(f"Source does not exist: {source}")
|
|
175
|
+
|
|
176
|
+
if not records:
|
|
177
|
+
raise RidaError("RIDA needs at least one record")
|
|
178
|
+
ids = [record_id for record_id, _ in records]
|
|
179
|
+
if len(set(ids)) != len(ids):
|
|
180
|
+
raise RidaError("Record IDs must be unique")
|
|
181
|
+
return records
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _is_sequential_numeric(ids: list[str]) -> bool:
|
|
185
|
+
return ids == [str(number) for number in range(1, len(ids) + 1)]
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
@dataclass(frozen=True)
|
|
189
|
+
class BuildPlan:
|
|
190
|
+
fields: list[str]
|
|
191
|
+
value_lengths: list[dict[str, int]]
|
|
192
|
+
sequential_numeric_ids: bool
|
|
193
|
+
total_present_fields: int
|
|
194
|
+
dense_raw_estimate: int
|
|
195
|
+
sparse_raw_estimate: int
|
|
196
|
+
recommended_mode: str
|
|
197
|
+
|
|
198
|
+
@property
|
|
199
|
+
def field_density(self) -> float:
|
|
200
|
+
if not self.fields or not self.value_lengths:
|
|
201
|
+
return 0.0
|
|
202
|
+
return self.total_present_fields / (len(self.fields) * len(self.value_lengths))
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def scan_records(
|
|
206
|
+
records: list[tuple[str, dict[str, Any]]], progress: ProgressCallback | None = None
|
|
207
|
+
) -> BuildPlan:
|
|
208
|
+
fields: list[str] = []
|
|
209
|
+
total_records = len(records)
|
|
210
|
+
_report_progress(progress, "Scanning field names", 0, total_records)
|
|
211
|
+
for position, (_, record) in enumerate(records, start=1):
|
|
212
|
+
for field in record:
|
|
213
|
+
if field not in fields:
|
|
214
|
+
fields.append(field)
|
|
215
|
+
_report_progress(progress, "Scanning field names", position, total_records)
|
|
216
|
+
if not fields:
|
|
217
|
+
raise RidaError("RIDA records must contain at least one field")
|
|
218
|
+
|
|
219
|
+
field_ids = {field: position for position, field in enumerate(fields)}
|
|
220
|
+
value_lengths: list[dict[str, int]] = []
|
|
221
|
+
total_present = 0
|
|
222
|
+
data_position = 0
|
|
223
|
+
dense_rows = 0
|
|
224
|
+
sparse_rows = 0
|
|
225
|
+
_report_progress(progress, "Measuring values", 0, total_records)
|
|
226
|
+
for position, (_, record) in enumerate(records, start=1):
|
|
227
|
+
lengths = {field: len(_compact_json(value)) for field, value in record.items()}
|
|
228
|
+
value_lengths.append(lengths)
|
|
229
|
+
total_present += len(lengths)
|
|
230
|
+
dense_rows += _varint_length(data_position)
|
|
231
|
+
sparse_rows += _varint_length(data_position) + _varint_length(len(lengths))
|
|
232
|
+
last_field_id = 0
|
|
233
|
+
for field in fields:
|
|
234
|
+
length = lengths.get(field, 0)
|
|
235
|
+
dense_rows += _varint_length(length)
|
|
236
|
+
if length:
|
|
237
|
+
field_id = field_ids[field]
|
|
238
|
+
sparse_rows += _varint_length(field_id - last_field_id) + _varint_length(length)
|
|
239
|
+
last_field_id = field_id
|
|
240
|
+
data_position += length
|
|
241
|
+
_report_progress(progress, "Measuring values", position, total_records)
|
|
242
|
+
|
|
243
|
+
schema_size = len(_compact_json(fields))
|
|
244
|
+
ids = [record_id for record_id, _ in records]
|
|
245
|
+
ids_size = 0 if _is_sequential_numeric(ids) else len(_compact_json(ids))
|
|
246
|
+
common = CATALOG_HEADER.size + schema_size + ids_size + (len(records) + 1) * 8
|
|
247
|
+
dense_estimate = common + dense_rows
|
|
248
|
+
sparse_estimate = common + sparse_rows
|
|
249
|
+
return BuildPlan(
|
|
250
|
+
fields=fields,
|
|
251
|
+
value_lengths=value_lengths,
|
|
252
|
+
sequential_numeric_ids=ids_size == 0,
|
|
253
|
+
total_present_fields=total_present,
|
|
254
|
+
dense_raw_estimate=dense_estimate,
|
|
255
|
+
sparse_raw_estimate=sparse_estimate,
|
|
256
|
+
recommended_mode="dense" if dense_estimate <= sparse_estimate else "sparse",
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def scan(
|
|
261
|
+
source: str | Path,
|
|
262
|
+
id_key: str | None = None,
|
|
263
|
+
progress: ProgressCallback | None = None,
|
|
264
|
+
) -> BuildPlan:
|
|
265
|
+
"""Scan JSON input and return its RIDA layout recommendation.
|
|
266
|
+
|
|
267
|
+
``source`` may be a JSON mapping, a JSON array together with ``id_key``,
|
|
268
|
+
or a directory containing one JSON record per file.
|
|
269
|
+
"""
|
|
270
|
+
return scan_records(load_records(Path(source), id_key, progress), progress)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def print_scan(records: list[tuple[str, dict[str, Any]]], plan: BuildPlan) -> None:
|
|
274
|
+
record_count = len(records)
|
|
275
|
+
print(f"Records: {record_count:,}")
|
|
276
|
+
print(f"Unique record IDs: {record_count:,}")
|
|
277
|
+
print(f"Unique fields: {len(plan.fields):,}")
|
|
278
|
+
print(f"Average fields per record: {plan.total_present_fields / record_count:.2f}")
|
|
279
|
+
print(f"Field density: {plan.field_density * 100:.2f}%")
|
|
280
|
+
print(f"Estimated dense catalog before compression: {plan.dense_raw_estimate:,} bytes")
|
|
281
|
+
print(f"Estimated sparse catalog before compression: {plan.sparse_raw_estimate:,} bytes")
|
|
282
|
+
print(f"Recommended mode: {plan.recommended_mode}")
|
|
283
|
+
print(f"Record IDs: {'sequential numeric' if plan.sequential_numeric_ids else 'dictionary'}")
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
@dataclass(frozen=True)
|
|
287
|
+
class Header:
|
|
288
|
+
metadata_length: int
|
|
289
|
+
catalog_length: int
|
|
290
|
+
raw_catalog_length: int
|
|
291
|
+
data_offset: int
|
|
292
|
+
data_length: int
|
|
293
|
+
record_count: int
|
|
294
|
+
catalog_digest: bytes
|
|
295
|
+
data_digest: bytes
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _parse_header(raw: bytes) -> Header:
|
|
299
|
+
if len(raw) != HEADER.size:
|
|
300
|
+
raise RidaError("RIDA header is incomplete")
|
|
301
|
+
(
|
|
302
|
+
magic,
|
|
303
|
+
version,
|
|
304
|
+
header_size,
|
|
305
|
+
metadata_length,
|
|
306
|
+
catalog_length,
|
|
307
|
+
raw_catalog_length,
|
|
308
|
+
data_offset,
|
|
309
|
+
data_length,
|
|
310
|
+
record_count,
|
|
311
|
+
catalog_digest,
|
|
312
|
+
data_digest,
|
|
313
|
+
) = HEADER.unpack(raw)
|
|
314
|
+
if magic != RIDA_MAGIC or version != RIDA_VERSION or header_size != HEADER.size:
|
|
315
|
+
raise RidaError("Unsupported or invalid RIDA file")
|
|
316
|
+
expected_data_offset = HEADER.size + metadata_length + catalog_length
|
|
317
|
+
if data_offset != expected_data_offset:
|
|
318
|
+
raise RidaError("RIDA data offset is invalid")
|
|
319
|
+
return Header(
|
|
320
|
+
metadata_length=metadata_length,
|
|
321
|
+
catalog_length=catalog_length,
|
|
322
|
+
raw_catalog_length=raw_catalog_length,
|
|
323
|
+
data_offset=data_offset,
|
|
324
|
+
data_length=data_length,
|
|
325
|
+
record_count=record_count,
|
|
326
|
+
catalog_digest=catalog_digest,
|
|
327
|
+
data_digest=data_digest,
|
|
328
|
+
)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
class Catalog:
|
|
332
|
+
"""Decompressed RIDA catalog with record and field location lookups."""
|
|
333
|
+
|
|
334
|
+
def __init__(self, header: Header, compressed_catalog: bytes):
|
|
335
|
+
if len(compressed_catalog) != header.catalog_length:
|
|
336
|
+
raise RidaError("RIDA catalog is incomplete")
|
|
337
|
+
if hashlib.sha256(compressed_catalog).digest() != header.catalog_digest:
|
|
338
|
+
raise RidaError("RIDA catalog checksum does not match")
|
|
339
|
+
try:
|
|
340
|
+
raw = lzma.decompress(compressed_catalog)
|
|
341
|
+
except lzma.LZMAError as exc:
|
|
342
|
+
raise RidaError("RIDA catalog cannot be decompressed") from exc
|
|
343
|
+
if len(raw) != header.raw_catalog_length:
|
|
344
|
+
raise RidaError("RIDA catalog length does not match its header")
|
|
345
|
+
self.raw = raw
|
|
346
|
+
(
|
|
347
|
+
magic,
|
|
348
|
+
version,
|
|
349
|
+
mode_code,
|
|
350
|
+
record_count,
|
|
351
|
+
field_count,
|
|
352
|
+
schema_length,
|
|
353
|
+
ids_length,
|
|
354
|
+
row_data_length,
|
|
355
|
+
) = CATALOG_HEADER.unpack_from(raw)
|
|
356
|
+
if magic != CATALOG_MAGIC or version != CATALOG_VERSION:
|
|
357
|
+
raise RidaError("Unsupported RIDA catalog version")
|
|
358
|
+
if record_count != header.record_count:
|
|
359
|
+
raise RidaError("RIDA record count does not match its catalog")
|
|
360
|
+
if mode_code not in (MODE_DENSE, MODE_SPARSE):
|
|
361
|
+
raise RidaError("RIDA catalog has an invalid index mode")
|
|
362
|
+
expected_length = (
|
|
363
|
+
CATALOG_HEADER.size
|
|
364
|
+
+ schema_length
|
|
365
|
+
+ ids_length
|
|
366
|
+
+ (record_count + 1) * 8
|
|
367
|
+
+ row_data_length
|
|
368
|
+
)
|
|
369
|
+
if len(raw) != expected_length:
|
|
370
|
+
raise RidaError("RIDA catalog layout is invalid")
|
|
371
|
+
schema_start = CATALOG_HEADER.size
|
|
372
|
+
schema_end = schema_start + schema_length
|
|
373
|
+
ids_end = schema_end + ids_length
|
|
374
|
+
self.fields = json.loads(raw[schema_start:schema_end])
|
|
375
|
+
if not isinstance(self.fields, list) or len(self.fields) != field_count:
|
|
376
|
+
raise RidaError("RIDA field dictionary is invalid")
|
|
377
|
+
if any(not isinstance(field, str) for field in self.fields) or len(set(self.fields)) != len(self.fields):
|
|
378
|
+
raise RidaError("RIDA field dictionary contains invalid names")
|
|
379
|
+
self.field_ids = {field: position for position, field in enumerate(self.fields)}
|
|
380
|
+
self.ids = [] if ids_length == 0 else json.loads(raw[schema_end:ids_end])
|
|
381
|
+
if self.ids:
|
|
382
|
+
if not isinstance(self.ids, list) or len(self.ids) != record_count:
|
|
383
|
+
raise RidaError("RIDA record-ID dictionary is invalid")
|
|
384
|
+
if any(not isinstance(record_id, str) for record_id in self.ids) or len(set(self.ids)) != len(self.ids):
|
|
385
|
+
raise RidaError("RIDA record-ID dictionary contains invalid IDs")
|
|
386
|
+
self.id_to_record = {record_id: position for position, record_id in enumerate(self.ids)}
|
|
387
|
+
else:
|
|
388
|
+
self.id_to_record = None
|
|
389
|
+
self.record_count = record_count
|
|
390
|
+
self.mode = "dense" if mode_code == MODE_DENSE else "sparse"
|
|
391
|
+
self.row_offsets_start = ids_end
|
|
392
|
+
self.row_data_start = ids_end + (record_count + 1) * 8
|
|
393
|
+
self.row_data_length = row_data_length
|
|
394
|
+
first = struct.unpack_from(">Q", raw, self.row_offsets_start)[0]
|
|
395
|
+
last = struct.unpack_from(">Q", raw, self.row_offsets_start + record_count * 8)[0]
|
|
396
|
+
if first != 0 or last != row_data_length:
|
|
397
|
+
raise RidaError("RIDA row offsets are invalid")
|
|
398
|
+
previous = first
|
|
399
|
+
for number in range(1, record_count + 1):
|
|
400
|
+
current = struct.unpack_from(">Q", raw, self.row_offsets_start + number * 8)[0]
|
|
401
|
+
if current < previous:
|
|
402
|
+
raise RidaError("RIDA row offsets are not ordered")
|
|
403
|
+
previous = current
|
|
404
|
+
|
|
405
|
+
def _record_number(self, record_id: str | int) -> int:
|
|
406
|
+
normalized = str(record_id)
|
|
407
|
+
if self.id_to_record is not None:
|
|
408
|
+
try:
|
|
409
|
+
return self.id_to_record[normalized]
|
|
410
|
+
except KeyError as exc:
|
|
411
|
+
raise KeyError(normalized) from exc
|
|
412
|
+
try:
|
|
413
|
+
number = int(normalized)
|
|
414
|
+
except ValueError as exc:
|
|
415
|
+
raise KeyError(normalized) from exc
|
|
416
|
+
if number < 1 or number > self.record_count or str(number) != normalized:
|
|
417
|
+
raise KeyError(normalized)
|
|
418
|
+
return number - 1
|
|
419
|
+
|
|
420
|
+
def pointer(self, record_id: str | int, field: str) -> tuple[int, int]:
|
|
421
|
+
record_number = self._record_number(record_id)
|
|
422
|
+
try:
|
|
423
|
+
wanted_field = self.field_ids[field]
|
|
424
|
+
except KeyError as exc:
|
|
425
|
+
raise KeyError(f"{record_id}.{field}") from exc
|
|
426
|
+
row_start = struct.unpack_from(">Q", self.raw, self.row_offsets_start + record_number * 8)[0]
|
|
427
|
+
row_end = struct.unpack_from(">Q", self.raw, self.row_offsets_start + (record_number + 1) * 8)[0]
|
|
428
|
+
row = memoryview(self.raw)[self.row_data_start + row_start:self.row_data_start + row_end]
|
|
429
|
+
data_start, position = _decode_varint(row, 0)
|
|
430
|
+
if self.mode == "dense":
|
|
431
|
+
value_offset = data_start
|
|
432
|
+
for field_number in range(len(self.fields)):
|
|
433
|
+
length, position = _decode_varint(row, position)
|
|
434
|
+
if field_number == wanted_field:
|
|
435
|
+
if length == 0:
|
|
436
|
+
raise KeyError(f"{record_id}.{field}")
|
|
437
|
+
return value_offset, length
|
|
438
|
+
value_offset += length
|
|
439
|
+
raise RidaError("RIDA dense row is shorter than its schema")
|
|
440
|
+
|
|
441
|
+
present_count, position = _decode_varint(row, position)
|
|
442
|
+
value_offset = data_start
|
|
443
|
+
previous_field = 0
|
|
444
|
+
for position_in_record in range(present_count):
|
|
445
|
+
delta, position = _decode_varint(row, position)
|
|
446
|
+
field_number = previous_field + delta
|
|
447
|
+
length, position = _decode_varint(row, position)
|
|
448
|
+
if position_in_record and delta == 0:
|
|
449
|
+
raise RidaError("RIDA sparse row repeats a field ID")
|
|
450
|
+
if field_number >= len(self.fields) or length == 0:
|
|
451
|
+
raise RidaError("RIDA sparse row is invalid")
|
|
452
|
+
if field_number == wanted_field:
|
|
453
|
+
return value_offset, length
|
|
454
|
+
if field_number > wanted_field:
|
|
455
|
+
break
|
|
456
|
+
value_offset += length
|
|
457
|
+
previous_field = field_number
|
|
458
|
+
raise KeyError(f"{record_id}.{field}")
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
@dataclass(frozen=True)
|
|
462
|
+
class BuildResult:
|
|
463
|
+
mode: str
|
|
464
|
+
records: int
|
|
465
|
+
fields: int
|
|
466
|
+
metadata_bytes: int
|
|
467
|
+
catalog_bytes: int
|
|
468
|
+
raw_catalog_bytes: int
|
|
469
|
+
data_bytes: int
|
|
470
|
+
output_bytes: int
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def build_rida(
|
|
474
|
+
records: list[tuple[str, dict[str, Any]]],
|
|
475
|
+
plan: BuildPlan,
|
|
476
|
+
output: Path,
|
|
477
|
+
mode: str,
|
|
478
|
+
title: str | None,
|
|
479
|
+
description: str | None,
|
|
480
|
+
reader_url: str | None,
|
|
481
|
+
compression: int,
|
|
482
|
+
progress: ProgressCallback | None = None,
|
|
483
|
+
) -> BuildResult:
|
|
484
|
+
if mode not in ("dense", "sparse"):
|
|
485
|
+
raise RidaError(f"Unsupported RIDA mode: {mode}")
|
|
486
|
+
output = output.resolve()
|
|
487
|
+
if output.exists():
|
|
488
|
+
raise RidaError(f"Output already exists: {output}. Choose a new path before building.")
|
|
489
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
490
|
+
fields = plan.fields
|
|
491
|
+
field_ids = {field: position for position, field in enumerate(fields)}
|
|
492
|
+
ids = [record_id for record_id, _ in records]
|
|
493
|
+
mode_code = MODE_DENSE if mode == "dense" else MODE_SPARSE
|
|
494
|
+
rows = bytearray()
|
|
495
|
+
row_offsets = [0]
|
|
496
|
+
data_length = 0
|
|
497
|
+
data_digest = hashlib.sha256()
|
|
498
|
+
data_temp_path: Path | None = None
|
|
499
|
+
output_temp_path: Path | None = None
|
|
500
|
+
try:
|
|
501
|
+
with tempfile.NamedTemporaryFile(
|
|
502
|
+
mode="w+b", prefix=".rida-data-", suffix=".tmp", dir=output.parent, delete=False
|
|
503
|
+
) as data_file:
|
|
504
|
+
data_temp_path = Path(data_file.name)
|
|
505
|
+
_report_progress(progress, "Writing value data", 0, len(records))
|
|
506
|
+
for record_number, (_, record) in enumerate(records, start=1):
|
|
507
|
+
rows.extend(_encode_varint(data_length))
|
|
508
|
+
if mode == "dense":
|
|
509
|
+
for field in fields:
|
|
510
|
+
if field not in record:
|
|
511
|
+
rows.extend(_encode_varint(0))
|
|
512
|
+
continue
|
|
513
|
+
value = _compact_json(record[field])
|
|
514
|
+
rows.extend(_encode_varint(len(value)))
|
|
515
|
+
data_file.write(value)
|
|
516
|
+
data_digest.update(value)
|
|
517
|
+
data_length += len(value)
|
|
518
|
+
else:
|
|
519
|
+
present_fields = [field for field in fields if field in record]
|
|
520
|
+
rows.extend(_encode_varint(len(present_fields)))
|
|
521
|
+
previous_field = 0
|
|
522
|
+
for position, field in enumerate(present_fields):
|
|
523
|
+
field_id = field_ids[field]
|
|
524
|
+
rows.extend(_encode_varint(field_id - previous_field))
|
|
525
|
+
value = _compact_json(record[field])
|
|
526
|
+
rows.extend(_encode_varint(len(value)))
|
|
527
|
+
data_file.write(value)
|
|
528
|
+
data_digest.update(value)
|
|
529
|
+
data_length += len(value)
|
|
530
|
+
previous_field = field_id
|
|
531
|
+
row_offsets.append(len(rows))
|
|
532
|
+
_report_progress(progress, "Writing value data", record_number, len(records))
|
|
533
|
+
data_file.flush()
|
|
534
|
+
os.fsync(data_file.fileno())
|
|
535
|
+
|
|
536
|
+
schema = _compact_json(fields)
|
|
537
|
+
record_ids = b"" if plan.sequential_numeric_ids else _compact_json(ids)
|
|
538
|
+
row_offset_table = b"".join(struct.pack(">Q", value) for value in row_offsets)
|
|
539
|
+
raw_catalog = (
|
|
540
|
+
CATALOG_HEADER.pack(
|
|
541
|
+
CATALOG_MAGIC,
|
|
542
|
+
CATALOG_VERSION,
|
|
543
|
+
mode_code,
|
|
544
|
+
len(records),
|
|
545
|
+
len(fields),
|
|
546
|
+
len(schema),
|
|
547
|
+
len(record_ids),
|
|
548
|
+
len(rows),
|
|
549
|
+
)
|
|
550
|
+
+ schema
|
|
551
|
+
+ record_ids
|
|
552
|
+
+ row_offset_table
|
|
553
|
+
+ rows
|
|
554
|
+
)
|
|
555
|
+
_report_progress(progress, "Compressing catalog", 0, 1)
|
|
556
|
+
compressed_catalog = lzma.compress(raw_catalog, preset=compression)
|
|
557
|
+
_report_progress(progress, "Compressing catalog", 1, 1)
|
|
558
|
+
metadata = {
|
|
559
|
+
"format": "RIDA",
|
|
560
|
+
"format_version": RIDA_VERSION,
|
|
561
|
+
"title": title or output.stem,
|
|
562
|
+
"description": description or "",
|
|
563
|
+
"open_with": "RIDA Explorer",
|
|
564
|
+
"reader_url": reader_url or "",
|
|
565
|
+
"encoding": "UTF-8",
|
|
566
|
+
"index_mode": mode,
|
|
567
|
+
"record_count": len(records),
|
|
568
|
+
"field_count": len(fields),
|
|
569
|
+
"record_id_mode": "sequential_numeric" if plan.sequential_numeric_ids else "dictionary",
|
|
570
|
+
"catalog_codec": "lzma",
|
|
571
|
+
}
|
|
572
|
+
metadata_bytes = _compact_json(metadata)
|
|
573
|
+
data_offset = HEADER.size + len(metadata_bytes) + len(compressed_catalog)
|
|
574
|
+
header = HEADER.pack(
|
|
575
|
+
RIDA_MAGIC,
|
|
576
|
+
RIDA_VERSION,
|
|
577
|
+
HEADER.size,
|
|
578
|
+
len(metadata_bytes),
|
|
579
|
+
len(compressed_catalog),
|
|
580
|
+
len(raw_catalog),
|
|
581
|
+
data_offset,
|
|
582
|
+
data_length,
|
|
583
|
+
len(records),
|
|
584
|
+
hashlib.sha256(compressed_catalog).digest(),
|
|
585
|
+
data_digest.digest(),
|
|
586
|
+
)
|
|
587
|
+
with tempfile.NamedTemporaryFile(
|
|
588
|
+
mode="w+b", prefix=f".{output.name}.", suffix=".tmp", dir=output.parent, delete=False
|
|
589
|
+
) as built:
|
|
590
|
+
_report_progress(progress, "Writing RIDA file", 0, data_length)
|
|
591
|
+
output_temp_path = Path(built.name)
|
|
592
|
+
built.write(header)
|
|
593
|
+
built.write(metadata_bytes)
|
|
594
|
+
built.write(compressed_catalog)
|
|
595
|
+
copied_data = 0
|
|
596
|
+
with data_temp_path.open("rb") as data_file:
|
|
597
|
+
while block := data_file.read(1024 * 1024):
|
|
598
|
+
built.write(block)
|
|
599
|
+
copied_data += len(block)
|
|
600
|
+
_report_progress(progress, "Writing RIDA file", copied_data, data_length)
|
|
601
|
+
built.flush()
|
|
602
|
+
os.fsync(built.fileno())
|
|
603
|
+
os.replace(output_temp_path, output)
|
|
604
|
+
output_temp_path = None
|
|
605
|
+
finally:
|
|
606
|
+
if data_temp_path is not None:
|
|
607
|
+
data_temp_path.unlink(missing_ok=True)
|
|
608
|
+
if output_temp_path is not None:
|
|
609
|
+
output_temp_path.unlink(missing_ok=True)
|
|
610
|
+
|
|
611
|
+
return BuildResult(
|
|
612
|
+
mode=mode,
|
|
613
|
+
records=len(records),
|
|
614
|
+
fields=len(fields),
|
|
615
|
+
metadata_bytes=len(metadata_bytes),
|
|
616
|
+
catalog_bytes=len(compressed_catalog),
|
|
617
|
+
raw_catalog_bytes=len(raw_catalog),
|
|
618
|
+
data_bytes=data_length,
|
|
619
|
+
output_bytes=output.stat().st_size,
|
|
620
|
+
)
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
def build(
|
|
624
|
+
source: str | Path,
|
|
625
|
+
output: str | Path,
|
|
626
|
+
*,
|
|
627
|
+
id_key: str | None = None,
|
|
628
|
+
mode: str = "auto",
|
|
629
|
+
title: str | None = None,
|
|
630
|
+
description: str | None = None,
|
|
631
|
+
reader_url: str | None = None,
|
|
632
|
+
compression: int = 9,
|
|
633
|
+
progress: ProgressCallback | None = None,
|
|
634
|
+
) -> BuildResult:
|
|
635
|
+
"""Build one immutable RIDA file from JSON input.
|
|
636
|
+
|
|
637
|
+
``mode`` can be ``"auto"`` (the default), ``"dense"``, or ``"sparse"``.
|
|
638
|
+
The source file is never changed. An existing output file is refused so a
|
|
639
|
+
build cannot replace a published dataset accidentally.
|
|
640
|
+
"""
|
|
641
|
+
if mode not in ("auto", "dense", "sparse"):
|
|
642
|
+
raise RidaError("RIDA mode must be 'auto', 'dense', or 'sparse'")
|
|
643
|
+
records = load_records(Path(source), id_key, progress)
|
|
644
|
+
plan = scan_records(records, progress)
|
|
645
|
+
selected_mode = plan.recommended_mode if mode == "auto" else mode
|
|
646
|
+
return build_rida(
|
|
647
|
+
records,
|
|
648
|
+
plan,
|
|
649
|
+
Path(output),
|
|
650
|
+
selected_mode,
|
|
651
|
+
title,
|
|
652
|
+
description,
|
|
653
|
+
reader_url,
|
|
654
|
+
compression,
|
|
655
|
+
progress,
|
|
656
|
+
)
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
def _read_exact(file: BinaryIO, offset: int, length: int) -> bytes:
|
|
660
|
+
file.seek(offset)
|
|
661
|
+
data = file.read(length)
|
|
662
|
+
if len(data) != length:
|
|
663
|
+
raise RidaError("RIDA file ended before the requested range")
|
|
664
|
+
return data
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
class RidaFile:
|
|
668
|
+
"""Read a local RIDA file."""
|
|
669
|
+
|
|
670
|
+
def __init__(self, path: str | Path):
|
|
671
|
+
self.path = Path(path)
|
|
672
|
+
self.file = self.path.open("rb")
|
|
673
|
+
try:
|
|
674
|
+
self.header = _parse_header(_read_exact(self.file, 0, HEADER.size))
|
|
675
|
+
expected_size = self.header.data_offset + self.header.data_length
|
|
676
|
+
if self.path.stat().st_size != expected_size:
|
|
677
|
+
raise RidaError("RIDA file size does not match its header")
|
|
678
|
+
self.metadata = json.loads(_read_exact(self.file, HEADER.size, self.header.metadata_length))
|
|
679
|
+
catalog_offset = HEADER.size + self.header.metadata_length
|
|
680
|
+
catalog = _read_exact(self.file, catalog_offset, self.header.catalog_length)
|
|
681
|
+
self.catalog = Catalog(self.header, catalog)
|
|
682
|
+
except Exception:
|
|
683
|
+
self.file.close()
|
|
684
|
+
raise
|
|
685
|
+
|
|
686
|
+
def get(self, record_id: str | int, field: str) -> Any:
|
|
687
|
+
relative_offset, length = self.catalog.pointer(record_id, field)
|
|
688
|
+
raw = _read_exact(self.file, self.header.data_offset + relative_offset, length)
|
|
689
|
+
return json.loads(raw)
|
|
690
|
+
|
|
691
|
+
def close(self) -> None:
|
|
692
|
+
if not self.file.closed:
|
|
693
|
+
self.file.close()
|
|
694
|
+
|
|
695
|
+
def __enter__(self) -> "RidaFile":
|
|
696
|
+
return self
|
|
697
|
+
|
|
698
|
+
def __exit__(self, *_: object) -> None:
|
|
699
|
+
self.close()
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
def _http_range(url: str, offset: int, length: int) -> bytes:
|
|
703
|
+
request = urllib.request.Request(url, headers={"Range": f"bytes={offset}-{offset + length - 1}"})
|
|
704
|
+
with urllib.request.urlopen(request) as response:
|
|
705
|
+
data = response.read()
|
|
706
|
+
status = response.status
|
|
707
|
+
content_range = response.headers.get("Content-Range", "")
|
|
708
|
+
expected_range = f"bytes {offset}-{offset + length - 1}/"
|
|
709
|
+
if status != 206 or not content_range.casefold().startswith(expected_range):
|
|
710
|
+
raise RidaError("Server did not honor the requested byte range")
|
|
711
|
+
if len(data) != length:
|
|
712
|
+
raise RidaError(f"Server returned {len(data)} bytes; expected {length}. Range support is required.")
|
|
713
|
+
return data
|
|
714
|
+
|
|
715
|
+
|
|
716
|
+
class RemoteRidaFile:
|
|
717
|
+
"""Read a RIDA file through standard HTTP byte-range requests."""
|
|
718
|
+
|
|
719
|
+
def __init__(self, url: str):
|
|
720
|
+
self.url = url
|
|
721
|
+
self.header = _parse_header(_http_range(url, 0, HEADER.size))
|
|
722
|
+
prefix = _http_range(url, HEADER.size, self.header.metadata_length + self.header.catalog_length)
|
|
723
|
+
self.metadata = json.loads(prefix[:self.header.metadata_length])
|
|
724
|
+
self.catalog = Catalog(self.header, prefix[self.header.metadata_length:])
|
|
725
|
+
|
|
726
|
+
def get(self, record_id: str | int, field: str) -> Any:
|
|
727
|
+
relative_offset, length = self.catalog.pointer(record_id, field)
|
|
728
|
+
raw = _http_range(self.url, self.header.data_offset + relative_offset, length)
|
|
729
|
+
return json.loads(raw)
|
|
730
|
+
|
|
731
|
+
|
|
732
|
+
def inspect_metadata(path: Path) -> dict[str, Any]:
|
|
733
|
+
with path.open("rb") as file:
|
|
734
|
+
header = _parse_header(_read_exact(file, 0, HEADER.size))
|
|
735
|
+
metadata = json.loads(_read_exact(file, HEADER.size, header.metadata_length))
|
|
736
|
+
return {
|
|
737
|
+
"metadata": metadata,
|
|
738
|
+
"header": {
|
|
739
|
+
"header_bytes": HEADER.size,
|
|
740
|
+
"metadata_bytes": header.metadata_length,
|
|
741
|
+
"catalog_bytes": header.catalog_length,
|
|
742
|
+
"raw_catalog_bytes": header.raw_catalog_length,
|
|
743
|
+
"data_bytes": header.data_length,
|
|
744
|
+
"record_count": header.record_count,
|
|
745
|
+
"file_bytes": header.data_offset + header.data_length,
|
|
746
|
+
},
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
def _print_value(value: Any) -> None:
|
|
751
|
+
if isinstance(value, str):
|
|
752
|
+
print(value)
|
|
753
|
+
else:
|
|
754
|
+
print(json.dumps(value, ensure_ascii=False, indent=2))
|
|
755
|
+
|
|
756
|
+
|
|
757
|
+
def _add_source_arguments(parser: argparse.ArgumentParser) -> None:
|
|
758
|
+
parser.add_argument("input", type=Path, help="JSON file, JSON array, or folder of JSON record files")
|
|
759
|
+
parser.add_argument("--id-key", help="ID field for a JSON array source")
|
|
760
|
+
|
|
761
|
+
|
|
762
|
+
class _TerminalProgress:
|
|
763
|
+
"""Small dependency-free progress renderer for the RIDA command."""
|
|
764
|
+
|
|
765
|
+
def __init__(self) -> None:
|
|
766
|
+
self.stream = sys.stderr
|
|
767
|
+
self.interactive = self.stream.isatty()
|
|
768
|
+
|
|
769
|
+
def __call__(self, stage: str, completed: int, total: int) -> None:
|
|
770
|
+
if total:
|
|
771
|
+
percent = completed * 100 // total
|
|
772
|
+
message = f"{stage}: {completed:,}/{total:,} ({percent}%)"
|
|
773
|
+
else:
|
|
774
|
+
message = f"{stage}…"
|
|
775
|
+
if self.interactive:
|
|
776
|
+
print(f"\r{message}", end="", file=self.stream, flush=True)
|
|
777
|
+
if total and completed >= total:
|
|
778
|
+
print(file=self.stream, flush=True)
|
|
779
|
+
elif total and completed >= total:
|
|
780
|
+
print(message, file=self.stream, flush=True)
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
def main() -> int:
|
|
784
|
+
parser = argparse.ArgumentParser(description="Build and read RIDA 0.1 files")
|
|
785
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
786
|
+
|
|
787
|
+
scan_parser = commands.add_parser("scan", help="Scan records and recommend dense or sparse mode")
|
|
788
|
+
_add_source_arguments(scan_parser)
|
|
789
|
+
|
|
790
|
+
build_parser = commands.add_parser("build", help="Build one .rida file")
|
|
791
|
+
_add_source_arguments(build_parser)
|
|
792
|
+
build_parser.add_argument("output", type=Path, help="Output .rida file")
|
|
793
|
+
build_parser.add_argument("--mode", choices=("auto", "dense", "sparse"), default="auto")
|
|
794
|
+
build_parser.add_argument("--title", help="Human-readable dataset title for embedded metadata")
|
|
795
|
+
build_parser.add_argument("--description", help="Dataset description for embedded metadata")
|
|
796
|
+
build_parser.add_argument("--reader-url", help="RIDA Explorer download or opener URL for embedded metadata")
|
|
797
|
+
build_parser.add_argument("--compression", type=int, choices=range(10), default=9)
|
|
798
|
+
build_parser.add_argument("--yes", action="store_true", help="Build without an interactive confirmation")
|
|
799
|
+
|
|
800
|
+
inspect_parser = commands.add_parser("inspect", help="Read RIDA header and embedded metadata")
|
|
801
|
+
inspect_parser.add_argument("file", type=Path)
|
|
802
|
+
|
|
803
|
+
get_parser = commands.add_parser("get", help="Read one field from a local RIDA file")
|
|
804
|
+
get_parser.add_argument("file", type=Path)
|
|
805
|
+
get_parser.add_argument("record_id")
|
|
806
|
+
get_parser.add_argument("field")
|
|
807
|
+
|
|
808
|
+
remote_get_parser = commands.add_parser("remote-get", help="Read one field from a public RIDA URL")
|
|
809
|
+
remote_get_parser.add_argument("url")
|
|
810
|
+
remote_get_parser.add_argument("record_id")
|
|
811
|
+
remote_get_parser.add_argument("field")
|
|
812
|
+
|
|
813
|
+
args = parser.parse_args()
|
|
814
|
+
if args.command in ("scan", "build"):
|
|
815
|
+
progress = _TerminalProgress()
|
|
816
|
+
records = load_records(args.input, args.id_key, progress)
|
|
817
|
+
plan = scan_records(records, progress)
|
|
818
|
+
print_scan(records, plan)
|
|
819
|
+
if args.command == "scan":
|
|
820
|
+
return 0
|
|
821
|
+
|
|
822
|
+
selected_mode = plan.recommended_mode if args.mode == "auto" else args.mode
|
|
823
|
+
print(f"Selected mode: {selected_mode}")
|
|
824
|
+
if not args.yes:
|
|
825
|
+
if not sys.stdin.isatty():
|
|
826
|
+
raise RidaError("Use --yes for non-interactive builds")
|
|
827
|
+
answer = input("Build this RIDA file? [y/N] ").strip().casefold()
|
|
828
|
+
if answer not in ("y", "yes"):
|
|
829
|
+
print("Build cancelled.")
|
|
830
|
+
return 0
|
|
831
|
+
result = build_rida(
|
|
832
|
+
records,
|
|
833
|
+
plan,
|
|
834
|
+
args.output,
|
|
835
|
+
selected_mode,
|
|
836
|
+
args.title,
|
|
837
|
+
args.description,
|
|
838
|
+
args.reader_url,
|
|
839
|
+
args.compression,
|
|
840
|
+
progress,
|
|
841
|
+
)
|
|
842
|
+
print(f"Created: {args.output}")
|
|
843
|
+
print(f"Records: {result.records:,}; fields: {result.fields:,}; mode: {result.mode}")
|
|
844
|
+
print(f"Catalog: {result.catalog_bytes:,} bytes compressed from {result.raw_catalog_bytes:,} bytes")
|
|
845
|
+
print(f"Data: {result.data_bytes:,} bytes; RIDA file: {result.output_bytes:,} bytes")
|
|
846
|
+
return 0
|
|
847
|
+
|
|
848
|
+
if args.command == "inspect":
|
|
849
|
+
print(json.dumps(inspect_metadata(args.file), ensure_ascii=False, indent=2))
|
|
850
|
+
return 0
|
|
851
|
+
|
|
852
|
+
if args.command == "get":
|
|
853
|
+
with RidaFile(args.file) as data:
|
|
854
|
+
_print_value(data.get(args.record_id, args.field))
|
|
855
|
+
return 0
|
|
856
|
+
|
|
857
|
+
if args.command == "remote-get":
|
|
858
|
+
data = RemoteRidaFile(args.url)
|
|
859
|
+
_print_value(data.get(args.record_id, args.field))
|
|
860
|
+
return 0
|
|
861
|
+
|
|
862
|
+
raise AssertionError("unreachable")
|
|
863
|
+
|
|
864
|
+
|
|
865
|
+
if __name__ == "__main__":
|
|
866
|
+
try:
|
|
867
|
+
raise SystemExit(main())
|
|
868
|
+
except (RidaError, json.JSONDecodeError, OSError, urllib.error.URLError) as error:
|
|
869
|
+
print(f"RIDA error: {error}", file=sys.stderr)
|
|
870
|
+
raise SystemExit(1)
|
rida/__main__.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: rida-format
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Range Indexed Data Access (RIDA) static data format and library
|
|
5
|
+
Author: Syed Ali Hamza Chishty
|
|
6
|
+
Maintainer-email: Qasra Foundation <admin@qasra.org>
|
|
7
|
+
License-Expression: LicenseRef-Proprietary
|
|
8
|
+
Keywords: rida,json,r2,range-requests,static-data
|
|
9
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Requires-Python: >=3.10
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# RIDA Python library — 0.1
|
|
23
|
+
|
|
24
|
+
RIDA means **Range Indexed Data Access**. It is an installable Python library
|
|
25
|
+
and terminal tool that builds one `.rida` file from a collection of JSON
|
|
26
|
+
records. The file contains:
|
|
27
|
+
|
|
28
|
+
- a fixed RIDA header;
|
|
29
|
+
- small, readable UTF-8 metadata at the start of the file;
|
|
30
|
+
- a compressed dense or sparse address catalog; and
|
|
31
|
+
- UTF-8 JSON values stored in a data region.
|
|
32
|
+
|
|
33
|
+
The reader loads the catalog once and then reads only the requested field bytes.
|
|
34
|
+
It works locally and over an HTTP server that supports byte-range requests.
|
|
35
|
+
|
|
36
|
+
## Install locally
|
|
37
|
+
|
|
38
|
+
From this project folder:
|
|
39
|
+
|
|
40
|
+
```sh
|
|
41
|
+
python3 -m pip install .
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
After that, the `rida` command is available in the same Python environment.
|
|
45
|
+
The library uses only Python's standard library at runtime: no database, cloud
|
|
46
|
+
account, or server process is required.
|
|
47
|
+
|
|
48
|
+
After the package is published, another person can install it with:
|
|
49
|
+
|
|
50
|
+
```sh
|
|
51
|
+
python3 -m pip install rida-format
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
The public package name is provisionally `rida`; publishing to PyPI will
|
|
55
|
+
happen only after the RIDA file format is frozen. The command and Python import
|
|
56
|
+
name are both simply `rida`.
|
|
57
|
+
|
|
58
|
+
### Library project files
|
|
59
|
+
|
|
60
|
+
Keep the source project in one folder, for example `rida/`:
|
|
61
|
+
|
|
62
|
+
```text
|
|
63
|
+
rida/
|
|
64
|
+
├── pyproject.toml package name and install command
|
|
65
|
+
├── MANIFEST.in files included in the public source archive
|
|
66
|
+
├── RIDA-README.md usage instructions
|
|
67
|
+
├── RIDA-DESIGN-0.1.md RIDA format design
|
|
68
|
+
├── rida-metadata.html optional browser metadata opener
|
|
69
|
+
└── src/
|
|
70
|
+
└── rida/
|
|
71
|
+
├── __init__.py RIDA builder and reader library
|
|
72
|
+
└── __main__.py enables: python -m rida
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
`src/rida/` is internal library code. After installation, Python copies it into
|
|
76
|
+
its own `site-packages/rida/` location. A developer never needs to run an
|
|
77
|
+
individual `.py` file: they use `import rida`, `rida ...`, or `python -m rida`.
|
|
78
|
+
|
|
79
|
+
## Requirements and downloads
|
|
80
|
+
|
|
81
|
+
- Python **3.10 or newer** and `pip` are required.
|
|
82
|
+
- RIDA has **zero third-party runtime dependencies**. It uses only Python's
|
|
83
|
+
built-in `json`, `lzma`, `hashlib`, `urllib`, and related standard modules.
|
|
84
|
+
- The `rida` command has its own progress display for loading, scanning, value
|
|
85
|
+
writing, catalog compression, and final file writing. It does not require
|
|
86
|
+
`tqdm`.
|
|
87
|
+
- It does not install or require AWS SDK, Cloudflare SDK, SQLite, Node.js,
|
|
88
|
+
Rust, a database server, or a Worker.
|
|
89
|
+
- When installing this source project, `pip` may temporarily download
|
|
90
|
+
`setuptools` (version 68 or newer) to build the package. It is an install
|
|
91
|
+
tool, not a RIDA runtime dependency.
|
|
92
|
+
- Official Python installers for macOS and Windows include the required `lzma`
|
|
93
|
+
support. On an unusually minimal Linux Python build, install the operating
|
|
94
|
+
system's `python3-lzma` package before using RIDA.
|
|
95
|
+
|
|
96
|
+
## Build
|
|
97
|
+
|
|
98
|
+
Scan first. It reports the field density and recommends dense or sparse mode:
|
|
99
|
+
|
|
100
|
+
```sh
|
|
101
|
+
rida scan users.json
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Build a RIDA file. The command asks for confirmation unless `--yes` is supplied:
|
|
105
|
+
|
|
106
|
+
```sh
|
|
107
|
+
rida build users.json users.rida \
|
|
108
|
+
--title "Users dataset" \
|
|
109
|
+
--description "Public sample data" \
|
|
110
|
+
--reader-url "https://example.com/rida-explorer" \
|
|
111
|
+
--yes
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
During a build, the terminal shows RIDA's own progress, for example:
|
|
115
|
+
|
|
116
|
+
```text
|
|
117
|
+
Reading JSON bytes: 217,221,288/217,221,288 (100%)
|
|
118
|
+
Parsing JSON: 1/1 (100%)
|
|
119
|
+
Scanning field names: 39,098/39,098 (100%)
|
|
120
|
+
Measuring values: 39,098/39,098 (100%)
|
|
121
|
+
Writing value data: 39,098/39,098 (100%)
|
|
122
|
+
Compressing catalog: 1/1 (100%)
|
|
123
|
+
Writing RIDA file: 217,221,288/217,221,288 (100%)
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
For a folder of JSON record files, loading progress counts record files. For
|
|
127
|
+
one large JSON file, it counts source bytes while reading, then shows a
|
|
128
|
+
separate parsing stage. RIDA 0.1 still keeps a single JSON source in memory
|
|
129
|
+
while parsing; the planned streaming importer is for very large single files.
|
|
130
|
+
|
|
131
|
+
Input can be:
|
|
132
|
+
|
|
133
|
+
- an object that maps IDs to JSON record objects;
|
|
134
|
+
- an array of JSON record objects, with `--id-key`; or
|
|
135
|
+
- a folder containing individual JSON record files. Filenames become IDs.
|
|
136
|
+
|
|
137
|
+
```sh
|
|
138
|
+
rida build records/ records.rida --yes
|
|
139
|
+
rida build users-array.json users.rida --id-key id --yes
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
Use `--mode dense` or `--mode sparse` to override the recommendation. The builder does not overwrite an existing output file.
|
|
143
|
+
|
|
144
|
+
## Read locally
|
|
145
|
+
|
|
146
|
+
```sh
|
|
147
|
+
rida inspect users.rida
|
|
148
|
+
rida get users.rida ali city
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
## Read from R2 or another public HTTP URL
|
|
152
|
+
|
|
153
|
+
After uploading the `.rida` file to an HTTP byte-range server:
|
|
154
|
+
|
|
155
|
+
```sh
|
|
156
|
+
rida remote-get https://data.example.com/users.rida ali city
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
The remote reader first fetches the 128-byte header and catalog, then fetches only the requested field range. For browser readers, configure CORS to allow `GET`, `HEAD`, and the `Range` request header, and expose `Content-Range`, `Content-Length`, and `ETag`.
|
|
160
|
+
|
|
161
|
+
One `RemoteRidaFile` object keeps that catalog in RAM, so later `.get()` calls on
|
|
162
|
+
the same object fetch only the requested value range. The `rida remote-get`
|
|
163
|
+
terminal command creates a new object each time, so persistent on-disk catalog
|
|
164
|
+
cache is a later RIDA Reader feature.
|
|
165
|
+
|
|
166
|
+
## Metadata opener page
|
|
167
|
+
|
|
168
|
+
Open `rida-metadata.html` in a browser and choose any `.rida` file. It reads only the embedded header and metadata on the local computer, then displays the title, record count, index mode, and RIDA Explorer download URL. It never uploads the file.
|
|
169
|
+
|
|
170
|
+
## Use from Python
|
|
171
|
+
|
|
172
|
+
```python
|
|
173
|
+
import rida
|
|
174
|
+
|
|
175
|
+
# Scan first if you want to show the publisher the recommendation.
|
|
176
|
+
report = rida.scan("users.json")
|
|
177
|
+
print(report.recommended_mode) # "dense" or "sparse"
|
|
178
|
+
|
|
179
|
+
# Build once. The source JSON stays unchanged.
|
|
180
|
+
rida.build(
|
|
181
|
+
"users.json",
|
|
182
|
+
"users.rida",
|
|
183
|
+
title="Users dataset",
|
|
184
|
+
reader_url="https://example.com/rida",
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
# Read only one stored value from a local RIDA file.
|
|
188
|
+
with rida.RidaFile("users.rida") as data:
|
|
189
|
+
print(data.get("ali", "city"))
|
|
190
|
+
|
|
191
|
+
# The same primary lookup works against an R2/public URL with Range support.
|
|
192
|
+
remote = rida.RemoteRidaFile("https://data.example.com/users.rida")
|
|
193
|
+
print(remote.get("fatima", "languages"))
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
A desktop app or another Python program can show the same stages in its own
|
|
197
|
+
interface by passing a callback:
|
|
198
|
+
|
|
199
|
+
```python
|
|
200
|
+
def progress(stage, completed, total):
|
|
201
|
+
print(f"{stage}: {completed}/{total}")
|
|
202
|
+
|
|
203
|
+
rida.build("users.json", "users.rida", progress=progress)
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
## Current scope
|
|
207
|
+
|
|
208
|
+
RIDA 0.1 implements primary lookup: `record ID + field name → value`.
|
|
209
|
+
|
|
210
|
+
The approved design for optional exact-match, numeric-range, and Unicode full-text indexes is in [RIDA-DESIGN-0.1.md](RIDA-DESIGN-0.1.md). Those search-index blocks are the next format layer; they are not claimed as implemented by this library yet.
|
|
211
|
+
|
|
212
|
+
## License
|
|
213
|
+
|
|
214
|
+
RIDA is distributed under the RIDA Proprietary License in the `LICENSE` file.
|
|
215
|
+
You may download and modify RIDA, and use it in free or paid applications.
|
|
216
|
+
You may not sell or redistribute RIDA as a standalone package or library.
|
|
217
|
+
Applications that include RIDA must show the attribution notice specified in
|
|
218
|
+
the license.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
rida/__init__.py,sha256=bh6IKBOkRT9gL2QmbatgS9T_emSOWay5Z15DhL9re9Q,34099
|
|
2
|
+
rida/__main__.py,sha256=aGKzTt9RtHae5loTKydrLuYUaHWkb3gprEvecQYGM-w,115
|
|
3
|
+
rida_format-0.1.0.dist-info/licenses/LICENSE,sha256=v2NDhI1QnQLJCrFXVXYuQfLRSxOGc43FbfafObq1mTo,1584
|
|
4
|
+
rida_format-0.1.0.dist-info/METADATA,sha256=CrvLbtmj7EAd7pChs9bOCaj1CBk1Ml4OKuxmV7EhVz0,7843
|
|
5
|
+
rida_format-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
6
|
+
rida_format-0.1.0.dist-info/entry_points.txt,sha256=yqkOnNK1kHLLQyxzIN_Hq50_ZVtGcT2bHYEwvmJVIAk,35
|
|
7
|
+
rida_format-0.1.0.dist-info/top_level.txt,sha256=JbIa--2Ftfm53IhiKdWIxn4k9GrRkSaGfRm79cvBbJM,5
|
|
8
|
+
rida_format-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
RIDA PROPRIETARY LICENSE
|
|
2
|
+
Version 1.0
|
|
3
|
+
|
|
4
|
+
Copyright (c) 2026 Syed Ali Hamza Chishty. All rights reserved.
|
|
5
|
+
|
|
6
|
+
This license applies to the RIDA software library and its source code
|
|
7
|
+
(“RIDA”). It does not apply to data files created with RIDA.
|
|
8
|
+
|
|
9
|
+
1. Permission to use and modify
|
|
10
|
+
|
|
11
|
+
You may download, install, run, inspect, and modify RIDA for your own use.
|
|
12
|
+
You may use RIDA, including a modified version, as a component of software
|
|
13
|
+
applications that you create.
|
|
14
|
+
|
|
15
|
+
2. Applications and commercial use
|
|
16
|
+
|
|
17
|
+
You may distribute and sell applications that include RIDA, including a
|
|
18
|
+
modified version of RIDA, as an integrated component. You may not offer RIDA
|
|
19
|
+
as a separately installable or downloadable library, package, or standalone
|
|
20
|
+
software product as part of that distribution.
|
|
21
|
+
|
|
22
|
+
Every application that includes RIDA must display this notice in an About,
|
|
23
|
+
Licenses, or Third-Party Notices section:
|
|
24
|
+
|
|
25
|
+
“Uses RIDA (Range Indexed Data Access).
|
|
26
|
+
Copyright (c) 2026 Syed Ali Hamza Chishty.
|
|
27
|
+
Used under the RIDA Proprietary License.”
|
|
28
|
+
|
|
29
|
+
3. Standalone redistribution and resale
|
|
30
|
+
|
|
31
|
+
You may not sell, sublicense, publish, or otherwise distribute RIDA or a
|
|
32
|
+
modified version of RIDA as a standalone library, package, or software
|
|
33
|
+
product. You may not claim that you own or authored the original RIDA code.
|
|
34
|
+
|
|
35
|
+
4. Ownership
|
|
36
|
+
|
|
37
|
+
Syed Ali Hamza Chishty retains ownership of RIDA. This license grants only
|
|
38
|
+
the permissions stated above; it does not transfer ownership of RIDA.
|
|
39
|
+
|
|
40
|
+
5. Warranty
|
|
41
|
+
|
|
42
|
+
RIDA is provided “AS IS”, without warranties or conditions of any kind,
|
|
43
|
+
express or implied, to the extent permitted by applicable law.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
rida
|