|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "flag" |
| 6 | + "fmt" |
| 7 | + "log" |
| 8 | + "time" |
| 9 | + |
| 10 | + "go.uber.org/zap" |
| 11 | + |
| 12 | + "github.com/odpf/entropy/pkg/errors" |
| 13 | + "github.com/odpf/entropy/pkg/worker" |
| 14 | + "github.com/odpf/entropy/pkg/worker/pgq" |
| 15 | +) |
| 16 | + |
| 17 | +var ( |
| 18 | + jID = flag.String("id", "test", "Job ID") |
| 19 | + kind = flag.String("kind", "print", "Job kind") |
| 20 | + count = flag.Int("count", 1, "Number of jobs to create") |
| 21 | + after = flag.Duration("after", 0, "Enqueue a job after") |
| 22 | + payload = flag.String("payload", "", "Payload for the job") |
| 23 | + |
| 24 | + runWorker = flag.Bool("worker", false, "Run in worker mode") |
| 25 | + queueName = flag.String("queue", "demo", "Queue name") |
| 26 | + pgConStr = flag.String("pg", "postgresql://postgres@localhost:5432/postgres?sslmode=disable", "PostgreSQL connection string") |
| 27 | +) |
| 28 | + |
| 29 | +func main() { |
| 30 | + flag.Parse() |
| 31 | + |
| 32 | + lg, err := zap.NewDevelopment() |
| 33 | + if err != nil { |
| 34 | + panic(err) |
| 35 | + } |
| 36 | + |
| 37 | + q, err := pgq.Open(*pgConStr, *queueName) |
| 38 | + if err != nil { |
| 39 | + panic(err) |
| 40 | + } |
| 41 | + |
| 42 | + opts := []worker.Option{ |
| 43 | + worker.WithJobKind("test", testJobFn), |
| 44 | + worker.WithLogger(lg), |
| 45 | + } |
| 46 | + |
| 47 | + w, err := worker.New(q, opts...) |
| 48 | + if err != nil { |
| 49 | + panic(err) |
| 50 | + } |
| 51 | + |
| 52 | + if *runWorker { |
| 53 | + if err := w.Run(context.Background()); err != nil { |
| 54 | + panic(err) |
| 55 | + } |
| 56 | + } else { |
| 57 | + for i := 0; i < *count; i++ { |
| 58 | + log.Println(w.Enqueue(context.Background(), worker.Job{ |
| 59 | + ID: fmt.Sprintf("%s_%d", *jID, i), |
| 60 | + Kind: *kind, |
| 61 | + Payload: []byte(*payload), |
| 62 | + RunAt: time.Now().Add(*after), |
| 63 | + })) |
| 64 | + } |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +func testJobFn(_ context.Context, job worker.Job) ([]byte, error) { |
| 69 | + const maxAttempts = 3 |
| 70 | + const attemptBackoff = 5 * time.Second |
| 71 | + |
| 72 | + switch string(job.Payload) { |
| 73 | + case "fail_after_3": |
| 74 | + if job.AttemptsDone < maxAttempts { |
| 75 | + return nil, &worker.RetryableError{ |
| 76 | + Cause: errors.New("fake error [retryable]"), |
| 77 | + RetryAfter: attemptBackoff, |
| 78 | + } |
| 79 | + } |
| 80 | + return nil, errors.New("fake error [permanent]") |
| 81 | + |
| 82 | + case "panic": |
| 83 | + panic("simulated panic") |
| 84 | + |
| 85 | + case "fail": |
| 86 | + return nil, errors.New("fake error [permanent]") |
| 87 | + |
| 88 | + default: |
| 89 | + log.Printf("Test Job Says Hello! (attempt=%d)\n", job.AttemptsDone+1) |
| 90 | + return []byte("job is done"), nil |
| 91 | + } |
| 92 | +} |
0 commit comments