Drop the module leader recompute event
The queue event did two things: set the routing-changed flag, which the lifecycle event of the same change already sets, and deliver the leader-change info log. It cost an extra raft INSERT per connect/disconnect, two GetForLeaderElection reads per lifecycle event used for nothing else, a payload kind, a compaction key and a subscription-service method that only logged. The leader is now logged where it is published: the address-list emission logs the leader it just sent, and the routing rebuild logs one summary line with the leaders it published. Modules without election stay silent, as before. A future self-election needs a recompute trigger that also re-broadcasts the address list; that event will be added when the requirement exists, not carried as a no-op.
This commit is contained in:
1 parent
a8a475435c
commit
439e6f5ebf
9 files changed
+156
-550
No files matched your search
@@ -19,13 +19,6 @@ func NewEvent(payload EventPayload) Event {
|
||||
}
|
||||
}
|
||||
|
||||
// Module leader recompute reasons. They tell the log which change of the cluster put the event in the queue,
|
||||
// and only that: the leader itself is taken from the module instances every time it is needed.
|
||||
const (
|
||||
ModuleLeaderReasonReady = "ready"
|
||||
ModuleLeaderReasonDisconnect = "disconnect"
|
||||
)
|
||||
|
||||
func (e Event) Key() string {
|
||||
switch {
|
||||
case e.Payload.Value.ConfigUpdated != nil:
|
||||
@@ -34,10 +27,6 @@ func (e Event) Key() string {
|
||||
return fmt.Sprintf("module_lifecycle_%s", e.Payload.Value.ModuleReady.ModuleId)
|
||||
case e.Payload.Value.ModuleDisconnected != nil:
|
||||
return fmt.Sprintf("module_lifecycle_%s", e.Payload.Value.ModuleDisconnected.ModuleId)
|
||||
case e.Payload.Value.ModuleLeaderRecompute != nil:
|
||||
// The leader recompute keeps its own key: the compactor collapses ready and disconnected into one
|
||||
// lifecycle event per module, and the recompute must not be swallowed by that collapse.
|
||||
return fmt.Sprintf("module_leader_%s", e.Payload.Value.ModuleLeaderRecompute.ModuleId)
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
@@ -48,8 +37,6 @@ type EventPayload struct {
|
||||
ConfigUpdated *PayloadConfigUpdated `json:",omitempty"`
|
||||
ModuleReady *PayloadModuleReady `json:",omitempty"`
|
||||
ModuleDisconnected *PayloadModuleDisconnected `json:",omitempty"`
|
||||
// ModuleLeaderRecompute is internal: no module receives it as a WebSocket event.
|
||||
ModuleLeaderRecompute *PayloadModuleLeaderRecompute `json:",omitempty"`
|
||||
}
|
||||
|
||||
type PayloadConfigUpdated struct {
|
||||
@@ -63,22 +50,3 @@ type PayloadModuleReady struct {
|
||||
type PayloadModuleDisconnected struct {
|
||||
ModuleId string
|
||||
}
|
||||
|
||||
// PayloadModuleLeaderRecompute asks the config service to look at the module leader again.
|
||||
//
|
||||
// PreviousLeader is the address the leader had before the change, and Leader is the address derived from the
|
||||
// module instances after it, empty when the module has no leader left. Both are assembled where the change
|
||||
// happens, together with the events of that change, so the event worker reads nothing from the database: an
|
||||
// extra read there races with the events of the same cluster and slows the whole queue down. The leader
|
||||
// address the modules see is still elected by the read path when it serves a request.
|
||||
//
|
||||
// nolint:tagliatelle
|
||||
type PayloadModuleLeaderRecompute struct {
|
||||
ModuleId string
|
||||
ModuleName string
|
||||
Reason string
|
||||
// PreviousLeader is empty when the module had no leader.
|
||||
PreviousLeader string
|
||||
// Leader is empty when the module has no leader after the change.
|
||||
Leader string
|
||||
}
|
||||
@@ -9,12 +9,9 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const (
|
||||
testModuleId = "test-module-id"
|
||||
testModuleName = "test-module"
|
||||
)
|
||||
const testModuleId = "test-module-id"
|
||||
|
||||
func TestCompactKeepsModuleLeaderRecompute(t *testing.T) {
|
||||
func TestCompactCollapsesModuleLifecycle(t *testing.T) {
|
||||
t.Parallel()
|
||||
require := require.New(t)
|
||||
|
||||
@@ -28,28 +25,17 @@ func TestCompactKeepsModuleLeaderRecompute(t *testing.T) {
|
||||
})
|
||||
disconnected.Id = 2
|
||||
|
||||
recompute := moduleLeaderRecomputeEvent(entity.ModuleLeaderReasonDisconnect, "10.0.0.1:9000")
|
||||
recompute.Id = 3
|
||||
configUpdated := entity.NewEvent(entity.EventPayload{
|
||||
ConfigUpdated: &entity.PayloadConfigUpdated{ModuleId: testModuleId},
|
||||
})
|
||||
configUpdated.Id = 3
|
||||
|
||||
require.Equal("module_lifecycle_"+testModuleId, ready.Key())
|
||||
require.Equal("module_lifecycle_"+testModuleId, disconnected.Key())
|
||||
require.Equal("module_leader_"+testModuleId, recompute.Key(),
|
||||
"the leader recompute must not share the lifecycle key")
|
||||
require.NotEmpty(recompute.Key())
|
||||
require.Equal("config_updated_"+testModuleId, configUpdated.Key())
|
||||
|
||||
compacted := event.NewCompactor().Compact([]entity.Event{ready, disconnected, recompute})
|
||||
compacted := event.NewCompactor().Compact([]entity.Event{ready, disconnected, configUpdated})
|
||||
|
||||
require.Equal([]entity.Event{disconnected, recompute}, compacted,
|
||||
"the newest lifecycle event wins, the leader recompute is a key of its own")
|
||||
}
|
||||
|
||||
func moduleLeaderRecomputeEvent(reason string, previousLeader string) entity.Event {
|
||||
return entity.NewEvent(entity.EventPayload{
|
||||
ModuleLeaderRecompute: &entity.PayloadModuleLeaderRecompute{
|
||||
ModuleId: testModuleId,
|
||||
ModuleName: testModuleName,
|
||||
Reason: reason,
|
||||
PreviousLeader: previousLeader,
|
||||
},
|
||||
})
|
||||
require.Equal([]entity.Event{disconnected, configUpdated}, compacted,
|
||||
"the newest lifecycle event wins, a config update is a key of its own")
|
||||
}
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
type SubscriptionService interface {
|
||||
NotifyConfigChanged(ctx context.Context, moduleId string) error
|
||||
NotifyBackendsChanged(ctx context.Context, moduleId string) error
|
||||
NotifyModuleLeaderRecompute(ctx context.Context, recompute entity.PayloadModuleLeaderRecompute)
|
||||
NotifyRoutingChanged(ctx context.Context) error
|
||||
}
|
||||
|
||||
@@ -36,8 +35,7 @@ func (h Handler) Handle(ctx context.Context, events []entity.Event) {
|
||||
payload := event.Payload.Value
|
||||
routingChanged = routingChanged ||
|
||||
payload.ModuleReady != nil ||
|
||||
payload.ModuleDisconnected != nil ||
|
||||
payload.ModuleLeaderRecompute != nil
|
||||
payload.ModuleDisconnected != nil
|
||||
err := h.handleEvent(ctx, event)
|
||||
if err != nil {
|
||||
h.logger.Error(ctx, errors.WithMessagef(err, "handle event: %s", event.Key()))
|
||||
@@ -70,8 +68,6 @@ func (h Handler) handleEvent(ctx context.Context, event entity.Event) error {
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "handle module disconnected event")
|
||||
}
|
||||
case payload.ModuleLeaderRecompute != nil:
|
||||
h.subscriptionService.NotifyModuleLeaderRecompute(ctx, *payload.ModuleLeaderRecompute)
|
||||
default:
|
||||
return errors.Errorf("unknown event: %v", payload)
|
||||
}
|
||||
|
||||
@@ -12,15 +12,8 @@ import (
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
type recomputeCall struct {
|
||||
moduleId string
|
||||
reason string
|
||||
previousLeader string
|
||||
}
|
||||
|
||||
type subscriptionSpy struct {
|
||||
backendsChanged []string
|
||||
recomputes []recomputeCall
|
||||
routingCalls int
|
||||
}
|
||||
|
||||
@@ -33,17 +26,6 @@ func (s *subscriptionSpy) NotifyBackendsChanged(ctx context.Context, moduleId st
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *subscriptionSpy) NotifyModuleLeaderRecompute(
|
||||
ctx context.Context,
|
||||
recompute entity.PayloadModuleLeaderRecompute,
|
||||
) {
|
||||
s.recomputes = append(s.recomputes, recomputeCall{
|
||||
moduleId: recompute.ModuleId,
|
||||
reason: recompute.Reason,
|
||||
previousLeader: recompute.PreviousLeader,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *subscriptionSpy) NotifyRoutingChanged(ctx context.Context) error {
|
||||
s.routingCalls++
|
||||
return nil
|
||||
@@ -63,55 +45,38 @@ func (l *loggerSpy) Info(ctx context.Context, message any, fields ...log.Field)
|
||||
|
||||
func (l *loggerSpy) Debug(ctx context.Context, message any, fields ...log.Field) {}
|
||||
|
||||
func TestHandleModuleLeaderRecomputeEvent(t *testing.T) {
|
||||
t.Parallel()
|
||||
require := require.New(t)
|
||||
|
||||
subscription := &subscriptionSpy{}
|
||||
logger := &loggerSpy{}
|
||||
handler := event.NewHandler(subscription, logger)
|
||||
|
||||
handler.Handle(t.Context(), []entity.Event{
|
||||
moduleLeaderRecomputeEvent(entity.ModuleLeaderReasonDisconnect, "10.0.0.1:9000"),
|
||||
})
|
||||
|
||||
require.Equal([]recomputeCall{{
|
||||
moduleId: testModuleId,
|
||||
reason: entity.ModuleLeaderReasonDisconnect,
|
||||
previousLeader: "10.0.0.1:9000",
|
||||
}}, subscription.recomputes)
|
||||
require.Empty(subscription.backendsChanged, "the recompute event maps the address list on its own")
|
||||
require.Equal(1, subscription.routingCalls, "the recompute event fans the routing map out with the batch")
|
||||
require.Empty(logger.errors)
|
||||
}
|
||||
|
||||
func TestHandleBatchKeepsModuleLeaderRecompute(t *testing.T) {
|
||||
t.Parallel()
|
||||
require := require.New(t)
|
||||
|
||||
subscription := &subscriptionSpy{}
|
||||
logger := &loggerSpy{}
|
||||
handler := event.NewHandler(subscription, logger)
|
||||
|
||||
ready := entity.NewEvent(entity.EventPayload{
|
||||
func moduleReadyEvent(id int) entity.Event {
|
||||
event := entity.NewEvent(entity.EventPayload{
|
||||
ModuleReady: &entity.PayloadModuleReady{ModuleId: testModuleId},
|
||||
})
|
||||
ready.Id = 1
|
||||
event.Id = id
|
||||
return event
|
||||
}
|
||||
|
||||
disconnected := entity.NewEvent(entity.EventPayload{
|
||||
func moduleDisconnectedEvent(id int) entity.Event {
|
||||
event := entity.NewEvent(entity.EventPayload{
|
||||
ModuleDisconnected: &entity.PayloadModuleDisconnected{ModuleId: testModuleId},
|
||||
})
|
||||
disconnected.Id = 2
|
||||
event.Id = id
|
||||
return event
|
||||
}
|
||||
|
||||
recompute := moduleLeaderRecomputeEvent(entity.ModuleLeaderReasonDisconnect, "10.0.0.1:9000")
|
||||
recompute.Id = 3
|
||||
func TestHandleLifecycleBatchFansRoutingOnce(t *testing.T) {
|
||||
t.Parallel()
|
||||
require := require.New(t)
|
||||
|
||||
batch := event.NewCompactor().Compact([]entity.Event{ready, disconnected, recompute})
|
||||
subscription := &subscriptionSpy{}
|
||||
logger := &loggerSpy{}
|
||||
handler := event.NewHandler(subscription, logger)
|
||||
|
||||
batch := event.NewCompactor().Compact([]entity.Event{
|
||||
moduleReadyEvent(1),
|
||||
moduleDisconnectedEvent(2),
|
||||
})
|
||||
handler.Handle(t.Context(), batch)
|
||||
|
||||
require.Equal([]string{testModuleId}, subscription.backendsChanged,
|
||||
"ready and disconnected collapse into the newest lifecycle event")
|
||||
require.Len(subscription.recomputes, 1, "the leader recompute must survive compaction")
|
||||
require.Equal(1, subscription.routingCalls, "the routing map is broadcast once per batch")
|
||||
require.Empty(logger.errors)
|
||||
}
|
||||
@@ -126,13 +91,11 @@ func TestHandleUnknownEventDoesNotAbortBatch(t *testing.T) {
|
||||
|
||||
unknown := entity.NewEvent(entity.EventPayload{})
|
||||
|
||||
handler.Handle(t.Context(), []entity.Event{unknown, moduleLeaderRecomputeEvent(
|
||||
entity.ModuleLeaderReasonReady,
|
||||
"",
|
||||
)})
|
||||
handler.Handle(t.Context(), []entity.Event{unknown, moduleReadyEvent(1)})
|
||||
|
||||
require.Len(logger.errors, 1)
|
||||
require.Contains(logger.errors[0], "unknown event")
|
||||
require.Len(subscription.recomputes, 1, "an unknown payload kind must not stop the batch")
|
||||
require.Equal([]string{testModuleId}, subscription.backendsChanged,
|
||||
"an unknown payload kind must not stop the batch")
|
||||
require.Equal(1, subscription.routingCalls)
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
|
||||
"isp-config-service/entity"
|
||||
"isp-config-service/entity/xtypes"
|
||||
"isp-config-service/service/module/leader"
|
||||
|
||||
"github.com/txix-open/etp/v4"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
@@ -20,7 +19,6 @@ type Repo interface {
|
||||
DeleteByWsConnectionIds(ctx context.Context, wsConnIds []string) error
|
||||
GetByConfigServiceNodeId(ctx context.Context, configServiceNodeId string) ([]entity.Backend, error)
|
||||
DeleteByConfigServiceNodeId(ctx context.Context, configServiceNodeId string) (int, error)
|
||||
GetForLeaderElection(ctx context.Context, moduleId string) ([]entity.Backend, error)
|
||||
}
|
||||
|
||||
type EventRepo interface {
|
||||
@@ -89,21 +87,11 @@ func (s Backend) Connect(
|
||||
MetricsAutodiscovery: metricsAd,
|
||||
}
|
||||
|
||||
previousLeader, err := s.leaderAddress(ctx, moduleId)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "get leader of module %s before connect", moduleId)
|
||||
}
|
||||
|
||||
err = s.backendRepo.Upsert(ctx, backend)
|
||||
err := s.backendRepo.Upsert(ctx, backend)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "upsert backend in store")
|
||||
}
|
||||
|
||||
leaderAddress, err := s.leaderAddress(ctx, moduleId)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "get leader of module %s after connect", moduleId)
|
||||
}
|
||||
|
||||
event := entity.NewEvent(entity.EventPayload{
|
||||
ModuleReady: &entity.PayloadModuleReady{
|
||||
ModuleId: moduleId,
|
||||
@@ -114,37 +102,16 @@ func (s Backend) Connect(
|
||||
return nil, errors.WithMessage(err, "insert event in store")
|
||||
}
|
||||
|
||||
err = s.insertLeaderRecomputeEvent(ctx, entity.PayloadModuleLeaderRecompute{
|
||||
ModuleId: moduleId,
|
||||
ModuleName: backend.ModuleName,
|
||||
Reason: entity.ModuleLeaderReasonReady,
|
||||
PreviousLeader: previousLeader,
|
||||
Leader: leaderAddress,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "insert module leader recompute event")
|
||||
}
|
||||
|
||||
return &backend, nil
|
||||
}
|
||||
|
||||
func (s Backend) Disconnect(ctx context.Context, backend entity.Backend) error {
|
||||
previousLeader, err := s.leaderAddress(ctx, backend.ModuleId)
|
||||
if err != nil {
|
||||
return errors.WithMessagef(err, "get leader of module %s before disconnect", backend.ModuleId)
|
||||
}
|
||||
|
||||
err = s.backendRepo.DeleteByWsConnectionIds(ctx, []string{backend.WsConnectionId})
|
||||
err := s.backendRepo.DeleteByWsConnectionIds(ctx, []string{backend.WsConnectionId})
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "delete backend in store")
|
||||
}
|
||||
|
||||
leaderAddress, err := s.leaderAddress(ctx, backend.ModuleId)
|
||||
if err != nil {
|
||||
return errors.WithMessagef(err, "get leader of module %s after disconnect", backend.ModuleId)
|
||||
}
|
||||
|
||||
err = s.insertDisconnectEvent(ctx, backend, previousLeader, leaderAddress)
|
||||
err = s.insertDisconnectEvent(ctx, backend)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "insert disconnect event")
|
||||
}
|
||||
@@ -174,27 +141,13 @@ func (s Backend) ClearPhantomBackends(ctx context.Context) (int, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
previousLeaders := make(map[string]string, len(phantoms))
|
||||
for moduleId := range phantoms {
|
||||
previousLeader, err := s.leaderAddress(ctx, moduleId)
|
||||
if err != nil {
|
||||
return 0, errors.WithMessagef(err, "get leader of module %s before phantom cleanup", moduleId)
|
||||
}
|
||||
previousLeaders[moduleId] = previousLeader
|
||||
}
|
||||
|
||||
err = s.backendRepo.DeleteByWsConnectionIds(ctx, toDelete)
|
||||
if err != nil {
|
||||
return 0, errors.WithMessage(err, "delete backends by ws connection ids")
|
||||
}
|
||||
|
||||
for moduleId, phantom := range phantoms {
|
||||
leaderAddress, err := s.leaderAddress(ctx, moduleId)
|
||||
if err != nil {
|
||||
return 0, errors.WithMessagef(err, "get leader of module %s after phantom cleanup", moduleId)
|
||||
}
|
||||
|
||||
err = s.insertDisconnectEvent(ctx, phantom, previousLeaders[moduleId], leaderAddress)
|
||||
for _, phantom := range phantoms {
|
||||
err = s.insertDisconnectEvent(ctx, phantom)
|
||||
if err != nil {
|
||||
return 0, errors.WithMessage(err, "insert disconnect event")
|
||||
}
|
||||
@@ -212,12 +165,7 @@ func (s Backend) DeleteOwnBackends(ctx context.Context) {
|
||||
s.logger.Info(ctx, fmt.Sprintf("delete %d own backends", deleted))
|
||||
}
|
||||
|
||||
func (s Backend) insertDisconnectEvent(
|
||||
ctx context.Context,
|
||||
backend entity.Backend,
|
||||
previousLeader string,
|
||||
leaderAddress string,
|
||||
) error {
|
||||
func (s Backend) insertDisconnectEvent(ctx context.Context, backend entity.Backend) error {
|
||||
event := entity.NewEvent(entity.EventPayload{
|
||||
ModuleDisconnected: &entity.PayloadModuleDisconnected{
|
||||
ModuleId: backend.ModuleId,
|
||||
@@ -228,46 +176,9 @@ func (s Backend) insertDisconnectEvent(
|
||||
return errors.WithMessage(err, "insert event in store")
|
||||
}
|
||||
|
||||
err = s.insertLeaderRecomputeEvent(ctx, entity.PayloadModuleLeaderRecompute{
|
||||
ModuleId: backend.ModuleId,
|
||||
ModuleName: backend.ModuleName,
|
||||
Reason: entity.ModuleLeaderReasonDisconnect,
|
||||
PreviousLeader: previousLeader,
|
||||
Leader: leaderAddress,
|
||||
})
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "insert module leader recompute event")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Backend) insertLeaderRecomputeEvent(
|
||||
ctx context.Context,
|
||||
recompute entity.PayloadModuleLeaderRecompute,
|
||||
) error {
|
||||
event := entity.NewEvent(entity.EventPayload{ModuleLeaderRecompute: &recompute})
|
||||
err := s.eventRepo.Insert(ctx, event)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "insert event in store")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Backend) leaderAddress(ctx context.Context, moduleId string) (string, error) {
|
||||
backends, err := s.backendRepo.GetForLeaderElection(ctx, moduleId)
|
||||
if err != nil {
|
||||
return "", errors.WithMessagef(err, "get backends by module id = %s", moduleId)
|
||||
}
|
||||
|
||||
election := leader.Derive(backends)
|
||||
if !election.Found {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
return election.Leader.Address, nil
|
||||
}
|
||||
|
||||
func (s Backend) normalizeModuleLeaderMode(
|
||||
ctx context.Context,
|
||||
moduleName string,
|
||||
|
||||
@@ -102,19 +102,6 @@ func (r *backendRepoSpy) DeleteByConfigServiceNodeId(ctx context.Context, config
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (r *backendRepoSpy) GetForLeaderElection(ctx context.Context, moduleId string) ([]entity.Backend, error) {
|
||||
r.calls = append(r.calls, "leader_election")
|
||||
|
||||
moduleBackends := make([]entity.Backend, 0, len(r.rows))
|
||||
for _, backend := range r.rows {
|
||||
if backend.ModuleId == moduleId {
|
||||
moduleBackends = append(moduleBackends, backend)
|
||||
}
|
||||
}
|
||||
|
||||
return moduleBackends, nil
|
||||
}
|
||||
|
||||
type eventRepoSpy struct {
|
||||
inserted []entity.Event
|
||||
}
|
||||
@@ -124,17 +111,6 @@ func (r *eventRepoSpy) Insert(ctx context.Context, event entity.Event) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *eventRepoSpy) byKey(key string) []entity.Event {
|
||||
found := make([]entity.Event, 0, len(r.inserted))
|
||||
for _, event := range r.inserted {
|
||||
if event.Key() == key {
|
||||
found = append(found, event)
|
||||
}
|
||||
}
|
||||
|
||||
return found
|
||||
}
|
||||
|
||||
func TestConnectNormalizesModuleLeaderMode(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -209,7 +185,7 @@ func TestConnectNormalizesModuleLeaderMode(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectInsertsModuleLeaderRecomputeEvent(t *testing.T) {
|
||||
func TestConnectInsertsOnlyLifecycleEvent(t *testing.T) {
|
||||
t.Parallel()
|
||||
require := require.New(t)
|
||||
|
||||
@@ -217,34 +193,6 @@ func TestConnectInsertsModuleLeaderRecomputeEvent(t *testing.T) {
|
||||
backendRepo := newBackendRepoSpy(electedInstance(leaderConnId, leaderAddress))
|
||||
service := backend.NewBackend(backendRepo, events, testNodeId, nil, &loggerSpy{})
|
||||
|
||||
declaration := cluster.BackendDeclaration{
|
||||
ModuleName: testModuleName,
|
||||
Address: cluster.AddressConfiguration{IP: "10.0.0.2", Port: "9000"},
|
||||
}
|
||||
_, err := service.Connect(t.Context(), followerConnId, testModuleId, declaration)
|
||||
|
||||
require.NoError(err)
|
||||
require.Equal([]string{"leader_election", "upsert", "leader_election"}, backendRepo.calls,
|
||||
"the leader must be derived from the stored instances before and after the connect")
|
||||
require.Equal([]string{
|
||||
"module_lifecycle_" + testModuleId,
|
||||
"module_leader_" + testModuleId,
|
||||
}, eventKeys(events), "the ready event and the leader recompute must both stay in the queue")
|
||||
|
||||
recompute := requireRecompute(t, events, testModuleId)
|
||||
require.Equal(testModuleName, recompute.ModuleName)
|
||||
require.Equal(entity.ModuleLeaderReasonReady, recompute.Reason)
|
||||
require.Equal(leaderAddress, recompute.PreviousLeader)
|
||||
require.Equal(leaderAddress, recompute.Leader, "the oldest instance keeps leadership")
|
||||
}
|
||||
|
||||
func TestConnectFirstInstanceInsertsModuleLeaderRecomputeEvent(t *testing.T) {
|
||||
t.Parallel()
|
||||
require := require.New(t)
|
||||
|
||||
events := &eventRepoSpy{}
|
||||
service := backend.NewBackend(newBackendRepoSpy(), events, testNodeId, nil, &loggerSpy{})
|
||||
|
||||
declaration := cluster.BackendDeclaration{
|
||||
ModuleName: testModuleName,
|
||||
Address: cluster.AddressConfiguration{IP: "10.0.0.2", Port: "9000"},
|
||||
@@ -253,13 +201,13 @@ func TestConnectFirstInstanceInsertsModuleLeaderRecomputeEvent(t *testing.T) {
|
||||
_, err := service.Connect(t.Context(), followerConnId, testModuleId, declaration)
|
||||
|
||||
require.NoError(err)
|
||||
recompute := requireRecompute(t, events, testModuleId)
|
||||
require.Equal(entity.ModuleLeaderReasonReady, recompute.Reason)
|
||||
require.Empty(recompute.PreviousLeader, "the first instance of a module has no previous leader")
|
||||
require.Equal(followerAddress, recompute.Leader, "the first instance is the leader")
|
||||
require.Equal([]string{"upsert"}, backendRepo.calls,
|
||||
"the connect path elects nobody: the leader is derived where the address list is emitted")
|
||||
require.Equal([]string{"module_lifecycle_" + testModuleId}, eventKeys(events),
|
||||
"one lifecycle event per connect, no dedicated leader event")
|
||||
}
|
||||
|
||||
func TestDisconnectInsertsModuleLeaderRecomputeEvent(t *testing.T) {
|
||||
func TestDisconnectInsertsOnlyLifecycleEvent(t *testing.T) {
|
||||
t.Parallel()
|
||||
require := require.New(t)
|
||||
|
||||
@@ -277,44 +225,31 @@ func TestDisconnectInsertsModuleLeaderRecomputeEvent(t *testing.T) {
|
||||
})
|
||||
|
||||
require.NoError(err)
|
||||
require.Equal([]string{"leader_election", "delete", "leader_election"}, backendRepo.calls,
|
||||
"the leader must be derived from the stored instances before and after the disconnect")
|
||||
require.Equal([]string{
|
||||
"module_lifecycle_" + testModuleId,
|
||||
"module_leader_" + testModuleId,
|
||||
}, eventKeys(events), "the disconnected event and the leader recompute must both stay in the queue")
|
||||
|
||||
recompute := requireRecompute(t, events, testModuleId)
|
||||
require.Equal(entity.ModuleLeaderReasonDisconnect, recompute.Reason)
|
||||
require.Equal(leaderAddress, recompute.PreviousLeader)
|
||||
require.Equal(followerAddress, recompute.Leader, "leadership moved to the surviving instance")
|
||||
require.Equal([]string{"delete"}, backendRepo.calls,
|
||||
"the disconnect path elects nobody")
|
||||
require.Equal([]string{"module_lifecycle_" + testModuleId}, eventKeys(events),
|
||||
"one lifecycle event per disconnect, no dedicated leader event")
|
||||
}
|
||||
|
||||
func TestClearPhantomBackendsInsertsModuleLeaderRecomputeEvent(t *testing.T) {
|
||||
func TestClearPhantomBackendsInsertsOneLifecycleEventPerModule(t *testing.T) {
|
||||
t.Parallel()
|
||||
require := require.New(t)
|
||||
|
||||
events := &eventRepoSpy{}
|
||||
backendRepo := newBackendRepoSpy(electedInstance(leaderConnId, leaderAddress))
|
||||
backendRepo := newBackendRepoSpy(
|
||||
electedInstance(leaderConnId, leaderAddress),
|
||||
electedInstance(followerConnId, followerAddress),
|
||||
)
|
||||
service := backend.NewBackend(backendRepo, events, testNodeId, &etp.Rooms{}, &loggerSpy{})
|
||||
|
||||
deleted, err := service.ClearPhantomBackends(t.Context())
|
||||
|
||||
require.NoError(err)
|
||||
require.Equal(1, deleted)
|
||||
require.Equal([]string{"own_node", "leader_election", "delete", "leader_election"}, backendRepo.calls,
|
||||
"the leader must be derived from the stored instances before and after the phantom cleanup")
|
||||
require.Equal([]string{
|
||||
"module_lifecycle_" + testModuleId,
|
||||
"module_leader_" + testModuleId,
|
||||
}, eventKeys(events), "the disconnected event and the leader recompute must both stay in the queue")
|
||||
|
||||
recompute := requireRecompute(t, events, testModuleId)
|
||||
require.Equal(testModuleId, recompute.ModuleId)
|
||||
require.Equal(testModuleName, recompute.ModuleName)
|
||||
require.Equal(entity.ModuleLeaderReasonDisconnect, recompute.Reason)
|
||||
require.Equal(leaderAddress, recompute.PreviousLeader)
|
||||
require.Empty(recompute.Leader, "with no instances left the module has no leader")
|
||||
require.Equal(2, deleted)
|
||||
require.Equal([]string{"own_node", "delete"}, backendRepo.calls,
|
||||
"the cleanup deletes and announces, it elects nobody")
|
||||
require.Equal([]string{"module_lifecycle_" + testModuleId}, eventKeys(events),
|
||||
"the instances of one module are announced once")
|
||||
}
|
||||
|
||||
func TestDeleteOwnBackendsInsertsNoEvents(t *testing.T) {
|
||||
@@ -326,7 +261,7 @@ func TestDeleteOwnBackendsInsertsNoEvents(t *testing.T) {
|
||||
|
||||
service.DeleteOwnBackends(t.Context())
|
||||
|
||||
require.Empty(events.inserted, "graceful shutdown keeps its current behaviour: no leader recompute")
|
||||
require.Empty(events.inserted, "graceful shutdown inserts no events at all")
|
||||
}
|
||||
|
||||
func electedInstance(connId string, address string) entity.Backend {
|
||||
@@ -347,29 +282,3 @@ func eventKeys(events *eventRepoSpy) []string {
|
||||
|
||||
return keys
|
||||
}
|
||||
|
||||
// requireRecompute returns the single leader recompute the module produced, proving it has a compaction key
|
||||
// of its own next to the lifecycle event of the same module. Every case in this file uses one module, so the
|
||||
// module id is a parameter only to keep the assertions readable at the call site.
|
||||
// nolint:unparam
|
||||
func requireRecompute(
|
||||
t *testing.T,
|
||||
events *eventRepoSpy,
|
||||
moduleId string,
|
||||
) *entity.PayloadModuleLeaderRecompute {
|
||||
t.Helper()
|
||||
require := require.New(t)
|
||||
|
||||
lifecycleKey := "module_lifecycle_" + testModuleId
|
||||
recomputeKey := "module_leader_" + testModuleId
|
||||
require.NotEqual(lifecycleKey, recomputeKey)
|
||||
|
||||
found := events.byKey(recomputeKey)
|
||||
require.Len(found, 1, "the leader recompute must have its own compaction key")
|
||||
|
||||
recompute := found[0].Payload.Value.ModuleLeaderRecompute
|
||||
require.NotNil(recompute)
|
||||
require.Equal(testModuleId, recompute.ModuleId)
|
||||
|
||||
return recompute
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package subscription
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/txix-open/etp/v4"
|
||||
|
||||
@@ -168,18 +169,6 @@ func (s Service) NotifyRoutingChanged(ctx context.Context) error {
|
||||
return s.notifyRoutingChanged(ctx, cluster.ConfigSendRoutesChanged, conns)
|
||||
}
|
||||
|
||||
func (s Service) NotifyModuleLeaderRecompute(ctx context.Context, recompute entity.PayloadModuleLeaderRecompute) {
|
||||
if recompute.Leader == recompute.PreviousLeader {
|
||||
return
|
||||
}
|
||||
|
||||
s.logger.Info(ctx, "module leader changed",
|
||||
log.String("moduleName", recompute.ModuleName),
|
||||
log.String("previousLeaderAddress", recompute.PreviousLeader),
|
||||
log.String("newLeaderAddress", recompute.Leader),
|
||||
log.String("reason", recompute.Reason))
|
||||
}
|
||||
|
||||
func (s Service) notifyBackendsChanged(
|
||||
ctx context.Context,
|
||||
moduleId string,
|
||||
@@ -225,7 +214,7 @@ func (s Service) emitLeaderAddress(
|
||||
leaderAddress = election.Leader.Address
|
||||
}
|
||||
|
||||
s.logger.Debug(ctx, "module leader election narrows the address list",
|
||||
s.logger.Info(ctx, "module address list narrowed to the leader",
|
||||
log.String("moduleName", moduleName),
|
||||
log.String("leaderAddress", leaderAddress))
|
||||
|
||||
@@ -242,6 +231,7 @@ func (s Service) notifyRoutingChanged(ctx context.Context, event string, conns [
|
||||
}
|
||||
|
||||
elections := leader.DeriveByModule(backends)
|
||||
moduleLeaders := make([]string, 0, len(elections))
|
||||
|
||||
routingConfig := cluster.RoutingConfig{}
|
||||
for _, backend := range backends {
|
||||
@@ -256,9 +246,7 @@ func (s Service) notifyRoutingChanged(ctx context.Context, event string, conns [
|
||||
}
|
||||
|
||||
if election.HasElection {
|
||||
s.logger.Debug(ctx, "module leader election narrows the routing map",
|
||||
log.String("moduleName", backend.ModuleName),
|
||||
log.String("leaderAddress", backend.Address))
|
||||
moduleLeaders = append(moduleLeaders, backend.ModuleName+"="+backend.Address)
|
||||
}
|
||||
|
||||
declaration := cluster.BackendDeclaration{
|
||||
@@ -276,6 +264,12 @@ func (s Service) notifyRoutingChanged(ctx context.Context, event string, conns [
|
||||
}
|
||||
routingConfig = append(routingConfig, declaration)
|
||||
}
|
||||
|
||||
if len(moduleLeaders) > 0 {
|
||||
s.logger.Info(ctx, "routing map publishes module leaders",
|
||||
log.String("moduleLeaders", strings.Join(moduleLeaders, ",")))
|
||||
}
|
||||
|
||||
data, err := json.Marshal(routingConfig)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "marshal routing config")
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/txix-open/etp/v4"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
@@ -16,8 +17,12 @@ const (
|
||||
testModuleId = "test-module-id"
|
||||
testModuleName = "test-module"
|
||||
|
||||
leaderConnId = "conn-1"
|
||||
followerConnId = "conn-2"
|
||||
|
||||
leaderAddress = "10.0.0.1:9000"
|
||||
successorAddress = "10.0.0.2:9000"
|
||||
plainAddress = "10.0.0.3:9000"
|
||||
)
|
||||
|
||||
type storedLog struct {
|
||||
@@ -49,27 +54,29 @@ func (l *loggerSpy) Debug(ctx context.Context, message any, fields ...log.Field)
|
||||
type moduleRepoSpy struct{}
|
||||
|
||||
func (r *moduleRepoSpy) GetByNames(ctx context.Context, names []string) ([]entity.Module, error) {
|
||||
return nil, nil
|
||||
return []entity.Module{{Id: testModuleId, Name: testModuleName}}, nil
|
||||
}
|
||||
|
||||
func (r *moduleRepoSpy) GetById(ctx context.Context, id string) (*entity.Module, error) {
|
||||
return &entity.Module{Id: testModuleId, Name: testModuleName}, nil
|
||||
}
|
||||
|
||||
type backendRepoSpy struct{}
|
||||
type backendRepoSpy struct {
|
||||
forLeaderElection []entity.Backend
|
||||
all []entity.Backend
|
||||
}
|
||||
|
||||
func (r *backendRepoSpy) GetForLeaderElection(ctx context.Context, moduleId string) ([]entity.Backend, error) {
|
||||
return nil, nil
|
||||
return r.forLeaderElection, nil
|
||||
}
|
||||
|
||||
func (r *backendRepoSpy) All(ctx context.Context) ([]entity.Backend, error) {
|
||||
return nil, nil
|
||||
return r.all, nil
|
||||
}
|
||||
|
||||
type configRepoSpy struct{}
|
||||
|
||||
func (r *configRepoSpy) GetActive(ctx context.Context, moduleId string) (*entity.Config, error) {
|
||||
// The leader recompute path never reads a configuration.
|
||||
return &entity.Config{ModuleId: moduleId}, nil
|
||||
}
|
||||
|
||||
@@ -83,121 +90,98 @@ type emitterSpy struct{}
|
||||
|
||||
func (e *emitterSpy) Emit(ctx context.Context, conn *etp.Conn, event string, data []byte) {}
|
||||
|
||||
func TestNotifyModuleLeaderRecomputeLogsLeaderChange(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
recompute entity.PayloadModuleLeaderRecompute
|
||||
expected *storedLog
|
||||
name string
|
||||
}{
|
||||
{
|
||||
name: "the leader moved to the successor",
|
||||
recompute: entity.PayloadModuleLeaderRecompute{
|
||||
ModuleId: testModuleId,
|
||||
ModuleName: testModuleName,
|
||||
Reason: entity.ModuleLeaderReasonDisconnect,
|
||||
PreviousLeader: leaderAddress,
|
||||
Leader: successorAddress,
|
||||
},
|
||||
expected: &storedLog{
|
||||
message: "module leader changed",
|
||||
fields: map[string]string{
|
||||
"moduleName": testModuleName,
|
||||
"previousLeaderAddress": leaderAddress,
|
||||
"newLeaderAddress": successorAddress,
|
||||
"reason": entity.ModuleLeaderReasonDisconnect,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "the last leader is gone",
|
||||
recompute: entity.PayloadModuleLeaderRecompute{
|
||||
ModuleId: testModuleId,
|
||||
ModuleName: testModuleName,
|
||||
Reason: entity.ModuleLeaderReasonDisconnect,
|
||||
PreviousLeader: leaderAddress,
|
||||
Leader: "",
|
||||
},
|
||||
expected: &storedLog{
|
||||
message: "module leader changed",
|
||||
fields: map[string]string{
|
||||
"moduleName": testModuleName,
|
||||
"previousLeaderAddress": leaderAddress,
|
||||
"newLeaderAddress": "",
|
||||
"reason": entity.ModuleLeaderReasonDisconnect,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// The on-call engineer answers "who is accepting sessions of this module" from the log of the node that
|
||||
// emitted the address list: the same derivation the subscriber received, logged where it is published.
|
||||
func TestNotifyBackendsChangedLogsTheLeaderItPublishes(t *testing.T) {
|
||||
t.Parallel()
|
||||
require := require.New(t)
|
||||
|
||||
logger := &loggerSpy{}
|
||||
service := newService(logger)
|
||||
rooms := etp.NewServer().Rooms()
|
||||
rooms.Join(&etp.Conn{}, subscription.BackendsChangingRoom(testModuleName))
|
||||
service := newService(logger, rooms, &backendRepoSpy{
|
||||
forLeaderElection: []entity.Backend{
|
||||
electedInstance(leaderConnId, leaderAddress),
|
||||
electedInstance(followerConnId, successorAddress),
|
||||
},
|
||||
})
|
||||
|
||||
service.NotifyModuleLeaderRecompute(t.Context(), tt.recompute)
|
||||
err := service.NotifyBackendsChanged(t.Context(), testModuleId)
|
||||
|
||||
require.NoError(err)
|
||||
require.Len(logger.infos, 1)
|
||||
require.Equal(tt.expected.message, logger.infos[0].message)
|
||||
require.Equal(tt.expected.fields, logger.infos[0].fields)
|
||||
})
|
||||
}
|
||||
require.Equal("module address list narrowed to the leader", logger.infos[0].message)
|
||||
require.Equal(testModuleName, logger.infos[0].fields["moduleName"])
|
||||
require.Equal(leaderAddress, logger.infos[0].fields["leaderAddress"],
|
||||
"the logged leader is the oldest elected instance, the one the subscriber received")
|
||||
}
|
||||
|
||||
// Nothing the module leader recompute describes as a leader change means no log: the queue carries an event
|
||||
// for every connect and disconnect, and most of them leave the leader where it was.
|
||||
func TestNotifyModuleLeaderRecomputeSkipsUnchangedLeader(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
recompute entity.PayloadModuleLeaderRecompute
|
||||
name string
|
||||
}{
|
||||
{
|
||||
name: "the leader is the same instance",
|
||||
recompute: entity.PayloadModuleLeaderRecompute{
|
||||
ModuleId: testModuleId,
|
||||
ModuleName: testModuleName,
|
||||
Reason: entity.ModuleLeaderReasonReady,
|
||||
PreviousLeader: leaderAddress,
|
||||
Leader: leaderAddress,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "the module has no leader at all",
|
||||
recompute: entity.PayloadModuleLeaderRecompute{
|
||||
ModuleId: testModuleId,
|
||||
ModuleName: testModuleName,
|
||||
Reason: entity.ModuleLeaderReasonReady,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
func TestNotifyRoutingChangedLogsPublishedLeaders(t *testing.T) {
|
||||
t.Parallel()
|
||||
require := require.New(t)
|
||||
|
||||
logger := &loggerSpy{}
|
||||
service := newService(logger)
|
||||
|
||||
service.NotifyModuleLeaderRecompute(t.Context(), tt.recompute)
|
||||
|
||||
require.Empty(logger.infos, "an event assembled without a leader change must not log")
|
||||
rooms := etp.NewServer().Rooms()
|
||||
rooms.Join(&etp.Conn{}, subscription.RoutingChangingRoom())
|
||||
service := newService(logger, rooms, &backendRepoSpy{
|
||||
all: []entity.Backend{
|
||||
electedInstance(leaderConnId, leaderAddress),
|
||||
electedInstance(followerConnId, successorAddress),
|
||||
plainInstance("conn-3", plainAddress),
|
||||
},
|
||||
})
|
||||
|
||||
err := service.NotifyRoutingChanged(t.Context())
|
||||
|
||||
require.NoError(err)
|
||||
require.Len(logger.infos, 1, "one summary line per routing rebuild")
|
||||
require.Equal("routing map publishes module leaders", logger.infos[0].message)
|
||||
require.Equal(testModuleName+"="+leaderAddress, logger.infos[0].fields["moduleLeaders"],
|
||||
"only the elected module and only its leader are published, the plain module is not listed")
|
||||
}
|
||||
|
||||
func TestNotifyRoutingChangedWithoutElectionLogsNothing(t *testing.T) {
|
||||
t.Parallel()
|
||||
require := require.New(t)
|
||||
|
||||
logger := &loggerSpy{}
|
||||
rooms := etp.NewServer().Rooms()
|
||||
rooms.Join(&etp.Conn{}, subscription.RoutingChangingRoom())
|
||||
service := newService(logger, rooms, &backendRepoSpy{
|
||||
all: []entity.Backend{plainInstance("conn-3", plainAddress)},
|
||||
})
|
||||
|
||||
err := service.NotifyRoutingChanged(t.Context())
|
||||
|
||||
require.NoError(err)
|
||||
require.Empty(logger.infos, "modules without election keep the previous behaviour, including the log")
|
||||
}
|
||||
|
||||
func electedInstance(connId string, address string) entity.Backend {
|
||||
return entity.Backend{
|
||||
WsConnectionId: connId,
|
||||
ModuleId: testModuleId,
|
||||
ModuleName: testModuleName,
|
||||
Address: address,
|
||||
ModuleLeaderMode: cluster.ModuleLeaderModeRequestElection,
|
||||
}
|
||||
}
|
||||
|
||||
func newService(logger log.Logger) subscription.Service {
|
||||
func plainInstance(connId string, address string) entity.Backend {
|
||||
return entity.Backend{
|
||||
WsConnectionId: connId,
|
||||
ModuleId: "plain-module-id",
|
||||
ModuleName: "plain-module",
|
||||
Address: address,
|
||||
}
|
||||
}
|
||||
|
||||
func newService(logger log.Logger, rooms *etp.Rooms, backendRepo subscription.BackendRepo) subscription.Service {
|
||||
return subscription.NewService(
|
||||
&moduleRepoSpy{},
|
||||
&backendRepoSpy{},
|
||||
backendRepo,
|
||||
&configRepoSpy{},
|
||||
&etp.Rooms{},
|
||||
rooms,
|
||||
&emitterSpy{},
|
||||
&variableServiceSpy{},
|
||||
logger,
|
||||
|
||||
@@ -1,105 +0,0 @@
|
||||
package tests_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"isp-config-service/entity"
|
||||
"isp-config-service/service/rqlite/db"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
)
|
||||
|
||||
const (
|
||||
recomputeModule = "leaderrecompute"
|
||||
recomputeHost = "10.2.9.21"
|
||||
)
|
||||
|
||||
// nolint:tagliatelle
|
||||
type recomputeTotalRow struct {
|
||||
Total int `json:"total"`
|
||||
}
|
||||
|
||||
// nolint:tagliatelle
|
||||
type recomputeModuleRow struct {
|
||||
Id string `json:"id"`
|
||||
}
|
||||
|
||||
//nolint:paralleltest
|
||||
func TestModuleLeaderRecomputeEventsInQueue(t *testing.T) {
|
||||
require, logger, testDb := setupTestApp(t)
|
||||
|
||||
instance := startModuleInstance(t, recomputeModule, recomputeHost, cluster.ModuleLeaderModeRequestElection, logger)
|
||||
|
||||
moduleId := requireRecomputeModuleId(t, testDb, recomputeModule)
|
||||
|
||||
require.Eventually(func() bool {
|
||||
return countLeaderRecomputeEvents(t, testDb, moduleId) == 1
|
||||
}, announceTimeout, announceTick, "a connected instance must add exactly one leader recompute event")
|
||||
require.Equal(1, countLeaderRecomputeEventsByReason(t, testDb, moduleId, entity.ModuleLeaderReasonReady))
|
||||
|
||||
instance.disconnect(t)
|
||||
|
||||
require.Eventually(func() bool {
|
||||
return countLeaderRecomputeEvents(t, testDb, moduleId) == 2
|
||||
}, announceTimeout, announceTick, "a disconnected instance must add exactly one leader recompute event")
|
||||
require.Equal(1, countLeaderRecomputeEventsByReason(t, testDb, moduleId, entity.ModuleLeaderReasonDisconnect))
|
||||
}
|
||||
|
||||
func requireRecomputeModuleId(t *testing.T, testDb db.DB, moduleName string) string {
|
||||
t.Helper()
|
||||
require := require.New(t)
|
||||
|
||||
var row recomputeModuleRow
|
||||
require.Eventually(func() bool {
|
||||
found := recomputeModuleRow{}
|
||||
err := testDb.SelectRow(t.Context(), &found, `
|
||||
select id
|
||||
from isp_config_service__module
|
||||
where name = ?`, moduleName)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
row = found
|
||||
return row.Id != ""
|
||||
}, announceTimeout, announceTick, "module %s must be registered", moduleName)
|
||||
|
||||
return row.Id
|
||||
}
|
||||
|
||||
func countLeaderRecomputeEvents(t *testing.T, testDb db.DB, moduleId string) int {
|
||||
t.Helper()
|
||||
require := require.New(t)
|
||||
|
||||
row := recomputeTotalRow{}
|
||||
err := testDb.SelectRow(t.Context(), &row, `
|
||||
select count(*) as total
|
||||
from isp_config_service__event
|
||||
where cast(payload as text) like ?
|
||||
and cast(payload as text) like ?`,
|
||||
"%moduleLeaderRecompute%", moduleIdLikePattern(moduleId))
|
||||
require.NoError(err)
|
||||
|
||||
return row.Total
|
||||
}
|
||||
|
||||
func countLeaderRecomputeEventsByReason(t *testing.T, testDb db.DB, moduleId string, reason string) int {
|
||||
t.Helper()
|
||||
require := require.New(t)
|
||||
|
||||
row := recomputeTotalRow{}
|
||||
err := testDb.SelectRow(t.Context(), &row, `
|
||||
select count(*) as total
|
||||
from isp_config_service__event
|
||||
where cast(payload as text) like ?
|
||||
and cast(payload as text) like ?
|
||||
and cast(payload as text) like ?`,
|
||||
"%moduleLeaderRecompute%", moduleIdLikePattern(moduleId), "%\"reason\":\""+reason+"\"%")
|
||||
require.NoError(err)
|
||||
|
||||
return row.Total
|
||||
}
|
||||
|
||||
func moduleIdLikePattern(moduleId string) string {
|
||||
return "%\"moduleId\":\"" + moduleId + "\"%"
|
||||
}
|
||||
Reference in new issue
Block a user