From cdaec9b3e00c66bd1233f747aa99975a88a6cdf6 Mon Sep 17 00:00:00 2001 From: Tyr Mactire Date: Sun, 12 Mar 2023 01:07:32 +0000 Subject: [PATCH] asynq scheduler (#185) Reviewed-on: https://git.ptzo.gdn/feditools/relay/pulls/185 Co-authored-by: Tyr Mactire Co-committed-by: Tyr Mactire --- .../relay/action}/scheduler/logger.go | 4 +- cmd/relay/action/scheduler/start.go | 210 +++ cmd/relay/action/server/start.go | 19 - cmd/relay/flag/schduler.go | 15 + cmd/relay/main.go | 1 + cmd/relay/scheduler.go | 33 + go.mod | 3 - go.sum | 6 - internal/http/webapp/admin_job.go | 13 - internal/language/text_s.go | 18 + internal/logic/logic1/block_add.go | 10 - internal/logic/logic1/block_delete.go | 4 - internal/logic/logic1/block_update.go | 10 - internal/logic/logic1/logic.go | 6 - internal/logic/logic1/scheduler.go | 17 +- internal/logic/schduler.go | 4 +- internal/runner/asynq/activity_deliver.go | 2 +- internal/runner/asynq/activity_inbox.go | 2 +- internal/runner/asynq/block_add.go | 2 +- internal/runner/asynq/block_delete.go | 2 +- internal/runner/asynq/block_update.go | 2 +- internal/runner/asynq/maint_delivery_error.go | 11 +- internal/runner/asynq/runner.go | 41 +- internal/runner/asynq/scheduler.go | 61 + internal/runner/asynq/send_notification.go | 2 +- internal/runner/asynq/update_account.go | 2 +- internal/runner/asynq/update_accounts.go | 23 + internal/runner/asynq/update_instance.go | 2 +- internal/runner/asynq/update_instances.go | 23 + internal/runner/faktory/account.go | 43 - internal/runner/faktory/activity.go | 120 -- internal/runner/faktory/block.go | 102 -- internal/runner/faktory/const.go | 15 - internal/runner/faktory/instance.go | 43 - internal/runner/faktory/logger.go | 9 - internal/runner/faktory/maintenance.go | 32 - internal/runner/faktory/middleware.go | 19 - internal/runner/faktory/notification.go | 49 - internal/runner/faktory/runner.go | 65 - internal/runner/faktory/util.go | 20 - internal/runner/runner.go | 2 + internal/scheduler/account.go | 15 - internal/scheduler/const.go | 9 - internal/scheduler/instance.go | 15 - internal/scheduler/maintenance.go | 11 - internal/scheduler/module.go | 54 - internal/scheduler/run.go | 5 - internal/scheduler/util.go | 7 - vendor/github.com/contribsys/faktory/LICENSE | 674 --------- .../contribsys/faktory/client/LICENSE | 373 ----- .../contribsys/faktory/client/batch.go | 189 --- .../contribsys/faktory/client/client.go | 692 --------- .../contribsys/faktory/client/client_bsd.go | 8 - .../contribsys/faktory/client/client_linux.go | 37 - .../faktory/client/client_windows.go | 6 - .../contribsys/faktory/client/faktory.go | 6 - .../contribsys/faktory/client/job.go | 127 -- .../contribsys/faktory/client/mutate.go | 153 -- .../contribsys/faktory/client/package.go | 4 - .../contribsys/faktory/client/pool.go | 69 - .../contribsys/faktory/client/tracking.go | 74 - .../contribsys/faktory/internal/pool/pool.go | 219 --- .../contribsys/faktory/util/logger.go | 123 -- .../contribsys/faktory/util/util.go | 131 -- .../contribsys/faktory/util/util_bsd.go | 20 - .../contribsys/faktory/util/util_linux.go | 25 - .../contribsys/faktory/util/util_windows.go | 16 - .../contribsys/faktory_worker_go/.gitignore | 17 - .../faktory_worker_go/.golangci.yml | 25 - .../contribsys/faktory_worker_go/Changes.md | 68 - .../contribsys/faktory_worker_go/LICENSE | 373 ----- .../contribsys/faktory_worker_go/Makefile | 15 - .../contribsys/faktory_worker_go/README.md | 190 --- .../contribsys/faktory_worker_go/context.go | 148 -- .../contribsys/faktory_worker_go/log.go | 60 - .../contribsys/faktory_worker_go/manager.go | 253 ---- .../faktory_worker_go/middleware.go | 27 - .../contribsys/faktory_worker_go/runner.go | 243 --- .../faktory_worker_go/runner_unix.go | 32 - .../faktory_worker_go/runner_windows.go | 28 - .../contribsys/faktory_worker_go/testing.go | 36 - .../contribsys/faktory_worker_go/types.go | 13 - vendor/github.com/go-co-op/gocron/.gitignore | 19 - .../github.com/go-co-op/gocron/.golangci.yaml | 49 - .../go-co-op/gocron/CODE_OF_CONDUCT.md | 73 - .../go-co-op/gocron/CONTRIBUTING.md | 40 - vendor/github.com/go-co-op/gocron/LICENSE | 21 - vendor/github.com/go-co-op/gocron/Makefile | 12 - vendor/github.com/go-co-op/gocron/README.md | 132 -- vendor/github.com/go-co-op/gocron/SECURITY.md | 15 - vendor/github.com/go-co-op/gocron/executor.go | 127 -- vendor/github.com/go-co-op/gocron/gocron.go | 129 -- vendor/github.com/go-co-op/gocron/job.go | 480 ------ .../github.com/go-co-op/gocron/scheduler.go | 1337 ----------------- .../github.com/go-co-op/gocron/timeHelper.go | 33 - .../golang.org/x/sync/semaphore/semaphore.go | 136 -- vendor/modules.txt | 12 - web/template/admin_jobs.gohtml | 6 +- 98 files changed, 443 insertions(+), 7835 deletions(-) rename {internal => cmd/relay/action}/scheduler/logger.go (60%) create mode 100644 cmd/relay/action/scheduler/start.go create mode 100644 cmd/relay/flag/schduler.go create mode 100644 cmd/relay/scheduler.go create mode 100644 internal/runner/asynq/scheduler.go create mode 100644 internal/runner/asynq/update_accounts.go create mode 100644 internal/runner/asynq/update_instances.go delete mode 100644 internal/runner/faktory/account.go delete mode 100644 internal/runner/faktory/activity.go delete mode 100644 internal/runner/faktory/block.go delete mode 100644 internal/runner/faktory/const.go delete mode 100644 internal/runner/faktory/instance.go delete mode 100644 internal/runner/faktory/logger.go delete mode 100644 internal/runner/faktory/maintenance.go delete mode 100644 internal/runner/faktory/middleware.go delete mode 100644 internal/runner/faktory/notification.go delete mode 100644 internal/runner/faktory/runner.go delete mode 100644 internal/runner/faktory/util.go delete mode 100644 internal/scheduler/account.go delete mode 100644 internal/scheduler/const.go delete mode 100644 internal/scheduler/instance.go delete mode 100644 internal/scheduler/maintenance.go delete mode 100644 internal/scheduler/module.go delete mode 100644 internal/scheduler/run.go delete mode 100644 internal/scheduler/util.go delete mode 100644 vendor/github.com/contribsys/faktory/LICENSE delete mode 100644 vendor/github.com/contribsys/faktory/client/LICENSE delete mode 100644 vendor/github.com/contribsys/faktory/client/batch.go delete mode 100644 vendor/github.com/contribsys/faktory/client/client.go delete mode 100644 vendor/github.com/contribsys/faktory/client/client_bsd.go delete mode 100644 vendor/github.com/contribsys/faktory/client/client_linux.go delete mode 100644 vendor/github.com/contribsys/faktory/client/client_windows.go delete mode 100644 vendor/github.com/contribsys/faktory/client/faktory.go delete mode 100644 vendor/github.com/contribsys/faktory/client/job.go delete mode 100644 vendor/github.com/contribsys/faktory/client/mutate.go delete mode 100644 vendor/github.com/contribsys/faktory/client/package.go delete mode 100644 vendor/github.com/contribsys/faktory/client/pool.go delete mode 100644 vendor/github.com/contribsys/faktory/client/tracking.go delete mode 100644 vendor/github.com/contribsys/faktory/internal/pool/pool.go delete mode 100644 vendor/github.com/contribsys/faktory/util/logger.go delete mode 100644 vendor/github.com/contribsys/faktory/util/util.go delete mode 100644 vendor/github.com/contribsys/faktory/util/util_bsd.go delete mode 100644 vendor/github.com/contribsys/faktory/util/util_linux.go delete mode 100644 vendor/github.com/contribsys/faktory/util/util_windows.go delete mode 100644 vendor/github.com/contribsys/faktory_worker_go/.gitignore delete mode 100644 vendor/github.com/contribsys/faktory_worker_go/.golangci.yml delete mode 100644 vendor/github.com/contribsys/faktory_worker_go/Changes.md delete mode 100644 vendor/github.com/contribsys/faktory_worker_go/LICENSE delete mode 100644 vendor/github.com/contribsys/faktory_worker_go/Makefile delete mode 100644 vendor/github.com/contribsys/faktory_worker_go/README.md delete mode 100644 vendor/github.com/contribsys/faktory_worker_go/context.go delete mode 100644 vendor/github.com/contribsys/faktory_worker_go/log.go delete mode 100644 vendor/github.com/contribsys/faktory_worker_go/manager.go delete mode 100644 vendor/github.com/contribsys/faktory_worker_go/middleware.go delete mode 100644 vendor/github.com/contribsys/faktory_worker_go/runner.go delete mode 100644 vendor/github.com/contribsys/faktory_worker_go/runner_unix.go delete mode 100644 vendor/github.com/contribsys/faktory_worker_go/runner_windows.go delete mode 100644 vendor/github.com/contribsys/faktory_worker_go/testing.go delete mode 100644 vendor/github.com/contribsys/faktory_worker_go/types.go delete mode 100644 vendor/github.com/go-co-op/gocron/.gitignore delete mode 100644 vendor/github.com/go-co-op/gocron/.golangci.yaml delete mode 100644 vendor/github.com/go-co-op/gocron/CODE_OF_CONDUCT.md delete mode 100644 vendor/github.com/go-co-op/gocron/CONTRIBUTING.md delete mode 100644 vendor/github.com/go-co-op/gocron/LICENSE delete mode 100644 vendor/github.com/go-co-op/gocron/Makefile delete mode 100644 vendor/github.com/go-co-op/gocron/README.md delete mode 100644 vendor/github.com/go-co-op/gocron/SECURITY.md delete mode 100644 vendor/github.com/go-co-op/gocron/executor.go delete mode 100644 vendor/github.com/go-co-op/gocron/gocron.go delete mode 100644 vendor/github.com/go-co-op/gocron/job.go delete mode 100644 vendor/github.com/go-co-op/gocron/scheduler.go delete mode 100644 vendor/github.com/go-co-op/gocron/timeHelper.go delete mode 100644 vendor/golang.org/x/sync/semaphore/semaphore.go diff --git a/internal/scheduler/logger.go b/cmd/relay/action/scheduler/logger.go similarity index 60% rename from internal/scheduler/logger.go rename to cmd/relay/action/scheduler/logger.go index 5f5c5d3..be99a02 100644 --- a/internal/scheduler/logger.go +++ b/cmd/relay/action/scheduler/logger.go @@ -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{} diff --git a/cmd/relay/action/scheduler/start.go b/cmd/relay/action/scheduler/start.go new file mode 100644 index 0000000..1878c02 --- /dev/null +++ b/cmd/relay/action/scheduler/start.go @@ -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://@uptrace.dev/"), + + 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 +} diff --git a/cmd/relay/action/server/start.go b/cmd/relay/action/server/start.go index 64bf8f0..41eab51 100644 --- a/cmd/relay/action/server/start.go +++ b/cmd/relay/action/server/start.go @@ -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") diff --git a/cmd/relay/flag/schduler.go b/cmd/relay/flag/schduler.go new file mode 100644 index 0000000..635306b --- /dev/null +++ b/cmd/relay/flag/schduler.go @@ -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) +} diff --git a/cmd/relay/main.go b/cmd/relay/main.go index 1f1d218..625d175 100644 --- a/cmd/relay/main.go +++ b/cmd/relay/main.go @@ -51,6 +51,7 @@ func main() { rootCmd.AddCommand(accountCommands()) rootCmd.AddCommand(databaseCommands()) rootCmd.AddCommand(serverCommands()) + rootCmd.AddCommand(schedulerCommands()) rootCmd.AddCommand(workerCommands()) err = rootCmd.Execute() diff --git a/cmd/relay/scheduler.go b/cmd/relay/scheduler.go new file mode 100644 index 0000000..53f9c57 --- /dev/null +++ b/cmd/relay/scheduler.go @@ -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 +} diff --git a/go.mod b/go.mod index 98a7bd0..1b737b6 100644 --- a/go.mod +++ b/go.mod @@ -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 diff --git a/go.sum b/go.sum index 9aff397..16b8d08 100644 --- a/go.sum +++ b/go.sum @@ -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= diff --git a/internal/http/webapp/admin_job.go b/internal/http/webapp/admin_job.go index 92ce438..1843856 100644 --- a/internal/http/webapp/admin_job.go +++ b/internal/http/webapp/admin_job.go @@ -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, }, diff --git a/internal/language/text_s.go b/internal/language/text_s.go index 412377b..0d1a748 100644 --- a/internal/language/text_s.go +++ b/internal/language/text_s.go @@ -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, + } +} diff --git a/internal/logic/logic1/block_add.go b/internal/logic/logic1/block_add.go index b1a04e4..41a55c2 100644 --- a/internal/logic/logic1/block_add.go +++ b/internal/logic/logic1/block_add.go @@ -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) diff --git a/internal/logic/logic1/block_delete.go b/internal/logic/logic1/block_delete.go index 5dec06f..6633aac 100644 --- a/internal/logic/logic1/block_delete.go +++ b/internal/logic/logic1/block_delete.go @@ -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 diff --git a/internal/logic/logic1/block_update.go b/internal/logic/logic1/block_update.go index 156c706..630f229 100644 --- a/internal/logic/logic1/block_update.go +++ b/internal/logic/logic1/block_update.go @@ -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) diff --git a/internal/logic/logic1/logic.go b/internal/logic/logic1/logic.go index 17d318e..43a3aab 100644 --- a/internal/logic/logic1/logic.go +++ b/internal/logic/logic1/logic.go @@ -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 -} diff --git a/internal/logic/logic1/scheduler.go b/internal/logic/logic1/scheduler.go index 3578ae2..7839420 100644 --- a/internal/logic/logic1/scheduler.go +++ b/internal/logic/logic1/scheduler.go @@ -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 } diff --git a/internal/logic/schduler.go b/internal/logic/schduler.go index b5ea1d9..73e7f98 100644 --- a/internal/logic/schduler.go +++ b/internal/logic/schduler.go @@ -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 } diff --git a/internal/runner/asynq/activity_deliver.go b/internal/runner/asynq/activity_deliver.go index 9a0bff3..ab213ac 100644 --- a/internal/runner/asynq/activity_deliver.go +++ b/internal/runner/asynq/activity_deliver.go @@ -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()) diff --git a/internal/runner/asynq/activity_inbox.go b/internal/runner/asynq/activity_inbox.go index bd2bec5..f5a9766 100644 --- a/internal/runner/asynq/activity_inbox.go +++ b/internal/runner/asynq/activity_inbox.go @@ -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()) diff --git a/internal/runner/asynq/block_add.go b/internal/runner/asynq/block_add.go index 3d752c6..fe93003 100644 --- a/internal/runner/asynq/block_add.go +++ b/internal/runner/asynq/block_add.go @@ -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()) diff --git a/internal/runner/asynq/block_delete.go b/internal/runner/asynq/block_delete.go index cc6b5f6..75b8205 100644 --- a/internal/runner/asynq/block_delete.go +++ b/internal/runner/asynq/block_delete.go @@ -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()) diff --git a/internal/runner/asynq/block_update.go b/internal/runner/asynq/block_update.go index 02d7230..13c16ec 100644 --- a/internal/runner/asynq/block_update.go +++ b/internal/runner/asynq/block_update.go @@ -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()) diff --git a/internal/runner/asynq/maint_delivery_error.go b/internal/runner/asynq/maint_delivery_error.go index 24f8b6c..623a880 100644 --- a/internal/runner/asynq/maint_delivery_error.go +++ b/internal/runner/asynq/maint_delivery_error.go @@ -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 } diff --git a/internal/runner/asynq/runner.go b/internal/runner/asynq/runner.go index 67c709d..eca7605 100644 --- a/internal/runner/asynq/runner.go +++ b/internal/runner/asynq/runner.go @@ -10,16 +10,17 @@ 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, - logic: c.Logic, - tracer: otel.Tracer("internal/runner/asynq"), + client: asynq.NewClient(redisConf), + inspector: asynq.NewInspector(redisConf), + logic: c.Logic, + tracer: otel.Tracer("internal/runner/asynq"), concurrency: c.Concurrency, address: c.Address, @@ -29,10 +30,11 @@ func New(c *Config) (*Runner, error) { } type Runner struct { - client *asynq.Client - logic logic.Logic - server *asynq.Server - tracer trace.Tracer + client *asynq.Client + inspector *asynq.Inspector + logic logic.Logic + server *asynq.Server + tracer trace.Tracer concurrency int address string @@ -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 +} diff --git a/internal/runner/asynq/scheduler.go b/internal/runner/asynq/scheduler.go new file mode 100644 index 0000000..840ffdd --- /dev/null +++ b/internal/runner/asynq/scheduler.go @@ -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 +} diff --git a/internal/runner/asynq/send_notification.go b/internal/runner/asynq/send_notification.go index 41b2c34..b974104 100644 --- a/internal/runner/asynq/send_notification.go +++ b/internal/runner/asynq/send_notification.go @@ -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()) diff --git a/internal/runner/asynq/update_account.go b/internal/runner/asynq/update_account.go index ce228fb..f8ae56a 100644 --- a/internal/runner/asynq/update_account.go +++ b/internal/runner/asynq/update_account.go @@ -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()) diff --git a/internal/runner/asynq/update_accounts.go b/internal/runner/asynq/update_accounts.go new file mode 100644 index 0000000..701e23a --- /dev/null +++ b/internal/runner/asynq/update_accounts.go @@ -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 +} diff --git a/internal/runner/asynq/update_instance.go b/internal/runner/asynq/update_instance.go index 8b733d1..5377cae 100644 --- a/internal/runner/asynq/update_instance.go +++ b/internal/runner/asynq/update_instance.go @@ -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()) diff --git a/internal/runner/asynq/update_instances.go b/internal/runner/asynq/update_instances.go new file mode 100644 index 0000000..aa3749d --- /dev/null +++ b/internal/runner/asynq/update_instances.go @@ -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 +} diff --git a/internal/runner/faktory/account.go b/internal/runner/faktory/account.go deleted file mode 100644 index e0a2131..0000000 --- a/internal/runner/faktory/account.go +++ /dev/null @@ -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) -} diff --git a/internal/runner/faktory/activity.go b/internal/runner/faktory/activity.go deleted file mode 100644 index 2cc4377..0000000 --- a/internal/runner/faktory/activity.go +++ /dev/null @@ -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) -} diff --git a/internal/runner/faktory/block.go b/internal/runner/faktory/block.go deleted file mode 100644 index 7da71df..0000000 --- a/internal/runner/faktory/block.go +++ /dev/null @@ -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) -} diff --git a/internal/runner/faktory/const.go b/internal/runner/faktory/const.go deleted file mode 100644 index 28c1711..0000000 --- a/internal/runner/faktory/const.go +++ /dev/null @@ -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" -) diff --git a/internal/runner/faktory/instance.go b/internal/runner/faktory/instance.go deleted file mode 100644 index 35cead7..0000000 --- a/internal/runner/faktory/instance.go +++ /dev/null @@ -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) -} diff --git a/internal/runner/faktory/logger.go b/internal/runner/faktory/logger.go deleted file mode 100644 index 3d3de64..0000000 --- a/internal/runner/faktory/logger.go +++ /dev/null @@ -1,9 +0,0 @@ -package faktory - -import ( - "git.ptzo.gdn/feditools/relay/internal/log" -) - -type empty struct{} - -var logger = log.WithPackageField(empty{}) diff --git a/internal/runner/faktory/maintenance.go b/internal/runner/faktory/maintenance.go deleted file mode 100644 index eda19cb..0000000 --- a/internal/runner/faktory/maintenance.go +++ /dev/null @@ -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()) -} diff --git a/internal/runner/faktory/middleware.go b/internal/runner/faktory/middleware.go deleted file mode 100644 index 441dfa7..0000000 --- a/internal/runner/faktory/middleware.go +++ /dev/null @@ -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) -} diff --git a/internal/runner/faktory/notification.go b/internal/runner/faktory/notification.go deleted file mode 100644 index e6e2c67..0000000 --- a/internal/runner/faktory/notification.go +++ /dev/null @@ -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) -} diff --git a/internal/runner/faktory/runner.go b/internal/runner/faktory/runner.go deleted file mode 100644 index 5090b5e..0000000 --- a/internal/runner/faktory/runner.go +++ /dev/null @@ -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()) - } - }() -} diff --git a/internal/runner/faktory/util.go b/internal/runner/faktory/util.go deleted file mode 100644 index ec2ae57..0000000 --- a/internal/runner/faktory/util.go +++ /dev/null @@ -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 -} diff --git a/internal/runner/runner.go b/internal/runner/runner.go index 321c0a3..15b5d70 100644 --- a/internal/runner/runner.go +++ b/internal/runner/runner.go @@ -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) } diff --git a/internal/scheduler/account.go b/internal/scheduler/account.go deleted file mode 100644 index 0d479ad..0000000 --- a/internal/scheduler/account.go +++ /dev/null @@ -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()) - } -} diff --git a/internal/scheduler/const.go b/internal/scheduler/const.go deleted file mode 100644 index ffee48e..0000000 --- a/internal/scheduler/const.go +++ /dev/null @@ -1,9 +0,0 @@ -package scheduler - -type Job string - -const ( - JobMaintDeliveryErrorTimeout Job = "MaintDeliveryErrorTimeout" - JobUpdateAccountInfo Job = "UpdateAccountInfo" - JobUpdateInstanceInfo Job = "UpdateInstanceInfo" -) diff --git a/internal/scheduler/instance.go b/internal/scheduler/instance.go deleted file mode 100644 index 4c3d5be..0000000 --- a/internal/scheduler/instance.go +++ /dev/null @@ -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()) - } -} diff --git a/internal/scheduler/maintenance.go b/internal/scheduler/maintenance.go deleted file mode 100644 index f78fac0..0000000 --- a/internal/scheduler/maintenance.go +++ /dev/null @@ -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()) - } -} diff --git a/internal/scheduler/module.go b/internal/scheduler/module.go deleted file mode 100644 index eff9b84..0000000 --- a/internal/scheduler/module.go +++ /dev/null @@ -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() -} diff --git a/internal/scheduler/run.go b/internal/scheduler/run.go deleted file mode 100644 index a0f0b2b..0000000 --- a/internal/scheduler/run.go +++ /dev/null @@ -1,5 +0,0 @@ -package scheduler - -func (m *Module) Run(t Job) error { - return m.scheduler.RunByTag(string(t)) -} diff --git a/internal/scheduler/util.go b/internal/scheduler/util.go deleted file mode 100644 index 2951ded..0000000 --- a/internal/scheduler/util.go +++ /dev/null @@ -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) -} diff --git a/vendor/github.com/contribsys/faktory/LICENSE b/vendor/github.com/contribsys/faktory/LICENSE deleted file mode 100644 index fcb19d7..0000000 --- a/vendor/github.com/contribsys/faktory/LICENSE +++ /dev/null @@ -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. - 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. - - - Copyright (C) - - 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 . - -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 -. diff --git a/vendor/github.com/contribsys/faktory/client/LICENSE b/vendor/github.com/contribsys/faktory/client/LICENSE deleted file mode 100644 index a612ad9..0000000 --- a/vendor/github.com/contribsys/faktory/client/LICENSE +++ /dev/null @@ -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. diff --git a/vendor/github.com/contribsys/faktory/client/batch.go b/vendor/github.com/contribsys/faktory/client/batch.go deleted file mode 100644 index cfe1a2f..0000000 --- a/vendor/github.com/contribsys/faktory/client/batch.go +++ /dev/null @@ -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 -} diff --git a/vendor/github.com/contribsys/faktory/client/client.go b/vendor/github.com/contribsys/faktory/client/client.go deleted file mode 100644 index 2c770d7..0000000 --- a/vendor/github.com/contribsys/faktory/client/client.go +++ /dev/null @@ -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) -} diff --git a/vendor/github.com/contribsys/faktory/client/client_bsd.go b/vendor/github.com/contribsys/faktory/client/client_bsd.go deleted file mode 100644 index 642e320..0000000 --- a/vendor/github.com/contribsys/faktory/client/client_bsd.go +++ /dev/null @@ -1,8 +0,0 @@ -// +build darwin freebsd netbsd openbsd - -package client - -func RssKb() int64 { - // TODO Submit a PR? - return 0 -} diff --git a/vendor/github.com/contribsys/faktory/client/client_linux.go b/vendor/github.com/contribsys/faktory/client/client_linux.go deleted file mode 100644 index 1854231..0000000 --- a/vendor/github.com/contribsys/faktory/client/client_linux.go +++ /dev/null @@ -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 -} diff --git a/vendor/github.com/contribsys/faktory/client/client_windows.go b/vendor/github.com/contribsys/faktory/client/client_windows.go deleted file mode 100644 index 9f657cb..0000000 --- a/vendor/github.com/contribsys/faktory/client/client_windows.go +++ /dev/null @@ -1,6 +0,0 @@ -package client - -func RssKb() int64 { - // TODO Submit a PR? - return 0 -} diff --git a/vendor/github.com/contribsys/faktory/client/faktory.go b/vendor/github.com/contribsys/faktory/client/faktory.go deleted file mode 100644 index 4a502f0..0000000 --- a/vendor/github.com/contribsys/faktory/client/faktory.go +++ /dev/null @@ -1,6 +0,0 @@ -package client - -var ( - Name = "Faktory" - Version = "1.6.2" -) diff --git a/vendor/github.com/contribsys/faktory/client/job.go b/vendor/github.com/contribsys/faktory/client/job.go deleted file mode 100644 index 1c28ad2..0000000 --- a/vendor/github.com/contribsys/faktory/client/job.go +++ /dev/null @@ -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)) -} diff --git a/vendor/github.com/contribsys/faktory/client/mutate.go b/vendor/github.com/contribsys/faktory/client/mutate.go deleted file mode 100644 index cd30135..0000000 --- a/vendor/github.com/contribsys/faktory/client/mutate.go +++ /dev/null @@ -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) -} diff --git a/vendor/github.com/contribsys/faktory/client/package.go b/vendor/github.com/contribsys/faktory/client/package.go deleted file mode 100644 index 7c3db11..0000000 --- a/vendor/github.com/contribsys/faktory/client/package.go +++ /dev/null @@ -1,4 +0,0 @@ -// Code within this package is licensed according to the MPL found -// in the LICENSE file. - -package client diff --git a/vendor/github.com/contribsys/faktory/client/pool.go b/vendor/github.com/contribsys/faktory/client/pool.go deleted file mode 100644 index 5bcf31e..0000000 --- a/vendor/github.com/contribsys/faktory/client/pool.go +++ /dev/null @@ -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) -} diff --git a/vendor/github.com/contribsys/faktory/client/tracking.go b/vendor/github.com/contribsys/faktory/client/tracking.go deleted file mode 100644 index 271cfff..0000000 --- a/vendor/github.com/contribsys/faktory/client/tracking.go +++ /dev/null @@ -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) -} diff --git a/vendor/github.com/contribsys/faktory/internal/pool/pool.go b/vendor/github.com/contribsys/faktory/internal/pool/pool.go deleted file mode 100644 index acb16f8..0000000 --- a/vendor/github.com/contribsys/faktory/internal/pool/pool.go +++ /dev/null @@ -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()) } diff --git a/vendor/github.com/contribsys/faktory/util/logger.go b/vendor/github.com/contribsys/faktory/util/logger.go deleted file mode 100644 index 2cd4b63..0000000 --- a/vendor/github.com/contribsys/faktory/util/logger.go +++ /dev/null @@ -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...)) - } -} diff --git a/vendor/github.com/contribsys/faktory/util/util.go b/vendor/github.com/contribsys/faktory/util/util.go deleted file mode 100644 index 2009a0f..0000000 --- a/vendor/github.com/contribsys/faktory/util/util.go +++ /dev/null @@ -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)) -} diff --git a/vendor/github.com/contribsys/faktory/util/util_bsd.go b/vendor/github.com/contribsys/faktory/util/util_bsd.go deleted file mode 100644 index 1a8ec82..0000000 --- a/vendor/github.com/contribsys/faktory/util/util_bsd.go +++ /dev/null @@ -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. -} diff --git a/vendor/github.com/contribsys/faktory/util/util_linux.go b/vendor/github.com/contribsys/faktory/util/util_linux.go deleted file mode 100644 index a8242db..0000000 --- a/vendor/github.com/contribsys/faktory/util/util_linux.go +++ /dev/null @@ -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), - } -} diff --git a/vendor/github.com/contribsys/faktory/util/util_windows.go b/vendor/github.com/contribsys/faktory/util/util_windows.go deleted file mode 100644 index d495c25..0000000 --- a/vendor/github.com/contribsys/faktory/util/util_windows.go +++ /dev/null @@ -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. -} diff --git a/vendor/github.com/contribsys/faktory_worker_go/.gitignore b/vendor/github.com/contribsys/faktory_worker_go/.gitignore deleted file mode 100644 index 3d875e7..0000000 --- a/vendor/github.com/contribsys/faktory_worker_go/.gitignore +++ /dev/null @@ -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 diff --git a/vendor/github.com/contribsys/faktory_worker_go/.golangci.yml b/vendor/github.com/contribsys/faktory_worker_go/.golangci.yml deleted file mode 100644 index 6915c2f..0000000 --- a/vendor/github.com/contribsys/faktory_worker_go/.golangci.yml +++ /dev/null @@ -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 diff --git a/vendor/github.com/contribsys/faktory_worker_go/Changes.md b/vendor/github.com/contribsys/faktory_worker_go/Changes.md deleted file mode 100644 index 3463bb0..0000000 --- a/vendor/github.com/contribsys/faktory_worker_go/Changes.md +++ /dev/null @@ -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 `, - 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. diff --git a/vendor/github.com/contribsys/faktory_worker_go/LICENSE b/vendor/github.com/contribsys/faktory_worker_go/LICENSE deleted file mode 100644 index a612ad9..0000000 --- a/vendor/github.com/contribsys/faktory_worker_go/LICENSE +++ /dev/null @@ -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. diff --git a/vendor/github.com/contribsys/faktory_worker_go/Makefile b/vendor/github.com/contribsys/faktory_worker_go/Makefile deleted file mode 100644 index be49491..0000000 --- a/vendor/github.com/contribsys/faktory_worker_go/Makefile +++ /dev/null @@ -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 diff --git a/vendor/github.com/contribsys/faktory_worker_go/README.md b/vendor/github.com/contribsys/faktory_worker_go/README.md deleted file mode 100644 index 0705905..0000000 --- a/vendor/github.com/contribsys/faktory_worker_go/README.md +++ /dev/null @@ -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/ diff --git a/vendor/github.com/contribsys/faktory_worker_go/context.go b/vendor/github.com/contribsys/faktory_worker_go/context.go deleted file mode 100644 index daf91e5..0000000 --- a/vendor/github.com/contribsys/faktory_worker_go/context.go +++ /dev/null @@ -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) -} diff --git a/vendor/github.com/contribsys/faktory_worker_go/log.go b/vendor/github.com/contribsys/faktory_worker_go/log.go deleted file mode 100644 index 1591e5b..0000000 --- a/vendor/github.com/contribsys/faktory_worker_go/log.go +++ /dev/null @@ -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...) -} diff --git a/vendor/github.com/contribsys/faktory_worker_go/manager.go b/vendor/github.com/contribsys/faktory_worker_go/manager.go deleted file mode 100644 index 7ba1a20..0000000 --- a/vendor/github.com/contribsys/faktory_worker_go/manager.go +++ /dev/null @@ -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 "" -} diff --git a/vendor/github.com/contribsys/faktory_worker_go/middleware.go b/vendor/github.com/contribsys/faktory_worker_go/middleware.go deleted file mode 100644 index e059d44..0000000 --- a/vendor/github.com/contribsys/faktory_worker_go/middleware.go +++ /dev/null @@ -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) - }) -} diff --git a/vendor/github.com/contribsys/faktory_worker_go/runner.go b/vendor/github.com/contribsys/faktory_worker_go/runner.go deleted file mode 100644 index 9d221af..0000000 --- a/vendor/github.com/contribsys/faktory_worker_go/runner.go +++ /dev/null @@ -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)) -} diff --git a/vendor/github.com/contribsys/faktory_worker_go/runner_unix.go b/vendor/github.com/contribsys/faktory_worker_go/runner_unix.go deleted file mode 100644 index 96c313d..0000000 --- a/vendor/github.com/contribsys/faktory_worker_go/runner_unix.go +++ /dev/null @@ -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 -} diff --git a/vendor/github.com/contribsys/faktory_worker_go/runner_windows.go b/vendor/github.com/contribsys/faktory_worker_go/runner_windows.go deleted file mode 100644 index 93d1437..0000000 --- a/vendor/github.com/contribsys/faktory_worker_go/runner_windows.go +++ /dev/null @@ -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 -} diff --git a/vendor/github.com/contribsys/faktory_worker_go/testing.go b/vendor/github.com/contribsys/faktory_worker_go/testing.go deleted file mode 100644 index 027ed83..0000000 --- a/vendor/github.com/contribsys/faktory_worker_go/testing.go +++ /dev/null @@ -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...) -} diff --git a/vendor/github.com/contribsys/faktory_worker_go/types.go b/vendor/github.com/contribsys/faktory_worker_go/types.go deleted file mode 100644 index 53e6546..0000000 --- a/vendor/github.com/contribsys/faktory_worker_go/types.go +++ /dev/null @@ -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 diff --git a/vendor/github.com/go-co-op/gocron/.gitignore b/vendor/github.com/go-co-op/gocron/.gitignore deleted file mode 100644 index f6409f9..0000000 --- a/vendor/github.com/go-co-op/gocron/.gitignore +++ /dev/null @@ -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 diff --git a/vendor/github.com/go-co-op/gocron/.golangci.yaml b/vendor/github.com/go-co-op/gocron/.golangci.yaml deleted file mode 100644 index 611fb36..0000000 --- a/vendor/github.com/go-co-op/gocron/.golangci.yaml +++ /dev/null @@ -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 diff --git a/vendor/github.com/go-co-op/gocron/CODE_OF_CONDUCT.md b/vendor/github.com/go-co-op/gocron/CODE_OF_CONDUCT.md deleted file mode 100644 index 7d913b5..0000000 --- a/vendor/github.com/go-co-op/gocron/CODE_OF_CONDUCT.md +++ /dev/null @@ -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 diff --git a/vendor/github.com/go-co-op/gocron/CONTRIBUTING.md b/vendor/github.com/go-co-op/gocron/CONTRIBUTING.md deleted file mode 100644 index b2d3be8..0000000 --- a/vendor/github.com/go-co-op/gocron/CONTRIBUTING.md +++ /dev/null @@ -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. diff --git a/vendor/github.com/go-co-op/gocron/LICENSE b/vendor/github.com/go-co-op/gocron/LICENSE deleted file mode 100644 index 3357d57..0000000 --- a/vendor/github.com/go-co-op/gocron/LICENSE +++ /dev/null @@ -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. diff --git a/vendor/github.com/go-co-op/gocron/Makefile b/vendor/github.com/go-co-op/gocron/Makefile deleted file mode 100644 index 81a8a69..0000000 --- a/vendor/github.com/go-co-op/gocron/Makefile +++ /dev/null @@ -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) diff --git a/vendor/github.com/go-co-op/gocron/README.md b/vendor/github.com/go-co-op/gocron/README.md deleted file mode 100644 index 7805fc0..0000000 --- a/vendor/github.com/go-co-op/gocron/README.md +++ /dev/null @@ -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! [](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! diff --git a/vendor/github.com/go-co-op/gocron/SECURITY.md b/vendor/github.com/go-co-op/gocron/SECURITY.md deleted file mode 100644 index 6b98641..0000000 --- a/vendor/github.com/go-co-op/gocron/SECURITY.md +++ /dev/null @@ -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: [](https://gophers.slack.com/archives/CQ7T0T1FW) - -We will do our best to addrerss any vulnerabilities in an expeditious manner. diff --git a/vendor/github.com/go-co-op/gocron/executor.go b/vendor/github.com/go-co-op/gocron/executor.go deleted file mode 100644 index f4e27c7..0000000 --- a/vendor/github.com/go-co-op/gocron/executor.go +++ /dev/null @@ -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 -} diff --git a/vendor/github.com/go-co-op/gocron/gocron.go b/vendor/github.com/go-co-op/gocron/gocron.go deleted file mode 100644 index 5a9afc4..0000000 --- a/vendor/github.com/go-co-op/gocron/gocron.go +++ /dev/null @@ -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 -} diff --git a/vendor/github.com/go-co-op/gocron/job.go b/vendor/github.com/go-co-op/gocron/job.go deleted file mode 100644 index 136be1e..0000000 --- a/vendor/github.com/go-co-op/gocron/job.go +++ /dev/null @@ -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, - } -} diff --git a/vendor/github.com/go-co-op/gocron/scheduler.go b/vendor/github.com/go-co-op/gocron/scheduler.go deleted file mode 100644 index 508f432..0000000 --- a/vendor/github.com/go-co-op/gocron/scheduler.go +++ /dev/null @@ -1,1337 +0,0 @@ -package gocron - -import ( - "context" - "fmt" - "reflect" - "sort" - "strings" - "sync" - "time" - - "github.com/robfig/cron/v3" - "golang.org/x/sync/semaphore" -) - -type limitMode int8 - -// Scheduler struct stores a list of Jobs and the location of time used by the Scheduler, -// and implements the sort.Interface{} for sorting Jobs, by the time of nextRun -type Scheduler struct { - jobsMutex sync.RWMutex - jobs []*Job - - locationMutex sync.RWMutex - location *time.Location - runningMutex sync.RWMutex - running bool // represents if the scheduler is running at the moment or not - - time TimeWrapper // wrapper around time.Time - timer func(d time.Duration, f func()) *time.Timer - executor *executor // executes jobs passed via chan - - tags sync.Map // for storing tags when unique tags is set - - tagsUnique bool // defines whether tags should be unique - updateJob bool // so the scheduler knows to create a new job or update the current - waitForInterval bool // defaults jobs to waiting for first interval to start - singletonMode bool // defaults all jobs to use SingletonMode() - jobCreated bool // so the scheduler knows a job was created prior to calling Every or Cron - - startBlockingStopChanMutex sync.Mutex - startBlockingStopChan chan struct{} // stops the scheduler -} - -// days in a week -const allWeekDays = 7 - -// NewScheduler creates a new Scheduler -func NewScheduler(loc *time.Location) *Scheduler { - executor := newExecutor() - - return &Scheduler{ - jobs: make([]*Job, 0), - location: loc, - running: false, - time: &trueTime{}, - executor: &executor, - tagsUnique: false, - timer: afterFunc, - } -} - -// SetMaxConcurrentJobs limits how many jobs can be running at the same time. -// This is useful when running resource intensive jobs and a precise start time is not critical. -func (s *Scheduler) SetMaxConcurrentJobs(n int, mode limitMode) { - s.executor.maxRunningJobs = semaphore.NewWeighted(int64(n)) - s.executor.limitMode = mode -} - -// StartBlocking starts all jobs and blocks the current thread. -// This blocking method can be stopped with Stop() from a separate goroutine. -func (s *Scheduler) StartBlocking() { - s.StartAsync() - s.startBlockingStopChanMutex.Lock() - s.startBlockingStopChan = make(chan struct{}, 1) - s.startBlockingStopChanMutex.Unlock() - <-s.startBlockingStopChan -} - -// StartAsync starts all jobs without blocking the current thread -func (s *Scheduler) StartAsync() { - if !s.IsRunning() { - s.start() - } -} - -// start starts the scheduler, scheduling and running jobs -func (s *Scheduler) start() { - go s.executor.start() - s.setRunning(true) - s.runJobs(s.Jobs()) -} - -func (s *Scheduler) runJobs(jobs []*Job) { - for _, job := range jobs { - s.runContinuous(job) - } -} - -func (s *Scheduler) setRunning(b bool) { - s.runningMutex.Lock() - defer s.runningMutex.Unlock() - s.running = b -} - -// IsRunning returns true if the scheduler is running -func (s *Scheduler) IsRunning() bool { - s.runningMutex.RLock() - defer s.runningMutex.RUnlock() - return s.running -} - -// Jobs returns the list of Jobs from the Scheduler -func (s *Scheduler) Jobs() []*Job { - s.jobsMutex.RLock() - defer s.jobsMutex.RUnlock() - return s.jobs -} - -func (s *Scheduler) setJobs(jobs []*Job) { - s.jobsMutex.Lock() - defer s.jobsMutex.Unlock() - s.jobs = jobs -} - -// Len returns the number of Jobs in the Scheduler - implemented for sort -func (s *Scheduler) Len() int { - s.jobsMutex.RLock() - defer s.jobsMutex.RUnlock() - return len(s.jobs) -} - -// Swap places each job into the other job's position given -// the provided job indexes. -func (s *Scheduler) Swap(i, j int) { - s.jobsMutex.Lock() - defer s.jobsMutex.Unlock() - s.jobs[i], s.jobs[j] = s.jobs[j], s.jobs[i] -} - -// Less compares the next run of jobs based on their index. -// Returns true if the second job is after the first. -func (s *Scheduler) Less(first, second int) bool { - return s.Jobs()[second].NextRun().Unix() >= s.Jobs()[first].NextRun().Unix() -} - -// ChangeLocation changes the default time location -func (s *Scheduler) ChangeLocation(newLocation *time.Location) { - s.locationMutex.Lock() - defer s.locationMutex.Unlock() - s.location = newLocation -} - -// Location provides the current location set on the scheduler -func (s *Scheduler) Location() *time.Location { - s.locationMutex.RLock() - defer s.locationMutex.RUnlock() - return s.location -} - -type nextRun struct { - duration time.Duration - dateTime time.Time -} - -// scheduleNextRun Compute the instant when this Job should run next -func (s *Scheduler) scheduleNextRun(job *Job) (bool, nextRun) { - now := s.now() - if !s.jobPresent(job) { - return false, nextRun{} - } - - lastRun := now - - if job.neverRan() { - // Increment startAtTime to the future - if !job.startAtTime.IsZero() && job.startAtTime.Before(now) { - duration := s.durationToNextRun(job.startAtTime, job).duration - job.startAtTime = job.startAtTime.Add(duration) - if job.startAtTime.Before(now) { - diff := now.Sub(job.startAtTime) - duration := s.durationToNextRun(job.startAtTime, job).duration - count := diff / duration - if diff%duration != 0 { - count++ - } - job.startAtTime = job.startAtTime.Add(duration * count) - } - } - } else { - lastRun = job.LastRun() - } - - if !job.shouldRun() { - s.RemoveByReference(job) - return false, nextRun{} - } - - next := s.durationToNextRun(lastRun, job) - - job.setLastRun(job.NextRun()) - if next.dateTime.IsZero() { - next.dateTime = lastRun.Add(next.duration) - job.setNextRun(next.dateTime) - } else { - job.setNextRun(next.dateTime) - } - return true, next -} - -// durationToNextRun calculate how much time to the next run, depending on unit -func (s *Scheduler) durationToNextRun(lastRun time.Time, job *Job) nextRun { - // job can be scheduled with .StartAt() - if job.getStartAtTime().After(lastRun) { - return nextRun{duration: job.getStartAtTime().Sub(s.now()), dateTime: job.getStartAtTime()} - } - - var next nextRun - switch job.getUnit() { - case milliseconds, seconds, minutes, hours: - next.duration = s.calculateDuration(job) - case days: - next = s.calculateDays(job, lastRun) - case weeks: - if len(job.scheduledWeekdays) != 0 { // weekday selected, Every().Monday(), for example - next = s.calculateWeekday(job, lastRun) - } else { - next = s.calculateWeeks(job, lastRun) - } - case months: - next = s.calculateMonths(job, lastRun) - case duration: - next.duration = job.getDuration() - case crontab: - next.dateTime = job.cronSchedule.Next(lastRun) - next.duration = next.dateTime.Sub(lastRun) - } - return next -} - -func (s *Scheduler) calculateMonths(job *Job, lastRun time.Time) nextRun { - lastRunRoundedMidnight := s.roundToMidnight(lastRun) - - // Special case: the last day of the month - if len(job.daysOfTheMonth) == 1 && job.daysOfTheMonth[0] == -1 { - return calculateNextRunForLastDayOfMonth(s, job, lastRun) - } - - if len(job.daysOfTheMonth) != 0 { // calculate days to job.daysOfTheMonth - - nextRunDateMap := make(map[int]nextRun) - for _, day := range job.daysOfTheMonth { - nextRunDateMap[day] = calculateNextRunForMonth(s, job, lastRun, day) - } - - nextRunResult := nextRun{} - for _, val := range nextRunDateMap { - if nextRunResult.dateTime.IsZero() { - nextRunResult = val - } else if nextRunResult.dateTime.Sub(val.dateTime).Milliseconds() > 0 { - nextRunResult = val - } - } - - return nextRunResult - } - next := lastRunRoundedMidnight.Add(job.getFirstAtTime()).AddDate(0, job.getInterval(), 0) - return nextRun{duration: until(lastRun, next), dateTime: next} -} - -func calculateNextRunForLastDayOfMonth(s *Scheduler, job *Job, lastRun time.Time) nextRun { - // Calculate the last day of the next month, by adding job.interval+1 months (i.e. the - // first day of the month after the next month), and subtracting one day, unless the - // last run occurred before the end of the month. - addMonth := job.getInterval() - atTime := job.getAtTime(lastRun) - if testDate := lastRun.AddDate(0, 0, 1); testDate.Month() != lastRun.Month() && - !s.roundToMidnight(lastRun).Add(atTime).After(lastRun) { - // Our last run was on the last day of this month. - addMonth++ - atTime = job.getFirstAtTime() - } - - next := time.Date(lastRun.Year(), lastRun.Month(), 1, 0, 0, 0, 0, s.Location()). - Add(atTime). - AddDate(0, addMonth, 0). - AddDate(0, 0, -1) - return nextRun{duration: until(lastRun, next), dateTime: next} -} - -func calculateNextRunForMonth(s *Scheduler, job *Job, lastRun time.Time, dayOfMonth int) nextRun { - atTime := job.getAtTime(lastRun) - natTime := atTime - jobDay := time.Date(lastRun.Year(), lastRun.Month(), dayOfMonth, 0, 0, 0, 0, s.Location()).Add(atTime) - difference := absDuration(lastRun.Sub(jobDay)) - next := lastRun - if jobDay.Before(lastRun) { // shouldn't run this month; schedule for next interval minus day difference - next = next.AddDate(0, job.getInterval(), -0) - next = next.Add(-difference) - natTime = job.getFirstAtTime() - } else { - if job.getInterval() == 1 && !jobDay.Equal(lastRun) { // every month counts current month - next = next.AddDate(0, job.getInterval()-1, 0) - } else { // should run next month interval - next = next.AddDate(0, job.getInterval(), 0) - natTime = job.getFirstAtTime() - } - next = next.Add(difference) - } - if atTime != natTime { - next = next.Add(-atTime).Add(natTime) - } - return nextRun{duration: until(lastRun, next), dateTime: next} -} - -func (s *Scheduler) calculateWeekday(job *Job, lastRun time.Time) nextRun { - daysToWeekday := s.remainingDaysToWeekday(lastRun, job) - totalDaysDifference := s.calculateTotalDaysDifference(lastRun, daysToWeekday, job) - acTime := job.getAtTime(lastRun) - if totalDaysDifference > 0 { - acTime = job.getFirstAtTime() - } - next := s.roundToMidnight(lastRun).Add(acTime).AddDate(0, 0, totalDaysDifference) - return nextRun{duration: until(lastRun, next), dateTime: next} -} - -func (s *Scheduler) calculateWeeks(job *Job, lastRun time.Time) nextRun { - totalDaysDifference := int(job.getInterval()) * 7 - next := s.roundToMidnight(lastRun).Add(job.getFirstAtTime()).AddDate(0, 0, totalDaysDifference) - return nextRun{duration: until(lastRun, next), dateTime: next} -} - -func (s *Scheduler) calculateTotalDaysDifference(lastRun time.Time, daysToWeekday int, job *Job) int { - if job.getInterval() > 1 { - // just count weeks after the first jobs were done - if job.RunCount() < len(job.Weekdays()) { - return daysToWeekday - } - if daysToWeekday > 0 { - return int(job.getInterval())*7 - (allWeekDays - daysToWeekday) - } - return int(job.getInterval()) * 7 - } - - if daysToWeekday == 0 { // today, at future time or already passed - lastRunAtTime := time.Date(lastRun.Year(), lastRun.Month(), lastRun.Day(), 0, 0, 0, 0, s.Location()).Add(job.getAtTime(lastRun)) - if lastRun.Before(lastRunAtTime) { - return 0 - } - return 7 - } - return daysToWeekday -} - -func (s *Scheduler) calculateDays(job *Job, lastRun time.Time) nextRun { - if job.getInterval() == 1 { - lastRunDayPlusJobAtTime := s.roundToMidnight(lastRun).Add(job.getAtTime(lastRun)) - - if shouldRunToday(lastRun, lastRunDayPlusJobAtTime) { - return nextRun{duration: until(lastRun, lastRunDayPlusJobAtTime), dateTime: lastRunDayPlusJobAtTime} - } - } - - nextRunAtTime := s.roundToMidnight(lastRun).Add(job.getFirstAtTime()).AddDate(0, 0, job.getInterval()).In(s.Location()) - return nextRun{duration: until(lastRun, nextRunAtTime), dateTime: nextRunAtTime} -} - -func until(from time.Time, until time.Time) time.Duration { - return until.Sub(from) -} - -func shouldRunToday(lastRun time.Time, atTime time.Time) bool { - return lastRun.Before(atTime) -} - -func in(scheduleWeekdays []time.Weekday, weekday time.Weekday) bool { - in := false - - for _, weekdayInSchedule := range scheduleWeekdays { - if int(weekdayInSchedule) == int(weekday) { - in = true - break - } - } - return in -} - -func (s *Scheduler) calculateDuration(job *Job) time.Duration { - if job.neverRan() && shouldRunAtSpecificTime(job) { // ugly. in order to avoid this we could prohibit setting .At() and allowing only .StartAt() when dealing with Duration types - now := s.time.Now(s.location) - next := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, s.Location()).Add(job.getFirstAtTime()) - if now.Before(next) || now.Equal(next) { - return next.Sub(now) - } - } - - interval := job.getInterval() - switch job.getUnit() { - case milliseconds: - return time.Duration(interval) * time.Millisecond - case seconds: - return time.Duration(interval) * time.Second - case minutes: - return time.Duration(interval) * time.Minute - default: - return time.Duration(interval) * time.Hour - } -} - -func shouldRunAtSpecificTime(job *Job) bool { - jobLastRun := job.LastRun() - return job.getAtTime(jobLastRun) != 0 -} - -func (s *Scheduler) remainingDaysToWeekday(lastRun time.Time, job *Job) int { - weekDays := job.Weekdays() - sort.Slice(weekDays, func(i, j int) bool { - return weekDays[i] < weekDays[j] - }) - - equals := false - lastRunWeekday := lastRun.Weekday() - index := sort.Search(len(weekDays), func(i int) bool { - b := weekDays[i] >= lastRunWeekday - if b { - equals = weekDays[i] == lastRunWeekday - } - return b - }) - // check atTime - if equals { - if s.roundToMidnight(lastRun).Add(job.getAtTime(lastRun)).After(lastRun) { - return 0 - } - index++ - } - - if index < len(weekDays) { - return int(weekDays[index] - lastRunWeekday) - } - - return int(weekDays[0]) + allWeekDays - int(lastRunWeekday) -} - -// absDuration returns the abs time difference -func absDuration(a time.Duration) time.Duration { - if a >= 0 { - return a - } - return -a -} - -// roundToMidnight truncates time to midnight -func (s *Scheduler) roundToMidnight(t time.Time) time.Time { - return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, s.Location()) -} - -// NextRun datetime when the next Job should run. -func (s *Scheduler) NextRun() (*Job, time.Time) { - if len(s.Jobs()) <= 0 { - return nil, s.now() - } - - sort.Sort(s) - - return s.Jobs()[0], s.Jobs()[0].NextRun() -} - -// EveryRandom schedules a new period Job that runs at random intervals -// between the provided lower (inclusive) and upper (inclusive) bounds. -// The default unit is Seconds(). Call a different unit in the chain -// if you would like to change that. For example, Minutes(), Hours(), etc. -func (s *Scheduler) EveryRandom(lower, upper int) *Scheduler { - job := s.newJob(0) - if s.updateJob || s.jobCreated { - job = s.getCurrentJob() - } - - job.setRandomInterval(lower, upper) - - if s.updateJob || s.jobCreated { - s.setJobs(append(s.Jobs()[:len(s.Jobs())-1], job)) - if s.jobCreated { - s.jobCreated = false - } - } else { - s.setJobs(append(s.Jobs(), job)) - } - - return s -} - -// Every schedules a new periodic Job with an interval. -// Interval can be an int, time.Duration or a string that -// parses with time.ParseDuration(). -// Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". -func (s *Scheduler) Every(interval interface{}) *Scheduler { - job := s.newJob(0) - if s.updateJob || s.jobCreated { - job = s.getCurrentJob() - } - - switch interval := interval.(type) { - case int: - job.interval = interval - if interval <= 0 { - job.error = wrapOrError(job.error, ErrInvalidInterval) - } - case time.Duration: - job.interval = 0 - job.setDuration(interval) - job.setUnit(duration) - case string: - d, err := time.ParseDuration(interval) - if err != nil { - job.error = wrapOrError(job.error, err) - } - job.setDuration(d) - job.setUnit(duration) - default: - job.error = wrapOrError(job.error, ErrInvalidIntervalType) - } - - if s.updateJob || s.jobCreated { - s.setJobs(append(s.Jobs()[:len(s.Jobs())-1], job)) - if s.jobCreated { - s.jobCreated = false - } - } else { - s.setJobs(append(s.Jobs(), job)) - } - - return s -} - -func (s *Scheduler) run(job *Job) { - if !s.IsRunning() { - return - } - - job.mu.Lock() - - if job.function == nil { - job.mu.Unlock() - s.Remove(job) - return - } - - defer job.mu.Unlock() - - if job.runWithDetails { - switch len(job.parameters) { - case job.parametersLen: - job.parameters = append(job.parameters, job.copy()) - case job.parametersLen + 1: - job.parameters[job.parametersLen] = job.copy() - default: - // something is really wrong and we should never get here - job.error = wrapOrError(job.error, ErrInvalidFunctionParameters) - return - } - } - - s.executor.jobFunctions <- job.jobFunction.copy() - job.runCount++ -} - -func (s *Scheduler) runContinuous(job *Job) { - shouldRun, next := s.scheduleNextRun(job) - if !shouldRun { - return - } - - if !job.getStartsImmediately() { - job.setStartsImmediately(true) - } else { - s.run(job) - } - - nextRun := next.dateTime.Sub(s.now()) - if nextRun < 0 { - time.Sleep(absDuration(nextRun)) - shouldRun, next := s.scheduleNextRun(job) - if !shouldRun { - return - } - nextRun = next.dateTime.Sub(s.now()) - } - - job.setTimer(s.timer(nextRun, func() { - if !next.dateTime.IsZero() { - for { - n := s.now().UnixNano() - next.dateTime.UnixNano() - if n >= 0 { - break - } - s.time.Sleep(time.Duration(n)) - } - } - s.runContinuous(job) - })) -} - -// RunAll run all Jobs regardless if they are scheduled to run or not -func (s *Scheduler) RunAll() { - s.RunAllWithDelay(0) -} - -// RunAllWithDelay runs all jobs with the provided delay in between each job -func (s *Scheduler) RunAllWithDelay(d time.Duration) { - for _, job := range s.Jobs() { - s.run(job) - s.time.Sleep(d) - } -} - -// RunByTag runs all the jobs containing a specific tag -// regardless of whether they are scheduled to run or not -func (s *Scheduler) RunByTag(tag string) error { - return s.RunByTagWithDelay(tag, 0) -} - -// RunByTagWithDelay is same as RunByTag but introduces a delay between -// each job execution -func (s *Scheduler) RunByTagWithDelay(tag string, d time.Duration) error { - jobs, err := s.FindJobsByTag(tag) - if err != nil { - return err - } - for _, job := range jobs { - s.run(job) - s.time.Sleep(d) - } - return nil -} - -// Remove specific Job by function -// -// Removing a job stops that job's timer. However, if a job has already -// been started by by the job's timer before being removed, there is no way to stop -// it through gocron as https://pkg.go.dev/time#Timer.Stop explains. -// The job function would need to have implemented a means of -// stopping, e.g. using a context.WithCancel(). -func (s *Scheduler) Remove(job interface{}) { - fName := getFunctionName(job) - j := s.findJobByTaskName(fName) - s.removeJobsUniqueTags(j) - s.removeByCondition(func(someJob *Job) bool { - return someJob.name == fName - }) -} - -// RemoveByReference removes specific Job by reference -func (s *Scheduler) RemoveByReference(job *Job) { - s.removeJobsUniqueTags(job) - s.removeByCondition(func(someJob *Job) bool { - job.mu.RLock() - defer job.mu.RUnlock() - return someJob == job - }) -} - -func (s *Scheduler) findJobByTaskName(name string) *Job { - for _, job := range s.Jobs() { - if job.name == name { - return job - } - } - return nil -} - -func (s *Scheduler) removeJobsUniqueTags(job *Job) { - if job == nil { - return - } - if s.tagsUnique && len(job.tags) > 0 { - for _, tag := range job.tags { - s.tags.Delete(tag) - } - } -} - -func (s *Scheduler) removeByCondition(shouldRemove func(*Job) bool) { - retainedJobs := make([]*Job, 0) - for _, job := range s.Jobs() { - if !shouldRemove(job) { - retainedJobs = append(retainedJobs, job) - } else { - job.stop() - } - } - s.setJobs(retainedJobs) -} - -// RemoveByTag will remove Jobs that match the given tag. -func (s *Scheduler) RemoveByTag(tag string) error { - return s.RemoveByTags(tag) -} - -// RemoveByTags will remove Jobs that match all given tags. -func (s *Scheduler) RemoveByTags(tags ...string) error { - jobs, err := s.FindJobsByTag(tags...) - if err != nil { - return err - } - - for _, job := range jobs { - s.RemoveByReference(job) - } - return nil -} - -// RemoveByTagsAny will remove Jobs that match any one of the given tags. -func (s *Scheduler) RemoveByTagsAny(tags ...string) error { - var errs error - mJob := make(map[*Job]struct{}) - for _, tag := range tags { - jobs, err := s.FindJobsByTag(tag) - if err != nil { - errs = wrapOrError(errs, fmt.Errorf("%s: %s", err.Error(), tag)) - } - for _, job := range jobs { - mJob[job] = struct{}{} - } - } - - for job := range mJob { - s.RemoveByReference(job) - } - - return errs -} - -// FindJobsByTag will return a slice of Jobs that match all given tags -func (s *Scheduler) FindJobsByTag(tags ...string) ([]*Job, error) { - var jobs []*Job - -Jobs: - for _, job := range s.Jobs() { - if job.hasTags(tags...) { - jobs = append(jobs, job) - continue Jobs - } - } - - if len(jobs) > 0 { - return jobs, nil - } - return nil, ErrJobNotFoundWithTag -} - -// MonthFirstWeekday sets the job to run the first specified weekday of the month -func (s *Scheduler) MonthFirstWeekday(weekday time.Weekday) *Scheduler { - _, month, day := s.time.Now(time.UTC).Date() - - if day < 7 { - return s.Cron(fmt.Sprintf("0 0 %d %d %d", day, month, weekday)) - } - - return s.Cron(fmt.Sprintf("0 0 %d %d %d", day, month+1, weekday)) -} - -// LimitRunsTo limits the number of executions of this job to n. -// Upon reaching the limit, the job is removed from the scheduler. -func (s *Scheduler) LimitRunsTo(i int) *Scheduler { - job := s.getCurrentJob() - job.LimitRunsTo(i) - return s -} - -// SingletonMode prevents a new job from starting if the prior job has not yet -// completed its run -func (s *Scheduler) SingletonMode() *Scheduler { - job := s.getCurrentJob() - job.SingletonMode() - return s -} - -// SingletonModeAll prevents new jobs from starting if the prior instance of the -// particular job has not yet completed its run -func (s *Scheduler) SingletonModeAll() { - s.singletonMode = true -} - -// TaskPresent checks if specific job's function was added to the scheduler. -func (s *Scheduler) TaskPresent(j interface{}) bool { - for _, job := range s.Jobs() { - if job.name == getFunctionName(j) { - return true - } - } - return false -} - -// To avoid the recursive read lock on s.Jobs() and this function, -// creating this new function and distributing the lock between jobPresent, _jobPresent -func (s *Scheduler) _jobPresent(j *Job, jobs []*Job) bool { - s.jobsMutex.RLock() - defer s.jobsMutex.RUnlock() - for _, job := range jobs { - if job == j { - return true - } - } - return false -} - -func (s *Scheduler) jobPresent(j *Job) bool { - return s._jobPresent(j, s.Jobs()) -} - -// Clear clears all Jobs from this scheduler -func (s *Scheduler) Clear() { - for _, job := range s.Jobs() { - job.stop() - } - s.setJobs(make([]*Job, 0)) - // If unique tags was enabled, delete all the tags loaded in the tags sync.Map - if s.tagsUnique { - s.tags.Range(func(key interface{}, value interface{}) bool { - s.tags.Delete(key) - return true - }) - } -} - -// Stop stops the scheduler. This is a no-op if the scheduler is already stopped. -// It waits for all running jobs to finish before returning, so it is safe to assume that running jobs will finish when calling this. -func (s *Scheduler) Stop() { - if s.IsRunning() { - s.stop() - } -} - -func (s *Scheduler) stop() { - s.setRunning(false) - s.stopJobs(s.jobs) - s.executor.stop() - s.StopBlockingChan() -} - -func (s *Scheduler) stopJobs(jobs []*Job) { - for _, job := range jobs { - job.stop() - } -} - -func (s *Scheduler) doCommon(jobFun interface{}, params ...interface{}) (*Job, error) { - job := s.getCurrentJob() - - jobUnit := job.getUnit() - jobLastRun := job.LastRun() - if job.getAtTime(jobLastRun) != 0 && (jobUnit <= hours || jobUnit >= duration) { - job.error = wrapOrError(job.error, ErrAtTimeNotSupported) - } - - if len(job.scheduledWeekdays) != 0 && jobUnit != weeks { - job.error = wrapOrError(job.error, ErrWeekdayNotSupported) - } - - if job.unit != crontab && job.getInterval() == 0 { - if job.unit != duration { - job.error = wrapOrError(job.error, ErrInvalidInterval) - } - } - - if job.error != nil { - // delete the job from the scheduler as this job - // cannot be executed - s.RemoveByReference(job) - return nil, job.error - } - - typ := reflect.TypeOf(jobFun) - if typ.Kind() != reflect.Func { - // delete the job for the same reason as above - s.RemoveByReference(job) - return nil, ErrNotAFunction - } - - fname := getFunctionName(jobFun) - if job.name != fname { - job.function = jobFun - job.parameters = params - job.name = fname - } - - f := reflect.ValueOf(jobFun) - expectedParamLength := f.Type().NumIn() - if job.runWithDetails { - expectedParamLength-- - } - - if len(params) != expectedParamLength { - s.RemoveByReference(job) - job.error = wrapOrError(job.error, ErrWrongParams) - return nil, job.error - } - - if job.runWithDetails && f.Type().In(len(params)).Kind() != reflect.ValueOf(*job).Kind() { - s.RemoveByReference(job) - job.error = wrapOrError(job.error, ErrDoWithJobDetails) - return nil, job.error - } - - // we should not schedule if not running since we can't foresee how long it will take for the scheduler to start - if s.IsRunning() { - s.runContinuous(job) - } - - return job, nil -} - -// Do specifies the jobFunc that should be called every time the Job runs -func (s *Scheduler) Do(jobFun interface{}, params ...interface{}) (*Job, error) { - return s.doCommon(jobFun, params...) -} - -// DoWithJobDetails specifies the jobFunc that should be called every time the Job runs -// and additionally passes the details of the current job to the jobFunc. -// The last argument of the function must be a gocron.Job that will be passed by -// the scheduler when the function is called. -func (s *Scheduler) DoWithJobDetails(jobFun interface{}, params ...interface{}) (*Job, error) { - job := s.getCurrentJob() - job.runWithDetails = true - job.parametersLen = len(params) - return s.doCommon(jobFun, params...) -} - -// At schedules the Job at a specific time of day in the form "HH:MM:SS" or "HH:MM" -// or time.Time (note that only the hours, minutes, seconds and nanos are used). -func (s *Scheduler) At(i interface{}) *Scheduler { - job := s.getCurrentJob() - - switch t := i.(type) { - case string: - for _, tt := range strings.Split(t, ";") { - hour, min, sec, err := parseTime(tt) - if err != nil { - job.error = wrapOrError(job.error, err) - return s - } - // save atTime start as duration from midnight - job.addAtTime(time.Duration(hour)*time.Hour + time.Duration(min)*time.Minute + time.Duration(sec)*time.Second) - } - case time.Time: - job.addAtTime(time.Duration(t.Hour())*time.Hour + time.Duration(t.Minute())*time.Minute + time.Duration(t.Second())*time.Second + time.Duration(t.Nanosecond())*time.Nanosecond) - default: - job.error = wrapOrError(job.error, ErrUnsupportedTimeFormat) - } - job.startsImmediately = false - return s -} - -// Tag will add a tag when creating a job. -func (s *Scheduler) Tag(t ...string) *Scheduler { - job := s.getCurrentJob() - - if s.tagsUnique { - for _, tag := range t { - if _, ok := s.tags.Load(tag); ok { - job.error = wrapOrError(job.error, ErrTagsUnique(tag)) - return s - } - s.tags.Store(tag, struct{}{}) - } - } - - job.tags = append(job.tags, t...) - return s -} - -// StartAt schedules the next run of the Job. If this time is in the past, the configured interval will be used -// to calculate the next future time -func (s *Scheduler) StartAt(t time.Time) *Scheduler { - job := s.getCurrentJob() - job.setStartAtTime(t) - job.startsImmediately = false - return s -} - -// setUnit sets the unit type -func (s *Scheduler) setUnit(unit schedulingUnit) { - job := s.getCurrentJob() - currentUnit := job.getUnit() - if currentUnit == duration || currentUnit == crontab { - job.error = wrapOrError(job.error, ErrInvalidIntervalUnitsSelection) - return - } - job.setUnit(unit) -} - -// Millisecond sets the unit with seconds -func (s *Scheduler) Millisecond() *Scheduler { - return s.Milliseconds() -} - -// Milliseconds sets the unit with seconds -func (s *Scheduler) Milliseconds() *Scheduler { - s.setUnit(milliseconds) - return s -} - -// Second sets the unit with seconds -func (s *Scheduler) Second() *Scheduler { - return s.Seconds() -} - -// Seconds sets the unit with seconds -func (s *Scheduler) Seconds() *Scheduler { - s.setUnit(seconds) - return s -} - -// Minute sets the unit with minutes -func (s *Scheduler) Minute() *Scheduler { - return s.Minutes() -} - -// Minutes sets the unit with minutes -func (s *Scheduler) Minutes() *Scheduler { - s.setUnit(minutes) - return s -} - -// Hour sets the unit with hours -func (s *Scheduler) Hour() *Scheduler { - return s.Hours() -} - -// Hours sets the unit with hours -func (s *Scheduler) Hours() *Scheduler { - s.setUnit(hours) - return s -} - -// Day sets the unit with days -func (s *Scheduler) Day() *Scheduler { - s.setUnit(days) - return s -} - -// Days set the unit with days -func (s *Scheduler) Days() *Scheduler { - s.setUnit(days) - return s -} - -// Week sets the unit with weeks -func (s *Scheduler) Week() *Scheduler { - s.setUnit(weeks) - return s -} - -// Weeks sets the unit with weeks -func (s *Scheduler) Weeks() *Scheduler { - s.setUnit(weeks) - return s -} - -// Month sets the unit with months -func (s *Scheduler) Month(daysOfMonth ...int) *Scheduler { - return s.Months(daysOfMonth...) -} - -// MonthLastDay sets the unit with months at every last day of the month -func (s *Scheduler) MonthLastDay() *Scheduler { - return s.Months(-1) -} - -// Months sets the unit with months -// Note: Only days 1 through 28 are allowed for monthly schedules -// Note: Multiple add same days of month cannot be allowed -// Note: -1 is a special value and can only occur as single argument -func (s *Scheduler) Months(daysOfTheMonth ...int) *Scheduler { - job := s.getCurrentJob() - - if len(daysOfTheMonth) == 0 { - job.error = wrapOrError(job.error, ErrInvalidDayOfMonthEntry) - } else if len(daysOfTheMonth) == 1 { - dayOfMonth := daysOfTheMonth[0] - if dayOfMonth != -1 && (dayOfMonth < 1 || dayOfMonth > 28) { - job.error = wrapOrError(job.error, ErrInvalidDayOfMonthEntry) - } - } else { - - repeatMap := make(map[int]int) - for _, dayOfMonth := range daysOfTheMonth { - - if dayOfMonth < 1 || dayOfMonth > 28 { - job.error = wrapOrError(job.error, ErrInvalidDayOfMonthEntry) - break - } - - for _, dayOfMonthInJob := range job.daysOfTheMonth { - if dayOfMonthInJob == dayOfMonth { - job.error = wrapOrError(job.error, ErrInvalidDaysOfMonthDuplicateValue) - break - } - } - - if _, ok := repeatMap[dayOfMonth]; ok { - job.error = wrapOrError(job.error, ErrInvalidDaysOfMonthDuplicateValue) - break - } else { - repeatMap[dayOfMonth]++ - } - } - } - if job.daysOfTheMonth == nil { - job.daysOfTheMonth = make([]int, 0) - } - job.daysOfTheMonth = append(job.daysOfTheMonth, daysOfTheMonth...) - job.startsImmediately = false - s.setUnit(months) - return s -} - -// NOTE: If the dayOfTheMonth for the above two functions is -// more than the number of days in that month, the extra day(s) -// spill over to the next month. Similarly, if it's less than 0, -// it will go back to the month before - -// Weekday sets the scheduledWeekdays with a specifics weekdays -func (s *Scheduler) Weekday(weekDay time.Weekday) *Scheduler { - job := s.getCurrentJob() - - if in := in(job.scheduledWeekdays, weekDay); !in { - job.scheduledWeekdays = append(job.scheduledWeekdays, weekDay) - } - - job.startsImmediately = false - s.setUnit(weeks) - return s -} - -func (s *Scheduler) Midday() *Scheduler { - return s.At("12:00") -} - -// Monday sets the start day as Monday -func (s *Scheduler) Monday() *Scheduler { - return s.Weekday(time.Monday) -} - -// Tuesday sets the start day as Tuesday -func (s *Scheduler) Tuesday() *Scheduler { - return s.Weekday(time.Tuesday) -} - -// Wednesday sets the start day as Wednesday -func (s *Scheduler) Wednesday() *Scheduler { - return s.Weekday(time.Wednesday) -} - -// Thursday sets the start day as Thursday -func (s *Scheduler) Thursday() *Scheduler { - return s.Weekday(time.Thursday) -} - -// Friday sets the start day as Friday -func (s *Scheduler) Friday() *Scheduler { - return s.Weekday(time.Friday) -} - -// Saturday sets the start day as Saturday -func (s *Scheduler) Saturday() *Scheduler { - return s.Weekday(time.Saturday) -} - -// Sunday sets the start day as Sunday -func (s *Scheduler) Sunday() *Scheduler { - return s.Weekday(time.Sunday) -} - -func (s *Scheduler) getCurrentJob() *Job { - if len(s.Jobs()) == 0 { - s.setJobs([]*Job{s.newJob(0)}) - s.jobCreated = true - } - return s.Jobs()[len(s.Jobs())-1] -} - -func (s *Scheduler) now() time.Time { - return s.time.Now(s.Location()) -} - -// TagsUnique forces job tags to be unique across the scheduler -// when adding tags with (s *Scheduler) Tag(). -// This does not enforce uniqueness on tags added via -// (j *Job) Tag() -func (s *Scheduler) TagsUnique() { - s.tagsUnique = true -} - -// Job puts the provided job in focus for the purpose -// of making changes to the job with the scheduler chain -// and finalized by calling Update() -func (s *Scheduler) Job(j *Job) *Scheduler { - jobs := s.Jobs() - for index, job := range jobs { - if job == j { - // the current job is always last, so put this job there - s.Swap(len(jobs)-1, index) - } - } - s.updateJob = true - return s -} - -// Update stops the job (if running) and starts it with any updates -// that were made to the job in the scheduler chain. Job() must be -// called first to put the given job in focus. -func (s *Scheduler) Update() (*Job, error) { - job := s.getCurrentJob() - - if !s.updateJob { - return job, wrapOrError(job.error, ErrUpdateCalledWithoutJob) - } - s.updateJob = false - job.stop() - job.ctx, job.cancel = context.WithCancel(context.Background()) - job.setStartsImmediately(false) - - if job.runWithDetails { - return s.DoWithJobDetails(job.function, job.parameters...) - } - - return s.Do(job.function, job.parameters...) -} - -func (s *Scheduler) Cron(cronExpression string) *Scheduler { - return s.cron(cronExpression, false) -} - -func (s *Scheduler) CronWithSeconds(cronExpression string) *Scheduler { - return s.cron(cronExpression, true) -} - -func (s *Scheduler) cron(cronExpression string, withSeconds bool) *Scheduler { - job := s.newJob(0) - if s.updateJob || s.jobCreated { - job = s.getCurrentJob() - } - - var withLocation string - if strings.HasPrefix(cronExpression, "TZ=") || strings.HasPrefix(cronExpression, "CRON_TZ=") { - withLocation = cronExpression - } else { - withLocation = fmt.Sprintf("CRON_TZ=%s %s", s.location.String(), cronExpression) - } - - var ( - cronSchedule cron.Schedule - err error - ) - - if withSeconds { - p := cron.NewParser(cron.Second | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor) - cronSchedule, err = p.Parse(withLocation) - } else { - cronSchedule, err = cron.ParseStandard(withLocation) - } - - if err != nil { - job.error = wrapOrError(err, ErrCronParseFailure) - } - - job.cronSchedule = cronSchedule - job.setUnit(crontab) - job.startsImmediately = false - - if s.updateJob || s.jobCreated { - s.setJobs(append(s.Jobs()[:len(s.Jobs())-1], job)) - s.jobCreated = false - } else { - s.setJobs(append(s.Jobs(), job)) - } - return s -} - -func (s *Scheduler) newJob(interval int) *Job { - return newJob(interval, !s.waitForInterval, s.singletonMode) -} - -// WaitForScheduleAll defaults the scheduler to create all -// new jobs with the WaitForSchedule option as true. -// The jobs will not start immediately but rather will -// wait until their first scheduled interval. -func (s *Scheduler) WaitForScheduleAll() { - s.waitForInterval = true -} - -// WaitForSchedule sets the job to not start immediately -// but rather wait until the first scheduled interval. -func (s *Scheduler) WaitForSchedule() *Scheduler { - job := s.getCurrentJob() - job.startsImmediately = false - return s -} - -// StartImmediately sets the job to run immediately upon -// starting the scheduler or adding the job to a running -// scheduler. This overrides the jobs start status of any -// previously called methods in the chain. -// -// Note: This is the default behavior of the scheduler -// for most jobs, but is useful for overriding the default -// behavior of Cron scheduled jobs which default to -// WaitForSchedule. -func (s *Scheduler) StartImmediately() *Scheduler { - job := s.getCurrentJob() - job.startsImmediately = true - return s -} - -// CustomTime takes an in a struct that implements the TimeWrapper interface -// allowing the caller to mock the time used by the scheduler. This is useful -// for tests relying on gocron. -func (s *Scheduler) CustomTime(customTimeWrapper TimeWrapper) { - s.time = customTimeWrapper -} - -// CustomTimer takes in a function that mirrors the time.AfterFunc -// This is used to mock the time.AfterFunc function used by the scheduler -// for testing long intervals in a short amount of time. -func (s *Scheduler) CustomTimer(customTimer func(d time.Duration, f func()) *time.Timer) { - s.timer = customTimer -} - -func (s *Scheduler) StopBlockingChan() { - s.startBlockingStopChanMutex.Lock() - if s.startBlockingStopChan != nil { - s.startBlockingStopChan <- struct{}{} - } - s.startBlockingStopChanMutex.Unlock() -} diff --git a/vendor/github.com/go-co-op/gocron/timeHelper.go b/vendor/github.com/go-co-op/gocron/timeHelper.go deleted file mode 100644 index 487a7a2..0000000 --- a/vendor/github.com/go-co-op/gocron/timeHelper.go +++ /dev/null @@ -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) -} diff --git a/vendor/golang.org/x/sync/semaphore/semaphore.go b/vendor/golang.org/x/sync/semaphore/semaphore.go deleted file mode 100644 index 30f632c..0000000 --- a/vendor/golang.org/x/sync/semaphore/semaphore.go +++ /dev/null @@ -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) - } -} diff --git a/vendor/modules.txt b/vendor/modules.txt index f416268..e99ddbd 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -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 diff --git a/web/template/admin_jobs.gohtml b/web/template/admin_jobs.gohtml index bce8091..f33ea9a 100644 --- a/web/template/admin_jobs.gohtml +++ b/web/template/admin_jobs.gohtml @@ -7,7 +7,7 @@ {{- $textNextRun := .Localizer.TextNextRun -}} {{- $textRunJob := .Localizer.TextRunJob -}} {{- $textRunCount := .Localizer.TextRunCount -}} -{{- $textRunning := .Localizer.TextRunning -}} +{{- $textStatus := .Localizer.TextStatus -}} {{- template "header" . }}
@@ -28,7 +28,7 @@ {{ $textJob }} - {{ $textRunning }} + {{ $textStatus }} {{ $textRunCount }} {{ $textLastRun }} {{ $textNextRun }} @@ -39,7 +39,7 @@ {{- range $job := .Jobs }} {{ $job.Name }} - {{ template "yesno" $job.Running }} + {{ $job.State }} {{ $job.RunCount }} {{ formatDateTimeUTC $job.LastRun }} {{ formatDateTimeUTC $job.NextRun }}