Skip to content

Sobamail Runtime Reference

Imports

On the Sobamail platform, every module names a hash in its import statements. This guarantees that the code is reproducible from the root module down to the last leaf of the import tree. The hash is the Sha224 digest of the module's source code, encoded in "urlsafe base64".

This Python script generates the import hash of a script file:

import base64
import hashlib
import sys

for fn in sys.argv[1:]:
    with open(fn, "rb") as f:
        digest = hashlib.sha224(f.read()).digest()
    digest_b64 = base64.urlsafe_b64encode(digest) \
        .replace(b"=", b"") \
        .decode("ascii")
    print(f"{fn}: ?sha224={digest_b64}")

The ?sha224= value is read in urlsafe base64, as above, or in base32hex.

How a module resolves

  • Every imported module declares export const namespace, a string equal to its own import URL. The runtime refuses an imported module whose declaration is missing, is not a string, or differs from the URL that imported it (error 529). No URL imports the root module, and it declares no namespace: its namespace is https://<appid>, where appid is the id its default export declares.
  • The first import of a mutator is the computer, soba://computer/R2. The runtime refuses a mutator that imports no computer, imports it after another module, or names a computer the platform does not provide. A module the mutator imports needs no computer import of its own. One that names a computer the platform does not provide refuses the app the same way.
  • A deployed app's module resolves by its hash alone: the file <basedir>/apps/code/<b32hex[0:2]>/<b32hex[2:]>.mjs, where b32hex is the hash in base32hex. The base module is built into the runtime. The runtime refuses these imports, each with its own code:
    • a hash under which no module is installed (516),
    • a file whose contents do not match the hash (537),
    • a malformed hash (531),
    • a root module whose contents do not match the instance's root hash (538).
  • A refused import is a refused initialization. The run ends with PR_ErrInitContext (4) whatever the fault, and nothing of the app runs. The runtime writes the fault's own code and message to its log.

Developer mode

A developer-mode instance is one with no root hash. Its root module is <basedir>/apps/devel/<appid>/Mutator.mjs. The runtime takes a module under the same tree at <basedir>/apps/devel/<appid>/<host><path>.mjs under any hash or none. Every other import, the base module's included, resolves and is checked exactly as in a deployed app.

Special JS Primitives

ArrayBuffer (Tagged)

The Sobamail runtime adds a special type of ArrayBuffer, which the soba.data.* family of functions returns. These buffers are mutation handles, not literal binary blobs.

A tagged buffer holds the mutation's hash, 64 bytes of SHA-512, and passes instanceof ArrayBuffer. The functions under soba.binary take a Uint8Array, not an ArrayBuffer, so view it before encoding or comparing it:

const {hash} = soba.data.find("channel", {uuid});
const text = soba.binary.b64Encode(new Uint8Array(hash)); // 88 characters

A call with the buffer itself fails with "Arg 1 must be a Uint8Array".

Execution Context

Runtime functions execute in either a replicated or a non-replicated context, as described under Mutations. A non-deterministic function cannot run while the app processes a replayable mutation. This reference flags such functions with the [NR] marker. A function without the marker can run in either context. soba.app.isReplicated() tells the current context at runtime.

What process() receives

The runtime calls the Mutator's process(message, metadata) once per event. message holds the event in one of these shapes, and soba.app.objectKey() answers its object key:

  • An email: an instance of the base module's Message class. Its object key is {https://sobamail.com/module/base/v1}Message.
  • A Structured Message: an instance of Message too, whose bodyObject.content is the SMC document the message carries, a plain Object of the keys namespace, name and content. Its object key is the document's. A Structured Message arrives this way from both routes: as email, or posted to the object route by the app's user interface (smc.md).
  • A signal: an SMC object the platform hands the app directly, without an email.
  • A task: an SMC object queued for the app in the mailbox, handed to the app from the queue.

A signal and a task are each a plain Object of the keys namespace, name and content, its object key the object's. A request from the app's user interface (smc.md) arrives in that shape too.

A Structured Message that came in as email is transport for the object it carries. Once at least one app instance processes it, the platform deletes the message from the mailbox, in every replica. What the app keeps of it is what process() wrote. A message that no instance took stays in the mailbox, and so does one taken only by instances the server does not run.

An app can be the first in the mailbox to list an object key. The platform then hands it the Structured Messages already in the mailbox that carry that key, the way it hands a newly arrived one.

A binary value of the document arrives as an ArrayBuffer, byte for byte as the sender packed it. This holds inside a signed or encrypted Envelope as much as in a bare document or a request.

API Reference

soba.app.account() [NR]

Returns the account of the current mailbox.

Return Value:

  • String: The account name in email address format.

soba.app.instanceId()

Returns the instance id of the current application instance.

Return Value:

  • String: The instance id.

soba.app.isReplicated()

Tells whether the object key at hand is replicated. Replicated objects are the ones that appear in the insertEvent attributes or the DeleteRow object.

Return Value:

  • Boolean: true if the object at hand is replicated, false otherwise.

soba.app.objectKey()

Returns the triggering object key.

Return Value:

  • String: The object key: the namespace URI in curly braces followed by the object's name, {namespace}Name.

soba.app.replicaUuid() [NR]

Returns the uuid of the current mailbox replica in braced hexadecimal uuid format.

Return Value:

  • String: The replica uuid, in braced hexadecimal uuid format.

soba.app.users() [NR]

Returns the list of users that share this app instance.

Return Value:

  • String[]: An array of email address strings.

soba.data.delete(table, hash)

Deletes data from the specified table and generates a DeleteRow mutation with a happens-before relationship with the mutation in the insertEvent attribute.

Rows of other tables whose fk check names the deleted row go with it, by the constraint's ON DELETE CASCADE. The cascade generates no mutation: the deleted row's DeleteRow is the only one, and every replica replaying it cascades the same way.

The call refuses a hash that names no row of the table: it throws and writes nothing. A delete of a row that is already deleted, by the same handle, is a no-op: the call throws nothing and generates no mutation. The runtime ignores an update() that reaches a deleted row. So a delete and an update of the same row, made concurrently on two replicas, leave the row deleted on both. Mutations are idempotent (concepts): the same mutation made again, a delete as much as an insert, is the one already in the log.

Parameters:

  • table (String): The name of the table.
  • hash (ArrayBuffer): The hash of the row entry to be deleted, as returned by the find() or insert() function. The call accepts any ArrayBuffer. It need not be a tagged mutation handle.

soba.data.exists(table, object)

Tells whether an insert mutation that matches the query is in the mutation log. If no matching insert mutation ever existed in the mutation log, the call throws a fatal exception. A matching mutation that existed but was later deleted comes back with its deleted flag set (see below).

The exception is fatal: the run ends as one that threw even when the app catches it, and every later soba.data call of the run throws. So a miss refuses the object at hand.

The call is the read for replicated context, where soba.db.exec() throws: an app uses it to check a precondition while it processes a replicated object. In non-replicated context soba.db.exec() is the general read, and it lets the app go on after a miss. A check that a sender holds a role is such a precondition:

if (soba.app.isReplicated()) {
    // `role` is lww over (userName, name): the call throws unless that row
    // was ever inserted
    const {deleted} = soba.data.exists("role", {userName, name : "Admin"});
    if (deleted) {
        throw new Error(`'${userName}' is an Admin no longer`);
    }
}

Parameters:

  • table (String): The name of the table.
  • object (Object): The query object used to search for the data. The keys name any columns of the table. No lww column is required. A row matches when every named column holds the given value. The call throws for a key that names no column of the table.

A query that names a complete lww key of the table, as find() takes it, also finds a deleted row and flags it. A query that names no complete lww key matches live rows only: its deleted is always false, and the call throws when none of them is live.

Return Value:

Returns an object with the following attributes:

  • found (bool): Always true. The call throws when the query matches no insert mutation.
  • deleted (bool): true if the matching insert mutation exists but another mutation later deleted it, false if the row is still live. When the query matches several rows, deleted is false as long as one of them is live.

soba.data.find(table, object)

Retrieves the mutation hash from the specified table based on the query. An app uses it for deterministic yet dynamic happens-before relationships with other mutations. If no matching insert mutation ever existed in the mutation log, the call throws a fatal exception. A matching mutation that existed but was later deleted comes back with its deleted flag set (see below).

The call itself orders the mutation in progress after the one it found. On every replica, the new mutation waits until the found one is applied. That is a plain happens-after relation, for cases where only the order matters and the found row's content does not. A chat message that follows the one it replies to is such a case. Unlike an fk or lww parent, or the parent of an update(), the runtime records this edge outside the mutation's parent hashes. So the edge leaves the mutation's hash, and with it its identity, unchanged.

Parameters:

  • table (String): The name of the table.
  • object (Object): The query object used to search for the data. The keys name a complete lww key of the table: the column of a single-column lww check, or every column of a multi-column lww check together. Further keys may name any other column of the table. A row matches when every named column holds the given value.

Return Value:

Returns an object with the following attributes:

  • object (Object): The matching insert mutation's object, as the string-keyed SMC it was recorded as: namespace and name are the table's insertEvent class's, and content is the row as inserted, a mapping from column names to values. For a row of the item table whose insertEvent is Item:

    {
        namespace : "https://example.com/model/v1",
        name : "Item",
        content : {name : "a", value : 1},
    }
    
  • hash (ArrayBuffer (Tagged)): The hash of the data that matches the query.

  • deleted (bool): true if the matching insert mutation exists but another mutation later deleted it, false if the row is still live.
  • signer (String or null): The sender of the signed Envelope the matching insert mutation's object arrived in: the address whose signature the Envelope carries. null if the object arrived in no signed Envelope. The attribute is always present. object is the same in both cases: the object itself, never the Envelope around it.

A mutation has a signer when the app inserted the row as the signed Envelope its object arrived in. The runtime takes an Envelope in insert() for a table whose insertEvent class declares static MUST_BE_SIGNED = true. It records the object as the mutation and keeps the Envelope beside it, and the Envelope replicates with the mutation. So signer answers the same address on every replica:

const {signer} = soba.data.find("role", {userName});
if (signer !== null) {
    // the row is the word of `signer`
}

soba.data.findLast(table, object) [NR]

Retrieves the last mutation hash from the specified table based on the query. An app uses it for non-deterministic happens-before relationships with other mutations. Because the result is not deterministic, this function throws in replicated context.

Parameters:

  • table (String): The name of the table.
  • object (Object): The query object used to search for the data. The keys name any columns of the table. No lww column is required, because the call answers the newest matching row even when the query does not identify a single row. A row matches when every named column holds the given value.

Return Value:

Returns an object with the following attributes:

  • object (Object): The matching insert mutation's object, {namespace, name, content}, exactly as find() returns it.
  • hash (ArrayBuffer (Tagged)): The hash of the data that matches the query.
  • deleted (bool): true if the matching insert mutation exists but another mutation later deleted it, false if the row is still live.
  • signer (String or null): The sender of the signed Envelope the matching insert mutation's object arrived in, or null, exactly as find() returns it.

soba.data.insert(table, data)

Inserts data into the specified table.

Parameters:

  • table (String): The name of the table.
  • data (Object): The data to be inserted. Must be a mapping from column names to values of type (String,Number,ArrayBuffer) or value null. A Boolean is recorded as the Number 1 or 0: the mutation carries the integer, and the column stores it as it stores any Number. A BigInt is accepted as long as its value fits a signed 64-bit integer (-2^63 to 2^63-1). The call refuses one outside that range. A column whose fk check targets a table's id takes the parent row's mutation handle (ArrayBuffer (Tagged)).

Return Value:

Returns an object with the following key:

  • hash (ArrayBuffer (Tagged)): The hash value of the inserted mutation.

An insert identical to one already in the log generates no new mutation: mutations are content-addressed (concepts), and hash is the existing mutation's.

A signed insert:

A table whose insertEvent class declares static MUST_BE_SIGNED = true takes the signed Envelope its row arrived in as data:

class Role {
    static KEY = `{${namespace}}Role`;
    static MUST_BE_SIGNED = true;
}

// in process(), `root` the SMC document of a message whose root is an Envelope
if (root.name == "Envelope") {
    soba.data.insert("role", root.content);
}

data is then the content of the Envelope: a plain Object of the Envelope's fields, with the object it carries, {namespace, name, content}, under content. That is the shape the root of a signed message has, and the shape soba.mail.verifyEnvelope() takes. The carried object is the row: its content maps column names to values.

The runtime records the carried object as the mutation, exactly as it records a plain insert, and keeps the Envelope beside it. The mutation's hash is the object's, so the Envelope leaves the mutation's identity unchanged. The Envelope replicates with the mutation, and find() returns its sender as signer on every replica.

The data the Envelope signs must be the mutation's own document: the SMC of the row in MessagePack with integer keys, byte for byte. The call throws for an Envelope whose signed data differs, a string-keyed document among them. So the signer signs the document the runtime would record for that row.

Such a table takes a signed Envelope and nothing else. The call throws for a plain row, a mapping from column names to values, and writes nothing.

The signed object names every column of the table, with null for a column that has no value. The mutation is the signed bytes themselves, so the row must serialize to exactly those bytes. The call throws, and writes nothing, for an object that leaves a column out, although a plain row may leave one out.

The call verifies the Envelope itself, in either context. It throws, and writes nothing, for an Envelope that has no signature, for one whose signature does not verify, and for one whose sender is not the address the signature belongs to.

For a table whose insertEvent class declares no MUST_BE_SIGNED, the runtime reads the same data as a row, and the call throws because the table has no column named after an Envelope field.

Note

The returned object also carries inserted and applied boolean fields. They are reserved and currently carry no meaning. Do not rely on them.

soba.data.missing(table, object)

Tells that no live row matches the query. It is the opposite of exists(): if a matching row is live, the call throws a fatal exception. A matching row that existed but was later deleted comes back with its deleted flag set (see below).

The exception is fatal: the run ends as one that threw even when the app catches it, and every later soba.data call of the run throws. So a hit refuses the object at hand.

The call runs in replicated context, where soba.db.exec() throws: an app uses it to check, while it processes a replicated object, that a row is absent. In non-replicated context soba.db.exec() is the general read, and it lets the app go on after a hit. A check that a grant is the first one for its key is such a precondition:

// `role` is lww over (userName, name): the call throws while that row is live
const {deleted} = soba.data.missing("role", {userName, name});
if (deleted) {
    throw new Error(`'${userName}' held '${name}' before`);
}
soba.data.insert("role", {userName, name});

Parameters:

  • table (String): The name of the table.
  • object (Object): The query object used to search for the data. The keys name any columns of the table. No lww column is required. A row matches when every named column holds the given value. The call throws for a key that names no column of the table. That exception is an ordinary one: the app may catch it and go on.

A query that names a complete lww key of the table, as find() takes it, also sees a deleted row and flags it. A query that names no complete lww key matches live rows only: its deleted is always false. When the query matches several rows, the call throws as long as one of them is live.

Return Value:

Returns an object with the following attributes:

  • found (bool): true if a matching insert mutation exists in the mutation log, false if none ever existed. The call throws when the query matches a live row, so a found row is a deleted one.
  • deleted (bool): true if a matching insert mutation exists but another mutation later deleted it, false otherwise.

soba.data.missing(table, hash)

Tells that the row one insert mutation wrote is not live. The call takes the hash of that mutation in place of a query. It answers for that mutation alone, whatever became of the row's lww key since: a row that was deleted stays deleted for its hash after another insert makes the key live again.

If the row the mutation wrote is live, the call throws the same fatal exception as the query form. An app uses the call to check that the row a new row replaces was deleted first:

// `previous` is the hash of the insert this grant replaces
const {deleted} = soba.data.missing("role", previous);
if (! deleted) {
    throw new Error("the grant this one replaces was never revoked");
}

Parameters:

  • table (String): The name of the table.
  • hash (ArrayBuffer): The hash of an insert mutation of the table, as find() or insert() returns it. The call accepts any ArrayBuffer. It need not be a tagged mutation handle.

Return Value:

Returns an object with the following attributes:

  • found (bool): true if the table has an insert mutation of that hash, false if it has none.
  • deleted (bool): true if that insert mutation exists but another mutation later deleted its row, false otherwise.

soba.data.update(table, operation, extra)

Applies a relative update to a single column of an existing row. The update describes an operation (op) that the runtime applies to one column of the row the parent mutation handle identifies. The rest of the row stays as it is. The update establishes a happens-before relationship with that parent mutation, so concurrent updates compose deterministically across replicas.

The runtime assumes every update is commutative and applies whatever operator it is given. Replicas apply concurrent updates from different replicas in any order, and the values converge only when the operations commute (addition, multiplication). A commutative operation is the app's responsibility. The runtime does not check the operator, so it applies a non-commutative one (subtraction, division) too. Replicas that receive such updates in different orders end up with different values.

The runtime ignores an update whose row a DeleteRow deleted, before it or concurrently with it. The row is already gone, and every replica ends with it gone, whichever of the two it applied first.

Parameters:

  • table (String): The name of the table.
  • operation (Object): The update to apply.
    • parent (ArrayBuffer (Tagged)): The mutation handle of the row to update, as returned by find(), findLast(), or insert().
    • column (String): The name of the column to update.
    • op (String): The operator to apply, e.g. "+" to add value to the current column value.
    • value (Any): The operand for op. A Boolean operand travels in the mutation as the integer 1 or 0.
  • extra (Object): More fields merged into the generated mutation but not written to the table. The mutation carries them under its key 4 (contentAux). An app typically carries a fresh uuid here (see soba.type.uuid.v4()) so that otherwise-identical updates are not deduplicated by their hash. A Boolean among them is in the mutation as 1 or 0.

Example:

soba.data.update("counter", {
    parent : parent.hash,
    column : "value",
    op : "+",
    value : content.value,
}, {
    uuid : soba.type.uuid.v4(),
});

soba.schema.table(defn)

Creates a table in the local SQLite database with the specified options.

Call it from the Mutator constructor. It throws anywhere else.

Parameters:

  • defn (Object): The definition object for the table. A table is declared once: the call refuses a name the instance already has a table of, whatever the second declaration's events and columns. Every table carries an id column beside the declared ones: an integer primary key the runtime assigns on each replica (a row id, which the fk bullet's id target names).

    • name (String): The name of the table.
    • insertEvent (Class): Mutation object generated on row insertion
    • deleteEvent (Class): Mutation object generated on row deletion. Must be DeleteRow object from the Base.mjs module.
    • columns (Array): An array of column definitions.

      • name (String): The name of the column.
      • checks (Array): An array of single column check objects.

        • op (String): The check operation to be performed. One of: ["==", "!=", ">", ">=", "<", "<=", "typeof", "in", "fk", "lww", "regexp"]

          These values mean the following:

          • ==: The equals constraint: The incoming value must be a constant equal to the value stored in the value key. A SQLite CHECK constraint enforces this, so consult the SQLite docs for exact semantics.

          • !=: The not equals constraint: The incoming value must be a constant not equal to the value stored in the value key. A SQLite CHECK constraint enforces this, so consult the SQLite docs for exact semantics.

          • >, >=, <, <=: The comparison constraints: The incoming value must be greater than, greater than or equal to, less than, or less than or equal to the value stored in the value key. A SQLite CHECK constraint with the operator of the same name enforces each, so the comparison follows SQLite's rules for the column's affinity. Consult the SQLite docs for exact semantics.

          • typeof: The type-of constraint: The type of the incoming value must equal the value stored in the value key. The accepted values for this constraint are: ["blob", "integer", "null", "real", "text"]. A SQLite CHECK constraint with SQLite's typeof operator enforces this, so consult the SQLite docs for exact semantics.

          • in: The in constraint: The incoming value must be equal to one of the values stored in the Array inside the value key. A SQLite CHECK constraint with SQLite's IN operator enforces this, so consult the SQLite docs for exact semantics.

          • fk: The foreign key constraint: The incoming value must be equal to one of the values stored in the given column of the given table. A SQLite FOREIGN KEY ... ON DELETE CASCADE constraint enforces this. The constraint establishes a happens-before relation between the insert mutation of the target table and the insert mutation at hand. So a replica that lacks the parent mutation does not execute the mutation at hand.

            The target column carries an lww check, or is the table's id (below): soba.schema.table() refuses a target without one. The runtime looks the target table up by its exact name: Item does not find item. A column may name its own table: the row it names is one an earlier insert made, never the row that this insert makes.

            A null in an fk column, or the column omitted, establishes no happens-before relation. The runtime inserts the row with null there and requires no parent row. The mutation records no parent edge for that column, and a delete of any target row leaves the row in place.

            A delete of the target row deletes the rows that reference it, on every replica, through the cascade alone. The one DeleteRow mutation is the target row's, and a cascaded row gets no DeleteRow of its own. A replica that replays the target's DeleteRow cascades the same way, so the mutation log holds one tombstone for the whole cascade.

            The target column may be the target table's id. A row id is replica-local (SQLite's ROWID, which differs from replica to replica), so it stays out of every mutation's hash. The app sets such a column to the parent row's mutation handle, the hash that find() or insert() returns. The runtime writes this replica's id of that row into the table row and records the handle's digest as the mutation's parent edge. The mutation's content carries no value for the column. A replica that replays the mutation resolves the edge to its own copy of the parent row and writes that row's id there.

          • lww: The last-write-wins constraint: The incoming value must be different from one of the values stored in the given column of the current table. A null is a value like any other here: an insert whose lww column is null, or omits it, matches the row that holds null there and replaces it the way a repeated value does. Null, 0 and "" are three distinct values. A SQLite UNIQUE constraint enforces this. A column carries one lww check: soba.schema.table() refuses a column that declares it twice. This constraint establishes a happens-before relation between the insert mutation at hand and a DeleteRow mutation, if one exists, by these rules:

            • If the value is missing from the table:

              • If the mutation log holds no DeleteRow mutation for the same value, no causal relationship stems from the LWW constraint.

              • If the mutation log holds a DeleteRow mutation for the same value, the new insert mutation gets a happens-before relationship with that old delete mutation.

            • If the value is present on the table:

              • If the digest of the new insert mutation matches the previous insert mutation's, the runtime ignores the current insert.

              • If the digest of the new insert mutation does not match the previous insert mutation's, the runtime generates a DeleteRow mutation for the column value of the previous insert mutation. It then generates the new insert mutation with a happens-before relationship with this new DeleteRow mutation.

            Two inserts of the same lww value made concurrently on two replicas, so that neither is a causal descendant of the other, are a data race. The runtime settles it by the mutations' hashes: the insert with the lower hash loses, and every replica picks the same winner. An insert whose lww parent is a DeleteRow made concurrently with it is the same race, settled the same way.

          • regexp: The regular expression constraint: The incoming value may be anything. The whole of it, as SQLite's text of it, must match the regular expression in the value key. The pattern is always anchored at both ends: the runtime strips a leading ^ and a trailing $ from it, then wraps it as ^(?:…)$. So b and ^b$ are the same check, and neither takes "abc". a|b becomes ^(?:a|b)$ and takes "a" or "b", never "ax". The check matches the value as the text SQLite converts it to: a number as its decimal text, an ArrayBuffer as its bytes read as text. Null and the column omitted land, because a NULL CHECK is no violation. The pattern itself must be a string, and must not be empty: soba.schema.table() refuses any other. A CHECK constraint with SQLite's REGEXP operator enforces this. That operator calls into the native regular expression engine of V8, so consult the SQLite, V8 and ECMAScript docs for the pattern's syntax and semantics within the anchors.

        • value (Any): The value to be used in the check. An ArrayBuffer is a valid value for the checks that compare values (==, !=, in): the check compares the stored bytes with it. An in list takes a BigInt whose value fits a signed 64-bit integer (-2^63 to 2^63-1): it compares as that integer. The call refuses one outside that range. A Boolean is not a valid value. A column stores a Boolean as the integer 1 or 0, so a check compares against 1 or 0, and soba.schema.table() refuses true or false as a check value. The call refuses a value that holds a NUL byte.

        • table (String): The name of the table to be used in foreign key constraint
        • column (String): The name of the column of the target table to be used in the foreign key constraint.
    • checks (Array): An array of multi-column check objects.

      • op (string): The check operation to be performed. One of: ["fk", "lww"]
      • Check-specific keys specified below:
        • op === "lww": For the Last-Write-Wins check:
          • columns (string[]): The name of the columns to be used in the LWW checks. The array names two or more columns. An LWW of one column is declared as that column's own lww check, and soba.schema.table() throws on an array of fewer than two. A set of columns carries one multi-column lww check: the call refuses a second one that names the same columns.
          • value (true): Must be true
        • op === "fk": For the Foreign Key check:
          • table (string): The name of the target table.
          • columns ({col:string}): A mapping from column names of the source table to column names of the target table: one object whose keys are the source table's column names and whose values are the target table's, e.g. {p : "x", q : "y"}. The target columns must be exactly the columns of one multi-column lww check of the target table, listed in that check's order. For a target lww of ["x", "y"] the mapping is {p : "x", q : "y"}. A mapping onto those columns in another order ({q : "y", p : "x"}, {p : "y", q : "x"}), onto a subset of them, onto a column twice, or onto columns no multi-column lww covers is an invalid declaration: soba.schema.table() throws. The mapping names two or more columns. A foreign key of one column is declared as that column's own fk check, and soba.schema.table() throws on a mapping of fewer than two.

      The multi-column FK and LWW checks operate the same as their single-column variants. The runtime serializes the column names and values to JSON and treats them exactly like the single-column constraints. A multi-column LWW takes a null component of its tuple as the single-column one takes a null value. A tuple that holds null where a stored row holds null, the other components equal, replaces that row. A multi-column FK with a null or omitted component establishes no happens-before relation, as the single-column one with a null value does not. The runtime inserts the row, requires no parent row and records no parent edge for that check.

soba.db.exec(query [, params ...]) [NR]

Always exposes a read-only SQLite connection. The connection reaches the instance's own database alone, its system tables included. An ATTACH answers SQLITE_ERROR (1).

The connection runs in its own read-only transaction, separate from the one that carries the mutation's writes. So a query sees the database as it was committed before the mutation began. A row the same mutation inserted, updated or deleted is not visible to it, and neither is an uncommitted write of any other mutation. To read back what a mutation wrote, query it from a later mutation.

Throws unconditionally in replicated context.

Parameters:

  • query: (String): The SQL query to run. Parameters use the ? notation and bind by position. ?NNN binds by number, and the named forms :a, @a and $a bind by position as well. A parameter not supplied binds NULL. One too many answers SQLITE_RANGE (25).
  • params: (null|true|false|Number|BigInt|String|ArrayBuffer): Zero or more parameters passed to the SQL query. A Number binds as an INTEGER when it is a whole number from -2^53+1 to 2^53-1, and as a REAL otherwise. A BigInt binds as an INTEGER as long as its value fits a signed 64-bit integer (-2^63 to 2^63-1). The call throws for a BigInt outside that range. To bind a larger integer than a Number binds, pass a BigInt.

Return Value:

Returns an object with the following keys:

  • code: Number: One of SQLite extended return codes. A query that runs answers SQLITE_OK (0).

  • data: any[][] | null: An array of rows, each row an array of JS values. It is [] when the query selects no row, and null when the query fails (code then carries the error). Each SQLite storage class comes back as its JavaScript value: an INTEGER as a Number from -2^53+1 to 2^53-1 and as a BigInt beyond that range, a REAL as a Number, TEXT as a String, a BLOB as an ArrayBuffer, and NULL as null.

  • text: String: SQLite's message for the outcome, where it has one (for example "Empty resultset" for a query selecting no row).

soba.task.respond(object)

Returns an ephemeral response to the current event. It is useful to answer requests from the application GUI.

The response is the object's SMC document: its class's KEY names the namespace and the name, and the object's fields are the content. The app may call it in either execution context. A request processed as a replicated mutation gets its answer the same way as a non-replicated one. A second call in the same event replaces the first response.

Parameters:

  • object: Object: An instance of a class that declares a static KEY holding an object key: one of the app's own table classes, or the base module's Message. Its fields must be serializable as msgpack, with string keys. true and false serialize as the integers 1 and 0, so the UI that reads the response finds a Number. Any other value, a plain Object included, throws.

Return Value:

Nothing.

soba.signal.emit(object)

Hands an object to the mail client. The client acts on the objects it knows and ignores the others. The app may call it in either execution context.

The client knows the base module's Notification:

  • id: Number: A non-negative integer. A notification with the id of one the same instance emitted before replaces that one.
  • title: String, body: String: What the notification says. Neither is empty.
  • topic: String: The name of the notification topic it belongs to.
  • link: String: A location in the app's own page, or null. It starts with /, followed by # and a fragment, by ? and a query, or by a path segment: its next character is #, ?, a letter, a digit, -, ., _ or ~, never another /. validate() throws on any other link, and the client drops a notification that carries one. When the user clicks the notification, the client opens the app on the link. It opens only links that start with /#, on the fragment after #, exactly as the app wrote it. Without a link, or with a link to a path or a query, a click opens nothing: it only removes the card. See the link of a notification.
  • thread: String: A key of the app's own, or null. The notifications of an instance that carry the same thread stack into one card.
  • badge: Number: The number on the app's icon, or null to leave it as it is. 0 clears it and removes the instance's notifications from the list.

The client lists the notifications as cards under the bell at the top right of its main window, the newest first. A stack of cards shows the latest of them. The bell shows a red dot while the list has cards. When the user empties the list, the dot goes away and the badges stay as they are.

The client takes a notification as new when its badge is higher than the instance's badge. A notification without a badge is new when the list has no notification of its id, or when the listed one has a different title, body, topic, thread or link. A new notification goes to the top of the list and also shows on the desktop. Any other notification replaces the one of its id where it is, and does not show on the desktop. So an app that lowers its badge after a read can send its latest unread item again with the lower badge, and the user sees no new alert. The client shows at most one desktop notification in 8 seconds, for apps and new mail together.

The client drops a notification that links to the page the user is looking at. It shows no card and no desktop notification for it, and removes the card of its id from the list. The badge of the notification still applies. The rules are in the link of a notification.

A notification whose link is /#message/ and a mail message's uuid, followed by a ? and a query or by nothing, is about that mail. The client looks the mail up in the instance's mailbox before it lists the notification. When the mail is only in the trash, or is not in the mailbox at all, the client drops the notification as above. When the user deletes a mail later, the client removes the cards about it. The client takes the notifications in the order they come, so one that is not about a mail can wait behind one that is.

Parameters:

Return Value:

Nothing.

soba.mail.send(message) [NR]

Sends an email. The runtime files the message when the event completes. An event that throws after it calls send() sends nothing.

Throws unconditionally in replicated context.

Parameters:

  • message: (Message): A Message instance.

Return Value:

Nothing. The value the call evaluates to is unspecified and subject to change. An app does not use it.

soba.mail.sign(message) [NR]

Signs an email and returns the signed Message instance. Throws if the sign operation fails.

Throws unconditionally in replicated context.

Parameters:

  • message: (Message): A Message instance.

Return Value:

  • The signed Message instance. In Sobamail, signed messages are StructuredMessage instances with an Envelope instance as root.

The signed instance has a Message-ID of its own, which replaces any Message-ID message had. The email goes out with the messageId of the signed instance, in the angle brackets of the Message-Id header. To name the email's Message-ID, for example in its body, read it from the signed instance.

The signature covers the structured content, not the text and HTML bodies. An app can set bodyText and bodyHtml on the signed instance before it calls soba.mail.send(), and the email goes out with those bodies.

soba.mail.verify(message)

Verifies the signature of an email. A signed email is a Structured Message whose root is an Envelope, such as the one soba.mail.sign() returns.

Throws when the email is signed and the verification fails. An app that does not catch the error processes nothing from an email whose signature does not verify.

The Message class has a verify() method that calls this function on the instance.

Parameters:

  • message: (Message): A Message instance.

Return Value:

  • true when the email is signed and its signature verifies.
  • false when the email is not signed. A plain email is not signed, and neither is a Structured Message whose root is an object other than an Envelope, or an Envelope that has no signature.
if (soba.mail.verify(message)) {
    // signed, and the signature verifies
}
else {
    // not signed
}

soba.mail.verifyEnvelope(envelope)

Verifies the signature of an Envelope. Use it for an Envelope that an app holds apart from the email it arrived in, for example one that is a field of another object.

Throws when the Envelope is signed and the verification fails.

Parameters:

  • envelope: (Object): The content of an Envelope, a plain Object that holds the fields of the Envelope. The runtime has no class for an Envelope. The root of a signed email is an SMC document of the keys namespace, name and content, and the content of that root is such an object.

Return Value:

  • true when the Envelope is signed and its signature verifies.
  • false when the Envelope has no signature.
const root = message.bodyObject.content;
if (root.name == "Envelope" && soba.mail.verifyEnvelope(root.content)) {
    // signed, and the signature verifies
}

soba.log.{debug,info,warning,error}(message)

Logs a message with the specified level.

Parameters:

  • message (String): The message to be logged.

soba.pack.msgpack.write(object)

This call was renamed from soba.pack.msgpack(object). An app that calls the old name must call soba.pack.msgpack.write(object): the parameters, the return value and the encoding are the same.

Serializes a JavaScript value into its msgpack representation. The encoding is canonical, which makes it suitable for building stable digests and mutation payloads: a value has exactly one byte representation, on every replica.

The keys of an Object are strings, so an Object serializes to a string-keyed msgpack map. A Map can also have integer keys, and each one serializes to a msgpack integer. Values may be binary (ArrayBuffer), which JSON cannot carry. The booleans true and false encode as the msgpack integers 1 and 0, so a decoder reads them back as Numbers. The same encoder serializes every document the runtime emits, so the rule holds for mutations and responses alike.

That canonical form follows from JavaScript's specified property iteration order, combined with a single fixed encoder. Array-index keys such as "0", "2" come first, in ascending numeric order, then the remaining keys in insertion order. The consequence: key order is part of an object's value, so object identity here is insertion-order based, not sort based. {a: 1, b: 2} and {b: 2, a: 1} are two different values. They encode to different bytes, hash differently and do not dedup. Build the object the same way each time and this is a non-issue.

Parameters:

  • object: null|true|false|String|Number|BigInt|ArrayBuffer|Uint8Array|Array|Object|Map: A JavaScript value of the listed types only. A Uint8Array packs as the bytes it views, the way an ArrayBuffer does. A Map packs as a msgpack map of its entries, in the order the Map holds them. A key of a Map is a String or an integer from -2^53+1 to 2^53-1, and one Map can hold keys of both types. An integer key is a Number and packs as a msgpack integer. The range is the range of the Numbers that pack as integers, so a key is never a BigInt: the call throws for a Map with a BigInt key, whatever its value. It also throws for a Map with an integer key outside that range, and for one with a key of any other type. A Number packs as an integer when it is a whole number from -2^53+1 to 2^53-1, and every other Number packs as a float: 2^53 packs as a float. To pack a larger integer, pass a BigInt. A BigInt value packs as a 64-bit integer as long as its value fits a signed one (-2^63 to 2^63-1). The call refuses a BigInt outside that range. The call also refuses a value of any other type, alone or inside an Array, Object or Map: it throws and packs nothing. The table in soba.pack.msgpack.read() shows each number rule.

Return Value:

  • ArrayBuffer: The msgpack-encoded bytes, as a raw (untagged) ArrayBuffer, not an ArrayBuffer (Tagged) mutation handle.

soba.pack.msgpack.read(buffer)

Reads a msgpack document into the JavaScript value it holds. It reads back what soba.pack.msgpack.write() packs.

Parameters:

  • buffer: ArrayBuffer|Uint8Array: The bytes of one msgpack document. The call throws for an argument of any other type, and for bytes that end before the document does.

Return Value:

The value the document holds, by msgpack type:

  • nil: null.
  • An integer: a Number from -2^53+1 to 2^53-1, a BigInt beyond that range. The call reads an integer from -2^63 to 2^63-1, the range of a signed 64-bit integer. It throws for an integer above 2^63-1.
  • A float: a Number.
  • A string: a String.
  • Binary: a raw (untagged) ArrayBuffer.
  • An array: an Array of the values in it.
  • A map whose keys are all strings: an Object, its keys in the order the document holds them. A map of no entries reads as an empty Object.
  • A map with an integer key: a Map, its entries in the order the document holds them. Each key keeps its type: an integer key is a Number, a string key is a String.

The rule applies to each map of the document separately, so a Map can hold an Object and an Object a Map. An SMC document has integer keys and reads as a Map, while its string-keyed content reads as an Object.

A map key is a string or an integer from -2^53+1 to 2^53-1. The call throws for a map with an integer key outside that range, and for a map with a key of any other type. An integer key is always a Number and never a BigInt. The range is the range of a key only: an integer value outside it reads as a BigInt.

write() takes the same keys, so a Map with integer keys that write() packs reads back as a Map with the same keys.

write() packs a boolean as the integer 1 or 0, so a boolean reads back as a Number. It packs a BigInt as an integer, so a BigInt from -2^53+1 to 2^53-1 also reads back as a Number. Every other value keeps its type: a larger BigInt reads back as a BigInt, and a Number reads back as a Number.

This table shows how write() and read() handle each number:

Operation Result
write() of a whole Number from -2^53+1 to 2^53-1 A msgpack integer
write() of any other Number, such as 2^53, 2^62, 1e30 or 0.5 A msgpack float
write() of a BigInt from -2^63 to 2^63-1 A msgpack integer
write() of a BigInt outside -2^63 to 2^63-1 The call throws
read() of an integer from -2^53+1 to 2^53-1 A Number
read() of an integer from -2^63 to -2^53, or from 2^53 to 2^63-1 A BigInt
read() of an integer above 2^63-1 The call throws
read() of a float A Number
A map key, in write() and in read() A String, or a Number from -2^53+1 to 2^53-1. The call throws for any other key
const packed = soba.pack.msgpack.write({name : "a", data : [ 1, null ]});
const value = soba.pack.msgpack.read(packed);
// {name : "a", data : [ 1, null ]}

// an SMC document: {0 : namespace, 1 : name, 3 : content}
const document = soba.pack.msgpack.read(data);
const name = document.get(1);
const content = document.get(3);

soba.text.encode(string)

Encodes a JavaScript string into its UTF-8 byte representation. A lone surrogate in the string encodes as the bytes of U+FFFD.

Parameters:

  • string (String): The string to encode.

Return Value:

  • Uint8Array: The UTF-8 encoded bytes.

soba.text.decode(buffer)

Decodes UTF-8 bytes into a JavaScript string. Invalid UTF-8 decodes to one U+FFFD per maximal invalid subpart, as the WHATWG Encoding standard's UTF-8 decoder does.

Parameters:

  • buffer (Uint8Array): The UTF-8 encoded bytes to decode.

Return Value:

  • String: The decoded string.

soba.binary.equals(a, b)

Compares two binary buffers for byte-wise equality.

Parameters:

  • a (Uint8Array): The first buffer.
  • b (Uint8Array): The second buffer.

Return Value:

  • Boolean: true if both buffers have the same length and identical contents, false otherwise.

soba.binary.b64Encode(buffer)

Encodes a binary buffer into a standard base64 string (RFC 4648 §4, the +// alphabet with = padding, not the url-safe variant).

Parameters:

  • buffer (Uint8Array): The bytes to encode. The call refuses an ArrayBuffer, the tagged one a soba.data.* call returns included ("Arg 1 must be a Uint8Array"): pass new Uint8Array(buffer).

Return Value:

  • String: The standard base64-encoded representation of the input.

soba.binary.b64Decode(text)

Decodes a standard base64 string (RFC 4648 §4, the +// alphabet with = padding, not the url-safe variant) back into bytes. The call throws on text that is not standard base64. That is another alphabet, a character outside it, padding anywhere but at the end or of the wrong count, or a final group of one character. The padding may be omitted.

Parameters:

  • text (String|Uint8Array): The standard base64-encoded text to decode, as a string or as a Uint8Array holding its characters (e.g. from soba.text.encode()).

Return Value:

soba.blob.create(data)

Creates a blob from the given binary data and returns its parts in an Array. A stored part's id derives deterministically from its contents, so a blob created from identical data gets the same blob ids.

Parameters:

  • data (ArrayBuffer): The binary contents of the blob.

Return Value:

  • Array: The parts of the blob, in order:

    • The runtime keeps data shorter than 512 bytes inline: the array's one element is data itself, verbatim.
    • The runtime stores data of 512 bytes or more in chunks of at most 1 GiB (1073741824 bytes), one {https://sobamail.com/module/base/v1}Blob object per chunk. A Blob carries its id as blobId, which matches soba.type.blobId.pattern.

Warning

The runtime currently has no function that reads a blob's contents back by id on the mutator side. The browser environment does offer endpoints that return blob data.

soba.clock.logical.digest() [NR]

Returns the digest of the newest mutation in the instance's mutation log on this replica, or null while the log holds no mutation.

The digest comes back as a tagged mutation handle, so an app can use it like any other handle to establish a happens-before relationship. A new mutation with it as a dependency happens after that newest mutation and, transitively, after every mutation that one depends on.

Warning

The newest mutation in the log may be another event's, so this dependency can reach past the caller's own writes. Other replicas cannot apply the new mutation until they hold that mutation and everything it depends on. Prefer a specific handle from find() when a narrower dependency suffices.

Return Value:

  • ArrayBuffer (Tagged): The newest mutation's digest, as a tagged mutation handle.
  • null: The log holds no mutation yet. A mutation made with this value as a dependency has no parent.

soba.clock.physical.secs() [NR]

Returns the current physical wall-clock time in seconds since the Unix epoch. Wall-clock time differs between replicas, so the runtime forbids this function in replicated context.

Return Value:

  • BigInt: Seconds since the Unix epoch, a whole number.

soba.clock.physical.msecs() [NR]

Returns the current physical wall-clock time in milliseconds since the Unix epoch. Wall-clock time differs between replicas, so the runtime forbids this function in replicated context.

Return Value:

  • BigInt: Milliseconds since the Unix epoch, a whole number. The three clock functions all answer a BigInt: Math.floor() and the other Math functions, and arithmetic with a Number, throw on one ("Cannot convert a BigInt value to a number"). Convert with Number() where you need a Number, as in a value to store as text or to compare with Date.now(). The millisecond count fits a Number exactly.

soba.clock.physical.usecs() [NR]

Returns the current physical wall-clock time in microseconds since the Unix epoch. Wall-clock time differs between replicas, so the runtime forbids this function in replicated context.

Return Value:

  • BigInt: Microseconds since the Unix epoch, a whole number.

soba.platform.releaseChannel()

Returns the release channel of the current Sobamail platform implementation.

Return Value:

Returns "Stable" in the real world.

soba.platform.version() [NR]

Returns the version of the current Sobamail platform implementation.

Throws unconditionally in replicated context.

Return Value:

  • String: The version of the current Sobamail platform implementation, four integers separated by dots: "major.minor.patch.build". The form is the promise. The values the integers take are unspecified.

soba.type.*.isValid(s)

The isValid helpers tell if a given string is a valid value of the corresponding type. Each is a pure, deterministic predicate.

  • soba.type.blobId.isValid(s): a valid blob id.
  • soba.type.domainName.isValid(s): a valid DNS domain name.
  • soba.type.folderName.isValid(s): a valid folder name.
  • soba.type.userName.isValid(s): a valid user name.

Parameters:

  • s (String): The string to be checked.

Return Value:

  • Boolean: true if the string is a valid value for that type, false otherwise.

TODO

The runtime does not yet implement isValid helpers for the uuid, address, and namespace types, though it exposes their patterns. Validate against the corresponding .pattern in the meantime.

soba.type.instanceId.gen() [NR]

Generates a fresh app instance id.

Throws unconditionally in replicated context.

Return Value:

  • String: A base32hex encoding of a RFC 4122-encoded UUIDv4 minus the trailing '=' chars.

soba.type.uuid.v4() [NR]

Generates a UUIDv4.

Throws unconditionally in replicated context.

Return Value:

  • String: A new uuid, in braced hexadecimal uuid format. The returned value is a tagged instance of the String object, not a primitive string.

soba.type.messageId.gen(fromDomain) [NR]

Generates a fresh Message-ID for an email sent from fromDomain.

Throws unconditionally in replicated context.

Parameters:

  • fromDomain (String): The domain of the email's From address, the part after the @. For ada@example.com it is example.com.

Return Value:

  • String: A new Message-ID without the angle brackets of the Message-Id header: a UUIDv4 in lowercase hexadecimal, without braces, then @, then fromDomain. For example, 3f2b8c1e-9a4d-4e7f-8b21-6c0d5e9a1f34@example.com. Every call returns a different value.

    An empty fromDomain gives the domain missing-sender.error.sobamail.com. A fromDomain that contains an @ gives the domain invalid-sender.error.sobamail.com. Neither is a valid Message-ID for an email sent from fromDomain.

soba.mail.sign() gives a message a new Message-ID. A signed email goes out with the Message-ID of the signed instance, not one set before signing.

soba.type.*.pattern

The pattern properties expose the regular expression source string that validates each type. They are constants, useful for client-side validation or for regexp column checks in soba.schema.table().

Property Validates
soba.type.address.pattern An email address.
soba.type.blobId.pattern A blob id.
soba.type.domainName.pattern A DNS domain name.
soba.type.folderName.pattern A folder name.
soba.type.instanceId.pattern An app instance id.
soba.type.namespace.pattern A namespace: a URI such as https://sobamail.com/module/base/v1, the part of an object key inside the braces.
soba.type.userName.pattern A user name.
soba.type.uuid.pattern A braced hexadecimal uuid.

Value:

  • String: The regular expression source for the corresponding type.