Skip to content

Commit

Permalink
update serverservice for toolbox/events v0.6.0 (#214)
Browse files Browse the repository at this point in the history
  • Loading branch information
DoctorVin authored May 19, 2023
1 parent 4551290 commit 6d4a327
Show file tree
Hide file tree
Showing 6 changed files with 122 additions and 17 deletions.
3 changes: 1 addition & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ require (

require (
github.com/volatiletech/sqlboiler v3.7.1+incompatible
go.hollow.sh/toolbox v0.5.2-0.20230403084733-0bfb6095e5a5
go.hollow.sh/toolbox v0.6.0
go.infratographer.com/x v0.0.7
gocloud.dev v0.29.0
golang.org/x/exp v0.0.0-20230425010034-47ecfdc1ba53
Expand Down Expand Up @@ -85,7 +85,6 @@ require (
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/nats-io/jwt/v2 v2.3.0 // indirect
github.com/nats-io/nats.go v1.25.0 // indirect
github.com/nats-io/nkeys v0.4.4 // indirect
github.com/nats-io/nuid v1.0.1 // indirect
Expand Down
8 changes: 3 additions & 5 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -1428,8 +1428,6 @@ github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/lib/pq v1.10.2/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/lib/pq v1.10.6/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/lib/pq v1.10.7/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/lib/pq v1.10.8 h1:3fdt97i/cwSU83+E0hZTC/Xpc9mTZxc6UWSCRcSbxiE=
github.com/lib/pq v1.10.8/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/linode/linodego v1.4.0/go.mod h1:PVsRxSlOiJyvG4/scTszpmZDTdgS+to3X6eS8pRrWI8=
Expand Down Expand Up @@ -1548,10 +1546,10 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8m
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw=
github.com/nats-io/jwt v1.2.2 h1:w3GMTO969dFg+UOKTmmyuu7IGdusK+7Ytlt//OYH/uU=
github.com/nats-io/jwt v1.2.2/go.mod h1:/xX356yQA6LuXI9xWW7mZNpxgF2mBmGecH+Fj34sP5Q=
github.com/nats-io/jwt/v2 v2.0.3/go.mod h1:VRP+deawSXyhNjXmxPCHskrR6Mq50BqpEI5SEcNiGlY=
github.com/nats-io/jwt/v2 v2.3.0 h1:z2mA1a7tIf5ShggOFlR1oBPgd6hGqcDYsISxZByUzdI=
github.com/nats-io/jwt/v2 v2.3.0/go.mod h1:0tqz9Hlu6bCBFLWAASKhE5vUA4c24L9KPUUgvwumE/k=
github.com/nats-io/nats-server/v2 v2.5.0/go.mod h1:Kj86UtrXAL6LwYRA6H4RqzkHhK0Vcv2ZnKD5WbQ1t3g=
github.com/nats-io/nats-server/v2 v2.9.15 h1:MuwEJheIwpvFgqvbs20W8Ish2azcygjf4Z0liVu2I4c=
github.com/nats-io/nats.go v1.12.1/go.mod h1:BPko4oXsySz4aSWeFgOHLZs3G4Jq4ZAyE6/zMCxRT6w=
Expand Down Expand Up @@ -1949,8 +1947,8 @@ go.etcd.io/etcd/client/v3 v3.5.4/go.mod h1:ZaRkVgBZC+L+dLCjTcF1hRXpgZXQPOvnA/Ak/
go.etcd.io/etcd/pkg/v3 v3.5.0/go.mod h1:UzJGatBQ1lXChBkQF0AuAtkRQMYnHubxAEYIrC3MSsE=
go.etcd.io/etcd/raft/v3 v3.5.0/go.mod h1:UFOHSIvO/nKwd4lhkwabrTD3cqW5yVyYYf/KlD00Szc=
go.etcd.io/etcd/server/v3 v3.5.0/go.mod h1:3Ah5ruV+M+7RZr0+Y/5mNLwC+eQlni+mQmOVdCRJoS4=
go.hollow.sh/toolbox v0.5.2-0.20230403084733-0bfb6095e5a5 h1:b+EylRbk0ZW6KR7fuTrrwLuhjZubsdvbnhi3dbgLQcM=
go.hollow.sh/toolbox v0.5.2-0.20230403084733-0bfb6095e5a5/go.mod h1:ie1D46xsLHj1RZTQ4D2HCni/FMP2hSqF8tbmCTkLP4A=
go.hollow.sh/toolbox v0.6.0 h1:4HTzh4gVPjJO1Q2FhNn2r4T+EaufTdJj49rUdasl3pA=
go.hollow.sh/toolbox v0.6.0/go.mod h1:imcLT0oRHkDSlA5ENoXWDihQCOQitsP8zZrPSezFyig=
go.infratographer.com/x v0.0.7 h1:eUdA1zZpV/odXWjsNlsuYR+s++zf6G//CG7SPFXglDQ=
go.infratographer.com/x v0.0.7/go.mod h1:yRNFRLtURkukh4Wbd1SpNgCzhsUMaxV544rFYc3g0ZU=
go.mongodb.org/mongo-driver v1.7.3/go.mod h1:NqaYOwnXWr5Pm7AOpO5QFxKJ503nbMse/R79oO62zWg=
Expand Down
61 changes: 61 additions & 0 deletions pkg/api/v1/messages.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
//nolint:wsl,revive
package serverservice

import (
"encoding/json"
"time"

"github.com/pkg/errors"
"github.com/volatiletech/null/v8"

"go.hollow.sh/serverservice/internal/models"
)

var (
ErrNilServer = errors.New("bogus server structure provided")
ErrBadJSONOut = errors.New("object serializaion failed")
ErrBadJSONIn = errors.New("object deserializaion failed")
)

// MsgMetadata captures some message-type agnostic descriptive data a consumer might need
type MsgMetadata struct {
CreatedAt time.Time `json:"created_at,omitempty"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
}

// CreateServer is a message type published via NATS
type CreateServer struct {
Metadata *MsgMetadata `json:"metadata,omitempty"`
Name null.String `json:"name"`
FacilityCode null.String `json:"facility_code"`
ID string `json:"id"`
}

// NewCreateServerMessage composes a CreateServer message for NATS
func NewCreateServerMessage(srv *models.Server) ([]byte, error) {
if srv == nil {
return nil, ErrNilServer
}
cs := &CreateServer{
Metadata: &MsgMetadata{
CreatedAt: time.Now(),
},
Name: srv.Name,
FacilityCode: srv.FacilityCode,
ID: srv.ID,
}
byt, err := json.Marshal(cs)
if err != nil {
return nil, errors.Wrap(ErrBadJSONOut, err.Error())
}
return byt, err
}

// DeserializeCreateServer reconstitutes a CreateServer from raw bytes
func DeserializeCreateServer(inc []byte) (*CreateServer, error) {
cs := &CreateServer{}
if err := json.Unmarshal(inc, cs); err != nil {
return nil, errors.Wrap(ErrBadJSONIn, err.Error())
}
return cs, nil
}
42 changes: 42 additions & 0 deletions pkg/api/v1/messages_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
//nolint:wsl
package serverservice

import (
"testing"

"github.com/stretchr/testify/require"
"github.com/volatiletech/null/v8"

"go.hollow.sh/serverservice/internal/models"
)

func TestSerialization(t *testing.T) {
srv := &models.Server{
Name: null.StringFrom("server-name"),
FacilityCode: null.StringFrom("fc13"),
ID: "some-uuid-str",
}

_, err := NewCreateServerMessage((*models.Server)(nil))
require.ErrorIs(t, err, ErrNilServer, "nil input")

byt, err := NewCreateServerMessage(srv)
require.NoError(t, err, "good server obj")
require.NotNil(t, byt, "good server obj")

bogus := []byte("bogus")
_, err = DeserializeCreateServer(bogus)
require.ErrorIs(t, err, ErrBadJSONIn, "bogus deserialize")

exp := &CreateServer{
Name: null.StringFrom("server-name"),
FacilityCode: null.StringFrom("fc13"),
ID: "some-uuid-str",
}

cs, err := DeserializeCreateServer(byt)
require.NoError(t, err, "good deserialize")
require.Equal(t, exp.Name, cs.Name, "good deserialize name")
require.Equal(t, exp.FacilityCode, cs.FacilityCode, "good deserialize facility")
require.Equal(t, exp.ID, cs.ID, "good deserialize id")
}
20 changes: 13 additions & 7 deletions pkg/api/v1/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"fmt"
"strings"

"github.com/gin-gonic/gin"
"github.com/google/uuid"
Expand Down Expand Up @@ -223,17 +224,22 @@ func (r *Router) loadComponentFirmwareVersionFromParams(c *gin.Context) (*models
return firmware, nil
}

// publishEventAsync wraps publishing to the event stream to publish them if the event stream is available.
func (r *Router) publishEventAsync(ctx context.Context, resType events.ResourceType, eventType events.EventType, obj interface{}, objID string) {
// publish a CreateServer message to the event stream. if the publish fails...?
//
//nolint:wsl
func (r *Router) publishCreateServerMessage(ctx context.Context, srv *models.Server) {
if r.EventStream == nil {
r.Logger.Error("Event publish skipped, eventStream not connected")

return
}

if err := r.EventStream.PublishAsyncWithContext(ctx, resType, eventType, objID, obj); err != nil {
r.Logger.Error("Error in event stream publish", zap.Error(err))

subject := strings.Join([]string{"server", "create"}, ".")
payload, err := NewCreateServerMessage(srv)
if err != nil {
r.Logger.With(zap.Error(err)).Error("unable to create a create-server message")
return
}
if err := r.EventStream.Publish(ctx, subject, payload); err != nil {
r.Logger.With(zap.Error(err)).Error("unable to publish create-server message")
return
}
}
5 changes: 2 additions & 3 deletions pkg/api/v1/router_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"github.com/volatiletech/sqlboiler/v4/boil"
"github.com/volatiletech/sqlboiler/v4/queries/qm"
"github.com/volatiletech/sqlboiler/v4/types"
"go.hollow.sh/toolbox/events"

"go.hollow.sh/serverservice/internal/models"
)
Expand Down Expand Up @@ -108,8 +107,8 @@ func (r *Router) serverCreate(c *gin.Context) {
return
}

// publish event
r.publishEventAsync(c.Request.Context(), "servers", events.Create, dbSRV, dbSRV.ID)
// publish event XXX: this should handle publish failures or otherwise take action if NATS is unavailable
r.publishCreateServerMessage(c.Request.Context(), dbSRV)

createdResponse(c, dbSRV.ID)
}
Expand Down

0 comments on commit 6d4a327

Please sign in to comment.