Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 5 additions & 7 deletions internal/api/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,9 @@ func (a *API) handleRegister(w http.ResponseWriter, r *http.Request) {
}

lease, err := a.node.Register(r.Context(), node.Registration{
Service: reg.Service,
InstanceID: reg.InstanceID,
Endpoint: reg.Endpoint,
TTL: ttl,
Service: reg.Service,
Endpoint: reg.Endpoint,
TTL: ttl,
})
if err != nil {
status := http.StatusInternalServerError
Expand Down Expand Up @@ -111,9 +110,8 @@ func (a *API) handleLookup(w http.ResponseWriter, r *http.Request) {
}

writeJSON(w, ProviderResponse{
Service: provider.Service,
InstanceID: provider.InstanceID,
Endpoint: provider.Endpoint,
Service: provider.Service,
Endpoint: provider.Endpoint,
})
}

Expand Down
12 changes: 5 additions & 7 deletions internal/api/requests.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@ import (
)

type RegistrationRequest struct {
Service string `json:"service"`
InstanceID string `json:"instance_id"`
Endpoint string `json:"endpoint"`
TTL string `json:"ttl"`
Service string `json:"service"`
Endpoint string `json:"endpoint"`
TTL string `json:"ttl"`
}

type RenewRequest struct {
Expand All @@ -22,9 +21,8 @@ type LeaseResponse struct {
}

type ProviderResponse struct {
Service string `json:"service"`
InstanceID string `json:"instance_id"`
Endpoint string `json:"endpoint"`
Service string `json:"service"`
Endpoint string `json:"endpoint"`
}

type StatusResponse struct {
Expand Down
7 changes: 3 additions & 4 deletions internal/node/leave_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,9 @@ import (

func testRegistration() Registration {
return Registration{
Service: "payments-api",
InstanceID: "i-1",
Endpoint: "http://127.0.0.1:9000",
TTL: time.Minute,
Service: "payments-api",
Endpoint: "http://127.0.0.1:9000",
TTL: time.Minute,
}
}

Expand Down
162 changes: 162 additions & 0 deletions internal/node/service_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
package node

import (
"errors"
"testing"
"time"

"github.com/cap-theorem/spectral/internal/transport"
"github.com/cap-theorem/spectral/internal/wire"
)

func settle(nodes ...*Node) {
for range 5 {
for _, n := range nodes {
for drained := false; !drained; {
select {
case env := <-n.transport.Recv():
n.handleEnvelope(env)
default:
drained = true
}
}
n.flush()
}
}
}

func TestRegisterAdvertisesService(t *testing.T) {
n := testNode()
reg := testRegistration()
inc := n.reg.records[n.self.ID].Inc

lease, err := n.registerService(reg)
if err != nil || lease.Token == "" {
t.Fatalf("registerService() = %+v, %v", lease, err)
}

own := n.reg.records[n.self.ID]
if own.Service.Name != reg.Service || own.Service.Endpoint != reg.Endpoint || own.Inc != inc+1 || own.Status != wire.StatusAlive {
t.Fatalf("own record = %+v", own.Record)
}
if len(n.mem.outbox) == 0 {
t.Fatal("registration not queued to flood")
}

got, err := n.lookupService(reg.Service)
if err != nil || got.Endpoint != reg.Endpoint {
t.Fatalf("lookupService() = %+v, %v", got, err)
}
}

func TestLookupServiceNotFound(t *testing.T) {
n := testNode()
if _, err := n.lookupService("missing"); !errors.Is(err, ErrServiceNotFound) {
t.Fatalf("lookupService() error = %v, want ErrServiceNotFound", err)
}
}

func TestRenewService(t *testing.T) {
tests := []struct {
name string
token func(lease Lease) string
expires time.Duration
wantErr error
}{
{"valid token", func(l Lease) string { return l.Token }, time.Second, nil},
{"wrong token", func(l Lease) string { return "nope" }, time.Second, ErrLeaseNotFound},
{"empty token", func(l Lease) string { return "" }, time.Second, ErrLeaseNotFound},
{"expired lease", func(l Lease) string { return l.Token }, -time.Second, ErrLeaseNotFound},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
n := testNode()
lease, err := n.registerService(testRegistration())
if err != nil {
t.Fatal(err)
}
before := time.Now().Add(tt.expires)
n.lease.ExpiresAt = before

got, err := n.renewService(tt.token(lease))
if !errors.Is(err, tt.wantErr) {
t.Fatalf("renewService() error = %v, want %v", err, tt.wantErr)
}
if tt.wantErr == nil && !got.ExpiresAt.After(before) {
t.Fatalf("expiry = %v, want after %v", got.ExpiresAt, before)
}
if tt.wantErr != nil && !n.lease.ExpiresAt.Equal(before) {
t.Fatalf("failed renew moved expiry to %v", n.lease.ExpiresAt)
}
})
}
}

func TestLeaseExpiryWithdrawsService(t *testing.T) {
n := testNode()
lease, err := n.registerService(testRegistration())
if err != nil {
t.Fatal(err)
}
inc := n.reg.records[n.self.ID].Inc

n.expireLease(lease.ExpiresAt.Add(-time.Millisecond))
if n.reg.records[n.self.ID].Service.Name == "" {
t.Fatal("service withdrawn before expiry")
}

n.expireLease(lease.ExpiresAt)
own := n.reg.records[n.self.ID]
if own.Service.Name != "" || own.Status != wire.StatusAlive || own.Inc != inc+1 || n.lease != nil {
t.Fatalf("after expiry: %+v, lease %v", own.Record, n.lease)
}
if _, err := n.lookupService(testRegistration().Service); !errors.Is(err, ErrServiceNotFound) {
t.Fatalf("lookupService() error = %v, want ErrServiceNotFound", err)
}
if _, err := n.renewService(lease.Token); !errors.Is(err, ErrLeaseNotFound) {
t.Fatalf("renewService() error = %v, want ErrLeaseNotFound", err)
}
}

func TestServiceLifecycleOverMem(t *testing.T) {
network := transport.NewMemNetwork()
a, b, c := memNode(network, 7601), memNode(network, 7602), memNode(network, 7603)
now := time.Now()
for _, n := range []*Node{a, b, c} {
for _, m := range []*Node{a, b, c} {
if n != m {
linkTo(n, m.self, now)
}
}
}

reg := testRegistration()
lease, err := a.registerService(reg)
if err != nil {
t.Fatal(err)
}
settle(a, b, c)

for _, n := range []*Node{b, c} {
got, err := n.lookupService(reg.Service)
if err != nil || got.Endpoint != reg.Endpoint {
t.Fatalf("lookup on %v = %+v, %v", n.self.Address, got, err)
}
}

if _, err := a.renewService(lease.Token); err != nil {
t.Fatalf("renewService() error = %v", err)
}
a.expireLease(time.Now().Add(time.Hour))
settle(a, b, c)

for _, n := range []*Node{b, c} {
if _, err := n.lookupService(reg.Service); !errors.Is(err, ErrServiceNotFound) {
t.Fatalf("lookup on %v after expiry: %v", n.self.Address, err)
}
if st := n.reg.records[a.self.ID].Status; st != wire.StatusAlive {
t.Fatalf("expiry changed node status to %v", st)
}
}
}
26 changes: 7 additions & 19 deletions internal/node/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,26 +17,15 @@ const (
StateLeft State = "left"
)

type RegistrationKey struct {
Service string
InstanceID string
}

type RegistrationEntry struct {
Provider Provider
Lease Lease
}

type Registration struct {
Service string
InstanceID string
Endpoint string
TTL time.Duration
Service string
Endpoint string
TTL time.Duration
}

func (r Registration) Validate() error {
if strings.TrimSpace(r.Service) == "" || strings.TrimSpace(r.InstanceID) == "" {
return fmt.Errorf("%w: service and instance_id are required", ErrInvalidRegistration)
if strings.TrimSpace(r.Service) == "" {
return fmt.Errorf("%w: service is required", ErrInvalidRegistration)
}
if r.TTL <= 0 {
return fmt.Errorf("%w: ttl must be positive", ErrInvalidRegistration)
Expand Down Expand Up @@ -64,9 +53,8 @@ type Lease struct {
}

type Provider struct {
Service string
InstanceID string
Endpoint string
Service string
Endpoint string
}

type Status struct {
Expand Down
8 changes: 3 additions & 5 deletions internal/node/types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,9 @@ import (

func TestRegistrationValidate(t *testing.T) {
valid := Registration{
Service: "payments",
InstanceID: "payments-1",
Endpoint: "http://10.0.0.1:8000",
TTL: 10 * time.Second,
Service: "payments",
Endpoint: "http://10.0.0.1:8000",
TTL: 10 * time.Second,
}

tests := []struct {
Expand All @@ -23,7 +22,6 @@ func TestRegistrationValidate(t *testing.T) {
{"https with path", func(r *Registration) { r.Endpoint = "https://pay.svc:443/v1" }, false},
{"ipv6 host", func(r *Registration) { r.Endpoint = "http://[::1]:8000" }, false},
{"blank service", func(r *Registration) { r.Service = " " }, true},
{"blank instance", func(r *Registration) { r.InstanceID = "" }, true},
{"zero ttl", func(r *Registration) { r.TTL = 0 }, true},
{"negative ttl", func(r *Registration) { r.TTL = -time.Second }, true},
{"no scheme", func(r *Registration) { r.Endpoint = "10.0.0.1:80" }, true},
Expand Down
Loading