Von Akka (JVM)
actor-ts ist der engste spirituelle Cousin von Akka im TypeScript-Umfeld. Die meisten Konzepte mappen 1:1; viele APIs sind identisch benannt. Dieser Guide führt durch die Übersetzung.
Konzept-Mapping
Abschnitt betitelt „Konzept-Mapping“| Akka (JVM) | actor-ts |
|---|---|
akka.actor.Actor | Actor<TMessage> |
akka.actor.ActorRef | ActorRef<T> |
akka.actor.Props | die Actor-Klasse, eine Factory oder ActorOptions<TMessage> |
tell(message) / ! | tell(message) |
ask(message).mapTo[T] | ref.ask<TRes>(message, timeoutMs) |
context.spawnAnonymous(props) | context.spawnAnonymous(actor) |
OneForOneStrategy | OneForOneStrategy |
AllForOneStrategy | AllForOneStrategy |
become(receive) | context.become(handler) |
stash() / unstashAll() | context.stash() / context.unstashAll() |
context.watch(ref) | context.watch(ref) |
Terminated(ref) | Terminated-Systemnachricht |
PoisonPill | PoisonPill.instance |
Kill | Kill.instance |
setReceiveTimeout(d) | context.setReceiveTimeout(ms) |
EventStream | system.eventStream |
Cluster.get(system).join(...) | Cluster.join(system, settings) |
ClusterSharding | cluster.sharding (+ ShardKey) |
ClusterSingleton | cluster.singleton (+ SingletonKey) |
DistributedPubSub | DistributedPubSub |
DistributedData | DistributedData (per Extension) |
PersistentActor | PersistentActor |
persist(event)(cb) | this.persist(event, afterPersist) |
Akka HTTP | HttpExtension + Route-DSL |
Akka Streams | NICHT verfügbar |
Before/After
Abschnitt betitelt „Before/After“// Akka Scala:class Counter extends Actor { var count = 0 def receive = { case "inc" => count += 1 case "get" => sender() ! count }}
// actor-ts:import { match } from 'ts-pattern';import { Actor, type ActorRef } from 'actor-ts';
type Command = { kind: 'increment' } | { kind: 'get'; replyTo: ActorRef<number> };
class Counter extends Actor<Command> { private count = 0; override onReceive(command: Command): void { match(command) .with({ kind: 'increment' }, () => this.onIncrement()) .with({ kind: 'get' }, (c) => this.onGet(c)) .exhaustive(); }
private onIncrement(): void { this.count++; } private onGet(command: GetCommand): void { command.replyTo.tell(this.count); }}Unterschiede:
- TypeScript braucht explizite Nachrichten-Typen (
Command) - AkkasAnylässt sich nicht übersetzen. sender()wird zu einer explizitenreplyTo-Ref in der Nachricht oder zuthis.sender(Option).- Keine Pattern-Matching-Syntax; nutze
if/elseoderts-pattern.
Supervisor
Abschnitt betitelt „Supervisor“// Akka Scala:override val supervisorStrategy = OneForOneStrategy() { case _: ArithmeticException => Resume case _: NullPointerException => Restart case _: Exception => Escalate}
// actor-ts:override supervisorStrategy = new OneForOneStrategy( decideBy([ { match: ArithmeticError, then: Directive.Resume }, { match: NullPointerError, then: Directive.Restart }, { match: Error, then: Directive.Escalate }, ]),);Benennung + Struktur identisch; die Direktiven sind dieselben.
Cluster + Sharding
Abschnitt betitelt „Cluster + Sharding“// Akka Scala:val cluster = Cluster(system)cluster.join(Address("akka", "MySystem", "host", port))
val region = ClusterSharding(system).start( typeName = "Counter", entityProps = Props[Counter], settings = ClusterShardingSettings(system), extractEntityId = ..., extractShardId = ...,)
// actor-ts:const clusterOptions = ClusterOptions.create() .withHost(host) .withPort(port) .withSeeds(seeds);const cluster = await Cluster.join(system, clusterOptions);
const region = cluster.sharding.start({ typeName: 'Counter', entityActor: Counter, extractEntityId: (message) => message.id, numShards: 100,});Größtenteils Drop-in. Unterschiede:
extractShardIdwird in actor-ts ausextractEntityId + numShardsabgeleitet (shardId = hash(entityId) % numShards). Keine separate Funktion.ClusterShardingSettingssteht inline als Optionen vonstart().
PersistentActor
Abschnitt betitelt „PersistentActor“// Akka Scala:class Account(val id: String) extends PersistentActor { override def persistenceId = s"account-$id" var balance = 0
override def receiveCommand = { case Deposit(amt) => persist(Deposited(amt))(e => balance += e.amount) }
override def receiveRecover = { case Deposited(amt) => balance += amt }}
// actor-ts:class Account extends PersistentActor<Command, Event, State> { constructor(public readonly id: string) { super(); } readonly persistenceId = `account-${this.id}`;
initialState(): State { return { balance: 0 }; }
onEvent(state: State, event: Event): State { return match(event) .with({ kind: 'deposited' }, (e) => ({ balance: state.balance + e.amount })) .exhaustive(); }
onCommand(state: State, command: Command): void { match(command) .with({ kind: 'deposit' }, (c) => this.onDeposit(c)) .exhaustive(); }
private onDeposit(command: DepositCommand): void { this.persist({ kind: 'deposited', amount: command.amount }, () => {}); }}Schlüssel-Unterschiede:
- Ein einziges
onEventstatt geteilterreceiveCommand/receiveRecover. Läuft sowohl beim Persistieren als auch bei Recovery. persist-Callback-Signatur -(newState) => voidstatt(event) => unit.- State ist expliziter Typ-Parameter - Akkas zustandsbehaftete Variable wird zu einer State-Form.
Cluster Singleton
Abschnitt betitelt „Cluster Singleton“// Akka Scala:val singleton = system.spawn( ClusterSingletonManager.props( singletonProps = Props[MyActor], terminationMessage = PoisonPill, settings = ClusterSingletonManagerSettings(system), ), name = "singletonManager",)
// actor-ts:class MyActor extends Actor<MyCommand> { static readonly singleton = SingletonKey.of<MyCommand>('my-singleton');}const singleton = cluster.singleton.start(MyActor);singleton.tell({ kind: 'do-something' });Dasselbe Modell, weniger Zeremonie — der Actor deklariert seine
Identität als Static, und start gibt direkt den Proxy-ActorRef
zurück statt eines Handles zum Auspacken. Ein terminationMessage-
Äquivalent gibt es nicht; ein Node, der die Rotation verlässt, stoppt
sein Kind über den normalen postStop-Pfad.
Nodes, die nur mit dem Singleton sprechen müssen, rufen
cluster.singleton.ref(MyActor) — das Gegenstück zu Akkas
ClusterSingletonProxy.props und zu ClusterSharding.startProxy auf
der Sharding-Seite.
Was fehlt
Abschnitt betitelt „Was fehlt“- Akka Streams - keine Portierung. Nutze Promise-basierte Patterns oder eine separate Streams-Library.
- Akka HTTPs typisierte Route-DSL - actor-ts hat eine eigene DSL, aber sie ist einfacher / weniger feature-reich.
- Akka Persistence Querys reaktive Stream-API - actor-ts hat
PersistenceQuery, aber alsAsyncIterable, nicht als Stream. - Einige fortgeschrittene Supervision-Features - Backoff-Supervision existiert; “watch a Future”-Patterns brauchen manuelles Wiring.
Was besser ist
Abschnitt betitelt „Was besser ist“- TypeScript-Typen - Nachrichten-Typen werden an der
Compile-Grenze geprüft. Keine
Any- /case class-Runtime-Checks. - Buns schneller Start - sub-100 ms statt 1+ Sekunde der JVM.
- Kleinere Binaries - keine JVM zum Ausliefern.
- Einfacheres operationelles Modell - Single-Process JS statt JVM-Tuning.
Migrations-Ansatz
Abschnitt betitelt „Migrations-Ansatz“Für eine bestehende Akka-App, die actor-ts erwägt:
- Nicht alles auf einmal umschreiben. Lass actor-ts in einem neuen Service laufen, der das Akka-System via HTTP/gRPC vorlagert.
- Einen Bounded Context nach dem anderen migrieren - wähle eine self-contained Domäne (Orders, Sessions) und portiere sie.
- Persistenz vorsichtig re-exportieren - von Akka geschriebene Events sind JSON, wenn du Jackson genutzt hast; actor-ts kann sie mit einem EventAdapter lesen.
Wohin als Nächstes
Abschnitt betitelt „Wohin als Nächstes“- Quickstart - actor-ts Hello-World.
- Fundamentals - Übersicht - Konzept-Landkarte.
- Migration - Übersicht - Framework-übergreifender Vergleich.
- from-pekko - für den Pekko-Fork.
