Remote / foldkit-remote-server

Mutations

A Mutation Source changes server-owned state. It returns the protocol output plus any normalized entity/connection changes that should settle the client's cache immediately:

ts
import { Effect } from 'effect'
import { Mutation } from 'foldkit-remote'

const RenameProject = Mutation.make('RenameProject', {
  Input: Schema.Struct({ id: Schema.String, name: Schema.String }),
  Output: Schema.Struct({ id: Schema.String }),
})

// `renameProject` is your own write, answering the Output.
const RenameProjectSource = RemoteServer.mutation(
  RenameProject,
  ({ input, principal }) =>
    renameProject(input, principal).pipe(
      Effect.map(output => ({
        output,
        entities: [
          Entity.patch(Project.ref(input.id), { name: input.name }),
        ],
      })),
    ),
)

The input is decoded before the Source runs and the output is encoded before it crosses the wire. The entities are cache patches of rows the caller may read: the answer carries your values, cut to what authorize and filter let the caller read of each row, and none for a row they may not read at all (a source with no authorize, filter or visible is answered as it is, with no read; if the read fails, none of that entity's patches is sent and an AnswerUnread is reported, and the write still succeeds). Live subscribers are told every patch and read each through their own rules. What a handler must tell a caller who may not read the row goes in output, which is its own Schema. A Source refuses with a value of the mutation's Refusal: Effect.fail(RemoteServer.refuse(SetPrice, { _tag: 'Field', key: 'price', reason: 'too low' })). The value is type-checked against that mutation, encoded by its schema, and sent beside a message (a 422 over JSON); a refusal made for another mutation, or not one the mutation declares, is sent as an invalid refusal instead.

A refusal of who is asking, rather than of what they asked, is Effect.fail(RemoteServer.forbid('Only an admin may archive.')): sent as Forbidden with the reason (a 403 over JSON), or with none when forbid() is given none, so the refusal says nothing of why. It is the same for every mutation, so it needs no Refusal declared. A refusal of a visitor, someone not signed in, is RemoteServer.unauthenticated(reason) instead (a 401): signing in is the remedy, and Remote's outbox keeps a durable write so answered waiting for it, where it settles a Forbidden one as failed. RemoteServer.write refuses a visitor a write whose Entity sets a member from who asks that way, and GuardServer refuses a visitor every write it would refuse.

A Source may additionally return connection changes:

ts
RemoteServer.prepend(connection, Project.ref(id))
RemoteServer.append(connection, Project.ref(id))
RemoteServer.remove(connection, Project.ref(id))

Those confirmed changes replace the corresponding optimistic connection layers on the client.

A write sent again: operation

The Source is also given requestId, the client's id for the request, and operation, the operation's id across clients, both the same on every retry of it. Record a write under operation, never requestId: a request id is a counter in one client's Model, so two clients' first requests share it, and a record keyed by it would answer one client with another's write. operation is none from a client that sends none, and bounded on the wire (128 characters of A-Z a-z 0-9 : . _ -).

Expect the same operation more than once. A write that no answer came back for fails on the client with Unreachable (RemoteUnreachable): the request did not go, or what came back was no Remote answer (not JSON, or under a 408, 429, 502, 503 or 504, which this package never answers with but a gateway or a rate limiter may). The server may have landed it. Data.retry sends it again under the same operation, and a durable write (Data.mutate(…, { durable: true })) is stored in the page's outbox and sent again on its own, after an Unreachable and after a reload, with the same operation id and the same now. What a retry does depends on the write: setting a value sets it again, an expected revision answers Conflict, and only a ledger (below) recognises the operation and answers it from its record. A durable Mutation therefore needs a writer with a ledger, or a handler that records by operation.

The outbox never sends one principal's waiting writes as another's: it holds its queue for one store key and scope, and sends none of it once either changes. The server still decides each send as whoever that request authenticates as.

Declared writes: no handler

A mutation declared as a Write (Mutation.write) needs no handler. RemoteServer.write(mutation, writer) binds the input to the write, only the keys the client named when it named some, and hands the row's id and new values to an EntityWriter, which writes them and answers the row as written:

ts
// `EditProject` is a Mutation.write; `writer` and the binding `Db` are foldkit-remote-drizzle's.
RemoteServer.write(EditProject, writer(Db.Project))

The answer is the mutation's patch, or for a delete its deletion. The writer must be for the write's own Entity, which is checked where the mutation is served. The declared writes guide walks through the whole path; what this package does with each part of a write:

  • What the server chooses. A write of an Entity with Entity.sets is handed the members its context sets as well, never from the input (an insert all of them, an update those set on: 'write'): Expr.viewer from RemoteServer.make({ viewer: principal => Option<{ entity, id }> }), and Expr.now from the write's time. A value that comes to null where the member holds none (a visitor's) is refused as forbidden; a server that serves a write setting the viewer with no viewer is refused where it is made. A path from the viewer is read through the server's own sources, as the asker may see each row (the run context's read); a server that mounts no source for a row the path reaches is refused where it is made, and a path reaching no row the asker may see is null.
  • The write's time is the client's when it sent one (Data.mutate's now, the moment the reader acted, which the client showed the row at) and it lies within RemoteServer.make({ clockSkew }) of the server's Effect Clock: 60 seconds unless given, 0 to never take a client's time. Otherwise it is the server's own, and a time past a bound above zero is reported as a ClockSkewed diagnostic: a durable write sent long after it was made takes the server's time. The bound is how far a client can backdate or postdate a row; nothing else of a write's context comes from the client. A hand-written mutation reads the same time as now in its context. A retried insert, which only a writer's ledger recognises, keeps its first time. A retried update is a new write to a server without a ledger, and stores the time of the attempt that ran: the same sent now while it lies within clockSkew, else the server's clock at that attempt. A ledger answers the retry from its record, so the first time stays.
  • expect: the writer is told the revision the row was read at; no row at it is refused as Refusal.conflict.
  • when: the writer is handed the precondition and the input encoded, checks it in the statement that writes, and fails a row at the revision that does not hold it with RemoteUnmet (RemoteServer.unmet()), refused as Refusal.unmet: absent first, then a moved revision, then the precondition.
  • Invariants (Entity.invariant) are the writer's to judge over the row the write would leave, refusing with RemoteServer.invalid(message, rule, path), sent as Refusal.invalid: the invariant's id and path, or none and empty when the caller may not be told them.
  • Increments and computed assignments reach the writer apart from its values (increments, each field's amount, encoded; assignments, each a Computation), to be applied in the statement that writes. One that expects no revision is served only over a writer with a ledger, and only for a request carrying an operation id; even so, a concurrent pair must land as one result: an increment only of an integer, and a computed assignment only where the writer commutes it, unless the writer pins the row it read (pins: true, a guard with a revision).
  • A rule over another row. A writer that holds an update's or a delete's row to a requires (RowRequirement: bodies over the row, all or any of them) in its own statement refuses a row that fails it with Forbidden: foldkit-guard hands it a rule that reads another row that way.
  • Creates and deletes. An update of no row fails, and a delete of a row already gone succeeds, so its retry is safe. An insert of an id already taken is refused as Refusal.taken (the writer fails insert with RemoteTaken, RemoteServer.taken()), with one answer whatever the row there holds and whether its asker may see it: comparing that row with the insert would tell the asker what it holds. Only a writer with a ledger tells a retry from another create of the id, by the operation the client sent, and answers it with the row; without one, a create whose answer was lost is refused when it is sent again. Give a writer a ledger where a client may resend a create, and make ids that a guess cannot find where whether a row exists is itself private.

A writer says what it can do, and RemoteServer.write refuses, where the write is served, one that needs what its writer lacks rather than writing it wrongly:

EntityWriter saysItNeeded by
preconditions: truechecks when in the write statementa write with a when
invariants: truejudges the Entity's invariantsa write of an Entity with invariants
postconditions: truejudges ensures beside invariants on update and inserta write with ensures
increments: trueadds increments in the write statementa write with an increment
assignments: truecomputes assignments in the write statementa write with a computed assignment
ledger: true (with recorded)records each update and insert under its operationan increment or computed write without expect
requires: trueholds the row to requiresGuardServer.writer over cross-row rules
refuses(write)names store limits (such as fractional ints in Drizzle)every write, checked before execution

A writer with a read (the row as a principal may see it, under the read rule its Source applies) answers through it: the patch is the written row as its writer now sees it, and a row the write moved out of their sight answers in deleted, so the client takes it out of every list rather than placing it where the server would not list it. A writer may refuse with RemoteServer.forbid, as foldkit-guard's GuardServer.writer does. Its linked answers a row's links as stored, whatever a reader may see of the rows they point at, so such a guard can tell a write that unlinks a hidden row from one that changes nothing; foldkit-remote-drizzle's writer has both.

What an answer carries

A Source answers the rows it changed; the client says what it shows of them. Data.mutate sends, with each request, what its active Surfaces read of each entity, every field its optimistic layer shows, and the supplied members a created or edited row foresees (may) (shown). After the Source runs, the handler reads, of each row the outcome names (a patch, or a list insert), the shown fields the patch left out and every shown relation, and returns that read beside the patch (read).

So a declared write, which answers the columns it stored, also answers the derived count, the may and the author's name the page reads of the row, and the client releases its optimistic layer with nothing left to fetch. The read is an ordinary one: the Sources' read, authorize and filter decide it, a field the asker may not read comes back settled, and a row they cannot see is left out of it, keeping what the patch gave.

A Source whose write the server cannot see (a row of a join table, a count it keeps itself) names the row with no values, and the read answers all of it:

ts
// Sketch, inside a mutation Source over a `Post` Entity: a like in a join table
// changes its post, so name the post and read nothing yourself.
return { output: { liked: true }, entities: [Remote.patch(Post, input.postId, {})] }

The read runs after the write commits, outside its transaction. If it fails, it is reported as an AnswerUnread diagnostic and the mutation is answered without it: the write has landed, and the client fetches what it lacks as it would have. A deleted row is not read.

A request also names the lists the client judges the write moves (lists): each the first page of a query, as the client's read entry would ask for it. The handler admits them before the write runs, then reads each after it with the query's own handler, so the page is what FoldkitRemoteQuery would answer (authorize and filter included), and returns them beside the rows in answer.lists.

A list is admitted when its query is one the server serves, its window is a first page (first, no after), its select names the query's Entity within a read's page bound, and the rows of every list admitted so far stay within maxIdsPerEntity per Entity. One that is not, or whose read fails (reported as AnswerUnread), is left out; the write runs either way, and the client fetches that list as it would have. The wire refuses more than MAX_ANSWER_LISTS lists in one request.

A declared write (RemoteServer.write) also reads each row its row points at through a one relation, before and after the write, through the writer's linked, where that link can change one of the row's derived members: a Derived.count or Derived.exists over that relation, or any supplied member (Derived.make), which may read anything. Inserting a Like reads what the page shows of its post, the new likeCount included, and not its user, whose members no like changes. A member declared after Entity.relate counts: the Entity has one set of members, whichever descriptor declared them. A row's derived members change only with the rows pointing at it, so no app names them. These rows are read, never sent as patches of their own: one the asker may not see is not answered at all. Live subscribers hear the outcome's own patches, not the read, which is one asker's view.