Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/pathways/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1151,6 +1151,31 @@ export class PathwaysBuilder<
}
})

// Listen for leadership changes to auto-start/stop the pump
this.clusterManager.onLeadershipChange((isLeader: boolean) => {
if (isLeader && this.pathwayPump && !this.pathwayPump.isRunning) {
this.logger.info("Became leader, starting pump")
const registrations = Object.keys(this.pathways).map((key) => {
const [flowType, eventType] = key.split("/")
return { flowType, eventType }
})
this.pathwayPump.start(registrations).catch((err) => {
this.logger.error(
"Failed to start pump after becoming leader",
err instanceof Error ? err : new Error(String(err)),
)
})
} else if (!isLeader && this.pathwayPump?.isRunning) {
this.logger.info("Lost leadership, stopping pump")
this.pathwayPump.stop().catch((err) => {
this.logger.error(
"Failed to stop pump after losing leadership",
err instanceof Error ? err : new Error(String(err)),
)
})
}
})

await this.clusterManager.start()

this.logger.info("Cluster started", {
Expand Down
11 changes: 11 additions & 0 deletions src/pathways/cluster/cluster-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ export class ClusterManager {
private wsServer: { shutdown(): Promise<void> } | null = null
private leaderConnection: ClusterSocket | null = null
private eventHandler: ((pathway: string, event: FlowcoreEvent) => Promise<void>) | null = null
private leadershipChangeHandler: ((isLeader: boolean) => void) | null = null

constructor(options: PathwayClusterOptions, logger?: Logger) {
this.coordinator = options.coordinator
Expand All @@ -112,6 +113,14 @@ export class ClusterManager {
this.eventHandler = handler
}

/**
* Set a callback that fires when this instance becomes or loses leadership.
* Used by PathwaysBuilder to auto-start the pump when becoming leader.
*/
onLeadershipChange(handler: (isLeader: boolean) => void) {
this.leadershipChangeHandler = handler
}

/**
* Start the cluster: register instance, begin heartbeat, attempt leader election
*/
Expand Down Expand Up @@ -301,6 +310,7 @@ export class ClusterManager {
this.logger.warn("Lost leader lease", { instanceId: this.instanceId })
this.role = "worker"
this.cleanupLeaderState()
this.leadershipChangeHandler?.(false)
} else {
await this.refreshWorkers()
}
Expand All @@ -311,6 +321,7 @@ export class ClusterManager {

private async onBecomeLeader(): Promise<void> {
await this.refreshWorkers()
this.leadershipChangeHandler?.(true)
}

private async refreshWorkers(): Promise<void> {
Expand Down
Loading