Concepts#
MetaRelay moves records to destinations. The ideas below are the same for every backend.
The pieces#
Concept |
What it is |
|---|---|
Record |
A JSON document: |
Schema |
A Pydantic model registered under an ID and version, for example |
Destination |
A URI that picks the backend: |
Session |
An open connection to one destination. |
Container |
Where records live, named by a LogicalPath such as |
Receipt |
What MetaRelay knows about a record after writing or reading it, including its checksum. Keep receipts (in a |
Preview |
A readable table of the record, stored next to it, so people never have to read raw JSON. |
Writing a record#
┌────────────── your receipt from last time
▼
record ──► write_record ──► compare with what's at the destination now
│
┌────────────────────────┼─────────────────────────┐
▼ ▼ ▼
nothing there, same as your record, changed by someone
or only your own nothing to do else since your
earlier version receipt
│ │ │
WRITE SKIP ConflictError
Write modes#
Mode |
If the record already exists |
|---|---|
|
Update it, unless it changed at the destination since your receipt. Without a receipt, only an identical record is accepted. |
|
Always |
|
Overwrite it. Use only after the user chose to. |
Edits made directly to the preview (a notebook entry, or the .md file) also count as a
change at the destination, so they are not overwritten silently. That holds
even if you read the record after the edit: a read returns the JSON, not the
preview, so its receipt still describes the preview MetaRelay last wrote.
Handling a conflict#
ConflictError means someone changed the record at the destination since
your receipt. MetaRelay never picks a winner. Show the person both versions
(read_record returns theirs), and let them choose:
Keep their change: copy it into your record, then write it with
mode=WriteMode.FORCE. Your record now holds both.Keep yours: write it with
mode=WriteMode.FORCE.
The save_metadata example writes
every record this way. It stops on a conflict unless the person already
chose to replace the change:
def write(
session: Session,
where: LogicalPath,
record: Record,
receipts: SyncIndex,
*,
force: bool = False,
) -> Receipt:
"""Write ``record`` with the receipt from the last write, and keep the new one.
Raises:
ConflictError: If the record changed at the destination since then,
unless ``force`` is set.
"""
prior = receipts.get(session.destination, where, record.record_id)
try:
receipt = session.write_record(where, record, prior_receipt=prior)
except ConflictError:
# Someone changed the record at the destination since `prior`.
# Stop, unless the person already chose to replace their change.
if not force:
raise
receipt = session.write_record(where, record, mode=WriteMode.FORCE)
receipts.put(receipt)
return receipt
When someone edited the preview#
The ConflictError for an edit to the preview says what changed. Its
preview_diff lists each table row whose value differs from what MetaRelay
wrote, and whether that list is complete. To keep the edits, accept_edits
copies them into the record and writes it, so the JSON and the preview agree
again:
from metarelay import ConflictError, accept_edits
try:
session.write_record(path, record, prior_receipt=receipt)
except ConflictError as error:
diff = error.preview_diff
if diff is None or not diff.complete:
raise # another kind of conflict, or changes MetaRelay can't list
for edit in diff.edits:
print(edit.describe()) # Metadata · fiber.core_um: '400' → '200'
if person_accepts():
written = accept_edits(session, path, record, diff)
record = written[record.record_id].record # now holds the edits
The JSON stays the source of truth: MetaRelay never takes a value from the
preview by itself, only when your code calls accept_edits. Keep the
returned record: writing your old copy again would undo the edits.
Each value goes back where the generic preview showed it (Context rows
into context, Metadata rows such as fiber.core_um into payload),
converted to the type it replaces, and the result is validated. If any edit
can’t be applied, nothing is written and ValidationError says why: an edit
to a value your record also changed, an added or removed row, a value that
isn’t a number where one was, or a schema with its own renderer.
apply_edits(record, edits) does the copying without writing.
On eLabFTW one entry holds several records, and the diff lists edits to all
of them. accept_edits reads the other records, applies their edits, and
writes them too, because a forced write rebuilds the whole entry. Like any
forced write, it overwrites a change someone makes at the same moment.
complete is False when someone also changed something MetaRelay can’t
list, such as text added between the tables: look at the entry and copy what
you want by hand. The written values come from rendering the stored record
again, so if a MetaRelay upgrade or a schema’s renderer changed how a value
reads since the last write, that row shows up as an edit too. On a local
folder or GitHub the diff lists no edits instead, as it does when someone
edited the .json but not the preview: MetaRelay can’t tell old values from
a person’s edits.
The metarelay command does the same: metarelay write lists the edits,
and metarelay write --accept-edits accepts them and updates your JSON file.
Errors#
Every backend raises the same errors, all subclasses of MetaRelayError:
Error |
Means |
|---|---|
|
Bad URI or config, or the backend’s extra isn’t installed |
|
Login failed |
|
Logged in, but not allowed |
|
Couldn’t reach the destination |
|
No such container or record |
|
The write would overwrite someone else’s change |
|
A record, payload or name is invalid |
Backends and the conformance suite#
A backend is done when it passes the conformance suite. It ships in
metarelay[testing], so a backend in another package can run the same
checks:
import pytest
from metarelay import connect
from metarelay.testing import BackendConformance
class TestMyBackend(BackendConformance):
@pytest.fixture
def session(self):
session = connect("mybackend://test-server")
yield session
session.close()
metarelay.testing.MemorySession is an in-memory backend for testing code
that uses MetaRelay without touching disk.
The local backend#
file:///path/to/folder stores each container as a folder. The folder must
already exist.
{id}.jsonis the record and the source of truth;{id}.mdis its preview..metarelay/index.jsonlists which files are records. Delete it, and it is rebuilt from the.jsonfiles..metarelay/history.jsonlgets one line per write.Names that are unsafe on any common filesystem are rejected everywhere (
\ : * ? " < > |, a trailing dot or space,CON,NUL, …). Names starting with.are reserved.Names are compared ignoring case and Unicode spelling, on every OS. A name that matches an existing one only that way (
studynext toStudy, or recordImplant-M1next toimplant-M1) is refused, so a folder behaves the same on macOS, Windows and Linux.Every
.jsonin a container is a record, except files written withwrite_file. A.jsonthat isn’t a valid record makes listing fail with an error naming the file, rather than the record silently disappearing. So give MetaRelay its own folder, not one where an app keeps other.jsonfiles.The same folder always gets the same destination URI (
lab dataandlab%20data, or a symlinked path, are one destination), so receipts match.createis enforced even with two writers. Other modes assume one writer per folder at a time.