diff --git a/CHANGELOG.md b/CHANGELOG.md index 9df7f83..b50b44b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,22 @@ becomes the release notes of the next tag. `smarttags.Vocabulary`; `smartcomments/catalog.Check` runs it over every commented object of a catalog. +### Fixed + +- `introspect.Introspect` no longer sorts the caller's schema slice in + place (a live boot alphabetised the products' `schema.schemas`, which a + cache boot did not); `Catalog.Schemas` keeps the configured order and + `Hash` ignores it. +- Strict environment loading reports a variable that doubles the + underscore after its section (`PDBQ_ROLES__ALLOWED`) with a did-you-mean + hint instead of ignoring it. +- `confx.ValidateDatabase` rejects a negative `database.max_conns`, a + non-positive `database.connect_timeout` and a negative + `database.statement_timeout`; `ValidateIdentity` rejects a non-positive + `auth.jwt.jwks_cache_ttl` with a JWKS URL (it silently became one hour); + `ValidateWatch` and `watch.New` reject a non-positive poll interval (the + polling fallback panicked). + ### Breaking: API hygiene See [docs/upgrading.md](docs/upgrading.md#api-hygiene). diff --git a/confx/confx_test.go b/confx/confx_test.go index c8afef3..f57e229 100644 --- a/confx/confx_test.go +++ b/confx/confx_test.go @@ -288,7 +288,7 @@ func TestValidateRejects(t *testing.T) { return ValidateIdentity(Auth{Mode: "none", JWT: JWT{SecretFile: "/nonexistent/secret"}}, Roles{}, Claims{}) }, "auth.jwt.secret_file: open /nonexistent/secret: no such file or directory"}, "jwks url": {func() []string { - return ValidateIdentity(Auth{Mode: "jwt", JWT: JWT{JWKSURL: "idp.example/jwks", RoleClaimPath: "role"}}, Roles{}, Claims{}) + return ValidateIdentity(Auth{Mode: "jwt", JWT: JWT{JWKSURL: "idp.example/jwks", JWKSCacheTTL: time.Hour, RoleClaimPath: "role"}}, Roles{}, Claims{}) }, `auth.jwt.jwks_url: "idp.example/jwks" is not an http(s) URL`}, "leeway": {func() []string { return ValidateIdentity(Auth{Mode: "none", JWT: JWT{Leeway: -time.Second}}, Roles{}, Claims{}) @@ -344,15 +344,21 @@ func TestValidateRejects(t *testing.T) { "headers needs trusted proxies": {func() []string { return ValidateIdentity(Auth{Mode: "headers", Headers: Headers{Prefix: "X-Pdbq-Claim-", RoleClaim: "role"}}, Roles{}, Claims{}) }, "auth.headers.trusted_proxies is required in auth mode headers: list the gateway addresses allowed to send claim headers"}, - "watch channel length": {func() []string { return ValidateWatch(Watch{Enabled: true, Channel: strings.Repeat("c", 64)}, "") }, + "watch channel length": {func() []string { + return ValidateWatch(Watch{Enabled: true, PollInterval: time.Second, Channel: strings.Repeat("c", 64)}, "") + }, `watch.channel: "` + strings.Repeat("c", 64) + `" is longer than 63 bytes`}, "isolation": {func() []string { return ValidateTX(TX{Isolation: "chaos"}) }, `transactions.isolation: "chaos" is not 'read_committed', 'repeatable_read' or 'serializable'`}, "max_retries": {func() []string { return ValidateTX(TX{Isolation: "serializable", MaxRetries: -1}) }, "transactions.max_retries must be >= 0"}, - "watch+cache": {func() []string { return ValidateWatch(Watch{Enabled: true, Channel: "c"}, "x") }, + "watch+cache": {func() []string { + return ValidateWatch(Watch{Enabled: true, PollInterval: time.Second, Channel: "c"}, "x") + }, "watch.enabled cannot be combined with schema.cache_path"}, - "watch channel": {func() []string { return ValidateWatch(Watch{Enabled: true, Channel: "bad$$chan"}, "") }, + "watch channel": {func() []string { + return ValidateWatch(Watch{Enabled: true, PollInterval: time.Second, Channel: "bad$$chan"}, "") + }, `watch.channel: "bad$$chan" invalid: only letters, digits and underscores are allowed`}, "no schemas": {func() []string { return ValidateSchema(Schema{}) }, "schema.schemas must list at least one schema"}, diff --git a/confx/load.go b/confx/load.go index 62a7a39..8cc953a 100644 --- a/confx/load.go +++ b/confx/load.go @@ -67,7 +67,9 @@ func WithFlags(values map[string]any) LoadOption { // naming the key it moved to (WithMoved), the reason it was removed // (WithRemoved) or the closest valid key. An environment variable with // the prefix is checked the same way when its first segment names a -// section of dst (or of a moved or removed key), or nearly does; other +// section of dst (or of a moved or removed key), or nearly does, or when +// it starts with a section name and a doubled underscore +// (PDBQ_ROLES__ALLOWED, a misspelt PDBQ_ROLES_ALLOWED); other // variables with the prefix (PDBQ_TEST_DATABASE_URL) are ignored. Values // are decoded with weak typing, so environment strings set booleans, // numbers, durations and lists. Validation is the caller's job. @@ -115,13 +117,28 @@ func Load(envPrefix, path string, dst any, opts ...LoadOption) error { if schema.known(key) { continue } + envPath := func(p string) string { return envName(envPrefix, p) } top, _, _ := strings.Cut(key, ".") + hintKey := key if !schema.section(top, o.hints) { - ek.Delete(key) - continue + fixed, ok := schema.underscoredSection(key, o.hints) + if !ok { + ek.Delete(key) + continue + } + hintKey = fixed } msg := fmt.Sprintf("unknown environment variable %s (%s)", envVars[key], key) - if hint := schema.unknownKey(key, o.hints, func(p string) string { return envName(envPrefix, p) }); hint != "" { + hint := "" + switch { + case hintKey != key && schema.known(hintKey): + hint = fmt.Sprintf("did you mean %s?", envPath(hintKey)) + case hintKey != key: + hint = schema.unknownKey(hintKey, o.hints, envPath) + default: + hint = schema.unknownKey(key, o.hints, envPath) + } + if hint != "" { msg += ": " + hint } errs = append(errs, msg) diff --git a/confx/sections.go b/confx/sections.go index b2635f6..04ff7b5 100644 --- a/confx/sections.go +++ b/confx/sections.go @@ -18,8 +18,8 @@ import ( // Database is the connection section. type Database struct { URL string `koanf:"url" doc:"PostgreSQL connection URL, e.g. postgres://user:pass@host:5432/db. Also honours standard PG* env vars when empty."` - MaxConns int32 `koanf:"max_conns" doc:"Maximum pooled connections."` - ConnectTimeout time.Duration `koanf:"connect_timeout" doc:"Timeout for establishing a connection."` + MaxConns int32 `koanf:"max_conns" doc:"Maximum pooled connections; 0 uses the pgx pool default (the larger of 4 and the number of CPUs)."` + ConnectTimeout time.Duration `koanf:"connect_timeout" doc:"Timeout for establishing a connection (must be positive)."` StatementTimeout time.Duration `koanf:"statement_timeout" doc:"Per-statement timeout applied to every request (0 disables). Keep it below the HTTP request timeout so a slow statement fails with SQLSTATE 57014 (a timeout error the client can act on) before the request is cut off."` } @@ -116,7 +116,7 @@ type TX struct { // Watch is the DDL watch (dev mode) section. type Watch struct { Enabled bool `koanf:"enabled" doc:"Re-introspect and hot-swap the schema on DDL changes (dev only; refuses to combine with schema.cache_path)."` - PollInterval time.Duration `koanf:"poll_interval" doc:"Poll interval used when event triggers cannot be installed."` + PollInterval time.Duration `koanf:"poll_interval" doc:"Poll interval used when event triggers cannot be installed (must be positive)."` Channel string `koanf:"channel" doc:"NOTIFY channel used by the DDL event trigger."` } diff --git a/confx/strict.go b/confx/strict.go index 292b2f9..78a7f04 100644 --- a/confx/strict.go +++ b/confx/strict.go @@ -141,6 +141,38 @@ func (s keySchema) section(name string, h hints) bool { return len(name) >= 4 && closest(name, tops) != "" } +// underscoredSection reports whether key, an environment key without a +// section of its own, starts with a section name of the schema (or of a +// moved or removed key) followed by "_": the mapping of an environment +// variable that doubled the underscore after the section +// (PREFIX_ROLES__ALLOWED is roles_allowed). It returns key with that "_" +// read as the section separator (roles.allowed), preferring the longest +// section name. +func (s keySchema) underscoredSection(key string, h hints) (string, bool) { + best := "" + consider := func(name string) { + if strings.HasPrefix(key, name+"_") && len(name) > len(best) { + best = name + } + } + for p, kind := range s { + if !strings.Contains(p, ".") && kind != leafKey { + consider(p) + } + } + for _, m := range []map[string]string{h.moved, h.removed} { + for old := range m { + if top, _, ok := strings.Cut(old, "."); ok { + consider(top) + } + } + } + if best == "" { + return "", false + } + return best + "." + key[len(best)+1:], true +} + // unknownKey describes an unknown key: where it moved to, why it was // removed, or the closest known or moved key; name renders a path for the // message. diff --git a/confx/strict_test.go b/confx/strict_test.go index 256846a..eaaf173 100644 --- a/confx/strict_test.go +++ b/confx/strict_test.go @@ -3,6 +3,7 @@ package confx import ( "os" "path/filepath" + "slices" "strings" "testing" "time" @@ -196,3 +197,49 @@ legacy: } } } + +func TestLoadRejectsDoubledUnderscoreAfterSection(t *testing.T) { + for env, want := range map[string]string{ + "PDBX_ROLES__ALLOWED": "unknown environment variable PDBX_ROLES__ALLOWED (roles_allowed): did you mean PDBX_ROLES_ALLOWED?", + "PDBX_AUTH__MODE": "unknown environment variable PDBX_AUTH__MODE (auth_mode): did you mean PDBX_AUTH_MODE?", + "PDBX_FILTERS__INDEXED__ONLY": "unknown environment variable PDBX_FILTERS__INDEXED__ONLY (filters_indexed_only): did you mean PDBX_FILTERS_INDEXED__ONLY?", + "PDBX_AUTH__JWT_SECRET": "unknown environment variable PDBX_AUTH__JWT_SECRET (auth_jwt.secret): did you mean PDBX_AUTH_JWT_SECRET?", + "PDBX_ROLES__NO__SUCH__THING": "unknown environment variable PDBX_ROLES__NO__SUCH__THING (roles_no_such_thing)", + "PDBX_RLS__ENABLED": "unknown environment variable PDBX_RLS__ENABLED (rls_enabled): moved to PDBX_ROLES_SWITCH", + } { + t.Run(env, func(t *testing.T) { + t.Setenv(env, "x") + cfg := pdbqDefaults() + err := Load("PDBX_", "", &cfg) + if err == nil || !strings.Contains(err.Error(), want) { + t.Fatalf("err = %v, want %q", err, want) + } + }) + } + t.Setenv("PDBX_UNRELATED__THING", "1") + t.Setenv("PDBX_TEST_DATABASE_URL", "postgres://test") + cfg := pdbqDefaults() + if err := Load("PDBX_", "", &cfg); err != nil { + t.Fatalf("variables outside every section must stay ignored: %v", err) + } +} + +func TestValidateSharedDurations(t *testing.T) { + for want, errs := range map[string][]string{ + "database.max_conns must be >= 0": ValidateDatabase(Database{MaxConns: -1, ConnectTimeout: time.Second}), + "database.connect_timeout must be > 0": ValidateDatabase(Database{MaxConns: 1}), + "database.statement_timeout must be >= 0": ValidateDatabase(Database{MaxConns: 1, ConnectTimeout: time.Second, StatementTimeout: -time.Second}), + "auth.jwt.jwks_cache_ttl must be > 0": ValidateIdentity(Auth{Mode: "jwt", JWT: JWT{JWKSURL: "https://idp.example/jwks", RoleClaimPath: "role"}}, Roles{Switch: true}, Claims{}), + "watch.poll_interval must be > 0": ValidateWatch(Watch{Enabled: true, Channel: "c"}, ""), + } { + if !slices.ContainsFunc(errs, func(e string) bool { return strings.HasPrefix(e, want) }) { + t.Errorf("want %q, got %q", want, errs) + } + } + if errs := ValidateDatabase(Database{ConnectTimeout: time.Second}); len(errs) != 0 { + t.Errorf("max_conns 0 or statement_timeout 0 rejected: %q", errs) + } + if errs := ValidateWatch(Watch{Channel: "c"}, ""); len(errs) != 0 { + t.Errorf("disabled watch checked: %q", errs) + } +} diff --git a/confx/testdata/pdbq.example.yaml b/confx/testdata/pdbq.example.yaml index 2f1a4ab..495a919 100644 --- a/confx/testdata/pdbq.example.yaml +++ b/confx/testdata/pdbq.example.yaml @@ -1,9 +1,9 @@ database: # PostgreSQL connection URL, e.g. postgres://user:pass@host:5432/db. Also honours standard PG* env vars when empty. url: "" - # Maximum pooled connections. + # Maximum pooled connections; 0 uses the pgx pool default (the larger of 4 and the number of CPUs). max_conns: 10 - # Timeout for establishing a connection. + # Timeout for establishing a connection (must be positive). connect_timeout: "10s" # Per-statement timeout applied to every request (0 disables). Keep it below the HTTP request timeout so a slow statement fails with SQLSTATE 57014 (a timeout error the client can act on) before the request is cut off. statement_timeout: "25s" @@ -115,7 +115,7 @@ transactions: watch: # Re-introspect and hot-swap the schema on DDL changes (dev only; refuses to combine with schema.cache_path). enabled: false - # Poll interval used when event triggers cannot be installed. + # Poll interval used when event triggers cannot be installed (must be positive). poll_interval: "5s" # NOTIFY channel used by the DDL event trigger. channel: "pdbq_ddl" diff --git a/confx/validate.go b/confx/validate.go index df2a12e..1490804 100644 --- a/confx/validate.go +++ b/confx/validate.go @@ -22,6 +22,24 @@ func InvalidConfig(errs []string) error { return fmt.Errorf("invalid config:\n - %s", strings.Join(errs, "\n - ")) } +// ValidateDatabase checks the database section's numbers: max_conns must +// not be negative (0 uses the pgx pool default), connect_timeout must be +// positive (0 would wait for a connection forever) and statement_timeout +// not negative (0 disables it). +func ValidateDatabase(d Database) []string { + var errs []string + if d.MaxConns < 0 { + errs = append(errs, "database.max_conns must be >= 0 (0 uses the pool default)") + } + if d.ConnectTimeout <= 0 { + errs = append(errs, "database.connect_timeout must be > 0") + } + if d.StatementTimeout < 0 { + errs = append(errs, "database.statement_timeout must be >= 0 (0 disables it)") + } + return errs +} + // ValidateErrors checks errors.detail (see [pgexec.ParseDetail]). func ValidateErrors(e Errors) []string { if _, err := pgexec.ParseDetail(e.Detail); err != nil { @@ -33,7 +51,7 @@ func ValidateErrors(e Errors) []string { // ValidateIdentity checks the auth, roles and claims sections together: // the auth mode; in jwt mode a secret, secret file or JWKS URL (a secret // file must be readable), the role claim path and a non-negative leeway; -// in headers mode the prefix, the claim names (auth.ValidHeaderClaim) and +// a positive JWKS cache TTL with a JWKS URL; in headers mode the prefix, the claim names (auth.ValidHeaderClaim) and // at least one trusted proxy; every trusted_proxies entry; mint_type's // shape and secret; the role names (pgexec.ValidRole), and an anonymous // role in mode none while roles switch; the claims prefix @@ -62,6 +80,9 @@ func ValidateIdentity(a Auth, r Roles, c Claims) []string { if j.Leeway < 0 { add("auth.jwt.leeway must be >= 0") } + if j.JWKSURL != "" && j.JWKSCacheTTL <= 0 { + add("auth.jwt.jwks_cache_ttl must be > 0") + } if a.Mode == auth.ModeJWT { if j.Secret == "" && j.SecretFile == "" && j.JWKSURL == "" { add("auth.jwt.secret, auth.jwt.secret_file or auth.jwt.jwks_url is required in auth mode jwt (use auth.mode: none to accept no credentials)") @@ -136,10 +157,13 @@ func ValidateTX(t TX) []string { return errs } -// ValidateWatch checks the watch section against schema.cache_path and the -// channel name. +// ValidateWatch checks the enabled watch section: the poll interval, the +// channel name, and that schema.cache_path is not set. func ValidateWatch(w Watch, cachePath string) []string { var errs []string + if w.Enabled && w.PollInterval <= 0 { + errs = append(errs, "watch.poll_interval must be > 0") + } if w.Enabled && cachePath != "" { errs = append(errs, "watch.enabled cannot be combined with schema.cache_path") } diff --git a/docs/upgrading.md b/docs/upgrading.md index c5332ce..0927d02 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -159,3 +159,15 @@ Go API changes: without `Run` writing back into the configuration, and `OnChange` is `func(ctx context.Context, cat *introspect.Catalog)` with `Run`'s context. + +### Stricter shared validation + +- `Catalog.Schemas` is in the order passed to `Introspect` (it used to be + sorted, and the caller's slice with it). Code that relied on the sorted + order must sort a copy. +- `PDBQ_ROLES__ALLOWED`-style variables (a doubled underscore right after + the section) are errors with a did-you-mean hint; they used to be + ignored. +- New `confx.ValidateDatabase`; `ValidateIdentity` checks + `auth.jwt.jwks_cache_ttl` when `auth.jwt.jwks_url` is set, and + `ValidateWatch` checks `watch.poll_interval` when the watch is enabled. diff --git a/introspect/catalog.go b/introspect/catalog.go index 419f48e..603e8d1 100644 --- a/introspect/catalog.go +++ b/introspect/catalog.go @@ -29,11 +29,14 @@ type Catalog struct { // ServerVersionNum is current_setting('server_version_num'), e.g. // 180001 for 18.1. Gate version-dependent SQL on it rather than parsing // ServerVersion. [Catalog.Hash] covers its major part only. - ServerVersionNum int `json:"server_version_num"` - Schemas []string `json:"schemas"` - Tables []*Table `json:"tables"` - Enums []*Enum `json:"enums"` - Composites []*Composite `json:"composites"` + ServerVersionNum int `json:"server_version_num"` + // Schemas are the introspected schemas in the order given to + // [Introspect], which products treat as a priority order (the first + // schema is the primary one). [Catalog.Hash] ignores their order. + Schemas []string `json:"schemas"` + Tables []*Table `json:"tables"` + Enums []*Enum `json:"enums"` + Composites []*Composite `json:"composites"` // [Introspect] orders Functions by schema, then name, then input parameters // (Args): fewer parameters first, then parameter by parameter by type // schema and type name. PostgreSQL identifies a function by exactly @@ -736,6 +739,7 @@ func (c *Catalog) Hash() (string, error) { Domains: slices.Clone(c.Domains), } v.sortStable() + slices.Sort(v.Schemas) b, err := json.Marshal(v) if err != nil { return "", err @@ -744,12 +748,11 @@ func (c *Catalog) Hash() (string, error) { return hex.EncodeToString(sum[:]), nil } -// sortStable puts the catalog's top-level slices in the canonical order -// [Introspect] returns: schemas by name; tables, enums, composites, ranges +// sortStable puts the catalog's top-level slices other than Schemas in the +// canonical order [Introspect] returns: tables, enums, composites, ranges // and domains by schema then name; extensions by name; and functions by // [compareFunctions]. func (c *Catalog) sortStable() { - slices.Sort(c.Schemas) byName := func(as, an, bs, bn string) int { return cmp.Or(strings.Compare(as, bs), strings.Compare(an, bn)) } diff --git a/introspect/hash_test.go b/introspect/hash_test.go index 197ff5d..4115b00 100644 --- a/introspect/hash_test.go +++ b/introspect/hash_test.go @@ -116,3 +116,16 @@ func TestFunctionOrder(t *testing.T) { } } } + +func TestHashIgnoresSchemaOrder(t *testing.T) { + a, b := hashCatalog(), hashCatalog() + b.Schemas = []string{"a", "b"} + ha, _ := a.Hash() + hb, _ := b.Hash() + if ha != hb { + t.Fatalf("hash depends on schema order: %s != %s", ha, hb) + } + if !slices.Equal(a.Schemas, []string{"b", "a"}) { + t.Fatalf("Hash reordered Schemas: %v", a.Schemas) + } +} diff --git a/introspect/introspect.go b/introspect/introspect.go index 508efb4..f5ab7af 100644 --- a/introspect/introspect.go +++ b/introspect/introspect.go @@ -38,7 +38,7 @@ func Introspect(ctx context.Context, db Querier, schemas []string) (*Catalog, er if len(schemas) == 0 { schemas = []string{"public"} } - cat := &Catalog{FormatVersion: CatalogFormatVersion, Schemas: schemas} + cat := &Catalog{FormatVersion: CatalogFormatVersion, Schemas: slices.Clone(schemas)} if err := db.QueryRow(ctx, `SELECT current_setting('server_version'), current_setting('server_version_num')::int`). Scan(&cat.ServerVersion, &cat.ServerVersionNum); err != nil { diff --git a/introspect/introspect_db_test.go b/introspect/introspect_db_test.go index b9c1b77..de2cacb 100644 --- a/introspect/introspect_db_test.go +++ b/introspect/introspect_db_test.go @@ -1096,3 +1096,32 @@ func TestIntrospectIndexOpClassesLive(t *testing.T) { } } } + +func TestIntrospectKeepsSchemaOrderLive(t *testing.T) { + url := os.Getenv("PDBCORE_TEST_DATABASE_URL") + if url == "" { + t.Skip("PDBCORE_TEST_DATABASE_URL not set; run `make test-e2e`") + } + ctx := context.Background() + conn, err := pgx.Connect(ctx, url) + if err != nil { + t.Fatal(err) + } + defer conn.Close(ctx) + schemas := []string{"public", "app", "audit"} + cat, err := Introspect(ctx, conn, schemas) + if err != nil { + t.Fatal(err) + } + want := []string{"public", "app", "audit"} + if !reflect.DeepEqual(schemas, want) { + t.Fatalf("Introspect reordered its argument: %v", schemas) + } + if !reflect.DeepEqual(cat.Schemas, want) { + t.Fatalf("Catalog.Schemas = %v, want the configured order %v", cat.Schemas, want) + } + cat.Schemas[0] = "changed" + if schemas[0] != "public" { + t.Fatal("Catalog.Schemas shares the caller's slice") + } +} diff --git a/watch/filter_test.go b/watch/filter_test.go index 44fca2f..96ad33f 100644 --- a/watch/filter_test.go +++ b/watch/filter_test.go @@ -305,7 +305,7 @@ func TestWatcherSkipsUnchangedCatalog(t *testing.T) { changed := make(chan *introspect.Catalog, 8) w := mustNew(t, Config{ Pool: pool, Schemas: []string{schema}, Channel: name, TriggerName: name, - InitialHash: hash, Log: slog.New(logTap{logs}), + InitialHash: hash, Log: slog.New(logTap{logs}), PollInterval: time.Second, OnChange: func(_ context.Context, c *introspect.Catalog) { mu.Lock() changes = append(changes, c) @@ -374,8 +374,9 @@ func TestRunDetectsChangeBeforeListening(t *testing.T) { changed := make(chan *introspect.Catalog, 1) w := mustNew(t, Config{ Pool: pool, Schemas: []string{schema}, Channel: name, TriggerName: name, InitialHash: hash, - Log: slog.New(logTap{make(chan string)}), - OnChange: func(_ context.Context, c *introspect.Catalog) { changed <- c }, + PollInterval: time.Second, + Log: slog.New(logTap{make(chan string)}), + OnChange: func(_ context.Context, c *introspect.Catalog) { changed <- c }, }) runCtx, stop := context.WithCancel(ctx) done := make(chan error, 1) diff --git a/watch/watch.go b/watch/watch.go index 819379c..46bce6a 100644 --- a/watch/watch.go +++ b/watch/watch.go @@ -28,7 +28,7 @@ type Config struct { // digits and underscores, at most 63 bytes. Channel string // PollInterval is the hash-polling interval used when the event - // trigger cannot be installed. + // trigger cannot be installed; it must be positive. PollInterval time.Duration // OnChange receives every changed catalog, with the context Run was // given; required. It runs on Run's goroutine. @@ -75,8 +75,8 @@ const DefaultInstallWait = 30 * time.Second const installPollInterval = 50 * time.Millisecond // New validates cfg, fills in its defaults and returns the Watcher. It is -// an error when Pool or OnChange is nil, or when Channel or TriggerName is -// not a valid name or too long to install. +// an error when Pool or OnChange is nil, PollInterval is not positive, or +// Channel or TriggerName is not a valid name or too long to install. func New(cfg Config) (*Watcher, error) { if !validChannel(cfg.Channel) { return nil, fmt.Errorf("watch: invalid channel name %q: only letters, digits and underscores are allowed", cfg.Channel) @@ -93,6 +93,9 @@ func New(cfg Config) (*Watcher, error) { if len(cfg.TriggerName)+len(longestSuffix) > maxIdentLen { return nil, fmt.Errorf("watch: trigger name %q is too long: with the %q suffix it must fit in %d bytes", cfg.TriggerName, longestSuffix, maxIdentLen) } + if cfg.PollInterval <= 0 { + return nil, fmt.Errorf("watch: poll interval %s must be positive", cfg.PollInterval) + } if cfg.Pool == nil { return nil, errors.New("watch: Pool is required") } diff --git a/watch/watch_test.go b/watch/watch_test.go index 0c245f3..6b2dc8a 100644 --- a/watch/watch_test.go +++ b/watch/watch_test.go @@ -14,7 +14,7 @@ import ( ) func TestNewRejectsInvalidConfig(t *testing.T) { - ok := Config{Pool: &pgxpool.Pool{}, Channel: "ok", OnChange: func(context.Context, *introspect.Catalog) {}} + ok := Config{Pool: &pgxpool.Pool{}, Channel: "ok", PollInterval: time.Second, OnChange: func(context.Context, *introspect.Catalog) {}} cases := []struct { edit func(*Config) want string @@ -24,6 +24,7 @@ func TestNewRejectsInvalidConfig(t *testing.T) { {func(c *Config) { c.Channel = strings.Repeat("c", 64) }, "longer than 63 bytes"}, {func(c *Config) { c.TriggerName = strings.Repeat("t", 57) }, "is too long"}, {func(c *Config) { c.Channel = strings.Repeat("c", 51) }, "is too long"}, + {func(c *Config) { c.PollInterval = 0 }, "poll interval 0s must be positive"}, {func(c *Config) { c.Pool = nil }, "Pool is required"}, {func(c *Config) { c.OnChange = nil }, "OnChange is required"}, }