package edge import ( "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "io" "log" "math/rand/v2" "os" "path/filepath" "strings" "sync" "time" "github.com/carlosframework/platform/internal/geo" "github.com/carlosframework/platform/internal/geoip" "github.com/carlosframework/platform/internal/release" ) // The GeoIP mirror (geoip spec §5): poll control/geoip/current.json, fetch // the content-addressed blob it names into an immutable local generation, // and hot-swap the edge's reader. genMu serialises everything that chooses, // expires or deletes a generation (codex R3-1); network I/O stays outside it. var ( // geoPointerReadTimeout bounds every pointer read on its own, so a // slow store cannot stretch the off bound past interval+jitter+this // (codex R9 on R8-2). geoPointerReadTimeout = 30 * time.Second geoMirrorInterval = 10 * time.Minute geoMirrorJitter = time.Minute geoMirrorDeadline = 10 * time.Minute geoExpiryInterval = time.Minute ) // geoCurrent is the shared local format (geoip.LocalCurrent), so the // console's follower reads exactly what this mirror writes. type geoCurrent = geoip.LocalCurrent type geoMirror struct { store release.Store dir string sw *geo.Swappable now func() time.Time maxBytes int64 genMu sync.Mutex loadedSHA string loadedType string loadedBuild time.Time skipSHA map[string]string // sha -> why (rejected | expired); cleared whenever the observed pointer changes pointerSHA string // the sha the last readable pointer named; "" for none syncPending bool // the last `current` rename is not known durable unsynced map[string]geoCurrent // every generation a crash could bring back while syncPending; kept until a sync succeeds or it expires // The alert's inputs (geoip spec §10.4). The pointer's metadata is // kept after the reader is dropped, so an expired pointer still reads // as expired by the clock before the console marks it (codex R11-1). pointerPresent bool pointerType string pointerBuild time.Time pointerMarked bool wantSince time.Time // a live pointer has named a sha not loaded here since then feedFailing bool feedBox string // pointerKnown and feedKnown are false until a read has succeeded or // confirmed absence: until then the alert's reading is unknown (nil), // so a restart cannot clear an alert the last process raised (code // review R4-2). pointerKnown bool feedKnown bool lastErr string // last poll's error category, "" when healthy failingAt time.Time lastFailLog time.Time } func newGeoMirror(store release.Store, dir string, sw *geo.Swappable) *geoMirror { return &geoMirror{store: store, dir: dir, sw: sw, now: time.Now, maxBytes: geoip.MaxBlobBytes, skipSHA: map[string]string{}} } // GeoIPState is the heartbeat's view of this edge's GeoIP (spec §5.5). type GeoIPState struct { Mode string `json:"mode"` // mirror | tunnel | none SHA256 string `json:"sha256,omitempty"` Type string `json:"type,omitempty"` Error string `json:"error,omitempty"` } func (m *geoMirror) State() GeoIPState { m.genMu.Lock() defer m.genMu.Unlock() return GeoIPState{Mode: "mirror", SHA256: m.loadedSHA, Type: m.loadedType, Error: m.lastErr} } func (m *geoMirror) path(sha string) string { return filepath.Join(m.dir, sha+".mmdb") } // Boot installs the local generation `current` names, if any, without // touching the bucket, and clears everything else (spec §5.3 "At boot"). func (m *geoMirror) Boot() { if err := os.MkdirAll(m.dir, 0o755); err != nil { log.Printf("edge: geoip directory unusable; GeoIP stays off until it is: %v", err) return } os.Chmod(m.dir, 0o755) m.genMu.Lock() defer m.genMu.Unlock() cur, err := m.readCurrent() keep := "" switch { case err != nil && !errors.Is(err, os.ErrNotExist): log.Printf("edge: geoip local state unreadable; starting with no database") os.Remove(filepath.Join(m.dir, "current")) case cur.SHA256 == "": case geoip.Expired(cur.DatabaseType, time.Unix(cur.BuildEpoch, 0), m.now()): log.Printf("edge: geoip database %s expired (GeoLite2, 30 days after build) and was removed", short(cur.SHA256)) m.writeCurrentLocked(geoCurrent{}) default: db, err := geo.OpenMMDBTrusted(m.path(cur.SHA256)) if err != nil { log.Printf("edge: geoip local generation %s unopenable; starting with no database", short(cur.SHA256)) os.Remove(filepath.Join(m.dir, "current")) break } m.sw.Swap(db) m.loadedSHA, m.loadedType, m.loadedBuild = cur.SHA256, db.Source(), db.BuildEpoch() keep = cur.SHA256 log.Printf("edge: geoip database %s (%s, built %s) loaded", short(cur.SHA256), db.Source(), db.BuildEpoch().Format("2006-01-02")) } m.cleanLocked(keep, true) } func short(sha string) string { if len(sha) > 8 { return sha[:8] } return sha } func (m *geoMirror) readCurrent() (geoCurrent, error) { var c geoCurrent b, err := os.ReadFile(filepath.Join(m.dir, geoip.LocalCurrentFile)) if err != nil { return c, err } return geoip.ParseLocalCurrent(b) } // writeCurrentLocked replaces `current` atomically: temp, fsync, rename, // fsync the directory (spec §5.2). func (m *geoMirror) writeCurrentLocked(c geoCurrent) error { b, _ := json.Marshal(c) tmp, err := os.CreateTemp(m.dir, ".current-*") if err != nil { return err } defer os.Remove(tmp.Name()) if _, err := tmp.Write(b); err != nil { tmp.Close() return err } if err := tmp.Sync(); err != nil { tmp.Close() return err } if err := tmp.Close(); err != nil { return err } if err := os.Chmod(tmp.Name(), 0o644); err != nil { return err } if err := os.Rename(tmp.Name(), filepath.Join(m.dir, "current")); err != nil { return err } // After the rename `current` already names the new generation, so a // failed directory fsync must not make the caller delete it (plan review // R1-4): it is logged, and the rename stands. But the rename is not // durable either: a crash could bring back the PREVIOUS `current`, so // m.syncPending tells install to keep the previous generation too until // a later write is durable (code review R1-4). if err := syncDirFn(m.dir); err != nil { log.Printf("edge: geoip directory sync failed after selecting a generation; keeping the earlier ones until it succeeds") m.syncPending = true return nil } m.syncPending, m.unsynced = false, nil return nil } // syncDirFn is syncDir, a variable so a test can inject a failure. var syncDirFn = syncDir func syncDir(dir string) error { d, err := os.Open(dir) if err != nil { return err } defer d.Close() return d.Sync() } // cleanLocked deletes every generation but keep and every stray // .current-*. Downloads (.incoming-*) are deleted only at boot: at any other // time one may be in progress outside genMu, and unlinking it would break // a replacement that an expiry tick happened to race (plan review R1-3). func (m *geoMirror) cleanLocked(keep string, atBoot bool) { m.cleanLockedKeeping(atBoot, keep) } // cleanLockedKeeping is cleanLocked with any number of generations kept. func (m *geoMirror) cleanLockedKeeping(atBoot bool, keep ...string) { kept := map[string]bool{} for _, k := range keep { if k != "" { kept[k+".mmdb"] = true } } entries, _ := os.ReadDir(m.dir) for _, e := range entries { n := e.Name() if n == "current" || kept[n] { continue } if strings.HasSuffix(n, ".mmdb") || strings.HasPrefix(n, ".current-") || (atBoot && strings.HasPrefix(n, ".incoming-")) { os.Remove(filepath.Join(m.dir, n)) } } } // clearLocked turns GeoIP off on this box: empty current, nil reader, no // generations. func (m *geoMirror) clearLocked() { if err := m.writeCurrentLocked(geoCurrent{}); err != nil { os.Remove(filepath.Join(m.dir, "current")) } m.sw.Swap(nil) m.loadedSHA, m.loadedType, m.loadedBuild = "", "", time.Time{} m.cleanLocked("", false) } // Poll is one pass (spec §5.3). The caller bounds ctx by geoMirrorDeadline. func (m *geoMirror) Poll(ctx context.Context) error { return m.poll(ctx, true) } // poll is one pass; recheck allows ONE immediate re-run when a finished // download turns out to be superseded, so an `off` or a newer publish that // landed during a long download takes effect now, not a whole interval later // (codex R8-2). func (m *geoMirror) poll(ctx context.Context, recheck bool) error { // The control-plane state (feed, pointer) is read whatever the local // directory's health, so the alert sees a published database this box // cannot install (code review R2-4). m.readFeedStatus(ctx) raw, err := m.readPointer(ctx) var p geoip.Pointer if err == nil { p, err = geoip.ParsePointer(raw) } if errors.Is(err, os.ErrNotExist) || errors.Is(err, geoip.ErrUnknownVersion) { // No pointer, or one this binary cannot read: GeoIP is off on this // box (spec §3), never "keep what is loaded" (plan review R1-7). m.genMu.Lock() if m.loadedSHA != "" { if errors.Is(err, geoip.ErrUnknownVersion) { log.Printf("edge: geoip turned off; the published pointer has a version this binary cannot read") } else { log.Printf("edge: geoip turned off; no database published") } } m.pointerSHA, m.skipSHA = "", map[string]string{} m.pointerPresent, m.pointerType, m.pointerBuild, m.pointerMarked, m.wantSince = false, "", time.Time{}, false, time.Time{} m.pointerKnown = true m.clearLocked() m.lastErr = "" m.genMu.Unlock() return nil } if raw == nil && err != nil { return m.fail("pointer unreadable", err) } if err != nil { return m.fail("pointer invalid", err) } m.genMu.Lock() m.pointerPresent, m.pointerType, m.pointerBuild, m.pointerMarked = true, p.DatabaseType, p.Build(), p.Expired m.pointerKnown = true switch { case p.Expired || geoip.Expired(p.DatabaseType, p.Build(), m.now()): m.wantSince = time.Time{} case p.SHA256 == m.loadedSHA: m.wantSince = time.Time{} case m.wantSince.IsZero(): m.wantSince = m.now() } if p.SHA256 != m.pointerSHA { // The pointer moved (to anything, including back to an sha seen // before): every earlier rejection is void (plan review R1-8). m.pointerSHA, m.skipSHA = p.SHA256, map[string]string{} } if p.Expired || geoip.Expired(p.DatabaseType, p.Build(), m.now()) { if m.skipSHA[p.SHA256] != "expired" { log.Printf("edge: geoip database %s expired (GeoLite2, 30 days after build) and was removed", short(p.SHA256)) } m.skipSHA[p.SHA256] = "expired" m.clearLocked() m.lastErr = "" m.genMu.Unlock() return nil } if p.SHA256 == m.loadedSHA { m.lastErr = "" if m.syncPending { // The selection was never made durable: retry the sync, and once // it lands the retained recovery copies can go (code review // R10-2). if err := syncDirFn(m.dir); err == nil { m.syncPending, m.unsynced = false, nil m.cleanLocked(m.loadedSHA, false) } } m.genMu.Unlock() return nil } if _, skip := m.skipSHA[p.SHA256]; skip { m.genMu.Unlock() return nil } m.genMu.Unlock() if err := os.MkdirAll(m.dir, 0o755); err != nil { return m.fail("local directory unusable", err) } tmp, err := m.download(ctx, p) if err == nil && !m.pointerStillNames(ctx, p.SHA256) { os.Remove(tmp) if recheck { return m.poll(ctx, false) } return nil } if err != nil { if errors.Is(err, errGeoDigest) || errors.Is(err, errGeoSize) { m.genMu.Lock() m.skipSHA[p.SHA256] = "rejected" m.genMu.Unlock() log.Printf("edge: geoip blob %s rejected: %v", short(p.SHA256), err) } return m.fail("blob unavailable", err) } return m.install(tmp, p) } // downloadHook is a test seam: called after .incoming is created, before // the body is copied, so a test can run an expiry tick mid-download. var downloadHook func() // pointerStillNames re-reads the pointer after a download: only a // candidate the pointer still selects (unexpired) may be installed. A read // failure answers false, which defers the install to the next pass rather // than installing something nobody has confirmed is still wanted. func (m *geoMirror) pointerStillNames(ctx context.Context, sha string) bool { raw, err := m.readPointer(ctx) if err != nil { return false } p, err := geoip.ParsePointer(raw) return err == nil && p.SHA256 == sha && !p.Expired && !geoip.Expired(p.DatabaseType, p.Build(), m.now()) } var ( errGeoDigest = errors.New("digest mismatch") errGeoSize = errors.New("size mismatch") ) // download streams the blob to .incoming-, checks size and digest, // fsyncs, and returns its path. Outside genMu. func (m *geoMirror) download(ctx context.Context, p geoip.Pointer) (string, error) { rc, _, err := release.OpenObject(ctx, m.store, p.Key) if err != nil { return "", err } defer rc.Close() tmp := filepath.Join(m.dir, ".incoming-"+p.SHA256) f, err := os.OpenFile(tmp, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o644) if err != nil { return "", err } limit := p.Size if m.maxBytes < limit { limit = m.maxBytes } if downloadHook != nil { downloadHook() } h := sha256.New() n, err := io.Copy(io.MultiWriter(f, h), io.LimitReader(rc, limit+1)) if err == nil { err = f.Sync() } if cerr := f.Close(); err == nil { err = cerr } switch { case err != nil: os.Remove(tmp) return "", err case n > limit || n != p.Size: // n > limit: the blob ran past the cap (the box's maxBytes may be // below what the pointer claims), however the counts compare. os.Remove(tmp) return "", errGeoSize case hex.EncodeToString(h.Sum(nil)) != p.SHA256: os.Remove(tmp) return "", errGeoDigest } return tmp, nil } // install commits a verified download under genMu (spec §5.3 steps 3-5), // re-checking expiry against the file's own metadata first. func (m *geoMirror) install(tmp string, p geoip.Pointer) error { m.genMu.Lock() defer m.genMu.Unlock() final := m.path(p.SHA256) if err := os.Rename(tmp, final); err != nil { os.Remove(tmp) return m.failLocked("install failed", err) } syncDir(m.dir) db, err := geo.OpenMMDBTrusted(final) if err != nil { m.removeGenerationLocked(p.SHA256) m.skipSHA[p.SHA256] = "rejected" log.Printf("edge: geoip blob %s rejected: unopenable", short(p.SHA256)) return m.failLocked("blob unopenable", err) } if geoip.Expired(db.Source(), db.BuildEpoch(), m.now()) { db.Close() m.removeGenerationLocked(p.SHA256) m.skipSHA[p.SHA256] = "expired" log.Printf("edge: geoip database %s expired (GeoLite2, 30 days after build) and was removed", short(p.SHA256)) return nil } if err := m.writeCurrentLocked(geoCurrent{SHA256: p.SHA256, DatabaseType: db.Source(), BuildEpoch: db.BuildEpoch().Unix()}); err != nil { db.Close() m.removeGenerationLocked(p.SHA256) return m.failLocked("install failed", err) } prev := geoCurrent{SHA256: m.loadedSHA, DatabaseType: m.loadedType, BuildEpoch: m.loadedBuild.Unix()} m.sw.Swap(db) m.loadedSHA, m.loadedType, m.loadedBuild = p.SHA256, db.Source(), db.BuildEpoch() if m.syncPending { // Until a sync succeeds, any `current` since the last durable one // could come back after a crash: keep every one of them (code // review R2 on R1-4). if m.unsynced == nil { m.unsynced = map[string]geoCurrent{} } if prev.SHA256 != "" { m.unsynced[prev.SHA256] = prev } keep := []string{p.SHA256} for sha := range m.unsynced { keep = append(keep, sha) } m.cleanLockedKeeping(false, keep...) } else { m.cleanLocked(p.SHA256, false) } m.lastErr, m.failingAt, m.wantSince = "", time.Time{}, time.Time{} log.Printf("edge: geoip database %s (%s, built %s) loaded", short(p.SHA256), db.Source(), db.BuildEpoch().Format("2006-01-02")) return nil } // removeGenerationLocked deletes a failed install's file unless the same // generation is one a crash could bring back (loaded, or kept while syncs // fail): republishing a retained A must never delete A on an error path // (code review R3 on R1-4). func (m *geoMirror) removeGenerationLocked(sha string) { if _, retained := m.unsynced[sha]; sha == m.loadedSHA || retained { return } os.Remove(m.path(sha)) } // ExpireTick is D1 on the loaded generation, under genMu, so it can only // ever remove the generation that is current at that moment (codex R3-1). func (m *geoMirror) ExpireTick() { m.genMu.Lock() defer m.genMu.Unlock() // Retained recovery copies obey D1 too (code review R10-2): an expired // GeoLite2 kept only in case a crash brings it back is destroyed. for sha, g := range m.unsynced { if geoip.Expired(g.DatabaseType, time.Unix(g.BuildEpoch, 0), m.now()) { os.Remove(m.path(sha)) delete(m.unsynced, sha) } } if m.loadedSHA == "" || !geoip.Expired(m.loadedType, m.loadedBuild, m.now()) { return } log.Printf("edge: geoip database %s expired (GeoLite2, 30 days after build) and was removed", short(m.loadedSHA)) m.skipSHA[m.loadedSHA] = "expired" m.clearLocked() } func (m *geoMirror) fail(category string, err error) error { m.genMu.Lock() defer m.genMu.Unlock() return m.failLocked(category, err) } // failLocked records the category for the heartbeat and logs at most hourly // while failing. The error text is never logged: it may carry a key or // bytes; the category is the message (spec §12). func (m *geoMirror) failLocked(category string, err error) error { now := m.now() if m.lastErr == "" { m.failingAt = now } m.lastErr = category if now.Sub(m.lastFailLog) >= time.Hour { m.lastFailLog = now log.Printf("edge: geoip %s; keeping the loaded database", category) } return fmt.Errorf("%s: %w", category, err) } // readFeedStatus refreshes the feed reason's inputs, best effort: a // missing or unreadable feed.json means no feed reason. func (m *geoMirror) readFeedStatus(ctx context.Context) { ctx, cancel := context.WithTimeout(ctx, geoPointerReadTimeout) defer cancel() raw, err := readCapped(ctx, m.store, geoip.FeedKey, geoip.MaxPointerBytes) if errors.Is(err, os.ErrNotExist) { m.genMu.Lock() m.feedFailing, m.feedBox, m.feedKnown = false, "", true // no feed: confirmed m.genMu.Unlock() return } if err != nil { return // keep the last known state: a blip must not clear a firing alert (code review R2-3) } st, err := geoip.ParseFeedStatus(raw) if err != nil { return } m.genMu.Lock() m.feedFailing, m.feedBox, m.feedKnown = st.Failing(), st.Box, true m.genMu.Unlock() } // Alert reason codes (geoip spec §10.4), the geoip rule's reading. const ( GeoAlertNone = 0 GeoAlertStale = 1 // the loaded database is over 45 days old GeoAlertExpiring = 2 // a GeoLite2 database within 9 days of D1 GeoAlertExpired = 3 // the pointer is expired, marked or by the clock GeoAlertNotLoaded = 4 // a live pointer not loaded here for over an hour GeoAlertFeed = 5 // the feed has failed 7 times in a row (the console's box only) ) // AlertCode is the geoip rule's reading for this box: the most severe // reason that holds (3, 4, 2, 1, then 5), or 0. known=false until both the // pointer and the feed status have been read (or confirmed absent) once. func (m *geoMirror) AlertCode(now time.Time, box string) (code float64, known bool) { m.genMu.Lock() defer m.genMu.Unlock() // A reason established from what IS known is reported even when the // other input is not (code review R5-1): an unreadable feed.json must // not hide a confirmed expiry. Only "healthy" needs everything known. if c := m.alertCodeLocked(now, box); c != GeoAlertNone { return c, true } if !m.pointerKnown || !m.feedKnown { return GeoAlertNone, false } return GeoAlertNone, true } func (m *geoMirror) alertCodeLocked(now time.Time, box string) float64 { // pointerPresent is only ever true after a successful read, and // feedFailing only after a parsed feed.json, so each reason below rests // on state that was actually read. expired := m.pointerPresent && (m.pointerMarked || geoip.Expired(m.pointerType, m.pointerBuild, now)) switch { case expired: return GeoAlertExpired case m.pointerPresent && !m.wantSince.IsZero() && now.Sub(m.wantSince) > time.Hour: return GeoAlertNotLoaded case m.loadedSHA != "" && strings.HasPrefix(m.loadedType, "GeoLite2-") && now.Sub(m.loadedBuild) >= geoip.GeoLiteWarn: return GeoAlertExpiring case m.loadedSHA != "" && now.Sub(m.loadedBuild) > geoip.StaleAfter: return GeoAlertStale case m.feedFailing && box != "" && m.feedBox == box: return GeoAlertFeed } return GeoAlertNone } // readPointer is one bounded pointer read. func (m *geoMirror) readPointer(ctx context.Context) ([]byte, error) { ctx, cancel := context.WithTimeout(ctx, geoPointerReadTimeout) defer cancel() return readCapped(ctx, m.store, geoip.PointerKey, geoip.MaxPointerBytes) } // readCapped reads key through OpenObject, refusing more than max bytes. func readCapped(ctx context.Context, s release.Store, key string, max int) ([]byte, error) { rc, _, err := release.OpenObject(ctx, s, key) if err != nil { return nil, err } defer rc.Close() b, err := io.ReadAll(io.LimitReader(rc, int64(max)+1)) if err != nil { return nil, err } if len(b) > max { return nil, fmt.Errorf("%s larger than %d bytes", key, max) } return b, nil } // run is the process-lifetime loop: a poll every interval+jitter, each // bounded by geoMirrorDeadline, and an independent expiry ticker that never // touches the network. func (m *geoMirror) run(stop <-chan struct{}) { go func() { t := time.NewTicker(geoExpiryInterval) defer t.Stop() for { select { case <-stop: return case <-t.C: m.ExpireTick() } } }() for { // The next pass is due interval+jitter after this one STARTED, not // after it finished: a pass is bounded by geoMirrorDeadline (10 min), // so a change to the pointer is seen within interval+jitter (11 min) // even when a long download was in flight (codex R8-2). next := time.Now().Add(geoMirrorInterval + rand.N(geoMirrorJitter)) ctx, cancel := context.WithTimeout(context.Background(), geoMirrorDeadline) m.Poll(ctx) cancel() select { case <-stop: return case <-time.After(time.Until(next)): } } } // WithGeoTunnelClient marks this edge as a tunnel client's: it never mirrors // the GeoIP database and takes the hub's answer instead (spec §5.1). func WithGeoTunnelClient() RunOption { return func(e *Edge) { e.geoTunnelClient = true } } // GeoIPState is the heartbeat block (spec §5.5). func (e *Edge) GeoIPState() GeoIPState { if e.geoMirror != nil { return e.geoMirror.State() } if e.geoMode == "" { return GeoIPState{Mode: "none"} } return GeoIPState{Mode: e.geoMode} } // GeoIPAlertCode is the geoip rule's reading for this box (spec §10.4); // 0 on an edge with no mirror. known=false means "no reading yet". func (e *Edge) GeoIPAlertCode(now time.Time) (float64, bool) { if e.geoMirror == nil { return GeoAlertNone, true } return e.geoMirror.AlertCode(now, e.box) }