asynq scheduler (#185)

Reviewed-on: https://git.ptzo.gdn/feditools/relay/pulls/185
Co-authored-by: Tyr Mactire <tyr@pettingzoo.co>
Co-committed-by: Tyr Mactire <tyr@pettingzoo.co>
This commit is contained in:
Tyr Mactire 2023-03-12 01:07:32 +00:00 committed by PettingZoo Gitea
parent 68627d7848
commit cdaec9b3e0
No known key found for this signature in database
GPG Key ID: 39788A4390A1372F
98 changed files with 443 additions and 7835 deletions

View File

@ -1,8 +1,6 @@
package scheduler
import (
"git.ptzo.gdn/feditools/relay/internal/log"
)
import "git.ptzo.gdn/feditools/relay/internal/log"
type empty struct{}

View File

@ -0,0 +1,210 @@
package scheduler
import (
"context"
"fmt"
"git.ptzo.gdn/feditools/relay/cmd/relay/action"
"git.ptzo.gdn/feditools/relay/internal/clock"
"git.ptzo.gdn/feditools/relay/internal/config"
"git.ptzo.gdn/feditools/relay/internal/db/bun"
"git.ptzo.gdn/feditools/relay/internal/db/cachemem"
"git.ptzo.gdn/feditools/relay/internal/http"
"git.ptzo.gdn/feditools/relay/internal/kv/redis"
"git.ptzo.gdn/feditools/relay/internal/logic/logic1"
"git.ptzo.gdn/feditools/relay/internal/metrics"
"git.ptzo.gdn/feditools/relay/internal/runner/asynq"
"git.ptzo.gdn/feditools/relay/internal/token"
"github.com/spf13/viper"
"github.com/uptrace/uptrace-go/uptrace"
"os"
"os/signal"
"syscall"
)
// Start runs a worker migrations.
var Start action.Action = func(ctx context.Context) error {
l := logger.WithField("func", "Start")
l.Info("starting")
ctx, cancel := context.WithCancel(ctx)
// Configure OpenTelemetry with sensible defaults.
uptrace.ConfigureOpentelemetry(
// copy your project DSN here or use UPTRACE_DSN env var
//uptrace.WithDSN("https://<token>@uptrace.dev/<project_id>"),
uptrace.WithServiceName(viper.GetString(config.Keys.ApplicationName)),
uptrace.WithServiceVersion(viper.GetString(config.Keys.SoftwareVersion)),
)
// Send buffered spans and free resources.
defer func() {
l.Info("closing uptrace")
err := uptrace.Shutdown(context.Background())
if err != nil {
l.Errorf("closing uptrace: %s", err.Error())
}
}()
// create metrics server
metricsServer := metrics.New(viper.GetString(config.Keys.MetricsHTTPBind))
// create clock module
l.Debug("creating clock")
clockMod := clock.NewClock()
// create database client
l.Debug("creating database client")
dbClient, err := bun.New(ctx)
if err != nil {
l.Errorf("db: %s", err.Error())
cancel()
return err
}
dbCacheClient, err := cachemem.New(ctx, dbClient)
if err != nil {
l.Errorf("db: %s", err.Error())
cancel()
return err
}
defer func() {
err := dbCacheClient.Close(ctx)
if err != nil {
l.Errorf("closing db: %s", err.Error())
}
}()
// create http client
httpClient, err := http.NewClient(
ctx,
fmt.Sprintf("Go-http-client/2.0 (%s/%s; +https://%s/)",
viper.GetString(config.Keys.ApplicationName),
viper.GetString(config.Keys.SoftwareVersion),
viper.GetString(config.Keys.ServerExternalHostname),
),
viper.GetInt(config.Keys.HTTPClientTimeout),
)
if err != nil {
l.Errorf("http client: %s", err.Error())
cancel()
return err
}
// create kv client
kvClient, err := redis.New(ctx)
if err != nil {
l.Errorf("redis: %s", err.Error())
cancel()
return err
}
defer func() {
err := kvClient.Close(ctx)
if err != nil {
l.Errorf("closing redis: %s", err.Error())
}
}()
// create tokenizer
tokz, err := token.New()
if err != nil {
l.Errorf("create tokenizer: %s", err.Error())
cancel()
return err
}
// create logic module
l.Debug("creating logic module")
logicMod, err := logic1.New(ctx, clockMod, dbCacheClient, httpClient, kvClient, tokz)
if err != nil {
l.Errorf("logic: %s", err.Error())
cancel()
return err
}
// create runner
// create runner
l.Debug("creating runner module")
runnerAddr := viper.GetString(config.Keys.RedisAddress)
runnerPassword := viper.GetString(config.Keys.RedisPassword)
runnerDB := viper.GetInt(config.Keys.RedisDB)
if viper.GetString(config.Keys.RunnerAddress) != "" {
runnerAddr = viper.GetString(config.Keys.RunnerAddress)
runnerPassword = viper.GetString(config.Keys.RunnerPassword)
runnerDB = viper.GetInt(config.Keys.RunnerDB)
}
runnerMod, err := asynq.New(&asynq.Config{
Logic: logicMod,
Concurrency: viper.GetInt(config.Keys.RunnerConcurrency),
Address: runnerAddr,
Password: runnerPassword,
DB: runnerDB,
})
if err != nil {
l.Errorf("runner server: %s", err.Error())
cancel()
return err
}
logicMod.SetRunner(runnerMod)
// scheduler
scheduler, err := runnerMod.NewScheduler()
if err != nil {
l.Errorf("getting scheduler: %s", err.Error())
cancel()
return err
}
err = scheduler.Start()
if err != nil {
l.Errorf("starting scheduler: %s", err.Error())
cancel()
return err
}
defer func() {
l.Debug("closing scheduler")
err := scheduler.Stop()
if err != nil {
l.Errorf("closing scheduler: %s", err.Error())
}
}()
// ** start application **
errChan := make(chan error)
// Wait for SIGINT and SIGTERM (HIT CTRL-C)
stopSigChan := make(chan os.Signal)
signal.Notify(stopSigChan, syscall.SIGINT, syscall.SIGTERM)
// start metrics server
go func(m *metrics.Module, errChan chan error) {
l.Debug("starting metrics server")
err := m.Start()
if err != nil {
errChan <- fmt.Errorf("metrics server: %s", err.Error())
}
}(metricsServer, errChan)
// wait for event
select {
case sig := <-stopSigChan:
l.Infof("got sig: %s", sig)
cancel()
case err := <-errChan:
l.Fatal(err.Error())
cancel()
}
<-ctx.Done()
l.Infof("done")
return nil
}

View File

@ -2,7 +2,6 @@ package server
import (
"context"
"errors"
"fmt"
"git.ptzo.gdn/feditools/relay/cmd/relay/action"
"git.ptzo.gdn/feditools/relay/internal/clock"
@ -16,7 +15,6 @@ import (
"git.ptzo.gdn/feditools/relay/internal/logic/logic1"
"git.ptzo.gdn/feditools/relay/internal/metrics"
"git.ptzo.gdn/feditools/relay/internal/runner/asynq"
"git.ptzo.gdn/feditools/relay/internal/scheduler"
"git.ptzo.gdn/feditools/relay/internal/token"
"github.com/spf13/viper"
"github.com/uptrace/uptrace-go/uptrace"
@ -186,16 +184,6 @@ var Start action.Action = func(topCtx context.Context) error {
}
logicMod.SetRunner(runnerMod)
// create scheduler
schedulerMod, err := scheduler.New(logicMod, runnerMod)
if err != nil {
l.Errorf("scheduler: %s", err.Error())
cancel()
return err
}
logicMod.SetScheduler(schedulerMod)
// create http server
l.Debug("creating http server")
server, err := newHttpServer(
@ -231,13 +219,6 @@ var Start action.Action = func(topCtx context.Context) error {
}
}(metricsServer, errChan)
// start scheduler
go func(s *scheduler.Module, errChan chan error) {
l.Debug("starting scheduler server")
s.Start()
errChan <- errors.New("scheduler stopped")
}(schedulerMod, errChan)
// start webserver
go func(s *http.Server, errChan chan error) {
l.Debug("starting http server")

View File

@ -0,0 +1,15 @@
package flag
import (
"git.ptzo.gdn/feditools/relay/internal/config"
"github.com/spf13/cobra"
)
// Scheduler adds all flags for running the scheduler.
func Scheduler(cmd *cobra.Command, values config.Values) {
Redis(cmd, values)
Runner(cmd, values)
// metrics
cmd.PersistentFlags().String(config.Keys.MetricsHTTPBind, values.MetricsHTTPBind, usage.MetricsHTTPBind)
}

View File

@ -51,6 +51,7 @@ func main() {
rootCmd.AddCommand(accountCommands())
rootCmd.AddCommand(databaseCommands())
rootCmd.AddCommand(serverCommands())
rootCmd.AddCommand(schedulerCommands())
rootCmd.AddCommand(workerCommands())
err = rootCmd.Execute()

33
cmd/relay/scheduler.go Normal file
View File

@ -0,0 +1,33 @@
package main
import (
"git.ptzo.gdn/feditools/relay/cmd/relay/action/scheduler"
"git.ptzo.gdn/feditools/relay/cmd/relay/flag"
"git.ptzo.gdn/feditools/relay/internal/config"
"github.com/spf13/cobra"
)
// schedulerCommands returns the 'scheduler' subcommand
func schedulerCommands() *cobra.Command {
schedulerCmd := &cobra.Command{
Use: "scheduler",
Short: "controls a scheduler",
}
schedulerStartCmd := &cobra.Command{
Use: "start",
Short: "start the relay scheduler",
PreRunE: func(cmd *cobra.Command, args []string) error {
return preRun(cmd)
},
RunE: func(cmd *cobra.Command, args []string) error {
return run(cmd.Context(), scheduler.Start)
},
}
flag.Scheduler(schedulerStartCmd, config.Defaults)
schedulerCmd.AddCommand(schedulerStartCmd)
return schedulerCmd
}

3
go.mod
View File

@ -5,9 +5,6 @@ go 1.19
require (
git.ptzo.gdn/feditools/go-lib v0.20.2-0.20230110023750-5bd60af86f11
github.com/allegro/bigcache/v3 v3.1.0
github.com/contribsys/faktory v1.6.2
github.com/contribsys/faktory_worker_go v1.6.0
github.com/go-co-op/gocron v1.18.0
github.com/go-fed/activity v1.0.0
github.com/go-fed/httpsig v1.1.0
github.com/go-playground/validator/v10 v10.11.1

6
go.sum
View File

@ -81,10 +81,6 @@ github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWH
github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs=
github.com/cockroachdb/apd v1.1.0 h1:3LFP3629v+1aKXU5Q37mxmRxX/pIu1nijXydLShEq5I=
github.com/cockroachdb/apd v1.1.0/go.mod h1:8Sl8LxpKi29FqWXR16WEFZRNSz3SoPzUzeMeY4+DwBQ=
github.com/contribsys/faktory v1.6.2 h1:HuqJI9ZEeInN2nJg10WRy8zPpxNwVIZgACbex7wQG1A=
github.com/contribsys/faktory v1.6.2/go.mod h1:R8+inlM1rq3GzyG8iZUL7qhfNfXGIgcbQRvTHmSyuUI=
github.com/contribsys/faktory_worker_go v1.6.0 h1:ov69BLHL62i/wRLJwvuj5UphwgjMOINRCGW3KzrKOjk=
github.com/contribsys/faktory_worker_go v1.6.0/go.mod h1:XMNGn3sBJdqFGfTH4SkmYkMovhdkq5cDJj36wowfbNY=
github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
@ -119,8 +115,6 @@ github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmV
github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY=
github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/go-co-op/gocron v1.18.0 h1:SxTyJ5xnSN4byCq7b10LmmszFdxQlSQJod8s3gbnXxA=
github.com/go-co-op/gocron v1.18.0/go.mod h1:sD/a0Aadtw5CpflUJ/lpP9Vfdk979Wl1Sg33HPHg0FY=
github.com/go-fed/activity v1.0.0 h1:j7w3auHZnVCjUcgA1mE+UqSOjFBhvW2Z2res3vNol+o=
github.com/go-fed/activity v1.0.0/go.mod h1:v4QoPaAzjWZ8zN2VFVGL5ep9C02mst0hQYHUpQwso4Q=
github.com/go-fed/httpsig v0.1.1-0.20190914113940-c2de3672e5b5/go.mod h1:T56HUNYZUQ1AGUzhAYPugZfp36sKApVnGBgKlIY+aIE=

View File

@ -4,7 +4,6 @@ import (
libtemplate "git.ptzo.gdn/feditools/go-lib/template"
"git.ptzo.gdn/feditools/relay/internal/http/template"
"git.ptzo.gdn/feditools/relay/internal/language"
"git.ptzo.gdn/feditools/relay/internal/scheduler"
"net/http"
)
@ -75,18 +74,6 @@ func (m *Module) displayAdminJobs(w http.ResponseWriter, r *http.Request, config
Required: true,
Options: []template.FormSelectOption{
{},
{
Text: string(scheduler.JobMaintDeliveryErrorTimeout),
Value: string(scheduler.JobMaintDeliveryErrorTimeout),
},
{
Text: string(scheduler.JobUpdateAccountInfo),
Value: string(scheduler.JobUpdateAccountInfo),
},
{
Text: string(scheduler.JobUpdateInstanceInfo),
Value: string(scheduler.JobUpdateInstanceInfo),
},
},
Validation: config.FormRunJobJobValidation,
},

View File

@ -91,3 +91,21 @@ func (l *Localizer) TextStatistics() *LocalizedString {
string: text,
}
}
// TextStatus returns a translated phrase.
func (l *Localizer) TextStatus() *LocalizedString {
text, tag, err := l.localizer.LocalizeWithTag(&i18n.LocalizeConfig{
DefaultMessage: &i18n.Message{
ID: "Status",
Other: "Status",
},
})
if err != nil {
logger.WithField("func", "TextStatus").Warningf(missingTranslationWarning, err.Error())
}
return &LocalizedString{
language: tag,
string: text,
}
}

View File

@ -5,7 +5,6 @@ import (
"errors"
"git.ptzo.gdn/feditools/relay/internal/db"
"git.ptzo.gdn/feditools/relay/internal/models"
worker "github.com/contribsys/faktory_worker_go"
"github.com/sirupsen/logrus"
)
@ -137,11 +136,8 @@ func (l *Logic) AddBlocks(ctx context.Context, account *models.Account, blocks .
}
func (l *Logic) ProcessBlockAdd(ctx context.Context, blockID int64) error {
help := worker.HelperFor(ctx)
log := logger.WithFields(logrus.Fields{
"func": "ProcessBlockAdd",
"jid": help.Jid(),
})
// read block
@ -160,11 +156,8 @@ func (l *Logic) ProcessBlockAdd(ctx context.Context, blockID int64) error {
}
func (l *Logic) doBlockAdd(ctx context.Context, block *models.Block) error {
help := worker.HelperFor(ctx)
log := logger.WithFields(logrus.Fields{
"func": "doBlockAdd",
"jid": help.Jid(),
})
instance, err := l.db.ReadInstanceByDomain(ctx, block.Domain)
@ -181,11 +174,8 @@ func (l *Logic) doBlockAdd(ctx context.Context, block *models.Block) error {
}
func (l *Logic) doBlockAddSubdomains(ctx context.Context, block *models.Block) error {
help := worker.HelperFor(ctx)
log := logger.WithFields(logrus.Fields{
"func": "doBlockAddSubdomains",
"jid": help.Jid(),
})
instances, err := l.db.ReadInstancesWithDomainSuffix(ctx, block.Domain)

View File

@ -5,7 +5,6 @@ import (
"errors"
"git.ptzo.gdn/feditools/relay/internal/db"
"git.ptzo.gdn/feditools/relay/internal/models"
worker "github.com/contribsys/faktory_worker_go"
"github.com/sirupsen/logrus"
"time"
)
@ -75,11 +74,8 @@ func (l *Logic) DeleteBlock(ctx context.Context, account *models.Account, block
}
func (l *Logic) ProcessBlockDelete(ctx context.Context, blockID int64) error {
help := worker.HelperFor(ctx)
log := logger.WithFields(logrus.Fields{
"func": "ProcessBlockDelete",
"jid": help.Jid(),
})
// read block

View File

@ -5,7 +5,6 @@ import (
"errors"
"git.ptzo.gdn/feditools/relay/internal/db"
"git.ptzo.gdn/feditools/relay/internal/models"
worker "github.com/contribsys/faktory_worker_go"
"github.com/sirupsen/logrus"
)
@ -82,11 +81,8 @@ func (l *Logic) UpdateBlock(
}
func (l *Logic) ProcessBlockUpdate(ctx context.Context, blockID int64) error {
help := worker.HelperFor(ctx)
log := logger.WithFields(logrus.Fields{
"func": "ProcessBlockUpdate",
"jid": help.Jid(),
})
// read block
@ -105,11 +101,8 @@ func (l *Logic) ProcessBlockUpdate(ctx context.Context, blockID int64) error {
}
func (l *Logic) doBlockUpdate(ctx context.Context, block *models.Block) error {
help := worker.HelperFor(ctx)
log := logger.WithFields(logrus.Fields{
"func": "doBlockUpdate",
"jid": help.Jid(),
})
instances, err := l.db.ReadInstancesWithBlockID(ctx, block.ID)
@ -141,11 +134,8 @@ func (l *Logic) doBlockUpdate(ctx context.Context, block *models.Block) error {
}
func (l *Logic) doBlockUpdateSubdomains(ctx context.Context, block *models.Block) error {
help := worker.HelperFor(ctx)
log := logger.WithFields(logrus.Fields{
"func": "doBlockUpdateSubdomains",
"jid": help.Jid(),
})
instances, err := l.db.ReadInstancesWithDomainSuffix(ctx, block.Domain)

View File

@ -12,7 +12,6 @@ import (
"git.ptzo.gdn/feditools/relay/internal/notification"
"git.ptzo.gdn/feditools/relay/internal/path"
"git.ptzo.gdn/feditools/relay/internal/runner"
"git.ptzo.gdn/feditools/relay/internal/scheduler"
"git.ptzo.gdn/feditools/relay/internal/token"
"github.com/go-fed/activity/pub"
"github.com/go-fed/httpsig"
@ -33,7 +32,6 @@ type Logic struct {
kv kv.KV
notifier notification.Notifier
runner runner.Runner
scheduler *scheduler.Module
tokz *token.Tokenizer
tracer trace.Tracer
transport *fedihelper.Transport
@ -137,7 +135,3 @@ func (l *Logic) SetNotifier(n notification.Notifier) {
func (l *Logic) SetRunner(r runner.Runner) {
l.runner = r
}
func (l *Logic) SetScheduler(s *scheduler.Module) {
l.scheduler = s
}

View File

@ -2,25 +2,12 @@ package logic1
import (
"git.ptzo.gdn/feditools/relay/internal/logic"
"git.ptzo.gdn/feditools/relay/internal/scheduler"
)
func (l *Logic) GetSchedulerJobs() ([]logic.SchedulerJob, error) {
jobs := l.scheduler.Jobs()
logicJobs := make([]logic.SchedulerJob, len(jobs))
for i, j := range jobs {
logicJobs[i].Name = j.Tags()[0]
logicJobs[i].Running = j.IsRunning()
logicJobs[i].RunCount = j.RunCount()
logicJobs[i].LastRun = j.LastRun()
logicJobs[i].NextRun = j.NextRun()
logicJobs[i].LastError = j.Error()
}
return logicJobs, nil
return l.runner.Jobs()
}
func (l *Logic) RunSchedulerJob(job string) error {
return l.scheduler.Run(scheduler.Job(job))
return nil
}

View File

@ -11,9 +11,9 @@ type Scheduler interface {
type SchedulerJob struct {
Name string
Running bool
State string
RunCount int
LastRun time.Time
NextRun time.Time
LastError error
LastError string
}

View File

@ -32,7 +32,7 @@ func (r *Runner) EnqueueDeliverActivity(ctx context.Context, instanceID int64, a
task := asynq.NewTask(TypeDeliverActivity, payload, asynq.Queue(runner.QueueDelivery))
info, err := r.client.Enqueue(task, asynq.MaxRetry(5))
info, err := r.client.EnqueueContext(ctx, task, asynq.MaxRetry(5))
if err != nil {
l.Debugf("can't enqueue: %s", err.Error())

View File

@ -41,7 +41,7 @@ func (r *Runner) EnqueueInboxActivity(ctx context.Context, instanceID int64, act
task := asynq.NewTask(TypeInboxActivity, payload)
info, err := r.client.Enqueue(task, asynq.MaxRetry(5))
info, err := r.client.EnqueueContext(ctx, task, asynq.MaxRetry(5))
if err != nil {
l.Debugf("can't enqueue: %s", err.Error())

View File

@ -28,7 +28,7 @@ func (r *Runner) EnqueueProcessBlockAdd(ctx context.Context, blockID int64) erro
task := asynq.NewTask(TypeProcessBlockAdd, payload)
info, err := r.client.Enqueue(task)
info, err := r.client.EnqueueContext(ctx, task)
if err != nil {
l.Debugf("can't enqueue: %s", err.Error())

View File

@ -28,7 +28,7 @@ func (r *Runner) EnqueueProcessBlockDelete(ctx context.Context, blockID int64) e
task := asynq.NewTask(TypeProcessBlockDelete, payload)
info, err := r.client.Enqueue(task)
info, err := r.client.EnqueueContext(ctx, task)
if err != nil {
l.Debugf("can't enqueue: %s", err.Error())

View File

@ -28,7 +28,7 @@ func (r *Runner) EnqueueProcessBlockUpdate(ctx context.Context, blockID int64) e
task := asynq.NewTask(TypeProcessBlockUpdate, payload)
info, err := r.client.Enqueue(task)
info, err := r.client.EnqueueContext(ctx, task)
if err != nil {
l.Debugf("can't enqueue: %s", err.Error())

View File

@ -2,6 +2,7 @@ package asynq
import (
"context"
"fmt"
"github.com/hibiken/asynq"
)
@ -15,7 +16,7 @@ func (r *Runner) EnqueueMaintDeliveryErrorTimeout(ctx context.Context) error {
task := asynq.NewTask(TypeMaintDeliveryErrorTimeout, nil)
info, err := r.client.Enqueue(task)
info, err := r.client.EnqueueContext(ctx, task)
if err != nil {
l.Debugf("can't enqueue: %s", err.Error())
@ -32,5 +33,11 @@ func (r *Runner) handleMaintDeliveryErrorTimeout(ctx context.Context, _ *asynq.T
//l := logger.WithField("func", "handleMaintDeliveryErrorTimeout")
return r.logic.MaintDeliveryErrorTimeout(ctx, "")
err := r.logic.MaintDeliveryErrorTimeout(ctx, "")
if err != nil {
span.RecordError(err)
return fmt.Errorf("%s: %w", err.Error(), asynq.SkipRetry)
}
return nil
}

View File

@ -10,14 +10,15 @@ import (
)
func New(c *Config) (*Runner, error) {
client := asynq.NewClient(asynq.RedisClientOpt{
redisConf := asynq.RedisClientOpt{
Addr: c.Address,
Password: c.Password,
DB: c.DB,
})
}
return &Runner{
client: client,
client: asynq.NewClient(redisConf),
inspector: asynq.NewInspector(redisConf),
logic: c.Logic,
tracer: otel.Tracer("internal/runner/asynq"),
@ -30,6 +31,7 @@ func New(c *Config) (*Runner, error) {
type Runner struct {
client *asynq.Client
inspector *asynq.Inspector
logic logic.Logic
server *asynq.Server
tracer trace.Tracer
@ -68,7 +70,9 @@ func (r *Runner) Start(_ context.Context) error {
mux.HandleFunc(TypeMaintDeliveryErrorTimeout, r.handleMaintDeliveryErrorTimeout)
mux.HandleFunc(TypeSendNotification, r.handleSendNotification)
mux.HandleFunc(TypeUpdateAccountInfo, r.handleUpdateAccountInfo)
mux.HandleFunc(TypeUpdateAccountsInfo, r.handleUpdateAccountsInfo)
mux.HandleFunc(TypeUpdateInstanceInfo, r.handleUpdateInstanceInfo)
mux.HandleFunc(TypeUpdateInstancesInfo, r.handleUpdateInstancesInfo)
return r.server.Run(mux)
}
@ -78,3 +82,22 @@ func (r *Runner) Stop() error {
return nil
}
func (r *Runner) Jobs() ([]logic.SchedulerJob, error) {
jobs, err := r.inspector.ListScheduledTasks(runner.QueuePriority)
if err != nil {
return nil, err
}
logicJobs := make([]logic.SchedulerJob, len(jobs))
for i, j := range jobs {
logicJobs[i].Name = j.Type
logicJobs[i].State = j.State.String()
logicJobs[i].RunCount = 0
logicJobs[i].LastRun = j.CompletedAt
logicJobs[i].NextRun = j.NextProcessAt
logicJobs[i].LastError = j.LastErr
}
return logicJobs, nil
}

View File

@ -0,0 +1,61 @@
package asynq
import (
"git.ptzo.gdn/feditools/relay/internal/runner"
"github.com/hibiken/asynq"
)
func (r *Runner) NewScheduler() (*Scheduler, error) {
l := logger.WithField("func", "NewScheduler")
s := asynq.NewScheduler(
asynq.RedisClientOpt{
Addr: r.address,
Password: r.password,
DB: r.db,
},
nil,
)
// delivery error
taskMaintDeliveryErrorTimeout := asynq.NewTask(TypeMaintDeliveryErrorTimeout, nil)
entryID, err := s.Register("0 1 * * *", taskMaintDeliveryErrorTimeout, asynq.Queue(runner.QueuePriority))
if err != nil {
return nil, err
}
l.Debugf("registered task %s: %q\n", TypeMaintDeliveryErrorTimeout, entryID)
// update accounts
taskUpdateAccountsInfo := asynq.NewTask(TypeUpdateAccountsInfo, nil)
entryID, err = s.Register("0 2 * * *", taskUpdateAccountsInfo, asynq.Queue(runner.QueuePriority))
if err != nil {
return nil, err
}
l.Debugf("registered task %s: %q\n", TypeUpdateAccountsInfo, entryID)
// update instances
taskUpdateInstancesInfo := asynq.NewTask(TypeUpdateInstancesInfo, nil)
entryID, err = s.Register("0 3 * * *", taskUpdateInstancesInfo, asynq.Queue(runner.QueuePriority))
if err != nil {
return nil, err
}
l.Debugf("registered task %s: %q\n", TypeUpdateInstancesInfo, entryID)
return &Scheduler{
scheduler: s,
}, nil
}
type Scheduler struct {
scheduler *asynq.Scheduler
}
func (s *Scheduler) Start() error {
return s.scheduler.Start()
}
func (s *Scheduler) Stop() error {
s.scheduler.Shutdown()
return nil
}

View File

@ -32,7 +32,7 @@ func (r *Runner) EnqueueSendNotification(ctx context.Context, event models.Event
task := asynq.NewTask(TypeSendNotification, payload, asynq.Queue(runner.QueuePriority))
info, err := r.client.Enqueue(task)
info, err := r.client.EnqueueContext(ctx, task)
if err != nil {
l.Debugf("can't enqueue: %s", err.Error())

View File

@ -28,7 +28,7 @@ func (r *Runner) EnqueueUpdateAccountInfo(ctx context.Context, accountID int64)
task := asynq.NewTask(TypeUpdateAccountInfo, payload)
info, err := r.client.Enqueue(task)
info, err := r.client.EnqueueContext(ctx, task)
if err != nil {
l.Debugf("can't enqueue: %s", err.Error())

View File

@ -0,0 +1,23 @@
package asynq
import (
"context"
"fmt"
"github.com/hibiken/asynq"
)
const TypeUpdateAccountsInfo = "update:accounts"
func (r *Runner) handleUpdateAccountsInfo(ctx context.Context, _ *asynq.Task) error {
ctx, span := r.tracer.Start(ctx, "handleUpdateAccountsInfo")
defer span.End()
//l := logger.WithField("func", "handleUpdateAccountsInfo")
// process activity
if err := r.logic.EnqueueAccountInfoUpdates(ctx); err != nil {
return fmt.Errorf("%s: %w", err.Error(), asynq.SkipRetry)
}
return nil
}

View File

@ -28,7 +28,7 @@ func (r *Runner) EnqueueUpdateInstanceInfo(ctx context.Context, instanceID int64
task := asynq.NewTask(TypeUpdateInstanceInfo, payload)
info, err := r.client.Enqueue(task)
info, err := r.client.EnqueueContext(ctx, task)
if err != nil {
l.Debugf("can't enqueue: %s", err.Error())

View File

@ -0,0 +1,23 @@
package asynq
import (
"context"
"fmt"
"github.com/hibiken/asynq"
)
const TypeUpdateInstancesInfo = "update:instances"
func (r *Runner) handleUpdateInstancesInfo(ctx context.Context, _ *asynq.Task) error {
ctx, span := r.tracer.Start(ctx, "handleUpdateInstancesInfo")
defer span.End()
//l := logger.WithField("func", "handleUpdateInstancesInfo")
// process activity
if err := r.logic.EnqueueInstanceInfoUpdates(ctx); err != nil {
return fmt.Errorf("%s: %w", err.Error(), asynq.SkipRetry)
}
return nil
}

View File

@ -1,43 +0,0 @@
package faktory
import (
"context"
faktory "github.com/contribsys/faktory/client"
worker "github.com/contribsys/faktory_worker_go"
"github.com/sirupsen/logrus"
"strconv"
)
func (r *Runner) EnqueueUpdateAccountInfo(_ context.Context, accountID int64) error {
retry := 0
job := faktory.NewJob(JobUpdateAccountInfo, strconv.FormatInt(accountID, 10))
job.Retry = &retry
return r.manager.Pool.With(func(conn *faktory.Client) error {
return conn.Push(job)
})
}
func (r *Runner) updateAccountInfo(ctx context.Context, args ...interface{}) error {
help := worker.HelperFor(ctx)
l := logger.WithFields(logrus.Fields{
"func": "updateAccountInfo",
"jid": help.Jid(),
})
if len(args) != 1 {
l.Errorf("wrong number of arguments, got: %d, want: %d", len(args), 2)
}
// cast arguments
accountID, err := getInt64(args, 0)
if err != nil {
l.Error(err.Error())
return err
}
return r.logic.UpdateAccountInfo(ctx, help.Jid(), accountID)
}

View File

@ -1,120 +0,0 @@
package faktory
import (
"context"
"fmt"
"git.ptzo.gdn/feditools/go-lib/fedihelper"
"git.ptzo.gdn/feditools/relay/internal/runner"
faktory "github.com/contribsys/faktory/client"
worker "github.com/contribsys/faktory_worker_go"
"github.com/sirupsen/logrus"
"net/url"
"strconv"
)
func (r *Runner) EnqueueDeliverActivity(_ context.Context, instanceID int64, activity fedihelper.Activity) error {
retry := 8
job := faktory.NewJob(JobDeliverActivity, strconv.FormatInt(instanceID, 10), activity)
job.Queue = runner.QueueDelivery
job.Retry = &retry
return r.manager.Pool.With(func(conn *faktory.Client) error {
return conn.Push(job)
})
}
func (r *Runner) deliverActivity(ctx context.Context, args ...interface{}) error {
help := worker.HelperFor(ctx)
l := logger.WithFields(logrus.Fields{
"func": "deliverActivity",
"jid": help.Jid(),
})
if len(args) != 2 {
l.Errorf("wrong number of arguments, got: %d, want: %d", len(args), 2)
}
// cast arguments
instanceIDStr, ok := args[0].(string)
if !ok {
l.Errorf("argument 0 is not an string")
return fmt.Errorf("argument 0 is not an int")
}
instanceID, err := strconv.ParseInt(instanceIDStr, 10, 64)
if err != nil {
l.Errorf("cant parse int from argument 0: %s", err.Error())
return fmt.Errorf("cant parse int from argument 0: %s", err.Error())
}
activity, ok := args[1].(map[string]interface{})
if !ok {
l.Errorf("argument 1 is not an activity")
return fmt.Errorf("argument 1 is not an activity")
}
return r.logic.DeliverActivity(ctx, help.Jid(), instanceID, activity, false)
}
func (r *Runner) EnqueueInboxActivity(_ context.Context, instanceID int64, actorIRI string, activity fedihelper.Activity) error {
job := faktory.NewJob(JobInboxActivity, strconv.FormatInt(instanceID, 10), actorIRI, activity)
job.Queue = runner.QueueDefault
return r.manager.Pool.With(func(conn *faktory.Client) error {
return conn.Push(job)
})
}
func (r *Runner) inboxActivity(ctx context.Context, args ...interface{}) error {
help := worker.HelperFor(ctx)
l := logger.WithFields(logrus.Fields{
"func": "inboxActivity",
"jid": help.Jid(),
})
if len(args) != 3 {
l.Errorf("wrong number of arguments, got: %d, want: %d", len(args), 2)
}
// cast arguments
instanceIDStr, ok := args[0].(string)
if !ok {
l.Errorf("argument 0 is not an string, got %T", args[0])
return fmt.Errorf("argument 0 is not an int")
}
instanceID, err := strconv.ParseInt(instanceIDStr, 10, 64)
if err != nil {
l.Errorf("cant parse int from argument 0: %s", err.Error())
return fmt.Errorf("cant parse int from argument 0: %s", err.Error())
}
actorID, ok := args[1].(string)
if !ok {
l.Errorf("argument 1 is not an string, got %T", args[1])
return fmt.Errorf("argument 1 is not an actor")
}
actorIRI, err := url.Parse(actorID)
if err != nil {
l.Errorf("cant parse url from argument 1: %s", err.Error())
return fmt.Errorf("cant parse url from argument 1: %s", err.Error())
}
activity, ok := args[2].(map[string]interface{})
if !ok {
l.Errorf("argument 2 is not an activity, got %T", args[2])
return fmt.Errorf("argument 2 is not an activity")
}
// process activity
return r.logic.ProcessActivity(ctx, help.Jid(), instanceID, actorIRI, activity)
}

View File

@ -1,102 +0,0 @@
package faktory
import (
"context"
faktory "github.com/contribsys/faktory/client"
worker "github.com/contribsys/faktory_worker_go"
"github.com/sirupsen/logrus"
"strconv"
)
func (r *Runner) EnqueueProcessBlockAdd(_ context.Context, blockID int64) error {
job := faktory.NewJob(JobProcessBlockAdd, strconv.FormatInt(blockID, 10))
return r.manager.Pool.With(func(conn *faktory.Client) error {
return conn.Push(job)
})
}
func (r *Runner) EnqueueProcessBlockDelete(_ context.Context, blockID int64) error {
job := faktory.NewJob(JobProcessBlockDelete, strconv.FormatInt(blockID, 10))
return r.manager.Pool.With(func(conn *faktory.Client) error {
return conn.Push(job)
})
}
func (r *Runner) EnqueueProcessBlockUpdate(_ context.Context, blockID int64) error {
job := faktory.NewJob(JobProcessBlockUpdate, strconv.FormatInt(blockID, 10))
return r.manager.Pool.With(func(conn *faktory.Client) error {
return conn.Push(job)
})
}
func (r *Runner) processBlockAdd(ctx context.Context, args ...interface{}) error {
help := worker.HelperFor(ctx)
l := logger.WithFields(logrus.Fields{
"func": "processBlockAdd",
"jid": help.Jid(),
})
if len(args) != 1 {
l.Errorf("wrong number of arguments, got: %d, want: %d", len(args), 2)
}
// cast arguments
blockID, err := getInt64(args, 0)
if err != nil {
l.Error(err.Error())
return err
}
return r.logic.ProcessBlockAdd(ctx, blockID)
}
func (r *Runner) processBlockDelete(ctx context.Context, args ...interface{}) error {
help := worker.HelperFor(ctx)
l := logger.WithFields(logrus.Fields{
"func": "processBlockDelete",
"jid": help.Jid(),
})
if len(args) != 1 {
l.Errorf("wrong number of arguments, got: %d, want: %d", len(args), 2)
}
// cast arguments
blockID, err := getInt64(args, 0)
if err != nil {
l.Error(err.Error())
return err
}
return r.logic.ProcessBlockDelete(ctx, blockID)
}
func (r *Runner) processBlockUpdate(ctx context.Context, args ...interface{}) error {
help := worker.HelperFor(ctx)
l := logger.WithFields(logrus.Fields{
"func": "processBlockDelete",
"jid": help.Jid(),
})
if len(args) != 1 {
l.Errorf("wrong number of arguments, got: %d, want: %d", len(args), 2)
}
// cast arguments
blockID, err := getInt64(args, 0)
if err != nil {
l.Error(err.Error())
return err
}
return r.logic.ProcessBlockUpdate(ctx, blockID)
}

View File

@ -1,15 +0,0 @@
package faktory
const (
twice = 2
JobDeliverActivity = "DeliverActivity"
JobInboxActivity = "InboxActivity"
JobMaintDeliveryErrorTimeout = "MaintDeliveryErrorTimeout"
JobProcessBlockAdd = "ProcessBlockAdd"
JobProcessBlockDelete = "ProcessBlockDelete"
JobProcessBlockUpdate = "ProcessBlockUpdate"
JobSendNotification = "SendNotification"
JobUpdateAccountInfo = "UpdateAccountInfo"
JobUpdateInstanceInfo = "UpdateInstanceInfo"
)

View File

@ -1,43 +0,0 @@
package faktory
import (
"context"
faktory "github.com/contribsys/faktory/client"
worker "github.com/contribsys/faktory_worker_go"
"github.com/sirupsen/logrus"
"strconv"
)
func (r *Runner) EnqueueUpdateInstanceInfo(_ context.Context, instanceID int64) error {
retry := 0
job := faktory.NewJob(JobUpdateInstanceInfo, strconv.FormatInt(instanceID, 10))
job.Retry = &retry
return r.manager.Pool.With(func(conn *faktory.Client) error {
return conn.Push(job)
})
}
func (r *Runner) updateInstanceInfo(ctx context.Context, args ...interface{}) error {
help := worker.HelperFor(ctx)
l := logger.WithFields(logrus.Fields{
"func": "updateInstanceInfo",
"jid": help.Jid(),
})
if len(args) != 1 {
l.Errorf("wrong number of arguments, got: %d, want: %d", len(args), 2)
}
// cast arguments
instanceID, err := getInt64(args, 0)
if err != nil {
l.Error(err.Error())
return err
}
return r.logic.UpdateInstanceInfo(ctx, help.Jid(), instanceID)
}

View File

@ -1,9 +0,0 @@
package faktory
import (
"git.ptzo.gdn/feditools/relay/internal/log"
)
type empty struct{}
var logger = log.WithPackageField(empty{})

View File

@ -1,32 +0,0 @@
package faktory
import (
"context"
faktory "github.com/contribsys/faktory/client"
worker "github.com/contribsys/faktory_worker_go"
"github.com/sirupsen/logrus"
)
func (r *Runner) EnqueueMaintDeliveryErrorTimeout(_ context.Context) error {
job := faktory.NewJob(JobMaintDeliveryErrorTimeout)
job.Args = []interface{}{}
return r.manager.Pool.With(func(conn *faktory.Client) error {
return conn.Push(job)
})
}
func (r *Runner) maintDeliveryErrorTimeout(ctx context.Context, args ...interface{}) error {
help := worker.HelperFor(ctx)
l := logger.WithFields(logrus.Fields{
"func": "maintDeliveryErrorTimeout",
"jid": help.Jid(),
})
if len(args) != 0 {
l.Errorf("wrong number of arguments, got: %d, want: %d", len(args), 0)
}
return r.logic.MaintDeliveryErrorTimeout(ctx, help.Jid())
}

View File

@ -1,19 +0,0 @@
package faktory
import (
"context"
"git.ptzo.gdn/feditools/relay/internal/runner"
faktory "github.com/contribsys/faktory/client"
"go.opentelemetry.io/otel/trace"
)
func (r *Runner) Middleware(ctx context.Context, job *faktory.Job, next func(ctx context.Context) error) error {
opts := []trace.SpanStartOption{
trace.WithAttributes(runner.JobIDKey.String(job.Jid)),
trace.WithSpanKind(trace.SpanKindConsumer),
}
tctx, main := r.tracer.Start(ctx, job.Type, opts...)
defer main.End()
return next(tctx)
}

View File

@ -1,49 +0,0 @@
package faktory
import (
"context"
"fmt"
"git.ptzo.gdn/feditools/relay/internal/models"
"git.ptzo.gdn/feditools/relay/internal/runner"
faktory "github.com/contribsys/faktory/client"
worker "github.com/contribsys/faktory_worker_go"
"github.com/sirupsen/logrus"
)
func (r *Runner) EnqueueSendNotification(_ context.Context, event models.EventType, metadata map[string]interface{}) error {
job := faktory.NewJob(JobSendNotification, event, metadata)
job.Queue = runner.QueuePriority
return r.manager.Pool.With(func(conn *faktory.Client) error {
return conn.Push(job)
})
}
func (r *Runner) sendNotification(ctx context.Context, args ...interface{}) error {
help := worker.HelperFor(ctx)
l := logger.WithFields(logrus.Fields{
"func": "sendNotification",
"jid": help.Jid(),
})
if len(args) != 2 {
l.Errorf("wrong number of arguments, got: %d, want: %d", len(args), 2)
}
// cast arguments
event, ok := args[0].(string)
if !ok {
l.Errorf("argument 0 is not an string")
return fmt.Errorf("argument 0 is not an int")
}
metadata, ok := args[1].(map[string]interface{})
if !ok {
l.Errorf("argument 1 is not an activity, got %T", args[2])
return fmt.Errorf("argument 1 is not an activity")
}
return r.logic.SendNotification(ctx, help.Jid(), models.EventType(event), metadata)
}

View File

@ -1,65 +0,0 @@
package faktory
import (
"context"
"git.ptzo.gdn/feditools/relay/internal/config"
"git.ptzo.gdn/feditools/relay/internal/logic"
"git.ptzo.gdn/feditools/relay/internal/runner"
faktory "github.com/contribsys/faktory/client"
worker "github.com/contribsys/faktory_worker_go"
"github.com/spf13/viper"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
)
type Runner struct {
logic logic.Logic
manager *worker.Manager
tracer trace.Tracer
}
// New created a new logic module
func New(l logic.Logic) (*Runner, error) {
newRunner := &Runner{
logic: l,
tracer: otel.Tracer("internal/runner/faktory"),
}
faktoryPool, err := faktory.NewPool(viper.GetInt(config.Keys.RunnerPoolSize))
if err != nil {
return nil, err
}
// create manager
mgr := worker.NewManager()
mgr.Pool = faktoryPool
mgr.Concurrency = viper.GetInt(config.Keys.RunnerConcurrency)
mgr.ProcessWeightedPriorityQueues(map[string]int{runner.QueuePriority: 3, runner.QueueDefault: 2, runner.QueueDelivery: 1})
// add handlers
mgr.Use(newRunner.Middleware)
mgr.Register(JobDeliverActivity, newRunner.deliverActivity)
mgr.Register(JobInboxActivity, newRunner.inboxActivity)
mgr.Register(JobMaintDeliveryErrorTimeout, newRunner.maintDeliveryErrorTimeout)
mgr.Register(JobProcessBlockAdd, newRunner.processBlockAdd)
mgr.Register(JobProcessBlockDelete, newRunner.processBlockDelete)
mgr.Register(JobProcessBlockUpdate, newRunner.processBlockUpdate)
mgr.Register(JobSendNotification, newRunner.sendNotification)
mgr.Register(JobUpdateAccountInfo, newRunner.updateAccountInfo)
mgr.Register(JobUpdateInstanceInfo, newRunner.updateInstanceInfo)
newRunner.manager = mgr
return newRunner, nil
}
func (r *Runner) Start(ctx context.Context) {
l := logger.WithField("func", "Start")
go func() {
err := r.manager.RunWithContext(ctx)
if err != nil {
l.Errorf("run error: %s", err.Error())
}
}()
}

View File

@ -1,20 +0,0 @@
package faktory
import (
"fmt"
"strconv"
)
func getInt64(args []interface{}, index int) (int64, error) {
intString, ok := args[index].(string)
if !ok {
return 0, fmt.Errorf("argument %d is not a string", index)
}
newInt, err := strconv.ParseInt(intString, 10, 64)
if err != nil {
return 0, fmt.Errorf("cant parse int64 from argument %d: %s", index, err.Error())
}
return newInt, nil
}

View File

@ -3,6 +3,7 @@ package runner
import (
"context"
"git.ptzo.gdn/feditools/go-lib/fedihelper"
"git.ptzo.gdn/feditools/relay/internal/logic"
"git.ptzo.gdn/feditools/relay/internal/models"
)
@ -16,4 +17,5 @@ type Runner interface {
EnqueueSendNotification(ctx context.Context, event models.EventType, metadata map[string]interface{}) error
EnqueueUpdateAccountInfo(ctx context.Context, accountID int64) error
EnqueueUpdateInstanceInfo(ctx context.Context, instanceID int64) error
Jobs() ([]logic.SchedulerJob, error)
}

View File

@ -1,15 +0,0 @@
package scheduler
import (
"context"
"go.opentelemetry.io/otel/trace"
)
func (m *Module) updateAccountInfo() {
tctx, tracer := m.tracer.Start(context.Background(), "updateAccountInfo", trace.WithSpanKind(trace.SpanKindInternal))
defer tracer.End()
if err := m.logic.EnqueueAccountInfoUpdates(tctx); err != nil {
logger.WithField("func", "updateAccountInfo").Error(err.Error())
}
}

View File

@ -1,9 +0,0 @@
package scheduler
type Job string
const (
JobMaintDeliveryErrorTimeout Job = "MaintDeliveryErrorTimeout"
JobUpdateAccountInfo Job = "UpdateAccountInfo"
JobUpdateInstanceInfo Job = "UpdateInstanceInfo"
)

View File

@ -1,15 +0,0 @@
package scheduler
import (
"context"
"go.opentelemetry.io/otel/trace"
)
func (m *Module) updateInstanceInfo() {
tctx, tracer := m.tracer.Start(context.Background(), "updateInstanceInfo", trace.WithSpanKind(trace.SpanKindInternal))
defer tracer.End()
if err := m.logic.EnqueueInstanceInfoUpdates(tctx); err != nil {
logger.WithField("func", "updateInstanceInfo").Error(err.Error())
}
}

View File

@ -1,11 +0,0 @@
package scheduler
import (
"context"
)
func (m *Module) maintDeliveryErrorTimeout() {
if err := m.runner.EnqueueMaintDeliveryErrorTimeout(context.Background()); err != nil {
logger.WithField("func", "maintDeliveryErrorTimeout").Error(err.Error())
}
}

View File

@ -1,54 +0,0 @@
package scheduler
import (
"git.ptzo.gdn/feditools/relay/internal/logic"
"git.ptzo.gdn/feditools/relay/internal/runner"
"github.com/go-co-op/gocron"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
"time"
)
func New(l logic.Logic, r runner.Runner) (*Module, error) {
m := &Module{
logic: l,
runner: r,
scheduler: gocron.NewScheduler(time.UTC),
tracer: otel.Tracer("internal/scheduler"),
}
m.scheduler.TagsUnique()
m.scheduler.SingletonModeAll()
_, err := m.scheduler.Every(1).Day().At("01:00").Tag(string(JobMaintDeliveryErrorTimeout)).Do(m.maintDeliveryErrorTimeout)
if err != nil {
return nil, err
}
_, err = m.scheduler.Every(1).Hour().StartAt(timeHourMinute(0, 40)).Tag(string(JobUpdateAccountInfo)).Do(m.updateAccountInfo)
if err != nil {
return nil, err
}
_, err = m.scheduler.Every(1).Hour().StartAt(timeHourMinute(0, 10)).Tag(string(JobUpdateInstanceInfo)).Do(m.updateInstanceInfo)
if err != nil {
return nil, err
}
return m, nil
}
type Module struct {
logic logic.Logic
runner runner.Runner
scheduler *gocron.Scheduler
tracer trace.Tracer
}
func (m *Module) Jobs() []*gocron.Job {
return m.scheduler.Jobs()
}
func (m *Module) Start() {
m.scheduler.StartBlocking()
}

View File

@ -1,5 +0,0 @@
package scheduler
func (m *Module) Run(t Job) error {
return m.scheduler.RunByTag(string(t))
}

View File

@ -1,7 +0,0 @@
package scheduler
import "time"
func timeHourMinute(h, m int) time.Time {
return time.Date(2000, 1, 1, h, m, 0, 0, time.UTC)
}

View File

@ -1,674 +0,0 @@
Faktory is AGPL licensed. What does this mean? In short:
If you fork Faktory, make changes and allow others to access your modified Faktory,
the source code for those changes must be made available to those users.
Note the Faktory client and worker libraries are NOT covered by this license, only the server is AGPL licensed.
You do NOT need to open source any business logic or code for your background jobs.
Please email mike@contribsys.com if you have further licensing questions.
---------
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

View File

@ -1,373 +0,0 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

View File

@ -1,189 +0,0 @@
package client
import (
"encoding/json"
"fmt"
)
type BatchStatus struct {
Bid string `json:"bid"`
ParentBid string `json:"parent_bid,omitempty"`
Description string `json:"description,omitempty"`
CreatedAt string `json:"created_at"`
Total int64 `json:"total"`
Pending int64 `json:"pending"`
Failed int64 `json:"failed"`
// "" if pending,
// "1" if callback enqueued,
// "2" if callback finished successfully
CompleteState string `json:"complete_st"`
SuccessState string `json:"success_st"`
}
type Batch struct {
// Unique identifier for each batch.
// NB: the caller should not set this, it is generated
// by Faktory when the batch is persisted to Redis.
Bid string `json:"bid"`
ParentBid string `json:"parent_bid,omitempty"`
Description string `json:"description,omitempty"`
Success *Job `json:"success,omitempty"`
Complete *Job `json:"complete,omitempty"`
faktory *Client
committed bool
new bool
}
//
// Allocate a new Batch.
// Caller must set one or more callbacks and
// push one or more jobs in the batch.
//
// b := faktory.NewBatch(cl)
// b.Success = faktory.NewJob("MySuccessCallback", 12345)
// b.Jobs(func() error {
// b.Push(...)
// })
//
func NewBatch(cl *Client) *Batch {
return &Batch{
committed: false,
new: true,
faktory: cl,
}
}
// Push one or more jobs within this function.
// Job processing will start **immediately**
// but callbacks will not fire until Commit()
// is called, allowing you to push jobs in slowly
// and avoid the obvious race condition.
func (b *Batch) Jobs(fn func() error) error {
if b.new {
if _, err := b.faktory.BatchNew(b); err != nil {
return fmt.Errorf("cannot create new batch: %w", err)
}
}
if b.faktory == nil || b.committed {
return ErrBatchNotOpen
}
if err := fn(); err != nil {
return fmt.Errorf("cannot push jobs in the %q batch: %w", b.Bid, err)
}
return b.Commit()
}
func (b *Batch) Push(job *Job) error {
if b.new {
return ErrBatchNotOpen
}
if b.faktory == nil || b.committed {
return ErrBatchAlreadyCommitted
}
job.SetCustom("bid", b.Bid)
return b.faktory.Push(job)
}
// Commit any pushed jobs in the batch to Redis so they can fire callbacks.
// A Batch object can only be committed once.
// You must use client.BatchOpen to get a new copy if you want to commit more jobs.
func (b *Batch) Commit() error {
if b.new {
return ErrBatchNotOpen
}
if b.faktory == nil || b.committed {
return ErrBatchAlreadyCommitted
}
if err := b.faktory.BatchCommit(b.Bid); err != nil {
return fmt.Errorf("cannot commit %q batch: %w", b.Bid, err)
}
b.faktory = nil
b.committed = true
return nil
}
var (
ErrBatchAlreadyCommitted = fmt.Errorf("batch has already been committed, must reopen")
ErrBatchNotOpen = fmt.Errorf("batch must be opened before it can be used")
)
/////////////////////////////////////////////
// Low-level command API
func (c *Client) BatchCommit(bid string) error {
err := c.writeLine(c.wtr, "BATCH COMMIT", []byte(bid))
if err != nil {
return err
}
return c.ok(c.rdr)
}
func (c *Client) BatchNew(def *Batch) (*Batch, error) {
if def.Bid != "" {
return nil, fmt.Errorf("BID must be blank when creating a new Batch, cannot specify it")
}
bbytes, err := json.Marshal(def)
if err != nil {
return nil, err
}
err = c.writeLine(c.wtr, "BATCH NEW", bbytes)
if err != nil {
return nil, err
}
bid, err := c.readString(c.rdr)
if err != nil {
return nil, err
}
def.Bid = bid
def.new = false
def.faktory = c
return def, nil
}
func (c *Client) BatchStatus(bid string) (*BatchStatus, error) {
err := c.writeLine(c.wtr, "BATCH STATUS", []byte(bid))
if err != nil {
return nil, err
}
data, err := c.readResponse(c.rdr)
if err != nil {
return nil, err
}
var stat BatchStatus
err = json.Unmarshal(data, &stat)
if err != nil {
return nil, err
}
return &stat, nil
}
func (c *Client) BatchOpen(bid string) (*Batch, error) {
err := c.writeLine(c.wtr, "BATCH OPEN", []byte(bid))
if err != nil {
return nil, err
}
bbid, err := c.readString(c.rdr)
if err != nil {
return nil, err
}
b := &Batch{
Bid: bbid,
new: false,
faktory: c,
}
return b, nil
}

View File

@ -1,692 +0,0 @@
package client
import (
"bufio"
"crypto/sha256"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/contribsys/faktory/internal/pool"
)
const (
// This is the protocol version supported by this client.
// The server might be running an older or newer version.
ExpectedProtocolVersion = 2
)
var (
// Set this to a non-empty value in a consumer process
// e.g. see how faktory_worker_go sets this.
RandomProcessWid = ""
Labels = []string{"golang"}
)
// Dialer is the interface for creating a specialized net.Conn.
type Dialer interface {
Dial(network, addr string) (c net.Conn, err error)
}
// The Client structure represents a thread-unsafe connection
// to a Faktory server. It is recommended to use a connection pool
// of Clients in a multi-threaded process. See faktory_worker_go's
// internal connection pool for example.
type Client struct {
Location string
Options *ClientData
rdr *bufio.Reader
wtr *bufio.Writer
conn net.Conn
poolConn *pool.PoolConn
}
// ClientData is serialized to JSON and sent
// with the HELLO command. PasswordHash is required
// if the server is not listening on localhost.
// The WID (worker id) must be random and unique
// for each worker process. It can be a UUID, etc.
// Non-worker processes should leave WID empty.
//
// The other elements can be useful for debugging
// and are displayed on the Busy tab.
type ClientData struct {
Hostname string `json:"hostname"`
Wid string `json:"wid"`
Pid int `json:"pid"`
Labels []string `json:"labels"`
// this can be used by proxies to route the connection.
// it is ignored by Faktory.
Username string `json:"username"`
// Hash is hex(sha256(password + nonce))
PasswordHash string `json:"pwdhash"`
// The protocol version used by this client.
// The server can reject this connection if the version will not work
// The server advertises its protocol version in the HI.
Version int `json:"v"`
}
type Server struct {
Network string
Address string
Username string
Password string
Timeout time.Duration
TLS *tls.Config
}
// OpenWithDialer creates a *Client with the dialer.
func (s *Server) OpenWithDialer(dialer Dialer) (*Client, error) {
return DialWithDialer(s, s.Password, dialer)
}
func (s *Server) Open() (*Client, error) {
return Dial(s, s.Password)
}
func (s *Server) ReadFromEnv() error {
val, ok := os.LookupEnv("FAKTORY_PROVIDER")
if ok {
if strings.Contains(val, ":") {
return fmt.Errorf(`Error: FAKTORY_PROVIDER is not a URL. It is the name of the ENV var that contains the URL:
FAKTORY_PROVIDER=FOO_URL
FOO_URL=tcp://:mypassword@faktory.example.com:7419`)
}
uval, ok := os.LookupEnv(val)
if ok {
uri, err := url.Parse(uval)
if err != nil {
return err
}
s.Network = uri.Scheme
s.Address = fmt.Sprintf("%s:%s", uri.Hostname(), uri.Port())
if uri.User != nil {
s.Username = uri.User.Username()
s.Password, _ = uri.User.Password()
}
return nil
}
return fmt.Errorf("FAKTORY_PROVIDER set to invalid value: %s", val)
}
uval, ok := os.LookupEnv("FAKTORY_URL")
if ok {
uri, err := url.Parse(uval)
if err != nil {
return fmt.Errorf("cannot parse value of FAKTORY_URL environment variable: %w", err)
}
s.Network = uri.Scheme
s.Address = fmt.Sprintf("%s:%s", uri.Hostname(), uri.Port())
if uri.User != nil {
s.Username = uri.User.Username()
s.Password, _ = uri.User.Password()
}
return nil
}
return nil
}
func DefaultServer() *Server {
return &Server{"tcp", "localhost:7419", "", "", 1 * time.Second, &tls.Config{MinVersion: tls.VersionTLS12}}
}
// Open connects to a Faktory server based on
// environment variable conventions:
//
// • Use FAKTORY_PROVIDER to point to a custom URL variable.
// • Use FAKTORY_URL as a catch-all default.
//
// Use the URL to configure any necessary password:
//
// tcp://:mypassword@localhost:7419
//
// By default Open assumes localhost with no password
// which is appropriate for local development.
func Open() (*Client, error) {
srv := DefaultServer()
if err := srv.ReadFromEnv(); err != nil {
return nil, fmt.Errorf("cannot read configuration from env: %w", err)
}
// Connect to default localhost
return srv.Open()
}
// OpenWithDialer connects to a Faktory server
// following the same conventions as Open but
// instead uses dialer as the transport.
func OpenWithDialer(dialer Dialer) (*Client, error) {
srv := DefaultServer()
if err := srv.ReadFromEnv(); err != nil {
return nil, fmt.Errorf("cannot read configuration from env: %w", err)
}
// Connect to default localhost
return srv.OpenWithDialer(dialer)
}
// Dial connects to the remote faktory server with
// a Dialer reflecting the value of srv.Network; i.e.,
// a *tls.Dialer if "tcp+tls" and a *net.Dialer if
// not.
//
// client.Dial(client.Localhost, "topsecret")
//
func Dial(srv *Server, password string) (*Client, error) {
d := &net.Dialer{Timeout: srv.Timeout}
dialer := Dialer(d)
if srv.Network == "tcp+tls" {
dialer = &tls.Dialer{NetDialer: d, Config: srv.TLS}
}
return dial(srv, password, dialer)
}
// DialWithDialer connects to the faktory server
func DialWithDialer(srv *Server, password string, dialer Dialer) (*Client, error) {
return dial(srv, password, dialer)
}
// dial connects to the remote faktory server.
func dial(srv *Server, password string, dialer Dialer) (*Client, error) {
client := emptyClientData()
client.Username = srv.Username
var err error
var conn net.Conn
conn, err = dialer.Dial("tcp", srv.Address)
if err != nil {
return nil, err
}
if x, ok := conn.(*net.TCPConn); ok {
_ = x.SetKeepAlive(true)
}
r := bufio.NewReader(conn)
w := bufio.NewWriter(conn)
line, err := readString(r)
if err != nil {
conn.Close()
return nil, err
}
if strings.HasPrefix(line, "HI ") {
str := strings.TrimSpace(line)[3:]
var hi map[string]interface{}
err = json.Unmarshal([]byte(str), &hi)
if err != nil {
conn.Close()
return nil, err
}
v, ok := hi["v"].(float64)
if ok {
if ExpectedProtocolVersion != int(v) {
fmt.Println("Warning: server and client protocol versions out of sync:", v, ExpectedProtocolVersion)
}
}
salt, ok := hi["s"].(string)
if ok {
iter := 1
iterVal, ok := hi["i"]
if ok {
iter = int(iterVal.(float64))
}
client.PasswordHash = hash(password, salt, iter)
}
} else {
conn.Close()
return nil, fmt.Errorf("expecting HI but got: %s", line)
}
data, err := json.Marshal(client)
if err != nil {
return nil, fmt.Errorf("cannot JSON marshal: %w", err)
}
if err := writeLine(w, "HELLO", data); err != nil {
conn.Close()
return nil, err
}
err = ok(r)
if err != nil {
conn.Close()
return nil, err
}
return &Client{Options: client, Location: srv.Address, conn: conn, rdr: r, wtr: w}, nil
}
func (c *Client) Close() error {
_ = writeLine(c.wtr, "END", nil)
return c.conn.Close()
}
func (c *Client) Ack(jid string) error {
err := c.writeLine(c.wtr, "ACK", []byte(fmt.Sprintf(`{"jid":%q}`, jid)))
if err != nil {
return err
}
return c.ok(c.rdr)
}
// Result is map[JID]ErrorMessage
func (c *Client) PushBulk(jobs []*Job) (map[string]string, error) {
jobBytes, err := json.Marshal(jobs)
if err != nil {
return nil, err
}
err = c.writeLine(c.wtr, "PUSHB", jobBytes)
if err != nil {
return nil, err
}
data, err := c.readResponse(c.rdr)
if err != nil {
return nil, err
}
results := map[string]string{}
err = json.Unmarshal(data, &results)
if err != nil {
return nil, err
}
return results, nil
}
func (c *Client) Push(job *Job) error {
jobBytes, err := json.Marshal(job)
if err != nil {
return err
}
err = c.writeLine(c.wtr, "PUSH", jobBytes)
if err != nil {
return err
}
return c.ok(c.rdr)
}
func (c *Client) Fetch(q ...string) (*Job, error) {
if len(q) == 0 {
return nil, fmt.Errorf("Fetch must be called with one or more queue names")
}
err := c.writeLine(c.wtr, "FETCH", []byte(strings.Join(q, " ")))
if err != nil {
return nil, err
}
data, err := c.readResponse(c.rdr)
if err != nil {
return nil, err
}
if len(data) == 0 {
return nil, nil
}
var job Job
err = json.Unmarshal(data, &job)
if err != nil {
return nil, err
}
return &job, nil
}
/*
buff := make([]byte, 4096)
count := runtime.Stack(buff, false)
str := string(buff[0:count])
bt := strings.Split(str, "\n")
*/
// Fail notifies Faktory that a job failed with the given error.
// If backtrace is non-nil, it is assumed to be the output from
// runtime/debug.Stack().
func (c *Client) Fail(jid string, err error, backtrace []byte) error {
failure := map[string]interface{}{
"message": err.Error(),
"errtype": "unknown",
"jid": jid,
}
if backtrace != nil {
str := string(backtrace)
bt := strings.Split(str, "\n")
failure["backtrace"] = bt[3:]
}
failbytes, err := json.Marshal(failure)
if err != nil {
return err
}
err = c.writeLine(c.wtr, "FAIL", failbytes)
if err != nil {
return err
}
return c.ok(c.rdr)
}
func (c *Client) Flush() error {
err := c.writeLine(c.wtr, "FLUSH", nil)
if err != nil {
return err
}
return c.ok(c.rdr)
}
// List queues explicitly or use "*" to remove all known queues
func (c *Client) RemoveQueues(names ...string) error {
err := c.writeLine(c.wtr, "QUEUE REMOVE", []byte(strings.Join(names, " ")))
if err != nil {
return err
}
return c.ok(c.rdr)
}
// List queues explicitly or use "*" to pause all known queues
func (c *Client) PauseQueues(names ...string) error {
err := c.writeLine(c.wtr, "QUEUE PAUSE", []byte(strings.Join(names, " ")))
if err != nil {
return err
}
return c.ok(c.rdr)
}
// List queues explicitly or use "*" to resume all known queues
func (c *Client) ResumeQueues(names ...string) error {
err := c.writeLine(c.wtr, "QUEUE RESUME", []byte(strings.Join(names, " ")))
if err != nil {
return err
}
return c.ok(c.rdr)
}
func (c *Client) Info() (map[string]interface{}, error) {
err := c.writeLine(c.wtr, "INFO", nil)
if err != nil {
return nil, err
}
data, err := c.readResponse(c.rdr)
if err != nil {
return nil, err
}
if len(data) == 0 {
return nil, nil
}
var hash map[string]interface{}
err = json.Unmarshal(data, &hash)
if err != nil {
return nil, err
}
return hash, nil
}
func (c *Client) QueueSizes() (map[string]uint64, error) {
hash, err := c.Info()
if err != nil {
return nil, err
}
faktory, ok := hash["faktory"].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("invalid info hash: %s", hash)
}
queues, ok := faktory["queues"].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("invalid info hash: %s", hash)
}
sizes := make(map[string]uint64)
for name, size := range queues {
size, ok := size.(float64)
if !ok {
return nil, fmt.Errorf("invalid queue size: %v", size)
}
sizes[name] = uint64(size)
}
return sizes, nil
}
func (c *Client) Generic(cmdline string) (string, error) {
err := c.writeLine(c.wtr, cmdline, nil)
if err != nil {
return "", err
}
return c.readString(c.rdr)
}
/*
* The first arg to Beat allows a worker process to report its current lifecycle state
* to Faktory. All worker processes must follow the same basic lifecycle:
*
* (startup) -> "" -> "quiet" -> "terminate"
*
* Quiet allows the process to finish its current work without fetching any new work.
* Terminate means the process should exit within X seconds, usually ~30 seconds.
*/
func (c *Client) Beat(args ...string) (string, error) {
state := ""
if len(args) > 0 {
state = args[0]
}
hash := map[string]interface{}{}
hash["wid"] = RandomProcessWid
hash["rss_kb"] = RssKb()
if state != "" {
hash["current_state"] = state
}
data, err := json.Marshal(hash)
if err != nil {
return "", err
}
cmd := fmt.Sprintf("BEAT %s", data)
val, err := c.Generic(cmd)
if val == "OK" {
return "", nil
}
return val, err
}
func (c *Client) writeLine(wtr *bufio.Writer, op string, payload []byte) error {
_ = c.conn.SetWriteDeadline(time.Now().Add(5 * time.Second))
err := writeLine(wtr, op, payload)
if err != nil {
c.markUnusable()
}
return err
}
func (c *Client) readResponse(rdr *bufio.Reader) ([]byte, error) {
_ = c.conn.SetReadDeadline(time.Now().Add(5 * time.Second))
data, err := readResponse(rdr)
if err != nil {
if _, ok := err.(*ProtocolError); !ok {
c.markUnusable()
}
}
return data, err
}
func (c *Client) ok(rdr *bufio.Reader) error {
_ = c.conn.SetReadDeadline(time.Now().Add(5 * time.Second))
err := ok(rdr)
if err != nil {
if _, ok := err.(*ProtocolError); !ok {
c.markUnusable()
}
}
return err
}
func (c *Client) readString(rdr *bufio.Reader) (string, error) {
_ = c.conn.SetReadDeadline(time.Now().Add(5 * time.Second))
s, err := readString(rdr)
if err != nil {
if _, ok := err.(*ProtocolError); !ok {
c.markUnusable()
}
}
return s, err
}
func (c *Client) markUnusable() {
if c.poolConn == nil {
// if this client was not created as part of a pool,
// this call becomes a no-op
return
}
c.poolConn.MarkUnusable()
}
//////////////////////////////////////////////////
func emptyClientData() *ClientData {
client := &ClientData{}
hs, err := os.Hostname()
if err != nil {
panic(err)
}
client.Hostname = hs
client.Pid = os.Getpid()
client.Wid = RandomProcessWid
client.Labels = Labels
client.Version = ExpectedProtocolVersion
return client
}
func writeLine(wtr *bufio.Writer, op string, payload []byte) error {
// util.Debugf("> %s %s", op, string(payload))
_, err := wtr.WriteString(op)
if payload != nil {
if err == nil {
_, err = wtr.WriteString(" ")
}
if err == nil {
_, err = wtr.Write(payload)
}
}
if err == nil {
_, err = wtr.WriteString("\r\n")
}
if err == nil {
err = wtr.Flush()
}
return err
}
func ok(rdr *bufio.Reader) error {
val, err := readResponse(rdr)
if err != nil {
return err
}
if string(val) == "OK" {
return nil
}
return fmt.Errorf("invalid response: %s", string(val))
}
func readString(rdr *bufio.Reader) (string, error) {
val, err := readResponse(rdr)
if err != nil {
return "", err
}
if val == nil {
return "", nil
}
return string(val), nil
}
type ProtocolError struct {
msg string
}
func (pe *ProtocolError) Error() string {
return pe.msg
}
func readResponse(rdr *bufio.Reader) ([]byte, error) {
chr, err := rdr.ReadByte()
if err != nil {
return nil, err
}
line, err := rdr.ReadBytes('\n')
if err != nil {
return nil, err
}
line = line[:len(line)-2]
switch chr {
case '$':
// read length $10\r\n
count, err := strconv.Atoi(string(line))
if err != nil {
return nil, err
}
if count == -1 {
return nil, nil
}
var buff []byte
if count > 0 {
buff = make([]byte, count)
_, err = io.ReadFull(rdr, buff)
if err != nil {
return nil, err
}
}
_, err = rdr.ReadString('\n')
if err != nil {
return nil, err
}
// util.Debugf("< %s%s", string(chr), string(line))
// util.Debugf("< %s", string(buff))
return buff, nil
case '-':
return nil, &ProtocolError{msg: string(line)}
default:
// util.Debugf("< %s%s", string(chr), string(line))
return line, nil
}
}
func hash(pwd, salt string, iterations int) string {
data := []byte(pwd + salt)
hash := sha256.Sum256(data)
if iterations > 1 {
for i := 1; i < iterations; i++ {
hash = sha256.Sum256(hash[:])
}
}
return fmt.Sprintf("%x", hash)
}

View File

@ -1,8 +0,0 @@
// +build darwin freebsd netbsd openbsd
package client
func RssKb() int64 {
// TODO Submit a PR?
return 0
}

View File

@ -1,37 +0,0 @@
package client
import (
"bytes"
"io/ioutil"
"os"
"strconv"
"strings"
)
func RssKb() int64 {
path := "/proc/self/status"
if _, err := os.Stat(path); err != nil {
return 0
}
content, err := ioutil.ReadFile(path)
if err != nil {
return 0
}
lines := bytes.Split(content, []byte("\n"))
for idx := range lines {
if lines[idx][0] == 'V' {
ls := string(lines[idx])
if strings.Contains(ls, "VmRSS") {
str := strings.Split(ls, ":")[1]
intt, err := strconv.Atoi(str)
if err != nil {
return 0
}
return int64(intt)
}
}
}
return 0
}

View File

@ -1,6 +0,0 @@
package client
func RssKb() int64 {
// TODO Submit a PR?
return 0
}

View File

@ -1,6 +0,0 @@
package client
var (
Name = "Faktory"
Version = "1.6.2"
)

View File

@ -1,127 +0,0 @@
package client
import (
cryptorand "crypto/rand"
"encoding/base64"
mathrand "math/rand"
"time"
)
type UniqueUntil string
var (
RetryPolicyDefault = 25
RetryPolicyEmphemeral = 0
RetryPolicyDirectToMorgue = -1
)
const (
UntilSuccess UniqueUntil = "success" // default
UntilStart UniqueUntil = "start"
)
type Failure struct {
RetryCount int `json:"retry_count"`
RetryRemaining int `json:"remaining"`
FailedAt string `json:"failed_at"`
NextAt string `json:"next_at,omitempty"`
ErrorMessage string `json:"message,omitempty"`
ErrorType string `json:"errtype,omitempty"`
Backtrace []string `json:"backtrace,omitempty"`
}
type Job struct {
// required
Jid string `json:"jid"`
Queue string `json:"queue"`
Type string `json:"jobtype"`
Args []interface{} `json:"args"`
// optional
CreatedAt string `json:"created_at,omitempty"`
EnqueuedAt string `json:"enqueued_at,omitempty"`
At string `json:"at,omitempty"`
ReserveFor int `json:"reserve_for,omitempty"`
Retry *int `json:"retry"`
Backtrace int `json:"backtrace,omitempty"`
Failure *Failure `json:"failure,omitempty"`
Custom map[string]interface{} `json:"custom,omitempty"`
}
// Clients should use this constructor to build a Job, not allocate
// a bare struct directly.
func NewJob(jobtype string, args ...interface{}) *Job {
return &Job{
Type: jobtype,
Queue: "default",
Args: args,
Jid: RandomJid(),
CreatedAt: time.Now().UTC().Format(time.RFC3339Nano),
Retry: &RetryPolicyDefault,
}
}
func RandomJid() string {
bytes := make([]byte, 12)
_, err := cryptorand.Read(bytes)
if err != nil {
//nolint:gosec
mathrand.Read(bytes)
}
return base64.RawURLEncoding.EncodeToString(bytes)
}
func (j *Job) GetCustom(name string) (interface{}, bool) {
if j.Custom == nil {
return nil, false
}
val, ok := j.Custom[name]
return val, ok
}
// Set custom metadata for this job. Faktory reserves all
// element names starting with "_" for internal use, e.g.
// SetCustom("_txid", "12345")
func (j *Job) SetCustom(name string, value interface{}) *Job {
if j.Custom == nil {
j.Custom = map[string]interface{}{}
}
j.Custom[name] = value
return j
}
////////////////////////////////////////////
// Faktory Enterprise helpers
//
// These helpers allow you to configure several Faktory Enterprise features.
// They will have no effect unless you are running Faktory Enterprise.
// Configure this job to be unique for +secs+ seconds or until the job
// has been successfully processed.
func (j *Job) SetUniqueFor(secs uint) *Job {
return j.SetCustom("unique_for", secs)
}
// Configure the uniqueness deadline for this job, legal values
// are:
//
// - "success" - the job will be considered unique until it has successfully processed
// or the +unique_for+ TTL has passed, this is the default value.
// - "start" - the job will be considered unique until it starts processing. Retries
// may lead to multiple copies of the job running.
func (j *Job) SetUniqueness(until UniqueUntil) *Job {
return j.SetCustom("unique_until", until)
}
// Configure the TTL for this job. After this point in time, the job will be
// discarded rather than executed.
func (j *Job) SetExpiresAt(expiresAt time.Time) *Job {
return j.SetCustom("expires_at", expiresAt.Format(time.RFC3339Nano))
}
func (j *Job) SetExpiresIn(expiresIn time.Duration) *Job {
return j.SetCustom("expires_at", time.Now().Add(expiresIn).Format(time.RFC3339Nano))
}

View File

@ -1,153 +0,0 @@
package client
import (
"encoding/json"
)
//
// Faktory's Mutate API allows clients to directly mutate the various
// persistent sets within Faktory. These use cases are typically for
// repair or data migration purposes.
//
// THESE APIs SHOULD NEVER BE USED WITHIN APP LOGIC.
// Many Mutate API use cases will have poor performance:
// O(N), O(N log N), or even O(M*N).
type Structure string
type JobFilter struct {
Jids []string `json:"jids,omitempty"`
Regexp string `json:"regexp,omitempty"`
Jobtype string `json:"jobtype,omitempty"`
}
func (jf JobFilter) WithJids(jids ...string) JobFilter {
jf.Jids = jids
return jf
}
func (jf JobFilter) Matching(pattern string) JobFilter {
jf.Regexp = pattern
return jf
}
func (jf JobFilter) OfType(jobtype string) JobFilter {
jf.Jobtype = jobtype
return jf
}
const (
Scheduled Structure = "scheduled"
Retries Structure = "retries"
Dead Structure = "dead"
)
var (
Everything = JobFilter{
Regexp: "*",
}
)
// Match jobs with the given JIDs. Warning: O(m*n), very slow
// because it has to pull every job into Faktory and check the JID
// against the list.
//
// If you pass in a single JID, it will devolve to matching within Redis
// and perform much faster. For that reason, it might be better to
// handle one JID at a time.
func WithJids(jids ...string) JobFilter {
return JobFilter{
Jids: jids,
}
}
// This is a generic pattern match across the entire job JSON payload.
// Be very careful that you don't accidentally match some unintended part
// of the payload.
//
// NB: your pattern should have * on each side. The pattern is passed
// directly to Redis.
//
// Example: discard any job retries whose payload contains the special word "uid:12345":
//
// client.Discard(faktory.Retries, faktory.Matching("*uid:12345*"))
//
// See the Redis SCAN documentation for pattern matching examples.
// https://redis.io/commands/scan
func Matching(pattern string) JobFilter {
return JobFilter{
Regexp: pattern,
}
}
// Matches jobs based on the exact Jobtype. This is pretty fast because
// it devolves to Matching(`"jobtype":"$ARG"`) and matches within Redis.
func OfType(jobtype string) JobFilter {
return JobFilter{
Jobtype: jobtype,
}
}
type Operation struct {
Cmd string `json:"cmd"`
Target Structure `json:"target"`
Filter *JobFilter `json:"filter,omitempty"`
}
// Commands which allow you to perform admin tasks on various Faktory structures.
// These are NOT designed to be used in business logic but rather for maintenance,
// data repair, migration, etc. They can have poor scalability or performance edge
// cases.
//
// Generally these operations are O(n) or worse. They will get slower as your
// data gets bigger.
type MutateClient interface {
// Move the given jobs from structure to the Dead set.
// Faktory will not touch them anymore but you can still see them in the Web UI.
//
// Kill(Retries, OfType("DataSyncJob").WithJids("abc", "123"))
Kill(name Structure, filter JobFilter) error
// Move the given jobs to their associated queue so they can be immediately
// picked up and processed.
Requeue(name Structure, filter JobFilter) error
// Throw away the given jobs, e.g. if you want to delete all jobs named "QuickbooksSyncJob"
//
// Discard(Dead, OfType("QuickbooksSyncJob"))
Discard(name Structure, filter JobFilter) error
// Empty the entire given structure, e.g. if you want to clear all retries.
// This is very fast as it is special cased by Faktory.
Clear(name Structure) error
}
func (c *Client) Kill(name Structure, filter JobFilter) error {
return c.mutate(Operation{Cmd: "kill", Target: name, Filter: &filter})
}
func (c *Client) Requeue(name Structure, filter JobFilter) error {
return c.mutate(Operation{Cmd: "requeue", Target: name, Filter: &filter})
}
func (c *Client) Discard(name Structure, filter JobFilter) error {
return c.mutate(Operation{Cmd: "discard", Target: name, Filter: &filter})
}
func (c *Client) Clear(name Structure) error {
return c.mutate(Operation{Cmd: "clear", Target: name, Filter: nil})
}
func (c *Client) mutate(op Operation) error {
j, err := json.Marshal(op)
if err != nil {
return err
}
err = writeLine(c.wtr, "MUTATE", j)
if err != nil {
return err
}
return ok(c.rdr)
}

View File

@ -1,4 +0,0 @@
// Code within this package is licensed according to the MPL found
// in the LICENSE file.
package client

View File

@ -1,69 +0,0 @@
package client
import (
"fmt"
"github.com/contribsys/faktory/internal/pool"
)
type Pool struct {
pool.Pool
}
// NewPool creates a new Pool object through which multiple clients will be managed on your behalf.
//
// Call Get() to retrieve a client instance and Put() to return it to the pool. If you do not call
// Put(), the connection will be leaked, and the pool will stop working once it hits capacity.
//
// Do NOT call Close() on the client, as the lifecycle is managed internally.
//
// The dialer clients in this pool use is determined by the URI scheme in FAKTORY_PROVIDER.
func NewPool(capacity int) (*Pool, error) {
return newPool(capacity, func() (pool.Closeable, error) { return Open() })
}
// NewPoolWithDialer creates a new Pool object similar to NewPool but clients will use the
// provided dialer instead of default ones.
func NewPoolWithDialer(capacity int, dialer Dialer) (*Pool, error) {
fn := func() (pool.Closeable, error) { return OpenWithDialer(dialer) }
return newPool(capacity, fn)
}
// newPool creates a *Pool channel with the provided capacity and opener.
func newPool(capacity int, opener pool.Factory) (*Pool, error) {
var p Pool
var err error
p.Pool, err = pool.NewChannelPool(0, capacity, opener)
return &p, err
}
// Get retrieves a Client from the pool. This Client is created, internally, by calling
// the Open() function, and has all the same behaviors.
func (p *Pool) Get() (*Client, error) {
conn, err := p.Pool.Get()
if err != nil {
return nil, err
}
pc := conn.(*pool.PoolConn)
client, ok := pc.Closeable.(*Client)
if !ok {
// Because we control the entire lifecycle of the pool, internally, this should never happen.
panic(fmt.Sprintf("Connection is not a Faktory client instance: %+v", conn))
}
client.poolConn = pc
return client, nil
}
// Put returns a client to the pool.
func (p *Pool) Put(client *Client) {
client.poolConn.Close()
}
func (p *Pool) With(fn func(conn *Client) error) error {
conn, err := p.Get()
if err != nil {
return err
}
defer p.Put(conn)
return fn(conn)
}

View File

@ -1,74 +0,0 @@
package client
import (
"encoding/json"
"fmt"
"time"
"github.com/contribsys/faktory/util"
)
type JobTrack struct {
Jid string `json:"jid"`
Percent int `json:"percent,omitempty"`
Description string `json:"desc,omitempty"`
State string `json:"state"`
UpdatedAt string `json:"updated_at"`
}
func (c *Client) TrackGet(jid string) (*JobTrack, error) {
err := c.writeLine(c.wtr, "TRACK GET", []byte(jid))
if err != nil {
return nil, err
}
data, err := c.readResponse(c.rdr)
if err != nil {
return nil, err
}
var trck JobTrack
err = json.Unmarshal(data, &trck)
if err != nil {
return nil, err
}
return &trck, nil
}
type setJobTrack struct {
Jid string `json:"jid"`
Percent int `json:"percent,omitempty"`
Description string `json:"desc,omitempty"`
ReserveUntil string `json:"reserve_until,omitempty"`
}
func (c *Client) TrackSet(jid string, percent int, desc string, reserveUntil *time.Time) error {
if jid == "" {
return fmt.Errorf("Job Track missing JID")
}
tset := setJobTrack{
Jid: jid,
Description: desc,
Percent: percent,
}
if reserveUntil != nil && time.Now().Before(*reserveUntil) {
tset.ReserveUntil = util.Thens(*reserveUntil)
}
return c.trackSet(&tset)
}
func (c *Client) trackSet(tset *setJobTrack) error {
data, err := json.Marshal(tset)
if err != nil {
return err
}
err = c.writeLine(c.wtr, "TRACK SET", data)
if err != nil {
return err
}
return c.ok(c.rdr)
}

View File

@ -1,219 +0,0 @@
/*
The MIT License (MIT)
Copyright (c) 2013 Fatih Arslan
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package pool
import (
"errors"
"fmt"
"sync"
)
var (
// ErrClosed is the error resulting if the pool is closed via pool.Close().
ErrClosed = errors.New("pool is closed")
)
// Closeable interface describes a closable implementation. The underlying procedure of the Close() function is determined by its implementation
type Closeable interface {
// Close closes the object
Close() error
}
// Pool interface describes a pool implementation. A pool should have maximum
// capacity. An ideal pool is threadsafe and easy to use.
type Pool interface {
// Get returns a new connection from the pool. Closing the connections puts
// it back to the Pool. Closing it when the pool is destroyed or full will
// be counted as an error.
Get() (Closeable, error)
// Close closes the pool and all its connections. After Close() the pool is
// no longer usable.
Close()
// Len returns the current number of connections of the pool.
Len() int
}
// PoolConn is a wrapper around net.Conn to modify the the behavior of
// net.Conn's Close() method.
type PoolConn struct {
Closeable
mu sync.RWMutex
c *channelPool
unusable bool
}
// Close puts the given connects back to the pool instead of closing it.
func (p *PoolConn) Close() error {
p.mu.RLock()
defer p.mu.RUnlock()
if p.unusable {
if p.Closeable != nil {
return p.Closeable.Close()
}
return nil
}
return p.c.put(p.Closeable)
}
// MarkUnusable marks the connection not usable any more, to let the pool close it instead of returning it to pool.
func (p *PoolConn) MarkUnusable() {
p.mu.Lock()
p.unusable = true
p.mu.Unlock()
}
// wrapConn wraps a standard net.Conn to a poolConn net.Conn.
func (c *channelPool) wrapConn(conn Closeable) Closeable {
p := &PoolConn{c: c}
p.Closeable = conn
return p
}
// channelPool implements the Pool interface based on buffered channels.
type channelPool struct {
// storage for our net.Conn connections
mu sync.Mutex
conns chan Closeable
// net.Conn generator
factory Factory
}
// Factory is a function to create new connections.
type Factory func() (Closeable, error)
// NewChannelPool returns a new pool based on buffered channels with an initial
// capacity and maximum capacity. Factory is used when initial capacity is
// greater than zero to fill the pool. A zero initialCap doesn't fill the Pool
// until a new Get() is called. During a Get(), If there is no new connection
// available in the pool, a new connection will be created via the Factory()
// method.
func NewChannelPool(initialCap, maxCap int, factory Factory) (Pool, error) {
if initialCap < 0 || maxCap <= 0 || initialCap > maxCap {
return nil, errors.New("invalid capacity settings")
}
c := &channelPool{
conns: make(chan Closeable, maxCap),
factory: factory,
}
// create initial connections, if something goes wrong,
// just close the pool error out.
for i := 0; i < initialCap; i++ {
conn, err := factory()
if err != nil {
c.Close()
return nil, fmt.Errorf("factory is not able to fill the pool: %w", err)
}
c.conns <- conn
}
return c, nil
}
func (c *channelPool) getConns() chan Closeable {
c.mu.Lock()
conns := c.conns
c.mu.Unlock()
return conns
}
// Get implements the Pool interfaces Get() method. If there is no new
// connection available in the pool, a new connection will be created via the
// Factory() method.
func (c *channelPool) Get() (Closeable, error) {
conns := c.getConns()
if conns == nil {
return nil, ErrClosed
}
// wrap our connections with out custom net.Conn implementation (wrapConn
// method) that puts the connection back to the pool if it's closed.
select {
case conn := <-conns:
if conn == nil {
return nil, ErrClosed
}
return c.wrapConn(conn), nil
default:
conn, err := c.factory()
if err != nil {
return nil, err
}
return c.wrapConn(conn), nil
}
}
// put puts the connection back to the pool. If the pool is full or closed,
// conn is simply closed. A nil conn will be rejected.
func (c *channelPool) put(conn Closeable) error {
if conn == nil {
return errors.New("connection is nil. rejecting")
}
c.mu.Lock()
defer c.mu.Unlock()
if c.conns == nil {
// pool is closed, close passed connection
return conn.Close()
}
// put the resource back into the pool. If the pool is full, this will
// block and the default case will be executed.
select {
case c.conns <- conn:
return nil
default:
// pool is full, close passed connection
return conn.Close()
}
}
// Close shuts down all of the Closeable objects in the Pool
func (c *channelPool) Close() {
c.mu.Lock()
conns := c.conns
c.conns = nil
c.factory = nil
c.mu.Unlock()
if conns == nil {
return
}
close(conns)
for conn := range conns {
conn.Close()
}
}
// Len returns the number of Closeable objects in the Pool
func (c *channelPool) Len() int { return len(c.getConns()) }

View File

@ -1,123 +0,0 @@
package util
import (
"fmt"
"os"
"time"
)
// colors.
const (
red = 31
green = 32
yellow = 33
blue = 34
)
type Level int
const (
InvalidLevel Level = iota - 1
DebugLevel
InfoLevel
WarnLevel
ErrorLevel
FatalLevel
)
var colors = [...]int{
DebugLevel: green,
InfoLevel: blue,
WarnLevel: yellow,
ErrorLevel: red,
FatalLevel: red,
}
var lvlPrefix = [...]string{
DebugLevel: "D",
InfoLevel: "I",
WarnLevel: "W",
ErrorLevel: "E",
FatalLevel: "F",
}
var (
LogInfo = false
LogDebug = false
logg = os.Stdout
colorize = isTTY(logg.Fd())
)
const (
TimeFormat = "2006-01-02T15:04:05.000Z"
)
func llog(lvl Level, msg string) {
prefix := lvlPrefix[lvl]
ts := time.Now().UTC().Format(TimeFormat)
if colorize {
color := colors[lvl]
fmt.Fprintf(logg, "\033[%dm%s\033[0m %s %s\n", color, prefix, ts, msg)
} else {
fmt.Fprintf(logg, "%s %s %s\n", prefix, ts, msg)
}
}
//
// Logging functions
//
func InitLogger(level string) {
if level == "info" {
LogInfo = true
}
if level == "debug" {
LogInfo = true
LogDebug = true
}
}
func Error(msg string, err error) {
llog(ErrorLevel, fmt.Sprintf("%s: %v", msg, err))
}
// Uh oh, not good but not worthy of process death
func Warn(arg string) {
llog(WarnLevel, arg)
}
func Warnf(msg string, args ...interface{}) {
llog(WarnLevel, fmt.Sprintf(msg, args...))
}
// Typical logging output, the default level
func Info(arg string) {
if LogInfo {
llog(InfoLevel, arg)
}
}
// Typical logging output, the default level
func Infof(msg string, args ...interface{}) {
if LogInfo {
llog(InfoLevel, fmt.Sprintf(msg, args...))
}
}
// Verbosity level helps track down production issues:
// -l debug
func Debug(arg string) {
if LogDebug {
llog(DebugLevel, arg)
}
}
// Verbosity level helps track down production issues:
// -l debug
func Debugf(msg string, args ...interface{}) {
if LogDebug {
llog(DebugLevel, fmt.Sprintf(msg, args...))
}
}

View File

@ -1,131 +0,0 @@
package util
import (
cryptorand "crypto/rand"
"encoding/base64"
"fmt"
"math/big"
mathrand "math/rand"
"os"
"runtime"
"time"
)
const (
SIGHUP = 0x1
SIGINT = 0x2
SIGQUIT = 0x3
SIGTERM = 0xF
maxInt63 = int64(^uint64(0) >> 1)
)
func Retryable(name string, count int, fn func() error) error {
var err error
for i := 0; i < count; i++ {
err = fn()
if err == nil {
return nil
}
time.Sleep(10 * time.Millisecond)
Debugf("Retrying %s due to %v", name, err)
}
return err
}
func Darwin() bool {
b, _ := FileExists("/Applications")
return b
}
// FileExists checks if given file exists
func FileExists(path string) (bool, error) {
if _, err := os.Stat(path); err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
return true, nil
}
func RandomJid() string {
bytes := make([]byte, 12)
_, err := cryptorand.Read(bytes)
if err != nil {
//nolint:gosec
mathrand.Read(bytes)
}
return base64.RawURLEncoding.EncodeToString(bytes)
}
func RandomInt63() (int64, error) {
r, err := cryptorand.Int(cryptorand.Reader, big.NewInt(maxInt63))
if err != nil {
return 0, err
}
return r.Int64(), nil
}
const (
// This is the canonical timestamp format used by Faktory.
// Always UTC, lexigraphically sortable. This is the best
// timestamp format, accept no others.
TimestampFormat = time.RFC3339Nano
)
func Thens(tim time.Time) string {
return tim.UTC().Format(TimestampFormat)
}
func Nows() string {
return time.Now().UTC().Format(TimestampFormat)
}
func ParseTime(str string) (time.Time, error) {
return time.Parse(TimestampFormat, str)
}
func MemoryUsageMB() uint64 {
m := runtime.MemStats{}
runtime.ReadMemStats(&m)
mb := m.Sys / 1024 / 1024
return mb
}
// Backtrace gathers a backtrace for the caller.
// Return a slice of up to N stack frames.
func Backtrace(size int) []string {
pc := make([]uintptr, size)
n := runtime.Callers(2, pc)
if n == 0 {
return []string{}
}
pc = pc[:n] // pass only valid pcs to runtime.CallersFrames
frames := runtime.CallersFrames(pc)
str := make([]string, size)
count := 0
// Loop to get frames.
// A fixed number of pcs can expand to an indefinite number of Frames.
for i := 0; i < size; i++ {
frame, more := frames.Next()
str[i] = fmt.Sprintf("in %s:%d %s", frame.File, frame.Line, frame.Function)
count++
if !more {
break
}
}
return str[0:count]
}
func DumpProcessTrace() {
buf := make([]byte, 64*1024)
_ = runtime.Stack(buf, true)
Info("FULL PROCESS THREAD DUMP:")
Info(string(buf))
}

View File

@ -1,20 +0,0 @@
// +build darwin freebsd netbsd openbsd
package util
import (
"os/exec"
"syscall"
"unsafe"
)
func isTTY(fd uintptr) bool {
var termios syscall.Termios
_, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, syscall.TIOCGETA, uintptr(unsafe.Pointer(&termios)), 0, 0, 0)
return err == 0
}
func EnsureChildShutdown(cmd *exec.Cmd, sig int) {
// This ensures that, on Linux, if Faktory panics, our Redis child process will immediately
// get a SIGTERM signal to shutdown. No such feature on Darwin/BSD, Redis will orphan.
}

View File

@ -1,25 +0,0 @@
// +build linux
package util
import (
"os/exec"
"syscall"
"unsafe"
)
func isTTY(fd uintptr) bool {
var termios syscall.Termios
// syscall.TCGETS
// https://groups.google.com/forum/#!topic/golang-checkins/kieURujjDEk
_, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, 0x5401, uintptr(unsafe.Pointer(&termios)), 0, 0, 0)
return err == 0
}
func EnsureChildShutdown(cmd *exec.Cmd, sig int) {
// This ensures that, on Linux, if Faktory panics, our child process will immediately
// get a SIGTERM signal to shutdown. No such feature on Darwin/BSD, child will orphan.
cmd.SysProcAttr = &syscall.SysProcAttr{
Pdeathsig: syscall.Signal(sig),
}
}

View File

@ -1,16 +0,0 @@
package util
import (
"os/exec"
)
func isTTY(fd uintptr) bool {
// this function controls if we output ANSI coloring to the terminal.
// dunno how to do this on Windows so just play safe and assume it is not a TTY
return false
}
func EnsureChildShutdown(cmd *exec.Cmd, sig int) {
// This ensures that, on Linux, if Faktory panics, the child process will immediately
// get a signal. Dunno if this is possible on Windows or how it will behave.
}

View File

@ -1,17 +0,0 @@
# Binaries for programs and plugins
*.exe
*.dll
*.so
*.dylib
# Test binary, build with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736
.glide/
# Folder by any jetbrains IDE
/.idea

View File

@ -1,25 +0,0 @@
linters-settings:
gocritic:
# Which checks should be enabled; can't be combined with 'disabled-checks';
# See https://go-critic.github.io/overview#checks-overview
# To check which checks are enabled run `GL_DEBUG=gocritic golangci-lint run`
# By default list of stable checks is used.
disabled-checks:
- commentedOutCode
- commentFormatting
# Enable multiple checks by tags, run `GL_DEBUG=gocritic golangci-lint run` to see all tags and checks.
# Empty list by default. See https://github.com/go-critic/go-critic#usage -> section "Tags".
enabled-tags:
- performance
- diagnostic
- opinionated
settings: # settings passed to gocritic
rangeExprCopy:
sizeThreshold: 16
rangeValCopy:
sizeThreshold: 16
linters:
enable:
- gocritic

View File

@ -1,68 +0,0 @@
# faktory\_worker\_go
## 1.6.0
- Upgrade to Go 1.17 and Faktory 1.6.0.
- Add `Manager.RunWithContext(ctx context.Context) error` [#58]
Allows the caller to directly control when FWG stops. See README for usage.
## 1.5.0
- Auto-shutdown worker process if heartbeat expires due to network issues [#57]
- Send process RSS to Faktory (only available on Linux)
- Fix connection issue which causes worker processes to appear and disappear on
Busy tab. [#47]
## 1.4.0
- **Breaking API changes due to misunderstanding the `context` package.**
I've had to make significant changes to FWG's public APIs to allow
for mutable contexts. This unfortunately requires breaking changes:
```
Job Handler
Before: func(ctx worker.Context, args ...interface{}) error
After: func(ctx context.Context, args ...interface{}) error
Middleware Handler
Before: func(ctx worker.Context, job *faktory.Job) error
After: func(ctx context.Context, job *faktory.Job, next func(context.Context) error) error
```
Middleware funcs now need to call `next` to continue job dispatch.
Use `help := worker.HelperFor(ctx)` to get the old APIs provided by `worker.Context`
within your handlers.
- Fix issue reporting job errors back to Faktory
- Add helpers for testing `Perform` funcs
```go
myFunc := func(ctx context.Context, args ...interface{}) error {
return nil
}
pool, err := faktory.NewPool(5)
perf := worker.NewTestExecutor(pool)
somejob := faktory.NewJob("sometype", 12, "foobar")
err = perf.Execute(somejob, myFunc)
```
## 1.3.0
- Add new job context APIs for Faktory Enterprise features
- Misc API refactoring to improve test coverage
- Remove `faktory_worker_go` Pool interface in favor of the Pool now in `faktory/client`
## 1.0.1
- FWG will now dump all thread backtraces upon `kill -TTIN <pid>`,
useful for debugging stuck job processing.
- Send current state back to Faktory so process state changes are visible on Busy page.
- Tweak log output formatting
## 1.0.0
- Allow process labels (visible in Web UI) to be set [#32]
- Add APIs to manage [Batches](https://github.com/contribsys/faktory/wiki/Ent-Batches).
## 0.7.0
- Implement weighted queue fetch [#20, nickpoorman]
- Initial version.

View File

@ -1,373 +0,0 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

View File

@ -1,15 +0,0 @@
test:
go test -v ./...
work:
go run test/main.go
cover:
go test -cover -coverprofile .cover.out .
go tool cover -html=.cover.out -o coverage.html
open coverage.html
lint:
golangci-lint run
.PHONY: work test cover

View File

@ -1,190 +0,0 @@
# faktory_worker_go
![travis](https://travis-ci.org/contribsys/faktory_worker_go.svg?branch=master)
This repository provides a Faktory worker process for Go apps. This
worker process fetches background jobs from the Faktory server and processes them.
How is this different from all the other Go background worker libraries?
They all use Redis or another "dumb" datastore. This library is far
simpler because the Faktory server implements most of the data storage, retry logic,
Web UI, etc.
# Installation
You must install [Faktory](https://github.com/contribsys/faktory) first.
Then:
```
go get -u github.com/contribsys/faktory_worker_go
```
# Usage
To process background jobs, follow these steps:
1. Register your job types and their associated funcs
2. Set a few optional parameters
3. Start the processing
There are a couple ways to stop the process.
In this example, send the TERM or INT signal.
```go
package main
import (
"log"
worker "github.com/contribsys/faktory_worker_go"
)
func someFunc(ctx context.Context, args ...interface{}) error {
help := worker.HelperFor(ctx)
log.Printf("Working on job %s\n", help.Jid())
return nil
}
func main() {
mgr := worker.NewManager()
// register job types and the function to execute them
mgr.Register("SomeJob", someFunc)
//mgr.Register("AnotherJob", anotherFunc)
// use up to N goroutines to execute jobs
mgr.Concurrency = 20
// pull jobs from these queues, in this order of precedence
mgr.ProcessStrictPriorityQueues("critical", "default", "bulk")
// alternatively you can use weights to avoid starvation
//mgr.ProcessWeightedPriorityQueues(map[string]int{"critical":3, "default":2, "bulk":1})
// Start processing jobs, this method does not return.
mgr.Run()
}
```
Alternatively you can control the stopping of the Manager using
`RunWithContext`. **You must process any signals yourself.**
```go
package main
import (
"context"
"log"
"os"
"os/signal"
"syscall"
worker "github.com/contribsys/faktory_worker_go"
)
func someFunc(ctx context.Context, args ...interface{}) error {
help := worker.HelperFor(ctx)
log.Printf("Working on job %s\n", help.Jid())
return nil
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
mgr := worker.NewManager()
// register job types and the function to execute them
mgr.Register("SomeJob", someFunc)
//mgr.Register("AnotherJob", anotherFunc)
// use up to N goroutines to execute jobs
mgr.Concurrency = 20
// pull jobs from these queues, in this order of precedence
mgr.ProcessStrictPriorityQueues("critical", "default", "bulk")
// alternatively you can use weights to avoid starvation
//mgr.ProcessWeightedPriorityQueues(map[string]int{"critical":3, "default":2, "bulk":1})
go func(){
// Start processing jobs in background routine, this method does not return
// unless an error is returned or cancel() is called
mgr.RunWithContext(ctx)
}()
go func() {
stopSignals := []os.Signal{
syscall.SIGTERM,
syscall.SIGINT,
}
stop := make(chan os.Signal, len(stopSignals))
for _, s := range stopSignals {
signal.Notify(stop, s)
}
for {
select {
case <-ctx.Done():
return
case <-stop:
cancel()
}
}
}()
<-ctx.Done()
}
```
See `test/main.go` for a working example.
# FAQ
* How do I specify the Faktory server location?
By default, it will use localhost:7419 which is sufficient for local development.
Use FAKTORY\_URL to specify the URL, e.g. `tcp://faktory.example.com:12345` or
use FAKTORY\_PROVIDER to specify the environment variable which does
contain the URL: FAKTORY\_PROVIDER=FAKTORYTOGO\_URL. This level of
indirection is useful for SaaSes, Heroku Addons, etc.
* How do I push new jobs to Faktory?
1. Inside a job, you can check out a connection from the Pool of Faktory
connections using the job helper's `With` method:
```go
func someFunc(ctx context.Context, args ...interface{}) error {
help := worker.HelperFor(ctx)
return help.With(func(cl *faktory.Client) error {
job := faktory.NewJob("SomeJob", 1, 2, 3)
return cl.Push(job)
})
}
```
2. You can always open a client connection to Faktory directly but this
won't perform as well:
```go
import (
faktory "github.com/contribsys/faktory/client"
)
client, err := faktory.Open()
job := faktory.NewJob("SomeJob", 1, 2, 3)
err = client.Push(job)
```
**NB:** Client instances are **not safe to share**, you can use a Pool of Clients
which is thread-safe.
See the Faktory Client API for
[Go](https://github.com/contribsys/faktory/blob/master/client) or
[Ruby](https://github.com/contribsys/faktory-ruby/blob/master/lib/faktory/client.rb).
You can implement a Faktory client in any programming langauge.
See [the wiki](https://github.com/contribsys/faktory/wiki) for details.
# Author
Mike Perham, @getajobmike, @contribsys
# License
This codebase is licensed via the Mozilla Public License, v2.0. https://choosealicense.com/licenses/mpl-2.0/

View File

@ -1,148 +0,0 @@
package faktory_worker
import (
"context"
"fmt"
"log"
"time"
faktory "github.com/contribsys/faktory/client"
)
// internal keys for context value storage
type valueKey int
const (
poolKey valueKey = 2
jobKey valueKey = 3
)
var (
NoAssociatedBatchError = fmt.Errorf("No batch associated with this job")
)
// The Helper provides access to valuable data and APIs
// within an executing job.
//
// We're pretty strict about what's exposed in the Helper
// because execution should be orthogonal to
// most of the Job payload contents.
//
// func myJob(ctx context.Context, args ...interface{}) error {
// helper := worker.HelperFor(ctx)
// jid := helper.Jid()
//
// helper.With(func(cl *faktory.Client) error {
// cl.Push("anotherJob", 4, "arg")
// })
//
type Helper interface {
Jid() string
JobType() string
// Faktory Enterprise:
// the BID of the Batch associated with this job
Bid() string
// Faktory Enterprise:
// open the batch associated with this job so we can add more jobs to it.
//
// func myJob(ctx context.Context, args ...interface{}) error {
// helper := worker.HelperFor(ctx)
// helper.Batch(func(b *faktory.Batch) error {
// return b.Push(faktory.NewJob("sometype", 1, 2, 3))
// })
Batch(func(*faktory.Batch) error) error
// allows direct access to the Faktory server from the job
With(func(*faktory.Client) error) error
// Faktory Enterprise:
// this method integrates with Faktory Enterprise's Job Tracking feature.
// `reserveUntil` is optional, only needed for long jobs which have more dynamic
// lifetimes.
//
// helper.TrackProgress(10, "Updating code...", nil)
// helper.TrackProgress(20, "Cleaning caches...", &time.Now().Add(1 * time.Hour)))
//
TrackProgress(percent int, desc string, reserveUntil *time.Time) error
}
type jobHelper struct {
job *faktory.Job
pool *faktory.Pool
}
func (h *jobHelper) Jid() string {
return h.job.Jid
}
func (h *jobHelper) Bid() string {
if b, ok := h.job.GetCustom("bid"); ok {
return b.(string)
}
return ""
}
func (h *jobHelper) JobType() string {
return h.job.Type
}
// Caution: this method must only be called within the
// context of an executing job. It will panic if it cannot
// create a Helper due to missing context values.
func HelperFor(ctx context.Context) Helper {
if j := ctx.Value(jobKey); j != nil {
job := j.(*faktory.Job)
if p := ctx.Value(poolKey); p != nil {
pool := p.(*faktory.Pool)
return &jobHelper{
job: job,
pool: pool,
}
}
}
log.Panic("Invalid job context, cannot create faktory_worker_go job helper")
return nil
}
func jobContext(pool *faktory.Pool, job *faktory.Job) context.Context {
ctx := context.Background()
ctx = context.WithValue(ctx, poolKey, pool)
ctx = context.WithValue(ctx, jobKey, job)
return ctx
}
// requires Faktory Enterprise
func (h *jobHelper) TrackProgress(percent int, desc string, reserveUntil *time.Time) error {
return h.With(func(cl *faktory.Client) error {
return cl.TrackSet(h.Jid(), percent, desc, reserveUntil)
})
}
// requires Faktory Enterprise
// Open the current batch so we can add more jobs to it.
func (h *jobHelper) Batch(fn func(*faktory.Batch) error) error {
bid := h.Bid()
if bid == "" {
return NoAssociatedBatchError
}
var b *faktory.Batch
var err error
err = h.pool.With(func(cl *faktory.Client) error {
b, err = cl.BatchOpen(bid)
if err != nil {
return err
}
return fn(b)
})
if err != nil {
return err
}
return nil
}
func (h *jobHelper) With(fn func(*faktory.Client) error) error {
return h.pool.With(fn)
}

View File

@ -1,60 +0,0 @@
package faktory_worker
import (
"log"
"os"
)
type Logger interface {
Debug(v ...interface{})
Debugf(format string, args ...interface{})
Info(v ...interface{})
Infof(format string, args ...interface{})
Warn(v ...interface{})
Warnf(format string, args ...interface{})
Error(v ...interface{})
Errorf(format string, args ...interface{})
Fatal(v ...interface{})
Fatalf(format string, args ...interface{})
}
type StdLogger struct {
*log.Logger
}
func NewStdLogger() Logger {
flags := log.Ldate | log.Ltime | log.Lmicroseconds | log.LUTC
return &StdLogger{log.New(os.Stdout, "", flags)}
}
func (l *StdLogger) Debug(v ...interface{}) {
l.Println(v...)
}
func (l *StdLogger) Debugf(format string, v ...interface{}) {
l.Printf(format+"\n", v...)
}
func (l *StdLogger) Error(v ...interface{}) {
l.Println(v...)
}
func (l *StdLogger) Errorf(format string, v ...interface{}) {
l.Printf(format+"\n", v...)
}
func (l *StdLogger) Info(v ...interface{}) {
l.Println(v...)
}
func (l *StdLogger) Infof(format string, v ...interface{}) {
l.Printf(format+"\n", v...)
}
func (l *StdLogger) Warn(v ...interface{}) {
l.Println(v...)
}
func (l *StdLogger) Warnf(format string, v ...interface{}) {
l.Printf(format+"\n", v...)
}

View File

@ -1,253 +0,0 @@
package faktory_worker
import (
"context"
"fmt"
"math/rand"
"os"
"strconv"
"sync"
"time"
faktory "github.com/contribsys/faktory/client"
)
// Manager coordinates the processes for the worker. It is responsible for
// starting and stopping goroutines to perform work at the desired concurrency level
type Manager struct {
mut sync.Mutex
Concurrency int
Logger Logger
ProcessWID string
Labels []string
Pool *faktory.Pool
queues []string
middleware []MiddlewareFunc
state string // "", "quiet" or "terminate"
// The done channel will always block unless
// the system is shutting down.
done chan interface{}
shutdownWaiter *sync.WaitGroup
jobHandlers map[string]Handler
eventHandlers map[lifecycleEventType][]LifecycleEventHandler
// This only needs to be computed once. Store it here to keep things fast.
weightedPriorityQueuesEnabled bool
weightedQueues []string
}
// Register a handler for the given jobtype. It is expected that all jobtypes
// are registered upon process startup.
//
// mgr.Register("ImportantJob", ImportantFunc)
func (mgr *Manager) Register(name string, fn Perform) {
mgr.jobHandlers[name] = func(ctx context.Context, job *faktory.Job) error {
return fn(ctx, job.Args...)
}
}
// Register a callback to be fired when a process lifecycle event occurs.
// These are useful for hooking into process startup or shutdown.
func (mgr *Manager) On(event lifecycleEventType, fn LifecycleEventHandler) {
mgr.eventHandlers[event] = append(mgr.eventHandlers[event], fn)
}
// After calling Quiet(), no more jobs will be pulled
// from Faktory by this process.
func (mgr *Manager) Quiet() {
mgr.mut.Lock()
defer mgr.mut.Unlock()
if mgr.state == "quiet" {
return
}
mgr.Logger.Info("Quieting...")
mgr.state = "quiet"
mgr.fireEvent(Quiet)
}
// Terminate signals that the various components should shutdown.
// Blocks on the shutdownWaiter until all components have finished.
func (mgr *Manager) Terminate(reallydie bool) {
mgr.mut.Lock()
defer mgr.mut.Unlock()
if mgr.state == "terminate" {
return
}
mgr.Logger.Info("Shutting down...")
mgr.state = "terminate"
close(mgr.done)
mgr.fireEvent(Shutdown)
mgr.shutdownWaiter.Wait()
mgr.Pool.Close()
mgr.Logger.Info("Goodbye")
if reallydie {
os.Exit(0) // nolint:gocritic
}
}
// NewManager returns a new manager with default values.
func NewManager() *Manager {
return &Manager{
Concurrency: 20,
Logger: NewStdLogger(),
Labels: []string{"golang-" + Version},
Pool: nil,
state: "",
queues: []string{"default"},
done: make(chan interface{}),
shutdownWaiter: &sync.WaitGroup{},
jobHandlers: map[string]Handler{},
eventHandlers: map[lifecycleEventType][]LifecycleEventHandler{
Startup: {},
Quiet: {},
Shutdown: {},
},
weightedPriorityQueuesEnabled: false,
weightedQueues: []string{},
}
}
func (mgr *Manager) setUpWorkerProcess() error {
mgr.mut.Lock()
defer mgr.mut.Unlock()
if mgr.state != "" {
return fmt.Errorf("cannot start worker process for the mananger in %v state", mgr.state)
}
// This will signal to Faktory that all connections from this process
// are worker connections.
if len(mgr.ProcessWID) == 0 {
rand.Seed(time.Now().UnixNano())
faktory.RandomProcessWid = strconv.FormatInt(rand.Int63(), 32)
} else {
faktory.RandomProcessWid = mgr.ProcessWID
}
// Set labels to be displayed in the UI
faktory.Labels = mgr.Labels
if mgr.Pool == nil {
pool, err := faktory.NewPool(mgr.Concurrency + 2)
if err != nil {
return fmt.Errorf("couldn't create Faktory connection pool: %w", err)
}
mgr.Pool = pool
}
return nil
}
// RunWithContext starts processing jobs. The method will return if an error is encountered while starting.
// If the context is present then os signals will be ignored, the context must be canceled for the method to return
// after running.
func (mgr *Manager) RunWithContext(ctx context.Context) error {
err := mgr.boot()
if err != nil {
return err
}
<-ctx.Done()
mgr.Terminate(false)
return nil
}
func (mgr *Manager) boot() error {
err := mgr.setUpWorkerProcess()
if err != nil {
return err
}
mgr.fireEvent(Startup)
go heartbeat(mgr)
mgr.Logger.Infof("faktory_worker_go %s PID %d now ready to process jobs", Version, os.Getpid())
mgr.Logger.Debugf("Using Faktory Client API %s", faktory.Version)
for i := 0; i < mgr.Concurrency; i++ {
go process(mgr, i)
}
return nil
}
// Run starts processing jobs.
// This method does not return unless an error is encountered while starting.
func (mgr *Manager) Run() error {
err := mgr.boot()
if err != nil {
return err
}
for {
sig := <-hookSignals()
mgr.handleEvent(signalMap[sig])
}
}
// One of the Process*Queues methods should be called once before Run()
func (mgr *Manager) ProcessStrictPriorityQueues(queues ...string) {
mgr.queues = queues
mgr.weightedPriorityQueuesEnabled = false
}
func (mgr *Manager) ProcessWeightedPriorityQueues(queues map[string]int) {
uniqueQueues := queueKeys(queues)
weightedQueues := expandWeightedQueues(queues)
mgr.queues = uniqueQueues
mgr.weightedQueues = weightedQueues
mgr.weightedPriorityQueuesEnabled = true
}
func (mgr *Manager) queueList() []string {
if mgr.weightedPriorityQueuesEnabled {
sq := shuffleQueues(mgr.weightedQueues)
return uniqQueues(len(mgr.queues), sq)
}
return mgr.queues
}
func (mgr *Manager) fireEvent(event lifecycleEventType) {
for _, fn := range mgr.eventHandlers[event] {
err := fn(mgr)
if err != nil {
mgr.Logger.Errorf("Error running lifecycle event handler: %v", err)
}
}
}
func (mgr *Manager) with(fn func(cl *faktory.Client) error) error {
if mgr.Pool == nil {
panic("No Pool set on Manager, have you called manager.Run() yet?")
}
return mgr.Pool.With(fn)
}
func (mgr *Manager) handleEvent(sig string) string {
if sig == mgr.state {
return mgr.state
}
if sig == "quiet" && mgr.state == "terminate" {
// this is a no-op, a terminating process is quiet already
return mgr.state
}
switch sig {
case "terminate":
go func() {
mgr.Terminate(true)
}()
case "quiet":
go func() {
mgr.Quiet()
}()
case "dump":
dumpThreads(mgr.Logger)
}
return ""
}

View File

@ -1,27 +0,0 @@
package faktory_worker
import (
"context"
faktory "github.com/contribsys/faktory/client"
)
type Handler func(ctx context.Context, job *faktory.Job) error
type MiddlewareFunc func(ctx context.Context, job *faktory.Job, next func(ctx context.Context) error) error
// Use(...) adds middleware to the chain.
func (mgr *Manager) Use(middleware ...MiddlewareFunc) {
mgr.middleware = append(mgr.middleware, middleware...)
}
func dispatch(chain []MiddlewareFunc, ctx context.Context, job *faktory.Job, perform Handler) error {
if len(chain) == 0 {
return perform(ctx, job)
}
link := chain[0]
rest := chain[1:]
return link(ctx, job, func(ctx context.Context) error {
return dispatch(rest, ctx, job, perform)
})
}

View File

@ -1,243 +0,0 @@
package faktory_worker
import (
"encoding/json"
"fmt"
"math/rand"
"os"
"runtime"
"sort"
"strings"
"syscall"
"time"
faktory "github.com/contribsys/faktory/client"
)
type lifecycleEventType int
const (
Startup lifecycleEventType = 1
Quiet lifecycleEventType = 2
Shutdown lifecycleEventType = 3
)
type NoHandlerError struct {
JobType string
}
func (s *NoHandlerError) Error() string {
return fmt.Sprintf("No handler registered for job type %s", s.JobType)
}
func heartbeat(mgr *Manager) {
mgr.shutdownWaiter.Add(1)
defer mgr.shutdownWaiter.Done()
timer := time.NewTicker(15 * time.Second)
for {
select {
case <-timer.C:
// we don't care about errors, assume any network
// errors will heal eventually
err := mgr.with(func(c *faktory.Client) error {
data, err := c.Beat(mgr.state)
if err != nil && strings.Contains(err.Error(), "Unknown worker") {
// If our heartbeat expires, we must restart and re-authenticate.
// Use a signal so we can unwind and shutdown cleanly.
mgr.Logger.Warn("Faktory heartbeat has expired, shutting down...")
_ = syscall.Kill(os.Getpid(), syscall.SIGTERM)
}
if err != nil || data == "" {
return err
}
var hash map[string]string
err = json.Unmarshal([]byte(data), &hash)
if err != nil {
return err
}
if state, ok := hash["state"]; ok && state != "" {
mgr.handleEvent(state)
}
return nil
})
if err != nil {
mgr.Logger.Error(fmt.Sprintf("heartbeat error: %v", err))
}
case <-mgr.done:
timer.Stop()
return
}
}
}
func process(mgr *Manager, idx int) {
mgr.shutdownWaiter.Add(1)
defer mgr.shutdownWaiter.Done()
// delay initial fetch randomly to prevent thundering herd.
// this will pause between 0 and 2B nanoseconds, i.e. 0-2 seconds
time.Sleep(time.Duration(rand.Int31()))
for {
if mgr.state != "" {
return
}
// check for shutdown
select {
case <-mgr.done:
return
default:
}
err := processOne(mgr)
if err != nil {
mgr.Logger.Debug(err)
if _, ok := err.(*NoHandlerError); !ok {
time.Sleep(1 * time.Second)
}
}
}
}
func processOne(mgr *Manager) error {
var job *faktory.Job
// explicit scopes to limit variable visibility
{
var e error
err := mgr.with(func(c *faktory.Client) error {
job, e = c.Fetch(mgr.queueList()...)
if e != nil {
return e
}
return nil
})
if err != nil {
return err
}
if job == nil {
return nil
}
}
perform := mgr.jobHandlers[job.Type]
if perform == nil {
je := &NoHandlerError{JobType: job.Type}
err := mgr.with(func(c *faktory.Client) error {
return c.Fail(job.Jid, je, nil)
})
if err != nil {
return err
}
return je
}
joberr := dispatch(mgr.middleware, jobContext(mgr.Pool, job), job, perform)
if joberr != nil {
// job errors are normal and expected, we don't return early from them
mgr.Logger.Errorf("Error running %s job %s: %v", job.Type, job.Jid, joberr)
}
for {
// we want to report the result back to Faktory.
// we stay in this loop until we successfully report.
err := mgr.with(func(c *faktory.Client) error {
if joberr != nil {
return c.Fail(job.Jid, joberr, nil)
} else {
return c.Ack(job.Jid)
}
})
if err == nil {
return nil
}
select {
case <-mgr.done:
mgr.Logger.Error(fmt.Errorf("Unable to report JID %v result to Faktory: %w", job.Jid, err))
return nil
default:
mgr.Logger.Debug(err)
time.Sleep(1 * time.Second)
}
}
}
// expandWeightedQueues builds a slice of queues represented the number of times equal to their weights.
func expandWeightedQueues(queueWeights map[string]int) []string {
weightsTotal := 0
for _, queueWeight := range queueWeights {
weightsTotal += queueWeight
}
weightedQueues := make([]string, weightsTotal)
fillIndex := 0
for queue, nTimes := range queueWeights {
// Fill weightedQueues with queue n times
for idx := 0; idx < nTimes; idx++ {
weightedQueues[fillIndex] = queue
fillIndex++
}
}
// weightedQueues has to be stable so we can write tests
sort.Strings(weightedQueues)
return weightedQueues
}
func queueKeys(queues map[string]int) []string {
keys := make([]string, len(queues))
i := 0
for k := range queues {
keys[i] = k
i++
}
// queues has to be stable so we can write tests
sort.Strings(keys)
return keys
}
// shuffleQueues returns a copy of the slice with the elements shuffled.
func shuffleQueues(queues []string) []string {
wq := make([]string, len(queues))
copy(wq, queues)
rand.Shuffle(len(wq), func(i, j int) {
wq[i], wq[j] = wq[j], wq[i]
})
return wq
}
// uniqQueues returns a slice of length len, of the unique elements while maintaining order.
// The underlying array is modified to avoid allocating another one.
func uniqQueues(length int, queues []string) []string {
// Record the unique values and position.
pos := 0
uniqMap := make(map[string]int)
for idx := range queues {
if _, ok := uniqMap[queues[idx]]; !ok {
uniqMap[queues[idx]] = pos
pos++
}
}
// Reuse the copied array, by updating the values.
for queue, position := range uniqMap {
queues[position] = queue
}
// Slice only what we need.
return queues[:length]
}
func dumpThreads(logg Logger) {
buf := make([]byte, 64*1024)
_ = runtime.Stack(buf, true)
logg.Info("FULL PROCESS THREAD DUMP:")
logg.Info(string(buf))
}

View File

@ -1,32 +0,0 @@
// +build linux freebsd netbsd openbsd dragonfly solaris illumos aix darwin
package faktory_worker
import (
"os"
"os/signal"
"syscall"
)
var (
SIGTERM os.Signal = syscall.SIGTERM
SIGTSTP os.Signal = syscall.SIGTSTP
SIGTTIN os.Signal = syscall.SIGTTIN
SIGINT os.Signal = os.Interrupt
signalMap = map[os.Signal]string{
SIGTERM: "terminate",
SIGINT: "terminate",
SIGTSTP: "quiet",
SIGTTIN: "dump",
}
)
func hookSignals() chan os.Signal {
sigchan := make(chan os.Signal, 1)
signal.Notify(sigchan, SIGINT)
signal.Notify(sigchan, SIGTERM)
signal.Notify(sigchan, SIGTSTP)
signal.Notify(sigchan, SIGTTIN)
return sigchan
}

View File

@ -1,28 +0,0 @@
// +build windows
package faktory_worker
import (
"os"
"os/signal"
"syscall"
)
var (
// SIGTERM is an alias for syscall.SIGTERM
SIGTERM os.Signal = syscall.SIGTERM
// SIGINT is and alias for syscall.SIGINT
SIGINT os.Signal = os.Interrupt
signalMap = map[os.Signal]string{
SIGTERM: "terminate",
SIGINT: "terminate",
}
)
func hookSignals() chan os.Signal {
sigchan := make(chan os.Signal)
signal.Notify(sigchan, SIGINT)
signal.Notify(sigchan, SIGTERM)
return sigchan
}

View File

@ -1,36 +0,0 @@
package faktory_worker
import (
"encoding/json"
faktory "github.com/contribsys/faktory/client"
)
type PerformExecutor interface {
Execute(*faktory.Job, Perform) error
}
type testExecutor struct {
*faktory.Pool
}
func NewTestExecutor(p *faktory.Pool) PerformExecutor {
return &testExecutor{Pool: p}
}
func (tp *testExecutor) Execute(specjob *faktory.Job, p Perform) error {
// perform a JSON round trip to ensure Perform gets the arguments
// exactly how a round trip to Faktory would look.
data, err := json.Marshal(specjob)
if err != nil {
return err
}
var job faktory.Job
err = json.Unmarshal(data, &job)
if err != nil {
return err
}
c := jobContext(tp.Pool, &job)
return p(c, job.Args...)
}

View File

@ -1,13 +0,0 @@
package faktory_worker
import "context"
const (
Version = "1.6.0"
)
// Perform actually executes the job.
// It must be thread-safe.
type Perform func(ctx context.Context, args ...interface{}) error
type LifecycleEventHandler func(*Manager) error

View File

@ -1,19 +0,0 @@
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, built with `go test -c`
*.test
local_testing
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Dependency directories (remove the comment below to include it)
vendor/
# IDE project files
.idea

View File

@ -1,49 +0,0 @@
run:
timeout: 2m
issues-exit-code: 1
tests: true
issues:
max-same-issues: 100
exclude-rules:
- path: _test\.go
linters:
- bodyclose
- errcheck
- gosec
linters:
enable:
- bodyclose
- deadcode
- errcheck
- gofmt
- revive
- gosec
- gosimple
- govet
- ineffassign
- misspell
- staticcheck
- structcheck
- typecheck
- unused
- varcheck
output:
# colored-line-number|line-number|json|tab|checkstyle|code-climate, default is "colored-line-number"
format: colored-line-number
# print lines of code with issue, default is true
print-issued-lines: true
# print linter name in the end of issue text, default is true
print-linter-name: true
# make issues output unique by line, default is true
uniq-by-line: true
# add a prefix to the output file references; default is no prefix
path-prefix: ""
# sorts results by: filepath, line and column
sort-results: true
linters-settings:
golint:
min-confidence: 0.8

View File

@ -1,73 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone. And we mean everyone!
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and kind language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team initially on Slack to coordinate private communication. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq

View File

@ -1,40 +0,0 @@
# Contributing to gocron
Thank you for coming to contribute to gocron! We welcome new ideas, PRs and general feedback.
## Reporting Bugs
If you find a bug then please let the project know by opening an issue after doing the following:
- Do a quick search of the existing issues to make sure the bug isn't already reported
- Try and make a minimal list of steps that can reliably reproduce the bug you are experiencing
- Collect as much information as you can to help identify what the issue is (project version, configuration files, etc)
## Suggesting Enhancements
If you have a use case that you don't see a way to support yet, we would welcome the feedback in an issue. Before opening the issue, please consider:
- Is this a common use case?
- Is it simple to understand?
You can help us out by doing the following before raising a new issue:
- Check that the feature hasn't been requested already by searching existing issues
- Try and reduce your enhancement into a single, concise and deliverable request, rather than a general idea
- Explain your own use cases as the basis of the request
## Adding Features
Pull requests are always welcome. However, before going through the trouble of implementing a change it's worth creating a bug or feature request issue.
This allows us to discuss the changes and make sure they are a good fit for the project.
Please always make sure a pull request has been:
- Unit tested with `make test`
- Linted with `make lint`
- Vetted with `make vet`
- Formatted with `make fmt` or validated with `make check-fmt`
## Writing Tests
Tests should follow the [table driven test pattern](https://dave.cheney.net/2013/06/09/writing-table-driven-tests-in-go). See other tests in the code base for additional examples.

View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2014, 辣椒面
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,12 +0,0 @@
.PHONY: fmt check-fmt lint vet test
GO_PKGS := $(shell go list -f {{.Dir}} ./...)
fmt:
@go list -f {{.Dir}} ./... | xargs -I{} gofmt -w -s {}
lint:
@golangci-lint run
test:
@go test -race -v $(GO_FLAGS) -count=1 $(GO_PKGS)

View File

@ -1,132 +0,0 @@
# gocron: A Golang Job Scheduling Package.
[![CI State](https://github.com/go-co-op/gocron/workflows/Go%20Test/badge.svg)](https://github.com/go-co-op/gocron/actions?query=workflow%3A"lint") ![Go Report Card](https://goreportcard.com/badge/github.com/go-co-op/gocron) [![Go Doc](https://godoc.org/github.com/go-co-op/gocron?status.svg)](https://pkg.go.dev/github.com/go-co-op/gocron)
gocron is a job scheduling package which lets you run Go functions at pre-determined intervals using a simple, human-friendly syntax.
gocron is a Golang scheduler implementation similar to the Ruby module [clockwork](https://github.com/tomykaira/clockwork) and the Python job scheduling package [schedule](https://github.com/dbader/schedule).
See also these two great articles that were used for design input:
- [Rethinking Cron](http://adam.herokuapp.com/past/2010/4/13/rethinking_cron/)
- [Replace Cron with Clockwork](http://adam.herokuapp.com/past/2010/6/30/replace_cron_with_clockwork/)
If you want to chat, you can find us at Slack! [<img src="https://img.shields.io/badge/gophers-gocron-brightgreen?logo=slack">](https://gophers.slack.com/archives/CQ7T0T1FW)
## Concepts
- **Scheduler**: The scheduler tracks all the jobs assigned to it and makes sure they are passed to the executor when ready to be run. The scheduler is able to manage overall aspects of job behavior like limiting how many jobs are running at one time.
- **Job**: The job is simply aware of the task (go function) it's provided and is therefore only able to perform actions related to that task like preventing itself from overruning a previous task that is taking a long time.
- **Executor**: The executor, as it's name suggests, is simply responsible for calling the task (go function) that the job hands to it when sent by the scheduler.
## Examples
```golang
s := gocron.NewScheduler(time.UTC)
s.Every(5).Seconds().Do(func(){ ... })
// strings parse to duration
s.Every("5m").Do(func(){ ... })
s.Every(5).Days().Do(func(){ ... })
s.Every(1).Month(1, 2, 3).Do(func(){ ... })
// set time
s.Every(1).Day().At("10:30").Do(func(){ ... })
// set multiple times
s.Every(1).Day().At("10:30;08:00").Do(func(){ ... })
s.Every(1).Day().At("10:30").At("08:00").Do(func(){ ... })
// Schedule each last day of the month
s.Every(1).MonthLastDay().Do(func(){ ... })
// Or each last day of every other month
s.Every(2).MonthLastDay().Do(func(){ ... })
// cron expressions supported
s.Cron("*/1 * * * *").Do(task) // every minute
// you can start running the scheduler in two different ways:
// starts the scheduler asynchronously
s.StartAsync()
// starts the scheduler and blocks current execution path
s.StartBlocking()
```
For more examples, take a look in our [go docs](https://pkg.go.dev/github.com/go-co-op/gocron#pkg-examples)
## Options
| Interval | Supported schedule options |
| ------------ | ------------------------------------------------------------------- |
| sub-second | `StartAt()` |
| milliseconds | `StartAt()` |
| seconds | `StartAt()` |
| minutes | `StartAt()` |
| hours | `StartAt()` |
| days | `StartAt()`, `At()` |
| weeks | `StartAt()`, `At()`, `Weekday()` (and all week day named functions) |
| months | `StartAt()`, `At()` |
There are several options available to restrict how jobs run:
| Mode | Function | Behavior |
| --------------- | ------------------------ | ------------------------------------------------------------------------------- |
| Default | | jobs are rescheduled at every interval |
| Job singleton | `SingletonMode()` | a long running job will not be rescheduled until the current run is completed |
| Scheduler limit | `SetMaxConcurrentJobs()` | set a collective maximum number of concurrent jobs running across the scheduler |
## Tags
Jobs may have arbitrary tags added which can be useful when tracking many jobs.
The scheduler supports both enforcing tags to be unique and when not unique,
running all jobs with a given tag.
```golang
s := gocron.NewScheduler(time.UTC)
s.TagsUnique()
_, _ = s.Every(1).Week().Tag("foo").Do(task)
_, err := s.Every(1).Week().Tag("foo").Do(task)
// error!!!
s := gocron.NewScheduler(time.UTC)
s.Every(2).Day().Tag("tag").At("10:00").Do(task)
s.Every(1).Minute().Tag("tag").Do(task)
s.RunByTag("tag")
// both jobs will run
```
## FAQ
- Q: I'm running multiple pods on a distributed environment. How can I make a job not run once per pod causing duplication?
- A: We recommend using your own lock solution within the jobs themselves (you could use [Redis](https://redis.io/topics/distlock), for example)
- Q: I've removed my job from the scheduler, but how can I stop a long-running job that has already been triggered?
- A: We recommend using a means of canceling your job, e.g. a `context.WithCancel()`.
---
Looking to contribute? Try to follow these guidelines:
- Use issues for everything
- For a small change, just send a PR!
- For bigger changes, please open an issue for discussion before sending a PR.
- PRs should have: tests, documentation and examples (if it makes sense)
- You can also contribute by:
- Reporting issues
- Suggesting new features or enhancements
- Improving/fixing documentation
---
## Design
![design-diagram](https://user-images.githubusercontent.com/19351306/110375142-2ba88680-8017-11eb-80c3-554cc746b165.png)
[Jetbrains](https://www.jetbrains.com/?from=gocron) supports this project with GoLand licenses. We appreciate their support for free and open source software!

View File

@ -1,15 +0,0 @@
# Security Policy
## Supported Versions
The current plan is to maintain version 1 as long as possible incorporating any necessary security patches.
| Version | Supported |
| ------- | ------------------ |
| 1.x.x | :white_check_mark: |
## Reporting a Vulnerability
Vulnerabilities can be reported by [opening an issue](https://github.com/go-co-op/gocron/issues/new/choose) or reaching out on Slack: [<img src="https://img.shields.io/badge/gophers-gocron-brightgreen?logo=slack">](https://gophers.slack.com/archives/CQ7T0T1FW)
We will do our best to addrerss any vulnerabilities in an expeditious manner.

View File

@ -1,127 +0,0 @@
package gocron
import (
"context"
"sync"
"golang.org/x/sync/semaphore"
)
const (
// RescheduleMode - the default is that if a limit on maximum
// concurrent jobs is set and the limit is reached, a job will
// skip it's run and try again on the next occurrence in the schedule
RescheduleMode limitMode = iota
// WaitMode - if a limit on maximum concurrent jobs is set
// and the limit is reached, a job will wait to try and run
// until a spot in the limit is freed up.
//
// Note: this mode can produce unpredictable results as
// job execution order isn't guaranteed. For example, a job that
// executes frequently may pile up in the wait queue and be executed
// many times back to back when the queue opens.
WaitMode
)
type executor struct {
jobFunctions chan jobFunction
stopCh chan struct{}
stoppedCh chan struct{}
limitMode limitMode
maxRunningJobs *semaphore.Weighted
}
func newExecutor() executor {
return executor{
jobFunctions: make(chan jobFunction, 1),
stopCh: make(chan struct{}),
stoppedCh: make(chan struct{}),
}
}
func (e *executor) start() {
stopCtx, cancel := context.WithCancel(context.Background())
runningJobsWg := sync.WaitGroup{}
for {
select {
case f := <-e.jobFunctions:
runningJobsWg.Add(1)
go func() {
defer runningJobsWg.Done()
panicHandlerMutex.RLock()
defer panicHandlerMutex.RUnlock()
if panicHandler != nil {
defer func() {
if r := recover(); r != interface{}(nil) {
panicHandler(f.name, r)
}
}()
}
if e.maxRunningJobs != nil {
if !e.maxRunningJobs.TryAcquire(1) {
switch e.limitMode {
case RescheduleMode:
return
case WaitMode:
select {
case <-stopCtx.Done():
return
case <-f.ctx.Done():
return
default:
}
if err := e.maxRunningJobs.Acquire(f.ctx, 1); err != nil {
break
}
}
}
defer e.maxRunningJobs.Release(1)
}
runJob := func() {
f.incrementRunState()
callJobFunc(f.eventListeners.onBeforeJobExecution)
callJobFuncWithParams(f.function, f.parameters)
callJobFunc(f.eventListeners.onAfterJobExecution)
f.decrementRunState()
}
switch f.runConfig.mode {
case defaultMode:
runJob()
case singletonMode:
_, _, _ = f.limiter.Do("main", func() (interface{}, error) {
select {
case <-stopCtx.Done():
return nil, nil
case <-f.ctx.Done():
return nil, nil
default:
}
runJob()
return nil, nil
})
}
}()
case <-e.stopCh:
cancel()
runningJobsWg.Wait()
close(e.stoppedCh)
return
}
}
}
func (e *executor) stop() {
close(e.stopCh)
<-e.stoppedCh
}

View File

@ -1,129 +0,0 @@
// Package gocron : A Golang Job Scheduling Package.
//
// An in-process scheduler for periodic jobs that uses the builder pattern
// for configuration. gocron lets you run Golang functions periodically
// at pre-determined intervals using a simple, human-friendly syntax.
package gocron
import (
"errors"
"fmt"
"reflect"
"regexp"
"runtime"
"sync"
"time"
)
// PanicHandlerFunc represents a type that can be set to handle panics occurring
// during job execution.
type PanicHandlerFunc func(jobName string, recoverData interface{})
// The global panic handler
var (
panicHandler PanicHandlerFunc
panicHandlerMutex = sync.RWMutex{}
)
// SetPanicHandler sets the global panicHandler to the given function.
// Leaving it nil or setting it to nil disables automatic panic handling.
// If the panicHandler is not nil, any panic that occurs during executing a job will be recovered
// and the panicHandlerFunc will be called with the job's name and the recover data.
func SetPanicHandler(handler PanicHandlerFunc) {
panicHandlerMutex.Lock()
defer panicHandlerMutex.Unlock()
panicHandler = handler
}
// Error declarations for gocron related errors
var (
ErrNotAFunction = errors.New("only functions can be scheduled into the job queue")
ErrNotScheduledWeekday = errors.New("job not scheduled weekly on a weekday")
ErrJobNotFoundWithTag = errors.New("no jobs found with given tag")
ErrUnsupportedTimeFormat = errors.New("the given time format is not supported")
ErrInvalidInterval = errors.New(".Every() interval must be greater than 0")
ErrInvalidIntervalType = errors.New(".Every() interval must be int, time.Duration, or string")
ErrInvalidIntervalUnitsSelection = errors.New(".Every(time.Duration) and .Cron() cannot be used with units (e.g. .Seconds())")
ErrInvalidFunctionParameters = errors.New("length of function parameters must match job function parameters")
ErrAtTimeNotSupported = errors.New("the At() method is not supported for this time unit")
ErrWeekdayNotSupported = errors.New("weekday is not supported for time unit")
ErrInvalidDayOfMonthEntry = errors.New("only days 1 through 28 are allowed for monthly schedules")
ErrTagsUnique = func(tag string) error { return fmt.Errorf("a non-unique tag was set on the job: %s", tag) }
ErrWrongParams = errors.New("wrong list of params")
ErrDoWithJobDetails = errors.New("DoWithJobDetails expects a function whose last parameter is a gocron.Job")
ErrUpdateCalledWithoutJob = errors.New("a call to Scheduler.Update() requires a call to Scheduler.Job() first")
ErrCronParseFailure = errors.New("cron expression failed to be parsed")
ErrInvalidDaysOfMonthDuplicateValue = errors.New("duplicate days of month is not allowed in Month() and Months() methods")
)
func wrapOrError(toWrap error, err error) error {
var returnErr error
if toWrap != nil && !errors.Is(err, toWrap) {
returnErr = fmt.Errorf("%s: %w", err, toWrap)
} else {
returnErr = err
}
return returnErr
}
// regex patterns for supported time formats
var (
timeWithSeconds = regexp.MustCompile(`(?m)^\d{1,2}:\d\d:\d\d$`)
timeWithoutSeconds = regexp.MustCompile(`(?m)^\d{1,2}:\d\d$`)
)
type schedulingUnit int
const (
// default unit is seconds
milliseconds schedulingUnit = iota
seconds
minutes
hours
days
weeks
months
duration
crontab
)
func callJobFunc(jobFunc interface{}) {
if jobFunc != nil {
reflect.ValueOf(jobFunc).Call([]reflect.Value{})
}
}
func callJobFuncWithParams(jobFunc interface{}, params []interface{}) {
f := reflect.ValueOf(jobFunc)
if len(params) != f.Type().NumIn() {
return
}
in := make([]reflect.Value, len(params))
for k, param := range params {
in[k] = reflect.ValueOf(param)
}
f.Call(in)
}
func getFunctionName(fn interface{}) string {
return runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name()
}
func parseTime(t string) (hour, min, sec int, err error) {
var timeLayout string
switch {
case timeWithSeconds.Match([]byte(t)):
timeLayout = "15:04:05"
case timeWithoutSeconds.Match([]byte(t)):
timeLayout = "15:04"
default:
return 0, 0, 0, ErrUnsupportedTimeFormat
}
parsedTime, err := time.Parse(timeLayout, t)
if err != nil {
return 0, 0, 0, ErrUnsupportedTimeFormat
}
return parsedTime.Hour(), parsedTime.Minute(), parsedTime.Second(), nil
}

View File

@ -1,480 +0,0 @@
package gocron
import (
"context"
"fmt"
"math/rand"
"sort"
"sync"
"sync/atomic"
"time"
"github.com/robfig/cron/v3"
"golang.org/x/sync/singleflight"
)
// Job struct stores the information necessary to run a Job
type Job struct {
mu *jobMutex
jobFunction
interval int // interval * unit between runs
random // details for randomness
duration time.Duration // time duration between runs
unit schedulingUnit // time units, e.g. 'minutes', 'hours'...
startsImmediately bool // if the Job should run upon scheduler start
atTimes []time.Duration // optional time(s) at which this Job runs when interval is day
startAtTime time.Time // optional time at which the Job starts
error error // error related to Job
lastRun time.Time // datetime of last run
nextRun time.Time // datetime of next run
scheduledWeekdays []time.Weekday // Specific days of the week to start on
daysOfTheMonth []int // Specific days of the month to run the job
tags []string // allow the user to tag Jobs with certain labels
runCount int // number of times the job ran
timer *time.Timer // handles running tasks at specific time
cronSchedule cron.Schedule // stores the schedule when a task uses cron
runWithDetails bool // when true the job is passed as the last arg of the jobFunc
}
type random struct {
rand *rand.Rand
randomizeInterval bool // whether the interval is random
randomIntervalRange [2]int // random interval range
}
type jobFunction struct {
eventListeners // additional functions to allow run 'em during job performing
function interface{} // task's function
parameters []interface{} // task's function parameters
parametersLen int // length of the passed parameters
name string //nolint the function name to run
runConfig runConfig // configuration for how many times to run the job
limiter *singleflight.Group // limits inflight runs of job to one
ctx context.Context // for cancellation
cancel context.CancelFunc // for cancellation
runState *int64 // will be non-zero when jobs are running
}
type eventListeners struct {
onBeforeJobExecution interface{} // performs before job executing
onAfterJobExecution interface{} // performs after job executing
}
type jobMutex struct {
sync.RWMutex
}
func (jf *jobFunction) incrementRunState() {
if jf.runState != nil {
atomic.AddInt64(jf.runState, 1)
}
}
func (jf *jobFunction) decrementRunState() {
if jf.runState != nil {
atomic.AddInt64(jf.runState, -1)
}
}
func (jf *jobFunction) copy() jobFunction {
cp := jobFunction{
eventListeners: jf.eventListeners,
function: jf.function,
parameters: nil,
parametersLen: jf.parametersLen,
name: jf.name,
runConfig: jf.runConfig,
limiter: jf.limiter,
ctx: jf.ctx,
cancel: jf.cancel,
runState: jf.runState,
}
cp.parameters = append(cp.parameters, jf.parameters...)
return cp
}
type runConfig struct {
finiteRuns bool
maxRuns int
mode mode
}
// mode is the Job's running mode
type mode int8
const (
// defaultMode disable any mode
defaultMode mode = iota
// singletonMode switch to single job mode
singletonMode
)
// newJob creates a new Job with the provided interval
func newJob(interval int, startImmediately bool, singletonMode bool) *Job {
ctx, cancel := context.WithCancel(context.Background())
var zero int64
job := &Job{
mu: &jobMutex{},
interval: interval,
unit: seconds,
lastRun: time.Time{},
nextRun: time.Time{},
jobFunction: jobFunction{
ctx: ctx,
cancel: cancel,
runState: &zero,
},
tags: []string{},
startsImmediately: startImmediately,
}
if singletonMode {
job.SingletonMode()
}
return job
}
func (j *Job) setRandomInterval(a, b int) {
j.random.rand = rand.New(rand.NewSource(time.Now().UnixNano())) // nolint
j.random.randomizeInterval = true
if a < b {
j.random.randomIntervalRange[0] = a
j.random.randomIntervalRange[1] = b + 1
} else {
j.random.randomIntervalRange[0] = b
j.random.randomIntervalRange[1] = a + 1
}
}
func (j *Job) getRandomInterval() int {
randNum := j.rand.Intn(j.randomIntervalRange[1] - j.randomIntervalRange[0])
return j.randomIntervalRange[0] + randNum
}
func (j *Job) getInterval() int {
if j.randomizeInterval {
return j.getRandomInterval()
}
return j.interval
}
func (j *Job) neverRan() bool {
jobLastRun := j.LastRun()
return jobLastRun.IsZero()
}
func (j *Job) getStartsImmediately() bool {
return j.startsImmediately
}
func (j *Job) setStartsImmediately(b bool) {
j.startsImmediately = b
}
func (j *Job) setTimer(t *time.Timer) {
j.mu.Lock()
defer j.mu.Unlock()
j.timer = t
}
func (j *Job) getFirstAtTime() time.Duration {
var t time.Duration
if len(j.atTimes) > 0 {
t = j.atTimes[0]
}
return t
}
func (j *Job) getAtTime(lastRun time.Time) time.Duration {
var r time.Duration
if len(j.atTimes) == 0 {
return r
}
if len(j.atTimes) == 1 {
return j.atTimes[0]
}
if lastRun.IsZero() {
r = j.atTimes[0]
} else {
for _, d := range j.atTimes {
nt := time.Date(lastRun.Year(), lastRun.Month(), lastRun.Day(), 0, 0, 0, 0, lastRun.Location()).Add(d)
if nt.After(lastRun) {
r = d
break
}
}
}
return r
}
func (j *Job) addAtTime(t time.Duration) {
if len(j.atTimes) == 0 {
j.atTimes = append(j.atTimes, t)
return
}
exist := false
index := sort.Search(len(j.atTimes), func(i int) bool {
atTime := j.atTimes[i]
b := atTime >= t
if b {
exist = atTime == t
}
return b
})
// ignore if present
if exist {
return
}
j.atTimes = append(j.atTimes, time.Duration(0))
copy(j.atTimes[index+1:], j.atTimes[index:])
j.atTimes[index] = t
}
func (j *Job) getStartAtTime() time.Time {
return j.startAtTime
}
func (j *Job) setStartAtTime(t time.Time) {
j.startAtTime = t
}
func (j *Job) getUnit() schedulingUnit {
j.mu.RLock()
defer j.mu.RUnlock()
return j.unit
}
func (j *Job) setUnit(t schedulingUnit) {
j.mu.Lock()
defer j.mu.Unlock()
j.unit = t
}
func (j *Job) getDuration() time.Duration {
j.mu.RLock()
defer j.mu.RUnlock()
return j.duration
}
func (j *Job) setDuration(t time.Duration) {
j.mu.Lock()
defer j.mu.Unlock()
j.duration = t
}
// hasTags returns true if all tags are matched on this Job
func (j *Job) hasTags(tags ...string) bool {
// Build map of all Job tags for easy comparison
jobTags := map[string]int{}
for _, tag := range j.tags {
jobTags[tag] = 0
}
// Loop through required tags and if one doesn't exist, return false
for _, tag := range tags {
_, ok := jobTags[tag]
if !ok {
return false
}
}
return true
}
// Error returns an error if one occurred while creating the Job.
// If multiple errors occurred, they will be wrapped and can be
// checked using the standard unwrap options.
func (j *Job) Error() error {
return j.error
}
// Tag allows you to add arbitrary labels to a Job that do not
// impact the functionality of the Job
func (j *Job) Tag(tags ...string) {
j.tags = append(j.tags, tags...)
}
// Untag removes a tag from a Job
func (j *Job) Untag(t string) {
var newTags []string
for _, tag := range j.tags {
if t != tag {
newTags = append(newTags, tag)
}
}
j.tags = newTags
}
// Tags returns the tags attached to the Job
func (j *Job) Tags() []string {
return j.tags
}
// SetEventListeners accepts two functions that will be called, one before and one after the job is run
func (j *Job) SetEventListeners(onBeforeJobExecution interface{}, onAfterJobExecution interface{}) {
j.eventListeners = eventListeners{
onBeforeJobExecution: onBeforeJobExecution,
onAfterJobExecution: onAfterJobExecution,
}
}
// ScheduledTime returns the time of the Job's next scheduled run
func (j *Job) ScheduledTime() time.Time {
j.mu.RLock()
defer j.mu.RUnlock()
return j.nextRun
}
// ScheduledAtTime returns the specific time of day the Job will run at.
// If multiple times are set, the earliest time will be returned.
func (j *Job) ScheduledAtTime() string {
if len(j.atTimes) == 0 {
return "0:0"
}
return fmt.Sprintf("%d:%d", j.getFirstAtTime()/time.Hour, (j.getFirstAtTime()%time.Hour)/time.Minute)
}
// ScheduledAtTimes returns the specific times of day the Job will run at
func (j *Job) ScheduledAtTimes() []string {
r := make([]string, len(j.atTimes))
for i, t := range j.atTimes {
r[i] = fmt.Sprintf("%d:%d", t/time.Hour, (t%time.Hour)/time.Minute)
}
return r
}
// Weekday returns which day of the week the Job will run on and
// will return an error if the Job is not scheduled weekly
func (j *Job) Weekday() (time.Weekday, error) {
if len(j.scheduledWeekdays) == 0 {
return time.Sunday, ErrNotScheduledWeekday
}
return j.scheduledWeekdays[0], nil
}
// Weekdays returns a slice of time.Weekday that the Job will run in a week and
// will return an error if the Job is not scheduled weekly
func (j *Job) Weekdays() []time.Weekday {
// appending on j.scheduledWeekdays may cause a side effect
if len(j.scheduledWeekdays) == 0 {
return []time.Weekday{time.Sunday}
}
return j.scheduledWeekdays
}
// LimitRunsTo limits the number of executions of this job to n.
// Upon reaching the limit, the job is removed from the scheduler.
//
// Note: If a job is added to a running scheduler and this method is then used
// you may see the job run more than the set limit as job is scheduled immediately
// by default upon being added to the scheduler. It is recommended to use the
// LimitRunsTo() func on the scheduler chain when scheduling the job.
// For example: scheduler.LimitRunsTo(1).Do()
func (j *Job) LimitRunsTo(n int) {
j.mu.Lock()
defer j.mu.Unlock()
j.runConfig.finiteRuns = true
j.runConfig.maxRuns = n
}
// SingletonMode prevents a new job from starting if the prior job has not yet
// completed it's run
// Note: If a job is added to a running scheduler and this method is then used
// you may see the job run overrun itself as job is scheduled immediately
// by default upon being added to the scheduler. It is recommended to use the
// SingletonMode() func on the scheduler chain when scheduling the job.
func (j *Job) SingletonMode() {
j.mu.Lock()
defer j.mu.Unlock()
j.runConfig.mode = singletonMode
j.jobFunction.limiter = &singleflight.Group{}
}
// shouldRun evaluates if this job should run again
// based on the runConfig
func (j *Job) shouldRun() bool {
j.mu.RLock()
defer j.mu.RUnlock()
return !j.runConfig.finiteRuns || j.runCount < j.runConfig.maxRuns
}
// LastRun returns the time the job was run last
func (j *Job) LastRun() time.Time {
j.mu.RLock()
defer j.mu.RUnlock()
return j.lastRun
}
func (j *Job) setLastRun(t time.Time) {
j.lastRun = t
}
// NextRun returns the time the job will run next
func (j *Job) NextRun() time.Time {
j.mu.RLock()
defer j.mu.RUnlock()
return j.nextRun
}
func (j *Job) setNextRun(t time.Time) {
j.mu.Lock()
defer j.mu.Unlock()
j.nextRun = t
}
// RunCount returns the number of time the job ran so far
func (j *Job) RunCount() int {
j.mu.Lock()
defer j.mu.Unlock()
return j.runCount
}
func (j *Job) stop() {
j.mu.Lock()
defer j.mu.Unlock()
if j.timer != nil {
j.timer.Stop()
}
if j.cancel != nil {
j.cancel()
}
}
// IsRunning reports whether any instances of the job function are currently running
func (j *Job) IsRunning() bool {
return atomic.LoadInt64(j.runState) != 0
}
// you must lock the job before calling copy
func (j *Job) copy() Job {
return Job{
mu: &jobMutex{},
jobFunction: j.jobFunction,
interval: j.interval,
duration: j.duration,
unit: j.unit,
startsImmediately: j.startsImmediately,
atTimes: j.atTimes,
startAtTime: j.startAtTime,
error: j.error,
lastRun: j.lastRun,
nextRun: j.nextRun,
scheduledWeekdays: j.scheduledWeekdays,
daysOfTheMonth: j.daysOfTheMonth,
tags: j.tags,
runCount: j.runCount,
timer: j.timer,
cronSchedule: j.cronSchedule,
runWithDetails: j.runWithDetails,
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,33 +0,0 @@
package gocron
import "time"
var _ TimeWrapper = (*trueTime)(nil)
// TimeWrapper is an interface that wraps the Now, Sleep, and Unix methods of the time package.
// This allows the library and users to mock the time package for testing.
type TimeWrapper interface {
Now(*time.Location) time.Time
Unix(int64, int64) time.Time
Sleep(time.Duration)
}
type trueTime struct{}
func (t *trueTime) Now(location *time.Location) time.Time {
return time.Now().In(location)
}
func (t *trueTime) Unix(sec int64, nsec int64) time.Time {
return time.Unix(sec, nsec)
}
func (t *trueTime) Sleep(d time.Duration) {
time.Sleep(d)
}
// afterFunc proxies the time.AfterFunc function.
// This allows it to be mocked for testing.
func afterFunc(d time.Duration, f func()) *time.Timer {
return time.AfterFunc(d, f)
}

View File

@ -1,136 +0,0 @@
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package semaphore provides a weighted semaphore implementation.
package semaphore // import "golang.org/x/sync/semaphore"
import (
"container/list"
"context"
"sync"
)
type waiter struct {
n int64
ready chan<- struct{} // Closed when semaphore acquired.
}
// NewWeighted creates a new weighted semaphore with the given
// maximum combined weight for concurrent access.
func NewWeighted(n int64) *Weighted {
w := &Weighted{size: n}
return w
}
// Weighted provides a way to bound concurrent access to a resource.
// The callers can request access with a given weight.
type Weighted struct {
size int64
cur int64
mu sync.Mutex
waiters list.List
}
// Acquire acquires the semaphore with a weight of n, blocking until resources
// are available or ctx is done. On success, returns nil. On failure, returns
// ctx.Err() and leaves the semaphore unchanged.
//
// If ctx is already done, Acquire may still succeed without blocking.
func (s *Weighted) Acquire(ctx context.Context, n int64) error {
s.mu.Lock()
if s.size-s.cur >= n && s.waiters.Len() == 0 {
s.cur += n
s.mu.Unlock()
return nil
}
if n > s.size {
// Don't make other Acquire calls block on one that's doomed to fail.
s.mu.Unlock()
<-ctx.Done()
return ctx.Err()
}
ready := make(chan struct{})
w := waiter{n: n, ready: ready}
elem := s.waiters.PushBack(w)
s.mu.Unlock()
select {
case <-ctx.Done():
err := ctx.Err()
s.mu.Lock()
select {
case <-ready:
// Acquired the semaphore after we were canceled. Rather than trying to
// fix up the queue, just pretend we didn't notice the cancelation.
err = nil
default:
isFront := s.waiters.Front() == elem
s.waiters.Remove(elem)
// If we're at the front and there're extra tokens left, notify other waiters.
if isFront && s.size > s.cur {
s.notifyWaiters()
}
}
s.mu.Unlock()
return err
case <-ready:
return nil
}
}
// TryAcquire acquires the semaphore with a weight of n without blocking.
// On success, returns true. On failure, returns false and leaves the semaphore unchanged.
func (s *Weighted) TryAcquire(n int64) bool {
s.mu.Lock()
success := s.size-s.cur >= n && s.waiters.Len() == 0
if success {
s.cur += n
}
s.mu.Unlock()
return success
}
// Release releases the semaphore with a weight of n.
func (s *Weighted) Release(n int64) {
s.mu.Lock()
s.cur -= n
if s.cur < 0 {
s.mu.Unlock()
panic("semaphore: released more than held")
}
s.notifyWaiters()
s.mu.Unlock()
}
func (s *Weighted) notifyWaiters() {
for {
next := s.waiters.Front()
if next == nil {
break // No more waiters blocked.
}
w := next.Value.(waiter)
if s.size-s.cur < w.n {
// Not enough tokens for the next waiter. We could keep going (to try to
// find a waiter with a smaller request), but under load that could cause
// starvation for large requests; instead, we leave all remaining waiters
// blocked.
//
// Consider a semaphore used as a read-write lock, with N tokens, N
// readers, and one writer. Each reader can Acquire(1) to obtain a read
// lock. The writer can Acquire(N) to obtain a write lock, excluding all
// of the readers. If we allow the readers to jump ahead in the queue,
// the writer will starve — there is always one token available for every
// reader.
break
}
s.cur += w.n
s.waiters.Remove(next)
close(w.ready)
}
}

12
vendor/modules.txt vendored
View File

@ -24,14 +24,6 @@ github.com/cenkalti/backoff/v4
# github.com/cespare/xxhash/v2 v2.1.2
## explicit; go 1.11
github.com/cespare/xxhash/v2
# github.com/contribsys/faktory v1.6.2
## explicit; go 1.17
github.com/contribsys/faktory/client
github.com/contribsys/faktory/internal/pool
github.com/contribsys/faktory/util
# github.com/contribsys/faktory_worker_go v1.6.0
## explicit; go 1.17
github.com/contribsys/faktory_worker_go
# github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f
## explicit
github.com/dgryski/go-rendezvous
@ -44,9 +36,6 @@ github.com/felixge/httpsnoop
# github.com/fsnotify/fsnotify v1.6.0
## explicit; go 1.16
github.com/fsnotify/fsnotify
# github.com/go-co-op/gocron v1.18.0
## explicit; go 1.19
github.com/go-co-op/gocron
# github.com/go-fed/activity v1.0.0
## explicit; go 1.12
github.com/go-fed/activity/pub
@ -661,7 +650,6 @@ golang.org/x/net/internal/timeseries
golang.org/x/net/trace
# golang.org/x/sync v0.1.0
## explicit
golang.org/x/sync/semaphore
golang.org/x/sync/singleflight
# golang.org/x/sys v0.2.0
## explicit; go 1.17

View File

@ -7,7 +7,7 @@
{{- $textNextRun := .Localizer.TextNextRun -}}
{{- $textRunJob := .Localizer.TextRunJob -}}
{{- $textRunCount := .Localizer.TextRunCount -}}
{{- $textRunning := .Localizer.TextRunning -}}
{{- $textStatus := .Localizer.TextStatus -}}
{{- template "header" . }}
<div class="container">
<div class="row">
@ -28,7 +28,7 @@
<thead>
<tr>
<th scope="col" lang="{{ $textJob.Language }}">{{ $textJob }}</th>
<th scope="col" lang="{{ $textRunning.Language }}">{{ $textRunning }}</th>
<th scope="col" lang="{{ $textStatus.Language }}">{{ $textStatus }}</th>
<th scope="col" lang="{{ $textRunCount.Language }}">{{ $textRunCount }}</th>
<th scope="col" lang="{{ $textLastRun.Language }}">{{ $textLastRun }}</th>
<th scope="col" lang="{{ $textNextRun.Language }}">{{ $textNextRun }}</th>
@ -39,7 +39,7 @@
{{- range $job := .Jobs }}
<tr>
<th scope="row" class="align-middle">{{ $job.Name }}</th>
<td class="align-middle">{{ template "yesno" $job.Running }}</td>
<td class="align-middle">{{ $job.State }}</td>
<td class="align-middle">{{ $job.RunCount }}</td>
<td class="align-middle">{{ formatDateTimeUTC $job.LastRun }}</td>
<td class="align-middle">{{ formatDateTimeUTC $job.NextRun }}</td>