Synapse

A synapse is a ‘smart’ sync database that will automatically synchronise data between two or more connected synapses. It is a more powerful version of a sync database that can be used to synchronise an entire sync database across multiple Volt instances.

When two or more synapses are connected together, the Volt will monitor the underlying sync database for changes and automatically synchronise such that all connected synapses will have the same document content.

This is achieved by requiring that all documents in a given synapse have a schema. Most documents use Yjs shared types at the root (map, array, or text). Binary payloads use a blob document instead: the bytes live in a content-addressed store on the synapse, not in the CRDT.

As a reminder, every Yjs document can have multiple shared types defined at the root level, for example, YMap and YArray and YText. These are accessed using the relevant Yjs API method, for example:

const map = ydoc.getMap("my-map");
const array = ydoc.getArray("my-array");
const text = ydoc.getText("my-text");

By defining a schema for each of these top-level shared types, the Volt is able to deterministically detect when a document is modified and apply the changes to all other connected synapses.

Example

The following example demonstrates how to use a synapse to synchronise AIS vessel data across multiple Volt instances.

Setup

Note that the following example assumes that you have already created two Volts and have acquired connection credentials for them stored in ./volt-1.config.json and ./volt-2.config.json (see the Volt auth CLI command).

For the purposes of this example, we will assume that the Volt DIDs are did:volt:1 and did:volt:2 respectively.

To start, we need to create two synapses using the create-synapse command. Note that we pass the connection credentials for Volt 1 and Volt 2 to the command using the -c switch.

Terminal window
# Create a synapse with the alias @ais-synapse-1 on Volt 1
volt create-synapse "AIS vessel data" --alias ais-synapse-1 -c ./volt-1.config.json
Terminal window
# Create a synapse with the alias @ais-synapse-2 on Volt 2
volt create-synapse "AIS vessel data" --alias ais-synapse-2 -c ./volt-2.config.json

You can also use the fusebox to create synapses.

We now have two synapses, @ais-synapse-1 and @ais-synapse-2. We can connect them together using the create-synapse-connection command.

Below we connect synapse @ais-synapse-1 on Volt 1 to synapse @ais-synapse-2 on Volt 2. Note that we pass the connection credentials for Volt 1 to the command using the -c switch. In this case, the connection is created on Volt 1 and is owned by the identity in ./volt-1.config.json. It will attempt to authenticate on Volt 2 and establish a bi-directional synchronisation.

Terminal window
# Connect synapse @ais-synapse-1 on Volt 1 to synapse @ais-synapse-2 on Volt 2
volt create-synapse-connection @ais-synapse-1 did:volt:2 @ais-synapse-2 -c ./volt-1.config.json

You will need to ensure that Volt 2 has granted volt:database-write permission for @ais-synapse-2 to the Volt 1 identity. If Volt 2 only wants to share part of the synapse, it can grant access to a folder or to individual documents instead (see Sharing part of a synapse).

In the event of any connection errors, the synapse will periodically retry to establish the connection until it succeeds.

Schema definition

Next, we need to define the schema for the shared types that will be used to store the AIS vessel data.

For example, the following JSON schema defines a property schema that can be used to store AIS vessel data. Copy this to a file called ais-trace-schema.json for use in the next step.

{
"type": "object",
"additionalProperties": {
"type": "object",
"x-yrs-storage": "shared",
"properties": {
"MMSI": { "type": "number" },
"TSTAMP": { "type": "string" },
"LATITUDE": { "type": "number" },
"LONGITUDE": { "type": "number" },
"COG": { "type": "number" },
"SOG": { "type": "number" },
"HEADING": { "type": "number" },
"NAVSTAT": { "type": "number" },
"IMO": { "type": "number" },
"NAME": { "type": "string" },
"CALLSIGN": { "type": "string" },
"TYPE": { "type": "number" },
"DRAUGHT": { "type": "number" },
"DEST": { "type": "string" },
"ETA": { "type": "string" }
}
}
}

x-yrs-storage

Note the x-yrs-storage custom JSON schema property in the above schema. This tells the Volt that the data is stored as a YJS shared type rather than a plain JSON object. The default storage type is json. This property can be used at any level in the schema, but only if the parent object is also a shared type, i.e. a plain JSON object cannot have a sub-property that is a shared type. This is useful for optimising the synchronisation deltas. For example, if the schema above omitted the x-yrs-storage property, then every time the LATITUDE property is updated, the entire Southern Cross object would be synchronised to the other synapse, even if only the LATITUDE property changed.

A document that conforms to this schema would look like this:

{
"Southern Cross": {
"MMSI": 203035273,
"TSTAMP": "2024-11-19 20:10:00 GMT",
"LATITUDE": 39.92121,
"LONGITUDE": 7.60231,
"COG": 144.9,
"SOG": 4.7,
"HEADING": 149,
"NAVSTAT": 7,
"IMO": 9666865,
"NAME": "Southern Cross",
"CALLSIGN": "KMUJ",
"TYPE": 0,
"DRAUGHT": 0,
"DEST": "STARNMEER",
"ETA": "11-26 20:10"
},
"Harbor Master": {
"MMSI": 209083743,
"TSTAMP": "2024-11-19 20:05:00 GMT",
"LATITUDE": 44.6323,
"LONGITUDE": 16.52741,
"COG": 226,
"SOG": 15.6,
"HEADING": 231,
"NAVSTAT": 0,
"IMO": 9908828,
"NAME": "Harbor Master",
"CALLSIGN": "IMOP2",
"TYPE": 70,
"DRAUGHT": 0,
"DEST": "ROTTERDAM",
"ETA": "11-26 20:05"
},
...
}

We now use the synapse-set-metadata CLI command to set the metadata for the synapse document that will contain the AIS vessel data.

Terminal window
# Set the metadata for the synapse document that will contain the AIS vessel data on Volt 1
volt synapse-set-metadata @ais-synapse-1 00000000-0000-0000-0000-000000000123 aisTrace map /path/to/ais-trace-schema.json -c ./volt-1.config.json

Note we only need to set the metadata on one of the synapses. The metadata will be synchronised to the other synapse automatically.

Writing data to a synapse

Let’s write some AIS vessel data to the synapse document, using the synapse-write-path CLI command.

Terminal window
# Write some AIS vessel data to the synapse document on Volt 1
volt synapse-write-path @ais-synapse-1 00000000-0000-0000-0000-000000000123 $.aisTrace.SouthernCross '{"MMSI": 203035273, "TSTAMP": "2024-11-19 20:10:00 GMT", "LATITUDE": 39.92121, "LONGITUDE": 7.60231}' -c ./volt-1.config.json

The data will be synchronised to the other synapse automatically.

We could also write data to the other synapse, note here we write to the LATITUDE property of the Southern Cross vessel, and we use the Volt 2 configuration file.

Terminal window
# Write some AIS vessel data to the synapse document on Volt 2
volt synapse-write-path @ais-synapse-2 00000000-0000-0000-0000-000000000123 $.aisTrace.SouthernCross.LATITUDE 39.9377 -c ./volt-2.config.json

Watching for changes to a synapse

We can also watch for changes to the synapse document using the synapse-watch-path CLI command. This will set up a long-lived connection to the synapse and print out the changes as they happen.

Terminal window
# Watch for changes to the synapse document on Volt 1
volt synapse-watch-path @ais-synapse-1 00000000-0000-0000-0000-000000000123 $.aisTrace.SouthernCross -c ./volt-1.config.json

We can watch for changes to specific vessels or any vessel using the wildcard *.

Terminal window
# Watch for changes to any vessel's NAVSTAT property
volt synapse-watch-path @ais-synapse-1 00000000-0000-0000-0000-000000000123 $.aisTrace.*.NAVSTAT -c ./volt-1.config.json

The output will indicate the path that was updated and the new value.

This will print out the changes as they happen.

Using the YJS API

So far we have been using the CLI to interact with the synapse. However, we can also use the standard Volt API to interact with the synapse via any of the client libraries.

When using the client libraries, we usually treat the synapse as a regular sync database and use the SyncProvider class to synchronise the data. The synapse running on the Volt will automatically synchronise the data to all connected synapses.

import grpc from "@grpc/grpc-js";
import { VoltClient } from "@tdxvolt/volt-client-grpc";
import { SyncProvider } from "@tdxvolt/volt-client-grpc";
import * as Y from "yjs";
const configPath = "./volt.config.json";
const voltClient = new VoltClient(grpc);
await voltClient.initialise(configPath);
const ydoc = new Y.Doc({ guid: "00000000-0000-0000-0000-000000000123" });
const syncProvider = new SyncProvider(Y, voltClient, "@ais-synapse-1", ydoc);
let aisTraceMap;
syncProvider.on("status", ({ status }) => {
if (status === "connected") {
console.log("connected");
aisTraceMap = ydoc.getMap("aisTrace");
aisTraceMap.observe((event) => {
// Handle change event.
});
aisTraceMap.set("Southern Cross", {
MMSI: 203035273,
TSTAMP: "2024-11-19 20:10:00 GMT",
LATITUDE: 39.92121,
LONGITUDE: 7.60231,
});
} else {
console.log("disconnected");
}
});
syncProvider.startSync();

When writing data via the YJS API, as long as the data you write to the document conforms to the schema defined for the shared type, it will be synchronised to all connected synapses automatically. When using the YJS API, the synapse won't be able to prevent you from writing data that doesn't conform to the schema, but it might not be synchronised to other synapses.

Only write values that have changed

Every write to a YJS shared type is recorded in the document’s history, even when the new value is identical to the value already stored. Overwriting LATITUDE with the value it already holds still creates a new entry and a tombstone for the old one, and neither can be reclaimed while the containing map is alive. For data that is updated continuously, such as a feed that re-sends the full record on every tick, unchanged values add memory use, storage, and sync traffic for no benefit.

When using the YJS API, compare each value with the current one and only call set when it differs:

function setIfChanged(map, key, value) {
if (map.get(key) !== value) {
map.set(key, value);
return true;
}
return false;
}
ydoc.transact(() => {
const vessel = aisTraceMap.get("Southern Cross");
for (const [key, value] of Object.entries(record)) {
setIfChanged(vessel, key, value);
}
});

Note that !== only compares primitives (strings, numbers, booleans) correctly. For object or array values, compare their contents, for example with JSON.stringify on both sides or a deep-equality helper.

The Volt applies the same rule when you use the WriteSynapsePath API: values that already equal the stored value are not written, and a write that changes nothing produces no update to the document at all. Numbers are compared by value, so writing 1.0 over a stored 1 is treated as unchanged. A change of type, for example writing the string "1" over the number 1, is always written.

This does not apply to writes made through the YJS API: an update sent by a client is applied exactly as received, so it is the client’s job to avoid sending unchanged values.

Using the synapse API

The section above utilised the YJS API to read and write data to the synapse.You can also use any of the synapse API methods via the client libraries.

To set the metadata for a shared type use the SetSynapseDocumentMetadata API.

const request = {
synapse_id: "@ais-synapse-1",
document_id: "00000000-0000-0000-0000-000000000123",
metadata: [
{
name: "aisTrace",
type: "map",
json_schema:
'{"type":"object","additionalProperties":{"type":"object","x-yrs-storage":"shared","properties":{"MMSI":{"type":"number"},"TSTAMP":{"type":"string"},"LATITUDE":{"type":"number"},"LONGITUDE":{"type":"number"},"COG":{"type":"number"},"SOG":{"type":"number"},"HEADING":{"type":"number"},"NAVSTAT":{"type":"number"},"IMO":{"type":"number"},"NAME":{"type":"string"},"CALLSIGN":{"type":"string"},"TYPE":{"type":"number"},"DRAUGHT":{"type":"number"},"DEST":{"type":"string"},"ETA":{"type":"string"}}}}',
},
],
};
const response = await voltClient.SetSynapseDocumentMetadata(request);
console.log(response);

To write data to a synapse use the WriteSynapsePath API.

const request = {
synapse_id: "@ais-synapse-1",
document_id: "00000000-0000-0000-0000-000000000123",
path: "$.aisTrace.SouthernCross.LATITUDE",
json: 39.9377,
};
const response = await voltClient.WriteSynapsePath(request);
console.log(response);

To watch for changes to a synapse use the WatchSynapsePath API.

const request = {
start: {
synapse_id: "@ais-synapse-1",
document_id: "00000000-0000-0000-0000-000000000123",
path: ["$.aisTrace.*.LATITUDE", "$.aisTrace.*.LONGITUDE"],
},
};
const watchStream = await voltClient.WatchSynapsePath(request);
watchStream.on("data", (response) => {
console.log(response);
});
watchStream.on("end", () => {
console.log("watch ended");
});
watchStream.on("error", (err) => {
console.log(err);
});

The synapse API methods will enforce the schema defined for the shared type and will fail if the data you write doesn't conform to the schema.

Documents, folders and paths

Every document in a synapse has an entry in the synapse metadata. As well as the schema, the entry can carry application-specific JSON (the json field of SetSynapseDocumentMetadata). The path key of that JSON places the document in the synapse’s folder hierarchy:

{ "path": "slides/index.html" }

A path is normalised, / separated, and has no leading or trailing / and no empty, . or .. segments. A synapse has no folder resources of its own. A folder exists in one of two ways:

  • Implicit folder - a folder that exists only because one or more visible documents have paths beneath it. It has no document id and disappears when the last document beneath it is removed.
  • Explicit folder - a document whose schema is a single entry of type folder, with the folder’s path in json. It has no content, is ready immediately, and persists when empty.

A document that holds binary content (a file, for example) has a single schema entry of type blob. Its content is stored as a content-addressed object in the synapse blob store rather than as a YJS shared type. See Blob documents.

The VoltDrive file system is built on these paths.

Listing a synapse

A synapse can hold a lot of documents, and the caller may be allowed to see only some of them. The synapse index reports what the caller may see, without reading the synapse metadata document directly (which a caller with a partial share cannot do).

  • ListSynapseIndex returns the entries beneath a folder, one page at a time. Set recursive to include everything beneath the folder rather than only its direct children.
  • WatchSynapseIndex sends the current entries as a snapshot, then a single OK status to mark the end of the snapshot, then every change. Use path_prefix to limit the watch to a folder.

Each entry has a kind (document, folder or implicit_folder), its path, its schema and JSON, and its content hash. Set include_writable on the request to have the Volt also report, in the writable field, whether the caller may modify each entry.

An update from WatchSynapseIndex lists entries that were added or changed (upserts) and entries that went away (removals). Apply the removals before the upserts. A removal has a reason:

ReasonMeaning
DELETEDThe document or folder was deleted.
NO_LONGER_VISIBLEThe entry still exists, but the caller can no longer see it. Access was revoked or the entry moved out of the caller’s scope. Do not delete anything in response.
const request = {
start: { synapse_id: "@ais-synapse-1", include_writable: true },
};
const watchStream = await voltClient.WatchSynapseIndex(request);
watchStream.on("data", (response) => {
if (response.update) {
// Apply response.update.removals, then response.update.upserts.
} else if (response.status) {
// An OK status marks the end of the initial snapshot.
}
});

Document content state

The synapse metadata and the content of a document replicate independently. The metadata describes the content with a hash (__hash), but a Volt may learn that a document exists before its content has arrived. Use GetSynapseDocumentState or WatchSynapseDocumentState to find out whether this Volt holds the content yet.

StateMeaning
ABSENTThere is no metadata entry for the document on this Volt.
DRAFTThe entry exists but no hash has been published, so no content has been committed.
ANNOUNCEDA hash is published, but the content this Volt holds does not match it yet. The content is still arriving from another Volt. Wait for READY before reading it.
READYThe content held by this Volt matches the published hash. The document can be read.
DELETEDThe metadata entry was removed.

A document can be ANNOUNCED on one Volt and READY on the Volt that produced it. If you create a document and want its hash published straight away, because the content already exists or the document is intentionally empty, set publish_hash in SetSynapseDocumentMetadata. Otherwise the Volt publishes the hash when the content arrives.

To watch every document the caller may read, including a caller with a partial share, set visible_only on the watch and leave document_id empty.

Blob documents

A blob document stores an opaque binary payload in the synapse blob store. There is no Yjs shared type for a blob: the document’s schema is a pointer to bytes that are addressed by their hash, and those bytes are transferred with dedicated blob RPCs rather than SyncDocument.

Use a blob document when the payload is a file (or other byte sequence) that should be replaced as a whole. Use map, array, or text roots when the data is structured JSON or collaboratively edited text.

VoltDrive uses blob documents for binary files and Y.Text documents for text files. The same blob APIs are available to any synapse client, not only VoltDrive.

Schema

A blob document’s __schema must be a single entry of type "blob". It cannot be mixed with map, array, or text roots, and a document cannot have more than one blob root.

const response = await voltClient.SetSynapseDocumentMetadata({
synapse_id: "@ais-synapse-1",
document_id: "photo-001",
metadata: [{ name: "content", type: "blob" }],
blob_hash: hash,
});

blob_hash is only valid on blob documents. For map, array, and text documents the server computes __hash from the Yjs content.

Content addressing

The blob hash is SHA-256 of the raw payload bytes, encoded as unpadded base64url. That value is both the blob store key and the document’s __hash once the document is bound.

Empty payloads are a special case: they are never written to the blob store. Binding a document to the SHA-256 of empty bytes is enough; every replica already holds that content.

Puts are idempotent. If the hash is already stored, PutSynapseBlob is a no-op. The server verifies that the received bytes match hash (and size) before committing a new blob.

APIs

MethodRole
HasSynapseBlobCheck whether a hash is already stored.
PutSynapseBlobUpload bytes. First message is start (synapse_id, hash, size); later messages are payload chunks.
GetSynapseBlobDownload bytes by hash.
SetSynapseDocumentMetadataDeclare the blob schema and, when the bytes are already stored, bind them with blob_hash.

WriteSynapsePath, WatchSynapsePath, and SyncDocument do not apply to blob documents. Path writes and Yjs sync operate on map, array, and text roots only.

Create and bind

Typical content-first flow:

  1. Hash the payload (sha256 of the raw bytes, unpadded base64url).
  2. Call HasSynapseBlob. Skip the upload if exists is true, or if the payload is empty.
  3. Otherwise stream the bytes with PutSynapseBlob.
  4. Call SetSynapseDocumentMetadata with a single type: "blob" entry and blob_hash set to that digest. The server checks that the blob is stored (or that the hash is the empty digest) and writes __hash.

You can also create the metadata first and omit blob_hash. The document stays in draft until a later call binds it to a stored blob.

See Store binary data for a worked example.

Replication and document state

Synapse connections replicate blob payloads with the same Has / Get / Put RPCs. Metadata (__schema, __hash) still travels with the synapse meta document, so a replica can learn of a blob before it holds the bytes.

GetSynapseDocumentState and WatchSynapseDocumentState report whether this Volt holds the content advertised by __hash:

  • DRAFT — metadata exists, but __hash has not been published yet.
  • ANNOUNCED — __hash is published, but this Volt does not yet hold matching content.
  • READY — this Volt holds the payload (the blob is in the local store, or the hash is the empty digest).

Wait for READY before reading a blob document. For a blob, READY means the bytes are in the blob store; nothing is hashed from a Yjs document.

Blobs and documents

The blob APIs can be tied to a document:

Each request can carry the document_id of the document the blob belongs to. When it does, access is checked against that document rather than the whole synapse, so a share limited to that document is enough. When you upload with a document_id and the blob document already exists, the Volt binds the stored blob to it for you, as if you had called SetSynapseDocumentMetadata with blob_hash. A client that is cut off after the upload therefore doesn’t leave the document waiting for its content.

Permissions

HasSynapseBlob and GetSynapseBlob require volt:database-read on the synapse (volt:database-write also implies read). PutSynapseBlob and SetSynapseDocumentMetadata require volt:database-write.

Sharing part of a synapse

Access to a synapse is controlled by the volt:database-read and volt:database-write permissions on the synapse resource, as for any sync database. Write access to a document implies read access to it.

A share does not have to cover the whole synapse. In addition to a whole-synapse share, access can be limited to:

  • A document, by its id.
  • A folder, by its path. The share covers the documents inside the folder and all its sub-folders, as well as any explicit folder document at the folder’s path.
  • Documents matching an attribute, such as the document type or creator.

These are expressed as extra resource attributes on the share rule. The attributes the policy can match on are described in Policy.

For example, giving someone volt:database-write on the slides folder lets them create, modify and delete documents in slides and its sub-folders. They can’t see or change anything outside it. Their writes are authorised against the path being written, so a document can’t be moved out of the folder to somewhere they have no access.

The creator of a document is also given read and write access to it.

Because the synapse metadata document describes every document, only the owner of a synapse normally needs access to it. A caller with a partial share never needs it. They read the synapse through the synapse index and the document state APIs, which report only what that caller may see.

Connecting to a partly shared synapse

A synapse connection normally mirrors the remote synapse’s whole metadata document. If the remote Volt has shared only a folder or some documents with the connection’s identity, it refuses that document. The local Volt then switches to scoped replication:

  • It watches the remote’s synapse index, which lists only the entries the identity may see.
  • It writes each visible entry into its own copy of the synapse metadata. The rest of the connection works as it does for a full replica: document content and blobs sync, and a local VoltDrive shows the files.
  • The local copy of the metadata is a projection of what the remote currently shows. It is rebuilt from the index whenever the connection starts, and it is never synchronised back as a whole.

The connection resource records this. The volt:synapse-connection-scoped attribute is true while the connection is replicating only part of the synapse, and is removed when the remote grants the whole synapse. Fusebox and VoltDrive Explorer display it as a partial share.

If the remote doesn’t share anything with the connection’s identity, the connection reports the error no documents in the remote synapse are visible to this connection in its volt:synapse-connection-error attribute and keeps retrying.

When a connection restarts, the Volt first checks whether the remote now grants the whole metadata document, using a read-only probe. It keeps the existing projection if not, so a restart does not discard it, and only resets the projection if the whole synapse is now shared. If the identity loses access to something, that entry is removed from the local copy. The data stays on the remote, and nothing is deleted there.

Read-only and writable documents

Which documents a connection may change depends on the remote’s grants. The index reports this per entry (writable):

  • Writable documents can be created, modified and deleted locally, like any document in a synapse.
  • Read-only documents can be read but not changed. Because nothing written to them could reach the remote, the local Volt refuses writes to them with a permission error, even for a local identity that would otherwise have volt:database-write. The index reports them as not writable.

A client that opens a read-only document for editing is refused. To show its content anyway, set read_only_fallback on the sync request. The Volt then opens the document read-only if the caller can’t write to it, and reports is_read_only in the first response. The client libraries expose this as the readOnlyFallback option of SyncProvider, and isReadOnly once the document has started syncing.

const syncProvider = new SyncProvider(Y, voltClient, "@ais-synapse-1", ydoc, {
readOnlyFallback: true,
});
syncProvider.on("sync", () => {
if (syncProvider.isReadOnly) {
// Show the content, but don't offer editing.
}
});

Changes made in a scoped replica

A change made through a scoped replica, such as creating a file in a drive, renaming it or deleting it, is applied locally and then sent on to the remote with SetSynapseDocumentMetadata or DeleteSynapseDocumentMetadata, as the connection’s identity. Document content is written through the usual sync stream.

  • If the remote accepts the change, nothing more happens.
  • If the remote refuses it, because access was denied or the request is invalid or conflicts with what is there, the local change is reverted. A refused modification restores the previous schema and JSON, a refused deletion restores the entry, and a refused creation removes it. From the caller’s point of view the change happens and then undoes itself shortly after, so a client that wants to know the outcome should check the index again.
  • If the change fails for any other reason, such as a dropped connection, the Volt retries it with a delay between attempts for as long as it is running.

Pending changes are held in memory only. A change that hasn’t reached the remote when the Volt stops is lost, and the local copy is brought back in line with the remote the next time the connection starts. Make changes while the connection shows as connected.