Committing vendored dependencies and generated protos
Change-Id: I349c149b513d9de7d9f60bde2c954a939da2fc54
diff --git a/vendor/github.com/looplab/fsm/.gitignore b/vendor/github.com/looplab/fsm/.gitignore
new file mode 100644
index 0000000..969bdaa
--- /dev/null
+++ b/vendor/github.com/looplab/fsm/.gitignore
@@ -0,0 +1,28 @@
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+
+# Folders
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.[568vq]
+[568vq].out
+
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
+
+*.sublime-project
+*.sublime-workspace
+
+.DS_Store
+.wercker
diff --git a/vendor/github.com/looplab/fsm/.travis.yml b/vendor/github.com/looplab/fsm/.travis.yml
new file mode 100644
index 0000000..b9b0eda
--- /dev/null
+++ b/vendor/github.com/looplab/fsm/.travis.yml
@@ -0,0 +1,26 @@
+language: go
+
+go:
+ - "1.11"
+
+services:
+ - docker
+
+cache:
+ directories:
+ - ${GOPATH}/pkg/mod
+
+jobs:
+ include:
+ - stage: test
+ if: type == pull_request
+ script: make test
+ env:
+ - GO111MODULE=on
+
+ - stage: test_and_cover
+ name: "Test (with coverage)"
+ if: type != pull_request
+ script: make cover publish_cover
+ env:
+ - GO111MODULE=on
diff --git a/vendor/github.com/looplab/fsm/LICENSE b/vendor/github.com/looplab/fsm/LICENSE
new file mode 100644
index 0000000..37ec93a
--- /dev/null
+++ b/vendor/github.com/looplab/fsm/LICENSE
@@ -0,0 +1,191 @@
+Apache License
+Version 2.0, January 2004
+http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+"License" shall mean the terms and conditions for use, reproduction, and
+distribution as defined by Sections 1 through 9 of this document.
+
+"Licensor" shall mean the copyright owner or entity authorized by the copyright
+owner that is granting the License.
+
+"Legal Entity" shall mean the union of the acting entity and all other entities
+that control, are controlled by, or are under common control with that entity.
+For the purposes of this definition, "control" means (i) the power, direct or
+indirect, to cause the direction or management of such entity, whether by
+contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
+outstanding shares, or (iii) beneficial ownership of such entity.
+
+"You" (or "Your") shall mean an individual or Legal Entity exercising
+permissions granted by this License.
+
+"Source" form shall mean the preferred form for making modifications, including
+but not limited to software source code, documentation source, and configuration
+files.
+
+"Object" form shall mean any form resulting from mechanical transformation or
+translation of a Source form, including but not limited to compiled object code,
+generated documentation, and conversions to other media types.
+
+"Work" shall mean the work of authorship, whether in Source or Object form, made
+available under the License, as indicated by a copyright notice that is included
+in or attached to the work (an example is provided in the Appendix below).
+
+"Derivative Works" shall mean any work, whether in Source or Object form, that
+is based on (or derived from) the Work and for which the editorial revisions,
+annotations, elaborations, or other modifications represent, as a whole, an
+original work of authorship. For the purposes of this License, Derivative Works
+shall not include works that remain separable from, or merely link (or bind by
+name) to the interfaces of, the Work and Derivative Works thereof.
+
+"Contribution" shall mean any work of authorship, including the original version
+of the Work and any modifications or additions to that Work or Derivative Works
+thereof, that is intentionally submitted to Licensor for inclusion in the Work
+by the copyright owner or by an individual or Legal Entity authorized to submit
+on behalf of the copyright owner. For the purposes of this definition,
+"submitted" means any form of electronic, verbal, or written communication sent
+to the Licensor or its representatives, including but not limited to
+communication on electronic mailing lists, source code control systems, and
+issue tracking systems that are managed by, or on behalf of, the Licensor for
+the purpose of discussing and improving the Work, but excluding communication
+that is conspicuously marked or otherwise designated in writing by the copyright
+owner as "Not a Contribution."
+
+"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
+of whom a Contribution has been received by Licensor and subsequently
+incorporated within the Work.
+
+2. Grant of Copyright License.
+
+Subject to the terms and conditions of this License, each Contributor hereby
+grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
+irrevocable copyright license to reproduce, prepare Derivative Works of,
+publicly display, publicly perform, sublicense, and distribute the Work and such
+Derivative Works in Source or Object form.
+
+3. Grant of Patent License.
+
+Subject to the terms and conditions of this License, each Contributor hereby
+grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
+irrevocable (except as stated in this section) patent license to make, have
+made, use, offer to sell, sell, import, and otherwise transfer the Work, where
+such license applies only to those patent claims licensable by such Contributor
+that are necessarily infringed by their Contribution(s) alone or by combination
+of their Contribution(s) with the Work to which such Contribution(s) was
+submitted. If You institute patent litigation against any entity (including a
+cross-claim or counterclaim in a lawsuit) alleging that the Work or a
+Contribution incorporated within the Work constitutes direct or contributory
+patent infringement, then any patent licenses granted to You under this License
+for that Work shall terminate as of the date such litigation is filed.
+
+4. Redistribution.
+
+You may reproduce and distribute copies of the Work or Derivative Works thereof
+in any medium, with or without modifications, and in Source or Object form,
+provided that You meet the following conditions:
+
+You must give any other recipients of the Work or Derivative Works a copy of
+this License; and
+You must cause any modified files to carry prominent notices stating that You
+changed the files; and
+You must retain, in the Source form of any Derivative Works that You distribute,
+all copyright, patent, trademark, and attribution notices from the Source form
+of the Work, excluding those notices that do not pertain to any part of the
+Derivative Works; and
+If the Work includes a "NOTICE" text file as part of its distribution, then any
+Derivative Works that You distribute must include a readable copy of the
+attribution notices contained within such NOTICE file, excluding those notices
+that do not pertain to any part of the Derivative Works, in at least one of the
+following places: within a NOTICE text file distributed as part of the
+Derivative Works; within the Source form or documentation, if provided along
+with the Derivative Works; or, within a display generated by the Derivative
+Works, if and wherever such third-party notices normally appear. The contents of
+the NOTICE file are for informational purposes only and do not modify the
+License. You may add Your own attribution notices within Derivative Works that
+You distribute, alongside or as an addendum to the NOTICE text from the Work,
+provided that such additional attribution notices cannot be construed as
+modifying the License.
+You may add Your own copyright statement to Your modifications and may provide
+additional or different license terms and conditions for use, reproduction, or
+distribution of Your modifications, or for any such Derivative Works as a whole,
+provided Your use, reproduction, and distribution of the Work otherwise complies
+with the conditions stated in this License.
+
+5. Submission of Contributions.
+
+Unless You explicitly state otherwise, any Contribution intentionally submitted
+for inclusion in the Work by You to the Licensor shall be under the terms and
+conditions of this License, without any additional terms or conditions.
+Notwithstanding the above, nothing herein shall supersede or modify the terms of
+any separate license agreement you may have executed with Licensor regarding
+such Contributions.
+
+6. Trademarks.
+
+This License does not grant permission to use the trade names, trademarks,
+service marks, or product names of the Licensor, except as required for
+reasonable and customary use in describing the origin of the Work and
+reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty.
+
+Unless required by applicable law or agreed to in writing, Licensor provides the
+Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
+including, without limitation, any warranties or conditions of TITLE,
+NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
+solely responsible for determining the appropriateness of using or
+redistributing the Work and assume any risks associated with Your exercise of
+permissions under this License.
+
+8. Limitation of Liability.
+
+In no event and under no legal theory, whether in tort (including negligence),
+contract, or otherwise, unless required by applicable law (such as deliberate
+and grossly negligent acts) or agreed to in writing, shall any Contributor be
+liable to You for damages, including any direct, indirect, special, incidental,
+or consequential damages of any character arising as a result of this License or
+out of the use or inability to use the Work (including but not limited to
+damages for loss of goodwill, work stoppage, computer failure or malfunction, or
+any and all other commercial damages or losses), even if such Contributor has
+been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability.
+
+While redistributing the Work or Derivative Works thereof, You may choose to
+offer, and charge a fee for, acceptance of support, warranty, indemnity, or
+other liability obligations and/or rights consistent with this License. However,
+in accepting such obligations, You may act only on Your own behalf and on Your
+sole responsibility, not on behalf of any other Contributor, and only if You
+agree to indemnify, defend, and hold each Contributor harmless for any liability
+incurred by, or claims asserted against, such Contributor by reason of your
+accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work
+
+To apply the Apache License to your work, attach the following boilerplate
+notice, with the fields enclosed by brackets "[]" replaced with your own
+identifying information. (Don't include the brackets!) The text should be
+enclosed in the appropriate comment syntax for the file format. We also
+recommend that a file or class name and description of purpose be included on
+the same "printed page" as the copyright notice for easier identification within
+third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor/github.com/looplab/fsm/Makefile b/vendor/github.com/looplab/fsm/Makefile
new file mode 100644
index 0000000..6cad29f
--- /dev/null
+++ b/vendor/github.com/looplab/fsm/Makefile
@@ -0,0 +1,22 @@
+default: services test
+
+.PHONY: test
+test:
+ go test ./...
+
+.PHONY: cover
+cover:
+ go list -f '{{if len .TestGoFiles}}"go test -coverprofile={{.Dir}}/.coverprofile {{.ImportPath}}"{{end}}' ./... | xargs -L 1 sh -c
+
+.PHONY: publish_cover
+publish_cover: cover
+ go get -d golang.org/x/tools/cmd/cover
+ go get github.com/modocache/gover
+ go get github.com/mattn/goveralls
+ gover
+ @goveralls -coverprofile=gover.coverprofile -service=travis-ci -repotoken=$(COVERALLS_TOKEN)
+
+.PHONY: clean
+clean:
+ @find . -name \.coverprofile -type f -delete
+ @rm -f gover.coverprofile
diff --git a/vendor/github.com/looplab/fsm/README.md b/vendor/github.com/looplab/fsm/README.md
new file mode 100644
index 0000000..f07e5eb
--- /dev/null
+++ b/vendor/github.com/looplab/fsm/README.md
@@ -0,0 +1,117 @@
+[![Build Status](https://travis-ci.com/looplab/fsm.svg?branch=master)](https://travis-ci.com/looplab/fsm)
+[![Coverage Status](https://img.shields.io/coveralls/looplab/fsm.svg)](https://coveralls.io/r/looplab/fsm)
+[![GoDoc](https://godoc.org/github.com/looplab/fsm?status.svg)](https://godoc.org/github.com/looplab/fsm)
+[![Go Report Card](https://goreportcard.com/badge/looplab/fsm)](https://goreportcard.com/report/looplab/fsm)
+
+# FSM for Go
+
+FSM is a finite state machine for Go.
+
+It is heavily based on two FSM implementations:
+
+- Javascript Finite State Machine, https://github.com/jakesgordon/javascript-state-machine
+
+- Fysom for Python, https://github.com/oxplot/fysom (forked at https://github.com/mriehl/fysom)
+
+For API docs and examples see http://godoc.org/github.com/looplab/fsm
+
+# Basic Example
+
+From examples/simple.go:
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/looplab/fsm"
+)
+
+func main() {
+ fsm := fsm.NewFSM(
+ "closed",
+ fsm.Events{
+ {Name: "open", Src: []string{"closed"}, Dst: "open"},
+ {Name: "close", Src: []string{"open"}, Dst: "closed"},
+ },
+ fsm.Callbacks{},
+ )
+
+ fmt.Println(fsm.Current())
+
+ err := fsm.Event("open")
+ if err != nil {
+ fmt.Println(err)
+ }
+
+ fmt.Println(fsm.Current())
+
+ err = fsm.Event("close")
+ if err != nil {
+ fmt.Println(err)
+ }
+
+ fmt.Println(fsm.Current())
+}
+```
+
+# Usage as a struct field
+
+From examples/struct.go:
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/looplab/fsm"
+)
+
+type Door struct {
+ To string
+ FSM *fsm.FSM
+}
+
+func NewDoor(to string) *Door {
+ d := &Door{
+ To: to,
+ }
+
+ d.FSM = fsm.NewFSM(
+ "closed",
+ fsm.Events{
+ {Name: "open", Src: []string{"closed"}, Dst: "open"},
+ {Name: "close", Src: []string{"open"}, Dst: "closed"},
+ },
+ fsm.Callbacks{
+ "enter_state": func(e *fsm.Event) { d.enterState(e) },
+ },
+ )
+
+ return d
+}
+
+func (d *Door) enterState(e *fsm.Event) {
+ fmt.Printf("The door to %s is %s\n", d.To, e.Dst)
+}
+
+func main() {
+ door := NewDoor("heaven")
+
+ err := door.FSM.Event("open")
+ if err != nil {
+ fmt.Println(err)
+ }
+
+ err = door.FSM.Event("close")
+ if err != nil {
+ fmt.Println(err)
+ }
+}
+```
+
+# License
+
+FSM is licensed under Apache License 2.0
+
+http://www.apache.org/licenses/LICENSE-2.0
diff --git a/vendor/github.com/looplab/fsm/errors.go b/vendor/github.com/looplab/fsm/errors.go
new file mode 100644
index 0000000..9c32a49
--- /dev/null
+++ b/vendor/github.com/looplab/fsm/errors.go
@@ -0,0 +1,100 @@
+// Copyright (c) 2013 - Max Persson <max@looplab.se>
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package fsm
+
+// InvalidEventError is returned by FSM.Event() when the event cannot be called
+// in the current state.
+type InvalidEventError struct {
+ Event string
+ State string
+}
+
+func (e InvalidEventError) Error() string {
+ return "event " + e.Event + " inappropriate in current state " + e.State
+}
+
+// UnknownEventError is returned by FSM.Event() when the event is not defined.
+type UnknownEventError struct {
+ Event string
+}
+
+func (e UnknownEventError) Error() string {
+ return "event " + e.Event + " does not exist"
+}
+
+// InTransitionError is returned by FSM.Event() when an asynchronous transition
+// is already in progress.
+type InTransitionError struct {
+ Event string
+}
+
+func (e InTransitionError) Error() string {
+ return "event " + e.Event + " inappropriate because previous transition did not complete"
+}
+
+// NotInTransitionError is returned by FSM.Transition() when an asynchronous
+// transition is not in progress.
+type NotInTransitionError struct{}
+
+func (e NotInTransitionError) Error() string {
+ return "transition inappropriate because no state change in progress"
+}
+
+// NoTransitionError is returned by FSM.Event() when no transition have happened,
+// for example if the source and destination states are the same.
+type NoTransitionError struct {
+ Err error
+}
+
+func (e NoTransitionError) Error() string {
+ if e.Err != nil {
+ return "no transition with error: " + e.Err.Error()
+ }
+ return "no transition"
+}
+
+// CanceledError is returned by FSM.Event() when a callback have canceled a
+// transition.
+type CanceledError struct {
+ Err error
+}
+
+func (e CanceledError) Error() string {
+ if e.Err != nil {
+ return "transition canceled with error: " + e.Err.Error()
+ }
+ return "transition canceled"
+}
+
+// AsyncError is returned by FSM.Event() when a callback have initiated an
+// asynchronous state transition.
+type AsyncError struct {
+ Err error
+}
+
+func (e AsyncError) Error() string {
+ if e.Err != nil {
+ return "async started with error: " + e.Err.Error()
+ }
+ return "async started"
+}
+
+// InternalError is returned by FSM.Event() and should never occur. It is a
+// probably because of a bug.
+type InternalError struct{}
+
+func (e InternalError) Error() string {
+ return "internal error on state transition"
+}
diff --git a/vendor/github.com/looplab/fsm/event.go b/vendor/github.com/looplab/fsm/event.go
new file mode 100644
index 0000000..fdca2d0
--- /dev/null
+++ b/vendor/github.com/looplab/fsm/event.go
@@ -0,0 +1,62 @@
+// Copyright (c) 2013 - Max Persson <max@looplab.se>
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package fsm
+
+// Event is the info that get passed as a reference in the callbacks.
+type Event struct {
+ // FSM is a reference to the current FSM.
+ FSM *FSM
+
+ // Event is the event name.
+ Event string
+
+ // Src is the state before the transition.
+ Src string
+
+ // Dst is the state after the transition.
+ Dst string
+
+ // Err is an optional error that can be returned from a callback.
+ Err error
+
+ // Args is a optinal list of arguments passed to the callback.
+ Args []interface{}
+
+ // canceled is an internal flag set if the transition is canceled.
+ canceled bool
+
+ // async is an internal flag set if the transition should be asynchronous
+ async bool
+}
+
+// Cancel can be called in before_<EVENT> or leave_<STATE> to cancel the
+// current transition before it happens. It takes an opitonal error, which will
+// overwrite e.Err if set before.
+func (e *Event) Cancel(err ...error) {
+ e.canceled = true
+
+ if len(err) > 0 {
+ e.Err = err[0]
+ }
+}
+
+// Async can be called in leave_<STATE> to do an asynchronous state transition.
+//
+// The current state transition will be on hold in the old state until a final
+// call to Transition is made. This will comlete the transition and possibly
+// call the other callbacks.
+func (e *Event) Async() {
+ e.async = true
+}
diff --git a/vendor/github.com/looplab/fsm/fsm.go b/vendor/github.com/looplab/fsm/fsm.go
new file mode 100644
index 0000000..9da9db3
--- /dev/null
+++ b/vendor/github.com/looplab/fsm/fsm.go
@@ -0,0 +1,447 @@
+// Copyright (c) 2013 - Max Persson <max@looplab.se>
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package fsm implements a finite state machine.
+//
+// It is heavily based on two FSM implementations:
+//
+// Javascript Finite State Machine
+// https://github.com/jakesgordon/javascript-state-machine
+//
+// Fysom for Python
+// https://github.com/oxplot/fysom (forked at https://github.com/mriehl/fysom)
+//
+package fsm
+
+import (
+ "strings"
+ "sync"
+)
+
+// transitioner is an interface for the FSM's transition function.
+type transitioner interface {
+ transition(*FSM) error
+}
+
+// FSM is the state machine that holds the current state.
+//
+// It has to be created with NewFSM to function properly.
+type FSM struct {
+ // current is the state that the FSM is currently in.
+ current string
+
+ // transitions maps events and source states to destination states.
+ transitions map[eKey]string
+
+ // callbacks maps events and targers to callback functions.
+ callbacks map[cKey]Callback
+
+ // transition is the internal transition functions used either directly
+ // or when Transition is called in an asynchronous state transition.
+ transition func()
+ // transitionerObj calls the FSM's transition() function.
+ transitionerObj transitioner
+
+ // stateMu guards access to the current state.
+ stateMu sync.RWMutex
+ // eventMu guards access to Event() and Transition().
+ eventMu sync.Mutex
+}
+
+// EventDesc represents an event when initializing the FSM.
+//
+// The event can have one or more source states that is valid for performing
+// the transition. If the FSM is in one of the source states it will end up in
+// the specified destination state, calling all defined callbacks as it goes.
+type EventDesc struct {
+ // Name is the event name used when calling for a transition.
+ Name string
+
+ // Src is a slice of source states that the FSM must be in to perform a
+ // state transition.
+ Src []string
+
+ // Dst is the destination state that the FSM will be in if the transition
+ // succeds.
+ Dst string
+}
+
+// Callback is a function type that callbacks should use. Event is the current
+// event info as the callback happens.
+type Callback func(*Event)
+
+// Events is a shorthand for defining the transition map in NewFSM.
+type Events []EventDesc
+
+// Callbacks is a shorthand for defining the callbacks in NewFSM.a
+type Callbacks map[string]Callback
+
+// NewFSM constructs a FSM from events and callbacks.
+//
+// The events and transitions are specified as a slice of Event structs
+// specified as Events. Each Event is mapped to one or more internal
+// transitions from Event.Src to Event.Dst.
+//
+// Callbacks are added as a map specified as Callbacks where the key is parsed
+// as the callback event as follows, and called in the same order:
+//
+// 1. before_<EVENT> - called before event named <EVENT>
+//
+// 2. before_event - called before all events
+//
+// 3. leave_<OLD_STATE> - called before leaving <OLD_STATE>
+//
+// 4. leave_state - called before leaving all states
+//
+// 5. enter_<NEW_STATE> - called after entering <NEW_STATE>
+//
+// 6. enter_state - called after entering all states
+//
+// 7. after_<EVENT> - called after event named <EVENT>
+//
+// 8. after_event - called after all events
+//
+// There are also two short form versions for the most commonly used callbacks.
+// They are simply the name of the event or state:
+//
+// 1. <NEW_STATE> - called after entering <NEW_STATE>
+//
+// 2. <EVENT> - called after event named <EVENT>
+//
+// If both a shorthand version and a full version is specified it is undefined
+// which version of the callback will end up in the internal map. This is due
+// to the psuedo random nature of Go maps. No checking for multiple keys is
+// currently performed.
+func NewFSM(initial string, events []EventDesc, callbacks map[string]Callback) *FSM {
+ f := &FSM{
+ transitionerObj: &transitionerStruct{},
+ current: initial,
+ transitions: make(map[eKey]string),
+ callbacks: make(map[cKey]Callback),
+ }
+
+ // Build transition map and store sets of all events and states.
+ allEvents := make(map[string]bool)
+ allStates := make(map[string]bool)
+ for _, e := range events {
+ for _, src := range e.Src {
+ f.transitions[eKey{e.Name, src}] = e.Dst
+ allStates[src] = true
+ allStates[e.Dst] = true
+ }
+ allEvents[e.Name] = true
+ }
+
+ // Map all callbacks to events/states.
+ for name, fn := range callbacks {
+ var target string
+ var callbackType int
+
+ switch {
+ case strings.HasPrefix(name, "before_"):
+ target = strings.TrimPrefix(name, "before_")
+ if target == "event" {
+ target = ""
+ callbackType = callbackBeforeEvent
+ } else if _, ok := allEvents[target]; ok {
+ callbackType = callbackBeforeEvent
+ }
+ case strings.HasPrefix(name, "leave_"):
+ target = strings.TrimPrefix(name, "leave_")
+ if target == "state" {
+ target = ""
+ callbackType = callbackLeaveState
+ } else if _, ok := allStates[target]; ok {
+ callbackType = callbackLeaveState
+ }
+ case strings.HasPrefix(name, "enter_"):
+ target = strings.TrimPrefix(name, "enter_")
+ if target == "state" {
+ target = ""
+ callbackType = callbackEnterState
+ } else if _, ok := allStates[target]; ok {
+ callbackType = callbackEnterState
+ }
+ case strings.HasPrefix(name, "after_"):
+ target = strings.TrimPrefix(name, "after_")
+ if target == "event" {
+ target = ""
+ callbackType = callbackAfterEvent
+ } else if _, ok := allEvents[target]; ok {
+ callbackType = callbackAfterEvent
+ }
+ default:
+ target = name
+ if _, ok := allStates[target]; ok {
+ callbackType = callbackEnterState
+ } else if _, ok := allEvents[target]; ok {
+ callbackType = callbackAfterEvent
+ }
+ }
+
+ if callbackType != callbackNone {
+ f.callbacks[cKey{target, callbackType}] = fn
+ }
+ }
+
+ return f
+}
+
+// Current returns the current state of the FSM.
+func (f *FSM) Current() string {
+ f.stateMu.RLock()
+ defer f.stateMu.RUnlock()
+ return f.current
+}
+
+// Is returns true if state is the current state.
+func (f *FSM) Is(state string) bool {
+ f.stateMu.RLock()
+ defer f.stateMu.RUnlock()
+ return state == f.current
+}
+
+// SetState allows the user to move to the given state from current state.
+// The call does not trigger any callbacks, if defined.
+func (f *FSM) SetState(state string) {
+ f.stateMu.Lock()
+ defer f.stateMu.Unlock()
+ f.current = state
+ return
+}
+
+// Can returns true if event can occur in the current state.
+func (f *FSM) Can(event string) bool {
+ f.stateMu.RLock()
+ defer f.stateMu.RUnlock()
+ _, ok := f.transitions[eKey{event, f.current}]
+ return ok && (f.transition == nil)
+}
+
+// AvailableTransitions returns a list of transitions avilable in the
+// current state.
+func (f *FSM) AvailableTransitions() []string {
+ f.stateMu.RLock()
+ defer f.stateMu.RUnlock()
+ var transitions []string
+ for key := range f.transitions {
+ if key.src == f.current {
+ transitions = append(transitions, key.event)
+ }
+ }
+ return transitions
+}
+
+// Cannot returns true if event can not occure in the current state.
+// It is a convenience method to help code read nicely.
+func (f *FSM) Cannot(event string) bool {
+ return !f.Can(event)
+}
+
+// Event initiates a state transition with the named event.
+//
+// The call takes a variable number of arguments that will be passed to the
+// callback, if defined.
+//
+// It will return nil if the state change is ok or one of these errors:
+//
+// - event X inappropriate because previous transition did not complete
+//
+// - event X inappropriate in current state Y
+//
+// - event X does not exist
+//
+// - internal error on state transition
+//
+// The last error should never occur in this situation and is a sign of an
+// internal bug.
+func (f *FSM) Event(event string, args ...interface{}) error {
+ f.eventMu.Lock()
+ defer f.eventMu.Unlock()
+
+ f.stateMu.RLock()
+ defer f.stateMu.RUnlock()
+
+ if f.transition != nil {
+ return InTransitionError{event}
+ }
+
+ dst, ok := f.transitions[eKey{event, f.current}]
+ if !ok {
+ for ekey := range f.transitions {
+ if ekey.event == event {
+ return InvalidEventError{event, f.current}
+ }
+ }
+ return UnknownEventError{event}
+ }
+
+ e := &Event{f, event, f.current, dst, nil, args, false, false}
+
+ err := f.beforeEventCallbacks(e)
+ if err != nil {
+ return err
+ }
+
+ if f.current == dst {
+ f.afterEventCallbacks(e)
+ return NoTransitionError{e.Err}
+ }
+
+ // Setup the transition, call it later.
+ f.transition = func() {
+ f.stateMu.Lock()
+ f.current = dst
+ f.stateMu.Unlock()
+
+ f.enterStateCallbacks(e)
+ f.afterEventCallbacks(e)
+ }
+
+ if err = f.leaveStateCallbacks(e); err != nil {
+ if _, ok := err.(CanceledError); ok {
+ f.transition = nil
+ }
+ return err
+ }
+
+ // Perform the rest of the transition, if not asynchronous.
+ f.stateMu.RUnlock()
+ err = f.doTransition()
+ f.stateMu.RLock()
+ if err != nil {
+ return InternalError{}
+ }
+
+ return e.Err
+}
+
+// Transition wraps transitioner.transition.
+func (f *FSM) Transition() error {
+ f.eventMu.Lock()
+ defer f.eventMu.Unlock()
+ return f.doTransition()
+}
+
+// doTransition wraps transitioner.transition.
+func (f *FSM) doTransition() error {
+ return f.transitionerObj.transition(f)
+}
+
+// transitionerStruct is the default implementation of the transitioner
+// interface. Other implementations can be swapped in for testing.
+type transitionerStruct struct{}
+
+// Transition completes an asynchrounous state change.
+//
+// The callback for leave_<STATE> must prviously have called Async on its
+// event to have initiated an asynchronous state transition.
+func (t transitionerStruct) transition(f *FSM) error {
+ if f.transition == nil {
+ return NotInTransitionError{}
+ }
+ f.transition()
+ f.transition = nil
+ return nil
+}
+
+// beforeEventCallbacks calls the before_ callbacks, first the named then the
+// general version.
+func (f *FSM) beforeEventCallbacks(e *Event) error {
+ if fn, ok := f.callbacks[cKey{e.Event, callbackBeforeEvent}]; ok {
+ fn(e)
+ if e.canceled {
+ return CanceledError{e.Err}
+ }
+ }
+ if fn, ok := f.callbacks[cKey{"", callbackBeforeEvent}]; ok {
+ fn(e)
+ if e.canceled {
+ return CanceledError{e.Err}
+ }
+ }
+ return nil
+}
+
+// leaveStateCallbacks calls the leave_ callbacks, first the named then the
+// general version.
+func (f *FSM) leaveStateCallbacks(e *Event) error {
+ if fn, ok := f.callbacks[cKey{f.current, callbackLeaveState}]; ok {
+ fn(e)
+ if e.canceled {
+ return CanceledError{e.Err}
+ } else if e.async {
+ return AsyncError{e.Err}
+ }
+ }
+ if fn, ok := f.callbacks[cKey{"", callbackLeaveState}]; ok {
+ fn(e)
+ if e.canceled {
+ return CanceledError{e.Err}
+ } else if e.async {
+ return AsyncError{e.Err}
+ }
+ }
+ return nil
+}
+
+// enterStateCallbacks calls the enter_ callbacks, first the named then the
+// general version.
+func (f *FSM) enterStateCallbacks(e *Event) {
+ if fn, ok := f.callbacks[cKey{f.current, callbackEnterState}]; ok {
+ fn(e)
+ }
+ if fn, ok := f.callbacks[cKey{"", callbackEnterState}]; ok {
+ fn(e)
+ }
+}
+
+// afterEventCallbacks calls the after_ callbacks, first the named then the
+// general version.
+func (f *FSM) afterEventCallbacks(e *Event) {
+ if fn, ok := f.callbacks[cKey{e.Event, callbackAfterEvent}]; ok {
+ fn(e)
+ }
+ if fn, ok := f.callbacks[cKey{"", callbackAfterEvent}]; ok {
+ fn(e)
+ }
+}
+
+const (
+ callbackNone int = iota
+ callbackBeforeEvent
+ callbackLeaveState
+ callbackEnterState
+ callbackAfterEvent
+)
+
+// cKey is a struct key used for keeping the callbacks mapped to a target.
+type cKey struct {
+ // target is either the name of a state or an event depending on which
+ // callback type the key refers to. It can also be "" for a non-targeted
+ // callback like before_event.
+ target string
+
+ // callbackType is the situation when the callback will be run.
+ callbackType int
+}
+
+// eKey is a struct key used for storing the transition map.
+type eKey struct {
+ // event is the name of the event that the keys refers to.
+ event string
+
+ // src is the source from where the event can transition.
+ src string
+}
diff --git a/vendor/github.com/looplab/fsm/go.mod b/vendor/github.com/looplab/fsm/go.mod
new file mode 100644
index 0000000..4ae0575
--- /dev/null
+++ b/vendor/github.com/looplab/fsm/go.mod
@@ -0,0 +1 @@
+module github.com/looplab/fsm
diff --git a/vendor/github.com/looplab/fsm/utils.go b/vendor/github.com/looplab/fsm/utils.go
new file mode 100644
index 0000000..e49892e
--- /dev/null
+++ b/vendor/github.com/looplab/fsm/utils.go
@@ -0,0 +1,45 @@
+package fsm
+
+import (
+ "bytes"
+ "fmt"
+)
+
+// Visualize outputs a visualization of a FSM in Graphviz format.
+func Visualize(fsm *FSM) string {
+ var buf bytes.Buffer
+
+ states := make(map[string]int)
+
+ buf.WriteString(fmt.Sprintf(`digraph fsm {`))
+ buf.WriteString("\n")
+
+ // make sure the initial state is at top
+ for k, v := range fsm.transitions {
+ if k.src == fsm.current {
+ states[k.src]++
+ states[v]++
+ buf.WriteString(fmt.Sprintf(` "%s" -> "%s" [ label = "%s" ];`, k.src, v, k.event))
+ buf.WriteString("\n")
+ }
+ }
+
+ for k, v := range fsm.transitions {
+ if k.src != fsm.current {
+ states[k.src]++
+ states[v]++
+ buf.WriteString(fmt.Sprintf(` "%s" -> "%s" [ label = "%s" ];`, k.src, v, k.event))
+ buf.WriteString("\n")
+ }
+ }
+
+ buf.WriteString("\n")
+
+ for k := range states {
+ buf.WriteString(fmt.Sprintf(` "%s";`, k))
+ buf.WriteString("\n")
+ }
+ buf.WriteString(fmt.Sprintln("}"))
+
+ return buf.String()
+}