Fix agent last work update throttling (#4124)

This commit is contained in:
Lukas 2024-09-18 18:26:18 +02:00 committed by GitHub
parent 276b279b7f
commit f2060db5c0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 52 additions and 2 deletions

View file

@ -525,8 +525,8 @@ func (s *RPC) getHostnameFromContext(ctx context.Context) (string, error) {
}
func (s *RPC) updateAgentLastWork(agent *model.Agent) error {
// only update agent.LastWork if not done recently
if time.Unix(agent.LastWork, 0).Add(updateAgentLastWorkDelay).Before(time.Now()) {
// only update agent.LastWork if not recently updated
if time.Unix(agent.LastWork, 0).Add(updateAgentLastWorkDelay).After(time.Now()) {
return nil
}

View file

@ -17,9 +17,11 @@ package grpc
import (
"context"
"testing"
"time"
"github.com/franela/goblin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"google.golang.org/grpc/metadata"
"go.woodpecker-ci.org/woodpecker/v2/server/model"
@ -107,3 +109,51 @@ func TestRegisterAgent(t *testing.T) {
})
})
}
func TestUpdateAgentLastWork(t *testing.T) {
t.Run("When last work was never updated it should update last work timestamp", func(t *testing.T) {
agent := model.Agent{
LastWork: 0,
}
store := mocks_store.NewStore(t)
rpc := RPC{
store: store,
}
store.On("AgentUpdate", mock.Anything).Once().Return(nil)
err := rpc.updateAgentLastWork(&agent)
assert.NoError(t, err)
assert.NotZero(t, agent.LastWork)
})
t.Run("When last work was updated over a minute ago it should update last work timestamp", func(t *testing.T) {
lastWork := time.Now().Add(-time.Hour).Unix()
agent := model.Agent{
LastWork: lastWork,
}
store := mocks_store.NewStore(t)
rpc := RPC{
store: store,
}
store.On("AgentUpdate", mock.Anything).Once().Return(nil)
err := rpc.updateAgentLastWork(&agent)
assert.NoError(t, err)
assert.NotEqual(t, lastWork, agent.LastWork)
})
t.Run("When last work was updated in the last minute it should not update last work timestamp again", func(t *testing.T) {
lastWork := time.Now().Add(-time.Second * 30).Unix()
agent := model.Agent{
LastWork: lastWork,
}
rpc := RPC{}
err := rpc.updateAgentLastWork(&agent)
assert.NoError(t, err)
assert.Equal(t, lastWork, agent.LastWork)
})
}