Added a backfill in 7-day windows, and fetches now keep their data on a failure
Backfilling a long window (an early --since, or a long time offline) hit the API's rate limit, which could still be exceeded after waiting once, and then everything fetched so far was lost. Before each Find a Tender source's worker starts, a start point more than 7 days ago is now backfilled in 7-day windows bounded on both sides, oldest first, each saved before the next is fetched. A window that fails is saved as far as it got and fetched again from its start after the source's interval. The worker then carries on from the end of the last window. A 429 is now waited out up to sources.<source>.rate_limit_retries times (default 5) rather than once; fts-once --ignore-rate-limit uses 0. FetchAll returns what it fetched before an error along with it, and the workers save it, so a failed run no longer loses its data. findatender's FetchAll and FetchOnce take RequestOptions, which gains Until (updatedTo), and RateLimitRetries replaces AllowRateLimit.
This commit is contained in:
1 parent
ff2aa316b5
commit
c09c30ae71
16 files changed
+683
-149
No files matched your search
@@ -0,0 +1,90 @@
|
||||
package fetcher
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"git.avsdev.uk/Go/job-search/internal/types"
|
||||
"git.avsdev.uk/Go/job-search/internal/util"
|
||||
)
|
||||
|
||||
// backfillChunk is the longest window a backfill fetches at once (the user's
|
||||
// choice: fixed, not a setting).
|
||||
const backfillChunk = 7 * 24 * time.Hour
|
||||
|
||||
// fetchWindowFunc fetches the opportunities a source updated from since up
|
||||
// to until; a zero until means no bound. If it fails partway, it returns
|
||||
// what it fetched before the error along with it.
|
||||
type fetchWindowFunc func(
|
||||
ctx context.Context, since, until time.Time,
|
||||
) ([]*types.Opportunity, error)
|
||||
|
||||
// backfill catches a source up from since, before its worker starts, so a
|
||||
// long window (an early --since, or a long time offline) isn't fetched in
|
||||
// one go. It fetches backfillChunk windows, bounded on both sides, oldest
|
||||
// first, saving each before fetching the next, until less than a window is
|
||||
// left before now. It returns where the worker carries on from: since when
|
||||
// it is zero (the client picks) or within backfillChunk of now.
|
||||
//
|
||||
// A window that fails is saved as far as it got, and fetched again from its
|
||||
// start after interval, until it succeeds or ctx is cancelled. Cancelling
|
||||
// ctx returns the start of the window it stopped in.
|
||||
//
|
||||
// logger is given untagged, as to the workers (see Fetcher.Run); source is
|
||||
// the source's name, for the backfill's own lines.
|
||||
func backfill(
|
||||
ctx context.Context,
|
||||
logger *slog.Logger,
|
||||
source string,
|
||||
interval time.Duration,
|
||||
fetch fetchWindowFunc,
|
||||
save saveFunc,
|
||||
since time.Time,
|
||||
) time.Time {
|
||||
backfillLogger := tagged(logger).With("source", source)
|
||||
|
||||
for !since.IsZero() && time.Since(since) > backfillChunk {
|
||||
until := since.Add(backfillChunk)
|
||||
backfillLogger.Info("backfilling", "since", since, "until", until)
|
||||
|
||||
opportunities, err := fetch(ctx, since, until)
|
||||
err = saveFetched(ctx, logger, save, opportunities, err)
|
||||
switch {
|
||||
case err == nil || errors.Is(err, util.ErrWorkerNoWork):
|
||||
since = until
|
||||
case ctx.Err() != nil:
|
||||
return since
|
||||
default:
|
||||
backfillLogger.Error(
|
||||
"backfill window failed, retrying",
|
||||
"since", since,
|
||||
"until", until,
|
||||
"error", err,
|
||||
"retry_in", interval,
|
||||
)
|
||||
if sleep(ctx, false, interval) != nil {
|
||||
return since
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return since
|
||||
}
|
||||
|
||||
// saveFetched saves what a fetch returned, even when it failed partway, so
|
||||
// nothing fetched is lost. It returns fetchErr, joined with save's error if
|
||||
// that failed too.
|
||||
func saveFetched(
|
||||
ctx context.Context,
|
||||
logger *slog.Logger,
|
||||
save saveFunc,
|
||||
opportunities []*types.Opportunity,
|
||||
fetchErr error,
|
||||
) error {
|
||||
if len(opportunities) == 0 {
|
||||
return fetchErr
|
||||
}
|
||||
return errors.Join(fetchErr, save(ctx, logger, opportunities))
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
package fetcher
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.avsdev.uk/Go/job-search/internal/config"
|
||||
"git.avsdev.uk/Go/job-search/internal/types"
|
||||
)
|
||||
|
||||
var errTestFetch = errors.New("test fetch failed")
|
||||
|
||||
// span describes the window from since to until, for comparing windows.
|
||||
func span(since, until time.Time) string {
|
||||
return since.Format(time.RFC3339) + "/" + until.Format(time.RFC3339)
|
||||
}
|
||||
|
||||
// recorder is a fake source for backfill: it records the windows fetched
|
||||
// and the saves, in order, in calls.
|
||||
type recorder struct {
|
||||
mu sync.Mutex
|
||||
calls []string
|
||||
windows []string
|
||||
saved int
|
||||
// fail returns the error for the nth fetch (from 1), if any.
|
||||
fail func(n int) error
|
||||
}
|
||||
|
||||
func (r *recorder) fetch(
|
||||
ctx context.Context, since, until time.Time,
|
||||
) ([]*types.Opportunity, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.windows = append(r.windows, span(since, until))
|
||||
r.calls = append(r.calls, "fetch")
|
||||
var err error
|
||||
if r.fail != nil {
|
||||
err = r.fail(len(r.windows))
|
||||
}
|
||||
opportunity := &types.Opportunity{
|
||||
UUID: "ocds-1",
|
||||
}
|
||||
return []*types.Opportunity{opportunity}, err
|
||||
}
|
||||
|
||||
func (r *recorder) save(
|
||||
ctx context.Context, logger *slog.Logger, opportunities []*types.Opportunity,
|
||||
) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.saved += len(opportunities)
|
||||
r.calls = append(r.calls, "save")
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestBackfillWindows(t *testing.T) {
|
||||
since := time.Now().Add(-20 * 24 * time.Hour)
|
||||
r := &recorder{}
|
||||
|
||||
got := backfill(
|
||||
context.Background(),
|
||||
slog.Default(),
|
||||
"Test",
|
||||
time.Millisecond,
|
||||
r.fetch,
|
||||
r.save,
|
||||
since,
|
||||
)
|
||||
|
||||
second := since.Add(backfillChunk)
|
||||
third := since.Add(2 * backfillChunk)
|
||||
want := []string{span(since, second), span(second, third)}
|
||||
if !slices.Equal(r.windows, want) {
|
||||
t.Errorf("windows = %v; want %v", r.windows, want)
|
||||
}
|
||||
if !got.Equal(third) {
|
||||
t.Errorf("backfill = %v; want the end of the last window", got)
|
||||
}
|
||||
// Each window is saved before the next is fetched.
|
||||
if calls := strings.Join(r.calls, ","); calls != "fetch,save,fetch,save" {
|
||||
t.Errorf("calls = %s", calls)
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing is backfilled for a zero since (the client picks) or one within a
|
||||
// window of now: the worker fetches it.
|
||||
func TestBackfillNothingToDo(t *testing.T) {
|
||||
for name, since := range map[string]time.Time{
|
||||
"zero": {},
|
||||
"recent": time.Now().Add(-3 * 24 * time.Hour),
|
||||
"future": time.Now().Add(time.Hour),
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
r := &recorder{}
|
||||
got := backfill(
|
||||
context.Background(),
|
||||
slog.Default(),
|
||||
"Test",
|
||||
time.Millisecond,
|
||||
r.fetch,
|
||||
r.save,
|
||||
since,
|
||||
)
|
||||
if !got.Equal(since) || len(r.windows) != 0 {
|
||||
t.Errorf(
|
||||
"backfill = %v after %d fetches; want %v and none",
|
||||
got, len(r.windows), since,
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A failed window is saved as far as it got and fetched again from its
|
||||
// start; finding nothing moves on like a success.
|
||||
func TestBackfillRetriesFailedWindow(t *testing.T) {
|
||||
since := time.Now().Add(-15 * 24 * time.Hour)
|
||||
r := &recorder{
|
||||
fail: func(n int) error {
|
||||
switch n {
|
||||
case 1, 2:
|
||||
return errTestFetch
|
||||
case 3:
|
||||
return ErrNoNewReleases
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
got := backfill(
|
||||
context.Background(),
|
||||
slog.Default(),
|
||||
"Test",
|
||||
time.Millisecond,
|
||||
r.fetch,
|
||||
r.save,
|
||||
since,
|
||||
)
|
||||
|
||||
second := since.Add(backfillChunk)
|
||||
third := since.Add(2 * backfillChunk)
|
||||
first := span(since, second)
|
||||
want := []string{first, first, first, span(second, third)}
|
||||
if !slices.Equal(r.windows, want) {
|
||||
t.Errorf("windows = %v; want %v", r.windows, want)
|
||||
}
|
||||
if r.saved != 4 {
|
||||
t.Errorf("saved %d opportunities; want 4 (failed windows too)", r.saved)
|
||||
}
|
||||
if !got.Equal(third) {
|
||||
t.Errorf("backfill = %v; want %v", got, third)
|
||||
}
|
||||
}
|
||||
|
||||
// Cancelling stops the backfill during its wait, returning the start of the
|
||||
// window it stopped in.
|
||||
func TestBackfillCancelled(t *testing.T) {
|
||||
since := time.Now().Add(-15 * 24 * time.Hour)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
r := &recorder{
|
||||
fail: func(n int) error {
|
||||
cancel()
|
||||
return errTestFetch
|
||||
},
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
got := backfill(
|
||||
ctx, slog.Default(), "Test", time.Hour, r.fetch, r.save, since,
|
||||
)
|
||||
|
||||
if time.Since(start) > 5*time.Second {
|
||||
t.Error("cancelling did not stop the wait")
|
||||
}
|
||||
if !got.Equal(since) || len(r.windows) != 1 {
|
||||
t.Errorf(
|
||||
"backfill = %v after %d fetches; want %v after 1",
|
||||
got, len(r.windows), since,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveFetched(t *testing.T) {
|
||||
r := &recorder{}
|
||||
partial := []*types.Opportunity{
|
||||
{
|
||||
UUID: "ocds-1",
|
||||
},
|
||||
}
|
||||
|
||||
err := saveFetched(
|
||||
context.Background(), slog.Default(), r.save, partial, errTestFetch,
|
||||
)
|
||||
if !errors.Is(err, errTestFetch) || r.saved != 1 {
|
||||
t.Errorf(
|
||||
"partial: err = %v, saved %d; want the fetch error, 1", err, r.saved,
|
||||
)
|
||||
}
|
||||
|
||||
err = saveFetched(
|
||||
context.Background(), slog.Default(), r.save, nil, ErrNoNewReleases,
|
||||
)
|
||||
if !errors.Is(err, ErrNoNewReleases) || r.saved != 1 {
|
||||
t.Errorf(
|
||||
"nothing: err = %v, saved %d; want ErrNoNewReleases, 1", err, r.saved,
|
||||
)
|
||||
}
|
||||
|
||||
failing := func(context.Context, *slog.Logger, []*types.Opportunity) error {
|
||||
return errTestFetch
|
||||
}
|
||||
err = saveFetched(context.Background(), slog.Default(), failing, partial, nil)
|
||||
if !errors.Is(err, errTestFetch) {
|
||||
t.Errorf("failed save: err = %v; want the save's error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Run backfills each Find a Tender source in windows bounded on both sides,
|
||||
// then its worker fetches the rest with no upper bound.
|
||||
func TestRunBackfills(t *testing.T) {
|
||||
for _, source := range []string{"FindATender", "FTSMock"} {
|
||||
t.Run(source, func(t *testing.T) {
|
||||
var (
|
||||
mu sync.Mutex
|
||||
until []string
|
||||
)
|
||||
srv := httptest.NewServer(
|
||||
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
until = append(until, r.URL.Query().Get("updatedTo"))
|
||||
mu.Unlock()
|
||||
io.WriteString(w, emptyPackage)
|
||||
}),
|
||||
)
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
sources := &config.JSCSources{}
|
||||
if source == "FindATender" {
|
||||
sources.FindATender.Enabled = true
|
||||
sources.FindATender.Interval = time.Hour
|
||||
sources.FindATender.APIRoot = srv.URL
|
||||
} else {
|
||||
sources.FTSMock.Enabled = true
|
||||
sources.FTSMock.Interval = time.Hour
|
||||
sources.FTSMock.APIRoot = srv.URL
|
||||
}
|
||||
|
||||
since := time.Now().UTC().Add(-15 * 24 * time.Hour)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- New(sources).Run(ctx, since)
|
||||
}()
|
||||
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for {
|
||||
mu.Lock()
|
||||
n := len(until)
|
||||
mu.Unlock()
|
||||
if n >= 3 || time.Now().After(deadline) {
|
||||
break
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
cancel()
|
||||
if err := <-done; err != nil {
|
||||
t.Fatalf("Run = %v", err)
|
||||
}
|
||||
|
||||
const layout = "2006-01-02T15:04:05"
|
||||
want := []string{
|
||||
since.Add(backfillChunk).Format(layout),
|
||||
since.Add(2 * backfillChunk).Format(layout),
|
||||
"",
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if !slices.Equal(until, want) {
|
||||
t.Errorf("updatedTo of each request = %q; want %q", until, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -77,7 +77,7 @@ var fetchers = map[string]fetchFunc{
|
||||
conf := &config.JSCSourceFindATender{
|
||||
APIRoot: apiRoot,
|
||||
}
|
||||
return fetchFindATender(ctx, slog.Default(), conf, since)
|
||||
return fetchFindATender(ctx, slog.Default(), conf, since, time.Time{})
|
||||
},
|
||||
"FTSMock": func(
|
||||
ctx context.Context, apiRoot string, since time.Time,
|
||||
@@ -85,7 +85,7 @@ var fetchers = map[string]fetchFunc{
|
||||
conf := &config.JSCSourceFTSMock{
|
||||
APIRoot: apiRoot,
|
||||
}
|
||||
return fetchFTSMock(ctx, slog.Default(), conf, since)
|
||||
return fetchFTSMock(ctx, slog.Default(), conf, since, time.Time{})
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,8 @@ import (
|
||||
const findATenderSource = "FindATender"
|
||||
|
||||
// runFindATender polls Find a Tender every configured interval until ctx
|
||||
// is cancelled, passing what each run fetches to save.
|
||||
// is cancelled, passing what each run fetches to save, even when the run
|
||||
// fails partway. A long window is backfilled first (see backfill).
|
||||
func runFindATender(
|
||||
ctx context.Context,
|
||||
logger *slog.Logger,
|
||||
@@ -29,29 +30,43 @@ func runFindATender(
|
||||
return errors.New("fetcher: sources.find_a_tender.api_root is not set")
|
||||
}
|
||||
|
||||
fetch := func(
|
||||
ctx context.Context, since, until time.Time,
|
||||
) ([]*types.Opportunity, error) {
|
||||
return fetchFindATender(ctx, logger, conf, since, until)
|
||||
}
|
||||
|
||||
since = backfill(
|
||||
ctx,
|
||||
logger,
|
||||
findATenderSource,
|
||||
conf.Interval,
|
||||
fetch,
|
||||
save,
|
||||
since,
|
||||
)
|
||||
|
||||
worker := util.Worker{
|
||||
Logger: tagged(logger),
|
||||
Name: findATenderSource,
|
||||
Interval: conf.Interval,
|
||||
Task: func(ctx context.Context, since time.Time) error {
|
||||
opportunities, err := fetchFindATender(ctx, logger, conf, since)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return save(ctx, logger, opportunities)
|
||||
opportunities, err := fetch(ctx, since, time.Time{})
|
||||
return saveFetched(ctx, logger, save, opportunities, err)
|
||||
},
|
||||
}
|
||||
return worker.Run(ctx, since)
|
||||
}
|
||||
|
||||
// fetchFindATender fetches everything updated since since from Find a
|
||||
// Tender. Finding nothing returns ErrNoNewReleases, so the worker still moves
|
||||
// its checkpoint on.
|
||||
// fetchFindATender fetches everything updated from since up to until (zero:
|
||||
// no bound) from Find a Tender. If it fails partway, what it fetched before
|
||||
// the error is returned along with it. Finding nothing returns
|
||||
// ErrNoNewReleases, so the worker still moves its checkpoint on.
|
||||
func fetchFindATender(
|
||||
ctx context.Context,
|
||||
logger *slog.Logger,
|
||||
conf *config.JSCSourceFindATender,
|
||||
since time.Time,
|
||||
since, until time.Time,
|
||||
) ([]*types.Opportunity, error) {
|
||||
opportunities, err := util.AwaitTask(
|
||||
ctx,
|
||||
@@ -60,17 +75,18 @@ func fetchFindATender(
|
||||
conf.APIRoot, findatender.WithLogger(logger),
|
||||
)
|
||||
defer findATender.Shutdown()
|
||||
return findATender.With(ctx).FetchAll(since, true)
|
||||
return findATender.With(ctx).FetchAll(findatender.RequestOptions{
|
||||
Since: since,
|
||||
Until: until,
|
||||
RateLimitRetries: conf.RateLimitRetries,
|
||||
})
|
||||
},
|
||||
)
|
||||
if errors.Is(err, findatender.ErrNoReleases) {
|
||||
return nil, ErrNoNewReleases
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tagged(logger).Info("fetched opportunities", "count", len(opportunities))
|
||||
|
||||
return opportunities, nil
|
||||
return opportunities, err
|
||||
}
|
||||
@@ -16,7 +16,7 @@ import (
|
||||
const ftsMockSource = "FTSMock"
|
||||
|
||||
// runFTSMock polls the mock Find a Tender server every configured interval
|
||||
// until ctx is cancelled, passing what each run fetches to save.
|
||||
// until ctx is cancelled, as runFindATender polls Find a Tender.
|
||||
func runFTSMock(
|
||||
ctx context.Context,
|
||||
logger *slog.Logger,
|
||||
@@ -28,31 +28,44 @@ func runFTSMock(
|
||||
return errors.New("fetcher: sources.fts_mock.api_root is not set")
|
||||
}
|
||||
|
||||
fetch := func(
|
||||
ctx context.Context, since, until time.Time,
|
||||
) ([]*types.Opportunity, error) {
|
||||
return fetchFTSMock(ctx, logger, conf, since, until)
|
||||
}
|
||||
|
||||
since = backfill(
|
||||
ctx,
|
||||
logger,
|
||||
ftsMockSource,
|
||||
conf.Interval,
|
||||
fetch,
|
||||
save,
|
||||
since,
|
||||
)
|
||||
|
||||
worker := util.Worker{
|
||||
Logger: tagged(logger),
|
||||
Name: ftsMockSource,
|
||||
Interval: conf.Interval,
|
||||
Task: func(ctx context.Context, since time.Time) error {
|
||||
opportunities, err := fetchFTSMock(ctx, logger, conf, since)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return save(ctx, logger, opportunities)
|
||||
opportunities, err := fetch(ctx, since, time.Time{})
|
||||
return saveFetched(ctx, logger, save, opportunities, err)
|
||||
},
|
||||
}
|
||||
return worker.Run(ctx, since)
|
||||
}
|
||||
|
||||
// fetchFTSMock fetches everything updated since since from the mock Find a
|
||||
// Tender server. The mock serves the real API's format, so the converter
|
||||
// marks the opportunities as Find a Tender's; their Source is set to
|
||||
// ftsMockSource here instead. Finding nothing returns ErrNoNewReleases, so
|
||||
// the worker still moves its checkpoint on.
|
||||
// fetchFTSMock fetches everything updated from since up to until (zero: no
|
||||
// bound) from the mock Find a Tender server, as fetchFindATender does. The
|
||||
// mock serves the real API's format, so the converter marks the
|
||||
// opportunities as Find a Tender's; their Source is set to ftsMockSource here
|
||||
// instead.
|
||||
func fetchFTSMock(
|
||||
ctx context.Context,
|
||||
logger *slog.Logger,
|
||||
conf *config.JSCSourceFTSMock,
|
||||
since time.Time,
|
||||
since, until time.Time,
|
||||
) ([]*types.Opportunity, error) {
|
||||
opportunities, err := util.AwaitTask(
|
||||
ctx,
|
||||
@@ -61,15 +74,16 @@ func fetchFTSMock(
|
||||
conf.APIRoot, findatender.WithLogger(logger),
|
||||
)
|
||||
defer findATender.Shutdown()
|
||||
return findATender.With(ctx).FetchAll(since, true)
|
||||
return findATender.With(ctx).FetchAll(findatender.RequestOptions{
|
||||
Since: since,
|
||||
Until: until,
|
||||
RateLimitRetries: conf.RateLimitRetries,
|
||||
})
|
||||
},
|
||||
)
|
||||
if errors.Is(err, findatender.ErrNoReleases) {
|
||||
return nil, ErrNoNewReleases
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, opportunity := range opportunities {
|
||||
opportunity.Source = ftsMockSource
|
||||
@@ -77,5 +91,5 @@ func fetchFTSMock(
|
||||
|
||||
tagged(logger).Info("fetched opportunities", "count", len(opportunities))
|
||||
|
||||
return opportunities, nil
|
||||
return opportunities, err
|
||||
}
|
||||
Reference in new issue
Block a user