Hands-on journey · Swift 6+
Learn CoAkka Runtime with Swift
Pin the exact SwiftPM tag, preserve both operation and close failures, and learn Embedded first. Advanced keeps the target while moving the handler to a peer, then opens File Lane, Stream Lane, and effective Monitor facts.
Beginner · 01 / 04
Create a package and receive the first reply
Use Swift 6 or newer. The package pins exact tag 3.3.2. For each episode, replace Sources/CoAkkaDemo/main.swift; keep AppScope.swift so cleanup failures remain observable.
swift --versionmkdir -p coakka-swift-demo/Sources/CoAkkaDemo
cd coakka-swift-demo// swift-tools-version: 6.0
import PackageDescription
let package = Package(
name: "CoAkkaSwiftDemo",
platforms: [.macOS(.v13)],
dependencies: [
.package(
url: "https://github.com/phuong-tran/coakka-runtime-swift.git",
exact: "3.3.2"
)
],
targets: [
.executableTarget(
name: "CoAkkaDemo",
dependencies: [
.product(name: "CoAkkaRuntime", package: "coakka-runtime-swift")
]
)
]
)
enum AppScopeError: Error {
case operationAndCleanup(any Error, any Error)
}
func withThrowingCleanup<T>(
_ operation: () throws -> T,
cleanup: () throws -> Void
) throws -> T {
let outcome = Result(catching: operation)
do {
try cleanup()
} catch {
if case .failure(let primary) = outcome {
throw AppScopeError.operationAndCleanup(primary, error)
}
throw error
}
return try outcome.get()
}
import CoAkkaRuntime
import Foundation
let target = "customers.accept"
let runtime = try RuntimeHost.startLocal(
systemName: "customer-app",
target: target,
nodeID: "customer-app-1"
)
try withThrowingCleanup({
try runtime.registerTextHandler(target) { name in "accepted-\(name)" }
let reply = try runtime.askText(
source: "customer-api",
target: target,
payload: "hello",
timeoutMs: 2_000
)
print(reply)
}, cleanup: runtime.close)
swift run CoAkkaDemoExpected output
accepted-hello
RuntimeHost.startLocal- Creates an Embedded owner and a local route for exactly one target.
registerTextHandler- A short UTF-8 handler; Core still owns delivery and outcome.
askText- Swift's synchronous request/reply projection.
withThrowingCleanup- Preserves operation and
close()failures while always running cleanup.
Beginner · 02 / 04
Name the work
Replace main.swift with the file below. The caller uses target orders.quote without knowing where the handler runs.
import CoAkkaRuntime
import Foundation
let target = "orders.quote"
let runtime = try RuntimeHost.startLocal(
systemName: "orders",
target: target,
nodeID: "orders-swift-1"
)
try withThrowingCleanup({
try runtime.registerTextHandler(target) { quantity in
String(Int(quantity)! * 120_000)
}
for quantity in [1, 2] {
let reply = try runtime.askText(
source: "checkout",
target: target,
payload: String(quantity),
timeoutMs: 2_000
)
print("quantity=\(quantity) quote=\(reply) VND")
}
}, cleanup: runtime.close)
swift run CoAkkaDemoExpected output
quantity=1 quote=120000 VND quantity=2 quote=240000 VND
Beginner · 03 / 04
Read a structured Deadletter
Match RuntimeError.deadletter and read the stable numeric reason; do not classify by error description.
import CoAkkaRuntime
import Foundation
let runtime = try RuntimeHost.startLocal(
systemName: "orders",
target: "orders.quote",
nodeID: "orders-swift-1"
)
try withThrowingCleanup({
do {
_ = try runtime.askText(
source: "checkout",
target: "orders.missing",
payload: "1",
timeoutMs: 2_000
)
} catch RuntimeError.deadletter(let deadletter) {
print(
"deadletter reason=\(deadletter.reasonCode) " +
"target=\(deadletter.originalTarget)"
)
}
}, cleanup: runtime.close)
swift run CoAkkaDemoExpected output
deadletter reason=2 target=orders.missing
Beginner · 04 / 04
Let the app own RuntimeHost
Create the owner at the app composition root, pass it into business code, and close it during app shutdown.
import CoAkkaRuntime
import Foundation
func runCheckout(_ runtime: RuntimeHost) throws {
let reply = try runtime.askText(
source: "checkout",
target: "orders.quote",
payload: "2",
timeoutMs: 2_000
)
print("checkout total=\(reply) VND")
}
let target = "orders.quote"
let runtime = try RuntimeHost.startLocal(
systemName: "orders",
target: target,
nodeID: "orders-swift-1"
)
try withThrowingCleanup({
try runtime.registerTextHandler(target) { quantity in
String(Int(quantity)! * 120_000)
}
try runCheckout(runtime)
}, cleanup: runtime.close)
swift run CoAkkaDemoExpected output
checkout total=240000 VND
Advanced · 05 / 08
Move the handler to a peer
Create two copies of the package, keep the same Package.swift/AppScope.swift in each, and use one file below as each main.swift. The target stays unchanged; CoAkka Runtime does not require Kubernetes.
import CoAkkaRuntime
import Foundation
let target = "orders.quote"
let startSpec = ConnectorStartSpec(
systemName: "orders",
nodeID: "quote-swift-1",
routes: [.local(target)],
network: .networkNode(
bindHost: "127.0.0.1",
bindPort: 19_323,
advertiseHost: "127.0.0.1",
advertisePort: 19_323
)
)
let runtime = try RuntimeHost.start(startSpec)
try withThrowingCleanup({
try runtime.registerTextHandler(target) { quantity in
String(Int(quantity)! * 120_000)
}
print("quote service ready on 127.0.0.1:19323")
print("Press Enter to stop...")
_ = readLine()
}, cleanup: runtime.close)
import CoAkkaRuntime
import Foundation
let target = "orders.quote"
let startSpec = ConnectorStartSpec(
systemName: "orders",
nodeID: "checkout-swift-1",
routes: [.remote(target, host: "127.0.0.1", port: 19_323)],
network: .outboundOnly()
)
let runtime = try RuntimeHost.start(startSpec)
try withThrowingCleanup({
let reply = try runtime.askText(
source: "checkout",
target: target,
payload: "3",
timeoutMs: 2_000
)
print("order quote: \(reply) VND")
}, cleanup: runtime.close)
swift run CoAkkaDemoCaller output
order quote: 360000 VND
.networkNode- The service binds and advertises one reachable endpoint.
.outboundOnly- The caller opens no listener.
.remote- Swift 3.3.2 projects an exact single remote endpoint; use the shared contract for multi-endpoint strategies.
Advanced · 06 / 08
File Lane with an exact-owner grant
Keep blocking waits away from the UI/main actor. SEND and RECEIVE must both be terminal and successful before forget/close.
import CoAkkaRuntime
import Foundation
func waitForFileTerminal(
lane: FileLane,
transferID: String,
direction: FileTransferDirection
) throws -> FileTransferSnapshot {
var sequence: UInt64 = 0
while true {
let snapshot = try lane.waitTransfer(
transferID,
direction: direction,
afterSequence: sequence,
timeoutMs: 5_000
)
if snapshot.terminal { return snapshot }
sequence = snapshot.updateSequence
}
}
let root = FileManager.default.temporaryDirectory
.appendingPathComponent("coakka-swift-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }
let source = root.appendingPathComponent("source.txt")
let destination = root.appendingPathComponent("received.txt")
try Data("hello from File Lane".utf8).write(to: source)
let digest = try FileLane.sha256(path: source.path)
let receiver = try FileLane.openOwned(
owner: LaneOwnerConfig(
ownerInstanceID: "receiver-swift-1",
advertisedHost: "127.0.0.1"
)
)
try withThrowingCleanup({
let sender = try FileLane.open()
try withThrowingCleanup({
let transferID = "swift-file-1"
let grant = try receiver.prepareReceiveGrant(
FileReceiveSpec(
transferID: transferID,
authorizationToken: "file-token-1",
destinationPath: destination.path,
expectedSize: digest.size,
expectedSHA256: digest.sha256
)
)
try sender.submitSend(grant.sendSpec(sourcePath: source.path, timeoutMs: 5_000))
let sent = try waitForFileTerminal(
lane: sender,
transferID: transferID,
direction: .send
)
let received = try waitForFileTerminal(
lane: receiver,
transferID: transferID,
direction: .receive
)
guard sent.succeeded, received.succeeded else {
throw RuntimeError.contractViolation("File Lane did not complete on both peers")
}
print(String(decoding: try Data(contentsOf: destination), as: UTF8.self))
try sender.forget(transferID, direction: .send)
try receiver.forget(transferID, direction: .receive)
}, cleanup: sender.close)
}, cleanup: receiver.close)
swift run CoAkkaDemoExpected output
hello from File Lane
Advanced · 07 / 08
Stream Lane with borrowed raw buffers
UnsafeMutableRawBufferPointer/UnsafeRawBufferPointer are valid only during the callback. The example copies data before retaining it.
import CoAkkaRuntime
import Foundation
final class FrameStore: @unchecked Sendable {
private let lock = NSLock()
private var outgoing = [Data("frame-one".utf8), Data("frame-two".utf8)]
private var incoming: [String] = []
func next(into destination: UnsafeMutableRawBufferPointer) -> StreamSourceResult {
lock.lock()
defer { lock.unlock() }
guard !outgoing.isEmpty else { return .end }
let frame = outgoing.removeFirst()
frame.withUnsafeBytes { destination.copyMemory(from: $0) }
return .frame(size: frame.count)
}
func consume(_ data: UnsafeRawBufferPointer) -> StreamConsumerDecision {
lock.lock()
incoming.append(String(decoding: Data(data), as: UTF8.self))
lock.unlock()
return .continue
}
func summary() -> String {
lock.lock()
defer { lock.unlock() }
return incoming.joined(separator: ", ")
}
}
func waitForStreamTerminal(
lane: StreamLane,
sessionID: String,
direction: StreamDirection
) throws -> StreamSessionSnapshot {
var sequence: UInt64 = 0
while true {
let snapshot = try lane.waitSession(
sessionID,
direction: direction,
afterSequence: sequence,
timeoutMs: 5_000
)
if snapshot.terminal { return snapshot }
sequence = snapshot.updateSequence
}
}
let frames = FrameStore()
let publisher = try StreamLane.openOwned(
owner: LaneOwnerConfig(
ownerInstanceID: "publisher-swift-1",
advertisedHost: "127.0.0.1"
)
)
try withThrowingCleanup({
let subscriber = try StreamLane.open()
try withThrowingCleanup({
let sessionID = "swift-stream-1"
let grant = try publisher.preparePublishGrant(
StreamPublishSpec(
sessionID: sessionID,
authorizationToken: "stream-token-1",
formatID: 1,
maxFrameBytes: 1_024,
source: frames.next
)
)
try subscriber.subscribe(
grant.subscribeSpec(
initialWindowBytes: 4_096,
timeoutMs: 5_000,
consumer: { data, _ in frames.consume(data) }
)
)
let published = try waitForStreamTerminal(
lane: publisher,
sessionID: sessionID,
direction: .publish
)
let subscribed = try waitForStreamTerminal(
lane: subscriber,
sessionID: sessionID,
direction: .subscribe
)
guard published.succeeded, subscribed.succeeded else {
throw RuntimeError.contractViolation("Stream Lane did not end on both peers")
}
print(frames.summary())
try publisher.forget(sessionID, direction: .publish)
try subscriber.forget(sessionID, direction: .subscribe)
}, cleanup: subscriber.close)
}, cleanup: publisher.close)
swift run CoAkkaDemoExpected output
frame-one, frame-two
Advanced · 08 / 08
Read Monitor facts through snapshots
Swift 3.3.2 projects the startup choice plus Core health/stats; do not invent a Monitor wait API from another connector.
import CoAkkaRuntime
import Foundation
let target = "orders.quote"
let runtime = try RuntimeHost.start(
ConnectorStartSpec(
systemName: "orders",
nodeID: "monitor-swift-1",
routes: [.local(target)],
enableMonitor: true
)
)
try withThrowingCleanup({
try runtime.registerTextHandler(target) { payload in payload }
_ = try runtime.askText(
source: "checkout",
target: target,
payload: "signal",
timeoutMs: 2_000
)
let startup = try runtime.startupConfig()
let health = try runtime.health()
let stats = try runtime.stats()
print("monitor enabled=\(startup.monitorEnabled)")
print("state=\(health.runtimeState) routes=\(stats.routeCount)")
}, cleanup: runtime.close)
swift run CoAkkaDemoVerified output
monitor enabled=true state=started routes=1