-
Notifications
You must be signed in to change notification settings - Fork 1
/
statebot.sh
executable file
·1102 lines (950 loc) · 23.9 KB
/
statebot.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/sh
# shellcheck disable=SC2039,SC1004
__STATEBOT_INFO__=':
|
| STATEBOT-SH 2.4.1
| - Write more robust and understandable programs.
|
| Github repo w/ example usage:
| - https://github.com/shuckster/statebot-sh
|
| Statebot runs in Node and the browser, too:
| - https://github.com/shuckster/statebot
|
|
| Written by Conan Theobald and MIT licensed.
|_____________________________________________ _ _ _ _ _
'
# shellcheck disable=SC2016
__STATEBOT_EXAMPLE__='
A basic implementation:
-----------------------
#!/bin/sh
STATEBOT_LOG_LEVEL=4
# 0 for silence, 4 for everything
STATEBOT_USE_LOGGER=0
# 1 to use the `logger` command instead of `echo`
#
# Define the states and allowed transitions:
#
PROMISE_CHART="
idle ->
// Behaves a bit like a JS Promise
pending ->
(rejected | resolved) ->
idle
"
#
# Implement "perform_transitions" to act on events:
#
perform_transitions ()
{
local ON THEN
ON=""
THEN=""
case $1 in
"idle->pending")
ON="start"
THEN="hello_world"
;;
"pending->resolved")
ON="okay"
THEN="statebot_emit done"
;;
"rejected->idle"|"resolved->idle")
ON="done"
THEN="all_finished"
;;
esac
echo $ON "$THEN"
}
#
# THEN callbacks:
#
hello_world ()
{
echo "Hello, World!"
statebot_emit "okay" persist
}
all_finished ()
{
echo "Done and done!"
}
#
# Entry point
#
main ()
{
statebot_init "demo" "idle" "start" "$PROMISE_CHART"
# machine name -^ ^ ^ ^
# 1st-run state -------+ | |
# 1st-run event --------------+ |
# statebot chart --------------------------+
echo "Current state: $CURRENT_STATE"
echo "Previous state: $PREVIOUS_STATE"
if [ "$1" = "" ]
then
exit
fi
# Send events/reset signal from the command-line:
if [ "$1" = "reset" ]
then
statebot_reset
else
statebot_emit "$1"
fi
}
cd "${0%/*}" || exit
# (^- change the working-directory to where this script is)
# Import Statebot
# shellcheck disable=SC1091
. ./statebot.sh
main "$1"
# Copy all this to a script and run it a few times
# to see what happens. :)
'
# shellcheck disable=SC2016
__STATEBOT_API__='
The Statebot-sh API:
--------------------
statebot_inspect "$YOUR_CHART"
#
# When developing your charts, it is useful
# to see the transitions they represent so
# you can copy-paste into your perform/
# on_transitions() functions.
#
# Use statebot_inspect() to give you this
# information, and the states too.
statebot_init "example" "idle" "start" "idle -> done"
# ^ ^ ^ ^
# machine name -| | | |
# 1st-run state --------+ | |
# 1st-run event --------------+ |
# statebot chart ------------------------+
#
# If your machine does not yet have an
# entry in the CSV database, this will
# initialise it with the values passed-in.
#
# If the machine already exists, then the
# values in the DB will be used from this
# point onwards.
#
# Only one machine is allowed per script,
# so do not call this more than once in
# order to try and have multiple state-
# machines in the same script! It is easy
# to use Statebot in many different and
# independent scripts.
#
# (Charts are not stored in the DB, and
# are specified as the last argument
# in order to enforce setting defaults
# for the initial state/event too.)
statebot_emit "start" persist
# ^ ^
# event name --+ |
# |
# Store this event ----+ (optional)
# for a future run instead of calling it
# immediately.
#
# When you run your script again later, the
# event will be picked-up by the call to
# statebot_init().
statebot_enter "pending"
# ^
# state name --+
#
# Changes to the specified state, if allowed
# by the rules in the state-chart.
statebot_reset
#
# Reset the machine to its 1st-run state
# & event. No events will be emitted.
statebot_states_available_from_here
#
# List the states available from the
# current-state.
statebot_current_state_of "statebot_name"
statebot_persisted_event_of "statebot_name"
# ^
# machine name -----------------+
#
# Get the current-state / persisted-event
# of the machine called "statebot_name".
statebot_delete "statebot_name"
# ^
# machine name -----+
#
# Delete the record of a "statebot_name"
# from the database.
echo " Current state: $CURRENT_STATE"
echo " Previous state: $PREVIOUS_STATE"
echo "Last emitted event: $PREVIOUS_EVENT"
#
# Details about the current machine
API in brief (scroll up for full):
----------------------------------
statebot_delete "machine-name"
statebot_inspect "chart -> of -> states"
statebot_init "machine-name" "state" "event" "chart"
-
statebot_emit "event"
statebot_enter "state"
statebot_reset
statebot_states_available_from_here
-
statebot_current_state_of "machine-name"
statebot_persisted_event_of "machine-name"
'
#
# "Private" globals
#
__STATEBOT_LOG_LEVEL__=4
__STATEBOT_DB__="/tmp/statebots.csv"
__STATEBOT_INITIAL_STATE__=""
__STATEBOT_INITIAL_EVENT__=""
__STATEBOT_AFTER_EVENT__=""
__STATEBOT_AFTER_TRANSITION__=""
__STATEBOT_HANDLING_EVENT__=0
__STATEBOT_THEN_STACK_SIZE__=0
__STATEBOT_EVENT_COUNT=0
__STATEBOT_RC__="${HOME}/.statebot-rc"
#
# Command-line usage
#
if echo "$0"|grep -q -e '/statebot\.sh$'
then
echo "${__STATEBOT_INFO__}"
if [ "$1" != "--example" ] && [ "$1" != "--help" ]
then
echo "See an example with: ./statebot.sh --example"
else
echo "${__STATEBOT_EXAMPLE__}"
fi
if [ "$1" != "--api" ] && [ "$1" != "--help" ]
then
echo "See the API: ./statebot.sh --api"
else
echo "${__STATEBOT_API__}"
fi
if [ "$1" != "--db" ]
then
echo "See the status of all your machines: ./statebot.sh --db"
else
echo ""
echo "Here's the content of ${__STATEBOT_DB__}:"
cat "${__STATEBOT_DB__}"
fi
echo ""
exit 1
fi
#
# "Public" globals
#
STATEBOT_NAME=""
STATEBOT_CHART=""
STATEBOT_VALID_STATES=""
STATEBOT_VALID_TRANSITIONS=""
CURRENT_STATE=""
PREVIOUS_STATE=""
PREVIOUS_EVENT=""
#
# By default, Statebot keeps track of your machines in a CSV:
#
# - /tmp/statebots.csv
#
# Change it using the variable STATEBOT_DB before importing
# Statebot into your script:
#
if [ "${STATEBOT_DB}" != "" ]
then
__STATEBOT_DB__=${STATEBOT_DB}
fi
#
# The log-level can be changed using STATEBOT_LOG_LEVEL. Again,
# do this before importing Statebot into your script.
#
if [ "${STATEBOT_LOG_LEVEL}" != "" ]
then
__STATEBOT_LOG_LEVEL__=${STATEBOT_LOG_LEVEL}
fi
#
# LOGGING
#
logit ()
{
local msg
msg="${*}"
if [ ${__STATEBOT_HANDLING_EVENT__} -eq 1 ]
then
msg=$(echo "${msg}"|sed "s/<eId> */<eId:${__STATEBOT_EVENT_COUNT}> /")
else
msg=$(echo "${msg}"|sed 's/<eId> *//')
fi
if [ "${STATEBOT_USE_LOGGER}" = "1" ]
then
msg=$(echo "${msg}"|sed 's/^-/=/')
logger -s -t "statebot(${STATEBOT_NAME:-'!'})" "${msg}"
else
echo "${msg}"
fi
}
info ()
{
[ "${__STATEBOT_LOG_LEVEL__}" -ge 4 ] && logit "INFO: ${*}"
}
log ()
{
[ "${__STATEBOT_LOG_LEVEL__}" -ge 3 ] && logit "${*}"
}
warn ()
{
[ "${__STATEBOT_LOG_LEVEL__}" -ge 2 ] && logit "WARN: ${*}"
}
error ()
{
[ "${__STATEBOT_LOG_LEVEL__}" -ge 1 ] && logit "ERR!: ${*}"
}
#
# CHART PARSING
#
#
# Take a chart and decompose it into its individual transitions.
#
decompose_chart ()
{
echo "${@}"|awk '
BEGIN {
condensed_line_count = 0
rxLineContinuations = "(->|\\|)$"
rxDisallowedCharacters = "[^a-z0-9!@#$%^&*:_+=<>|~.\x2D]"
decomposed_line_count = 0
}
{
line = $0
line_wo_comment = remove_comment(line)
line_sanitised = line_wo_comment
gsub(rxDisallowedCharacters, "", line_sanitised)
if ( line_sanitised != "" ) {
if ( line_sanitised ~ rxLineContinuations ) {
condensed_line = condensed_line "" line_sanitised
} else {
condensed_line_count += 1
condensed_lines[condensed_line_count] = condensed_line "" line_sanitised
condensed_line = ""
}
}
}
function remove_comment(line) {
rxComment = "(\/\/[^\n\r]*)"
sub(rxComment, "", line)
return line
}
function decompose_line_into_route(line) {
split_len = split(line, array, "->");
line = ""
for (split_idx = 1; split_idx <= split_len; split_idx++) {
node = array[split_idx]
if (split_idx != 1) {
decomposed_line_count += 1
decomposed_lines[decomposed_line_count] = previous_states "->" node
}
previous_states = node
}
}
function decompose_route_into_transition(line) {
split(line, nodes, "->");
from_count = split(nodes[1], from_states, "|");
to_count = split(nodes[2], to_states, "|");
for (from_idx = 1; from_idx <= from_count; from_idx++ ) {
for (to_idx = 1; to_idx <= to_count; to_idx++ ) {
# Technique to remove duplicates and keep sort-order: 1/3
route = from_states[from_idx] "->" to_states[to_idx]
if (!transitions[route]) {
transitions[route] = transitions_line_count++
}
}
}
}
END {
for (cnd_idx = 1; cnd_idx <= condensed_line_count; cnd_idx++) {
condensed_line = condensed_lines[cnd_idx]
decompose_line_into_route(condensed_line)
}
for (dcmp_idx = 1; dcmp_idx <= decomposed_line_count; dcmp_idx++) {
decompose_route_into_transition(decomposed_lines[dcmp_idx])
}
# De-dupe + sort: 2/3
for (trn_idx in transitions) {
out[transitions[trn_idx]] = trn_idx
}
# De-dupe + sort: 3/3
for (trn_idx = 0; trn_idx < transitions_line_count; trn_idx++) {
print out[trn_idx]
}
}
'
}
#
# Take a single chart-line and reduce it into its individual states.
#
decompose_transitions ()
{
echo "${@}"|awk '
{
len = split($0,states,"->");
# Technique to remove duplicates and keep sort-order: 1/3
for (i = 1; i <= len; i++ ) {
state = states[i]
if (!data[state]) {
data[state] = count++
}
}
}
END {
# De-dupe + sort: 2/3
for (i in data) {
out[data[i]] = i
}
# De-dupe + sort: 3/3
for (i = 0; i < count; i++) {
if (out[i]) {
print out[i]
}
}
}
'
}
#
# We use a stack to store the THEN="" commands. This allows us to
# specify statebot_emit() and statebot_enter() as THEN's.
#
# Since no arrays are allowed in sh, we use a fake one.
#
__statebot_then_stack_push ()
{
local array_item
: $((__STATEBOT_THEN_STACK_SIZE__+=1))
array_item="__STATEBOT_THEN_FN_${__STATEBOT_THEN_STACK_SIZE__}"
eval "${array_item}"='$@'
}
__statebot_then_stack_peek ()
{
local array_item next_then
array_item="__STATEBOT_THEN_FN_${__STATEBOT_THEN_STACK_SIZE__}"
# shell-check disable=SC2140
eval "next_then"='"$'"${array_item}"'"'
echo "${next_then}"
}
__statebot_then_stack_clear_topmost ()
{
local array_item
array_item="__STATEBOT_THEN_FN_${__STATEBOT_THEN_STACK_SIZE__}"
eval "${array_item}"=''
}
__statebot_run_then_stack ()
{
if [ "${__STATEBOT_THEN_STACK_SIZE__}" -eq 0 ]
then
return 1
fi
local next_then
while [ "${__STATEBOT_THEN_STACK_SIZE__}" -gt 0 ]
do
next_then="$(__statebot_then_stack_peek)"
__statebot_then_stack_clear_topmost
: $((__STATEBOT_THEN_STACK_SIZE__-=1))
if ! ${next_then}
then
warn "<eId> Problem running THEN function: ${next_then}"
fi
done
}
#
# Transitions available from the current-state.
#
__statebot_transitions_available_from_here ()
{
local transition
for transition in ${STATEBOT_VALID_TRANSITIONS}
do
if ! echo "${transition}"|grep -q "^${CURRENT_STATE}->[^$]*"
then
continue
fi
echo "${transition}"
done
}
#
# Bail-out of various functions if Statebot has not
# been initialised.
#
__statebot_bail ()
{
error "<eId>: ${*}"
error "Run the statebot.sh script for help"
echo ""
}
#
# Looks at the last performed transition and invokes any handlers.
#
# Handlers are defined inside a user-defined on_transitions() function.
#
__statebot_get_handler_for_transition ()
{
local test_transition last_transition THEN
__STATEBOT_AFTER_TRANSITION__=""
test_transition="$1"
last_transition="${PREVIOUS_STATE}->${CURRENT_STATE}"
if [ "${test_transition}" != "${last_transition}" ]
then
warn "Not handling invalid transition: ${test_transition}"
return 1
fi
if ! type 'on_transitions' 2>&1|grep -q 'function'
then
info "<eId> on_transitions() undefined: Skipping transition handlers"
return 1
fi
# Process user-defined on_transitions() ...
info "<eId> Handling transition: ${last_transition}"
THEN=$(on_transitions "${last_transition}")
if [ "${THEN}" != "" ]
then
__STATEBOT_AFTER_TRANSITION__="${THEN}"
fi
return 0
}
#
# Takes an event and changes to the next state if available.
#
# If perform_transitions() returns a "THEN" command, then the global
# variable __STATEBOT_AFTER_EVENT__ will be set and statebot_emit()
# will run it.
#
__statebot_change_state_for_event_and_get_handler ()
{
if ! type 'perform_transitions' 2>&1|grep -q 'function'
then
info "<eId> perform_transitions() undefined: Skipping event handlers"
return 1
fi
if [ "$1" = "" ]
then
__statebot_bail "No event to process!"
return 1
fi
local state_changed on_then on
__STATEBOT_AFTER_EVENT__=""
previous_event="$1"
state_changed=0
# Process user-defined perform_transitions() ...
for transition in $(__statebot_transitions_available_from_here)
do
on_then=$(perform_transitions "${transition}")
on=$(echo "${on_then}"|awk '{ print $1 }')
if [ "${previous_event}" != "${on}" ]
then
continue
fi
info "<eId> Changing state: ${transition}"
PREVIOUS_STATE="${CURRENT_STATE}"
CURRENT_STATE=$(echo "${transition}"|awk 'BEGIN { FS="->" } { print $2 }')
__STATEBOT_AFTER_EVENT__=$(echo "${on_then}"|awk '{ $1=""; sub(/^ */, "", $0); print }')
state_changed=1
break
done
return ${state_changed}
}
#
# Pretty-prints information about the current machine.
#
__statebot_info ()
{
if [ "${__STATEBOT_INITIALISED__}" -eq 0 ]
then
__statebot_bail "Statebot not initialised"
return 1
fi
log ". : "
log "| | Statebot :: ${STATEBOT_NAME}"
log "| | Current state: [${CURRENT_STATE}]"
if [ "${PREVIOUS_EVENT}" != "" ]
then
log "| : Event pending: ${PREVIOUS_EVENT}"
fi
log "|_|________________________________________ _ _ _ _ _ "
log ""
}
#
# Shows state/event of a specified machine.
#
__statebot_stat ()
{
local name db_entry sb_current_state sb_persisted_event
name="${1}"
db_entry=$(grep "^${name}," "${__STATEBOT_DB__}")
sb_current_state=$(echo "${db_entry}"|awk 'BEGIN { FS="," } { print $2 }')
sb_persisted_event=$(echo "${db_entry}"|awk 'BEGIN { FS="," } { print $3 }')
echo "${sb_current_state} ${sb_persisted_event}"
}
#
# "PUBLIC" API
#
#
# See the all the transitions + states of a chart before
# committing to initialising it.
#
# Helps with writing the perform_transitions() and
# on_transitions() functions for your script.
#
# statebot_inspect '
# pending -> resolved | rejected -> done
# '
#
statebot_inspect ()
{
local chart transitions states
chart="$1"
transitions=$(decompose_chart "${chart}")
states=$(decompose_transitions "${transitions}")
log ""
log "Chart:"
log "---"
log "${chart}"
log ""
log "Transitions:"
log "---"
log "${transitions}"
log ""
log "States:"
log "---"
log "${states}"
log ""
}
#
# Get current-state / previous-event of specified machines.
#
statebot_current_state_of ()
{
local name sb_current_state
name="$1"
sb_current_state=$(__statebot_stat "${name}"|awk '{ print $1 }')
echo "${sb_current_state}"
}
statebot_persisted_event_of ()
{
local name sb_persisted_event
name="$1"
sb_persisted_event=$(__statebot_stat "${name}"|awk '{ print $2 }')
echo "${sb_persisted_event}"
}
#
# Initialise a Statebot:
#
# statebot_init "name" "starting-state" "starting-event" '
# // Statebot chart
# pending -> resolved | rejected -> done
# '
#
statebot_init ()
{
local RETURN
__statebot_init "$@"; RETURN=$?
__statebot_run_then_stack
return ${RETURN}
}
__statebot_init ()
{
local name sb_stat
# These are only used if the current machine does not exist in the DB
__STATEBOT_INITIAL_STATE__="$2"
__STATEBOT_INITIAL_EVENT__="$3"
# Check for DB
if [ ! -f "${__STATEBOT_DB__}" ]
then
info "Creating DB: ${__STATEBOT_DB__}"
touch "${__STATEBOT_DB__}"
fi
# Check for DB record, set initial values
name="$1"
if ! grep -q "^${name}," "${__STATEBOT_DB__}"
then
info "No record of this machine, creating..."
echo "${name},${__STATEBOT_INITIAL_STATE__},${__STATEBOT_INITIAL_EVENT__}" >> "${__STATEBOT_DB__}"
fi
# Set current machine name/state/event
STATEBOT_NAME=${name}
sb_stat=$(__statebot_stat "${STATEBOT_NAME}")
CURRENT_STATE=$(echo "${sb_stat}"|awk '{ print $1 }')
PREVIOUS_EVENT=$(echo "${sb_stat}"|awk '{ print $2 }')
STATEBOT_CHART="$4"
# Parse the chart
STATEBOT_VALID_TRANSITIONS=$(decompose_chart "${STATEBOT_CHART}")
# shellcheck disable=SC2034
STATEBOT_VALID_STATES=$(decompose_transitions "${STATEBOT_VALID_TRANSITIONS}")
# Load ~/.statebot-rc if it exists
if [ -f "${__STATEBOT_RC__}" ]
then
# shellcheck disable=1090
. "${__STATEBOT_RC__}"
fi
# We're initialised at this point
__STATEBOT_INITIALISED__=1
# Info + initial event, if we have one
__statebot_info
statebot_emit "${PREVIOUS_EVENT}" "__first-run__"
}
#
# Emit an event to the current machine:
#
# statebot_emit "event-name"
#
statebot_emit ()
{
local RETURN
__statebot_emit "$@"; RETURN=$?
__statebot_run_then_stack
return ${RETURN}
}
__statebot_emit ()
{
if [ ${__STATEBOT_INITIALISED__} -eq 0 ]
then
__statebot_bail "Statebot not initialised"
return 1
fi
if [ "$1" = "" ]
then
if [ "$2" != "__first-run__" ]
then
__statebot_bail "No event to process"
fi
return 1
fi
local __previous_state emitted_event
local persist_option persist_event
local event_handled state_changed
local name state event db
__STATEBOT_HANDLING_EVENT__=1
__previous_state="${CURRENT_STATE}"
emitted_event="$1"
persist_option="$2"
__STATEBOT_AFTER_EVENT__=""
__STATEBOT_AFTER_TRANSITION__=""
: $((__STATEBOT_EVENT_COUNT+=1))
info "<eId> Handling event: ${emitted_event}, from state [${CURRENT_STATE}]"
# Persist event for another run, or execute it immediately?
persist_event=""
event_handled=0
state_changed=0
if [ "${persist_option}" = "persist" ]
then
info "<eId> Peristing event instead of emitting it"
persist_event="${emitted_event}"
PREVIOUS_EVENT=""
event_handled=1
else
__statebot_change_state_for_event_and_get_handler "${emitted_event}"
state_changed=$?
if [ ${state_changed} -eq 1 ]
then
event_handled=1
fi
fi
if [ ${event_handled} -eq 0 ]
then
info "<eId> Nothing happened"
fi
# Persist the current state
name="${STATEBOT_NAME}"
state="${CURRENT_STATE}"
event="${persist_event}"
db=$(sed -e "s/^${name},.*/${name},${state},${event}/" "${__STATEBOT_DB__}")
echo "${db}" > "${__STATEBOT_DB__}"
if [ ${state_changed} -eq 1 ]
then
# Handle perform_transitions() THEN="..."
if [ "${__STATEBOT_AFTER_EVENT__}" != "" ]
then
__statebot_then_stack_push "${__STATEBOT_AFTER_EVENT__}"
fi
# Handle on_transitions() THEN="..."
__statebot_get_handler_for_transition "${__previous_state}->${CURRENT_STATE}"
if [ "${__STATEBOT_AFTER_TRANSITION__}" != "" ]
then
__statebot_then_stack_push "${__STATEBOT_AFTER_TRANSITION__}"
__STATEBOT_AFTER_TRANSITION__=""
fi
fi
__STATEBOT_HANDLING_EVENT__=0
if [ ${event_handled} -eq 1 ]
then
return 0
else
return 1
fi
}
#
# Enter a new state, so long as it is allowed from the current-state:
#
# statebot_enter "state-name"
#
statebot_enter ()
{
local RETURN
__statebot_enter "$@"; RETURN=$?
__statebot_run_then_stack
return ${RETURN}
}
__statebot_enter ()
{
if [ $__STATEBOT_INITIALISED__ -eq 0 ]
then
__statebot_bail "Statebot not initialised"
return 1
fi
local next_state state_changed name state event db
next_state="$1"
state_changed=0
if [ "${CURRENT_STATE}" = "${next_state}" ]
then
info "<eId> Not changing state, already in: ${next_state}"
return 1
fi
for state in $(statebot_states_available_from_here)
do
if [ "${state}" != "${next_state}" ]
then
continue
fi
# Found the next valid state
info "<eId> Changing state to: ${next_state}"
__previous_state="${CURRENT_STATE}"
CURRENT_STATE="${next_state}"
# Persist the current state, clear the current event too
name="${STATEBOT_NAME}"
state="${CURRENT_STATE}"
event=""
db=$(sed -e "s/^${name},.*/${name},${state},${event}/" "${__STATEBOT_DB__}")
echo "${db}" > "${__STATEBOT_DB__}"
state_changed=1
break
done
if [ ${state_changed} -eq 1 ]
then
PREVIOUS_STATE="${__previous_state}"
__statebot_get_handler_for_transition "${PREVIOUS_STATE}->${CURRENT_STATE}"
else
info "<eId> Invalid transition: ${CURRENT_STATE}->${next_state}, not switching"
fi
# Handle on_transitions() THEN="..."
if [ "${__STATEBOT_AFTER_TRANSITION__}" != "" ]
then
__statebot_then_stack_push "${__STATEBOT_AFTER_TRANSITION__}"
__STATEBOT_AFTER_TRANSITION__=""
fi
if [ ${state_changed} -eq 1 ]
then
return 0
else
return 1
fi
}
#