Add SQLite persistence and write-through gRPC mutations
Database (internal/db) stores listeners, routes, and firewall rules with WAL mode, foreign keys, and idempotent migrations. First run seeds from TOML config; subsequent runs load from DB as source of truth. gRPC admin API now writes to the database before updating in-memory state (write-through cache pattern). Adds snapshot command for VACUUM INTO backups. Refactors firewall.New to accept raw rule slices instead of config struct for flexibility. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
56
internal/db/seed.go
Normal file
56
internal/db/seed.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"git.wntrmute.dev/kyle/mc-proxy/internal/config"
|
||||
)
|
||||
|
||||
// Seed populates the database from TOML config data. Only called when the
|
||||
// database is empty (first run).
|
||||
func (s *Store) Seed(listeners []config.Listener, fw config.Firewall) error {
|
||||
tx, err := s.db.Begin()
|
||||
if err != nil {
|
||||
return fmt.Errorf("beginning seed transaction: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
for _, l := range listeners {
|
||||
result, err := tx.Exec("INSERT INTO listeners (addr) VALUES (?)", l.Addr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("seeding listener %q: %w", l.Addr, err)
|
||||
}
|
||||
listenerID, _ := result.LastInsertId()
|
||||
|
||||
for _, r := range l.Routes {
|
||||
_, err := tx.Exec(
|
||||
"INSERT INTO routes (listener_id, hostname, backend) VALUES (?, ?, ?)",
|
||||
listenerID, strings.ToLower(r.Hostname), r.Backend,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("seeding route %q on listener %q: %w", r.Hostname, l.Addr, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, ip := range fw.BlockedIPs {
|
||||
if _, err := tx.Exec("INSERT INTO firewall_rules (type, value) VALUES ('ip', ?)", ip); err != nil {
|
||||
return fmt.Errorf("seeding blocked IP %q: %w", ip, err)
|
||||
}
|
||||
}
|
||||
|
||||
for _, cidr := range fw.BlockedCIDRs {
|
||||
if _, err := tx.Exec("INSERT INTO firewall_rules (type, value) VALUES ('cidr', ?)", cidr); err != nil {
|
||||
return fmt.Errorf("seeding blocked CIDR %q: %w", cidr, err)
|
||||
}
|
||||
}
|
||||
|
||||
for _, code := range fw.BlockedCountries {
|
||||
if _, err := tx.Exec("INSERT INTO firewall_rules (type, value) VALUES ('country', ?)", strings.ToUpper(code)); err != nil {
|
||||
return fmt.Errorf("seeding blocked country %q: %w", code, err)
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
}
|
||||
Reference in New Issue
Block a user