Errors and testing

Handle the errors a Swift app meets, word and report them, and test the app against a fake working copy.

Every call on a working copy, Folders, a Server or Client throws a MarfaError. A sign-in throws a SignInError instead.

Handle errors

MemberGives
messageText fit to show a person. It can repeat a title, an ID or an address.
code()The stable name shared with the core and the marfa command line, such as not_found. A case's own code field is the server's refusal code.
serverServerAnswer?: the status, refusal code and details the server sent. nil for a failure the device met itself.
fixedTextFixedErrorText: text fixed in the SDK, safe to send to the app's own error reporting. The SDK sends nothing itself.

Four properties sort an error into what the app does next:

PropertyTrue forWhat the app does
isOfflinenetwork and noConnection. A write may still have reached the server.Show that the app is offline. Queued writes wait.
isKeyRefusalunauthorized, signedOut, and copyExpired or streamIncomplete with the reason credential_ended.Ask the person to sign in again, or for a new key.
isTransientnetwork, noConnection, io, storageFull, storeBusy, rateLimited, unnamed, keyChanging, and server with status 408 or 500 and above.Try again later.
isHydrationNeededcopyExpired with any other reason, instanceChanged, noCursor, hydrationIncomplete and firstSyncWaiting.Hydrate the copy.

An error is at most one of a key refusal, transient or a need to hydrate. Asking again can't clear a key refusal or a need to hydrate. forbidden is none of them: the key works but lacks a permission.

FixedErrorText has type, the code() word; sentence, one sentence fixed in the SDK; and code, the server's refusal code where it is lowercase letters and underscores of at most 48 characters, and type otherwise. None holds a value the error carries, such as a title, an ID or an address.

Refusals

CaseMeans
notFound(code:message:server:)No such row, route or name (404), from the server or from the copy before anything was sent.
unauthorized(code:message:server:)The server doesn't accept the key or token (401). A revoked or expired key gets this.
forbidden(code:message:server:)The key is valid but lacks the permission (403), such as type_not_permitted.
validation(code:message:details:server:)The server refused the values (400 or 422), or the copy refused them first, as the server would.
server(status:code:message:details:server:)Any other answer from the server.
rateLimited(code:message:retryAfterSeconds:server:)The server asked for a wait (429), for retryAfterSeconds where it said.
versionConflict(message:server:)The write was based on a version that is no longer current (409 version_conflict). Read the row again and decide.
unknownType(message:server:)The copy's catalog holds no type of that name.
invalid(message:)A value given to the call can't be used.

The server's codes are in Errors. validation's details holds what the server's error.details would for each edge_constraint_violation and edge_cycle the copy gives itself (Edge refusals), so an app reads it one way whichever refused. It is nil for every other refusal, a direct call's included: read server?.details there.

Sign-in and the owner

CaseMeans
signedOut(origin:message:)The keychain holds no sign-in for origin, or the server ended it. Sign in again.
renewalRefused(reason:message:)The sign-in couldn't be renewed, and is kept. reason is a RenewalRefusalReason: .refused by the server, .redirected, since a redirect isn't followed, or .unreadable, an answer or sign-in metadata the SDK can't read. Word it from reason: message can hold an address. Queued writes wait, and the next call renews again.
noKeychain(message:)The keychain can't be used.
confirmationRequired(maxAgeSeconds:message:server:)The owner must confirm it's them (401 insufficient_user_authentication): they signed in longer ago than maxAgeSeconds allows.
appSignInRequired(message:server:)An API key made a call only an app the owner signed in to can make (403 app_sign_in_required), such as restoring a backup. Its message is fixed.

A Server given confirming(from:) signs the owner in again and resends the call, so an app sees confirmationRequired only without a window or a browser redirect, or when the server asks again. Asking again with nothing changed clears neither case.

The connection and the server

CaseMeans
network(message:)The request didn't reach the server, or its answer didn't come back in time.
noConnection(message:)The device is offline. Nothing was sent.
unnamed(status:message:server:)A proxy or the like answered without the server's contract. Transient whatever its status.
redirected(origin:status:location:message:server:)The server answered with a redirect. It isn't followed, so the key goes nowhere else.
contractMismatch(served:expected:status:writeSent:message:server:)The server speaks another contract, and its answer wasn't read. Where writeSent, the write may have taken effect: it stays queued, and goes again under its key once the app speaks that contract.
noServer(message:)The call needs a server, and the copy was opened without one.
wrongServer(expected:got:message:)The store or file belongs to another server. The copy sends it no credential or data: wrong_server.
instanceChanged(message:server:)Another instance answers at the server's address (409 instance_changed). Hydrate from it. The queue is kept.
copyExpired(reason:message:server:)The copy needs a hydration for reason, such as reach_changed or catchup_too_old. The queue is kept.
streamIncomplete(reason:message:server:)The server ended the event stream early, for reason.

A stale copy (catchup_too_old) refuses a drain and a catch-up until hydrated: A working copy that can't catch up.

The copy and its store

CaseMeans
hydrationIncomplete(message:)A read by ID, a view's read, an edge write, or a write to a row the copy doesn't hold came while a hydration fills the copy.
noCursor(message:), noCatalog(message:)The copy holds no position in the instance's events, or no type catalog. Hydrate first.
notAnswerable(message:)The copy lacks the data for a local count. counts(of:_:) handles it by asking the server.
readingHandle(message:)Another process, or another open copy in this one, holds the store's writer role, so this copy only reads.
storeBusy(message:)Another process held the store when the call needed it. Ask again later.
store(message:)The store couldn't be opened, read or written.
storeDamaged(path:reason:unsent:message:)SQLite can't read the store, or a set-aside of it stopped part way. unsent counts the writes the server hasn't taken, nil where the queue can't be read whole. path is empty where the call doesn't know it.
wrongSchema(path:reason:unsent:message:)The store has a shape this build can't read. unsent counts the writes another build can still send.
unsentDiffers(path:unsent:message:)A removal found unsent writes other than the ones the person was shown, and removed nothing.
keyChanging(message:)The call came while use(_:) replaced the sign-in, and wasn't made. Ask again once it's done.
closed(message:)The copy was closed, or failed to reopen its store with a new key. Open the store again.
firstSyncWaiting(message:)A folder's first sync waits for the person to confirm it.
fault(message:)The core itself went wrong, such as a crash during the call. It is never the app's input or the server's answer. Report it. A crash can leave the store unusable, and every later call that reads or writes it throws fault: close the copy and open it again.

A store the copy refuses lists the calls that check, set aside or remove a damaged or refused store, and what each loses.

Files and the device

CaseMeans
bytesAbsent(hash:reason:message:)A file's bytes aren't on the device and can't be fetched.
noRoom(hash:size:free:message:)The volume has less room than a fetch still has to receive.
storageFull(message:)The device has no room left to write the store.
io(message:), decoding(message:)A local file couldn't be read or written, or an answer or stored value couldn't be read.
canceled(message:)The caller canceled the call.

Other errors

Thrown byError
Server(url:key:)Server.AddressError.userInfo: the address holds a user or password.
Server.fromEnvironment()Server.EnvironmentError: .incomplete(missing:) or .notAServer. Neither repeats a value.
KeychainKeychain.Failure with the keychain's status.

Test against a fake copy

WorkingCopy.fake(items:edges:itemTypes:edgeTypes:views:displays:linkCandidates:) from the MarfaTesting product returns a FakeCopy. Its copy is a real WorkingCopy over an engine that keeps items, edges and types in memory, so its argument checks, change feed and value conversion are the app's own. It compiles empty in a release build.

#if DEBUG
import MarfaTesting

let fake = WorkingCopy.fake(items: [note], itemTypes: [noteType])
let model = NotesModel(copy: fake.copy)
#endif
AreaThe fake answers
Readsitems.list(_:sort:) without a filter, with source, date ranges and a property sort; items.get, with or without includingBin:; edges.get, from, to and ofType; the four catalog reads; declaredTypes() and status(). catalog.fromServer() throws noServer.
Searchsearch(_:filters:limit:) and search(_:inView:limit:), through the core's full-text index rules, so hits, order, scores and excerpts are the core's. completeness is always .complete.
WritesItem writes, without a sourceId on a create; tag, metadata and extension writes; edges.create, check, update and delete; declareTypes(_:).
ViewscreateView, changeView, deleteView, items.views(), items.view(_:), and listing and grouping a view. A view write never enters the queue.
The queueall(), drain(), withdraw(_:), discard(_:), forgetAnswered() with or without ids, and takeAnswered().
Streamschanges(), with the app's own writes, and updates(), which tells .local.
TablesNone held: tables.held() is empty, tables.letGo answers false, and tables.write and tables.undo refuse an item the fake doesn't hold.

A call or input the fake can't match exactly throws FakeCopyError.unsupported(call:) rather than answer differently. That covers:

  • a filter, status_group included, and listing, grouping or searching a view that has one;
  • changes(since:most:), counts(of:_:), body links, hydration, files and folders;
  • every other table call;
  • declareTypes(_:) with a status field or status words.

The fake refuses as the core does, with its code, message and details: a status word the type doesn't declare (invalid_properties), and each edge the core would refuse, judged from the types and edges it holds.

It knows only the types given and declared, not the built-in catalog. A row it makes is at version 0 until a drain takes its create.

Drive the fake

MemberDoes
verdictChooses each write's verdict at a drain. The default accepts, and nil leaves a write unanswered, as when the server is lost. A write that depends on a refused one is refused unsent.
writesEvery write received, in order, with its verdict now.
displaysScripts what items.displays(for:) and displays(of:) answer, one closure call for each input. Unscripted, they throw unsupported.
linkCandidatesScripts what items.linkCandidates(of:in:) answers for each target. The answer's target is replaced by the one asked.
send(_:)Tells every changes() stream a change, as if the copy made it.
sendUpdate(_:)Delivers a CopyUpdate, such as .offline or .stopped, to every updates() sequence held. Call it after copy.updates().

A keychain and key store in memory

MemoryKeychain() keeps keychain items in memory, so a test never touches the system keychain. Give its keychain to KeychainKeyStore, Authorization or Server.

MemberDoes
failReads(with:), failWrites(with:)Makes every read or write throw Keychain.Failure with that OSStatus, as a locked keychain does.
succeed()Ends both.
signIn(to:service:accessToken:refreshToken:scopes:)Keeps a sign-in as an approval would, with no browser or server, and returns its Credential.

With no refreshToken, a refused access token ends the sign-in, and calls throw signedOut. With one, a renewal reaches no server and fails with network, keeping the sign-in.

MemoryKeyStore([URL: String]) is a KeyStore in memory. makeUnreadable(_:) makes key(for:) throw MemoryKeyStore.Unreadable for that server.

On this page