Tüm Yazılar
KategoriSwift
Okuma Süresi
22 dk okuma
Yayın Tarihi
...
Kelime Sayısı
1.735kelime

Kahveni hazırla - bu içerikli bir makale!

Swift Distributed Actors ile dagitik sistem gelistirme. Actor isolation, distributed method call, Codable transport ve cluster yonetimi.

Swift Distributed Actors: Dagitik Sistemlerde Swift

# Swift Distributed Actors: Dagitik Sistemlerde Swift

Swift 5.7 ile gelen distributed actor kavrami, dagitik sistemlerin gelistirilmesini kokten degistirdi. Ayni dilde hem mobil uygulama hem de dagitik backend servisi yazabilmek, Swift ekosisteminin en heyecan verici gelismelerinden biri. Bu rehberde distributed actor'lerin tum detaylarini, transport layer implementasyonunu ve production senaryolarini inceleyecegiz.

Onkosul: Bu rehberi takip etmek icin Swift Concurrency (async/await, actor) konularinda temel bilgiye sahip olmaniz gerekmektedir.

Icindekiler


1. Distributed Actor Nedir?

Normal bir actor sadece ayni process icinde calisir. distributed actor ise farkli makinelerde, farkli process'lerde calisan actor'ler arasinda iletisim kurmamizi saglar - sanki local bir fonksiyon cagiriyormusuz gibi.

Temel Farklar

Ozellik
Actor
Distributed Actor
**Konum**
Ayni process
Farkli process/makine
**Erisim**
Dogrudan
Network uzerinden
**Hata**
Synchronous
throws (network hatasi)
**Kimlik**
Reference
ActorID (serializable)
**Transport**
Yok
Gerekli (custom/library)
**Performans**
Hizli
Network latency
**Isolation**
Compiler-enforced
Compiler + runtime
**Serialization**
Gerekli degil
Codable zorunlu

Neden Distributed Actors?

Geleneksel dagitik sistemlerde RPC (Remote Procedure Call) kullanirsiniz. Sorunlar:

  • Farkli serialization formatlari
  • Manuel hata yonetimi
  • Tip guvenligi yok
  • Interface tanimlamalari ayri dosyalarda

Distributed actors tum bunlari cozuyor: derleyici seviyesinde tip guvenligi, otomatik serialization ve transparan remote call'lar.


2. Local vs Distributed Actor

swift
1// Normal actor - sadece local
2actor BankAccount {
3 let id: String
4 private var balance: Double = 0
5 
6 init(id: String) {
7 self.id = id
8 }
9 
10 func deposit(_ amount: Double) {
11 balance += amount
12 }
13 
14 func getBalance() -> Double {
15 return balance
16 }
17}
18 
19// Distributed actor - local VEYA remote
20distributed actor DistributedBankAccount {
21 typealias ActorSystem = ClusterSystem
22 
23 private var balance: Double = 0
24 
25 distributed func deposit(_ amount: Double) {
26 balance += amount
27 }
28 
29 distributed func getBalance() -> Double {
30 return balance
31 }
32 
33 // distributed OLMAYAN fonksiyonlar sadece local erisim
34 func internalAudit() -> AuditReport {
35 // Bu fonksiyon remote'dan cagrilamaz
36 AuditReport(balance: balance, timestamp: .now)
37 }
38}

Easter Egg

Gizli bir bilgi buldun!

Bu bölümde gizli bir bilgi var. Keşfetmek ister misin?


3. Temel Kullanim

swift
1import Distributed
2 
3// 1. Actor System tanimla
4distributed actor GamePlayer {
5 typealias ActorSystem = ClusterSystem
6 
7 let username: String
8 private var score: Int = 0
9 private var level: Int = 1
10 
11 init(username: String, actorSystem: ActorSystem) {
12 self.actorSystem = actorSystem
13 self.username = username
14 }
15 
16 distributed func addScore(_ points: Int) {
17 score += points
18 if score >= level * 1000 {
19 level += 1
20 }
21 }
22 
23 distributed func getStats() -> PlayerStats {
24 PlayerStats(
25 username: username,
26 score: score,
27 level: level
28 )
29 }
30 
31 distributed func challenge(_ opponent: GamePlayer) async throws -> ChallengeResult {
32 let myStats = getStats()
33 let opponentStats = try await opponent.getStats()
34 
35 // Basit bir challenge mekanigi
36 if myStats.score > opponentStats.score {
37 return .won
38 } else if myStats.score < opponentStats.score {
39 return .lost
40 } else {
41 return .draw
42 }
43 }
44}
45 
46struct PlayerStats: Codable, Sendable {
47 let username: String
48 let score: Int
49 let level: Int
50}
51 
52enum ChallengeResult: Codable, Sendable {
53 case won, lost, draw
54}

Distributed Fonksiyon Kurallari

  • Tum parametre ve donus turleri Codable & Sendable olmali
  • Her distributed fonksiyon throws olarak ele alinir (network hatasi)
  • Remote cagirilarda await zorunludur (local olsa bile)
  • Property'ler distributed olamaz, fonksiyon kullanin

4. Transport Layer

Distributed actors, bir DistributedActorSystem uzerinden haberlesir. Bu transport layer'i kendiniz yazabilir veya hazir kutuphaneler kullanabilirsiniz.

swift
1// Basit bir in-memory transport ornegi (test icin ideal)
2final class LocalTestingActorSystem: DistributedActorSystem {
3 typealias ActorID = String
4 typealias InvocationEncoder = LocalInvocationEncoder
5 typealias InvocationDecoder = LocalInvocationDecoder
6 typealias SerializationRequirement = Codable
7 typealias ResultHandler = LocalResultHandler
8 
9 private var actors: [String: any DistributedActor] = [:]
10 
11 func resolve<Act>(id: ActorID, as actorType: Act.Type) throws -> Act?
12 where Act: DistributedActor, ActorID == Act.ID {
13 actors[id] as? Act
14 }
15 
16 func assignID<Act>(_ actorType: Act.Type) -> ActorID
17 where Act: DistributedActor, ActorID == Act.ID {
18 UUID().uuidString
19 }
20 
21 func actorReady<Act>(_ actor: Act)
22 where Act: DistributedActor, ActorID == Act.ID {
23 actors[actor.id] = actor
24 }
25 
26 func resignID(_ id: ActorID) {
27 actors.removeValue(forKey: id)
28 }
29 
30 func makeInvocationEncoder() -> InvocationEncoder {
31 LocalInvocationEncoder()
32 }
33 
34 func remoteCall<Act, Err, Res>(
35 on actor: Act,
36 target: RemoteCallTarget,
37 invocation: inout InvocationEncoder,
38 throwing: Err.Type,
39 returning: Res.Type
40 ) async throws -> Res
41 where Act: DistributedActor,
42 Err: Error,
43 Res: SerializationRequirement {
44 fatalError("Local-only system, remote call desteklenmez")
45 }
46 
47 func remoteCallVoid<Act, Err>(
48 on actor: Act,
49 target: RemoteCallTarget,
50 invocation: inout InvocationEncoder,
51 throwing: Err.Type
52 ) async throws
53 where Act: DistributedActor, Err: Error {
54 fatalError("Local-only system, remote call desteklenmez")
55 }
56}

Transport Secenekleri

Transport
Kullanim Alani
Avantaj
Dezavantaj
**WebSocket**
Realtime uygulamalar
Dusuk latency
Baglanti yonetimi
**HTTP/2**
REST-benzeri servisler
Yaygin destek
Overhead
**gRPC**
Mikroservisler
Yuksek performans
Karmasiklik
**Local (test)**
Unit test
Hizli, basit
Sadece test
**Custom TCP**
Oyun serverlari
Tam kontrol
Cok is

5. Distributed Method Call Mekanigi

Bir distributed fonksiyon cagrildiginda arka planda neler olur:

  1. Serialization: Parametreler Codable ile serialize edilir
  2. Routing: ActorSystem, hedef actor'un konumunu bulur
  3. Transport: Serialized veri network uzerinden gonderilir
  4. Deserialization: Hedef tarafta parametreler deserialize edilir
  5. Execution: Fonksiyon local olarak calistirilir
  6. Response: Sonuc ayni yoldan geri doner

6. Codable ve Serialization

Distributed actor'lerdeki tum paylasilan tipler Codable & Sendable olmalidir.

swift
1// Tum distributed fonksiyon parametreleri ve donus turleri
2// Codable & Sendable olmak zorunda
3 
4struct GameMove: Codable, Sendable {
5 let playerId: String
6 let position: Position
7 let timestamp: Date
8 let moveType: MoveType
9}
10 
11struct Position: Codable, Sendable {
12 let x: Int
13 let y: Int
14}
15 
16enum MoveType: String, Codable, Sendable {
17 case attack
18 case defend
19 case move
20 case special
21}
22 
23// Distributed actor'de kullanim
24distributed actor GameSession {
25 typealias ActorSystem = ClusterSystem
26 
27 private var moves: [GameMove] = []
28 private var players: [String: GamePlayer] = [:]
29 
30 distributed func makeMove(_ move: GameMove) throws -> MoveResult {
31 guard players[move.playerId] != nil else {
32 throw GameError.playerNotFound
33 }
34 
35 // Hareket validasyonu
36 guard isValidMove(move) else {
37 throw GameError.invalidMove
38 }
39 
40 moves.append(move)
41 return MoveResult(accepted: true, newState: currentState())
42 }
43 
44 distributed func getHistory() -> [GameMove] {
45 return moves
46 }
47 
48 private func isValidMove(_ move: GameMove) -> Bool {
49 // Oyun kurallari kontrolu
50 return true
51 }
52 
53 private func currentState() -> GameState {
54 GameState(moveCount: moves.count, lastMove: moves.last)
55 }
56}
57 
58struct MoveResult: Codable, Sendable {
59 let accepted: Bool
60 let newState: GameState
61}
62 
63struct GameState: Codable, Sendable {
64 let moveCount: Int
65 let lastMove: GameMove?
66}
67 
68enum GameError: Error, Codable, Sendable {
69 case playerNotFound
70 case invalidMove
71 case sessionExpired
72}

7. Cluster Yonetimi

Production ortaminda birden fazla node'un birlikte calismasi gerekir. Cluster yonetimi, node discovery, health check ve failover konularini kapsar.

Cluster Mimarisi

  • Leader Election: Bir node cluster'i yonetir
  • Membership: Node'larin katilimi ve ayrilmasi
  • Health Check: Duzenli kalp atisi kontrolu
  • Failover: Ariza durumunda otomatik gecis

8. Hata Yonetimi

Dagitik sistemlerde hata kacinilmazdir. Network kesintisi, timeout, node cokmeleri...

swift
1// Retry mekanizmasi ile distributed call
2func fetchPlayerStatsWithRetry(
3 player: GamePlayer,
4 maxRetries: Int = 3
5) async throws -> PlayerStats {
6 var lastError: Error?
7 
8 for attempt in 1...maxRetries {
9 do {
10 return try await player.getStats()
11 } catch {
12 lastError = error
13 // Exponential backoff
14 let delay = UInt64(pow(2.0, Double(attempt))) * 100_000_000
15 try await Task.sleep(nanoseconds: delay)
16 }
17 }
18 
19 throw lastError ?? DistributedSystemError.unknown
20}
21 
22enum DistributedSystemError: Error {
23 case unknown
24 case nodeUnreachable
25 case timeout
26 case serializationFailed
27}

9. Testing Stratejileri

Distributed actor'leri test etmek icin local actor system kullanin.

Test Ornegi

  • Unit test: LocalTestingActorSystem ile
  • Integration test: Gercek transport ile
  • Chaos testing: Network hatasi simulasyonu

10. Production Ornekleri

Kullanim Alanlari

Senaryo
Aciklama
Fayda
**Chat uygulamasi**
Her kullanici bir actor
Dogal isolation
**Oyun serveri**
Her session bir actor
State yonetimi
**IoT gateway**
Her cihaz bir actor
Olceklenebilirlik
**Mikroservis**
Her servis bir actor cluster
Tip guvenligi
**Edge computing**
Cihaz-server iletisimi
Transparan RPC

11. Sonuc ve Oneriler

Swift Distributed Actors, dagitik sistem gelistirmeyi dramatik sekilde basitlestiriyor. Ancak henuz ekosistem olgunlasmadi - production kullanimi icin dikkatli olun.

Aksiyon Plani

  • Swift Concurrency temellerini ogrenmeden baslamayin
  • Kucuk bir projede local actor system ile deneyin
  • Transport layer secimini kullanim senaryonuza gore yapin
  • Hata yonetimi ve retry mekanizmasini mutlaka ekleyin
  • Monitoring ve logging altyapisini kurun

ALTIN İPUCU

Bu yazının en değerli bilgisi

Bu ipucu, yazının en önemli çıkarımını içeriyor.

Okuyucu Ödülü

Tebrikler! Bu yazıyı sonuna kadar okuduğun için sana özel bir hediyem var:

Etiketler

#Swift#Distributed Actors#Concurrency#Backend#Networking#Architecture
Muhittin Çamdalı

Muhittin Çamdalı

Senior iOS Developer

12+ yıllık deneyime sahip iOS Developer. Swift, SwiftUI ve modern iOS mimarileri konusunda uzman. Apple platformlarında performanslı ve kullanıcı dostu uygulamalar geliştiriyorum.

iOS Geliştirme Haberleri

Haftalık Swift tips, SwiftUI tricks ve iOS best practices. Spam yok, sadece değerli içerik.

Gizliliğinize saygı duyuyoruz. İstediğiniz zaman abonelikten çıkabilirsiniz.

Paylaş

Bunu da begenebilirsiniz