The mailbox sync (Microsoft Graph and IMAP), its Claude classifier, the /email routes and the Settings page's email section are taken out while the pipeline is unused. The last commit with it is tagged email-pipeline-last; reverting this commit brings it back. The status rules the capture path shares (statusOrder, StatusAdvances, NormalizeStatus) move to job_status.go with their tests. ProcessedEmail stays in the migration, marked dormant, so its history survives for a restored pipeline. golang.org/x/oauth2 is no longer needed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
203 lines
7.2 KiB
Go
203 lines
7.2 KiB
Go
// Command jobtracker is the job application tracker: the applications list,
|
|
// the leads inbox, and the capture endpoints behind the browser userscript.
|
|
//
|
|
// It was split out of the adam-french.co.uk backend and is built to sit
|
|
// behind that site's nginx at /jobs/, borrowing its login (internal/auth).
|
|
// main is the single place everything is wired together: it reads every
|
|
// setting from the environment, builds the services, packs them into one
|
|
// handlers.Store, and registers the routes. README.md lists the variables.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/99designs/gqlgen/graphql/handler"
|
|
"github.com/99designs/gqlgen/graphql/handler/extension"
|
|
"github.com/99designs/gqlgen/graphql/handler/lru"
|
|
"github.com/99designs/gqlgen/graphql/handler/transport"
|
|
"github.com/99designs/gqlgen/graphql/playground"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/vektah/gqlparser/v2/ast"
|
|
|
|
"adam-french.co.uk/job-tracker/internal/auth"
|
|
"adam-french.co.uk/job-tracker/internal/claude"
|
|
"adam-french.co.uk/job-tracker/internal/graph"
|
|
"adam-french.co.uk/job-tracker/internal/handlers"
|
|
"adam-french.co.uk/job-tracker/internal/services"
|
|
)
|
|
|
|
func main() {
|
|
devMode := os.Getenv("DEV_MODE") == "true"
|
|
if !devMode {
|
|
gin.SetMode(gin.ReleaseMode)
|
|
}
|
|
|
|
// Everything is served under basePath, and nginx proxies it without
|
|
// stripping the prefix, so the app's own URLs and the ones the browser
|
|
// sees are the same. The SPA is built for /jobs/ (web/vite.config.js), so
|
|
// changing this means rebuilding it with a matching base.
|
|
basePath := strings.TrimRight(getenv("BASE_PATH", "/jobs"), "/")
|
|
// The Docker volume: the capture token.
|
|
dataDir := getenv("DATA_DIR", "/data")
|
|
// The built SPA, copied in by the Dockerfile.
|
|
staticDir := getenv("STATIC_DIR", "/app/static")
|
|
|
|
// AUTH
|
|
// Settled before anything else, so a bad mode fails fast.
|
|
// "forward" (the default) asks the main site; "dev" admits everyone and
|
|
// is refused outside DEV_MODE, so a stray setting cannot open the
|
|
// tracker in production.
|
|
var checker auth.Checker
|
|
switch mode := getenv("AUTH_MODE", "forward"); mode {
|
|
case "forward":
|
|
checker = auth.NewForward(getenv("AUTH_VALIDATE_URL", "http://backend:8080/auth/validate-admin"))
|
|
case "dev":
|
|
if !devMode {
|
|
log.Fatal("AUTH_MODE=dev is only allowed with DEV_MODE=true")
|
|
}
|
|
log.Println("[Auth] AUTH_MODE=dev: every request is treated as the admin")
|
|
checker = auth.AllowAll{}
|
|
default:
|
|
log.Fatalf("unknown AUTH_MODE %q (want forward or dev)", mode)
|
|
}
|
|
|
|
databaseURL := os.Getenv("DATABASE_URL")
|
|
if databaseURL == "" {
|
|
log.Fatal("DATABASE_URL is not set")
|
|
}
|
|
db, err := services.InitDatabase(databaseURL)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
if os.Getenv("SEED_DB") == "true" {
|
|
services.SeedDatabase(db)
|
|
}
|
|
|
|
// CLAUDE
|
|
// A missing key is not fatal: the tracker works without Claude, and each
|
|
// Claude feature reports the missing key when it is used.
|
|
claudeClient := claude.New(os.Getenv("CLAUDE_API_KEY"), os.Getenv("CLAUDE_MODEL"))
|
|
if os.Getenv("CLAUDE_API_KEY") == "" {
|
|
log.Println("[Claude] CLAUDE_API_KEY is not set: posting reading and lead scoring are off")
|
|
} else {
|
|
log.Printf("[Claude] using %s", claudeClient.Model())
|
|
}
|
|
|
|
// JOB LEADS
|
|
// Six hours by default: boards change a few times a day at most, and
|
|
// every run can spend Claude calls.
|
|
jobLeads := services.InitJobLeads(&services.JobLeadConfig{
|
|
Enabled: os.Getenv("JOB_LEADS_ENABLED") == "true",
|
|
Interval: duration("JOB_LEADS_INTERVAL", 6*time.Hour),
|
|
AdzunaAppID: os.Getenv("ADZUNA_APP_ID"),
|
|
AdzunaAppKey: os.Getenv("ADZUNA_APP_KEY"),
|
|
ReedAPIKey: os.Getenv("REED_API_KEY"),
|
|
}, db, claudeClient)
|
|
|
|
// JOB CAPTURE
|
|
// A damaged token file is logged, not fatal: capture stays off until a
|
|
// new token is generated on the settings page.
|
|
captureToken, err := services.InitCaptureToken(filepath.Join(dataDir, services.CaptureTokenFile))
|
|
if err != nil {
|
|
log.Println("Job capture token not loaded:", err)
|
|
}
|
|
|
|
store := handlers.Store{DB: db, JobLeads: jobLeads, Extractor: claudeClient, CaptureToken: captureToken}
|
|
|
|
r := gin.New()
|
|
r.Use(gin.Logger(), gin.Recovery())
|
|
// Nothing here keys on the client's IP, so no proxy is trusted to
|
|
// report one.
|
|
if err := r.SetTrustedProxies(nil); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
api := r.Group(basePath + "/api")
|
|
admin := api.Group("", auth.Require(checker))
|
|
|
|
api.GET("/health", func(ctx *gin.Context) {
|
|
if sqlDB, err := db.DB(); err != nil || sqlDB.PingContext(ctx.Request.Context()) != nil {
|
|
ctx.JSON(503, gin.H{"status": "database unreachable"})
|
|
return
|
|
}
|
|
ctx.JSON(200, gin.H{"status": "ok"})
|
|
})
|
|
|
|
// JOB CAPTURE: called by the browser userscript from other origins, so
|
|
// these authenticate with a bearer token instead of the session cookies.
|
|
capture := api.Group("/capture", store.CaptureTokenMiddleware)
|
|
capture.GET("/status", store.JobCaptureStatus)
|
|
capture.POST("/extract", store.JobCaptureExtract)
|
|
capture.POST("", store.JobCapture)
|
|
|
|
// The capture token is managed with the session, never with the token
|
|
// itself.
|
|
admin.GET("/admin/capture-token", store.GetCaptureToken)
|
|
admin.POST("/admin/capture-token", store.GenerateCaptureToken)
|
|
admin.DELETE("/admin/capture-token", store.RevokeCaptureToken)
|
|
|
|
// GRAPHQL
|
|
// auth.Annotate records whether the caller is the admin without refusing
|
|
// anything; the @admin directive on each field does the refusing, so a
|
|
// client gets the usual GraphQL error rather than a bare 401. Every
|
|
// field in the schema carries it (graph/directives_test.go).
|
|
gqlSrv := handler.New(graph.NewExecutableSchema(graph.Config{
|
|
Resolvers: &graph.Resolver{Store: &store},
|
|
Directives: graph.Directives(),
|
|
}))
|
|
gqlSrv.AddTransport(transport.Options{})
|
|
gqlSrv.AddTransport(transport.POST{})
|
|
gqlSrv.SetQueryCache(lru.New[*ast.QueryDocument](1000))
|
|
gqlSrv.Use(extension.FixedComplexityLimit(200))
|
|
if devMode && os.Getenv("GQL_INTROSPECTION") == "true" {
|
|
gqlSrv.Use(extension.Introspection{})
|
|
}
|
|
api.POST("/graphql", auth.Annotate(checker), func(ctx *gin.Context) {
|
|
gqlSrv.ServeHTTP(ctx.Writer, ctx.Request)
|
|
})
|
|
if devMode && os.Getenv("GQL_PLAYGROUND") == "true" {
|
|
api.GET("/graphql", func(ctx *gin.Context) {
|
|
playground.Handler("Job tracker GraphQL", basePath+"/api/graphql").ServeHTTP(ctx.Writer, ctx.Request)
|
|
})
|
|
}
|
|
|
|
// Everything else under basePath is the SPA.
|
|
r.NoRoute(handlers.SPA(staticDir, basePath))
|
|
|
|
// The scheduler runs until ctx is cancelled, which only happens if r.Run
|
|
// returns; there is no graceful shutdown, so the container is simply
|
|
// killed.
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
defer cancel()
|
|
go jobLeads.StartScheduler(ctx)
|
|
|
|
port := getenv("PORT", "8080")
|
|
// Any return is a failure, so exit non-zero; otherwise Docker would see a
|
|
// clean shutdown and report the container as having succeeded.
|
|
if err := r.Run(fmt.Sprintf(":%s", port)); err != nil {
|
|
log.Fatalf("http server stopped: %v", err)
|
|
}
|
|
}
|
|
|
|
func getenv(key, fallback string) string {
|
|
if v := os.Getenv(key); v != "" {
|
|
return v
|
|
}
|
|
return fallback
|
|
}
|
|
|
|
// duration reads a Go duration such as 30m, falling back on a missing,
|
|
// unparseable or non-positive value.
|
|
func duration(key string, fallback time.Duration) time.Duration {
|
|
if parsed, err := time.ParseDuration(os.Getenv(key)); err == nil && parsed > 0 {
|
|
return parsed
|
|
}
|
|
return fallback
|
|
}
|