Added CODE_CONVENTIONS.md and linters to enforce it, and applied it across the codebase
CODE_CONVENTIONS.md sets out the conventions for Go code in this repository: naming, layout, comments, errors, logging, configuration and tests. .golangci.json enables the linters that check the parts that can be checked (each limited to the rules the conventions use); the rest is applied by hand. Applied across the codebase: - Naming: full-word names in application code, initialisms in one case (BuyerID, PrintJSON, PrintYAML, ocdsGetBuyerID), no names shadowing built-ins (min/max are minGap/maxGap), mustRaw renamed rawJSON as it returns nil rather than panicking, and config.ConfigLevelToLogLevel renamed LevelToLogLevel. - Layout: lines kept to 80 characters where possible, assignments taken out of if and for statements that don't fit, wrapped arguments all on one line or one per line, steps separated by blank lines, no else after a return, function and struct literals wrapped. - Comments: doc comments on every exported name (including each section's Map, Flatten, TypeOf, ValueOf and SetValue), section banners, British spelling. - Errors: a created error starts with its package name, a wrapping error adds only what was being done, sentinels in one commented var block, errors.Is and errors.As in place of == and type assertions, and no err := shadowing of a named result. That fixes the mock server losing its access log's close error. - Logging: the fetcher passes its workers an untagged logger, so findatender's lines are tagged with their own component rather than with fetcher's as well; cmd/mock-fts logs "stopped" with slog. - Configuration: util.WithTimeout (moved from the websocket package) applies a timeout of 0 or less as no limit, used for the websocket write and ping, TCP close and tcpserver shutdown timeouts; every setting documents what 0 or empty means, including the rate limit rule's keys in internal/config/README.md. - Tests: related tests merged into table-driven ones with named cases. Separately from CODE_CONVENTIONS.md, internal/store/README.md gains a soft SQL style convention for the queries in internal/store/queries.go, and the queries are reformatted to follow it.
This commit is contained in:
1 parent
465358609a
commit
67215a6aaa
104 files changed
+3189
-1206
No files matched your search
@@ -79,33 +79,19 @@ func parseCatalog(data []byte, name string) (*Catalog, error) {
|
||||
func (c *Catalog) validate() error {
|
||||
var errs []error
|
||||
|
||||
for _, pool := range []struct {
|
||||
name string
|
||||
n int
|
||||
pools := []struct {
|
||||
name string
|
||||
count int
|
||||
}{
|
||||
{
|
||||
name: "buyers",
|
||||
n: len(c.Buyers),
|
||||
},
|
||||
{
|
||||
name: "suppliers",
|
||||
n: len(c.Suppliers),
|
||||
},
|
||||
{
|
||||
name: "subjects",
|
||||
n: len(c.Subjects),
|
||||
},
|
||||
{
|
||||
name: "methods",
|
||||
n: len(c.Methods),
|
||||
},
|
||||
{
|
||||
name: "classifications",
|
||||
n: len(c.Classifications),
|
||||
},
|
||||
} {
|
||||
if pool.n == 0 {
|
||||
errs = append(errs, fmt.Errorf("no %s", pool.name))
|
||||
{name: "buyers", count: len(c.Buyers)},
|
||||
{name: "suppliers", count: len(c.Suppliers)},
|
||||
{name: "subjects", count: len(c.Subjects)},
|
||||
{name: "methods", count: len(c.Methods)},
|
||||
{name: "classifications", count: len(c.Classifications)},
|
||||
}
|
||||
for _, pool := range pools {
|
||||
if pool.count == 0 {
|
||||
errs = append(errs, fmt.Errorf("mock: no %s", pool.name))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,8 +122,9 @@ func (c *Catalog) validate() error {
|
||||
keys = append(keys[:5], "...")
|
||||
}
|
||||
errs = append(errs, fmt.Errorf(
|
||||
"%d classification key(s) not found in classifications: %s",
|
||||
len(missing), strings.Join(keys, ", "),
|
||||
"mock: %d classification key(s) not found in classifications: %s",
|
||||
len(missing),
|
||||
strings.Join(keys, ", "),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -164,13 +151,19 @@ func (c *Catalog) subject(rng *rand.Rand) ocds.Tender {
|
||||
subject := clone(c.Subjects[rng.Intn(len(c.Subjects))])
|
||||
tender := subject.Tender
|
||||
tender.Classification = c.resolveOne(subject.Classification)
|
||||
tender.AdditionalClassifications = c.resolve(subject.AdditionalClassifications)
|
||||
tender.AdditionalClassifications = c.resolve(
|
||||
subject.AdditionalClassifications,
|
||||
)
|
||||
|
||||
tender.Items = nil
|
||||
for _, subjectItem := range subject.Items {
|
||||
item := subjectItem.Item
|
||||
item.AdditionalClassifications = c.resolve(subjectItem.AdditionalClassifications)
|
||||
item.AdditionalClassifications = c.resolve(
|
||||
subjectItem.AdditionalClassifications,
|
||||
)
|
||||
tender.Items = append(tender.Items, item)
|
||||
}
|
||||
|
||||
return tender
|
||||
}
|
||||
|
||||
@@ -195,12 +188,13 @@ func (c *Catalog) resolve(keys []string) []ocds.Classification {
|
||||
return out
|
||||
}
|
||||
|
||||
// clone deep-copies a value through JSON, which is all the generated types need.
|
||||
// clone deep-copies a value through JSON, which is all the generated types
|
||||
// need.
|
||||
func clone[T any](value T) T {
|
||||
var out T
|
||||
data, err := json.Marshal(value)
|
||||
if err == nil {
|
||||
json.Unmarshal(data, &out) //nolint:errcheck,gosec // b was just marshalled from a T
|
||||
json.Unmarshal(data, &out) //nolint:errcheck,gosec // data was just marshalled from a T
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -31,8 +31,8 @@ func TestEmbeddedCatalogIsValid(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(cat.Buyers) == 0 || len(cat.Suppliers) == 0 || len(cat.Subjects) == 0 ||
|
||||
len(cat.Methods) == 0 {
|
||||
if len(cat.Buyers) == 0 || len(cat.Suppliers) == 0 ||
|
||||
len(cat.Subjects) == 0 || len(cat.Methods) == 0 {
|
||||
t.Fatalf(
|
||||
"embedded catalog has an empty pool: %d buyers, %d suppliers, %d subjects, %d methods",
|
||||
len(cat.Buyers),
|
||||
@@ -45,8 +45,8 @@ func TestEmbeddedCatalogIsValid(t *testing.T) {
|
||||
|
||||
func TestParseCatalog(t *testing.T) {
|
||||
cat := loadTestCatalog(t)
|
||||
if len(cat.Buyers) != 2 || len(cat.Suppliers) != 1 || len(cat.Subjects) != 2 ||
|
||||
len(cat.Methods) != 2 {
|
||||
if len(cat.Buyers) != 2 || len(cat.Suppliers) != 1 ||
|
||||
len(cat.Subjects) != 2 || len(cat.Methods) != 2 {
|
||||
t.Fatalf(
|
||||
"got %d buyers, %d suppliers, %d subjects, %d methods",
|
||||
len(cat.Buyers),
|
||||
@@ -55,18 +55,22 @@ func TestParseCatalog(t *testing.T) {
|
||||
len(cat.Methods),
|
||||
)
|
||||
}
|
||||
|
||||
if d := cat.Buyers[0].Details; d == nil || len(d.Classifications) != 1 ||
|
||||
d.Classifications[0].Scheme != "UK_CA_TYPE" {
|
||||
t.Fatalf("buyer details.classifications not read: %+v", d)
|
||||
}
|
||||
|
||||
s := cat.Subjects[0]
|
||||
if s.Classification != "CPV-77314000" || len(s.Items) != 1 {
|
||||
t.Fatalf("subject classification key/items not read: %+v", s)
|
||||
}
|
||||
if ac := s.Items[0].AdditionalClassifications; len(ac) != 1 || ac[0] != "CPV-77310000" {
|
||||
if ac := s.Items[0].AdditionalClassifications; len(ac) != 1 ||
|
||||
ac[0] != "CPV-77310000" {
|
||||
t.Fatalf("items.additionalClassifications keys not read: %+v", ac)
|
||||
}
|
||||
if v := s.Lots[0].Value; v == nil || v.AmountGross == nil || *v.AmountGross != 120000 {
|
||||
if v := s.Lots[0].Value; v == nil || v.AmountGross == nil ||
|
||||
*v.AmountGross != 120000 {
|
||||
t.Fatalf("lot value not read: %+v", v)
|
||||
}
|
||||
}
|
||||
@@ -86,7 +90,8 @@ func TestSubjectResolvesClassifications(t *testing.T) {
|
||||
t.Fatalf("main classification = %+v", cl)
|
||||
}
|
||||
ac := tender.Items[0].AdditionalClassifications
|
||||
if len(ac) != 1 || ac[0].Description != "Planting and maintenance services of green areas" {
|
||||
if len(ac) != 1 ||
|
||||
ac[0].Description != "Planting and maintenance services of green areas" {
|
||||
t.Fatalf("item classifications = %+v", ac)
|
||||
}
|
||||
// The catalog itself still holds keys, untouched by picking.
|
||||
|
||||
@@ -17,61 +17,63 @@ const ocidPrefix = "ocds-mock-"
|
||||
// moves an existing procedure on (planning -> tender -> award) so the same ocid
|
||||
// appears in several releases, as it does on the real service.
|
||||
type Generator struct {
|
||||
cat *Catalog
|
||||
store *Store
|
||||
rnd *rand.Rand
|
||||
opts options
|
||||
catalog *Catalog
|
||||
store *Store
|
||||
rng *rand.Rand
|
||||
opts options
|
||||
}
|
||||
|
||||
// NewGenerator returns a generator drawing from catalog and storing releases in
|
||||
// store. The same seed and store contents give the same releases. It logs to
|
||||
// slog.Default() unless given WithLogger.
|
||||
func NewGenerator(catalog *Catalog, store *Store, seed int64, opts ...Option) *Generator {
|
||||
func NewGenerator(
|
||||
catalog *Catalog, store *Store, seed int64, opts ...Option,
|
||||
) *Generator {
|
||||
return &Generator{
|
||||
cat: catalog,
|
||||
store: store,
|
||||
rnd: rand.New(rand.NewSource(seed)), //nolint:gosec // seeded for repeatable mock data
|
||||
opts: applyOptions(opts),
|
||||
catalog: catalog,
|
||||
store: store,
|
||||
rng: rand.New(rand.NewSource(seed)), //nolint:gosec // seeded for repeatable mock data
|
||||
opts: applyOptions(opts),
|
||||
}
|
||||
}
|
||||
|
||||
// Make returns a new release dated at (to the second). About a third of the
|
||||
// time it moves on a procedure still open from the last 60 days; otherwise it
|
||||
// starts a new one.
|
||||
func (g *Generator) Make(at time.Time) ocds.Release {
|
||||
at = at.UTC().Truncate(time.Second)
|
||||
if g.rnd.Float64() < 0.35 {
|
||||
if prev, ok := g.store.RandomOpen(g.rnd, at.AddDate(0, 0, -60)); ok {
|
||||
return g.advance(prev, at)
|
||||
// Make returns a new release with the given date (to the second). About a third
|
||||
// of the time it moves on a procedure still open from the last 60 days;
|
||||
// otherwise it starts a new one.
|
||||
func (g *Generator) Make(date time.Time) ocds.Release {
|
||||
date = date.UTC().Truncate(time.Second)
|
||||
if g.rng.Float64() < 0.35 {
|
||||
if previous, ok := g.store.RandomOpen(g.rng, date.AddDate(0, 0, -60)); ok {
|
||||
return g.advance(previous, date)
|
||||
}
|
||||
}
|
||||
return g.newProcedure(at)
|
||||
return g.newProcedure(date)
|
||||
}
|
||||
|
||||
// newProcedure returns the first release of a new procedure: a tender (or,
|
||||
// one time in five, a planning notice) from a random catalog buyer and
|
||||
// subject, using a random procurement method. Values are scaled by a random
|
||||
// factor, and a tender without lots gets a single lot covering it all.
|
||||
func (g *Generator) newProcedure(at time.Time) ocds.Release {
|
||||
buyer := g.cat.buyer(g.rnd)
|
||||
func (g *Generator) newProcedure(date time.Time) ocds.Release {
|
||||
buyer := g.catalog.buyer(g.rng)
|
||||
ensurePartyID(&buyer)
|
||||
buyer.Roles = []string{"buyer"}
|
||||
method := g.cat.method(g.rnd)
|
||||
method := g.catalog.method(g.rng)
|
||||
|
||||
tag, status := "tender", "active"
|
||||
if g.rnd.Float64() < 0.2 {
|
||||
if g.rng.Float64() < 0.2 {
|
||||
tag, status = "planning", "planned"
|
||||
}
|
||||
ocid := g.newOCID()
|
||||
|
||||
tender := g.cat.subject(g.rnd)
|
||||
tender := g.catalog.subject(g.rng)
|
||||
tender.ID = ocds.ID(ocid)
|
||||
tender.ProcurementMethod = method.Method
|
||||
tender.ProcurementMethodDetails = method.Details
|
||||
|
||||
factor := 0.5 + g.rnd.Float64()*1.5
|
||||
factor := 0.5 + g.rng.Float64()*1.5
|
||||
if tender.Value == nil {
|
||||
amount := float64((g.rnd.Intn(5000) + 10) * 1000)
|
||||
amount := float64((g.rng.Intn(5000) + 10) * 1000)
|
||||
tender.Value = &ocds.Value{
|
||||
Amount: &amount,
|
||||
Currency: "GBP",
|
||||
@@ -96,14 +98,14 @@ func (g *Generator) newProcedure(at time.Time) ocds.Release {
|
||||
setStatus(&tender, status)
|
||||
if status == "active" {
|
||||
tender.TenderPeriod = &ocds.Period{
|
||||
EndDate: ptr(at.AddDate(0, 0, 30+g.rnd.Intn(30))),
|
||||
EndDate: ptr(date.AddDate(0, 0, 30+g.rng.Intn(30))),
|
||||
}
|
||||
}
|
||||
|
||||
return ocds.Release{
|
||||
OCID: ocid,
|
||||
ID: g.store.NextNoticeID(at.Year()),
|
||||
Date: at,
|
||||
ID: g.store.NextNoticeID(date.Year()),
|
||||
Date: date,
|
||||
Tag: []string{tag},
|
||||
InitiationType: "tender",
|
||||
Parties: []ocds.Organization{buyer},
|
||||
@@ -116,13 +118,15 @@ func (g *Generator) newProcedure(at time.Time) ocds.Release {
|
||||
}
|
||||
}
|
||||
|
||||
// advance returns the next release in prev's procedure: planning moves to
|
||||
// advance returns the next release in previous's procedure: planning moves to
|
||||
// tender, and a tender either has its deadline extended (tenderUpdate) or is
|
||||
// awarded to a supplier from the catalog.
|
||||
func (g *Generator) advance(prev ocds.Release, at time.Time) ocds.Release {
|
||||
release := clone(prev)
|
||||
release.ID = g.store.NextNoticeID(at.Year())
|
||||
release.Date = at
|
||||
func (g *Generator) advance(
|
||||
previous ocds.Release, date time.Time,
|
||||
) ocds.Release {
|
||||
release := clone(previous)
|
||||
release.ID = g.store.NextNoticeID(date.Year())
|
||||
release.Date = date
|
||||
release.Awards = nil
|
||||
if release.Tender == nil {
|
||||
release.Tender = &ocds.Tender{
|
||||
@@ -131,11 +135,11 @@ func (g *Generator) advance(prev ocds.Release, at time.Time) ocds.Release {
|
||||
}
|
||||
|
||||
next := "award"
|
||||
switch prev.Tag[0] {
|
||||
switch previous.Tag[0] {
|
||||
case "planning":
|
||||
next = "tender"
|
||||
case "tender":
|
||||
if g.rnd.Float64() < 0.25 {
|
||||
if g.rng.Float64() < 0.25 {
|
||||
next = "tenderUpdate"
|
||||
}
|
||||
}
|
||||
@@ -145,12 +149,13 @@ func (g *Generator) advance(prev ocds.Release, at time.Time) ocds.Release {
|
||||
case "tender":
|
||||
setStatus(release.Tender, "active")
|
||||
release.Tender.TenderPeriod = &ocds.Period{
|
||||
EndDate: ptr(at.AddDate(0, 0, 30+g.rnd.Intn(30))),
|
||||
EndDate: ptr(date.AddDate(0, 0, 30+g.rng.Intn(30))),
|
||||
}
|
||||
case "tenderUpdate":
|
||||
// A typical update: the deadline is extended by two weeks.
|
||||
end := at.AddDate(0, 0, 30)
|
||||
if period := release.Tender.TenderPeriod; period != nil && period.EndDate != nil {
|
||||
end := date.AddDate(0, 0, 30)
|
||||
if period := release.Tender.TenderPeriod; period != nil &&
|
||||
period.EndDate != nil {
|
||||
end = *period.EndDate
|
||||
}
|
||||
release.Tender.TenderPeriod = &ocds.Period{
|
||||
@@ -158,7 +163,7 @@ func (g *Generator) advance(prev ocds.Release, at time.Time) ocds.Release {
|
||||
}
|
||||
case "award":
|
||||
setStatus(release.Tender, "complete")
|
||||
supplier := g.cat.supplier(g.rnd)
|
||||
supplier := g.catalog.supplier(g.rng)
|
||||
ensurePartyID(&supplier)
|
||||
supplier.Roles = []string{"supplier"}
|
||||
release.Parties = append(release.Parties, supplier)
|
||||
@@ -166,7 +171,7 @@ func (g *Generator) advance(prev ocds.Release, at time.Time) ocds.Release {
|
||||
var value *ocds.Value
|
||||
if release.Tender.Value != nil {
|
||||
scaled := clone(*release.Tender.Value)
|
||||
scaleValue(&scaled, 0.8+g.rnd.Float64()*0.2)
|
||||
scaleValue(&scaled, 0.8+g.rng.Float64()*0.2)
|
||||
value = &scaled
|
||||
}
|
||||
|
||||
@@ -180,7 +185,7 @@ func (g *Generator) advance(prev ocds.Release, at time.Time) ocds.Release {
|
||||
release.Awards = []ocds.Award{{
|
||||
ID: "1",
|
||||
Status: "active",
|
||||
Date: ptr(at),
|
||||
Date: ptr(date),
|
||||
Value: value,
|
||||
Suppliers: []ocds.OrganizationReference{
|
||||
{
|
||||
@@ -198,26 +203,26 @@ func (g *Generator) advance(prev ocds.Release, at time.Time) ocds.Release {
|
||||
// newOCID returns a random ocid not already in the store.
|
||||
func (g *Generator) newOCID() string {
|
||||
for {
|
||||
id := fmt.Sprintf("%s%06x", ocidPrefix, g.rnd.Intn(1<<24))
|
||||
id := fmt.Sprintf("%s%06x", ocidPrefix, g.rng.Intn(1<<24))
|
||||
if !g.store.HasOCID(id) {
|
||||
return id
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// gap returns a random duration from min to max inclusive, or min if max is
|
||||
// not larger.
|
||||
func (g *Generator) gap(min, max time.Duration) time.Duration {
|
||||
if max <= min {
|
||||
return min
|
||||
// gap returns a random duration from minGap to maxGap inclusive, or minGap if
|
||||
// maxGap is not larger.
|
||||
func (g *Generator) gap(minGap, maxGap time.Duration) time.Duration {
|
||||
if maxGap <= minGap {
|
||||
return minGap
|
||||
}
|
||||
return min + time.Duration(g.rnd.Int63n(int64(max-min)+1))
|
||||
return minGap + time.Duration(g.rng.Int63n(int64(maxGap-minGap)+1))
|
||||
}
|
||||
|
||||
// CatchUp fills the period since the last stored release (or the last backfill
|
||||
// period, whichever is shorter) so restarts leave no gap in the timeline.
|
||||
func (g *Generator) CatchUp(
|
||||
now time.Time, backfill, min, max time.Duration,
|
||||
now time.Time, backfill, minGap, maxGap time.Duration,
|
||||
) (int, error) {
|
||||
start := now.Add(-backfill)
|
||||
if last, ok := g.store.Last(); ok && last.After(start) {
|
||||
@@ -225,7 +230,8 @@ func (g *Generator) CatchUp(
|
||||
}
|
||||
|
||||
count := 0
|
||||
for when := start.Add(g.gap(min, max)); !when.After(now); when = when.Add(g.gap(min, max)) {
|
||||
when := start.Add(g.gap(minGap, maxGap))
|
||||
for ; !when.After(now); when = when.Add(g.gap(minGap, maxGap)) {
|
||||
if err := g.store.AppendNoSync(g.Make(when)); err != nil {
|
||||
return count, err
|
||||
}
|
||||
@@ -235,11 +241,12 @@ func (g *Generator) CatchUp(
|
||||
return count, g.store.Sync()
|
||||
}
|
||||
|
||||
// Run publishes a new release after a random gap between min and max until ctx ends.
|
||||
func (g *Generator) Run(ctx context.Context, min, max time.Duration) {
|
||||
// Run publishes a new release after a random gap between minGap and maxGap
|
||||
// until ctx ends.
|
||||
func (g *Generator) Run(ctx context.Context, minGap, maxGap time.Duration) {
|
||||
logger := g.opts.logger("generator")
|
||||
for {
|
||||
gap := g.gap(min, max)
|
||||
gap := g.gap(minGap, maxGap)
|
||||
logger.Info("next release", "in", gap.Round(time.Second))
|
||||
|
||||
timer := time.NewTimer(gap)
|
||||
|
||||
@@ -2,8 +2,7 @@ package mock
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"log"
|
||||
"log/slog"
|
||||
"math/rand"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -13,19 +12,13 @@ import (
|
||||
"git.avsdev.uk/Go/job-search/internal/mock/findatender/ocds"
|
||||
)
|
||||
|
||||
func quietLog(t *testing.T) {
|
||||
t.Helper()
|
||||
w := log.Writer()
|
||||
log.SetOutput(io.Discard)
|
||||
t.Cleanup(func() {
|
||||
log.SetOutput(w)
|
||||
})
|
||||
}
|
||||
// quiet discards the logging of the Store and Generator it is given to.
|
||||
var quiet = WithLogger(slog.New(slog.DiscardHandler))
|
||||
|
||||
func TestGap(t *testing.T) {
|
||||
//nolint:gosec // G404: seeded math/rand keeps the test deterministic
|
||||
g := &Generator{
|
||||
rnd: rand.New(rand.NewSource(1)),
|
||||
rng: rand.New(rand.NewSource(1)),
|
||||
}
|
||||
if d := g.gap(time.Second, time.Second); d != time.Second {
|
||||
t.Errorf("min == max: %s", d)
|
||||
@@ -34,7 +27,8 @@ func TestGap(t *testing.T) {
|
||||
t.Errorf("max < min: %s, want min", d)
|
||||
}
|
||||
for i := 0; i < 1000; i++ {
|
||||
if d := g.gap(time.Second, 2*time.Second); d < time.Second || d > 2*time.Second {
|
||||
if d := g.gap(time.Second, 2*time.Second); d < time.Second ||
|
||||
d > 2*time.Second {
|
||||
t.Fatalf("gap out of range: %s", d)
|
||||
}
|
||||
}
|
||||
@@ -135,7 +129,14 @@ func TestAdvance(t *testing.T) {
|
||||
Amount: ptr(10000.0),
|
||||
Currency: "GBP",
|
||||
},
|
||||
Lots: []ocds.Lot{{ID: "1"}, {ID: ""}},
|
||||
Lots: []ocds.Lot{
|
||||
{
|
||||
ID: "1",
|
||||
},
|
||||
{
|
||||
ID: "",
|
||||
},
|
||||
},
|
||||
TenderPeriod: &ocds.Period{
|
||||
EndDate: &end,
|
||||
},
|
||||
@@ -147,7 +148,8 @@ func TestAdvance(t *testing.T) {
|
||||
seen[r.Tag[0]] = true
|
||||
switch r.Tag[0] {
|
||||
case "tenderUpdate":
|
||||
if got := *r.Tender.TenderPeriod.EndDate; !got.Equal(end.AddDate(0, 0, 14)) {
|
||||
got := *r.Tender.TenderPeriod.EndDate
|
||||
if !got.Equal(end.AddDate(0, 0, 14)) {
|
||||
t.Fatalf("updated deadline %s", got)
|
||||
}
|
||||
case "award":
|
||||
@@ -155,13 +157,15 @@ func TestAdvance(t *testing.T) {
|
||||
t.Fatalf("award: status %s, %d awards", r.Tender.Status, len(r.Awards))
|
||||
}
|
||||
aw := r.Awards[0]
|
||||
if aw.Value == nil || *aw.Value.Amount < 8000 || *aw.Value.Amount > 10000 {
|
||||
if aw.Value == nil || *aw.Value.Amount < 8000 ||
|
||||
*aw.Value.Amount > 10000 {
|
||||
t.Fatalf("award value %+v", aw.Value)
|
||||
}
|
||||
if len(aw.RelatedLots) != 1 || aw.RelatedLots[0] != "1" {
|
||||
t.Fatalf("related lots %v", aw.RelatedLots)
|
||||
}
|
||||
if len(aw.Suppliers) != 1 || len(r.Parties) != 1 || r.Parties[0].Roles[0] != "supplier" {
|
||||
if len(aw.Suppliers) != 1 || len(r.Parties) != 1 ||
|
||||
r.Parties[0].Roles[0] != "supplier" {
|
||||
t.Fatalf("suppliers %v, parties %v", aw.Suppliers, r.Parties)
|
||||
}
|
||||
default:
|
||||
@@ -188,7 +192,8 @@ func TestAdvance(t *testing.T) {
|
||||
r := g.advance(prev, at)
|
||||
switch r.Tag[0] {
|
||||
case "tenderUpdate":
|
||||
if got := *r.Tender.TenderPeriod.EndDate; !got.Equal(at.AddDate(0, 0, 44)) {
|
||||
got := *r.Tender.TenderPeriod.EndDate
|
||||
if !got.Equal(at.AddDate(0, 0, 44)) {
|
||||
t.Fatalf("default deadline %s", got)
|
||||
}
|
||||
case "award":
|
||||
@@ -200,9 +205,8 @@ func TestAdvance(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestRunPublishesUntilCancelled(t *testing.T) {
|
||||
quietLog(t)
|
||||
cat := loadTestCatalog(t)
|
||||
store, err := OpenStore(filepath.Join(t.TempDir(), "r.jsonl"))
|
||||
store, err := OpenStore(filepath.Join(t.TempDir(), "r.jsonl"), quiet)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -210,8 +214,9 @@ func TestRunPublishesUntilCancelled(t *testing.T) {
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
generator := NewGenerator(cat, store, 1, quiet)
|
||||
go func() {
|
||||
NewGenerator(cat, store, 1).Run(ctx, time.Millisecond, 2*time.Millisecond)
|
||||
generator.Run(ctx, time.Millisecond, 2*time.Millisecond)
|
||||
close(done)
|
||||
}()
|
||||
|
||||
@@ -234,7 +239,6 @@ func TestRunPublishesUntilCancelled(t *testing.T) {
|
||||
|
||||
// A failing store is logged and Run carries on until cancelled.
|
||||
func TestRunSurvivesStoreErrors(t *testing.T) {
|
||||
quietLog(t)
|
||||
cat := loadTestCatalog(t)
|
||||
store, err := OpenStore(filepath.Join(t.TempDir(), "r.jsonl"))
|
||||
if err != nil {
|
||||
@@ -244,7 +248,8 @@ func TestRunSurvivesStoreErrors(t *testing.T) {
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
|
||||
defer cancel()
|
||||
NewGenerator(cat, store, 1).Run(ctx, time.Millisecond, time.Millisecond)
|
||||
generator := NewGenerator(cat, store, 1, quiet)
|
||||
generator.Run(ctx, time.Millisecond, time.Millisecond)
|
||||
if store.Len() != 0 {
|
||||
t.Errorf("Len = %d, want 0", store.Len())
|
||||
}
|
||||
|
||||
@@ -31,8 +31,10 @@ const (
|
||||
type server struct {
|
||||
store *Store
|
||||
baseURL string
|
||||
loc *time.Location // zone for updatedFrom/updatedTo without an offset; nil means UTC
|
||||
opts options
|
||||
// location is the zone for updatedFrom/updatedTo without an offset; nil
|
||||
// means UTC.
|
||||
location *time.Location
|
||||
opts options
|
||||
}
|
||||
|
||||
// NewHandler serves release packages from store. baseURL is the public base
|
||||
@@ -42,16 +44,13 @@ type server struct {
|
||||
// Stored release dates are UTC; comparisons are on absolute instants. It
|
||||
// logs to slog.Default() unless given WithLogger.
|
||||
func NewHandler(
|
||||
store *Store,
|
||||
baseURL string,
|
||||
location *time.Location,
|
||||
opts ...Option,
|
||||
store *Store, baseURL string, location *time.Location, opts ...Option,
|
||||
) http.HandlerFunc {
|
||||
handler := &server{
|
||||
store: store,
|
||||
baseURL: baseURL,
|
||||
loc: location,
|
||||
opts: applyOptions(opts),
|
||||
store: store,
|
||||
baseURL: baseURL,
|
||||
location: location,
|
||||
opts: applyOptions(opts),
|
||||
}
|
||||
return handler.handle
|
||||
}
|
||||
@@ -86,8 +85,8 @@ func badRequest(w http.ResponseWriter, msg string) {
|
||||
}
|
||||
|
||||
// parseTime reads a query timestamp. Values without an offset (the documented
|
||||
// yyyy-MM-ddTHH:mm:ss, or a plain date) are local time in location; values with an
|
||||
// offset or Z (RFC 3339) mean exactly what they say.
|
||||
// yyyy-MM-ddTHH:mm:ss, or a plain date) are local time in location; values with
|
||||
// an offset or Z (RFC 3339) mean exactly what they say.
|
||||
func parseTime(value string, location *time.Location) (time.Time, error) {
|
||||
if location == nil {
|
||||
location = time.UTC
|
||||
@@ -98,7 +97,8 @@ func parseTime(value string, location *time.Location) (time.Time, error) {
|
||||
}
|
||||
|
||||
for _, layout := range []string{timeLayout, "2006-01-02"} {
|
||||
if parsed, err := time.ParseInLocation(layout, value, location); err == nil {
|
||||
parsed, err := time.ParseInLocation(layout, value, location)
|
||||
if err == nil {
|
||||
return parsed, nil
|
||||
}
|
||||
}
|
||||
@@ -115,22 +115,24 @@ type pageQuery struct {
|
||||
|
||||
// handle answers a GET for a page of releases as an OCDS release package,
|
||||
// with a links.next when more releases match.
|
||||
func (s *server) handle(w http.ResponseWriter, req *http.Request) {
|
||||
if req.Method != http.MethodGet {
|
||||
func (s *server) handle(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
query := req.URL.Query()
|
||||
query := r.URL.Query()
|
||||
page, err := s.parseQuery(query)
|
||||
if err != nil {
|
||||
badRequest(w, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
releases, next, more := s.store.Page(page.from, page.upper, page.start, page.limit)
|
||||
releases, next, more := s.store.Page(
|
||||
page.from, page.upper, page.start, page.limit,
|
||||
)
|
||||
releasePackage := ocds.ReleasePackage{
|
||||
URI: s.baseURL + req.URL.RequestURI(),
|
||||
URI: s.baseURL + r.URL.RequestURI(),
|
||||
Version: "1.1",
|
||||
Extensions: ocds.DeclaredExtensions,
|
||||
PublishedDate: ptr(time.Now().UTC().Truncate(time.Second)),
|
||||
@@ -167,13 +169,15 @@ func (s *server) parseQuery(query url.Values) (pageQuery, error) {
|
||||
if value := query.Get("limit"); value != "" {
|
||||
number, err := strconv.Atoi(value)
|
||||
if err != nil || number < 1 || number > maxLimit {
|
||||
return page, fmt.Errorf("limit must be an integer between 1 and %d", maxLimit)
|
||||
return page, fmt.Errorf(
|
||||
"limit must be an integer between 1 and %d", maxLimit,
|
||||
)
|
||||
}
|
||||
page.limit = number
|
||||
}
|
||||
|
||||
if value := query.Get("updatedFrom"); value != "" {
|
||||
from, err := parseTime(value, s.loc)
|
||||
from, err := parseTime(value, s.location)
|
||||
if err != nil {
|
||||
return page, fmt.Errorf("updatedFrom %w", err)
|
||||
}
|
||||
@@ -181,15 +185,15 @@ func (s *server) parseQuery(query url.Values) (pageQuery, error) {
|
||||
}
|
||||
|
||||
if value := query.Get("updatedTo"); value != "" {
|
||||
to, err := parseTime(value, s.loc)
|
||||
until, err := parseTime(value, s.location)
|
||||
if err != nil {
|
||||
return page, fmt.Errorf("updatedTo %w", err)
|
||||
}
|
||||
if query.Get("updatedFrom") != "" && to.Before(page.from) {
|
||||
if query.Get("updatedFrom") != "" && until.Before(page.from) {
|
||||
return page, errors.New("updatedTo must not be before updatedFrom")
|
||||
}
|
||||
if to.Before(page.upper) {
|
||||
page.upper = to
|
||||
if until.Before(page.upper) {
|
||||
page.upper = until
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -120,7 +120,8 @@ func TestHandlerRejectsBadRequests(t *testing.T) {
|
||||
t.Errorf("%s: Content-Type %q", q, ct)
|
||||
}
|
||||
var body map[string]string
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil || body["error"] != want {
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil ||
|
||||
body["error"] != want {
|
||||
t.Errorf("%s: body %s, want error %q", q, rec.Body.String(), want)
|
||||
}
|
||||
}
|
||||
@@ -147,7 +148,12 @@ func TestParseTimeFormats(t *testing.T) {
|
||||
t.Errorf("parseTime(%q) = %s, %v; want %s", v, got, err, want)
|
||||
}
|
||||
}
|
||||
for _, v := range []string{"", "08/10/2026", "2026-10-08 12:00:00", "2026-10-08T25:00:00"} {
|
||||
for _, v := range []string{
|
||||
"",
|
||||
"08/10/2026",
|
||||
"2026-10-08 12:00:00",
|
||||
"2026-10-08T25:00:00",
|
||||
} {
|
||||
if _, err := parseTime(v, nil); err == nil {
|
||||
t.Errorf("parseTime(%q): expected error", v)
|
||||
}
|
||||
|
||||
@@ -66,7 +66,8 @@ func (rl *RateLimiter) allow(key string) (bool, int) {
|
||||
|
||||
// Move to whichever fixed window, counted from the anchor, now falls in.
|
||||
index := now.Sub(client.anchor) / rl.window
|
||||
if windowStart := client.anchor.Add(index * rl.window); !windowStart.Equal(client.windowStart) {
|
||||
windowStart := client.anchor.Add(index * rl.window)
|
||||
if !windowStart.Equal(client.windowStart) {
|
||||
client.windowStart = windowStart
|
||||
client.count = 0
|
||||
}
|
||||
@@ -82,10 +83,12 @@ func (rl *RateLimiter) allow(key string) (bool, int) {
|
||||
if nextHour := hour.Add(time.Hour); nextHour.Before(next) {
|
||||
next = nextHour
|
||||
}
|
||||
|
||||
seconds := int((next.Sub(now) + time.Second - 1) / time.Second) // round up
|
||||
if seconds < 1 {
|
||||
seconds = 1
|
||||
}
|
||||
|
||||
return false, seconds
|
||||
}
|
||||
|
||||
@@ -100,10 +103,10 @@ func (rl *RateLimiter) prune(hour time.Time) {
|
||||
|
||||
// clientKey produces an identifier for the client based on remote address.
|
||||
// Could be updated to support proxy and forwarded-for headers.
|
||||
func clientKey(req *http.Request) string {
|
||||
host, _, err := net.SplitHostPort(req.RemoteAddr)
|
||||
func clientKey(r *http.Request) string {
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
return req.RemoteAddr
|
||||
return r.RemoteAddr
|
||||
}
|
||||
return host
|
||||
}
|
||||
@@ -112,18 +115,20 @@ func clientKey(req *http.Request) string {
|
||||
// to make a request in their current window or returns a "TooManyRequests"
|
||||
// status and the time the client should wait before making another request.
|
||||
func (rl *RateLimiter) Middleware(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, req *http.Request) {
|
||||
ok, retry := rl.allow(clientKey(req))
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
ok, retry := rl.allow(clientKey(r))
|
||||
if !ok {
|
||||
w.Header().Set("Retry-After", strconv.Itoa(retry))
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
fmt.Fprintf( //nolint:errcheck // the client may have gone; nothing to do
|
||||
w, "Rate limit of %d exceeded. Please retry after %d seconds.",
|
||||
rl.limit, retry,
|
||||
w,
|
||||
"Rate limit of %d exceeded. Please retry after %d seconds.",
|
||||
rl.limit,
|
||||
retry,
|
||||
)
|
||||
return
|
||||
}
|
||||
next(w, req)
|
||||
next(w, r)
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,8 @@ import (
|
||||
)
|
||||
|
||||
func TestRateLimitWindows(t *testing.T) {
|
||||
now := time.Date(2026, 10, 6, 10, 3, 20, 0, time.UTC) // first request of the hour
|
||||
// The first request of the hour.
|
||||
now := time.Date(2026, 10, 6, 10, 3, 20, 0, time.UTC)
|
||||
rl := NewRateLimiter(12, 5*time.Minute)
|
||||
rl.now = func() time.Time {
|
||||
return now
|
||||
|
||||
@@ -22,17 +22,17 @@ import (
|
||||
// Store keeps every release in memory and appends each new one to a JSON Lines
|
||||
// file, so releases survive restarts. Releases are kept in date order.
|
||||
type Store struct {
|
||||
mu sync.RWMutex
|
||||
f *os.File
|
||||
releases []ocds.Release
|
||||
times []time.Time
|
||||
latest map[string]int // ocid -> index of its most recent release
|
||||
lastNum map[int]int // year -> highest notice number used
|
||||
mu sync.RWMutex
|
||||
file *os.File
|
||||
releases []ocds.Release
|
||||
times []time.Time
|
||||
latest map[string]int // ocid -> index of its most recent release
|
||||
lastNumber map[int]int // year -> highest notice number used
|
||||
|
||||
// Procedures not yet awarded, as a slice plus positions so that adding,
|
||||
// removing and picking one at random are all constant time.
|
||||
open []string
|
||||
openPos map[string]int
|
||||
open []string
|
||||
openPosition map[string]int
|
||||
|
||||
opts options
|
||||
}
|
||||
@@ -44,11 +44,12 @@ type Store struct {
|
||||
// It logs to slog.Default() unless given WithLogger.
|
||||
func OpenStore(path string, opts ...Option) (*Store, error) {
|
||||
store := &Store{
|
||||
latest: map[string]int{},
|
||||
lastNum: map[int]int{},
|
||||
openPos: map[string]int{},
|
||||
opts: applyOptions(opts),
|
||||
latest: map[string]int{},
|
||||
lastNumber: map[int]int{},
|
||||
openPosition: map[string]int{},
|
||||
opts: applyOptions(opts),
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -57,6 +58,7 @@ func OpenStore(path string, opts ...Option) (*Store, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// The file is written in order, but sort anyway in case it was hand-edited.
|
||||
sort.SliceStable(releases, func(i, other int) bool {
|
||||
return releases[i].Date.Before(releases[other].Date)
|
||||
@@ -69,9 +71,10 @@ func OpenStore(path string, opts ...Option) (*Store, error) {
|
||||
store.index(i, release)
|
||||
}
|
||||
|
||||
if store.f, err = openForAppend(path); err != nil {
|
||||
if store.file, err = openForAppend(path); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return store, nil
|
||||
}
|
||||
|
||||
@@ -106,6 +109,7 @@ func readReleases(logger *slog.Logger, path string) ([]ocds.Release, error) {
|
||||
if err := scanner.Err(); err != nil {
|
||||
return nil, fmt.Errorf("reading %s: %w", path, err)
|
||||
}
|
||||
|
||||
return releases, nil
|
||||
}
|
||||
|
||||
@@ -113,18 +117,25 @@ func readReleases(logger *slog.Logger, path string) ([]ocds.Release, error) {
|
||||
// mid-write, it ends the partial record so the next one starts on a fresh
|
||||
// line.
|
||||
func openForAppend(path string) (*os.File, error) {
|
||||
file, err := os.OpenFile(filepath.Clean(path), os.O_CREATE|os.O_RDWR|os.O_APPEND, 0o600)
|
||||
file, err := os.OpenFile(
|
||||
filepath.Clean(path), os.O_CREATE|os.O_RDWR|os.O_APPEND, 0o600,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if info, err := file.Stat(); err == nil && info.Size() > 0 {
|
||||
last := make([]byte, 1)
|
||||
if _, err := file.ReadAt(last, info.Size()-1); err == nil && last[0] != '\n' {
|
||||
_, readErr := file.ReadAt(last, info.Size()-1)
|
||||
if readErr == nil && last[0] != '\n' {
|
||||
if _, err := file.Write([]byte("\n")); err != nil {
|
||||
return nil, errors.Join(fmt.Errorf("repairing %s: %w", path, err), file.Close())
|
||||
return nil, errors.Join(
|
||||
fmt.Errorf("repairing %s: %w", path, err), file.Close(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return file, nil
|
||||
}
|
||||
|
||||
@@ -133,51 +144,58 @@ func openForAppend(path string) (*os.File, error) {
|
||||
// highest notice number used each year.
|
||||
func (s *Store) index(i int, release ocds.Release) {
|
||||
s.latest[release.OCID] = i
|
||||
|
||||
if len(release.Tag) > 0 && release.Tag[0] == "award" {
|
||||
s.closeProcedure(release.OCID)
|
||||
} else if _, ok := s.openPos[release.OCID]; !ok {
|
||||
s.openPos[release.OCID] = len(s.open)
|
||||
} else if _, ok := s.openPosition[release.OCID]; !ok {
|
||||
s.openPosition[release.OCID] = len(s.open)
|
||||
s.open = append(s.open, release.OCID)
|
||||
}
|
||||
|
||||
if numberText, year, ok := strings.Cut(release.ID, "-"); ok {
|
||||
number, numberErr := strconv.Atoi(numberText)
|
||||
yearNumber, yearErr := strconv.Atoi(year)
|
||||
if numberErr == nil && yearErr == nil && number > s.lastNum[yearNumber] {
|
||||
s.lastNum[yearNumber] = number
|
||||
if numberErr == nil && yearErr == nil && number > s.lastNumber[yearNumber] {
|
||||
s.lastNumber[yearNumber] = number
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// closeProcedure removes ocid from the open procedures, if it is there.
|
||||
func (s *Store) closeProcedure(ocid string) {
|
||||
position, ok := s.openPos[ocid]
|
||||
position, ok := s.openPosition[ocid]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
last := len(s.open) - 1
|
||||
s.open[position] = s.open[last]
|
||||
s.openPos[s.open[position]] = position
|
||||
s.openPosition[s.open[position]] = position
|
||||
s.open = s.open[:last]
|
||||
delete(s.openPos, ocid)
|
||||
delete(s.openPosition, ocid)
|
||||
}
|
||||
|
||||
// Append persists a release and flushes it to disk.
|
||||
func (s *Store) Append(release ocds.Release) error { return s.append(release, true) }
|
||||
func (s *Store) Append(release ocds.Release) error {
|
||||
return s.append(release, true)
|
||||
}
|
||||
|
||||
// AppendNoSync persists a release without an fsync; call Sync afterwards.
|
||||
// Used for bulk catch-up, where a sync per record would be very slow.
|
||||
func (s *Store) AppendNoSync(release ocds.Release) error { return s.append(release, false) }
|
||||
func (s *Store) AppendNoSync(release ocds.Release) error {
|
||||
return s.append(release, false)
|
||||
}
|
||||
|
||||
// Sync flushes appended releases to disk. Call it after AppendNoSync.
|
||||
func (s *Store) Sync() error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.f.Sync()
|
||||
return s.file.Sync()
|
||||
}
|
||||
|
||||
// append stores release, syncing the file to disk if sync is true. A date earlier
|
||||
// than the newest stored release (for example after a clock change) is moved
|
||||
// up so the order stays valid.
|
||||
// append stores release, syncing the file to disk if sync is true. A date
|
||||
// earlier than the newest stored release (for example after a clock change) is
|
||||
// moved up so the order stays valid.
|
||||
func (s *Store) append(release ocds.Release, sync bool) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
@@ -186,27 +204,34 @@ func (s *Store) append(release ocds.Release, sync bool) error {
|
||||
if count := len(s.times); count > 0 && release.Date.Before(s.times[count-1]) {
|
||||
release.Date = s.times[count-1]
|
||||
}
|
||||
|
||||
data, err := json.Marshal(release)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := s.f.Write(append(data, '\n')); err != nil {
|
||||
if _, err := s.file.Write(append(data, '\n')); err != nil {
|
||||
return err
|
||||
}
|
||||
if sync {
|
||||
if err := s.f.Sync(); err != nil {
|
||||
if err := s.file.Sync(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
s.releases = append(s.releases, release)
|
||||
s.times = append(s.times, release.Date)
|
||||
s.index(len(s.releases)-1, release)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Page returns up to limit releases dated in [from, upper], starting no earlier
|
||||
// than position start, plus the position to continue from and whether more exist.
|
||||
func (s *Store) Page(from, upper time.Time, start, limit int) ([]ocds.Release, int, bool) {
|
||||
// than position start, plus the position to continue from and whether more
|
||||
// exist.
|
||||
func (s *Store) Page(
|
||||
from, upper time.Time,
|
||||
start, limit int,
|
||||
) ([]ocds.Release, int, bool) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
@@ -216,12 +241,15 @@ func (s *Store) Page(from, upper time.Time, start, limit int) ([]ocds.Release, i
|
||||
if start > i {
|
||||
i = start
|
||||
}
|
||||
|
||||
out := make([]ocds.Release, 0, limit)
|
||||
for i < len(s.releases) && len(out) < limit && !s.times[i].After(upper) {
|
||||
out = append(out, s.releases[i])
|
||||
i++
|
||||
}
|
||||
|
||||
more := i < len(s.releases) && !s.times[i].After(upper)
|
||||
|
||||
return out, i, more
|
||||
}
|
||||
|
||||
@@ -255,13 +283,15 @@ func (s *Store) HasOCID(ocid string) bool {
|
||||
func (s *Store) NextNoticeID(year int) string {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return fmt.Sprintf("%06d-%d", s.lastNum[year]+1, year)
|
||||
return fmt.Sprintf("%06d-%d", s.lastNumber[year]+1, year)
|
||||
}
|
||||
|
||||
// RandomOpen picks a procedure that has not been awarded and whose latest
|
||||
// release is after since. Procedures idle since before then are dropped from
|
||||
// the open set, as if they had been abandoned.
|
||||
func (s *Store) RandomOpen(rng *rand.Rand, since time.Time) (ocds.Release, bool) {
|
||||
func (s *Store) RandomOpen(
|
||||
rng *rand.Rand, since time.Time,
|
||||
) (ocds.Release, bool) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for len(s.open) > 0 {
|
||||
@@ -279,5 +309,5 @@ func (s *Store) RandomOpen(rng *rand.Rand, since time.Time) (ocds.Release, bool)
|
||||
func (s *Store) Close() error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.f.Close()
|
||||
return s.file.Close()
|
||||
}
|
||||
@@ -56,7 +56,9 @@ func TestStorePersistsAndGeneratorProgresses(t *testing.T) {
|
||||
t.Fatalf("after reopen: %d releases, want %d", store2.Len(), len(all))
|
||||
}
|
||||
gen2 := NewGenerator(cat, store2, 7)
|
||||
m, _ := gen2.CatchUp(now.Add(time.Hour), 48*time.Hour, 3*time.Minute, 15*time.Minute)
|
||||
m, _ := gen2.CatchUp(
|
||||
now.Add(time.Hour), 48*time.Hour, 3*time.Minute, 15*time.Minute,
|
||||
)
|
||||
if m < 4 || m > 20 {
|
||||
t.Fatalf("one hour gap produced %d releases", m)
|
||||
}
|
||||
@@ -66,9 +68,9 @@ func TestStorePersistsAndGeneratorProgresses(t *testing.T) {
|
||||
|
||||
// The HTTP handler pages through the store without gaps or repeats.
|
||||
srv := &server{
|
||||
store: store2,
|
||||
baseURL: "",
|
||||
loc: time.UTC,
|
||||
store: store2,
|
||||
baseURL: "",
|
||||
location: time.UTC,
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
next := BasePath + "?updatedFrom=2026-10-07T00:00:00&limit=7"
|
||||
@@ -102,7 +104,9 @@ func TestStorePersistsAndGeneratorProgresses(t *testing.T) {
|
||||
|
||||
func writeLines(t *testing.T, path string, lines ...string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(path, []byte(strings.Join(lines, "\n")), 0o600); err != nil {
|
||||
if err := os.WriteFile(
|
||||
path, []byte(strings.Join(lines, "\n")), 0o600,
|
||||
); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -122,7 +126,8 @@ func releaseLine(t *testing.T, ocid, id, tag string, at time.Time) string {
|
||||
}
|
||||
|
||||
// Unreadable lines are skipped, blank lines ignored, a hand-edited file is put
|
||||
// back in date order, and the index (open procedures, notice numbers) is rebuilt.
|
||||
// back in date order, and the index (open procedures, notice numbers) is
|
||||
// rebuilt.
|
||||
func TestOpenStoreRecoversFromMessyFile(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "r.jsonl")
|
||||
t0 := time.Date(2026, 10, 8, 9, 0, 0, 0, time.UTC)
|
||||
@@ -148,7 +153,8 @@ func TestOpenStoreRecoversFromMessyFile(t *testing.T) {
|
||||
for _, r := range all {
|
||||
ids = append(ids, r.ID)
|
||||
}
|
||||
if got, want := strings.Join(ids, ","), "000003-2026,000005-2026,000007-2026"; got != want {
|
||||
want := "000003-2026,000005-2026,000007-2026"
|
||||
if got := strings.Join(ids, ","); got != want {
|
||||
t.Fatalf("releases %s, want %s", got, want)
|
||||
}
|
||||
if got := store.NextNoticeID(2026); got != "000008-2026" {
|
||||
@@ -199,7 +205,11 @@ func TestOpenStoreAfterTruncatedWrite(t *testing.T) {
|
||||
}
|
||||
defer store2.Close()
|
||||
if store2.Len() != 2 || !store2.HasOCID("ocds-c") {
|
||||
t.Fatalf("after reopen: Len = %d, has ocds-c = %v", store2.Len(), store2.HasOCID("ocds-c"))
|
||||
t.Fatalf(
|
||||
"after reopen: Len = %d, has ocds-c = %v",
|
||||
store2.Len(),
|
||||
store2.HasOCID("ocds-c"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -294,7 +304,8 @@ func TestRandomOpenDropsStaleProcedures(t *testing.T) {
|
||||
//nolint:gosec // G404: seeded math/rand keeps the test deterministic
|
||||
rnd := rand.New(rand.NewSource(1))
|
||||
for i := 0; i < 10; i++ {
|
||||
if r, ok := store.RandomOpen(rnd, t0.Add(time.Minute)); !ok || r.OCID != "new" {
|
||||
if r, ok := store.RandomOpen(rnd, t0.Add(time.Minute)); !ok ||
|
||||
r.OCID != "new" {
|
||||
t.Fatalf("RandomOpen = %s, %v; want new", r.OCID, ok)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user