diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..03d2684b --- /dev/null +++ b/.dockerignore @@ -0,0 +1,40 @@ +# flyctl launch added from .gitignore +# If you prefer the allow list template instead of the deny list, see community template: +# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore + +# SQLite database files +**/*.db + +# Binaries for programs and plugins +**/bin +**/*.exe +**/*.exe~ +**/*.dll +**/*.so +**/*.dylib + +# Test binary, built with `go test -c` +**/*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +**/*.out + +# Dependency directories (remove the comment below to include it) +**/vendor + +# Go workspace file +**/go.work +**/*.sqlite + +# Nix related +**/.direnv +**/result + +# Build artifact generated by Makefile +**/.generate.marker + +**/tmp + +**/.env +**/.DS_Store +fly.toml diff --git a/.github/workflows/fly-deploy.yml b/.github/workflows/fly-deploy.yml new file mode 100644 index 00000000..b0c246ed --- /dev/null +++ b/.github/workflows/fly-deploy.yml @@ -0,0 +1,18 @@ +# See https://fly.io/docs/app-guides/continuous-deployment-with-github-actions/ + +name: Fly Deploy +on: + push: + branches: + - main +jobs: + deploy: + name: Deploy app + runs-on: ubuntu-latest + concurrency: deploy-group # optional: ensure only one action runs at a time + steps: + - uses: actions/checkout@v4 + - uses: superfly/flyctl-actions/setup-flyctl@master + - run: flyctl deploy --remote-only + env: + FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN }} diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..e2462c31 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,21 @@ +ARG GO_VERSION=1 +FROM golang:${GO_VERSION}-bookworm AS builder + +WORKDIR /usr/src/app +COPY go.mod go.sum ./ +RUN go mod download && go mod verify +COPY . . +RUN go build -v -o /run-app ./cmd/acmcsuf-api + + +FROM debian:bookworm + +COPY --from=builder /run-app /usr/local/bin/ +RUN apt-get update \ + && apt-get install -y --no-install-recommends ca-certificates \ + && rm -rf /var/lib/apt/lists/* \ + && mkdir -p /app/data +WORKDIR /app +COPY --from=builder /usr/src/app/sql/migrations ./sql/migrations +EXPOSE 8080 +CMD ["run-app"] diff --git a/Makefile b/Makefile index 94433eb4..a1a91ea4 100644 --- a/Makefile +++ b/Makefile @@ -22,13 +22,13 @@ api: $(BIN_DIR)/$(API_NAME) ## Build the api binary $(BIN_DIR)/$(API_NAME): $(GO_DEPS) sqlc @mkdir -p $(BIN_DIR) - go build -x -ldflags "-X main.Version=$(VERSION)" -o $(BIN_DIR)/$(API_NAME) ./cmd/$(API_NAME) + go build -ldflags "-X main.Version=$(VERSION)" -o $(BIN_DIR)/$(API_NAME) ./cmd/$(API_NAME) cli: $(BIN_DIR)/$(CLI_NAME) ## Build the cli binary $(BIN_DIR)/$(CLI_NAME): $(GO_DEPS) @mkdir -p $(BIN_DIR) - go build -x -ldflags "-X cli.Version=$(VERSION)" -o $(BIN_DIR)/$(CLI_NAME) ./cmd/$(CLI_NAME) + go build -ldflags "-X cli.Version=$(VERSION)" -o $(BIN_DIR)/$(CLI_NAME) ./cmd/$(CLI_NAME) generate: swag sqlc ## Generate all necessary files diff --git a/README.md b/README.md index 029ecfe7..e51e387b 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,20 @@ Use "acmcsuf-cli [command] --help" for more information about a command. ``` #### Configuring the CLI -The CLI's auth-related configuration is currently handled via environment variables similarly to the API. Other settings can be configured by modifiying the config file, located at `~/.config/acmcsuf-cli/config.json`. +The CLI's auth-related configuration is currently handled via environment variables similarly to the API. Other settings can be configured by modifying `~/.config/acmcsuf-cli/config.json`: + +```json +{ + "api_url": "http://localhost:8080", + "log_level": "info" +} +``` + +Override the configured API for one command with `--api-url`, for example: + +```sh +acmcsuf-cli events post --api-url https://api-acmcsuf-com-black-wind-9210.fly.dev +``` ### Other useful commands from the Makefile diff --git a/docs/docker.md b/docs/docker.md new file mode 100644 index 00000000..c358fdec --- /dev/null +++ b/docs/docker.md @@ -0,0 +1,14 @@ +# Useful docker commands + +```sh +# build +docker build -t acmcsuf-api:latest . + +# run +docker run --rm \ +--name acmcsuf-api \ +--mount type=volume,source=sqlite_data,target=/app/data \ +-p 8080:8080 \ +acmcsuf-api:latest + +``` diff --git a/fly.toml b/fly.toml new file mode 100644 index 00000000..678725d5 --- /dev/null +++ b/fly.toml @@ -0,0 +1,34 @@ +# fly.toml app configuration file generated for api-acmcsuf-com-black-wind-9210 on 2026-08-01T19:15:18-07:00 +# +# See https://fly.io/docs/reference/configuration/ for information about how to use this file. +# + +app = 'api-acmcsuf-com-black-wind-9210' +primary_region = 'lax' + +[build] + [build.args] + GO_VERSION = '1.25.0' + +[env] + PORT = '8080' + DATABASE_URL= 'file:/app/data/acmcsuf.db?cache=shared&mode=rwc' + GIN_MODE = 'debug' + ENV = 'development' + +[http_service] + internal_port = 8080 + force_https = true + auto_stop_machines = 'stop' + auto_start_machines = true + min_machines_running = 1 + processes = ['app'] + +[[vm]] + memory = '256m' + cpu_kind = 'shared' + cpus = 1 + +[mounts] + source = "sqlite_data" + destination = "/app/data" diff --git a/internal/api/routes/v1.go b/internal/api/routes/v1.go index ee97bc24..2df9c4c4 100644 --- a/internal/api/routes/v1.go +++ b/internal/api/routes/v1.go @@ -24,7 +24,7 @@ func SetupV1(router *gin.Engine, eventService services.EventsServicer, var botSession *discordgo.Session var err error - if cfg.DiscordBotToken != "" { + if cfg.DiscordBotToken != "" && cfg.Env != "development" { botSession, err = discordgo.New("Bot " + cfg.DiscordBotToken) if err != nil { log.Fatalf("%v", err) diff --git a/internal/api/server.go b/internal/api/server.go index 760a51ba..d5d22c99 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -62,10 +62,10 @@ func Run(ctx context.Context) { go func() { serverAddr := ":" + cfg.Port - if cfg.Env == "development" { - // this binds the server to the loopback interface in dev mode for security reasons - serverAddr = "localhost:" + cfg.Port - } + // if cfg.Env == "development" { + // this binds the server to the loopback interface in dev mode for security reasons + // serverAddr = "localhost:" + cfg.Port + // } if err := router.Run(serverAddr); err != nil { log.Fatalf("Failed to start server: %v", err) diff --git a/internal/cli/client/client.go b/internal/cli/client/client.go index 4d0712a1..9dfcfcc8 100644 --- a/internal/cli/client/client.go +++ b/internal/cli/client/client.go @@ -42,10 +42,7 @@ func SendRequestAndReadResponse(url *url.URL, enableAuth bool, method string, bo func CheckConnection(url string) error { _, err := http.Get(url) if err != nil { - // fang/lipgloss lowk nukes this custom formatting - return fmt.Errorf("\x1b[1;37;41mUNABLE TO CONNECT\x1b[0m | %s\n\t↳ %v", - "Did you forget to start the server?", - err) + return fmt.Errorf("UNABLE TO CONNECT: %v", err) } return nil } diff --git a/internal/cli/command/root.go b/internal/cli/command/root.go index 3bd16c79..1fc30df9 100644 --- a/internal/cli/command/root.go +++ b/internal/cli/command/root.go @@ -28,8 +28,6 @@ const ( var Version = "dev" -var overrides *config.ConfigOverrides - var rootCmd = &cobra.Command{ Use: os.Args[0], Short: "A CLI tool to help manage the API of the CSUF ACM website", @@ -37,33 +35,21 @@ var rootCmd = &cobra.Command{ // init() is a special function that always gets run before main func init() { - overrides = &config.ConfigOverrides{ - Host: "", - Port: "", - } - - var err error - config.Cfg, err = config.Load(overrides) - if err != nil { - fmt.Printf("failed to load config: %s", err) - return - } - rootCmd.AddCommand(events.CLIEvents) rootCmd.AddCommand(officers.CLIOfficers) rootCmd.AddCommand(config.ConfigCmd) - rootCmd.PersistentFlags().String("host", "", "API server hostname (overrides config)") - rootCmd.PersistentFlags().String("port", "", "API server port (overrides config)") + rootCmd.PersistentFlags().String("api-url", "", "API base URL (overrides config)") rootCmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error { - overrides = &config.ConfigOverrides{ - Host: cmd.Flag("host").Value.String(), - Port: cmd.Flag("port").Value.String(), + apiURL, err := cmd.Flags().GetString("api-url") + if err != nil { + return fmt.Errorf("failed to read API URL flag: %w", err) } - config.Cfg, err = config.Load(overrides) + + config.Cfg, err = config.Load(apiURL) if err != nil { - return fmt.Errorf("failed to load config: %w", err) + return fmt.Errorf("failed to load API configuration: %w", err) } url := config.GetBaseURL(config.Cfg).JoinPath("health") diff --git a/internal/cli/config/commands.go b/internal/cli/config/commands.go index 0de0770a..fd05cdd3 100644 --- a/internal/cli/config/commands.go +++ b/internal/cli/config/commands.go @@ -8,8 +8,9 @@ import ( ) var ConfigCmd = &cobra.Command{ - Use: "config ", - Short: "Manage this tool's persistent configuration.", + Use: "config ", + Short: "Manage this tool's persistent configuration.", + PersistentPreRunE: func(cmd *cobra.Command, args []string) error { return nil }, } func init() { diff --git a/internal/cli/config/config.go b/internal/cli/config/config.go index 51e53df8..706d6c3a 100644 --- a/internal/cli/config/config.go +++ b/internal/cli/config/config.go @@ -9,26 +9,17 @@ import ( ) type Config struct { - Host string `json:"host"` - Port string `json:"port"` + APIURL string `json:"api_url"` LogLevel string `json:"log_level"` } -// Subset of Config struct that can be overridden with command line flags -type ConfigOverrides struct { - Host string - Port string -} - var defaultConfig = Config{ - Host: "localhost", - Port: "8080", + APIURL: "http://localhost:8080", LogLevel: "info", } // Global config variable var Cfg *Config -var CfgOverride ConfigOverrides func init() { Cfg = &Config{} @@ -37,12 +28,11 @@ func init() { // Loads config with three layers of precedence // 1. Start with default config // 2. Load values from config file if present -// 3. Provide any overrides passed in through command line flags (if any) -func Load(overrides *ConfigOverrides) (*Config, error) { +// 3. Apply the API URL override passed on the command line (if any) +func Load(apiURLOverride string) (*Config, error) { // Load default config cfg := &Config{ - Host: defaultConfig.Host, - Port: defaultConfig.Port, + APIURL: defaultConfig.APIURL, LogLevel: defaultConfig.LogLevel, } @@ -59,13 +49,15 @@ func Load(overrides *ConfigOverrides) (*Config, error) { } } - // Override with args passed with command line args - if overrides.Host != "" { - cfg.Host = overrides.Host + if apiURLOverride != "" { + cfg.APIURL = apiURLOverride } - if overrides.Port != "" { - cfg.Port = overrides.Port + + apiURL, err := NormalizeAPIURL(cfg.APIURL) + if err != nil { + return nil, err } + cfg.APIURL = apiURL return cfg, nil } diff --git a/internal/cli/config/url.go b/internal/cli/config/url.go index 17dd7b85..f10dc16e 100644 --- a/internal/cli/config/url.go +++ b/internal/cli/config/url.go @@ -3,12 +3,33 @@ package config import ( "fmt" "net/url" + "strings" ) -// Intended to be used with .JoinPath() to construct URLs with configured host:port +// Intended to be used with .JoinPath() to construct URLs func GetBaseURL(cfg *Config) *url.URL { - return &url.URL{ - Scheme: "http", - Host: fmt.Sprintf("%s:%s", cfg.Host, cfg.Port), + apiURL, _ := url.Parse(cfg.APIURL) + return apiURL +} + +func NormalizeAPIURL(rawURL string) (string, error) { + apiURL, err := url.Parse(strings.TrimSpace(rawURL)) + if err != nil { + return "", fmt.Errorf("invalid API URL: %w", err) + } + if apiURL.Scheme != "http" && apiURL.Scheme != "https" { + return "", fmt.Errorf("API URL must use http or https") + } + if apiURL.Host == "" { + return "", fmt.Errorf("API URL must include a host") } + if apiURL.User != nil || apiURL.RawQuery != "" || apiURL.Fragment != "" { + return "", fmt.Errorf("API URL must not include credentials, a query, or a fragment") + } + if apiURL.Path != "" && apiURL.Path != "/" { + return "", fmt.Errorf("API URL must not include a path") + } + + apiURL.Path = "" + return apiURL.String(), nil } diff --git a/nix/shell.nix b/nix/shell.nix index 5adb23b6..d81789da 100644 --- a/nix/shell.nix +++ b/nix/shell.nix @@ -15,6 +15,7 @@ sqlite, sqlite-web, nilaway, + flyctl, isCI ? false, full ? false, }: let @@ -38,6 +39,7 @@ in sqlite cobra-cli delve # Go debugger + flyctl ] # Heavyweight or rarely used tools go here ++ lib.optionals full [