Phase 13, part 5: each team's jobs, locks, files and sign-ins
Background jobs run for each active team on its own Server and under its own locks, a few teams at a time and from a different team each round, so the work is shared between copies of the app and no team holds up another. Each team's files are under its own prefix, and an OAuth sign-in comes back only to the team that started it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -362,10 +362,11 @@ func (s *Server) teamServer(r *http.Request) (*Server, error) {
|
||||
return s.forTeam(v.Session.Team)
|
||||
}
|
||||
|
||||
// team is the team this Server works for.
|
||||
// team is the team this Server works for: 1 on the local and server
|
||||
// editions.
|
||||
func (s *Server) team() int64 {
|
||||
if s.Team == 0 {
|
||||
if s.Team == 0 && !s.multi() {
|
||||
return users.Team
|
||||
}
|
||||
return s.Team
|
||||
return s.Team // 0: the multi-tenant edition's platform, no team's
|
||||
}
|
||||
|
||||
@@ -41,12 +41,12 @@ func TestTwoCopies(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ran := false
|
||||
b.jobDo(context.Background(), "seo", func(context.Context) { ran = true })
|
||||
b.jobDo(context.Background(), "seo", func(context.Context, *Server) { ran = true })
|
||||
if ran {
|
||||
t.Error("both copies ran the SEO job")
|
||||
}
|
||||
release()
|
||||
b.jobDo(context.Background(), "seo", func(context.Context) { ran = true })
|
||||
b.jobDo(context.Background(), "seo", func(context.Context, *Server) { ran = true })
|
||||
if !ran {
|
||||
t.Error("the job didn't run once free")
|
||||
}
|
||||
|
||||
@@ -429,7 +429,7 @@ func (s *Server) RunScheduler(ctx context.Context) {
|
||||
tick := time.NewTicker(schedulerInterval)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
s.jobDo(ctx, "scheduler", func(ctx context.Context) {
|
||||
s.jobDo(ctx, "scheduler", func(ctx context.Context, s *Server) {
|
||||
s.publishDue(ctx, time.Now())
|
||||
})
|
||||
select {
|
||||
|
||||
@@ -184,7 +184,7 @@ func (s *Server) RunMetrics(ctx context.Context) {
|
||||
tick := time.NewTicker(10 * time.Minute)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
s.jobDo(ctx, "metrics", func(ctx context.Context) {
|
||||
s.jobDo(ctx, "metrics", func(ctx context.Context, s *Server) {
|
||||
if c := s.stripe(); c != nil {
|
||||
if _, err := metrics.SyncOutsideSpend(s.DB, time.Now()); err != nil {
|
||||
s.Log.Warn("metrics: outside spend", "err", err)
|
||||
|
||||
@@ -371,7 +371,7 @@ func (s *Server) outreachAction(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute)
|
||||
var sctx context.Context
|
||||
var release func()
|
||||
if sctx, release, err = s.jobs().Lock(ctx, sendLock); err == nil {
|
||||
if sctx, release, err = s.jobs().Lock(ctx, s.lockName(sendLock)); err == nil {
|
||||
err = outreach.SendNow(sctx, s.DB, set, mb, s.tagger(), id, now)
|
||||
release()
|
||||
} else if errors.Is(err, jobs.ErrBusy) {
|
||||
@@ -423,13 +423,13 @@ func (s *Server) RunOutreach(ctx context.Context) {
|
||||
tick := time.NewTicker(time.Minute)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
s.jobDo(ctx, "outreach", func(ctx context.Context) {
|
||||
s.jobDo(ctx, "outreach", func(ctx context.Context, s *Server) {
|
||||
set, mb, err := s.mailbox()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
sctx, cancel := context.WithTimeout(ctx, 3*time.Minute)
|
||||
if lctx, release, err := s.jobs().Lock(sctx, sendLock); err == nil {
|
||||
if lctx, release, err := s.jobs().Lock(sctx, s.lockName(sendLock)); err == nil {
|
||||
m, err := outreach.SendDue(lctx, s.DB, set, mb, s.tagger(), time.Now())
|
||||
release()
|
||||
if err != nil {
|
||||
|
||||
+19
-14
@@ -258,23 +258,12 @@ func (s *Server) syncSearchConsole(ctx context.Context) error {
|
||||
// RunSEO syncs Search Console twice a day.
|
||||
func (s *Server) RunSEO(ctx context.Context) {
|
||||
if s.alone() { // otherwise "running" may be another copy's work
|
||||
if err := seo.RecoverAudits(s.DB); err != nil {
|
||||
s.Log.Error("seo: recovering audits", "err", err)
|
||||
}
|
||||
if err := seo.RecoverChanges(s.DB); err != nil {
|
||||
s.Log.Error("seo: recovering changes", "err", err)
|
||||
}
|
||||
if err := seo.RecoverBriefs(s.DB); err != nil {
|
||||
s.Log.Error("seo: recovering briefs", "err", err)
|
||||
}
|
||||
if err := sites.RecoverPages(s.DB); err != nil {
|
||||
s.Log.Error("sites: recovering pages", "err", err)
|
||||
}
|
||||
s.eachTeam(ctx, func(_ context.Context, s *Server) { s.recoverSEO() })
|
||||
}
|
||||
tick := time.NewTicker(30 * time.Minute)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
s.jobDo(ctx, "seo", func(ctx context.Context) {
|
||||
s.jobDo(ctx, "seo", func(ctx context.Context, s *Server) {
|
||||
s.weeklyAudits(time.Now())
|
||||
if s.gsc() != nil {
|
||||
due := false
|
||||
@@ -611,7 +600,7 @@ func (s *Server) seoAuditRun(w http.ResponseWriter, r *http.Request) {
|
||||
// site.
|
||||
func (s *Server) startAudit(site seoSite, speed bool) {
|
||||
// One audit per site at a time, across copies of the app.
|
||||
lctx, release, err := s.jobs().TryLock(context.Background(), "audit:"+site.URL)
|
||||
lctx, release, err := s.jobs().TryLock(context.Background(), s.lockName("audit:"+site.URL))
|
||||
if err != nil {
|
||||
if !errors.Is(err, jobs.ErrBusy) {
|
||||
s.Log.Error("seo: starting the audit", "err", err)
|
||||
@@ -711,3 +700,19 @@ func (s *Server) giteaTest(w http.ResponseWriter, r *http.Request) {
|
||||
s.noteCheck("gitea", data)
|
||||
s.fragment(w, r, "sources", "test-result", data)
|
||||
}
|
||||
|
||||
// recoverSEO marks the work left "running" by a stopped app as stopped.
|
||||
func (s *Server) recoverSEO() {
|
||||
if err := seo.RecoverAudits(s.DB); err != nil {
|
||||
s.Log.Error("seo: recovering audits", "err", err)
|
||||
}
|
||||
if err := seo.RecoverChanges(s.DB); err != nil {
|
||||
s.Log.Error("seo: recovering changes", "err", err)
|
||||
}
|
||||
if err := seo.RecoverBriefs(s.DB); err != nil {
|
||||
s.Log.Error("seo: recovering briefs", "err", err)
|
||||
}
|
||||
if err := sites.RecoverPages(s.DB); err != nil {
|
||||
s.Log.Error("sites: recovering pages", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
+84
-4
@@ -92,7 +92,8 @@ type state struct {
|
||||
pages map[string]*template.Template
|
||||
jobsOnce sync.Once
|
||||
runner *jobs.Runner
|
||||
setupDone atomic.Bool // the team has its owner (server edition)
|
||||
setupDone atomic.Bool // the team has its owner (server edition)
|
||||
rotation atomic.Uint64 // which team's turn comes first (eachTeam)
|
||||
|
||||
mu sync.Mutex
|
||||
copies map[int64]*Server // each team's Server
|
||||
@@ -177,6 +178,9 @@ func (s *Server) forTeam(team int64) (*Server, error) {
|
||||
cp := *s
|
||||
cp.Team, cp.DB, cp.Secrets = team, d, sec
|
||||
cp.Platform = s.platform()
|
||||
if s.Files != nil {
|
||||
cp.Files = storage.Under(s.Files, fmt.Sprintf("teams/%d", team))
|
||||
}
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
if c := st.copies[team]; c != nil {
|
||||
@@ -218,10 +222,86 @@ func (s *Server) alone() bool {
|
||||
|
||||
// jobDo runs one turn of a background job under its lock, job:<name>:
|
||||
// with several copies of the app, one of them does it.
|
||||
func (s *Server) jobDo(ctx context.Context, name string, fn func(context.Context)) {
|
||||
if _, err := s.jobs().Do(ctx, "job:"+name, fn); err != nil {
|
||||
s.Log.Warn("jobs: taking the lock", "job", name, "err", err)
|
||||
//
|
||||
// On the multi-tenant edition it runs the turn for each active team, on
|
||||
// that team's Server, under the team's own lock (team:<id>:job:<name>), so
|
||||
// copies of the app share the teams between them. A few teams at a time,
|
||||
// starting from another one each round, so one team's long turn doesn't
|
||||
// hold up the others'. fn's Server is the team's.
|
||||
func (s *Server) jobDo(ctx context.Context, name string, fn func(context.Context, *Server)) {
|
||||
if !s.multi() {
|
||||
if _, err := s.jobs().Do(ctx, "job:"+name, func(c context.Context) { fn(c, s) }); err != nil {
|
||||
s.Log.Warn("jobs: taking the lock", "job", name, "err", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
s.eachTeam(ctx, func(ctx context.Context, ts *Server) {
|
||||
if name == "seo" && !ts.domainProved() {
|
||||
return // nothing crawled or read before the domain is proved
|
||||
}
|
||||
if _, err := ts.jobs().Do(ctx, ts.lockName("job:"+name), func(c context.Context) { fn(c, ts) }); err != nil {
|
||||
ts.Log.Warn("jobs: taking the lock", "job", name, "team", ts.team(), "err", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// teamsAtOnce is how many teams' turns run together, in one copy.
|
||||
const teamsAtOnce = 4
|
||||
|
||||
// eachTeam runs fn for every active team (multi-tenant), a few at once,
|
||||
// from a different team each time.
|
||||
func (s *Server) eachTeam(ctx context.Context, fn func(context.Context, *Server)) {
|
||||
if !s.multi() {
|
||||
fn(ctx, s)
|
||||
return
|
||||
}
|
||||
list, err := users.ListTeams(s.platform())
|
||||
if err != nil {
|
||||
s.Log.Error("jobs: listing teams", "err", err)
|
||||
return
|
||||
}
|
||||
var ids []int64
|
||||
for _, t := range list {
|
||||
if t.Status == users.TeamActive {
|
||||
ids = append(ids, t.ID)
|
||||
}
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return
|
||||
}
|
||||
start := int(s.st().rotation.Add(1) % uint64(len(ids)))
|
||||
sem := make(chan struct{}, teamsAtOnce)
|
||||
var wg sync.WaitGroup
|
||||
for i := range ids {
|
||||
id := ids[(start+i)%len(ids)]
|
||||
ts, err := s.forTeam(id)
|
||||
if err != nil {
|
||||
s.Log.Error("jobs: opening a team", "team", id, "err", err)
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case sem <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
wg.Wait()
|
||||
return
|
||||
}
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
defer func() { <-sem }()
|
||||
fn(ctx, ts)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
// lockName is a lock's name for this team: shared by every copy of the
|
||||
// app, and apart from other teams' on the multi-tenant edition.
|
||||
func (s *Server) lockName(name string) string {
|
||||
if !s.multi() {
|
||||
return name
|
||||
}
|
||||
return fmt.Sprintf("team:%d:%s", s.team(), name)
|
||||
}
|
||||
|
||||
// sendLock is held while an email goes out, from the queue or Send now:
|
||||
|
||||
@@ -417,7 +417,7 @@ func (s *Server) oauthStart(w http.ResponseWriter, r *http.Request) {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
p.For = forUser
|
||||
p.For, p.Team = forUser, s.team()
|
||||
// Kept in the database: the callback may reach another copy of the app.
|
||||
if err := s.DB.PutJSON(oauthFlowKey+p.State, p); err != nil {
|
||||
s.serverError(w, err)
|
||||
@@ -483,7 +483,7 @@ func (s *Server) oauthCallback(w http.ResponseWriter, r *http.Request) {
|
||||
if p != nil && p.For != 0 {
|
||||
back, nav = "/settings/account#posting", "settings/account"
|
||||
}
|
||||
if p == nil || p.Provider != provider || time.Since(p.Started) > oauthTTL {
|
||||
if p == nil || p.Provider != provider || time.Since(p.Started) > oauthTTL || (p.Team != 0 && p.Team != s.team()) {
|
||||
s.Log.Warn("oauth: callback with an unknown or expired state", "provider", provider)
|
||||
redirect(w, r, back, "oauth-expired")
|
||||
return
|
||||
|
||||
@@ -479,7 +479,7 @@ func (s *Server) importSource(w http.ResponseWriter, r *http.Request) {
|
||||
// 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)
|
||||
ctx, release, err := s.jobs().TryLock(ctx, s.lockName("import:"+source))
|
||||
if errors.Is(err, jobs.ErrBusy) {
|
||||
return nil, leadsource.ErrRunning
|
||||
} else if err != nil {
|
||||
@@ -506,7 +506,7 @@ func (s *Server) RunImports(ctx context.Context) {
|
||||
tick := time.NewTicker(10 * time.Minute)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
s.jobDo(ctx, "imports", func(ctx context.Context) {
|
||||
s.jobDo(ctx, "imports", func(ctx context.Context, s *Server) {
|
||||
for _, src := range []string{signals.SourceOrigami, signals.SourceExplee} {
|
||||
last, _ := leadsource.Last(s.DB, src)
|
||||
if last != nil && time.Since(last.At) < leadsource.Every {
|
||||
@@ -587,7 +587,7 @@ func (s *Server) discover(sig *signals.Signal, source string) error {
|
||||
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))
|
||||
lctx, release, err := s.jobs().TryLock(context.Background(), s.lockName(fmt.Sprintf("discover:%d:%s", sig.ID, source)))
|
||||
if errors.Is(err, jobs.ErrBusy) {
|
||||
return discovery.ErrRunning
|
||||
} else if err != nil {
|
||||
@@ -660,9 +660,11 @@ 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 s.alone() {
|
||||
if err := discovery.RecoverInterrupted(s.DB); err != nil {
|
||||
s.Log.Error("discovery: recovering interrupted runs", "err", err)
|
||||
}
|
||||
s.eachTeam(ctx, func(_ context.Context, s *Server) {
|
||||
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()
|
||||
@@ -672,7 +674,7 @@ func (s *Server) RunDiscovery(ctx context.Context) {
|
||||
return
|
||||
case <-tick.C:
|
||||
}
|
||||
s.jobDo(ctx, "discovery", func(ctx context.Context) {
|
||||
s.jobDo(ctx, "discovery", func(ctx context.Context, s *Server) {
|
||||
list, err := signals.List(s.DB)
|
||||
if err != nil {
|
||||
s.Log.Error("discovery: listing signals", "err", err)
|
||||
|
||||
@@ -411,7 +411,7 @@ func (s *Server) RunAccounts(ctx context.Context) {
|
||||
tick := time.NewTicker(time.Hour)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
s.jobDo(ctx, "accounts", func(context.Context) {
|
||||
s.jobDo(ctx, "accounts", func(_ context.Context, s *Server) {
|
||||
now := time.Now()
|
||||
if _, err := users.PruneSessions(s.DB, now); err != nil {
|
||||
s.Log.Warn("accounts: pruning sessions", "err", err)
|
||||
|
||||
@@ -13,8 +13,10 @@ import (
|
||||
"time"
|
||||
|
||||
"supermarket/internal/config"
|
||||
"supermarket/internal/content"
|
||||
"supermarket/internal/db"
|
||||
"supermarket/internal/inventory"
|
||||
"supermarket/internal/posting"
|
||||
"supermarket/internal/users"
|
||||
)
|
||||
|
||||
@@ -320,3 +322,39 @@ func TestProvingTheDomain(t *testing.T) {
|
||||
t.Errorf("file: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestJobsRunPerTeam(t *testing.T) {
|
||||
s, _ := newMultiEdition(t)
|
||||
sent := &fakePosts{}
|
||||
s.testPublisher = func(a *posting.Account) content.Publisher { return fakePub{sent, a} }
|
||||
var teams []*users.TeamInfo
|
||||
for _, name := range []string{"Acme", "Bolt", "Calm"} {
|
||||
tm, _, _ := newTeam(t, s, name, strings.ToLower(name)+"@x.example")
|
||||
teams = append(teams, tm)
|
||||
ts, err := s.forTeam(tm.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
acct := &posting.Account{Network: posting.X, Name: "@" + strings.ToLower(name), External: strings.ToLower(name)}
|
||||
posting.Save(ts.DB, ts.Secrets, acct, "t", "", time.Now())
|
||||
content.CreateDrafts(ts.DB, []content.Draft{{Channel: content.ChannelX, Content: name + " news"}})
|
||||
ds, _ := content.ListDrafts(ts.DB, 1, content.StatusDraft)
|
||||
content.Schedule(ts.DB, ds[0].ID, time.Now().Add(time.Minute))
|
||||
}
|
||||
// Calm is suspended: its work waits.
|
||||
users.SetTeamStatus(s.platform(), teams[2].ID, users.TeamSuspended, time.Time{})
|
||||
s.jobDo(context.Background(), "scheduler", func(ctx context.Context, ts *Server) { ts.publishDue(ctx, time.Now().Add(2*time.Minute)) })
|
||||
got := strings.Join(sent.sent, "|")
|
||||
if len(sent.sent) != 2 || !strings.Contains(got, "X @acme: Acme news") || !strings.Contains(got, "X @bolt: Bolt news") {
|
||||
t.Errorf("sent %v", sent.sent)
|
||||
}
|
||||
// Each team's lock is its own.
|
||||
ts, _ := s.forTeam(teams[0].ID)
|
||||
if ts.lockName("job:seo") == s.lockName("job:seo") || !strings.HasPrefix(ts.lockName("job:seo"), "team:") {
|
||||
t.Errorf("lock %s", ts.lockName("job:seo"))
|
||||
}
|
||||
// Its files are under its own prefix.
|
||||
if ts.Files != nil && !strings.Contains(ts.Files.String(), "teams/") {
|
||||
t.Errorf("files %s", ts.Files.String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -255,7 +255,7 @@ func (s *Server) RunTracking(ctx context.Context) {
|
||||
defer tick.Stop()
|
||||
tried := map[string]time.Time{}
|
||||
for {
|
||||
s.jobDo(ctx, "tracking", func(ctx context.Context) {
|
||||
s.jobDo(ctx, "tracking", func(ctx context.Context, s *Server) {
|
||||
s.hourlyOptOuts(ctx)
|
||||
yesterday := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
|
||||
for _, src := range []string{tracking.SourcePlausible, tracking.SourceStripe} {
|
||||
|
||||
Reference in New Issue
Block a user