fin.cx/swiftsupport

Swift for fin.cx. Its library Doclink is a Swift client of doclink 1.1.0, the protocol over which a document source (DocBox, invoice.bot) delivers documents to a finance app such as nevermind.finance. It runs on the TypedSocket 9 client of api.global/swiftsupport, and its wire types are generated from doclink's TypeScript contracts, so a Swift source speaks to the same DoclinkServer as DocBox does.

Issue Reporting and Security

For reporting bugs, issues, or security vulnerabilities, please visit community.foss.global/. This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a code.foss.global/ account to submit Pull Requests directly.

Install

Swift 6, iOS 17, macOS 14, tvOS 17, watchOS 10, visionOS 1:

dependencies: [
  .package(url: "https://code.foss.global/fin.cx/swiftsupport.git", from: "1.0.0"),
],
targets: [
  .target(name: "MyKit", dependencies: [.product(name: "Doclink", package: "swiftsupport")]),
]

Releases are tagged vX.Y.Z, which SwiftPM reads as version X.Y.Z.

Not usable this way yet. SwiftPM names a package by the last part of its URL, so fin.cx/swiftsupport, api.global/swiftsupport (which this package depends on) and modelprofile.com/swiftsupport are all the package swiftsupport. Two of them in one dependency graph fail to resolve (Conflicting identity for swiftsupport, then product 'SwiftSupport' … not found in package 'swiftsupport'), and so does a checkout of this repository in a folder named swiftsupport building itself. Until the repositories have identities of their own (other repository names, or a Swift package registry with scoped ids such as fin.cx.swiftsupport), the package builds and tests only from a folder of another name; its manifest is named fincx-swiftsupport for the same reason.

Delivering documents

A host holds one DoclinkClient per connection and gives it the connection's outbox:

import Doclink

actor InvoiceOutbox: DoclinkOutboxAdapter {
    func outboxId() async throws -> String { … }                       // stable while the outbox lives
    func pendingNotifications(after sequence: Int, limit: Int) async throws -> [DoclinkDocument] { … }
    func pendingCount() async throws -> Int? { … }                     // optional: for the heartbeat
    func applyAcks(_ acks: [DoclinkAck]) async throws { … }            // every outcome, later decisions included
    func pruneThrough(outboxId: String, settledThrough: Int) async throws { … }
    func reopenAfter(outboxId: String, afterSequence: Int) async throws -> Int? { … }  // optional: a replay
    func readDocument(documentId: String, sha256: String) async throws -> DoclinkDocumentRead { … }
}

var configuration = DoclinkClient.Configuration(
    url: URL(string: "https://nevermind.finance/socket")!,
    token: token,                                                      // dlk_…, from the keychain; never logged
    client: DoclinkClientInfo(product: "invoice.bot", version: "1.0.0", instanceId: installationId, instanceLabel: "iPad Office"),
    binding: DoclinkBinding(organizationId: "org_1", organizationLabel: "Example GmbH", entityId: "ent_a", entityLabel: "Company A")
)
configuration.onStatus = { status in … }                               // or `await client.statusUpdates()`
let client = try DoclinkClient(configuration: configuration, outbox: outbox)
await client.start()
// after appending to the outbox:
client.notifyOutboxChanged()
// when the connection is removed or the app is done with it:
await client.stop()

Sequences are dense per outbox (1, 2, 3 …); a document is unsettled until an acknowledgement settled it, and the outbox may forget what pruneThrough names. A host checks a document before it puts it in its outbox with DoclinkValidation.checkDocument(_:): the server refuses a notification of another shape, and the outbox would keep it.

What the client does

  • Hello. Each connection the socket client opens starts with doclinkHello: protocol version 1, the token, the client (product, version, instanceId, instanceLabel), the binding, the features it offers and its outbox. The answer is checked before any of it is used — limits within the protocol's ceilings, the cursor of this outbox, features it offered, bounded labels; members it does not know are left alone — and the outbox is pruned to the cursor.
  • Status. DoclinkClientStatus as doclink has it: connecting, connected, paused (with the reason and retryAt), reconnecting (with the reason after a closing status), refused (the reason), stopped; with the server, the connection, the features used, what the server accepts and the limits of the last hello. whenConnected(timeout:) waits for connected and throws the refusal.
  • Offers. The outbox is offered in order, at most limits.maxNotificationsInFlight unacknowledged at a time; a rate_limited refusal pauses for the time the server named and offers again; a notification the server refuses otherwise is logged and stays with the host. A settled receipt hands its outcome to the outbox at once.
  • Files. doclinkFetchChunk is answered from the outbox's bytes, checked against the notified SHA-256 (changed otherwise, not_found for a document the outbox does not hold), cut into chunks of the size the server asks within its limit; the two files fetched last stay in memory until their last chunk.
  • Acknowledgements. At most 50 per request, each checked (no field the contract does not name, only this connection's outbox) before the outbox sees one; the cursor moves forward only and prunes the outbox. A replay request reopens what the outbox still holds after a sequence.
  • Heartbeat. At once when connected, then every limits.heartbeatIntervalMs, with the outbox's pending count. A refusal that ends the link (token_revoked from another process of the server, say) ends it here. When nothing has come back from the server for limits.staleAfterMs the connection is left as stale and opened again — a half-open connection on a phone that changed networks is never mistaken for a link.
  • Reconnect. The socket client reconnects a dropped connection; when one ends, a new one is opened after a jittered backoff, 1 s doubling to 5 min, ±20 %. rate_limited waits as long as the server said, account_closed an hour, both as paused; token_invalid, token_revoked, token_rotated, connection_deleted, protocol_unsupported and superseded end the loop as refused until a person acts.
  • Refusals. DoclinkRefusedError carries the server's refusal (code, status, field, reason, retryAfterMs, supportedVersions); DoclinkRefusals.refusal(of:) reads one from any error.

Words

DoclinkWords.word(_:_:_:) words an outcome, a refusal reason, a link reason, a job's state and failure and a device's status in English and German ({service} is the server's name as the client shows it). The values have their own: ack.words(.de, service: "nevermind.finance") gives "Von nevermind.finance übernommen", status.words(.en, service:) and refusal.words(.en, service:) say why a link was refused, paused or ended.

Not in this build

  • Scanning and printing. doclink's devices — exposing local scanners and printers to a connection, the server's scan and print jobs — are left out: the client offers neither scan nor print, and refuses a server that asks anyway (feature_unavailable, job_unknown), as the TypeScript client without a device adapter does. Their contracts are generated with the rest.
  • The coming extension (a client kind, sources and retrieval jobs the server starts, watched runs with JPEG frames) follows in a minor release. A feature is added as its own part of the client: the contracts are generated again, the feature joins DoclinkClient.supportedFeatures, its handlers and requests live in their own extension of the client, and what the host has to answer is a protocol of its own, handed in through a new optional member of the configuration — nothing a host writes today changes.

Contracts

Sources/Doclink/Generated/DoclinkContracts.swift is generated from the TypeScript of @fin.cx/doclink (a development dependency) by the generator of @api.global/swiftsupport, with swiftsupport.config.json:

pnpm run generate          # writes the file
pnpm run generate:check    # exit 1 when it is out of date (swift test checks it too)

It holds every type that travels or that doclink states as data: the fifteen contracts in both directions and their data, the refusal data and codes, the backoff, the client's status and its states, the reasons of a failed check, the keys and languages of the words. Wire names and shapes are doclink's; doclink's numbers are TypeScript numbers without @asType integer, so they are Double in Swift (a sequence, a size, a moment in epoch milliseconds — all whole numbers below 2^53).

Written by hand, because they are values or behaviour the generator does not carry: the constants (DoclinkConstants), the words (DoclinkWords), the checks (DoclinkValidation, with DoclinkCheck as its Swift result), the chunks (DoclinkChunks), the reconnect rules (DoclinkReconnect, with DoclinkReconnectAdvice), the refusal statuses and errors (DoclinkRefusals, DoclinkRefusedError), the outbox adapter (DoclinkOutboxAdapter) and the client. swift test holds the constants, the lists, the refusal statuses and the words against the installed @fin.cx/doclink.

Development

pnpm install        # the generator, doclink and the TypedSocket 9 server the Swift tests run against
swift test          # the helpers; the client against a real DoclinkServer; the drift of what is written by hand
pnpm run generate
xcodebuild -scheme fincx-swiftsupport -destination 'generic/platform=iOS Simulator' build

The client tests start Tests/Fixtures/doclinkserver.mjs with node (on PATH): real DoclinkServers of @fin.cx/doclink 1.1.0 on TypedSocket and SmartServe with a host kept in memory, one per test, driven through a control endpoint (start, stop and restart on the same port, revoke, close a connection, hold heartbeats, deliver acknowledgements, ask for a replay, read the server's state). Without node or the installed dependencies those suites are skipped.

This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the license.md file.

Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.

Trademarks

This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.

Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.

Company Information

Task Venture Capital GmbH Registered at District Court Bremen HRB 35230 HB, Germany

For any legal inquiries or further information, please contact us via email at hello@task.vc.

By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

S
Description
No description provided
Readme
134 KiB
Languages
Swift 94.2%
JavaScript 5.8%