| 1 | Title: State Machines |
| 2 | |
| 3 | [[email protected]] provides a small table-driven state machine for |
| 4 | asynchronous workflows. |
| 5 | |
| 6 | Use it when an object has a finite set of modes and transitions between those |
| 7 | modes may need to wait for asynchronous work. Common examples include |
| 8 | connection lifecycles, authentication handoff, device setup, or UI workflows |
| 9 | where a request must move through well-defined states. |
| 10 | |
| 11 | The state machine serializes transition requests internally, runs transition |
| 12 | callbacks from a fiber, and rejects attempts to use edges that were not declared |
| 13 | up front. |
| 14 | |
| 15 | ## Defining States |
| 16 | |
| 17 | States are represented by a `GEnum` type. This lets libdex validate transition |
| 18 | tables and return enum values from [[email protected]]. |
| 19 | |
| 20 | ```c |
| 21 | typedef enum |
| 22 | { |
| 23 | PASSWORD_DAEMON_INITIAL, |
| 24 | PASSWORD_DAEMON_PREPARE, |
| 25 | PASSWORD_DAEMON_READY, |
| 26 | PASSWORD_DAEMON_LOCKED, |
| 27 | PASSWORD_DAEMON_UNLOCKED, |
| 28 | } PasswordDaemonState; |
| 29 | ``` |
| 30 | |
| 31 | The enum must have a registered `GType`, for example using |
| 32 | `G_DEFINE_ENUM_TYPE()`. |
| 33 | |
| 34 | ## Defining Transitions |
| 35 | |
| 36 | A transition table declares every supported edge. |
| 37 | |
| 38 | ```c |
| 39 | static const DexStateTransition password_daemon_transitions[] = { |
| 40 | { PASSWORD_DAEMON_INITIAL, PASSWORD_DAEMON_PREPARE, enter_prepare }, |
| 41 | { PASSWORD_DAEMON_PREPARE, PASSWORD_DAEMON_READY, enter_ready }, |
| 42 | { PASSWORD_DAEMON_READY, PASSWORD_DAEMON_LOCKED, enter_locked }, |
| 43 | { PASSWORD_DAEMON_LOCKED, PASSWORD_DAEMON_UNLOCKED, enter_unlocked }, |
| 44 | { PASSWORD_DAEMON_UNLOCKED, PASSWORD_DAEMON_LOCKED, enter_locked }, |
| 45 | }; |
| 46 | ``` |
| 47 | |
| 48 | The table is copied and validated when the [[email protected]] is created. |
| 49 | Each entry must use valid enum values and have a transition callback. Duplicate |
| 50 | edges are rejected. |
| 51 | |
| 52 | Once created, the transition table is immutable. There is no API to add |
| 53 | transitions while the state machine is running. |
| 54 | |
| 55 | ## Creating a State Machine |
| 56 | |
| 57 | The constructor accepts user data that is passed to every transition callback. |
| 58 | Use normal C ownership rules for this data. If the state machine should keep an |
| 59 | object alive, pass a strong reference and destroy notify. If it should not, |
| 60 | pass a weak-reference holder instead. |
| 61 | |
| 62 | ```c |
| 63 | daemon->state_machine = |
| 64 | dex_state_machine_new (PASSWORD_DAEMON_TYPE_STATE, |
| 65 | PASSWORD_DAEMON_INITIAL, |
| 66 | password_daemon_transitions, |
| 67 | G_N_ELEMENTS (password_daemon_transitions), |
| 68 | NULL, |
| 69 | 0, |
| 70 | g_object_ref (daemon), |
| 71 | g_object_unref); |
| 72 | ``` |
| 73 | |
| 74 | ## Writing Transition Callbacks |
| 75 | |
| 76 | Transition callbacks use [[email protected]]. |
| 77 | |
| 78 | ```c |
| 79 | static gboolean |
| 80 | enter_prepare (DexStateTransitionContext *context, |
| 81 | gpointer user_data, |
| 82 | GError **error) |
| 83 | { |
| 84 | PasswordDaemon *daemon = user_data; |
| 85 | g_autoptr(GSocket) control = NULL; |
| 86 | |
| 87 | g_assert_cmpuint (dex_state_transition_context_get_from (context), |
| 88 | ==, |
| 89 | PASSWORD_DAEMON_INITIAL); |
| 90 | g_assert_cmpuint (dex_state_transition_context_get_to (context), |
| 91 | ==, |
| 92 | PASSWORD_DAEMON_PREPARE); |
| 93 | |
| 94 | control = dex_await_object (create_control_socket (daemon), error); |
| 95 | if (control == NULL) |
| 96 | return FALSE; |
| 97 | |
| 98 | daemon->control = g_steal_pointer (&control); |
| 99 | |
| 100 | return TRUE; |
| 101 | } |
| 102 | ``` |
| 103 | |
| 104 | Callbacks are run from a fiber, so they may call `dex_await()` and |
| 105 | `dex_await_*()` directly. They should return %TRUE on success or %FALSE with |
| 106 | @error set on failure. |
| 107 | |
| 108 | If a callback succeeds without calling |
| 109 | [[email protected]_state], the state machine commits the |
| 110 | target state from [[email protected]_to]. If the callback |
| 111 | fails before setting state, the state remains unchanged. |
| 112 | |
| 113 | Callbacks may also call [[email protected]_to] to |
| 114 | continue through another declared edge before queued transition requests are |
| 115 | processed. |
| 116 | |
| 117 | ## Requesting Transitions |
| 118 | |
| 119 | Call [[email protected]] to request a transition. The returned |
| 120 | future resolves to the final enum state or rejects with an error. |
| 121 | |
| 122 | ```c |
| 123 | DexFuture *future = |
| 124 | dex_state_machine_transition (daemon->state_machine, |
| 125 | PASSWORD_DAEMON_LOCKED); |
| 126 | ``` |
| 127 | |
| 128 | Requests are serialized. If multiple callers request transitions at once, only |
| 129 | one transition fiber runs at a time. |
| 130 | |
| 131 | Use [[email protected]_requested_state] to read the most recent |
| 132 | valid target passed to [[email protected]]. This is useful |
| 133 | when an owner wants to expose requested state separately from current state. |
| 134 | It is updated when the request is made, before the transition runs. It does |
| 135 | not mean that the requested transition will succeed, and it may differ from |
| 136 | the current state after a rejected transition. |
| 137 | |
| 138 | Unsupported transitions reject with |
| 139 | [[email protected]_TRANSITION]. For example, a request to go directly |
| 140 | from `PASSWORD_DAEMON_INITIAL` to `PASSWORD_DAEMON_UNLOCKED` will fail unless |
| 141 | that edge exists in the transition table. |
| 142 | |
| 143 | ## Waiting for State |
| 144 | |
| 145 | Call [[email protected]_for_state] when code outside the transition |
| 146 | callback needs to wait until the current state reaches a specific value. |
| 147 | |
| 148 | ```c |
| 149 | DexFuture *future = |
| 150 | dex_state_machine_wait_for_state (daemon->state_machine, |
| 151 | PASSWORD_DAEMON_READY); |
| 152 | ``` |
| 153 | |
| 154 | The returned future resolves immediately if the state machine is already in |
| 155 | that state. Otherwise it resolves the next time the state is set to that value, |
| 156 | including intermediate states exposed by |
| 157 | [[email protected]_state]. |
| 158 | |
| 159 | Waiting does not request a transition. Pair it with |
| 160 | [[email protected]] when the caller also needs to initiate the |
| 161 | state change. |
| 162 | |
| 163 | ## Interrupting Active Transitions |
| 164 | |
| 165 | Long-running transition callbacks can opt in to cooperative interruption with |
| 166 | [[email protected]_for_interrupt]. The returned future |
| 167 | resolves when another caller calls [[email protected]]. |
| 168 | |
| 169 | ```c |
| 170 | static gboolean |
| 171 | enter_unlocked (DexStateTransitionContext *context, |
| 172 | gpointer user_data, |
| 173 | GError **error) |
| 174 | { |
| 175 | PasswordDaemon *daemon = user_data; |
| 176 | |
| 177 | if (!dex_await (dex_future_first ( |
| 178 | dex_state_transition_context_wait_for_interrupt (context), |
| 179 | password_daemon_read_loop (daemon), |
| 180 | NULL), |
| 181 | error)) |
| 182 | return FALSE; |
| 183 | |
| 184 | return dex_state_transition_context_continue_to (context, |
| 185 | PASSWORD_DAEMON_LOCKED, |
| 186 | error); |
| 187 | } |
| 188 | ``` |
| 189 | |
| 190 | Interrupting does not request a transition, change state, or skip the |
| 191 | transition callback. It only resolves the active context's interrupt future. |
| 192 | The callback decides whether to continue to another state, return successfully, |
| 193 | or fail with an error. |
| 194 | |
| 195 | If [[email protected]] is called before the active callback |
| 196 | requests the interrupt future, the interrupt is remembered and |
| 197 | [[email protected]_for_interrupt] returns an already |
| 198 | resolved future. If the callback completes before interruption, the interrupt |
| 199 | future rejects with %G_IO_ERROR_CANCELLED. |
| 200 | |
| 201 | ## Updating State During a Transition |
| 202 | |
| 203 | [[email protected]] gives callbacks access to both the declared |
| 204 | transition edge and the real current state. The context is only valid for the |
| 205 | duration of the transition callback and must not be stored. |
| 206 | |
| 207 | [[email protected]_from] and |
| 208 | [[email protected]_to] are fixed for the callback. They |
| 209 | describe the transition table edge being executed. They do not change if the |
| 210 | callback updates the state. |
| 211 | |
| 212 | [[email protected]_state] reads the real current state |
| 213 | from the state machine. [[email protected]_state] updates |
| 214 | that real state immediately. This is useful for quiescent transitions that need |
| 215 | to expose progress through intermediate states in one pass. `set_state()` may |
| 216 | only be used while the transition callback is active. |
| 217 | |
| 218 | ```c |
| 219 | static gboolean |
| 220 | enter_prepare (DexStateTransitionContext *context, |
| 221 | gpointer user_data, |
| 222 | GError **error) |
| 223 | { |
| 224 | PasswordDaemon *daemon = user_data; |
| 225 | |
| 226 | dex_state_transition_context_set_state (context, PASSWORD_DAEMON_PREPARE); |
| 227 | |
| 228 | if (!dex_await (password_daemon_prepare (daemon), error)) |
| 229 | return FALSE; |
| 230 | |
| 231 | dex_state_transition_context_set_state (context, PASSWORD_DAEMON_READY); |
| 232 | |
| 233 | return TRUE; |
| 234 | } |
| 235 | ``` |
| 236 | |
| 237 | With this table, requesting `INITIAL -> PREPARE` runs `enter_prepare()` and |
| 238 | resolves with `READY` when the callback succeeds. |
| 239 | |
| 240 | ```c |
| 241 | static const DexStateTransition password_daemon_transitions[] = { |
| 242 | { PASSWORD_DAEMON_INITIAL, PASSWORD_DAEMON_PREPARE, enter_prepare }, |
| 243 | }; |
| 244 | ``` |
| 245 | |
| 246 | If a callback calls [[email protected]_state], those |
| 247 | updates are not rolled back automatically if the callback later fails. They are |
| 248 | real state changes. Set an explicit failure state before returning %FALSE when |
| 249 | that is the state machine behavior you want. |
| 250 | |
| 251 | ## GObject State Properties |
| 252 | |
| 253 | [[email protected]] is not a `GObject`. When a `GObject` owns a state |
| 254 | machine, keep the state machine private and expose state from the owning object. |
| 255 | |
| 256 | Install a readable enum property on the owner. Transition callbacks will emit |
| 257 | `notify::state` explicitly when observable state changes. |
| 258 | |
| 259 | ```c |
| 260 | enum { |
| 261 | PROP_0, |
| 262 | PROP_STATE, |
| 263 | N_PROPS |
| 264 | }; |
| 265 | |
| 266 | static GParamSpec *properties[N_PROPS]; |
| 267 | |
| 268 | static PasswordDaemonState |
| 269 | password_daemon_get_state (PasswordDaemon *daemon) |
| 270 | { |
| 271 | return dex_state_machine_get_state (daemon->state_machine); |
| 272 | } |
| 273 | |
| 274 | static void |
| 275 | password_daemon_get_property (GObject *object, |
| 276 | guint prop_id, |
| 277 | GValue *value, |
| 278 | GParamSpec *pspec) |
| 279 | { |
| 280 | PasswordDaemon *daemon = PASSWORD_DAEMON (object); |
| 281 | |
| 282 | switch (prop_id) |
| 283 | { |
| 284 | case PROP_STATE: |
| 285 | g_value_set_enum (value, password_daemon_get_state (daemon)); |
| 286 | break; |
| 287 | |
| 288 | default: |
| 289 | G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | static void |
| 294 | password_daemon_class_init (PasswordDaemonClass *daemon_class) |
| 295 | { |
| 296 | GObjectClass *object_class = G_OBJECT_CLASS (daemon_class); |
| 297 | |
| 298 | object_class->get_property = password_daemon_get_property; |
| 299 | |
| 300 | properties[PROP_STATE] = |
| 301 | g_param_spec_enum ("state", NULL, NULL, |
| 302 | PASSWORD_DAEMON_TYPE_STATE, |
| 303 | PASSWORD_DAEMON_INITIAL, |
| 304 | (G_PARAM_READABLE | |
| 305 | G_PARAM_STATIC_STRINGS)); |
| 306 | |
| 307 | g_object_class_install_properties (object_class, N_PROPS, properties); |
| 308 | } |
| 309 | ``` |
| 310 | |
| 311 | If the owner stores a strong reference to the state machine, do not also pass a |
| 312 | strong reference to the owner as transition user data. That creates a reference |
| 313 | cycle: |
| 314 | |
| 315 | ```c |
| 316 | daemon -> state_machine -> daemon |
| 317 | ``` |
| 318 | |
| 319 | Use a small weak-reference holder instead. |
| 320 | |
| 321 | ```c |
| 322 | typedef struct |
| 323 | { |
| 324 | GWeakRef daemon; |
| 325 | } PasswordDaemonTransitionData; |
| 326 | |
| 327 | static PasswordDaemonTransitionData * |
| 328 | password_daemon_transition_data_new (PasswordDaemon *daemon) |
| 329 | { |
| 330 | PasswordDaemonTransitionData *data; |
| 331 | |
| 332 | data = g_new0 (PasswordDaemonTransitionData, 1); |
| 333 | g_weak_ref_init (&data->daemon, daemon); |
| 334 | |
| 335 | return data; |
| 336 | } |
| 337 | |
| 338 | static void |
| 339 | password_daemon_transition_data_free (PasswordDaemonTransitionData *data) |
| 340 | { |
| 341 | g_weak_ref_clear (&data->daemon); |
| 342 | g_free (data); |
| 343 | } |
| 344 | |
| 345 | daemon->state_machine = |
| 346 | dex_state_machine_new (PASSWORD_DAEMON_TYPE_STATE, |
| 347 | PASSWORD_DAEMON_INITIAL, |
| 348 | password_daemon_transitions, |
| 349 | G_N_ELEMENTS (password_daemon_transitions), |
| 350 | NULL, |
| 351 | 0, |
| 352 | password_daemon_transition_data_new (daemon), |
| 353 | (GDestroyNotify)password_daemon_transition_data_free); |
| 354 | ``` |
| 355 | |
| 356 | When transition callbacks update the state machine state directly, notify the |
| 357 | owner at the same time. A helper keeps this consistent. |
| 358 | |
| 359 | ```c |
| 360 | static void |
| 361 | password_daemon_set_state (PasswordDaemon *daemon, |
| 362 | DexStateTransitionContext *context, |
| 363 | PasswordDaemonState state) |
| 364 | { |
| 365 | if (dex_state_transition_context_get_state (context) == state) |
| 366 | return; |
| 367 | |
| 368 | dex_state_transition_context_set_state (context, state); |
| 369 | g_object_notify_by_pspec (G_OBJECT (daemon), properties[PROP_STATE]); |
| 370 | } |
| 371 | ``` |
| 372 | |
| 373 | Then transition callbacks can acquire the owner from the weak reference and use |
| 374 | the helper for every state change that should be visible through `:state`. |
| 375 | |
| 376 | ```c |
| 377 | static gboolean |
| 378 | enter_prepare (DexStateTransitionContext *context, |
| 379 | gpointer user_data, |
| 380 | GError **error) |
| 381 | { |
| 382 | PasswordDaemonTransitionData *data = user_data; |
| 383 | g_autoptr(PasswordDaemon) daemon = NULL; |
| 384 | |
| 385 | daemon = g_weak_ref_get (&data->daemon); |
| 386 | if (daemon == NULL) |
| 387 | { |
| 388 | g_set_error_literal (error, |
| 389 | G_IO_ERROR, |
| 390 | G_IO_ERROR_CANCELLED, |
| 391 | "PasswordDaemon was disposed"); |
| 392 | return FALSE; |
| 393 | } |
| 394 | |
| 395 | password_daemon_set_state (daemon, context, PASSWORD_DAEMON_PREPARE); |
| 396 | |
| 397 | if (!dex_await (password_daemon_prepare (daemon), error)) |
| 398 | return FALSE; |
| 399 | |
| 400 | password_daemon_set_state (daemon, context, PASSWORD_DAEMON_READY); |
| 401 | |
| 402 | return TRUE; |
| 403 | } |
| 404 | ``` |
| 405 | |
| 406 | If `:state` notifications matter, do not rely on the state machine's automatic |
| 407 | target commit for those states. The automatic commit happens after the |
| 408 | transition callback returns, where the owner has no callback-local opportunity |
| 409 | to emit `notify::state`. Call [[email protected]_state] |
| 410 | through your notification helper instead. |
| 411 | |
| 412 | The same rule applies when using [[email protected]_to]. |
| 413 | If the current edge target should be observable, set and notify it before |
| 414 | calling `continue_to()`. The continued edge callback should notify its own |
| 415 | observable state changes. |
| 416 | |
| 417 | Notifications are emitted from the transition fiber. If signal handlers for |
| 418 | the owner must run on a specific main context or thread, create and use the |
| 419 | state machine with a scheduler that runs there. |
| 420 | |
| 421 | If callers need to observe both intent and progress, expose a separate |
| 422 | `:requested-state` property on the owner and read it from |
| 423 | [[email protected]_requested_state]. Notify that property from the |
| 424 | owner method that calls [[email protected]], because |
| 425 | [[email protected]] is not a `GObject`. |
| 426 | |
| 427 | ## Continuing Through Edges |
| 428 | |
| 429 | [[email protected]_to] lets a transition callback run |
| 430 | another declared edge immediately while the state machine still owns its |
| 431 | serialization slot. It is synchronous composition: the next transition |
| 432 | callback is called before `continue_to()` returns, and queued transition |
| 433 | requests wait until the continuation chain finishes. |
| 434 | |
| 435 | ```c |
| 436 | static gboolean |
| 437 | enter_prepare (DexStateTransitionContext *context, |
| 438 | gpointer user_data, |
| 439 | GError **error) |
| 440 | { |
| 441 | PasswordDaemon *daemon = user_data; |
| 442 | |
| 443 | if (!dex_await (password_daemon_prepare (daemon), error)) |
| 444 | return FALSE; |
| 445 | |
| 446 | return dex_state_transition_context_continue_to (context, |
| 447 | PASSWORD_DAEMON_READY, |
| 448 | error); |
| 449 | } |
| 450 | ``` |
| 451 | |
| 452 | With this table, a request for `INITIAL -> PREPARE` runs `enter_prepare()`, |
| 453 | commits `PREPARE`, then immediately runs `enter_ready()` before any queued |
| 454 | transition request can run. |
| 455 | |
| 456 | ```c |
| 457 | static const DexStateTransition password_daemon_transitions[] = { |
| 458 | { PASSWORD_DAEMON_INITIAL, PASSWORD_DAEMON_PREPARE, enter_prepare }, |
| 459 | { PASSWORD_DAEMON_PREPARE, PASSWORD_DAEMON_READY, enter_ready }, |
| 460 | }; |
| 461 | ``` |
| 462 | |
| 463 | If the callback has not called [[email protected]_state], |
| 464 | `continue_to()` validates the next edge before committing the current edge. An |
| 465 | unsupported continuation returns %FALSE with |
| 466 | [[email protected]_TRANSITION]. If the next callback fails after the |
| 467 | current edge has been committed, that state change is not rolled back. |
| 468 | |
| 469 | If a continued transition callback uses `dex_await()`, the same transition |
| 470 | fiber suspends and later resumes; the main context is not blocked, but the |
| 471 | state machine queue is still held. Chained continuations use ordinary C calls, |
| 472 | so this API is intended for short, bounded handoffs between edges rather than |
| 473 | unbounded graph traversal. |
| 474 | |
| 475 | ## Circular State Machines |
| 476 | |
| 477 | Circular graphs are valid. For example, a lock state machine can declare both |
| 478 | directions explicitly. |
| 479 | |
| 480 | ```c |
| 481 | static const DexStateTransition lock_transitions[] = { |
| 482 | { PASSWORD_DAEMON_LOCKED, PASSWORD_DAEMON_UNLOCKED, unlock }, |
| 483 | { PASSWORD_DAEMON_UNLOCKED, PASSWORD_DAEMON_LOCKED, lock }, |
| 484 | }; |
| 485 | ``` |
| 486 | |
| 487 | The state machine does not reject cycles. It rejects only invalid states, |
| 488 | duplicate edges at construction time, and unsupported edges at transition time. |
| 489 | |
| 490 | ## Error Handling |
| 491 | |
| 492 | There are three common failure cases: |
| 493 | |
| 494 | * Construction fails if the transition table is invalid. |
| 495 | * Transition requests reject with [[email protected]_TRANSITION] when no |
| 496 | declared edge exists. |
| 497 | * Transition callbacks may fail with their own error. |
| 498 | |
| 499 | Callback failures leave the state unchanged only if the callback has not |
| 500 | already called [[email protected]_state]. Invalid explicit |
| 501 | state updates are programmer errors. |
| 502 | |
| 503 | ## Related Pages |
| 504 | |
| 505 | * [Limiters](limiters.html) |
| 506 | * [Scheduler behavior and pinning](schedulers.html) |