Files
servicedemon/registrar/approval.go

92 lines
2.0 KiB
Go

package registrar
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"github.com/google/uuid"
svc "go.fixergrid.net/servicedemon/registrar/internal/services"
)
const APPROVAL_TOPIC = "net.fixergrid.events.app.approved"
type ApprovalListener struct {
svc.ApprovalRequester
svc.PubSub
svc.AppRepo
log ilogger
}
type option func(r *ApprovalListener)
func OptionLog(l logger) option {
return func(r *ApprovalListener) {
r.log = internalLog{l}
}
}
func NewApprovalListener(ps svc.PubSub, requester svc.ApprovalRequester, repo svc.AppRepo, options ...option) ApprovalListener {
out := ApprovalListener{
PubSub: ps,
ApprovalRequester: requester,
AppRepo: repo,
log: log.New(os.Stderr, "servicedemon/registrar - ", log.LstdFlags|log.Lshortfile),
}
for _, opt := range options {
opt(&out)
}
return out
}
func (a ApprovalListener) Run(ctx context.Context) {
newAppEvents := a.Subscribe(REGISTRATION_TOPIC)
approvalEvents := a.Subscribe(APPROVAL_TOPIC)
for {
select {
case <-ctx.Done():
return
case event := <-newAppEvents:
msg, err := readMessage(event)
if err != nil {
a.log.Printf("failed to read message: got '%s': %v", event, err)
}
a.SendApprovalRequest(msg["name"])
case event := <-approvalEvents:
msg, err := readMessage(event)
if err != nil {
a.log.Printf("approvalevent: failed to read message: got '%s': %v", event, err)
}
id := uuid.MustParse(msg["id"])
a.HandleApprovedRequest(id)
}
}
}
func (a ApprovalListener) SendApprovalRequest(name string) {
a.log.Printf("sent approval message for [%s]", name)
}
func (a ApprovalListener) HandleApprovedRequest(id uuid.UUID) {
res, err := a.ApproveApp(id)
if err != nil {
a.log.Printf("ERROR: couldn't approve request: %v", err)
return
}
a.log.Printf("approved application [%s]", res.ID)
}
func readMessage(event string) (map[string]string, error) {
out := map[string]string{}
err := json.Unmarshal([]byte(event), &out)
if err != nil {
return nil, fmt.Errorf("readMessage: %w", err)
}
return out, nil
}