puerta/internal/door/door.go

112 lines
2.5 KiB
Go
Raw Permalink Normal View History

2022-12-30 06:51:51 +00:00
// SPDX-License-Identifier: Apache-2.0
// Copyright © 2022 Roberto Hidalgo <nidito@un.rob.mx>
package door
import (
"fmt"
"strings"
"sync"
"github.com/sirupsen/logrus"
)
var (
isOpening bool
statusMu sync.Mutex
Active Door
2022-12-30 06:51:51 +00:00
)
type newDoorFunc func(map[string]any) (Door, error)
2022-12-30 06:51:51 +00:00
var adapters = &struct {
factories map[string]newDoorFunc
names []string
}{
factories: map[string]newDoorFunc{},
names: []string{},
}
func _register(name string, factory newDoorFunc) {
adapters.factories[name] = factory
adapters.names = append(adapters.names, name)
}
type Door interface {
IsOpen() (bool, error)
Open(errors chan<- error, done chan<- bool)
}
func setStatus(status bool) {
statusMu.Lock()
isOpening = status
statusMu.Unlock()
}
// RequestToEnter opens the door unless it's already open or opening
func RequestToEnter(username string) error {
2022-12-30 06:51:51 +00:00
statusMu.Lock()
if isOpening {
defer statusMu.Unlock()
return &ErrorCommunication{"checking status", fmt.Errorf("Door is busy processing another request")}
2022-12-30 06:51:51 +00:00
}
isOpen, err := Active.IsOpen()
2022-12-30 06:51:51 +00:00
if err != nil {
statusMu.Unlock()
return &ErrorCommunication{"checking status", err}
2022-12-30 06:51:51 +00:00
} else if isOpen {
statusMu.Unlock()
return &ErrorAlreadyOpen{}
2022-12-30 06:51:51 +00:00
}
// okay, we're triggering an open and preventing others
// from doing the same until this function toggles this value again
isOpening = true
statusMu.Unlock()
logrus.Infof("Opening door for %s\n", username)
errors := make(chan error, 2)
done := make(chan bool)
go Active.Open(errors, done)
2022-12-30 06:51:51 +00:00
if err = <-errors; err != nil {
setStatus(false)
return &ErrorCommunication{"opening", err}
2022-12-30 06:51:51 +00:00
}
logrus.Infof("Door opened for %s", username)
go func() {
// Door might continue working on stuff after we Open,
// wait for done or another error
select {
case <-done:
logrus.Info("REX complete")
case err, ok := <-errors:
if ok && err != nil {
logrus.Errorf("Failed during power off: %s", err)
} else if ok {
logrus.Info("Door power shut off correctly")
}
}
// now it's safe for others to open the door
setStatus(false)
}()
return nil
}
func Connect(config map[string]any) (err error) {
2022-12-30 06:51:51 +00:00
adapterName, hasAdapter := config["kind"]
if !hasAdapter {
return fmt.Errorf("missing DOOR_ADAPTER")
2022-12-30 06:51:51 +00:00
}
factory, exists := adapters.factories[adapterName.(string)]
if !exists {
return fmt.Errorf("unknown DOOR_ADAPTER \"%s\", not one of [%s]", adapterName, strings.Join(adapters.names, ","))
2022-12-30 06:51:51 +00:00
}
Active, err = factory(config)
return err
2022-12-30 06:51:51 +00:00
}