🐛 Stop stale entries without overwriting a concurrent stop

The auto-stop listed the running entries and later saved the whole stale
row, so a stop pushed by a client in between was overwritten and then
answered as stale. Each candidate is now loaded again inside its own
transaction and only saved while it is still running and not deleted.
The end of the day uses the timezone effective on the day of the entry,
and entries without a real day_key are skipped with a debug message
instead of an error every minute.
This commit is contained in:
2026-12-01 16:49:15 +01:00
parent 0bfacb7059
commit 2bcf2d69a1
2 changed files with 240 additions and 27 deletions
+66 -24
View File
@@ -1,53 +1,95 @@
package tracking
import (
"database/sql"
"errors"
"time"
"github.com/pocketbase/pocketbase/core"
)
// AutoStopStalled stops every running entry whose day lies before today in the
// timezone of its owner. The entry ends at 23:59:59.999 of its own day and is
// flagged as auto stopped. It returns the number of stopped entries. A single
// entry that cannot be saved is logged and skipped.
// timezone of its owner. The entry ends at 23:59:59.999 of its own day in the
// timezone effective on that day and is flagged as auto stopped. It returns the
// number of stopped entries. A single entry that cannot be saved is logged and
// skipped.
func AutoStopStalled(app core.App, now time.Time) (int, error) {
running, err := app.FindRecordsByFilter("entries", "deleted = false && end_time = 0", "start_time", 0, 0)
entries, err := stalledEntries(app, now)
if err != nil {
return 0, err
}
byOwner := map[string][]*core.Record{}
for _, entry := range running {
owner := entry.GetString("owner")
byOwner[owner] = append(byOwner[owner], entry)
}
stopped := 0
for owner, entries := range byOwner {
loc := location(app, owner, now.UTC().Format(dayKeyLayout))
today := now.In(loc).Format(dayKeyLayout)
for _, entry := range entries {
if entry.GetString("day_key") >= today {
continue
}
if stopAtEndOfDay(app, entry, loc, now) {
if stopStalled(app, entry.Id, now) {
stopped++
}
}
}
return stopped, nil
}
func stopAtEndOfDay(app core.App, entry *core.Record, loc *time.Location, now time.Time) bool {
endMs, err := endOfDayMs(entry.GetString("day_key"), loc)
if err == nil {
// stalledEntries lists the running entries whose day lies before today in the
// timezone of their owner. Entries whose day_key is not a real date are left
// out: they have no end of day and would otherwise be reported every minute.
func stalledEntries(app core.App, now time.Time) ([]*core.Record, error) {
running, err := app.FindRecordsByFilter("entries", "deleted = false && end_time = 0", "start_time", 0, 0)
if err != nil {
return nil, err
}
today := now.UTC().Format(dayKeyLayout)
locations := map[string]*time.Location{}
var stalled []*core.Record
for _, entry := range running {
dayKey := entry.GetString("day_key")
if !validDayKey(dayKey) {
app.Logger().Debug("auto-stop skipped entry without a real day_key", "id", entry.Id, "day_key", dayKey)
continue
}
owner := entry.GetString("owner")
loc, ok := locations[owner]
if !ok {
loc = location(app, owner, today)
locations[owner] = loc
}
if dayKey < now.In(loc).Format(dayKeyLayout) {
stalled = append(stalled, entry)
}
}
return stalled, nil
}
// stopStalled ends the entry id at the end of its day and reports whether it was
// stopped. The entry is loaded again inside the transaction so that a stop or a
// delete pushed by the client since the entry was listed is not overwritten.
func stopStalled(app core.App, id string, now time.Time) bool {
stopped := false
err := app.RunInTransaction(func(tx core.App) error {
entry, err := tx.FindRecordById("entries", id)
if errors.Is(err, sql.ErrNoRows) {
return nil
}
if err != nil {
return err
}
if entry.GetInt64("end_time") != 0 || entry.GetBool("deleted") {
return nil
}
dayKey := entry.GetString("day_key")
endMs, err := endOfDayMs(dayKey, location(tx, entry.GetString("owner"), dayKey))
if err != nil {
return err
}
entry.Set("end_time", endMs)
entry.Set("auto_stopped", true)
bump(entry, now)
err = app.Save(entry)
if err := tx.Save(entry); err != nil {
return err
}
stopped = true
return nil
})
if err != nil {
app.Logger().Error("auto-stop failed for entry", "id", entry.Id, "error", err)
app.Logger().Error("auto-stop failed for entry", "id", id, "error", err)
return false
}
return true
return stopped
}
+171
View File
@@ -1,12 +1,33 @@
package tracking
import (
"bytes"
"log/slog"
"strings"
"testing"
"time"
"github.com/pocketbase/pocketbase/core"
)
// loggedApp wraps an app so that a test can read what a call logged.
type loggedApp struct {
core.App
logs *bytes.Buffer
}
func (a loggedApp) Logger() *slog.Logger {
return slog.New(slog.NewTextHandler(a.logs, &slog.HandlerOptions{Level: slog.LevelDebug}))
}
func ids(records []*core.Record) string {
list := make([]string, len(records))
for i, r := range records {
list[i] = r.Id
}
return strings.Join(list, ",")
}
func zone(t testing.TB, name string) *time.Location {
t.Helper()
loc, err := time.LoadLocation(name)
@@ -119,6 +140,156 @@ func TestAutoStopStalledIgnoresDeletedAndInvalidEntries(t *testing.T) {
wantInt(t, got, "rev", 1)
}
func TestAutoStopStalledSkipsEntriesWithoutRealDayKey(t *testing.T) {
e := setup(t)
app := loggedApp{App: e.app, logs: &bytes.Buffer{}}
// The day key passes the collection pattern but is not a real date.
invalid := e.seed("entries", map[string]any{
"start_time": 1000, "end_time": 0, "auto_stopped": false, "note": "", "day_key": "2026-02-30",
})
stale := e.entry(dayTue, utc(dayTue, 8, 0), time.Time{})
listed, err := stalledEntries(app, testNow)
if err != nil {
t.Fatal(err)
}
if len(listed) != 1 || listed[0].Id != stale.Id {
t.Fatalf("listed %s, want only the stale entry %s", ids(listed), stale.Id)
}
stopped, err := AutoStopStalled(app, testNow)
if err != nil {
t.Fatal(err)
}
if stopped != 1 {
t.Fatalf("stopped %d entries, want 1", stopped)
}
got := e.load("entries", invalid.Id)
wantInt(t, got, "end_time", 0)
wantBool(t, got, "auto_stopped", false)
wantInt(t, got, "rev", 1)
// The skip is a debug message only: an error used to be logged every minute.
logs := app.logs.String()
if !strings.Contains(logs, "level=DEBUG") || !strings.Contains(logs, invalid.Id) {
t.Errorf("logs lack the debug message for %s:\n%s", invalid.Id, logs)
}
if strings.Contains(logs, "level=ERROR") {
t.Errorf("logs contain an error:\n%s", logs)
}
}
func TestAutoStopStalledEndsAtTheLocalEndOfDay(t *testing.T) {
e := setup(t)
berlin := zone(t, "Europe/Berlin")
e.settings("2026-01-01", 40, 31, "Europe/Berlin")
// The days of the DST transitions in Berlin: the night of 29 March loses
// an hour, the night of 25 October gains one.
spring := e.entry("2026-03-29", utc("2026-03-29", 8, 0), time.Time{})
autumn := e.entry("2026-10-25", utc("2026-10-25", 8, 0), time.Time{})
now := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)
stopped, err := AutoStopStalled(e.app, now)
if err != nil {
t.Fatalf("AutoStopStalled: %v", err)
}
if stopped != 2 {
t.Fatalf("stopped %d entries, want 2", stopped)
}
got := e.load("entries", spring.Id)
wantInt(t, got, "end_time", endOf("2026-03-29", berlin))
wantInt(t, got, "end_time", utc("2026-03-29", 21, 59).UnixMilli()+59_999) // CEST is UTC+2
wantBool(t, got, "auto_stopped", true)
got = e.load("entries", autumn.Id)
wantInt(t, got, "end_time", endOf("2026-10-25", berlin))
wantInt(t, got, "end_time", utc("2026-10-25", 22, 59).UnixMilli()+59_999) // CET is UTC+1 again
wantBool(t, got, "auto_stopped", true)
}
func TestAutoStopStalledUsesTimezoneOfTheEntryDay(t *testing.T) {
e := setup(t)
e.settings("2026-01-01", 40, 31, "Europe/Berlin")
e.settings("2026-06-01", 40, 31, "UTC")
// The owner switched to UTC in June: the entry of 31 May still ends at the
// end of the day in Berlin, the one of 1 June at the end of the day in UTC.
may := e.entry("2026-05-31", utc("2026-05-31", 8, 0), time.Time{})
june := e.entry("2026-06-01", utc("2026-06-01", 8, 0), time.Time{})
now := time.Date(2026, 6, 2, 12, 0, 0, 0, time.UTC)
stopped, err := AutoStopStalled(e.app, now)
if err != nil {
t.Fatalf("AutoStopStalled: %v", err)
}
if stopped != 2 {
t.Fatalf("stopped %d entries, want 2", stopped)
}
wantInt(t, e.load("entries", may.Id), "end_time", utc("2026-05-31", 21, 59).UnixMilli()+59_999)
wantInt(t, e.load("entries", june.Id), "end_time", utc("2026-06-01", 23, 59).UnixMilli()+59_999)
}
func TestStopStalledKeepsChangesMadeSinceListing(t *testing.T) {
e := setup(t)
// The client stops the entry after it was listed but before it is processed.
running := e.entry(dayTue, utc(dayTue, 8, 0), time.Time{})
listed, err := stalledEntries(e.app, testNow)
if err != nil || len(listed) != 1 {
t.Fatalf("stalledEntries listed %s, err %v", ids(listed), err)
}
client := e.load("entries", running.Id)
client.Set("end_time", utc(dayTue, 16, 30).UnixMilli())
client.Set("client_updated_at", 5)
client.Set("rev", 2)
if err := e.app.Save(client); err != nil {
t.Fatal(err)
}
if stopStalled(e.app, listed[0].Id, testNow) {
t.Error("the entry was reported as stopped although the client had stopped it")
}
got := e.load("entries", running.Id)
wantInt(t, got, "end_time", utc(dayTue, 16, 30).UnixMilli())
wantBool(t, got, "auto_stopped", false)
wantInt(t, got, "rev", 2)
wantInt(t, got, "client_updated_at", 5)
// A delete pushed in between is kept too.
running = e.entry(dayMon, utc(dayMon, 8, 0), time.Time{})
listed, err = stalledEntries(e.app, testNow)
if err != nil || len(listed) != 1 {
t.Fatalf("stalledEntries listed %s, err %v", ids(listed), err)
}
gone := e.load("entries", running.Id)
gone.Set("deleted", true)
gone.Set("rev", 2)
if err := e.app.Save(gone); err != nil {
t.Fatal(err)
}
if stopStalled(e.app, listed[0].Id, testNow) {
t.Error("a deleted entry was reported as stopped")
}
got = e.load("entries", running.Id)
wantBool(t, got, "deleted", true)
wantInt(t, got, "end_time", 0)
wantInt(t, got, "rev", 2)
// An entry that was removed from the server in between is not a failure either.
removed := e.entry("2026-05-04", utc("2026-05-04", 8, 0), time.Time{}) // the Monday before
listed, err = stalledEntries(e.app, testNow)
if err != nil || len(listed) != 1 {
t.Fatalf("stalledEntries listed %s, err %v", ids(listed), err)
}
if err := e.app.Delete(removed); err != nil {
t.Fatal(err)
}
app := loggedApp{App: e.app, logs: &bytes.Buffer{}}
if stopStalled(app, listed[0].Id, testNow) {
t.Error("a removed entry was reported as stopped")
}
if logs := app.logs.String(); strings.Contains(logs, "auto-stop failed") {
t.Errorf("removing the entry was logged as a failure:\n%s", logs)
}
}
func TestLocation(t *testing.T) {
e := setup(t)
e.settings("2026-01-01", 40, 31, "Europe/Berlin")