v0.3.0 storage with sqlite3 and pid management added

This commit is contained in:
2025-10-30 09:52:23 -04:00
parent 0ad608293e
commit b79900b1bf
18 changed files with 1570 additions and 69 deletions

131
cmd/chessd/cli/cli.go Normal file
View File

@ -0,0 +1,131 @@
// FILE: cmd/chessd/cli/cli.go
package cli
import (
"chess/internal/storage"
"flag"
"fmt"
"os"
"strings"
"text/tabwriter"
)
// Run is the entry point for the CLI mini-app
func Run(args []string) error {
if len(args) == 0 {
return fmt.Errorf("subcommand required: init, delete, or query")
}
switch args[0] {
case "init":
return runInit(args[1:])
case "delete":
return runDelete(args[1:])
case "query":
return runQuery(args[1:])
default:
return fmt.Errorf("unknown subcommand: %s", args[0])
}
}
func runInit(args []string) error {
fs := flag.NewFlagSet("init", flag.ContinueOnError)
path := fs.String("path", "", "Database file path (required)")
if err := fs.Parse(args); err != nil {
return err
}
if *path == "" {
return fmt.Errorf("database path required")
}
store, err := storage.NewStore(*path, false)
if err != nil {
return fmt.Errorf("failed to create store: %w", err)
}
defer store.Close()
if err := store.InitDB(); err != nil {
return fmt.Errorf("failed to initialize database: %w", err)
}
fmt.Printf("Database initialized at: %s\n", *path)
return nil
}
func runDelete(args []string) error {
fs := flag.NewFlagSet("delete", flag.ContinueOnError)
path := fs.String("path", "", "Database file path (required)")
if err := fs.Parse(args); err != nil {
return err
}
if *path == "" {
return fmt.Errorf("database path required")
}
store, err := storage.NewStore(*path, false)
if err != nil {
return fmt.Errorf("failed to open store: %w", err)
}
if err := store.DeleteDB(); err != nil {
return fmt.Errorf("failed to delete database: %w", err)
}
fmt.Printf("Database deleted: %s\n", *path)
return nil
}
func runQuery(args []string) error {
fs := flag.NewFlagSet("query", flag.ContinueOnError)
path := fs.String("path", "", "Database file path (required)")
gameID := fs.String("gameId", "", "Game ID to filter (optional, * for all)")
playerID := fs.String("playerId", "", "Player ID to filter (optional, * for all)")
if err := fs.Parse(args); err != nil {
return err
}
if *path == "" {
return fmt.Errorf("database path required")
}
store, err := storage.NewStore(*path, false)
if err != nil {
return fmt.Errorf("failed to open store: %w", err)
}
defer store.Close()
games, err := store.QueryGames(*gameID, *playerID)
if err != nil {
return fmt.Errorf("query failed: %w", err)
}
if len(games) == 0 {
fmt.Println("No games found")
return nil
}
// Print results in tabular format
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
fmt.Fprintln(w, "Game ID\tWhite Player\tBlack Player\tStart Time")
fmt.Fprintln(w, strings.Repeat("-", 80))
for _, g := range games {
whiteInfo := fmt.Sprintf("%s (T%d)", g.WhitePlayerID[:8], g.WhiteType)
blackInfo := fmt.Sprintf("%s (T%d)", g.BlackPlayerID[:8], g.BlackType)
fmt.Fprintf(w, "%s\t%s\t%s\t%s\n",
g.GameID[:8]+"...",
whiteInfo,
blackInfo,
g.StartTimeUTC.Format("2006-01-02 15:04:05"),
)
}
w.Flush()
fmt.Printf("\nFound %d game(s)\n", len(games))
return nil
}

View File

@ -2,6 +2,11 @@
package main
import (
"chess/cmd/chessd/cli"
"chess/internal/http"
"chess/internal/processor"
"chess/internal/service"
"chess/internal/storage"
"flag"
"fmt"
"log"
@ -9,29 +14,69 @@ import (
"os/signal"
"syscall"
"time"
"chess/internal/http"
"chess/internal/processor"
"chess/internal/service"
)
func main() {
// Check for CLI database commands
if len(os.Args) > 1 && os.Args[1] == "db" {
if err := cli.Run(os.Args[2:]); err != nil {
log.Fatalf("CLI error: %v", err)
}
os.Exit(0)
}
// Command-line flags
var (
host = flag.String("host", "localhost", "Server host")
port = flag.Int("port", 8080, "Server port")
dev = flag.Bool("dev", false, "Development mode (relaxed rate limits)")
host = flag.String("host", "localhost", "Server host")
port = flag.Int("port", 8080, "Server port")
dev = flag.Bool("dev", false, "Development mode (relaxed rate limits)")
storagePath = flag.String("storage-path", "", "Path to SQLite database file (disables persistence if empty)")
pidPath = flag.String("pid", "", "Optional path to write PID file")
pidLock = flag.Bool("pid-lock", false, "Lock PID file to allow only one instance (requires -pid)")
)
flag.Parse()
// 1. Initialize the Service (Pure State Manager)
svc, err := service.New()
// Validate PID flags
if *pidLock && *pidPath == "" {
log.Fatal("Error: -pid-lock flag requires the -pid flag to be set")
}
// Manage PID file if requested
if *pidPath != "" {
cleanup, err := managePIDFile(*pidPath, *pidLock)
if err != nil {
log.Fatalf("Failed to manage PID file: %v", err)
}
defer cleanup()
log.Printf("PID file created at: %s (lock: %v)", *pidPath, *pidLock)
}
// 1. Initialize Storage (optional)
var store *storage.Store
if *storagePath != "" {
log.Printf("Initializing persistent storage at: %s", *storagePath)
var err error
store, err = storage.NewStore(*storagePath, *dev) // CHANGED: Added *dev parameter
if err != nil {
log.Fatalf("Failed to initialize storage: %v", err)
}
defer func() {
if err := store.Close(); err != nil {
log.Printf("Warning: failed to close storage cleanly: %v", err)
}
}()
} else {
log.Printf("Persistent storage disabled (use -storage-path to enable)")
}
// 2. Initialize the Service with optional storage
svc, err := service.New(store)
if err != nil {
log.Fatalf("Failed to initialize service: %v", err)
}
defer svc.Close()
// 2. Initialize the Processor (Orchestrator), injecting the service
// 3. Initialize the Processor (Orchestrator), injecting the service
proc, err := processor.New(svc)
if err != nil {
log.Fatalf("Failed to initialize processor: %v", err)
@ -42,8 +87,8 @@ func main() {
}
}()
// 3. Initialize the Fiber App/HTTP Handler, injecting the processor
app := http.NewFiberApp(proc, *dev)
// 4. Initialize the Fiber App/HTTP Handler, injecting processor and service
app := http.NewFiberApp(proc, svc, *dev)
// Server configuration
addr := fmt.Sprintf("%s:%d", *host, *port)
@ -54,9 +99,14 @@ func main() {
log.Printf("Listening on: http://%s", addr)
log.Printf("API Version: v1")
if *dev {
log.Printf("Rate Limit: 10 requests/second per IP (DEV MODE)")
log.Printf("Rate Limit: 20 requests/second per IP (DEV MODE)")
} else {
log.Printf("Rate Limit: 1 request/second per IP")
log.Printf("Rate Limit: 10 requests/second per IP")
}
if *storagePath != "" {
log.Printf("Storage: Enabled (%s)", *storagePath)
} else {
log.Printf("Storage: Disabled")
}
log.Printf("Endpoints: http://%s/api/v1/games", addr)
log.Printf("Health: http://%s/health", addr)

106
cmd/chessd/pid.go Normal file
View File

@ -0,0 +1,106 @@
// FILE: cmd/chessd/pid.go
package main
import (
"errors"
"fmt"
"os"
"strconv"
"strings"
"syscall"
)
// managePIDFile creates and manages a PID file with optional locking.
// Returns a cleanup function that must be called on exit.
func managePIDFile(path string, lock bool) (func(), error) {
// Open/create PID file with exclusive create first attempt
file, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
if err != nil {
if !os.IsExist(err) {
return nil, fmt.Errorf("cannot create PID file: %w", err)
}
// File exists - check if stale
if lock {
if err := checkStalePID(path); err != nil {
return nil, err
}
}
// Reopen for writing (truncate existing content)
file, err = os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
return nil, fmt.Errorf("cannot open PID file: %w", err)
}
}
// Acquire exclusive lock if requested
if lock {
if err = syscall.Flock(int(file.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
file.Close()
if errors.Is(err, syscall.EWOULDBLOCK) {
return nil, fmt.Errorf("cannot acquire lock: another instance is running")
}
return nil, fmt.Errorf("lock failed: %w", err)
}
}
// Write current PID
pid := os.Getpid()
if _, err = fmt.Fprintf(file, "%d\n", pid); err != nil {
file.Close()
os.Remove(path)
return nil, fmt.Errorf("cannot write PID: %w", err)
}
// Sync to ensure PID is written
if err = file.Sync(); err != nil {
file.Close()
os.Remove(path)
return nil, fmt.Errorf("cannot sync PID file: %w", err)
}
// Return cleanup function
cleanup := func() {
if lock {
// Release lock explicitly, file close works too
syscall.Flock(int(file.Fd()), syscall.LOCK_UN)
}
file.Close()
os.Remove(path)
}
return cleanup, nil
}
// checkStalePID reads an existing PID file and checks if the process is running
func checkStalePID(path string) error {
// Try to read existing PID
data, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf("cannot read existing PID file: %w", err)
}
pidStr := string(data)
pid, err := strconv.Atoi(strings.TrimSpace(pidStr))
if err != nil {
// Corrupted PID file
return fmt.Errorf("corrupted PID file (contains: %q)", pidStr)
}
// Check if process exists using kill(0), never errors on Unix
proc, _ := os.FindProcess(pid)
// Send signal 0 to check if process exists
if err = proc.Signal(syscall.Signal(0)); err != nil {
// Process doesn't exist or we don't have permission
if errors.Is(err, os.ErrProcessDone) || errors.Is(err, syscall.ESRCH) {
return fmt.Errorf("stale PID file found for defunct process %d", pid)
}
// Process exists but we can't signal it (different user?)
return fmt.Errorf("process %d exists but cannot verify ownership: %v", pid, err)
}
// Process is running
return fmt.Errorf("stale PID file: process %d is running but not holding lock", pid)
}