build: add makefile, dockerfile, ci and development stack
- build: add makefile, dockerfile, ci and development stack - feat(config): add environment configuration and logger - feat(server): add server lifecycle with health and version routes - feat(db): add connection, contract check, migrations and stores - feat(cli): add command dispatch and user management - test(db): add integration tests against mysql
This commit is contained in:
1 parent
45d1e307c6
commit
7089a6f408
46 files changed
+8456
No files matched your search
+377
@@ -0,0 +1,377 @@
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
// Copyright (C) 2026 Bryan Joshua Pedini
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"math"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-sql-driver/mysql"
|
||||
)
|
||||
|
||||
const (
|
||||
dbCollation = "utf8mb4_0900_ai_ci"
|
||||
dbConnectTimeout = 5 * time.Second
|
||||
dbReadTimeout = 30 * time.Second
|
||||
dbWriteTimeout = 30 * time.Second
|
||||
dbMaxOpenConns = 10
|
||||
dbMaxIdleConns = 10
|
||||
dbConnMaxLifetime = time.Minute
|
||||
dbPingMaxWait = 30 * time.Second
|
||||
dbPingAttemptTimeout = 5 * time.Second
|
||||
dbPingFirstDelay = 250 * time.Millisecond
|
||||
dbPingMaxDelay = 4 * time.Second
|
||||
zoneLockTimeout = 10 * time.Second
|
||||
migrateLockTimeout = 30 * time.Second
|
||||
mysqlErrDupEntry = 1062
|
||||
)
|
||||
|
||||
var (
|
||||
errLockTimeout = errors.New("named lock timeout")
|
||||
errRowNotFound = errors.New("row not found")
|
||||
errUsernameTaken = errors.New("username already used")
|
||||
errContract = errors.New("records table contract violated")
|
||||
errDatabase = errors.New("database unavailable")
|
||||
)
|
||||
|
||||
type dbtx interface {
|
||||
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
|
||||
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
|
||||
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
|
||||
}
|
||||
|
||||
type txBeginner interface {
|
||||
BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
|
||||
}
|
||||
|
||||
type pinger interface {
|
||||
PingContext(ctx context.Context) error
|
||||
}
|
||||
|
||||
type tableNames struct {
|
||||
prefix string
|
||||
records string
|
||||
schema string
|
||||
users string
|
||||
sessions string
|
||||
delegations string
|
||||
audit string
|
||||
}
|
||||
|
||||
func newTableNames(prefix string) (tableNames, error) {
|
||||
if !validTablePrefix(prefix) {
|
||||
return tableNames{}, errors.New("invalid table prefix")
|
||||
}
|
||||
return tableNames{
|
||||
prefix: prefix,
|
||||
records: quoteIdent(prefix + "records"),
|
||||
schema: quoteIdent(prefix + "webui_schema"),
|
||||
users: quoteIdent(prefix + "webui_users"),
|
||||
sessions: quoteIdent(prefix + "webui_sessions"),
|
||||
delegations: quoteIdent(prefix + "webui_zone_delegations"),
|
||||
audit: quoteIdent(prefix + "webui_audit"),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func quoteIdent(name string) string {
|
||||
return "`" + name + "`"
|
||||
}
|
||||
|
||||
func (t tableNames) sql(query string) string {
|
||||
return strings.NewReplacer(
|
||||
"{records}", t.records,
|
||||
"{schema}", t.schema,
|
||||
"{users}", t.users,
|
||||
"{sessions}", t.sessions,
|
||||
"{delegations}", t.delegations,
|
||||
"{audit}", t.audit,
|
||||
).Replace(query)
|
||||
}
|
||||
|
||||
func (t tableNames) migrateLockName() string {
|
||||
return t.prefix + "webui_migrate"
|
||||
}
|
||||
|
||||
func (t tableNames) zoneLockName(zone string) string {
|
||||
sum := sha256.Sum256([]byte(zone))
|
||||
return t.prefix + "webui:" + hex.EncodeToString(sum[:])[:16]
|
||||
}
|
||||
|
||||
func mysqlConfig(cfg Config) *mysql.Config {
|
||||
mc := mysql.NewConfig()
|
||||
mc.User = cfg.DBUser
|
||||
mc.Passwd = cfg.DBPassword
|
||||
mc.Net = "tcp"
|
||||
mc.Addr = cfg.DBAddress()
|
||||
mc.DBName = cfg.DBName
|
||||
mc.ParseTime = true
|
||||
mc.Loc = time.UTC
|
||||
mc.Collation = dbCollation
|
||||
mc.Timeout = dbConnectTimeout
|
||||
mc.ReadTimeout = dbReadTimeout
|
||||
mc.WriteTimeout = dbWriteTimeout
|
||||
mc.MultiStatements = false
|
||||
mc.InterpolateParams = false
|
||||
mc.TLSConfig = cfg.DBTLS
|
||||
return mc
|
||||
}
|
||||
|
||||
func openDatabase(cfg Config, log *slog.Logger) (*sql.DB, error) {
|
||||
connector, err := mysql.NewConnector(mysqlConfig(cfg))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: invalid connection settings", errDatabase)
|
||||
}
|
||||
db := sql.OpenDB(connector)
|
||||
db.SetMaxOpenConns(dbMaxOpenConns)
|
||||
db.SetMaxIdleConns(dbMaxIdleConns)
|
||||
db.SetConnMaxLifetime(dbConnMaxLifetime)
|
||||
log.Debug("database pool opened", "host", cfg.DBHost, "port", cfg.DBPort, "user", cfg.DBUser, "database", cfg.DBName, "tls", cfg.DBTLS)
|
||||
return db, nil
|
||||
}
|
||||
|
||||
type backoff struct {
|
||||
maxWait time.Duration
|
||||
attemptTimeout time.Duration
|
||||
firstDelay time.Duration
|
||||
maxDelay time.Duration
|
||||
now func() time.Time
|
||||
sleep func(ctx context.Context, d time.Duration) error
|
||||
}
|
||||
|
||||
func defaultPingBackoff() backoff {
|
||||
return backoff{
|
||||
maxWait: dbPingMaxWait,
|
||||
attemptTimeout: dbPingAttemptTimeout,
|
||||
firstDelay: dbPingFirstDelay,
|
||||
maxDelay: dbPingMaxDelay,
|
||||
now: time.Now,
|
||||
sleep: sleepContext,
|
||||
}
|
||||
}
|
||||
|
||||
func sleepContext(ctx context.Context, d time.Duration) error {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-t.C:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func pingDatabase(ctx context.Context, p pinger, b backoff, log *slog.Logger) error {
|
||||
deadline := b.now().Add(b.maxWait)
|
||||
delay := b.firstDelay
|
||||
for attempt := 1; ; attempt++ {
|
||||
attemptCtx, cancel := context.WithTimeout(ctx, b.attemptTimeout)
|
||||
err := p.PingContext(attemptCtx)
|
||||
cancel()
|
||||
if err == nil {
|
||||
log.DebugContext(ctx, "database reachable", "attempts", attempt)
|
||||
return nil
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
remaining := deadline.Sub(b.now())
|
||||
if remaining <= 0 {
|
||||
log.ErrorContext(ctx, "database unreachable", "attempts", attempt, "error", err)
|
||||
return fmt.Errorf("%w: ping failed after %d attempts: %v", errDatabase, attempt, err)
|
||||
}
|
||||
log.DebugContext(ctx, "database ping failed, retrying", "attempt", attempt, "delay", delay, "error", err)
|
||||
if err := b.sleep(ctx, min(delay, remaining)); err != nil {
|
||||
return err
|
||||
}
|
||||
delay = min(delay*2, b.maxDelay)
|
||||
}
|
||||
}
|
||||
|
||||
type contractColumn struct {
|
||||
name string
|
||||
types []string
|
||||
}
|
||||
|
||||
var integerTypes = []string{"tinyint", "smallint", "mediumint", "int", "bigint"}
|
||||
|
||||
var textTypes = []string{"char", "varchar", "tinytext", "text", "mediumtext", "longtext"}
|
||||
|
||||
var recordsContract = []contractColumn{
|
||||
{"id", integerTypes},
|
||||
{"zone", textTypes},
|
||||
{"name", textTypes},
|
||||
{"ttl", integerTypes},
|
||||
{"content", append(append([]string{}, textTypes...), "json")},
|
||||
{"record_type", textTypes},
|
||||
}
|
||||
|
||||
func verifyRecordsContract(ctx context.Context, q dbtx, t tableNames, log *slog.Logger) error {
|
||||
table := t.prefix + "records"
|
||||
rows, err := q.QueryContext(ctx,
|
||||
"SELECT COLUMN_NAME, DATA_TYPE FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?",
|
||||
table)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read records table columns: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
columns := map[string]string{}
|
||||
for rows.Next() {
|
||||
var name, dataType string
|
||||
if err := rows.Scan(&name, &dataType); err != nil {
|
||||
return fmt.Errorf("read records table columns: %w", err)
|
||||
}
|
||||
columns[strings.ToLower(name)] = strings.ToLower(dataType)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return fmt.Errorf("read records table columns: %w", err)
|
||||
}
|
||||
if err := checkRecordsColumns(table, columns); err != nil {
|
||||
return err
|
||||
}
|
||||
log.DebugContext(ctx, "records table contract verified", "table", table)
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkRecordsColumns(table string, columns map[string]string) error {
|
||||
if len(columns) == 0 {
|
||||
return fmt.Errorf("%w: table %s does not exist in the configured database", errContract, table)
|
||||
}
|
||||
for _, c := range recordsContract {
|
||||
dataType, ok := columns[c.name]
|
||||
if !ok {
|
||||
return fmt.Errorf("%w: table %s has no column %s", errContract, table, c.name)
|
||||
}
|
||||
compatible := false
|
||||
for _, allowed := range c.types {
|
||||
if dataType == allowed {
|
||||
compatible = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !compatible {
|
||||
return fmt.Errorf("%w: column %s of table %s has incompatible type %s", errContract, c.name, table, dataType)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type namedLock struct {
|
||||
conn *sql.Conn
|
||||
name string
|
||||
}
|
||||
|
||||
func acquireNamedLock(ctx context.Context, conn *sql.Conn, name string, timeout time.Duration) (*namedLock, error) {
|
||||
seconds := int64(math.Ceil(timeout.Seconds()))
|
||||
var result sql.NullInt64
|
||||
if err := conn.QueryRowContext(ctx, "SELECT GET_LOCK(?, ?)", name, seconds).Scan(&result); err != nil {
|
||||
return nil, fmt.Errorf("acquire lock: %w", err)
|
||||
}
|
||||
if !result.Valid {
|
||||
return nil, errors.New("acquire lock: GET_LOCK returned NULL")
|
||||
}
|
||||
if result.Int64 != 1 {
|
||||
return nil, errLockTimeout
|
||||
}
|
||||
return &namedLock{conn: conn, name: name}, nil
|
||||
}
|
||||
|
||||
func (l *namedLock) release(ctx context.Context) error {
|
||||
var result sql.NullInt64
|
||||
if err := l.conn.QueryRowContext(ctx, "SELECT RELEASE_LOCK(?)", l.name).Scan(&result); err != nil {
|
||||
return fmt.Errorf("release lock: %w", err)
|
||||
}
|
||||
if !result.Valid || result.Int64 != 1 {
|
||||
return errors.New("release lock: lock was not held")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type connSource interface {
|
||||
Conn(ctx context.Context) (*sql.Conn, error)
|
||||
}
|
||||
|
||||
func withNamedLock(ctx context.Context, db connSource, name string, timeout time.Duration, log *slog.Logger, fn func(conn *sql.Conn) error) (err error) {
|
||||
conn, err := db.Conn(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("dedicated connection: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
if cerr := conn.Close(); cerr != nil && err == nil {
|
||||
err = fmt.Errorf("close dedicated connection: %w", cerr)
|
||||
}
|
||||
}()
|
||||
lock, err := acquireNamedLock(ctx, conn, name, timeout)
|
||||
if err != nil {
|
||||
if errors.Is(err, errLockTimeout) {
|
||||
log.WarnContext(ctx, "named lock timeout", "lock", name, "timeout", timeout)
|
||||
}
|
||||
return err
|
||||
}
|
||||
log.DebugContext(ctx, "named lock acquired", "lock", name)
|
||||
defer func() {
|
||||
releaseCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), dbPingAttemptTimeout)
|
||||
defer cancel()
|
||||
if rerr := lock.release(releaseCtx); rerr != nil {
|
||||
log.ErrorContext(ctx, "named lock release failed", "lock", name, "error", rerr)
|
||||
if err == nil {
|
||||
err = rerr
|
||||
}
|
||||
return
|
||||
}
|
||||
log.DebugContext(ctx, "named lock released", "lock", name)
|
||||
}()
|
||||
return fn(conn)
|
||||
}
|
||||
|
||||
func withZoneLock(ctx context.Context, db connSource, t tableNames, zone string, log *slog.Logger, fn func(conn *sql.Conn) error) error {
|
||||
return withNamedLock(ctx, db, t.zoneLockName(zone), zoneLockTimeout, log, fn)
|
||||
}
|
||||
|
||||
func runInTx(ctx context.Context, b txBeginner, fn func(tx *sql.Tx) error) (err error) {
|
||||
tx, err := b.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin transaction: %w", err)
|
||||
}
|
||||
committed := false
|
||||
defer func() {
|
||||
if !committed {
|
||||
_ = tx.Rollback()
|
||||
}
|
||||
}()
|
||||
if err := fn(tx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("commit transaction: %w", err)
|
||||
}
|
||||
committed = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func isDuplicateKey(err error) bool {
|
||||
var me *mysql.MySQLError
|
||||
return errors.As(err, &me) && me.Number == mysqlErrDupEntry
|
||||
}
|
||||
|
||||
func dbTime(t time.Time) time.Time {
|
||||
return t.UTC().Truncate(time.Microsecond)
|
||||
}
|
||||
|
||||
func scanUTC(t *time.Time) {
|
||||
*t = t.UTC()
|
||||
}
|
||||
|
||||
func scanNullUTC(t *sql.NullTime) {
|
||||
if t.Valid {
|
||||
t.Time = t.Time.UTC()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user