Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

swift-state-machine-patterns

БесплатноБез исполняемых скриптовНе проверен

Build type-safe Swift state machines with enum states and action-based transitions. Use for lifecycle or protocol flows, reentrancy-sensitive operations, or…

nonameplumот nonameplum★ 17 звёзд на GitHub

Об этом скилле

Swift State Machine Patterns

When to use

  • Reentrancy-sensitive flows
  • Protocol or lifecycle logic with strict transition rules
  • Async streams or continuations that need cancellation safety
  • Boundaries where invalid state must be unrepresentable

Core rules

  1. Model state as an enum with associated values. Each case carries only data valid in that state.
  2. Keep the state machine as a value type (struct) with a private state.
  3. Transition methods are pure: mutate state and return Action values.
  4. Execute side effects outside the transition (and outside any lock).
  5. Use strong types for events (enum or method parameters), actions, and identifiers. Avoid strings or boolean flags for state.
  6. Prefer per-state structs for larger associated data to prevent accidental access to irrelevant fields.
  7. Make invalid states unrepresentable by construction, not by runtime checks.

Sub-state pattern

Model each state as a dedicated struct and store it as an associated value in the enum. Capabilities are expressed as protocols and only adopted by states that support them.

  • Use one struct per state (IdleState, ActiveState, QuiescingState).
  • Store only the fields valid in that state; move shared data into protocols.
  • Use init(from:) to build the next state from the prior one and copy only relevant fields.
  • Use capability protocols (e.g., MaySendFrames, HasLocalSettings) to keep helpers constrained to valid states.
  • Optional: a modifying sentinel state can avoid CoW during transitions.
private struct IdleState: ConnectionStateWithRole, ConnectionStateWithConfiguration { /* ... */ }
private struct ActiveState: ConnectionStateWithRole, HasLocalSettings, HasRemoteSettings { /* ... */ }

private enum State {
  case idle(IdleState)
  case active(ActiveState)
}

Usage pattern: driver + state machine

Embed the state machine inside a handler/coordinator that owns side effects. The driver calls transition methods, applies effects, and decides whether to forward/emit/drop inputs.

final class ProtocolHandler {
  private var stateMachine = ConnectionStateMachine()
  private var pendingEvents: [UserEvent] = []

  func receive(_ message: Message) {
    let result = stateMachine.receive(message)
    apply(effect: result.effect)

    switch result.result {
    case .succeed:
      forward(message)
    case .ignore:
      break
    case .connectionError(let error):
      handleConnectionError(error)
    case .streamError(let id, let error):
      handleStreamError(id, error)
    }

    flushPendingEvents()
  }

  func send(_ message: Message) {
    let result = stateMachine.send(message)
    apply(effect: result.effect)
    if case .succeed = result.result {
      write(message)
    } else {
      handleSendError(result.result)
    }
    flushPendingEvents()
  }
}

Pattern: Method-per-event (SwiftNIO style)

Model events as dedicated mutating methods (send/receive). Each method switches on state and returns a typed result or actions. This mirrors HTTP2ConnectionStateMachine in SwiftNIO HTTP/2.

struct ConnectionStateMachine: Sendable {
  private enum State: Sendable {
    case idle(IdleState)
    case active(ActiveState)
    case quiescing(QuiescingState)
  }

  private struct IdleState: Sendable { }
  private struct ActiveState: Sendable { var streamID: Int }
  private struct QuiescingState: Sendable { var lastStreamID: Int }

  enum Action: Sendable {
    case sendPreface
    case closeStream(id: Int)
    case ignore
  }

  private var state: State = .idle(IdleState())

  mutating func receiveGoaway(lastStreamID: Int) -> [Action] {
    switch state {
    case .active(let data):
      state = .quiescing(QuiescingState(lastStreamID: lastStreamID))
      return lastStreamID < data.streamID ? [.closeStream(id: data.streamID)] : []
    default:
      return [.ignore]
    }
  }

  mutating func sendPreface() -> [Action] {
    switch state {
    case .idle:
      state = .active(ActiveState(streamID: 0))
      return [.sendPreface]
    default:
      return [.ignore]
    }
  }
}

Notes:

  • For complex inputs, use a nested Request struct to keep method signatures small.
  • Share repeated transitions in private helpers that mutate state and return actions.
  • Expose read-only query helpers (e.g., isConnected) as computed properties.
  • When each event returns a different shape, use per-event action enums (NextAction, FinishAction) instead of a single shared Action.
  • Use a .modifying sentinel state to avoid CoW when updating associated data.
  • Trap impossible transitions with preconditionFailure to keep invariants strict.
  • Track suspended and cancelled sets with placeholder IDs for out-of-order cancel.
  • Model terminal outcomes with a Termination enum (e.g., finished vs failed).
  • Return optional actions when an event produces no side effects.

SwiftNIO-derived refinements

From NIOTypedHTTPClientUpgraderStateMachine and `NIO

Полный SKILL.md на GitHub

Установить swift-state-machine-patterns в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл swift-state-machine-patterns?

Build type-safe Swift state machines with enum states and action-based transitions. Use for lifecycle or protocol flows, reentrancy-sensitive operations, or async/concurrent workflows.

Как установить скилл swift-state-machine-patterns?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл swift-state-machine-patterns запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить swift-state-machine-patterns с