Section 11/161 menit

11. Distributed Actors

11. Distributed Actors

Distributed actors (Swift 5.7, SE-0336) memperluas actor model ke across process dan network boundaries. Setiap distributed actor bisa berada di process berbeda atau bahkan machine berbeda.

Konsep Dasar

swift
import Distributed

// Distributed actor: seperti actor biasa tapi bisa di remote process
distributed actor Counter {
    var count: Int = 0

    // Hanya distributed func yang bisa dipanggil dari remote
    distributed func increment() async throws {
        count += 1
    }

    distributed func getValue() async throws -> Int {
        return count
    }

    // Method non-distributed: hanya bisa dipanggil dari process yang sama
    func resetInternal() {
        count = 0
    }
}

ActorSystem: Backend Transport

ActorSystem mengabstraksi transport layer (in-process, TCP, gRPC, dsb):

swift
// Contoh: LocalTestingDistributedActorSystem untuk testing in-process
import DistributedCluster  // hypothetical package

// Konfigurasi actor system
let system = LocalTestingDistributedActorSystem()

// Buat distributed actor di system
let counter = Counter(actorSystem: system)
let counterID = counter.id

// Panggil method
try await counter.increment()
let value = try await counter.getValue()
print(value)  // 1

// Di process lain: resolve actor dari ID
let remoteCounter = try Counter.resolve(id: counterID, using: system)
try await remoteCounter.increment()
// → kirim message ke process yang punya counter

Distributed Actor Lifecycle

swift
// Distributed actor bisa resign dari system
distributed actor SessionManager: LifecycleWatch {
    var activeSessions: [String: Session] = [:]

    // Dipanggil saat actor lain yang di-watch resign/terputus
    func actorTerminated(id: ActorID) async {
        // Cleanup sessions dari actor yang terminated
        activeSessions.removeValue(forKey: id.description)
    }

    distributed func createSession(userID: String) async throws -> Session {
        let session = Session(userID: userID)
        activeSessions[userID] = session
        return session
    }
}

struct Session: Sendable, Codable { let userID: String }

Distributed Actor untuk IPC (Inter-Process Communication)

swift
// Contoh: extension process berkomunikasi dengan host app via distributed actors
// Berguna untuk: App Extensions, XPC services, multiple windows

distributed actor ExtensionBridge {
    // Dipanggil dari extension untuk push update ke host app
    distributed func updateBadgeCount(_ count: Int) async throws
    distributed func sendNotification(_ message: String) async throws
    distributed func fetchSharedState() async throws -> SharedAppState
}

struct SharedAppState: Sendable, Codable {
    let userID: String
    let lastSyncDate: Date
}

// Host app: buat actor dan daftarkan ke system
// Extension: resolve actor dari system dan panggil method