Phase 9, part 6: background work shared safely between copies of the app

internal/jobs keeps named locks as leases in the database (schema 31:
locks, instances), taken with one conditional UPDATE on SQLite or Postgres,
renewed while the work runs and lapsing if its copy stops. Each background
loop's turn, sending an email, audits, discovery runs and imports run
under a lock; OAuth sign-ins under way are kept in the database. Copies
check in, and work marked running is recovered at start only when no
other copy is alive. Settings -> About lists the copies and work under
way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 07:56:47 -07:00
co-authored by Claude Opus 5.5
parent ba6114f367
commit c6c4c40600
18 changed files with 873 additions and 150 deletions
+62 -39
View File
@@ -9,6 +9,7 @@ import (
"net/url"
"strconv"
"strings"
"supermarket/internal/jobs"
"supermarket/internal/sites"
"supermarket/internal/tracking"
"time"
@@ -476,6 +477,14 @@ func (s *Server) importSource(w http.ResponseWriter, r *http.Request) {
// runImport imports from one tool, if its key is saved. It returns nil, nil
// without one.
func (s *Server) runImport(ctx context.Context, source string) (*leadsource.Result, error) {
// One import per tool at a time, across copies of the app.
ctx, release, err := s.jobs().TryLock(ctx, "import:"+source)
if errors.Is(err, jobs.ErrBusy) {
return nil, leadsource.ErrRunning
} else if err != nil {
return nil, err
}
defer release()
now := time.Now()
switch source {
case signals.SourceExplee:
@@ -496,23 +505,25 @@ func (s *Server) RunImports(ctx context.Context) {
tick := time.NewTicker(10 * time.Minute)
defer tick.Stop()
for {
for _, src := range []string{signals.SourceOrigami, signals.SourceExplee} {
last, _ := leadsource.Last(s.DB, src)
if last != nil && time.Since(last.At) < leadsource.Every {
continue
s.jobDo(ctx, "imports", func(ctx context.Context) {
for _, src := range []string{signals.SourceOrigami, signals.SourceExplee} {
last, _ := leadsource.Last(s.DB, src)
if last != nil && time.Since(last.At) < leadsource.Every {
continue
}
ictx, cancel := context.WithTimeout(ctx, 10*time.Minute)
res, err := s.runImport(ictx, src)
cancel()
switch {
case res == nil:
case err != nil:
s.Log.Warn("lead source import failed", "source", src, "err", err)
default:
s.Log.Info("lead source imported", "source", src, "campaigns", res.Campaigns, "events", res.Events,
"prospects", res.Prospects, "suppressed", res.Suppressed)
}
}
ictx, cancel := context.WithTimeout(ctx, 10*time.Minute)
res, err := s.runImport(ictx, src)
cancel()
switch {
case res == nil:
case err != nil:
s.Log.Warn("lead source import failed", "source", src, "err", err)
default:
s.Log.Info("lead source imported", "source", src, "campaigns", res.Campaigns, "events", res.Events,
"prospects", res.Prospects, "suppressed", res.Suppressed)
}
}
})
select {
case <-ctx.Done():
return
@@ -574,9 +585,17 @@ func (s *Server) discover(sig *signals.Signal, source string) error {
default:
return errors.New("unknown source")
}
// One search per signal and source at a time, across copies of the app.
lctx, release, err := s.jobs().TryLock(context.Background(), fmt.Sprintf("discover:%d:%s", sig.ID, source))
if errors.Is(err, jobs.ErrBusy) {
return discovery.ErrRunning
} else if err != nil {
return err
}
started := make(chan error, 1)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), discoverTimeout)
defer release()
ctx, cancel := context.WithTimeout(lctx, discoverTimeout)
defer cancel()
res, err := run(ctx)
if res == nil {
@@ -639,8 +658,10 @@ func (s *Server) signalRuns(w http.ResponseWriter, r *http.Request) {
// RunDiscovery searches for signals that ask to be searched on a schedule.
func (s *Server) RunDiscovery(ctx context.Context) {
if err := discovery.RecoverInterrupted(s.DB); err != nil {
s.Log.Error("discovery: recovering interrupted runs", "err", err)
if s.alone() {
if err := discovery.RecoverInterrupted(s.DB); err != nil {
s.Log.Error("discovery: recovering interrupted runs", "err", err)
}
}
tick := time.NewTicker(30 * time.Minute)
defer tick.Stop()
@@ -650,31 +671,33 @@ func (s *Server) RunDiscovery(ctx context.Context) {
return
case <-tick.C:
}
list, err := signals.List(s.DB)
if err != nil {
s.Log.Error("discovery: listing signals", "err", err)
continue
}
for i := range list {
sig := &list[i]
if sig.DiscoverEveryDays <= 0 || sig.Status == signals.StatusRetired {
continue
s.jobDo(ctx, "discovery", func(ctx context.Context) {
list, err := signals.List(s.DB)
if err != nil {
s.Log.Error("discovery: listing signals", "err", err)
return
}
due := time.Duration(sig.DiscoverEveryDays) * 24 * time.Hour
sources := []string{discovery.SourceClaude}
if sig.ExpleeDefinition != "" && s.Secrets.Has(secrets.ExpleeAPIKey) {
sources = append(sources, discovery.SourceExplee)
}
for _, src := range sources {
last, err := discovery.LastStarted(s.DB, sig.ID, src)
if err != nil || time.Since(last) < due {
for i := range list {
sig := &list[i]
if sig.DiscoverEveryDays <= 0 || sig.Status == signals.StatusRetired {
continue
}
if err := s.discover(sig, src); err != nil {
s.Log.Warn("discovery: scheduled run didn't start", "signal", sig.ID, "source", src, "err", err)
due := time.Duration(sig.DiscoverEveryDays) * 24 * time.Hour
sources := []string{discovery.SourceClaude}
if sig.ExpleeDefinition != "" && s.Secrets.Has(secrets.ExpleeAPIKey) {
sources = append(sources, discovery.SourceExplee)
}
for _, src := range sources {
last, err := discovery.LastStarted(s.DB, sig.ID, src)
if err != nil || time.Since(last) < due {
continue
}
if err := s.discover(sig, src); err != nil {
s.Log.Warn("discovery: scheduled run didn't start", "signal", sig.ID, "source", src, "err", err)
}
}
}
}
})
}
}