Documentation
¶
Overview ¶
Package settings keeps the settings that an admin changes while the service runs — limits, switches, texts — in Postgres, and their current value in the memory of every replica.
Settings are one document of a type T under a name, stored as JSONB in the table settings. Every replica reads them at its start and rereads them on an interval; a hot path reads Current, which never waits for the database and never fails. An admin handler stores a new document with Save.
Usage ¶
The table comes from EnsureSchema at the start, or from Schema in the migrations of the service. New reads the settings, with the defaults for what is not stored; the group of the service runs the rereads:
type Limits struct {
MaxWithdrawal int64 `json:"max_withdrawal"`
Maintenance bool `json:"maintenance"`
}
if err := settings.EnsureSchema(ctx, log, db); err != nil {
return err
}
limits, err := settings.New(ctx, log, db, "limits", Limits{
MaxWithdrawal: 100_000,
})
if err != nil {
return err
}
group.Add(limits) // rereads every 30s
A hot path reads the settings from memory:
if limits.Current().Maintenance {
return errs.New(errs.Unavailable, ErrMaintenance)
}
An admin handler checks a new document and saves it:
if v.MaxWithdrawal <= 0 {
return errs.New(errs.InvalidArgument, ErrBadLimit)
}
if err := limits.Save(ctx, v); err != nil {
return err
}
Defaults ¶
A read decodes the stored document over the defaults with encoding/json/v2: a field the document lacks keeps its default, and a member the type lacks is skipped. So a field added to T with its default, or removed from it, needs no migration; a renamed field is a new one, and starts at its default. A map of the document is merged into the map of the defaults, a slice replaces the slice of the defaults.
Replicas ¶
Each replica keeps and rereads the settings on its own. A Save shows on the replica that made it at once, on the others with their next read: within the interval of WithInterval, 30s by default. Of two concurrent Saves the last one wins, whole: a Save writes the entire document.
New reads the settings once before it returns. No document stored is not an error: the settings are the defaults until the first Save. A failed read is, and the service does not start on the defaults in place of the settings it was given. Later a failed reread is logged and keeps the settings as they were; the next one tries again.
Table ¶
The table settings holds a row per name: the document in value, the time of its last Save in updated_at. The document is plain JSON:
SELECT value->>'maintenance' FROM settings WHERE name = 'limits';
Options ¶
- WithInterval(d): how often the settings are reread (default 30s).
Example ¶
The limits are read at the start, with the defaults for what is not stored, and the group rereads them every 30s next to the HTTP server: a hot path reads them from memory, the admin saves new ones. The example needs Postgres, so go test builds it but does not run it.
package main
import (
"context"
"encoding/json/v2"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/assanoff/skit/dbx/pg"
"github.com/assanoff/skit/settings"
"github.com/assanoff/skit/worker"
)
// Limits are the settings of the examples, which an admin changes while the
// service runs.
type Limits struct {
MaxWithdrawal int64 `json:"max_withdrawal"`
Maintenance bool `json:"maintenance"`
}
// The limits are read at the start, with the defaults for what is not stored,
// and the group rereads them every 30s next to the HTTP server: a hot path
// reads them from memory, the admin saves new ones. The example needs
// Postgres, so go test builds it but does not run it.
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
log := slog.Default()
db, err := pg.Open(pg.Config{Host: "localhost:5432", Name: "shop", DisableTLS: true})
if err != nil {
log.ErrorContext(ctx, "open", "err", err)
return
}
defer func() { _ = db.Close() }()
if err := settings.EnsureSchema(ctx, log, db); err != nil {
log.ErrorContext(ctx, "settings table", "err", err)
return
}
limits, err := settings.New(ctx, log, db, "limits", Limits{MaxWithdrawal: 100_000})
if err != nil {
log.ErrorContext(ctx, "limits", "err", err)
return
}
mux := http.NewServeMux()
// A hot path reads the limits from memory, without the database.
mux.HandleFunc("POST /withdrawals", func(w http.ResponseWriter, _ *http.Request) {
if limits.Current().Maintenance {
http.Error(w, "withdrawals are paused", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusAccepted)
})
// The admin checks the new limits and saves them. The replica that saved
// them uses them at once, the others after their next reread.
mux.HandleFunc("PUT /admin/limits", func(w http.ResponseWriter, r *http.Request) {
var v Limits
if err := json.UnmarshalRead(r.Body, &v); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if v.MaxWithdrawal <= 0 {
http.Error(w, "max_withdrawal must be positive", http.StatusUnprocessableEntity)
return
}
if err := limits.Save(r.Context(), v); err != nil {
http.Error(w, "the limits are not saved", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
})
srv := &http.Server{Addr: ":8080", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
g := worker.NewGroup(log, worker.GroupConfig{ShutdownTimeout: 10 * time.Second})
g.Add(limits)
g.Add(worker.RunnableFunc{
NameValue: "http",
StartFn: func(context.Context) error { return srv.ListenAndServe() },
StopFn: srv.Shutdown,
})
if err := g.Run(ctx); err != nil {
log.ErrorContext(ctx, "group stopped", "err", err)
}
}
Output:
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func EnsureSchema ¶
EnsureSchema creates the table settings if it is absent. Several replicas may run it at their start at once: they take their turns on an advisory lock. log may be nil.
Types ¶
type Option ¶
type Option func(*options)
Option configures Settings.
func WithInterval ¶
WithInterval sets how often the settings are reread (default 30s): the longest a change saved on another replica takes to show here.
type Settings ¶
type Settings[T any] struct { // contains filtered or unexported fields }
Settings are one document of settings of type T: stored in the table settings under their name, kept in memory and reread on an interval. They are a worker.Runnable: the group that runs them runs the rereads.
func New ¶
func New[T any](ctx context.Context, log *slog.Logger, db *dbx.DB, name string, defaults T, opts ...Option) (*Settings[T], error)
New reads the settings stored under name and keeps them. The defaults stand for the fields the stored document lacks, and for all of it before the first Save. A failed read fails New: the service does not start on the defaults in place of the settings it was given. log may be nil.
func (*Settings[T]) Current ¶
func (s *Settings[T]) Current() T
Current returns the settings as last read. It never waits for the database and is safe for concurrent use.
func (*Settings[T]) Save ¶
Save stores v under the name of the settings, and this replica rereads them at once; the others see v on their next read. Of two concurrent Saves, the last one wins.