Add initial shared code packages

This commit is contained in:
Gabriel20xx committed 2026-08-04 15:17:15 +02:00
commit 838a97d344
54 files changed
+6265

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
# Shared Go backend packages
The Go packages under this directory hold infrastructure shared by the
services, not application-specific SQL or HTTP handlers.
- `config` — environment string, required value, boolean, integer, and duration helpers.
- `postgres` — validated `DATABASE_URL` configuration, `pgxpool` creation/ping, transaction wrapper, and PostgreSQL error classification.
- `auth` — shared bcrypt policy, secure token generation/hashing, account/session schema, and account/session persistence.
- `migrate` — embedded filesystem adapter for Goose migrations.
Run `go test ./...` and `go vet ./...` from this directory. The module path is
`repos.gfranz.ch/Gabriel20xx/SharedCode/backend`; change it if the SharedCode folder is
hosted under a different repository path.
Application-specific table definitions and HTTP behavior stay in the service.
That lets a service reuse reliable connection/auth plumbing without coupling
its domain model to another project.
+21
View File
@@ -0,0 +1,21 @@
package auth
import "golang.org/x/crypto/bcrypt"
// BcryptCost is kept in one place so all services use the same password
// storage policy. Existing hashes remain valid when this value is raised.
const BcryptCost = 12
// HashPassword returns a bcrypt password hash suitable for storage.
func HashPassword(password string) (string, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(password), BcryptCost)
if err != nil {
return "", err
}
return string(hash), nil
}
// VerifyPassword checks a plaintext password against a stored bcrypt hash.
func VerifyPassword(hash, password string) bool {
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
}
+270
View File
@@ -0,0 +1,270 @@
// Package auth contains the shared single-account/session persistence used by
// the self-hosted web services. HTTP handlers, cookies, authorization policy,
// and application-specific roles remain in each service.
package auth
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
)
// User is the shared account record. PasswordHash should never be serialized
// into an API response.
type User struct {
ID int64
Username string
Email string
PasswordHash string
CreatedAt time.Time
UpdatedAt time.Time
}
// Store performs common auth persistence against a caller-owned pool.
type Store struct {
pool *pgxpool.Pool
}
// NewStore creates an auth store. The pool remains owned by the caller.
func NewStore(pool *pgxpool.Pool) *Store {
return &Store{pool: pool}
}
// SchemaOptions controls optional auth schema features.
type SchemaOptions struct {
// SingleUser adds a constraint that allows exactly one account. This is the
// default model for GameStream, SimpleCollection, and home-server tools.
SingleUser bool
// APITokens creates the optional per-user API token table.
APITokens bool
}
// DefaultSchemaOptions returns the single-account schema used by most small
// self-hosted services.
func DefaultSchemaOptions() SchemaOptions {
return SchemaOptions{SingleUser: true}
}
// EnsureSchema creates the shared auth tables and indexes idempotently.
func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions) error {
if pool == nil {
return errors.New("auth postgres pool is nil")
}
_, err := pool.Exec(ctx, `
CREATE TABLE IF NOT EXISTS auth_users (
id BIGSERIAL PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
email TEXT NOT NULL DEFAULT '',
password_hash TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx
ON auth_users (lower(email)) WHERE email <> '';
CREATE TABLE IF NOT EXISTS auth_sessions (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
token_hash TEXT NOT NULL UNIQUE,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions (expires_at);
CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions (user_id);
`)
if err != nil {
return fmt.Errorf("ensure auth schema: %w", err)
}
if options.SingleUser {
if _, err := pool.Exec(ctx, `
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true));
`); err != nil {
return fmt.Errorf("ensure single-user auth constraint: %w", err)
}
}
if options.APITokens {
if _, err := pool.Exec(ctx, `
CREATE TABLE IF NOT EXISTS auth_api_tokens (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
token_hash TEXT NOT NULL UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS auth_api_tokens_user_idx ON auth_api_tokens (user_id);
`); err != nil {
return fmt.Errorf("ensure auth API-token schema: %w", err)
}
}
return nil
}
// CountUsers returns the number of configured accounts.
func (s *Store) CountUsers(ctx context.Context) (int, error) {
if err := s.validate(); err != nil {
return 0, err
}
var count int
if err := s.pool.QueryRow(ctx, `SELECT count(*) FROM auth_users`).Scan(&count); err != nil {
return 0, fmt.Errorf("count auth users: %w", err)
}
return count, nil
}
// CreateUser inserts an account and returns ErrUserExists for a uniqueness
// conflict, including the single-user constraint.
func (s *Store) CreateUser(ctx context.Context, username, email, passwordHash string) (*User, error) {
if err := s.validate(); err != nil {
return nil, err
}
var user User
err := s.pool.QueryRow(ctx, `
INSERT INTO auth_users (username, email, password_hash, updated_at)
VALUES ($1, $2, $3, now())
RETURNING id, username, email, password_hash, created_at, updated_at
`, username, email, passwordHash).Scan(
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.CreatedAt, &user.UpdatedAt,
)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return nil, ErrUserExists
}
return nil, fmt.Errorf("create auth user: %w", err)
}
return &user, nil
}
// FindByIdentifier looks up a user by exact username or case-insensitive email.
func (s *Store) FindByIdentifier(ctx context.Context, identifier string) (*User, error) {
if err := s.validate(); err != nil {
return nil, err
}
return s.find(ctx, `
SELECT id, username, email, password_hash, created_at, updated_at
FROM auth_users
WHERE username = $1 OR lower(email) = lower($1)
`, identifier)
}
// FindByID looks up a user by primary key.
func (s *Store) FindByID(ctx context.Context, id int64) (*User, error) {
if err := s.validate(); err != nil {
return nil, err
}
return s.find(ctx, `
SELECT id, username, email, password_hash, created_at, updated_at
FROM auth_users WHERE id = $1
`, id)
}
// UpdateCredentials updates the normalized account fields and password hash.
func (s *Store) UpdateCredentials(ctx context.Context, id int64, username, email, passwordHash string) error {
if err := s.validate(); err != nil {
return err
}
_, err := s.pool.Exec(ctx, `
UPDATE auth_users
SET username = $1, email = $2, password_hash = $3, updated_at = now()
WHERE id = $4
`, username, email, passwordHash, id)
if err != nil {
return fmt.Errorf("update auth credentials: %w", err)
}
return nil
}
// CreateSession stores a hash of a session token until expiresAt.
func (s *Store) CreateSession(ctx context.Context, userID int64, tokenHash string, expiresAt time.Time) error {
if err := s.validate(); err != nil {
return err
}
_, err := s.pool.Exec(ctx, `
INSERT INTO auth_sessions (user_id, token_hash, expires_at)
VALUES ($1, $2, $3)
`, userID, tokenHash, expiresAt)
if err != nil {
return fmt.Errorf("create auth session: %w", err)
}
return nil
}
// FindSessionUser resolves an unexpired session to its user.
func (s *Store) FindSessionUser(ctx context.Context, tokenHash string) (*User, error) {
if err := s.validate(); err != nil {
return nil, err
}
return s.find(ctx, `
SELECT u.id, u.username, u.email, u.password_hash, u.created_at, u.updated_at
FROM auth_sessions s
JOIN auth_users u ON u.id = s.user_id
WHERE s.token_hash = $1 AND s.expires_at > now()
`, tokenHash)
}
// DeleteSession removes one session, typically during logout.
func (s *Store) DeleteSession(ctx context.Context, tokenHash string) error {
if err := s.validate(); err != nil {
return err
}
if _, err := s.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE token_hash = $1`, tokenHash); err != nil {
return fmt.Errorf("delete auth session: %w", err)
}
return nil
}
// DeleteSessionsForUser invalidates all sessions after credential changes.
func (s *Store) DeleteSessionsForUser(ctx context.Context, userID int64) error {
if err := s.validate(); err != nil {
return err
}
if _, err := s.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE user_id = $1`, userID); err != nil {
return fmt.Errorf("delete auth sessions for user: %w", err)
}
return nil
}
// DeleteExpiredSessions performs the periodic session cleanup shared by the
// services. A caller can run it from its own scheduler.
func (s *Store) DeleteExpiredSessions(ctx context.Context) error {
if err := s.validate(); err != nil {
return err
}
if _, err := s.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE expires_at < now()`); err != nil {
return fmt.Errorf("delete expired auth sessions: %w", err)
}
return nil
}
var ErrUserExists = errors.New("auth user already exists")
func (s *Store) validate() error {
if s == nil || s.pool == nil {
return errors.New("auth store has no postgres pool")
}
return nil
}
func (s *Store) find(ctx context.Context, query string, arg any) (*User, error) {
var user User
err := s.pool.QueryRow(ctx, query, arg).Scan(
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.CreatedAt, &user.UpdatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("find auth user: %w", err)
}
return &user, nil
}
+37
View File
@@ -0,0 +1,37 @@
package auth
import (
"testing"
"golang.org/x/crypto/bcrypt"
)
func TestPasswordRoundTrip(t *testing.T) {
hash, err := HashPassword("correct horse battery staple")
if err != nil {
t.Fatalf("HashPassword() error = %v", err)
}
if !VerifyPassword(hash, "correct horse battery staple") {
t.Fatal("VerifyPassword() rejected the original password")
}
if VerifyPassword(hash, "wrong password") {
t.Fatal("VerifyPassword() accepted the wrong password")
}
if cost, err := bcrypt.Cost([]byte(hash)); err != nil || cost != BcryptCost {
t.Fatalf("bcrypt cost = %d, error = %v; want %d", cost, err, BcryptCost)
}
}
func TestNewSessionToken(t *testing.T) {
raw, hash, err := NewSessionToken()
if err != nil {
t.Fatalf("NewSessionToken() error = %v", err)
}
if raw == "" || hash == "" {
t.Fatal("NewSessionToken() returned an empty token or hash")
}
if got := HashToken(raw); got != hash {
diff := got
t.Fatalf("HashToken(raw) = %q, want %q", diff, hash)
}
}
+25
View File
@@ -0,0 +1,25 @@
package auth
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
)
// NewSessionToken creates a random bearer token and its SHA-256 storage hash.
// Store only the hash; return the raw token to the caller that sets the cookie
// or authorization header.
func NewSessionToken() (raw string, hash string, err error) {
bytes := make([]byte, 32)
if _, err := rand.Read(bytes); err != nil {
return "", "", err
}
raw = base64.RawURLEncoding.EncodeToString(bytes)
return raw, HashToken(raw), nil
}
// HashToken creates the stable database key for a raw session/API token.
func HashToken(raw string) string {
sum := sha256.Sum256([]byte(raw))
return base64.RawURLEncoding.EncodeToString(sum[:])
}
+71
View File
@@ -0,0 +1,71 @@
// Package config contains small, dependency-free environment helpers shared
// by the Go services. It intentionally does not define an application's full
// configuration struct.
package config
import (
"fmt"
"os"
"strconv"
"strings"
"time"
)
// String returns the environment value or fallback when the variable is empty.
func String(key, fallback string) string {
if value := strings.TrimSpace(os.Getenv(key)); value != "" {
return value
}
return fallback
}
// Required returns a trimmed environment value or an actionable error.
func Required(key string) (string, error) {
value := strings.TrimSpace(os.Getenv(key))
if value == "" {
return "", fmt.Errorf("%s is required", key)
}
return value, nil
}
// Bool returns a parsed boolean environment value or fallback for an unset or
// invalid value. Invalid values are deliberately non-fatal for optional flags.
func Bool(key string, fallback bool) bool {
value := strings.TrimSpace(os.Getenv(key))
if value == "" {
return fallback
}
parsed, err := strconv.ParseBool(value)
if err != nil {
return fallback
}
return parsed
}
// Int returns a parsed integer environment value or fallback for an unset or
// invalid value. Callers should validate application-specific ranges.
func Int(key string, fallback int) int {
value := strings.TrimSpace(os.Getenv(key))
if value == "" {
return fallback
}
parsed, err := strconv.Atoi(value)
if err != nil {
return fallback
}
return parsed
}
// Duration returns a parsed duration environment value or fallback for an
// unset or invalid value.
func Duration(key string, fallback time.Duration) time.Duration {
value := strings.TrimSpace(os.Getenv(key))
if value == "" {
return fallback
}
parsed, err := time.ParseDuration(value)
if err != nil {
return fallback
}
return parsed
}
+20
View File
@@ -0,0 +1,20 @@
module repos.gfranz.ch/Gabriel20xx/SharedCode/backend
go 1.25.7
require (
github.com/jackc/pgx/v5 v5.10.0
github.com/pressly/goose/v3 v3.27.3
golang.org/x/crypto v0.54.0
)
require (
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/mfridman/interpolate v0.0.2 // indirect
github.com/sethvargo/go-retry v0.4.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/sync v0.22.0 // indirect
golang.org/x/text v0.40.0 // indirect
)
+56
View File
@@ -0,0 +1,56 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/mattn/go-isatty v0.0.23 h1:cYwCQTQf3HB6xUC+BtyCLZNr7IzbOmoZbmssVNzSyiQ=
github.com/mattn/go-isatty v0.0.23/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pressly/goose/v3 v3.27.3 h1:pIglVHjw99r4e/hDHHwbl9vfOsDMqUokfkXo6+n/RxA=
github.com/pressly/goose/v3 v3.27.3/go.mod h1:Dag+xpV6o20HR2LFY1j0q6MDwc3f7vPUFDA77R+0yGY=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/sethvargo/go-retry v0.4.0 h1:9qy1OoIAxBL+gBYnkTnTnWle5wlfsXQlwRzIbbpdqPw=
github.com/sethvargo/go-retry v0.4.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/libc v1.74.3 h1:a4J+Z8aVaxPyjyxRAdJzw246PqpcFGvVPnfT/AuM5Ws=
modernc.org/libc v1.74.3/go.mod h1:4H7h/MJ8wnjL8RAbp9v3OXgnk22X7MouHIhDbvP3gj4=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/sqlite v1.54.0 h1:JCxR4qwkJvOaqAoYcgDoO25Nc+ROg6EJ2LfBVzdrgog=
modernc.org/sqlite v1.54.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw=
+42
View File
@@ -0,0 +1,42 @@
// Package migrate provides a small embedded-filesystem wrapper around Goose.
// Applications still own their SQL files and migration policy.
package migrate
import (
"context"
"database/sql"
"fmt"
"io/fs"
_ "github.com/jackc/pgx/v5/stdlib"
"github.com/pressly/goose/v3"
)
// Up applies all pending PostgreSQL migrations in migrationsFS/dir. The
// filesystem is normally an embed.FS supplied by the consuming application.
func Up(ctx context.Context, databaseURL string, migrationsFS fs.FS, dir string) error {
if databaseURL == "" {
return fmt.Errorf("database URL is required")
}
if migrationsFS == nil {
return fmt.Errorf("migration filesystem is required")
}
db, err := sql.Open("pgx", databaseURL)
if err != nil {
return fmt.Errorf("open migration database: %w", err)
}
defer db.Close()
if err := db.PingContext(ctx); err != nil {
return fmt.Errorf("ping migration database: %w", err)
}
goose.SetBaseFS(migrationsFS)
if err := goose.SetDialect("postgres"); err != nil {
return fmt.Errorf("set migration dialect: %w", err)
}
if err := goose.UpContext(ctx, db, dir); err != nil {
return fmt.Errorf("run migrations: %w", err)
}
return nil
}
+153
View File
@@ -0,0 +1,153 @@
// Package postgres centralizes PostgreSQL pool creation and the small pieces
// of error/transaction handling that are repeated by the Go services.
package postgres
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"repos.gfranz.ch/Gabriel20xx/SharedCode/backend/config"
)
// Config controls a shared pgx connection pool. URL is normally read from
// DATABASE_URL with FromEnv.
type Config struct {
URL string
MaxConns int32
MinConns int32
MaxConnLifetime time.Duration
MaxConnIdleTime time.Duration
HealthCheckPeriod time.Duration
ConnectTimeout time.Duration
}
// DefaultConfig returns sensible defaults for a small self-hosted service.
func DefaultConfig(url string) Config {
return Config{
URL: strings.TrimSpace(url),
MaxConns: 20,
MinConns: 0,
MaxConnLifetime: time.Hour,
MaxConnIdleTime: 30 * time.Minute,
HealthCheckPeriod: 30 * time.Second,
ConnectTimeout: 10 * time.Second,
}
}
// FromEnv loads DATABASE_URL and optional pool settings. Duration values use
// Go duration syntax, for example 30s or 1h. Invalid optional values fall back
// to defaults; the URL is the only required setting.
func FromEnv() (Config, error) {
url, err := config.Required("DATABASE_URL")
if err != nil {
return Config{}, err
}
cfg := DefaultConfig(url)
cfg.MaxConns = int32(config.Int("DATABASE_MAX_CONNS", int(cfg.MaxConns)))
cfg.MinConns = int32(config.Int("DATABASE_MIN_CONNS", int(cfg.MinConns)))
cfg.MaxConnLifetime = config.Duration("DATABASE_MAX_CONN_LIFETIME", cfg.MaxConnLifetime)
cfg.MaxConnIdleTime = config.Duration("DATABASE_MAX_CONN_IDLE_TIME", cfg.MaxConnIdleTime)
cfg.HealthCheckPeriod = config.Duration("DATABASE_HEALTH_CHECK_PERIOD", cfg.HealthCheckPeriod)
cfg.ConnectTimeout = config.Duration("DATABASE_CONNECT_TIMEOUT", cfg.ConnectTimeout)
if cfg.MaxConns < 1 {
return Config{}, fmt.Errorf("DATABASE_MAX_CONNS must be at least 1")
}
if cfg.MinConns < 0 || cfg.MinConns > cfg.MaxConns {
return Config{}, fmt.Errorf("DATABASE_MIN_CONNS must be between 0 and DATABASE_MAX_CONNS")
}
if cfg.ConnectTimeout <= 0 {
return Config{}, fmt.Errorf("DATABASE_CONNECT_TIMEOUT must be greater than 0")
}
return cfg, nil
}
// Open creates and verifies a PostgreSQL pool. A failed ping closes the pool
// before returning so callers do not leak connections during startup errors.
func Open(ctx context.Context, cfg Config) (*pgxpool.Pool, error) {
if strings.TrimSpace(cfg.URL) == "" {
return nil, errors.New("postgres URL is required")
}
poolConfig, err := pgxpool.ParseConfig(cfg.URL)
if err != nil {
return nil, fmt.Errorf("parse postgres URL: %w", err)
}
if cfg.MaxConns > 0 {
poolConfig.MaxConns = cfg.MaxConns
}
if cfg.MinConns >= 0 {
poolConfig.MinConns = cfg.MinConns
}
if cfg.MaxConnLifetime > 0 {
poolConfig.MaxConnLifetime = cfg.MaxConnLifetime
}
if cfg.MaxConnIdleTime > 0 {
poolConfig.MaxConnIdleTime = cfg.MaxConnIdleTime
}
if cfg.HealthCheckPeriod > 0 {
poolConfig.HealthCheckPeriod = cfg.HealthCheckPeriod
}
if cfg.ConnectTimeout > 0 {
poolConfig.ConnConfig.ConnectTimeout = cfg.ConnectTimeout
}
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
if err != nil {
return nil, fmt.Errorf("create postgres pool: %w", err)
}
if err := pool.Ping(ctx); err != nil {
pool.Close()
return nil, fmt.Errorf("ping postgres: %w", err)
}
return pool, nil
}
// WithTx runs fn in a transaction and rolls back on all error paths.
func WithTx(ctx context.Context, pool *pgxpool.Pool, fn func(pgx.Tx) error) error {
if pool == nil {
return errors.New("postgres pool is nil")
}
if fn == nil {
return errors.New("postgres transaction callback is nil")
}
tx, err := pool.Begin(ctx)
if err != nil {
return fmt.Errorf("begin postgres transaction: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
if err := fn(tx); err != nil {
return err
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("commit postgres transaction: %w", err)
}
return nil
}
// IsNoRows reports whether err is pgx's not-found sentinel.
func IsNoRows(err error) bool {
return errors.Is(err, pgx.ErrNoRows)
}
// IsUniqueViolation reports a PostgreSQL unique/exclusion constraint error.
func IsUniqueViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && (pgErr.Code == "23505" || pgErr.Code == "23P01")
}
// IsForeignKeyViolation reports a PostgreSQL foreign-key constraint error.
func IsForeignKeyViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23503"
}
+31
View File
@@ -0,0 +1,31 @@
package postgres
import (
"os"
"testing"
)
func TestFromEnvRequiresDatabaseURL(t *testing.T) {
t.Setenv("DATABASE_URL", "")
if _, err := FromEnv(); err == nil {
t.Fatal("FromEnv() returned nil error without DATABASE_URL")
}
}
func TestFromEnvLoadsPoolSettings(t *testing.T) {
t.Setenv("DATABASE_URL", "postgres://user:password@localhost:5432/app")
t.Setenv("DATABASE_MAX_CONNS", "7")
t.Setenv("DATABASE_MIN_CONNS", "2")
defer func() {
_ = os.Unsetenv("DATABASE_MAX_CONNS")
_ = os.Unsetenv("DATABASE_MIN_CONNS")
}()
cfg, err := FromEnv()
if err != nil {
t.Fatalf("FromEnv() error = %v", err)
}
if cfg.MaxConns != 7 || cfg.MinConns != 2 {
t.Fatalf("pool limits = (%d, %d), want (7, 2)", cfg.MaxConns, cfg.MinConns)
}
}