mirror of
https://github.com/hibiken/asynq.git
synced 2025-10-24 10:36:12 +08:00
Compare commits
307 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
461d922616 | ||
|
|
5daa3c52ed | ||
|
|
d04888e748 | ||
|
|
174008843d | ||
|
|
2b632b93d5 | ||
|
|
b35b559d40 | ||
|
|
8df0bfa583 | ||
|
|
b25d10b61d | ||
|
|
38f7499b71 | ||
|
|
0a73fc6201 | ||
|
|
1a11a33b4f | ||
|
|
f0888df813 | ||
|
|
c2dd648a51 | ||
|
|
a3cca853a0 | ||
|
|
83df622a92 | ||
|
|
fdbf54eb04 | ||
|
|
16ec43cbca | ||
|
|
1e0bf88bf3 | ||
|
|
d0041c55a3 | ||
|
|
7ef0511f35 | ||
|
|
1ec90810db | ||
|
|
90188a093d | ||
|
|
e05f0b7196 | ||
|
|
c1096a0fae | ||
|
|
9e548fc097 | ||
|
|
6a7bf2ceff | ||
|
|
e7fa0ae865 | ||
|
|
fc4b6713f6 | ||
|
|
6b98c0bbae | ||
|
|
ed1ab8ee55 | ||
|
|
e18c0381ad | ||
|
|
8b422c237c | ||
|
|
e6f74c1c2b | ||
|
|
6edba6994e | ||
|
|
571f0d2613 | ||
|
|
2165ed133b | ||
|
|
551b0c7119 | ||
|
|
123d560a44 | ||
|
|
5bef53d1ac | ||
|
|
90af7749ca | ||
|
|
e4b8663154 | ||
|
|
fde294be32 | ||
|
|
cbb1be34ac | ||
|
|
6ed70adf3b | ||
|
|
1f42d71e9b | ||
|
|
f966a6c3b8 | ||
|
|
8b057b8767 | ||
|
|
c72bfef094 | ||
|
|
dffb78cca4 | ||
|
|
0275df8df4 | ||
|
|
cc777ebdaa | ||
|
|
783071c47f | ||
|
|
bafed907e9 | ||
|
|
0b8cfad703 | ||
|
|
c08f142b56 | ||
|
|
c70ff6a335 | ||
|
|
a04ba6411d | ||
|
|
d0209d9273 | ||
|
|
6c954c87bf | ||
|
|
86fe31990b | ||
|
|
e0e5d1ac24 | ||
|
|
30d409371b | ||
|
|
aefd276146 | ||
|
|
94ad9e5e74 | ||
|
|
5187844ca5 | ||
|
|
4dd2b5738a | ||
|
|
9116c096ec | ||
|
|
5c723f597e | ||
|
|
dd6f84c575 | ||
|
|
c438339c3d | ||
|
|
901938b0fe | ||
|
|
245d4fe663 | ||
|
|
94719e325c | ||
|
|
8b2a787759 | ||
|
|
451be7e50f | ||
|
|
578321f226 | ||
|
|
2c783566f3 | ||
|
|
39718f8bea | ||
|
|
829f64fd38 | ||
|
|
a369443955 | ||
|
|
de139cc18e | ||
|
|
74db013ab9 | ||
|
|
725105ca03 | ||
|
|
d8f31e45f1 | ||
|
|
9023cbf4be | ||
|
|
9279c09125 | ||
|
|
bc27126670 | ||
|
|
0cfa7f47ba | ||
|
|
8a4fb71dd5 | ||
|
|
7fb5b25944 | ||
|
|
71bd8f0535 | ||
|
|
4c8432e0ce | ||
|
|
e939b5d166 | ||
|
|
1acd62c760 | ||
|
|
0149396bae | ||
|
|
45ed560708 | ||
|
|
01eeb8756e | ||
|
|
47af17cfb4 | ||
|
|
eb064c2bab | ||
|
|
652939dd3a | ||
|
|
efe3c74037 | ||
|
|
74d2eea4e0 | ||
|
|
60a4dc1401 | ||
|
|
4b716780ef | ||
|
|
e63f41fb24 | ||
|
|
1c388baf06 | ||
|
|
47a66231b3 | ||
|
|
3551d3334c | ||
|
|
8b16ede8bc | ||
|
|
c8658a53e6 | ||
|
|
562506c7ba | ||
|
|
888b5590fb | ||
|
|
196db64d4d | ||
|
|
4b35eb0e1a | ||
|
|
b29fe58434 | ||
|
|
7849b1114c | ||
|
|
99c00bffeb | ||
|
|
4542b52da8 | ||
|
|
d841dc2f8d | ||
|
|
ab28234767 | ||
|
|
eb27b0fe1e | ||
|
|
088be63ee4 | ||
|
|
ed69667e86 | ||
|
|
4e8885276c | ||
|
|
401f7fb4fe | ||
|
|
61854ea1dc | ||
|
|
f17c157b0f | ||
|
|
8b582899ad | ||
|
|
e3d2939a4c | ||
|
|
2ce71e83b0 | ||
|
|
1608366032 | ||
|
|
3f4f0c1daa | ||
|
|
f94a65dc9f | ||
|
|
04d7c8c38c | ||
|
|
c04fd41653 | ||
|
|
7e5efb0e30 | ||
|
|
cabf8d3627 | ||
|
|
a19909f5f4 | ||
|
|
cea5110d15 | ||
|
|
9b63e23274 | ||
|
|
de25201d9f | ||
|
|
ec560afb01 | ||
|
|
d4006894ad | ||
|
|
59927509d8 | ||
|
|
8211167de2 | ||
|
|
d7169cd445 | ||
|
|
dfae8638e1 | ||
|
|
b9943de2ab | ||
|
|
871474f220 | ||
|
|
87dc392c7f | ||
|
|
dabcb120d5 | ||
|
|
bc2f1986d7 | ||
|
|
b8cb579407 | ||
|
|
bca624792c | ||
|
|
d865d89900 | ||
|
|
852af7abd1 | ||
|
|
5490d2c625 | ||
|
|
ebd7a32c0f | ||
|
|
55d0610a03 | ||
|
|
ab8a4f5b1e | ||
|
|
d7ceb0c090 | ||
|
|
8bd70c6f84 | ||
|
|
10ab4e3745 | ||
|
|
349f4c50fb | ||
|
|
dff2e3a336 | ||
|
|
65040af7b5 | ||
|
|
053fe2d1ee | ||
|
|
25832e5e95 | ||
|
|
aa26f3819e | ||
|
|
d94614bb9b | ||
|
|
ce46b07652 | ||
|
|
2d0170541c | ||
|
|
c1f08106da | ||
|
|
74cf804197 | ||
|
|
8dfabfccb3 | ||
|
|
5f20edcbd1 | ||
|
|
1ddb2f7bce | ||
|
|
82d18e3d91 | ||
|
|
43cb4ddf19 | ||
|
|
ddfc6747a1 | ||
|
|
970cb7a606 | ||
|
|
157e97e72e | ||
|
|
22e6c9d297 | ||
|
|
99a6750656 | ||
|
|
e7c1c3ad6f | ||
|
|
c9183374c5 | ||
|
|
6e7106c8f2 | ||
|
|
9f2c321e98 | ||
|
|
e2b61c9056 | ||
|
|
531d1ef089 | ||
|
|
413afc2ab6 | ||
|
|
6bb4818509 | ||
|
|
f4ddac4dcc | ||
|
|
4638405cbd | ||
|
|
9e2f88c00d | ||
|
|
dbdd9c6d5f | ||
|
|
2261c7c9a0 | ||
|
|
83cae4bb24 | ||
|
|
23c522dc9f | ||
|
|
0d2c0f612b | ||
|
|
d612a8a9e4 | ||
|
|
b3ef9e91a9 | ||
|
|
05534c6f24 | ||
|
|
f0db219f6a | ||
|
|
3ae0e7f528 | ||
|
|
421dc584ff | ||
|
|
cfd1a1dfe8 | ||
|
|
c197902dc0 | ||
|
|
e6355bf3f5 | ||
|
|
95c90a5cb8 | ||
|
|
6817af366a | ||
|
|
4bce28d677 | ||
|
|
73f930313c | ||
|
|
bff2a05d59 | ||
|
|
684a7e0c98 | ||
|
|
46b23d6495 | ||
|
|
c0ae62499f | ||
|
|
7744ade362 | ||
|
|
f532c95394 | ||
|
|
ff6768f9bb | ||
|
|
d5e9f3b1bd | ||
|
|
d02b722d8a | ||
|
|
99c7ebeef2 | ||
|
|
bf54621196 | ||
|
|
27baf6de0d | ||
|
|
1bd0bee1e5 | ||
|
|
a9feec5967 | ||
|
|
e01c6379c8 | ||
|
|
a0df047f71 | ||
|
|
68dd6d9a9d | ||
|
|
6cce31a134 | ||
|
|
f9d7af3def | ||
|
|
b0321fb465 | ||
|
|
7776c7ae53 | ||
|
|
709ca79a2b | ||
|
|
08d8f0b37c | ||
|
|
385323b679 | ||
|
|
77604af265 | ||
|
|
4765742e8a | ||
|
|
68839dc9d3 | ||
|
|
8922d2423a | ||
|
|
b358de907e | ||
|
|
8ee1825e67 | ||
|
|
c8bda26bed | ||
|
|
8aeeb61c9d | ||
|
|
96c51fdc23 | ||
|
|
ea9086fd8b | ||
|
|
e63d51da0c | ||
|
|
cd351d49b9 | ||
|
|
87264b66f3 | ||
|
|
62168b8d0d | ||
|
|
840f7245b1 | ||
|
|
12f4c7cf6e | ||
|
|
0ec3b55e6b | ||
|
|
4bcc5ab6aa | ||
|
|
456edb6b71 | ||
|
|
b835090ad8 | ||
|
|
09cbea66f6 | ||
|
|
b9c2572203 | ||
|
|
0bf767cf21 | ||
|
|
1812d05d21 | ||
|
|
4af65d5fa5 | ||
|
|
a19ad19382 | ||
|
|
8117ce8972 | ||
|
|
d98ecdebb4 | ||
|
|
ffe9aa74b3 | ||
|
|
d2d4029aba | ||
|
|
76bd865ebc | ||
|
|
136d1c9ea9 | ||
|
|
52e04355d3 | ||
|
|
cde3e57c6c | ||
|
|
dd66acef1b | ||
|
|
30a3d9641a | ||
|
|
961582cba6 | ||
|
|
430dbb298e | ||
|
|
675826be5f | ||
|
|
62f4e46b73 | ||
|
|
a500f8a534 | ||
|
|
bcfeff38ed | ||
|
|
12a90f6a8d | ||
|
|
807624e7dd | ||
|
|
4d65024bd7 | ||
|
|
76486b5cb4 | ||
|
|
1db516c53c | ||
|
|
cb5bdf245c | ||
|
|
267493ccef | ||
|
|
5d7f1b6a80 | ||
|
|
77ded502ab | ||
|
|
f2284be43d | ||
|
|
3cadab55cb | ||
|
|
298a420f9f | ||
|
|
b1d717c842 | ||
|
|
56e5762eea | ||
|
|
5ec41e388b | ||
|
|
9c95c41651 | ||
|
|
476812475e | ||
|
|
7af3981929 | ||
|
|
2516c4baba | ||
|
|
ebe482a65c | ||
|
|
3e9fc2f972 | ||
|
|
63ce9ed0f9 | ||
|
|
32d3f329b9 | ||
|
|
544c301a8b | ||
|
|
8b997d2fab | ||
|
|
901105a8d7 | ||
|
|
aaa3f1d4fd | ||
|
|
4722ca2d3d |
4
.github/FUNDING.yml
vendored
Normal file
4
.github/FUNDING.yml
vendored
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
# These are supported funding model platforms
|
||||||
|
|
||||||
|
github: [hibiken]
|
||||||
|
open_collective: ken-hibino
|
||||||
21
.github/dependabot.yaml
vendored
Normal file
21
.github/dependabot.yaml
vendored
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
version: 2
|
||||||
|
updates:
|
||||||
|
- package-ecosystem: "gomod"
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
|
labels:
|
||||||
|
- "pr-deps"
|
||||||
|
- package-ecosystem: "gomod"
|
||||||
|
directory: "/tools"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
|
labels:
|
||||||
|
- "pr-deps"
|
||||||
|
- package-ecosystem: "gomod"
|
||||||
|
directory: "/x"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
|
labels:
|
||||||
|
- "pr-deps"
|
||||||
|
|
||||||
32
.github/workflows/benchstat.yml
vendored
32
.github/workflows/benchstat.yml
vendored
@@ -11,20 +11,20 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
services:
|
services:
|
||||||
redis:
|
redis:
|
||||||
image: redis
|
image: redis:7
|
||||||
ports:
|
ports:
|
||||||
- 6379:6379
|
- 6379:6379
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v4
|
||||||
- name: Set up Go
|
- name: Set up Go
|
||||||
uses: actions/setup-go@v2
|
uses: actions/setup-go@v4
|
||||||
with:
|
with:
|
||||||
go-version: 1.16.x
|
go-version: 1.21.x
|
||||||
- name: Benchmark
|
- name: Benchmark
|
||||||
run: go test -run=^$ -bench=. -count=5 -timeout=60m ./... | tee -a new.txt
|
run: go test -run=^$ -bench=. -count=5 -timeout=60m ./... | tee -a new.txt
|
||||||
- name: Upload Benchmark
|
- name: Upload Benchmark
|
||||||
uses: actions/upload-artifact@v2
|
uses: actions/upload-artifact@v3
|
||||||
with:
|
with:
|
||||||
name: bench-incoming
|
name: bench-incoming
|
||||||
path: new.txt
|
path: new.txt
|
||||||
@@ -33,22 +33,22 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
services:
|
services:
|
||||||
redis:
|
redis:
|
||||||
image: redis
|
image: redis:7
|
||||||
ports:
|
ports:
|
||||||
- 6379:6379
|
- 6379:6379
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
ref: master
|
ref: master
|
||||||
- name: Set up Go
|
- name: Set up Go
|
||||||
uses: actions/setup-go@v2
|
uses: actions/setup-go@v4
|
||||||
with:
|
with:
|
||||||
go-version: 1.15.x
|
go-version: 1.21.x
|
||||||
- name: Benchmark
|
- name: Benchmark
|
||||||
run: go test -run=^$ -bench=. -count=5 -timeout=60m ./... | tee -a old.txt
|
run: go test -run=^$ -bench=. -count=5 -timeout=60m ./... | tee -a old.txt
|
||||||
- name: Upload Benchmark
|
- name: Upload Benchmark
|
||||||
uses: actions/upload-artifact@v2
|
uses: actions/upload-artifact@v3
|
||||||
with:
|
with:
|
||||||
name: bench-current
|
name: bench-current
|
||||||
path: old.txt
|
path: old.txt
|
||||||
@@ -58,25 +58,25 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v4
|
||||||
- name: Set up Go
|
- name: Set up Go
|
||||||
uses: actions/setup-go@v2
|
uses: actions/setup-go@v4
|
||||||
with:
|
with:
|
||||||
go-version: 1.15.x
|
go-version: 1.21.x
|
||||||
- name: Install benchstat
|
- name: Install benchstat
|
||||||
run: go get -u golang.org/x/perf/cmd/benchstat
|
run: go get -u golang.org/x/perf/cmd/benchstat
|
||||||
- name: Download Incoming
|
- name: Download Incoming
|
||||||
uses: actions/download-artifact@v2
|
uses: actions/download-artifact@v3
|
||||||
with:
|
with:
|
||||||
name: bench-incoming
|
name: bench-incoming
|
||||||
- name: Download Current
|
- name: Download Current
|
||||||
uses: actions/download-artifact@v2
|
uses: actions/download-artifact@v3
|
||||||
with:
|
with:
|
||||||
name: bench-current
|
name: bench-current
|
||||||
- name: Benchstat Results
|
- name: Benchstat Results
|
||||||
run: benchstat old.txt new.txt | tee -a benchstat.txt
|
run: benchstat old.txt new.txt | tee -a benchstat.txt
|
||||||
- name: Upload benchstat results
|
- name: Upload benchstat results
|
||||||
uses: actions/upload-artifact@v2
|
uses: actions/upload-artifact@v3
|
||||||
with:
|
with:
|
||||||
name: benchstat
|
name: benchstat
|
||||||
path: benchstat.txt
|
path: benchstat.txt
|
||||||
|
|||||||
46
.github/workflows/build.yml
vendored
46
.github/workflows/build.yml
vendored
@@ -7,29 +7,63 @@ jobs:
|
|||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
os: [ubuntu-latest]
|
os: [ubuntu-latest]
|
||||||
go-version: [1.13.x, 1.14.x, 1.15.x, 1.16.x]
|
go-version: [1.20.x, 1.21.x]
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
services:
|
services:
|
||||||
redis:
|
redis:
|
||||||
image: redis
|
image: redis:7
|
||||||
ports:
|
ports:
|
||||||
- 6379:6379
|
- 6379:6379
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Set up Go
|
- name: Set up Go
|
||||||
uses: actions/setup-go@v2
|
uses: actions/setup-go@v4
|
||||||
with:
|
with:
|
||||||
go-version: ${{ matrix.go-version }}
|
go-version: ${{ matrix.go-version }}
|
||||||
|
cache: false
|
||||||
|
|
||||||
- name: Build
|
- name: Build core module
|
||||||
run: go build -v ./...
|
run: go build -v ./...
|
||||||
|
|
||||||
- name: Test
|
- name: Build x module
|
||||||
|
run: cd x && go build -v ./... && cd ..
|
||||||
|
|
||||||
|
- name: Test core module
|
||||||
run: go test -race -v -coverprofile=coverage.txt -covermode=atomic ./...
|
run: go test -race -v -coverprofile=coverage.txt -covermode=atomic ./...
|
||||||
|
|
||||||
|
- name: Test x module
|
||||||
|
run: cd x && go test -race -v ./... && cd ..
|
||||||
|
|
||||||
- name: Benchmark Test
|
- name: Benchmark Test
|
||||||
run: go test -run=^$ -bench=. -loglevel=debug ./...
|
run: go test -run=^$ -bench=. -loglevel=debug ./...
|
||||||
|
|
||||||
- name: Upload coverage to Codecov
|
- name: Upload coverage to Codecov
|
||||||
uses: codecov/codecov-action@v1
|
uses: codecov/codecov-action@v1
|
||||||
|
|
||||||
|
build-tool:
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
os: [ubuntu-latest]
|
||||||
|
go-version: [1.20.x, 1.21.x]
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
services:
|
||||||
|
redis:
|
||||||
|
image: redis:7
|
||||||
|
ports:
|
||||||
|
- 6379:6379
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@v4
|
||||||
|
with:
|
||||||
|
go-version: ${{ matrix.go-version }}
|
||||||
|
cache: false
|
||||||
|
|
||||||
|
- name: Build tools module
|
||||||
|
run: cd tools && go build -v ./... && cd ..
|
||||||
|
|
||||||
|
- name: Test tools module
|
||||||
|
run: cd tools && go test -race -v ./... && cd ..
|
||||||
|
|
||||||
|
|||||||
8
.gitignore
vendored
8
.gitignore
vendored
@@ -1,3 +1,4 @@
|
|||||||
|
vendor
|
||||||
# Binaries for programs and plugins
|
# Binaries for programs and plugins
|
||||||
*.exe
|
*.exe
|
||||||
*.exe~
|
*.exe~
|
||||||
@@ -14,8 +15,13 @@
|
|||||||
# Ignore examples for now
|
# Ignore examples for now
|
||||||
/examples
|
/examples
|
||||||
|
|
||||||
# Ignore command binary
|
# Ignore tool binaries
|
||||||
/tools/asynq/asynq
|
/tools/asynq/asynq
|
||||||
|
/tools/metrics_exporter/metrics_exporter
|
||||||
|
|
||||||
# Ignore asynq config file
|
# Ignore asynq config file
|
||||||
.asynq.*
|
.asynq.*
|
||||||
|
|
||||||
|
# Ignore editor config files
|
||||||
|
.vscode
|
||||||
|
.idea
|
||||||
|
|||||||
185
CHANGELOG.md
185
CHANGELOG.md
@@ -7,6 +7,191 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [0.25.0] - 2023-01-02
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Added configuration for Janitor's Interval and Deletion Batch Size (PR: https://github.com/hibiken/asynq/pull/715)
|
||||||
|
|
||||||
|
## [0.24.1] - 2023-05-01
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Updated package version dependency for go-redis
|
||||||
|
|
||||||
|
## [0.24.0] - 2023-01-02
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- `PreEnqueueFunc`, `PostEnqueueFunc` is added in `Scheduler` and deprecated `EnqueueErrorHandler` (PR: https://github.com/hibiken/asynq/pull/476)
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Removed error log when `Scheduler` failed to enqueue a task. Use `PostEnqueueFunc` to check for errors and task actions if needed.
|
||||||
|
- Changed log level from ERROR to WARNINING when `Scheduler` failed to record `SchedulerEnqueueEvent`.
|
||||||
|
|
||||||
|
## [0.23.0] - 2022-04-11
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- `Group` option is introduced to enqueue task in a group.
|
||||||
|
- `GroupAggregator` and related types are introduced for task aggregation feature.
|
||||||
|
- `GroupGracePeriod`, `GroupMaxSize`, `GroupMaxDelay`, and `GroupAggregator` fields are added to `Config`.
|
||||||
|
- `Inspector` has new methods related to "aggregating tasks".
|
||||||
|
- `Group` field is added to `TaskInfo`.
|
||||||
|
- (CLI): `group ls` command is added
|
||||||
|
- (CLI): `task ls` supports listing aggregating tasks via `--state=aggregating --group=<GROUP>` flags
|
||||||
|
- Enable rediss url parsing support
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Fixed overflow issue with 32-bit systems (For details, see https://github.com/hibiken/asynq/pull/426)
|
||||||
|
|
||||||
|
## [0.22.1] - 2022-02-20
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Fixed Redis version compatibility: Keep support for redis v4.0+
|
||||||
|
|
||||||
|
## [0.22.0] - 2022-02-19
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- `BaseContext` is introduced in `Config` to specify callback hook to provide a base `context` from which `Handler` `context` is derived
|
||||||
|
- `IsOrphaned` field is added to `TaskInfo` to describe a task left in active state with no worker processing it.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- `Server` now recovers tasks with an expired lease. Recovered tasks are retried/archived with `ErrLeaseExpired` error.
|
||||||
|
|
||||||
|
## [0.21.0] - 2022-01-22
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- `PeriodicTaskManager` is added. Prefer using this over `Scheduler` as it has better support for dynamic periodic tasks.
|
||||||
|
- The `asynq stats` command now supports a `--json` option, making its output a JSON object
|
||||||
|
- Introduced new configuration for `DelayedTaskCheckInterval`. See [godoc](https://godoc.org/github.com/hibiken/asynq) for more details.
|
||||||
|
|
||||||
|
## [0.20.0] - 2021-12-19
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Package `x/metrics` is added.
|
||||||
|
- Tool `tools/metrics_exporter` binary is added.
|
||||||
|
- `ProcessedTotal` and `FailedTotal` fields were added to `QueueInfo` struct.
|
||||||
|
|
||||||
|
## [0.19.1] - 2021-12-12
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- `Latency` field is added to `QueueInfo`.
|
||||||
|
- `EnqueueContext` method is added to `Client`.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Fixed an error when user pass a duration less than 1s to `Unique` option
|
||||||
|
|
||||||
|
## [0.19.0] - 2021-11-06
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- `NewTask` takes `Option` as variadic argument
|
||||||
|
- Bumped minimum supported go version to 1.14 (i.e. go1.14 or higher is required).
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- `Retention` option is added to allow user to specify task retention duration after completion.
|
||||||
|
- `TaskID` option is added to allow user to specify task ID.
|
||||||
|
- `ErrTaskIDConflict` sentinel error value is added.
|
||||||
|
- `ResultWriter` type is added and provided through `Task.ResultWriter` method.
|
||||||
|
- `TaskInfo` has new fields `CompletedAt`, `Result` and `Retention`.
|
||||||
|
|
||||||
|
### Removed
|
||||||
|
|
||||||
|
- `Client.SetDefaultOptions` is removed. Use `NewTask` instead to pass default options for tasks.
|
||||||
|
|
||||||
|
## [0.18.6] - 2021-10-03
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Updated `github.com/go-redis/redis` package to v8
|
||||||
|
|
||||||
|
## [0.18.5] - 2021-09-01
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- `IsFailure` config option is added to determine whether error returned from Handler counts as a failure.
|
||||||
|
|
||||||
|
## [0.18.4] - 2021-08-17
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Scheduler methods are now thread-safe. It's now safe to call `Register` and `Unregister` concurrently.
|
||||||
|
|
||||||
|
## [0.18.3] - 2021-08-09
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- `Client.Enqueue` no longer enqueues tasks with empty typename; Error message is returned.
|
||||||
|
|
||||||
|
## [0.18.2] - 2021-07-15
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Changed `Queue` function to not to convert the provided queue name to lowercase. Queue names are now case-sensitive.
|
||||||
|
- `QueueInfo.MemoryUsage` is now an approximate usage value.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Fixed latency issue around memory usage (see https://github.com/hibiken/asynq/issues/309).
|
||||||
|
|
||||||
|
## [0.18.1] - 2021-07-04
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Changed to execute task recovering logic when server starts up; Previously it needed to wait for a minute for task recovering logic to exeucte.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Fixed task recovering logic to execute every minute
|
||||||
|
|
||||||
|
## [0.18.0] - 2021-06-29
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- NewTask function now takes array of bytes as payload.
|
||||||
|
- Task `Type` and `Payload` should be accessed by a method call.
|
||||||
|
- `Server` API has changed. Renamed `Quiet` to `Stop`. Renamed `Stop` to `Shutdown`. _Note:_ As a result of this renaming, the behavior of `Stop` has changed. Please update the exising code to call `Shutdown` where it used to call `Stop`.
|
||||||
|
- `Scheduler` API has changed. Renamed `Stop` to `Shutdown`.
|
||||||
|
- Requires redis v4.0+ for multiple field/value pair support
|
||||||
|
- `Client.Enqueue` now returns `TaskInfo`
|
||||||
|
- `Inspector.RunTaskByKey` is replaced with `Inspector.RunTask`
|
||||||
|
- `Inspector.DeleteTaskByKey` is replaced with `Inspector.DeleteTask`
|
||||||
|
- `Inspector.ArchiveTaskByKey` is replaced with `Inspector.ArchiveTask`
|
||||||
|
- `inspeq` package is removed. All types and functions from the package is moved to `asynq` package.
|
||||||
|
- `WorkerInfo` field names have changed.
|
||||||
|
- `Inspector.CancelActiveTask` is renamed to `Inspector.CancelProcessing`
|
||||||
|
|
||||||
|
## [0.17.2] - 2021-06-06
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Free unique lock when task is deleted (https://github.com/hibiken/asynq/issues/275).
|
||||||
|
|
||||||
|
## [0.17.1] - 2021-04-04
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Fix bug in internal `RDB.memoryUsage` method.
|
||||||
|
|
||||||
|
## [0.17.0] - 2021-03-24
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- `DialTimeout`, `ReadTimeout`, and `WriteTimeout` options are added to `RedisConnOpt`.
|
||||||
|
|
||||||
|
## [0.16.1] - 2021-03-20
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Replace `KEYS` command with `SCAN` as recommended by [redis doc](https://redis.io/commands/KEYS).
|
||||||
|
|
||||||
## [0.16.0] - 2021-03-10
|
## [0.16.0] - 2021-03-10
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|||||||
128
CODE_OF_CONDUCT.md
Normal file
128
CODE_OF_CONDUCT.md
Normal file
@@ -0,0 +1,128 @@
|
|||||||
|
# Contributor Covenant Code of Conduct
|
||||||
|
|
||||||
|
## Our Pledge
|
||||||
|
|
||||||
|
We as members, contributors, and leaders pledge to make participation in our
|
||||||
|
community a harassment-free experience for everyone, regardless of age, body
|
||||||
|
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
||||||
|
identity and expression, level of experience, education, socio-economic status,
|
||||||
|
nationality, personal appearance, race, religion, or sexual identity
|
||||||
|
and orientation.
|
||||||
|
|
||||||
|
We pledge to act and interact in ways that contribute to an open, welcoming,
|
||||||
|
diverse, inclusive, and healthy community.
|
||||||
|
|
||||||
|
## Our Standards
|
||||||
|
|
||||||
|
Examples of behavior that contributes to a positive environment for our
|
||||||
|
community include:
|
||||||
|
|
||||||
|
* Demonstrating empathy and kindness toward other people
|
||||||
|
* Being respectful of differing opinions, viewpoints, and experiences
|
||||||
|
* Giving and gracefully accepting constructive feedback
|
||||||
|
* Accepting responsibility and apologizing to those affected by our mistakes,
|
||||||
|
and learning from the experience
|
||||||
|
* Focusing on what is best not just for us as individuals, but for the
|
||||||
|
overall community
|
||||||
|
|
||||||
|
Examples of unacceptable behavior include:
|
||||||
|
|
||||||
|
* The use of sexualized language or imagery, and sexual attention or
|
||||||
|
advances of any kind
|
||||||
|
* Trolling, insulting or derogatory comments, and personal or political attacks
|
||||||
|
* Public or private harassment
|
||||||
|
* Publishing others' private information, such as a physical or email
|
||||||
|
address, without their explicit permission
|
||||||
|
* Other conduct which could reasonably be considered inappropriate in a
|
||||||
|
professional setting
|
||||||
|
|
||||||
|
## Enforcement Responsibilities
|
||||||
|
|
||||||
|
Community leaders are responsible for clarifying and enforcing our standards of
|
||||||
|
acceptable behavior and will take appropriate and fair corrective action in
|
||||||
|
response to any behavior that they deem inappropriate, threatening, offensive,
|
||||||
|
or harmful.
|
||||||
|
|
||||||
|
Community leaders 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, and will communicate reasons for moderation
|
||||||
|
decisions when appropriate.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
This Code of Conduct applies within all community spaces, and also applies when
|
||||||
|
an individual is officially representing the community in public spaces.
|
||||||
|
Examples of representing our community include using an official e-mail address,
|
||||||
|
posting via an official social media account, or acting as an appointed
|
||||||
|
representative at an online or offline event.
|
||||||
|
|
||||||
|
## Enforcement
|
||||||
|
|
||||||
|
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||||
|
reported to the community leaders responsible for enforcement at
|
||||||
|
ken.hibino7@gmail.com.
|
||||||
|
All complaints will be reviewed and investigated promptly and fairly.
|
||||||
|
|
||||||
|
All community leaders are obligated to respect the privacy and security of the
|
||||||
|
reporter of any incident.
|
||||||
|
|
||||||
|
## Enforcement Guidelines
|
||||||
|
|
||||||
|
Community leaders will follow these Community Impact Guidelines in determining
|
||||||
|
the consequences for any action they deem in violation of this Code of Conduct:
|
||||||
|
|
||||||
|
### 1. Correction
|
||||||
|
|
||||||
|
**Community Impact**: Use of inappropriate language or other behavior deemed
|
||||||
|
unprofessional or unwelcome in the community.
|
||||||
|
|
||||||
|
**Consequence**: A private, written warning from community leaders, providing
|
||||||
|
clarity around the nature of the violation and an explanation of why the
|
||||||
|
behavior was inappropriate. A public apology may be requested.
|
||||||
|
|
||||||
|
### 2. Warning
|
||||||
|
|
||||||
|
**Community Impact**: A violation through a single incident or series
|
||||||
|
of actions.
|
||||||
|
|
||||||
|
**Consequence**: A warning with consequences for continued behavior. No
|
||||||
|
interaction with the people involved, including unsolicited interaction with
|
||||||
|
those enforcing the Code of Conduct, for a specified period of time. This
|
||||||
|
includes avoiding interactions in community spaces as well as external channels
|
||||||
|
like social media. Violating these terms may lead to a temporary or
|
||||||
|
permanent ban.
|
||||||
|
|
||||||
|
### 3. Temporary Ban
|
||||||
|
|
||||||
|
**Community Impact**: A serious violation of community standards, including
|
||||||
|
sustained inappropriate behavior.
|
||||||
|
|
||||||
|
**Consequence**: A temporary ban from any sort of interaction or public
|
||||||
|
communication with the community for a specified period of time. No public or
|
||||||
|
private interaction with the people involved, including unsolicited interaction
|
||||||
|
with those enforcing the Code of Conduct, is allowed during this period.
|
||||||
|
Violating these terms may lead to a permanent ban.
|
||||||
|
|
||||||
|
### 4. Permanent Ban
|
||||||
|
|
||||||
|
**Community Impact**: Demonstrating a pattern of violation of community
|
||||||
|
standards, including sustained inappropriate behavior, harassment of an
|
||||||
|
individual, or aggression toward or disparagement of classes of individuals.
|
||||||
|
|
||||||
|
**Consequence**: A permanent ban from any sort of public interaction within
|
||||||
|
the community.
|
||||||
|
|
||||||
|
## Attribution
|
||||||
|
|
||||||
|
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||||
|
version 2.0, available at
|
||||||
|
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
||||||
|
|
||||||
|
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
||||||
|
enforcement ladder](https://github.com/mozilla/diversity).
|
||||||
|
|
||||||
|
[homepage]: https://www.contributor-covenant.org
|
||||||
|
|
||||||
|
For answers to common questions about this code of conduct, see the FAQ at
|
||||||
|
https://www.contributor-covenant.org/faq. Translations are available at
|
||||||
|
https://www.contributor-covenant.org/translations.
|
||||||
@@ -38,7 +38,7 @@ Thank you! We'll try to respond as quickly as possible.
|
|||||||
## Contributing Code
|
## Contributing Code
|
||||||
|
|
||||||
1. Fork this repo
|
1. Fork this repo
|
||||||
2. Download your fork `git clone https://github.com/your-username/asynq && cd asynq`
|
2. Download your fork `git clone git@github.com:your-username/asynq.git && cd asynq`
|
||||||
3. Create your branch `git checkout -b your-branch-name`
|
3. Create your branch `git checkout -b your-branch-name`
|
||||||
4. Make and commit your changes
|
4. Make and commit your changes
|
||||||
5. Push the branch `git push origin your-branch-name`
|
5. Push the branch `git push origin your-branch-name`
|
||||||
|
|||||||
7
Makefile
Normal file
7
Makefile
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
ROOT_DIR:=$(shell dirname $(realpath $(firstword $(MAKEFILE_LIST))))
|
||||||
|
|
||||||
|
proto: internal/proto/asynq.proto
|
||||||
|
protoc -I=$(ROOT_DIR)/internal/proto \
|
||||||
|
--go_out=$(ROOT_DIR)/internal/proto \
|
||||||
|
--go_opt=module=github.com/hibiken/asynq/internal/proto \
|
||||||
|
$(ROOT_DIR)/internal/proto/asynq.proto
|
||||||
241
README.md
241
README.md
@@ -1,68 +1,80 @@
|
|||||||
# Asynq
|
<img src="https://user-images.githubusercontent.com/11155743/114697792-ffbfa580-9d26-11eb-8e5b-33bef69476dc.png" alt="Asynq logo" width="360px" />
|
||||||
|
|
||||||
|
# Simple, reliable & efficient distributed task queue in Go
|
||||||
|
|
||||||

|
|
||||||
[](https://godoc.org/github.com/hibiken/asynq)
|
[](https://godoc.org/github.com/hibiken/asynq)
|
||||||
[](https://goreportcard.com/report/github.com/hibiken/asynq)
|
[](https://goreportcard.com/report/github.com/hibiken/asynq)
|
||||||
|

|
||||||
[](https://opensource.org/licenses/MIT)
|
[](https://opensource.org/licenses/MIT)
|
||||||
[](https://gitter.im/go-asynq/community)
|
[](https://gitter.im/go-asynq/community)
|
||||||
|
|
||||||
## Overview
|
Asynq is a Go library for queueing tasks and processing them asynchronously with workers. It's backed by [Redis](https://redis.io/) and is designed to be scalable yet easy to get started.
|
||||||
|
|
||||||
Asynq is a Go library for queueing tasks and processing them asynchronously with workers. It's backed by Redis and is designed to be scalable yet easy to get started.
|
|
||||||
|
|
||||||
Highlevel overview of how Asynq works:
|
Highlevel overview of how Asynq works:
|
||||||
|
|
||||||
- Client puts task on a queue
|
- Client puts tasks on a queue
|
||||||
- Server pulls task off queues and starts a worker goroutine for each task
|
- Server pulls tasks off queues and starts a worker goroutine for each task
|
||||||
- Tasks are processed concurrently by multiple workers
|
- Tasks are processed concurrently by multiple workers
|
||||||
|
|
||||||
Task queues are used as a mechanism to distribute work across multiple machines.
|
Task queues are used as a mechanism to distribute work across multiple machines. A system can consist of multiple worker servers and brokers, giving way to high availability and horizontal scaling.
|
||||||
A system can consist of multiple worker servers and brokers, giving way to high availability and horizontal scaling.
|
|
||||||
|
|
||||||

|
**Example use case**
|
||||||
|
|
||||||
## Stability and Compatibility
|

|
||||||
|
|
||||||
**Important Note**: Current major version is zero (v0.x.x) to accomodate rapid development and fast iteration while getting early feedback from users (Feedback on APIs are appreciated!). The public API could change without a major version update before v1.0.0 release.
|
|
||||||
|
|
||||||
**Status**: The library is currently undergoing heavy development with frequent, breaking API changes.
|
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- Guaranteed [at least one execution](https://www.cloudcomputingpatterns.org/at_least_once_delivery/) of a task
|
- Guaranteed [at least one execution](https://www.cloudcomputingpatterns.org/at_least_once_delivery/) of a task
|
||||||
- Scheduling of tasks
|
- Scheduling of tasks
|
||||||
- Durability since tasks are written to Redis
|
|
||||||
- [Retries](https://github.com/hibiken/asynq/wiki/Task-Retry) of failed tasks
|
- [Retries](https://github.com/hibiken/asynq/wiki/Task-Retry) of failed tasks
|
||||||
- Automatic recovery of tasks in the event of a worker crash
|
- Automatic recovery of tasks in the event of a worker crash
|
||||||
- [Weighted priority queues](https://github.com/hibiken/asynq/wiki/Priority-Queues#weighted-priority-queues)
|
- [Weighted priority queues](https://github.com/hibiken/asynq/wiki/Queue-Priority#weighted-priority)
|
||||||
- [Strict priority queues](https://github.com/hibiken/asynq/wiki/Priority-Queues#strict-priority-queues)
|
- [Strict priority queues](https://github.com/hibiken/asynq/wiki/Queue-Priority#strict-priority)
|
||||||
- Low latency to add a task since writes are fast in Redis
|
- Low latency to add a task since writes are fast in Redis
|
||||||
- De-duplication of tasks using [unique option](https://github.com/hibiken/asynq/wiki/Unique-Tasks)
|
- De-duplication of tasks using [unique option](https://github.com/hibiken/asynq/wiki/Unique-Tasks)
|
||||||
- Allow [timeout and deadline per task](https://github.com/hibiken/asynq/wiki/Task-Timeout-and-Cancelation)
|
- Allow [timeout and deadline per task](https://github.com/hibiken/asynq/wiki/Task-Timeout-and-Cancelation)
|
||||||
|
- Allow [aggregating group of tasks](https://github.com/hibiken/asynq/wiki/Task-aggregation) to batch multiple successive operations
|
||||||
- [Flexible handler interface with support for middlewares](https://github.com/hibiken/asynq/wiki/Handler-Deep-Dive)
|
- [Flexible handler interface with support for middlewares](https://github.com/hibiken/asynq/wiki/Handler-Deep-Dive)
|
||||||
- [Ability to pause queue](/tools/asynq/README.md#pause) to stop processing tasks from the queue
|
- [Ability to pause queue](/tools/asynq/README.md#pause) to stop processing tasks from the queue
|
||||||
- [Periodic Tasks](https://github.com/hibiken/asynq/wiki/Periodic-Tasks)
|
- [Periodic Tasks](https://github.com/hibiken/asynq/wiki/Periodic-Tasks)
|
||||||
- [Support Redis Cluster](https://github.com/hibiken/asynq/wiki/Redis-Cluster) for automatic sharding and high availability
|
- [Support Redis Cluster](https://github.com/hibiken/asynq/wiki/Redis-Cluster) for automatic sharding and high availability
|
||||||
- [Support Redis Sentinels](https://github.com/hibiken/asynq/wiki/Automatic-Failover) for high availability
|
- [Support Redis Sentinels](https://github.com/hibiken/asynq/wiki/Automatic-Failover) for high availability
|
||||||
|
- Integration with [Prometheus](https://prometheus.io/) to collect and visualize queue metrics
|
||||||
- [Web UI](#web-ui) to inspect and remote-control queues and tasks
|
- [Web UI](#web-ui) to inspect and remote-control queues and tasks
|
||||||
- [CLI](#command-line-tool) to inspect and remote-control queues and tasks
|
- [CLI](#command-line-tool) to inspect and remote-control queues and tasks
|
||||||
|
|
||||||
|
## Stability and Compatibility
|
||||||
|
|
||||||
|
**Status**: The library is currently undergoing **heavy development** with frequent, breaking API changes.
|
||||||
|
|
||||||
|
> ☝️ **Important Note**: Current major version is zero (`v0.x.x`) to accommodate rapid development and fast iteration while getting early feedback from users (_feedback on APIs are appreciated!_). The public API could change without a major version update before `v1.0.0` release.
|
||||||
|
|
||||||
|
## Sponsoring
|
||||||
|
If you are using this package in production, **please consider sponsoring the project to show your support!**
|
||||||
|
|
||||||
## Quickstart
|
## Quickstart
|
||||||
|
|
||||||
First, make sure you are running a Redis server locally.
|
Make sure you have Go installed ([download](https://golang.org/dl/)). Latest two Go versions are supported (See https://go.dev/dl).
|
||||||
|
|
||||||
|
Initialize your project by creating a folder and then running `go mod init github.com/your/repo` ([learn more](https://blog.golang.org/using-go-modules)) inside the folder. Then install Asynq library with the [`go get`](https://golang.org/cmd/go/#hdr-Add_dependencies_to_current_module_and_install_them) command:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
$ redis-server
|
go get -u github.com/hibiken/asynq
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Make sure you're running a Redis server locally or from a [Docker](https://hub.docker.com/_/redis) container. Version `4.0` or higher is required.
|
||||||
|
|
||||||
Next, write a package that encapsulates task creation and task handling.
|
Next, write a package that encapsulates task creation and task handling.
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package tasks
|
package tasks
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"time"
|
||||||
"github.com/hibiken/asynq"
|
"github.com/hibiken/asynq"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -72,19 +84,35 @@ const (
|
|||||||
TypeImageResize = "image:resize"
|
TypeImageResize = "image:resize"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type EmailDeliveryPayload struct {
|
||||||
|
UserID int
|
||||||
|
TemplateID string
|
||||||
|
}
|
||||||
|
|
||||||
|
type ImageResizePayload struct {
|
||||||
|
SourceURL string
|
||||||
|
}
|
||||||
|
|
||||||
//----------------------------------------------
|
//----------------------------------------------
|
||||||
// Write a function NewXXXTask to create a task.
|
// Write a function NewXXXTask to create a task.
|
||||||
// A task consists of a type and a payload.
|
// A task consists of a type and a payload.
|
||||||
//----------------------------------------------
|
//----------------------------------------------
|
||||||
|
|
||||||
func NewEmailDeliveryTask(userID int, tmplID string) *asynq.Task {
|
func NewEmailDeliveryTask(userID int, tmplID string) (*asynq.Task, error) {
|
||||||
payload := map[string]interface{}{"user_id": userID, "template_id": tmplID}
|
payload, err := json.Marshal(EmailDeliveryPayload{UserID: userID, TemplateID: tmplID})
|
||||||
return asynq.NewTask(TypeEmailDelivery, payload)
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return asynq.NewTask(TypeEmailDelivery, payload), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewImageResizeTask(src string) *asynq.Task {
|
func NewImageResizeTask(src string) (*asynq.Task, error) {
|
||||||
payload := map[string]interface{}{"src": src}
|
payload, err := json.Marshal(ImageResizePayload{SourceURL: src})
|
||||||
return asynq.NewTask(TypeImageResize, payload)
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// task options can be passed to NewTask, which can be overridden at enqueue time.
|
||||||
|
return asynq.NewTask(TypeImageResize, payload, asynq.MaxRetry(5), asynq.Timeout(20 * time.Minute)), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
//---------------------------------------------------------------
|
//---------------------------------------------------------------
|
||||||
@@ -96,15 +124,11 @@ func NewImageResizeTask(src string) *asynq.Task {
|
|||||||
//---------------------------------------------------------------
|
//---------------------------------------------------------------
|
||||||
|
|
||||||
func HandleEmailDeliveryTask(ctx context.Context, t *asynq.Task) error {
|
func HandleEmailDeliveryTask(ctx context.Context, t *asynq.Task) error {
|
||||||
userID, err := t.Payload.GetInt("user_id")
|
var p EmailDeliveryPayload
|
||||||
if err != nil {
|
if err := json.Unmarshal(t.Payload(), &p); err != nil {
|
||||||
return err
|
return fmt.Errorf("json.Unmarshal failed: %v: %w", err, asynq.SkipRetry)
|
||||||
}
|
}
|
||||||
tmplID, err := t.Payload.GetString("template_id")
|
log.Printf("Sending Email to User: user_id=%d, template_id=%s", p.UserID, p.TemplateID)
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
fmt.Printf("Send Email to User: user_id = %d, template_id = %s\n", userID, tmplID)
|
|
||||||
// Email delivery code ...
|
// Email delivery code ...
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -114,28 +138,27 @@ type ImageProcessor struct {
|
|||||||
// ... fields for struct
|
// ... fields for struct
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *ImageProcessor) ProcessTask(ctx context.Context, t *asynq.Task) error {
|
func (processor *ImageProcessor) ProcessTask(ctx context.Context, t *asynq.Task) error {
|
||||||
src, err := t.Payload.GetString("src")
|
var p ImageResizePayload
|
||||||
if err != nil {
|
if err := json.Unmarshal(t.Payload(), &p); err != nil {
|
||||||
return err
|
return fmt.Errorf("json.Unmarshal failed: %v: %w", err, asynq.SkipRetry)
|
||||||
}
|
}
|
||||||
fmt.Printf("Resize image: src = %s\n", src)
|
log.Printf("Resizing image: src=%s", p.SourceURL)
|
||||||
// Image resizing code ...
|
// Image resizing code ...
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewImageProcessor() *ImageProcessor {
|
func NewImageProcessor() *ImageProcessor {
|
||||||
// ... return an instance
|
return &ImageProcessor{}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
In your application code, import the above package and use [`Client`](https://pkg.go.dev/github.com/hibiken/asynq?tab=doc#Client) to put tasks on the queue.
|
In your application code, import the above package and use [`Client`](https://pkg.go.dev/github.com/hibiken/asynq?tab=doc#Client) to put tasks on queues.
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"log"
|
"log"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -146,21 +169,23 @@ import (
|
|||||||
const redisAddr = "127.0.0.1:6379"
|
const redisAddr = "127.0.0.1:6379"
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
r := asynq.RedisClientOpt{Addr: redisAddr}
|
client := asynq.NewClient(asynq.RedisClientOpt{Addr: redisAddr})
|
||||||
c := asynq.NewClient(r)
|
defer client.Close()
|
||||||
defer c.Close()
|
|
||||||
|
|
||||||
// ------------------------------------------------------
|
// ------------------------------------------------------
|
||||||
// Example 1: Enqueue task to be processed immediately.
|
// Example 1: Enqueue task to be processed immediately.
|
||||||
// Use (*Client).Enqueue method.
|
// Use (*Client).Enqueue method.
|
||||||
// ------------------------------------------------------
|
// ------------------------------------------------------
|
||||||
|
|
||||||
t := tasks.NewEmailDeliveryTask(42, "some:template:id")
|
task, err := tasks.NewEmailDeliveryTask(42, "some:template:id")
|
||||||
res, err := c.Enqueue(t)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("could not enqueue task: %v", err)
|
log.Fatalf("could not create task: %v", err)
|
||||||
}
|
}
|
||||||
fmt.Printf("Enqueued Result: %+v\n", res)
|
info, err := client.Enqueue(task)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("could not enqueue task: %v", err)
|
||||||
|
}
|
||||||
|
log.Printf("enqueued task: id=%s queue=%s", info.ID, info.Queue)
|
||||||
|
|
||||||
|
|
||||||
// ------------------------------------------------------------
|
// ------------------------------------------------------------
|
||||||
@@ -168,12 +193,11 @@ func main() {
|
|||||||
// Use ProcessIn or ProcessAt option.
|
// Use ProcessIn or ProcessAt option.
|
||||||
// ------------------------------------------------------------
|
// ------------------------------------------------------------
|
||||||
|
|
||||||
t = tasks.NewEmailDeliveryTask(42, "other:template:id")
|
info, err = client.Enqueue(task, asynq.ProcessIn(24*time.Hour))
|
||||||
res, err = c.Enqueue(t, asynq.ProcessIn(24*time.Hour))
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("could not schedule task: %v", err)
|
log.Fatalf("could not schedule task: %v", err)
|
||||||
}
|
}
|
||||||
fmt.Printf("Enqueued Result: %+v\n", res)
|
log.Printf("enqueued task: id=%s queue=%s", info.ID, info.Queue)
|
||||||
|
|
||||||
|
|
||||||
// ----------------------------------------------------------------------------
|
// ----------------------------------------------------------------------------
|
||||||
@@ -181,33 +205,21 @@ func main() {
|
|||||||
// Options include MaxRetry, Queue, Timeout, Deadline, Unique etc.
|
// Options include MaxRetry, Queue, Timeout, Deadline, Unique etc.
|
||||||
// ----------------------------------------------------------------------------
|
// ----------------------------------------------------------------------------
|
||||||
|
|
||||||
c.SetDefaultOptions(tasks.TypeImageResize, asynq.MaxRetry(10), asynq.Timeout(3*time.Minute))
|
task, err = tasks.NewImageResizeTask("https://example.com/myassets/image.jpg")
|
||||||
|
|
||||||
t = tasks.NewImageResizeTask("some/blobstore/path")
|
|
||||||
res, err = c.Enqueue(t)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("could not enqueue task: %v", err)
|
log.Fatalf("could not create task: %v", err)
|
||||||
}
|
}
|
||||||
fmt.Printf("Enqueued Result: %+v\n", res)
|
info, err = client.Enqueue(task, asynq.MaxRetry(10), asynq.Timeout(3 * time.Minute))
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Example 4: Pass options to tune task processing behavior at enqueue time.
|
|
||||||
// Options passed at enqueue time override default ones, if any.
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
t = tasks.NewImageResizeTask("some/blobstore/path")
|
|
||||||
res, err = c.Enqueue(t, asynq.Queue("critical"), asynq.Timeout(30*time.Second))
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("could not enqueue task: %v", err)
|
log.Fatalf("could not enqueue task: %v", err)
|
||||||
}
|
}
|
||||||
fmt.Printf("Enqueued Result: %+v\n", res)
|
log.Printf("enqueued task: id=%s queue=%s", info.ID, info.Queue)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Next, start a worker server to process these tasks in the background.
|
Next, start a worker server to process these tasks in the background. To start the background workers, use [`Server`](https://pkg.go.dev/github.com/hibiken/asynq?tab=doc#Server) and provide your [`Handler`](https://pkg.go.dev/github.com/hibiken/asynq?tab=doc#Handler) to process the tasks.
|
||||||
To start the background workers, use [`Server`](https://pkg.go.dev/github.com/hibiken/asynq?tab=doc#Server) and provide your [`Handler`](https://pkg.go.dev/github.com/hibiken/asynq?tab=doc#Handler) to process the tasks.
|
|
||||||
|
|
||||||
You can optionally use [`ServeMux`](https://pkg.go.dev/github.com/hibiken/asynq?tab=doc#ServeMux) to create a handler, just as you would with [`"net/http"`](https://golang.org/pkg/net/http/) Handler.
|
You can optionally use [`ServeMux`](https://pkg.go.dev/github.com/hibiken/asynq?tab=doc#ServeMux) to create a handler, just as you would with [`net/http`](https://golang.org/pkg/net/http/) Handler.
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -222,19 +234,20 @@ import (
|
|||||||
const redisAddr = "127.0.0.1:6379"
|
const redisAddr = "127.0.0.1:6379"
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
r := asynq.RedisClientOpt{Addr: redisAddr}
|
srv := asynq.NewServer(
|
||||||
|
asynq.RedisClientOpt{Addr: redisAddr},
|
||||||
srv := asynq.NewServer(r, asynq.Config{
|
asynq.Config{
|
||||||
// Specify how many concurrent workers to use
|
// Specify how many concurrent workers to use
|
||||||
Concurrency: 10,
|
Concurrency: 10,
|
||||||
// Optionally specify multiple queues with different priority.
|
// Optionally specify multiple queues with different priority.
|
||||||
Queues: map[string]int{
|
Queues: map[string]int{
|
||||||
"critical": 6,
|
"critical": 6,
|
||||||
"default": 3,
|
"default": 3,
|
||||||
"low": 1,
|
"low": 1,
|
||||||
|
},
|
||||||
|
// See the godoc for other configuration options
|
||||||
},
|
},
|
||||||
// See the godoc for other configuration options
|
)
|
||||||
})
|
|
||||||
|
|
||||||
// mux maps a type to a handler
|
// mux maps a type to a handler
|
||||||
mux := asynq.NewServeMux()
|
mux := asynq.NewServeMux()
|
||||||
@@ -248,65 +261,55 @@ func main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
For a more detailed walk-through of the library, see our [Getting Started Guide](https://github.com/hibiken/asynq/wiki/Getting-Started).
|
For a more detailed walk-through of the library, see our [Getting Started](https://github.com/hibiken/asynq/wiki/Getting-Started) guide.
|
||||||
|
|
||||||
To Learn more about `asynq` features and APIs, see our [Wiki](https://github.com/hibiken/asynq/wiki) and [godoc](https://godoc.org/github.com/hibiken/asynq).
|
To learn more about `asynq` features and APIs, see the package [godoc](https://godoc.org/github.com/hibiken/asynq).
|
||||||
|
|
||||||
## Web UI
|
## Web UI
|
||||||
|
|
||||||
[Asynqmon](https://github.com/hibiken/asynqmon) is a web based tool for monitoring and administrating Asynq queues and tasks.
|
[Asynqmon](https://github.com/hibiken/asynqmon) is a web based tool for monitoring and administrating Asynq queues and tasks.
|
||||||
Please see the tool's [README](https://github.com/hibiken/asynqmon) for details.
|
|
||||||
|
|
||||||
Here's a few screenshots of the web UI.
|
Here's a few screenshots of the Web UI:
|
||||||
|
|
||||||
**Queues view**
|
**Queues view**
|
||||||

|
|
||||||
|

|
||||||
|
|
||||||
**Tasks view**
|
**Tasks view**
|
||||||

|
|
||||||
|

|
||||||
|
|
||||||
|
**Metrics view**
|
||||||
|
<img width="1532" alt="Screen Shot 2021-12-19 at 4 37 19 PM" src="https://user-images.githubusercontent.com/10953044/146777420-cae6c476-bac6-469c-acce-b2f6584e8707.png">
|
||||||
|
|
||||||
|
**Settings and adaptive dark mode**
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
For details on how to use the tool, refer to the tool's [README](https://github.com/hibiken/asynqmon#readme).
|
||||||
|
|
||||||
## Command Line Tool
|
## Command Line Tool
|
||||||
|
|
||||||
Asynq ships with a command line tool to inspect the state of queues and tasks.
|
Asynq ships with a command line tool to inspect the state of queues and tasks.
|
||||||
|
|
||||||
Here's an example of running the `stats` command.
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
For details on how to use the tool, refer to the tool's [README](/tools/asynq/README.md).
|
|
||||||
|
|
||||||
## Installation
|
|
||||||
|
|
||||||
To install `asynq` library, run the following command:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
go get -u github.com/hibiken/asynq
|
|
||||||
```
|
|
||||||
|
|
||||||
To install the CLI tool, run the following command:
|
To install the CLI tool, run the following command:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
go get -u github.com/hibiken/asynq/tools/asynq
|
go install github.com/hibiken/asynq/tools/asynq@latest
|
||||||
```
|
```
|
||||||
|
|
||||||
## Requirements
|
Here's an example of running the `asynq dash` command:
|
||||||
|
|
||||||
| Dependency | Version |
|

|
||||||
| -------------------------- | ------- |
|
|
||||||
| [Redis](https://redis.io/) | v3.0+ |
|
For details on how to use the tool, refer to the tool's [README](/tools/asynq/README.md).
|
||||||
| [Go](https://golang.org/) | v1.13+ |
|
|
||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
|
|
||||||
We are open to, and grateful for, any contributions (Github issues/pull-requests, feedback on Gitter channel, etc) made by the community.
|
We are open to, and grateful for, any contributions (GitHub issues/PRs, feedback on [Gitter channel](https://gitter.im/go-asynq/community), etc) made by the community.
|
||||||
|
|
||||||
Please see the [Contribution Guide](/CONTRIBUTING.md) before contributing.
|
Please see the [Contribution Guide](/CONTRIBUTING.md) before contributing.
|
||||||
|
|
||||||
## Acknowledgements
|
|
||||||
|
|
||||||
- [Sidekiq](https://github.com/mperham/sidekiq) : Many of the design ideas are taken from sidekiq and its Web UI
|
|
||||||
- [RQ](https://github.com/rq/rq) : Client APIs are inspired by rq library.
|
|
||||||
- [Cobra](https://github.com/spf13/cobra) : Asynq CLI is built with cobra
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
Asynq is released under the MIT license. See [LICENSE](https://github.com/hibiken/asynq/blob/master/LICENSE).
|
Copyright (c) 2019-present [Ken Hibino](https://github.com/hibiken) and [Contributors](https://github.com/hibiken/asynq/graphs/contributors). `Asynq` is free and open-source software licensed under the [MIT License](https://github.com/hibiken/asynq/blob/master/LICENSE). Official logo was created by [Vic Shóstak](https://github.com/koddr) and distributed under [Creative Commons](https://creativecommons.org/publicdomain/zero/1.0/) license (CC0 1.0 Universal).
|
||||||
|
|||||||
176
aggregator.go
Normal file
176
aggregator.go
Normal file
@@ -0,0 +1,176 @@
|
|||||||
|
// Copyright 2022 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package asynq
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/hibiken/asynq/internal/base"
|
||||||
|
"github.com/hibiken/asynq/internal/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
// An aggregator is responsible for checking groups and aggregate into one task
|
||||||
|
// if any of the grouping condition is met.
|
||||||
|
type aggregator struct {
|
||||||
|
logger *log.Logger
|
||||||
|
broker base.Broker
|
||||||
|
client *Client
|
||||||
|
|
||||||
|
// channel to communicate back to the long running "aggregator" goroutine.
|
||||||
|
done chan struct{}
|
||||||
|
|
||||||
|
// list of queue names to check and aggregate.
|
||||||
|
queues []string
|
||||||
|
|
||||||
|
// Group configurations
|
||||||
|
gracePeriod time.Duration
|
||||||
|
maxDelay time.Duration
|
||||||
|
maxSize int
|
||||||
|
|
||||||
|
// User provided group aggregator.
|
||||||
|
ga GroupAggregator
|
||||||
|
|
||||||
|
// interval used to check for aggregation
|
||||||
|
interval time.Duration
|
||||||
|
|
||||||
|
// sema is a counting semaphore to ensure the number of active aggregating function
|
||||||
|
// does not exceed the limit.
|
||||||
|
sema chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
type aggregatorParams struct {
|
||||||
|
logger *log.Logger
|
||||||
|
broker base.Broker
|
||||||
|
queues []string
|
||||||
|
gracePeriod time.Duration
|
||||||
|
maxDelay time.Duration
|
||||||
|
maxSize int
|
||||||
|
groupAggregator GroupAggregator
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
// Maximum number of aggregation checks in flight concurrently.
|
||||||
|
maxConcurrentAggregationChecks = 3
|
||||||
|
|
||||||
|
// Default interval used for aggregation checks. If the provided gracePeriod is less than
|
||||||
|
// the default, use the gracePeriod.
|
||||||
|
defaultAggregationCheckInterval = 7 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
func newAggregator(params aggregatorParams) *aggregator {
|
||||||
|
interval := defaultAggregationCheckInterval
|
||||||
|
if params.gracePeriod < interval {
|
||||||
|
interval = params.gracePeriod
|
||||||
|
}
|
||||||
|
return &aggregator{
|
||||||
|
logger: params.logger,
|
||||||
|
broker: params.broker,
|
||||||
|
client: &Client{broker: params.broker},
|
||||||
|
done: make(chan struct{}),
|
||||||
|
queues: params.queues,
|
||||||
|
gracePeriod: params.gracePeriod,
|
||||||
|
maxDelay: params.maxDelay,
|
||||||
|
maxSize: params.maxSize,
|
||||||
|
ga: params.groupAggregator,
|
||||||
|
sema: make(chan struct{}, maxConcurrentAggregationChecks),
|
||||||
|
interval: interval,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *aggregator) shutdown() {
|
||||||
|
if a.ga == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
a.logger.Debug("Aggregator shutting down...")
|
||||||
|
// Signal the aggregator goroutine to stop.
|
||||||
|
a.done <- struct{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *aggregator) start(wg *sync.WaitGroup) {
|
||||||
|
if a.ga == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
ticker := time.NewTicker(a.interval)
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-a.done:
|
||||||
|
a.logger.Debug("Waiting for all aggregation checks to finish...")
|
||||||
|
// block until all aggregation checks released the token
|
||||||
|
for i := 0; i < cap(a.sema); i++ {
|
||||||
|
a.sema <- struct{}{}
|
||||||
|
}
|
||||||
|
a.logger.Debug("Aggregator done")
|
||||||
|
ticker.Stop()
|
||||||
|
return
|
||||||
|
case t := <-ticker.C:
|
||||||
|
a.exec(t)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *aggregator) exec(t time.Time) {
|
||||||
|
select {
|
||||||
|
case a.sema <- struct{}{}: // acquire token
|
||||||
|
go a.aggregate(t)
|
||||||
|
default:
|
||||||
|
// If the semaphore blocks, then we are currently running max number of
|
||||||
|
// aggregation checks. Skip this round and log warning.
|
||||||
|
a.logger.Warnf("Max number of aggregation checks in flight. Skipping")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *aggregator) aggregate(t time.Time) {
|
||||||
|
defer func() { <-a.sema /* release token */ }()
|
||||||
|
for _, qname := range a.queues {
|
||||||
|
groups, err := a.broker.ListGroups(qname)
|
||||||
|
if err != nil {
|
||||||
|
a.logger.Errorf("Failed to list groups in queue: %q", qname)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, gname := range groups {
|
||||||
|
aggregationSetID, err := a.broker.AggregationCheck(
|
||||||
|
qname, gname, t, a.gracePeriod, a.maxDelay, a.maxSize)
|
||||||
|
if err != nil {
|
||||||
|
a.logger.Errorf("Failed to run aggregation check: queue=%q group=%q", qname, gname)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if aggregationSetID == "" {
|
||||||
|
a.logger.Debugf("No aggregation needed at this time: queue=%q group=%q", qname, gname)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Aggregate and enqueue.
|
||||||
|
msgs, deadline, err := a.broker.ReadAggregationSet(qname, gname, aggregationSetID)
|
||||||
|
if err != nil {
|
||||||
|
a.logger.Errorf("Failed to read aggregation set: queue=%q, group=%q, setID=%q",
|
||||||
|
qname, gname, aggregationSetID)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
tasks := make([]*Task, len(msgs))
|
||||||
|
for i, m := range msgs {
|
||||||
|
tasks[i] = NewTask(m.Type, m.Payload)
|
||||||
|
}
|
||||||
|
aggregatedTask := a.ga.Aggregate(gname, tasks)
|
||||||
|
ctx, cancel := context.WithDeadline(context.Background(), deadline)
|
||||||
|
if _, err := a.client.EnqueueContext(ctx, aggregatedTask, Queue(qname)); err != nil {
|
||||||
|
a.logger.Errorf("Failed to enqueue aggregated task (queue=%q, group=%q, setID=%q): %v",
|
||||||
|
qname, gname, aggregationSetID, err)
|
||||||
|
cancel()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := a.broker.DeleteAggregationSet(ctx, qname, gname, aggregationSetID); err != nil {
|
||||||
|
a.logger.Warnf("Failed to delete aggregation set: queue=%q, group=%q, setID=%q",
|
||||||
|
qname, gname, aggregationSetID)
|
||||||
|
}
|
||||||
|
cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
165
aggregator_test.go
Normal file
165
aggregator_test.go
Normal file
@@ -0,0 +1,165 @@
|
|||||||
|
// Copyright 2022 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package asynq
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/go-cmp/cmp"
|
||||||
|
"github.com/hibiken/asynq/internal/base"
|
||||||
|
"github.com/hibiken/asynq/internal/rdb"
|
||||||
|
h "github.com/hibiken/asynq/internal/testutil"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAggregator(t *testing.T) {
|
||||||
|
r := setup(t)
|
||||||
|
defer r.Close()
|
||||||
|
rdbClient := rdb.NewRDB(r)
|
||||||
|
client := Client{broker: rdbClient}
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
desc string
|
||||||
|
gracePeriod time.Duration
|
||||||
|
maxDelay time.Duration
|
||||||
|
maxSize int
|
||||||
|
aggregateFunc func(gname string, tasks []*Task) *Task
|
||||||
|
tasks []*Task // tasks to enqueue
|
||||||
|
enqueueFrequency time.Duration // time between one enqueue event to another
|
||||||
|
waitTime time.Duration // time to wait
|
||||||
|
wantGroups map[string]map[string][]base.Z
|
||||||
|
wantPending map[string][]*base.TaskMessage
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
desc: "group older than the grace period should be aggregated",
|
||||||
|
gracePeriod: 1 * time.Second,
|
||||||
|
maxDelay: 0, // no maxdelay limit
|
||||||
|
maxSize: 0, // no maxsize limit
|
||||||
|
aggregateFunc: func(gname string, tasks []*Task) *Task {
|
||||||
|
return NewTask(gname, nil, MaxRetry(len(tasks))) // use max retry to see how many tasks were aggregated
|
||||||
|
},
|
||||||
|
tasks: []*Task{
|
||||||
|
NewTask("task1", nil, Group("mygroup")),
|
||||||
|
NewTask("task2", nil, Group("mygroup")),
|
||||||
|
NewTask("task3", nil, Group("mygroup")),
|
||||||
|
},
|
||||||
|
enqueueFrequency: 300 * time.Millisecond,
|
||||||
|
waitTime: 3 * time.Second,
|
||||||
|
wantGroups: map[string]map[string][]base.Z{
|
||||||
|
"default": {
|
||||||
|
"mygroup": {},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
wantPending: map[string][]*base.TaskMessage{
|
||||||
|
"default": {
|
||||||
|
h.NewTaskMessageBuilder().SetType("mygroup").SetRetry(3).Build(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "group older than the max-delay should be aggregated",
|
||||||
|
gracePeriod: 2 * time.Second,
|
||||||
|
maxDelay: 4 * time.Second,
|
||||||
|
maxSize: 0, // no maxsize limit
|
||||||
|
aggregateFunc: func(gname string, tasks []*Task) *Task {
|
||||||
|
return NewTask(gname, nil, MaxRetry(len(tasks))) // use max retry to see how many tasks were aggregated
|
||||||
|
},
|
||||||
|
tasks: []*Task{
|
||||||
|
NewTask("task1", nil, Group("mygroup")), // time 0
|
||||||
|
NewTask("task2", nil, Group("mygroup")), // time 1s
|
||||||
|
NewTask("task3", nil, Group("mygroup")), // time 2s
|
||||||
|
NewTask("task4", nil, Group("mygroup")), // time 3s
|
||||||
|
},
|
||||||
|
enqueueFrequency: 1 * time.Second,
|
||||||
|
waitTime: 4 * time.Second,
|
||||||
|
wantGroups: map[string]map[string][]base.Z{
|
||||||
|
"default": {
|
||||||
|
"mygroup": {},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
wantPending: map[string][]*base.TaskMessage{
|
||||||
|
"default": {
|
||||||
|
h.NewTaskMessageBuilder().SetType("mygroup").SetRetry(4).Build(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "group reached the max-size should be aggregated",
|
||||||
|
gracePeriod: 1 * time.Minute,
|
||||||
|
maxDelay: 0, // no maxdelay limit
|
||||||
|
maxSize: 5,
|
||||||
|
aggregateFunc: func(gname string, tasks []*Task) *Task {
|
||||||
|
return NewTask(gname, nil, MaxRetry(len(tasks))) // use max retry to see how many tasks were aggregated
|
||||||
|
},
|
||||||
|
tasks: []*Task{
|
||||||
|
NewTask("task1", nil, Group("mygroup")),
|
||||||
|
NewTask("task2", nil, Group("mygroup")),
|
||||||
|
NewTask("task3", nil, Group("mygroup")),
|
||||||
|
NewTask("task4", nil, Group("mygroup")),
|
||||||
|
NewTask("task5", nil, Group("mygroup")),
|
||||||
|
},
|
||||||
|
enqueueFrequency: 300 * time.Millisecond,
|
||||||
|
waitTime: defaultAggregationCheckInterval * 2,
|
||||||
|
wantGroups: map[string]map[string][]base.Z{
|
||||||
|
"default": {
|
||||||
|
"mygroup": {},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
wantPending: map[string][]*base.TaskMessage{
|
||||||
|
"default": {
|
||||||
|
h.NewTaskMessageBuilder().SetType("mygroup").SetRetry(5).Build(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
h.FlushDB(t, r)
|
||||||
|
|
||||||
|
aggregator := newAggregator(aggregatorParams{
|
||||||
|
logger: testLogger,
|
||||||
|
broker: rdbClient,
|
||||||
|
queues: []string{"default"},
|
||||||
|
gracePeriod: tc.gracePeriod,
|
||||||
|
maxDelay: tc.maxDelay,
|
||||||
|
maxSize: tc.maxSize,
|
||||||
|
groupAggregator: GroupAggregatorFunc(tc.aggregateFunc),
|
||||||
|
})
|
||||||
|
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
aggregator.start(&wg)
|
||||||
|
|
||||||
|
for _, task := range tc.tasks {
|
||||||
|
if _, err := client.Enqueue(task); err != nil {
|
||||||
|
t.Errorf("%s: Client Enqueue failed: %v", tc.desc, err)
|
||||||
|
aggregator.shutdown()
|
||||||
|
wg.Wait()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
time.Sleep(tc.enqueueFrequency)
|
||||||
|
}
|
||||||
|
|
||||||
|
time.Sleep(tc.waitTime)
|
||||||
|
|
||||||
|
for qname, groups := range tc.wantGroups {
|
||||||
|
for gname, want := range groups {
|
||||||
|
gotGroup := h.GetGroupEntries(t, r, qname, gname)
|
||||||
|
if diff := cmp.Diff(want, gotGroup, h.SortZSetEntryOpt); diff != "" {
|
||||||
|
t.Errorf("%s: mismatch found in %q; (-want,+got)\n%s", tc.desc, base.GroupKey(qname, gname), diff)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for qname, want := range tc.wantPending {
|
||||||
|
gotPending := h.GetPendingMessages(t, r, qname)
|
||||||
|
if diff := cmp.Diff(want, gotPending, h.SortMsgOpt, h.IgnoreIDOpt); diff != "" {
|
||||||
|
t.Errorf("%s: mismatch found in %q; (-want,+got)\n%s", tc.desc, base.PendingKey(qname), diff)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
aggregator.shutdown()
|
||||||
|
wg.Wait()
|
||||||
|
}
|
||||||
|
}
|
||||||
343
asynq.go
343
asynq.go
@@ -5,34 +5,226 @@
|
|||||||
package asynq
|
package asynq
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/go-redis/redis/v7"
|
"github.com/redis/go-redis/v9"
|
||||||
|
"github.com/hibiken/asynq/internal/base"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Task represents a unit of work to be performed.
|
// Task represents a unit of work to be performed.
|
||||||
type Task struct {
|
type Task struct {
|
||||||
// Type indicates the type of task to be performed.
|
// typename indicates the type of task to be performed.
|
||||||
Type string
|
typename string
|
||||||
|
|
||||||
// Payload holds data needed to perform the task.
|
// payload holds data needed to perform the task.
|
||||||
Payload Payload
|
payload []byte
|
||||||
|
|
||||||
|
// opts holds options for the task.
|
||||||
|
opts []Option
|
||||||
|
|
||||||
|
// w is the ResultWriter for the task.
|
||||||
|
w *ResultWriter
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewTask returns a new Task given a type name and payload data.
|
func (t *Task) Type() string { return t.typename }
|
||||||
|
func (t *Task) Payload() []byte { return t.payload }
|
||||||
|
|
||||||
|
// ResultWriter returns a pointer to the ResultWriter associated with the task.
|
||||||
//
|
//
|
||||||
// The payload values must be serializable.
|
// Nil pointer is returned if called on a newly created task (i.e. task created by calling NewTask).
|
||||||
func NewTask(typename string, payload map[string]interface{}) *Task {
|
// Only the tasks passed to Handler.ProcessTask have a valid ResultWriter pointer.
|
||||||
|
func (t *Task) ResultWriter() *ResultWriter { return t.w }
|
||||||
|
|
||||||
|
// NewTask returns a new Task given a type name and payload data.
|
||||||
|
// Options can be passed to configure task processing behavior.
|
||||||
|
func NewTask(typename string, payload []byte, opts ...Option) *Task {
|
||||||
return &Task{
|
return &Task{
|
||||||
Type: typename,
|
typename: typename,
|
||||||
Payload: Payload{payload},
|
payload: payload,
|
||||||
|
opts: opts,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// newTask creates a task with the given typename, payload and ResultWriter.
|
||||||
|
func newTask(typename string, payload []byte, w *ResultWriter) *Task {
|
||||||
|
return &Task{
|
||||||
|
typename: typename,
|
||||||
|
payload: payload,
|
||||||
|
w: w,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A TaskInfo describes a task and its metadata.
|
||||||
|
type TaskInfo struct {
|
||||||
|
// ID is the identifier of the task.
|
||||||
|
ID string
|
||||||
|
|
||||||
|
// Queue is the name of the queue in which the task belongs.
|
||||||
|
Queue string
|
||||||
|
|
||||||
|
// Type is the type name of the task.
|
||||||
|
Type string
|
||||||
|
|
||||||
|
// Payload is the payload data of the task.
|
||||||
|
Payload []byte
|
||||||
|
|
||||||
|
// State indicates the task state.
|
||||||
|
State TaskState
|
||||||
|
|
||||||
|
// MaxRetry is the maximum number of times the task can be retried.
|
||||||
|
MaxRetry int
|
||||||
|
|
||||||
|
// Retried is the number of times the task has retried so far.
|
||||||
|
Retried int
|
||||||
|
|
||||||
|
// LastErr is the error message from the last failure.
|
||||||
|
LastErr string
|
||||||
|
|
||||||
|
// LastFailedAt is the time time of the last failure if any.
|
||||||
|
// If the task has no failures, LastFailedAt is zero time (i.e. time.Time{}).
|
||||||
|
LastFailedAt time.Time
|
||||||
|
|
||||||
|
// Timeout is the duration the task can be processed by Handler before being retried,
|
||||||
|
// zero if not specified
|
||||||
|
Timeout time.Duration
|
||||||
|
|
||||||
|
// Deadline is the deadline for the task, zero value if not specified.
|
||||||
|
Deadline time.Time
|
||||||
|
|
||||||
|
// Group is the name of the group in which the task belongs.
|
||||||
|
//
|
||||||
|
// Tasks in the same queue can be grouped together by Group name and will be aggregated into one task
|
||||||
|
// by a Server processing the queue.
|
||||||
|
//
|
||||||
|
// Empty string (default) indicates task does not belong to any groups, and no aggregation will be applied to the task.
|
||||||
|
Group string
|
||||||
|
|
||||||
|
// NextProcessAt is the time the task is scheduled to be processed,
|
||||||
|
// zero if not applicable.
|
||||||
|
NextProcessAt time.Time
|
||||||
|
|
||||||
|
// IsOrphaned describes whether the task is left in active state with no worker processing it.
|
||||||
|
// An orphaned task indicates that the worker has crashed or experienced network failures and was not able to
|
||||||
|
// extend its lease on the task.
|
||||||
|
//
|
||||||
|
// This task will be recovered by running a server against the queue the task is in.
|
||||||
|
// This field is only applicable to tasks with TaskStateActive.
|
||||||
|
IsOrphaned bool
|
||||||
|
|
||||||
|
// Retention is duration of the retention period after the task is successfully processed.
|
||||||
|
Retention time.Duration
|
||||||
|
|
||||||
|
// CompletedAt is the time when the task is processed successfully.
|
||||||
|
// Zero value (i.e. time.Time{}) indicates no value.
|
||||||
|
CompletedAt time.Time
|
||||||
|
|
||||||
|
// Result holds the result data associated with the task.
|
||||||
|
// Use ResultWriter to write result data from the Handler.
|
||||||
|
Result []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
// If t is non-zero, returns time converted from t as unix time in seconds.
|
||||||
|
// If t is zero, returns zero value of time.Time.
|
||||||
|
func fromUnixTimeOrZero(t int64) time.Time {
|
||||||
|
if t == 0 {
|
||||||
|
return time.Time{}
|
||||||
|
}
|
||||||
|
return time.Unix(t, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newTaskInfo(msg *base.TaskMessage, state base.TaskState, nextProcessAt time.Time, result []byte) *TaskInfo {
|
||||||
|
info := TaskInfo{
|
||||||
|
ID: msg.ID,
|
||||||
|
Queue: msg.Queue,
|
||||||
|
Type: msg.Type,
|
||||||
|
Payload: msg.Payload, // Do we need to make a copy?
|
||||||
|
MaxRetry: msg.Retry,
|
||||||
|
Retried: msg.Retried,
|
||||||
|
LastErr: msg.ErrorMsg,
|
||||||
|
Group: msg.GroupKey,
|
||||||
|
Timeout: time.Duration(msg.Timeout) * time.Second,
|
||||||
|
Deadline: fromUnixTimeOrZero(msg.Deadline),
|
||||||
|
Retention: time.Duration(msg.Retention) * time.Second,
|
||||||
|
NextProcessAt: nextProcessAt,
|
||||||
|
LastFailedAt: fromUnixTimeOrZero(msg.LastFailedAt),
|
||||||
|
CompletedAt: fromUnixTimeOrZero(msg.CompletedAt),
|
||||||
|
Result: result,
|
||||||
|
}
|
||||||
|
|
||||||
|
switch state {
|
||||||
|
case base.TaskStateActive:
|
||||||
|
info.State = TaskStateActive
|
||||||
|
case base.TaskStatePending:
|
||||||
|
info.State = TaskStatePending
|
||||||
|
case base.TaskStateScheduled:
|
||||||
|
info.State = TaskStateScheduled
|
||||||
|
case base.TaskStateRetry:
|
||||||
|
info.State = TaskStateRetry
|
||||||
|
case base.TaskStateArchived:
|
||||||
|
info.State = TaskStateArchived
|
||||||
|
case base.TaskStateCompleted:
|
||||||
|
info.State = TaskStateCompleted
|
||||||
|
case base.TaskStateAggregating:
|
||||||
|
info.State = TaskStateAggregating
|
||||||
|
default:
|
||||||
|
panic(fmt.Sprintf("internal error: unknown state: %d", state))
|
||||||
|
}
|
||||||
|
return &info
|
||||||
|
}
|
||||||
|
|
||||||
|
// TaskState denotes the state of a task.
|
||||||
|
type TaskState int
|
||||||
|
|
||||||
|
const (
|
||||||
|
// Indicates that the task is currently being processed by Handler.
|
||||||
|
TaskStateActive TaskState = iota + 1
|
||||||
|
|
||||||
|
// Indicates that the task is ready to be processed by Handler.
|
||||||
|
TaskStatePending
|
||||||
|
|
||||||
|
// Indicates that the task is scheduled to be processed some time in the future.
|
||||||
|
TaskStateScheduled
|
||||||
|
|
||||||
|
// Indicates that the task has previously failed and scheduled to be processed some time in the future.
|
||||||
|
TaskStateRetry
|
||||||
|
|
||||||
|
// Indicates that the task is archived and stored for inspection purposes.
|
||||||
|
TaskStateArchived
|
||||||
|
|
||||||
|
// Indicates that the task is processed successfully and retained until the retention TTL expires.
|
||||||
|
TaskStateCompleted
|
||||||
|
|
||||||
|
// Indicates that the task is waiting in a group to be aggregated into one task.
|
||||||
|
TaskStateAggregating
|
||||||
|
)
|
||||||
|
|
||||||
|
func (s TaskState) String() string {
|
||||||
|
switch s {
|
||||||
|
case TaskStateActive:
|
||||||
|
return "active"
|
||||||
|
case TaskStatePending:
|
||||||
|
return "pending"
|
||||||
|
case TaskStateScheduled:
|
||||||
|
return "scheduled"
|
||||||
|
case TaskStateRetry:
|
||||||
|
return "retry"
|
||||||
|
case TaskStateArchived:
|
||||||
|
return "archived"
|
||||||
|
case TaskStateCompleted:
|
||||||
|
return "completed"
|
||||||
|
case TaskStateAggregating:
|
||||||
|
return "aggregating"
|
||||||
|
}
|
||||||
|
panic("asynq: unknown task state")
|
||||||
|
}
|
||||||
|
|
||||||
// RedisConnOpt is a discriminated union of types that represent Redis connection configuration option.
|
// RedisConnOpt is a discriminated union of types that represent Redis connection configuration option.
|
||||||
//
|
//
|
||||||
// RedisConnOpt represents a sum of following types:
|
// RedisConnOpt represents a sum of following types:
|
||||||
@@ -68,6 +260,26 @@ type RedisClientOpt struct {
|
|||||||
// See: https://redis.io/commands/select.
|
// See: https://redis.io/commands/select.
|
||||||
DB int
|
DB int
|
||||||
|
|
||||||
|
// Dial timeout for establishing new connections.
|
||||||
|
// Default is 5 seconds.
|
||||||
|
DialTimeout time.Duration
|
||||||
|
|
||||||
|
// Timeout for socket reads.
|
||||||
|
// If timeout is reached, read commands will fail with a timeout error
|
||||||
|
// instead of blocking.
|
||||||
|
//
|
||||||
|
// Use value -1 for no timeout and 0 for default.
|
||||||
|
// Default is 3 seconds.
|
||||||
|
ReadTimeout time.Duration
|
||||||
|
|
||||||
|
// Timeout for socket writes.
|
||||||
|
// If timeout is reached, write commands will fail with a timeout error
|
||||||
|
// instead of blocking.
|
||||||
|
//
|
||||||
|
// Use value -1 for no timeout and 0 for default.
|
||||||
|
// Default is ReadTimout.
|
||||||
|
WriteTimeout time.Duration
|
||||||
|
|
||||||
// Maximum number of socket connections.
|
// Maximum number of socket connections.
|
||||||
// Default is 10 connections per every CPU as reported by runtime.NumCPU.
|
// Default is 10 connections per every CPU as reported by runtime.NumCPU.
|
||||||
PoolSize int
|
PoolSize int
|
||||||
@@ -79,13 +291,16 @@ type RedisClientOpt struct {
|
|||||||
|
|
||||||
func (opt RedisClientOpt) MakeRedisClient() interface{} {
|
func (opt RedisClientOpt) MakeRedisClient() interface{} {
|
||||||
return redis.NewClient(&redis.Options{
|
return redis.NewClient(&redis.Options{
|
||||||
Network: opt.Network,
|
Network: opt.Network,
|
||||||
Addr: opt.Addr,
|
Addr: opt.Addr,
|
||||||
Username: opt.Username,
|
Username: opt.Username,
|
||||||
Password: opt.Password,
|
Password: opt.Password,
|
||||||
DB: opt.DB,
|
DB: opt.DB,
|
||||||
PoolSize: opt.PoolSize,
|
DialTimeout: opt.DialTimeout,
|
||||||
TLSConfig: opt.TLSConfig,
|
ReadTimeout: opt.ReadTimeout,
|
||||||
|
WriteTimeout: opt.WriteTimeout,
|
||||||
|
PoolSize: opt.PoolSize,
|
||||||
|
TLSConfig: opt.TLSConfig,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,6 +331,26 @@ type RedisFailoverClientOpt struct {
|
|||||||
// See: https://redis.io/commands/select.
|
// See: https://redis.io/commands/select.
|
||||||
DB int
|
DB int
|
||||||
|
|
||||||
|
// Dial timeout for establishing new connections.
|
||||||
|
// Default is 5 seconds.
|
||||||
|
DialTimeout time.Duration
|
||||||
|
|
||||||
|
// Timeout for socket reads.
|
||||||
|
// If timeout is reached, read commands will fail with a timeout error
|
||||||
|
// instead of blocking.
|
||||||
|
//
|
||||||
|
// Use value -1 for no timeout and 0 for default.
|
||||||
|
// Default is 3 seconds.
|
||||||
|
ReadTimeout time.Duration
|
||||||
|
|
||||||
|
// Timeout for socket writes.
|
||||||
|
// If timeout is reached, write commands will fail with a timeout error
|
||||||
|
// instead of blocking.
|
||||||
|
//
|
||||||
|
// Use value -1 for no timeout and 0 for default.
|
||||||
|
// Default is ReadTimeout
|
||||||
|
WriteTimeout time.Duration
|
||||||
|
|
||||||
// Maximum number of socket connections.
|
// Maximum number of socket connections.
|
||||||
// Default is 10 connections per every CPU as reported by runtime.NumCPU.
|
// Default is 10 connections per every CPU as reported by runtime.NumCPU.
|
||||||
PoolSize int
|
PoolSize int
|
||||||
@@ -133,6 +368,9 @@ func (opt RedisFailoverClientOpt) MakeRedisClient() interface{} {
|
|||||||
Username: opt.Username,
|
Username: opt.Username,
|
||||||
Password: opt.Password,
|
Password: opt.Password,
|
||||||
DB: opt.DB,
|
DB: opt.DB,
|
||||||
|
DialTimeout: opt.DialTimeout,
|
||||||
|
ReadTimeout: opt.ReadTimeout,
|
||||||
|
WriteTimeout: opt.WriteTimeout,
|
||||||
PoolSize: opt.PoolSize,
|
PoolSize: opt.PoolSize,
|
||||||
TLSConfig: opt.TLSConfig,
|
TLSConfig: opt.TLSConfig,
|
||||||
})
|
})
|
||||||
@@ -157,6 +395,26 @@ type RedisClusterClientOpt struct {
|
|||||||
// See: https://redis.io/commands/auth.
|
// See: https://redis.io/commands/auth.
|
||||||
Password string
|
Password string
|
||||||
|
|
||||||
|
// Dial timeout for establishing new connections.
|
||||||
|
// Default is 5 seconds.
|
||||||
|
DialTimeout time.Duration
|
||||||
|
|
||||||
|
// Timeout for socket reads.
|
||||||
|
// If timeout is reached, read commands will fail with a timeout error
|
||||||
|
// instead of blocking.
|
||||||
|
//
|
||||||
|
// Use value -1 for no timeout and 0 for default.
|
||||||
|
// Default is 3 seconds.
|
||||||
|
ReadTimeout time.Duration
|
||||||
|
|
||||||
|
// Timeout for socket writes.
|
||||||
|
// If timeout is reached, write commands will fail with a timeout error
|
||||||
|
// instead of blocking.
|
||||||
|
//
|
||||||
|
// Use value -1 for no timeout and 0 for default.
|
||||||
|
// Default is ReadTimeout.
|
||||||
|
WriteTimeout time.Duration
|
||||||
|
|
||||||
// TLS Config used to connect to a server.
|
// TLS Config used to connect to a server.
|
||||||
// TLS will be negotiated only if this field is set.
|
// TLS will be negotiated only if this field is set.
|
||||||
TLSConfig *tls.Config
|
TLSConfig *tls.Config
|
||||||
@@ -168,6 +426,9 @@ func (opt RedisClusterClientOpt) MakeRedisClient() interface{} {
|
|||||||
MaxRedirects: opt.MaxRedirects,
|
MaxRedirects: opt.MaxRedirects,
|
||||||
Username: opt.Username,
|
Username: opt.Username,
|
||||||
Password: opt.Password,
|
Password: opt.Password,
|
||||||
|
DialTimeout: opt.DialTimeout,
|
||||||
|
ReadTimeout: opt.ReadTimeout,
|
||||||
|
WriteTimeout: opt.WriteTimeout,
|
||||||
TLSConfig: opt.TLSConfig,
|
TLSConfig: opt.TLSConfig,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -175,9 +436,10 @@ func (opt RedisClusterClientOpt) MakeRedisClient() interface{} {
|
|||||||
// ParseRedisURI parses redis uri string and returns RedisConnOpt if uri is valid.
|
// ParseRedisURI parses redis uri string and returns RedisConnOpt if uri is valid.
|
||||||
// It returns a non-nil error if uri cannot be parsed.
|
// It returns a non-nil error if uri cannot be parsed.
|
||||||
//
|
//
|
||||||
// Three URI schemes are supported, which are redis:, redis-socket:, and redis-sentinel:.
|
// Three URI schemes are supported, which are redis:, rediss:, redis-socket:, and redis-sentinel:.
|
||||||
// Supported formats are:
|
// Supported formats are:
|
||||||
// redis://[:password@]host[:port][/dbnumber]
|
// redis://[:password@]host[:port][/dbnumber]
|
||||||
|
// rediss://[:password@]host[:port][/dbnumber]
|
||||||
// redis-socket://[:password@]path[?db=dbnumber]
|
// redis-socket://[:password@]path[?db=dbnumber]
|
||||||
// redis-sentinel://[:password@]host1[:port][,host2:[:port]][,hostN:[:port]][?master=masterName]
|
// redis-sentinel://[:password@]host1[:port][,host2:[:port]][,hostN:[:port]][?master=masterName]
|
||||||
func ParseRedisURI(uri string) (RedisConnOpt, error) {
|
func ParseRedisURI(uri string) (RedisConnOpt, error) {
|
||||||
@@ -186,7 +448,7 @@ func ParseRedisURI(uri string) (RedisConnOpt, error) {
|
|||||||
return nil, fmt.Errorf("asynq: could not parse redis uri: %v", err)
|
return nil, fmt.Errorf("asynq: could not parse redis uri: %v", err)
|
||||||
}
|
}
|
||||||
switch u.Scheme {
|
switch u.Scheme {
|
||||||
case "redis":
|
case "redis", "rediss":
|
||||||
return parseRedisURI(u)
|
return parseRedisURI(u)
|
||||||
case "redis-socket":
|
case "redis-socket":
|
||||||
return parseRedisSocketURI(u)
|
return parseRedisSocketURI(u)
|
||||||
@@ -200,6 +462,8 @@ func ParseRedisURI(uri string) (RedisConnOpt, error) {
|
|||||||
func parseRedisURI(u *url.URL) (RedisConnOpt, error) {
|
func parseRedisURI(u *url.URL) (RedisConnOpt, error) {
|
||||||
var db int
|
var db int
|
||||||
var err error
|
var err error
|
||||||
|
var redisConnOpt RedisClientOpt
|
||||||
|
|
||||||
if len(u.Path) > 0 {
|
if len(u.Path) > 0 {
|
||||||
xs := strings.Split(strings.Trim(u.Path, "/"), "/")
|
xs := strings.Split(strings.Trim(u.Path, "/"), "/")
|
||||||
db, err = strconv.Atoi(xs[0])
|
db, err = strconv.Atoi(xs[0])
|
||||||
@@ -211,7 +475,20 @@ func parseRedisURI(u *url.URL) (RedisConnOpt, error) {
|
|||||||
if v, ok := u.User.Password(); ok {
|
if v, ok := u.User.Password(); ok {
|
||||||
password = v
|
password = v
|
||||||
}
|
}
|
||||||
return RedisClientOpt{Addr: u.Host, DB: db, Password: password}, nil
|
|
||||||
|
if u.Scheme == "rediss" {
|
||||||
|
h, _, err := net.SplitHostPort(u.Host)
|
||||||
|
if err != nil {
|
||||||
|
h = u.Host
|
||||||
|
}
|
||||||
|
redisConnOpt.TLSConfig = &tls.Config{ServerName: h}
|
||||||
|
}
|
||||||
|
|
||||||
|
redisConnOpt.Addr = u.Host
|
||||||
|
redisConnOpt.Password = password
|
||||||
|
redisConnOpt.DB = db
|
||||||
|
|
||||||
|
return redisConnOpt, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseRedisSocketURI(u *url.URL) (RedisConnOpt, error) {
|
func parseRedisSocketURI(u *url.URL) (RedisConnOpt, error) {
|
||||||
@@ -242,5 +519,29 @@ func parseRedisSentinelURI(u *url.URL) (RedisConnOpt, error) {
|
|||||||
if v, ok := u.User.Password(); ok {
|
if v, ok := u.User.Password(); ok {
|
||||||
password = v
|
password = v
|
||||||
}
|
}
|
||||||
return RedisFailoverClientOpt{MasterName: master, SentinelAddrs: addrs, Password: password}, nil
|
return RedisFailoverClientOpt{MasterName: master, SentinelAddrs: addrs, SentinelPassword: password}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResultWriter is a client interface to write result data for a task.
|
||||||
|
// It writes the data to the redis instance the server is connected to.
|
||||||
|
type ResultWriter struct {
|
||||||
|
id string // task ID this writer is responsible for
|
||||||
|
qname string // queue name the task belongs to
|
||||||
|
broker base.Broker
|
||||||
|
ctx context.Context // context associated with the task
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write writes the given data as a result of the task the ResultWriter is associated with.
|
||||||
|
func (w *ResultWriter) Write(data []byte) (n int, err error) {
|
||||||
|
select {
|
||||||
|
case <-w.ctx.Done():
|
||||||
|
return 0, fmt.Errorf("failed to result task result: %v", w.ctx.Err())
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
return w.broker.WriteResult(w.qname, w.id, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TaskID returns the ID of the task the ResultWriter is associated with.
|
||||||
|
func (w *ResultWriter) TaskID() string {
|
||||||
|
return w.id
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,15 +5,17 @@
|
|||||||
package asynq
|
package asynq
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/tls"
|
||||||
"flag"
|
"flag"
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/go-redis/redis/v7"
|
"github.com/redis/go-redis/v9"
|
||||||
"github.com/google/go-cmp/cmp"
|
"github.com/google/go-cmp/cmp"
|
||||||
h "github.com/hibiken/asynq/internal/asynqtest"
|
"github.com/google/go-cmp/cmp/cmpopts"
|
||||||
"github.com/hibiken/asynq/internal/log"
|
"github.com/hibiken/asynq/internal/log"
|
||||||
|
h "github.com/hibiken/asynq/internal/testutil"
|
||||||
)
|
)
|
||||||
|
|
||||||
//============================================================================
|
//============================================================================
|
||||||
@@ -85,7 +87,7 @@ func getRedisConnOpt(tb testing.TB) RedisConnOpt {
|
|||||||
var sortTaskOpt = cmp.Transformer("SortMsg", func(in []*Task) []*Task {
|
var sortTaskOpt = cmp.Transformer("SortMsg", func(in []*Task) []*Task {
|
||||||
out := append([]*Task(nil), in...) // Copy input to avoid mutating it
|
out := append([]*Task(nil), in...) // Copy input to avoid mutating it
|
||||||
sort.Slice(out, func(i, j int) bool {
|
sort.Slice(out, func(i, j int) bool {
|
||||||
return out[i].Type < out[j].Type
|
return out[i].Type() < out[j].Type()
|
||||||
})
|
})
|
||||||
return out
|
return out
|
||||||
})
|
})
|
||||||
@@ -99,6 +101,10 @@ func TestParseRedisURI(t *testing.T) {
|
|||||||
"redis://localhost:6379",
|
"redis://localhost:6379",
|
||||||
RedisClientOpt{Addr: "localhost:6379"},
|
RedisClientOpt{Addr: "localhost:6379"},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"rediss://localhost:6379",
|
||||||
|
RedisClientOpt{Addr: "localhost:6379", TLSConfig: &tls.Config{ServerName: "localhost"}},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"redis://localhost:6379/3",
|
"redis://localhost:6379/3",
|
||||||
RedisClientOpt{Addr: "localhost:6379", DB: 3},
|
RedisClientOpt{Addr: "localhost:6379", DB: 3},
|
||||||
@@ -137,9 +143,9 @@ func TestParseRedisURI(t *testing.T) {
|
|||||||
{
|
{
|
||||||
"redis-sentinel://:mypassword@localhost:5000,localhost:5001,localhost:5002?master=mymaster",
|
"redis-sentinel://:mypassword@localhost:5000,localhost:5001,localhost:5002?master=mymaster",
|
||||||
RedisFailoverClientOpt{
|
RedisFailoverClientOpt{
|
||||||
MasterName: "mymaster",
|
MasterName: "mymaster",
|
||||||
SentinelAddrs: []string{"localhost:5000", "localhost:5001", "localhost:5002"},
|
SentinelAddrs: []string{"localhost:5000", "localhost:5001", "localhost:5002"},
|
||||||
Password: "mypassword",
|
SentinelPassword: "mypassword",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -151,7 +157,7 @@ func TestParseRedisURI(t *testing.T) {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if diff := cmp.Diff(tc.want, got); diff != "" {
|
if diff := cmp.Diff(tc.want, got, cmpopts.IgnoreUnexported(tls.Config{})); diff != "" {
|
||||||
t.Errorf("ParseRedisURI(%q) = %+v, want %+v\n(-want,+got)\n%s", tc.uri, got, tc.want, diff)
|
t.Errorf("ParseRedisURI(%q) = %+v, want %+v\n(-want,+got)\n%s", tc.uri, got, tc.want, diff)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,12 +6,24 @@ package asynq
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
h "github.com/hibiken/asynq/internal/testutil"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Creates a new task of type "task<n>" with payload {"data": n}.
|
||||||
|
func makeTask(n int) *Task {
|
||||||
|
b, err := json.Marshal(map[string]int{"data": n})
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return NewTask(fmt.Sprintf("task%d", n), b)
|
||||||
|
}
|
||||||
|
|
||||||
// Simple E2E Benchmark testing with no scheduled tasks and retries.
|
// Simple E2E Benchmark testing with no scheduled tasks and retries.
|
||||||
func BenchmarkEndToEndSimple(b *testing.B) {
|
func BenchmarkEndToEndSimple(b *testing.B) {
|
||||||
const count = 100000
|
const count = 100000
|
||||||
@@ -29,8 +41,7 @@ func BenchmarkEndToEndSimple(b *testing.B) {
|
|||||||
})
|
})
|
||||||
// Create a bunch of tasks
|
// Create a bunch of tasks
|
||||||
for i := 0; i < count; i++ {
|
for i := 0; i < count; i++ {
|
||||||
t := NewTask(fmt.Sprintf("task%d", i), map[string]interface{}{"data": i})
|
if _, err := client.Enqueue(makeTask(i)); err != nil {
|
||||||
if _, err := client.Enqueue(t); err != nil {
|
|
||||||
b.Fatalf("could not enqueue a task: %v", err)
|
b.Fatalf("could not enqueue a task: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -70,14 +81,12 @@ func BenchmarkEndToEnd(b *testing.B) {
|
|||||||
})
|
})
|
||||||
// Create a bunch of tasks
|
// Create a bunch of tasks
|
||||||
for i := 0; i < count; i++ {
|
for i := 0; i < count; i++ {
|
||||||
t := NewTask(fmt.Sprintf("task%d", i), map[string]interface{}{"data": i})
|
if _, err := client.Enqueue(makeTask(i)); err != nil {
|
||||||
if _, err := client.Enqueue(t); err != nil {
|
|
||||||
b.Fatalf("could not enqueue a task: %v", err)
|
b.Fatalf("could not enqueue a task: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for i := 0; i < count; i++ {
|
for i := 0; i < count; i++ {
|
||||||
t := NewTask(fmt.Sprintf("scheduled%d", i), map[string]interface{}{"data": i})
|
if _, err := client.Enqueue(makeTask(i), ProcessIn(1*time.Second)); err != nil {
|
||||||
if _, err := client.Enqueue(t, ProcessIn(1*time.Second)); err != nil {
|
|
||||||
b.Fatalf("could not enqueue a task: %v", err)
|
b.Fatalf("could not enqueue a task: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -86,13 +95,18 @@ func BenchmarkEndToEnd(b *testing.B) {
|
|||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
wg.Add(count * 2)
|
wg.Add(count * 2)
|
||||||
handler := func(ctx context.Context, t *Task) error {
|
handler := func(ctx context.Context, t *Task) error {
|
||||||
n, err := t.Payload.GetInt("data")
|
var p map[string]int
|
||||||
if err != nil {
|
if err := json.Unmarshal(t.Payload(), &p); err != nil {
|
||||||
b.Logf("internal error: %v", err)
|
b.Logf("internal error: %v", err)
|
||||||
}
|
}
|
||||||
|
n, ok := p["data"]
|
||||||
|
if !ok {
|
||||||
|
n = 1
|
||||||
|
b.Logf("internal error: could not get data from payload")
|
||||||
|
}
|
||||||
retried, ok := GetRetryCount(ctx)
|
retried, ok := GetRetryCount(ctx)
|
||||||
if !ok {
|
if !ok {
|
||||||
b.Logf("internal error: %v", err)
|
b.Logf("internal error: could not get retry count from context")
|
||||||
}
|
}
|
||||||
// Fail 1% of tasks for the first attempt.
|
// Fail 1% of tasks for the first attempt.
|
||||||
if retried == 0 && n%100 == 0 {
|
if retried == 0 && n%100 == 0 {
|
||||||
@@ -136,20 +150,17 @@ func BenchmarkEndToEndMultipleQueues(b *testing.B) {
|
|||||||
})
|
})
|
||||||
// Create a bunch of tasks
|
// Create a bunch of tasks
|
||||||
for i := 0; i < highCount; i++ {
|
for i := 0; i < highCount; i++ {
|
||||||
t := NewTask(fmt.Sprintf("task%d", i), map[string]interface{}{"data": i})
|
if _, err := client.Enqueue(makeTask(i), Queue("high")); err != nil {
|
||||||
if _, err := client.Enqueue(t, Queue("high")); err != nil {
|
|
||||||
b.Fatalf("could not enqueue a task: %v", err)
|
b.Fatalf("could not enqueue a task: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for i := 0; i < defaultCount; i++ {
|
for i := 0; i < defaultCount; i++ {
|
||||||
t := NewTask(fmt.Sprintf("task%d", i), map[string]interface{}{"data": i})
|
if _, err := client.Enqueue(makeTask(i)); err != nil {
|
||||||
if _, err := client.Enqueue(t); err != nil {
|
|
||||||
b.Fatalf("could not enqueue a task: %v", err)
|
b.Fatalf("could not enqueue a task: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for i := 0; i < lowCount; i++ {
|
for i := 0; i < lowCount; i++ {
|
||||||
t := NewTask(fmt.Sprintf("task%d", i), map[string]interface{}{"data": i})
|
if _, err := client.Enqueue(makeTask(i), Queue("low")); err != nil {
|
||||||
if _, err := client.Enqueue(t, Queue("low")); err != nil {
|
|
||||||
b.Fatalf("could not enqueue a task: %v", err)
|
b.Fatalf("could not enqueue a task: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -190,15 +201,13 @@ func BenchmarkClientWhileServerRunning(b *testing.B) {
|
|||||||
})
|
})
|
||||||
// Enqueue 10,000 tasks.
|
// Enqueue 10,000 tasks.
|
||||||
for i := 0; i < count; i++ {
|
for i := 0; i < count; i++ {
|
||||||
t := NewTask(fmt.Sprintf("task%d", i), map[string]interface{}{"data": i})
|
if _, err := client.Enqueue(makeTask(i)); err != nil {
|
||||||
if _, err := client.Enqueue(t); err != nil {
|
|
||||||
b.Fatalf("could not enqueue a task: %v", err)
|
b.Fatalf("could not enqueue a task: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Schedule 10,000 tasks.
|
// Schedule 10,000 tasks.
|
||||||
for i := 0; i < count; i++ {
|
for i := 0; i < count; i++ {
|
||||||
t := NewTask(fmt.Sprintf("scheduled%d", i), map[string]interface{}{"data": i})
|
if _, err := client.Enqueue(makeTask(i), ProcessIn(1*time.Second)); err != nil {
|
||||||
if _, err := client.Enqueue(t, ProcessIn(1*time.Second)); err != nil {
|
|
||||||
b.Fatalf("could not enqueue a task: %v", err)
|
b.Fatalf("could not enqueue a task: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -213,7 +222,7 @@ func BenchmarkClientWhileServerRunning(b *testing.B) {
|
|||||||
b.Log("Starting enqueueing")
|
b.Log("Starting enqueueing")
|
||||||
enqueued := 0
|
enqueued := 0
|
||||||
for enqueued < 100000 {
|
for enqueued < 100000 {
|
||||||
t := NewTask(fmt.Sprintf("enqueued%d", enqueued), map[string]interface{}{"data": enqueued})
|
t := NewTask(fmt.Sprintf("enqueued%d", enqueued), h.JSON(map[string]interface{}{"data": enqueued}))
|
||||||
if _, err := client.Enqueue(t); err != nil {
|
if _, err := client.Enqueue(t); err != nil {
|
||||||
b.Logf("could not enqueue task %d: %v", enqueued, err)
|
b.Logf("could not enqueue task %d: %v", enqueued, err)
|
||||||
continue
|
continue
|
||||||
|
|||||||
279
client.go
279
client.go
@@ -5,16 +5,16 @@
|
|||||||
package asynq
|
package asynq
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/go-redis/redis/v7"
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"github.com/hibiken/asynq/internal/base"
|
"github.com/hibiken/asynq/internal/base"
|
||||||
|
"github.com/hibiken/asynq/internal/errors"
|
||||||
"github.com/hibiken/asynq/internal/rdb"
|
"github.com/hibiken/asynq/internal/rdb"
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
)
|
)
|
||||||
|
|
||||||
// A Client is responsible for scheduling tasks.
|
// A Client is responsible for scheduling tasks.
|
||||||
@@ -24,22 +24,27 @@ import (
|
|||||||
//
|
//
|
||||||
// Clients are safe for concurrent use by multiple goroutines.
|
// Clients are safe for concurrent use by multiple goroutines.
|
||||||
type Client struct {
|
type Client struct {
|
||||||
mu sync.Mutex
|
broker base.Broker
|
||||||
opts map[string][]Option
|
// When a Client has been created with an existing Redis connection, we do
|
||||||
rdb *rdb.RDB
|
// not want to close it.
|
||||||
|
sharedConnection bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewClient returns a new Client instance given a redis connection option.
|
// NewClient returns a new Client instance given a redis connection option.
|
||||||
func NewClient(r RedisConnOpt) *Client {
|
func NewClient(r RedisConnOpt) *Client {
|
||||||
c, ok := r.MakeRedisClient().(redis.UniversalClient)
|
redisClient, ok := r.MakeRedisClient().(redis.UniversalClient)
|
||||||
if !ok {
|
if !ok {
|
||||||
panic(fmt.Sprintf("asynq: unsupported RedisConnOpt type %T", r))
|
panic(fmt.Sprintf("asynq: unsupported RedisConnOpt type %T", r))
|
||||||
}
|
}
|
||||||
rdb := rdb.NewRDB(c)
|
client := NewClientFromRedisClient(redisClient)
|
||||||
return &Client{
|
client.sharedConnection = false
|
||||||
opts: make(map[string][]Option),
|
return client
|
||||||
rdb: rdb,
|
}
|
||||||
}
|
|
||||||
|
// NewClientFromRedisClient returns a new instance of Client given a redis.UniversalClient
|
||||||
|
// Warning: The underlying redis connection pool will not be closed by Asynq, you are responsible for closing it.
|
||||||
|
func NewClientFromRedisClient(c redis.UniversalClient) *Client {
|
||||||
|
return &Client{broker: rdb.NewRDB(c), sharedConnection: true}
|
||||||
}
|
}
|
||||||
|
|
||||||
type OptionType int
|
type OptionType int
|
||||||
@@ -52,6 +57,9 @@ const (
|
|||||||
UniqueOpt
|
UniqueOpt
|
||||||
ProcessAtOpt
|
ProcessAtOpt
|
||||||
ProcessInOpt
|
ProcessInOpt
|
||||||
|
TaskIDOpt
|
||||||
|
RetentionOpt
|
||||||
|
GroupOpt
|
||||||
)
|
)
|
||||||
|
|
||||||
// Option specifies the task processing behavior.
|
// Option specifies the task processing behavior.
|
||||||
@@ -70,11 +78,14 @@ type Option interface {
|
|||||||
type (
|
type (
|
||||||
retryOption int
|
retryOption int
|
||||||
queueOption string
|
queueOption string
|
||||||
|
taskIDOption string
|
||||||
timeoutOption time.Duration
|
timeoutOption time.Duration
|
||||||
deadlineOption time.Time
|
deadlineOption time.Time
|
||||||
uniqueOption time.Duration
|
uniqueOption time.Duration
|
||||||
processAtOption time.Time
|
processAtOption time.Time
|
||||||
processInOption time.Duration
|
processInOption time.Duration
|
||||||
|
retentionOption time.Duration
|
||||||
|
groupOption string
|
||||||
)
|
)
|
||||||
|
|
||||||
// MaxRetry returns an option to specify the max number of times
|
// MaxRetry returns an option to specify the max number of times
|
||||||
@@ -93,15 +104,22 @@ func (n retryOption) Type() OptionType { return MaxRetryOpt }
|
|||||||
func (n retryOption) Value() interface{} { return int(n) }
|
func (n retryOption) Value() interface{} { return int(n) }
|
||||||
|
|
||||||
// Queue returns an option to specify the queue to enqueue the task into.
|
// Queue returns an option to specify the queue to enqueue the task into.
|
||||||
//
|
func Queue(name string) Option {
|
||||||
// Queue name is case-insensitive and the lowercased version is used.
|
return queueOption(name)
|
||||||
func Queue(qname string) Option {
|
|
||||||
return queueOption(strings.ToLower(qname))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (qname queueOption) String() string { return fmt.Sprintf("Queue(%q)", string(qname)) }
|
func (name queueOption) String() string { return fmt.Sprintf("Queue(%q)", string(name)) }
|
||||||
func (qname queueOption) Type() OptionType { return QueueOpt }
|
func (name queueOption) Type() OptionType { return QueueOpt }
|
||||||
func (qname queueOption) Value() interface{} { return string(qname) }
|
func (name queueOption) Value() interface{} { return string(name) }
|
||||||
|
|
||||||
|
// TaskID returns an option to specify the task ID.
|
||||||
|
func TaskID(id string) Option {
|
||||||
|
return taskIDOption(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (id taskIDOption) String() string { return fmt.Sprintf("TaskID(%q)", string(id)) }
|
||||||
|
func (id taskIDOption) Type() OptionType { return TaskIDOpt }
|
||||||
|
func (id taskIDOption) Value() interface{} { return string(id) }
|
||||||
|
|
||||||
// Timeout returns an option to specify how long a task may run.
|
// Timeout returns an option to specify how long a task may run.
|
||||||
// If the timeout elapses before the Handler returns, then the task
|
// If the timeout elapses before the Handler returns, then the task
|
||||||
@@ -137,13 +155,15 @@ func (t deadlineOption) Value() interface{} { return time.Time(t) }
|
|||||||
|
|
||||||
// Unique returns an option to enqueue a task only if the given task is unique.
|
// Unique returns an option to enqueue a task only if the given task is unique.
|
||||||
// Task enqueued with this option is guaranteed to be unique within the given ttl.
|
// Task enqueued with this option is guaranteed to be unique within the given ttl.
|
||||||
// Once the task gets processed successfully or once the TTL has expired, another task with the same uniqueness may be enqueued.
|
// Once the task gets processed successfully or once the TTL has expired,
|
||||||
|
// another task with the same uniqueness may be enqueued.
|
||||||
// ErrDuplicateTask error is returned when enqueueing a duplicate task.
|
// ErrDuplicateTask error is returned when enqueueing a duplicate task.
|
||||||
|
// TTL duration must be greater than or equal to 1 second.
|
||||||
//
|
//
|
||||||
// Uniqueness of a task is based on the following properties:
|
// Uniqueness of a task is based on the following properties:
|
||||||
// - Task Type
|
// - Task Type
|
||||||
// - Task Payload
|
// - Task Payload
|
||||||
// - Queue Name
|
// - Queue Name
|
||||||
func Unique(ttl time.Duration) Option {
|
func Unique(ttl time.Duration) Option {
|
||||||
return uniqueOption(ttl)
|
return uniqueOption(ttl)
|
||||||
}
|
}
|
||||||
@@ -176,19 +196,47 @@ func (d processInOption) String() string { return fmt.Sprintf("ProcessIn(%v)
|
|||||||
func (d processInOption) Type() OptionType { return ProcessInOpt }
|
func (d processInOption) Type() OptionType { return ProcessInOpt }
|
||||||
func (d processInOption) Value() interface{} { return time.Duration(d) }
|
func (d processInOption) Value() interface{} { return time.Duration(d) }
|
||||||
|
|
||||||
|
// Retention returns an option to specify the duration of retention period for the task.
|
||||||
|
// If this option is provided, the task will be stored as a completed task after successful processing.
|
||||||
|
// A completed task will be deleted after the specified duration elapses.
|
||||||
|
func Retention(d time.Duration) Option {
|
||||||
|
return retentionOption(d)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ttl retentionOption) String() string { return fmt.Sprintf("Retention(%v)", time.Duration(ttl)) }
|
||||||
|
func (ttl retentionOption) Type() OptionType { return RetentionOpt }
|
||||||
|
func (ttl retentionOption) Value() interface{} { return time.Duration(ttl) }
|
||||||
|
|
||||||
|
// Group returns an option to specify the group used for the task.
|
||||||
|
// Tasks in a given queue with the same group will be aggregated into one task before passed to Handler.
|
||||||
|
func Group(name string) Option {
|
||||||
|
return groupOption(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (name groupOption) String() string { return fmt.Sprintf("Group(%q)", string(name)) }
|
||||||
|
func (name groupOption) Type() OptionType { return GroupOpt }
|
||||||
|
func (name groupOption) Value() interface{} { return string(name) }
|
||||||
|
|
||||||
// ErrDuplicateTask indicates that the given task could not be enqueued since it's a duplicate of another task.
|
// ErrDuplicateTask indicates that the given task could not be enqueued since it's a duplicate of another task.
|
||||||
//
|
//
|
||||||
// ErrDuplicateTask error only applies to tasks enqueued with a Unique option.
|
// ErrDuplicateTask error only applies to tasks enqueued with a Unique option.
|
||||||
var ErrDuplicateTask = errors.New("task already exists")
|
var ErrDuplicateTask = errors.New("task already exists")
|
||||||
|
|
||||||
|
// ErrTaskIDConflict indicates that the given task could not be enqueued since its task ID already exists.
|
||||||
|
//
|
||||||
|
// ErrTaskIDConflict error only applies to tasks enqueued with a TaskID option.
|
||||||
|
var ErrTaskIDConflict = errors.New("task ID conflicts with another task")
|
||||||
|
|
||||||
type option struct {
|
type option struct {
|
||||||
retry int
|
retry int
|
||||||
queue string
|
queue string
|
||||||
|
taskID string
|
||||||
timeout time.Duration
|
timeout time.Duration
|
||||||
deadline time.Time
|
deadline time.Time
|
||||||
uniqueTTL time.Duration
|
uniqueTTL time.Duration
|
||||||
processAt time.Time
|
processAt time.Time
|
||||||
|
retention time.Duration
|
||||||
|
group string
|
||||||
}
|
}
|
||||||
|
|
||||||
// composeOptions merges user provided options into the default options
|
// composeOptions merges user provided options into the default options
|
||||||
@@ -199,7 +247,8 @@ func composeOptions(opts ...Option) (option, error) {
|
|||||||
res := option{
|
res := option{
|
||||||
retry: defaultMaxRetry,
|
retry: defaultMaxRetry,
|
||||||
queue: base.DefaultQueueName,
|
queue: base.DefaultQueueName,
|
||||||
timeout: 0, // do not set to deafultTimeout here
|
taskID: uuid.NewString(),
|
||||||
|
timeout: 0, // do not set to defaultTimeout here
|
||||||
deadline: time.Time{},
|
deadline: time.Time{},
|
||||||
processAt: time.Now(),
|
processAt: time.Now(),
|
||||||
}
|
}
|
||||||
@@ -208,21 +257,39 @@ func composeOptions(opts ...Option) (option, error) {
|
|||||||
case retryOption:
|
case retryOption:
|
||||||
res.retry = int(opt)
|
res.retry = int(opt)
|
||||||
case queueOption:
|
case queueOption:
|
||||||
trimmed := strings.TrimSpace(string(opt))
|
qname := string(opt)
|
||||||
if err := base.ValidateQueueName(trimmed); err != nil {
|
if err := base.ValidateQueueName(qname); err != nil {
|
||||||
return option{}, err
|
return option{}, err
|
||||||
}
|
}
|
||||||
res.queue = trimmed
|
res.queue = qname
|
||||||
|
case taskIDOption:
|
||||||
|
id := string(opt)
|
||||||
|
if isBlank(id) {
|
||||||
|
return option{}, errors.New("task ID cannot be empty")
|
||||||
|
}
|
||||||
|
res.taskID = id
|
||||||
case timeoutOption:
|
case timeoutOption:
|
||||||
res.timeout = time.Duration(opt)
|
res.timeout = time.Duration(opt)
|
||||||
case deadlineOption:
|
case deadlineOption:
|
||||||
res.deadline = time.Time(opt)
|
res.deadline = time.Time(opt)
|
||||||
case uniqueOption:
|
case uniqueOption:
|
||||||
res.uniqueTTL = time.Duration(opt)
|
ttl := time.Duration(opt)
|
||||||
|
if ttl < 1*time.Second {
|
||||||
|
return option{}, errors.New("Unique TTL cannot be less than 1s")
|
||||||
|
}
|
||||||
|
res.uniqueTTL = ttl
|
||||||
case processAtOption:
|
case processAtOption:
|
||||||
res.processAt = time.Time(opt)
|
res.processAt = time.Time(opt)
|
||||||
case processInOption:
|
case processInOption:
|
||||||
res.processAt = time.Now().Add(time.Duration(opt))
|
res.processAt = time.Now().Add(time.Duration(opt))
|
||||||
|
case retentionOption:
|
||||||
|
res.retention = time.Duration(opt)
|
||||||
|
case groupOption:
|
||||||
|
key := string(opt)
|
||||||
|
if isBlank(key) {
|
||||||
|
return option{}, errors.New("group key cannot be empty")
|
||||||
|
}
|
||||||
|
res.group = key
|
||||||
default:
|
default:
|
||||||
// ignore unexpected option
|
// ignore unexpected option
|
||||||
}
|
}
|
||||||
@@ -230,6 +297,11 @@ func composeOptions(opts ...Option) (option, error) {
|
|||||||
return res, nil
|
return res, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// isBlank returns true if the given s is empty or consist of all whitespaces.
|
||||||
|
func isBlank(s string) bool {
|
||||||
|
return strings.TrimSpace(s) == ""
|
||||||
|
}
|
||||||
|
|
||||||
const (
|
const (
|
||||||
// Default max retry count used if nothing is specified.
|
// Default max retry count used if nothing is specified.
|
||||||
defaultMaxRetry = 25
|
defaultMaxRetry = 25
|
||||||
@@ -244,71 +316,51 @@ var (
|
|||||||
noDeadline time.Time = time.Unix(0, 0)
|
noDeadline time.Time = time.Unix(0, 0)
|
||||||
)
|
)
|
||||||
|
|
||||||
// SetDefaultOptions sets options to be used for a given task type.
|
|
||||||
// The argument opts specifies the behavior of task processing.
|
|
||||||
// If there are conflicting Option values the last one overrides others.
|
|
||||||
//
|
|
||||||
// Default options can be overridden by options passed at enqueue time.
|
|
||||||
func (c *Client) SetDefaultOptions(taskType string, opts ...Option) {
|
|
||||||
c.mu.Lock()
|
|
||||||
defer c.mu.Unlock()
|
|
||||||
c.opts[taskType] = opts
|
|
||||||
}
|
|
||||||
|
|
||||||
// A Result holds enqueued task's metadata.
|
|
||||||
type Result struct {
|
|
||||||
// ID is a unique identifier for the task.
|
|
||||||
ID string
|
|
||||||
|
|
||||||
// EnqueuedAt is the time the task was enqueued in UTC.
|
|
||||||
EnqueuedAt time.Time
|
|
||||||
|
|
||||||
// ProcessAt indicates when the task should be processed.
|
|
||||||
ProcessAt time.Time
|
|
||||||
|
|
||||||
// Retry is the maximum number of retry for the task.
|
|
||||||
Retry int
|
|
||||||
|
|
||||||
// Queue is a name of the queue the task is enqueued to.
|
|
||||||
Queue string
|
|
||||||
|
|
||||||
// Timeout is the timeout value for the task.
|
|
||||||
// Counting for timeout starts when a worker starts processing the task.
|
|
||||||
// If task processing doesn't complete within the timeout, the task will be retried.
|
|
||||||
// The value zero means no timeout.
|
|
||||||
//
|
|
||||||
// If deadline is set, min(now+timeout, deadline) is used, where the now is the time when
|
|
||||||
// a worker starts processing the task.
|
|
||||||
Timeout time.Duration
|
|
||||||
|
|
||||||
// Deadline is the deadline value for the task.
|
|
||||||
// If task processing doesn't complete before the deadline, the task will be retried.
|
|
||||||
// The value time.Unix(0, 0) means no deadline.
|
|
||||||
//
|
|
||||||
// If timeout is set, min(now+timeout, deadline) is used, where the now is the time when
|
|
||||||
// a worker starts processing the task.
|
|
||||||
Deadline time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close closes the connection with redis.
|
// Close closes the connection with redis.
|
||||||
func (c *Client) Close() error {
|
func (c *Client) Close() error {
|
||||||
return c.rdb.Close()
|
if c.sharedConnection {
|
||||||
|
return fmt.Errorf("redis connection is shared so the Client can't be closed through asynq")
|
||||||
|
}
|
||||||
|
return c.broker.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Enqueue enqueues the given task to be processed asynchronously.
|
// Enqueue enqueues the given task to a queue.
|
||||||
//
|
//
|
||||||
// Enqueue returns nil if the task is enqueued successfully, otherwise returns a non-nil error.
|
// Enqueue returns TaskInfo and nil error if the task is enqueued successfully, otherwise returns a non-nil error.
|
||||||
//
|
//
|
||||||
// The argument opts specifies the behavior of task processing.
|
// The argument opts specifies the behavior of task processing.
|
||||||
// If there are conflicting Option values the last one overrides others.
|
// If there are conflicting Option values the last one overrides others.
|
||||||
// By deafult, max retry is set to 25 and timeout is set to 30 minutes.
|
// Any options provided to NewTask can be overridden by options passed to Enqueue.
|
||||||
// If no ProcessAt or ProcessIn options are passed, the task will be processed immediately.
|
// By default, max retry is set to 25 and timeout is set to 30 minutes.
|
||||||
func (c *Client) Enqueue(task *Task, opts ...Option) (*Result, error) {
|
//
|
||||||
c.mu.Lock()
|
// If no ProcessAt or ProcessIn options are provided, the task will be pending immediately.
|
||||||
if defaults, ok := c.opts[task.Type]; ok {
|
//
|
||||||
opts = append(defaults, opts...)
|
// Enqueue uses context.Background internally; to specify the context, use EnqueueContext.
|
||||||
|
func (c *Client) Enqueue(task *Task, opts ...Option) (*TaskInfo, error) {
|
||||||
|
return c.EnqueueContext(context.Background(), task, opts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// EnqueueContext enqueues the given task to a queue.
|
||||||
|
//
|
||||||
|
// EnqueueContext returns TaskInfo and nil error if the task is enqueued successfully, otherwise returns a non-nil error.
|
||||||
|
//
|
||||||
|
// The argument opts specifies the behavior of task processing.
|
||||||
|
// If there are conflicting Option values the last one overrides others.
|
||||||
|
// Any options provided to NewTask can be overridden by options passed to Enqueue.
|
||||||
|
// By default, max retry is set to 25 and timeout is set to 30 minutes.
|
||||||
|
//
|
||||||
|
// If no ProcessAt or ProcessIn options are provided, the task will be pending immediately.
|
||||||
|
//
|
||||||
|
// The first argument context applies to the enqueue operation. To specify task timeout and deadline, use Timeout and Deadline option instead.
|
||||||
|
func (c *Client) EnqueueContext(ctx context.Context, task *Task, opts ...Option) (*TaskInfo, error) {
|
||||||
|
if task == nil {
|
||||||
|
return nil, fmt.Errorf("task cannot be nil")
|
||||||
}
|
}
|
||||||
c.mu.Unlock()
|
if strings.TrimSpace(task.Type()) == "" {
|
||||||
|
return nil, fmt.Errorf("task typename cannot be empty")
|
||||||
|
}
|
||||||
|
// merge task options with the options provided at enqueue time.
|
||||||
|
opts = append(task.opts, opts...)
|
||||||
opt, err := composeOptions(opts...)
|
opt, err := composeOptions(opts...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -327,53 +379,64 @@ func (c *Client) Enqueue(task *Task, opts ...Option) (*Result, error) {
|
|||||||
}
|
}
|
||||||
var uniqueKey string
|
var uniqueKey string
|
||||||
if opt.uniqueTTL > 0 {
|
if opt.uniqueTTL > 0 {
|
||||||
uniqueKey = base.UniqueKey(opt.queue, task.Type, task.Payload.data)
|
uniqueKey = base.UniqueKey(opt.queue, task.Type(), task.Payload())
|
||||||
}
|
}
|
||||||
msg := &base.TaskMessage{
|
msg := &base.TaskMessage{
|
||||||
ID: uuid.New(),
|
ID: opt.taskID,
|
||||||
Type: task.Type,
|
Type: task.Type(),
|
||||||
Payload: task.Payload.data,
|
Payload: task.Payload(),
|
||||||
Queue: opt.queue,
|
Queue: opt.queue,
|
||||||
Retry: opt.retry,
|
Retry: opt.retry,
|
||||||
Deadline: deadline.Unix(),
|
Deadline: deadline.Unix(),
|
||||||
Timeout: int64(timeout.Seconds()),
|
Timeout: int64(timeout.Seconds()),
|
||||||
UniqueKey: uniqueKey,
|
UniqueKey: uniqueKey,
|
||||||
|
GroupKey: opt.group,
|
||||||
|
Retention: int64(opt.retention.Seconds()),
|
||||||
}
|
}
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
if opt.processAt.Before(now) || opt.processAt.Equal(now) {
|
var state base.TaskState
|
||||||
opt.processAt = now
|
if opt.processAt.After(now) {
|
||||||
err = c.enqueue(msg, opt.uniqueTTL)
|
err = c.schedule(ctx, msg, opt.processAt, opt.uniqueTTL)
|
||||||
|
state = base.TaskStateScheduled
|
||||||
|
} else if opt.group != "" {
|
||||||
|
// Use zero value for processAt since we don't know when the task will be aggregated and processed.
|
||||||
|
opt.processAt = time.Time{}
|
||||||
|
err = c.addToGroup(ctx, msg, opt.group, opt.uniqueTTL)
|
||||||
|
state = base.TaskStateAggregating
|
||||||
} else {
|
} else {
|
||||||
err = c.schedule(msg, opt.processAt, opt.uniqueTTL)
|
opt.processAt = now
|
||||||
|
err = c.enqueue(ctx, msg, opt.uniqueTTL)
|
||||||
|
state = base.TaskStatePending
|
||||||
}
|
}
|
||||||
switch {
|
switch {
|
||||||
case err == rdb.ErrDuplicateTask:
|
case errors.Is(err, errors.ErrDuplicateTask):
|
||||||
return nil, fmt.Errorf("%w", ErrDuplicateTask)
|
return nil, fmt.Errorf("%w", ErrDuplicateTask)
|
||||||
|
case errors.Is(err, errors.ErrTaskIdConflict):
|
||||||
|
return nil, fmt.Errorf("%w", ErrTaskIDConflict)
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return &Result{
|
return newTaskInfo(msg, state, opt.processAt, nil), nil
|
||||||
ID: msg.ID.String(),
|
|
||||||
EnqueuedAt: time.Now().UTC(),
|
|
||||||
ProcessAt: opt.processAt,
|
|
||||||
Queue: msg.Queue,
|
|
||||||
Retry: msg.Retry,
|
|
||||||
Timeout: timeout,
|
|
||||||
Deadline: deadline,
|
|
||||||
}, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) enqueue(msg *base.TaskMessage, uniqueTTL time.Duration) error {
|
func (c *Client) enqueue(ctx context.Context, msg *base.TaskMessage, uniqueTTL time.Duration) error {
|
||||||
if uniqueTTL > 0 {
|
if uniqueTTL > 0 {
|
||||||
return c.rdb.EnqueueUnique(msg, uniqueTTL)
|
return c.broker.EnqueueUnique(ctx, msg, uniqueTTL)
|
||||||
}
|
}
|
||||||
return c.rdb.Enqueue(msg)
|
return c.broker.Enqueue(ctx, msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) schedule(msg *base.TaskMessage, t time.Time, uniqueTTL time.Duration) error {
|
func (c *Client) schedule(ctx context.Context, msg *base.TaskMessage, t time.Time, uniqueTTL time.Duration) error {
|
||||||
if uniqueTTL > 0 {
|
if uniqueTTL > 0 {
|
||||||
ttl := t.Add(uniqueTTL).Sub(time.Now())
|
ttl := t.Add(uniqueTTL).Sub(time.Now())
|
||||||
return c.rdb.ScheduleUnique(msg, t, ttl)
|
return c.broker.ScheduleUnique(ctx, msg, t, ttl)
|
||||||
}
|
}
|
||||||
return c.rdb.Schedule(msg, t)
|
return c.broker.Schedule(ctx, msg, t)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) addToGroup(ctx context.Context, msg *base.TaskMessage, group string, uniqueTTL time.Duration) error {
|
||||||
|
if uniqueTTL > 0 {
|
||||||
|
return c.broker.AddToGroupUnique(ctx, msg, group, uniqueTTL)
|
||||||
|
}
|
||||||
|
return c.broker.AddToGroup(ctx, msg, group)
|
||||||
}
|
}
|
||||||
|
|||||||
746
client_test.go
746
client_test.go
File diff suppressed because it is too large
Load Diff
61
context.go
61
context.go
@@ -6,49 +6,16 @@ package asynq
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/hibiken/asynq/internal/base"
|
asynqcontext "github.com/hibiken/asynq/internal/context"
|
||||||
)
|
)
|
||||||
|
|
||||||
// A taskMetadata holds task scoped data to put in context.
|
|
||||||
type taskMetadata struct {
|
|
||||||
id string
|
|
||||||
maxRetry int
|
|
||||||
retryCount int
|
|
||||||
qname string
|
|
||||||
}
|
|
||||||
|
|
||||||
// ctxKey type is unexported to prevent collisions with context keys defined in
|
|
||||||
// other packages.
|
|
||||||
type ctxKey int
|
|
||||||
|
|
||||||
// metadataCtxKey is the context key for the task metadata.
|
|
||||||
// Its value of zero is arbitrary.
|
|
||||||
const metadataCtxKey ctxKey = 0
|
|
||||||
|
|
||||||
// createContext returns a context and cancel function for a given task message.
|
|
||||||
func createContext(msg *base.TaskMessage, deadline time.Time) (context.Context, context.CancelFunc) {
|
|
||||||
metadata := taskMetadata{
|
|
||||||
id: msg.ID.String(),
|
|
||||||
maxRetry: msg.Retry,
|
|
||||||
retryCount: msg.Retried,
|
|
||||||
qname: msg.Queue,
|
|
||||||
}
|
|
||||||
ctx := context.WithValue(context.Background(), metadataCtxKey, metadata)
|
|
||||||
return context.WithDeadline(ctx, deadline)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetTaskID extracts a task ID from a context, if any.
|
// GetTaskID extracts a task ID from a context, if any.
|
||||||
//
|
//
|
||||||
// ID of a task is guaranteed to be unique.
|
// ID of a task is guaranteed to be unique.
|
||||||
// ID of a task doesn't change if the task is being retried.
|
// ID of a task doesn't change if the task is being retried.
|
||||||
func GetTaskID(ctx context.Context) (id string, ok bool) {
|
func GetTaskID(ctx context.Context) (id string, ok bool) {
|
||||||
metadata, ok := ctx.Value(metadataCtxKey).(taskMetadata)
|
return asynqcontext.GetTaskID(ctx)
|
||||||
if !ok {
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
return metadata.id, true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetRetryCount extracts retry count from a context, if any.
|
// GetRetryCount extracts retry count from a context, if any.
|
||||||
@@ -56,32 +23,20 @@ func GetTaskID(ctx context.Context) (id string, ok bool) {
|
|||||||
// Return value n indicates the number of times associated task has been
|
// Return value n indicates the number of times associated task has been
|
||||||
// retried so far.
|
// retried so far.
|
||||||
func GetRetryCount(ctx context.Context) (n int, ok bool) {
|
func GetRetryCount(ctx context.Context) (n int, ok bool) {
|
||||||
metadata, ok := ctx.Value(metadataCtxKey).(taskMetadata)
|
return asynqcontext.GetRetryCount(ctx)
|
||||||
if !ok {
|
|
||||||
return 0, false
|
|
||||||
}
|
|
||||||
return metadata.retryCount, true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetMaxRetry extracts maximum retry from a context, if any.
|
// GetMaxRetry extracts maximum retry from a context, if any.
|
||||||
//
|
//
|
||||||
// Return value n indicates the maximum number of times the assoicated task
|
// Return value n indicates the maximum number of times the associated task
|
||||||
// can be retried if ProcessTask returns a non-nil error.
|
// can be retried if ProcessTask returns a non-nil error.
|
||||||
func GetMaxRetry(ctx context.Context) (n int, ok bool) {
|
func GetMaxRetry(ctx context.Context) (n int, ok bool) {
|
||||||
metadata, ok := ctx.Value(metadataCtxKey).(taskMetadata)
|
return asynqcontext.GetMaxRetry(ctx)
|
||||||
if !ok {
|
|
||||||
return 0, false
|
|
||||||
}
|
|
||||||
return metadata.maxRetry, true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetQueueName extracts queue name from a context, if any.
|
// GetQueueName extracts queue name from a context, if any.
|
||||||
//
|
//
|
||||||
// Return value qname indicates which queue the task was pulled from.
|
// Return value queue indicates which queue the task was pulled from.
|
||||||
func GetQueueName(ctx context.Context) (qname string, ok bool) {
|
func GetQueueName(ctx context.Context) (queue string, ok bool) {
|
||||||
metadata, ok := ctx.Value(metadataCtxKey).(taskMetadata)
|
return asynqcontext.GetQueueName(ctx)
|
||||||
if !ok {
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
return metadata.qname, true
|
|
||||||
}
|
}
|
||||||
|
|||||||
27
doc.go
27
doc.go
@@ -11,7 +11,7 @@ specify the connection using one of RedisConnOpt types.
|
|||||||
redisConnOpt = asynq.RedisClientOpt{
|
redisConnOpt = asynq.RedisClientOpt{
|
||||||
Addr: "127.0.0.1:6379",
|
Addr: "127.0.0.1:6379",
|
||||||
Password: "xxxxx",
|
Password: "xxxxx",
|
||||||
DB: 3,
|
DB: 2,
|
||||||
}
|
}
|
||||||
|
|
||||||
The Client is used to enqueue a task.
|
The Client is used to enqueue a task.
|
||||||
@@ -20,15 +20,19 @@ The Client is used to enqueue a task.
|
|||||||
client := asynq.NewClient(redisConnOpt)
|
client := asynq.NewClient(redisConnOpt)
|
||||||
|
|
||||||
// Task is created with two parameters: its type and payload.
|
// Task is created with two parameters: its type and payload.
|
||||||
t := asynq.NewTask(
|
// Payload data is simply an array of bytes. It can be encoded in JSON, Protocol Buffer, Gob, etc.
|
||||||
"send_email",
|
b, err := json.Marshal(ExamplePayload{UserID: 42})
|
||||||
map[string]interface{}{"user_id": 42})
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
task := asynq.NewTask("example", b)
|
||||||
|
|
||||||
// Enqueue the task to be processed immediately.
|
// Enqueue the task to be processed immediately.
|
||||||
res, err := client.Enqueue(t)
|
info, err := client.Enqueue(task)
|
||||||
|
|
||||||
// Schedule the task to be processed after one minute.
|
// Schedule the task to be processed after one minute.
|
||||||
res, err = client.Enqueue(t, asynq.ProcessIn(1*time.Minute))
|
info, err = client.Enqueue(t, asynq.ProcessIn(1*time.Minute))
|
||||||
|
|
||||||
The Server is used to run the task processing workers with a given
|
The Server is used to run the task processing workers with a given
|
||||||
handler.
|
handler.
|
||||||
@@ -52,10 +56,13 @@ Example of a type that implements the Handler interface.
|
|||||||
|
|
||||||
func (h *TaskHandler) ProcessTask(ctx context.Context, task *asynq.Task) error {
|
func (h *TaskHandler) ProcessTask(ctx context.Context, task *asynq.Task) error {
|
||||||
switch task.Type {
|
switch task.Type {
|
||||||
case "send_email":
|
case "example":
|
||||||
id, err := task.Payload.GetInt("user_id")
|
var data ExamplePayload
|
||||||
// send email
|
if err := json.Unmarshal(task.Payload(), &data); err != nil {
|
||||||
//...
|
return err
|
||||||
|
}
|
||||||
|
// perform task with the data
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return fmt.Errorf("unexpected task type %q", task.Type)
|
return fmt.Errorf("unexpected task type %q", task.Type)
|
||||||
}
|
}
|
||||||
|
|||||||
BIN
docs/assets/dash.gif
Normal file
BIN
docs/assets/dash.gif
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 809 KiB |
@@ -5,6 +5,7 @@
|
|||||||
package asynq_test
|
package asynq_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
@@ -30,7 +31,7 @@ func ExampleServer_Run() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func ExampleServer_Stop() {
|
func ExampleServer_Shutdown() {
|
||||||
srv := asynq.NewServer(
|
srv := asynq.NewServer(
|
||||||
asynq.RedisClientOpt{Addr: ":6379"},
|
asynq.RedisClientOpt{Addr: ":6379"},
|
||||||
asynq.Config{Concurrency: 20},
|
asynq.Config{Concurrency: 20},
|
||||||
@@ -47,10 +48,10 @@ func ExampleServer_Stop() {
|
|||||||
signal.Notify(sigs, unix.SIGTERM, unix.SIGINT)
|
signal.Notify(sigs, unix.SIGTERM, unix.SIGINT)
|
||||||
<-sigs // wait for termination signal
|
<-sigs // wait for termination signal
|
||||||
|
|
||||||
srv.Stop()
|
srv.Shutdown()
|
||||||
}
|
}
|
||||||
|
|
||||||
func ExampleServer_Quiet() {
|
func ExampleServer_Stop() {
|
||||||
srv := asynq.NewServer(
|
srv := asynq.NewServer(
|
||||||
asynq.RedisClientOpt{Addr: ":6379"},
|
asynq.RedisClientOpt{Addr: ":6379"},
|
||||||
asynq.Config{Concurrency: 20},
|
asynq.Config{Concurrency: 20},
|
||||||
@@ -70,13 +71,13 @@ func ExampleServer_Quiet() {
|
|||||||
for {
|
for {
|
||||||
s := <-sigs
|
s := <-sigs
|
||||||
if s == unix.SIGTSTP {
|
if s == unix.SIGTSTP {
|
||||||
srv.Quiet() // stop processing new tasks
|
srv.Stop() // stop processing new tasks
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
break
|
break // received SIGTERM or SIGINT signal
|
||||||
}
|
}
|
||||||
|
|
||||||
srv.Stop()
|
srv.Shutdown()
|
||||||
}
|
}
|
||||||
|
|
||||||
func ExampleScheduler() {
|
func ExampleScheduler() {
|
||||||
@@ -113,3 +114,20 @@ func ExampleParseRedisURI() {
|
|||||||
// localhost:6379
|
// localhost:6379
|
||||||
// 10
|
// 10
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ExampleResultWriter() {
|
||||||
|
// ResultWriter is only accessible in Handler.
|
||||||
|
h := func(ctx context.Context, task *asynq.Task) error {
|
||||||
|
// .. do task processing work
|
||||||
|
|
||||||
|
res := []byte("task result data")
|
||||||
|
n, err := task.ResultWriter().Write(res) // implements io.Writer
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to write task result: %v", err)
|
||||||
|
}
|
||||||
|
log.Printf(" %d bytes written", n)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = h
|
||||||
|
}
|
||||||
|
|||||||
10
forwarder.go
10
forwarder.go
@@ -45,7 +45,7 @@ func newForwarder(params forwarderParams) *forwarder {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *forwarder) terminate() {
|
func (f *forwarder) shutdown() {
|
||||||
f.logger.Debug("Forwarder shutting down...")
|
f.logger.Debug("Forwarder shutting down...")
|
||||||
// Signal the forwarder goroutine to stop polling.
|
// Signal the forwarder goroutine to stop polling.
|
||||||
f.done <- struct{}{}
|
f.done <- struct{}{}
|
||||||
@@ -56,20 +56,22 @@ func (f *forwarder) start(wg *sync.WaitGroup) {
|
|||||||
wg.Add(1)
|
wg.Add(1)
|
||||||
go func() {
|
go func() {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
|
timer := time.NewTimer(f.avgInterval)
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-f.done:
|
case <-f.done:
|
||||||
f.logger.Debug("Forwarder done")
|
f.logger.Debug("Forwarder done")
|
||||||
return
|
return
|
||||||
case <-time.After(f.avgInterval):
|
case <-timer.C:
|
||||||
f.exec()
|
f.exec()
|
||||||
|
timer.Reset(f.avgInterval)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *forwarder) exec() {
|
func (f *forwarder) exec() {
|
||||||
if err := f.broker.CheckAndEnqueue(f.queues...); err != nil {
|
if err := f.broker.ForwardIfReady(f.queues...); err != nil {
|
||||||
f.logger.Errorf("Could not enqueue scheduled tasks: %v", err)
|
f.logger.Errorf("Failed to forward scheduled tasks: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,9 +10,9 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/google/go-cmp/cmp"
|
"github.com/google/go-cmp/cmp"
|
||||||
h "github.com/hibiken/asynq/internal/asynqtest"
|
|
||||||
"github.com/hibiken/asynq/internal/base"
|
"github.com/hibiken/asynq/internal/base"
|
||||||
"github.com/hibiken/asynq/internal/rdb"
|
"github.com/hibiken/asynq/internal/rdb"
|
||||||
|
h "github.com/hibiken/asynq/internal/testutil"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestForwarder(t *testing.T) {
|
func TestForwarder(t *testing.T) {
|
||||||
@@ -111,7 +111,7 @@ func TestForwarder(t *testing.T) {
|
|||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
s.start(&wg)
|
s.start(&wg)
|
||||||
time.Sleep(tc.wait)
|
time.Sleep(tc.wait)
|
||||||
s.terminate()
|
s.shutdown()
|
||||||
|
|
||||||
for qname, want := range tc.wantScheduled {
|
for qname, want := range tc.wantScheduled {
|
||||||
gotScheduled := h.GetScheduledMessages(t, r, qname)
|
gotScheduled := h.GetScheduledMessages(t, r, qname)
|
||||||
@@ -130,7 +130,7 @@ func TestForwarder(t *testing.T) {
|
|||||||
for qname, want := range tc.wantPending {
|
for qname, want := range tc.wantPending {
|
||||||
gotPending := h.GetPendingMessages(t, r, qname)
|
gotPending := h.GetPendingMessages(t, r, qname)
|
||||||
if diff := cmp.Diff(want, gotPending, h.SortMsgOpt); diff != "" {
|
if diff := cmp.Diff(want, gotPending, h.SortMsgOpt); diff != "" {
|
||||||
t.Errorf("mismatch found in %q after running forwarder: (-want, +got)\n%s", base.QueueKey(qname), diff)
|
t.Errorf("mismatch found in %q after running forwarder: (-want, +got)\n%s", base.PendingKey(qname), diff)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
24
go.mod
24
go.mod
@@ -1,15 +1,21 @@
|
|||||||
module github.com/hibiken/asynq
|
module github.com/hibiken/asynq
|
||||||
|
|
||||||
go 1.13
|
go 1.20
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/go-redis/redis/v7 v7.4.0
|
github.com/golang/protobuf v1.5.3
|
||||||
github.com/google/go-cmp v0.4.0
|
github.com/google/go-cmp v0.6.0
|
||||||
github.com/google/uuid v1.1.1
|
github.com/google/uuid v1.6.0
|
||||||
|
github.com/redis/go-redis/v9 v9.4.0
|
||||||
github.com/robfig/cron/v3 v3.0.1
|
github.com/robfig/cron/v3 v3.0.1
|
||||||
github.com/spf13/cast v1.3.1
|
github.com/spf13/cast v1.5.1
|
||||||
go.uber.org/goleak v0.10.0
|
go.uber.org/goleak v1.3.0
|
||||||
golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e
|
golang.org/x/sys v0.16.0
|
||||||
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4
|
golang.org/x/time v0.3.0
|
||||||
gopkg.in/yaml.v2 v2.2.7 // indirect
|
google.golang.org/protobuf v1.31.0
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/cespare/xxhash/v2 v2.2.0 // indirect
|
||||||
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
99
go.sum
99
go.sum
@@ -1,70 +1,39 @@
|
|||||||
|
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||||
|
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||||
|
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
|
||||||
|
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||||
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
github.com/frankban/quicktest v1.14.4 h1:g2rn0vABPOOXmZUj+vbmUp0lPoXEMuhTpIluN0XL9UY=
|
||||||
github.com/go-redis/redis/v7 v7.2.0 h1:CrCexy/jYWZjW0AyVoHlcJUeZN19VWlbepTh1Vq6dJs=
|
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||||
github.com/go-redis/redis/v7 v7.2.0/go.mod h1:JDNMw23GTyLNC4GZu9njt15ctBQVn7xjRfnwdHj/Dcg=
|
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
|
||||||
github.com/go-redis/redis/v7 v7.4.0 h1:7obg6wUoj05T0EpY0o8B59S9w5yeMWql7sw2kwNW1x4=
|
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||||
github.com/go-redis/redis/v7 v7.4.0/go.mod h1:JDNMw23GTyLNC4GZu9njt15ctBQVn7xjRfnwdHj/Dcg=
|
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||||
github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs=
|
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||||
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4=
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||||
github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY=
|
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||||
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
|
||||||
github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
|
|
||||||
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
|
||||||
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
|
|
||||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
|
||||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
|
||||||
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
|
|
||||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
|
||||||
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
|
||||||
github.com/onsi/ginkgo v1.10.1 h1:q/mM8GF/n0shIN8SaAZ0V+jnLPzen6WIVZdiwrRlMlo=
|
|
||||||
github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
|
||||||
github.com/onsi/gomega v1.7.0 h1:XPnZz8VVBHjVsy1vzJmRwIcSwiUO+JFfrv/xGiigmME=
|
|
||||||
github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
|
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/redis/go-redis/v9 v9.4.0 h1:Yzoz33UZw9I/mFhx4MNrB6Fk+XHO1VukNcCa1+lwyKk=
|
||||||
|
github.com/redis/go-redis/v9 v9.4.0/go.mod h1:hdY0cQFCN4fnSYT6TkisLufl/4W5UIXyv0b/CLO2V2M=
|
||||||
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
||||||
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
||||||
github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng=
|
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
|
||||||
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
|
github.com/spf13/cast v1.5.1 h1:R+kOtfhWQE6TVQzY+4D7wJLBgkdVasCEFxSUBYBYIlA=
|
||||||
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
|
github.com/spf13/cast v1.5.1/go.mod h1:b9PdjNptOpzXr7Rq1q9gJML/2cdGQAo69NKzQ10KN48=
|
||||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
|
||||||
go.uber.org/goleak v0.10.0 h1:G3eWbSNIskeRqtsN/1uI5B+eP73y3JUuBsv9AZjehb4=
|
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||||
go.uber.org/goleak v0.10.0/go.mod h1:VCZuO8V8mFPlL0F5J5GK1rtHV3DrFcQ1R8ryq7FK0aI=
|
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU=
|
||||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd h1:nTDtHvHSdCn1m6ITfMRqtOd/9+7a3s8RBNOZ3eYZzJA=
|
golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4=
|
||||||
golang.org/x/net v0.0.0-20190923162816-aa69164e4478 h1:l5EDrHhldLYb3ZRHDUhXF7Om7MvYXnkV9/iQNo1lX6g=
|
golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||||
golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
|
||||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
|
||||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e h1:o3PsSEY8E4eXWkXrIP9YJALUkVZqzHJT5DOasTyn8Vs=
|
|
||||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
|
||||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
|
||||||
golang.org/x/sys v0.0.0-20191010194322-b09406accb47/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
|
||||||
golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e h1:9vRrk9YW2BTzLP0VCB9ZDjU4cPqkg+IDWL7XgxA1yxQ=
|
|
||||||
golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
|
||||||
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
|
|
||||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
|
||||||
golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
|
|
||||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
|
||||||
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4 h1:SvFZT6jyqRaOeXpc5h/JSfZenJ2O330aBsf7JfSUXmQ=
|
|
||||||
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
|
||||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
|
||||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
|
||||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
|
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
||||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=
|
||||||
gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=
|
google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
|
||||||
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
|
|
||||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
|
||||||
gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE=
|
|
||||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
|
||||||
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
|
||||||
gopkg.in/yaml.v2 v2.2.7 h1:VUgggvou5XRW9mHwD/yXxIYSMtY0zoKQf/v226p2nyo=
|
|
||||||
gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ func newHealthChecker(params healthcheckerParams) *healthchecker {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *healthchecker) terminate() {
|
func (hc *healthchecker) shutdown() {
|
||||||
if hc.healthcheckFunc == nil {
|
if hc.healthcheckFunc == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -51,7 +51,7 @@ func TestHealthChecker(t *testing.T) {
|
|||||||
}
|
}
|
||||||
mu.Unlock()
|
mu.Unlock()
|
||||||
|
|
||||||
hc.terminate()
|
hc.shutdown()
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestHealthCheckerWhenRedisDown(t *testing.T) {
|
func TestHealthCheckerWhenRedisDown(t *testing.T) {
|
||||||
@@ -99,5 +99,5 @@ func TestHealthCheckerWhenRedisDown(t *testing.T) {
|
|||||||
}
|
}
|
||||||
mu.Unlock()
|
mu.Unlock()
|
||||||
|
|
||||||
hc.terminate()
|
hc.shutdown()
|
||||||
}
|
}
|
||||||
|
|||||||
50
heartbeat.go
50
heartbeat.go
@@ -12,6 +12,7 @@ import (
|
|||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"github.com/hibiken/asynq/internal/base"
|
"github.com/hibiken/asynq/internal/base"
|
||||||
"github.com/hibiken/asynq/internal/log"
|
"github.com/hibiken/asynq/internal/log"
|
||||||
|
"github.com/hibiken/asynq/internal/timeutil"
|
||||||
)
|
)
|
||||||
|
|
||||||
// heartbeater is responsible for writing process info to redis periodically to
|
// heartbeater is responsible for writing process info to redis periodically to
|
||||||
@@ -19,6 +20,7 @@ import (
|
|||||||
type heartbeater struct {
|
type heartbeater struct {
|
||||||
logger *log.Logger
|
logger *log.Logger
|
||||||
broker base.Broker
|
broker base.Broker
|
||||||
|
clock timeutil.Clock
|
||||||
|
|
||||||
// channel to communicate back to the long running "heartbeater" goroutine.
|
// channel to communicate back to the long running "heartbeater" goroutine.
|
||||||
done chan struct{}
|
done chan struct{}
|
||||||
@@ -40,8 +42,8 @@ type heartbeater struct {
|
|||||||
started time.Time
|
started time.Time
|
||||||
workers map[string]*workerInfo
|
workers map[string]*workerInfo
|
||||||
|
|
||||||
// status is shared with other goroutine but is concurrency safe.
|
// state is shared with other goroutine but is concurrency safe.
|
||||||
status *base.ServerStatus
|
state *serverState
|
||||||
|
|
||||||
// channels to receive updates on active workers.
|
// channels to receive updates on active workers.
|
||||||
starting <-chan *workerInfo
|
starting <-chan *workerInfo
|
||||||
@@ -55,7 +57,7 @@ type heartbeaterParams struct {
|
|||||||
concurrency int
|
concurrency int
|
||||||
queues map[string]int
|
queues map[string]int
|
||||||
strictPriority bool
|
strictPriority bool
|
||||||
status *base.ServerStatus
|
state *serverState
|
||||||
starting <-chan *workerInfo
|
starting <-chan *workerInfo
|
||||||
finished <-chan *base.TaskMessage
|
finished <-chan *base.TaskMessage
|
||||||
}
|
}
|
||||||
@@ -69,6 +71,7 @@ func newHeartbeater(params heartbeaterParams) *heartbeater {
|
|||||||
return &heartbeater{
|
return &heartbeater{
|
||||||
logger: params.logger,
|
logger: params.logger,
|
||||||
broker: params.broker,
|
broker: params.broker,
|
||||||
|
clock: timeutil.NewRealClock(),
|
||||||
done: make(chan struct{}),
|
done: make(chan struct{}),
|
||||||
interval: params.interval,
|
interval: params.interval,
|
||||||
|
|
||||||
@@ -79,14 +82,14 @@ func newHeartbeater(params heartbeaterParams) *heartbeater {
|
|||||||
queues: params.queues,
|
queues: params.queues,
|
||||||
strictPriority: params.strictPriority,
|
strictPriority: params.strictPriority,
|
||||||
|
|
||||||
status: params.status,
|
state: params.state,
|
||||||
workers: make(map[string]*workerInfo),
|
workers: make(map[string]*workerInfo),
|
||||||
starting: params.starting,
|
starting: params.starting,
|
||||||
finished: params.finished,
|
finished: params.finished,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *heartbeater) terminate() {
|
func (h *heartbeater) shutdown() {
|
||||||
h.logger.Debug("Heartbeater shutting down...")
|
h.logger.Debug("Heartbeater shutting down...")
|
||||||
// Signal the heartbeater goroutine to stop.
|
// Signal the heartbeater goroutine to stop.
|
||||||
h.done <- struct{}{}
|
h.done <- struct{}{}
|
||||||
@@ -100,6 +103,8 @@ type workerInfo struct {
|
|||||||
started time.Time
|
started time.Time
|
||||||
// deadline the worker has to finish processing the task by.
|
// deadline the worker has to finish processing the task by.
|
||||||
deadline time.Time
|
deadline time.Time
|
||||||
|
// lease the worker holds for the task.
|
||||||
|
lease *base.Lease
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *heartbeater) start(wg *sync.WaitGroup) {
|
func (h *heartbeater) start(wg *sync.WaitGroup) {
|
||||||
@@ -107,7 +112,7 @@ func (h *heartbeater) start(wg *sync.WaitGroup) {
|
|||||||
go func() {
|
go func() {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
|
|
||||||
h.started = time.Now()
|
h.started = h.clock.Now()
|
||||||
|
|
||||||
h.beat()
|
h.beat()
|
||||||
|
|
||||||
@@ -125,16 +130,21 @@ func (h *heartbeater) start(wg *sync.WaitGroup) {
|
|||||||
timer.Reset(h.interval)
|
timer.Reset(h.interval)
|
||||||
|
|
||||||
case w := <-h.starting:
|
case w := <-h.starting:
|
||||||
h.workers[w.msg.ID.String()] = w
|
h.workers[w.msg.ID] = w
|
||||||
|
|
||||||
case msg := <-h.finished:
|
case msg := <-h.finished:
|
||||||
delete(h.workers, msg.ID.String())
|
delete(h.workers, msg.ID)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// beat extends lease for workers and writes server/worker info to redis.
|
||||||
func (h *heartbeater) beat() {
|
func (h *heartbeater) beat() {
|
||||||
|
h.state.mu.Lock()
|
||||||
|
srvStatus := h.state.value.String()
|
||||||
|
h.state.mu.Unlock()
|
||||||
|
|
||||||
info := base.ServerInfo{
|
info := base.ServerInfo{
|
||||||
Host: h.host,
|
Host: h.host,
|
||||||
PID: h.pid,
|
PID: h.pid,
|
||||||
@@ -142,12 +152,13 @@ func (h *heartbeater) beat() {
|
|||||||
Concurrency: h.concurrency,
|
Concurrency: h.concurrency,
|
||||||
Queues: h.queues,
|
Queues: h.queues,
|
||||||
StrictPriority: h.strictPriority,
|
StrictPriority: h.strictPriority,
|
||||||
Status: h.status.String(),
|
Status: srvStatus,
|
||||||
Started: h.started,
|
Started: h.started,
|
||||||
ActiveWorkerCount: len(h.workers),
|
ActiveWorkerCount: len(h.workers),
|
||||||
}
|
}
|
||||||
|
|
||||||
var ws []*base.WorkerInfo
|
var ws []*base.WorkerInfo
|
||||||
|
idsByQueue := make(map[string][]string)
|
||||||
for id, w := range h.workers {
|
for id, w := range h.workers {
|
||||||
ws = append(ws, &base.WorkerInfo{
|
ws = append(ws, &base.WorkerInfo{
|
||||||
Host: h.host,
|
Host: h.host,
|
||||||
@@ -160,11 +171,30 @@ func (h *heartbeater) beat() {
|
|||||||
Started: w.started,
|
Started: w.started,
|
||||||
Deadline: w.deadline,
|
Deadline: w.deadline,
|
||||||
})
|
})
|
||||||
|
// Check lease before adding to the set to make sure not to extend the lease if the lease is already expired.
|
||||||
|
if w.lease.IsValid() {
|
||||||
|
idsByQueue[w.msg.Queue] = append(idsByQueue[w.msg.Queue], id)
|
||||||
|
} else {
|
||||||
|
w.lease.NotifyExpiration() // notify processor if the lease is expired
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Note: Set TTL to be long enough so that it won't expire before we write again
|
// Note: Set TTL to be long enough so that it won't expire before we write again
|
||||||
// and short enough to expire quickly once the process is shut down or killed.
|
// and short enough to expire quickly once the process is shut down or killed.
|
||||||
if err := h.broker.WriteServerState(&info, ws, h.interval*2); err != nil {
|
if err := h.broker.WriteServerState(&info, ws, h.interval*2); err != nil {
|
||||||
h.logger.Errorf("could not write server state data: %v", err)
|
h.logger.Errorf("Failed to write server state data: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for qname, ids := range idsByQueue {
|
||||||
|
expirationTime, err := h.broker.ExtendLease(qname, ids...)
|
||||||
|
if err != nil {
|
||||||
|
h.logger.Errorf("Failed to extend lease for tasks %v: %v", ids, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, id := range ids {
|
||||||
|
if l := h.workers[id].lease; !l.Reset(expirationTime) {
|
||||||
|
h.logger.Warnf("Lease reset failed for %s; lease deadline: %v", id, l.Deadline())
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,31 +5,154 @@
|
|||||||
package asynq
|
package asynq
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/google/go-cmp/cmp"
|
"github.com/google/go-cmp/cmp"
|
||||||
"github.com/google/go-cmp/cmp/cmpopts"
|
"github.com/google/go-cmp/cmp/cmpopts"
|
||||||
h "github.com/hibiken/asynq/internal/asynqtest"
|
|
||||||
"github.com/hibiken/asynq/internal/base"
|
"github.com/hibiken/asynq/internal/base"
|
||||||
"github.com/hibiken/asynq/internal/rdb"
|
"github.com/hibiken/asynq/internal/rdb"
|
||||||
"github.com/hibiken/asynq/internal/testbroker"
|
"github.com/hibiken/asynq/internal/testbroker"
|
||||||
|
h "github.com/hibiken/asynq/internal/testutil"
|
||||||
|
"github.com/hibiken/asynq/internal/timeutil"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Test goes through a few phases.
|
||||||
|
//
|
||||||
|
// Phase1: Simulate Server startup; Simulate starting tasks listed in startedWorkers
|
||||||
|
// Phase2: Simulate finishing tasks listed in finishedTasks
|
||||||
|
// Phase3: Simulate Server shutdown;
|
||||||
func TestHeartbeater(t *testing.T) {
|
func TestHeartbeater(t *testing.T) {
|
||||||
r := setup(t)
|
r := setup(t)
|
||||||
defer r.Close()
|
defer r.Close()
|
||||||
rdbClient := rdb.NewRDB(r)
|
rdbClient := rdb.NewRDB(r)
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
const elapsedTime = 10 * time.Second // simulated time elapsed between phase1 and phase2
|
||||||
|
|
||||||
|
clock := timeutil.NewSimulatedClock(time.Time{}) // time will be set in each test
|
||||||
|
|
||||||
|
t1 := h.NewTaskMessageWithQueue("task1", nil, "default")
|
||||||
|
t2 := h.NewTaskMessageWithQueue("task2", nil, "default")
|
||||||
|
t3 := h.NewTaskMessageWithQueue("task3", nil, "default")
|
||||||
|
t4 := h.NewTaskMessageWithQueue("task4", nil, "custom")
|
||||||
|
t5 := h.NewTaskMessageWithQueue("task5", nil, "custom")
|
||||||
|
t6 := h.NewTaskMessageWithQueue("task6", nil, "default")
|
||||||
|
|
||||||
|
// Note: intentionally set to time less than now.Add(rdb.LeaseDuration) to test lease extension is working.
|
||||||
|
lease1 := h.NewLeaseWithClock(now.Add(10*time.Second), clock)
|
||||||
|
lease2 := h.NewLeaseWithClock(now.Add(10*time.Second), clock)
|
||||||
|
lease3 := h.NewLeaseWithClock(now.Add(10*time.Second), clock)
|
||||||
|
lease4 := h.NewLeaseWithClock(now.Add(10*time.Second), clock)
|
||||||
|
lease5 := h.NewLeaseWithClock(now.Add(10*time.Second), clock)
|
||||||
|
lease6 := h.NewLeaseWithClock(now.Add(10*time.Second), clock)
|
||||||
|
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
interval time.Duration
|
desc string
|
||||||
|
|
||||||
|
// Interval between heartbeats.
|
||||||
|
interval time.Duration
|
||||||
|
|
||||||
|
// Server info.
|
||||||
host string
|
host string
|
||||||
pid int
|
pid int
|
||||||
queues map[string]int
|
queues map[string]int
|
||||||
concurrency int
|
concurrency int
|
||||||
|
|
||||||
|
active map[string][]*base.TaskMessage // initial active set state
|
||||||
|
lease map[string][]base.Z // initial lease set state
|
||||||
|
wantLease1 map[string][]base.Z // expected lease set state after starting all startedWorkers
|
||||||
|
wantLease2 map[string][]base.Z // expected lease set state after finishing all finishedTasks
|
||||||
|
startedWorkers []*workerInfo // workerInfo to send via the started channel
|
||||||
|
finishedTasks []*base.TaskMessage // tasks to send via the finished channel
|
||||||
|
|
||||||
|
startTime time.Time // simulated start time
|
||||||
|
elapsedTime time.Duration // simulated time elapsed between starting and finishing processing tasks
|
||||||
}{
|
}{
|
||||||
{2 * time.Second, "localhost", 45678, map[string]int{"default": 1}, 10},
|
{
|
||||||
|
desc: "With single queue",
|
||||||
|
interval: 2 * time.Second,
|
||||||
|
host: "localhost",
|
||||||
|
pid: 45678,
|
||||||
|
queues: map[string]int{"default": 1},
|
||||||
|
concurrency: 10,
|
||||||
|
active: map[string][]*base.TaskMessage{
|
||||||
|
"default": {t1, t2, t3},
|
||||||
|
},
|
||||||
|
lease: map[string][]base.Z{
|
||||||
|
"default": {
|
||||||
|
{Message: t1, Score: now.Add(10 * time.Second).Unix()},
|
||||||
|
{Message: t2, Score: now.Add(10 * time.Second).Unix()},
|
||||||
|
{Message: t3, Score: now.Add(10 * time.Second).Unix()},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
startedWorkers: []*workerInfo{
|
||||||
|
{msg: t1, started: now, deadline: now.Add(2 * time.Minute), lease: lease1},
|
||||||
|
{msg: t2, started: now, deadline: now.Add(2 * time.Minute), lease: lease2},
|
||||||
|
{msg: t3, started: now, deadline: now.Add(2 * time.Minute), lease: lease3},
|
||||||
|
},
|
||||||
|
finishedTasks: []*base.TaskMessage{t1, t2},
|
||||||
|
wantLease1: map[string][]base.Z{
|
||||||
|
"default": {
|
||||||
|
{Message: t1, Score: now.Add(rdb.LeaseDuration).Unix()},
|
||||||
|
{Message: t2, Score: now.Add(rdb.LeaseDuration).Unix()},
|
||||||
|
{Message: t3, Score: now.Add(rdb.LeaseDuration).Unix()},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
wantLease2: map[string][]base.Z{
|
||||||
|
"default": {
|
||||||
|
{Message: t3, Score: now.Add(elapsedTime).Add(rdb.LeaseDuration).Unix()},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
startTime: now,
|
||||||
|
elapsedTime: elapsedTime,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "With multiple queue",
|
||||||
|
interval: 2 * time.Second,
|
||||||
|
host: "localhost",
|
||||||
|
pid: 45678,
|
||||||
|
queues: map[string]int{"default": 1, "custom": 2},
|
||||||
|
concurrency: 10,
|
||||||
|
active: map[string][]*base.TaskMessage{
|
||||||
|
"default": {t6},
|
||||||
|
"custom": {t4, t5},
|
||||||
|
},
|
||||||
|
lease: map[string][]base.Z{
|
||||||
|
"default": {
|
||||||
|
{Message: t6, Score: now.Add(10 * time.Second).Unix()},
|
||||||
|
},
|
||||||
|
"custom": {
|
||||||
|
{Message: t4, Score: now.Add(10 * time.Second).Unix()},
|
||||||
|
{Message: t5, Score: now.Add(10 * time.Second).Unix()},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
startedWorkers: []*workerInfo{
|
||||||
|
{msg: t6, started: now, deadline: now.Add(2 * time.Minute), lease: lease6},
|
||||||
|
{msg: t4, started: now, deadline: now.Add(2 * time.Minute), lease: lease4},
|
||||||
|
{msg: t5, started: now, deadline: now.Add(2 * time.Minute), lease: lease5},
|
||||||
|
},
|
||||||
|
finishedTasks: []*base.TaskMessage{t6, t5},
|
||||||
|
wantLease1: map[string][]base.Z{
|
||||||
|
"default": {
|
||||||
|
{Message: t6, Score: now.Add(rdb.LeaseDuration).Unix()},
|
||||||
|
},
|
||||||
|
"custom": {
|
||||||
|
{Message: t4, Score: now.Add(rdb.LeaseDuration).Unix()},
|
||||||
|
{Message: t5, Score: now.Add(rdb.LeaseDuration).Unix()},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
wantLease2: map[string][]base.Z{
|
||||||
|
"default": {},
|
||||||
|
"custom": {
|
||||||
|
{Message: t4, Score: now.Add(elapsedTime).Add(rdb.LeaseDuration).Unix()},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
startTime: now,
|
||||||
|
elapsedTime: elapsedTime,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
timeCmpOpt := cmpopts.EquateApproxTime(10 * time.Millisecond)
|
timeCmpOpt := cmpopts.EquateApproxTime(10 * time.Millisecond)
|
||||||
@@ -37,8 +160,15 @@ func TestHeartbeater(t *testing.T) {
|
|||||||
ignoreFieldOpt := cmpopts.IgnoreFields(base.ServerInfo{}, "ServerID")
|
ignoreFieldOpt := cmpopts.IgnoreFields(base.ServerInfo{}, "ServerID")
|
||||||
for _, tc := range tests {
|
for _, tc := range tests {
|
||||||
h.FlushDB(t, r)
|
h.FlushDB(t, r)
|
||||||
|
h.SeedAllActiveQueues(t, r, tc.active)
|
||||||
|
h.SeedAllLease(t, r, tc.lease)
|
||||||
|
|
||||||
status := base.NewServerStatus(base.StatusIdle)
|
clock.SetTime(tc.startTime)
|
||||||
|
rdbClient.SetClock(clock)
|
||||||
|
|
||||||
|
srvState := &serverState{}
|
||||||
|
startingCh := make(chan *workerInfo)
|
||||||
|
finishedCh := make(chan *base.TaskMessage)
|
||||||
hb := newHeartbeater(heartbeaterParams{
|
hb := newHeartbeater(heartbeaterParams{
|
||||||
logger: testLogger,
|
logger: testLogger,
|
||||||
broker: rdbClient,
|
broker: rdbClient,
|
||||||
@@ -46,77 +176,139 @@ func TestHeartbeater(t *testing.T) {
|
|||||||
concurrency: tc.concurrency,
|
concurrency: tc.concurrency,
|
||||||
queues: tc.queues,
|
queues: tc.queues,
|
||||||
strictPriority: false,
|
strictPriority: false,
|
||||||
status: status,
|
state: srvState,
|
||||||
starting: make(chan *workerInfo),
|
starting: startingCh,
|
||||||
finished: make(chan *base.TaskMessage),
|
finished: finishedCh,
|
||||||
})
|
})
|
||||||
|
hb.clock = clock
|
||||||
|
|
||||||
// Change host and pid fields for testing purpose.
|
// Change host and pid fields for testing purpose.
|
||||||
hb.host = tc.host
|
hb.host = tc.host
|
||||||
hb.pid = tc.pid
|
hb.pid = tc.pid
|
||||||
|
|
||||||
status.Set(base.StatusRunning)
|
//===================
|
||||||
|
// Start Phase1
|
||||||
|
//===================
|
||||||
|
|
||||||
|
srvState.mu.Lock()
|
||||||
|
srvState.value = srvStateActive // simulating Server.Start
|
||||||
|
srvState.mu.Unlock()
|
||||||
|
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
hb.start(&wg)
|
hb.start(&wg)
|
||||||
|
|
||||||
want := &base.ServerInfo{
|
// Simulate processor starting to work on tasks.
|
||||||
Host: tc.host,
|
for _, w := range tc.startedWorkers {
|
||||||
PID: tc.pid,
|
startingCh <- w
|
||||||
Queues: tc.queues,
|
|
||||||
Concurrency: tc.concurrency,
|
|
||||||
Started: time.Now(),
|
|
||||||
Status: "running",
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// allow for heartbeater to write to redis
|
// Wait for heartbeater to write to redis
|
||||||
time.Sleep(tc.interval)
|
time.Sleep(tc.interval * 2)
|
||||||
|
|
||||||
ss, err := rdbClient.ListServers()
|
ss, err := rdbClient.ListServers()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Errorf("could not read server info from redis: %v", err)
|
t.Errorf("%s: could not read server info from redis: %v", tc.desc, err)
|
||||||
hb.terminate()
|
hb.shutdown()
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(ss) != 1 {
|
if len(ss) != 1 {
|
||||||
t.Errorf("(*RDB).ListServers returned %d process info, want 1", len(ss))
|
t.Errorf("%s: (*RDB).ListServers returned %d server info, want 1", tc.desc, len(ss))
|
||||||
hb.terminate()
|
hb.shutdown()
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if diff := cmp.Diff(want, ss[0], timeCmpOpt, ignoreOpt, ignoreFieldOpt); diff != "" {
|
wantInfo := &base.ServerInfo{
|
||||||
t.Errorf("redis stored process status %+v, want %+v; (-want, +got)\n%s", ss[0], want, diff)
|
Host: tc.host,
|
||||||
hb.terminate()
|
PID: tc.pid,
|
||||||
|
Queues: tc.queues,
|
||||||
|
Concurrency: tc.concurrency,
|
||||||
|
Started: now,
|
||||||
|
Status: "active",
|
||||||
|
ActiveWorkerCount: len(tc.startedWorkers),
|
||||||
|
}
|
||||||
|
if diff := cmp.Diff(wantInfo, ss[0], timeCmpOpt, ignoreOpt, ignoreFieldOpt); diff != "" {
|
||||||
|
t.Errorf("%s: redis stored server status %+v, want %+v; (-want, +got)\n%s", tc.desc, ss[0], wantInfo, diff)
|
||||||
|
hb.shutdown()
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// status change
|
for qname, wantLease := range tc.wantLease1 {
|
||||||
status.Set(base.StatusStopped)
|
gotLease := h.GetLeaseEntries(t, r, qname)
|
||||||
|
if diff := cmp.Diff(wantLease, gotLease, h.SortZSetEntryOpt); diff != "" {
|
||||||
|
t.Errorf("%s: mismatch found in %q: (-want,+got):\n%s", tc.desc, base.LeaseKey(qname), diff)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// allow for heartbeater to write to redis
|
for _, w := range tc.startedWorkers {
|
||||||
|
if want := now.Add(rdb.LeaseDuration); w.lease.Deadline() != want {
|
||||||
|
t.Errorf("%s: lease deadline for %v is set to %v, want %v", tc.desc, w.msg, w.lease.Deadline(), want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//===================
|
||||||
|
// Start Phase2
|
||||||
|
//===================
|
||||||
|
|
||||||
|
clock.AdvanceTime(tc.elapsedTime)
|
||||||
|
// Simulate processor finished processing tasks.
|
||||||
|
for _, msg := range tc.finishedTasks {
|
||||||
|
if err := rdbClient.Done(context.Background(), msg); err != nil {
|
||||||
|
t.Fatalf("RDB.Done failed: %v", err)
|
||||||
|
}
|
||||||
|
finishedCh <- msg
|
||||||
|
}
|
||||||
|
// Wait for heartbeater to write to redis
|
||||||
time.Sleep(tc.interval * 2)
|
time.Sleep(tc.interval * 2)
|
||||||
|
|
||||||
want.Status = "stopped"
|
for qname, wantLease := range tc.wantLease2 {
|
||||||
|
gotLease := h.GetLeaseEntries(t, r, qname)
|
||||||
|
if diff := cmp.Diff(wantLease, gotLease, h.SortZSetEntryOpt); diff != "" {
|
||||||
|
t.Errorf("%s: mismatch found in %q: (-want,+got):\n%s", tc.desc, base.LeaseKey(qname), diff)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//===================
|
||||||
|
// Start Phase3
|
||||||
|
//===================
|
||||||
|
|
||||||
|
// Server state change; simulating Server.Shutdown
|
||||||
|
srvState.mu.Lock()
|
||||||
|
srvState.value = srvStateClosed
|
||||||
|
srvState.mu.Unlock()
|
||||||
|
|
||||||
|
// Wait for heartbeater to write to redis
|
||||||
|
time.Sleep(tc.interval * 2)
|
||||||
|
|
||||||
|
wantInfo = &base.ServerInfo{
|
||||||
|
Host: tc.host,
|
||||||
|
PID: tc.pid,
|
||||||
|
Queues: tc.queues,
|
||||||
|
Concurrency: tc.concurrency,
|
||||||
|
Started: now,
|
||||||
|
Status: "closed",
|
||||||
|
ActiveWorkerCount: len(tc.startedWorkers) - len(tc.finishedTasks),
|
||||||
|
}
|
||||||
ss, err = rdbClient.ListServers()
|
ss, err = rdbClient.ListServers()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Errorf("could not read process status from redis: %v", err)
|
t.Errorf("%s: could not read server status from redis: %v", tc.desc, err)
|
||||||
hb.terminate()
|
hb.shutdown()
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(ss) != 1 {
|
if len(ss) != 1 {
|
||||||
t.Errorf("(*RDB).ListProcesses returned %d process info, want 1", len(ss))
|
t.Errorf("%s: (*RDB).ListServers returned %d server info, want 1", tc.desc, len(ss))
|
||||||
hb.terminate()
|
hb.shutdown()
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if diff := cmp.Diff(want, ss[0], timeCmpOpt, ignoreOpt, ignoreFieldOpt); diff != "" {
|
if diff := cmp.Diff(wantInfo, ss[0], timeCmpOpt, ignoreOpt, ignoreFieldOpt); diff != "" {
|
||||||
t.Errorf("redis stored process status %+v, want %+v; (-want, +got)\n%s", ss[0], want, diff)
|
t.Errorf("%s: redis stored process status %+v, want %+v; (-want, +got)\n%s", tc.desc, ss[0], wantInfo, diff)
|
||||||
hb.terminate()
|
hb.shutdown()
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
hb.terminate()
|
hb.shutdown()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -131,6 +323,7 @@ func TestHeartbeaterWithRedisDown(t *testing.T) {
|
|||||||
r := rdb.NewRDB(setup(t))
|
r := rdb.NewRDB(setup(t))
|
||||||
defer r.Close()
|
defer r.Close()
|
||||||
testBroker := testbroker.NewTestBroker(r)
|
testBroker := testbroker.NewTestBroker(r)
|
||||||
|
state := &serverState{value: srvStateActive}
|
||||||
hb := newHeartbeater(heartbeaterParams{
|
hb := newHeartbeater(heartbeaterParams{
|
||||||
logger: testLogger,
|
logger: testLogger,
|
||||||
broker: testBroker,
|
broker: testBroker,
|
||||||
@@ -138,7 +331,7 @@ func TestHeartbeaterWithRedisDown(t *testing.T) {
|
|||||||
concurrency: 10,
|
concurrency: 10,
|
||||||
queues: map[string]int{"default": 1},
|
queues: map[string]int{"default": 1},
|
||||||
strictPriority: false,
|
strictPriority: false,
|
||||||
status: base.NewServerStatus(base.StatusRunning),
|
state: state,
|
||||||
starting: make(chan *workerInfo),
|
starting: make(chan *workerInfo),
|
||||||
finished: make(chan *base.TaskMessage),
|
finished: make(chan *base.TaskMessage),
|
||||||
})
|
})
|
||||||
@@ -150,5 +343,5 @@ func TestHeartbeaterWithRedisDown(t *testing.T) {
|
|||||||
// wait for heartbeater to try writing data to redis
|
// wait for heartbeater to try writing data to redis
|
||||||
time.Sleep(2 * time.Second)
|
time.Sleep(2 * time.Second)
|
||||||
|
|
||||||
hb.terminate()
|
hb.shutdown()
|
||||||
}
|
}
|
||||||
|
|||||||
1026
inspector.go
Normal file
1026
inspector.go
Normal file
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,22 +0,0 @@
|
|||||||
// Copyright 2020 Kentaro Hibino. All rights reserved.
|
|
||||||
// Use of this source code is governed by a MIT license
|
|
||||||
// that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
/*
|
|
||||||
Package inspeq provides helper types and functions to inspect queues and tasks managed by Asynq.
|
|
||||||
|
|
||||||
Inspector is used to query and mutate the state of queues and tasks.
|
|
||||||
|
|
||||||
Example:
|
|
||||||
|
|
||||||
inspector := inspeq.New(asynq.RedisClientOpt{Addr: "localhost:6379"})
|
|
||||||
|
|
||||||
tasks, err := inspector.ListArchivedTasks("my-queue")
|
|
||||||
|
|
||||||
for _, t := range tasks {
|
|
||||||
if err := inspector.DeleteTaskByKey(t.Key()); err != nil {
|
|
||||||
// handle error
|
|
||||||
}
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
package inspeq
|
|
||||||
@@ -1,956 +0,0 @@
|
|||||||
// Copyright 2020 Kentaro Hibino. All rights reserved.
|
|
||||||
// Use of this source code is governed by a MIT license
|
|
||||||
// that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package inspeq
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/go-redis/redis/v7"
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"github.com/hibiken/asynq"
|
|
||||||
"github.com/hibiken/asynq/internal/base"
|
|
||||||
"github.com/hibiken/asynq/internal/rdb"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Inspector is a client interface to inspect and mutate the state of
|
|
||||||
// queues and tasks.
|
|
||||||
type Inspector struct {
|
|
||||||
rdb *rdb.RDB
|
|
||||||
}
|
|
||||||
|
|
||||||
// New returns a new instance of Inspector.
|
|
||||||
func New(r asynq.RedisConnOpt) *Inspector {
|
|
||||||
c, ok := r.MakeRedisClient().(redis.UniversalClient)
|
|
||||||
if !ok {
|
|
||||||
panic(fmt.Sprintf("inspeq: unsupported RedisConnOpt type %T", r))
|
|
||||||
}
|
|
||||||
return &Inspector{
|
|
||||||
rdb: rdb.NewRDB(c),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close closes the connection with redis.
|
|
||||||
func (i *Inspector) Close() error {
|
|
||||||
return i.rdb.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Queues returns a list of all queue names.
|
|
||||||
func (i *Inspector) Queues() ([]string, error) {
|
|
||||||
return i.rdb.AllQueues()
|
|
||||||
}
|
|
||||||
|
|
||||||
// QueueStats represents a state of queues at a certain time.
|
|
||||||
type QueueStats struct {
|
|
||||||
// Name of the queue.
|
|
||||||
Queue string
|
|
||||||
// Total number of bytes that the queue and its tasks require to be stored in redis.
|
|
||||||
MemoryUsage int64
|
|
||||||
// Size is the total number of tasks in the queue.
|
|
||||||
// The value is the sum of Pending, Active, Scheduled, Retry, and Archived.
|
|
||||||
Size int
|
|
||||||
// Number of pending tasks.
|
|
||||||
Pending int
|
|
||||||
// Number of active tasks.
|
|
||||||
Active int
|
|
||||||
// Number of scheduled tasks.
|
|
||||||
Scheduled int
|
|
||||||
// Number of retry tasks.
|
|
||||||
Retry int
|
|
||||||
// Number of archived tasks.
|
|
||||||
Archived int
|
|
||||||
// Total number of tasks being processed during the given date.
|
|
||||||
// The number includes both succeeded and failed tasks.
|
|
||||||
Processed int
|
|
||||||
// Total number of tasks failed to be processed during the given date.
|
|
||||||
Failed int
|
|
||||||
// Paused indicates whether the queue is paused.
|
|
||||||
// If true, tasks in the queue will not be processed.
|
|
||||||
Paused bool
|
|
||||||
// Time when this stats was taken.
|
|
||||||
Timestamp time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
// CurrentStats returns a current stats of the given queue.
|
|
||||||
func (i *Inspector) CurrentStats(qname string) (*QueueStats, error) {
|
|
||||||
if err := base.ValidateQueueName(qname); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
stats, err := i.rdb.CurrentStats(qname)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &QueueStats{
|
|
||||||
Queue: stats.Queue,
|
|
||||||
MemoryUsage: stats.MemoryUsage,
|
|
||||||
Size: stats.Size,
|
|
||||||
Pending: stats.Pending,
|
|
||||||
Active: stats.Active,
|
|
||||||
Scheduled: stats.Scheduled,
|
|
||||||
Retry: stats.Retry,
|
|
||||||
Archived: stats.Archived,
|
|
||||||
Processed: stats.Processed,
|
|
||||||
Failed: stats.Failed,
|
|
||||||
Paused: stats.Paused,
|
|
||||||
Timestamp: stats.Timestamp,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// DailyStats holds aggregate data for a given day for a given queue.
|
|
||||||
type DailyStats struct {
|
|
||||||
// Name of the queue.
|
|
||||||
Queue string
|
|
||||||
// Total number of tasks being processed during the given date.
|
|
||||||
// The number includes both succeeded and failed tasks.
|
|
||||||
Processed int
|
|
||||||
// Total number of tasks failed to be processed during the given date.
|
|
||||||
Failed int
|
|
||||||
// Date this stats was taken.
|
|
||||||
Date time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
// History returns a list of stats from the last n days.
|
|
||||||
func (i *Inspector) History(qname string, n int) ([]*DailyStats, error) {
|
|
||||||
if err := base.ValidateQueueName(qname); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
stats, err := i.rdb.HistoricalStats(qname, n)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var res []*DailyStats
|
|
||||||
for _, s := range stats {
|
|
||||||
res = append(res, &DailyStats{
|
|
||||||
Queue: s.Queue,
|
|
||||||
Processed: s.Processed,
|
|
||||||
Failed: s.Failed,
|
|
||||||
Date: s.Time,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return res, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ErrQueueNotFound indicates that the specified queue does not exist.
|
|
||||||
type ErrQueueNotFound struct {
|
|
||||||
qname string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *ErrQueueNotFound) Error() string {
|
|
||||||
return fmt.Sprintf("queue %q does not exist", e.qname)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ErrQueueNotEmpty indicates that the specified queue is not empty.
|
|
||||||
type ErrQueueNotEmpty struct {
|
|
||||||
qname string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *ErrQueueNotEmpty) Error() string {
|
|
||||||
return fmt.Sprintf("queue %q is not empty", e.qname)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeleteQueue removes the specified queue.
|
|
||||||
//
|
|
||||||
// If force is set to true, DeleteQueue will remove the queue regardless of
|
|
||||||
// the queue size as long as no tasks are active in the queue.
|
|
||||||
// If force is set to false, DeleteQueue will remove the queue only if
|
|
||||||
// the queue is empty.
|
|
||||||
//
|
|
||||||
// If the specified queue does not exist, DeleteQueue returns ErrQueueNotFound.
|
|
||||||
// If force is set to false and the specified queue is not empty, DeleteQueue
|
|
||||||
// returns ErrQueueNotEmpty.
|
|
||||||
func (i *Inspector) DeleteQueue(qname string, force bool) error {
|
|
||||||
err := i.rdb.RemoveQueue(qname, force)
|
|
||||||
if _, ok := err.(*rdb.ErrQueueNotFound); ok {
|
|
||||||
return &ErrQueueNotFound{qname}
|
|
||||||
}
|
|
||||||
if _, ok := err.(*rdb.ErrQueueNotEmpty); ok {
|
|
||||||
return &ErrQueueNotEmpty{qname}
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// PendingTask is a task in a queue and is ready to be processed.
|
|
||||||
type PendingTask struct {
|
|
||||||
*asynq.Task
|
|
||||||
ID string
|
|
||||||
Queue string
|
|
||||||
MaxRetry int
|
|
||||||
Retried int
|
|
||||||
LastError string
|
|
||||||
}
|
|
||||||
|
|
||||||
// ActiveTask is a task that's currently being processed.
|
|
||||||
type ActiveTask struct {
|
|
||||||
*asynq.Task
|
|
||||||
ID string
|
|
||||||
Queue string
|
|
||||||
MaxRetry int
|
|
||||||
Retried int
|
|
||||||
LastError string
|
|
||||||
}
|
|
||||||
|
|
||||||
// ScheduledTask is a task scheduled to be processed in the future.
|
|
||||||
type ScheduledTask struct {
|
|
||||||
*asynq.Task
|
|
||||||
ID string
|
|
||||||
Queue string
|
|
||||||
MaxRetry int
|
|
||||||
Retried int
|
|
||||||
LastError string
|
|
||||||
NextProcessAt time.Time
|
|
||||||
|
|
||||||
score int64
|
|
||||||
}
|
|
||||||
|
|
||||||
// RetryTask is a task scheduled to be retried in the future.
|
|
||||||
type RetryTask struct {
|
|
||||||
*asynq.Task
|
|
||||||
ID string
|
|
||||||
Queue string
|
|
||||||
NextProcessAt time.Time
|
|
||||||
MaxRetry int
|
|
||||||
Retried int
|
|
||||||
LastError string
|
|
||||||
// TODO: LastFailedAt time.Time
|
|
||||||
|
|
||||||
score int64
|
|
||||||
}
|
|
||||||
|
|
||||||
// ArchivedTask is a task archived for debugging and inspection purposes, and
|
|
||||||
// it won't be retried automatically.
|
|
||||||
// A task can be archived when the task exhausts its retry counts or manually
|
|
||||||
// archived by a user via the CLI or Inspector.
|
|
||||||
type ArchivedTask struct {
|
|
||||||
*asynq.Task
|
|
||||||
ID string
|
|
||||||
Queue string
|
|
||||||
MaxRetry int
|
|
||||||
Retried int
|
|
||||||
LastFailedAt time.Time
|
|
||||||
LastError string
|
|
||||||
|
|
||||||
score int64
|
|
||||||
}
|
|
||||||
|
|
||||||
// Format string used for task key.
|
|
||||||
// Format is <prefix>:<uuid>:<score>.
|
|
||||||
const taskKeyFormat = "%s:%v:%v"
|
|
||||||
|
|
||||||
// Prefix used for task key.
|
|
||||||
const (
|
|
||||||
keyPrefixPending = "p"
|
|
||||||
keyPrefixScheduled = "s"
|
|
||||||
keyPrefixRetry = "r"
|
|
||||||
keyPrefixArchived = "a"
|
|
||||||
|
|
||||||
allKeyPrefixes = keyPrefixPending + keyPrefixScheduled + keyPrefixRetry + keyPrefixArchived
|
|
||||||
)
|
|
||||||
|
|
||||||
// Key returns a key used to delete, and archive the pending task.
|
|
||||||
func (t *PendingTask) Key() string {
|
|
||||||
// Note: Pending tasks are stored in redis LIST, therefore no score.
|
|
||||||
// Use zero for the score to use the same key format.
|
|
||||||
return fmt.Sprintf(taskKeyFormat, keyPrefixPending, t.ID, 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Key returns a key used to delete, run, and archive the scheduled task.
|
|
||||||
func (t *ScheduledTask) Key() string {
|
|
||||||
return fmt.Sprintf(taskKeyFormat, keyPrefixScheduled, t.ID, t.score)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Key returns a key used to delete, run, and archive the retry task.
|
|
||||||
func (t *RetryTask) Key() string {
|
|
||||||
return fmt.Sprintf(taskKeyFormat, keyPrefixRetry, t.ID, t.score)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Key returns a key used to delete and run the archived task.
|
|
||||||
func (t *ArchivedTask) Key() string {
|
|
||||||
return fmt.Sprintf(taskKeyFormat, keyPrefixArchived, t.ID, t.score)
|
|
||||||
}
|
|
||||||
|
|
||||||
// parseTaskKey parses a key string and returns each part of key with proper
|
|
||||||
// type if valid, otherwise it reports an error.
|
|
||||||
func parseTaskKey(key string) (prefix string, id uuid.UUID, score int64, err error) {
|
|
||||||
parts := strings.Split(key, ":")
|
|
||||||
if len(parts) != 3 {
|
|
||||||
return "", uuid.Nil, 0, fmt.Errorf("invalid id")
|
|
||||||
}
|
|
||||||
id, err = uuid.Parse(parts[1])
|
|
||||||
if err != nil {
|
|
||||||
return "", uuid.Nil, 0, fmt.Errorf("invalid id")
|
|
||||||
}
|
|
||||||
score, err = strconv.ParseInt(parts[2], 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
return "", uuid.Nil, 0, fmt.Errorf("invalid id")
|
|
||||||
}
|
|
||||||
prefix = parts[0]
|
|
||||||
if len(prefix) != 1 || !strings.Contains(allKeyPrefixes, prefix) {
|
|
||||||
return "", uuid.Nil, 0, fmt.Errorf("invalid id")
|
|
||||||
}
|
|
||||||
return prefix, id, score, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListOption specifies behavior of list operation.
|
|
||||||
type ListOption interface{}
|
|
||||||
|
|
||||||
// Internal list option representations.
|
|
||||||
type (
|
|
||||||
pageSizeOpt int
|
|
||||||
pageNumOpt int
|
|
||||||
)
|
|
||||||
|
|
||||||
type listOption struct {
|
|
||||||
pageSize int
|
|
||||||
pageNum int
|
|
||||||
}
|
|
||||||
|
|
||||||
const (
|
|
||||||
// Page size used by default in list operation.
|
|
||||||
defaultPageSize = 30
|
|
||||||
|
|
||||||
// Page number used by default in list operation.
|
|
||||||
defaultPageNum = 1
|
|
||||||
)
|
|
||||||
|
|
||||||
func composeListOptions(opts ...ListOption) listOption {
|
|
||||||
res := listOption{
|
|
||||||
pageSize: defaultPageSize,
|
|
||||||
pageNum: defaultPageNum,
|
|
||||||
}
|
|
||||||
for _, opt := range opts {
|
|
||||||
switch opt := opt.(type) {
|
|
||||||
case pageSizeOpt:
|
|
||||||
res.pageSize = int(opt)
|
|
||||||
case pageNumOpt:
|
|
||||||
res.pageNum = int(opt)
|
|
||||||
default:
|
|
||||||
// ignore unexpected option
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
// PageSize returns an option to specify the page size for list operation.
|
|
||||||
//
|
|
||||||
// Negative page size is treated as zero.
|
|
||||||
func PageSize(n int) ListOption {
|
|
||||||
if n < 0 {
|
|
||||||
n = 0
|
|
||||||
}
|
|
||||||
return pageSizeOpt(n)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Page returns an option to specify the page number for list operation.
|
|
||||||
// The value 1 fetches the first page.
|
|
||||||
//
|
|
||||||
// Negative page number is treated as one.
|
|
||||||
func Page(n int) ListOption {
|
|
||||||
if n < 0 {
|
|
||||||
n = 1
|
|
||||||
}
|
|
||||||
return pageNumOpt(n)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListPendingTasks retrieves pending tasks from the specified queue.
|
|
||||||
//
|
|
||||||
// By default, it retrieves the first 30 tasks.
|
|
||||||
func (i *Inspector) ListPendingTasks(qname string, opts ...ListOption) ([]*PendingTask, error) {
|
|
||||||
if err := base.ValidateQueueName(qname); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
opt := composeListOptions(opts...)
|
|
||||||
pgn := rdb.Pagination{Size: opt.pageSize, Page: opt.pageNum - 1}
|
|
||||||
msgs, err := i.rdb.ListPending(qname, pgn)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var tasks []*PendingTask
|
|
||||||
for _, m := range msgs {
|
|
||||||
tasks = append(tasks, &PendingTask{
|
|
||||||
Task: asynq.NewTask(m.Type, m.Payload),
|
|
||||||
ID: m.ID.String(),
|
|
||||||
Queue: m.Queue,
|
|
||||||
MaxRetry: m.Retry,
|
|
||||||
Retried: m.Retried,
|
|
||||||
LastError: m.ErrorMsg,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return tasks, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListActiveTasks retrieves active tasks from the specified queue.
|
|
||||||
//
|
|
||||||
// By default, it retrieves the first 30 tasks.
|
|
||||||
func (i *Inspector) ListActiveTasks(qname string, opts ...ListOption) ([]*ActiveTask, error) {
|
|
||||||
if err := base.ValidateQueueName(qname); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
opt := composeListOptions(opts...)
|
|
||||||
pgn := rdb.Pagination{Size: opt.pageSize, Page: opt.pageNum - 1}
|
|
||||||
msgs, err := i.rdb.ListActive(qname, pgn)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var tasks []*ActiveTask
|
|
||||||
for _, m := range msgs {
|
|
||||||
|
|
||||||
tasks = append(tasks, &ActiveTask{
|
|
||||||
Task: asynq.NewTask(m.Type, m.Payload),
|
|
||||||
ID: m.ID.String(),
|
|
||||||
Queue: m.Queue,
|
|
||||||
MaxRetry: m.Retry,
|
|
||||||
Retried: m.Retried,
|
|
||||||
LastError: m.ErrorMsg,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return tasks, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListScheduledTasks retrieves scheduled tasks from the specified queue.
|
|
||||||
// Tasks are sorted by NextProcessAt field in ascending order.
|
|
||||||
//
|
|
||||||
// By default, it retrieves the first 30 tasks.
|
|
||||||
func (i *Inspector) ListScheduledTasks(qname string, opts ...ListOption) ([]*ScheduledTask, error) {
|
|
||||||
if err := base.ValidateQueueName(qname); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
opt := composeListOptions(opts...)
|
|
||||||
pgn := rdb.Pagination{Size: opt.pageSize, Page: opt.pageNum - 1}
|
|
||||||
zs, err := i.rdb.ListScheduled(qname, pgn)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var tasks []*ScheduledTask
|
|
||||||
for _, z := range zs {
|
|
||||||
processAt := time.Unix(z.Score, 0)
|
|
||||||
t := asynq.NewTask(z.Message.Type, z.Message.Payload)
|
|
||||||
tasks = append(tasks, &ScheduledTask{
|
|
||||||
Task: t,
|
|
||||||
ID: z.Message.ID.String(),
|
|
||||||
Queue: z.Message.Queue,
|
|
||||||
MaxRetry: z.Message.Retry,
|
|
||||||
Retried: z.Message.Retried,
|
|
||||||
LastError: z.Message.ErrorMsg,
|
|
||||||
NextProcessAt: processAt,
|
|
||||||
score: z.Score,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return tasks, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListRetryTasks retrieves retry tasks from the specified queue.
|
|
||||||
// Tasks are sorted by NextProcessAt field in ascending order.
|
|
||||||
//
|
|
||||||
// By default, it retrieves the first 30 tasks.
|
|
||||||
func (i *Inspector) ListRetryTasks(qname string, opts ...ListOption) ([]*RetryTask, error) {
|
|
||||||
if err := base.ValidateQueueName(qname); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
opt := composeListOptions(opts...)
|
|
||||||
pgn := rdb.Pagination{Size: opt.pageSize, Page: opt.pageNum - 1}
|
|
||||||
zs, err := i.rdb.ListRetry(qname, pgn)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var tasks []*RetryTask
|
|
||||||
for _, z := range zs {
|
|
||||||
processAt := time.Unix(z.Score, 0)
|
|
||||||
t := asynq.NewTask(z.Message.Type, z.Message.Payload)
|
|
||||||
tasks = append(tasks, &RetryTask{
|
|
||||||
Task: t,
|
|
||||||
ID: z.Message.ID.String(),
|
|
||||||
Queue: z.Message.Queue,
|
|
||||||
NextProcessAt: processAt,
|
|
||||||
MaxRetry: z.Message.Retry,
|
|
||||||
Retried: z.Message.Retried,
|
|
||||||
// TODO: LastFailedAt: z.Message.LastFailedAt
|
|
||||||
LastError: z.Message.ErrorMsg,
|
|
||||||
score: z.Score,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return tasks, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListArchivedTasks retrieves archived tasks from the specified queue.
|
|
||||||
// Tasks are sorted by LastFailedAt field in descending order.
|
|
||||||
//
|
|
||||||
// By default, it retrieves the first 30 tasks.
|
|
||||||
func (i *Inspector) ListArchivedTasks(qname string, opts ...ListOption) ([]*ArchivedTask, error) {
|
|
||||||
if err := base.ValidateQueueName(qname); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
opt := composeListOptions(opts...)
|
|
||||||
pgn := rdb.Pagination{Size: opt.pageSize, Page: opt.pageNum - 1}
|
|
||||||
zs, err := i.rdb.ListArchived(qname, pgn)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var tasks []*ArchivedTask
|
|
||||||
for _, z := range zs {
|
|
||||||
failedAt := time.Unix(z.Score, 0)
|
|
||||||
t := asynq.NewTask(z.Message.Type, z.Message.Payload)
|
|
||||||
tasks = append(tasks, &ArchivedTask{
|
|
||||||
Task: t,
|
|
||||||
ID: z.Message.ID.String(),
|
|
||||||
Queue: z.Message.Queue,
|
|
||||||
MaxRetry: z.Message.Retry,
|
|
||||||
Retried: z.Message.Retried,
|
|
||||||
LastFailedAt: failedAt,
|
|
||||||
LastError: z.Message.ErrorMsg,
|
|
||||||
score: z.Score,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return tasks, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeleteAllPendingTasks deletes all pending tasks from the specified queue,
|
|
||||||
// and reports the number tasks deleted.
|
|
||||||
func (i *Inspector) DeleteAllPendingTasks(qname string) (int, error) {
|
|
||||||
if err := base.ValidateQueueName(qname); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
n, err := i.rdb.DeleteAllPendingTasks(qname)
|
|
||||||
return int(n), err
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeleteAllScheduledTasks deletes all scheduled tasks from the specified queue,
|
|
||||||
// and reports the number tasks deleted.
|
|
||||||
func (i *Inspector) DeleteAllScheduledTasks(qname string) (int, error) {
|
|
||||||
if err := base.ValidateQueueName(qname); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
n, err := i.rdb.DeleteAllScheduledTasks(qname)
|
|
||||||
return int(n), err
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeleteAllRetryTasks deletes all retry tasks from the specified queue,
|
|
||||||
// and reports the number tasks deleted.
|
|
||||||
func (i *Inspector) DeleteAllRetryTasks(qname string) (int, error) {
|
|
||||||
if err := base.ValidateQueueName(qname); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
n, err := i.rdb.DeleteAllRetryTasks(qname)
|
|
||||||
return int(n), err
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeleteAllArchivedTasks deletes all archived tasks from the specified queue,
|
|
||||||
// and reports the number tasks deleted.
|
|
||||||
func (i *Inspector) DeleteAllArchivedTasks(qname string) (int, error) {
|
|
||||||
if err := base.ValidateQueueName(qname); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
n, err := i.rdb.DeleteAllArchivedTasks(qname)
|
|
||||||
return int(n), err
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeleteTaskByKey deletes a task with the given key from the given queue.
|
|
||||||
func (i *Inspector) DeleteTaskByKey(qname, key string) error {
|
|
||||||
if err := base.ValidateQueueName(qname); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
prefix, id, score, err := parseTaskKey(key)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
switch prefix {
|
|
||||||
case keyPrefixPending:
|
|
||||||
return i.rdb.DeletePendingTask(qname, id)
|
|
||||||
case keyPrefixScheduled:
|
|
||||||
return i.rdb.DeleteScheduledTask(qname, id, score)
|
|
||||||
case keyPrefixRetry:
|
|
||||||
return i.rdb.DeleteRetryTask(qname, id, score)
|
|
||||||
case keyPrefixArchived:
|
|
||||||
return i.rdb.DeleteArchivedTask(qname, id, score)
|
|
||||||
default:
|
|
||||||
return fmt.Errorf("invalid key")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// RunAllScheduledTasks transition all scheduled tasks to pending state from the given queue,
|
|
||||||
// and reports the number of tasks transitioned.
|
|
||||||
func (i *Inspector) RunAllScheduledTasks(qname string) (int, error) {
|
|
||||||
if err := base.ValidateQueueName(qname); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
n, err := i.rdb.RunAllScheduledTasks(qname)
|
|
||||||
return int(n), err
|
|
||||||
}
|
|
||||||
|
|
||||||
// RunAllRetryTasks transition all retry tasks to pending state from the given queue,
|
|
||||||
// and reports the number of tasks transitioned.
|
|
||||||
func (i *Inspector) RunAllRetryTasks(qname string) (int, error) {
|
|
||||||
if err := base.ValidateQueueName(qname); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
n, err := i.rdb.RunAllRetryTasks(qname)
|
|
||||||
return int(n), err
|
|
||||||
}
|
|
||||||
|
|
||||||
// RunAllArchivedTasks transition all archived tasks to pending state from the given queue,
|
|
||||||
// and reports the number of tasks transitioned.
|
|
||||||
func (i *Inspector) RunAllArchivedTasks(qname string) (int, error) {
|
|
||||||
if err := base.ValidateQueueName(qname); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
n, err := i.rdb.RunAllArchivedTasks(qname)
|
|
||||||
return int(n), err
|
|
||||||
}
|
|
||||||
|
|
||||||
// RunTaskByKey transition a task to pending state given task key and queue name.
|
|
||||||
func (i *Inspector) RunTaskByKey(qname, key string) error {
|
|
||||||
if err := base.ValidateQueueName(qname); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
prefix, id, score, err := parseTaskKey(key)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
switch prefix {
|
|
||||||
case keyPrefixScheduled:
|
|
||||||
return i.rdb.RunScheduledTask(qname, id, score)
|
|
||||||
case keyPrefixRetry:
|
|
||||||
return i.rdb.RunRetryTask(qname, id, score)
|
|
||||||
case keyPrefixArchived:
|
|
||||||
return i.rdb.RunArchivedTask(qname, id, score)
|
|
||||||
case keyPrefixPending:
|
|
||||||
return fmt.Errorf("task is already pending for run")
|
|
||||||
default:
|
|
||||||
return fmt.Errorf("invalid key")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ArchiveAllPendingTasks archives all pending tasks from the given queue,
|
|
||||||
// and reports the number of tasks archived.
|
|
||||||
func (i *Inspector) ArchiveAllPendingTasks(qname string) (int, error) {
|
|
||||||
if err := base.ValidateQueueName(qname); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
n, err := i.rdb.ArchiveAllPendingTasks(qname)
|
|
||||||
return int(n), err
|
|
||||||
}
|
|
||||||
|
|
||||||
// ArchiveAllScheduledTasks archives all scheduled tasks from the given queue,
|
|
||||||
// and reports the number of tasks archiveed.
|
|
||||||
func (i *Inspector) ArchiveAllScheduledTasks(qname string) (int, error) {
|
|
||||||
if err := base.ValidateQueueName(qname); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
n, err := i.rdb.ArchiveAllScheduledTasks(qname)
|
|
||||||
return int(n), err
|
|
||||||
}
|
|
||||||
|
|
||||||
// ArchiveAllRetryTasks archives all retry tasks from the given queue,
|
|
||||||
// and reports the number of tasks archiveed.
|
|
||||||
func (i *Inspector) ArchiveAllRetryTasks(qname string) (int, error) {
|
|
||||||
if err := base.ValidateQueueName(qname); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
n, err := i.rdb.ArchiveAllRetryTasks(qname)
|
|
||||||
return int(n), err
|
|
||||||
}
|
|
||||||
|
|
||||||
// ArchiveTaskByKey archives a task with the given key in the given queue.
|
|
||||||
func (i *Inspector) ArchiveTaskByKey(qname, key string) error {
|
|
||||||
if err := base.ValidateQueueName(qname); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
prefix, id, score, err := parseTaskKey(key)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
switch prefix {
|
|
||||||
case keyPrefixPending:
|
|
||||||
return i.rdb.ArchivePendingTask(qname, id)
|
|
||||||
case keyPrefixScheduled:
|
|
||||||
return i.rdb.ArchiveScheduledTask(qname, id, score)
|
|
||||||
case keyPrefixRetry:
|
|
||||||
return i.rdb.ArchiveRetryTask(qname, id, score)
|
|
||||||
case keyPrefixArchived:
|
|
||||||
return fmt.Errorf("task is already archived")
|
|
||||||
default:
|
|
||||||
return fmt.Errorf("invalid key")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// CancelActiveTask sends a signal to cancel processing of the task with
|
|
||||||
// the given id. CancelActiveTask is best-effort, which means that it does not
|
|
||||||
// guarantee that the task with the given id will be canceled. The return
|
|
||||||
// value only indicates whether the cancelation signal has been sent.
|
|
||||||
func (i *Inspector) CancelActiveTask(id string) error {
|
|
||||||
return i.rdb.PublishCancelation(id)
|
|
||||||
}
|
|
||||||
|
|
||||||
// PauseQueue pauses task processing on the specified queue.
|
|
||||||
// If the queue is already paused, it will return a non-nil error.
|
|
||||||
func (i *Inspector) PauseQueue(qname string) error {
|
|
||||||
if err := base.ValidateQueueName(qname); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return i.rdb.Pause(qname)
|
|
||||||
}
|
|
||||||
|
|
||||||
// UnpauseQueue resumes task processing on the specified queue.
|
|
||||||
// If the queue is not paused, it will return a non-nil error.
|
|
||||||
func (i *Inspector) UnpauseQueue(qname string) error {
|
|
||||||
if err := base.ValidateQueueName(qname); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return i.rdb.Unpause(qname)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Servers return a list of running servers' information.
|
|
||||||
func (i *Inspector) Servers() ([]*ServerInfo, error) {
|
|
||||||
servers, err := i.rdb.ListServers()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
workers, err := i.rdb.ListWorkers()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
m := make(map[string]*ServerInfo) // ServerInfo keyed by serverID
|
|
||||||
for _, s := range servers {
|
|
||||||
m[s.ServerID] = &ServerInfo{
|
|
||||||
ID: s.ServerID,
|
|
||||||
Host: s.Host,
|
|
||||||
PID: s.PID,
|
|
||||||
Concurrency: s.Concurrency,
|
|
||||||
Queues: s.Queues,
|
|
||||||
StrictPriority: s.StrictPriority,
|
|
||||||
Started: s.Started,
|
|
||||||
Status: s.Status,
|
|
||||||
ActiveWorkers: make([]*WorkerInfo, 0),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, w := range workers {
|
|
||||||
srvInfo, ok := m[w.ServerID]
|
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
wrkInfo := &WorkerInfo{
|
|
||||||
Started: w.Started,
|
|
||||||
Deadline: w.Deadline,
|
|
||||||
Task: &ActiveTask{
|
|
||||||
Task: asynq.NewTask(w.Type, w.Payload),
|
|
||||||
ID: w.ID,
|
|
||||||
Queue: w.Queue,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
srvInfo.ActiveWorkers = append(srvInfo.ActiveWorkers, wrkInfo)
|
|
||||||
}
|
|
||||||
var out []*ServerInfo
|
|
||||||
for _, srvInfo := range m {
|
|
||||||
out = append(out, srvInfo)
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ServerInfo describes a running Server instance.
|
|
||||||
type ServerInfo struct {
|
|
||||||
// Unique Identifier for the server.
|
|
||||||
ID string
|
|
||||||
// Host machine on which the server is running.
|
|
||||||
Host string
|
|
||||||
// PID of the process in which the server is running.
|
|
||||||
PID int
|
|
||||||
|
|
||||||
// Server configuration details.
|
|
||||||
// See Config doc for field descriptions.
|
|
||||||
Concurrency int
|
|
||||||
Queues map[string]int
|
|
||||||
StrictPriority bool
|
|
||||||
|
|
||||||
// Time the server started.
|
|
||||||
Started time.Time
|
|
||||||
// Status indicates the status of the server.
|
|
||||||
// TODO: Update comment with more details.
|
|
||||||
Status string
|
|
||||||
// A List of active workers currently processing tasks.
|
|
||||||
ActiveWorkers []*WorkerInfo
|
|
||||||
}
|
|
||||||
|
|
||||||
// WorkerInfo describes a running worker processing a task.
|
|
||||||
type WorkerInfo struct {
|
|
||||||
// The task the worker is processing.
|
|
||||||
Task *ActiveTask
|
|
||||||
// Time the worker started processing the task.
|
|
||||||
Started time.Time
|
|
||||||
// Time the worker needs to finish processing the task by.
|
|
||||||
Deadline time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
// ClusterKeySlot returns an integer identifying the hash slot the given queue hashes to.
|
|
||||||
func (i *Inspector) ClusterKeySlot(qname string) (int64, error) {
|
|
||||||
return i.rdb.ClusterKeySlot(qname)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ClusterNode describes a node in redis cluster.
|
|
||||||
type ClusterNode struct {
|
|
||||||
// Node ID in the cluster.
|
|
||||||
ID string
|
|
||||||
|
|
||||||
// Address of the node.
|
|
||||||
Addr string
|
|
||||||
}
|
|
||||||
|
|
||||||
// ClusterNodes returns a list of nodes the given queue belongs to.
|
|
||||||
func (i *Inspector) ClusterNodes(qname string) ([]ClusterNode, error) {
|
|
||||||
nodes, err := i.rdb.ClusterNodes(qname)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var res []ClusterNode
|
|
||||||
for _, node := range nodes {
|
|
||||||
res = append(res, ClusterNode{ID: node.ID, Addr: node.Addr})
|
|
||||||
}
|
|
||||||
return res, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SchedulerEntry holds information about a periodic task registered with a scheduler.
|
|
||||||
type SchedulerEntry struct {
|
|
||||||
// Identifier of this entry.
|
|
||||||
ID string
|
|
||||||
|
|
||||||
// Spec describes the schedule of this entry.
|
|
||||||
Spec string
|
|
||||||
|
|
||||||
// Periodic Task registered for this entry.
|
|
||||||
Task *asynq.Task
|
|
||||||
|
|
||||||
// Opts is the options for the periodic task.
|
|
||||||
Opts []asynq.Option
|
|
||||||
|
|
||||||
// Next shows the next time the task will be enqueued.
|
|
||||||
Next time.Time
|
|
||||||
|
|
||||||
// Prev shows the last time the task was enqueued.
|
|
||||||
// Zero time if task was never enqueued.
|
|
||||||
Prev time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
// SchedulerEntries returns a list of all entries registered with
|
|
||||||
// currently running schedulers.
|
|
||||||
func (i *Inspector) SchedulerEntries() ([]*SchedulerEntry, error) {
|
|
||||||
var entries []*SchedulerEntry
|
|
||||||
res, err := i.rdb.ListSchedulerEntries()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
for _, e := range res {
|
|
||||||
task := asynq.NewTask(e.Type, e.Payload)
|
|
||||||
var opts []asynq.Option
|
|
||||||
for _, s := range e.Opts {
|
|
||||||
if o, err := parseOption(s); err == nil {
|
|
||||||
// ignore bad data
|
|
||||||
opts = append(opts, o)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
entries = append(entries, &SchedulerEntry{
|
|
||||||
ID: e.ID,
|
|
||||||
Spec: e.Spec,
|
|
||||||
Task: task,
|
|
||||||
Opts: opts,
|
|
||||||
Next: e.Next,
|
|
||||||
Prev: e.Prev,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return entries, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// parseOption interprets a string s as an Option and returns the Option if parsing is successful,
|
|
||||||
// otherwise returns non-nil error.
|
|
||||||
func parseOption(s string) (asynq.Option, error) {
|
|
||||||
fn, arg := parseOptionFunc(s), parseOptionArg(s)
|
|
||||||
switch fn {
|
|
||||||
case "Queue":
|
|
||||||
qname, err := strconv.Unquote(arg)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return asynq.Queue(qname), nil
|
|
||||||
case "MaxRetry":
|
|
||||||
n, err := strconv.Atoi(arg)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return asynq.MaxRetry(n), nil
|
|
||||||
case "Timeout":
|
|
||||||
d, err := time.ParseDuration(arg)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return asynq.Timeout(d), nil
|
|
||||||
case "Deadline":
|
|
||||||
t, err := time.Parse(time.UnixDate, arg)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return asynq.Deadline(t), nil
|
|
||||||
case "Unique":
|
|
||||||
d, err := time.ParseDuration(arg)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return asynq.Unique(d), nil
|
|
||||||
case "ProcessAt":
|
|
||||||
t, err := time.Parse(time.UnixDate, arg)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return asynq.ProcessAt(t), nil
|
|
||||||
case "ProcessIn":
|
|
||||||
d, err := time.ParseDuration(arg)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return asynq.ProcessIn(d), nil
|
|
||||||
default:
|
|
||||||
return nil, fmt.Errorf("cannot not parse option string %q", s)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseOptionFunc(s string) string {
|
|
||||||
i := strings.Index(s, "(")
|
|
||||||
return s[:i]
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseOptionArg(s string) string {
|
|
||||||
i := strings.Index(s, "(")
|
|
||||||
if i >= 0 {
|
|
||||||
j := strings.Index(s, ")")
|
|
||||||
if j > i {
|
|
||||||
return s[i+1 : j]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
// SchedulerEnqueueEvent holds information about an enqueue event by a scheduler.
|
|
||||||
type SchedulerEnqueueEvent struct {
|
|
||||||
// ID of the task that was enqueued.
|
|
||||||
TaskID string
|
|
||||||
|
|
||||||
// Time the task was enqueued.
|
|
||||||
EnqueuedAt time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListSchedulerEnqueueEvents retrieves a list of enqueue events from the specified scheduler entry.
|
|
||||||
//
|
|
||||||
// By default, it retrieves the first 30 tasks.
|
|
||||||
func (i *Inspector) ListSchedulerEnqueueEvents(entryID string, opts ...ListOption) ([]*SchedulerEnqueueEvent, error) {
|
|
||||||
opt := composeListOptions(opts...)
|
|
||||||
pgn := rdb.Pagination{Size: opt.pageSize, Page: opt.pageNum - 1}
|
|
||||||
data, err := i.rdb.ListSchedulerEnqueueEvents(entryID, pgn)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var events []*SchedulerEnqueueEvent
|
|
||||||
for _, e := range data {
|
|
||||||
events = append(events, &SchedulerEnqueueEvent{TaskID: e.TaskID, EnqueuedAt: e.EnqueuedAt})
|
|
||||||
}
|
|
||||||
return events, nil
|
|
||||||
}
|
|
||||||
@@ -1,373 +0,0 @@
|
|||||||
// Copyright 2020 Kentaro Hibino. All rights reserved.
|
|
||||||
// Use of this source code is governed by a MIT license
|
|
||||||
// that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
// Package asynqtest defines test helpers for asynq and its internal packages.
|
|
||||||
package asynqtest
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"math"
|
|
||||||
"sort"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/go-redis/redis/v7"
|
|
||||||
"github.com/google/go-cmp/cmp"
|
|
||||||
"github.com/google/go-cmp/cmp/cmpopts"
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"github.com/hibiken/asynq/internal/base"
|
|
||||||
)
|
|
||||||
|
|
||||||
// EquateInt64Approx returns a Comparer option that treats int64 values
|
|
||||||
// to be equal if they are within the given margin.
|
|
||||||
func EquateInt64Approx(margin int64) cmp.Option {
|
|
||||||
return cmp.Comparer(func(a, b int64) bool {
|
|
||||||
return math.Abs(float64(a-b)) <= float64(margin)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// SortMsgOpt is a cmp.Option to sort base.TaskMessage for comparing slice of task messages.
|
|
||||||
var SortMsgOpt = cmp.Transformer("SortTaskMessages", func(in []*base.TaskMessage) []*base.TaskMessage {
|
|
||||||
out := append([]*base.TaskMessage(nil), in...) // Copy input to avoid mutating it
|
|
||||||
sort.Slice(out, func(i, j int) bool {
|
|
||||||
return out[i].ID.String() < out[j].ID.String()
|
|
||||||
})
|
|
||||||
return out
|
|
||||||
})
|
|
||||||
|
|
||||||
// SortZSetEntryOpt is an cmp.Option to sort ZSetEntry for comparing slice of zset entries.
|
|
||||||
var SortZSetEntryOpt = cmp.Transformer("SortZSetEntries", func(in []base.Z) []base.Z {
|
|
||||||
out := append([]base.Z(nil), in...) // Copy input to avoid mutating it
|
|
||||||
sort.Slice(out, func(i, j int) bool {
|
|
||||||
return out[i].Message.ID.String() < out[j].Message.ID.String()
|
|
||||||
})
|
|
||||||
return out
|
|
||||||
})
|
|
||||||
|
|
||||||
// SortServerInfoOpt is a cmp.Option to sort base.ServerInfo for comparing slice of process info.
|
|
||||||
var SortServerInfoOpt = cmp.Transformer("SortServerInfo", func(in []*base.ServerInfo) []*base.ServerInfo {
|
|
||||||
out := append([]*base.ServerInfo(nil), in...) // Copy input to avoid mutating it
|
|
||||||
sort.Slice(out, func(i, j int) bool {
|
|
||||||
if out[i].Host != out[j].Host {
|
|
||||||
return out[i].Host < out[j].Host
|
|
||||||
}
|
|
||||||
return out[i].PID < out[j].PID
|
|
||||||
})
|
|
||||||
return out
|
|
||||||
})
|
|
||||||
|
|
||||||
// SortWorkerInfoOpt is a cmp.Option to sort base.WorkerInfo for comparing slice of worker info.
|
|
||||||
var SortWorkerInfoOpt = cmp.Transformer("SortWorkerInfo", func(in []*base.WorkerInfo) []*base.WorkerInfo {
|
|
||||||
out := append([]*base.WorkerInfo(nil), in...) // Copy input to avoid mutating it
|
|
||||||
sort.Slice(out, func(i, j int) bool {
|
|
||||||
return out[i].ID < out[j].ID
|
|
||||||
})
|
|
||||||
return out
|
|
||||||
})
|
|
||||||
|
|
||||||
// SortSchedulerEntryOpt is a cmp.Option to sort base.SchedulerEntry for comparing slice of entries.
|
|
||||||
var SortSchedulerEntryOpt = cmp.Transformer("SortSchedulerEntry", func(in []*base.SchedulerEntry) []*base.SchedulerEntry {
|
|
||||||
out := append([]*base.SchedulerEntry(nil), in...) // Copy input to avoid mutating it
|
|
||||||
sort.Slice(out, func(i, j int) bool {
|
|
||||||
return out[i].Spec < out[j].Spec
|
|
||||||
})
|
|
||||||
return out
|
|
||||||
})
|
|
||||||
|
|
||||||
// SortSchedulerEnqueueEventOpt is a cmp.Option to sort base.SchedulerEnqueueEvent for comparing slice of events.
|
|
||||||
var SortSchedulerEnqueueEventOpt = cmp.Transformer("SortSchedulerEnqueueEvent", func(in []*base.SchedulerEnqueueEvent) []*base.SchedulerEnqueueEvent {
|
|
||||||
out := append([]*base.SchedulerEnqueueEvent(nil), in...)
|
|
||||||
sort.Slice(out, func(i, j int) bool {
|
|
||||||
return out[i].EnqueuedAt.Unix() < out[j].EnqueuedAt.Unix()
|
|
||||||
})
|
|
||||||
return out
|
|
||||||
})
|
|
||||||
|
|
||||||
// SortStringSliceOpt is a cmp.Option to sort string slice.
|
|
||||||
var SortStringSliceOpt = cmp.Transformer("SortStringSlice", func(in []string) []string {
|
|
||||||
out := append([]string(nil), in...)
|
|
||||||
sort.Strings(out)
|
|
||||||
return out
|
|
||||||
})
|
|
||||||
|
|
||||||
// IgnoreIDOpt is an cmp.Option to ignore ID field in task messages when comparing.
|
|
||||||
var IgnoreIDOpt = cmpopts.IgnoreFields(base.TaskMessage{}, "ID")
|
|
||||||
|
|
||||||
// NewTaskMessage returns a new instance of TaskMessage given a task type and payload.
|
|
||||||
func NewTaskMessage(taskType string, payload map[string]interface{}) *base.TaskMessage {
|
|
||||||
return NewTaskMessageWithQueue(taskType, payload, base.DefaultQueueName)
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewTaskMessageWithQueue returns a new instance of TaskMessage given a
|
|
||||||
// task type, payload and queue name.
|
|
||||||
func NewTaskMessageWithQueue(taskType string, payload map[string]interface{}, qname string) *base.TaskMessage {
|
|
||||||
return &base.TaskMessage{
|
|
||||||
ID: uuid.New(),
|
|
||||||
Type: taskType,
|
|
||||||
Queue: qname,
|
|
||||||
Retry: 25,
|
|
||||||
Payload: payload,
|
|
||||||
Timeout: 1800, // default timeout of 30 mins
|
|
||||||
Deadline: 0, // no deadline
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TaskMessageAfterRetry returns an updated copy of t after retry.
|
|
||||||
// It increments retry count and sets the error message.
|
|
||||||
func TaskMessageAfterRetry(t base.TaskMessage, errMsg string) *base.TaskMessage {
|
|
||||||
t.Retried = t.Retried + 1
|
|
||||||
t.ErrorMsg = errMsg
|
|
||||||
return &t
|
|
||||||
}
|
|
||||||
|
|
||||||
// TaskMessageWithError returns an updated copy of t with the given error message.
|
|
||||||
func TaskMessageWithError(t base.TaskMessage, errMsg string) *base.TaskMessage {
|
|
||||||
t.ErrorMsg = errMsg
|
|
||||||
return &t
|
|
||||||
}
|
|
||||||
|
|
||||||
// MustMarshal marshals given task message and returns a json string.
|
|
||||||
// Calling test will fail if marshaling errors out.
|
|
||||||
func MustMarshal(tb testing.TB, msg *base.TaskMessage) string {
|
|
||||||
tb.Helper()
|
|
||||||
data, err := json.Marshal(msg)
|
|
||||||
if err != nil {
|
|
||||||
tb.Fatal(err)
|
|
||||||
}
|
|
||||||
return string(data)
|
|
||||||
}
|
|
||||||
|
|
||||||
// MustUnmarshal unmarshals given string into task message struct.
|
|
||||||
// Calling test will fail if unmarshaling errors out.
|
|
||||||
func MustUnmarshal(tb testing.TB, data string) *base.TaskMessage {
|
|
||||||
tb.Helper()
|
|
||||||
var msg base.TaskMessage
|
|
||||||
err := json.Unmarshal([]byte(data), &msg)
|
|
||||||
if err != nil {
|
|
||||||
tb.Fatal(err)
|
|
||||||
}
|
|
||||||
return &msg
|
|
||||||
}
|
|
||||||
|
|
||||||
// MustMarshalSlice marshals a slice of task messages and return a slice of
|
|
||||||
// json strings. Calling test will fail if marshaling errors out.
|
|
||||||
func MustMarshalSlice(tb testing.TB, msgs []*base.TaskMessage) []string {
|
|
||||||
tb.Helper()
|
|
||||||
var data []string
|
|
||||||
for _, m := range msgs {
|
|
||||||
data = append(data, MustMarshal(tb, m))
|
|
||||||
}
|
|
||||||
return data
|
|
||||||
}
|
|
||||||
|
|
||||||
// MustUnmarshalSlice unmarshals a slice of strings into a slice of task message structs.
|
|
||||||
// Calling test will fail if marshaling errors out.
|
|
||||||
func MustUnmarshalSlice(tb testing.TB, data []string) []*base.TaskMessage {
|
|
||||||
tb.Helper()
|
|
||||||
var msgs []*base.TaskMessage
|
|
||||||
for _, s := range data {
|
|
||||||
msgs = append(msgs, MustUnmarshal(tb, s))
|
|
||||||
}
|
|
||||||
return msgs
|
|
||||||
}
|
|
||||||
|
|
||||||
// FlushDB deletes all the keys of the currently selected DB.
|
|
||||||
func FlushDB(tb testing.TB, r redis.UniversalClient) {
|
|
||||||
tb.Helper()
|
|
||||||
switch r := r.(type) {
|
|
||||||
case *redis.Client:
|
|
||||||
if err := r.FlushDB().Err(); err != nil {
|
|
||||||
tb.Fatal(err)
|
|
||||||
}
|
|
||||||
case *redis.ClusterClient:
|
|
||||||
err := r.ForEachMaster(func(c *redis.Client) error {
|
|
||||||
if err := c.FlushAll().Err(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
tb.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// SeedPendingQueue initializes the specified queue with the given messages.
|
|
||||||
func SeedPendingQueue(tb testing.TB, r redis.UniversalClient, msgs []*base.TaskMessage, qname string) {
|
|
||||||
tb.Helper()
|
|
||||||
r.SAdd(base.AllQueues, qname)
|
|
||||||
seedRedisList(tb, r, base.QueueKey(qname), msgs)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SeedActiveQueue initializes the active queue with the given messages.
|
|
||||||
func SeedActiveQueue(tb testing.TB, r redis.UniversalClient, msgs []*base.TaskMessage, qname string) {
|
|
||||||
tb.Helper()
|
|
||||||
r.SAdd(base.AllQueues, qname)
|
|
||||||
seedRedisList(tb, r, base.ActiveKey(qname), msgs)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SeedScheduledQueue initializes the scheduled queue with the given messages.
|
|
||||||
func SeedScheduledQueue(tb testing.TB, r redis.UniversalClient, entries []base.Z, qname string) {
|
|
||||||
tb.Helper()
|
|
||||||
r.SAdd(base.AllQueues, qname)
|
|
||||||
seedRedisZSet(tb, r, base.ScheduledKey(qname), entries)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SeedRetryQueue initializes the retry queue with the given messages.
|
|
||||||
func SeedRetryQueue(tb testing.TB, r redis.UniversalClient, entries []base.Z, qname string) {
|
|
||||||
tb.Helper()
|
|
||||||
r.SAdd(base.AllQueues, qname)
|
|
||||||
seedRedisZSet(tb, r, base.RetryKey(qname), entries)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SeedArchivedQueue initializes the archived queue with the given messages.
|
|
||||||
func SeedArchivedQueue(tb testing.TB, r redis.UniversalClient, entries []base.Z, qname string) {
|
|
||||||
tb.Helper()
|
|
||||||
r.SAdd(base.AllQueues, qname)
|
|
||||||
seedRedisZSet(tb, r, base.ArchivedKey(qname), entries)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SeedDeadlines initializes the deadlines set with the given entries.
|
|
||||||
func SeedDeadlines(tb testing.TB, r redis.UniversalClient, entries []base.Z, qname string) {
|
|
||||||
tb.Helper()
|
|
||||||
r.SAdd(base.AllQueues, qname)
|
|
||||||
seedRedisZSet(tb, r, base.DeadlinesKey(qname), entries)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SeedAllPendingQueues initializes all of the specified queues with the given messages.
|
|
||||||
//
|
|
||||||
// pending maps a queue name to a list of messages.
|
|
||||||
func SeedAllPendingQueues(tb testing.TB, r redis.UniversalClient, pending map[string][]*base.TaskMessage) {
|
|
||||||
for q, msgs := range pending {
|
|
||||||
SeedPendingQueue(tb, r, msgs, q)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// SeedAllActiveQueues initializes all of the specified active queues with the given messages.
|
|
||||||
func SeedAllActiveQueues(tb testing.TB, r redis.UniversalClient, active map[string][]*base.TaskMessage) {
|
|
||||||
for q, msgs := range active {
|
|
||||||
SeedActiveQueue(tb, r, msgs, q)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// SeedAllScheduledQueues initializes all of the specified scheduled queues with the given entries.
|
|
||||||
func SeedAllScheduledQueues(tb testing.TB, r redis.UniversalClient, scheduled map[string][]base.Z) {
|
|
||||||
for q, entries := range scheduled {
|
|
||||||
SeedScheduledQueue(tb, r, entries, q)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// SeedAllRetryQueues initializes all of the specified retry queues with the given entries.
|
|
||||||
func SeedAllRetryQueues(tb testing.TB, r redis.UniversalClient, retry map[string][]base.Z) {
|
|
||||||
for q, entries := range retry {
|
|
||||||
SeedRetryQueue(tb, r, entries, q)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// SeedAllArchivedQueues initializes all of the specified archived queues with the given entries.
|
|
||||||
func SeedAllArchivedQueues(tb testing.TB, r redis.UniversalClient, archived map[string][]base.Z) {
|
|
||||||
for q, entries := range archived {
|
|
||||||
SeedArchivedQueue(tb, r, entries, q)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// SeedAllDeadlines initializes all of the deadlines with the given entries.
|
|
||||||
func SeedAllDeadlines(tb testing.TB, r redis.UniversalClient, deadlines map[string][]base.Z) {
|
|
||||||
for q, entries := range deadlines {
|
|
||||||
SeedDeadlines(tb, r, entries, q)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func seedRedisList(tb testing.TB, c redis.UniversalClient, key string, msgs []*base.TaskMessage) {
|
|
||||||
data := MustMarshalSlice(tb, msgs)
|
|
||||||
for _, s := range data {
|
|
||||||
if err := c.LPush(key, s).Err(); err != nil {
|
|
||||||
tb.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func seedRedisZSet(tb testing.TB, c redis.UniversalClient, key string, items []base.Z) {
|
|
||||||
for _, item := range items {
|
|
||||||
z := &redis.Z{Member: MustMarshal(tb, item.Message), Score: float64(item.Score)}
|
|
||||||
if err := c.ZAdd(key, z).Err(); err != nil {
|
|
||||||
tb.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetPendingMessages returns all pending messages in the given queue.
|
|
||||||
func GetPendingMessages(tb testing.TB, r redis.UniversalClient, qname string) []*base.TaskMessage {
|
|
||||||
tb.Helper()
|
|
||||||
return getListMessages(tb, r, base.QueueKey(qname))
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetActiveMessages returns all active messages in the given queue.
|
|
||||||
func GetActiveMessages(tb testing.TB, r redis.UniversalClient, qname string) []*base.TaskMessage {
|
|
||||||
tb.Helper()
|
|
||||||
return getListMessages(tb, r, base.ActiveKey(qname))
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetScheduledMessages returns all scheduled task messages in the given queue.
|
|
||||||
func GetScheduledMessages(tb testing.TB, r redis.UniversalClient, qname string) []*base.TaskMessage {
|
|
||||||
tb.Helper()
|
|
||||||
return getZSetMessages(tb, r, base.ScheduledKey(qname))
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetRetryMessages returns all retry messages in the given queue.
|
|
||||||
func GetRetryMessages(tb testing.TB, r redis.UniversalClient, qname string) []*base.TaskMessage {
|
|
||||||
tb.Helper()
|
|
||||||
return getZSetMessages(tb, r, base.RetryKey(qname))
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetArchivedMessages returns all archived messages in the given queue.
|
|
||||||
func GetArchivedMessages(tb testing.TB, r redis.UniversalClient, qname string) []*base.TaskMessage {
|
|
||||||
tb.Helper()
|
|
||||||
return getZSetMessages(tb, r, base.ArchivedKey(qname))
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetScheduledEntries returns all scheduled messages and its score in the given queue.
|
|
||||||
func GetScheduledEntries(tb testing.TB, r redis.UniversalClient, qname string) []base.Z {
|
|
||||||
tb.Helper()
|
|
||||||
return getZSetEntries(tb, r, base.ScheduledKey(qname))
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetRetryEntries returns all retry messages and its score in the given queue.
|
|
||||||
func GetRetryEntries(tb testing.TB, r redis.UniversalClient, qname string) []base.Z {
|
|
||||||
tb.Helper()
|
|
||||||
return getZSetEntries(tb, r, base.RetryKey(qname))
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetArchivedEntries returns all archived messages and its score in the given queue.
|
|
||||||
func GetArchivedEntries(tb testing.TB, r redis.UniversalClient, qname string) []base.Z {
|
|
||||||
tb.Helper()
|
|
||||||
return getZSetEntries(tb, r, base.ArchivedKey(qname))
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetDeadlinesEntries returns all task messages and its score in the deadlines set for the given queue.
|
|
||||||
func GetDeadlinesEntries(tb testing.TB, r redis.UniversalClient, qname string) []base.Z {
|
|
||||||
tb.Helper()
|
|
||||||
return getZSetEntries(tb, r, base.DeadlinesKey(qname))
|
|
||||||
}
|
|
||||||
|
|
||||||
func getListMessages(tb testing.TB, r redis.UniversalClient, list string) []*base.TaskMessage {
|
|
||||||
data := r.LRange(list, 0, -1).Val()
|
|
||||||
return MustUnmarshalSlice(tb, data)
|
|
||||||
}
|
|
||||||
|
|
||||||
func getZSetMessages(tb testing.TB, r redis.UniversalClient, zset string) []*base.TaskMessage {
|
|
||||||
data := r.ZRange(zset, 0, -1).Val()
|
|
||||||
return MustUnmarshalSlice(tb, data)
|
|
||||||
}
|
|
||||||
|
|
||||||
func getZSetEntries(tb testing.TB, r redis.UniversalClient, zset string) []base.Z {
|
|
||||||
data := r.ZRangeWithScores(zset, 0, -1).Val()
|
|
||||||
var entries []base.Z
|
|
||||||
for _, z := range data {
|
|
||||||
entries = append(entries, base.Z{
|
|
||||||
Message: MustUnmarshal(tb, z.Member.(string)),
|
|
||||||
Score: int64(z.Score),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return entries
|
|
||||||
}
|
|
||||||
@@ -7,25 +7,29 @@ package base
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"crypto/md5"
|
||||||
|
"encoding/hex"
|
||||||
"fmt"
|
"fmt"
|
||||||
"sort"
|
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/go-redis/redis/v7"
|
"github.com/golang/protobuf/ptypes"
|
||||||
"github.com/google/uuid"
|
"github.com/hibiken/asynq/internal/errors"
|
||||||
|
pb "github.com/hibiken/asynq/internal/proto"
|
||||||
|
"github.com/hibiken/asynq/internal/timeutil"
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
"google.golang.org/protobuf/proto"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Version of asynq library and CLI.
|
// Version of asynq library and CLI.
|
||||||
const Version = "0.16.0"
|
const Version = "0.24.1"
|
||||||
|
|
||||||
// DefaultQueueName is the queue name used if none are specified by user.
|
// DefaultQueueName is the queue name used if none are specified by user.
|
||||||
const DefaultQueueName = "default"
|
const DefaultQueueName = "default"
|
||||||
|
|
||||||
// DefaultQueue is the redis key for the default queue.
|
// DefaultQueue is the redis key for the default queue.
|
||||||
var DefaultQueue = QueueKey(DefaultQueueName)
|
var DefaultQueue = PendingKey(DefaultQueueName)
|
||||||
|
|
||||||
// Global Redis keys.
|
// Global Redis keys.
|
||||||
const (
|
const (
|
||||||
@@ -36,58 +40,140 @@ const (
|
|||||||
CancelChannel = "asynq:cancel" // PubSub channel
|
CancelChannel = "asynq:cancel" // PubSub channel
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// TaskState denotes the state of a task.
|
||||||
|
type TaskState int
|
||||||
|
|
||||||
|
const (
|
||||||
|
TaskStateActive TaskState = iota + 1
|
||||||
|
TaskStatePending
|
||||||
|
TaskStateScheduled
|
||||||
|
TaskStateRetry
|
||||||
|
TaskStateArchived
|
||||||
|
TaskStateCompleted
|
||||||
|
TaskStateAggregating // describes a state where task is waiting in a group to be aggregated
|
||||||
|
)
|
||||||
|
|
||||||
|
func (s TaskState) String() string {
|
||||||
|
switch s {
|
||||||
|
case TaskStateActive:
|
||||||
|
return "active"
|
||||||
|
case TaskStatePending:
|
||||||
|
return "pending"
|
||||||
|
case TaskStateScheduled:
|
||||||
|
return "scheduled"
|
||||||
|
case TaskStateRetry:
|
||||||
|
return "retry"
|
||||||
|
case TaskStateArchived:
|
||||||
|
return "archived"
|
||||||
|
case TaskStateCompleted:
|
||||||
|
return "completed"
|
||||||
|
case TaskStateAggregating:
|
||||||
|
return "aggregating"
|
||||||
|
}
|
||||||
|
panic(fmt.Sprintf("internal error: unknown task state %d", s))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TaskStateFromString(s string) (TaskState, error) {
|
||||||
|
switch s {
|
||||||
|
case "active":
|
||||||
|
return TaskStateActive, nil
|
||||||
|
case "pending":
|
||||||
|
return TaskStatePending, nil
|
||||||
|
case "scheduled":
|
||||||
|
return TaskStateScheduled, nil
|
||||||
|
case "retry":
|
||||||
|
return TaskStateRetry, nil
|
||||||
|
case "archived":
|
||||||
|
return TaskStateArchived, nil
|
||||||
|
case "completed":
|
||||||
|
return TaskStateCompleted, nil
|
||||||
|
case "aggregating":
|
||||||
|
return TaskStateAggregating, nil
|
||||||
|
}
|
||||||
|
return 0, errors.E(errors.FailedPrecondition, fmt.Sprintf("%q is not supported task state", s))
|
||||||
|
}
|
||||||
|
|
||||||
// ValidateQueueName validates a given qname to be used as a queue name.
|
// ValidateQueueName validates a given qname to be used as a queue name.
|
||||||
// Returns nil if valid, otherwise returns non-nil error.
|
// Returns nil if valid, otherwise returns non-nil error.
|
||||||
func ValidateQueueName(qname string) error {
|
func ValidateQueueName(qname string) error {
|
||||||
if len(qname) == 0 {
|
if len(strings.TrimSpace(qname)) == 0 {
|
||||||
return fmt.Errorf("queue name must contain one or more characters")
|
return fmt.Errorf("queue name must contain one or more characters")
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// QueueKey returns a redis key for the given queue name.
|
// QueueKeyPrefix returns a prefix for all keys in the given queue.
|
||||||
func QueueKey(qname string) string {
|
func QueueKeyPrefix(qname string) string {
|
||||||
return fmt.Sprintf("asynq:{%s}", qname)
|
return fmt.Sprintf("asynq:{%s}:", qname)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TaskKeyPrefix returns a prefix for task key.
|
||||||
|
func TaskKeyPrefix(qname string) string {
|
||||||
|
return fmt.Sprintf("%st:", QueueKeyPrefix(qname))
|
||||||
|
}
|
||||||
|
|
||||||
|
// TaskKey returns a redis key for the given task message.
|
||||||
|
func TaskKey(qname, id string) string {
|
||||||
|
return fmt.Sprintf("%s%s", TaskKeyPrefix(qname), id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PendingKey returns a redis key for the given queue name.
|
||||||
|
func PendingKey(qname string) string {
|
||||||
|
return fmt.Sprintf("%spending", QueueKeyPrefix(qname))
|
||||||
}
|
}
|
||||||
|
|
||||||
// ActiveKey returns a redis key for the active tasks.
|
// ActiveKey returns a redis key for the active tasks.
|
||||||
func ActiveKey(qname string) string {
|
func ActiveKey(qname string) string {
|
||||||
return fmt.Sprintf("asynq:{%s}:active", qname)
|
return fmt.Sprintf("%sactive", QueueKeyPrefix(qname))
|
||||||
}
|
}
|
||||||
|
|
||||||
// ScheduledKey returns a redis key for the scheduled tasks.
|
// ScheduledKey returns a redis key for the scheduled tasks.
|
||||||
func ScheduledKey(qname string) string {
|
func ScheduledKey(qname string) string {
|
||||||
return fmt.Sprintf("asynq:{%s}:scheduled", qname)
|
return fmt.Sprintf("%sscheduled", QueueKeyPrefix(qname))
|
||||||
}
|
}
|
||||||
|
|
||||||
// RetryKey returns a redis key for the retry tasks.
|
// RetryKey returns a redis key for the retry tasks.
|
||||||
func RetryKey(qname string) string {
|
func RetryKey(qname string) string {
|
||||||
return fmt.Sprintf("asynq:{%s}:retry", qname)
|
return fmt.Sprintf("%sretry", QueueKeyPrefix(qname))
|
||||||
}
|
}
|
||||||
|
|
||||||
// ArchivedKey returns a redis key for the archived tasks.
|
// ArchivedKey returns a redis key for the archived tasks.
|
||||||
func ArchivedKey(qname string) string {
|
func ArchivedKey(qname string) string {
|
||||||
return fmt.Sprintf("asynq:{%s}:archived", qname)
|
return fmt.Sprintf("%sarchived", QueueKeyPrefix(qname))
|
||||||
}
|
}
|
||||||
|
|
||||||
// DeadlinesKey returns a redis key for the deadlines.
|
// LeaseKey returns a redis key for the lease.
|
||||||
func DeadlinesKey(qname string) string {
|
func LeaseKey(qname string) string {
|
||||||
return fmt.Sprintf("asynq:{%s}:deadlines", qname)
|
return fmt.Sprintf("%slease", QueueKeyPrefix(qname))
|
||||||
|
}
|
||||||
|
|
||||||
|
func CompletedKey(qname string) string {
|
||||||
|
return fmt.Sprintf("%scompleted", QueueKeyPrefix(qname))
|
||||||
}
|
}
|
||||||
|
|
||||||
// PausedKey returns a redis key to indicate that the given queue is paused.
|
// PausedKey returns a redis key to indicate that the given queue is paused.
|
||||||
func PausedKey(qname string) string {
|
func PausedKey(qname string) string {
|
||||||
return fmt.Sprintf("asynq:{%s}:paused", qname)
|
return fmt.Sprintf("%spaused", QueueKeyPrefix(qname))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ProcessedTotalKey returns a redis key for total processed count for the given queue.
|
||||||
|
func ProcessedTotalKey(qname string) string {
|
||||||
|
return fmt.Sprintf("%sprocessed", QueueKeyPrefix(qname))
|
||||||
|
}
|
||||||
|
|
||||||
|
// FailedTotalKey returns a redis key for total failure count for the given queue.
|
||||||
|
func FailedTotalKey(qname string) string {
|
||||||
|
return fmt.Sprintf("%sfailed", QueueKeyPrefix(qname))
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProcessedKey returns a redis key for processed count for the given day for the queue.
|
// ProcessedKey returns a redis key for processed count for the given day for the queue.
|
||||||
func ProcessedKey(qname string, t time.Time) string {
|
func ProcessedKey(qname string, t time.Time) string {
|
||||||
return fmt.Sprintf("asynq:{%s}:processed:%s", qname, t.UTC().Format("2006-01-02"))
|
return fmt.Sprintf("%sprocessed:%s", QueueKeyPrefix(qname), t.UTC().Format("2006-01-02"))
|
||||||
}
|
}
|
||||||
|
|
||||||
// FailedKey returns a redis key for failure count for the given day for the queue.
|
// FailedKey returns a redis key for failure count for the given day for the queue.
|
||||||
func FailedKey(qname string, t time.Time) string {
|
func FailedKey(qname string, t time.Time) string {
|
||||||
return fmt.Sprintf("asynq:{%s}:failed:%s", qname, t.UTC().Format("2006-01-02"))
|
return fmt.Sprintf("%sfailed:%s", QueueKeyPrefix(qname), t.UTC().Format("2006-01-02"))
|
||||||
}
|
}
|
||||||
|
|
||||||
// ServerInfoKey returns a redis key for process info.
|
// ServerInfoKey returns a redis key for process info.
|
||||||
@@ -111,32 +197,38 @@ func SchedulerHistoryKey(entryID string) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// UniqueKey returns a redis key with the given type, payload, and queue name.
|
// UniqueKey returns a redis key with the given type, payload, and queue name.
|
||||||
func UniqueKey(qname, tasktype string, payload map[string]interface{}) string {
|
func UniqueKey(qname, tasktype string, payload []byte) string {
|
||||||
return fmt.Sprintf("asynq:{%s}:unique:%s:%s", qname, tasktype, serializePayload(payload))
|
if payload == nil {
|
||||||
|
return fmt.Sprintf("%sunique:%s:", QueueKeyPrefix(qname), tasktype)
|
||||||
|
}
|
||||||
|
checksum := md5.Sum(payload)
|
||||||
|
return fmt.Sprintf("%sunique:%s:%s", QueueKeyPrefix(qname), tasktype, hex.EncodeToString(checksum[:]))
|
||||||
}
|
}
|
||||||
|
|
||||||
func serializePayload(payload map[string]interface{}) string {
|
// GroupKeyPrefix returns a prefix for group key.
|
||||||
if payload == nil {
|
func GroupKeyPrefix(qname string) string {
|
||||||
return "nil"
|
return fmt.Sprintf("%sg:", QueueKeyPrefix(qname))
|
||||||
}
|
}
|
||||||
type entry struct {
|
|
||||||
k string
|
// GroupKey returns a redis key used to group tasks belong in the same group.
|
||||||
v interface{}
|
func GroupKey(qname, gkey string) string {
|
||||||
}
|
return fmt.Sprintf("%s%s", GroupKeyPrefix(qname), gkey)
|
||||||
var es []entry
|
}
|
||||||
for k, v := range payload {
|
|
||||||
es = append(es, entry{k, v})
|
// AggregationSetKey returns a redis key used for an aggregation set.
|
||||||
}
|
func AggregationSetKey(qname, gname, setID string) string {
|
||||||
// sort entries by key
|
return fmt.Sprintf("%s:%s", GroupKey(qname, gname), setID)
|
||||||
sort.Slice(es, func(i, j int) bool { return es[i].k < es[j].k })
|
}
|
||||||
var b strings.Builder
|
|
||||||
for _, e := range es {
|
// AllGroups return a redis key used to store all group keys used in a given queue.
|
||||||
if b.Len() > 0 {
|
func AllGroups(qname string) string {
|
||||||
b.WriteString(",")
|
return fmt.Sprintf("%sgroups", QueueKeyPrefix(qname))
|
||||||
}
|
}
|
||||||
b.WriteString(fmt.Sprintf("%s=%v", e.k, e.v))
|
|
||||||
}
|
// AllAggregationSets returns a redis key used to store all aggregation sets (set of tasks staged to be aggregated)
|
||||||
return b.String()
|
// in a given queue.
|
||||||
|
func AllAggregationSets(qname string) string {
|
||||||
|
return fmt.Sprintf("%saggregation_sets", QueueKeyPrefix(qname))
|
||||||
}
|
}
|
||||||
|
|
||||||
// TaskMessage is the internal representation of a task with additional metadata fields.
|
// TaskMessage is the internal representation of a task with additional metadata fields.
|
||||||
@@ -146,10 +238,10 @@ type TaskMessage struct {
|
|||||||
Type string
|
Type string
|
||||||
|
|
||||||
// Payload holds data needed to process the task.
|
// Payload holds data needed to process the task.
|
||||||
Payload map[string]interface{}
|
Payload []byte
|
||||||
|
|
||||||
// ID is a unique identifier for each task.
|
// ID is a unique identifier for each task.
|
||||||
ID uuid.UUID
|
ID string
|
||||||
|
|
||||||
// Queue is a name this message should be enqueued to.
|
// Queue is a name this message should be enqueued to.
|
||||||
Queue string
|
Queue string
|
||||||
@@ -163,6 +255,12 @@ type TaskMessage struct {
|
|||||||
// ErrorMsg holds the error message from the last failure.
|
// ErrorMsg holds the error message from the last failure.
|
||||||
ErrorMsg string
|
ErrorMsg string
|
||||||
|
|
||||||
|
// Time of last failure in Unix time,
|
||||||
|
// the number of seconds elapsed since January 1, 1970 UTC.
|
||||||
|
//
|
||||||
|
// Use zero to indicate no last failure
|
||||||
|
LastFailedAt int64
|
||||||
|
|
||||||
// Timeout specifies timeout in seconds.
|
// Timeout specifies timeout in seconds.
|
||||||
// If task processing doesn't complete within the timeout, the task will be retried
|
// If task processing doesn't complete within the timeout, the task will be retried
|
||||||
// if retry count is remaining. Otherwise it will be moved to the archive.
|
// if retry count is remaining. Otherwise it will be moved to the archive.
|
||||||
@@ -182,26 +280,75 @@ type TaskMessage struct {
|
|||||||
//
|
//
|
||||||
// Empty string indicates that no uniqueness lock was used.
|
// Empty string indicates that no uniqueness lock was used.
|
||||||
UniqueKey string
|
UniqueKey string
|
||||||
|
|
||||||
|
// GroupKey holds the group key used for task aggregation.
|
||||||
|
//
|
||||||
|
// Empty string indicates no aggregation is used for this task.
|
||||||
|
GroupKey string
|
||||||
|
|
||||||
|
// Retention specifies the number of seconds the task should be retained after completion.
|
||||||
|
Retention int64
|
||||||
|
|
||||||
|
// CompletedAt is the time the task was processed successfully in Unix time,
|
||||||
|
// the number of seconds elapsed since January 1, 1970 UTC.
|
||||||
|
//
|
||||||
|
// Use zero to indicate no value.
|
||||||
|
CompletedAt int64
|
||||||
}
|
}
|
||||||
|
|
||||||
// EncodeMessage marshals the given task message in JSON and returns an encoded string.
|
// EncodeMessage marshals the given task message and returns an encoded bytes.
|
||||||
func EncodeMessage(msg *TaskMessage) (string, error) {
|
func EncodeMessage(msg *TaskMessage) ([]byte, error) {
|
||||||
b, err := json.Marshal(msg)
|
if msg == nil {
|
||||||
if err != nil {
|
return nil, fmt.Errorf("cannot encode nil message")
|
||||||
return "", err
|
|
||||||
}
|
}
|
||||||
return string(b), nil
|
return proto.Marshal(&pb.TaskMessage{
|
||||||
|
Type: msg.Type,
|
||||||
|
Payload: msg.Payload,
|
||||||
|
Id: msg.ID,
|
||||||
|
Queue: msg.Queue,
|
||||||
|
Retry: int32(msg.Retry),
|
||||||
|
Retried: int32(msg.Retried),
|
||||||
|
ErrorMsg: msg.ErrorMsg,
|
||||||
|
LastFailedAt: msg.LastFailedAt,
|
||||||
|
Timeout: msg.Timeout,
|
||||||
|
Deadline: msg.Deadline,
|
||||||
|
UniqueKey: msg.UniqueKey,
|
||||||
|
GroupKey: msg.GroupKey,
|
||||||
|
Retention: msg.Retention,
|
||||||
|
CompletedAt: msg.CompletedAt,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// DecodeMessage unmarshals the given encoded string and returns a decoded task message.
|
// DecodeMessage unmarshals the given bytes and returns a decoded task message.
|
||||||
func DecodeMessage(s string) (*TaskMessage, error) {
|
func DecodeMessage(data []byte) (*TaskMessage, error) {
|
||||||
d := json.NewDecoder(strings.NewReader(s))
|
var pbmsg pb.TaskMessage
|
||||||
d.UseNumber()
|
if err := proto.Unmarshal(data, &pbmsg); err != nil {
|
||||||
var msg TaskMessage
|
|
||||||
if err := d.Decode(&msg); err != nil {
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return &msg, nil
|
return &TaskMessage{
|
||||||
|
Type: pbmsg.GetType(),
|
||||||
|
Payload: pbmsg.GetPayload(),
|
||||||
|
ID: pbmsg.GetId(),
|
||||||
|
Queue: pbmsg.GetQueue(),
|
||||||
|
Retry: int(pbmsg.GetRetry()),
|
||||||
|
Retried: int(pbmsg.GetRetried()),
|
||||||
|
ErrorMsg: pbmsg.GetErrorMsg(),
|
||||||
|
LastFailedAt: pbmsg.GetLastFailedAt(),
|
||||||
|
Timeout: pbmsg.GetTimeout(),
|
||||||
|
Deadline: pbmsg.GetDeadline(),
|
||||||
|
UniqueKey: pbmsg.GetUniqueKey(),
|
||||||
|
GroupKey: pbmsg.GetGroupKey(),
|
||||||
|
Retention: pbmsg.GetRetention(),
|
||||||
|
CompletedAt: pbmsg.GetCompletedAt(),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TaskInfo describes a task message and its metadata.
|
||||||
|
type TaskInfo struct {
|
||||||
|
Message *TaskMessage
|
||||||
|
State TaskState
|
||||||
|
NextProcessAt time.Time
|
||||||
|
Result []byte
|
||||||
}
|
}
|
||||||
|
|
||||||
// Z represents sorted set member.
|
// Z represents sorted set member.
|
||||||
@@ -210,65 +357,6 @@ type Z struct {
|
|||||||
Score int64
|
Score int64
|
||||||
}
|
}
|
||||||
|
|
||||||
// ServerStatus represents status of a server.
|
|
||||||
// ServerStatus methods are concurrency safe.
|
|
||||||
type ServerStatus struct {
|
|
||||||
mu sync.Mutex
|
|
||||||
val ServerStatusValue
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewServerStatus returns a new status instance given an initial value.
|
|
||||||
func NewServerStatus(v ServerStatusValue) *ServerStatus {
|
|
||||||
return &ServerStatus{val: v}
|
|
||||||
}
|
|
||||||
|
|
||||||
type ServerStatusValue int
|
|
||||||
|
|
||||||
const (
|
|
||||||
// StatusIdle indicates the server is in idle state.
|
|
||||||
StatusIdle ServerStatusValue = iota
|
|
||||||
|
|
||||||
// StatusRunning indicates the server is up and active.
|
|
||||||
StatusRunning
|
|
||||||
|
|
||||||
// StatusQuiet indicates the server is up but not active.
|
|
||||||
StatusQuiet
|
|
||||||
|
|
||||||
// StatusStopped indicates the server server has been stopped.
|
|
||||||
StatusStopped
|
|
||||||
)
|
|
||||||
|
|
||||||
var statuses = []string{
|
|
||||||
"idle",
|
|
||||||
"running",
|
|
||||||
"quiet",
|
|
||||||
"stopped",
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *ServerStatus) String() string {
|
|
||||||
s.mu.Lock()
|
|
||||||
defer s.mu.Unlock()
|
|
||||||
if StatusIdle <= s.val && s.val <= StatusStopped {
|
|
||||||
return statuses[s.val]
|
|
||||||
}
|
|
||||||
return "unknown status"
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get returns the status value.
|
|
||||||
func (s *ServerStatus) Get() ServerStatusValue {
|
|
||||||
s.mu.Lock()
|
|
||||||
v := s.val
|
|
||||||
s.mu.Unlock()
|
|
||||||
return v
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set sets the status value.
|
|
||||||
func (s *ServerStatus) Set(v ServerStatusValue) {
|
|
||||||
s.mu.Lock()
|
|
||||||
s.val = v
|
|
||||||
s.mu.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
// ServerInfo holds information about a running server.
|
// ServerInfo holds information about a running server.
|
||||||
type ServerInfo struct {
|
type ServerInfo struct {
|
||||||
Host string
|
Host string
|
||||||
@@ -282,6 +370,59 @@ type ServerInfo struct {
|
|||||||
ActiveWorkerCount int
|
ActiveWorkerCount int
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// EncodeServerInfo marshals the given ServerInfo and returns the encoded bytes.
|
||||||
|
func EncodeServerInfo(info *ServerInfo) ([]byte, error) {
|
||||||
|
if info == nil {
|
||||||
|
return nil, fmt.Errorf("cannot encode nil server info")
|
||||||
|
}
|
||||||
|
queues := make(map[string]int32)
|
||||||
|
for q, p := range info.Queues {
|
||||||
|
queues[q] = int32(p)
|
||||||
|
}
|
||||||
|
started, err := ptypes.TimestampProto(info.Started)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return proto.Marshal(&pb.ServerInfo{
|
||||||
|
Host: info.Host,
|
||||||
|
Pid: int32(info.PID),
|
||||||
|
ServerId: info.ServerID,
|
||||||
|
Concurrency: int32(info.Concurrency),
|
||||||
|
Queues: queues,
|
||||||
|
StrictPriority: info.StrictPriority,
|
||||||
|
Status: info.Status,
|
||||||
|
StartTime: started,
|
||||||
|
ActiveWorkerCount: int32(info.ActiveWorkerCount),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// DecodeServerInfo decodes the given bytes into ServerInfo.
|
||||||
|
func DecodeServerInfo(b []byte) (*ServerInfo, error) {
|
||||||
|
var pbmsg pb.ServerInfo
|
||||||
|
if err := proto.Unmarshal(b, &pbmsg); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
queues := make(map[string]int)
|
||||||
|
for q, p := range pbmsg.GetQueues() {
|
||||||
|
queues[q] = int(p)
|
||||||
|
}
|
||||||
|
startTime, err := ptypes.Timestamp(pbmsg.GetStartTime())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &ServerInfo{
|
||||||
|
Host: pbmsg.GetHost(),
|
||||||
|
PID: int(pbmsg.GetPid()),
|
||||||
|
ServerID: pbmsg.GetServerId(),
|
||||||
|
Concurrency: int(pbmsg.GetConcurrency()),
|
||||||
|
Queues: queues,
|
||||||
|
StrictPriority: pbmsg.GetStrictPriority(),
|
||||||
|
Status: pbmsg.GetStatus(),
|
||||||
|
Started: startTime,
|
||||||
|
ActiveWorkerCount: int(pbmsg.GetActiveWorkerCount()),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
// WorkerInfo holds information about a running worker.
|
// WorkerInfo holds information about a running worker.
|
||||||
type WorkerInfo struct {
|
type WorkerInfo struct {
|
||||||
Host string
|
Host string
|
||||||
@@ -289,12 +430,65 @@ type WorkerInfo struct {
|
|||||||
ServerID string
|
ServerID string
|
||||||
ID string
|
ID string
|
||||||
Type string
|
Type string
|
||||||
|
Payload []byte
|
||||||
Queue string
|
Queue string
|
||||||
Payload map[string]interface{}
|
|
||||||
Started time.Time
|
Started time.Time
|
||||||
Deadline time.Time
|
Deadline time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// EncodeWorkerInfo marshals the given WorkerInfo and returns the encoded bytes.
|
||||||
|
func EncodeWorkerInfo(info *WorkerInfo) ([]byte, error) {
|
||||||
|
if info == nil {
|
||||||
|
return nil, fmt.Errorf("cannot encode nil worker info")
|
||||||
|
}
|
||||||
|
startTime, err := ptypes.TimestampProto(info.Started)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
deadline, err := ptypes.TimestampProto(info.Deadline)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return proto.Marshal(&pb.WorkerInfo{
|
||||||
|
Host: info.Host,
|
||||||
|
Pid: int32(info.PID),
|
||||||
|
ServerId: info.ServerID,
|
||||||
|
TaskId: info.ID,
|
||||||
|
TaskType: info.Type,
|
||||||
|
TaskPayload: info.Payload,
|
||||||
|
Queue: info.Queue,
|
||||||
|
StartTime: startTime,
|
||||||
|
Deadline: deadline,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// DecodeWorkerInfo decodes the given bytes into WorkerInfo.
|
||||||
|
func DecodeWorkerInfo(b []byte) (*WorkerInfo, error) {
|
||||||
|
var pbmsg pb.WorkerInfo
|
||||||
|
if err := proto.Unmarshal(b, &pbmsg); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
startTime, err := ptypes.Timestamp(pbmsg.GetStartTime())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
deadline, err := ptypes.Timestamp(pbmsg.GetDeadline())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &WorkerInfo{
|
||||||
|
Host: pbmsg.GetHost(),
|
||||||
|
PID: int(pbmsg.GetPid()),
|
||||||
|
ServerID: pbmsg.GetServerId(),
|
||||||
|
ID: pbmsg.GetTaskId(),
|
||||||
|
Type: pbmsg.GetTaskType(),
|
||||||
|
Payload: pbmsg.GetTaskPayload(),
|
||||||
|
Queue: pbmsg.GetQueue(),
|
||||||
|
Started: startTime,
|
||||||
|
Deadline: deadline,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
// SchedulerEntry holds information about a periodic task registered with a scheduler.
|
// SchedulerEntry holds information about a periodic task registered with a scheduler.
|
||||||
type SchedulerEntry struct {
|
type SchedulerEntry struct {
|
||||||
// Identifier of this entry.
|
// Identifier of this entry.
|
||||||
@@ -307,7 +501,7 @@ type SchedulerEntry struct {
|
|||||||
Type string
|
Type string
|
||||||
|
|
||||||
// Payload is the payload of the periodic task.
|
// Payload is the payload of the periodic task.
|
||||||
Payload map[string]interface{}
|
Payload []byte
|
||||||
|
|
||||||
// Opts is the options for the periodic task.
|
// Opts is the options for the periodic task.
|
||||||
Opts []string
|
Opts []string
|
||||||
@@ -320,6 +514,55 @@ type SchedulerEntry struct {
|
|||||||
Prev time.Time
|
Prev time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// EncodeSchedulerEntry marshals the given entry and returns an encoded bytes.
|
||||||
|
func EncodeSchedulerEntry(entry *SchedulerEntry) ([]byte, error) {
|
||||||
|
if entry == nil {
|
||||||
|
return nil, fmt.Errorf("cannot encode nil scheduler entry")
|
||||||
|
}
|
||||||
|
next, err := ptypes.TimestampProto(entry.Next)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
prev, err := ptypes.TimestampProto(entry.Prev)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return proto.Marshal(&pb.SchedulerEntry{
|
||||||
|
Id: entry.ID,
|
||||||
|
Spec: entry.Spec,
|
||||||
|
TaskType: entry.Type,
|
||||||
|
TaskPayload: entry.Payload,
|
||||||
|
EnqueueOptions: entry.Opts,
|
||||||
|
NextEnqueueTime: next,
|
||||||
|
PrevEnqueueTime: prev,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// DecodeSchedulerEntry unmarshals the given bytes and returns a decoded SchedulerEntry.
|
||||||
|
func DecodeSchedulerEntry(b []byte) (*SchedulerEntry, error) {
|
||||||
|
var pbmsg pb.SchedulerEntry
|
||||||
|
if err := proto.Unmarshal(b, &pbmsg); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
next, err := ptypes.Timestamp(pbmsg.GetNextEnqueueTime())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
prev, err := ptypes.Timestamp(pbmsg.GetPrevEnqueueTime())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &SchedulerEntry{
|
||||||
|
ID: pbmsg.GetId(),
|
||||||
|
Spec: pbmsg.GetSpec(),
|
||||||
|
Type: pbmsg.GetTaskType(),
|
||||||
|
Payload: pbmsg.GetTaskPayload(),
|
||||||
|
Opts: pbmsg.GetEnqueueOptions(),
|
||||||
|
Next: next,
|
||||||
|
Prev: prev,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
// SchedulerEnqueueEvent holds information about an enqueue event by a scheduler.
|
// SchedulerEnqueueEvent holds information about an enqueue event by a scheduler.
|
||||||
type SchedulerEnqueueEvent struct {
|
type SchedulerEnqueueEvent struct {
|
||||||
// ID of the task that was enqueued.
|
// ID of the task that was enqueued.
|
||||||
@@ -329,9 +572,42 @@ type SchedulerEnqueueEvent struct {
|
|||||||
EnqueuedAt time.Time
|
EnqueuedAt time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// EncodeSchedulerEnqueueEvent marshals the given event
|
||||||
|
// and returns an encoded bytes.
|
||||||
|
func EncodeSchedulerEnqueueEvent(event *SchedulerEnqueueEvent) ([]byte, error) {
|
||||||
|
if event == nil {
|
||||||
|
return nil, fmt.Errorf("cannot encode nil enqueue event")
|
||||||
|
}
|
||||||
|
enqueuedAt, err := ptypes.TimestampProto(event.EnqueuedAt)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return proto.Marshal(&pb.SchedulerEnqueueEvent{
|
||||||
|
TaskId: event.TaskID,
|
||||||
|
EnqueueTime: enqueuedAt,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// DecodeSchedulerEnqueueEvent unmarshals the given bytes
|
||||||
|
// and returns a decoded SchedulerEnqueueEvent.
|
||||||
|
func DecodeSchedulerEnqueueEvent(b []byte) (*SchedulerEnqueueEvent, error) {
|
||||||
|
var pbmsg pb.SchedulerEnqueueEvent
|
||||||
|
if err := proto.Unmarshal(b, &pbmsg); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
enqueuedAt, err := ptypes.Timestamp(pbmsg.GetEnqueueTime())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &SchedulerEnqueueEvent{
|
||||||
|
TaskID: pbmsg.GetTaskId(),
|
||||||
|
EnqueuedAt: enqueuedAt,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
// Cancelations is a collection that holds cancel functions for all active tasks.
|
// Cancelations is a collection that holds cancel functions for all active tasks.
|
||||||
//
|
//
|
||||||
// Cancelations are safe for concurrent use by multipel goroutines.
|
// Cancelations are safe for concurrent use by multiple goroutines.
|
||||||
type Cancelations struct {
|
type Cancelations struct {
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
cancelFuncs map[string]context.CancelFunc
|
cancelFuncs map[string]context.CancelFunc
|
||||||
@@ -366,25 +642,114 @@ func (c *Cancelations) Get(id string) (fn context.CancelFunc, ok bool) {
|
|||||||
return fn, ok
|
return fn, ok
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Lease is a time bound lease for worker to process task.
|
||||||
|
// It provides a communication channel between lessor and lessee about lease expiration.
|
||||||
|
type Lease struct {
|
||||||
|
once sync.Once
|
||||||
|
ch chan struct{}
|
||||||
|
|
||||||
|
Clock timeutil.Clock
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
expireAt time.Time // guarded by mu
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewLease(expirationTime time.Time) *Lease {
|
||||||
|
return &Lease{
|
||||||
|
ch: make(chan struct{}),
|
||||||
|
expireAt: expirationTime,
|
||||||
|
Clock: timeutil.NewRealClock(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset changes the lease to expire at the given time.
|
||||||
|
// It returns true if the lease is still valid and reset operation was successful, false if the lease had been expired.
|
||||||
|
func (l *Lease) Reset(expirationTime time.Time) bool {
|
||||||
|
if !l.IsValid() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
l.mu.Lock()
|
||||||
|
defer l.mu.Unlock()
|
||||||
|
l.expireAt = expirationTime
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sends a notification to lessee about expired lease
|
||||||
|
// Returns true if notification was sent, returns false if the lease is still valid and notification was not sent.
|
||||||
|
func (l *Lease) NotifyExpiration() bool {
|
||||||
|
if l.IsValid() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
l.once.Do(l.closeCh)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *Lease) closeCh() {
|
||||||
|
close(l.ch)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Done returns a communication channel from which the lessee can read to get notified when lessor notifies about lease expiration.
|
||||||
|
func (l *Lease) Done() <-chan struct{} {
|
||||||
|
return l.ch
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deadline returns the expiration time of the lease.
|
||||||
|
func (l *Lease) Deadline() time.Time {
|
||||||
|
l.mu.Lock()
|
||||||
|
defer l.mu.Unlock()
|
||||||
|
return l.expireAt
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsValid returns true if the lease's expiration time is in the future or equals to the current time,
|
||||||
|
// returns false otherwise.
|
||||||
|
func (l *Lease) IsValid() bool {
|
||||||
|
now := l.Clock.Now()
|
||||||
|
l.mu.Lock()
|
||||||
|
defer l.mu.Unlock()
|
||||||
|
return l.expireAt.After(now) || l.expireAt.Equal(now)
|
||||||
|
}
|
||||||
|
|
||||||
// Broker is a message broker that supports operations to manage task queues.
|
// Broker is a message broker that supports operations to manage task queues.
|
||||||
//
|
//
|
||||||
// See rdb.RDB as a reference implementation.
|
// See rdb.RDB as a reference implementation.
|
||||||
type Broker interface {
|
type Broker interface {
|
||||||
Ping() error
|
Ping() error
|
||||||
Enqueue(msg *TaskMessage) error
|
Close() error
|
||||||
EnqueueUnique(msg *TaskMessage, ttl time.Duration) error
|
Enqueue(ctx context.Context, msg *TaskMessage) error
|
||||||
|
EnqueueUnique(ctx context.Context, msg *TaskMessage, ttl time.Duration) error
|
||||||
Dequeue(qnames ...string) (*TaskMessage, time.Time, error)
|
Dequeue(qnames ...string) (*TaskMessage, time.Time, error)
|
||||||
Done(msg *TaskMessage) error
|
Done(ctx context.Context, msg *TaskMessage) error
|
||||||
Requeue(msg *TaskMessage) error
|
MarkAsComplete(ctx context.Context, msg *TaskMessage) error
|
||||||
Schedule(msg *TaskMessage, processAt time.Time) error
|
Requeue(ctx context.Context, msg *TaskMessage) error
|
||||||
ScheduleUnique(msg *TaskMessage, processAt time.Time, ttl time.Duration) error
|
Schedule(ctx context.Context, msg *TaskMessage, processAt time.Time) error
|
||||||
Retry(msg *TaskMessage, processAt time.Time, errMsg string) error
|
ScheduleUnique(ctx context.Context, msg *TaskMessage, processAt time.Time, ttl time.Duration) error
|
||||||
Archive(msg *TaskMessage, errMsg string) error
|
Retry(ctx context.Context, msg *TaskMessage, processAt time.Time, errMsg string, isFailure bool) error
|
||||||
CheckAndEnqueue(qnames ...string) error
|
Archive(ctx context.Context, msg *TaskMessage, errMsg string) error
|
||||||
ListDeadlineExceeded(deadline time.Time, qnames ...string) ([]*TaskMessage, error)
|
ForwardIfReady(qnames ...string) error
|
||||||
|
|
||||||
|
// Group aggregation related methods
|
||||||
|
AddToGroup(ctx context.Context, msg *TaskMessage, gname string) error
|
||||||
|
AddToGroupUnique(ctx context.Context, msg *TaskMessage, groupKey string, ttl time.Duration) error
|
||||||
|
ListGroups(qname string) ([]string, error)
|
||||||
|
AggregationCheck(qname, gname string, t time.Time, gracePeriod, maxDelay time.Duration, maxSize int) (aggregationSetID string, err error)
|
||||||
|
ReadAggregationSet(qname, gname, aggregationSetID string) ([]*TaskMessage, time.Time, error)
|
||||||
|
DeleteAggregationSet(ctx context.Context, qname, gname, aggregationSetID string) error
|
||||||
|
ReclaimStaleAggregationSets(qname string) error
|
||||||
|
|
||||||
|
// Task retention related method
|
||||||
|
DeleteExpiredCompletedTasks(qname string, batchSize int) error
|
||||||
|
|
||||||
|
// Lease related methods
|
||||||
|
ListLeaseExpired(cutoff time.Time, qnames ...string) ([]*TaskMessage, error)
|
||||||
|
ExtendLease(qname string, ids ...string) (time.Time, error)
|
||||||
|
|
||||||
|
// State snapshot related methods
|
||||||
WriteServerState(info *ServerInfo, workers []*WorkerInfo, ttl time.Duration) error
|
WriteServerState(info *ServerInfo, workers []*WorkerInfo, ttl time.Duration) error
|
||||||
ClearServerState(host string, pid int, serverID string) error
|
ClearServerState(host string, pid int, serverID string) error
|
||||||
|
|
||||||
|
// Cancelation related methods
|
||||||
CancelationPubSub() (*redis.PubSub, error) // TODO: Need to decouple from redis to support other brokers
|
CancelationPubSub() (*redis.PubSub, error) // TODO: Need to decouple from redis to support other brokers
|
||||||
PublishCancelation(id string) error
|
PublishCancelation(id string) error
|
||||||
Close() error
|
|
||||||
|
WriteResult(qname, id string, data []byte) (n int, err error)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,26 +6,49 @@ package base
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"crypto/md5"
|
||||||
|
"encoding/hex"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/google/go-cmp/cmp"
|
"github.com/google/go-cmp/cmp"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
|
"github.com/hibiken/asynq/internal/timeutil"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestTaskKey(t *testing.T) {
|
||||||
|
id := uuid.NewString()
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
qname string
|
||||||
|
id string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"default", id, fmt.Sprintf("asynq:{default}:t:%s", id)},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
got := TaskKey(tc.qname, tc.id)
|
||||||
|
if got != tc.want {
|
||||||
|
t.Errorf("TaskKey(%q, %s) = %q, want %q", tc.qname, tc.id, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestQueueKey(t *testing.T) {
|
func TestQueueKey(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
qname string
|
qname string
|
||||||
want string
|
want string
|
||||||
}{
|
}{
|
||||||
{"default", "asynq:{default}"},
|
{"default", "asynq:{default}:pending"},
|
||||||
{"custom", "asynq:{custom}"},
|
{"custom", "asynq:{custom}:pending"},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, tc := range tests {
|
for _, tc := range tests {
|
||||||
got := QueueKey(tc.qname)
|
got := PendingKey(tc.qname)
|
||||||
if got != tc.want {
|
if got != tc.want {
|
||||||
t.Errorf("QueueKey(%q) = %q, want %q", tc.qname, got, tc.want)
|
t.Errorf("QueueKey(%q) = %q, want %q", tc.qname, got, tc.want)
|
||||||
}
|
}
|
||||||
@@ -49,19 +72,19 @@ func TestActiveKey(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestDeadlinesKey(t *testing.T) {
|
func TestLeaseKey(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
qname string
|
qname string
|
||||||
want string
|
want string
|
||||||
}{
|
}{
|
||||||
{"default", "asynq:{default}:deadlines"},
|
{"default", "asynq:{default}:lease"},
|
||||||
{"custom", "asynq:{custom}:deadlines"},
|
{"custom", "asynq:{custom}:lease"},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, tc := range tests {
|
for _, tc := range tests {
|
||||||
got := DeadlinesKey(tc.qname)
|
got := LeaseKey(tc.qname)
|
||||||
if got != tc.want {
|
if got != tc.want {
|
||||||
t.Errorf("DeadlinesKey(%q) = %q, want %q", tc.qname, got, tc.want)
|
t.Errorf("LeaseKey(%q) = %q, want %q", tc.qname, got, tc.want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -117,6 +140,23 @@ func TestArchivedKey(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCompletedKey(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
qname string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"default", "asynq:{default}:completed"},
|
||||||
|
{"custom", "asynq:{custom}:completed"},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
got := CompletedKey(tc.qname)
|
||||||
|
if got != tc.want {
|
||||||
|
t.Errorf("CompletedKey(%q) = %q, want %q", tc.qname, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestPausedKey(t *testing.T) {
|
func TestPausedKey(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
qname string
|
qname string
|
||||||
@@ -134,6 +174,40 @@ func TestPausedKey(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestProcessedTotalKey(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
qname string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"default", "asynq:{default}:processed"},
|
||||||
|
{"custom", "asynq:{custom}:processed"},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
got := ProcessedTotalKey(tc.qname)
|
||||||
|
if got != tc.want {
|
||||||
|
t.Errorf("ProcessedTotalKey(%q) = %q, want %q", tc.qname, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFailedTotalKey(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
qname string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"default", "asynq:{default}:failed"},
|
||||||
|
{"custom", "asynq:{custom}:failed"},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
got := FailedTotalKey(tc.qname)
|
||||||
|
if got != tc.want {
|
||||||
|
t.Errorf("FailedTotalKey(%q) = %q, want %q", tc.qname, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestProcessedKey(t *testing.T) {
|
func TestProcessedKey(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
qname string
|
qname string
|
||||||
@@ -247,52 +321,69 @@ func TestSchedulerHistoryKey(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func toBytes(m map[string]interface{}) []byte {
|
||||||
|
b, err := json.Marshal(m)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
func TestUniqueKey(t *testing.T) {
|
func TestUniqueKey(t *testing.T) {
|
||||||
|
payload1 := toBytes(map[string]interface{}{"a": 123, "b": "hello", "c": true})
|
||||||
|
payload2 := toBytes(map[string]interface{}{"b": "hello", "c": true, "a": 123})
|
||||||
|
payload3 := toBytes(map[string]interface{}{
|
||||||
|
"address": map[string]string{"line": "123 Main St", "city": "Boston", "state": "MA"},
|
||||||
|
"names": []string{"bob", "mike", "rob"}})
|
||||||
|
payload4 := toBytes(map[string]interface{}{
|
||||||
|
"time": time.Date(2020, time.July, 28, 0, 0, 0, 0, time.UTC),
|
||||||
|
"duration": time.Hour})
|
||||||
|
|
||||||
|
checksum := func(data []byte) string {
|
||||||
|
sum := md5.Sum(data)
|
||||||
|
return hex.EncodeToString(sum[:])
|
||||||
|
}
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
desc string
|
desc string
|
||||||
qname string
|
qname string
|
||||||
tasktype string
|
tasktype string
|
||||||
payload map[string]interface{}
|
payload []byte
|
||||||
want string
|
want string
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
"with primitive types",
|
"with primitive types",
|
||||||
"default",
|
"default",
|
||||||
"email:send",
|
"email:send",
|
||||||
map[string]interface{}{"a": 123, "b": "hello", "c": true},
|
payload1,
|
||||||
"asynq:{default}:unique:email:send:a=123,b=hello,c=true",
|
fmt.Sprintf("asynq:{default}:unique:email:send:%s", checksum(payload1)),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"with unsorted keys",
|
"with unsorted keys",
|
||||||
"default",
|
"default",
|
||||||
"email:send",
|
"email:send",
|
||||||
map[string]interface{}{"b": "hello", "c": true, "a": 123},
|
payload2,
|
||||||
"asynq:{default}:unique:email:send:a=123,b=hello,c=true",
|
fmt.Sprintf("asynq:{default}:unique:email:send:%s", checksum(payload2)),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"with composite types",
|
"with composite types",
|
||||||
"default",
|
"default",
|
||||||
"email:send",
|
"email:send",
|
||||||
map[string]interface{}{
|
payload3,
|
||||||
"address": map[string]string{"line": "123 Main St", "city": "Boston", "state": "MA"},
|
fmt.Sprintf("asynq:{default}:unique:email:send:%s", checksum(payload3)),
|
||||||
"names": []string{"bob", "mike", "rob"}},
|
|
||||||
"asynq:{default}:unique:email:send:address=map[city:Boston line:123 Main St state:MA],names=[bob mike rob]",
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"with complex types",
|
"with complex types",
|
||||||
"default",
|
"default",
|
||||||
"email:send",
|
"email:send",
|
||||||
map[string]interface{}{
|
payload4,
|
||||||
"time": time.Date(2020, time.July, 28, 0, 0, 0, 0, time.UTC),
|
fmt.Sprintf("asynq:{default}:unique:email:send:%s", checksum(payload4)),
|
||||||
"duration": time.Hour},
|
|
||||||
"asynq:{default}:unique:email:send:duration=1h0m0s,time=2020-07-28 00:00:00 +0000 UTC",
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"with nil payload",
|
"with nil payload",
|
||||||
"default",
|
"default",
|
||||||
"reindex",
|
"reindex",
|
||||||
nil,
|
nil,
|
||||||
"asynq:{default}:unique:reindex:nil",
|
"asynq:{default}:unique:reindex:",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -304,32 +395,137 @@ func TestUniqueKey(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestGroupKey(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
qname string
|
||||||
|
gkey string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
qname: "default",
|
||||||
|
gkey: "mygroup",
|
||||||
|
want: "asynq:{default}:g:mygroup",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
qname: "custom",
|
||||||
|
gkey: "foo",
|
||||||
|
want: "asynq:{custom}:g:foo",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
got := GroupKey(tc.qname, tc.gkey)
|
||||||
|
if got != tc.want {
|
||||||
|
t.Errorf("GroupKey(%q, %q) = %q, want %q", tc.qname, tc.gkey, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAggregationSetKey(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
qname string
|
||||||
|
gname string
|
||||||
|
setID string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
qname: "default",
|
||||||
|
gname: "mygroup",
|
||||||
|
setID: "12345",
|
||||||
|
want: "asynq:{default}:g:mygroup:12345",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
qname: "custom",
|
||||||
|
gname: "foo",
|
||||||
|
setID: "98765",
|
||||||
|
want: "asynq:{custom}:g:foo:98765",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
got := AggregationSetKey(tc.qname, tc.gname, tc.setID)
|
||||||
|
if got != tc.want {
|
||||||
|
t.Errorf("AggregationSetKey(%q, %q, %q) = %q, want %q", tc.qname, tc.gname, tc.setID, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAllGroups(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
qname string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
qname: "default",
|
||||||
|
want: "asynq:{default}:groups",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
qname: "custom",
|
||||||
|
want: "asynq:{custom}:groups",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
got := AllGroups(tc.qname)
|
||||||
|
if got != tc.want {
|
||||||
|
t.Errorf("AllGroups(%q) = %q, want %q", tc.qname, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAllAggregationSets(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
qname string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
qname: "default",
|
||||||
|
want: "asynq:{default}:aggregation_sets",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
qname: "custom",
|
||||||
|
want: "asynq:{custom}:aggregation_sets",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
got := AllAggregationSets(tc.qname)
|
||||||
|
if got != tc.want {
|
||||||
|
t.Errorf("AllAggregationSets(%q) = %q, want %q", tc.qname, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestMessageEncoding(t *testing.T) {
|
func TestMessageEncoding(t *testing.T) {
|
||||||
id := uuid.New()
|
id := uuid.NewString()
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
in *TaskMessage
|
in *TaskMessage
|
||||||
out *TaskMessage
|
out *TaskMessage
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
in: &TaskMessage{
|
in: &TaskMessage{
|
||||||
Type: "task1",
|
Type: "task1",
|
||||||
Payload: map[string]interface{}{"a": 1, "b": "hello!", "c": true},
|
Payload: toBytes(map[string]interface{}{"a": 1, "b": "hello!", "c": true}),
|
||||||
ID: id,
|
ID: id,
|
||||||
Queue: "default",
|
Queue: "default",
|
||||||
Retry: 10,
|
GroupKey: "mygroup",
|
||||||
Retried: 0,
|
Retry: 10,
|
||||||
Timeout: 1800,
|
Retried: 0,
|
||||||
Deadline: 1692311100,
|
Timeout: 1800,
|
||||||
|
Deadline: 1692311100,
|
||||||
|
Retention: 3600,
|
||||||
},
|
},
|
||||||
out: &TaskMessage{
|
out: &TaskMessage{
|
||||||
Type: "task1",
|
Type: "task1",
|
||||||
Payload: map[string]interface{}{"a": json.Number("1"), "b": "hello!", "c": true},
|
Payload: toBytes(map[string]interface{}{"a": json.Number("1"), "b": "hello!", "c": true}),
|
||||||
ID: id,
|
ID: id,
|
||||||
Queue: "default",
|
Queue: "default",
|
||||||
Retry: 10,
|
GroupKey: "mygroup",
|
||||||
Retried: 0,
|
Retry: 10,
|
||||||
Timeout: 1800,
|
Retried: 0,
|
||||||
Deadline: 1692311100,
|
Timeout: 1800,
|
||||||
|
Deadline: 1692311100,
|
||||||
|
Retention: 3600,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -352,28 +548,143 @@ func TestMessageEncoding(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Test for status being accessed by multiple goroutines.
|
func TestServerInfoEncoding(t *testing.T) {
|
||||||
// Run with -race flag to check for data race.
|
tests := []struct {
|
||||||
func TestStatusConcurrentAccess(t *testing.T) {
|
info ServerInfo
|
||||||
status := NewServerStatus(StatusIdle)
|
}{
|
||||||
|
{
|
||||||
|
info: ServerInfo{
|
||||||
|
Host: "127.0.0.1",
|
||||||
|
PID: 9876,
|
||||||
|
ServerID: "abc123",
|
||||||
|
Concurrency: 10,
|
||||||
|
Queues: map[string]int{"default": 1, "critical": 2},
|
||||||
|
StrictPriority: false,
|
||||||
|
Status: "active",
|
||||||
|
Started: time.Now().Add(-3 * time.Hour),
|
||||||
|
ActiveWorkerCount: 8,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
var wg sync.WaitGroup
|
for _, tc := range tests {
|
||||||
|
encoded, err := EncodeServerInfo(&tc.info)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("EncodeServerInfo(info) returned error: %v", err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
decoded, err := DecodeServerInfo(encoded)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("DecodeServerInfo(encoded) returned error: %v", err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if diff := cmp.Diff(&tc.info, decoded); diff != "" {
|
||||||
|
t.Errorf("Decoded ServerInfo == %+v, want %+v;(-want,+got)\n%s",
|
||||||
|
decoded, tc.info, diff)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
wg.Add(1)
|
func TestWorkerInfoEncoding(t *testing.T) {
|
||||||
go func() {
|
tests := []struct {
|
||||||
defer wg.Done()
|
info WorkerInfo
|
||||||
status.Get()
|
}{
|
||||||
_ = status.String()
|
{
|
||||||
}()
|
info: WorkerInfo{
|
||||||
|
Host: "127.0.0.1",
|
||||||
|
PID: 9876,
|
||||||
|
ServerID: "abc123",
|
||||||
|
ID: uuid.NewString(),
|
||||||
|
Type: "taskA",
|
||||||
|
Payload: toBytes(map[string]interface{}{"foo": "bar"}),
|
||||||
|
Queue: "default",
|
||||||
|
Started: time.Now().Add(-3 * time.Hour),
|
||||||
|
Deadline: time.Now().Add(30 * time.Second),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
wg.Add(1)
|
for _, tc := range tests {
|
||||||
go func() {
|
encoded, err := EncodeWorkerInfo(&tc.info)
|
||||||
defer wg.Done()
|
if err != nil {
|
||||||
status.Set(StatusStopped)
|
t.Errorf("EncodeWorkerInfo(info) returned error: %v", err)
|
||||||
_ = status.String()
|
continue
|
||||||
}()
|
}
|
||||||
|
decoded, err := DecodeWorkerInfo(encoded)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("DecodeWorkerInfo(encoded) returned error: %v", err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if diff := cmp.Diff(&tc.info, decoded); diff != "" {
|
||||||
|
t.Errorf("Decoded WorkerInfo == %+v, want %+v;(-want,+got)\n%s",
|
||||||
|
decoded, tc.info, diff)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
wg.Wait()
|
func TestSchedulerEntryEncoding(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
entry SchedulerEntry
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
entry: SchedulerEntry{
|
||||||
|
ID: uuid.NewString(),
|
||||||
|
Spec: "* * * * *",
|
||||||
|
Type: "task_A",
|
||||||
|
Payload: toBytes(map[string]interface{}{"foo": "bar"}),
|
||||||
|
Opts: []string{"Queue('email')"},
|
||||||
|
Next: time.Now().Add(30 * time.Second).UTC(),
|
||||||
|
Prev: time.Now().Add(-2 * time.Minute).UTC(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
encoded, err := EncodeSchedulerEntry(&tc.entry)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("EncodeSchedulerEntry(entry) returned error: %v", err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
decoded, err := DecodeSchedulerEntry(encoded)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("DecodeSchedulerEntry(encoded) returned error: %v", err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if diff := cmp.Diff(&tc.entry, decoded); diff != "" {
|
||||||
|
t.Errorf("Decoded SchedulerEntry == %+v, want %+v;(-want,+got)\n%s",
|
||||||
|
decoded, tc.entry, diff)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSchedulerEnqueueEventEncoding(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
event SchedulerEnqueueEvent
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
event: SchedulerEnqueueEvent{
|
||||||
|
TaskID: uuid.NewString(),
|
||||||
|
EnqueuedAt: time.Now().Add(-30 * time.Second).UTC(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
encoded, err := EncodeSchedulerEnqueueEvent(&tc.event)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("EncodeSchedulerEnqueueEvent(event) returned error: %v", err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
decoded, err := DecodeSchedulerEnqueueEvent(encoded)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("DecodeSchedulerEnqueueEvent(encoded) returned error: %v", err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if diff := cmp.Diff(&tc.event, decoded); diff != "" {
|
||||||
|
t.Errorf("Decoded SchedulerEnqueueEvent == %+v, want %+v;(-want,+got)\n%s",
|
||||||
|
decoded, tc.event, diff)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Test for cancelations being accessed by multiple goroutines.
|
// Test for cancelations being accessed by multiple goroutines.
|
||||||
@@ -420,3 +731,75 @@ func TestCancelationsConcurrentAccess(t *testing.T) {
|
|||||||
t.Errorf("(*Cancelations).Get(%q) = _, true, want <nil>, false", key2)
|
t.Errorf("(*Cancelations).Get(%q) = _, true, want <nil>, false", key2)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestLeaseReset(t *testing.T) {
|
||||||
|
now := time.Now()
|
||||||
|
clock := timeutil.NewSimulatedClock(now)
|
||||||
|
|
||||||
|
l := NewLease(now.Add(30 * time.Second))
|
||||||
|
l.Clock = clock
|
||||||
|
|
||||||
|
// Check initial state
|
||||||
|
if !l.IsValid() {
|
||||||
|
t.Errorf("lease should be valid when expiration is set to a future time")
|
||||||
|
}
|
||||||
|
if want := now.Add(30 * time.Second); l.Deadline() != want {
|
||||||
|
t.Errorf("Lease.Deadline() = %v, want %v", l.Deadline(), want)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test Reset
|
||||||
|
if !l.Reset(now.Add(45 * time.Second)) {
|
||||||
|
t.Fatalf("Lease.Reset returned false when extending")
|
||||||
|
}
|
||||||
|
if want := now.Add(45 * time.Second); l.Deadline() != want {
|
||||||
|
t.Errorf("After Reset: Lease.Deadline() = %v, want %v", l.Deadline(), want)
|
||||||
|
}
|
||||||
|
|
||||||
|
clock.AdvanceTime(1 * time.Minute) // simulate lease expiration
|
||||||
|
|
||||||
|
if l.IsValid() {
|
||||||
|
t.Errorf("lease should be invalid after expiration")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset should return false if lease is expired.
|
||||||
|
if l.Reset(time.Now().Add(20 * time.Second)) {
|
||||||
|
t.Errorf("Lease.Reset should return false after expiration")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLeaseNotifyExpiration(t *testing.T) {
|
||||||
|
now := time.Now()
|
||||||
|
clock := timeutil.NewSimulatedClock(now)
|
||||||
|
|
||||||
|
l := NewLease(now.Add(30 * time.Second))
|
||||||
|
l.Clock = clock
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-l.Done():
|
||||||
|
t.Fatalf("Lease.Done() did not block")
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
|
||||||
|
if l.NotifyExpiration() {
|
||||||
|
t.Fatalf("Lease.NotifyExpiration() should return false when lease is still valid")
|
||||||
|
}
|
||||||
|
|
||||||
|
clock.AdvanceTime(1 * time.Minute) // simulate lease expiration
|
||||||
|
|
||||||
|
if l.IsValid() {
|
||||||
|
t.Errorf("Lease should be invalid after expiration")
|
||||||
|
}
|
||||||
|
if !l.NotifyExpiration() {
|
||||||
|
t.Errorf("Lease.NotifyExpiration() return return true after expiration")
|
||||||
|
}
|
||||||
|
if !l.NotifyExpiration() {
|
||||||
|
t.Errorf("It should be leagal to call Lease.NotifyExpiration multiple times")
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-l.Done():
|
||||||
|
// expected
|
||||||
|
default:
|
||||||
|
t.Errorf("Lease.Done() blocked after call to Lease.NotifyExpiration()")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
87
internal/context/context.go
Normal file
87
internal/context/context.go
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
// Copyright 2020 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package context
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/hibiken/asynq/internal/base"
|
||||||
|
)
|
||||||
|
|
||||||
|
// A taskMetadata holds task scoped data to put in context.
|
||||||
|
type taskMetadata struct {
|
||||||
|
id string
|
||||||
|
maxRetry int
|
||||||
|
retryCount int
|
||||||
|
qname string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ctxKey type is unexported to prevent collisions with context keys defined in
|
||||||
|
// other packages.
|
||||||
|
type ctxKey int
|
||||||
|
|
||||||
|
// metadataCtxKey is the context key for the task metadata.
|
||||||
|
// Its value of zero is arbitrary.
|
||||||
|
const metadataCtxKey ctxKey = 0
|
||||||
|
|
||||||
|
// New returns a context and cancel function for a given task message.
|
||||||
|
func New(base context.Context, msg *base.TaskMessage, deadline time.Time) (context.Context, context.CancelFunc) {
|
||||||
|
metadata := taskMetadata{
|
||||||
|
id: msg.ID,
|
||||||
|
maxRetry: msg.Retry,
|
||||||
|
retryCount: msg.Retried,
|
||||||
|
qname: msg.Queue,
|
||||||
|
}
|
||||||
|
ctx := context.WithValue(base, metadataCtxKey, metadata)
|
||||||
|
return context.WithDeadline(ctx, deadline)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetTaskID extracts a task ID from a context, if any.
|
||||||
|
//
|
||||||
|
// ID of a task is guaranteed to be unique.
|
||||||
|
// ID of a task doesn't change if the task is being retried.
|
||||||
|
func GetTaskID(ctx context.Context) (id string, ok bool) {
|
||||||
|
metadata, ok := ctx.Value(metadataCtxKey).(taskMetadata)
|
||||||
|
if !ok {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return metadata.id, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetRetryCount extracts retry count from a context, if any.
|
||||||
|
//
|
||||||
|
// Return value n indicates the number of times associated task has been
|
||||||
|
// retried so far.
|
||||||
|
func GetRetryCount(ctx context.Context) (n int, ok bool) {
|
||||||
|
metadata, ok := ctx.Value(metadataCtxKey).(taskMetadata)
|
||||||
|
if !ok {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return metadata.retryCount, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetMaxRetry extracts maximum retry from a context, if any.
|
||||||
|
//
|
||||||
|
// Return value n indicates the maximum number of times the associated task
|
||||||
|
// can be retried if ProcessTask returns a non-nil error.
|
||||||
|
func GetMaxRetry(ctx context.Context) (n int, ok bool) {
|
||||||
|
metadata, ok := ctx.Value(metadataCtxKey).(taskMetadata)
|
||||||
|
if !ok {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return metadata.maxRetry, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetQueueName extracts queue name from a context, if any.
|
||||||
|
//
|
||||||
|
// Return value qname indicates which queue the task was pulled from.
|
||||||
|
func GetQueueName(ctx context.Context) (qname string, ok bool) {
|
||||||
|
metadata, ok := ctx.Value(metadataCtxKey).(taskMetadata)
|
||||||
|
if !ok {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return metadata.qname, true
|
||||||
|
}
|
||||||
@@ -2,10 +2,11 @@
|
|||||||
// Use of this source code is governed by a MIT license
|
// Use of this source code is governed by a MIT license
|
||||||
// that can be found in the LICENSE file.
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
package asynq
|
package context
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -24,12 +25,11 @@ func TestCreateContextWithFutureDeadline(t *testing.T) {
|
|||||||
for _, tc := range tests {
|
for _, tc := range tests {
|
||||||
msg := &base.TaskMessage{
|
msg := &base.TaskMessage{
|
||||||
Type: "something",
|
Type: "something",
|
||||||
ID: uuid.New(),
|
ID: uuid.NewString(),
|
||||||
Payload: nil,
|
Payload: nil,
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx, cancel := createContext(msg, tc.deadline)
|
ctx, cancel := New(context.Background(), msg, tc.deadline)
|
||||||
|
|
||||||
select {
|
select {
|
||||||
case x := <-ctx.Done():
|
case x := <-ctx.Done():
|
||||||
t.Errorf("<-ctx.Done() == %v, want nothing (it should block)", x)
|
t.Errorf("<-ctx.Done() == %v, want nothing (it should block)", x)
|
||||||
@@ -54,6 +54,53 @@ func TestCreateContextWithFutureDeadline(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCreateContextWithBaseContext(t *testing.T) {
|
||||||
|
type ctxKey string
|
||||||
|
type ctxValue string
|
||||||
|
var key ctxKey = "key"
|
||||||
|
var value ctxValue = "value"
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
baseCtx context.Context
|
||||||
|
validate func(ctx context.Context, t *testing.T) error
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
baseCtx: context.WithValue(context.Background(), key, value),
|
||||||
|
validate: func(ctx context.Context, t *testing.T) error {
|
||||||
|
got, ok := ctx.Value(key).(ctxValue)
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("ctx.Value().(ctxValue) returned false, expected to be true")
|
||||||
|
}
|
||||||
|
if want := value; got != want {
|
||||||
|
return fmt.Errorf("ctx.Value().(ctxValue) returned unknown value (%v), expected to be %s", got, value)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
msg := &base.TaskMessage{
|
||||||
|
Type: "something",
|
||||||
|
ID: uuid.NewString(),
|
||||||
|
Payload: nil,
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := New(tc.baseCtx, msg, time.Now().Add(30*time.Minute))
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case x := <-ctx.Done():
|
||||||
|
t.Errorf("<-ctx.Done() == %v, want nothing (it should block)", x)
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tc.validate(ctx, t); err != nil {
|
||||||
|
t.Errorf("%v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestCreateContextWithPastDeadline(t *testing.T) {
|
func TestCreateContextWithPastDeadline(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
deadline time.Time
|
deadline time.Time
|
||||||
@@ -64,11 +111,11 @@ func TestCreateContextWithPastDeadline(t *testing.T) {
|
|||||||
for _, tc := range tests {
|
for _, tc := range tests {
|
||||||
msg := &base.TaskMessage{
|
msg := &base.TaskMessage{
|
||||||
Type: "something",
|
Type: "something",
|
||||||
ID: uuid.New(),
|
ID: uuid.NewString(),
|
||||||
Payload: nil,
|
Payload: nil,
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx, cancel := createContext(msg, tc.deadline)
|
ctx, cancel := New(context.Background(), msg, tc.deadline)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
select {
|
select {
|
||||||
@@ -92,21 +139,21 @@ func TestGetTaskMetadataFromContext(t *testing.T) {
|
|||||||
desc string
|
desc string
|
||||||
msg *base.TaskMessage
|
msg *base.TaskMessage
|
||||||
}{
|
}{
|
||||||
{"with zero retried message", &base.TaskMessage{Type: "something", ID: uuid.New(), Retry: 25, Retried: 0, Timeout: 1800, Queue: "default"}},
|
{"with zero retried message", &base.TaskMessage{Type: "something", ID: uuid.NewString(), Retry: 25, Retried: 0, Timeout: 1800, Queue: "default"}},
|
||||||
{"with non-zero retried message", &base.TaskMessage{Type: "something", ID: uuid.New(), Retry: 10, Retried: 5, Timeout: 1800, Queue: "default"}},
|
{"with non-zero retried message", &base.TaskMessage{Type: "something", ID: uuid.NewString(), Retry: 10, Retried: 5, Timeout: 1800, Queue: "default"}},
|
||||||
{"with custom queue name", &base.TaskMessage{Type: "something", ID: uuid.New(), Retry: 25, Retried: 0, Timeout: 1800, Queue: "custom"}},
|
{"with custom queue name", &base.TaskMessage{Type: "something", ID: uuid.NewString(), Retry: 25, Retried: 0, Timeout: 1800, Queue: "custom"}},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, tc := range tests {
|
for _, tc := range tests {
|
||||||
ctx, cancel := createContext(tc.msg, time.Now().Add(30*time.Minute))
|
ctx, cancel := New(context.Background(), tc.msg, time.Now().Add(30*time.Minute))
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
id, ok := GetTaskID(ctx)
|
id, ok := GetTaskID(ctx)
|
||||||
if !ok {
|
if !ok {
|
||||||
t.Errorf("%s: GetTaskID(ctx) returned ok == false", tc.desc)
|
t.Errorf("%s: GetTaskID(ctx) returned ok == false", tc.desc)
|
||||||
}
|
}
|
||||||
if ok && id != tc.msg.ID.String() {
|
if ok && id != tc.msg.ID {
|
||||||
t.Errorf("%s: GetTaskID(ctx) returned id == %q, want %q", tc.desc, id, tc.msg.ID.String())
|
t.Errorf("%s: GetTaskID(ctx) returned id == %q, want %q", tc.desc, id, tc.msg.ID)
|
||||||
}
|
}
|
||||||
|
|
||||||
retried, ok := GetRetryCount(ctx)
|
retried, ok := GetRetryCount(ctx)
|
||||||
303
internal/errors/errors.go
Normal file
303
internal/errors/errors.go
Normal file
@@ -0,0 +1,303 @@
|
|||||||
|
// Copyright 2020 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// Package errors defines the error type and functions used by
|
||||||
|
// asynq and its internal packages.
|
||||||
|
package errors
|
||||||
|
|
||||||
|
// Note: This package is inspired by a blog post about error handling in project Upspin
|
||||||
|
// https://commandcenter.blogspot.com/2017/12/error-handling-in-upspin.html.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Error is the type that implements the error interface.
|
||||||
|
// It contains a number of fields, each of different type.
|
||||||
|
// An Error value may leave some values unset.
|
||||||
|
type Error struct {
|
||||||
|
Code Code
|
||||||
|
Op Op
|
||||||
|
Err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *Error) DebugString() string {
|
||||||
|
var b strings.Builder
|
||||||
|
if e.Op != "" {
|
||||||
|
b.WriteString(string(e.Op))
|
||||||
|
}
|
||||||
|
if e.Code != Unspecified {
|
||||||
|
if b.Len() > 0 {
|
||||||
|
b.WriteString(": ")
|
||||||
|
}
|
||||||
|
b.WriteString(e.Code.String())
|
||||||
|
}
|
||||||
|
if e.Err != nil {
|
||||||
|
if b.Len() > 0 {
|
||||||
|
b.WriteString(": ")
|
||||||
|
}
|
||||||
|
b.WriteString(e.Err.Error())
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *Error) Error() string {
|
||||||
|
var b strings.Builder
|
||||||
|
if e.Code != Unspecified {
|
||||||
|
b.WriteString(e.Code.String())
|
||||||
|
}
|
||||||
|
if e.Err != nil {
|
||||||
|
if b.Len() > 0 {
|
||||||
|
b.WriteString(": ")
|
||||||
|
}
|
||||||
|
b.WriteString(e.Err.Error())
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *Error) Unwrap() error {
|
||||||
|
return e.Err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Code defines the canonical error code.
|
||||||
|
type Code uint8
|
||||||
|
|
||||||
|
// List of canonical error codes.
|
||||||
|
const (
|
||||||
|
Unspecified Code = iota
|
||||||
|
NotFound
|
||||||
|
FailedPrecondition
|
||||||
|
Internal
|
||||||
|
AlreadyExists
|
||||||
|
Unknown
|
||||||
|
// Note: If you add a new value here, make sure to update String method.
|
||||||
|
)
|
||||||
|
|
||||||
|
func (c Code) String() string {
|
||||||
|
switch c {
|
||||||
|
case Unspecified:
|
||||||
|
return "ERROR_CODE_UNSPECIFIED"
|
||||||
|
case NotFound:
|
||||||
|
return "NOT_FOUND"
|
||||||
|
case FailedPrecondition:
|
||||||
|
return "FAILED_PRECONDITION"
|
||||||
|
case Internal:
|
||||||
|
return "INTERNAL_ERROR"
|
||||||
|
case AlreadyExists:
|
||||||
|
return "ALREADY_EXISTS"
|
||||||
|
case Unknown:
|
||||||
|
return "UNKNOWN"
|
||||||
|
}
|
||||||
|
panic(fmt.Sprintf("unknown error code %d", c))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Op describes an operation, usually as the package and method,
|
||||||
|
// such as "rdb.Enqueue".
|
||||||
|
type Op string
|
||||||
|
|
||||||
|
// E builds an error value from its arguments.
|
||||||
|
// There must be at least one argument or E panics.
|
||||||
|
// The type of each argument determines its meaning.
|
||||||
|
// If more than one argument of a given type is presented,
|
||||||
|
// only the last one is recorded.
|
||||||
|
//
|
||||||
|
// The types are:
|
||||||
|
// errors.Op
|
||||||
|
// The operation being performed, usually the method
|
||||||
|
// being invoked (Get, Put, etc.).
|
||||||
|
// errors.Code
|
||||||
|
// The canonical error code, such as NOT_FOUND.
|
||||||
|
// string
|
||||||
|
// Treated as an error message and assigned to the
|
||||||
|
// Err field after a call to errors.New.
|
||||||
|
// error
|
||||||
|
// The underlying error that triggered this one.
|
||||||
|
//
|
||||||
|
// If the error is printed, only those items that have been
|
||||||
|
// set to non-zero values will appear in the result.
|
||||||
|
func E(args ...interface{}) error {
|
||||||
|
if len(args) == 0 {
|
||||||
|
panic("call to errors.E with no arguments")
|
||||||
|
}
|
||||||
|
e := &Error{}
|
||||||
|
for _, arg := range args {
|
||||||
|
switch arg := arg.(type) {
|
||||||
|
case Op:
|
||||||
|
e.Op = arg
|
||||||
|
case Code:
|
||||||
|
e.Code = arg
|
||||||
|
case error:
|
||||||
|
e.Err = arg
|
||||||
|
case string:
|
||||||
|
e.Err = errors.New(arg)
|
||||||
|
default:
|
||||||
|
_, file, line, _ := runtime.Caller(1)
|
||||||
|
log.Printf("errors.E: bad call from %s:%d: %v", file, line, args)
|
||||||
|
return fmt.Errorf("unknown type %T, value %v in error call", arg, arg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
|
||||||
|
// CanonicalCode returns the canonical code of the given error if one is present.
|
||||||
|
// Otherwise it returns Unspecified.
|
||||||
|
func CanonicalCode(err error) Code {
|
||||||
|
if err == nil {
|
||||||
|
return Unspecified
|
||||||
|
}
|
||||||
|
e, ok := err.(*Error)
|
||||||
|
if !ok {
|
||||||
|
return Unspecified
|
||||||
|
}
|
||||||
|
if e.Code == Unspecified {
|
||||||
|
return CanonicalCode(e.Err)
|
||||||
|
}
|
||||||
|
return e.Code
|
||||||
|
}
|
||||||
|
|
||||||
|
/******************************************
|
||||||
|
Domain Specific Error Types & Values
|
||||||
|
*******************************************/
|
||||||
|
|
||||||
|
var (
|
||||||
|
// ErrNoProcessableTask indicates that there are no tasks ready to be processed.
|
||||||
|
ErrNoProcessableTask = errors.New("no tasks are ready for processing")
|
||||||
|
|
||||||
|
// ErrDuplicateTask indicates that another task with the same unique key holds the uniqueness lock.
|
||||||
|
ErrDuplicateTask = errors.New("task already exists")
|
||||||
|
|
||||||
|
// ErrTaskIdConflict indicates that another task with the same task ID already exist
|
||||||
|
ErrTaskIdConflict = errors.New("task id conflicts with another task")
|
||||||
|
)
|
||||||
|
|
||||||
|
// TaskNotFoundError indicates that a task with the given ID does not exist
|
||||||
|
// in the given queue.
|
||||||
|
type TaskNotFoundError struct {
|
||||||
|
Queue string // queue name
|
||||||
|
ID string // task id
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *TaskNotFoundError) Error() string {
|
||||||
|
return fmt.Sprintf("cannot find task with id=%s in queue %q", e.ID, e.Queue)
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsTaskNotFound reports whether any error in err's chain is of type TaskNotFoundError.
|
||||||
|
func IsTaskNotFound(err error) bool {
|
||||||
|
var target *TaskNotFoundError
|
||||||
|
return As(err, &target)
|
||||||
|
}
|
||||||
|
|
||||||
|
// QueueNotFoundError indicates that a queue with the given name does not exist.
|
||||||
|
type QueueNotFoundError struct {
|
||||||
|
Queue string // queue name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *QueueNotFoundError) Error() string {
|
||||||
|
return fmt.Sprintf("queue %q does not exist", e.Queue)
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsQueueNotFound reports whether any error in err's chain is of type QueueNotFoundError.
|
||||||
|
func IsQueueNotFound(err error) bool {
|
||||||
|
var target *QueueNotFoundError
|
||||||
|
return As(err, &target)
|
||||||
|
}
|
||||||
|
|
||||||
|
// QueueNotEmptyError indicates that the given queue is not empty.
|
||||||
|
type QueueNotEmptyError struct {
|
||||||
|
Queue string // queue name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *QueueNotEmptyError) Error() string {
|
||||||
|
return fmt.Sprintf("queue %q is not empty", e.Queue)
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsQueueNotEmpty reports whether any error in err's chain is of type QueueNotEmptyError.
|
||||||
|
func IsQueueNotEmpty(err error) bool {
|
||||||
|
var target *QueueNotEmptyError
|
||||||
|
return As(err, &target)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TaskAlreadyArchivedError indicates that the task in question is already archived.
|
||||||
|
type TaskAlreadyArchivedError struct {
|
||||||
|
Queue string // queue name
|
||||||
|
ID string // task id
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *TaskAlreadyArchivedError) Error() string {
|
||||||
|
return fmt.Sprintf("task is already archived: id=%s, queue=%s", e.ID, e.Queue)
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsTaskAlreadyArchived reports whether any error in err's chain is of type TaskAlreadyArchivedError.
|
||||||
|
func IsTaskAlreadyArchived(err error) bool {
|
||||||
|
var target *TaskAlreadyArchivedError
|
||||||
|
return As(err, &target)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RedisCommandError indicates that the given redis command returned error.
|
||||||
|
type RedisCommandError struct {
|
||||||
|
Command string // redis command (e.g. LRANGE, ZADD, etc)
|
||||||
|
Err error // underlying error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *RedisCommandError) Error() string {
|
||||||
|
return fmt.Sprintf("redis command error: %s failed: %v", strings.ToUpper(e.Command), e.Err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *RedisCommandError) Unwrap() error { return e.Err }
|
||||||
|
|
||||||
|
// IsRedisCommandError reports whether any error in err's chain is of type RedisCommandError.
|
||||||
|
func IsRedisCommandError(err error) bool {
|
||||||
|
var target *RedisCommandError
|
||||||
|
return As(err, &target)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PanicError defines an error when occurred a panic error.
|
||||||
|
type PanicError struct {
|
||||||
|
ErrMsg string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *PanicError) Error() string {
|
||||||
|
return fmt.Sprintf("panic error cause by: %s", e.ErrMsg)
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsPanicError reports whether any error in err's chain is of type PanicError.
|
||||||
|
func IsPanicError(err error) bool {
|
||||||
|
var target *PanicError
|
||||||
|
return As(err, &target)
|
||||||
|
}
|
||||||
|
|
||||||
|
/*************************************************
|
||||||
|
Standard Library errors package functions
|
||||||
|
*************************************************/
|
||||||
|
|
||||||
|
// New returns an error that formats as the given text.
|
||||||
|
// Each call to New returns a distinct error value even if the text is identical.
|
||||||
|
//
|
||||||
|
// This function is the errors.New function from the standard library (https://golang.org/pkg/errors/#New).
|
||||||
|
// It is exported from this package for import convenience.
|
||||||
|
func New(text string) error { return errors.New(text) }
|
||||||
|
|
||||||
|
// Is reports whether any error in err's chain matches target.
|
||||||
|
//
|
||||||
|
// This function is the errors.Is function from the standard library (https://golang.org/pkg/errors/#Is).
|
||||||
|
// It is exported from this package for import convenience.
|
||||||
|
func Is(err, target error) bool { return errors.Is(err, target) }
|
||||||
|
|
||||||
|
// As finds the first error in err's chain that matches target, and if so, sets target to that error value and returns true.
|
||||||
|
// Otherwise, it returns false.
|
||||||
|
//
|
||||||
|
// This function is the errors.As function from the standard library (https://golang.org/pkg/errors/#As).
|
||||||
|
// It is exported from this package for import convenience.
|
||||||
|
func As(err error, target interface{}) bool { return errors.As(err, target) }
|
||||||
|
|
||||||
|
// Unwrap returns the result of calling the Unwrap method on err, if err's type contains an Unwrap method returning error.
|
||||||
|
// Otherwise, Unwrap returns nil.
|
||||||
|
//
|
||||||
|
// This function is the errors.Unwrap function from the standard library (https://golang.org/pkg/errors/#Unwrap).
|
||||||
|
// It is exported from this package for import convenience.
|
||||||
|
func Unwrap(err error) error { return errors.Unwrap(err) }
|
||||||
182
internal/errors/errors_test.go
Normal file
182
internal/errors/errors_test.go
Normal file
@@ -0,0 +1,182 @@
|
|||||||
|
// Copyright 2020 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package errors
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestErrorDebugString(t *testing.T) {
|
||||||
|
// DebugString should include Op since its meant to be used by
|
||||||
|
// maintainers/contributors of the asynq package.
|
||||||
|
tests := []struct {
|
||||||
|
desc string
|
||||||
|
err error
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
desc: "With Op, Code, and string",
|
||||||
|
err: E(Op("rdb.DeleteTask"), NotFound, "cannot find task with id=123"),
|
||||||
|
want: "rdb.DeleteTask: NOT_FOUND: cannot find task with id=123",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "With Op, Code and error",
|
||||||
|
err: E(Op("rdb.DeleteTask"), NotFound, &TaskNotFoundError{Queue: "default", ID: "123"}),
|
||||||
|
want: `rdb.DeleteTask: NOT_FOUND: cannot find task with id=123 in queue "default"`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
if got := tc.err.(*Error).DebugString(); got != tc.want {
|
||||||
|
t.Errorf("%s: got=%q, want=%q", tc.desc, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestErrorString(t *testing.T) {
|
||||||
|
// String method should omit Op since op is an internal detail
|
||||||
|
// and we don't want to provide it to users of the package.
|
||||||
|
tests := []struct {
|
||||||
|
desc string
|
||||||
|
err error
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
desc: "With Op, Code, and string",
|
||||||
|
err: E(Op("rdb.DeleteTask"), NotFound, "cannot find task with id=123"),
|
||||||
|
want: "NOT_FOUND: cannot find task with id=123",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "With Op, Code and error",
|
||||||
|
err: E(Op("rdb.DeleteTask"), NotFound, &TaskNotFoundError{Queue: "default", ID: "123"}),
|
||||||
|
want: `NOT_FOUND: cannot find task with id=123 in queue "default"`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
if got := tc.err.Error(); got != tc.want {
|
||||||
|
t.Errorf("%s: got=%q, want=%q", tc.desc, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestErrorIs(t *testing.T) {
|
||||||
|
var ErrCustom = New("custom sentinel error")
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
desc string
|
||||||
|
err error
|
||||||
|
target error
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
desc: "should unwrap one level",
|
||||||
|
err: E(Op("rdb.DeleteTask"), ErrCustom),
|
||||||
|
target: ErrCustom,
|
||||||
|
want: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
if got := Is(tc.err, tc.target); got != tc.want {
|
||||||
|
t.Errorf("%s: got=%t, want=%t", tc.desc, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestErrorAs(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
desc string
|
||||||
|
err error
|
||||||
|
target interface{}
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
desc: "should unwrap one level",
|
||||||
|
err: E(Op("rdb.DeleteTask"), NotFound, &QueueNotFoundError{Queue: "email"}),
|
||||||
|
target: &QueueNotFoundError{},
|
||||||
|
want: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
if got := As(tc.err, &tc.target); got != tc.want {
|
||||||
|
t.Errorf("%s: got=%t, want=%t", tc.desc, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestErrorPredicates(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
desc string
|
||||||
|
fn func(err error) bool
|
||||||
|
err error
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
desc: "IsTaskNotFound should detect presence of TaskNotFoundError in err's chain",
|
||||||
|
fn: IsTaskNotFound,
|
||||||
|
err: E(Op("rdb.ArchiveTask"), NotFound, &TaskNotFoundError{Queue: "default", ID: "9876"}),
|
||||||
|
want: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "IsTaskNotFound should detect absence of TaskNotFoundError in err's chain",
|
||||||
|
fn: IsTaskNotFound,
|
||||||
|
err: E(Op("rdb.ArchiveTask"), NotFound, &QueueNotFoundError{Queue: "default"}),
|
||||||
|
want: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "IsQueueNotFound should detect presence of QueueNotFoundError in err's chain",
|
||||||
|
fn: IsQueueNotFound,
|
||||||
|
err: E(Op("rdb.ArchiveTask"), NotFound, &QueueNotFoundError{Queue: "default"}),
|
||||||
|
want: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "IsPanicError should detect presence of PanicError in err's chain",
|
||||||
|
fn: IsPanicError,
|
||||||
|
err: E(Op("unknown"), Unknown, &PanicError{ErrMsg: "Something went wrong"}),
|
||||||
|
want: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
if got := tc.fn(tc.err); got != tc.want {
|
||||||
|
t.Errorf("%s: got=%t, want=%t", tc.desc, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCanonicalCode(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
desc string
|
||||||
|
err error
|
||||||
|
want Code
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
desc: "without nesting",
|
||||||
|
err: E(Op("rdb.DeleteTask"), NotFound, &TaskNotFoundError{Queue: "default", ID: "123"}),
|
||||||
|
want: NotFound,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "with nesting",
|
||||||
|
err: E(FailedPrecondition, E(NotFound)),
|
||||||
|
want: FailedPrecondition,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "returns Unspecified if err is not *Error",
|
||||||
|
err: New("some other error"),
|
||||||
|
want: Unspecified,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "returns Unspecified if err is nil",
|
||||||
|
err: nil,
|
||||||
|
want: Unspecified,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
if got := CanonicalCode(tc.err); got != tc.want {
|
||||||
|
t.Errorf("%s: got=%s, want=%s", tc.desc, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
851
internal/proto/asynq.pb.go
Normal file
851
internal/proto/asynq.pb.go
Normal file
@@ -0,0 +1,851 @@
|
|||||||
|
// Copyright 2020 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||||
|
// versions:
|
||||||
|
// protoc-gen-go v1.25.0
|
||||||
|
// protoc v3.17.3
|
||||||
|
// source: asynq.proto
|
||||||
|
|
||||||
|
package proto
|
||||||
|
|
||||||
|
import (
|
||||||
|
proto "github.com/golang/protobuf/proto"
|
||||||
|
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||||
|
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||||
|
timestamppb "google.golang.org/protobuf/types/known/timestamppb"
|
||||||
|
reflect "reflect"
|
||||||
|
sync "sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// Verify that this generated code is sufficiently up-to-date.
|
||||||
|
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||||
|
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||||
|
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||||
|
)
|
||||||
|
|
||||||
|
// This is a compile-time assertion that a sufficiently up-to-date version
|
||||||
|
// of the legacy proto package is being used.
|
||||||
|
const _ = proto.ProtoPackageIsVersion4
|
||||||
|
|
||||||
|
// TaskMessage is the internal representation of a task with additional
|
||||||
|
// metadata fields.
|
||||||
|
// Next ID: 15
|
||||||
|
type TaskMessage struct {
|
||||||
|
state protoimpl.MessageState
|
||||||
|
sizeCache protoimpl.SizeCache
|
||||||
|
unknownFields protoimpl.UnknownFields
|
||||||
|
|
||||||
|
// Type indicates the kind of the task to be performed.
|
||||||
|
Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"`
|
||||||
|
// Payload holds data needed to process the task.
|
||||||
|
Payload []byte `protobuf:"bytes,2,opt,name=payload,proto3" json:"payload,omitempty"`
|
||||||
|
// Unique identifier for the task.
|
||||||
|
Id string `protobuf:"bytes,3,opt,name=id,proto3" json:"id,omitempty"`
|
||||||
|
// Name of the queue to which this task belongs.
|
||||||
|
Queue string `protobuf:"bytes,4,opt,name=queue,proto3" json:"queue,omitempty"`
|
||||||
|
// Max number of retries for this task.
|
||||||
|
Retry int32 `protobuf:"varint,5,opt,name=retry,proto3" json:"retry,omitempty"`
|
||||||
|
// Number of times this task has been retried so far.
|
||||||
|
Retried int32 `protobuf:"varint,6,opt,name=retried,proto3" json:"retried,omitempty"`
|
||||||
|
// Error message from the last failure.
|
||||||
|
ErrorMsg string `protobuf:"bytes,7,opt,name=error_msg,json=errorMsg,proto3" json:"error_msg,omitempty"`
|
||||||
|
// Time of last failure in Unix time,
|
||||||
|
// the number of seconds elapsed since January 1, 1970 UTC.
|
||||||
|
// Use zero to indicate no last failure.
|
||||||
|
LastFailedAt int64 `protobuf:"varint,11,opt,name=last_failed_at,json=lastFailedAt,proto3" json:"last_failed_at,omitempty"`
|
||||||
|
// Timeout specifies timeout in seconds.
|
||||||
|
// Use zero to indicate no timeout.
|
||||||
|
Timeout int64 `protobuf:"varint,8,opt,name=timeout,proto3" json:"timeout,omitempty"`
|
||||||
|
// Deadline specifies the deadline for the task in Unix time,
|
||||||
|
// the number of seconds elapsed since January 1, 1970 UTC.
|
||||||
|
// Use zero to indicate no deadline.
|
||||||
|
Deadline int64 `protobuf:"varint,9,opt,name=deadline,proto3" json:"deadline,omitempty"`
|
||||||
|
// UniqueKey holds the redis key used for uniqueness lock for this task.
|
||||||
|
// Empty string indicates that no uniqueness lock was used.
|
||||||
|
UniqueKey string `protobuf:"bytes,10,opt,name=unique_key,json=uniqueKey,proto3" json:"unique_key,omitempty"`
|
||||||
|
// GroupKey is a name of the group used for task aggregation.
|
||||||
|
// This field is optional and empty value means no aggregation for the task.
|
||||||
|
GroupKey string `protobuf:"bytes,14,opt,name=group_key,json=groupKey,proto3" json:"group_key,omitempty"`
|
||||||
|
// Retention period specified in a number of seconds.
|
||||||
|
// The task will be stored in redis as a completed task until the TTL
|
||||||
|
// expires.
|
||||||
|
Retention int64 `protobuf:"varint,12,opt,name=retention,proto3" json:"retention,omitempty"`
|
||||||
|
// Time when the task completed in success in Unix time,
|
||||||
|
// the number of seconds elapsed since January 1, 1970 UTC.
|
||||||
|
// This field is populated if result_ttl > 0 upon completion.
|
||||||
|
CompletedAt int64 `protobuf:"varint,13,opt,name=completed_at,json=completedAt,proto3" json:"completed_at,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *TaskMessage) Reset() {
|
||||||
|
*x = TaskMessage{}
|
||||||
|
if protoimpl.UnsafeEnabled {
|
||||||
|
mi := &file_asynq_proto_msgTypes[0]
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *TaskMessage) String() string {
|
||||||
|
return protoimpl.X.MessageStringOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*TaskMessage) ProtoMessage() {}
|
||||||
|
|
||||||
|
func (x *TaskMessage) ProtoReflect() protoreflect.Message {
|
||||||
|
mi := &file_asynq_proto_msgTypes[0]
|
||||||
|
if protoimpl.UnsafeEnabled && x != nil {
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
if ms.LoadMessageInfo() == nil {
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
return ms
|
||||||
|
}
|
||||||
|
return mi.MessageOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deprecated: Use TaskMessage.ProtoReflect.Descriptor instead.
|
||||||
|
func (*TaskMessage) Descriptor() ([]byte, []int) {
|
||||||
|
return file_asynq_proto_rawDescGZIP(), []int{0}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *TaskMessage) GetType() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.Type
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *TaskMessage) GetPayload() []byte {
|
||||||
|
if x != nil {
|
||||||
|
return x.Payload
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *TaskMessage) GetId() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.Id
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *TaskMessage) GetQueue() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.Queue
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *TaskMessage) GetRetry() int32 {
|
||||||
|
if x != nil {
|
||||||
|
return x.Retry
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *TaskMessage) GetRetried() int32 {
|
||||||
|
if x != nil {
|
||||||
|
return x.Retried
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *TaskMessage) GetErrorMsg() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.ErrorMsg
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *TaskMessage) GetLastFailedAt() int64 {
|
||||||
|
if x != nil {
|
||||||
|
return x.LastFailedAt
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *TaskMessage) GetTimeout() int64 {
|
||||||
|
if x != nil {
|
||||||
|
return x.Timeout
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *TaskMessage) GetDeadline() int64 {
|
||||||
|
if x != nil {
|
||||||
|
return x.Deadline
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *TaskMessage) GetUniqueKey() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.UniqueKey
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *TaskMessage) GetGroupKey() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.GroupKey
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *TaskMessage) GetRetention() int64 {
|
||||||
|
if x != nil {
|
||||||
|
return x.Retention
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *TaskMessage) GetCompletedAt() int64 {
|
||||||
|
if x != nil {
|
||||||
|
return x.CompletedAt
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// ServerInfo holds information about a running server.
|
||||||
|
type ServerInfo struct {
|
||||||
|
state protoimpl.MessageState
|
||||||
|
sizeCache protoimpl.SizeCache
|
||||||
|
unknownFields protoimpl.UnknownFields
|
||||||
|
|
||||||
|
// Host machine the server is running on.
|
||||||
|
Host string `protobuf:"bytes,1,opt,name=host,proto3" json:"host,omitempty"`
|
||||||
|
// PID of the server process.
|
||||||
|
Pid int32 `protobuf:"varint,2,opt,name=pid,proto3" json:"pid,omitempty"`
|
||||||
|
// Unique identifier for this server.
|
||||||
|
ServerId string `protobuf:"bytes,3,opt,name=server_id,json=serverId,proto3" json:"server_id,omitempty"`
|
||||||
|
// Maximum number of concurrency this server will use.
|
||||||
|
Concurrency int32 `protobuf:"varint,4,opt,name=concurrency,proto3" json:"concurrency,omitempty"`
|
||||||
|
// List of queue names with their priorities.
|
||||||
|
// The server will consume tasks from the queues and prioritize
|
||||||
|
// queues with higher priority numbers.
|
||||||
|
Queues map[string]int32 `protobuf:"bytes,5,rep,name=queues,proto3" json:"queues,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"`
|
||||||
|
// If set, the server will always consume tasks from a queue with higher
|
||||||
|
// priority.
|
||||||
|
StrictPriority bool `protobuf:"varint,6,opt,name=strict_priority,json=strictPriority,proto3" json:"strict_priority,omitempty"`
|
||||||
|
// Status indicates the status of the server.
|
||||||
|
Status string `protobuf:"bytes,7,opt,name=status,proto3" json:"status,omitempty"`
|
||||||
|
// Time this server was started.
|
||||||
|
StartTime *timestamppb.Timestamp `protobuf:"bytes,8,opt,name=start_time,json=startTime,proto3" json:"start_time,omitempty"`
|
||||||
|
// Number of workers currently processing tasks.
|
||||||
|
ActiveWorkerCount int32 `protobuf:"varint,9,opt,name=active_worker_count,json=activeWorkerCount,proto3" json:"active_worker_count,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *ServerInfo) Reset() {
|
||||||
|
*x = ServerInfo{}
|
||||||
|
if protoimpl.UnsafeEnabled {
|
||||||
|
mi := &file_asynq_proto_msgTypes[1]
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *ServerInfo) String() string {
|
||||||
|
return protoimpl.X.MessageStringOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*ServerInfo) ProtoMessage() {}
|
||||||
|
|
||||||
|
func (x *ServerInfo) ProtoReflect() protoreflect.Message {
|
||||||
|
mi := &file_asynq_proto_msgTypes[1]
|
||||||
|
if protoimpl.UnsafeEnabled && x != nil {
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
if ms.LoadMessageInfo() == nil {
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
return ms
|
||||||
|
}
|
||||||
|
return mi.MessageOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deprecated: Use ServerInfo.ProtoReflect.Descriptor instead.
|
||||||
|
func (*ServerInfo) Descriptor() ([]byte, []int) {
|
||||||
|
return file_asynq_proto_rawDescGZIP(), []int{1}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *ServerInfo) GetHost() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.Host
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *ServerInfo) GetPid() int32 {
|
||||||
|
if x != nil {
|
||||||
|
return x.Pid
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *ServerInfo) GetServerId() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.ServerId
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *ServerInfo) GetConcurrency() int32 {
|
||||||
|
if x != nil {
|
||||||
|
return x.Concurrency
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *ServerInfo) GetQueues() map[string]int32 {
|
||||||
|
if x != nil {
|
||||||
|
return x.Queues
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *ServerInfo) GetStrictPriority() bool {
|
||||||
|
if x != nil {
|
||||||
|
return x.StrictPriority
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *ServerInfo) GetStatus() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.Status
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *ServerInfo) GetStartTime() *timestamppb.Timestamp {
|
||||||
|
if x != nil {
|
||||||
|
return x.StartTime
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *ServerInfo) GetActiveWorkerCount() int32 {
|
||||||
|
if x != nil {
|
||||||
|
return x.ActiveWorkerCount
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// WorkerInfo holds information about a running worker.
|
||||||
|
type WorkerInfo struct {
|
||||||
|
state protoimpl.MessageState
|
||||||
|
sizeCache protoimpl.SizeCache
|
||||||
|
unknownFields protoimpl.UnknownFields
|
||||||
|
|
||||||
|
// Host matchine this worker is running on.
|
||||||
|
Host string `protobuf:"bytes,1,opt,name=host,proto3" json:"host,omitempty"`
|
||||||
|
// PID of the process in which this worker is running.
|
||||||
|
Pid int32 `protobuf:"varint,2,opt,name=pid,proto3" json:"pid,omitempty"`
|
||||||
|
// ID of the server in which this worker is running.
|
||||||
|
ServerId string `protobuf:"bytes,3,opt,name=server_id,json=serverId,proto3" json:"server_id,omitempty"`
|
||||||
|
// ID of the task this worker is processing.
|
||||||
|
TaskId string `protobuf:"bytes,4,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"`
|
||||||
|
// Type of the task this worker is processing.
|
||||||
|
TaskType string `protobuf:"bytes,5,opt,name=task_type,json=taskType,proto3" json:"task_type,omitempty"`
|
||||||
|
// Payload of the task this worker is processing.
|
||||||
|
TaskPayload []byte `protobuf:"bytes,6,opt,name=task_payload,json=taskPayload,proto3" json:"task_payload,omitempty"`
|
||||||
|
// Name of the queue the task the worker is processing belongs.
|
||||||
|
Queue string `protobuf:"bytes,7,opt,name=queue,proto3" json:"queue,omitempty"`
|
||||||
|
// Time this worker started processing the task.
|
||||||
|
StartTime *timestamppb.Timestamp `protobuf:"bytes,8,opt,name=start_time,json=startTime,proto3" json:"start_time,omitempty"`
|
||||||
|
// Deadline by which the worker needs to complete processing
|
||||||
|
// the task. If worker exceeds the deadline, the task will fail.
|
||||||
|
Deadline *timestamppb.Timestamp `protobuf:"bytes,9,opt,name=deadline,proto3" json:"deadline,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *WorkerInfo) Reset() {
|
||||||
|
*x = WorkerInfo{}
|
||||||
|
if protoimpl.UnsafeEnabled {
|
||||||
|
mi := &file_asynq_proto_msgTypes[2]
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *WorkerInfo) String() string {
|
||||||
|
return protoimpl.X.MessageStringOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*WorkerInfo) ProtoMessage() {}
|
||||||
|
|
||||||
|
func (x *WorkerInfo) ProtoReflect() protoreflect.Message {
|
||||||
|
mi := &file_asynq_proto_msgTypes[2]
|
||||||
|
if protoimpl.UnsafeEnabled && x != nil {
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
if ms.LoadMessageInfo() == nil {
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
return ms
|
||||||
|
}
|
||||||
|
return mi.MessageOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deprecated: Use WorkerInfo.ProtoReflect.Descriptor instead.
|
||||||
|
func (*WorkerInfo) Descriptor() ([]byte, []int) {
|
||||||
|
return file_asynq_proto_rawDescGZIP(), []int{2}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *WorkerInfo) GetHost() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.Host
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *WorkerInfo) GetPid() int32 {
|
||||||
|
if x != nil {
|
||||||
|
return x.Pid
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *WorkerInfo) GetServerId() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.ServerId
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *WorkerInfo) GetTaskId() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.TaskId
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *WorkerInfo) GetTaskType() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.TaskType
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *WorkerInfo) GetTaskPayload() []byte {
|
||||||
|
if x != nil {
|
||||||
|
return x.TaskPayload
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *WorkerInfo) GetQueue() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.Queue
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *WorkerInfo) GetStartTime() *timestamppb.Timestamp {
|
||||||
|
if x != nil {
|
||||||
|
return x.StartTime
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *WorkerInfo) GetDeadline() *timestamppb.Timestamp {
|
||||||
|
if x != nil {
|
||||||
|
return x.Deadline
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SchedulerEntry holds information about a periodic task registered
|
||||||
|
// with a scheduler.
|
||||||
|
type SchedulerEntry struct {
|
||||||
|
state protoimpl.MessageState
|
||||||
|
sizeCache protoimpl.SizeCache
|
||||||
|
unknownFields protoimpl.UnknownFields
|
||||||
|
|
||||||
|
// Identifier of the scheduler entry.
|
||||||
|
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
|
||||||
|
// Periodic schedule spec of the entry.
|
||||||
|
Spec string `protobuf:"bytes,2,opt,name=spec,proto3" json:"spec,omitempty"`
|
||||||
|
// Task type of the periodic task.
|
||||||
|
TaskType string `protobuf:"bytes,3,opt,name=task_type,json=taskType,proto3" json:"task_type,omitempty"`
|
||||||
|
// Task payload of the periodic task.
|
||||||
|
TaskPayload []byte `protobuf:"bytes,4,opt,name=task_payload,json=taskPayload,proto3" json:"task_payload,omitempty"`
|
||||||
|
// Options used to enqueue the periodic task.
|
||||||
|
EnqueueOptions []string `protobuf:"bytes,5,rep,name=enqueue_options,json=enqueueOptions,proto3" json:"enqueue_options,omitempty"`
|
||||||
|
// Next time the task will be enqueued.
|
||||||
|
NextEnqueueTime *timestamppb.Timestamp `protobuf:"bytes,6,opt,name=next_enqueue_time,json=nextEnqueueTime,proto3" json:"next_enqueue_time,omitempty"`
|
||||||
|
// Last time the task was enqueued.
|
||||||
|
// Zero time if task was never enqueued.
|
||||||
|
PrevEnqueueTime *timestamppb.Timestamp `protobuf:"bytes,7,opt,name=prev_enqueue_time,json=prevEnqueueTime,proto3" json:"prev_enqueue_time,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *SchedulerEntry) Reset() {
|
||||||
|
*x = SchedulerEntry{}
|
||||||
|
if protoimpl.UnsafeEnabled {
|
||||||
|
mi := &file_asynq_proto_msgTypes[3]
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *SchedulerEntry) String() string {
|
||||||
|
return protoimpl.X.MessageStringOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*SchedulerEntry) ProtoMessage() {}
|
||||||
|
|
||||||
|
func (x *SchedulerEntry) ProtoReflect() protoreflect.Message {
|
||||||
|
mi := &file_asynq_proto_msgTypes[3]
|
||||||
|
if protoimpl.UnsafeEnabled && x != nil {
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
if ms.LoadMessageInfo() == nil {
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
return ms
|
||||||
|
}
|
||||||
|
return mi.MessageOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deprecated: Use SchedulerEntry.ProtoReflect.Descriptor instead.
|
||||||
|
func (*SchedulerEntry) Descriptor() ([]byte, []int) {
|
||||||
|
return file_asynq_proto_rawDescGZIP(), []int{3}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *SchedulerEntry) GetId() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.Id
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *SchedulerEntry) GetSpec() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.Spec
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *SchedulerEntry) GetTaskType() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.TaskType
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *SchedulerEntry) GetTaskPayload() []byte {
|
||||||
|
if x != nil {
|
||||||
|
return x.TaskPayload
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *SchedulerEntry) GetEnqueueOptions() []string {
|
||||||
|
if x != nil {
|
||||||
|
return x.EnqueueOptions
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *SchedulerEntry) GetNextEnqueueTime() *timestamppb.Timestamp {
|
||||||
|
if x != nil {
|
||||||
|
return x.NextEnqueueTime
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *SchedulerEntry) GetPrevEnqueueTime() *timestamppb.Timestamp {
|
||||||
|
if x != nil {
|
||||||
|
return x.PrevEnqueueTime
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SchedulerEnqueueEvent holds information about an enqueue event
|
||||||
|
// by a scheduler.
|
||||||
|
type SchedulerEnqueueEvent struct {
|
||||||
|
state protoimpl.MessageState
|
||||||
|
sizeCache protoimpl.SizeCache
|
||||||
|
unknownFields protoimpl.UnknownFields
|
||||||
|
|
||||||
|
// ID of the task that was enqueued.
|
||||||
|
TaskId string `protobuf:"bytes,1,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"`
|
||||||
|
// Time the task was enqueued.
|
||||||
|
EnqueueTime *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=enqueue_time,json=enqueueTime,proto3" json:"enqueue_time,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *SchedulerEnqueueEvent) Reset() {
|
||||||
|
*x = SchedulerEnqueueEvent{}
|
||||||
|
if protoimpl.UnsafeEnabled {
|
||||||
|
mi := &file_asynq_proto_msgTypes[4]
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *SchedulerEnqueueEvent) String() string {
|
||||||
|
return protoimpl.X.MessageStringOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*SchedulerEnqueueEvent) ProtoMessage() {}
|
||||||
|
|
||||||
|
func (x *SchedulerEnqueueEvent) ProtoReflect() protoreflect.Message {
|
||||||
|
mi := &file_asynq_proto_msgTypes[4]
|
||||||
|
if protoimpl.UnsafeEnabled && x != nil {
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
if ms.LoadMessageInfo() == nil {
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
return ms
|
||||||
|
}
|
||||||
|
return mi.MessageOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deprecated: Use SchedulerEnqueueEvent.ProtoReflect.Descriptor instead.
|
||||||
|
func (*SchedulerEnqueueEvent) Descriptor() ([]byte, []int) {
|
||||||
|
return file_asynq_proto_rawDescGZIP(), []int{4}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *SchedulerEnqueueEvent) GetTaskId() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.TaskId
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *SchedulerEnqueueEvent) GetEnqueueTime() *timestamppb.Timestamp {
|
||||||
|
if x != nil {
|
||||||
|
return x.EnqueueTime
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var File_asynq_proto protoreflect.FileDescriptor
|
||||||
|
|
||||||
|
var file_asynq_proto_rawDesc = []byte{
|
||||||
|
0x0a, 0x0b, 0x61, 0x73, 0x79, 0x6e, 0x71, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x05, 0x61,
|
||||||
|
0x73, 0x79, 0x6e, 0x71, 0x1a, 0x1f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f,
|
||||||
|
0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e,
|
||||||
|
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x87, 0x03, 0x0a, 0x0b, 0x54, 0x61, 0x73, 0x6b, 0x4d, 0x65,
|
||||||
|
0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20,
|
||||||
|
0x01, 0x28, 0x09, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x70, 0x61, 0x79,
|
||||||
|
0x6c, 0x6f, 0x61, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x70, 0x61, 0x79, 0x6c,
|
||||||
|
0x6f, 0x61, 0x64, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52,
|
||||||
|
0x02, 0x69, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x71, 0x75, 0x65, 0x75, 0x65, 0x18, 0x04, 0x20, 0x01,
|
||||||
|
0x28, 0x09, 0x52, 0x05, 0x71, 0x75, 0x65, 0x75, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x72, 0x65, 0x74,
|
||||||
|
0x72, 0x79, 0x18, 0x05, 0x20, 0x01, 0x28, 0x05, 0x52, 0x05, 0x72, 0x65, 0x74, 0x72, 0x79, 0x12,
|
||||||
|
0x18, 0x0a, 0x07, 0x72, 0x65, 0x74, 0x72, 0x69, 0x65, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x05,
|
||||||
|
0x52, 0x07, 0x72, 0x65, 0x74, 0x72, 0x69, 0x65, 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x65, 0x72, 0x72,
|
||||||
|
0x6f, 0x72, 0x5f, 0x6d, 0x73, 0x67, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x65, 0x72,
|
||||||
|
0x72, 0x6f, 0x72, 0x4d, 0x73, 0x67, 0x12, 0x24, 0x0a, 0x0e, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x66,
|
||||||
|
0x61, 0x69, 0x6c, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0c,
|
||||||
|
0x6c, 0x61, 0x73, 0x74, 0x46, 0x61, 0x69, 0x6c, 0x65, 0x64, 0x41, 0x74, 0x12, 0x18, 0x0a, 0x07,
|
||||||
|
0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x08, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, 0x74,
|
||||||
|
0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69,
|
||||||
|
0x6e, 0x65, 0x18, 0x09, 0x20, 0x01, 0x28, 0x03, 0x52, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69,
|
||||||
|
0x6e, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x75, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x5f, 0x6b, 0x65, 0x79,
|
||||||
|
0x18, 0x0a, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x75, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x4b, 0x65,
|
||||||
|
0x79, 0x12, 0x1b, 0x0a, 0x09, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x6b, 0x65, 0x79, 0x18, 0x0e,
|
||||||
|
0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x4b, 0x65, 0x79, 0x12, 0x1c,
|
||||||
|
0x0a, 0x09, 0x72, 0x65, 0x74, 0x65, 0x6e, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x0c, 0x20, 0x01, 0x28,
|
||||||
|
0x03, 0x52, 0x09, 0x72, 0x65, 0x74, 0x65, 0x6e, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x21, 0x0a, 0x0c,
|
||||||
|
0x63, 0x6f, 0x6d, 0x70, 0x6c, 0x65, 0x74, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x18, 0x0d, 0x20, 0x01,
|
||||||
|
0x28, 0x03, 0x52, 0x0b, 0x63, 0x6f, 0x6d, 0x70, 0x6c, 0x65, 0x74, 0x65, 0x64, 0x41, 0x74, 0x22,
|
||||||
|
0x8f, 0x03, 0x0a, 0x0a, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x12,
|
||||||
|
0x0a, 0x04, 0x68, 0x6f, 0x73, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x68, 0x6f,
|
||||||
|
0x73, 0x74, 0x12, 0x10, 0x0a, 0x03, 0x70, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52,
|
||||||
|
0x03, 0x70, 0x69, 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x5f, 0x69,
|
||||||
|
0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x49,
|
||||||
|
0x64, 0x12, 0x20, 0x0a, 0x0b, 0x63, 0x6f, 0x6e, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x63, 0x79,
|
||||||
|
0x18, 0x04, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0b, 0x63, 0x6f, 0x6e, 0x63, 0x75, 0x72, 0x72, 0x65,
|
||||||
|
0x6e, 0x63, 0x79, 0x12, 0x35, 0x0a, 0x06, 0x71, 0x75, 0x65, 0x75, 0x65, 0x73, 0x18, 0x05, 0x20,
|
||||||
|
0x03, 0x28, 0x0b, 0x32, 0x1d, 0x2e, 0x61, 0x73, 0x79, 0x6e, 0x71, 0x2e, 0x53, 0x65, 0x72, 0x76,
|
||||||
|
0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x51, 0x75, 0x65, 0x75, 0x65, 0x73, 0x45, 0x6e, 0x74,
|
||||||
|
0x72, 0x79, 0x52, 0x06, 0x71, 0x75, 0x65, 0x75, 0x65, 0x73, 0x12, 0x27, 0x0a, 0x0f, 0x73, 0x74,
|
||||||
|
0x72, 0x69, 0x63, 0x74, 0x5f, 0x70, 0x72, 0x69, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x18, 0x06, 0x20,
|
||||||
|
0x01, 0x28, 0x08, 0x52, 0x0e, 0x73, 0x74, 0x72, 0x69, 0x63, 0x74, 0x50, 0x72, 0x69, 0x6f, 0x72,
|
||||||
|
0x69, 0x74, 0x79, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x07, 0x20,
|
||||||
|
0x01, 0x28, 0x09, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x39, 0x0a, 0x0a, 0x73,
|
||||||
|
0x74, 0x61, 0x72, 0x74, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32,
|
||||||
|
0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75,
|
||||||
|
0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x73, 0x74, 0x61,
|
||||||
|
0x72, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x2e, 0x0a, 0x13, 0x61, 0x63, 0x74, 0x69, 0x76, 0x65,
|
||||||
|
0x5f, 0x77, 0x6f, 0x72, 0x6b, 0x65, 0x72, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x09, 0x20,
|
||||||
|
0x01, 0x28, 0x05, 0x52, 0x11, 0x61, 0x63, 0x74, 0x69, 0x76, 0x65, 0x57, 0x6f, 0x72, 0x6b, 0x65,
|
||||||
|
0x72, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x1a, 0x39, 0x0a, 0x0b, 0x51, 0x75, 0x65, 0x75, 0x65, 0x73,
|
||||||
|
0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01,
|
||||||
|
0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65,
|
||||||
|
0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38,
|
||||||
|
0x01, 0x22, 0xb1, 0x02, 0x0a, 0x0a, 0x57, 0x6f, 0x72, 0x6b, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f,
|
||||||
|
0x12, 0x12, 0x0a, 0x04, 0x68, 0x6f, 0x73, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04,
|
||||||
|
0x68, 0x6f, 0x73, 0x74, 0x12, 0x10, 0x0a, 0x03, 0x70, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28,
|
||||||
|
0x05, 0x52, 0x03, 0x70, 0x69, 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72,
|
||||||
|
0x5f, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x73, 0x65, 0x72, 0x76, 0x65,
|
||||||
|
0x72, 0x49, 0x64, 0x12, 0x17, 0x0a, 0x07, 0x74, 0x61, 0x73, 0x6b, 0x5f, 0x69, 0x64, 0x18, 0x04,
|
||||||
|
0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x74, 0x61, 0x73, 0x6b, 0x49, 0x64, 0x12, 0x1b, 0x0a, 0x09,
|
||||||
|
0x74, 0x61, 0x73, 0x6b, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52,
|
||||||
|
0x08, 0x74, 0x61, 0x73, 0x6b, 0x54, 0x79, 0x70, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x74, 0x61, 0x73,
|
||||||
|
0x6b, 0x5f, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0c, 0x52,
|
||||||
|
0x0b, 0x74, 0x61, 0x73, 0x6b, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x12, 0x14, 0x0a, 0x05,
|
||||||
|
0x71, 0x75, 0x65, 0x75, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x71, 0x75, 0x65,
|
||||||
|
0x75, 0x65, 0x12, 0x39, 0x0a, 0x0a, 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x74, 0x69, 0x6d, 0x65,
|
||||||
|
0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e,
|
||||||
|
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61,
|
||||||
|
0x6d, 0x70, 0x52, 0x09, 0x73, 0x74, 0x61, 0x72, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x36, 0x0a,
|
||||||
|
0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32,
|
||||||
|
0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75,
|
||||||
|
0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x08, 0x64, 0x65, 0x61,
|
||||||
|
0x64, 0x6c, 0x69, 0x6e, 0x65, 0x22, 0xad, 0x02, 0x0a, 0x0e, 0x53, 0x63, 0x68, 0x65, 0x64, 0x75,
|
||||||
|
0x6c, 0x65, 0x72, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01,
|
||||||
|
0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x73, 0x70, 0x65, 0x63,
|
||||||
|
0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x73, 0x70, 0x65, 0x63, 0x12, 0x1b, 0x0a, 0x09,
|
||||||
|
0x74, 0x61, 0x73, 0x6b, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52,
|
||||||
|
0x08, 0x74, 0x61, 0x73, 0x6b, 0x54, 0x79, 0x70, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x74, 0x61, 0x73,
|
||||||
|
0x6b, 0x5f, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52,
|
||||||
|
0x0b, 0x74, 0x61, 0x73, 0x6b, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x12, 0x27, 0x0a, 0x0f,
|
||||||
|
0x65, 0x6e, 0x71, 0x75, 0x65, 0x75, 0x65, 0x5f, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18,
|
||||||
|
0x05, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0e, 0x65, 0x6e, 0x71, 0x75, 0x65, 0x75, 0x65, 0x4f, 0x70,
|
||||||
|
0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x46, 0x0a, 0x11, 0x6e, 0x65, 0x78, 0x74, 0x5f, 0x65, 0x6e,
|
||||||
|
0x71, 0x75, 0x65, 0x75, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b,
|
||||||
|
0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62,
|
||||||
|
0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0f, 0x6e, 0x65,
|
||||||
|
0x78, 0x74, 0x45, 0x6e, 0x71, 0x75, 0x65, 0x75, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x46, 0x0a,
|
||||||
|
0x11, 0x70, 0x72, 0x65, 0x76, 0x5f, 0x65, 0x6e, 0x71, 0x75, 0x65, 0x75, 0x65, 0x5f, 0x74, 0x69,
|
||||||
|
0x6d, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c,
|
||||||
|
0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73,
|
||||||
|
0x74, 0x61, 0x6d, 0x70, 0x52, 0x0f, 0x70, 0x72, 0x65, 0x76, 0x45, 0x6e, 0x71, 0x75, 0x65, 0x75,
|
||||||
|
0x65, 0x54, 0x69, 0x6d, 0x65, 0x22, 0x6f, 0x0a, 0x15, 0x53, 0x63, 0x68, 0x65, 0x64, 0x75, 0x6c,
|
||||||
|
0x65, 0x72, 0x45, 0x6e, 0x71, 0x75, 0x65, 0x75, 0x65, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x12, 0x17,
|
||||||
|
0x0a, 0x07, 0x74, 0x61, 0x73, 0x6b, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52,
|
||||||
|
0x06, 0x74, 0x61, 0x73, 0x6b, 0x49, 0x64, 0x12, 0x3d, 0x0a, 0x0c, 0x65, 0x6e, 0x71, 0x75, 0x65,
|
||||||
|
0x75, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e,
|
||||||
|
0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e,
|
||||||
|
0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0b, 0x65, 0x6e, 0x71, 0x75, 0x65,
|
||||||
|
0x75, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x42, 0x29, 0x5a, 0x27, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62,
|
||||||
|
0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x68, 0x69, 0x62, 0x69, 0x6b, 0x65, 0x6e, 0x2f, 0x61, 0x73, 0x79,
|
||||||
|
0x6e, 0x71, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x70, 0x72, 0x6f, 0x74,
|
||||||
|
0x6f, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
file_asynq_proto_rawDescOnce sync.Once
|
||||||
|
file_asynq_proto_rawDescData = file_asynq_proto_rawDesc
|
||||||
|
)
|
||||||
|
|
||||||
|
func file_asynq_proto_rawDescGZIP() []byte {
|
||||||
|
file_asynq_proto_rawDescOnce.Do(func() {
|
||||||
|
file_asynq_proto_rawDescData = protoimpl.X.CompressGZIP(file_asynq_proto_rawDescData)
|
||||||
|
})
|
||||||
|
return file_asynq_proto_rawDescData
|
||||||
|
}
|
||||||
|
|
||||||
|
var file_asynq_proto_msgTypes = make([]protoimpl.MessageInfo, 6)
|
||||||
|
var file_asynq_proto_goTypes = []interface{}{
|
||||||
|
(*TaskMessage)(nil), // 0: asynq.TaskMessage
|
||||||
|
(*ServerInfo)(nil), // 1: asynq.ServerInfo
|
||||||
|
(*WorkerInfo)(nil), // 2: asynq.WorkerInfo
|
||||||
|
(*SchedulerEntry)(nil), // 3: asynq.SchedulerEntry
|
||||||
|
(*SchedulerEnqueueEvent)(nil), // 4: asynq.SchedulerEnqueueEvent
|
||||||
|
nil, // 5: asynq.ServerInfo.QueuesEntry
|
||||||
|
(*timestamppb.Timestamp)(nil), // 6: google.protobuf.Timestamp
|
||||||
|
}
|
||||||
|
var file_asynq_proto_depIdxs = []int32{
|
||||||
|
5, // 0: asynq.ServerInfo.queues:type_name -> asynq.ServerInfo.QueuesEntry
|
||||||
|
6, // 1: asynq.ServerInfo.start_time:type_name -> google.protobuf.Timestamp
|
||||||
|
6, // 2: asynq.WorkerInfo.start_time:type_name -> google.protobuf.Timestamp
|
||||||
|
6, // 3: asynq.WorkerInfo.deadline:type_name -> google.protobuf.Timestamp
|
||||||
|
6, // 4: asynq.SchedulerEntry.next_enqueue_time:type_name -> google.protobuf.Timestamp
|
||||||
|
6, // 5: asynq.SchedulerEntry.prev_enqueue_time:type_name -> google.protobuf.Timestamp
|
||||||
|
6, // 6: asynq.SchedulerEnqueueEvent.enqueue_time:type_name -> google.protobuf.Timestamp
|
||||||
|
7, // [7:7] is the sub-list for method output_type
|
||||||
|
7, // [7:7] is the sub-list for method input_type
|
||||||
|
7, // [7:7] is the sub-list for extension type_name
|
||||||
|
7, // [7:7] is the sub-list for extension extendee
|
||||||
|
0, // [0:7] is the sub-list for field type_name
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() { file_asynq_proto_init() }
|
||||||
|
func file_asynq_proto_init() {
|
||||||
|
if File_asynq_proto != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !protoimpl.UnsafeEnabled {
|
||||||
|
file_asynq_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
|
||||||
|
switch v := v.(*TaskMessage); i {
|
||||||
|
case 0:
|
||||||
|
return &v.state
|
||||||
|
case 1:
|
||||||
|
return &v.sizeCache
|
||||||
|
case 2:
|
||||||
|
return &v.unknownFields
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
file_asynq_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
|
||||||
|
switch v := v.(*ServerInfo); i {
|
||||||
|
case 0:
|
||||||
|
return &v.state
|
||||||
|
case 1:
|
||||||
|
return &v.sizeCache
|
||||||
|
case 2:
|
||||||
|
return &v.unknownFields
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
file_asynq_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
|
||||||
|
switch v := v.(*WorkerInfo); i {
|
||||||
|
case 0:
|
||||||
|
return &v.state
|
||||||
|
case 1:
|
||||||
|
return &v.sizeCache
|
||||||
|
case 2:
|
||||||
|
return &v.unknownFields
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
file_asynq_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
|
||||||
|
switch v := v.(*SchedulerEntry); i {
|
||||||
|
case 0:
|
||||||
|
return &v.state
|
||||||
|
case 1:
|
||||||
|
return &v.sizeCache
|
||||||
|
case 2:
|
||||||
|
return &v.unknownFields
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
file_asynq_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} {
|
||||||
|
switch v := v.(*SchedulerEnqueueEvent); i {
|
||||||
|
case 0:
|
||||||
|
return &v.state
|
||||||
|
case 1:
|
||||||
|
return &v.sizeCache
|
||||||
|
case 2:
|
||||||
|
return &v.unknownFields
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
type x struct{}
|
||||||
|
out := protoimpl.TypeBuilder{
|
||||||
|
File: protoimpl.DescBuilder{
|
||||||
|
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||||
|
RawDescriptor: file_asynq_proto_rawDesc,
|
||||||
|
NumEnums: 0,
|
||||||
|
NumMessages: 6,
|
||||||
|
NumExtensions: 0,
|
||||||
|
NumServices: 0,
|
||||||
|
},
|
||||||
|
GoTypes: file_asynq_proto_goTypes,
|
||||||
|
DependencyIndexes: file_asynq_proto_depIdxs,
|
||||||
|
MessageInfos: file_asynq_proto_msgTypes,
|
||||||
|
}.Build()
|
||||||
|
File_asynq_proto = out.File
|
||||||
|
file_asynq_proto_rawDesc = nil
|
||||||
|
file_asynq_proto_goTypes = nil
|
||||||
|
file_asynq_proto_depIdxs = nil
|
||||||
|
}
|
||||||
168
internal/proto/asynq.proto
Normal file
168
internal/proto/asynq.proto
Normal file
@@ -0,0 +1,168 @@
|
|||||||
|
// Copyright 2020 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
syntax = "proto3";
|
||||||
|
package asynq;
|
||||||
|
|
||||||
|
import "google/protobuf/timestamp.proto";
|
||||||
|
|
||||||
|
option go_package = "github.com/hibiken/asynq/internal/proto";
|
||||||
|
|
||||||
|
// TaskMessage is the internal representation of a task with additional
|
||||||
|
// metadata fields.
|
||||||
|
// Next ID: 15
|
||||||
|
message TaskMessage {
|
||||||
|
// Type indicates the kind of the task to be performed.
|
||||||
|
string type = 1;
|
||||||
|
|
||||||
|
// Payload holds data needed to process the task.
|
||||||
|
bytes payload = 2;
|
||||||
|
|
||||||
|
// Unique identifier for the task.
|
||||||
|
string id = 3;
|
||||||
|
|
||||||
|
// Name of the queue to which this task belongs.
|
||||||
|
string queue = 4;
|
||||||
|
|
||||||
|
// Max number of retries for this task.
|
||||||
|
int32 retry = 5;
|
||||||
|
|
||||||
|
// Number of times this task has been retried so far.
|
||||||
|
int32 retried = 6;
|
||||||
|
|
||||||
|
// Error message from the last failure.
|
||||||
|
string error_msg = 7;
|
||||||
|
|
||||||
|
// Time of last failure in Unix time,
|
||||||
|
// the number of seconds elapsed since January 1, 1970 UTC.
|
||||||
|
// Use zero to indicate no last failure.
|
||||||
|
int64 last_failed_at = 11;
|
||||||
|
|
||||||
|
// Timeout specifies timeout in seconds.
|
||||||
|
// Use zero to indicate no timeout.
|
||||||
|
int64 timeout = 8;
|
||||||
|
|
||||||
|
// Deadline specifies the deadline for the task in Unix time,
|
||||||
|
// the number of seconds elapsed since January 1, 1970 UTC.
|
||||||
|
// Use zero to indicate no deadline.
|
||||||
|
int64 deadline = 9;
|
||||||
|
|
||||||
|
// UniqueKey holds the redis key used for uniqueness lock for this task.
|
||||||
|
// Empty string indicates that no uniqueness lock was used.
|
||||||
|
string unique_key = 10;
|
||||||
|
|
||||||
|
// GroupKey is a name of the group used for task aggregation.
|
||||||
|
// This field is optional and empty value means no aggregation for the task.
|
||||||
|
string group_key = 14;
|
||||||
|
|
||||||
|
// Retention period specified in a number of seconds.
|
||||||
|
// The task will be stored in redis as a completed task until the TTL
|
||||||
|
// expires.
|
||||||
|
int64 retention = 12;
|
||||||
|
|
||||||
|
// Time when the task completed in success in Unix time,
|
||||||
|
// the number of seconds elapsed since January 1, 1970 UTC.
|
||||||
|
// This field is populated if result_ttl > 0 upon completion.
|
||||||
|
int64 completed_at = 13;
|
||||||
|
};
|
||||||
|
|
||||||
|
// ServerInfo holds information about a running server.
|
||||||
|
message ServerInfo {
|
||||||
|
// Host machine the server is running on.
|
||||||
|
string host = 1;
|
||||||
|
|
||||||
|
// PID of the server process.
|
||||||
|
int32 pid = 2;
|
||||||
|
|
||||||
|
// Unique identifier for this server.
|
||||||
|
string server_id = 3;
|
||||||
|
|
||||||
|
// Maximum number of concurrency this server will use.
|
||||||
|
int32 concurrency = 4;
|
||||||
|
|
||||||
|
// List of queue names with their priorities.
|
||||||
|
// The server will consume tasks from the queues and prioritize
|
||||||
|
// queues with higher priority numbers.
|
||||||
|
map<string, int32> queues = 5;
|
||||||
|
|
||||||
|
// If set, the server will always consume tasks from a queue with higher
|
||||||
|
// priority.
|
||||||
|
bool strict_priority = 6;
|
||||||
|
|
||||||
|
// Status indicates the status of the server.
|
||||||
|
string status = 7;
|
||||||
|
|
||||||
|
// Time this server was started.
|
||||||
|
google.protobuf.Timestamp start_time = 8;
|
||||||
|
|
||||||
|
// Number of workers currently processing tasks.
|
||||||
|
int32 active_worker_count = 9;
|
||||||
|
};
|
||||||
|
|
||||||
|
// WorkerInfo holds information about a running worker.
|
||||||
|
message WorkerInfo {
|
||||||
|
// Host matchine this worker is running on.
|
||||||
|
string host = 1;
|
||||||
|
|
||||||
|
// PID of the process in which this worker is running.
|
||||||
|
int32 pid = 2;
|
||||||
|
|
||||||
|
// ID of the server in which this worker is running.
|
||||||
|
string server_id = 3;
|
||||||
|
|
||||||
|
// ID of the task this worker is processing.
|
||||||
|
string task_id = 4;
|
||||||
|
|
||||||
|
// Type of the task this worker is processing.
|
||||||
|
string task_type = 5;
|
||||||
|
|
||||||
|
// Payload of the task this worker is processing.
|
||||||
|
bytes task_payload = 6;
|
||||||
|
|
||||||
|
// Name of the queue the task the worker is processing belongs.
|
||||||
|
string queue = 7;
|
||||||
|
|
||||||
|
// Time this worker started processing the task.
|
||||||
|
google.protobuf.Timestamp start_time = 8;
|
||||||
|
|
||||||
|
// Deadline by which the worker needs to complete processing
|
||||||
|
// the task. If worker exceeds the deadline, the task will fail.
|
||||||
|
google.protobuf.Timestamp deadline = 9;
|
||||||
|
};
|
||||||
|
|
||||||
|
// SchedulerEntry holds information about a periodic task registered
|
||||||
|
// with a scheduler.
|
||||||
|
message SchedulerEntry {
|
||||||
|
// Identifier of the scheduler entry.
|
||||||
|
string id = 1;
|
||||||
|
|
||||||
|
// Periodic schedule spec of the entry.
|
||||||
|
string spec = 2;
|
||||||
|
|
||||||
|
// Task type of the periodic task.
|
||||||
|
string task_type = 3;
|
||||||
|
|
||||||
|
// Task payload of the periodic task.
|
||||||
|
bytes task_payload = 4;
|
||||||
|
|
||||||
|
// Options used to enqueue the periodic task.
|
||||||
|
repeated string enqueue_options = 5;
|
||||||
|
|
||||||
|
// Next time the task will be enqueued.
|
||||||
|
google.protobuf.Timestamp next_enqueue_time = 6;
|
||||||
|
|
||||||
|
// Last time the task was enqueued.
|
||||||
|
// Zero time if task was never enqueued.
|
||||||
|
google.protobuf.Timestamp prev_enqueue_time = 7;
|
||||||
|
};
|
||||||
|
|
||||||
|
// SchedulerEnqueueEvent holds information about an enqueue event
|
||||||
|
// by a scheduler.
|
||||||
|
message SchedulerEnqueueEvent {
|
||||||
|
// ID of the task that was enqueued.
|
||||||
|
string task_id = 1;
|
||||||
|
|
||||||
|
// Time the task was enqueued.
|
||||||
|
google.protobuf.Timestamp enqueue_time = 2;
|
||||||
|
};
|
||||||
@@ -5,25 +5,27 @@
|
|||||||
package rdb
|
package rdb
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/hibiken/asynq/internal/asynqtest"
|
|
||||||
"github.com/hibiken/asynq/internal/base"
|
"github.com/hibiken/asynq/internal/base"
|
||||||
|
"github.com/hibiken/asynq/internal/testutil"
|
||||||
)
|
)
|
||||||
|
|
||||||
func BenchmarkEnqueue(b *testing.B) {
|
func BenchmarkEnqueue(b *testing.B) {
|
||||||
r := setup(b)
|
r := setup(b)
|
||||||
msg := asynqtest.NewTaskMessage("task1", nil)
|
ctx := context.Background()
|
||||||
|
msg := testutil.NewTaskMessage("task1", nil)
|
||||||
b.ResetTimer()
|
b.ResetTimer()
|
||||||
|
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
b.StopTimer()
|
b.StopTimer()
|
||||||
asynqtest.FlushDB(b, r.client)
|
testutil.FlushDB(b, r.client)
|
||||||
b.StartTimer()
|
b.StartTimer()
|
||||||
|
|
||||||
if err := r.Enqueue(msg); err != nil {
|
if err := r.Enqueue(ctx, msg); err != nil {
|
||||||
b.Fatalf("Enqueue failed: %v", err)
|
b.Fatalf("Enqueue failed: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -31,6 +33,7 @@ func BenchmarkEnqueue(b *testing.B) {
|
|||||||
|
|
||||||
func BenchmarkEnqueueUnique(b *testing.B) {
|
func BenchmarkEnqueueUnique(b *testing.B) {
|
||||||
r := setup(b)
|
r := setup(b)
|
||||||
|
ctx := context.Background()
|
||||||
msg := &base.TaskMessage{
|
msg := &base.TaskMessage{
|
||||||
Type: "task1",
|
Type: "task1",
|
||||||
Payload: nil,
|
Payload: nil,
|
||||||
@@ -42,10 +45,10 @@ func BenchmarkEnqueueUnique(b *testing.B) {
|
|||||||
|
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
b.StopTimer()
|
b.StopTimer()
|
||||||
asynqtest.FlushDB(b, r.client)
|
testutil.FlushDB(b, r.client)
|
||||||
b.StartTimer()
|
b.StartTimer()
|
||||||
|
|
||||||
if err := r.EnqueueUnique(msg, uniqueTTL); err != nil {
|
if err := r.EnqueueUnique(ctx, msg, uniqueTTL); err != nil {
|
||||||
b.Fatalf("EnqueueUnique failed: %v", err)
|
b.Fatalf("EnqueueUnique failed: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -53,16 +56,17 @@ func BenchmarkEnqueueUnique(b *testing.B) {
|
|||||||
|
|
||||||
func BenchmarkSchedule(b *testing.B) {
|
func BenchmarkSchedule(b *testing.B) {
|
||||||
r := setup(b)
|
r := setup(b)
|
||||||
msg := asynqtest.NewTaskMessage("task1", nil)
|
ctx := context.Background()
|
||||||
|
msg := testutil.NewTaskMessage("task1", nil)
|
||||||
processAt := time.Now().Add(3 * time.Minute)
|
processAt := time.Now().Add(3 * time.Minute)
|
||||||
b.ResetTimer()
|
b.ResetTimer()
|
||||||
|
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
b.StopTimer()
|
b.StopTimer()
|
||||||
asynqtest.FlushDB(b, r.client)
|
testutil.FlushDB(b, r.client)
|
||||||
b.StartTimer()
|
b.StartTimer()
|
||||||
|
|
||||||
if err := r.Schedule(msg, processAt); err != nil {
|
if err := r.Schedule(ctx, msg, processAt); err != nil {
|
||||||
b.Fatalf("Schedule failed: %v", err)
|
b.Fatalf("Schedule failed: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -70,6 +74,7 @@ func BenchmarkSchedule(b *testing.B) {
|
|||||||
|
|
||||||
func BenchmarkScheduleUnique(b *testing.B) {
|
func BenchmarkScheduleUnique(b *testing.B) {
|
||||||
r := setup(b)
|
r := setup(b)
|
||||||
|
ctx := context.Background()
|
||||||
msg := &base.TaskMessage{
|
msg := &base.TaskMessage{
|
||||||
Type: "task1",
|
Type: "task1",
|
||||||
Payload: nil,
|
Payload: nil,
|
||||||
@@ -82,10 +87,10 @@ func BenchmarkScheduleUnique(b *testing.B) {
|
|||||||
|
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
b.StopTimer()
|
b.StopTimer()
|
||||||
asynqtest.FlushDB(b, r.client)
|
testutil.FlushDB(b, r.client)
|
||||||
b.StartTimer()
|
b.StartTimer()
|
||||||
|
|
||||||
if err := r.ScheduleUnique(msg, processAt, uniqueTTL); err != nil {
|
if err := r.ScheduleUnique(ctx, msg, processAt, uniqueTTL); err != nil {
|
||||||
b.Fatalf("EnqueueUnique failed: %v", err)
|
b.Fatalf("EnqueueUnique failed: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -93,15 +98,16 @@ func BenchmarkScheduleUnique(b *testing.B) {
|
|||||||
|
|
||||||
func BenchmarkDequeueSingleQueue(b *testing.B) {
|
func BenchmarkDequeueSingleQueue(b *testing.B) {
|
||||||
r := setup(b)
|
r := setup(b)
|
||||||
|
ctx := context.Background()
|
||||||
b.ResetTimer()
|
b.ResetTimer()
|
||||||
|
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
b.StopTimer()
|
b.StopTimer()
|
||||||
asynqtest.FlushDB(b, r.client)
|
testutil.FlushDB(b, r.client)
|
||||||
for i := 0; i < 10; i++ {
|
for i := 0; i < 10; i++ {
|
||||||
m := asynqtest.NewTaskMessageWithQueue(
|
m := testutil.NewTaskMessageWithQueue(
|
||||||
fmt.Sprintf("task%d", i), nil, base.DefaultQueueName)
|
fmt.Sprintf("task%d", i), nil, base.DefaultQueueName)
|
||||||
if err := r.Enqueue(m); err != nil {
|
if err := r.Enqueue(ctx, m); err != nil {
|
||||||
b.Fatalf("Enqueue failed: %v", err)
|
b.Fatalf("Enqueue failed: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -116,16 +122,17 @@ func BenchmarkDequeueSingleQueue(b *testing.B) {
|
|||||||
func BenchmarkDequeueMultipleQueues(b *testing.B) {
|
func BenchmarkDequeueMultipleQueues(b *testing.B) {
|
||||||
qnames := []string{"critical", "default", "low"}
|
qnames := []string{"critical", "default", "low"}
|
||||||
r := setup(b)
|
r := setup(b)
|
||||||
|
ctx := context.Background()
|
||||||
b.ResetTimer()
|
b.ResetTimer()
|
||||||
|
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
b.StopTimer()
|
b.StopTimer()
|
||||||
asynqtest.FlushDB(b, r.client)
|
testutil.FlushDB(b, r.client)
|
||||||
for i := 0; i < 10; i++ {
|
for i := 0; i < 10; i++ {
|
||||||
for _, qname := range qnames {
|
for _, qname := range qnames {
|
||||||
m := asynqtest.NewTaskMessageWithQueue(
|
m := testutil.NewTaskMessageWithQueue(
|
||||||
fmt.Sprintf("%s_task%d", qname, i), nil, qname)
|
fmt.Sprintf("%s_task%d", qname, i), nil, qname)
|
||||||
if err := r.Enqueue(m); err != nil {
|
if err := r.Enqueue(ctx, m); err != nil {
|
||||||
b.Fatalf("Enqueue failed: %v", err)
|
b.Fatalf("Enqueue failed: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -140,25 +147,26 @@ func BenchmarkDequeueMultipleQueues(b *testing.B) {
|
|||||||
|
|
||||||
func BenchmarkDone(b *testing.B) {
|
func BenchmarkDone(b *testing.B) {
|
||||||
r := setup(b)
|
r := setup(b)
|
||||||
m1 := asynqtest.NewTaskMessage("task1", nil)
|
m1 := testutil.NewTaskMessage("task1", nil)
|
||||||
m2 := asynqtest.NewTaskMessage("task2", nil)
|
m2 := testutil.NewTaskMessage("task2", nil)
|
||||||
m3 := asynqtest.NewTaskMessage("task3", nil)
|
m3 := testutil.NewTaskMessage("task3", nil)
|
||||||
msgs := []*base.TaskMessage{m1, m2, m3}
|
msgs := []*base.TaskMessage{m1, m2, m3}
|
||||||
zs := []base.Z{
|
zs := []base.Z{
|
||||||
{Message: m1, Score: time.Now().Add(10 * time.Second).Unix()},
|
{Message: m1, Score: time.Now().Add(10 * time.Second).Unix()},
|
||||||
{Message: m2, Score: time.Now().Add(20 * time.Second).Unix()},
|
{Message: m2, Score: time.Now().Add(20 * time.Second).Unix()},
|
||||||
{Message: m3, Score: time.Now().Add(30 * time.Second).Unix()},
|
{Message: m3, Score: time.Now().Add(30 * time.Second).Unix()},
|
||||||
}
|
}
|
||||||
|
ctx := context.Background()
|
||||||
b.ResetTimer()
|
b.ResetTimer()
|
||||||
|
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
b.StopTimer()
|
b.StopTimer()
|
||||||
asynqtest.FlushDB(b, r.client)
|
testutil.FlushDB(b, r.client)
|
||||||
asynqtest.SeedActiveQueue(b, r.client, msgs, base.DefaultQueueName)
|
testutil.SeedActiveQueue(b, r.client, msgs, base.DefaultQueueName)
|
||||||
asynqtest.SeedDeadlines(b, r.client, zs, base.DefaultQueueName)
|
testutil.SeedLease(b, r.client, zs, base.DefaultQueueName)
|
||||||
b.StartTimer()
|
b.StartTimer()
|
||||||
|
|
||||||
if err := r.Done(msgs[0]); err != nil {
|
if err := r.Done(ctx, msgs[0]); err != nil {
|
||||||
b.Fatalf("Done failed: %v", err)
|
b.Fatalf("Done failed: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -166,25 +174,26 @@ func BenchmarkDone(b *testing.B) {
|
|||||||
|
|
||||||
func BenchmarkRetry(b *testing.B) {
|
func BenchmarkRetry(b *testing.B) {
|
||||||
r := setup(b)
|
r := setup(b)
|
||||||
m1 := asynqtest.NewTaskMessage("task1", nil)
|
m1 := testutil.NewTaskMessage("task1", nil)
|
||||||
m2 := asynqtest.NewTaskMessage("task2", nil)
|
m2 := testutil.NewTaskMessage("task2", nil)
|
||||||
m3 := asynqtest.NewTaskMessage("task3", nil)
|
m3 := testutil.NewTaskMessage("task3", nil)
|
||||||
msgs := []*base.TaskMessage{m1, m2, m3}
|
msgs := []*base.TaskMessage{m1, m2, m3}
|
||||||
zs := []base.Z{
|
zs := []base.Z{
|
||||||
{Message: m1, Score: time.Now().Add(10 * time.Second).Unix()},
|
{Message: m1, Score: time.Now().Add(10 * time.Second).Unix()},
|
||||||
{Message: m2, Score: time.Now().Add(20 * time.Second).Unix()},
|
{Message: m2, Score: time.Now().Add(20 * time.Second).Unix()},
|
||||||
{Message: m3, Score: time.Now().Add(30 * time.Second).Unix()},
|
{Message: m3, Score: time.Now().Add(30 * time.Second).Unix()},
|
||||||
}
|
}
|
||||||
|
ctx := context.Background()
|
||||||
b.ResetTimer()
|
b.ResetTimer()
|
||||||
|
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
b.StopTimer()
|
b.StopTimer()
|
||||||
asynqtest.FlushDB(b, r.client)
|
testutil.FlushDB(b, r.client)
|
||||||
asynqtest.SeedActiveQueue(b, r.client, msgs, base.DefaultQueueName)
|
testutil.SeedActiveQueue(b, r.client, msgs, base.DefaultQueueName)
|
||||||
asynqtest.SeedDeadlines(b, r.client, zs, base.DefaultQueueName)
|
testutil.SeedLease(b, r.client, zs, base.DefaultQueueName)
|
||||||
b.StartTimer()
|
b.StartTimer()
|
||||||
|
|
||||||
if err := r.Retry(msgs[0], time.Now().Add(1*time.Minute), "error"); err != nil {
|
if err := r.Retry(ctx, msgs[0], time.Now().Add(1*time.Minute), "error", true /*isFailure*/); err != nil {
|
||||||
b.Fatalf("Retry failed: %v", err)
|
b.Fatalf("Retry failed: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -192,25 +201,26 @@ func BenchmarkRetry(b *testing.B) {
|
|||||||
|
|
||||||
func BenchmarkArchive(b *testing.B) {
|
func BenchmarkArchive(b *testing.B) {
|
||||||
r := setup(b)
|
r := setup(b)
|
||||||
m1 := asynqtest.NewTaskMessage("task1", nil)
|
m1 := testutil.NewTaskMessage("task1", nil)
|
||||||
m2 := asynqtest.NewTaskMessage("task2", nil)
|
m2 := testutil.NewTaskMessage("task2", nil)
|
||||||
m3 := asynqtest.NewTaskMessage("task3", nil)
|
m3 := testutil.NewTaskMessage("task3", nil)
|
||||||
msgs := []*base.TaskMessage{m1, m2, m3}
|
msgs := []*base.TaskMessage{m1, m2, m3}
|
||||||
zs := []base.Z{
|
zs := []base.Z{
|
||||||
{Message: m1, Score: time.Now().Add(10 * time.Second).Unix()},
|
{Message: m1, Score: time.Now().Add(10 * time.Second).Unix()},
|
||||||
{Message: m2, Score: time.Now().Add(20 * time.Second).Unix()},
|
{Message: m2, Score: time.Now().Add(20 * time.Second).Unix()},
|
||||||
{Message: m3, Score: time.Now().Add(30 * time.Second).Unix()},
|
{Message: m3, Score: time.Now().Add(30 * time.Second).Unix()},
|
||||||
}
|
}
|
||||||
|
ctx := context.Background()
|
||||||
b.ResetTimer()
|
b.ResetTimer()
|
||||||
|
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
b.StopTimer()
|
b.StopTimer()
|
||||||
asynqtest.FlushDB(b, r.client)
|
testutil.FlushDB(b, r.client)
|
||||||
asynqtest.SeedActiveQueue(b, r.client, msgs, base.DefaultQueueName)
|
testutil.SeedActiveQueue(b, r.client, msgs, base.DefaultQueueName)
|
||||||
asynqtest.SeedDeadlines(b, r.client, zs, base.DefaultQueueName)
|
testutil.SeedLease(b, r.client, zs, base.DefaultQueueName)
|
||||||
b.StartTimer()
|
b.StartTimer()
|
||||||
|
|
||||||
if err := r.Archive(msgs[0], "error"); err != nil {
|
if err := r.Archive(ctx, msgs[0], "error"); err != nil {
|
||||||
b.Fatalf("Archive failed: %v", err)
|
b.Fatalf("Archive failed: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -218,25 +228,26 @@ func BenchmarkArchive(b *testing.B) {
|
|||||||
|
|
||||||
func BenchmarkRequeue(b *testing.B) {
|
func BenchmarkRequeue(b *testing.B) {
|
||||||
r := setup(b)
|
r := setup(b)
|
||||||
m1 := asynqtest.NewTaskMessage("task1", nil)
|
m1 := testutil.NewTaskMessage("task1", nil)
|
||||||
m2 := asynqtest.NewTaskMessage("task2", nil)
|
m2 := testutil.NewTaskMessage("task2", nil)
|
||||||
m3 := asynqtest.NewTaskMessage("task3", nil)
|
m3 := testutil.NewTaskMessage("task3", nil)
|
||||||
msgs := []*base.TaskMessage{m1, m2, m3}
|
msgs := []*base.TaskMessage{m1, m2, m3}
|
||||||
zs := []base.Z{
|
zs := []base.Z{
|
||||||
{Message: m1, Score: time.Now().Add(10 * time.Second).Unix()},
|
{Message: m1, Score: time.Now().Add(10 * time.Second).Unix()},
|
||||||
{Message: m2, Score: time.Now().Add(20 * time.Second).Unix()},
|
{Message: m2, Score: time.Now().Add(20 * time.Second).Unix()},
|
||||||
{Message: m3, Score: time.Now().Add(30 * time.Second).Unix()},
|
{Message: m3, Score: time.Now().Add(30 * time.Second).Unix()},
|
||||||
}
|
}
|
||||||
|
ctx := context.Background()
|
||||||
b.ResetTimer()
|
b.ResetTimer()
|
||||||
|
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
b.StopTimer()
|
b.StopTimer()
|
||||||
asynqtest.FlushDB(b, r.client)
|
testutil.FlushDB(b, r.client)
|
||||||
asynqtest.SeedActiveQueue(b, r.client, msgs, base.DefaultQueueName)
|
testutil.SeedActiveQueue(b, r.client, msgs, base.DefaultQueueName)
|
||||||
asynqtest.SeedDeadlines(b, r.client, zs, base.DefaultQueueName)
|
testutil.SeedLease(b, r.client, zs, base.DefaultQueueName)
|
||||||
b.StartTimer()
|
b.StartTimer()
|
||||||
|
|
||||||
if err := r.Requeue(msgs[0]); err != nil {
|
if err := r.Requeue(ctx, msgs[0]); err != nil {
|
||||||
b.Fatalf("Requeue failed: %v", err)
|
b.Fatalf("Requeue failed: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -247,7 +258,7 @@ func BenchmarkCheckAndEnqueue(b *testing.B) {
|
|||||||
now := time.Now()
|
now := time.Now()
|
||||||
var zs []base.Z
|
var zs []base.Z
|
||||||
for i := -100; i < 100; i++ {
|
for i := -100; i < 100; i++ {
|
||||||
msg := asynqtest.NewTaskMessage(fmt.Sprintf("task%d", i), nil)
|
msg := testutil.NewTaskMessage(fmt.Sprintf("task%d", i), nil)
|
||||||
score := now.Add(time.Duration(i) * time.Second).Unix()
|
score := now.Add(time.Duration(i) * time.Second).Unix()
|
||||||
zs = append(zs, base.Z{Message: msg, Score: score})
|
zs = append(zs, base.Z{Message: msg, Score: score})
|
||||||
}
|
}
|
||||||
@@ -255,12 +266,12 @@ func BenchmarkCheckAndEnqueue(b *testing.B) {
|
|||||||
|
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
b.StopTimer()
|
b.StopTimer()
|
||||||
asynqtest.FlushDB(b, r.client)
|
testutil.FlushDB(b, r.client)
|
||||||
asynqtest.SeedScheduledQueue(b, r.client, zs, base.DefaultQueueName)
|
testutil.SeedScheduledQueue(b, r.client, zs, base.DefaultQueueName)
|
||||||
b.StartTimer()
|
b.StartTimer()
|
||||||
|
|
||||||
if err := r.CheckAndEnqueue(base.DefaultQueueName); err != nil {
|
if err := r.ForwardIfReady(base.DefaultQueueName); err != nil {
|
||||||
b.Fatalf("CheckAndEnqueue failed: %v", err)
|
b.Fatalf("ForwardIfReady failed: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
1443
internal/rdb/rdb.go
1443
internal/rdb/rdb.go
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -6,15 +6,16 @@
|
|||||||
package testbroker
|
package testbroker
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/go-redis/redis/v7"
|
|
||||||
"github.com/hibiken/asynq/internal/base"
|
"github.com/hibiken/asynq/internal/base"
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
)
|
)
|
||||||
|
|
||||||
var errRedisDown = errors.New("asynqtest: redis is down")
|
var errRedisDown = errors.New("testutil: redis is down")
|
||||||
|
|
||||||
// TestBroker is a broker implementation which enables
|
// TestBroker is a broker implementation which enables
|
||||||
// to simulate Redis failure in tests.
|
// to simulate Redis failure in tests.
|
||||||
@@ -45,22 +46,22 @@ func (tb *TestBroker) Wakeup() {
|
|||||||
tb.sleeping = false
|
tb.sleeping = false
|
||||||
}
|
}
|
||||||
|
|
||||||
func (tb *TestBroker) Enqueue(msg *base.TaskMessage) error {
|
func (tb *TestBroker) Enqueue(ctx context.Context, msg *base.TaskMessage) error {
|
||||||
tb.mu.Lock()
|
tb.mu.Lock()
|
||||||
defer tb.mu.Unlock()
|
defer tb.mu.Unlock()
|
||||||
if tb.sleeping {
|
if tb.sleeping {
|
||||||
return errRedisDown
|
return errRedisDown
|
||||||
}
|
}
|
||||||
return tb.real.Enqueue(msg)
|
return tb.real.Enqueue(ctx, msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (tb *TestBroker) EnqueueUnique(msg *base.TaskMessage, ttl time.Duration) error {
|
func (tb *TestBroker) EnqueueUnique(ctx context.Context, msg *base.TaskMessage, ttl time.Duration) error {
|
||||||
tb.mu.Lock()
|
tb.mu.Lock()
|
||||||
defer tb.mu.Unlock()
|
defer tb.mu.Unlock()
|
||||||
if tb.sleeping {
|
if tb.sleeping {
|
||||||
return errRedisDown
|
return errRedisDown
|
||||||
}
|
}
|
||||||
return tb.real.EnqueueUnique(msg, ttl)
|
return tb.real.EnqueueUnique(ctx, msg, ttl)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (tb *TestBroker) Dequeue(qnames ...string) (*base.TaskMessage, time.Time, error) {
|
func (tb *TestBroker) Dequeue(qnames ...string) (*base.TaskMessage, time.Time, error) {
|
||||||
@@ -72,76 +73,103 @@ func (tb *TestBroker) Dequeue(qnames ...string) (*base.TaskMessage, time.Time, e
|
|||||||
return tb.real.Dequeue(qnames...)
|
return tb.real.Dequeue(qnames...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (tb *TestBroker) Done(msg *base.TaskMessage) error {
|
func (tb *TestBroker) Done(ctx context.Context, msg *base.TaskMessage) error {
|
||||||
tb.mu.Lock()
|
tb.mu.Lock()
|
||||||
defer tb.mu.Unlock()
|
defer tb.mu.Unlock()
|
||||||
if tb.sleeping {
|
if tb.sleeping {
|
||||||
return errRedisDown
|
return errRedisDown
|
||||||
}
|
}
|
||||||
return tb.real.Done(msg)
|
return tb.real.Done(ctx, msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (tb *TestBroker) Requeue(msg *base.TaskMessage) error {
|
func (tb *TestBroker) MarkAsComplete(ctx context.Context, msg *base.TaskMessage) error {
|
||||||
tb.mu.Lock()
|
tb.mu.Lock()
|
||||||
defer tb.mu.Unlock()
|
defer tb.mu.Unlock()
|
||||||
if tb.sleeping {
|
if tb.sleeping {
|
||||||
return errRedisDown
|
return errRedisDown
|
||||||
}
|
}
|
||||||
return tb.real.Requeue(msg)
|
return tb.real.MarkAsComplete(ctx, msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (tb *TestBroker) Schedule(msg *base.TaskMessage, processAt time.Time) error {
|
func (tb *TestBroker) Requeue(ctx context.Context, msg *base.TaskMessage) error {
|
||||||
tb.mu.Lock()
|
tb.mu.Lock()
|
||||||
defer tb.mu.Unlock()
|
defer tb.mu.Unlock()
|
||||||
if tb.sleeping {
|
if tb.sleeping {
|
||||||
return errRedisDown
|
return errRedisDown
|
||||||
}
|
}
|
||||||
return tb.real.Schedule(msg, processAt)
|
return tb.real.Requeue(ctx, msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (tb *TestBroker) ScheduleUnique(msg *base.TaskMessage, processAt time.Time, ttl time.Duration) error {
|
func (tb *TestBroker) Schedule(ctx context.Context, msg *base.TaskMessage, processAt time.Time) error {
|
||||||
tb.mu.Lock()
|
tb.mu.Lock()
|
||||||
defer tb.mu.Unlock()
|
defer tb.mu.Unlock()
|
||||||
if tb.sleeping {
|
if tb.sleeping {
|
||||||
return errRedisDown
|
return errRedisDown
|
||||||
}
|
}
|
||||||
return tb.real.ScheduleUnique(msg, processAt, ttl)
|
return tb.real.Schedule(ctx, msg, processAt)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (tb *TestBroker) Retry(msg *base.TaskMessage, processAt time.Time, errMsg string) error {
|
func (tb *TestBroker) ScheduleUnique(ctx context.Context, msg *base.TaskMessage, processAt time.Time, ttl time.Duration) error {
|
||||||
tb.mu.Lock()
|
tb.mu.Lock()
|
||||||
defer tb.mu.Unlock()
|
defer tb.mu.Unlock()
|
||||||
if tb.sleeping {
|
if tb.sleeping {
|
||||||
return errRedisDown
|
return errRedisDown
|
||||||
}
|
}
|
||||||
return tb.real.Retry(msg, processAt, errMsg)
|
return tb.real.ScheduleUnique(ctx, msg, processAt, ttl)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (tb *TestBroker) Archive(msg *base.TaskMessage, errMsg string) error {
|
func (tb *TestBroker) Retry(ctx context.Context, msg *base.TaskMessage, processAt time.Time, errMsg string, isFailure bool) error {
|
||||||
tb.mu.Lock()
|
tb.mu.Lock()
|
||||||
defer tb.mu.Unlock()
|
defer tb.mu.Unlock()
|
||||||
if tb.sleeping {
|
if tb.sleeping {
|
||||||
return errRedisDown
|
return errRedisDown
|
||||||
}
|
}
|
||||||
return tb.real.Archive(msg, errMsg)
|
return tb.real.Retry(ctx, msg, processAt, errMsg, isFailure)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (tb *TestBroker) CheckAndEnqueue(qnames ...string) error {
|
func (tb *TestBroker) Archive(ctx context.Context, msg *base.TaskMessage, errMsg string) error {
|
||||||
tb.mu.Lock()
|
tb.mu.Lock()
|
||||||
defer tb.mu.Unlock()
|
defer tb.mu.Unlock()
|
||||||
if tb.sleeping {
|
if tb.sleeping {
|
||||||
return errRedisDown
|
return errRedisDown
|
||||||
}
|
}
|
||||||
return tb.real.CheckAndEnqueue(qnames...)
|
return tb.real.Archive(ctx, msg, errMsg)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (tb *TestBroker) ListDeadlineExceeded(deadline time.Time, qnames ...string) ([]*base.TaskMessage, error) {
|
func (tb *TestBroker) ForwardIfReady(qnames ...string) error {
|
||||||
|
tb.mu.Lock()
|
||||||
|
defer tb.mu.Unlock()
|
||||||
|
if tb.sleeping {
|
||||||
|
return errRedisDown
|
||||||
|
}
|
||||||
|
return tb.real.ForwardIfReady(qnames...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tb *TestBroker) DeleteExpiredCompletedTasks(qname string, batchSize int) error {
|
||||||
|
tb.mu.Lock()
|
||||||
|
defer tb.mu.Unlock()
|
||||||
|
if tb.sleeping {
|
||||||
|
return errRedisDown
|
||||||
|
}
|
||||||
|
return tb.real.DeleteExpiredCompletedTasks(qname, batchSize)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tb *TestBroker) ListLeaseExpired(cutoff time.Time, qnames ...string) ([]*base.TaskMessage, error) {
|
||||||
tb.mu.Lock()
|
tb.mu.Lock()
|
||||||
defer tb.mu.Unlock()
|
defer tb.mu.Unlock()
|
||||||
if tb.sleeping {
|
if tb.sleeping {
|
||||||
return nil, errRedisDown
|
return nil, errRedisDown
|
||||||
}
|
}
|
||||||
return tb.real.ListDeadlineExceeded(deadline, qnames...)
|
return tb.real.ListLeaseExpired(cutoff, qnames...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tb *TestBroker) ExtendLease(qname string, ids ...string) (time.Time, error) {
|
||||||
|
tb.mu.Lock()
|
||||||
|
defer tb.mu.Unlock()
|
||||||
|
if tb.sleeping {
|
||||||
|
return time.Time{}, errRedisDown
|
||||||
|
}
|
||||||
|
return tb.real.ExtendLease(qname, ids...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (tb *TestBroker) WriteServerState(info *base.ServerInfo, workers []*base.WorkerInfo, ttl time.Duration) error {
|
func (tb *TestBroker) WriteServerState(info *base.ServerInfo, workers []*base.WorkerInfo, ttl time.Duration) error {
|
||||||
@@ -180,6 +208,15 @@ func (tb *TestBroker) PublishCancelation(id string) error {
|
|||||||
return tb.real.PublishCancelation(id)
|
return tb.real.PublishCancelation(id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (tb *TestBroker) WriteResult(qname, id string, data []byte) (int, error) {
|
||||||
|
tb.mu.Lock()
|
||||||
|
defer tb.mu.Unlock()
|
||||||
|
if tb.sleeping {
|
||||||
|
return 0, errRedisDown
|
||||||
|
}
|
||||||
|
return tb.real.WriteResult(qname, id, data)
|
||||||
|
}
|
||||||
|
|
||||||
func (tb *TestBroker) Ping() error {
|
func (tb *TestBroker) Ping() error {
|
||||||
tb.mu.Lock()
|
tb.mu.Lock()
|
||||||
defer tb.mu.Unlock()
|
defer tb.mu.Unlock()
|
||||||
@@ -197,3 +234,66 @@ func (tb *TestBroker) Close() error {
|
|||||||
}
|
}
|
||||||
return tb.real.Close()
|
return tb.real.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (tb *TestBroker) AddToGroup(ctx context.Context, msg *base.TaskMessage, gname string) error {
|
||||||
|
tb.mu.Lock()
|
||||||
|
defer tb.mu.Unlock()
|
||||||
|
if tb.sleeping {
|
||||||
|
return errRedisDown
|
||||||
|
}
|
||||||
|
return tb.real.AddToGroup(ctx, msg, gname)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tb *TestBroker) AddToGroupUnique(ctx context.Context, msg *base.TaskMessage, gname string, ttl time.Duration) error {
|
||||||
|
tb.mu.Lock()
|
||||||
|
defer tb.mu.Unlock()
|
||||||
|
if tb.sleeping {
|
||||||
|
return errRedisDown
|
||||||
|
}
|
||||||
|
return tb.real.AddToGroupUnique(ctx, msg, gname, ttl)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tb *TestBroker) ListGroups(qname string) ([]string, error) {
|
||||||
|
tb.mu.Lock()
|
||||||
|
defer tb.mu.Unlock()
|
||||||
|
if tb.sleeping {
|
||||||
|
return nil, errRedisDown
|
||||||
|
}
|
||||||
|
return tb.real.ListGroups(qname)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tb *TestBroker) AggregationCheck(qname, gname string, t time.Time, gracePeriod, maxDelay time.Duration, maxSize int) (aggregationSetID string, err error) {
|
||||||
|
tb.mu.Lock()
|
||||||
|
defer tb.mu.Unlock()
|
||||||
|
if tb.sleeping {
|
||||||
|
return "", errRedisDown
|
||||||
|
}
|
||||||
|
return tb.real.AggregationCheck(qname, gname, t, gracePeriod, maxDelay, maxSize)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tb *TestBroker) ReadAggregationSet(qname, gname, aggregationSetID string) ([]*base.TaskMessage, time.Time, error) {
|
||||||
|
tb.mu.Lock()
|
||||||
|
defer tb.mu.Unlock()
|
||||||
|
if tb.sleeping {
|
||||||
|
return nil, time.Time{}, errRedisDown
|
||||||
|
}
|
||||||
|
return tb.real.ReadAggregationSet(qname, gname, aggregationSetID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tb *TestBroker) DeleteAggregationSet(ctx context.Context, qname, gname, aggregationSetID string) error {
|
||||||
|
tb.mu.Lock()
|
||||||
|
defer tb.mu.Unlock()
|
||||||
|
if tb.sleeping {
|
||||||
|
return errRedisDown
|
||||||
|
}
|
||||||
|
return tb.real.DeleteAggregationSet(ctx, qname, gname, aggregationSetID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tb *TestBroker) ReclaimStaleAggregationSets(qname string) error {
|
||||||
|
tb.mu.Lock()
|
||||||
|
defer tb.mu.Unlock()
|
||||||
|
if tb.sleeping {
|
||||||
|
return errRedisDown
|
||||||
|
}
|
||||||
|
return tb.real.ReclaimStaleAggregationSets(qname)
|
||||||
|
}
|
||||||
|
|||||||
84
internal/testutil/builder.go
Normal file
84
internal/testutil/builder.go
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
// Copyright 2022 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package testutil
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/hibiken/asynq/internal/base"
|
||||||
|
)
|
||||||
|
|
||||||
|
func makeDefaultTaskMessage() *base.TaskMessage {
|
||||||
|
return &base.TaskMessage{
|
||||||
|
ID: uuid.NewString(),
|
||||||
|
Type: "default_task",
|
||||||
|
Queue: "default",
|
||||||
|
Retry: 25,
|
||||||
|
Timeout: 1800, // default timeout of 30 mins
|
||||||
|
Deadline: 0, // no deadline
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type TaskMessageBuilder struct {
|
||||||
|
msg *base.TaskMessage
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewTaskMessageBuilder() *TaskMessageBuilder {
|
||||||
|
return &TaskMessageBuilder{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *TaskMessageBuilder) lazyInit() {
|
||||||
|
if b.msg == nil {
|
||||||
|
b.msg = makeDefaultTaskMessage()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *TaskMessageBuilder) Build() *base.TaskMessage {
|
||||||
|
b.lazyInit()
|
||||||
|
return b.msg
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *TaskMessageBuilder) SetType(typename string) *TaskMessageBuilder {
|
||||||
|
b.lazyInit()
|
||||||
|
b.msg.Type = typename
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *TaskMessageBuilder) SetPayload(payload []byte) *TaskMessageBuilder {
|
||||||
|
b.lazyInit()
|
||||||
|
b.msg.Payload = payload
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *TaskMessageBuilder) SetQueue(qname string) *TaskMessageBuilder {
|
||||||
|
b.lazyInit()
|
||||||
|
b.msg.Queue = qname
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *TaskMessageBuilder) SetRetry(n int) *TaskMessageBuilder {
|
||||||
|
b.lazyInit()
|
||||||
|
b.msg.Retry = n
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *TaskMessageBuilder) SetTimeout(timeout time.Duration) *TaskMessageBuilder {
|
||||||
|
b.lazyInit()
|
||||||
|
b.msg.Timeout = int64(timeout.Seconds())
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *TaskMessageBuilder) SetDeadline(deadline time.Time) *TaskMessageBuilder {
|
||||||
|
b.lazyInit()
|
||||||
|
b.msg.Deadline = deadline.Unix()
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *TaskMessageBuilder) SetGroup(gname string) *TaskMessageBuilder {
|
||||||
|
b.lazyInit()
|
||||||
|
b.msg.GroupKey = gname
|
||||||
|
return b
|
||||||
|
}
|
||||||
94
internal/testutil/builder_test.go
Normal file
94
internal/testutil/builder_test.go
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
// Copyright 2022 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package testutil
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/go-cmp/cmp"
|
||||||
|
"github.com/google/go-cmp/cmp/cmpopts"
|
||||||
|
"github.com/hibiken/asynq/internal/base"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTaskMessageBuilder(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
desc string
|
||||||
|
ops func(b *TaskMessageBuilder) // operations to perform on the builder
|
||||||
|
want *base.TaskMessage
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
desc: "zero value and build",
|
||||||
|
ops: nil,
|
||||||
|
want: &base.TaskMessage{
|
||||||
|
Type: "default_task",
|
||||||
|
Queue: "default",
|
||||||
|
Payload: nil,
|
||||||
|
Retry: 25,
|
||||||
|
Timeout: 1800, // 30m
|
||||||
|
Deadline: 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "with type, payload, and queue",
|
||||||
|
ops: func(b *TaskMessageBuilder) {
|
||||||
|
b.SetType("foo").SetPayload([]byte("hello")).SetQueue("myqueue")
|
||||||
|
},
|
||||||
|
want: &base.TaskMessage{
|
||||||
|
Type: "foo",
|
||||||
|
Queue: "myqueue",
|
||||||
|
Payload: []byte("hello"),
|
||||||
|
Retry: 25,
|
||||||
|
Timeout: 1800, // 30m
|
||||||
|
Deadline: 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "with retry, timeout, and deadline",
|
||||||
|
ops: func(b *TaskMessageBuilder) {
|
||||||
|
b.SetRetry(1).
|
||||||
|
SetTimeout(20 * time.Second).
|
||||||
|
SetDeadline(time.Date(2017, 3, 6, 0, 0, 0, 0, time.UTC))
|
||||||
|
},
|
||||||
|
want: &base.TaskMessage{
|
||||||
|
Type: "default_task",
|
||||||
|
Queue: "default",
|
||||||
|
Payload: nil,
|
||||||
|
Retry: 1,
|
||||||
|
Timeout: 20,
|
||||||
|
Deadline: time.Date(2017, 3, 6, 0, 0, 0, 0, time.UTC).Unix(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "with group",
|
||||||
|
ops: func(b *TaskMessageBuilder) {
|
||||||
|
b.SetGroup("mygroup")
|
||||||
|
},
|
||||||
|
want: &base.TaskMessage{
|
||||||
|
Type: "default_task",
|
||||||
|
Queue: "default",
|
||||||
|
Payload: nil,
|
||||||
|
Retry: 25,
|
||||||
|
Timeout: 1800,
|
||||||
|
Deadline: 0,
|
||||||
|
GroupKey: "mygroup",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cmpOpts := []cmp.Option{cmpopts.IgnoreFields(base.TaskMessage{}, "ID")}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
var b TaskMessageBuilder
|
||||||
|
if tc.ops != nil {
|
||||||
|
tc.ops(&b)
|
||||||
|
}
|
||||||
|
|
||||||
|
got := b.Build()
|
||||||
|
if diff := cmp.Diff(tc.want, got, cmpOpts...); diff != "" {
|
||||||
|
t.Errorf("%s: TaskMessageBuilder.Build() = %+v, want %+v;\n(-want,+got)\n%s",
|
||||||
|
tc.desc, got, tc.want, diff)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
642
internal/testutil/testutil.go
Normal file
642
internal/testutil/testutil.go
Normal file
@@ -0,0 +1,642 @@
|
|||||||
|
// Copyright 2020 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// Package testutil defines test helpers for asynq and its internal packages.
|
||||||
|
package testutil
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"math"
|
||||||
|
"sort"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/go-cmp/cmp"
|
||||||
|
"github.com/google/go-cmp/cmp/cmpopts"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/hibiken/asynq/internal/base"
|
||||||
|
"github.com/hibiken/asynq/internal/timeutil"
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
)
|
||||||
|
|
||||||
|
// EquateInt64Approx returns a Comparer option that treats int64 values
|
||||||
|
// to be equal if they are within the given margin.
|
||||||
|
func EquateInt64Approx(margin int64) cmp.Option {
|
||||||
|
return cmp.Comparer(func(a, b int64) bool {
|
||||||
|
return math.Abs(float64(a-b)) <= float64(margin)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// SortMsgOpt is a cmp.Option to sort base.TaskMessage for comparing slice of task messages.
|
||||||
|
var SortMsgOpt = cmp.Transformer("SortTaskMessages", func(in []*base.TaskMessage) []*base.TaskMessage {
|
||||||
|
out := append([]*base.TaskMessage(nil), in...) // Copy input to avoid mutating it
|
||||||
|
sort.Slice(out, func(i, j int) bool {
|
||||||
|
return out[i].ID < out[j].ID
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
})
|
||||||
|
|
||||||
|
// SortZSetEntryOpt is an cmp.Option to sort ZSetEntry for comparing slice of zset entries.
|
||||||
|
var SortZSetEntryOpt = cmp.Transformer("SortZSetEntries", func(in []base.Z) []base.Z {
|
||||||
|
out := append([]base.Z(nil), in...) // Copy input to avoid mutating it
|
||||||
|
sort.Slice(out, func(i, j int) bool {
|
||||||
|
return out[i].Message.ID < out[j].Message.ID
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
})
|
||||||
|
|
||||||
|
// SortServerInfoOpt is a cmp.Option to sort base.ServerInfo for comparing slice of process info.
|
||||||
|
var SortServerInfoOpt = cmp.Transformer("SortServerInfo", func(in []*base.ServerInfo) []*base.ServerInfo {
|
||||||
|
out := append([]*base.ServerInfo(nil), in...) // Copy input to avoid mutating it
|
||||||
|
sort.Slice(out, func(i, j int) bool {
|
||||||
|
if out[i].Host != out[j].Host {
|
||||||
|
return out[i].Host < out[j].Host
|
||||||
|
}
|
||||||
|
return out[i].PID < out[j].PID
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
})
|
||||||
|
|
||||||
|
// SortWorkerInfoOpt is a cmp.Option to sort base.WorkerInfo for comparing slice of worker info.
|
||||||
|
var SortWorkerInfoOpt = cmp.Transformer("SortWorkerInfo", func(in []*base.WorkerInfo) []*base.WorkerInfo {
|
||||||
|
out := append([]*base.WorkerInfo(nil), in...) // Copy input to avoid mutating it
|
||||||
|
sort.Slice(out, func(i, j int) bool {
|
||||||
|
return out[i].ID < out[j].ID
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
})
|
||||||
|
|
||||||
|
// SortSchedulerEntryOpt is a cmp.Option to sort base.SchedulerEntry for comparing slice of entries.
|
||||||
|
var SortSchedulerEntryOpt = cmp.Transformer("SortSchedulerEntry", func(in []*base.SchedulerEntry) []*base.SchedulerEntry {
|
||||||
|
out := append([]*base.SchedulerEntry(nil), in...) // Copy input to avoid mutating it
|
||||||
|
sort.Slice(out, func(i, j int) bool {
|
||||||
|
return out[i].Spec < out[j].Spec
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
})
|
||||||
|
|
||||||
|
// SortSchedulerEnqueueEventOpt is a cmp.Option to sort base.SchedulerEnqueueEvent for comparing slice of events.
|
||||||
|
var SortSchedulerEnqueueEventOpt = cmp.Transformer("SortSchedulerEnqueueEvent", func(in []*base.SchedulerEnqueueEvent) []*base.SchedulerEnqueueEvent {
|
||||||
|
out := append([]*base.SchedulerEnqueueEvent(nil), in...)
|
||||||
|
sort.Slice(out, func(i, j int) bool {
|
||||||
|
return out[i].EnqueuedAt.Unix() < out[j].EnqueuedAt.Unix()
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
})
|
||||||
|
|
||||||
|
// SortStringSliceOpt is a cmp.Option to sort string slice.
|
||||||
|
var SortStringSliceOpt = cmp.Transformer("SortStringSlice", func(in []string) []string {
|
||||||
|
out := append([]string(nil), in...)
|
||||||
|
sort.Strings(out)
|
||||||
|
return out
|
||||||
|
})
|
||||||
|
|
||||||
|
var SortRedisZSetEntryOpt = cmp.Transformer("SortZSetEntries", func(in []redis.Z) []redis.Z {
|
||||||
|
out := append([]redis.Z(nil), in...) // Copy input to avoid mutating it
|
||||||
|
sort.Slice(out, func(i, j int) bool {
|
||||||
|
// TODO: If member is a comparable type (int, string, etc) compare by the member
|
||||||
|
// Use generic comparable type here once update to go1.18
|
||||||
|
if _, ok := out[i].Member.(string); ok {
|
||||||
|
// If member is a string, compare the member
|
||||||
|
return out[i].Member.(string) < out[j].Member.(string)
|
||||||
|
}
|
||||||
|
return out[i].Score < out[j].Score
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
})
|
||||||
|
|
||||||
|
// IgnoreIDOpt is an cmp.Option to ignore ID field in task messages when comparing.
|
||||||
|
var IgnoreIDOpt = cmpopts.IgnoreFields(base.TaskMessage{}, "ID")
|
||||||
|
|
||||||
|
// NewTaskMessage returns a new instance of TaskMessage given a task type and payload.
|
||||||
|
func NewTaskMessage(taskType string, payload []byte) *base.TaskMessage {
|
||||||
|
return NewTaskMessageWithQueue(taskType, payload, base.DefaultQueueName)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewTaskMessageWithQueue returns a new instance of TaskMessage given a
|
||||||
|
// task type, payload and queue name.
|
||||||
|
func NewTaskMessageWithQueue(taskType string, payload []byte, qname string) *base.TaskMessage {
|
||||||
|
return &base.TaskMessage{
|
||||||
|
ID: uuid.NewString(),
|
||||||
|
Type: taskType,
|
||||||
|
Queue: qname,
|
||||||
|
Retry: 25,
|
||||||
|
Payload: payload,
|
||||||
|
Timeout: 1800, // default timeout of 30 mins
|
||||||
|
Deadline: 0, // no deadline
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewLeaseWithClock returns a new lease with the given expiration time and clock.
|
||||||
|
func NewLeaseWithClock(expirationTime time.Time, clock timeutil.Clock) *base.Lease {
|
||||||
|
l := base.NewLease(expirationTime)
|
||||||
|
l.Clock = clock
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
|
||||||
|
// JSON serializes the given key-value pairs into stream of bytes in JSON.
|
||||||
|
func JSON(kv map[string]interface{}) []byte {
|
||||||
|
b, err := json.Marshal(kv)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
// TaskMessageAfterRetry returns an updated copy of t after retry.
|
||||||
|
// It increments retry count and sets the error message and last_failed_at time.
|
||||||
|
func TaskMessageAfterRetry(t base.TaskMessage, errMsg string, failedAt time.Time) *base.TaskMessage {
|
||||||
|
t.Retried = t.Retried + 1
|
||||||
|
t.ErrorMsg = errMsg
|
||||||
|
t.LastFailedAt = failedAt.Unix()
|
||||||
|
return &t
|
||||||
|
}
|
||||||
|
|
||||||
|
// TaskMessageWithError returns an updated copy of t with the given error message.
|
||||||
|
func TaskMessageWithError(t base.TaskMessage, errMsg string, failedAt time.Time) *base.TaskMessage {
|
||||||
|
t.ErrorMsg = errMsg
|
||||||
|
t.LastFailedAt = failedAt.Unix()
|
||||||
|
return &t
|
||||||
|
}
|
||||||
|
|
||||||
|
// TaskMessageWithCompletedAt returns an updated copy of t after completion.
|
||||||
|
func TaskMessageWithCompletedAt(t base.TaskMessage, completedAt time.Time) *base.TaskMessage {
|
||||||
|
t.CompletedAt = completedAt.Unix()
|
||||||
|
return &t
|
||||||
|
}
|
||||||
|
|
||||||
|
// MustMarshal marshals given task message and returns a json string.
|
||||||
|
// Calling test will fail if marshaling errors out.
|
||||||
|
func MustMarshal(tb testing.TB, msg *base.TaskMessage) string {
|
||||||
|
tb.Helper()
|
||||||
|
data, err := base.EncodeMessage(msg)
|
||||||
|
if err != nil {
|
||||||
|
tb.Fatal(err)
|
||||||
|
}
|
||||||
|
return string(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MustUnmarshal unmarshals given string into task message struct.
|
||||||
|
// Calling test will fail if unmarshaling errors out.
|
||||||
|
func MustUnmarshal(tb testing.TB, data string) *base.TaskMessage {
|
||||||
|
tb.Helper()
|
||||||
|
msg, err := base.DecodeMessage([]byte(data))
|
||||||
|
if err != nil {
|
||||||
|
tb.Fatal(err)
|
||||||
|
}
|
||||||
|
return msg
|
||||||
|
}
|
||||||
|
|
||||||
|
// FlushDB deletes all the keys of the currently selected DB.
|
||||||
|
func FlushDB(tb testing.TB, r redis.UniversalClient) {
|
||||||
|
tb.Helper()
|
||||||
|
switch r := r.(type) {
|
||||||
|
case *redis.Client:
|
||||||
|
if err := r.FlushDB(context.Background()).Err(); err != nil {
|
||||||
|
tb.Fatal(err)
|
||||||
|
}
|
||||||
|
case *redis.ClusterClient:
|
||||||
|
err := r.ForEachMaster(context.Background(), func(ctx context.Context, c *redis.Client) error {
|
||||||
|
if err := c.FlushAll(ctx).Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
tb.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SeedPendingQueue initializes the specified queue with the given messages.
|
||||||
|
func SeedPendingQueue(tb testing.TB, r redis.UniversalClient, msgs []*base.TaskMessage, qname string) {
|
||||||
|
tb.Helper()
|
||||||
|
r.SAdd(context.Background(), base.AllQueues, qname)
|
||||||
|
seedRedisList(tb, r, base.PendingKey(qname), msgs, base.TaskStatePending)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SeedActiveQueue initializes the active queue with the given messages.
|
||||||
|
func SeedActiveQueue(tb testing.TB, r redis.UniversalClient, msgs []*base.TaskMessage, qname string) {
|
||||||
|
tb.Helper()
|
||||||
|
r.SAdd(context.Background(), base.AllQueues, qname)
|
||||||
|
seedRedisList(tb, r, base.ActiveKey(qname), msgs, base.TaskStateActive)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SeedScheduledQueue initializes the scheduled queue with the given messages.
|
||||||
|
func SeedScheduledQueue(tb testing.TB, r redis.UniversalClient, entries []base.Z, qname string) {
|
||||||
|
tb.Helper()
|
||||||
|
r.SAdd(context.Background(), base.AllQueues, qname)
|
||||||
|
seedRedisZSet(tb, r, base.ScheduledKey(qname), entries, base.TaskStateScheduled)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SeedRetryQueue initializes the retry queue with the given messages.
|
||||||
|
func SeedRetryQueue(tb testing.TB, r redis.UniversalClient, entries []base.Z, qname string) {
|
||||||
|
tb.Helper()
|
||||||
|
r.SAdd(context.Background(), base.AllQueues, qname)
|
||||||
|
seedRedisZSet(tb, r, base.RetryKey(qname), entries, base.TaskStateRetry)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SeedArchivedQueue initializes the archived queue with the given messages.
|
||||||
|
func SeedArchivedQueue(tb testing.TB, r redis.UniversalClient, entries []base.Z, qname string) {
|
||||||
|
tb.Helper()
|
||||||
|
r.SAdd(context.Background(), base.AllQueues, qname)
|
||||||
|
seedRedisZSet(tb, r, base.ArchivedKey(qname), entries, base.TaskStateArchived)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SeedLease initializes the lease set with the given entries.
|
||||||
|
func SeedLease(tb testing.TB, r redis.UniversalClient, entries []base.Z, qname string) {
|
||||||
|
tb.Helper()
|
||||||
|
r.SAdd(context.Background(), base.AllQueues, qname)
|
||||||
|
seedRedisZSet(tb, r, base.LeaseKey(qname), entries, base.TaskStateActive)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SeedCompletedQueue initializes the completed set with the given entries.
|
||||||
|
func SeedCompletedQueue(tb testing.TB, r redis.UniversalClient, entries []base.Z, qname string) {
|
||||||
|
tb.Helper()
|
||||||
|
r.SAdd(context.Background(), base.AllQueues, qname)
|
||||||
|
seedRedisZSet(tb, r, base.CompletedKey(qname), entries, base.TaskStateCompleted)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SeedGroup initializes the group with the given entries.
|
||||||
|
func SeedGroup(tb testing.TB, r redis.UniversalClient, entries []base.Z, qname, gname string) {
|
||||||
|
tb.Helper()
|
||||||
|
ctx := context.Background()
|
||||||
|
r.SAdd(ctx, base.AllQueues, qname)
|
||||||
|
r.SAdd(ctx, base.AllGroups(qname), gname)
|
||||||
|
seedRedisZSet(tb, r, base.GroupKey(qname, gname), entries, base.TaskStateAggregating)
|
||||||
|
}
|
||||||
|
|
||||||
|
func SeedAggregationSet(tb testing.TB, r redis.UniversalClient, entries []base.Z, qname, gname, setID string) {
|
||||||
|
tb.Helper()
|
||||||
|
r.SAdd(context.Background(), base.AllQueues, qname)
|
||||||
|
seedRedisZSet(tb, r, base.AggregationSetKey(qname, gname, setID), entries, base.TaskStateAggregating)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SeedAllPendingQueues initializes all of the specified queues with the given messages.
|
||||||
|
//
|
||||||
|
// pending maps a queue name to a list of messages.
|
||||||
|
func SeedAllPendingQueues(tb testing.TB, r redis.UniversalClient, pending map[string][]*base.TaskMessage) {
|
||||||
|
tb.Helper()
|
||||||
|
for q, msgs := range pending {
|
||||||
|
SeedPendingQueue(tb, r, msgs, q)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SeedAllActiveQueues initializes all of the specified active queues with the given messages.
|
||||||
|
func SeedAllActiveQueues(tb testing.TB, r redis.UniversalClient, active map[string][]*base.TaskMessage) {
|
||||||
|
tb.Helper()
|
||||||
|
for q, msgs := range active {
|
||||||
|
SeedActiveQueue(tb, r, msgs, q)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SeedAllScheduledQueues initializes all of the specified scheduled queues with the given entries.
|
||||||
|
func SeedAllScheduledQueues(tb testing.TB, r redis.UniversalClient, scheduled map[string][]base.Z) {
|
||||||
|
tb.Helper()
|
||||||
|
for q, entries := range scheduled {
|
||||||
|
SeedScheduledQueue(tb, r, entries, q)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SeedAllRetryQueues initializes all of the specified retry queues with the given entries.
|
||||||
|
func SeedAllRetryQueues(tb testing.TB, r redis.UniversalClient, retry map[string][]base.Z) {
|
||||||
|
tb.Helper()
|
||||||
|
for q, entries := range retry {
|
||||||
|
SeedRetryQueue(tb, r, entries, q)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SeedAllArchivedQueues initializes all of the specified archived queues with the given entries.
|
||||||
|
func SeedAllArchivedQueues(tb testing.TB, r redis.UniversalClient, archived map[string][]base.Z) {
|
||||||
|
tb.Helper()
|
||||||
|
for q, entries := range archived {
|
||||||
|
SeedArchivedQueue(tb, r, entries, q)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SeedAllLease initializes all of the lease sets with the given entries.
|
||||||
|
func SeedAllLease(tb testing.TB, r redis.UniversalClient, lease map[string][]base.Z) {
|
||||||
|
tb.Helper()
|
||||||
|
for q, entries := range lease {
|
||||||
|
SeedLease(tb, r, entries, q)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SeedAllCompletedQueues initializes all of the completed queues with the given entries.
|
||||||
|
func SeedAllCompletedQueues(tb testing.TB, r redis.UniversalClient, completed map[string][]base.Z) {
|
||||||
|
tb.Helper()
|
||||||
|
for q, entries := range completed {
|
||||||
|
SeedCompletedQueue(tb, r, entries, q)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SeedAllGroups initializes all groups in all queues.
|
||||||
|
// The map maps queue names to group names which maps to a list of task messages and the time it was
|
||||||
|
// added to the group.
|
||||||
|
func SeedAllGroups(tb testing.TB, r redis.UniversalClient, groups map[string]map[string][]base.Z) {
|
||||||
|
tb.Helper()
|
||||||
|
for qname, g := range groups {
|
||||||
|
for gname, entries := range g {
|
||||||
|
SeedGroup(tb, r, entries, qname, gname)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func seedRedisList(tb testing.TB, c redis.UniversalClient, key string,
|
||||||
|
msgs []*base.TaskMessage, state base.TaskState) {
|
||||||
|
tb.Helper()
|
||||||
|
for _, msg := range msgs {
|
||||||
|
encoded := MustMarshal(tb, msg)
|
||||||
|
if err := c.LPush(context.Background(), key, msg.ID).Err(); err != nil {
|
||||||
|
tb.Fatal(err)
|
||||||
|
}
|
||||||
|
taskKey := base.TaskKey(msg.Queue, msg.ID)
|
||||||
|
data := map[string]interface{}{
|
||||||
|
"msg": encoded,
|
||||||
|
"state": state.String(),
|
||||||
|
"unique_key": msg.UniqueKey,
|
||||||
|
"group": msg.GroupKey,
|
||||||
|
}
|
||||||
|
if err := c.HSet(context.Background(), taskKey, data).Err(); err != nil {
|
||||||
|
tb.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(msg.UniqueKey) > 0 {
|
||||||
|
err := c.SetNX(context.Background(), msg.UniqueKey, msg.ID, 1*time.Minute).Err()
|
||||||
|
if err != nil {
|
||||||
|
tb.Fatalf("Failed to set unique lock in redis: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func seedRedisZSet(tb testing.TB, c redis.UniversalClient, key string,
|
||||||
|
items []base.Z, state base.TaskState) {
|
||||||
|
tb.Helper()
|
||||||
|
for _, item := range items {
|
||||||
|
msg := item.Message
|
||||||
|
encoded := MustMarshal(tb, msg)
|
||||||
|
z := redis.Z{Member: msg.ID, Score: float64(item.Score)}
|
||||||
|
if err := c.ZAdd(context.Background(), key, z).Err(); err != nil {
|
||||||
|
tb.Fatal(err)
|
||||||
|
}
|
||||||
|
taskKey := base.TaskKey(msg.Queue, msg.ID)
|
||||||
|
data := map[string]interface{}{
|
||||||
|
"msg": encoded,
|
||||||
|
"state": state.String(),
|
||||||
|
"unique_key": msg.UniqueKey,
|
||||||
|
"group": msg.GroupKey,
|
||||||
|
}
|
||||||
|
if err := c.HSet(context.Background(), taskKey, data).Err(); err != nil {
|
||||||
|
tb.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(msg.UniqueKey) > 0 {
|
||||||
|
err := c.SetNX(context.Background(), msg.UniqueKey, msg.ID, 1*time.Minute).Err()
|
||||||
|
if err != nil {
|
||||||
|
tb.Fatalf("Failed to set unique lock in redis: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetPendingMessages returns all pending messages in the given queue.
|
||||||
|
// It also asserts the state field of the task.
|
||||||
|
func GetPendingMessages(tb testing.TB, r redis.UniversalClient, qname string) []*base.TaskMessage {
|
||||||
|
tb.Helper()
|
||||||
|
return getMessagesFromList(tb, r, qname, base.PendingKey, base.TaskStatePending)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetActiveMessages returns all active messages in the given queue.
|
||||||
|
// It also asserts the state field of the task.
|
||||||
|
func GetActiveMessages(tb testing.TB, r redis.UniversalClient, qname string) []*base.TaskMessage {
|
||||||
|
tb.Helper()
|
||||||
|
return getMessagesFromList(tb, r, qname, base.ActiveKey, base.TaskStateActive)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetScheduledMessages returns all scheduled task messages in the given queue.
|
||||||
|
// It also asserts the state field of the task.
|
||||||
|
func GetScheduledMessages(tb testing.TB, r redis.UniversalClient, qname string) []*base.TaskMessage {
|
||||||
|
tb.Helper()
|
||||||
|
return getMessagesFromZSet(tb, r, qname, base.ScheduledKey, base.TaskStateScheduled)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetRetryMessages returns all retry messages in the given queue.
|
||||||
|
// It also asserts the state field of the task.
|
||||||
|
func GetRetryMessages(tb testing.TB, r redis.UniversalClient, qname string) []*base.TaskMessage {
|
||||||
|
tb.Helper()
|
||||||
|
return getMessagesFromZSet(tb, r, qname, base.RetryKey, base.TaskStateRetry)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetArchivedMessages returns all archived messages in the given queue.
|
||||||
|
// It also asserts the state field of the task.
|
||||||
|
func GetArchivedMessages(tb testing.TB, r redis.UniversalClient, qname string) []*base.TaskMessage {
|
||||||
|
tb.Helper()
|
||||||
|
return getMessagesFromZSet(tb, r, qname, base.ArchivedKey, base.TaskStateArchived)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetCompletedMessages returns all completed task messages in the given queue.
|
||||||
|
// It also asserts the state field of the task.
|
||||||
|
func GetCompletedMessages(tb testing.TB, r redis.UniversalClient, qname string) []*base.TaskMessage {
|
||||||
|
tb.Helper()
|
||||||
|
return getMessagesFromZSet(tb, r, qname, base.CompletedKey, base.TaskStateCompleted)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetScheduledEntries returns all scheduled messages and its score in the given queue.
|
||||||
|
// It also asserts the state field of the task.
|
||||||
|
func GetScheduledEntries(tb testing.TB, r redis.UniversalClient, qname string) []base.Z {
|
||||||
|
tb.Helper()
|
||||||
|
return getMessagesFromZSetWithScores(tb, r, qname, base.ScheduledKey, base.TaskStateScheduled)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetRetryEntries returns all retry messages and its score in the given queue.
|
||||||
|
// It also asserts the state field of the task.
|
||||||
|
func GetRetryEntries(tb testing.TB, r redis.UniversalClient, qname string) []base.Z {
|
||||||
|
tb.Helper()
|
||||||
|
return getMessagesFromZSetWithScores(tb, r, qname, base.RetryKey, base.TaskStateRetry)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetArchivedEntries returns all archived messages and its score in the given queue.
|
||||||
|
// It also asserts the state field of the task.
|
||||||
|
func GetArchivedEntries(tb testing.TB, r redis.UniversalClient, qname string) []base.Z {
|
||||||
|
tb.Helper()
|
||||||
|
return getMessagesFromZSetWithScores(tb, r, qname, base.ArchivedKey, base.TaskStateArchived)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetLeaseEntries returns all task IDs and its score in the lease set for the given queue.
|
||||||
|
// It also asserts the state field of the task.
|
||||||
|
func GetLeaseEntries(tb testing.TB, r redis.UniversalClient, qname string) []base.Z {
|
||||||
|
tb.Helper()
|
||||||
|
return getMessagesFromZSetWithScores(tb, r, qname, base.LeaseKey, base.TaskStateActive)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetCompletedEntries returns all completed messages and its score in the given queue.
|
||||||
|
// It also asserts the state field of the task.
|
||||||
|
func GetCompletedEntries(tb testing.TB, r redis.UniversalClient, qname string) []base.Z {
|
||||||
|
tb.Helper()
|
||||||
|
return getMessagesFromZSetWithScores(tb, r, qname, base.CompletedKey, base.TaskStateCompleted)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetGroupEntries returns all scheduled messages and its score in the given queue.
|
||||||
|
// It also asserts the state field of the task.
|
||||||
|
func GetGroupEntries(tb testing.TB, r redis.UniversalClient, qname, groupKey string) []base.Z {
|
||||||
|
tb.Helper()
|
||||||
|
return getMessagesFromZSetWithScores(tb, r, qname,
|
||||||
|
func(qname string) string { return base.GroupKey(qname, groupKey) }, base.TaskStateAggregating)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Retrieves all messages stored under `keyFn(qname)` key in redis list.
|
||||||
|
func getMessagesFromList(tb testing.TB, r redis.UniversalClient, qname string,
|
||||||
|
keyFn func(qname string) string, state base.TaskState) []*base.TaskMessage {
|
||||||
|
tb.Helper()
|
||||||
|
ids := r.LRange(context.Background(), keyFn(qname), 0, -1).Val()
|
||||||
|
var msgs []*base.TaskMessage
|
||||||
|
for _, id := range ids {
|
||||||
|
taskKey := base.TaskKey(qname, id)
|
||||||
|
data := r.HGet(context.Background(), taskKey, "msg").Val()
|
||||||
|
msgs = append(msgs, MustUnmarshal(tb, data))
|
||||||
|
if gotState := r.HGet(context.Background(), taskKey, "state").Val(); gotState != state.String() {
|
||||||
|
tb.Errorf("task (id=%q) is in %q state, want %v", id, gotState, state)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return msgs
|
||||||
|
}
|
||||||
|
|
||||||
|
// Retrieves all messages stored under `keyFn(qname)` key in redis zset (sorted-set).
|
||||||
|
func getMessagesFromZSet(tb testing.TB, r redis.UniversalClient, qname string,
|
||||||
|
keyFn func(qname string) string, state base.TaskState) []*base.TaskMessage {
|
||||||
|
tb.Helper()
|
||||||
|
ids := r.ZRange(context.Background(), keyFn(qname), 0, -1).Val()
|
||||||
|
var msgs []*base.TaskMessage
|
||||||
|
for _, id := range ids {
|
||||||
|
taskKey := base.TaskKey(qname, id)
|
||||||
|
msg := r.HGet(context.Background(), taskKey, "msg").Val()
|
||||||
|
msgs = append(msgs, MustUnmarshal(tb, msg))
|
||||||
|
if gotState := r.HGet(context.Background(), taskKey, "state").Val(); gotState != state.String() {
|
||||||
|
tb.Errorf("task (id=%q) is in %q state, want %v", id, gotState, state)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return msgs
|
||||||
|
}
|
||||||
|
|
||||||
|
// Retrieves all messages along with their scores stored under `keyFn(qname)` key in redis zset (sorted-set).
|
||||||
|
func getMessagesFromZSetWithScores(tb testing.TB, r redis.UniversalClient,
|
||||||
|
qname string, keyFn func(qname string) string, state base.TaskState) []base.Z {
|
||||||
|
tb.Helper()
|
||||||
|
zs := r.ZRangeWithScores(context.Background(), keyFn(qname), 0, -1).Val()
|
||||||
|
var res []base.Z
|
||||||
|
for _, z := range zs {
|
||||||
|
taskID := z.Member.(string)
|
||||||
|
taskKey := base.TaskKey(qname, taskID)
|
||||||
|
msg := r.HGet(context.Background(), taskKey, "msg").Val()
|
||||||
|
res = append(res, base.Z{Message: MustUnmarshal(tb, msg), Score: int64(z.Score)})
|
||||||
|
if gotState := r.HGet(context.Background(), taskKey, "state").Val(); gotState != state.String() {
|
||||||
|
tb.Errorf("task (id=%q) is in %q state, want %v", taskID, gotState, state)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
// TaskSeedData holds the data required to seed tasks under the task key in test.
|
||||||
|
type TaskSeedData struct {
|
||||||
|
Msg *base.TaskMessage
|
||||||
|
State base.TaskState
|
||||||
|
PendingSince time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func SeedTasks(tb testing.TB, r redis.UniversalClient, taskData []*TaskSeedData) {
|
||||||
|
for _, data := range taskData {
|
||||||
|
msg := data.Msg
|
||||||
|
ctx := context.Background()
|
||||||
|
key := base.TaskKey(msg.Queue, msg.ID)
|
||||||
|
v := map[string]interface{}{
|
||||||
|
"msg": MustMarshal(tb, msg),
|
||||||
|
"state": data.State.String(),
|
||||||
|
"unique_key": msg.UniqueKey,
|
||||||
|
"group": msg.GroupKey,
|
||||||
|
}
|
||||||
|
if !data.PendingSince.IsZero() {
|
||||||
|
v["pending_since"] = data.PendingSince.Unix()
|
||||||
|
}
|
||||||
|
if err := r.HSet(ctx, key, v).Err(); err != nil {
|
||||||
|
tb.Fatalf("Failed to write task data in redis: %v", err)
|
||||||
|
}
|
||||||
|
if len(msg.UniqueKey) > 0 {
|
||||||
|
err := r.SetNX(ctx, msg.UniqueKey, msg.ID, 1*time.Minute).Err()
|
||||||
|
if err != nil {
|
||||||
|
tb.Fatalf("Failed to set unique lock in redis: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func SeedRedisZSets(tb testing.TB, r redis.UniversalClient, zsets map[string][]redis.Z) {
|
||||||
|
for key, zs := range zsets {
|
||||||
|
// FIXME: How come we can't simply do ZAdd(ctx, key, zs...) here?
|
||||||
|
for _, z := range zs {
|
||||||
|
if err := r.ZAdd(context.Background(), key, z).Err(); err != nil {
|
||||||
|
tb.Fatalf("Failed to seed zset (key=%q): %v", key, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func SeedRedisSets(tb testing.TB, r redis.UniversalClient, sets map[string][]string) {
|
||||||
|
for key, set := range sets {
|
||||||
|
SeedRedisSet(tb, r, key, set)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func SeedRedisSet(tb testing.TB, r redis.UniversalClient, key string, members []string) {
|
||||||
|
for _, mem := range members {
|
||||||
|
if err := r.SAdd(context.Background(), key, mem).Err(); err != nil {
|
||||||
|
tb.Fatalf("Failed to seed set (key=%q): %v", key, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func SeedRedisLists(tb testing.TB, r redis.UniversalClient, lists map[string][]string) {
|
||||||
|
for key, vals := range lists {
|
||||||
|
for _, v := range vals {
|
||||||
|
if err := r.LPush(context.Background(), key, v).Err(); err != nil {
|
||||||
|
tb.Fatalf("Failed to seed list (key=%q): %v", key, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func AssertRedisLists(t *testing.T, r redis.UniversalClient, wantLists map[string][]string) {
|
||||||
|
for key, want := range wantLists {
|
||||||
|
got, err := r.LRange(context.Background(), key, 0, -1).Result()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Failed to read list (key=%q): %v", key, err)
|
||||||
|
}
|
||||||
|
if diff := cmp.Diff(want, got, SortStringSliceOpt); diff != "" {
|
||||||
|
t.Errorf("mismatch found in list (key=%q): (-want,+got)\n%s", key, diff)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func AssertRedisSets(t *testing.T, r redis.UniversalClient, wantSets map[string][]string) {
|
||||||
|
for key, want := range wantSets {
|
||||||
|
got, err := r.SMembers(context.Background(), key).Result()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Failed to read set (key=%q): %v", key, err)
|
||||||
|
}
|
||||||
|
if diff := cmp.Diff(want, got, SortStringSliceOpt); diff != "" {
|
||||||
|
t.Errorf("mismatch found in set (key=%q): (-want,+got)\n%s", key, diff)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func AssertRedisZSets(t *testing.T, r redis.UniversalClient, wantZSets map[string][]redis.Z) {
|
||||||
|
for key, want := range wantZSets {
|
||||||
|
got, err := r.ZRangeWithScores(context.Background(), key, 0, -1).Result()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Failed to read zset (key=%q): %v", key, err)
|
||||||
|
}
|
||||||
|
if diff := cmp.Diff(want, got, SortRedisZSetEntryOpt); diff != "" {
|
||||||
|
t.Errorf("mismatch found in zset (key=%q): (-want,+got)\n%s", key, diff)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
59
internal/timeutil/timeutil.go
Normal file
59
internal/timeutil/timeutil.go
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
// Copyright 2022 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// Package timeutil exports functions and types related to time and date.
|
||||||
|
package timeutil
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// A Clock is an object that can tell you the current time.
|
||||||
|
//
|
||||||
|
// This interface allows decoupling code that uses time from the code that creates
|
||||||
|
// a point in time. You can use this to your advantage by injecting Clocks into interfaces
|
||||||
|
// rather than having implementations call time.Now() directly.
|
||||||
|
//
|
||||||
|
// Use RealClock() in production.
|
||||||
|
// Use SimulatedClock() in test.
|
||||||
|
type Clock interface {
|
||||||
|
Now() time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRealClock() Clock { return &realTimeClock{} }
|
||||||
|
|
||||||
|
type realTimeClock struct{}
|
||||||
|
|
||||||
|
func (_ *realTimeClock) Now() time.Time { return time.Now() }
|
||||||
|
|
||||||
|
// A SimulatedClock is a concrete Clock implementation that doesn't "tick" on its own.
|
||||||
|
// Time is advanced by explicit call to the AdvanceTime() or SetTime() functions.
|
||||||
|
// This object is concurrency safe.
|
||||||
|
type SimulatedClock struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
t time.Time // guarded by mu
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSimulatedClock(t time.Time) *SimulatedClock {
|
||||||
|
return &SimulatedClock{t: t}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *SimulatedClock) Now() time.Time {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
return c.t
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *SimulatedClock) SetTime(t time.Time) {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
c.t = t
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *SimulatedClock) AdvanceTime(d time.Duration) {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
c.t = c.t.Add(d)
|
||||||
|
}
|
||||||
48
internal/timeutil/timeutil_test.go
Normal file
48
internal/timeutil/timeutil_test.go
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
// Copyright 2022 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package timeutil
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSimulatedClock(t *testing.T) {
|
||||||
|
now := time.Now()
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
desc string
|
||||||
|
initTime time.Time
|
||||||
|
advanceBy time.Duration
|
||||||
|
wantTime time.Time
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
desc: "advance time forward",
|
||||||
|
initTime: now,
|
||||||
|
advanceBy: 30 * time.Second,
|
||||||
|
wantTime: now.Add(30 * time.Second),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "advance time backward",
|
||||||
|
initTime: now,
|
||||||
|
advanceBy: -10 * time.Second,
|
||||||
|
wantTime: now.Add(-10 * time.Second),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
c := NewSimulatedClock(tc.initTime)
|
||||||
|
|
||||||
|
if c.Now() != tc.initTime {
|
||||||
|
t.Errorf("%s: Before Advance; SimulatedClock.Now() = %v, want %v", tc.desc, c.Now(), tc.initTime)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.AdvanceTime(tc.advanceBy)
|
||||||
|
|
||||||
|
if c.Now() != tc.wantTime {
|
||||||
|
t.Errorf("%s: After Advance; SimulatedClock.Now() = %v, want %v", tc.desc, c.Now(), tc.wantTime)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
86
janitor.go
Normal file
86
janitor.go
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
// Copyright 2021 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package asynq
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/hibiken/asynq/internal/base"
|
||||||
|
"github.com/hibiken/asynq/internal/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
// A janitor is responsible for deleting expired completed tasks from the specified
|
||||||
|
// queues. It periodically checks for any expired tasks in the completed set, and
|
||||||
|
// deletes them.
|
||||||
|
type janitor struct {
|
||||||
|
logger *log.Logger
|
||||||
|
broker base.Broker
|
||||||
|
|
||||||
|
// channel to communicate back to the long running "janitor" goroutine.
|
||||||
|
done chan struct{}
|
||||||
|
|
||||||
|
// list of queue names to check.
|
||||||
|
queues []string
|
||||||
|
|
||||||
|
// average interval between checks.
|
||||||
|
avgInterval time.Duration
|
||||||
|
|
||||||
|
// number of tasks to be deleted when janitor runs to delete the expired completed tasks.
|
||||||
|
batchSize int
|
||||||
|
}
|
||||||
|
|
||||||
|
type janitorParams struct {
|
||||||
|
logger *log.Logger
|
||||||
|
broker base.Broker
|
||||||
|
queues []string
|
||||||
|
interval time.Duration
|
||||||
|
batchSize int
|
||||||
|
}
|
||||||
|
|
||||||
|
func newJanitor(params janitorParams) *janitor {
|
||||||
|
return &janitor{
|
||||||
|
logger: params.logger,
|
||||||
|
broker: params.broker,
|
||||||
|
done: make(chan struct{}),
|
||||||
|
queues: params.queues,
|
||||||
|
avgInterval: params.interval,
|
||||||
|
batchSize: params.batchSize,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (j *janitor) shutdown() {
|
||||||
|
j.logger.Debug("Janitor shutting down...")
|
||||||
|
// Signal the janitor goroutine to stop.
|
||||||
|
j.done <- struct{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// start starts the "janitor" goroutine.
|
||||||
|
func (j *janitor) start(wg *sync.WaitGroup) {
|
||||||
|
wg.Add(1)
|
||||||
|
timer := time.NewTimer(j.avgInterval) // randomize this interval with margin of 1s
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-j.done:
|
||||||
|
j.logger.Debug("Janitor done")
|
||||||
|
return
|
||||||
|
case <-timer.C:
|
||||||
|
j.exec()
|
||||||
|
timer.Reset(j.avgInterval)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (j *janitor) exec() {
|
||||||
|
for _, qname := range j.queues {
|
||||||
|
if err := j.broker.DeleteExpiredCompletedTasks(qname, j.batchSize); err != nil {
|
||||||
|
j.logger.Errorf("Failed to delete expired completed tasks from queue %q: %v",
|
||||||
|
qname, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
91
janitor_test.go
Normal file
91
janitor_test.go
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
// Copyright 2021 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package asynq
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/go-cmp/cmp"
|
||||||
|
"github.com/hibiken/asynq/internal/base"
|
||||||
|
"github.com/hibiken/asynq/internal/rdb"
|
||||||
|
h "github.com/hibiken/asynq/internal/testutil"
|
||||||
|
)
|
||||||
|
|
||||||
|
func newCompletedTask(qname, tasktype string, payload []byte, completedAt time.Time) *base.TaskMessage {
|
||||||
|
msg := h.NewTaskMessageWithQueue(tasktype, payload, qname)
|
||||||
|
msg.CompletedAt = completedAt.Unix()
|
||||||
|
return msg
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestJanitor(t *testing.T) {
|
||||||
|
r := setup(t)
|
||||||
|
defer r.Close()
|
||||||
|
rdbClient := rdb.NewRDB(r)
|
||||||
|
const interval = 1 * time.Second
|
||||||
|
const batchSize = 100
|
||||||
|
janitor := newJanitor(janitorParams{
|
||||||
|
logger: testLogger,
|
||||||
|
broker: rdbClient,
|
||||||
|
queues: []string{"default", "custom"},
|
||||||
|
interval: interval,
|
||||||
|
batchSize: batchSize,
|
||||||
|
})
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
hourAgo := now.Add(-1 * time.Hour)
|
||||||
|
minuteAgo := now.Add(-1 * time.Minute)
|
||||||
|
halfHourAgo := now.Add(-30 * time.Minute)
|
||||||
|
halfHourFromNow := now.Add(30 * time.Minute)
|
||||||
|
fiveMinFromNow := now.Add(5 * time.Minute)
|
||||||
|
msg1 := newCompletedTask("default", "task1", nil, hourAgo)
|
||||||
|
msg2 := newCompletedTask("default", "task2", nil, minuteAgo)
|
||||||
|
msg3 := newCompletedTask("custom", "task3", nil, hourAgo)
|
||||||
|
msg4 := newCompletedTask("custom", "task4", nil, minuteAgo)
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
completed map[string][]base.Z // initial completed sets
|
||||||
|
wantCompleted map[string][]base.Z // expected completed sets after janitor runs
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
completed: map[string][]base.Z{
|
||||||
|
"default": {
|
||||||
|
{Message: msg1, Score: halfHourAgo.Unix()},
|
||||||
|
{Message: msg2, Score: fiveMinFromNow.Unix()},
|
||||||
|
},
|
||||||
|
"custom": {
|
||||||
|
{Message: msg3, Score: halfHourFromNow.Unix()},
|
||||||
|
{Message: msg4, Score: minuteAgo.Unix()},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
wantCompleted: map[string][]base.Z{
|
||||||
|
"default": {
|
||||||
|
{Message: msg2, Score: fiveMinFromNow.Unix()},
|
||||||
|
},
|
||||||
|
"custom": {
|
||||||
|
{Message: msg3, Score: halfHourFromNow.Unix()},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
h.FlushDB(t, r)
|
||||||
|
h.SeedAllCompletedQueues(t, r, tc.completed)
|
||||||
|
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
janitor.start(&wg)
|
||||||
|
time.Sleep(2 * interval) // make sure to let janitor run at least one time
|
||||||
|
janitor.shutdown()
|
||||||
|
|
||||||
|
for qname, want := range tc.wantCompleted {
|
||||||
|
got := h.GetCompletedEntries(t, r, qname)
|
||||||
|
if diff := cmp.Diff(want, got, h.SortZSetEntryOpt); diff != "" {
|
||||||
|
t.Errorf("diff found in %q after running janitor: (-want, +got)\n%s", base.CompletedKey(qname), diff)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
230
payload.go
230
payload.go
@@ -1,230 +0,0 @@
|
|||||||
// Copyright 2020 Kentaro Hibino. All rights reserved.
|
|
||||||
// Use of this source code is governed by a MIT license
|
|
||||||
// that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package asynq
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/spf13/cast"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Payload holds arbitrary data needed for task execution.
|
|
||||||
type Payload struct {
|
|
||||||
data map[string]interface{}
|
|
||||||
}
|
|
||||||
|
|
||||||
type errKeyNotFound struct {
|
|
||||||
key string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *errKeyNotFound) Error() string {
|
|
||||||
return fmt.Sprintf("key %q does not exist", e.key)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Has reports whether key exists.
|
|
||||||
func (p Payload) Has(key string) bool {
|
|
||||||
_, ok := p.data[key]
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
|
|
||||||
func toInt(v interface{}) (int, error) {
|
|
||||||
switch v := v.(type) {
|
|
||||||
case json.Number:
|
|
||||||
val, err := v.Int64()
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return int(val), nil
|
|
||||||
default:
|
|
||||||
return cast.ToIntE(v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// String returns a string representation of payload data.
|
|
||||||
func (p Payload) String() string {
|
|
||||||
return fmt.Sprint(p.data)
|
|
||||||
}
|
|
||||||
|
|
||||||
// MarshalJSON returns the JSON encoding of payload data.
|
|
||||||
func (p Payload) MarshalJSON() ([]byte, error) {
|
|
||||||
return json.Marshal(p.data)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetString returns a string value if a string type is associated with
|
|
||||||
// the key, otherwise reports an error.
|
|
||||||
func (p Payload) GetString(key string) (string, error) {
|
|
||||||
v, ok := p.data[key]
|
|
||||||
if !ok {
|
|
||||||
return "", &errKeyNotFound{key}
|
|
||||||
}
|
|
||||||
return cast.ToStringE(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetInt returns an int value if a numeric type is associated with
|
|
||||||
// the key, otherwise reports an error.
|
|
||||||
func (p Payload) GetInt(key string) (int, error) {
|
|
||||||
v, ok := p.data[key]
|
|
||||||
if !ok {
|
|
||||||
return 0, &errKeyNotFound{key}
|
|
||||||
}
|
|
||||||
return toInt(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetFloat64 returns a float64 value if a numeric type is associated with
|
|
||||||
// the key, otherwise reports an error.
|
|
||||||
func (p Payload) GetFloat64(key string) (float64, error) {
|
|
||||||
v, ok := p.data[key]
|
|
||||||
if !ok {
|
|
||||||
return 0, &errKeyNotFound{key}
|
|
||||||
}
|
|
||||||
switch v := v.(type) {
|
|
||||||
case json.Number:
|
|
||||||
return v.Float64()
|
|
||||||
default:
|
|
||||||
return cast.ToFloat64E(v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetBool returns a boolean value if a boolean type is associated with
|
|
||||||
// the key, otherwise reports an error.
|
|
||||||
func (p Payload) GetBool(key string) (bool, error) {
|
|
||||||
v, ok := p.data[key]
|
|
||||||
if !ok {
|
|
||||||
return false, &errKeyNotFound{key}
|
|
||||||
}
|
|
||||||
return cast.ToBoolE(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetStringSlice returns a slice of strings if a string slice type is associated with
|
|
||||||
// the key, otherwise reports an error.
|
|
||||||
func (p Payload) GetStringSlice(key string) ([]string, error) {
|
|
||||||
v, ok := p.data[key]
|
|
||||||
if !ok {
|
|
||||||
return nil, &errKeyNotFound{key}
|
|
||||||
}
|
|
||||||
return cast.ToStringSliceE(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIntSlice returns a slice of ints if a int slice type is associated with
|
|
||||||
// the key, otherwise reports an error.
|
|
||||||
func (p Payload) GetIntSlice(key string) ([]int, error) {
|
|
||||||
v, ok := p.data[key]
|
|
||||||
if !ok {
|
|
||||||
return nil, &errKeyNotFound{key}
|
|
||||||
}
|
|
||||||
switch v := v.(type) {
|
|
||||||
case []interface{}:
|
|
||||||
var res []int
|
|
||||||
for _, elem := range v {
|
|
||||||
val, err := toInt(elem)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
res = append(res, int(val))
|
|
||||||
}
|
|
||||||
return res, nil
|
|
||||||
default:
|
|
||||||
return cast.ToIntSliceE(v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetStringMap returns a map of string to empty interface
|
|
||||||
// if a correct map type is associated with the key,
|
|
||||||
// otherwise reports an error.
|
|
||||||
func (p Payload) GetStringMap(key string) (map[string]interface{}, error) {
|
|
||||||
v, ok := p.data[key]
|
|
||||||
if !ok {
|
|
||||||
return nil, &errKeyNotFound{key}
|
|
||||||
}
|
|
||||||
return cast.ToStringMapE(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetStringMapString returns a map of string to string
|
|
||||||
// if a correct map type is associated with the key,
|
|
||||||
// otherwise reports an error.
|
|
||||||
func (p Payload) GetStringMapString(key string) (map[string]string, error) {
|
|
||||||
v, ok := p.data[key]
|
|
||||||
if !ok {
|
|
||||||
return nil, &errKeyNotFound{key}
|
|
||||||
}
|
|
||||||
return cast.ToStringMapStringE(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetStringMapStringSlice returns a map of string to string slice
|
|
||||||
// if a correct map type is associated with the key,
|
|
||||||
// otherwise reports an error.
|
|
||||||
func (p Payload) GetStringMapStringSlice(key string) (map[string][]string, error) {
|
|
||||||
v, ok := p.data[key]
|
|
||||||
if !ok {
|
|
||||||
return nil, &errKeyNotFound{key}
|
|
||||||
}
|
|
||||||
return cast.ToStringMapStringSliceE(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetStringMapInt returns a map of string to int
|
|
||||||
// if a correct map type is associated with the key,
|
|
||||||
// otherwise reports an error.
|
|
||||||
func (p Payload) GetStringMapInt(key string) (map[string]int, error) {
|
|
||||||
v, ok := p.data[key]
|
|
||||||
if !ok {
|
|
||||||
return nil, &errKeyNotFound{key}
|
|
||||||
}
|
|
||||||
switch v := v.(type) {
|
|
||||||
case map[string]interface{}:
|
|
||||||
res := make(map[string]int)
|
|
||||||
for key, val := range v {
|
|
||||||
ival, err := toInt(val)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
res[key] = ival
|
|
||||||
}
|
|
||||||
return res, nil
|
|
||||||
default:
|
|
||||||
return cast.ToStringMapIntE(v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetStringMapBool returns a map of string to boolean
|
|
||||||
// if a correct map type is associated with the key,
|
|
||||||
// otherwise reports an error.
|
|
||||||
func (p Payload) GetStringMapBool(key string) (map[string]bool, error) {
|
|
||||||
v, ok := p.data[key]
|
|
||||||
if !ok {
|
|
||||||
return nil, &errKeyNotFound{key}
|
|
||||||
}
|
|
||||||
return cast.ToStringMapBoolE(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetTime returns a time value if a correct map type is associated with the key,
|
|
||||||
// otherwise reports an error.
|
|
||||||
func (p Payload) GetTime(key string) (time.Time, error) {
|
|
||||||
v, ok := p.data[key]
|
|
||||||
if !ok {
|
|
||||||
return time.Time{}, &errKeyNotFound{key}
|
|
||||||
}
|
|
||||||
return cast.ToTimeE(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetDuration returns a duration value if a correct map type is associated with the key,
|
|
||||||
// otherwise reports an error.
|
|
||||||
func (p Payload) GetDuration(key string) (time.Duration, error) {
|
|
||||||
v, ok := p.data[key]
|
|
||||||
if !ok {
|
|
||||||
return 0, &errKeyNotFound{key}
|
|
||||||
}
|
|
||||||
switch v := v.(type) {
|
|
||||||
case json.Number:
|
|
||||||
val, err := v.Int64()
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return time.Duration(val), nil
|
|
||||||
default:
|
|
||||||
return cast.ToDurationE(v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
675
payload_test.go
675
payload_test.go
@@ -1,675 +0,0 @@
|
|||||||
// Copyright 2020 Kentaro Hibino. All rights reserved.
|
|
||||||
// Use of this source code is governed by a MIT license
|
|
||||||
// that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package asynq
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/google/go-cmp/cmp"
|
|
||||||
"github.com/google/go-cmp/cmp/cmpopts"
|
|
||||||
h "github.com/hibiken/asynq/internal/asynqtest"
|
|
||||||
"github.com/hibiken/asynq/internal/base"
|
|
||||||
)
|
|
||||||
|
|
||||||
type payloadTest struct {
|
|
||||||
data map[string]interface{}
|
|
||||||
key string
|
|
||||||
nonkey string
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPayloadString(t *testing.T) {
|
|
||||||
tests := []payloadTest{
|
|
||||||
{
|
|
||||||
data: map[string]interface{}{"name": "gopher"},
|
|
||||||
key: "name",
|
|
||||||
nonkey: "unknown",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tc := range tests {
|
|
||||||
payload := Payload{tc.data}
|
|
||||||
|
|
||||||
got, err := payload.GetString(tc.key)
|
|
||||||
if err != nil || got != tc.data[tc.key] {
|
|
||||||
t.Errorf("Payload.GetString(%q) = %v, %v, want %v, nil",
|
|
||||||
tc.key, got, err, tc.data[tc.key])
|
|
||||||
}
|
|
||||||
|
|
||||||
// encode and then decode task messsage.
|
|
||||||
in := h.NewTaskMessage("testing", tc.data)
|
|
||||||
encoded, err := base.EncodeMessage(in)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
out, err := base.DecodeMessage(encoded)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
payload = Payload{out.Payload}
|
|
||||||
got, err = payload.GetString(tc.key)
|
|
||||||
if err != nil || got != tc.data[tc.key] {
|
|
||||||
t.Errorf("With Marshaling: Payload.GetString(%q) = %v, %v, want %v, nil",
|
|
||||||
tc.key, got, err, tc.data[tc.key])
|
|
||||||
}
|
|
||||||
|
|
||||||
// access non-existent key.
|
|
||||||
got, err = payload.GetString(tc.nonkey)
|
|
||||||
if err == nil || got != "" {
|
|
||||||
t.Errorf("Payload.GetString(%q) = %v, %v; want '', error",
|
|
||||||
tc.key, got, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPayloadInt(t *testing.T) {
|
|
||||||
tests := []payloadTest{
|
|
||||||
{
|
|
||||||
data: map[string]interface{}{"user_id": 42},
|
|
||||||
key: "user_id",
|
|
||||||
nonkey: "unknown",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tc := range tests {
|
|
||||||
payload := Payload{tc.data}
|
|
||||||
|
|
||||||
got, err := payload.GetInt(tc.key)
|
|
||||||
if err != nil || got != tc.data[tc.key] {
|
|
||||||
t.Errorf("Payload.GetInt(%q) = %v, %v, want %v, nil",
|
|
||||||
tc.key, got, err, tc.data[tc.key])
|
|
||||||
}
|
|
||||||
|
|
||||||
// encode and then decode task messsage.
|
|
||||||
in := h.NewTaskMessage("testing", tc.data)
|
|
||||||
encoded, err := base.EncodeMessage(in)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
out, err := base.DecodeMessage(encoded)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
payload = Payload{out.Payload}
|
|
||||||
got, err = payload.GetInt(tc.key)
|
|
||||||
if err != nil || got != tc.data[tc.key] {
|
|
||||||
t.Errorf("With Marshaling: Payload.GetInt(%q) = %v, %v, want %v, nil",
|
|
||||||
tc.key, got, err, tc.data[tc.key])
|
|
||||||
}
|
|
||||||
|
|
||||||
// access non-existent key.
|
|
||||||
got, err = payload.GetInt(tc.nonkey)
|
|
||||||
if err == nil || got != 0 {
|
|
||||||
t.Errorf("Payload.GetInt(%q) = %v, %v; want 0, error",
|
|
||||||
tc.key, got, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPayloadFloat64(t *testing.T) {
|
|
||||||
tests := []payloadTest{
|
|
||||||
{
|
|
||||||
data: map[string]interface{}{"pi": 3.14},
|
|
||||||
key: "pi",
|
|
||||||
nonkey: "unknown",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tc := range tests {
|
|
||||||
payload := Payload{tc.data}
|
|
||||||
|
|
||||||
got, err := payload.GetFloat64(tc.key)
|
|
||||||
if err != nil || got != tc.data[tc.key] {
|
|
||||||
t.Errorf("Payload.GetFloat64(%q) = %v, %v, want %v, nil",
|
|
||||||
tc.key, got, err, tc.data[tc.key])
|
|
||||||
}
|
|
||||||
|
|
||||||
// encode and then decode task messsage.
|
|
||||||
in := h.NewTaskMessage("testing", tc.data)
|
|
||||||
encoded, err := base.EncodeMessage(in)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
out, err := base.DecodeMessage(encoded)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
payload = Payload{out.Payload}
|
|
||||||
got, err = payload.GetFloat64(tc.key)
|
|
||||||
if err != nil || got != tc.data[tc.key] {
|
|
||||||
t.Errorf("With Marshaling: Payload.GetFloat64(%q) = %v, %v, want %v, nil",
|
|
||||||
tc.key, got, err, tc.data[tc.key])
|
|
||||||
}
|
|
||||||
|
|
||||||
// access non-existent key.
|
|
||||||
got, err = payload.GetFloat64(tc.nonkey)
|
|
||||||
if err == nil || got != 0 {
|
|
||||||
t.Errorf("Payload.GetFloat64(%q) = %v, %v; want 0, error",
|
|
||||||
tc.key, got, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPayloadBool(t *testing.T) {
|
|
||||||
tests := []payloadTest{
|
|
||||||
{
|
|
||||||
data: map[string]interface{}{"enabled": true},
|
|
||||||
key: "enabled",
|
|
||||||
nonkey: "unknown",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tc := range tests {
|
|
||||||
payload := Payload{tc.data}
|
|
||||||
|
|
||||||
got, err := payload.GetBool(tc.key)
|
|
||||||
if err != nil || got != tc.data[tc.key] {
|
|
||||||
t.Errorf("Payload.GetBool(%q) = %v, %v, want %v, nil",
|
|
||||||
tc.key, got, err, tc.data[tc.key])
|
|
||||||
}
|
|
||||||
|
|
||||||
// encode and then decode task messsage.
|
|
||||||
in := h.NewTaskMessage("testing", tc.data)
|
|
||||||
encoded, err := base.EncodeMessage(in)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
out, err := base.DecodeMessage(encoded)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
payload = Payload{out.Payload}
|
|
||||||
got, err = payload.GetBool(tc.key)
|
|
||||||
if err != nil || got != tc.data[tc.key] {
|
|
||||||
t.Errorf("With Marshaling: Payload.GetBool(%q) = %v, %v, want %v, nil",
|
|
||||||
tc.key, got, err, tc.data[tc.key])
|
|
||||||
}
|
|
||||||
|
|
||||||
// access non-existent key.
|
|
||||||
got, err = payload.GetBool(tc.nonkey)
|
|
||||||
if err == nil || got != false {
|
|
||||||
t.Errorf("Payload.GetBool(%q) = %v, %v; want false, error",
|
|
||||||
tc.key, got, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPayloadStringSlice(t *testing.T) {
|
|
||||||
tests := []payloadTest{
|
|
||||||
{
|
|
||||||
data: map[string]interface{}{"names": []string{"luke", "rey", "anakin"}},
|
|
||||||
key: "names",
|
|
||||||
nonkey: "unknown",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tc := range tests {
|
|
||||||
payload := Payload{tc.data}
|
|
||||||
|
|
||||||
got, err := payload.GetStringSlice(tc.key)
|
|
||||||
diff := cmp.Diff(got, tc.data[tc.key])
|
|
||||||
if err != nil || diff != "" {
|
|
||||||
t.Errorf("Payload.GetStringSlice(%q) = %v, %v, want %v, nil",
|
|
||||||
tc.key, got, err, tc.data[tc.key])
|
|
||||||
}
|
|
||||||
|
|
||||||
// encode and then decode task messsage.
|
|
||||||
in := h.NewTaskMessage("testing", tc.data)
|
|
||||||
encoded, err := base.EncodeMessage(in)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
out, err := base.DecodeMessage(encoded)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
payload = Payload{out.Payload}
|
|
||||||
got, err = payload.GetStringSlice(tc.key)
|
|
||||||
diff = cmp.Diff(got, tc.data[tc.key])
|
|
||||||
if err != nil || diff != "" {
|
|
||||||
t.Errorf("With Marshaling: Payload.GetStringSlice(%q) = %v, %v, want %v, nil",
|
|
||||||
tc.key, got, err, tc.data[tc.key])
|
|
||||||
}
|
|
||||||
|
|
||||||
// access non-existent key.
|
|
||||||
got, err = payload.GetStringSlice(tc.nonkey)
|
|
||||||
if err == nil || got != nil {
|
|
||||||
t.Errorf("Payload.GetStringSlice(%q) = %v, %v; want nil, error",
|
|
||||||
tc.key, got, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPayloadIntSlice(t *testing.T) {
|
|
||||||
tests := []payloadTest{
|
|
||||||
{
|
|
||||||
data: map[string]interface{}{"nums": []int{9, 8, 7}},
|
|
||||||
key: "nums",
|
|
||||||
nonkey: "unknown",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tc := range tests {
|
|
||||||
payload := Payload{tc.data}
|
|
||||||
|
|
||||||
got, err := payload.GetIntSlice(tc.key)
|
|
||||||
diff := cmp.Diff(got, tc.data[tc.key])
|
|
||||||
if err != nil || diff != "" {
|
|
||||||
t.Errorf("Payload.GetIntSlice(%q) = %v, %v, want %v, nil",
|
|
||||||
tc.key, got, err, tc.data[tc.key])
|
|
||||||
}
|
|
||||||
|
|
||||||
// encode and then decode task messsage.
|
|
||||||
in := h.NewTaskMessage("testing", tc.data)
|
|
||||||
encoded, err := base.EncodeMessage(in)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
out, err := base.DecodeMessage(encoded)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
payload = Payload{out.Payload}
|
|
||||||
got, err = payload.GetIntSlice(tc.key)
|
|
||||||
diff = cmp.Diff(got, tc.data[tc.key])
|
|
||||||
if err != nil || diff != "" {
|
|
||||||
t.Errorf("With Marshaling: Payload.GetIntSlice(%q) = %v, %v, want %v, nil",
|
|
||||||
tc.key, got, err, tc.data[tc.key])
|
|
||||||
}
|
|
||||||
|
|
||||||
// access non-existent key.
|
|
||||||
got, err = payload.GetIntSlice(tc.nonkey)
|
|
||||||
if err == nil || got != nil {
|
|
||||||
t.Errorf("Payload.GetIntSlice(%q) = %v, %v; want nil, error",
|
|
||||||
tc.key, got, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPayloadStringMap(t *testing.T) {
|
|
||||||
tests := []payloadTest{
|
|
||||||
{
|
|
||||||
data: map[string]interface{}{"user": map[string]interface{}{"name": "Jon Doe", "score": 2.2}},
|
|
||||||
key: "user",
|
|
||||||
nonkey: "unknown",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tc := range tests {
|
|
||||||
payload := Payload{tc.data}
|
|
||||||
|
|
||||||
got, err := payload.GetStringMap(tc.key)
|
|
||||||
diff := cmp.Diff(got, tc.data[tc.key])
|
|
||||||
if err != nil || diff != "" {
|
|
||||||
t.Errorf("Payload.GetStringMap(%q) = %v, %v, want %v, nil",
|
|
||||||
tc.key, got, err, tc.data[tc.key])
|
|
||||||
}
|
|
||||||
|
|
||||||
// encode and then decode task messsage.
|
|
||||||
in := h.NewTaskMessage("testing", tc.data)
|
|
||||||
encoded, err := base.EncodeMessage(in)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
out, err := base.DecodeMessage(encoded)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
payload = Payload{out.Payload}
|
|
||||||
got, err = payload.GetStringMap(tc.key)
|
|
||||||
ignoreOpt := cmpopts.IgnoreMapEntries(func(key string, val interface{}) bool {
|
|
||||||
switch val.(type) {
|
|
||||||
case json.Number:
|
|
||||||
return true
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
})
|
|
||||||
diff = cmp.Diff(got, tc.data[tc.key], ignoreOpt)
|
|
||||||
if err != nil || diff != "" {
|
|
||||||
t.Errorf("With Marshaling: Payload.GetStringMap(%q) = %v, %v, want %v, nil;(-want,+got)\n%s",
|
|
||||||
tc.key, got, err, tc.data[tc.key], diff)
|
|
||||||
}
|
|
||||||
|
|
||||||
// access non-existent key.
|
|
||||||
got, err = payload.GetStringMap(tc.nonkey)
|
|
||||||
if err == nil || got != nil {
|
|
||||||
t.Errorf("Payload.GetStringMap(%q) = %v, %v; want nil, error",
|
|
||||||
tc.key, got, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPayloadStringMapString(t *testing.T) {
|
|
||||||
tests := []payloadTest{
|
|
||||||
{
|
|
||||||
data: map[string]interface{}{"address": map[string]string{"line": "123 Main St", "city": "San Francisco", "state": "CA"}},
|
|
||||||
key: "address",
|
|
||||||
nonkey: "unknown",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tc := range tests {
|
|
||||||
payload := Payload{tc.data}
|
|
||||||
|
|
||||||
got, err := payload.GetStringMapString(tc.key)
|
|
||||||
diff := cmp.Diff(got, tc.data[tc.key])
|
|
||||||
if err != nil || diff != "" {
|
|
||||||
t.Errorf("Payload.GetStringMapString(%q) = %v, %v, want %v, nil",
|
|
||||||
tc.key, got, err, tc.data[tc.key])
|
|
||||||
}
|
|
||||||
|
|
||||||
// encode and then decode task messsage.
|
|
||||||
in := h.NewTaskMessage("testing", tc.data)
|
|
||||||
encoded, err := base.EncodeMessage(in)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
out, err := base.DecodeMessage(encoded)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
payload = Payload{out.Payload}
|
|
||||||
got, err = payload.GetStringMapString(tc.key)
|
|
||||||
diff = cmp.Diff(got, tc.data[tc.key])
|
|
||||||
if err != nil || diff != "" {
|
|
||||||
t.Errorf("With Marshaling: Payload.GetStringMapString(%q) = %v, %v, want %v, nil",
|
|
||||||
tc.key, got, err, tc.data[tc.key])
|
|
||||||
}
|
|
||||||
|
|
||||||
// access non-existent key.
|
|
||||||
got, err = payload.GetStringMapString(tc.nonkey)
|
|
||||||
if err == nil || got != nil {
|
|
||||||
t.Errorf("Payload.GetStringMapString(%q) = %v, %v; want nil, error",
|
|
||||||
tc.key, got, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPayloadStringMapStringSlice(t *testing.T) {
|
|
||||||
favs := map[string][]string{
|
|
||||||
"movies": {"forrest gump", "star wars"},
|
|
||||||
"tv_shows": {"game of thrones", "HIMYM", "breaking bad"},
|
|
||||||
}
|
|
||||||
tests := []payloadTest{
|
|
||||||
{
|
|
||||||
data: map[string]interface{}{"favorites": favs},
|
|
||||||
key: "favorites",
|
|
||||||
nonkey: "unknown",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tc := range tests {
|
|
||||||
payload := Payload{tc.data}
|
|
||||||
|
|
||||||
got, err := payload.GetStringMapStringSlice(tc.key)
|
|
||||||
diff := cmp.Diff(got, tc.data[tc.key])
|
|
||||||
if err != nil || diff != "" {
|
|
||||||
t.Errorf("Payload.GetStringMapStringSlice(%q) = %v, %v, want %v, nil",
|
|
||||||
tc.key, got, err, tc.data[tc.key])
|
|
||||||
}
|
|
||||||
|
|
||||||
// encode and then decode task messsage.
|
|
||||||
in := h.NewTaskMessage("testing", tc.data)
|
|
||||||
encoded, err := base.EncodeMessage(in)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
out, err := base.DecodeMessage(encoded)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
payload = Payload{out.Payload}
|
|
||||||
got, err = payload.GetStringMapStringSlice(tc.key)
|
|
||||||
diff = cmp.Diff(got, tc.data[tc.key])
|
|
||||||
if err != nil || diff != "" {
|
|
||||||
t.Errorf("With Marshaling: Payload.GetStringMapStringSlice(%q) = %v, %v, want %v, nil",
|
|
||||||
tc.key, got, err, tc.data[tc.key])
|
|
||||||
}
|
|
||||||
|
|
||||||
// access non-existent key.
|
|
||||||
got, err = payload.GetStringMapStringSlice(tc.nonkey)
|
|
||||||
if err == nil || got != nil {
|
|
||||||
t.Errorf("Payload.GetStringMapStringSlice(%q) = %v, %v; want nil, error",
|
|
||||||
tc.key, got, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPayloadStringMapInt(t *testing.T) {
|
|
||||||
counter := map[string]int{
|
|
||||||
"a": 1,
|
|
||||||
"b": 101,
|
|
||||||
"c": 42,
|
|
||||||
}
|
|
||||||
tests := []payloadTest{
|
|
||||||
{
|
|
||||||
data: map[string]interface{}{"counts": counter},
|
|
||||||
key: "counts",
|
|
||||||
nonkey: "unknown",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tc := range tests {
|
|
||||||
payload := Payload{tc.data}
|
|
||||||
|
|
||||||
got, err := payload.GetStringMapInt(tc.key)
|
|
||||||
diff := cmp.Diff(got, tc.data[tc.key])
|
|
||||||
if err != nil || diff != "" {
|
|
||||||
t.Errorf("Payload.GetStringMapInt(%q) = %v, %v, want %v, nil",
|
|
||||||
tc.key, got, err, tc.data[tc.key])
|
|
||||||
}
|
|
||||||
|
|
||||||
// encode and then decode task messsage.
|
|
||||||
in := h.NewTaskMessage("testing", tc.data)
|
|
||||||
encoded, err := base.EncodeMessage(in)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
out, err := base.DecodeMessage(encoded)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
payload = Payload{out.Payload}
|
|
||||||
got, err = payload.GetStringMapInt(tc.key)
|
|
||||||
diff = cmp.Diff(got, tc.data[tc.key])
|
|
||||||
if err != nil || diff != "" {
|
|
||||||
t.Errorf("With Marshaling: Payload.GetStringMapInt(%q) = %v, %v, want %v, nil",
|
|
||||||
tc.key, got, err, tc.data[tc.key])
|
|
||||||
}
|
|
||||||
|
|
||||||
// access non-existent key.
|
|
||||||
got, err = payload.GetStringMapInt(tc.nonkey)
|
|
||||||
if err == nil || got != nil {
|
|
||||||
t.Errorf("Payload.GetStringMapInt(%q) = %v, %v; want nil, error",
|
|
||||||
tc.key, got, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPayloadStringMapBool(t *testing.T) {
|
|
||||||
features := map[string]bool{
|
|
||||||
"A": false,
|
|
||||||
"B": true,
|
|
||||||
"C": true,
|
|
||||||
}
|
|
||||||
tests := []payloadTest{
|
|
||||||
{
|
|
||||||
data: map[string]interface{}{"features": features},
|
|
||||||
key: "features",
|
|
||||||
nonkey: "unknown",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tc := range tests {
|
|
||||||
payload := Payload{tc.data}
|
|
||||||
|
|
||||||
got, err := payload.GetStringMapBool(tc.key)
|
|
||||||
diff := cmp.Diff(got, tc.data[tc.key])
|
|
||||||
if err != nil || diff != "" {
|
|
||||||
t.Errorf("Payload.GetStringMapBool(%q) = %v, %v, want %v, nil",
|
|
||||||
tc.key, got, err, tc.data[tc.key])
|
|
||||||
}
|
|
||||||
|
|
||||||
// encode and then decode task messsage.
|
|
||||||
in := h.NewTaskMessage("testing", tc.data)
|
|
||||||
encoded, err := base.EncodeMessage(in)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
out, err := base.DecodeMessage(encoded)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
payload = Payload{out.Payload}
|
|
||||||
got, err = payload.GetStringMapBool(tc.key)
|
|
||||||
diff = cmp.Diff(got, tc.data[tc.key])
|
|
||||||
if err != nil || diff != "" {
|
|
||||||
t.Errorf("With Marshaling: Payload.GetStringMapBool(%q) = %v, %v, want %v, nil",
|
|
||||||
tc.key, got, err, tc.data[tc.key])
|
|
||||||
}
|
|
||||||
|
|
||||||
// access non-existent key.
|
|
||||||
got, err = payload.GetStringMapBool(tc.nonkey)
|
|
||||||
if err == nil || got != nil {
|
|
||||||
t.Errorf("Payload.GetStringMapBool(%q) = %v, %v; want nil, error",
|
|
||||||
tc.key, got, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPayloadTime(t *testing.T) {
|
|
||||||
tests := []payloadTest{
|
|
||||||
{
|
|
||||||
data: map[string]interface{}{"current": time.Now()},
|
|
||||||
key: "current",
|
|
||||||
nonkey: "unknown",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tc := range tests {
|
|
||||||
payload := Payload{tc.data}
|
|
||||||
|
|
||||||
got, err := payload.GetTime(tc.key)
|
|
||||||
diff := cmp.Diff(got, tc.data[tc.key])
|
|
||||||
if err != nil || diff != "" {
|
|
||||||
t.Errorf("Payload.GetTime(%q) = %v, %v, want %v, nil",
|
|
||||||
tc.key, got, err, tc.data[tc.key])
|
|
||||||
}
|
|
||||||
|
|
||||||
// encode and then decode task messsage.
|
|
||||||
in := h.NewTaskMessage("testing", tc.data)
|
|
||||||
encoded, err := base.EncodeMessage(in)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
out, err := base.DecodeMessage(encoded)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
payload = Payload{out.Payload}
|
|
||||||
got, err = payload.GetTime(tc.key)
|
|
||||||
diff = cmp.Diff(got, tc.data[tc.key])
|
|
||||||
if err != nil || diff != "" {
|
|
||||||
t.Errorf("With Marshaling: Payload.GetTime(%q) = %v, %v, want %v, nil",
|
|
||||||
tc.key, got, err, tc.data[tc.key])
|
|
||||||
}
|
|
||||||
|
|
||||||
// access non-existent key.
|
|
||||||
got, err = payload.GetTime(tc.nonkey)
|
|
||||||
if err == nil || !got.IsZero() {
|
|
||||||
t.Errorf("Payload.GetTime(%q) = %v, %v; want %v, error",
|
|
||||||
tc.key, got, err, time.Time{})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPayloadDuration(t *testing.T) {
|
|
||||||
tests := []payloadTest{
|
|
||||||
{
|
|
||||||
data: map[string]interface{}{"duration": 15 * time.Minute},
|
|
||||||
key: "duration",
|
|
||||||
nonkey: "unknown",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tc := range tests {
|
|
||||||
payload := Payload{tc.data}
|
|
||||||
|
|
||||||
got, err := payload.GetDuration(tc.key)
|
|
||||||
diff := cmp.Diff(got, tc.data[tc.key])
|
|
||||||
if err != nil || diff != "" {
|
|
||||||
t.Errorf("Payload.GetDuration(%q) = %v, %v, want %v, nil",
|
|
||||||
tc.key, got, err, tc.data[tc.key])
|
|
||||||
}
|
|
||||||
|
|
||||||
// encode and then decode task messsage.
|
|
||||||
in := h.NewTaskMessage("testing", tc.data)
|
|
||||||
encoded, err := base.EncodeMessage(in)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
out, err := base.DecodeMessage(encoded)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
payload = Payload{out.Payload}
|
|
||||||
got, err = payload.GetDuration(tc.key)
|
|
||||||
diff = cmp.Diff(got, tc.data[tc.key])
|
|
||||||
if err != nil || diff != "" {
|
|
||||||
t.Errorf("With Marshaling: Payload.GetDuration(%q) = %v, %v, want %v, nil",
|
|
||||||
tc.key, got, err, tc.data[tc.key])
|
|
||||||
}
|
|
||||||
|
|
||||||
// access non-existent key.
|
|
||||||
got, err = payload.GetDuration(tc.nonkey)
|
|
||||||
if err == nil || got != 0 {
|
|
||||||
t.Errorf("Payload.GetDuration(%q) = %v, %v; want %v, error",
|
|
||||||
tc.key, got, err, time.Duration(0))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPayloadHas(t *testing.T) {
|
|
||||||
payload := Payload{map[string]interface{}{
|
|
||||||
"user_id": 123,
|
|
||||||
}}
|
|
||||||
|
|
||||||
if !payload.Has("user_id") {
|
|
||||||
t.Errorf("Payload.Has(%q) = false, want true", "user_id")
|
|
||||||
}
|
|
||||||
if payload.Has("name") {
|
|
||||||
t.Errorf("Payload.Has(%q) = true, want false", "name")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPayloadDebuggingStrings(t *testing.T) {
|
|
||||||
data := map[string]interface{}{
|
|
||||||
"foo": 123,
|
|
||||||
"bar": "hello",
|
|
||||||
"baz": false,
|
|
||||||
}
|
|
||||||
payload := Payload{data: data}
|
|
||||||
|
|
||||||
if payload.String() != fmt.Sprint(data) {
|
|
||||||
t.Errorf("Payload.String() = %q, want %q",
|
|
||||||
payload.String(), fmt.Sprint(data))
|
|
||||||
}
|
|
||||||
|
|
||||||
got, err := payload.MarshalJSON()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
want, err := json.Marshal(data)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if diff := cmp.Diff(got, want); diff != "" {
|
|
||||||
t.Errorf("Payload.MarhsalJSON() = %s, want %s; (-want,+got)\n%s",
|
|
||||||
got, want, diff)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
243
periodic_task_manager.go
Normal file
243
periodic_task_manager.go
Normal file
@@ -0,0 +1,243 @@
|
|||||||
|
// Copyright 2022 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package asynq
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"sort"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PeriodicTaskManager manages scheduling of periodic tasks.
|
||||||
|
// It syncs scheduler's entries by calling the config provider periodically.
|
||||||
|
type PeriodicTaskManager struct {
|
||||||
|
s *Scheduler
|
||||||
|
p PeriodicTaskConfigProvider
|
||||||
|
syncInterval time.Duration
|
||||||
|
done chan (struct{})
|
||||||
|
wg sync.WaitGroup
|
||||||
|
m map[string]string // map[hash]entryID
|
||||||
|
}
|
||||||
|
|
||||||
|
type PeriodicTaskManagerOpts struct {
|
||||||
|
// Required: must be non nil
|
||||||
|
PeriodicTaskConfigProvider PeriodicTaskConfigProvider
|
||||||
|
|
||||||
|
// Required: must be non nil
|
||||||
|
RedisConnOpt RedisConnOpt
|
||||||
|
|
||||||
|
// Optional: scheduler options
|
||||||
|
*SchedulerOpts
|
||||||
|
|
||||||
|
// Optional: default is 3m
|
||||||
|
SyncInterval time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
const defaultSyncInterval = 3 * time.Minute
|
||||||
|
|
||||||
|
// NewPeriodicTaskManager returns a new PeriodicTaskManager instance.
|
||||||
|
// The given opts should specify the RedisConnOp and PeriodicTaskConfigProvider at minimum.
|
||||||
|
func NewPeriodicTaskManager(opts PeriodicTaskManagerOpts) (*PeriodicTaskManager, error) {
|
||||||
|
if opts.PeriodicTaskConfigProvider == nil {
|
||||||
|
return nil, fmt.Errorf("PeriodicTaskConfigProvider cannot be nil")
|
||||||
|
}
|
||||||
|
if opts.RedisConnOpt == nil {
|
||||||
|
return nil, fmt.Errorf("RedisConnOpt cannot be nil")
|
||||||
|
}
|
||||||
|
scheduler := NewScheduler(opts.RedisConnOpt, opts.SchedulerOpts)
|
||||||
|
syncInterval := opts.SyncInterval
|
||||||
|
if syncInterval == 0 {
|
||||||
|
syncInterval = defaultSyncInterval
|
||||||
|
}
|
||||||
|
return &PeriodicTaskManager{
|
||||||
|
s: scheduler,
|
||||||
|
p: opts.PeriodicTaskConfigProvider,
|
||||||
|
syncInterval: syncInterval,
|
||||||
|
done: make(chan struct{}),
|
||||||
|
m: make(map[string]string),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// PeriodicTaskConfigProvider provides configs for periodic tasks.
|
||||||
|
// GetConfigs will be called by a PeriodicTaskManager periodically to
|
||||||
|
// sync the scheduler's entries with the configs returned by the provider.
|
||||||
|
type PeriodicTaskConfigProvider interface {
|
||||||
|
GetConfigs() ([]*PeriodicTaskConfig, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PeriodicTaskConfig specifies the details of a periodic task.
|
||||||
|
type PeriodicTaskConfig struct {
|
||||||
|
Cronspec string // required: must be non empty string
|
||||||
|
Task *Task // required: must be non nil
|
||||||
|
Opts []Option // optional: can be nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *PeriodicTaskConfig) hash() string {
|
||||||
|
h := sha256.New()
|
||||||
|
io.WriteString(h, c.Cronspec)
|
||||||
|
io.WriteString(h, c.Task.Type())
|
||||||
|
h.Write(c.Task.Payload())
|
||||||
|
opts := stringifyOptions(c.Opts)
|
||||||
|
sort.Strings(opts)
|
||||||
|
for _, opt := range opts {
|
||||||
|
io.WriteString(h, opt)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%x", h.Sum(nil))
|
||||||
|
}
|
||||||
|
|
||||||
|
func validatePeriodicTaskConfig(c *PeriodicTaskConfig) error {
|
||||||
|
if c == nil {
|
||||||
|
return fmt.Errorf("PeriodicTaskConfig cannot be nil")
|
||||||
|
}
|
||||||
|
if c.Task == nil {
|
||||||
|
return fmt.Errorf("PeriodicTaskConfig.Task cannot be nil")
|
||||||
|
}
|
||||||
|
if c.Cronspec == "" {
|
||||||
|
return fmt.Errorf("PeriodicTaskConfig.Cronspec cannot be empty")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start starts a scheduler and background goroutine to sync the scheduler with the configs
|
||||||
|
// returned by the provider.
|
||||||
|
//
|
||||||
|
// Start returns any error encountered at start up time.
|
||||||
|
func (mgr *PeriodicTaskManager) Start() error {
|
||||||
|
if mgr.s == nil || mgr.p == nil {
|
||||||
|
panic("asynq: cannot start uninitialized PeriodicTaskManager; use NewPeriodicTaskManager to initialize")
|
||||||
|
}
|
||||||
|
if err := mgr.initialSync(); err != nil {
|
||||||
|
return fmt.Errorf("asynq: %v", err)
|
||||||
|
}
|
||||||
|
if err := mgr.s.Start(); err != nil {
|
||||||
|
return fmt.Errorf("asynq: %v", err)
|
||||||
|
}
|
||||||
|
mgr.wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer mgr.wg.Done()
|
||||||
|
ticker := time.NewTicker(mgr.syncInterval)
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-mgr.done:
|
||||||
|
mgr.s.logger.Debugf("Stopping syncer goroutine")
|
||||||
|
ticker.Stop()
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
mgr.sync()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Shutdown gracefully shuts down the manager.
|
||||||
|
// It notifies a background syncer goroutine to stop and stops scheduler.
|
||||||
|
func (mgr *PeriodicTaskManager) Shutdown() {
|
||||||
|
close(mgr.done)
|
||||||
|
mgr.wg.Wait()
|
||||||
|
mgr.s.Shutdown()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run starts the manager and blocks until an os signal to exit the program is received.
|
||||||
|
// Once it receives a signal, it gracefully shuts down the manager.
|
||||||
|
func (mgr *PeriodicTaskManager) Run() error {
|
||||||
|
if err := mgr.Start(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
mgr.s.waitForSignals()
|
||||||
|
mgr.Shutdown()
|
||||||
|
mgr.s.logger.Debugf("PeriodicTaskManager exiting")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (mgr *PeriodicTaskManager) initialSync() error {
|
||||||
|
configs, err := mgr.p.GetConfigs()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("initial call to GetConfigs failed: %v", err)
|
||||||
|
}
|
||||||
|
for _, c := range configs {
|
||||||
|
if err := validatePeriodicTaskConfig(c); err != nil {
|
||||||
|
return fmt.Errorf("initial call to GetConfigs contained an invalid config: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mgr.add(configs)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (mgr *PeriodicTaskManager) add(configs []*PeriodicTaskConfig) {
|
||||||
|
for _, c := range configs {
|
||||||
|
entryID, err := mgr.s.Register(c.Cronspec, c.Task, c.Opts...)
|
||||||
|
if err != nil {
|
||||||
|
mgr.s.logger.Errorf("Failed to register periodic task: cronspec=%q task=%q",
|
||||||
|
c.Cronspec, c.Task.Type())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
mgr.m[c.hash()] = entryID
|
||||||
|
mgr.s.logger.Infof("Successfully registered periodic task: cronspec=%q task=%q, entryID=%s",
|
||||||
|
c.Cronspec, c.Task.Type(), entryID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (mgr *PeriodicTaskManager) remove(removed map[string]string) {
|
||||||
|
for hash, entryID := range removed {
|
||||||
|
if err := mgr.s.Unregister(entryID); err != nil {
|
||||||
|
mgr.s.logger.Errorf("Failed to unregister periodic task: %v", err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
delete(mgr.m, hash)
|
||||||
|
mgr.s.logger.Infof("Successfully unregistered periodic task: entryID=%s", entryID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (mgr *PeriodicTaskManager) sync() {
|
||||||
|
configs, err := mgr.p.GetConfigs()
|
||||||
|
if err != nil {
|
||||||
|
mgr.s.logger.Errorf("Failed to get periodic task configs: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, c := range configs {
|
||||||
|
if err := validatePeriodicTaskConfig(c); err != nil {
|
||||||
|
mgr.s.logger.Errorf("Failed to sync: GetConfigs returned an invalid config: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Diff and only register/unregister the newly added/removed entries.
|
||||||
|
removed := mgr.diffRemoved(configs)
|
||||||
|
added := mgr.diffAdded(configs)
|
||||||
|
mgr.remove(removed)
|
||||||
|
mgr.add(added)
|
||||||
|
}
|
||||||
|
|
||||||
|
// diffRemoved diffs the incoming configs with the registered config and returns
|
||||||
|
// a map containing hash and entryID of each config that was removed.
|
||||||
|
func (mgr *PeriodicTaskManager) diffRemoved(configs []*PeriodicTaskConfig) map[string]string {
|
||||||
|
newConfigs := make(map[string]string)
|
||||||
|
for _, c := range configs {
|
||||||
|
newConfigs[c.hash()] = "" // empty value since we don't have entryID yet
|
||||||
|
}
|
||||||
|
removed := make(map[string]string)
|
||||||
|
for k, v := range mgr.m {
|
||||||
|
// test whether existing config is present in the incoming configs
|
||||||
|
if _, found := newConfigs[k]; !found {
|
||||||
|
removed[k] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return removed
|
||||||
|
}
|
||||||
|
|
||||||
|
// diffAdded diffs the incoming configs with the registered configs and returns
|
||||||
|
// a list of configs that were added.
|
||||||
|
func (mgr *PeriodicTaskManager) diffAdded(configs []*PeriodicTaskConfig) []*PeriodicTaskConfig {
|
||||||
|
var added []*PeriodicTaskConfig
|
||||||
|
for _, c := range configs {
|
||||||
|
if _, found := mgr.m[c.hash()]; !found {
|
||||||
|
added = append(added, c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return added
|
||||||
|
}
|
||||||
343
periodic_task_manager_test.go
Normal file
343
periodic_task_manager_test.go
Normal file
@@ -0,0 +1,343 @@
|
|||||||
|
// Copyright 2022 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package asynq
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sort"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/go-cmp/cmp"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Trivial implementation of PeriodicTaskConfigProvider for testing purpose.
|
||||||
|
type FakeConfigProvider struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
cfgs []*PeriodicTaskConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *FakeConfigProvider) SetConfigs(cfgs []*PeriodicTaskConfig) {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
p.cfgs = cfgs
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *FakeConfigProvider) GetConfigs() ([]*PeriodicTaskConfig, error) {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
return p.cfgs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewPeriodicTaskManager(t *testing.T) {
|
||||||
|
cfgs := []*PeriodicTaskConfig{
|
||||||
|
{Cronspec: "* * * * *", Task: NewTask("foo", nil)},
|
||||||
|
{Cronspec: "* * * * *", Task: NewTask("bar", nil)},
|
||||||
|
}
|
||||||
|
tests := []struct {
|
||||||
|
desc string
|
||||||
|
opts PeriodicTaskManagerOpts
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
desc: "with provider and redisConnOpt",
|
||||||
|
opts: PeriodicTaskManagerOpts{
|
||||||
|
RedisConnOpt: RedisClientOpt{Addr: ":6379"},
|
||||||
|
PeriodicTaskConfigProvider: &FakeConfigProvider{cfgs: cfgs},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "with sync option",
|
||||||
|
opts: PeriodicTaskManagerOpts{
|
||||||
|
RedisConnOpt: RedisClientOpt{Addr: ":6379"},
|
||||||
|
PeriodicTaskConfigProvider: &FakeConfigProvider{cfgs: cfgs},
|
||||||
|
SyncInterval: 5 * time.Minute,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "with scheduler option",
|
||||||
|
opts: PeriodicTaskManagerOpts{
|
||||||
|
RedisConnOpt: RedisClientOpt{Addr: ":6379"},
|
||||||
|
PeriodicTaskConfigProvider: &FakeConfigProvider{cfgs: cfgs},
|
||||||
|
SyncInterval: 5 * time.Minute,
|
||||||
|
SchedulerOpts: &SchedulerOpts{
|
||||||
|
LogLevel: DebugLevel,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
_, err := NewPeriodicTaskManager(tc.opts)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("%s; NewPeriodicTaskManager returned error: %v", tc.desc, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewPeriodicTaskManagerError(t *testing.T) {
|
||||||
|
cfgs := []*PeriodicTaskConfig{
|
||||||
|
{Cronspec: "* * * * *", Task: NewTask("foo", nil)},
|
||||||
|
{Cronspec: "* * * * *", Task: NewTask("bar", nil)},
|
||||||
|
}
|
||||||
|
tests := []struct {
|
||||||
|
desc string
|
||||||
|
opts PeriodicTaskManagerOpts
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
desc: "without provider",
|
||||||
|
opts: PeriodicTaskManagerOpts{
|
||||||
|
RedisConnOpt: RedisClientOpt{Addr: ":6379"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "without redisConOpt",
|
||||||
|
opts: PeriodicTaskManagerOpts{
|
||||||
|
PeriodicTaskConfigProvider: &FakeConfigProvider{cfgs: cfgs},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
_, err := NewPeriodicTaskManager(tc.opts)
|
||||||
|
if err == nil {
|
||||||
|
t.Errorf("%s; NewPeriodicTaskManager did not return error", tc.desc)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPeriodicTaskConfigHash(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
desc string
|
||||||
|
a *PeriodicTaskConfig
|
||||||
|
b *PeriodicTaskConfig
|
||||||
|
isSame bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
desc: "basic identity test",
|
||||||
|
a: &PeriodicTaskConfig{
|
||||||
|
Cronspec: "* * * * *",
|
||||||
|
Task: NewTask("foo", nil),
|
||||||
|
},
|
||||||
|
b: &PeriodicTaskConfig{
|
||||||
|
Cronspec: "* * * * *",
|
||||||
|
Task: NewTask("foo", nil),
|
||||||
|
},
|
||||||
|
isSame: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "with a option",
|
||||||
|
a: &PeriodicTaskConfig{
|
||||||
|
Cronspec: "* * * * *",
|
||||||
|
Task: NewTask("foo", nil),
|
||||||
|
Opts: []Option{Queue("myqueue")},
|
||||||
|
},
|
||||||
|
b: &PeriodicTaskConfig{
|
||||||
|
Cronspec: "* * * * *",
|
||||||
|
Task: NewTask("foo", nil),
|
||||||
|
Opts: []Option{Queue("myqueue")},
|
||||||
|
},
|
||||||
|
isSame: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "with multiple options (different order)",
|
||||||
|
a: &PeriodicTaskConfig{
|
||||||
|
Cronspec: "* * * * *",
|
||||||
|
Task: NewTask("foo", nil),
|
||||||
|
Opts: []Option{Unique(5 * time.Minute), Queue("myqueue")},
|
||||||
|
},
|
||||||
|
b: &PeriodicTaskConfig{
|
||||||
|
Cronspec: "* * * * *",
|
||||||
|
Task: NewTask("foo", nil),
|
||||||
|
Opts: []Option{Queue("myqueue"), Unique(5 * time.Minute)},
|
||||||
|
},
|
||||||
|
isSame: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "with payload",
|
||||||
|
a: &PeriodicTaskConfig{
|
||||||
|
Cronspec: "* * * * *",
|
||||||
|
Task: NewTask("foo", []byte("hello world!")),
|
||||||
|
Opts: []Option{Queue("myqueue")},
|
||||||
|
},
|
||||||
|
b: &PeriodicTaskConfig{
|
||||||
|
Cronspec: "* * * * *",
|
||||||
|
Task: NewTask("foo", []byte("hello world!")),
|
||||||
|
Opts: []Option{Queue("myqueue")},
|
||||||
|
},
|
||||||
|
isSame: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "with different cronspecs",
|
||||||
|
a: &PeriodicTaskConfig{
|
||||||
|
Cronspec: "* * * * *",
|
||||||
|
Task: NewTask("foo", nil),
|
||||||
|
},
|
||||||
|
b: &PeriodicTaskConfig{
|
||||||
|
Cronspec: "5 * * * *",
|
||||||
|
Task: NewTask("foo", nil),
|
||||||
|
},
|
||||||
|
isSame: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "with different task type",
|
||||||
|
a: &PeriodicTaskConfig{
|
||||||
|
Cronspec: "* * * * *",
|
||||||
|
Task: NewTask("foo", nil),
|
||||||
|
},
|
||||||
|
b: &PeriodicTaskConfig{
|
||||||
|
Cronspec: "* * * * *",
|
||||||
|
Task: NewTask("bar", nil),
|
||||||
|
},
|
||||||
|
isSame: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "with different options",
|
||||||
|
a: &PeriodicTaskConfig{
|
||||||
|
Cronspec: "* * * * *",
|
||||||
|
Task: NewTask("foo", nil),
|
||||||
|
Opts: []Option{Queue("myqueue")},
|
||||||
|
},
|
||||||
|
b: &PeriodicTaskConfig{
|
||||||
|
Cronspec: "* * * * *",
|
||||||
|
Task: NewTask("foo", nil),
|
||||||
|
Opts: []Option{Unique(10 * time.Minute)},
|
||||||
|
},
|
||||||
|
isSame: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "with different options (one is subset of the other)",
|
||||||
|
a: &PeriodicTaskConfig{
|
||||||
|
Cronspec: "* * * * *",
|
||||||
|
Task: NewTask("foo", nil),
|
||||||
|
Opts: []Option{Queue("myqueue")},
|
||||||
|
},
|
||||||
|
b: &PeriodicTaskConfig{
|
||||||
|
Cronspec: "* * * * *",
|
||||||
|
Task: NewTask("foo", nil),
|
||||||
|
Opts: []Option{Queue("myqueue"), Unique(10 * time.Minute)},
|
||||||
|
},
|
||||||
|
isSame: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "with different payload",
|
||||||
|
a: &PeriodicTaskConfig{
|
||||||
|
Cronspec: "* * * * *",
|
||||||
|
Task: NewTask("foo", []byte("hello!")),
|
||||||
|
Opts: []Option{Queue("myqueue")},
|
||||||
|
},
|
||||||
|
b: &PeriodicTaskConfig{
|
||||||
|
Cronspec: "* * * * *",
|
||||||
|
Task: NewTask("foo", []byte("HELLO!")),
|
||||||
|
Opts: []Option{Queue("myqueue"), Unique(10 * time.Minute)},
|
||||||
|
},
|
||||||
|
isSame: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
if tc.isSame && tc.a.hash() != tc.b.hash() {
|
||||||
|
t.Errorf("%s: a.hash=%s b.hash=%s expected to be equal",
|
||||||
|
tc.desc, tc.a.hash(), tc.b.hash())
|
||||||
|
}
|
||||||
|
if !tc.isSame && tc.a.hash() == tc.b.hash() {
|
||||||
|
t.Errorf("%s: a.hash=%s b.hash=%s expected to be not equal",
|
||||||
|
tc.desc, tc.a.hash(), tc.b.hash())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Things to test.
|
||||||
|
// - Run the manager
|
||||||
|
// - Change provider to return new configs
|
||||||
|
// - Verify that the scheduler synced with the new config
|
||||||
|
func TestPeriodicTaskManager(t *testing.T) {
|
||||||
|
// Note: In this test, we'll use task type as an ID for each config.
|
||||||
|
cfgs := []*PeriodicTaskConfig{
|
||||||
|
{Task: NewTask("task1", nil), Cronspec: "* * * * 1"},
|
||||||
|
{Task: NewTask("task2", nil), Cronspec: "* * * * 2"},
|
||||||
|
}
|
||||||
|
const syncInterval = 3 * time.Second
|
||||||
|
provider := &FakeConfigProvider{cfgs: cfgs}
|
||||||
|
mgr, err := NewPeriodicTaskManager(PeriodicTaskManagerOpts{
|
||||||
|
RedisConnOpt: getRedisConnOpt(t),
|
||||||
|
PeriodicTaskConfigProvider: provider,
|
||||||
|
SyncInterval: syncInterval,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Failed to initialize PeriodicTaskManager: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := mgr.Start(); err != nil {
|
||||||
|
t.Fatalf("Failed to start PeriodicTaskManager: %v", err)
|
||||||
|
}
|
||||||
|
defer mgr.Shutdown()
|
||||||
|
|
||||||
|
got := extractCronEntries(mgr.s)
|
||||||
|
want := []*cronEntry{
|
||||||
|
{Cronspec: "* * * * 1", TaskType: "task1"},
|
||||||
|
{Cronspec: "* * * * 2", TaskType: "task2"},
|
||||||
|
}
|
||||||
|
if diff := cmp.Diff(want, got, sortCronEntry); diff != "" {
|
||||||
|
t.Errorf("Diff found in scheduler's registered entries: %s", diff)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Change the underlying configs
|
||||||
|
// - task2 removed
|
||||||
|
// - task3 added
|
||||||
|
provider.SetConfigs([]*PeriodicTaskConfig{
|
||||||
|
{Task: NewTask("task1", nil), Cronspec: "* * * * 1"},
|
||||||
|
{Task: NewTask("task3", nil), Cronspec: "* * * * 3"},
|
||||||
|
})
|
||||||
|
|
||||||
|
// Wait for the next sync
|
||||||
|
time.Sleep(syncInterval * 2)
|
||||||
|
|
||||||
|
// Verify the entries are synced
|
||||||
|
got = extractCronEntries(mgr.s)
|
||||||
|
want = []*cronEntry{
|
||||||
|
{Cronspec: "* * * * 1", TaskType: "task1"},
|
||||||
|
{Cronspec: "* * * * 3", TaskType: "task3"},
|
||||||
|
}
|
||||||
|
if diff := cmp.Diff(want, got, sortCronEntry); diff != "" {
|
||||||
|
t.Errorf("Diff found in scheduler's registered entries: %s", diff)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Change the underlying configs
|
||||||
|
// All configs removed, empty set.
|
||||||
|
provider.SetConfigs([]*PeriodicTaskConfig{})
|
||||||
|
|
||||||
|
// Wait for the next sync
|
||||||
|
time.Sleep(syncInterval * 2)
|
||||||
|
|
||||||
|
// Verify the entries are synced
|
||||||
|
got = extractCronEntries(mgr.s)
|
||||||
|
want = []*cronEntry{}
|
||||||
|
if diff := cmp.Diff(want, got, sortCronEntry); diff != "" {
|
||||||
|
t.Errorf("Diff found in scheduler's registered entries: %s", diff)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func extractCronEntries(s *Scheduler) []*cronEntry {
|
||||||
|
var out []*cronEntry
|
||||||
|
for _, e := range s.cron.Entries() {
|
||||||
|
job := e.Job.(*enqueueJob)
|
||||||
|
out = append(out, &cronEntry{Cronspec: job.cronspec, TaskType: job.task.Type()})
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
var sortCronEntry = cmp.Transformer("sortCronEntry", func(in []*cronEntry) []*cronEntry {
|
||||||
|
out := append([]*cronEntry(nil), in...)
|
||||||
|
sort.Slice(out, func(i, j int) bool {
|
||||||
|
return out[i].TaskType < out[j].TaskType
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
})
|
||||||
|
|
||||||
|
// A simple struct to allow for simpler comparison in test.
|
||||||
|
type cronEntry struct {
|
||||||
|
Cronspec string
|
||||||
|
TaskType string
|
||||||
|
}
|
||||||
263
processor.go
263
processor.go
@@ -6,8 +6,8 @@ package asynq
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"math"
|
||||||
"math/rand"
|
"math/rand"
|
||||||
"runtime"
|
"runtime"
|
||||||
"runtime/debug"
|
"runtime/debug"
|
||||||
@@ -17,26 +17,31 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/hibiken/asynq/internal/base"
|
"github.com/hibiken/asynq/internal/base"
|
||||||
|
asynqcontext "github.com/hibiken/asynq/internal/context"
|
||||||
|
"github.com/hibiken/asynq/internal/errors"
|
||||||
"github.com/hibiken/asynq/internal/log"
|
"github.com/hibiken/asynq/internal/log"
|
||||||
"github.com/hibiken/asynq/internal/rdb"
|
"github.com/hibiken/asynq/internal/timeutil"
|
||||||
"golang.org/x/time/rate"
|
"golang.org/x/time/rate"
|
||||||
)
|
)
|
||||||
|
|
||||||
type processor struct {
|
type processor struct {
|
||||||
logger *log.Logger
|
logger *log.Logger
|
||||||
broker base.Broker
|
broker base.Broker
|
||||||
|
clock timeutil.Clock
|
||||||
|
|
||||||
handler Handler
|
handler Handler
|
||||||
|
baseCtxFn func() context.Context
|
||||||
|
|
||||||
queueConfig map[string]int
|
queueConfig map[string]int
|
||||||
|
|
||||||
// orderedQueues is set only in strict-priority mode.
|
// orderedQueues is set only in strict-priority mode.
|
||||||
orderedQueues []string
|
orderedQueues []string
|
||||||
|
|
||||||
retryDelayFunc RetryDelayFunc
|
taskCheckInterval time.Duration
|
||||||
|
retryDelayFunc RetryDelayFunc
|
||||||
errHandler ErrorHandler
|
isFailureFunc func(error) bool
|
||||||
|
|
||||||
|
errHandler ErrorHandler
|
||||||
shutdownTimeout time.Duration
|
shutdownTimeout time.Duration
|
||||||
|
|
||||||
// channel via which to send sync requests to syncer.
|
// channel via which to send sync requests to syncer.
|
||||||
@@ -68,18 +73,21 @@ type processor struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type processorParams struct {
|
type processorParams struct {
|
||||||
logger *log.Logger
|
logger *log.Logger
|
||||||
broker base.Broker
|
broker base.Broker
|
||||||
retryDelayFunc RetryDelayFunc
|
baseCtxFn func() context.Context
|
||||||
syncCh chan<- *syncRequest
|
retryDelayFunc RetryDelayFunc
|
||||||
cancelations *base.Cancelations
|
taskCheckInterval time.Duration
|
||||||
concurrency int
|
isFailureFunc func(error) bool
|
||||||
queues map[string]int
|
syncCh chan<- *syncRequest
|
||||||
strictPriority bool
|
cancelations *base.Cancelations
|
||||||
errHandler ErrorHandler
|
concurrency int
|
||||||
shutdownTimeout time.Duration
|
queues map[string]int
|
||||||
starting chan<- *workerInfo
|
strictPriority bool
|
||||||
finished chan<- *base.TaskMessage
|
errHandler ErrorHandler
|
||||||
|
shutdownTimeout time.Duration
|
||||||
|
starting chan<- *workerInfo
|
||||||
|
finished chan<- *base.TaskMessage
|
||||||
}
|
}
|
||||||
|
|
||||||
// newProcessor constructs a new processor.
|
// newProcessor constructs a new processor.
|
||||||
@@ -90,23 +98,27 @@ func newProcessor(params processorParams) *processor {
|
|||||||
orderedQueues = sortByPriority(queues)
|
orderedQueues = sortByPriority(queues)
|
||||||
}
|
}
|
||||||
return &processor{
|
return &processor{
|
||||||
logger: params.logger,
|
logger: params.logger,
|
||||||
broker: params.broker,
|
broker: params.broker,
|
||||||
queueConfig: queues,
|
baseCtxFn: params.baseCtxFn,
|
||||||
orderedQueues: orderedQueues,
|
clock: timeutil.NewRealClock(),
|
||||||
retryDelayFunc: params.retryDelayFunc,
|
queueConfig: queues,
|
||||||
syncRequestCh: params.syncCh,
|
orderedQueues: orderedQueues,
|
||||||
cancelations: params.cancelations,
|
taskCheckInterval: params.taskCheckInterval,
|
||||||
errLogLimiter: rate.NewLimiter(rate.Every(3*time.Second), 1),
|
retryDelayFunc: params.retryDelayFunc,
|
||||||
sema: make(chan struct{}, params.concurrency),
|
isFailureFunc: params.isFailureFunc,
|
||||||
done: make(chan struct{}),
|
syncRequestCh: params.syncCh,
|
||||||
quit: make(chan struct{}),
|
cancelations: params.cancelations,
|
||||||
abort: make(chan struct{}),
|
errLogLimiter: rate.NewLimiter(rate.Every(3*time.Second), 1),
|
||||||
errHandler: params.errHandler,
|
sema: make(chan struct{}, params.concurrency),
|
||||||
handler: HandlerFunc(func(ctx context.Context, t *Task) error { return fmt.Errorf("handler not set") }),
|
done: make(chan struct{}),
|
||||||
shutdownTimeout: params.shutdownTimeout,
|
quit: make(chan struct{}),
|
||||||
starting: params.starting,
|
abort: make(chan struct{}),
|
||||||
finished: params.finished,
|
errHandler: params.errHandler,
|
||||||
|
handler: HandlerFunc(func(ctx context.Context, t *Task) error { return fmt.Errorf("handler not set") }),
|
||||||
|
shutdownTimeout: params.shutdownTimeout,
|
||||||
|
starting: params.starting,
|
||||||
|
finished: params.finished,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -123,8 +135,8 @@ func (p *processor) stop() {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// NOTE: once terminated, processor cannot be re-started.
|
// NOTE: once shutdown, processor cannot be re-started.
|
||||||
func (p *processor) terminate() {
|
func (p *processor) shutdown() {
|
||||||
p.stop()
|
p.stop()
|
||||||
|
|
||||||
time.AfterFunc(p.shutdownTimeout, func() { close(p.abort) })
|
time.AfterFunc(p.shutdownTimeout, func() { close(p.abort) })
|
||||||
@@ -161,15 +173,15 @@ func (p *processor) exec() {
|
|||||||
return
|
return
|
||||||
case p.sema <- struct{}{}: // acquire token
|
case p.sema <- struct{}{}: // acquire token
|
||||||
qnames := p.queues()
|
qnames := p.queues()
|
||||||
msg, deadline, err := p.broker.Dequeue(qnames...)
|
msg, leaseExpirationTime, err := p.broker.Dequeue(qnames...)
|
||||||
switch {
|
switch {
|
||||||
case err == rdb.ErrNoProcessableTask:
|
case errors.Is(err, errors.ErrNoProcessableTask):
|
||||||
p.logger.Debug("All queues are empty")
|
p.logger.Debug("All queues are empty")
|
||||||
// Queues are empty, this is a normal behavior.
|
// Queues are empty, this is a normal behavior.
|
||||||
// Sleep to avoid slamming redis and let scheduler move tasks into queues.
|
// Sleep to avoid slamming redis and let scheduler move tasks into queues.
|
||||||
// Note: We are not using blocking pop operation and polling queues instead.
|
// Note: We are not using blocking pop operation and polling queues instead.
|
||||||
// This adds significant load to redis.
|
// This adds significant load to redis.
|
||||||
time.Sleep(time.Second)
|
time.Sleep(p.taskCheckInterval)
|
||||||
<-p.sema // release token
|
<-p.sema // release token
|
||||||
return
|
return
|
||||||
case err != nil:
|
case err != nil:
|
||||||
@@ -180,60 +192,77 @@ func (p *processor) exec() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
p.starting <- &workerInfo{msg, time.Now(), deadline}
|
lease := base.NewLease(leaseExpirationTime)
|
||||||
|
deadline := p.computeDeadline(msg)
|
||||||
|
p.starting <- &workerInfo{msg, time.Now(), deadline, lease}
|
||||||
go func() {
|
go func() {
|
||||||
defer func() {
|
defer func() {
|
||||||
p.finished <- msg
|
p.finished <- msg
|
||||||
<-p.sema // release token
|
<-p.sema // release token
|
||||||
}()
|
}()
|
||||||
|
|
||||||
ctx, cancel := createContext(msg, deadline)
|
ctx, cancel := asynqcontext.New(p.baseCtxFn(), msg, deadline)
|
||||||
p.cancelations.Add(msg.ID.String(), cancel)
|
p.cancelations.Add(msg.ID, cancel)
|
||||||
defer func() {
|
defer func() {
|
||||||
cancel()
|
cancel()
|
||||||
p.cancelations.Delete(msg.ID.String())
|
p.cancelations.Delete(msg.ID)
|
||||||
}()
|
}()
|
||||||
|
|
||||||
// check context before starting a worker goroutine.
|
// check context before starting a worker goroutine.
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
// already canceled (e.g. deadline exceeded).
|
// already canceled (e.g. deadline exceeded).
|
||||||
p.retryOrKill(ctx, msg, ctx.Err())
|
p.handleFailedMessage(ctx, lease, msg, ctx.Err())
|
||||||
return
|
return
|
||||||
default:
|
default:
|
||||||
}
|
}
|
||||||
|
|
||||||
resCh := make(chan error, 1)
|
resCh := make(chan error, 1)
|
||||||
go func() {
|
go func() {
|
||||||
resCh <- p.perform(ctx, NewTask(msg.Type, msg.Payload))
|
task := newTask(
|
||||||
|
msg.Type,
|
||||||
|
msg.Payload,
|
||||||
|
&ResultWriter{
|
||||||
|
id: msg.ID,
|
||||||
|
qname: msg.Queue,
|
||||||
|
broker: p.broker,
|
||||||
|
ctx: ctx,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
resCh <- p.perform(ctx, task)
|
||||||
}()
|
}()
|
||||||
|
|
||||||
select {
|
select {
|
||||||
case <-p.abort:
|
case <-p.abort:
|
||||||
// time is up, push the message back to queue and quit this worker goroutine.
|
// time is up, push the message back to queue and quit this worker goroutine.
|
||||||
p.logger.Warnf("Quitting worker. task id=%s", msg.ID)
|
p.logger.Warnf("Quitting worker. task id=%s", msg.ID)
|
||||||
p.requeue(msg)
|
p.requeue(lease, msg)
|
||||||
|
return
|
||||||
|
case <-lease.Done():
|
||||||
|
cancel()
|
||||||
|
p.handleFailedMessage(ctx, lease, msg, ErrLeaseExpired)
|
||||||
return
|
return
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
p.retryOrKill(ctx, msg, ctx.Err())
|
p.handleFailedMessage(ctx, lease, msg, ctx.Err())
|
||||||
return
|
return
|
||||||
case resErr := <-resCh:
|
case resErr := <-resCh:
|
||||||
// Note: One of three things should happen.
|
|
||||||
// 1) Done -> Removes the message from Active
|
|
||||||
// 2) Retry -> Removes the message from Active & Adds the message to Retry
|
|
||||||
// 3) Archive -> Removes the message from Active & Adds the message to archive
|
|
||||||
if resErr != nil {
|
if resErr != nil {
|
||||||
p.retryOrKill(ctx, msg, resErr)
|
p.handleFailedMessage(ctx, lease, msg, resErr)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
p.markAsDone(ctx, msg)
|
p.handleSucceededMessage(lease, msg)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *processor) requeue(msg *base.TaskMessage) {
|
func (p *processor) requeue(l *base.Lease, msg *base.TaskMessage) {
|
||||||
err := p.broker.Requeue(msg)
|
if !l.IsValid() {
|
||||||
|
// If lease is not valid, do not write to redis; Let recoverer take care of it.
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx, _ := context.WithDeadline(context.Background(), l.Deadline())
|
||||||
|
err := p.broker.Requeue(ctx, msg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
p.logger.Errorf("Could not push task id=%s back to queue: %v", msg.ID, err)
|
p.logger.Errorf("Could not push task id=%s back to queue: %v", msg.ID, err)
|
||||||
} else {
|
} else {
|
||||||
@@ -241,21 +270,51 @@ func (p *processor) requeue(msg *base.TaskMessage) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *processor) markAsDone(ctx context.Context, msg *base.TaskMessage) {
|
func (p *processor) handleSucceededMessage(l *base.Lease, msg *base.TaskMessage) {
|
||||||
err := p.broker.Done(msg)
|
if msg.Retention > 0 {
|
||||||
|
p.markAsComplete(l, msg)
|
||||||
|
} else {
|
||||||
|
p.markAsDone(l, msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *processor) markAsComplete(l *base.Lease, msg *base.TaskMessage) {
|
||||||
|
if !l.IsValid() {
|
||||||
|
// If lease is not valid, do not write to redis; Let recoverer take care of it.
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx, _ := context.WithDeadline(context.Background(), l.Deadline())
|
||||||
|
err := p.broker.MarkAsComplete(ctx, msg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
errMsg := fmt.Sprintf("Could not remove task id=%s type=%q from %q err: %+v", msg.ID, msg.Type, base.ActiveKey(msg.Queue), err)
|
errMsg := fmt.Sprintf("Could not move task id=%s type=%q from %q to %q: %+v",
|
||||||
deadline, ok := ctx.Deadline()
|
msg.ID, msg.Type, base.ActiveKey(msg.Queue), base.CompletedKey(msg.Queue), err)
|
||||||
if !ok {
|
|
||||||
panic("asynq: internal error: missing deadline in context")
|
|
||||||
}
|
|
||||||
p.logger.Warnf("%s; Will retry syncing", errMsg)
|
p.logger.Warnf("%s; Will retry syncing", errMsg)
|
||||||
p.syncRequestCh <- &syncRequest{
|
p.syncRequestCh <- &syncRequest{
|
||||||
fn: func() error {
|
fn: func() error {
|
||||||
return p.broker.Done(msg)
|
return p.broker.MarkAsComplete(ctx, msg)
|
||||||
},
|
},
|
||||||
errMsg: errMsg,
|
errMsg: errMsg,
|
||||||
deadline: deadline,
|
deadline: l.Deadline(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *processor) markAsDone(l *base.Lease, msg *base.TaskMessage) {
|
||||||
|
if !l.IsValid() {
|
||||||
|
// If lease is not valid, do not write to redis; Let recoverer take care of it.
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx, _ := context.WithDeadline(context.Background(), l.Deadline())
|
||||||
|
err := p.broker.Done(ctx, msg)
|
||||||
|
if err != nil {
|
||||||
|
errMsg := fmt.Sprintf("Could not remove task id=%s type=%q from %q err: %+v", msg.ID, msg.Type, base.ActiveKey(msg.Queue), err)
|
||||||
|
p.logger.Warnf("%s; Will retry syncing", errMsg)
|
||||||
|
p.syncRequestCh <- &syncRequest{
|
||||||
|
fn: func() error {
|
||||||
|
return p.broker.Done(ctx, msg)
|
||||||
|
},
|
||||||
|
errMsg: errMsg,
|
||||||
|
deadline: l.Deadline(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -264,54 +323,61 @@ func (p *processor) markAsDone(ctx context.Context, msg *base.TaskMessage) {
|
|||||||
// the task should not be retried and should be archived instead.
|
// the task should not be retried and should be archived instead.
|
||||||
var SkipRetry = errors.New("skip retry for the task")
|
var SkipRetry = errors.New("skip retry for the task")
|
||||||
|
|
||||||
func (p *processor) retryOrKill(ctx context.Context, msg *base.TaskMessage, err error) {
|
func (p *processor) handleFailedMessage(ctx context.Context, l *base.Lease, msg *base.TaskMessage, err error) {
|
||||||
if p.errHandler != nil {
|
if p.errHandler != nil {
|
||||||
p.errHandler.HandleError(ctx, NewTask(msg.Type, msg.Payload), err)
|
p.errHandler.HandleError(ctx, NewTask(msg.Type, msg.Payload), err)
|
||||||
}
|
}
|
||||||
|
if !p.isFailureFunc(err) {
|
||||||
|
// retry the task without marking it as failed
|
||||||
|
p.retry(l, msg, err, false /*isFailure*/)
|
||||||
|
return
|
||||||
|
}
|
||||||
if msg.Retried >= msg.Retry || errors.Is(err, SkipRetry) {
|
if msg.Retried >= msg.Retry || errors.Is(err, SkipRetry) {
|
||||||
p.logger.Warnf("Retry exhausted for task id=%s", msg.ID)
|
p.logger.Warnf("Retry exhausted for task id=%s", msg.ID)
|
||||||
p.archive(ctx, msg, err)
|
p.archive(l, msg, err)
|
||||||
} else {
|
} else {
|
||||||
p.retry(ctx, msg, err)
|
p.retry(l, msg, err, true /*isFailure*/)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *processor) retry(ctx context.Context, msg *base.TaskMessage, e error) {
|
func (p *processor) retry(l *base.Lease, msg *base.TaskMessage, e error, isFailure bool) {
|
||||||
|
if !l.IsValid() {
|
||||||
|
// If lease is not valid, do not write to redis; Let recoverer take care of it.
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx, _ := context.WithDeadline(context.Background(), l.Deadline())
|
||||||
d := p.retryDelayFunc(msg.Retried, e, NewTask(msg.Type, msg.Payload))
|
d := p.retryDelayFunc(msg.Retried, e, NewTask(msg.Type, msg.Payload))
|
||||||
retryAt := time.Now().Add(d)
|
retryAt := time.Now().Add(d)
|
||||||
err := p.broker.Retry(msg, retryAt, e.Error())
|
err := p.broker.Retry(ctx, msg, retryAt, e.Error(), isFailure)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
errMsg := fmt.Sprintf("Could not move task id=%s from %q to %q", msg.ID, base.ActiveKey(msg.Queue), base.RetryKey(msg.Queue))
|
errMsg := fmt.Sprintf("Could not move task id=%s from %q to %q", msg.ID, base.ActiveKey(msg.Queue), base.RetryKey(msg.Queue))
|
||||||
deadline, ok := ctx.Deadline()
|
|
||||||
if !ok {
|
|
||||||
panic("asynq: internal error: missing deadline in context")
|
|
||||||
}
|
|
||||||
p.logger.Warnf("%s; Will retry syncing", errMsg)
|
p.logger.Warnf("%s; Will retry syncing", errMsg)
|
||||||
p.syncRequestCh <- &syncRequest{
|
p.syncRequestCh <- &syncRequest{
|
||||||
fn: func() error {
|
fn: func() error {
|
||||||
return p.broker.Retry(msg, retryAt, e.Error())
|
return p.broker.Retry(ctx, msg, retryAt, e.Error(), isFailure)
|
||||||
},
|
},
|
||||||
errMsg: errMsg,
|
errMsg: errMsg,
|
||||||
deadline: deadline,
|
deadline: l.Deadline(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *processor) archive(ctx context.Context, msg *base.TaskMessage, e error) {
|
func (p *processor) archive(l *base.Lease, msg *base.TaskMessage, e error) {
|
||||||
err := p.broker.Archive(msg, e.Error())
|
if !l.IsValid() {
|
||||||
|
// If lease is not valid, do not write to redis; Let recoverer take care of it.
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx, _ := context.WithDeadline(context.Background(), l.Deadline())
|
||||||
|
err := p.broker.Archive(ctx, msg, e.Error())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
errMsg := fmt.Sprintf("Could not move task id=%s from %q to %q", msg.ID, base.ActiveKey(msg.Queue), base.ArchivedKey(msg.Queue))
|
errMsg := fmt.Sprintf("Could not move task id=%s from %q to %q", msg.ID, base.ActiveKey(msg.Queue), base.ArchivedKey(msg.Queue))
|
||||||
deadline, ok := ctx.Deadline()
|
|
||||||
if !ok {
|
|
||||||
panic("asynq: internal error: missing deadline in context")
|
|
||||||
}
|
|
||||||
p.logger.Warnf("%s; Will retry syncing", errMsg)
|
p.logger.Warnf("%s; Will retry syncing", errMsg)
|
||||||
p.syncRequestCh <- &syncRequest{
|
p.syncRequestCh <- &syncRequest{
|
||||||
fn: func() error {
|
fn: func() error {
|
||||||
return p.broker.Archive(msg, e.Error())
|
return p.broker.Archive(ctx, msg, e.Error())
|
||||||
},
|
},
|
||||||
errMsg: errMsg,
|
errMsg: errMsg,
|
||||||
deadline: deadline,
|
deadline: l.Deadline(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -356,12 +422,15 @@ func (p *processor) perform(ctx context.Context, task *Task) (err error) {
|
|||||||
// map/slice usage. The parent frame should have the real trigger.
|
// map/slice usage. The parent frame should have the real trigger.
|
||||||
_, file, line, ok = runtime.Caller(2)
|
_, file, line, ok = runtime.Caller(2)
|
||||||
}
|
}
|
||||||
|
var errMsg string
|
||||||
// Include the file and line number info in the error, if runtime.Caller returned ok.
|
// Include the file and line number info in the error, if runtime.Caller returned ok.
|
||||||
if ok {
|
if ok {
|
||||||
err = fmt.Errorf("panic [%s:%d]: %v", file, line, x)
|
errMsg = fmt.Sprintf("panic [%s:%d]: %v", file, line, x)
|
||||||
} else {
|
} else {
|
||||||
err = fmt.Errorf("panic: %v", x)
|
errMsg = fmt.Sprintf("panic: %v", x)
|
||||||
|
}
|
||||||
|
err = &errors.PanicError{
|
||||||
|
ErrMsg: errMsg,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
@@ -441,3 +510,23 @@ func gcd(xs ...int) int {
|
|||||||
}
|
}
|
||||||
return res
|
return res
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// computeDeadline returns the given task's deadline,
|
||||||
|
func (p *processor) computeDeadline(msg *base.TaskMessage) time.Time {
|
||||||
|
if msg.Timeout == 0 && msg.Deadline == 0 {
|
||||||
|
p.logger.Errorf("asynq: internal error: both timeout and deadline are not set for the task message: %s", msg.ID)
|
||||||
|
return p.clock.Now().Add(defaultTimeout)
|
||||||
|
}
|
||||||
|
if msg.Timeout != 0 && msg.Deadline != 0 {
|
||||||
|
deadlineUnix := math.Min(float64(p.clock.Now().Unix()+msg.Timeout), float64(msg.Deadline))
|
||||||
|
return time.Unix(int64(deadlineUnix), 0)
|
||||||
|
}
|
||||||
|
if msg.Timeout != 0 {
|
||||||
|
return p.clock.Now().Add(time.Duration(msg.Timeout) * time.Second)
|
||||||
|
}
|
||||||
|
return time.Unix(msg.Deadline, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsPanicError(err error) bool {
|
||||||
|
return errors.IsPanicError(err)
|
||||||
|
}
|
||||||
|
|||||||
@@ -6,19 +6,30 @@ package asynq
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"sort"
|
"sort"
|
||||||
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/google/go-cmp/cmp"
|
"github.com/google/go-cmp/cmp"
|
||||||
"github.com/google/go-cmp/cmp/cmpopts"
|
"github.com/google/go-cmp/cmp/cmpopts"
|
||||||
h "github.com/hibiken/asynq/internal/asynqtest"
|
|
||||||
"github.com/hibiken/asynq/internal/base"
|
"github.com/hibiken/asynq/internal/base"
|
||||||
|
"github.com/hibiken/asynq/internal/errors"
|
||||||
|
"github.com/hibiken/asynq/internal/log"
|
||||||
"github.com/hibiken/asynq/internal/rdb"
|
"github.com/hibiken/asynq/internal/rdb"
|
||||||
|
h "github.com/hibiken/asynq/internal/testutil"
|
||||||
|
"github.com/hibiken/asynq/internal/timeutil"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var taskCmpOpts = []cmp.Option{
|
||||||
|
sortTaskOpt, // sort the tasks
|
||||||
|
cmp.AllowUnexported(Task{}), // allow typename, payload fields to be compared
|
||||||
|
cmpopts.IgnoreFields(Task{}, "opts", "w"), // ignore opts, w fields
|
||||||
|
}
|
||||||
|
|
||||||
// fakeHeartbeater receives from starting and finished channels and do nothing.
|
// fakeHeartbeater receives from starting and finished channels and do nothing.
|
||||||
func fakeHeartbeater(starting <-chan *workerInfo, finished <-chan *base.TaskMessage, done <-chan struct{}) {
|
func fakeHeartbeater(starting <-chan *workerInfo, finished <-chan *base.TaskMessage, done <-chan struct{}) {
|
||||||
for {
|
for {
|
||||||
@@ -42,8 +53,39 @@ func fakeSyncer(syncCh <-chan *syncRequest, done <-chan struct{}) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Returns a processor instance configured for testing purpose.
|
||||||
|
func newProcessorForTest(t *testing.T, r *rdb.RDB, h Handler) *processor {
|
||||||
|
starting := make(chan *workerInfo)
|
||||||
|
finished := make(chan *base.TaskMessage)
|
||||||
|
syncCh := make(chan *syncRequest)
|
||||||
|
done := make(chan struct{})
|
||||||
|
t.Cleanup(func() { close(done) })
|
||||||
|
go fakeHeartbeater(starting, finished, done)
|
||||||
|
go fakeSyncer(syncCh, done)
|
||||||
|
p := newProcessor(processorParams{
|
||||||
|
logger: testLogger,
|
||||||
|
broker: r,
|
||||||
|
baseCtxFn: context.Background,
|
||||||
|
retryDelayFunc: DefaultRetryDelayFunc,
|
||||||
|
taskCheckInterval: defaultTaskCheckInterval,
|
||||||
|
isFailureFunc: defaultIsFailureFunc,
|
||||||
|
syncCh: syncCh,
|
||||||
|
cancelations: base.NewCancelations(),
|
||||||
|
concurrency: 10,
|
||||||
|
queues: defaultQueueConfig,
|
||||||
|
strictPriority: false,
|
||||||
|
errHandler: nil,
|
||||||
|
shutdownTimeout: defaultShutdownTimeout,
|
||||||
|
starting: starting,
|
||||||
|
finished: finished,
|
||||||
|
})
|
||||||
|
p.handler = h
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
func TestProcessorSuccessWithSingleQueue(t *testing.T) {
|
func TestProcessorSuccessWithSingleQueue(t *testing.T) {
|
||||||
r := setup(t)
|
r := setup(t)
|
||||||
|
defer r.Close()
|
||||||
rdbClient := rdb.NewRDB(r)
|
rdbClient := rdb.NewRDB(r)
|
||||||
|
|
||||||
m1 := h.NewTaskMessage("task1", nil)
|
m1 := h.NewTaskMessage("task1", nil)
|
||||||
@@ -86,45 +128,24 @@ func TestProcessorSuccessWithSingleQueue(t *testing.T) {
|
|||||||
processed = append(processed, task)
|
processed = append(processed, task)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
starting := make(chan *workerInfo)
|
p := newProcessorForTest(t, rdbClient, HandlerFunc(handler))
|
||||||
finished := make(chan *base.TaskMessage)
|
|
||||||
syncCh := make(chan *syncRequest)
|
|
||||||
done := make(chan struct{})
|
|
||||||
defer func() { close(done) }()
|
|
||||||
go fakeHeartbeater(starting, finished, done)
|
|
||||||
go fakeSyncer(syncCh, done)
|
|
||||||
p := newProcessor(processorParams{
|
|
||||||
logger: testLogger,
|
|
||||||
broker: rdbClient,
|
|
||||||
retryDelayFunc: DefaultRetryDelayFunc,
|
|
||||||
syncCh: syncCh,
|
|
||||||
cancelations: base.NewCancelations(),
|
|
||||||
concurrency: 10,
|
|
||||||
queues: defaultQueueConfig,
|
|
||||||
strictPriority: false,
|
|
||||||
errHandler: nil,
|
|
||||||
shutdownTimeout: defaultShutdownTimeout,
|
|
||||||
starting: starting,
|
|
||||||
finished: finished,
|
|
||||||
})
|
|
||||||
p.handler = HandlerFunc(handler)
|
|
||||||
|
|
||||||
p.start(&sync.WaitGroup{})
|
p.start(&sync.WaitGroup{})
|
||||||
for _, msg := range tc.incoming {
|
for _, msg := range tc.incoming {
|
||||||
err := rdbClient.Enqueue(msg)
|
err := rdbClient.Enqueue(context.Background(), msg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
p.terminate()
|
p.shutdown()
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
time.Sleep(2 * time.Second) // wait for two second to allow all pending tasks to be processed.
|
time.Sleep(2 * time.Second) // wait for two second to allow all pending tasks to be processed.
|
||||||
if l := r.LLen(base.ActiveKey(base.DefaultQueueName)).Val(); l != 0 {
|
if l := r.LLen(context.Background(), base.ActiveKey(base.DefaultQueueName)).Val(); l != 0 {
|
||||||
t.Errorf("%q has %d tasks, want 0", base.ActiveKey(base.DefaultQueueName), l)
|
t.Errorf("%q has %d tasks, want 0", base.ActiveKey(base.DefaultQueueName), l)
|
||||||
}
|
}
|
||||||
p.terminate()
|
p.shutdown()
|
||||||
|
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
if diff := cmp.Diff(tc.wantProcessed, processed, sortTaskOpt, cmp.AllowUnexported(Payload{})); diff != "" {
|
if diff := cmp.Diff(tc.wantProcessed, processed, taskCmpOpts...); diff != "" {
|
||||||
t.Errorf("mismatch found in processed tasks; (-want, +got)\n%s", diff)
|
t.Errorf("mismatch found in processed tasks; (-want, +got)\n%s", diff)
|
||||||
}
|
}
|
||||||
mu.Unlock()
|
mu.Unlock()
|
||||||
@@ -146,6 +167,7 @@ func TestProcessorSuccessWithMultipleQueues(t *testing.T) {
|
|||||||
t3 = NewTask(m3.Type, m3.Payload)
|
t3 = NewTask(m3.Type, m3.Payload)
|
||||||
t4 = NewTask(m4.Type, m4.Payload)
|
t4 = NewTask(m4.Type, m4.Payload)
|
||||||
)
|
)
|
||||||
|
defer r.Close()
|
||||||
|
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
pending map[string][]*base.TaskMessage
|
pending map[string][]*base.TaskMessage
|
||||||
@@ -177,46 +199,26 @@ func TestProcessorSuccessWithMultipleQueues(t *testing.T) {
|
|||||||
processed = append(processed, task)
|
processed = append(processed, task)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
starting := make(chan *workerInfo)
|
p := newProcessorForTest(t, rdbClient, HandlerFunc(handler))
|
||||||
finished := make(chan *base.TaskMessage)
|
p.queueConfig = map[string]int{
|
||||||
syncCh := make(chan *syncRequest)
|
"default": 2,
|
||||||
done := make(chan struct{})
|
"high": 3,
|
||||||
defer func() { close(done) }()
|
"low": 1,
|
||||||
go fakeHeartbeater(starting, finished, done)
|
}
|
||||||
go fakeSyncer(syncCh, done)
|
|
||||||
p := newProcessor(processorParams{
|
|
||||||
logger: testLogger,
|
|
||||||
broker: rdbClient,
|
|
||||||
retryDelayFunc: DefaultRetryDelayFunc,
|
|
||||||
syncCh: syncCh,
|
|
||||||
cancelations: base.NewCancelations(),
|
|
||||||
concurrency: 10,
|
|
||||||
queues: map[string]int{
|
|
||||||
"default": 2,
|
|
||||||
"high": 3,
|
|
||||||
"low": 1,
|
|
||||||
},
|
|
||||||
strictPriority: false,
|
|
||||||
errHandler: nil,
|
|
||||||
shutdownTimeout: defaultShutdownTimeout,
|
|
||||||
starting: starting,
|
|
||||||
finished: finished,
|
|
||||||
})
|
|
||||||
p.handler = HandlerFunc(handler)
|
|
||||||
|
|
||||||
p.start(&sync.WaitGroup{})
|
p.start(&sync.WaitGroup{})
|
||||||
// Wait for two second to allow all pending tasks to be processed.
|
// Wait for two second to allow all pending tasks to be processed.
|
||||||
time.Sleep(2 * time.Second)
|
time.Sleep(2 * time.Second)
|
||||||
// Make sure no messages are stuck in active list.
|
// Make sure no messages are stuck in active list.
|
||||||
for _, qname := range tc.queues {
|
for _, qname := range tc.queues {
|
||||||
if l := r.LLen(base.ActiveKey(qname)).Val(); l != 0 {
|
if l := r.LLen(context.Background(), base.ActiveKey(qname)).Val(); l != 0 {
|
||||||
t.Errorf("%q has %d tasks, want 0", base.ActiveKey(qname), l)
|
t.Errorf("%q has %d tasks, want 0", base.ActiveKey(qname), l)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
p.terminate()
|
p.shutdown()
|
||||||
|
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
if diff := cmp.Diff(tc.wantProcessed, processed, sortTaskOpt, cmp.AllowUnexported(Payload{})); diff != "" {
|
if diff := cmp.Diff(tc.wantProcessed, processed, taskCmpOpts...); diff != "" {
|
||||||
t.Errorf("mismatch found in processed tasks; (-want, +got)\n%s", diff)
|
t.Errorf("mismatch found in processed tasks; (-want, +got)\n%s", diff)
|
||||||
}
|
}
|
||||||
mu.Unlock()
|
mu.Unlock()
|
||||||
@@ -226,9 +228,10 @@ func TestProcessorSuccessWithMultipleQueues(t *testing.T) {
|
|||||||
// https://github.com/hibiken/asynq/issues/166
|
// https://github.com/hibiken/asynq/issues/166
|
||||||
func TestProcessTasksWithLargeNumberInPayload(t *testing.T) {
|
func TestProcessTasksWithLargeNumberInPayload(t *testing.T) {
|
||||||
r := setup(t)
|
r := setup(t)
|
||||||
|
defer r.Close()
|
||||||
rdbClient := rdb.NewRDB(r)
|
rdbClient := rdb.NewRDB(r)
|
||||||
|
|
||||||
m1 := h.NewTaskMessage("large_number", map[string]interface{}{"data": 111111111111111111})
|
m1 := h.NewTaskMessage("large_number", h.JSON(map[string]interface{}{"data": 111111111111111111}))
|
||||||
t1 := NewTask(m1.Type, m1.Payload)
|
t1 := NewTask(m1.Type, m1.Payload)
|
||||||
|
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
@@ -250,46 +253,29 @@ func TestProcessTasksWithLargeNumberInPayload(t *testing.T) {
|
|||||||
handler := func(ctx context.Context, task *Task) error {
|
handler := func(ctx context.Context, task *Task) error {
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
defer mu.Unlock()
|
defer mu.Unlock()
|
||||||
if data, err := task.Payload.GetInt("data"); err != nil {
|
var payload map[string]int
|
||||||
t.Errorf("coult not get data from payload: %v", err)
|
if err := json.Unmarshal(task.Payload(), &payload); err != nil {
|
||||||
} else {
|
t.Errorf("coult not decode payload: %v", err)
|
||||||
|
}
|
||||||
|
if data, ok := payload["data"]; ok {
|
||||||
t.Logf("data == %d", data)
|
t.Logf("data == %d", data)
|
||||||
|
} else {
|
||||||
|
t.Errorf("could not get data from payload")
|
||||||
}
|
}
|
||||||
processed = append(processed, task)
|
processed = append(processed, task)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
starting := make(chan *workerInfo)
|
p := newProcessorForTest(t, rdbClient, HandlerFunc(handler))
|
||||||
finished := make(chan *base.TaskMessage)
|
|
||||||
syncCh := make(chan *syncRequest)
|
|
||||||
done := make(chan struct{})
|
|
||||||
defer func() { close(done) }()
|
|
||||||
go fakeHeartbeater(starting, finished, done)
|
|
||||||
go fakeSyncer(syncCh, done)
|
|
||||||
p := newProcessor(processorParams{
|
|
||||||
logger: testLogger,
|
|
||||||
broker: rdbClient,
|
|
||||||
retryDelayFunc: DefaultRetryDelayFunc,
|
|
||||||
syncCh: syncCh,
|
|
||||||
cancelations: base.NewCancelations(),
|
|
||||||
concurrency: 10,
|
|
||||||
queues: defaultQueueConfig,
|
|
||||||
strictPriority: false,
|
|
||||||
errHandler: nil,
|
|
||||||
shutdownTimeout: defaultShutdownTimeout,
|
|
||||||
starting: starting,
|
|
||||||
finished: finished,
|
|
||||||
})
|
|
||||||
p.handler = HandlerFunc(handler)
|
|
||||||
|
|
||||||
p.start(&sync.WaitGroup{})
|
p.start(&sync.WaitGroup{})
|
||||||
time.Sleep(2 * time.Second) // wait for two second to allow all pending tasks to be processed.
|
time.Sleep(2 * time.Second) // wait for two second to allow all pending tasks to be processed.
|
||||||
if l := r.LLen(base.ActiveKey(base.DefaultQueueName)).Val(); l != 0 {
|
if l := r.LLen(context.Background(), base.ActiveKey(base.DefaultQueueName)).Val(); l != 0 {
|
||||||
t.Errorf("%q has %d tasks, want 0", base.ActiveKey(base.DefaultQueueName), l)
|
t.Errorf("%q has %d tasks, want 0", base.ActiveKey(base.DefaultQueueName), l)
|
||||||
}
|
}
|
||||||
p.terminate()
|
p.shutdown()
|
||||||
|
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
if diff := cmp.Diff(tc.wantProcessed, processed, sortTaskOpt, cmpopts.IgnoreUnexported(Payload{})); diff != "" {
|
if diff := cmp.Diff(tc.wantProcessed, processed, taskCmpOpts...); diff != "" {
|
||||||
t.Errorf("mismatch found in processed tasks; (-want, +got)\n%s", diff)
|
t.Errorf("mismatch found in processed tasks; (-want, +got)\n%s", diff)
|
||||||
}
|
}
|
||||||
mu.Unlock()
|
mu.Unlock()
|
||||||
@@ -298,6 +284,7 @@ func TestProcessTasksWithLargeNumberInPayload(t *testing.T) {
|
|||||||
|
|
||||||
func TestProcessorRetry(t *testing.T) {
|
func TestProcessorRetry(t *testing.T) {
|
||||||
r := setup(t)
|
r := setup(t)
|
||||||
|
defer r.Close()
|
||||||
rdbClient := rdb.NewRDB(r)
|
rdbClient := rdb.NewRDB(r)
|
||||||
|
|
||||||
m1 := h.NewTaskMessage("send_email", nil)
|
m1 := h.NewTaskMessage("send_email", nil)
|
||||||
@@ -308,66 +295,55 @@ func TestProcessorRetry(t *testing.T) {
|
|||||||
|
|
||||||
errMsg := "something went wrong"
|
errMsg := "something went wrong"
|
||||||
wrappedSkipRetry := fmt.Errorf("%s:%w", errMsg, SkipRetry)
|
wrappedSkipRetry := fmt.Errorf("%s:%w", errMsg, SkipRetry)
|
||||||
now := time.Now()
|
|
||||||
|
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
desc string // test description
|
desc string // test description
|
||||||
pending []*base.TaskMessage // initial default queue state
|
pending []*base.TaskMessage // initial default queue state
|
||||||
incoming []*base.TaskMessage // tasks to be enqueued during run
|
|
||||||
delay time.Duration // retry delay duration
|
delay time.Duration // retry delay duration
|
||||||
handler Handler // task handler
|
handler Handler // task handler
|
||||||
wait time.Duration // wait duration between starting and stopping processor for this test case
|
wait time.Duration // wait duration between starting and stopping processor for this test case
|
||||||
wantRetry []base.Z // tasks in retry queue at the end
|
wantErrMsg string // error message the task should record
|
||||||
|
wantRetry []*base.TaskMessage // tasks in retry queue at the end
|
||||||
wantArchived []*base.TaskMessage // tasks in archived queue at the end
|
wantArchived []*base.TaskMessage // tasks in archived queue at the end
|
||||||
wantErrCount int // number of times error handler should be called
|
wantErrCount int // number of times error handler should be called
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
desc: "Should automatically retry errored tasks",
|
desc: "Should automatically retry errored tasks",
|
||||||
pending: []*base.TaskMessage{m1, m2},
|
pending: []*base.TaskMessage{m1, m2, m3, m4},
|
||||||
incoming: []*base.TaskMessage{m3, m4},
|
delay: time.Minute,
|
||||||
delay: time.Minute,
|
|
||||||
handler: HandlerFunc(func(ctx context.Context, task *Task) error {
|
handler: HandlerFunc(func(ctx context.Context, task *Task) error {
|
||||||
return fmt.Errorf(errMsg)
|
return fmt.Errorf(errMsg)
|
||||||
}),
|
}),
|
||||||
wait: 2 * time.Second,
|
wait: 2 * time.Second,
|
||||||
wantRetry: []base.Z{
|
wantErrMsg: errMsg,
|
||||||
{Message: h.TaskMessageAfterRetry(*m2, errMsg), Score: now.Add(time.Minute).Unix()},
|
wantRetry: []*base.TaskMessage{m2, m3, m4},
|
||||||
{Message: h.TaskMessageAfterRetry(*m3, errMsg), Score: now.Add(time.Minute).Unix()},
|
wantArchived: []*base.TaskMessage{m1},
|
||||||
{Message: h.TaskMessageAfterRetry(*m4, errMsg), Score: now.Add(time.Minute).Unix()},
|
|
||||||
},
|
|
||||||
wantArchived: []*base.TaskMessage{h.TaskMessageWithError(*m1, errMsg)},
|
|
||||||
wantErrCount: 4,
|
wantErrCount: 4,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
desc: "Should skip retry errored tasks",
|
desc: "Should skip retry errored tasks",
|
||||||
pending: []*base.TaskMessage{m1, m2},
|
pending: []*base.TaskMessage{m1, m2},
|
||||||
incoming: []*base.TaskMessage{},
|
delay: time.Minute,
|
||||||
delay: time.Minute,
|
|
||||||
handler: HandlerFunc(func(ctx context.Context, task *Task) error {
|
handler: HandlerFunc(func(ctx context.Context, task *Task) error {
|
||||||
return SkipRetry // return SkipRetry without wrapping
|
return SkipRetry // return SkipRetry without wrapping
|
||||||
}),
|
}),
|
||||||
wait: 2 * time.Second,
|
wait: 2 * time.Second,
|
||||||
wantRetry: []base.Z{},
|
wantErrMsg: SkipRetry.Error(),
|
||||||
wantArchived: []*base.TaskMessage{
|
wantRetry: []*base.TaskMessage{},
|
||||||
h.TaskMessageWithError(*m1, SkipRetry.Error()),
|
wantArchived: []*base.TaskMessage{m1, m2},
|
||||||
h.TaskMessageWithError(*m2, SkipRetry.Error()),
|
|
||||||
},
|
|
||||||
wantErrCount: 2, // ErrorHandler should still be called with SkipRetry error
|
wantErrCount: 2, // ErrorHandler should still be called with SkipRetry error
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
desc: "Should skip retry errored tasks (with error wrapping)",
|
desc: "Should skip retry errored tasks (with error wrapping)",
|
||||||
pending: []*base.TaskMessage{m1, m2},
|
pending: []*base.TaskMessage{m1, m2},
|
||||||
incoming: []*base.TaskMessage{},
|
delay: time.Minute,
|
||||||
delay: time.Minute,
|
|
||||||
handler: HandlerFunc(func(ctx context.Context, task *Task) error {
|
handler: HandlerFunc(func(ctx context.Context, task *Task) error {
|
||||||
return wrappedSkipRetry
|
return wrappedSkipRetry
|
||||||
}),
|
}),
|
||||||
wait: 2 * time.Second,
|
wait: 2 * time.Second,
|
||||||
wantRetry: []base.Z{},
|
wantErrMsg: wrappedSkipRetry.Error(),
|
||||||
wantArchived: []*base.TaskMessage{
|
wantRetry: []*base.TaskMessage{},
|
||||||
h.TaskMessageWithError(*m1, wrappedSkipRetry.Error()),
|
wantArchived: []*base.TaskMessage{m1, m2},
|
||||||
h.TaskMessageWithError(*m2, wrappedSkipRetry.Error()),
|
|
||||||
},
|
|
||||||
wantErrCount: 2, // ErrorHandler should still be called with SkipRetry error
|
wantErrCount: 2, // ErrorHandler should still be called with SkipRetry error
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -389,50 +365,43 @@ func TestProcessorRetry(t *testing.T) {
|
|||||||
defer mu.Unlock()
|
defer mu.Unlock()
|
||||||
n++
|
n++
|
||||||
}
|
}
|
||||||
starting := make(chan *workerInfo)
|
p := newProcessorForTest(t, rdbClient, tc.handler)
|
||||||
finished := make(chan *base.TaskMessage)
|
p.errHandler = ErrorHandlerFunc(errHandler)
|
||||||
done := make(chan struct{})
|
p.retryDelayFunc = delayFunc
|
||||||
defer func() { close(done) }()
|
|
||||||
go fakeHeartbeater(starting, finished, done)
|
|
||||||
p := newProcessor(processorParams{
|
|
||||||
logger: testLogger,
|
|
||||||
broker: rdbClient,
|
|
||||||
retryDelayFunc: delayFunc,
|
|
||||||
syncCh: nil,
|
|
||||||
cancelations: base.NewCancelations(),
|
|
||||||
concurrency: 10,
|
|
||||||
queues: defaultQueueConfig,
|
|
||||||
strictPriority: false,
|
|
||||||
errHandler: ErrorHandlerFunc(errHandler),
|
|
||||||
shutdownTimeout: defaultShutdownTimeout,
|
|
||||||
starting: starting,
|
|
||||||
finished: finished,
|
|
||||||
})
|
|
||||||
p.handler = tc.handler
|
|
||||||
|
|
||||||
p.start(&sync.WaitGroup{})
|
p.start(&sync.WaitGroup{})
|
||||||
for _, msg := range tc.incoming {
|
runTime := time.Now() // time when processor is running
|
||||||
err := rdbClient.Enqueue(msg)
|
time.Sleep(tc.wait) // FIXME: This makes test flaky.
|
||||||
if err != nil {
|
p.shutdown()
|
||||||
p.terminate()
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
time.Sleep(tc.wait) // FIXME: This makes test flaky.
|
|
||||||
p.terminate()
|
|
||||||
|
|
||||||
cmpOpt := h.EquateInt64Approx(1) // allow up to a second difference in zset score
|
cmpOpt := h.EquateInt64Approx(int64(tc.wait.Seconds())) // allow up to a wait-second difference in zset score
|
||||||
gotRetry := h.GetRetryEntries(t, r, base.DefaultQueueName)
|
gotRetry := h.GetRetryEntries(t, r, base.DefaultQueueName)
|
||||||
if diff := cmp.Diff(tc.wantRetry, gotRetry, h.SortZSetEntryOpt, cmpOpt); diff != "" {
|
var wantRetry []base.Z // Note: construct wantRetry here since `LastFailedAt` and ZSCORE is relative to each test run.
|
||||||
|
for _, msg := range tc.wantRetry {
|
||||||
|
wantRetry = append(wantRetry,
|
||||||
|
base.Z{
|
||||||
|
Message: h.TaskMessageAfterRetry(*msg, tc.wantErrMsg, runTime),
|
||||||
|
Score: runTime.Add(tc.delay).Unix(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if diff := cmp.Diff(wantRetry, gotRetry, h.SortZSetEntryOpt, cmpOpt); diff != "" {
|
||||||
t.Errorf("%s: mismatch found in %q after running processor; (-want, +got)\n%s", tc.desc, base.RetryKey(base.DefaultQueueName), diff)
|
t.Errorf("%s: mismatch found in %q after running processor; (-want, +got)\n%s", tc.desc, base.RetryKey(base.DefaultQueueName), diff)
|
||||||
}
|
}
|
||||||
|
|
||||||
gotDead := h.GetArchivedMessages(t, r, base.DefaultQueueName)
|
gotArchived := h.GetArchivedEntries(t, r, base.DefaultQueueName)
|
||||||
if diff := cmp.Diff(tc.wantArchived, gotDead, h.SortMsgOpt); diff != "" {
|
var wantArchived []base.Z // Note: construct wantArchived here since `LastFailedAt` and ZSCORE is relative to each test run.
|
||||||
|
for _, msg := range tc.wantArchived {
|
||||||
|
wantArchived = append(wantArchived,
|
||||||
|
base.Z{
|
||||||
|
Message: h.TaskMessageWithError(*msg, tc.wantErrMsg, runTime),
|
||||||
|
Score: runTime.Unix(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if diff := cmp.Diff(wantArchived, gotArchived, h.SortZSetEntryOpt, cmpOpt); diff != "" {
|
||||||
t.Errorf("%s: mismatch found in %q after running processor; (-want, +got)\n%s", tc.desc, base.ArchivedKey(base.DefaultQueueName), diff)
|
t.Errorf("%s: mismatch found in %q after running processor; (-want, +got)\n%s", tc.desc, base.ArchivedKey(base.DefaultQueueName), diff)
|
||||||
}
|
}
|
||||||
|
|
||||||
if l := r.LLen(base.ActiveKey(base.DefaultQueueName)).Val(); l != 0 {
|
if l := r.LLen(context.Background(), base.ActiveKey(base.DefaultQueueName)).Val(); l != 0 {
|
||||||
t.Errorf("%s: %q has %d tasks, want 0", base.ActiveKey(base.DefaultQueueName), tc.desc, l)
|
t.Errorf("%s: %q has %d tasks, want 0", base.ActiveKey(base.DefaultQueueName), tc.desc, l)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -442,6 +411,180 @@ func TestProcessorRetry(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestProcessorMarkAsComplete(t *testing.T) {
|
||||||
|
r := setup(t)
|
||||||
|
defer r.Close()
|
||||||
|
rdbClient := rdb.NewRDB(r)
|
||||||
|
|
||||||
|
msg1 := h.NewTaskMessage("one", nil)
|
||||||
|
msg2 := h.NewTaskMessage("two", nil)
|
||||||
|
msg3 := h.NewTaskMessageWithQueue("three", nil, "custom")
|
||||||
|
msg1.Retention = 3600
|
||||||
|
msg3.Retention = 7200
|
||||||
|
|
||||||
|
handler := func(ctx context.Context, task *Task) error { return nil }
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
pending map[string][]*base.TaskMessage
|
||||||
|
completed map[string][]base.Z
|
||||||
|
queueCfg map[string]int
|
||||||
|
wantPending map[string][]*base.TaskMessage
|
||||||
|
wantCompleted func(completedAt time.Time) map[string][]base.Z
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
pending: map[string][]*base.TaskMessage{
|
||||||
|
"default": {msg1, msg2},
|
||||||
|
"custom": {msg3},
|
||||||
|
},
|
||||||
|
completed: map[string][]base.Z{
|
||||||
|
"default": {},
|
||||||
|
"custom": {},
|
||||||
|
},
|
||||||
|
queueCfg: map[string]int{
|
||||||
|
"default": 1,
|
||||||
|
"custom": 1,
|
||||||
|
},
|
||||||
|
wantPending: map[string][]*base.TaskMessage{
|
||||||
|
"default": {},
|
||||||
|
"custom": {},
|
||||||
|
},
|
||||||
|
wantCompleted: func(completedAt time.Time) map[string][]base.Z {
|
||||||
|
return map[string][]base.Z{
|
||||||
|
"default": {{Message: h.TaskMessageWithCompletedAt(*msg1, completedAt), Score: completedAt.Unix() + msg1.Retention}},
|
||||||
|
"custom": {{Message: h.TaskMessageWithCompletedAt(*msg3, completedAt), Score: completedAt.Unix() + msg3.Retention}},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
h.FlushDB(t, r)
|
||||||
|
h.SeedAllPendingQueues(t, r, tc.pending)
|
||||||
|
h.SeedAllCompletedQueues(t, r, tc.completed)
|
||||||
|
|
||||||
|
p := newProcessorForTest(t, rdbClient, HandlerFunc(handler))
|
||||||
|
p.queueConfig = tc.queueCfg
|
||||||
|
|
||||||
|
p.start(&sync.WaitGroup{})
|
||||||
|
runTime := time.Now() // time when processor is running
|
||||||
|
time.Sleep(2 * time.Second)
|
||||||
|
p.shutdown()
|
||||||
|
|
||||||
|
for qname, want := range tc.wantPending {
|
||||||
|
gotPending := h.GetPendingMessages(t, r, qname)
|
||||||
|
if diff := cmp.Diff(want, gotPending, cmpopts.EquateEmpty()); diff != "" {
|
||||||
|
t.Errorf("diff found in %q pending set; want=%v, got=%v\n%s", qname, want, gotPending, diff)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for qname, want := range tc.wantCompleted(runTime) {
|
||||||
|
gotCompleted := h.GetCompletedEntries(t, r, qname)
|
||||||
|
if diff := cmp.Diff(want, gotCompleted, cmpopts.EquateEmpty()); diff != "" {
|
||||||
|
t.Errorf("diff found in %q completed set; want=%v, got=%v\n%s", qname, want, gotCompleted, diff)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test a scenario where the worker server cannot communicate with redis due to a network failure
|
||||||
|
// and the lease expires
|
||||||
|
func TestProcessorWithExpiredLease(t *testing.T) {
|
||||||
|
r := setup(t)
|
||||||
|
defer r.Close()
|
||||||
|
rdbClient := rdb.NewRDB(r)
|
||||||
|
|
||||||
|
m1 := h.NewTaskMessage("task1", nil)
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
pending []*base.TaskMessage
|
||||||
|
handler Handler
|
||||||
|
wantErrCount int
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
pending: []*base.TaskMessage{m1},
|
||||||
|
handler: HandlerFunc(func(ctx context.Context, task *Task) error {
|
||||||
|
// make sure the task processing time exceeds lease duration
|
||||||
|
// to test expired lease.
|
||||||
|
time.Sleep(rdb.LeaseDuration + 10*time.Second)
|
||||||
|
return nil
|
||||||
|
}),
|
||||||
|
wantErrCount: 1, // ErrorHandler should still be called with ErrLeaseExpired
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
h.FlushDB(t, r)
|
||||||
|
h.SeedPendingQueue(t, r, tc.pending, base.DefaultQueueName)
|
||||||
|
|
||||||
|
starting := make(chan *workerInfo)
|
||||||
|
finished := make(chan *base.TaskMessage)
|
||||||
|
syncCh := make(chan *syncRequest)
|
||||||
|
done := make(chan struct{})
|
||||||
|
t.Cleanup(func() { close(done) })
|
||||||
|
// fake heartbeater which notifies lease expiration
|
||||||
|
go func() {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case w := <-starting:
|
||||||
|
// simulate expiration by resetting to some time in the past
|
||||||
|
w.lease.Reset(time.Now().Add(-5 * time.Second))
|
||||||
|
if !w.lease.NotifyExpiration() {
|
||||||
|
panic("Failed to notifiy lease expiration")
|
||||||
|
}
|
||||||
|
case <-finished:
|
||||||
|
// do nothing
|
||||||
|
case <-done:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
go fakeSyncer(syncCh, done)
|
||||||
|
p := newProcessor(processorParams{
|
||||||
|
logger: testLogger,
|
||||||
|
broker: rdbClient,
|
||||||
|
baseCtxFn: context.Background,
|
||||||
|
taskCheckInterval: defaultTaskCheckInterval,
|
||||||
|
retryDelayFunc: DefaultRetryDelayFunc,
|
||||||
|
isFailureFunc: defaultIsFailureFunc,
|
||||||
|
syncCh: syncCh,
|
||||||
|
cancelations: base.NewCancelations(),
|
||||||
|
concurrency: 10,
|
||||||
|
queues: defaultQueueConfig,
|
||||||
|
strictPriority: false,
|
||||||
|
errHandler: nil,
|
||||||
|
shutdownTimeout: defaultShutdownTimeout,
|
||||||
|
starting: starting,
|
||||||
|
finished: finished,
|
||||||
|
})
|
||||||
|
p.handler = tc.handler
|
||||||
|
var (
|
||||||
|
mu sync.Mutex // guards n and errs
|
||||||
|
n int // number of times error handler is called
|
||||||
|
errs []error // error passed to error handler
|
||||||
|
)
|
||||||
|
p.errHandler = ErrorHandlerFunc(func(ctx context.Context, t *Task, err error) {
|
||||||
|
mu.Lock()
|
||||||
|
defer mu.Unlock()
|
||||||
|
n++
|
||||||
|
errs = append(errs, err)
|
||||||
|
})
|
||||||
|
|
||||||
|
p.start(&sync.WaitGroup{})
|
||||||
|
time.Sleep(4 * time.Second)
|
||||||
|
p.shutdown()
|
||||||
|
|
||||||
|
if n != tc.wantErrCount {
|
||||||
|
t.Errorf("Unexpected number of error count: got %d, want %d", n, tc.wantErrCount)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for i := 0; i < tc.wantErrCount; i++ {
|
||||||
|
if !errors.Is(errs[i], ErrLeaseExpired) {
|
||||||
|
t.Errorf("Unexpected error was passed to ErrorHandler: got %v want %v", errs[i], ErrLeaseExpired)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestProcessorQueues(t *testing.T) {
|
func TestProcessorQueues(t *testing.T) {
|
||||||
sortOpt := cmp.Transformer("SortStrings", func(in []string) []string {
|
sortOpt := cmp.Transformer("SortStrings", func(in []string) []string {
|
||||||
out := append([]string(nil), in...) // Copy input to avoid mutating it
|
out := append([]string(nil), in...) // Copy input to avoid mutating it
|
||||||
@@ -470,25 +613,10 @@ func TestProcessorQueues(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, tc := range tests {
|
for _, tc := range tests {
|
||||||
starting := make(chan *workerInfo)
|
// Note: rdb and handler not needed for this test.
|
||||||
finished := make(chan *base.TaskMessage)
|
p := newProcessorForTest(t, nil, nil)
|
||||||
done := make(chan struct{})
|
p.queueConfig = tc.queueCfg
|
||||||
defer func() { close(done) }()
|
|
||||||
go fakeHeartbeater(starting, finished, done)
|
|
||||||
p := newProcessor(processorParams{
|
|
||||||
logger: testLogger,
|
|
||||||
broker: nil,
|
|
||||||
retryDelayFunc: DefaultRetryDelayFunc,
|
|
||||||
syncCh: nil,
|
|
||||||
cancelations: base.NewCancelations(),
|
|
||||||
concurrency: 10,
|
|
||||||
queues: tc.queueCfg,
|
|
||||||
strictPriority: false,
|
|
||||||
errHandler: nil,
|
|
||||||
shutdownTimeout: defaultShutdownTimeout,
|
|
||||||
starting: starting,
|
|
||||||
finished: finished,
|
|
||||||
})
|
|
||||||
got := p.queues()
|
got := p.queues()
|
||||||
if diff := cmp.Diff(tc.want, got, sortOpt); diff != "" {
|
if diff := cmp.Diff(tc.want, got, sortOpt); diff != "" {
|
||||||
t.Errorf("with queue config: %v\n(*processor).queues() = %v, want %v\n(-want,+got):\n%s",
|
t.Errorf("with queue config: %v\n(*processor).queues() = %v, want %v\n(-want,+got):\n%s",
|
||||||
@@ -567,18 +695,21 @@ func TestProcessorWithStrictPriority(t *testing.T) {
|
|||||||
go fakeHeartbeater(starting, finished, done)
|
go fakeHeartbeater(starting, finished, done)
|
||||||
go fakeSyncer(syncCh, done)
|
go fakeSyncer(syncCh, done)
|
||||||
p := newProcessor(processorParams{
|
p := newProcessor(processorParams{
|
||||||
logger: testLogger,
|
logger: testLogger,
|
||||||
broker: rdbClient,
|
broker: rdbClient,
|
||||||
retryDelayFunc: DefaultRetryDelayFunc,
|
baseCtxFn: context.Background,
|
||||||
syncCh: syncCh,
|
taskCheckInterval: defaultTaskCheckInterval,
|
||||||
cancelations: base.NewCancelations(),
|
retryDelayFunc: DefaultRetryDelayFunc,
|
||||||
concurrency: 1, // Set concurrency to 1 to make sure tasks are processed one at a time.
|
isFailureFunc: defaultIsFailureFunc,
|
||||||
queues: queueCfg,
|
syncCh: syncCh,
|
||||||
strictPriority: true,
|
cancelations: base.NewCancelations(),
|
||||||
errHandler: nil,
|
concurrency: 1, // Set concurrency to 1 to make sure tasks are processed one at a time.
|
||||||
shutdownTimeout: defaultShutdownTimeout,
|
queues: queueCfg,
|
||||||
starting: starting,
|
strictPriority: true,
|
||||||
finished: finished,
|
errHandler: nil,
|
||||||
|
shutdownTimeout: defaultShutdownTimeout,
|
||||||
|
starting: starting,
|
||||||
|
finished: finished,
|
||||||
})
|
})
|
||||||
p.handler = HandlerFunc(handler)
|
p.handler = HandlerFunc(handler)
|
||||||
|
|
||||||
@@ -586,13 +717,13 @@ func TestProcessorWithStrictPriority(t *testing.T) {
|
|||||||
time.Sleep(tc.wait)
|
time.Sleep(tc.wait)
|
||||||
// Make sure no tasks are stuck in active list.
|
// Make sure no tasks are stuck in active list.
|
||||||
for _, qname := range tc.queues {
|
for _, qname := range tc.queues {
|
||||||
if l := r.LLen(base.ActiveKey(qname)).Val(); l != 0 {
|
if l := r.LLen(context.Background(), base.ActiveKey(qname)).Val(); l != 0 {
|
||||||
t.Errorf("%q has %d tasks, want 0", base.ActiveKey(qname), l)
|
t.Errorf("%q has %d tasks, want 0", base.ActiveKey(qname), l)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
p.terminate()
|
p.shutdown()
|
||||||
|
|
||||||
if diff := cmp.Diff(tc.wantProcessed, processed, cmp.AllowUnexported(Payload{})); diff != "" {
|
if diff := cmp.Diff(tc.wantProcessed, processed, taskCmpOpts...); diff != "" {
|
||||||
t.Errorf("mismatch found in processed tasks; (-want, +got)\n%s", diff)
|
t.Errorf("mismatch found in processed tasks; (-want, +got)\n%s", diff)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -611,7 +742,7 @@ func TestProcessorPerform(t *testing.T) {
|
|||||||
handler: func(ctx context.Context, t *Task) error {
|
handler: func(ctx context.Context, t *Task) error {
|
||||||
return nil
|
return nil
|
||||||
},
|
},
|
||||||
task: NewTask("gen_thumbnail", map[string]interface{}{"src": "some/img/path"}),
|
task: NewTask("gen_thumbnail", h.JSON(map[string]interface{}{"src": "some/img/path"})),
|
||||||
wantErr: false,
|
wantErr: false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -619,7 +750,7 @@ func TestProcessorPerform(t *testing.T) {
|
|||||||
handler: func(ctx context.Context, t *Task) error {
|
handler: func(ctx context.Context, t *Task) error {
|
||||||
return fmt.Errorf("something went wrong")
|
return fmt.Errorf("something went wrong")
|
||||||
},
|
},
|
||||||
task: NewTask("gen_thumbnail", map[string]interface{}{"src": "some/img/path"}),
|
task: NewTask("gen_thumbnail", h.JSON(map[string]interface{}{"src": "some/img/path"})),
|
||||||
wantErr: true,
|
wantErr: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -627,16 +758,13 @@ func TestProcessorPerform(t *testing.T) {
|
|||||||
handler: func(ctx context.Context, t *Task) error {
|
handler: func(ctx context.Context, t *Task) error {
|
||||||
panic("something went terribly wrong")
|
panic("something went terribly wrong")
|
||||||
},
|
},
|
||||||
task: NewTask("gen_thumbnail", map[string]interface{}{"src": "some/img/path"}),
|
task: NewTask("gen_thumbnail", h.JSON(map[string]interface{}{"src": "some/img/path"})),
|
||||||
wantErr: true,
|
wantErr: true,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
// Note: We don't need to fully initialize the processor since we are only testing
|
// Note: We don't need to fully initialized the processor since we are only testing
|
||||||
// perform method.
|
// perform method.
|
||||||
p := newProcessor(processorParams{
|
p := newProcessorForTest(t, nil, nil)
|
||||||
logger: testLogger,
|
|
||||||
queues: defaultQueueConfig,
|
|
||||||
})
|
|
||||||
|
|
||||||
for _, tc := range tests {
|
for _, tc := range tests {
|
||||||
p.handler = tc.handler
|
p.handler = tc.handler
|
||||||
@@ -731,3 +859,111 @@ func TestNormalizeQueues(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestProcessorComputeDeadline(t *testing.T) {
|
||||||
|
now := time.Now()
|
||||||
|
p := processor{
|
||||||
|
logger: log.NewLogger(nil),
|
||||||
|
clock: timeutil.NewSimulatedClock(now),
|
||||||
|
}
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
desc string
|
||||||
|
msg *base.TaskMessage
|
||||||
|
want time.Time
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
desc: "message with only timeout specified",
|
||||||
|
msg: &base.TaskMessage{
|
||||||
|
Timeout: int64((30 * time.Minute).Seconds()),
|
||||||
|
},
|
||||||
|
want: now.Add(30 * time.Minute),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "message with only deadline specified",
|
||||||
|
msg: &base.TaskMessage{
|
||||||
|
Deadline: now.Add(24 * time.Hour).Unix(),
|
||||||
|
},
|
||||||
|
want: now.Add(24 * time.Hour),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "message with both timeout and deadline set (now+timeout < deadline)",
|
||||||
|
msg: &base.TaskMessage{
|
||||||
|
Deadline: now.Add(24 * time.Hour).Unix(),
|
||||||
|
Timeout: int64((30 * time.Minute).Seconds()),
|
||||||
|
},
|
||||||
|
want: now.Add(30 * time.Minute),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "message with both timeout and deadline set (now+timeout > deadline)",
|
||||||
|
msg: &base.TaskMessage{
|
||||||
|
Deadline: now.Add(10 * time.Minute).Unix(),
|
||||||
|
Timeout: int64((30 * time.Minute).Seconds()),
|
||||||
|
},
|
||||||
|
want: now.Add(10 * time.Minute),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "message with both timeout and deadline set (now+timeout == deadline)",
|
||||||
|
msg: &base.TaskMessage{
|
||||||
|
Deadline: now.Add(30 * time.Minute).Unix(),
|
||||||
|
Timeout: int64((30 * time.Minute).Seconds()),
|
||||||
|
},
|
||||||
|
want: now.Add(30 * time.Minute),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "message without timeout and deadline",
|
||||||
|
msg: &base.TaskMessage{},
|
||||||
|
want: now.Add(defaultTimeout),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
got := p.computeDeadline(tc.msg)
|
||||||
|
// Compare the Unix epoch with seconds granularity
|
||||||
|
if got.Unix() != tc.want.Unix() {
|
||||||
|
t.Errorf("%s: got=%v, want=%v", tc.desc, got.Unix(), tc.want.Unix())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReturnPanicError(t *testing.T) {
|
||||||
|
|
||||||
|
task := NewTask("gen_thumbnail", h.JSON(map[string]interface{}{"src": "some/img/path"}))
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
handler HandlerFunc
|
||||||
|
IsPanicError bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "should return panic error when occurred panic recovery",
|
||||||
|
handler: func(ctx context.Context, t *Task) error {
|
||||||
|
panic("something went terribly wrong")
|
||||||
|
},
|
||||||
|
IsPanicError: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "should return normal error when don't occur panic recovery",
|
||||||
|
handler: func(ctx context.Context, t *Task) error {
|
||||||
|
return fmt.Errorf("something went terribly wrong")
|
||||||
|
},
|
||||||
|
IsPanicError: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
p := processor{
|
||||||
|
logger: log.NewLogger(nil),
|
||||||
|
handler: tc.handler,
|
||||||
|
}
|
||||||
|
got := p.perform(context.Background(), task)
|
||||||
|
if tc.IsPanicError != IsPanicError(got) {
|
||||||
|
t.Errorf("%s: got=%t, want=%t", tc.name, IsPanicError(got), tc.IsPanicError)
|
||||||
|
}
|
||||||
|
if tc.IsPanicError && !strings.HasPrefix(got.Error(), "panic error cause by:") {
|
||||||
|
t.Error("wrong text msg for panic error")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
75
recoverer.go
75
recoverer.go
@@ -5,11 +5,12 @@
|
|||||||
package asynq
|
package asynq
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"context"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/hibiken/asynq/internal/base"
|
"github.com/hibiken/asynq/internal/base"
|
||||||
|
"github.com/hibiken/asynq/internal/errors"
|
||||||
"github.com/hibiken/asynq/internal/log"
|
"github.com/hibiken/asynq/internal/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -17,6 +18,7 @@ type recoverer struct {
|
|||||||
logger *log.Logger
|
logger *log.Logger
|
||||||
broker base.Broker
|
broker base.Broker
|
||||||
retryDelayFunc RetryDelayFunc
|
retryDelayFunc RetryDelayFunc
|
||||||
|
isFailureFunc func(error) bool
|
||||||
|
|
||||||
// channel to communicate back to the long running "recoverer" goroutine.
|
// channel to communicate back to the long running "recoverer" goroutine.
|
||||||
done chan struct{}
|
done chan struct{}
|
||||||
@@ -34,6 +36,7 @@ type recovererParams struct {
|
|||||||
queues []string
|
queues []string
|
||||||
interval time.Duration
|
interval time.Duration
|
||||||
retryDelayFunc RetryDelayFunc
|
retryDelayFunc RetryDelayFunc
|
||||||
|
isFailureFunc func(error) bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func newRecoverer(params recovererParams) *recoverer {
|
func newRecoverer(params recovererParams) *recoverer {
|
||||||
@@ -44,10 +47,11 @@ func newRecoverer(params recovererParams) *recoverer {
|
|||||||
queues: params.queues,
|
queues: params.queues,
|
||||||
interval: params.interval,
|
interval: params.interval,
|
||||||
retryDelayFunc: params.retryDelayFunc,
|
retryDelayFunc: params.retryDelayFunc,
|
||||||
|
isFailureFunc: params.isFailureFunc,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *recoverer) terminate() {
|
func (r *recoverer) shutdown() {
|
||||||
r.logger.Debug("Recoverer shutting down...")
|
r.logger.Debug("Recoverer shutting down...")
|
||||||
// Signal the recoverer goroutine to stop polling.
|
// Signal the recoverer goroutine to stop polling.
|
||||||
r.done <- struct{}{}
|
r.done <- struct{}{}
|
||||||
@@ -57,6 +61,7 @@ func (r *recoverer) start(wg *sync.WaitGroup) {
|
|||||||
wg.Add(1)
|
wg.Add(1)
|
||||||
go func() {
|
go func() {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
|
r.recover()
|
||||||
timer := time.NewTimer(r.interval)
|
timer := time.NewTimer(r.interval)
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
@@ -65,37 +70,57 @@ func (r *recoverer) start(wg *sync.WaitGroup) {
|
|||||||
timer.Stop()
|
timer.Stop()
|
||||||
return
|
return
|
||||||
case <-timer.C:
|
case <-timer.C:
|
||||||
// Get all tasks which have expired 30 seconds ago or earlier.
|
r.recover()
|
||||||
deadline := time.Now().Add(-30 * time.Second)
|
timer.Reset(r.interval)
|
||||||
msgs, err := r.broker.ListDeadlineExceeded(deadline, r.queues...)
|
|
||||||
if err != nil {
|
|
||||||
r.logger.Warn("recoverer: could not list deadline exceeded tasks")
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
const errMsg = "deadline exceeded" // TODO: better error message
|
|
||||||
for _, msg := range msgs {
|
|
||||||
if msg.Retried >= msg.Retry {
|
|
||||||
r.archive(msg, errMsg)
|
|
||||||
} else {
|
|
||||||
r.retry(msg, errMsg)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *recoverer) retry(msg *base.TaskMessage, errMsg string) {
|
// ErrLeaseExpired error indicates that the task failed because the worker working on the task
|
||||||
delay := r.retryDelayFunc(msg.Retried, fmt.Errorf(errMsg), NewTask(msg.Type, msg.Payload))
|
// could not extend its lease due to missing heartbeats. The worker may have crashed or got cutoff from the network.
|
||||||
retryAt := time.Now().Add(delay)
|
var ErrLeaseExpired = errors.New("asynq: task lease expired")
|
||||||
if err := r.broker.Retry(msg, retryAt, errMsg); err != nil {
|
|
||||||
r.logger.Warnf("recoverer: could not retry deadline exceeded task: %v", err)
|
func (r *recoverer) recover() {
|
||||||
|
r.recoverLeaseExpiredTasks()
|
||||||
|
r.recoverStaleAggregationSets()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *recoverer) recoverLeaseExpiredTasks() {
|
||||||
|
// Get all tasks which have expired 30 seconds ago or earlier to accommodate certain amount of clock skew.
|
||||||
|
cutoff := time.Now().Add(-30 * time.Second)
|
||||||
|
msgs, err := r.broker.ListLeaseExpired(cutoff, r.queues...)
|
||||||
|
if err != nil {
|
||||||
|
r.logger.Warnf("recoverer: could not list lease expired tasks: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, msg := range msgs {
|
||||||
|
if msg.Retried >= msg.Retry {
|
||||||
|
r.archive(msg, ErrLeaseExpired)
|
||||||
|
} else {
|
||||||
|
r.retry(msg, ErrLeaseExpired)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *recoverer) archive(msg *base.TaskMessage, errMsg string) {
|
func (r *recoverer) recoverStaleAggregationSets() {
|
||||||
if err := r.broker.Archive(msg, errMsg); err != nil {
|
for _, qname := range r.queues {
|
||||||
|
if err := r.broker.ReclaimStaleAggregationSets(qname); err != nil {
|
||||||
|
r.logger.Warnf("recoverer: could not reclaim stale aggregation sets in queue %q: %v", qname, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *recoverer) retry(msg *base.TaskMessage, err error) {
|
||||||
|
delay := r.retryDelayFunc(msg.Retried, err, NewTask(msg.Type, msg.Payload))
|
||||||
|
retryAt := time.Now().Add(delay)
|
||||||
|
if err := r.broker.Retry(context.Background(), msg, retryAt, err.Error(), r.isFailureFunc(err)); err != nil {
|
||||||
|
r.logger.Warnf("recoverer: could not retry lease expired task: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *recoverer) archive(msg *base.TaskMessage, err error) {
|
||||||
|
if err := r.broker.Archive(context.Background(), msg, err.Error()); err != nil {
|
||||||
r.logger.Warnf("recoverer: could not move task to archive: %v", err)
|
r.logger.Warnf("recoverer: could not move task to archive: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,9 +10,9 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/google/go-cmp/cmp"
|
"github.com/google/go-cmp/cmp"
|
||||||
h "github.com/hibiken/asynq/internal/asynqtest"
|
|
||||||
"github.com/hibiken/asynq/internal/base"
|
"github.com/hibiken/asynq/internal/base"
|
||||||
"github.com/hibiken/asynq/internal/rdb"
|
"github.com/hibiken/asynq/internal/rdb"
|
||||||
|
h "github.com/hibiken/asynq/internal/testutil"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestRecoverer(t *testing.T) {
|
func TestRecoverer(t *testing.T) {
|
||||||
@@ -27,29 +27,25 @@ func TestRecoverer(t *testing.T) {
|
|||||||
t4.Retried = t4.Retry // t4 has reached its max retry count
|
t4.Retried = t4.Retry // t4 has reached its max retry count
|
||||||
|
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
oneHourFromNow := now.Add(1 * time.Hour)
|
|
||||||
fiveMinutesFromNow := now.Add(5 * time.Minute)
|
|
||||||
fiveMinutesAgo := now.Add(-5 * time.Minute)
|
|
||||||
oneHourAgo := now.Add(-1 * time.Hour)
|
|
||||||
|
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
desc string
|
desc string
|
||||||
inProgress map[string][]*base.TaskMessage
|
active map[string][]*base.TaskMessage
|
||||||
deadlines map[string][]base.Z
|
lease map[string][]base.Z
|
||||||
retry map[string][]base.Z
|
retry map[string][]base.Z
|
||||||
archived map[string][]base.Z
|
archived map[string][]base.Z
|
||||||
wantActive map[string][]*base.TaskMessage
|
wantActive map[string][]*base.TaskMessage
|
||||||
wantDeadlines map[string][]base.Z
|
wantLease map[string][]base.Z
|
||||||
wantRetry map[string][]*base.TaskMessage
|
wantRetry map[string][]*base.TaskMessage
|
||||||
wantArchived map[string][]*base.TaskMessage
|
wantArchived map[string][]*base.TaskMessage
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
desc: "with one active task",
|
desc: "with one active task",
|
||||||
inProgress: map[string][]*base.TaskMessage{
|
active: map[string][]*base.TaskMessage{
|
||||||
"default": {t1},
|
"default": {t1},
|
||||||
},
|
},
|
||||||
deadlines: map[string][]base.Z{
|
lease: map[string][]base.Z{
|
||||||
"default": {{Message: t1, Score: fiveMinutesAgo.Unix()}},
|
"default": {{Message: t1, Score: now.Add(-1 * time.Minute).Unix()}},
|
||||||
},
|
},
|
||||||
retry: map[string][]base.Z{
|
retry: map[string][]base.Z{
|
||||||
"default": {},
|
"default": {},
|
||||||
@@ -60,11 +56,11 @@ func TestRecoverer(t *testing.T) {
|
|||||||
wantActive: map[string][]*base.TaskMessage{
|
wantActive: map[string][]*base.TaskMessage{
|
||||||
"default": {},
|
"default": {},
|
||||||
},
|
},
|
||||||
wantDeadlines: map[string][]base.Z{
|
wantLease: map[string][]base.Z{
|
||||||
"default": {},
|
"default": {},
|
||||||
},
|
},
|
||||||
wantRetry: map[string][]*base.TaskMessage{
|
wantRetry: map[string][]*base.TaskMessage{
|
||||||
"default": {h.TaskMessageAfterRetry(*t1, "deadline exceeded")},
|
"default": {t1},
|
||||||
},
|
},
|
||||||
wantArchived: map[string][]*base.TaskMessage{
|
wantArchived: map[string][]*base.TaskMessage{
|
||||||
"default": {},
|
"default": {},
|
||||||
@@ -72,12 +68,12 @@ func TestRecoverer(t *testing.T) {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
desc: "with a task with max-retry reached",
|
desc: "with a task with max-retry reached",
|
||||||
inProgress: map[string][]*base.TaskMessage{
|
active: map[string][]*base.TaskMessage{
|
||||||
"default": {t4},
|
"default": {t4},
|
||||||
"critical": {},
|
"critical": {},
|
||||||
},
|
},
|
||||||
deadlines: map[string][]base.Z{
|
lease: map[string][]base.Z{
|
||||||
"default": {{Message: t4, Score: fiveMinutesAgo.Unix()}},
|
"default": {{Message: t4, Score: now.Add(-40 * time.Second).Unix()}},
|
||||||
"critical": {},
|
"critical": {},
|
||||||
},
|
},
|
||||||
retry: map[string][]base.Z{
|
retry: map[string][]base.Z{
|
||||||
@@ -92,7 +88,7 @@ func TestRecoverer(t *testing.T) {
|
|||||||
"default": {},
|
"default": {},
|
||||||
"critical": {},
|
"critical": {},
|
||||||
},
|
},
|
||||||
wantDeadlines: map[string][]base.Z{
|
wantLease: map[string][]base.Z{
|
||||||
"default": {},
|
"default": {},
|
||||||
"critical": {},
|
"critical": {},
|
||||||
},
|
},
|
||||||
@@ -101,23 +97,23 @@ func TestRecoverer(t *testing.T) {
|
|||||||
"critical": {},
|
"critical": {},
|
||||||
},
|
},
|
||||||
wantArchived: map[string][]*base.TaskMessage{
|
wantArchived: map[string][]*base.TaskMessage{
|
||||||
"default": {h.TaskMessageWithError(*t4, "deadline exceeded")},
|
"default": {t4},
|
||||||
"critical": {},
|
"critical": {},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
desc: "with multiple active tasks, and one expired",
|
desc: "with multiple active tasks, and one expired",
|
||||||
inProgress: map[string][]*base.TaskMessage{
|
active: map[string][]*base.TaskMessage{
|
||||||
"default": {t1, t2},
|
"default": {t1, t2},
|
||||||
"critical": {t3},
|
"critical": {t3},
|
||||||
},
|
},
|
||||||
deadlines: map[string][]base.Z{
|
lease: map[string][]base.Z{
|
||||||
"default": {
|
"default": {
|
||||||
{Message: t1, Score: oneHourAgo.Unix()},
|
{Message: t1, Score: now.Add(-2 * time.Minute).Unix()},
|
||||||
{Message: t2, Score: fiveMinutesFromNow.Unix()},
|
{Message: t2, Score: now.Add(20 * time.Second).Unix()},
|
||||||
},
|
},
|
||||||
"critical": {
|
"critical": {
|
||||||
{Message: t3, Score: oneHourFromNow.Unix()},
|
{Message: t3, Score: now.Add(20 * time.Second).Unix()},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
retry: map[string][]base.Z{
|
retry: map[string][]base.Z{
|
||||||
@@ -132,12 +128,12 @@ func TestRecoverer(t *testing.T) {
|
|||||||
"default": {t2},
|
"default": {t2},
|
||||||
"critical": {t3},
|
"critical": {t3},
|
||||||
},
|
},
|
||||||
wantDeadlines: map[string][]base.Z{
|
wantLease: map[string][]base.Z{
|
||||||
"default": {{Message: t2, Score: fiveMinutesFromNow.Unix()}},
|
"default": {{Message: t2, Score: now.Add(20 * time.Second).Unix()}},
|
||||||
"critical": {{Message: t3, Score: oneHourFromNow.Unix()}},
|
"critical": {{Message: t3, Score: now.Add(20 * time.Second).Unix()}},
|
||||||
},
|
},
|
||||||
wantRetry: map[string][]*base.TaskMessage{
|
wantRetry: map[string][]*base.TaskMessage{
|
||||||
"default": {h.TaskMessageAfterRetry(*t1, "deadline exceeded")},
|
"default": {t1},
|
||||||
"critical": {},
|
"critical": {},
|
||||||
},
|
},
|
||||||
wantArchived: map[string][]*base.TaskMessage{
|
wantArchived: map[string][]*base.TaskMessage{
|
||||||
@@ -147,17 +143,17 @@ func TestRecoverer(t *testing.T) {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
desc: "with multiple expired active tasks",
|
desc: "with multiple expired active tasks",
|
||||||
inProgress: map[string][]*base.TaskMessage{
|
active: map[string][]*base.TaskMessage{
|
||||||
"default": {t1, t2},
|
"default": {t1, t2},
|
||||||
"critical": {t3},
|
"critical": {t3},
|
||||||
},
|
},
|
||||||
deadlines: map[string][]base.Z{
|
lease: map[string][]base.Z{
|
||||||
"default": {
|
"default": {
|
||||||
{Message: t1, Score: oneHourAgo.Unix()},
|
{Message: t1, Score: now.Add(-1 * time.Minute).Unix()},
|
||||||
{Message: t2, Score: oneHourFromNow.Unix()},
|
{Message: t2, Score: now.Add(10 * time.Second).Unix()},
|
||||||
},
|
},
|
||||||
"critical": {
|
"critical": {
|
||||||
{Message: t3, Score: fiveMinutesAgo.Unix()},
|
{Message: t3, Score: now.Add(-1 * time.Minute).Unix()},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
retry: map[string][]base.Z{
|
retry: map[string][]base.Z{
|
||||||
@@ -172,12 +168,12 @@ func TestRecoverer(t *testing.T) {
|
|||||||
"default": {t2},
|
"default": {t2},
|
||||||
"critical": {},
|
"critical": {},
|
||||||
},
|
},
|
||||||
wantDeadlines: map[string][]base.Z{
|
wantLease: map[string][]base.Z{
|
||||||
"default": {{Message: t2, Score: oneHourFromNow.Unix()}},
|
"default": {{Message: t2, Score: now.Add(10 * time.Second).Unix()}},
|
||||||
},
|
},
|
||||||
wantRetry: map[string][]*base.TaskMessage{
|
wantRetry: map[string][]*base.TaskMessage{
|
||||||
"default": {h.TaskMessageAfterRetry(*t1, "deadline exceeded")},
|
"default": {t1},
|
||||||
"critical": {h.TaskMessageAfterRetry(*t3, "deadline exceeded")},
|
"critical": {t3},
|
||||||
},
|
},
|
||||||
wantArchived: map[string][]*base.TaskMessage{
|
wantArchived: map[string][]*base.TaskMessage{
|
||||||
"default": {},
|
"default": {},
|
||||||
@@ -186,11 +182,11 @@ func TestRecoverer(t *testing.T) {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
desc: "with empty active queue",
|
desc: "with empty active queue",
|
||||||
inProgress: map[string][]*base.TaskMessage{
|
active: map[string][]*base.TaskMessage{
|
||||||
"default": {},
|
"default": {},
|
||||||
"critical": {},
|
"critical": {},
|
||||||
},
|
},
|
||||||
deadlines: map[string][]base.Z{
|
lease: map[string][]base.Z{
|
||||||
"default": {},
|
"default": {},
|
||||||
"critical": {},
|
"critical": {},
|
||||||
},
|
},
|
||||||
@@ -206,7 +202,7 @@ func TestRecoverer(t *testing.T) {
|
|||||||
"default": {},
|
"default": {},
|
||||||
"critical": {},
|
"critical": {},
|
||||||
},
|
},
|
||||||
wantDeadlines: map[string][]base.Z{
|
wantLease: map[string][]base.Z{
|
||||||
"default": {},
|
"default": {},
|
||||||
"critical": {},
|
"critical": {},
|
||||||
},
|
},
|
||||||
@@ -223,8 +219,8 @@ func TestRecoverer(t *testing.T) {
|
|||||||
|
|
||||||
for _, tc := range tests {
|
for _, tc := range tests {
|
||||||
h.FlushDB(t, r)
|
h.FlushDB(t, r)
|
||||||
h.SeedAllActiveQueues(t, r, tc.inProgress)
|
h.SeedAllActiveQueues(t, r, tc.active)
|
||||||
h.SeedAllDeadlines(t, r, tc.deadlines)
|
h.SeedAllLease(t, r, tc.lease)
|
||||||
h.SeedAllRetryQueues(t, r, tc.retry)
|
h.SeedAllRetryQueues(t, r, tc.retry)
|
||||||
h.SeedAllArchivedQueues(t, r, tc.archived)
|
h.SeedAllArchivedQueues(t, r, tc.archived)
|
||||||
|
|
||||||
@@ -234,12 +230,14 @@ func TestRecoverer(t *testing.T) {
|
|||||||
queues: []string{"default", "critical"},
|
queues: []string{"default", "critical"},
|
||||||
interval: 1 * time.Second,
|
interval: 1 * time.Second,
|
||||||
retryDelayFunc: func(n int, err error, task *Task) time.Duration { return 30 * time.Second },
|
retryDelayFunc: func(n int, err error, task *Task) time.Duration { return 30 * time.Second },
|
||||||
|
isFailureFunc: defaultIsFailureFunc,
|
||||||
})
|
})
|
||||||
|
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
recoverer.start(&wg)
|
recoverer.start(&wg)
|
||||||
|
runTime := time.Now() // time when recoverer is running
|
||||||
time.Sleep(2 * time.Second)
|
time.Sleep(2 * time.Second)
|
||||||
recoverer.terminate()
|
recoverer.shutdown()
|
||||||
|
|
||||||
for qname, want := range tc.wantActive {
|
for qname, want := range tc.wantActive {
|
||||||
gotActive := h.GetActiveMessages(t, r, qname)
|
gotActive := h.GetActiveMessages(t, r, qname)
|
||||||
@@ -247,21 +245,30 @@ func TestRecoverer(t *testing.T) {
|
|||||||
t.Errorf("%s; mismatch found in %q; (-want,+got)\n%s", tc.desc, base.ActiveKey(qname), diff)
|
t.Errorf("%s; mismatch found in %q; (-want,+got)\n%s", tc.desc, base.ActiveKey(qname), diff)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for qname, want := range tc.wantDeadlines {
|
for qname, want := range tc.wantLease {
|
||||||
gotDeadlines := h.GetDeadlinesEntries(t, r, qname)
|
gotLease := h.GetLeaseEntries(t, r, qname)
|
||||||
if diff := cmp.Diff(want, gotDeadlines, h.SortZSetEntryOpt); diff != "" {
|
if diff := cmp.Diff(want, gotLease, h.SortZSetEntryOpt); diff != "" {
|
||||||
t.Errorf("%s; mismatch found in %q; (-want,+got)\n%s", tc.desc, base.DeadlinesKey(qname), diff)
|
t.Errorf("%s; mismatch found in %q; (-want,+got)\n%s", tc.desc, base.LeaseKey(qname), diff)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for qname, want := range tc.wantRetry {
|
cmpOpt := h.EquateInt64Approx(2) // allow up to two-second difference in `LastFailedAt`
|
||||||
|
for qname, msgs := range tc.wantRetry {
|
||||||
gotRetry := h.GetRetryMessages(t, r, qname)
|
gotRetry := h.GetRetryMessages(t, r, qname)
|
||||||
if diff := cmp.Diff(want, gotRetry, h.SortMsgOpt); diff != "" {
|
var wantRetry []*base.TaskMessage // Note: construct message here since `LastFailedAt` is relative to each test run
|
||||||
|
for _, msg := range msgs {
|
||||||
|
wantRetry = append(wantRetry, h.TaskMessageAfterRetry(*msg, ErrLeaseExpired.Error(), runTime))
|
||||||
|
}
|
||||||
|
if diff := cmp.Diff(wantRetry, gotRetry, h.SortMsgOpt, cmpOpt); diff != "" {
|
||||||
t.Errorf("%s; mismatch found in %q: (-want, +got)\n%s", tc.desc, base.RetryKey(qname), diff)
|
t.Errorf("%s; mismatch found in %q: (-want, +got)\n%s", tc.desc, base.RetryKey(qname), diff)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for qname, want := range tc.wantArchived {
|
for qname, msgs := range tc.wantArchived {
|
||||||
gotDead := h.GetArchivedMessages(t, r, qname)
|
gotArchived := h.GetArchivedMessages(t, r, qname)
|
||||||
if diff := cmp.Diff(want, gotDead, h.SortMsgOpt); diff != "" {
|
var wantArchived []*base.TaskMessage
|
||||||
|
for _, msg := range msgs {
|
||||||
|
wantArchived = append(wantArchived, h.TaskMessageWithError(*msg, ErrLeaseExpired.Error(), runTime))
|
||||||
|
}
|
||||||
|
if diff := cmp.Diff(wantArchived, gotArchived, h.SortMsgOpt, cmpOpt); diff != "" {
|
||||||
t.Errorf("%s; mismatch found in %q: (-want, +got)\n%s", tc.desc, base.ArchivedKey(qname), diff)
|
t.Errorf("%s; mismatch found in %q: (-want, +got)\n%s", tc.desc, base.ArchivedKey(qname), diff)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
200
scheduler.go
200
scheduler.go
@@ -10,39 +10,60 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/go-redis/redis/v7"
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"github.com/hibiken/asynq/internal/base"
|
"github.com/hibiken/asynq/internal/base"
|
||||||
"github.com/hibiken/asynq/internal/log"
|
"github.com/hibiken/asynq/internal/log"
|
||||||
"github.com/hibiken/asynq/internal/rdb"
|
"github.com/hibiken/asynq/internal/rdb"
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
"github.com/robfig/cron/v3"
|
"github.com/robfig/cron/v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
// A Scheduler kicks off tasks at regular intervals based on the user defined schedule.
|
// A Scheduler kicks off tasks at regular intervals based on the user defined schedule.
|
||||||
|
//
|
||||||
|
// Schedulers are safe for concurrent use by multiple goroutines.
|
||||||
type Scheduler struct {
|
type Scheduler struct {
|
||||||
id string
|
id string
|
||||||
status *base.ServerStatus
|
|
||||||
logger *log.Logger
|
state *serverState
|
||||||
client *Client
|
|
||||||
rdb *rdb.RDB
|
logger *log.Logger
|
||||||
cron *cron.Cron
|
client *Client
|
||||||
location *time.Location
|
rdb *rdb.RDB
|
||||||
done chan struct{}
|
cron *cron.Cron
|
||||||
wg sync.WaitGroup
|
location *time.Location
|
||||||
errHandler func(task *Task, opts []Option, err error)
|
done chan struct{}
|
||||||
|
wg sync.WaitGroup
|
||||||
|
preEnqueueFunc func(task *Task, opts []Option)
|
||||||
|
postEnqueueFunc func(info *TaskInfo, err error)
|
||||||
|
errHandler func(task *Task, opts []Option, err error)
|
||||||
|
|
||||||
|
// guards idmap
|
||||||
|
mu sync.Mutex
|
||||||
// idmap maps Scheduler's entry ID to cron.EntryID
|
// idmap maps Scheduler's entry ID to cron.EntryID
|
||||||
// to avoid using cron.EntryID as the public API of
|
// to avoid using cron.EntryID as the public API of
|
||||||
// the Scheduler.
|
// the Scheduler.
|
||||||
idmap map[string]cron.EntryID
|
idmap map[string]cron.EntryID
|
||||||
|
// When a Scheduler has been created with an existing Redis connection, we do
|
||||||
|
// not want to close it.
|
||||||
|
sharedConnection bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewScheduler returns a new Scheduler instance given the redis connection option.
|
// NewScheduler returns a new Scheduler instance given the redis connection option.
|
||||||
// The parameter opts is optional, defaults will be used if opts is set to nil
|
// The parameter opts is optional, defaults will be used if opts is set to nil
|
||||||
func NewScheduler(r RedisConnOpt, opts *SchedulerOpts) *Scheduler {
|
func NewScheduler(r RedisConnOpt, opts *SchedulerOpts) *Scheduler {
|
||||||
c, ok := r.MakeRedisClient().(redis.UniversalClient)
|
redisClient, ok := r.MakeRedisClient().(redis.UniversalClient)
|
||||||
if !ok {
|
if !ok {
|
||||||
panic(fmt.Sprintf("asynq: unsupported RedisConnOpt type %T", r))
|
panic(fmt.Sprintf("asynq: unsupported RedisConnOpt type %T", r))
|
||||||
}
|
}
|
||||||
|
scheduler := NewSchedulerFromRedisClient(redisClient, opts)
|
||||||
|
scheduler.sharedConnection = false
|
||||||
|
return scheduler
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewSchedulerFromRedisClient returns a new instance of Scheduler given a redis.UniversalClient
|
||||||
|
// The parameter opts is optional, defaults will be used if opts is set to nil.
|
||||||
|
// Warning: The underlying redis connection pool will not be closed by Asynq, you are responsible for closing it.
|
||||||
|
func NewSchedulerFromRedisClient(c redis.UniversalClient, opts *SchedulerOpts) *Scheduler {
|
||||||
if opts == nil {
|
if opts == nil {
|
||||||
opts = &SchedulerOpts{}
|
opts = &SchedulerOpts{}
|
||||||
}
|
}
|
||||||
@@ -60,16 +81,18 @@ func NewScheduler(r RedisConnOpt, opts *SchedulerOpts) *Scheduler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return &Scheduler{
|
return &Scheduler{
|
||||||
id: generateSchedulerID(),
|
id: generateSchedulerID(),
|
||||||
status: base.NewServerStatus(base.StatusIdle),
|
state: &serverState{value: srvStateNew},
|
||||||
logger: logger,
|
logger: logger,
|
||||||
client: NewClient(r),
|
client: NewClientFromRedisClient(c),
|
||||||
rdb: rdb.NewRDB(c),
|
rdb: rdb.NewRDB(c),
|
||||||
cron: cron.New(cron.WithLocation(loc)),
|
cron: cron.New(cron.WithLocation(loc)),
|
||||||
location: loc,
|
location: loc,
|
||||||
done: make(chan struct{}),
|
done: make(chan struct{}),
|
||||||
errHandler: opts.EnqueueErrorHandler,
|
preEnqueueFunc: opts.PreEnqueueFunc,
|
||||||
idmap: make(map[string]cron.EntryID),
|
postEnqueueFunc: opts.PostEnqueueFunc,
|
||||||
|
errHandler: opts.EnqueueErrorHandler,
|
||||||
|
idmap: make(map[string]cron.EntryID),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,41 +121,57 @@ type SchedulerOpts struct {
|
|||||||
// If unset, the UTC time zone (time.UTC) is used.
|
// If unset, the UTC time zone (time.UTC) is used.
|
||||||
Location *time.Location
|
Location *time.Location
|
||||||
|
|
||||||
|
// PreEnqueueFunc, if provided, is called before a task gets enqueued by Scheduler.
|
||||||
|
// The callback function should return quickly to not block the current thread.
|
||||||
|
PreEnqueueFunc func(task *Task, opts []Option)
|
||||||
|
|
||||||
|
// PostEnqueueFunc, if provided, is called after a task gets enqueued by Scheduler.
|
||||||
|
// The callback function should return quickly to not block the current thread.
|
||||||
|
PostEnqueueFunc func(info *TaskInfo, err error)
|
||||||
|
|
||||||
|
// Deprecated: Use PostEnqueueFunc instead
|
||||||
// EnqueueErrorHandler gets called when scheduler cannot enqueue a registered task
|
// EnqueueErrorHandler gets called when scheduler cannot enqueue a registered task
|
||||||
// due to an error.
|
// due to an error.
|
||||||
EnqueueErrorHandler func(task *Task, opts []Option, err error)
|
EnqueueErrorHandler func(task *Task, opts []Option, err error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// enqueueJob encapsulates the job of enqueing a task and recording the event.
|
// enqueueJob encapsulates the job of enqueuing a task and recording the event.
|
||||||
type enqueueJob struct {
|
type enqueueJob struct {
|
||||||
id uuid.UUID
|
id uuid.UUID
|
||||||
cronspec string
|
cronspec string
|
||||||
task *Task
|
task *Task
|
||||||
opts []Option
|
opts []Option
|
||||||
location *time.Location
|
location *time.Location
|
||||||
logger *log.Logger
|
logger *log.Logger
|
||||||
client *Client
|
client *Client
|
||||||
rdb *rdb.RDB
|
rdb *rdb.RDB
|
||||||
errHandler func(task *Task, opts []Option, err error)
|
preEnqueueFunc func(task *Task, opts []Option)
|
||||||
|
postEnqueueFunc func(info *TaskInfo, err error)
|
||||||
|
errHandler func(task *Task, opts []Option, err error)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (j *enqueueJob) Run() {
|
func (j *enqueueJob) Run() {
|
||||||
res, err := j.client.Enqueue(j.task, j.opts...)
|
if j.preEnqueueFunc != nil {
|
||||||
|
j.preEnqueueFunc(j.task, j.opts)
|
||||||
|
}
|
||||||
|
info, err := j.client.Enqueue(j.task, j.opts...)
|
||||||
|
if j.postEnqueueFunc != nil {
|
||||||
|
j.postEnqueueFunc(info, err)
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
j.logger.Errorf("scheduler could not enqueue a task %+v: %v", j.task, err)
|
|
||||||
if j.errHandler != nil {
|
if j.errHandler != nil {
|
||||||
j.errHandler(j.task, j.opts, err)
|
j.errHandler(j.task, j.opts, err)
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
j.logger.Debugf("scheduler enqueued a task: %+v", res)
|
j.logger.Debugf("scheduler enqueued a task: %+v", info)
|
||||||
event := &base.SchedulerEnqueueEvent{
|
event := &base.SchedulerEnqueueEvent{
|
||||||
TaskID: res.ID,
|
TaskID: info.ID,
|
||||||
EnqueuedAt: res.EnqueuedAt.In(j.location),
|
EnqueuedAt: time.Now().In(j.location),
|
||||||
}
|
}
|
||||||
err = j.rdb.RecordSchedulerEnqueueEvent(j.id.String(), event)
|
err = j.rdb.RecordSchedulerEnqueueEvent(j.id.String(), event)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
j.logger.Errorf("scheduler could not record enqueue event of enqueued task %+v: %v", j.task, err)
|
j.logger.Warnf("scheduler could not record enqueue event of enqueued task %s: %v", info.ID, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -140,69 +179,93 @@ func (j *enqueueJob) Run() {
|
|||||||
// It returns an ID of the newly registered entry.
|
// It returns an ID of the newly registered entry.
|
||||||
func (s *Scheduler) Register(cronspec string, task *Task, opts ...Option) (entryID string, err error) {
|
func (s *Scheduler) Register(cronspec string, task *Task, opts ...Option) (entryID string, err error) {
|
||||||
job := &enqueueJob{
|
job := &enqueueJob{
|
||||||
id: uuid.New(),
|
id: uuid.New(),
|
||||||
cronspec: cronspec,
|
cronspec: cronspec,
|
||||||
task: task,
|
task: task,
|
||||||
opts: opts,
|
opts: opts,
|
||||||
location: s.location,
|
location: s.location,
|
||||||
client: s.client,
|
client: s.client,
|
||||||
rdb: s.rdb,
|
rdb: s.rdb,
|
||||||
logger: s.logger,
|
logger: s.logger,
|
||||||
errHandler: s.errHandler,
|
preEnqueueFunc: s.preEnqueueFunc,
|
||||||
|
postEnqueueFunc: s.postEnqueueFunc,
|
||||||
|
errHandler: s.errHandler,
|
||||||
}
|
}
|
||||||
cronID, err := s.cron.AddJob(cronspec, job)
|
cronID, err := s.cron.AddJob(cronspec, job)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
s.mu.Lock()
|
||||||
s.idmap[job.id.String()] = cronID
|
s.idmap[job.id.String()] = cronID
|
||||||
|
s.mu.Unlock()
|
||||||
return job.id.String(), nil
|
return job.id.String(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unregister removes a registered entry by entry ID.
|
// Unregister removes a registered entry by entry ID.
|
||||||
// Unregister returns a non-nil error if no entries were found for the given entryID.
|
// Unregister returns a non-nil error if no entries were found for the given entryID.
|
||||||
func (s *Scheduler) Unregister(entryID string) error {
|
func (s *Scheduler) Unregister(entryID string) error {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
cronID, ok := s.idmap[entryID]
|
cronID, ok := s.idmap[entryID]
|
||||||
if !ok {
|
if !ok {
|
||||||
return fmt.Errorf("asynq: no scheduler entry found")
|
return fmt.Errorf("asynq: no scheduler entry found")
|
||||||
}
|
}
|
||||||
|
delete(s.idmap, entryID)
|
||||||
s.cron.Remove(cronID)
|
s.cron.Remove(cronID)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Run starts the scheduler until an os signal to exit the program is received.
|
// Run starts the scheduler until an os signal to exit the program is received.
|
||||||
// It returns an error if scheduler is already running or has been stopped.
|
// It returns an error if scheduler is already running or has been shutdown.
|
||||||
func (s *Scheduler) Run() error {
|
func (s *Scheduler) Run() error {
|
||||||
if err := s.Start(); err != nil {
|
if err := s.Start(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
s.waitForSignals()
|
s.waitForSignals()
|
||||||
return s.Stop()
|
s.Shutdown()
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Start starts the scheduler.
|
// Start starts the scheduler.
|
||||||
// It returns an error if the scheduler is already running or has been stopped.
|
// It returns an error if the scheduler is already running or has been shutdown.
|
||||||
func (s *Scheduler) Start() error {
|
func (s *Scheduler) Start() error {
|
||||||
switch s.status.Get() {
|
if err := s.start(); err != nil {
|
||||||
case base.StatusRunning:
|
return err
|
||||||
return fmt.Errorf("asynq: the scheduler is already running")
|
|
||||||
case base.StatusStopped:
|
|
||||||
return fmt.Errorf("asynq: the scheduler has already been stopped")
|
|
||||||
}
|
}
|
||||||
s.logger.Info("Scheduler starting")
|
s.logger.Info("Scheduler starting")
|
||||||
s.logger.Infof("Scheduler timezone is set to %v", s.location)
|
s.logger.Infof("Scheduler timezone is set to %v", s.location)
|
||||||
s.cron.Start()
|
s.cron.Start()
|
||||||
s.wg.Add(1)
|
s.wg.Add(1)
|
||||||
go s.runHeartbeater()
|
go s.runHeartbeater()
|
||||||
s.status.Set(base.StatusRunning)
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stop stops the scheduler.
|
// Checks server state and returns an error if pre-condition is not met.
|
||||||
// It returns an error if the scheduler is not currently running.
|
// Otherwise it sets the server state to active.
|
||||||
func (s *Scheduler) Stop() error {
|
func (s *Scheduler) start() error {
|
||||||
if s.status.Get() != base.StatusRunning {
|
s.state.mu.Lock()
|
||||||
return fmt.Errorf("asynq: the scheduler is not running")
|
defer s.state.mu.Unlock()
|
||||||
|
switch s.state.value {
|
||||||
|
case srvStateActive:
|
||||||
|
return fmt.Errorf("asynq: the scheduler is already running")
|
||||||
|
case srvStateClosed:
|
||||||
|
return fmt.Errorf("asynq: the scheduler has already been stopped")
|
||||||
}
|
}
|
||||||
|
s.state.value = srvStateActive
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Shutdown stops and shuts down the scheduler.
|
||||||
|
func (s *Scheduler) Shutdown() {
|
||||||
|
s.state.mu.Lock()
|
||||||
|
if s.state.value == srvStateNew || s.state.value == srvStateClosed {
|
||||||
|
// scheduler is not running, do nothing and return.
|
||||||
|
s.state.mu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.state.value = srvStateClosed
|
||||||
|
s.state.mu.Unlock()
|
||||||
|
|
||||||
s.logger.Info("Scheduler shutting down")
|
s.logger.Info("Scheduler shutting down")
|
||||||
close(s.done) // signal heartbeater to stop
|
close(s.done) // signal heartbeater to stop
|
||||||
ctx := s.cron.Stop()
|
ctx := s.cron.Stop()
|
||||||
@@ -210,11 +273,13 @@ func (s *Scheduler) Stop() error {
|
|||||||
s.wg.Wait()
|
s.wg.Wait()
|
||||||
|
|
||||||
s.clearHistory()
|
s.clearHistory()
|
||||||
s.client.Close()
|
if err := s.client.Close(); err != nil {
|
||||||
s.rdb.Close()
|
s.logger.Errorf("Failed to close redis client connection: %v", err)
|
||||||
s.status.Set(base.StatusStopped)
|
}
|
||||||
|
if !s.sharedConnection {
|
||||||
|
s.rdb.Close()
|
||||||
|
}
|
||||||
s.logger.Info("Scheduler stopped")
|
s.logger.Info("Scheduler stopped")
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Scheduler) runHeartbeater() {
|
func (s *Scheduler) runHeartbeater() {
|
||||||
@@ -225,6 +290,7 @@ func (s *Scheduler) runHeartbeater() {
|
|||||||
case <-s.done:
|
case <-s.done:
|
||||||
s.logger.Debugf("Scheduler heatbeater shutting down")
|
s.logger.Debugf("Scheduler heatbeater shutting down")
|
||||||
s.rdb.ClearSchedulerEntries(s.id)
|
s.rdb.ClearSchedulerEntries(s.id)
|
||||||
|
ticker.Stop()
|
||||||
return
|
return
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
s.beat()
|
s.beat()
|
||||||
@@ -240,8 +306,8 @@ func (s *Scheduler) beat() {
|
|||||||
e := &base.SchedulerEntry{
|
e := &base.SchedulerEntry{
|
||||||
ID: job.id.String(),
|
ID: job.id.String(),
|
||||||
Spec: job.cronspec,
|
Spec: job.cronspec,
|
||||||
Type: job.task.Type,
|
Type: job.task.Type(),
|
||||||
Payload: job.task.Payload.data,
|
Payload: job.task.Payload(),
|
||||||
Opts: stringifyOptions(job.opts),
|
Opts: stringifyOptions(job.opts),
|
||||||
Next: entry.Next,
|
Next: entry.Next,
|
||||||
Prev: entry.Prev,
|
Prev: entry.Prev,
|
||||||
|
|||||||
@@ -5,13 +5,15 @@
|
|||||||
package asynq
|
package asynq
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/google/go-cmp/cmp"
|
"github.com/google/go-cmp/cmp"
|
||||||
"github.com/hibiken/asynq/internal/asynqtest"
|
|
||||||
"github.com/hibiken/asynq/internal/base"
|
"github.com/hibiken/asynq/internal/base"
|
||||||
|
"github.com/hibiken/asynq/internal/testutil"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestSchedulerRegister(t *testing.T) {
|
func TestSchedulerRegister(t *testing.T) {
|
||||||
@@ -57,6 +59,7 @@ func TestSchedulerRegister(t *testing.T) {
|
|||||||
|
|
||||||
r := setup(t)
|
r := setup(t)
|
||||||
|
|
||||||
|
// Tests for new redis connection.
|
||||||
for _, tc := range tests {
|
for _, tc := range tests {
|
||||||
scheduler := NewScheduler(getRedisConnOpt(t), nil)
|
scheduler := NewScheduler(getRedisConnOpt(t), nil)
|
||||||
if _, err := scheduler.Register(tc.cronspec, tc.task, tc.opts...); err != nil {
|
if _, err := scheduler.Register(tc.cronspec, tc.task, tc.opts...); err != nil {
|
||||||
@@ -67,12 +70,32 @@ func TestSchedulerRegister(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
time.Sleep(tc.wait)
|
time.Sleep(tc.wait)
|
||||||
if err := scheduler.Stop(); err != nil {
|
scheduler.Shutdown()
|
||||||
|
|
||||||
|
got := testutil.GetPendingMessages(t, r, tc.queue)
|
||||||
|
if diff := cmp.Diff(tc.want, got, testutil.IgnoreIDOpt); diff != "" {
|
||||||
|
t.Errorf("mismatch found in queue %q: (-want,+got)\n%s", tc.queue, diff)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
r = setup(t)
|
||||||
|
|
||||||
|
// Tests for existing redis connection.
|
||||||
|
for _, tc := range tests {
|
||||||
|
redisClient := getRedisConnOpt(t).MakeRedisClient().(redis.UniversalClient)
|
||||||
|
scheduler := NewSchedulerFromRedisClient(redisClient, nil)
|
||||||
|
if _, err := scheduler.Register(tc.cronspec, tc.task, tc.opts...); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
got := asynqtest.GetPendingMessages(t, r, tc.queue)
|
if err := scheduler.Start(); err != nil {
|
||||||
if diff := cmp.Diff(tc.want, got, asynqtest.IgnoreIDOpt); diff != "" {
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
time.Sleep(tc.wait)
|
||||||
|
scheduler.Shutdown()
|
||||||
|
|
||||||
|
got := testutil.GetPendingMessages(t, r, tc.queue)
|
||||||
|
if diff := cmp.Diff(tc.want, got, testutil.IgnoreIDOpt); diff != "" {
|
||||||
t.Errorf("mismatch found in queue %q: (-want,+got)\n%s", tc.queue, diff)
|
t.Errorf("mismatch found in queue %q: (-want,+got)\n%s", tc.queue, diff)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -106,9 +129,7 @@ func TestSchedulerWhenRedisDown(t *testing.T) {
|
|||||||
}
|
}
|
||||||
// Scheduler should attempt to enqueue the task three times (every 3s).
|
// Scheduler should attempt to enqueue the task three times (every 3s).
|
||||||
time.Sleep(10 * time.Second)
|
time.Sleep(10 * time.Second)
|
||||||
if err := scheduler.Stop(); err != nil {
|
scheduler.Shutdown()
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
if counter != 3 {
|
if counter != 3 {
|
||||||
@@ -150,13 +171,64 @@ func TestSchedulerUnregister(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
time.Sleep(tc.wait)
|
time.Sleep(tc.wait)
|
||||||
if err := scheduler.Stop(); err != nil {
|
scheduler.Shutdown()
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
got := asynqtest.GetPendingMessages(t, r, tc.queue)
|
got := testutil.GetPendingMessages(t, r, tc.queue)
|
||||||
if len(got) != 0 {
|
if len(got) != 0 {
|
||||||
t.Errorf("%d tasks were enqueued, want zero", len(got))
|
t.Errorf("%d tasks were enqueued, want zero", len(got))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSchedulerPostAndPreEnqueueHandler(t *testing.T) {
|
||||||
|
var (
|
||||||
|
preMu sync.Mutex
|
||||||
|
preCounter int
|
||||||
|
postMu sync.Mutex
|
||||||
|
postCounter int
|
||||||
|
)
|
||||||
|
preHandler := func(task *Task, opts []Option) {
|
||||||
|
preMu.Lock()
|
||||||
|
preCounter++
|
||||||
|
preMu.Unlock()
|
||||||
|
}
|
||||||
|
postHandler := func(info *TaskInfo, err error) {
|
||||||
|
postMu.Lock()
|
||||||
|
postCounter++
|
||||||
|
postMu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Connect to non-existent redis instance to simulate a redis server being down.
|
||||||
|
scheduler := NewScheduler(
|
||||||
|
getRedisConnOpt(t),
|
||||||
|
&SchedulerOpts{
|
||||||
|
PreEnqueueFunc: preHandler,
|
||||||
|
PostEnqueueFunc: postHandler,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
task := NewTask("test", nil)
|
||||||
|
|
||||||
|
if _, err := scheduler.Register("@every 3s", task); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := scheduler.Start(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// Scheduler should attempt to enqueue the task three times (every 3s).
|
||||||
|
time.Sleep(10 * time.Second)
|
||||||
|
scheduler.Shutdown()
|
||||||
|
|
||||||
|
preMu.Lock()
|
||||||
|
if preCounter != 3 {
|
||||||
|
t.Errorf("PreEnqueueFunc was called %d times, want 3", preCounter)
|
||||||
|
}
|
||||||
|
preMu.Unlock()
|
||||||
|
|
||||||
|
postMu.Lock()
|
||||||
|
if postCounter != 3 {
|
||||||
|
t.Errorf("PostEnqueueFunc was called %d times, want 3", postCounter)
|
||||||
|
}
|
||||||
|
postMu.Unlock()
|
||||||
|
}
|
||||||
|
|||||||
10
servemux.go
10
servemux.go
@@ -62,7 +62,7 @@ func (mux *ServeMux) Handler(t *Task) (h Handler, pattern string) {
|
|||||||
mux.mu.RLock()
|
mux.mu.RLock()
|
||||||
defer mux.mu.RUnlock()
|
defer mux.mu.RUnlock()
|
||||||
|
|
||||||
h, pattern = mux.match(t.Type)
|
h, pattern = mux.match(t.Type())
|
||||||
if h == nil {
|
if h == nil {
|
||||||
h, pattern = NotFoundHandler(), ""
|
h, pattern = NotFoundHandler(), ""
|
||||||
}
|
}
|
||||||
@@ -98,7 +98,7 @@ func (mux *ServeMux) Handle(pattern string, handler Handler) {
|
|||||||
mux.mu.Lock()
|
mux.mu.Lock()
|
||||||
defer mux.mu.Unlock()
|
defer mux.mu.Unlock()
|
||||||
|
|
||||||
if pattern == "" {
|
if strings.TrimSpace(pattern) == "" {
|
||||||
panic("asynq: invalid pattern")
|
panic("asynq: invalid pattern")
|
||||||
}
|
}
|
||||||
if handler == nil {
|
if handler == nil {
|
||||||
@@ -144,14 +144,12 @@ func (mux *ServeMux) HandleFunc(pattern string, handler func(context.Context, *T
|
|||||||
func (mux *ServeMux) Use(mws ...MiddlewareFunc) {
|
func (mux *ServeMux) Use(mws ...MiddlewareFunc) {
|
||||||
mux.mu.Lock()
|
mux.mu.Lock()
|
||||||
defer mux.mu.Unlock()
|
defer mux.mu.Unlock()
|
||||||
for _, fn := range mws {
|
mux.mws = append(mux.mws, mws...)
|
||||||
mux.mws = append(mux.mws, fn)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// NotFound returns an error indicating that the handler was not found for the given task.
|
// NotFound returns an error indicating that the handler was not found for the given task.
|
||||||
func NotFound(ctx context.Context, task *Task) error {
|
func NotFound(ctx context.Context, task *Task) error {
|
||||||
return fmt.Errorf("handler not found for task %q", task.Type)
|
return fmt.Errorf("handler not found for task %q", task.Type())
|
||||||
}
|
}
|
||||||
|
|
||||||
// NotFoundHandler returns a simple task handler that returns a ``not found`` error.
|
// NotFoundHandler returns a simple task handler that returns a ``not found`` error.
|
||||||
|
|||||||
@@ -68,7 +68,7 @@ func TestServeMux(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if called != tc.want {
|
if called != tc.want {
|
||||||
t.Errorf("%q handler was called for task %q, want %q to be called", called, task.Type, tc.want)
|
t.Errorf("%q handler was called for task %q, want %q to be called", called, task.Type(), tc.want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -124,7 +124,7 @@ func TestServeMuxNotFound(t *testing.T) {
|
|||||||
task := NewTask(tc.typename, nil)
|
task := NewTask(tc.typename, nil)
|
||||||
err := mux.ProcessTask(context.Background(), task)
|
err := mux.ProcessTask(context.Background(), task)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Errorf("ProcessTask did not return error for task %q, should return 'not found' error", task.Type)
|
t.Errorf("ProcessTask did not return error for task %q, should return 'not found' error", task.Type())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -164,7 +164,7 @@ func TestServeMuxMiddlewares(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if called != tc.want {
|
if called != tc.want {
|
||||||
t.Errorf("%q handler was called for task %q, want %q to be called", called, task.Type, tc.want)
|
t.Errorf("%q handler was called for task %q, want %q to be called", called, task.Type(), tc.want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
415
server.go
415
server.go
@@ -15,29 +15,33 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/go-redis/redis/v7"
|
|
||||||
"github.com/hibiken/asynq/internal/base"
|
"github.com/hibiken/asynq/internal/base"
|
||||||
"github.com/hibiken/asynq/internal/log"
|
"github.com/hibiken/asynq/internal/log"
|
||||||
"github.com/hibiken/asynq/internal/rdb"
|
"github.com/hibiken/asynq/internal/rdb"
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Server is responsible for managing the task processing.
|
// Server is responsible for task processing and task lifecycle management.
|
||||||
//
|
//
|
||||||
// Server pulls tasks off queues and processes them.
|
// Server pulls tasks off queues and processes them.
|
||||||
// If the processing of a task is unsuccessful, server will schedule it for a retry.
|
// If the processing of a task is unsuccessful, server will schedule it for a retry.
|
||||||
|
//
|
||||||
// A task will be retried until either the task gets processed successfully
|
// A task will be retried until either the task gets processed successfully
|
||||||
// or until it reaches its max retry count.
|
// or until it reaches its max retry count.
|
||||||
//
|
//
|
||||||
// If a task exhausts its retries, it will be moved to the archive and
|
// If a task exhausts its retries, it will be moved to the archive and
|
||||||
// will be kept in the archive for some time until a certain condition is met
|
// will be kept in the archive set.
|
||||||
// (e.g., archive size reaches a certain limit, or the task has been in the
|
// Note that the archive size is finite and once it reaches its max size,
|
||||||
// archive for a certain amount of time).
|
// oldest tasks in the archive will be deleted.
|
||||||
type Server struct {
|
type Server struct {
|
||||||
logger *log.Logger
|
logger *log.Logger
|
||||||
|
|
||||||
broker base.Broker
|
broker base.Broker
|
||||||
|
// When a Server has been created with an existing Redis connection, we do
|
||||||
|
// not want to close it.
|
||||||
|
sharedConnection bool
|
||||||
|
|
||||||
status *base.ServerStatus
|
state *serverState
|
||||||
|
|
||||||
// wait group to wait for all goroutines to finish.
|
// wait group to wait for all goroutines to finish.
|
||||||
wg sync.WaitGroup
|
wg sync.WaitGroup
|
||||||
@@ -48,6 +52,45 @@ type Server struct {
|
|||||||
subscriber *subscriber
|
subscriber *subscriber
|
||||||
recoverer *recoverer
|
recoverer *recoverer
|
||||||
healthchecker *healthchecker
|
healthchecker *healthchecker
|
||||||
|
janitor *janitor
|
||||||
|
aggregator *aggregator
|
||||||
|
}
|
||||||
|
|
||||||
|
type serverState struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
value serverStateValue
|
||||||
|
}
|
||||||
|
|
||||||
|
type serverStateValue int
|
||||||
|
|
||||||
|
const (
|
||||||
|
// StateNew represents a new server. Server begins in
|
||||||
|
// this state and then transition to StatusActive when
|
||||||
|
// Start or Run is callled.
|
||||||
|
srvStateNew serverStateValue = iota
|
||||||
|
|
||||||
|
// StateActive indicates the server is up and active.
|
||||||
|
srvStateActive
|
||||||
|
|
||||||
|
// StateStopped indicates the server is up but no longer processing new tasks.
|
||||||
|
srvStateStopped
|
||||||
|
|
||||||
|
// StateClosed indicates the server has been shutdown.
|
||||||
|
srvStateClosed
|
||||||
|
)
|
||||||
|
|
||||||
|
var serverStates = []string{
|
||||||
|
"new",
|
||||||
|
"active",
|
||||||
|
"stopped",
|
||||||
|
"closed",
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s serverStateValue) String() string {
|
||||||
|
if srvStateNew <= s && s <= srvStateClosed {
|
||||||
|
return serverStates[s]
|
||||||
|
}
|
||||||
|
return "unknown status"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Config specifies the server's background-task processing behavior.
|
// Config specifies the server's background-task processing behavior.
|
||||||
@@ -55,14 +98,37 @@ type Config struct {
|
|||||||
// Maximum number of concurrent processing of tasks.
|
// Maximum number of concurrent processing of tasks.
|
||||||
//
|
//
|
||||||
// If set to a zero or negative value, NewServer will overwrite the value
|
// If set to a zero or negative value, NewServer will overwrite the value
|
||||||
// to the number of CPUs usable by the currennt process.
|
// to the number of CPUs usable by the current process.
|
||||||
Concurrency int
|
Concurrency int
|
||||||
|
|
||||||
|
// BaseContext optionally specifies a function that returns the base context for Handler invocations on this server.
|
||||||
|
//
|
||||||
|
// If BaseContext is nil, the default is context.Background().
|
||||||
|
// If this is defined, then it MUST return a non-nil context
|
||||||
|
BaseContext func() context.Context
|
||||||
|
|
||||||
|
// TaskCheckInterval specifies the interval between checks for new tasks to process when all queues are empty.
|
||||||
|
//
|
||||||
|
// If unset, zero or a negative value, the interval is set to 1 second.
|
||||||
|
//
|
||||||
|
// Note: Setting this value too low may add significant load to redis.
|
||||||
|
//
|
||||||
|
// By default, TaskCheckInterval is set to 1 seconds.
|
||||||
|
TaskCheckInterval time.Duration
|
||||||
|
|
||||||
// Function to calculate retry delay for a failed task.
|
// Function to calculate retry delay for a failed task.
|
||||||
//
|
//
|
||||||
// By default, it uses exponential backoff algorithm to calculate the delay.
|
// By default, it uses exponential backoff algorithm to calculate the delay.
|
||||||
RetryDelayFunc RetryDelayFunc
|
RetryDelayFunc RetryDelayFunc
|
||||||
|
|
||||||
|
// Predicate function to determine whether the error returned from Handler is a failure.
|
||||||
|
// If the function returns false, Server will not increment the retried counter for the task,
|
||||||
|
// and Server won't record the queue stats (processed and failed stats) to avoid skewing the error
|
||||||
|
// rate of the queue.
|
||||||
|
//
|
||||||
|
// By default, if the given error is non-nil the function returns true.
|
||||||
|
IsFailure func(error) bool
|
||||||
|
|
||||||
// List of queues to process with given priority value. Keys are the names of the
|
// List of queues to process with given priority value. Keys are the names of the
|
||||||
// queues and values are associated priority value.
|
// queues and values are associated priority value.
|
||||||
//
|
//
|
||||||
@@ -108,6 +174,16 @@ type Config struct {
|
|||||||
// })
|
// })
|
||||||
//
|
//
|
||||||
// ErrorHandler: asynq.ErrorHandlerFunc(reportError)
|
// ErrorHandler: asynq.ErrorHandlerFunc(reportError)
|
||||||
|
|
||||||
|
// we can also handle panic error like:
|
||||||
|
// func reportError(ctx context, task *asynq.Task, err error) {
|
||||||
|
// if asynq.IsPanic(err) {
|
||||||
|
// errorReportingService.Notify(err)
|
||||||
|
// }
|
||||||
|
// })
|
||||||
|
//
|
||||||
|
// ErrorHandler: asynq.ErrorHandlerFunc(reportError)
|
||||||
|
|
||||||
ErrorHandler ErrorHandler
|
ErrorHandler ErrorHandler
|
||||||
|
|
||||||
// Logger specifies the logger used by the server instance.
|
// Logger specifies the logger used by the server instance.
|
||||||
@@ -134,9 +210,72 @@ type Config struct {
|
|||||||
//
|
//
|
||||||
// If unset or zero, the interval is set to 15 seconds.
|
// If unset or zero, the interval is set to 15 seconds.
|
||||||
HealthCheckInterval time.Duration
|
HealthCheckInterval time.Duration
|
||||||
|
|
||||||
|
// DelayedTaskCheckInterval specifies the interval between checks run on 'scheduled' and 'retry'
|
||||||
|
// tasks, and forwarding them to 'pending' state if they are ready to be processed.
|
||||||
|
//
|
||||||
|
// If unset or zero, the interval is set to 5 seconds.
|
||||||
|
DelayedTaskCheckInterval time.Duration
|
||||||
|
|
||||||
|
// GroupGracePeriod specifies the amount of time the server will wait for an incoming task before aggregating
|
||||||
|
// the tasks in a group. If an incoming task is received within this period, the server will wait for another
|
||||||
|
// period of the same length, up to GroupMaxDelay if specified.
|
||||||
|
//
|
||||||
|
// If unset or zero, the grace period is set to 1 minute.
|
||||||
|
// Minimum duration for GroupGracePeriod is 1 second. If value specified is less than a second, the call to
|
||||||
|
// NewServer will panic.
|
||||||
|
GroupGracePeriod time.Duration
|
||||||
|
|
||||||
|
// GroupMaxDelay specifies the maximum amount of time the server will wait for incoming tasks before aggregating
|
||||||
|
// the tasks in a group.
|
||||||
|
//
|
||||||
|
// If unset or zero, no delay limit is used.
|
||||||
|
GroupMaxDelay time.Duration
|
||||||
|
|
||||||
|
// GroupMaxSize specifies the maximum number of tasks that can be aggregated into a single task within a group.
|
||||||
|
// If GroupMaxSize is reached, the server will aggregate the tasks into one immediately.
|
||||||
|
//
|
||||||
|
// If unset or zero, no size limit is used.
|
||||||
|
GroupMaxSize int
|
||||||
|
|
||||||
|
// GroupAggregator specifies the aggregation function used to aggregate multiple tasks in a group into one task.
|
||||||
|
//
|
||||||
|
// If unset or nil, the group aggregation feature will be disabled on the server.
|
||||||
|
GroupAggregator GroupAggregator
|
||||||
|
|
||||||
|
// JanitorInterval specifies the average interval of janitor checks for expired completed tasks.
|
||||||
|
//
|
||||||
|
// If unset or zero, default interval of 8 seconds is used.
|
||||||
|
JanitorInterval time.Duration
|
||||||
|
|
||||||
|
// JanitorBatchSize specifies the number of expired completed tasks to be deleted in one run.
|
||||||
|
//
|
||||||
|
// If unset or zero, default batch size of 100 is used.
|
||||||
|
// Make sure to not put a big number as the batch size to prevent a long-running script.
|
||||||
|
JanitorBatchSize int
|
||||||
}
|
}
|
||||||
|
|
||||||
// An ErrorHandler handles an error occured during task processing.
|
// GroupAggregator aggregates a group of tasks into one before the tasks are passed to the Handler.
|
||||||
|
type GroupAggregator interface {
|
||||||
|
// Aggregate aggregates the given tasks in a group with the given group name,
|
||||||
|
// and returns a new task which is the aggregation of those tasks.
|
||||||
|
//
|
||||||
|
// Use NewTask(typename, payload, opts...) to set any options for the aggregated task.
|
||||||
|
// The Queue option, if provided, will be ignored and the aggregated task will always be enqueued
|
||||||
|
// to the same queue the group belonged.
|
||||||
|
Aggregate(group string, tasks []*Task) *Task
|
||||||
|
}
|
||||||
|
|
||||||
|
// The GroupAggregatorFunc type is an adapter to allow the use of ordinary functions as a GroupAggregator.
|
||||||
|
// If f is a function with the appropriate signature, GroupAggregatorFunc(f) is a GroupAggregator that calls f.
|
||||||
|
type GroupAggregatorFunc func(group string, tasks []*Task) *Task
|
||||||
|
|
||||||
|
// Aggregate calls fn(group, tasks)
|
||||||
|
func (fn GroupAggregatorFunc) Aggregate(group string, tasks []*Task) *Task {
|
||||||
|
return fn(group, tasks)
|
||||||
|
}
|
||||||
|
|
||||||
|
// An ErrorHandler handles an error occurred during task processing.
|
||||||
type ErrorHandler interface {
|
type ErrorHandler interface {
|
||||||
HandleError(ctx context.Context, task *Task, err error)
|
HandleError(ctx context.Context, task *Task, err error)
|
||||||
}
|
}
|
||||||
@@ -267,33 +406,71 @@ func DefaultRetryDelayFunc(n int, e error, t *Task) time.Duration {
|
|||||||
return time.Duration(s) * time.Second
|
return time.Duration(s) * time.Second
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func defaultIsFailureFunc(err error) bool { return err != nil }
|
||||||
|
|
||||||
var defaultQueueConfig = map[string]int{
|
var defaultQueueConfig = map[string]int{
|
||||||
base.DefaultQueueName: 1,
|
base.DefaultQueueName: 1,
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
defaultTaskCheckInterval = 1 * time.Second
|
||||||
|
|
||||||
defaultShutdownTimeout = 8 * time.Second
|
defaultShutdownTimeout = 8 * time.Second
|
||||||
|
|
||||||
defaultHealthCheckInterval = 15 * time.Second
|
defaultHealthCheckInterval = 15 * time.Second
|
||||||
|
|
||||||
|
defaultDelayedTaskCheckInterval = 5 * time.Second
|
||||||
|
|
||||||
|
defaultGroupGracePeriod = 1 * time.Minute
|
||||||
|
|
||||||
|
defaultJanitorInterval = 8 * time.Second
|
||||||
|
|
||||||
|
defaultJanitorBatchSize = 100
|
||||||
)
|
)
|
||||||
|
|
||||||
// NewServer returns a new Server given a redis connection option
|
// NewServer returns a new Server given a redis connection option
|
||||||
// and background processing configuration.
|
// and server configuration.
|
||||||
func NewServer(r RedisConnOpt, cfg Config) *Server {
|
func NewServer(r RedisConnOpt, cfg Config) *Server {
|
||||||
c, ok := r.MakeRedisClient().(redis.UniversalClient)
|
redisClient, ok := r.MakeRedisClient().(redis.UniversalClient)
|
||||||
if !ok {
|
if !ok {
|
||||||
panic(fmt.Sprintf("asynq: unsupported RedisConnOpt type %T", r))
|
panic(fmt.Sprintf("asynq: unsupported RedisConnOpt type %T", r))
|
||||||
}
|
}
|
||||||
|
server := NewServerFromRedisClient(redisClient, cfg)
|
||||||
|
server.sharedConnection = false
|
||||||
|
return server
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewServerFromRedisClient returns a new instance of Server given a redis.UniversalClient
|
||||||
|
// and server configuration
|
||||||
|
// Warning: The underlying redis connection pool will not be closed by Asynq, you are responsible for closing it.
|
||||||
|
func NewServerFromRedisClient(c redis.UniversalClient, cfg Config) *Server {
|
||||||
|
baseCtxFn := cfg.BaseContext
|
||||||
|
if baseCtxFn == nil {
|
||||||
|
baseCtxFn = context.Background
|
||||||
|
}
|
||||||
n := cfg.Concurrency
|
n := cfg.Concurrency
|
||||||
if n < 1 {
|
if n < 1 {
|
||||||
n = runtime.NumCPU()
|
n = runtime.NumCPU()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
taskCheckInterval := cfg.TaskCheckInterval
|
||||||
|
if taskCheckInterval <= 0 {
|
||||||
|
taskCheckInterval = defaultTaskCheckInterval
|
||||||
|
}
|
||||||
|
|
||||||
delayFunc := cfg.RetryDelayFunc
|
delayFunc := cfg.RetryDelayFunc
|
||||||
if delayFunc == nil {
|
if delayFunc == nil {
|
||||||
delayFunc = DefaultRetryDelayFunc
|
delayFunc = DefaultRetryDelayFunc
|
||||||
}
|
}
|
||||||
|
isFailureFunc := cfg.IsFailure
|
||||||
|
if isFailureFunc == nil {
|
||||||
|
isFailureFunc = defaultIsFailureFunc
|
||||||
|
}
|
||||||
queues := make(map[string]int)
|
queues := make(map[string]int)
|
||||||
for qname, p := range cfg.Queues {
|
for qname, p := range cfg.Queues {
|
||||||
|
if err := base.ValidateQueueName(qname); err != nil {
|
||||||
|
continue // ignore invalid queue names
|
||||||
|
}
|
||||||
if p > 0 {
|
if p > 0 {
|
||||||
queues[qname] = p
|
queues[qname] = p
|
||||||
}
|
}
|
||||||
@@ -313,6 +490,14 @@ func NewServer(r RedisConnOpt, cfg Config) *Server {
|
|||||||
if healthcheckInterval == 0 {
|
if healthcheckInterval == 0 {
|
||||||
healthcheckInterval = defaultHealthCheckInterval
|
healthcheckInterval = defaultHealthCheckInterval
|
||||||
}
|
}
|
||||||
|
// TODO: Create a helper to check for zero value and fall back to default (e.g. getDurationOrDefault())
|
||||||
|
groupGracePeriod := cfg.GroupGracePeriod
|
||||||
|
if groupGracePeriod == 0 {
|
||||||
|
groupGracePeriod = defaultGroupGracePeriod
|
||||||
|
}
|
||||||
|
if groupGracePeriod < time.Second {
|
||||||
|
panic("GroupGracePeriod cannot be less than a second")
|
||||||
|
}
|
||||||
logger := log.NewLogger(cfg.Logger)
|
logger := log.NewLogger(cfg.Logger)
|
||||||
loglevel := cfg.LogLevel
|
loglevel := cfg.LogLevel
|
||||||
if loglevel == level_unspecified {
|
if loglevel == level_unspecified {
|
||||||
@@ -324,7 +509,7 @@ func NewServer(r RedisConnOpt, cfg Config) *Server {
|
|||||||
starting := make(chan *workerInfo)
|
starting := make(chan *workerInfo)
|
||||||
finished := make(chan *base.TaskMessage)
|
finished := make(chan *base.TaskMessage)
|
||||||
syncCh := make(chan *syncRequest)
|
syncCh := make(chan *syncRequest)
|
||||||
status := base.NewServerStatus(base.StatusIdle)
|
srvState := &serverState{value: srvStateNew}
|
||||||
cancels := base.NewCancelations()
|
cancels := base.NewCancelations()
|
||||||
|
|
||||||
syncer := newSyncer(syncerParams{
|
syncer := newSyncer(syncerParams{
|
||||||
@@ -339,15 +524,19 @@ func NewServer(r RedisConnOpt, cfg Config) *Server {
|
|||||||
concurrency: n,
|
concurrency: n,
|
||||||
queues: queues,
|
queues: queues,
|
||||||
strictPriority: cfg.StrictPriority,
|
strictPriority: cfg.StrictPriority,
|
||||||
status: status,
|
state: srvState,
|
||||||
starting: starting,
|
starting: starting,
|
||||||
finished: finished,
|
finished: finished,
|
||||||
})
|
})
|
||||||
|
delayedTaskCheckInterval := cfg.DelayedTaskCheckInterval
|
||||||
|
if delayedTaskCheckInterval == 0 {
|
||||||
|
delayedTaskCheckInterval = defaultDelayedTaskCheckInterval
|
||||||
|
}
|
||||||
forwarder := newForwarder(forwarderParams{
|
forwarder := newForwarder(forwarderParams{
|
||||||
logger: logger,
|
logger: logger,
|
||||||
broker: rdb,
|
broker: rdb,
|
||||||
queues: qnames,
|
queues: qnames,
|
||||||
interval: 5 * time.Second,
|
interval: delayedTaskCheckInterval,
|
||||||
})
|
})
|
||||||
subscriber := newSubscriber(subscriberParams{
|
subscriber := newSubscriber(subscriberParams{
|
||||||
logger: logger,
|
logger: logger,
|
||||||
@@ -355,23 +544,27 @@ func NewServer(r RedisConnOpt, cfg Config) *Server {
|
|||||||
cancelations: cancels,
|
cancelations: cancels,
|
||||||
})
|
})
|
||||||
processor := newProcessor(processorParams{
|
processor := newProcessor(processorParams{
|
||||||
logger: logger,
|
logger: logger,
|
||||||
broker: rdb,
|
broker: rdb,
|
||||||
retryDelayFunc: delayFunc,
|
retryDelayFunc: delayFunc,
|
||||||
syncCh: syncCh,
|
taskCheckInterval: taskCheckInterval,
|
||||||
cancelations: cancels,
|
baseCtxFn: baseCtxFn,
|
||||||
concurrency: n,
|
isFailureFunc: isFailureFunc,
|
||||||
queues: queues,
|
syncCh: syncCh,
|
||||||
strictPriority: cfg.StrictPriority,
|
cancelations: cancels,
|
||||||
errHandler: cfg.ErrorHandler,
|
concurrency: n,
|
||||||
shutdownTimeout: shutdownTimeout,
|
queues: queues,
|
||||||
starting: starting,
|
strictPriority: cfg.StrictPriority,
|
||||||
finished: finished,
|
errHandler: cfg.ErrorHandler,
|
||||||
|
shutdownTimeout: shutdownTimeout,
|
||||||
|
starting: starting,
|
||||||
|
finished: finished,
|
||||||
})
|
})
|
||||||
recoverer := newRecoverer(recovererParams{
|
recoverer := newRecoverer(recovererParams{
|
||||||
logger: logger,
|
logger: logger,
|
||||||
broker: rdb,
|
broker: rdb,
|
||||||
retryDelayFunc: delayFunc,
|
retryDelayFunc: delayFunc,
|
||||||
|
isFailureFunc: isFailureFunc,
|
||||||
queues: qnames,
|
queues: qnames,
|
||||||
interval: 1 * time.Minute,
|
interval: 1 * time.Minute,
|
||||||
})
|
})
|
||||||
@@ -381,17 +574,50 @@ func NewServer(r RedisConnOpt, cfg Config) *Server {
|
|||||||
interval: healthcheckInterval,
|
interval: healthcheckInterval,
|
||||||
healthcheckFunc: cfg.HealthCheckFunc,
|
healthcheckFunc: cfg.HealthCheckFunc,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
janitorInterval := cfg.JanitorInterval
|
||||||
|
if janitorInterval == 0 {
|
||||||
|
janitorInterval = defaultJanitorInterval
|
||||||
|
}
|
||||||
|
|
||||||
|
janitorBatchSize := cfg.JanitorBatchSize
|
||||||
|
if janitorBatchSize == 0 {
|
||||||
|
janitorBatchSize = defaultJanitorBatchSize
|
||||||
|
}
|
||||||
|
if janitorBatchSize > defaultJanitorBatchSize {
|
||||||
|
logger.Warnf("Janitor batch size of %d is greater than the recommended batch size of %d. "+
|
||||||
|
"This might cause a long-running script", janitorBatchSize, defaultJanitorBatchSize)
|
||||||
|
}
|
||||||
|
janitor := newJanitor(janitorParams{
|
||||||
|
logger: logger,
|
||||||
|
broker: rdb,
|
||||||
|
queues: qnames,
|
||||||
|
interval: janitorInterval,
|
||||||
|
batchSize: janitorBatchSize,
|
||||||
|
})
|
||||||
|
aggregator := newAggregator(aggregatorParams{
|
||||||
|
logger: logger,
|
||||||
|
broker: rdb,
|
||||||
|
queues: qnames,
|
||||||
|
gracePeriod: groupGracePeriod,
|
||||||
|
maxDelay: cfg.GroupMaxDelay,
|
||||||
|
maxSize: cfg.GroupMaxSize,
|
||||||
|
groupAggregator: cfg.GroupAggregator,
|
||||||
|
})
|
||||||
return &Server{
|
return &Server{
|
||||||
logger: logger,
|
logger: logger,
|
||||||
broker: rdb,
|
broker: rdb,
|
||||||
status: status,
|
sharedConnection: true,
|
||||||
forwarder: forwarder,
|
state: srvState,
|
||||||
processor: processor,
|
forwarder: forwarder,
|
||||||
syncer: syncer,
|
processor: processor,
|
||||||
heartbeater: heartbeater,
|
syncer: syncer,
|
||||||
subscriber: subscriber,
|
heartbeater: heartbeater,
|
||||||
recoverer: recoverer,
|
subscriber: subscriber,
|
||||||
healthchecker: healthchecker,
|
recoverer: recoverer,
|
||||||
|
healthchecker: healthchecker,
|
||||||
|
janitor: janitor,
|
||||||
|
aggregator: aggregator,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -400,11 +626,13 @@ func NewServer(r RedisConnOpt, cfg Config) *Server {
|
|||||||
// ProcessTask should return nil if the processing of a task
|
// ProcessTask should return nil if the processing of a task
|
||||||
// is successful.
|
// is successful.
|
||||||
//
|
//
|
||||||
// If ProcessTask return a non-nil error or panics, the task
|
// If ProcessTask returns a non-nil error or panics, the task
|
||||||
// will be retried after delay.
|
// will be retried after delay if retry-count is remaining,
|
||||||
// One exception to this rule is when ProcessTask returns SkipRetry error.
|
// otherwise the task will be archived.
|
||||||
// If the returned error is SkipRetry or the error wraps SkipRetry, retry is
|
//
|
||||||
// skipped and task will be archived instead.
|
// One exception to this rule is when ProcessTask returns a SkipRetry error.
|
||||||
|
// If the returned error is SkipRetry or an error wraps SkipRetry, retry is
|
||||||
|
// skipped and the task will be immediately archived instead.
|
||||||
type Handler interface {
|
type Handler interface {
|
||||||
ProcessTask(context.Context, *Task) error
|
ProcessTask(context.Context, *Task) error
|
||||||
}
|
}
|
||||||
@@ -420,45 +648,42 @@ func (fn HandlerFunc) ProcessTask(ctx context.Context, task *Task) error {
|
|||||||
return fn(ctx, task)
|
return fn(ctx, task)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ErrServerStopped indicates that the operation is now illegal because of the server being stopped.
|
// ErrServerClosed indicates that the operation is now illegal because of the server has been shutdown.
|
||||||
var ErrServerStopped = errors.New("asynq: the server has been stopped")
|
var ErrServerClosed = errors.New("asynq: Server closed")
|
||||||
|
|
||||||
// Run starts the background-task processing and blocks until
|
// Run starts the task processing and blocks until
|
||||||
// an os signal to exit the program is received. Once it receives
|
// an os signal to exit the program is received. Once it receives
|
||||||
// a signal, it gracefully shuts down all active workers and other
|
// a signal, it gracefully shuts down all active workers and other
|
||||||
// goroutines to process the tasks.
|
// goroutines to process the tasks.
|
||||||
//
|
//
|
||||||
// Run returns any error encountered during server startup time.
|
// Run returns any error encountered at server startup time.
|
||||||
// If the server has already been stopped, ErrServerStopped is returned.
|
// If the server has already been shutdown, ErrServerClosed is returned.
|
||||||
func (srv *Server) Run(handler Handler) error {
|
func (srv *Server) Run(handler Handler) error {
|
||||||
if err := srv.Start(handler); err != nil {
|
if err := srv.Start(handler); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
srv.waitForSignals()
|
srv.waitForSignals()
|
||||||
srv.Stop()
|
srv.Shutdown()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Start starts the worker server. Once the server has started,
|
// Start starts the worker server. Once the server has started,
|
||||||
// it pulls tasks off queues and starts a worker goroutine for each task.
|
// it pulls tasks off queues and starts a worker goroutine for each task
|
||||||
// Tasks are processed concurrently by the workers up to the number of
|
// and then call Handler to process it.
|
||||||
// concurrency specified at the initialization time.
|
// Tasks are processed concurrently by the workers up to the number of
|
||||||
|
// concurrency specified in Config.Concurrency.
|
||||||
//
|
//
|
||||||
// Start returns any error encountered during server startup time.
|
// Start returns any error encountered at server startup time.
|
||||||
// If the server has already been stopped, ErrServerStopped is returned.
|
// If the server has already been shutdown, ErrServerClosed is returned.
|
||||||
func (srv *Server) Start(handler Handler) error {
|
func (srv *Server) Start(handler Handler) error {
|
||||||
if handler == nil {
|
if handler == nil {
|
||||||
return fmt.Errorf("asynq: server cannot run with nil handler")
|
return fmt.Errorf("asynq: server cannot run with nil handler")
|
||||||
}
|
}
|
||||||
switch srv.status.Get() {
|
|
||||||
case base.StatusRunning:
|
|
||||||
return fmt.Errorf("asynq: the server is already running")
|
|
||||||
case base.StatusStopped:
|
|
||||||
return ErrServerStopped
|
|
||||||
}
|
|
||||||
srv.status.Set(base.StatusRunning)
|
|
||||||
srv.processor.handler = handler
|
srv.processor.handler = handler
|
||||||
|
|
||||||
|
if err := srv.start(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
srv.logger.Info("Starting processing")
|
srv.logger.Info("Starting processing")
|
||||||
|
|
||||||
srv.heartbeater.start(&srv.wg)
|
srv.heartbeater.start(&srv.wg)
|
||||||
@@ -468,46 +693,80 @@ func (srv *Server) Start(handler Handler) error {
|
|||||||
srv.recoverer.start(&srv.wg)
|
srv.recoverer.start(&srv.wg)
|
||||||
srv.forwarder.start(&srv.wg)
|
srv.forwarder.start(&srv.wg)
|
||||||
srv.processor.start(&srv.wg)
|
srv.processor.start(&srv.wg)
|
||||||
|
srv.janitor.start(&srv.wg)
|
||||||
|
srv.aggregator.start(&srv.wg)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stop stops the worker server.
|
// Checks server state and returns an error if pre-condition is not met.
|
||||||
|
// Otherwise it sets the server state to active.
|
||||||
|
func (srv *Server) start() error {
|
||||||
|
srv.state.mu.Lock()
|
||||||
|
defer srv.state.mu.Unlock()
|
||||||
|
switch srv.state.value {
|
||||||
|
case srvStateActive:
|
||||||
|
return fmt.Errorf("asynq: the server is already running")
|
||||||
|
case srvStateStopped:
|
||||||
|
return fmt.Errorf("asynq: the server is in the stopped state. Waiting for shutdown.")
|
||||||
|
case srvStateClosed:
|
||||||
|
return ErrServerClosed
|
||||||
|
}
|
||||||
|
srv.state.value = srvStateActive
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Shutdown gracefully shuts down the server.
|
||||||
// It gracefully closes all active workers. The server will wait for
|
// It gracefully closes all active workers. The server will wait for
|
||||||
// active workers to finish processing tasks for duration specified in Config.ShutdownTimeout.
|
// active workers to finish processing tasks for duration specified in Config.ShutdownTimeout.
|
||||||
// If worker didn't finish processing a task during the timeout, the task will be pushed back to Redis.
|
// If worker didn't finish processing a task during the timeout, the task will be pushed back to Redis.
|
||||||
func (srv *Server) Stop() {
|
func (srv *Server) Shutdown() {
|
||||||
switch srv.status.Get() {
|
srv.state.mu.Lock()
|
||||||
case base.StatusIdle, base.StatusStopped:
|
if srv.state.value == srvStateNew || srv.state.value == srvStateClosed {
|
||||||
|
srv.state.mu.Unlock()
|
||||||
// server is not running, do nothing and return.
|
// server is not running, do nothing and return.
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
srv.state.value = srvStateClosed
|
||||||
|
srv.state.mu.Unlock()
|
||||||
|
|
||||||
srv.logger.Info("Starting graceful shutdown")
|
srv.logger.Info("Starting graceful shutdown")
|
||||||
// Note: The order of termination is important.
|
// Note: The order of shutdown is important.
|
||||||
// Sender goroutines should be terminated before the receiver goroutines.
|
// Sender goroutines should be terminated before the receiver goroutines.
|
||||||
// processor -> syncer (via syncCh)
|
// processor -> syncer (via syncCh)
|
||||||
// processor -> heartbeater (via starting, finished channels)
|
// processor -> heartbeater (via starting, finished channels)
|
||||||
srv.forwarder.terminate()
|
srv.forwarder.shutdown()
|
||||||
srv.processor.terminate()
|
srv.processor.shutdown()
|
||||||
srv.recoverer.terminate()
|
srv.recoverer.shutdown()
|
||||||
srv.syncer.terminate()
|
srv.syncer.shutdown()
|
||||||
srv.subscriber.terminate()
|
srv.subscriber.shutdown()
|
||||||
srv.healthchecker.terminate()
|
srv.janitor.shutdown()
|
||||||
srv.heartbeater.terminate()
|
srv.aggregator.shutdown()
|
||||||
|
srv.healthchecker.shutdown()
|
||||||
|
srv.heartbeater.shutdown()
|
||||||
srv.wg.Wait()
|
srv.wg.Wait()
|
||||||
|
|
||||||
srv.broker.Close()
|
if !srv.sharedConnection {
|
||||||
srv.status.Set(base.StatusStopped)
|
srv.broker.Close()
|
||||||
|
}
|
||||||
srv.logger.Info("Exiting")
|
srv.logger.Info("Exiting")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Quiet signals the server to stop pulling new tasks off queues.
|
// Stop signals the server to stop pulling new tasks off queues.
|
||||||
// Quiet should be used before stopping the server.
|
// Stop can be used before shutting down the server to ensure that all
|
||||||
func (srv *Server) Quiet() {
|
// currently active tasks are processed before server shutdown.
|
||||||
|
//
|
||||||
|
// Stop does not shutdown the server, make sure to call Shutdown before exit.
|
||||||
|
func (srv *Server) Stop() {
|
||||||
|
srv.state.mu.Lock()
|
||||||
|
if srv.state.value != srvStateActive {
|
||||||
|
// Invalid calll to Stop, server can only go from Active state to Stopped state.
|
||||||
|
srv.state.mu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
srv.state.value = srvStateStopped
|
||||||
|
srv.state.mu.Unlock()
|
||||||
|
|
||||||
srv.logger.Info("Stopping processor")
|
srv.logger.Info("Stopping processor")
|
||||||
srv.processor.stop()
|
srv.processor.stop()
|
||||||
srv.status.Set(base.StatusQuiet)
|
|
||||||
srv.logger.Info("Processor stopped")
|
srv.logger.Info("Processor stopped")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,22 +13,13 @@ import (
|
|||||||
|
|
||||||
"github.com/hibiken/asynq/internal/rdb"
|
"github.com/hibiken/asynq/internal/rdb"
|
||||||
"github.com/hibiken/asynq/internal/testbroker"
|
"github.com/hibiken/asynq/internal/testbroker"
|
||||||
|
"github.com/hibiken/asynq/internal/testutil"
|
||||||
|
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
"go.uber.org/goleak"
|
"go.uber.org/goleak"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestServer(t *testing.T) {
|
func testServer(t *testing.T, c *Client, srv *Server) {
|
||||||
// https://github.com/go-redis/redis/issues/1029
|
|
||||||
ignoreOpt := goleak.IgnoreTopFunction("github.com/go-redis/redis/v7/internal/pool.(*ConnPool).reaper")
|
|
||||||
defer goleak.VerifyNoLeaks(t, ignoreOpt)
|
|
||||||
|
|
||||||
redisConnOpt := getRedisConnOpt(t)
|
|
||||||
c := NewClient(redisConnOpt)
|
|
||||||
defer c.Close()
|
|
||||||
srv := NewServer(redisConnOpt, Config{
|
|
||||||
Concurrency: 10,
|
|
||||||
LogLevel: testLogLevel,
|
|
||||||
})
|
|
||||||
|
|
||||||
// no-op handler
|
// no-op handler
|
||||||
h := func(ctx context.Context, task *Task) error {
|
h := func(ctx context.Context, task *Task) error {
|
||||||
return nil
|
return nil
|
||||||
@@ -39,23 +30,60 @@ func TestServer(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = c.Enqueue(NewTask("send_email", map[string]interface{}{"recipient_id": 123}))
|
_, err = c.Enqueue(NewTask("send_email", testutil.JSON(map[string]interface{}{"recipient_id": 123})))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Errorf("could not enqueue a task: %v", err)
|
t.Errorf("could not enqueue a task: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = c.Enqueue(NewTask("send_email", map[string]interface{}{"recipient_id": 456}), ProcessIn(1*time.Hour))
|
_, err = c.Enqueue(NewTask("send_email", testutil.JSON(map[string]interface{}{"recipient_id": 456})), ProcessIn(1*time.Hour))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Errorf("could not enqueue a task: %v", err)
|
t.Errorf("could not enqueue a task: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
srv.Stop()
|
srv.Shutdown()
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServer(t *testing.T) {
|
||||||
|
// https://github.com/go-redis/redis/issues/1029
|
||||||
|
ignoreOpt := goleak.IgnoreTopFunction("github.com/redis/go-redis/v9/internal/pool.(*ConnPool).reaper")
|
||||||
|
defer goleak.VerifyNone(t, ignoreOpt)
|
||||||
|
|
||||||
|
redisConnOpt := getRedisConnOpt(t)
|
||||||
|
c := NewClient(redisConnOpt)
|
||||||
|
defer c.Close()
|
||||||
|
srv := NewServer(redisConnOpt, Config{
|
||||||
|
Concurrency: 10,
|
||||||
|
LogLevel: testLogLevel,
|
||||||
|
})
|
||||||
|
|
||||||
|
testServer(t, c, srv)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServerFromRedisClient(t *testing.T) {
|
||||||
|
// https://github.com/go-redis/redis/issues/1029
|
||||||
|
ignoreOpt := goleak.IgnoreTopFunction("github.com/redis/go-redis/v9/internal/pool.(*ConnPool).reaper")
|
||||||
|
defer goleak.VerifyNone(t, ignoreOpt)
|
||||||
|
|
||||||
|
redisConnOpt := getRedisConnOpt(t)
|
||||||
|
redisClient := redisConnOpt.MakeRedisClient().(redis.UniversalClient)
|
||||||
|
c := NewClientFromRedisClient(redisClient)
|
||||||
|
srv := NewServerFromRedisClient(redisClient, Config{
|
||||||
|
Concurrency: 10,
|
||||||
|
LogLevel: testLogLevel,
|
||||||
|
})
|
||||||
|
|
||||||
|
testServer(t, c, srv)
|
||||||
|
|
||||||
|
err := c.Close()
|
||||||
|
if err == nil {
|
||||||
|
t.Error("client.Close() should have failed because of a shared client but it didn't")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestServerRun(t *testing.T) {
|
func TestServerRun(t *testing.T) {
|
||||||
// https://github.com/go-redis/redis/issues/1029
|
// https://github.com/go-redis/redis/issues/1029
|
||||||
ignoreOpt := goleak.IgnoreTopFunction("github.com/go-redis/redis/v7/internal/pool.(*ConnPool).reaper")
|
ignoreOpt := goleak.IgnoreTopFunction("github.com/redis/go-redis/v9/internal/pool.(*ConnPool).reaper")
|
||||||
defer goleak.VerifyNoLeaks(t, ignoreOpt)
|
defer goleak.VerifyNone(t, ignoreOpt)
|
||||||
|
|
||||||
srv := NewServer(RedisClientOpt{Addr: ":6379"}, Config{LogLevel: testLogLevel})
|
srv := NewServer(RedisClientOpt{Addr: ":6379"}, Config{LogLevel: testLogLevel})
|
||||||
|
|
||||||
@@ -81,16 +109,16 @@ func TestServerRun(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestServerErrServerStopped(t *testing.T) {
|
func TestServerErrServerClosed(t *testing.T) {
|
||||||
srv := NewServer(RedisClientOpt{Addr: ":6379"}, Config{LogLevel: testLogLevel})
|
srv := NewServer(RedisClientOpt{Addr: ":6379"}, Config{LogLevel: testLogLevel})
|
||||||
handler := NewServeMux()
|
handler := NewServeMux()
|
||||||
if err := srv.Start(handler); err != nil {
|
if err := srv.Start(handler); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
srv.Stop()
|
srv.Shutdown()
|
||||||
err := srv.Start(handler)
|
err := srv.Start(handler)
|
||||||
if err != ErrServerStopped {
|
if err != ErrServerClosed {
|
||||||
t.Errorf("Restarting server: (*Server).Start(handler) = %v, want ErrServerStopped error", err)
|
t.Errorf("Restarting server: (*Server).Start(handler) = %v, want ErrServerClosed error", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,7 +127,7 @@ func TestServerErrNilHandler(t *testing.T) {
|
|||||||
err := srv.Start(nil)
|
err := srv.Start(nil)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Error("Starting server with nil handler: (*Server).Start(nil) did not return error")
|
t.Error("Starting server with nil handler: (*Server).Start(nil) did not return error")
|
||||||
srv.Stop()
|
srv.Shutdown()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,7 +141,7 @@ func TestServerErrServerRunning(t *testing.T) {
|
|||||||
if err == nil {
|
if err == nil {
|
||||||
t.Error("Calling (*Server).Start(handler) on already running server did not return error")
|
t.Error("Calling (*Server).Start(handler) on already running server did not return error")
|
||||||
}
|
}
|
||||||
srv.Stop()
|
srv.Shutdown()
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestServerWithRedisDown(t *testing.T) {
|
func TestServerWithRedisDown(t *testing.T) {
|
||||||
@@ -145,7 +173,7 @@ func TestServerWithRedisDown(t *testing.T) {
|
|||||||
|
|
||||||
time.Sleep(3 * time.Second)
|
time.Sleep(3 * time.Second)
|
||||||
|
|
||||||
srv.Stop()
|
srv.Shutdown()
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestServerWithFlakyBroker(t *testing.T) {
|
func TestServerWithFlakyBroker(t *testing.T) {
|
||||||
@@ -169,8 +197,8 @@ func TestServerWithFlakyBroker(t *testing.T) {
|
|||||||
|
|
||||||
h := func(ctx context.Context, task *Task) error {
|
h := func(ctx context.Context, task *Task) error {
|
||||||
// force task retry.
|
// force task retry.
|
||||||
if task.Type == "bad_task" {
|
if task.Type() == "bad_task" {
|
||||||
return fmt.Errorf("could not process %q", task.Type)
|
return fmt.Errorf("could not process %q", task.Type())
|
||||||
}
|
}
|
||||||
time.Sleep(2 * time.Second)
|
time.Sleep(2 * time.Second)
|
||||||
return nil
|
return nil
|
||||||
@@ -206,7 +234,7 @@ func TestServerWithFlakyBroker(t *testing.T) {
|
|||||||
|
|
||||||
time.Sleep(3 * time.Second)
|
time.Sleep(3 * time.Second)
|
||||||
|
|
||||||
srv.Stop()
|
srv.Shutdown()
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestLogLevel(t *testing.T) {
|
func TestLogLevel(t *testing.T) {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// +build linux bsd darwin
|
//go:build linux || dragonfly || freebsd || netbsd || openbsd || darwin
|
||||||
|
|
||||||
package asynq
|
package asynq
|
||||||
|
|
||||||
@@ -22,7 +22,7 @@ func (srv *Server) waitForSignals() {
|
|||||||
for {
|
for {
|
||||||
sig := <-sigs
|
sig := <-sigs
|
||||||
if sig == unix.SIGTSTP {
|
if sig == unix.SIGTSTP {
|
||||||
srv.Quiet()
|
srv.Stop()
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// +build windows
|
//go:build windows
|
||||||
|
|
||||||
package asynq
|
package asynq
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/go-redis/redis/v7"
|
"github.com/redis/go-redis/v9"
|
||||||
"github.com/hibiken/asynq/internal/base"
|
"github.com/hibiken/asynq/internal/base"
|
||||||
"github.com/hibiken/asynq/internal/log"
|
"github.com/hibiken/asynq/internal/log"
|
||||||
)
|
)
|
||||||
@@ -43,7 +43,7 @@ func newSubscriber(params subscriberParams) *subscriber {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *subscriber) terminate() {
|
func (s *subscriber) shutdown() {
|
||||||
s.logger.Debug("Subscriber shutting down...")
|
s.logger.Debug("Subscriber shutting down...")
|
||||||
// Signal the subscriber goroutine to stop.
|
// Signal the subscriber goroutine to stop.
|
||||||
s.done <- struct{}{}
|
s.done <- struct{}{}
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ func TestSubscriber(t *testing.T) {
|
|||||||
})
|
})
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
subscriber.start(&wg)
|
subscriber.start(&wg)
|
||||||
defer subscriber.terminate()
|
defer subscriber.shutdown()
|
||||||
|
|
||||||
// wait for subscriber to establish connection to pubsub channel
|
// wait for subscriber to establish connection to pubsub channel
|
||||||
time.Sleep(time.Second)
|
time.Sleep(time.Second)
|
||||||
@@ -91,7 +91,7 @@ func TestSubscriberWithRedisDown(t *testing.T) {
|
|||||||
testBroker.Sleep() // simulate a situation where subscriber cannot connect to redis.
|
testBroker.Sleep() // simulate a situation where subscriber cannot connect to redis.
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
subscriber.start(&wg)
|
subscriber.start(&wg)
|
||||||
defer subscriber.terminate()
|
defer subscriber.shutdown()
|
||||||
|
|
||||||
time.Sleep(2 * time.Second) // subscriber should wait and retry connecting to redis.
|
time.Sleep(2 * time.Second) // subscriber should wait and retry connecting to redis.
|
||||||
|
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ func newSyncer(params syncerParams) *syncer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *syncer) terminate() {
|
func (s *syncer) shutdown() {
|
||||||
s.logger.Debug("Syncer shutting down...")
|
s.logger.Debug("Syncer shutting down...")
|
||||||
// Signal the syncer goroutine to stop.
|
// Signal the syncer goroutine to stop.
|
||||||
s.done <- struct{}{}
|
s.done <- struct{}{}
|
||||||
|
|||||||
@@ -5,14 +5,15 @@
|
|||||||
package asynq
|
package asynq
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
h "github.com/hibiken/asynq/internal/asynqtest"
|
|
||||||
"github.com/hibiken/asynq/internal/base"
|
"github.com/hibiken/asynq/internal/base"
|
||||||
"github.com/hibiken/asynq/internal/rdb"
|
"github.com/hibiken/asynq/internal/rdb"
|
||||||
|
h "github.com/hibiken/asynq/internal/testutil"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestSyncer(t *testing.T) {
|
func TestSyncer(t *testing.T) {
|
||||||
@@ -35,13 +36,13 @@ func TestSyncer(t *testing.T) {
|
|||||||
})
|
})
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
syncer.start(&wg)
|
syncer.start(&wg)
|
||||||
defer syncer.terminate()
|
defer syncer.shutdown()
|
||||||
|
|
||||||
for _, msg := range inProgress {
|
for _, msg := range inProgress {
|
||||||
m := msg
|
m := msg
|
||||||
syncRequestCh <- &syncRequest{
|
syncRequestCh <- &syncRequest{
|
||||||
fn: func() error {
|
fn: func() error {
|
||||||
return rdbClient.Done(m)
|
return rdbClient.Done(context.Background(), m)
|
||||||
},
|
},
|
||||||
deadline: time.Now().Add(5 * time.Minute),
|
deadline: time.Now().Add(5 * time.Minute),
|
||||||
}
|
}
|
||||||
@@ -66,7 +67,7 @@ func TestSyncerRetry(t *testing.T) {
|
|||||||
|
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
syncer.start(&wg)
|
syncer.start(&wg)
|
||||||
defer syncer.terminate()
|
defer syncer.shutdown()
|
||||||
|
|
||||||
var (
|
var (
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
@@ -131,7 +132,7 @@ func TestSyncerDropsStaleRequests(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
time.Sleep(2 * interval) // ensure that syncer runs at least once
|
time.Sleep(2 * interval) // ensure that syncer runs at least once
|
||||||
syncer.terminate()
|
syncer.shutdown()
|
||||||
|
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
if n != 0 {
|
if n != 0 {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ Asynq CLI is a command line tool to monitor the queues and tasks managed by `asy
|
|||||||
|
|
||||||
In order to use the tool, compile it using the following command:
|
In order to use the tool, compile it using the following command:
|
||||||
|
|
||||||
go get github.com/hibiken/asynq/tools/asynq
|
go install github.com/hibiken/asynq/tools/asynq@latest
|
||||||
|
|
||||||
This will create the asynq executable under your `$GOPATH/bin` directory.
|
This will create the asynq executable under your `$GOPATH/bin` directory.
|
||||||
|
|
||||||
@@ -22,9 +22,10 @@ This will create the asynq executable under your `$GOPATH/bin` directory.
|
|||||||
|
|
||||||
To view details on any command, use `asynq help <command> <subcommand>`.
|
To view details on any command, use `asynq help <command> <subcommand>`.
|
||||||
|
|
||||||
|
- `asynq dash`
|
||||||
- `asynq stats`
|
- `asynq stats`
|
||||||
- `asynq queue [ls inspect history rm pause unpause]`
|
- `asynq queue [ls inspect history rm pause unpause]`
|
||||||
- `asynq task [ls cancel delete archive run delete-all archive-all run-all]`
|
- `asynq task [ls cancel delete archive run deleteall archiveall runall]`
|
||||||
- `asynq server [ls]`
|
- `asynq server [ls]`
|
||||||
|
|
||||||
### Global flags
|
### Global flags
|
||||||
|
|||||||
@@ -11,7 +11,8 @@ import (
|
|||||||
"sort"
|
"sort"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/hibiken/asynq/inspeq"
|
"github.com/MakeNowJust/heredoc/v2"
|
||||||
|
"github.com/hibiken/asynq"
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -24,21 +25,30 @@ func init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var cronCmd = &cobra.Command{
|
var cronCmd = &cobra.Command{
|
||||||
Use: "cron",
|
Use: "cron <command> [flags]",
|
||||||
Short: "Manage cron",
|
Short: "Manage cron",
|
||||||
|
Example: heredoc.Doc(`
|
||||||
|
$ asynq cron ls
|
||||||
|
$ asynq cron history 7837f142-6337-4217-9276-8f27281b67d1`),
|
||||||
}
|
}
|
||||||
|
|
||||||
var cronListCmd = &cobra.Command{
|
var cronListCmd = &cobra.Command{
|
||||||
Use: "ls",
|
Use: "list",
|
||||||
Short: "List cron entries",
|
Aliases: []string{"ls"},
|
||||||
Run: cronList,
|
Short: "List cron entries",
|
||||||
|
Run: cronList,
|
||||||
}
|
}
|
||||||
|
|
||||||
var cronHistoryCmd = &cobra.Command{
|
var cronHistoryCmd = &cobra.Command{
|
||||||
Use: "history [ENTRY_ID...]",
|
Use: "history <entry_id> [<entry_id>...]",
|
||||||
Short: "Show history of each cron tasks",
|
Short: "Show history of each cron tasks",
|
||||||
Args: cobra.MinimumNArgs(1),
|
Args: cobra.MinimumNArgs(1),
|
||||||
Run: cronHistory,
|
Run: cronHistory,
|
||||||
|
Example: heredoc.Doc(`
|
||||||
|
$ asynq cron history 7837f142-6337-4217-9276-8f27281b67d1
|
||||||
|
$ asynq cron history 7837f142-6337-4217-9276-8f27281b67d1 bf6a8594-cd03-4968-b36a-8572c5e160dd
|
||||||
|
$ asynq cron history 7837f142-6337-4217-9276-8f27281b67d1 --size=100
|
||||||
|
$ asynq cron history 7837f142-6337-4217-9276-8f27281b67d1 --page=2`),
|
||||||
}
|
}
|
||||||
|
|
||||||
func cronList(cmd *cobra.Command, args []string) {
|
func cronList(cmd *cobra.Command, args []string) {
|
||||||
@@ -63,7 +73,7 @@ func cronList(cmd *cobra.Command, args []string) {
|
|||||||
cols := []string{"EntryID", "Spec", "Type", "Payload", "Options", "Next", "Prev"}
|
cols := []string{"EntryID", "Spec", "Type", "Payload", "Options", "Next", "Prev"}
|
||||||
printRows := func(w io.Writer, tmpl string) {
|
printRows := func(w io.Writer, tmpl string) {
|
||||||
for _, e := range entries {
|
for _, e := range entries {
|
||||||
fmt.Fprintf(w, tmpl, e.ID, e.Spec, e.Task.Type, e.Task.Payload, e.Opts,
|
fmt.Fprintf(w, tmpl, e.ID, e.Spec, e.Task.Type(), sprintBytes(e.Task.Payload()), e.Opts,
|
||||||
nextEnqueue(e.Next), prevEnqueue(e.Prev))
|
nextEnqueue(e.Next), prevEnqueue(e.Prev))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -108,7 +118,7 @@ func cronHistory(cmd *cobra.Command, args []string) {
|
|||||||
fmt.Printf("Entry: %s\n\n", entryID)
|
fmt.Printf("Entry: %s\n\n", entryID)
|
||||||
|
|
||||||
events, err := inspector.ListSchedulerEnqueueEvents(
|
events, err := inspector.ListSchedulerEnqueueEvents(
|
||||||
entryID, inspeq.PageSize(pageSize), inspeq.Page(pageNum))
|
entryID, asynq.PageSize(pageSize), asynq.Page(pageNum))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("error: %v\n", err)
|
fmt.Printf("error: %v\n", err)
|
||||||
continue
|
continue
|
||||||
|
|||||||
45
tools/asynq/cmd/dash.go
Normal file
45
tools/asynq/cmd/dash.go
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
// Copyright 2022 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package cmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/MakeNowJust/heredoc/v2"
|
||||||
|
"github.com/hibiken/asynq/tools/asynq/cmd/dash"
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
flagPollInterval = 8 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
rootCmd.AddCommand(dashCmd)
|
||||||
|
dashCmd.Flags().DurationVar(&flagPollInterval, "refresh", 8*time.Second, "Interval between data refresh (default: 8s, min allowed: 1s)")
|
||||||
|
}
|
||||||
|
|
||||||
|
var dashCmd = &cobra.Command{
|
||||||
|
Use: "dash",
|
||||||
|
Short: "View dashboard",
|
||||||
|
Long: heredoc.Doc(`
|
||||||
|
Display interactive dashboard.`),
|
||||||
|
Args: cobra.NoArgs,
|
||||||
|
Example: heredoc.Doc(`
|
||||||
|
$ asynq dash
|
||||||
|
$ asynq dash --refresh=3s`),
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
if flagPollInterval < 1*time.Second {
|
||||||
|
fmt.Println("error: --refresh cannot be less than 1s")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
dash.Run(dash.Options{
|
||||||
|
PollInterval: flagPollInterval,
|
||||||
|
RedisConnOpt: getRedisConnOpt(),
|
||||||
|
})
|
||||||
|
},
|
||||||
|
}
|
||||||
220
tools/asynq/cmd/dash/dash.go
Normal file
220
tools/asynq/cmd/dash/dash.go
Normal file
@@ -0,0 +1,220 @@
|
|||||||
|
// Copyright 2022 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package dash
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gdamore/tcell/v2"
|
||||||
|
"github.com/hibiken/asynq"
|
||||||
|
)
|
||||||
|
|
||||||
|
// viewType is an enum for dashboard views.
|
||||||
|
type viewType int
|
||||||
|
|
||||||
|
const (
|
||||||
|
viewTypeQueues viewType = iota
|
||||||
|
viewTypeQueueDetails
|
||||||
|
viewTypeHelp
|
||||||
|
)
|
||||||
|
|
||||||
|
// State holds dashboard state.
|
||||||
|
type State struct {
|
||||||
|
queues []*asynq.QueueInfo
|
||||||
|
tasks []*asynq.TaskInfo
|
||||||
|
groups []*asynq.GroupInfo
|
||||||
|
err error
|
||||||
|
|
||||||
|
// Note: index zero corresponds to the table header; index=1 correctponds to the first element
|
||||||
|
queueTableRowIdx int // highlighted row in queue table
|
||||||
|
taskTableRowIdx int // highlighted row in task table
|
||||||
|
groupTableRowIdx int // highlighted row in group table
|
||||||
|
taskState asynq.TaskState // highlighted task state in queue details view
|
||||||
|
taskID string // selected task ID
|
||||||
|
|
||||||
|
selectedQueue *asynq.QueueInfo // queue shown on queue details view
|
||||||
|
selectedGroup *asynq.GroupInfo
|
||||||
|
selectedTask *asynq.TaskInfo
|
||||||
|
|
||||||
|
pageNum int // pagination page number
|
||||||
|
|
||||||
|
view viewType // current view type
|
||||||
|
prevView viewType // to support "go back"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *State) DebugString() string {
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString(fmt.Sprintf("len(queues)=%d ", len(s.queues)))
|
||||||
|
b.WriteString(fmt.Sprintf("len(tasks)=%d ", len(s.tasks)))
|
||||||
|
b.WriteString(fmt.Sprintf("len(groups)=%d ", len(s.groups)))
|
||||||
|
b.WriteString(fmt.Sprintf("err=%v ", s.err))
|
||||||
|
|
||||||
|
if s.taskState != 0 {
|
||||||
|
b.WriteString(fmt.Sprintf("taskState=%s ", s.taskState.String()))
|
||||||
|
} else {
|
||||||
|
b.WriteString(fmt.Sprintf("taskState=0"))
|
||||||
|
}
|
||||||
|
b.WriteString(fmt.Sprintf("taskID=%s ", s.taskID))
|
||||||
|
|
||||||
|
b.WriteString(fmt.Sprintf("queueTableRowIdx=%d ", s.queueTableRowIdx))
|
||||||
|
b.WriteString(fmt.Sprintf("taskTableRowIdx=%d ", s.taskTableRowIdx))
|
||||||
|
b.WriteString(fmt.Sprintf("groupTableRowIdx=%d ", s.groupTableRowIdx))
|
||||||
|
|
||||||
|
if s.selectedQueue != nil {
|
||||||
|
b.WriteString(fmt.Sprintf("selectedQueue={Queue:%s} ", s.selectedQueue.Queue))
|
||||||
|
} else {
|
||||||
|
b.WriteString("selectedQueue=nil ")
|
||||||
|
}
|
||||||
|
|
||||||
|
if s.selectedGroup != nil {
|
||||||
|
b.WriteString(fmt.Sprintf("selectedGroup={Group:%s} ", s.selectedGroup.Group))
|
||||||
|
} else {
|
||||||
|
b.WriteString("selectedGroup=nil ")
|
||||||
|
}
|
||||||
|
|
||||||
|
if s.selectedTask != nil {
|
||||||
|
b.WriteString(fmt.Sprintf("selectedTask={ID:%s} ", s.selectedTask.ID))
|
||||||
|
} else {
|
||||||
|
b.WriteString("selectedTask=nil ")
|
||||||
|
}
|
||||||
|
|
||||||
|
b.WriteString(fmt.Sprintf("pageNum=%d", s.pageNum))
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
type Options struct {
|
||||||
|
DebugMode bool
|
||||||
|
PollInterval time.Duration
|
||||||
|
RedisConnOpt asynq.RedisConnOpt
|
||||||
|
}
|
||||||
|
|
||||||
|
func Run(opts Options) {
|
||||||
|
s, err := tcell.NewScreen()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("failed to create a screen: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
if err := s.Init(); err != nil {
|
||||||
|
fmt.Printf("failed to initialize screen: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
s.SetStyle(baseStyle) // set default text style
|
||||||
|
|
||||||
|
var (
|
||||||
|
state = State{} // confined in this goroutine only; DO NOT SHARE
|
||||||
|
|
||||||
|
inspector = asynq.NewInspector(opts.RedisConnOpt)
|
||||||
|
ticker = time.NewTicker(opts.PollInterval)
|
||||||
|
|
||||||
|
eventCh = make(chan tcell.Event)
|
||||||
|
done = make(chan struct{})
|
||||||
|
|
||||||
|
// channels to send/receive data fetched asynchronously
|
||||||
|
errorCh = make(chan error)
|
||||||
|
queueCh = make(chan *asynq.QueueInfo)
|
||||||
|
taskCh = make(chan *asynq.TaskInfo)
|
||||||
|
queuesCh = make(chan []*asynq.QueueInfo)
|
||||||
|
groupsCh = make(chan []*asynq.GroupInfo)
|
||||||
|
tasksCh = make(chan []*asynq.TaskInfo)
|
||||||
|
)
|
||||||
|
defer ticker.Stop()
|
||||||
|
|
||||||
|
f := dataFetcher{
|
||||||
|
inspector,
|
||||||
|
opts,
|
||||||
|
s,
|
||||||
|
errorCh,
|
||||||
|
queueCh,
|
||||||
|
taskCh,
|
||||||
|
queuesCh,
|
||||||
|
groupsCh,
|
||||||
|
tasksCh,
|
||||||
|
}
|
||||||
|
|
||||||
|
d := dashDrawer{
|
||||||
|
s,
|
||||||
|
opts,
|
||||||
|
}
|
||||||
|
|
||||||
|
h := keyEventHandler{
|
||||||
|
s: s,
|
||||||
|
fetcher: &f,
|
||||||
|
drawer: &d,
|
||||||
|
state: &state,
|
||||||
|
done: done,
|
||||||
|
ticker: ticker,
|
||||||
|
pollInterval: opts.PollInterval,
|
||||||
|
}
|
||||||
|
|
||||||
|
go fetchQueues(inspector, queuesCh, errorCh, opts)
|
||||||
|
go s.ChannelEvents(eventCh, done) // TODO: Double check that we are not leaking goroutine with this one.
|
||||||
|
d.Draw(&state) // draw initial screen
|
||||||
|
|
||||||
|
for {
|
||||||
|
// Update screen
|
||||||
|
s.Show()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case ev := <-eventCh:
|
||||||
|
// Process event
|
||||||
|
switch ev := ev.(type) {
|
||||||
|
case *tcell.EventResize:
|
||||||
|
s.Sync()
|
||||||
|
case *tcell.EventKey:
|
||||||
|
h.HandleKeyEvent(ev)
|
||||||
|
}
|
||||||
|
|
||||||
|
case <-ticker.C:
|
||||||
|
f.Fetch(&state)
|
||||||
|
|
||||||
|
case queues := <-queuesCh:
|
||||||
|
state.queues = queues
|
||||||
|
state.err = nil
|
||||||
|
if len(queues) < state.queueTableRowIdx {
|
||||||
|
state.queueTableRowIdx = len(queues)
|
||||||
|
}
|
||||||
|
d.Draw(&state)
|
||||||
|
|
||||||
|
case q := <-queueCh:
|
||||||
|
state.selectedQueue = q
|
||||||
|
state.err = nil
|
||||||
|
d.Draw(&state)
|
||||||
|
|
||||||
|
case groups := <-groupsCh:
|
||||||
|
state.groups = groups
|
||||||
|
state.err = nil
|
||||||
|
if len(groups) < state.groupTableRowIdx {
|
||||||
|
state.groupTableRowIdx = len(groups)
|
||||||
|
}
|
||||||
|
d.Draw(&state)
|
||||||
|
|
||||||
|
case tasks := <-tasksCh:
|
||||||
|
state.tasks = tasks
|
||||||
|
state.err = nil
|
||||||
|
if len(tasks) < state.taskTableRowIdx {
|
||||||
|
state.taskTableRowIdx = len(tasks)
|
||||||
|
}
|
||||||
|
d.Draw(&state)
|
||||||
|
|
||||||
|
case t := <-taskCh:
|
||||||
|
state.selectedTask = t
|
||||||
|
state.err = nil
|
||||||
|
d.Draw(&state)
|
||||||
|
|
||||||
|
case err := <-errorCh:
|
||||||
|
if errors.Is(err, asynq.ErrTaskNotFound) {
|
||||||
|
state.selectedTask = nil
|
||||||
|
} else {
|
||||||
|
state.err = err
|
||||||
|
}
|
||||||
|
d.Draw(&state)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
724
tools/asynq/cmd/dash/draw.go
Normal file
724
tools/asynq/cmd/dash/draw.go
Normal file
@@ -0,0 +1,724 @@
|
|||||||
|
// Copyright 2022 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package dash
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/gdamore/tcell/v2"
|
||||||
|
"github.com/hibiken/asynq"
|
||||||
|
"github.com/mattn/go-runewidth"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
baseStyle = tcell.StyleDefault.Background(tcell.ColorReset).Foreground(tcell.ColorReset)
|
||||||
|
labelStyle = baseStyle.Foreground(tcell.ColorLightGray)
|
||||||
|
|
||||||
|
// styles for bar graph
|
||||||
|
activeStyle = baseStyle.Foreground(tcell.ColorBlue)
|
||||||
|
pendingStyle = baseStyle.Foreground(tcell.ColorGreen)
|
||||||
|
aggregatingStyle = baseStyle.Foreground(tcell.ColorLightGreen)
|
||||||
|
scheduledStyle = baseStyle.Foreground(tcell.ColorYellow)
|
||||||
|
retryStyle = baseStyle.Foreground(tcell.ColorPink)
|
||||||
|
archivedStyle = baseStyle.Foreground(tcell.ColorPurple)
|
||||||
|
completedStyle = baseStyle.Foreground(tcell.ColorDarkGreen)
|
||||||
|
)
|
||||||
|
|
||||||
|
// drawer draws UI with the given state.
|
||||||
|
type drawer interface {
|
||||||
|
Draw(state *State)
|
||||||
|
}
|
||||||
|
|
||||||
|
type dashDrawer struct {
|
||||||
|
s tcell.Screen
|
||||||
|
opts Options
|
||||||
|
}
|
||||||
|
|
||||||
|
func (dd *dashDrawer) Draw(state *State) {
|
||||||
|
s, opts := dd.s, dd.opts
|
||||||
|
s.Clear()
|
||||||
|
// Simulate data update on every render
|
||||||
|
d := NewScreenDrawer(s)
|
||||||
|
switch state.view {
|
||||||
|
case viewTypeQueues:
|
||||||
|
d.Println("=== Queues ===", baseStyle.Bold(true))
|
||||||
|
d.NL()
|
||||||
|
drawQueueSizeGraphs(d, state)
|
||||||
|
d.NL()
|
||||||
|
drawQueueTable(d, baseStyle, state)
|
||||||
|
case viewTypeQueueDetails:
|
||||||
|
d.Println("=== Queue Summary ===", baseStyle.Bold(true))
|
||||||
|
d.NL()
|
||||||
|
drawQueueSummary(d, state)
|
||||||
|
d.NL()
|
||||||
|
d.NL()
|
||||||
|
d.Println("=== Tasks ===", baseStyle.Bold(true))
|
||||||
|
d.NL()
|
||||||
|
drawTaskStateBreakdown(d, baseStyle, state)
|
||||||
|
d.NL()
|
||||||
|
drawTaskTable(d, state)
|
||||||
|
drawTaskModal(d, state)
|
||||||
|
case viewTypeHelp:
|
||||||
|
drawHelp(d)
|
||||||
|
}
|
||||||
|
d.GoToBottom()
|
||||||
|
if opts.DebugMode {
|
||||||
|
drawDebugInfo(d, state)
|
||||||
|
} else {
|
||||||
|
drawFooter(d, state)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func drawQueueSizeGraphs(d *ScreenDrawer, state *State) {
|
||||||
|
var qnames []string
|
||||||
|
var qsizes []string // queue size in strings
|
||||||
|
maxSize := 1 // not zero to avoid division by zero
|
||||||
|
for _, q := range state.queues {
|
||||||
|
qnames = append(qnames, q.Queue)
|
||||||
|
qsizes = append(qsizes, strconv.Itoa(q.Size))
|
||||||
|
if q.Size > maxSize {
|
||||||
|
maxSize = q.Size
|
||||||
|
}
|
||||||
|
}
|
||||||
|
qnameWidth := maxwidth(qnames)
|
||||||
|
qsizeWidth := maxwidth(qsizes)
|
||||||
|
|
||||||
|
// Calculate the multipler to scale the graph
|
||||||
|
screenWidth, _ := d.Screen().Size()
|
||||||
|
graphMaxWidth := screenWidth - (qnameWidth + qsizeWidth + 3) // <qname> |<graph> <size>
|
||||||
|
multipiler := 1.0
|
||||||
|
if graphMaxWidth < maxSize {
|
||||||
|
multipiler = float64(graphMaxWidth) / float64(maxSize)
|
||||||
|
}
|
||||||
|
|
||||||
|
const tick = '▇'
|
||||||
|
for _, q := range state.queues {
|
||||||
|
d.Print(q.Queue, baseStyle)
|
||||||
|
d.Print(strings.Repeat(" ", qnameWidth-runewidth.StringWidth(q.Queue)+1), baseStyle) // padding between qname and graph
|
||||||
|
d.Print("|", baseStyle)
|
||||||
|
d.Print(strings.Repeat(string(tick), int(math.Floor(float64(q.Active)*multipiler))), activeStyle)
|
||||||
|
d.Print(strings.Repeat(string(tick), int(math.Floor(float64(q.Pending)*multipiler))), pendingStyle)
|
||||||
|
d.Print(strings.Repeat(string(tick), int(math.Floor(float64(q.Aggregating)*multipiler))), aggregatingStyle)
|
||||||
|
d.Print(strings.Repeat(string(tick), int(math.Floor(float64(q.Scheduled)*multipiler))), scheduledStyle)
|
||||||
|
d.Print(strings.Repeat(string(tick), int(math.Floor(float64(q.Retry)*multipiler))), retryStyle)
|
||||||
|
d.Print(strings.Repeat(string(tick), int(math.Floor(float64(q.Archived)*multipiler))), archivedStyle)
|
||||||
|
d.Print(strings.Repeat(string(tick), int(math.Floor(float64(q.Completed)*multipiler))), completedStyle)
|
||||||
|
d.Print(fmt.Sprintf(" %d", q.Size), baseStyle)
|
||||||
|
d.NL()
|
||||||
|
}
|
||||||
|
d.NL()
|
||||||
|
d.Print("active=", baseStyle)
|
||||||
|
d.Print(string(tick), activeStyle)
|
||||||
|
d.Print(" pending=", baseStyle)
|
||||||
|
d.Print(string(tick), pendingStyle)
|
||||||
|
d.Print(" aggregating=", baseStyle)
|
||||||
|
d.Print(string(tick), aggregatingStyle)
|
||||||
|
d.Print(" scheduled=", baseStyle)
|
||||||
|
d.Print(string(tick), scheduledStyle)
|
||||||
|
d.Print(" retry=", baseStyle)
|
||||||
|
d.Print(string(tick), retryStyle)
|
||||||
|
d.Print(" archived=", baseStyle)
|
||||||
|
d.Print(string(tick), archivedStyle)
|
||||||
|
d.Print(" completed=", baseStyle)
|
||||||
|
d.Print(string(tick), completedStyle)
|
||||||
|
d.NL()
|
||||||
|
}
|
||||||
|
|
||||||
|
func drawFooter(d *ScreenDrawer, state *State) {
|
||||||
|
if state.err != nil {
|
||||||
|
style := baseStyle.Background(tcell.ColorDarkRed)
|
||||||
|
d.Print(state.err.Error(), style)
|
||||||
|
d.FillLine(' ', style)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
style := baseStyle.Background(tcell.ColorDarkSlateGray).Foreground(tcell.ColorWhite)
|
||||||
|
switch state.view {
|
||||||
|
case viewTypeHelp:
|
||||||
|
d.Print("<Esc>: GoBack", style)
|
||||||
|
default:
|
||||||
|
d.Print("<?>: Help <Ctrl+C>: Exit ", style)
|
||||||
|
}
|
||||||
|
d.FillLine(' ', style)
|
||||||
|
}
|
||||||
|
|
||||||
|
// returns the maximum width from the given list of names
|
||||||
|
func maxwidth(names []string) int {
|
||||||
|
max := 0
|
||||||
|
for _, s := range names {
|
||||||
|
if w := runewidth.StringWidth(s); w > max {
|
||||||
|
max = w
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return max
|
||||||
|
}
|
||||||
|
|
||||||
|
// rpad adds padding to the right of a string.
|
||||||
|
func rpad(s string, padding int) string {
|
||||||
|
tmpl := fmt.Sprintf("%%-%ds ", padding)
|
||||||
|
return fmt.Sprintf(tmpl, s)
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// lpad adds padding to the left of a string.
|
||||||
|
func lpad(s string, padding int) string {
|
||||||
|
tmpl := fmt.Sprintf("%%%ds ", padding)
|
||||||
|
return fmt.Sprintf(tmpl, s)
|
||||||
|
}
|
||||||
|
|
||||||
|
// byteCount converts the given bytes into human readable string
|
||||||
|
func byteCount(b int64) string {
|
||||||
|
const unit = 1000
|
||||||
|
if b < unit {
|
||||||
|
return fmt.Sprintf("%d B", b)
|
||||||
|
|
||||||
|
}
|
||||||
|
div, exp := int64(unit), 0
|
||||||
|
for n := b / unit; n >= unit; n /= unit {
|
||||||
|
div *= unit
|
||||||
|
exp++
|
||||||
|
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%.1f %cB", float64(b)/float64(div), "kMGTPE"[exp])
|
||||||
|
}
|
||||||
|
|
||||||
|
var queueColumnConfigs = []*columnConfig[*asynq.QueueInfo]{
|
||||||
|
{"Queue", alignLeft, func(q *asynq.QueueInfo) string { return q.Queue }},
|
||||||
|
{"State", alignLeft, func(q *asynq.QueueInfo) string { return formatQueueState(q) }},
|
||||||
|
{"Size", alignRight, func(q *asynq.QueueInfo) string { return strconv.Itoa(q.Size) }},
|
||||||
|
{"Latency", alignRight, func(q *asynq.QueueInfo) string { return q.Latency.Round(time.Second).String() }},
|
||||||
|
{"MemoryUsage", alignRight, func(q *asynq.QueueInfo) string { return byteCount(q.MemoryUsage) }},
|
||||||
|
{"Processed", alignRight, func(q *asynq.QueueInfo) string { return strconv.Itoa(q.Processed) }},
|
||||||
|
{"Failed", alignRight, func(q *asynq.QueueInfo) string { return strconv.Itoa(q.Failed) }},
|
||||||
|
{"ErrorRate", alignRight, func(q *asynq.QueueInfo) string { return formatErrorRate(q.Processed, q.Failed) }},
|
||||||
|
}
|
||||||
|
|
||||||
|
func formatQueueState(q *asynq.QueueInfo) string {
|
||||||
|
if q.Paused {
|
||||||
|
return "PAUSED"
|
||||||
|
}
|
||||||
|
return "RUN"
|
||||||
|
}
|
||||||
|
|
||||||
|
func formatErrorRate(processed, failed int) string {
|
||||||
|
if processed == 0 {
|
||||||
|
return "-"
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%.2f", float64(failed)/float64(processed))
|
||||||
|
}
|
||||||
|
|
||||||
|
func formatNextProcessTime(t time.Time) string {
|
||||||
|
now := time.Now()
|
||||||
|
if t.Before(now) {
|
||||||
|
return "now"
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("in %v", (t.Sub(now).Round(time.Second)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func formatPastTime(t time.Time) string {
|
||||||
|
now := time.Now()
|
||||||
|
if t.After(now) || t.Equal(now) {
|
||||||
|
return "just now"
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%v ago", time.Since(t).Round(time.Second))
|
||||||
|
}
|
||||||
|
|
||||||
|
func drawQueueTable(d *ScreenDrawer, style tcell.Style, state *State) {
|
||||||
|
drawTable(d, style, queueColumnConfigs, state.queues, state.queueTableRowIdx-1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func drawQueueSummary(d *ScreenDrawer, state *State) {
|
||||||
|
q := state.selectedQueue
|
||||||
|
if q == nil {
|
||||||
|
d.Println("ERROR: Press q to go back", baseStyle)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
d.Print("Name ", labelStyle)
|
||||||
|
d.Println(q.Queue, baseStyle)
|
||||||
|
d.Print("Size ", labelStyle)
|
||||||
|
d.Println(strconv.Itoa(q.Size), baseStyle)
|
||||||
|
d.Print("Latency ", labelStyle)
|
||||||
|
d.Println(q.Latency.Round(time.Second).String(), baseStyle)
|
||||||
|
d.Print("MemUsage ", labelStyle)
|
||||||
|
d.Println(byteCount(q.MemoryUsage), baseStyle)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Returns the max number of groups that can be displayed.
|
||||||
|
func groupPageSize(s tcell.Screen) int {
|
||||||
|
_, h := s.Size()
|
||||||
|
return h - 16 // height - (# of rows used)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Returns the number of tasks to fetch.
|
||||||
|
func taskPageSize(s tcell.Screen) int {
|
||||||
|
_, h := s.Size()
|
||||||
|
return h - 15 // height - (# of rows used)
|
||||||
|
}
|
||||||
|
|
||||||
|
func shouldShowGroupTable(state *State) bool {
|
||||||
|
return state.taskState == asynq.TaskStateAggregating && state.selectedGroup == nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getTaskTableColumnConfig(taskState asynq.TaskState) []*columnConfig[*asynq.TaskInfo] {
|
||||||
|
switch taskState {
|
||||||
|
case asynq.TaskStateActive:
|
||||||
|
return activeTaskTableColumns
|
||||||
|
case asynq.TaskStatePending:
|
||||||
|
return pendingTaskTableColumns
|
||||||
|
case asynq.TaskStateAggregating:
|
||||||
|
return aggregatingTaskTableColumns
|
||||||
|
case asynq.TaskStateScheduled:
|
||||||
|
return scheduledTaskTableColumns
|
||||||
|
case asynq.TaskStateRetry:
|
||||||
|
return retryTaskTableColumns
|
||||||
|
case asynq.TaskStateArchived:
|
||||||
|
return archivedTaskTableColumns
|
||||||
|
case asynq.TaskStateCompleted:
|
||||||
|
return completedTaskTableColumns
|
||||||
|
}
|
||||||
|
panic("unknown task state")
|
||||||
|
}
|
||||||
|
|
||||||
|
var activeTaskTableColumns = []*columnConfig[*asynq.TaskInfo]{
|
||||||
|
{"ID", alignLeft, func(t *asynq.TaskInfo) string { return t.ID }},
|
||||||
|
{"Type", alignLeft, func(t *asynq.TaskInfo) string { return t.Type }},
|
||||||
|
{"Retried", alignRight, func(t *asynq.TaskInfo) string { return strconv.Itoa(t.Retried) }},
|
||||||
|
{"Max Retry", alignRight, func(t *asynq.TaskInfo) string { return strconv.Itoa(t.MaxRetry) }},
|
||||||
|
{"Payload", alignLeft, func(t *asynq.TaskInfo) string { return formatByteSlice(t.Payload) }},
|
||||||
|
}
|
||||||
|
|
||||||
|
var pendingTaskTableColumns = []*columnConfig[*asynq.TaskInfo]{
|
||||||
|
{"ID", alignLeft, func(t *asynq.TaskInfo) string { return t.ID }},
|
||||||
|
{"Type", alignLeft, func(t *asynq.TaskInfo) string { return t.Type }},
|
||||||
|
{"Retried", alignRight, func(t *asynq.TaskInfo) string { return strconv.Itoa(t.Retried) }},
|
||||||
|
{"Max Retry", alignRight, func(t *asynq.TaskInfo) string { return strconv.Itoa(t.MaxRetry) }},
|
||||||
|
{"Payload", alignLeft, func(t *asynq.TaskInfo) string { return formatByteSlice(t.Payload) }},
|
||||||
|
}
|
||||||
|
|
||||||
|
var aggregatingTaskTableColumns = []*columnConfig[*asynq.TaskInfo]{
|
||||||
|
{"ID", alignLeft, func(t *asynq.TaskInfo) string { return t.ID }},
|
||||||
|
{"Type", alignLeft, func(t *asynq.TaskInfo) string { return t.Type }},
|
||||||
|
{"Payload", alignLeft, func(t *asynq.TaskInfo) string { return formatByteSlice(t.Payload) }},
|
||||||
|
{"Group", alignLeft, func(t *asynq.TaskInfo) string { return t.Group }},
|
||||||
|
}
|
||||||
|
|
||||||
|
var scheduledTaskTableColumns = []*columnConfig[*asynq.TaskInfo]{
|
||||||
|
{"ID", alignLeft, func(t *asynq.TaskInfo) string { return t.ID }},
|
||||||
|
{"Type", alignLeft, func(t *asynq.TaskInfo) string { return t.Type }},
|
||||||
|
{"Next Process Time", alignLeft, func(t *asynq.TaskInfo) string {
|
||||||
|
return formatNextProcessTime(t.NextProcessAt)
|
||||||
|
}},
|
||||||
|
{"Payload", alignLeft, func(t *asynq.TaskInfo) string { return formatByteSlice(t.Payload) }},
|
||||||
|
}
|
||||||
|
|
||||||
|
var retryTaskTableColumns = []*columnConfig[*asynq.TaskInfo]{
|
||||||
|
{"ID", alignLeft, func(t *asynq.TaskInfo) string { return t.ID }},
|
||||||
|
{"Type", alignLeft, func(t *asynq.TaskInfo) string { return t.Type }},
|
||||||
|
{"Retry", alignRight, func(t *asynq.TaskInfo) string { return fmt.Sprintf("%d/%d", t.Retried, t.MaxRetry) }},
|
||||||
|
{"Last Failure", alignLeft, func(t *asynq.TaskInfo) string { return t.LastErr }},
|
||||||
|
{"Last Failure Time", alignLeft, func(t *asynq.TaskInfo) string { return formatPastTime(t.LastFailedAt) }},
|
||||||
|
{"Next Process Time", alignLeft, func(t *asynq.TaskInfo) string {
|
||||||
|
return formatNextProcessTime(t.NextProcessAt)
|
||||||
|
}},
|
||||||
|
{"Payload", alignLeft, func(t *asynq.TaskInfo) string { return formatByteSlice(t.Payload) }},
|
||||||
|
}
|
||||||
|
|
||||||
|
var archivedTaskTableColumns = []*columnConfig[*asynq.TaskInfo]{
|
||||||
|
{"ID", alignLeft, func(t *asynq.TaskInfo) string { return t.ID }},
|
||||||
|
{"Type", alignLeft, func(t *asynq.TaskInfo) string { return t.Type }},
|
||||||
|
{"Retry", alignRight, func(t *asynq.TaskInfo) string { return fmt.Sprintf("%d/%d", t.Retried, t.MaxRetry) }},
|
||||||
|
{"Last Failure", alignLeft, func(t *asynq.TaskInfo) string { return t.LastErr }},
|
||||||
|
{"Last Failure Time", alignLeft, func(t *asynq.TaskInfo) string { return formatPastTime(t.LastFailedAt) }},
|
||||||
|
{"Payload", alignLeft, func(t *asynq.TaskInfo) string { return formatByteSlice(t.Payload) }},
|
||||||
|
}
|
||||||
|
|
||||||
|
var completedTaskTableColumns = []*columnConfig[*asynq.TaskInfo]{
|
||||||
|
{"ID", alignLeft, func(t *asynq.TaskInfo) string { return t.ID }},
|
||||||
|
{"Type", alignLeft, func(t *asynq.TaskInfo) string { return t.Type }},
|
||||||
|
{"Completion Time", alignLeft, func(t *asynq.TaskInfo) string { return formatPastTime(t.CompletedAt) }},
|
||||||
|
{"Payload", alignLeft, func(t *asynq.TaskInfo) string { return formatByteSlice(t.Payload) }},
|
||||||
|
{"Result", alignLeft, func(t *asynq.TaskInfo) string { return formatByteSlice(t.Result) }},
|
||||||
|
}
|
||||||
|
|
||||||
|
func drawTaskTable(d *ScreenDrawer, state *State) {
|
||||||
|
if shouldShowGroupTable(state) {
|
||||||
|
drawGroupTable(d, state)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(state.tasks) == 0 {
|
||||||
|
return // print nothing
|
||||||
|
}
|
||||||
|
drawTable(d, baseStyle, getTaskTableColumnConfig(state.taskState), state.tasks, state.taskTableRowIdx-1)
|
||||||
|
|
||||||
|
// Pagination
|
||||||
|
pageSize := taskPageSize(d.Screen())
|
||||||
|
totalCount := getTaskCount(state.selectedQueue, state.taskState)
|
||||||
|
if state.taskState == asynq.TaskStateAggregating {
|
||||||
|
// aggregating tasks are scoped to each group when shown in the table.
|
||||||
|
totalCount = state.selectedGroup.Size
|
||||||
|
}
|
||||||
|
if pageSize < totalCount {
|
||||||
|
start := (state.pageNum-1)*pageSize + 1
|
||||||
|
end := start + len(state.tasks) - 1
|
||||||
|
paginationStyle := baseStyle.Foreground(tcell.ColorLightGray)
|
||||||
|
d.Print(fmt.Sprintf("Showing %d-%d out of %d", start, end, totalCount), paginationStyle)
|
||||||
|
if isNextTaskPageAvailable(d.Screen(), state) {
|
||||||
|
d.Print(" n=NextPage", paginationStyle)
|
||||||
|
}
|
||||||
|
if state.pageNum > 1 {
|
||||||
|
d.Print(" p=PrevPage", paginationStyle)
|
||||||
|
}
|
||||||
|
d.FillLine(' ', paginationStyle)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func isNextTaskPageAvailable(s tcell.Screen, state *State) bool {
|
||||||
|
totalCount := getTaskCount(state.selectedQueue, state.taskState)
|
||||||
|
end := (state.pageNum-1)*taskPageSize(s) + len(state.tasks)
|
||||||
|
return end < totalCount
|
||||||
|
}
|
||||||
|
|
||||||
|
func drawGroupTable(d *ScreenDrawer, state *State) {
|
||||||
|
if len(state.groups) == 0 {
|
||||||
|
return // print nothing
|
||||||
|
}
|
||||||
|
d.Println("<<< Select group >>>", baseStyle)
|
||||||
|
colConfigs := []*columnConfig[*asynq.GroupInfo]{
|
||||||
|
{"Name", alignLeft, func(g *asynq.GroupInfo) string { return g.Group }},
|
||||||
|
{"Size", alignRight, func(g *asynq.GroupInfo) string { return strconv.Itoa(g.Size) }},
|
||||||
|
}
|
||||||
|
// pagination
|
||||||
|
pageSize := groupPageSize(d.Screen())
|
||||||
|
total := len(state.groups)
|
||||||
|
start := (state.pageNum - 1) * pageSize
|
||||||
|
end := min(start+pageSize, total)
|
||||||
|
drawTable(d, baseStyle, colConfigs, state.groups[start:end], state.groupTableRowIdx-1)
|
||||||
|
|
||||||
|
if pageSize < total {
|
||||||
|
d.Print(fmt.Sprintf("Showing %d-%d out of %d", start+1, end, total), labelStyle)
|
||||||
|
if end < total {
|
||||||
|
d.Print(" n=NextPage", labelStyle)
|
||||||
|
}
|
||||||
|
if start > 0 {
|
||||||
|
d.Print(" p=PrevPage", labelStyle)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
d.FillLine(' ', labelStyle)
|
||||||
|
}
|
||||||
|
|
||||||
|
type number interface {
|
||||||
|
int | int64 | float64
|
||||||
|
}
|
||||||
|
|
||||||
|
// min returns the smaller of x and y. if x==y, returns x
|
||||||
|
func min[V number](x, y V) V {
|
||||||
|
if x > y {
|
||||||
|
return y
|
||||||
|
}
|
||||||
|
return x
|
||||||
|
}
|
||||||
|
|
||||||
|
// Define the order of states to show
|
||||||
|
var taskStates = []asynq.TaskState{
|
||||||
|
asynq.TaskStateActive,
|
||||||
|
asynq.TaskStatePending,
|
||||||
|
asynq.TaskStateAggregating,
|
||||||
|
asynq.TaskStateScheduled,
|
||||||
|
asynq.TaskStateRetry,
|
||||||
|
asynq.TaskStateArchived,
|
||||||
|
asynq.TaskStateCompleted,
|
||||||
|
}
|
||||||
|
|
||||||
|
func nextTaskState(current asynq.TaskState) asynq.TaskState {
|
||||||
|
for i, ts := range taskStates {
|
||||||
|
if current == ts {
|
||||||
|
if i == len(taskStates)-1 {
|
||||||
|
return taskStates[0]
|
||||||
|
} else {
|
||||||
|
return taskStates[i+1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
panic("unknown task state")
|
||||||
|
}
|
||||||
|
|
||||||
|
func prevTaskState(current asynq.TaskState) asynq.TaskState {
|
||||||
|
for i, ts := range taskStates {
|
||||||
|
if current == ts {
|
||||||
|
if i == 0 {
|
||||||
|
return taskStates[len(taskStates)-1]
|
||||||
|
} else {
|
||||||
|
return taskStates[i-1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
panic("unknown task state")
|
||||||
|
}
|
||||||
|
|
||||||
|
func getTaskCount(queue *asynq.QueueInfo, taskState asynq.TaskState) int {
|
||||||
|
switch taskState {
|
||||||
|
case asynq.TaskStateActive:
|
||||||
|
return queue.Active
|
||||||
|
case asynq.TaskStatePending:
|
||||||
|
return queue.Pending
|
||||||
|
case asynq.TaskStateAggregating:
|
||||||
|
return queue.Aggregating
|
||||||
|
case asynq.TaskStateScheduled:
|
||||||
|
return queue.Scheduled
|
||||||
|
case asynq.TaskStateRetry:
|
||||||
|
return queue.Retry
|
||||||
|
case asynq.TaskStateArchived:
|
||||||
|
return queue.Archived
|
||||||
|
case asynq.TaskStateCompleted:
|
||||||
|
return queue.Completed
|
||||||
|
}
|
||||||
|
panic("unkonwn task state")
|
||||||
|
}
|
||||||
|
|
||||||
|
func drawTaskStateBreakdown(d *ScreenDrawer, style tcell.Style, state *State) {
|
||||||
|
const pad = " " // padding between states
|
||||||
|
for _, ts := range taskStates {
|
||||||
|
s := style
|
||||||
|
if state.taskState == ts {
|
||||||
|
s = s.Bold(true).Underline(true)
|
||||||
|
}
|
||||||
|
d.Print(fmt.Sprintf("%s:%d", strings.Title(ts.String()), getTaskCount(state.selectedQueue, ts)), s)
|
||||||
|
d.Print(pad, style)
|
||||||
|
}
|
||||||
|
d.NL()
|
||||||
|
}
|
||||||
|
|
||||||
|
func drawTaskModal(d *ScreenDrawer, state *State) {
|
||||||
|
if state.taskID == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
task := state.selectedTask
|
||||||
|
if task == nil {
|
||||||
|
// task no longer found
|
||||||
|
fns := []func(d *modalRowDrawer){
|
||||||
|
func(d *modalRowDrawer) { d.Print("=== Task Info ===", baseStyle.Bold(true)) },
|
||||||
|
func(d *modalRowDrawer) { d.Print("", baseStyle) },
|
||||||
|
func(d *modalRowDrawer) {
|
||||||
|
d.Print(fmt.Sprintf("Task %q no longer exists", state.taskID), baseStyle)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
withModal(d, fns)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fns := []func(d *modalRowDrawer){
|
||||||
|
func(d *modalRowDrawer) { d.Print("=== Task Info ===", baseStyle.Bold(true)) },
|
||||||
|
func(d *modalRowDrawer) { d.Print("", baseStyle) },
|
||||||
|
func(d *modalRowDrawer) {
|
||||||
|
d.Print("ID: ", labelStyle)
|
||||||
|
d.Print(task.ID, baseStyle)
|
||||||
|
},
|
||||||
|
func(d *modalRowDrawer) {
|
||||||
|
d.Print("Type: ", labelStyle)
|
||||||
|
d.Print(task.Type, baseStyle)
|
||||||
|
},
|
||||||
|
func(d *modalRowDrawer) {
|
||||||
|
d.Print("State: ", labelStyle)
|
||||||
|
d.Print(task.State.String(), baseStyle)
|
||||||
|
},
|
||||||
|
func(d *modalRowDrawer) {
|
||||||
|
d.Print("Queue: ", labelStyle)
|
||||||
|
d.Print(task.Queue, baseStyle)
|
||||||
|
},
|
||||||
|
func(d *modalRowDrawer) {
|
||||||
|
d.Print("Retry: ", labelStyle)
|
||||||
|
d.Print(fmt.Sprintf("%d/%d", task.Retried, task.MaxRetry), baseStyle)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if task.LastErr != "" {
|
||||||
|
fns = append(fns, func(d *modalRowDrawer) {
|
||||||
|
d.Print("Last Failure: ", labelStyle)
|
||||||
|
d.Print(task.LastErr, baseStyle)
|
||||||
|
})
|
||||||
|
fns = append(fns, func(d *modalRowDrawer) {
|
||||||
|
d.Print("Last Failure Time: ", labelStyle)
|
||||||
|
d.Print(fmt.Sprintf("%v (%s)", task.LastFailedAt, formatPastTime(task.LastFailedAt)), baseStyle)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if !task.NextProcessAt.IsZero() {
|
||||||
|
fns = append(fns, func(d *modalRowDrawer) {
|
||||||
|
d.Print("Next Process Time: ", labelStyle)
|
||||||
|
d.Print(fmt.Sprintf("%v (%s)", task.NextProcessAt, formatNextProcessTime(task.NextProcessAt)), baseStyle)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if !task.CompletedAt.IsZero() {
|
||||||
|
fns = append(fns, func(d *modalRowDrawer) {
|
||||||
|
d.Print("Completion Time: ", labelStyle)
|
||||||
|
d.Print(fmt.Sprintf("%v (%s)", task.CompletedAt, formatPastTime(task.CompletedAt)), baseStyle)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fns = append(fns, func(d *modalRowDrawer) {
|
||||||
|
d.Print("Payload: ", labelStyle)
|
||||||
|
d.Print(formatByteSlice(task.Payload), baseStyle)
|
||||||
|
})
|
||||||
|
if task.Result != nil {
|
||||||
|
fns = append(fns, func(d *modalRowDrawer) {
|
||||||
|
d.Print("Result: ", labelStyle)
|
||||||
|
d.Print(formatByteSlice(task.Result), baseStyle)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
withModal(d, fns)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reports whether the given byte slice is printable (i.e. human readable)
|
||||||
|
func isPrintable(data []byte) bool {
|
||||||
|
if !utf8.Valid(data) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
isAllSpace := true
|
||||||
|
for _, r := range string(data) {
|
||||||
|
if !unicode.IsGraphic(r) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if !unicode.IsSpace(r) {
|
||||||
|
isAllSpace = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return !isAllSpace
|
||||||
|
}
|
||||||
|
|
||||||
|
func formatByteSlice(data []byte) string {
|
||||||
|
if data == nil {
|
||||||
|
return "<nil>"
|
||||||
|
}
|
||||||
|
if !isPrintable(data) {
|
||||||
|
return "<non-printable>"
|
||||||
|
}
|
||||||
|
return strings.ReplaceAll(string(data), "\n", " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
type modalRowDrawer struct {
|
||||||
|
d *ScreenDrawer
|
||||||
|
width int // current width occupied by content
|
||||||
|
maxWidth int
|
||||||
|
}
|
||||||
|
|
||||||
|
// Note: s should not include newline
|
||||||
|
func (d *modalRowDrawer) Print(s string, style tcell.Style) {
|
||||||
|
if d.width >= d.maxWidth {
|
||||||
|
return // no longer write to this row
|
||||||
|
}
|
||||||
|
if d.width+runewidth.StringWidth(s) > d.maxWidth {
|
||||||
|
s = truncate(s, d.maxWidth-d.width)
|
||||||
|
}
|
||||||
|
d.d.Print(s, style)
|
||||||
|
}
|
||||||
|
|
||||||
|
// withModal draws a modal with the given functions row by row.
|
||||||
|
func withModal(d *ScreenDrawer, rowPrintFns []func(d *modalRowDrawer)) {
|
||||||
|
w, h := d.Screen().Size()
|
||||||
|
var (
|
||||||
|
modalWidth = int(math.Floor(float64(w) * 0.6))
|
||||||
|
modalHeight = int(math.Floor(float64(h) * 0.6))
|
||||||
|
rowOffset = int(math.Floor(float64(h) * 0.2)) // 20% from the top
|
||||||
|
colOffset = int(math.Floor(float64(w) * 0.2)) // 20% from the left
|
||||||
|
)
|
||||||
|
if modalHeight < 3 {
|
||||||
|
return // no content can be shown
|
||||||
|
}
|
||||||
|
d.Goto(colOffset, rowOffset)
|
||||||
|
d.Print(string(tcell.RuneULCorner), baseStyle)
|
||||||
|
d.Print(strings.Repeat(string(tcell.RuneHLine), modalWidth-2), baseStyle)
|
||||||
|
d.Print(string(tcell.RuneURCorner), baseStyle)
|
||||||
|
d.NL()
|
||||||
|
rowDrawer := modalRowDrawer{
|
||||||
|
d: d,
|
||||||
|
width: 0,
|
||||||
|
maxWidth: modalWidth - 4, /* borders + paddings */
|
||||||
|
}
|
||||||
|
for i := 1; i < modalHeight-1; i++ {
|
||||||
|
d.Goto(colOffset, rowOffset+i)
|
||||||
|
d.Print(fmt.Sprintf("%c ", tcell.RuneVLine), baseStyle)
|
||||||
|
if i <= len(rowPrintFns) {
|
||||||
|
rowPrintFns[i-1](&rowDrawer)
|
||||||
|
}
|
||||||
|
d.FillUntil(' ', baseStyle, colOffset+modalWidth-2)
|
||||||
|
d.Print(fmt.Sprintf(" %c", tcell.RuneVLine), baseStyle)
|
||||||
|
d.NL()
|
||||||
|
}
|
||||||
|
d.Goto(colOffset, rowOffset+modalHeight-1)
|
||||||
|
d.Print(string(tcell.RuneLLCorner), baseStyle)
|
||||||
|
d.Print(strings.Repeat(string(tcell.RuneHLine), modalWidth-2), baseStyle)
|
||||||
|
d.Print(string(tcell.RuneLRCorner), baseStyle)
|
||||||
|
d.NL()
|
||||||
|
}
|
||||||
|
|
||||||
|
func adjustWidth(s string, width int) string {
|
||||||
|
sw := runewidth.StringWidth(s)
|
||||||
|
if sw > width {
|
||||||
|
return truncate(s, width)
|
||||||
|
}
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString(s)
|
||||||
|
b.WriteString(strings.Repeat(" ", width-sw))
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// truncates s if s exceeds max length.
|
||||||
|
func truncate(s string, max int) string {
|
||||||
|
if runewidth.StringWidth(s) <= max {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
return string([]rune(s)[:max-1]) + "…"
|
||||||
|
}
|
||||||
|
|
||||||
|
func drawDebugInfo(d *ScreenDrawer, state *State) {
|
||||||
|
d.Println(state.DebugString(), baseStyle)
|
||||||
|
}
|
||||||
|
|
||||||
|
func drawHelp(d *ScreenDrawer) {
|
||||||
|
keyStyle := labelStyle.Bold(true)
|
||||||
|
withModal(d, []func(*modalRowDrawer){
|
||||||
|
func(d *modalRowDrawer) { d.Print("=== Help ===", baseStyle.Bold(true)) },
|
||||||
|
func(d *modalRowDrawer) { d.Print("", baseStyle) },
|
||||||
|
func(d *modalRowDrawer) {
|
||||||
|
d.Print("<Enter>", keyStyle)
|
||||||
|
d.Print(" to select", baseStyle)
|
||||||
|
},
|
||||||
|
func(d *modalRowDrawer) {
|
||||||
|
d.Print("<Esc>", keyStyle)
|
||||||
|
d.Print(" or ", baseStyle)
|
||||||
|
d.Print("<q>", keyStyle)
|
||||||
|
d.Print(" to go back", baseStyle)
|
||||||
|
},
|
||||||
|
func(d *modalRowDrawer) {
|
||||||
|
d.Print("<UpArrow>", keyStyle)
|
||||||
|
d.Print(" or ", baseStyle)
|
||||||
|
d.Print("<k>", keyStyle)
|
||||||
|
d.Print(" to move up", baseStyle)
|
||||||
|
},
|
||||||
|
func(d *modalRowDrawer) {
|
||||||
|
d.Print("<DownArrow>", keyStyle)
|
||||||
|
d.Print(" or ", baseStyle)
|
||||||
|
d.Print("<j>", keyStyle)
|
||||||
|
d.Print(" to move down", baseStyle)
|
||||||
|
},
|
||||||
|
func(d *modalRowDrawer) {
|
||||||
|
d.Print("<LeftArrow>", keyStyle)
|
||||||
|
d.Print(" or ", baseStyle)
|
||||||
|
d.Print("<h>", keyStyle)
|
||||||
|
d.Print(" to move left", baseStyle)
|
||||||
|
},
|
||||||
|
func(d *modalRowDrawer) {
|
||||||
|
d.Print("<RightArrow>", keyStyle)
|
||||||
|
d.Print(" or ", baseStyle)
|
||||||
|
d.Print("<l>", keyStyle)
|
||||||
|
d.Print(" to move right", baseStyle)
|
||||||
|
},
|
||||||
|
func(d *modalRowDrawer) {
|
||||||
|
d.Print("<Ctrl+C>", keyStyle)
|
||||||
|
d.Print(" to quit", baseStyle)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
33
tools/asynq/cmd/dash/draw_test.go
Normal file
33
tools/asynq/cmd/dash/draw_test.go
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
// Copyright 2022 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package dash
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestTruncate(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
s string
|
||||||
|
max int
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
s: "hello world!",
|
||||||
|
max: 15,
|
||||||
|
want: "hello world!",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
s: "hello world!",
|
||||||
|
max: 6,
|
||||||
|
want: "hello…",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
got := truncate(tc.s, tc.max)
|
||||||
|
if tc.want != got {
|
||||||
|
t.Errorf("truncate(%q, %d) = %q, want %q", tc.s, tc.max, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
185
tools/asynq/cmd/dash/fetch.go
Normal file
185
tools/asynq/cmd/dash/fetch.go
Normal file
@@ -0,0 +1,185 @@
|
|||||||
|
// Copyright 2022 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package dash
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sort"
|
||||||
|
|
||||||
|
"github.com/gdamore/tcell/v2"
|
||||||
|
"github.com/hibiken/asynq"
|
||||||
|
)
|
||||||
|
|
||||||
|
type fetcher interface {
|
||||||
|
// Fetch retries data required by the given state of the dashboard.
|
||||||
|
Fetch(state *State)
|
||||||
|
}
|
||||||
|
|
||||||
|
type dataFetcher struct {
|
||||||
|
inspector *asynq.Inspector
|
||||||
|
opts Options
|
||||||
|
s tcell.Screen
|
||||||
|
|
||||||
|
errorCh chan<- error
|
||||||
|
queueCh chan<- *asynq.QueueInfo
|
||||||
|
taskCh chan<- *asynq.TaskInfo
|
||||||
|
queuesCh chan<- []*asynq.QueueInfo
|
||||||
|
groupsCh chan<- []*asynq.GroupInfo
|
||||||
|
tasksCh chan<- []*asynq.TaskInfo
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *dataFetcher) Fetch(state *State) {
|
||||||
|
switch state.view {
|
||||||
|
case viewTypeQueues:
|
||||||
|
f.fetchQueues()
|
||||||
|
case viewTypeQueueDetails:
|
||||||
|
if shouldShowGroupTable(state) {
|
||||||
|
f.fetchGroups(state.selectedQueue.Queue)
|
||||||
|
} else if state.taskState == asynq.TaskStateAggregating {
|
||||||
|
f.fetchAggregatingTasks(state.selectedQueue.Queue, state.selectedGroup.Group, taskPageSize(f.s), state.pageNum)
|
||||||
|
} else {
|
||||||
|
f.fetchTasks(state.selectedQueue.Queue, state.taskState, taskPageSize(f.s), state.pageNum)
|
||||||
|
}
|
||||||
|
// if the task modal is open, additionally fetch the selected task's info
|
||||||
|
if state.taskID != "" {
|
||||||
|
f.fetchTaskInfo(state.selectedQueue.Queue, state.taskID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *dataFetcher) fetchQueues() {
|
||||||
|
var (
|
||||||
|
inspector = f.inspector
|
||||||
|
queuesCh = f.queuesCh
|
||||||
|
errorCh = f.errorCh
|
||||||
|
opts = f.opts
|
||||||
|
)
|
||||||
|
go fetchQueues(inspector, queuesCh, errorCh, opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
func fetchQueues(i *asynq.Inspector, queuesCh chan<- []*asynq.QueueInfo, errorCh chan<- error, opts Options) {
|
||||||
|
queues, err := i.Queues()
|
||||||
|
if err != nil {
|
||||||
|
errorCh <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
sort.Strings(queues)
|
||||||
|
var res []*asynq.QueueInfo
|
||||||
|
for _, q := range queues {
|
||||||
|
info, err := i.GetQueueInfo(q)
|
||||||
|
if err != nil {
|
||||||
|
errorCh <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
res = append(res, info)
|
||||||
|
}
|
||||||
|
queuesCh <- res
|
||||||
|
}
|
||||||
|
|
||||||
|
func fetchQueueInfo(i *asynq.Inspector, qname string, queueCh chan<- *asynq.QueueInfo, errorCh chan<- error) {
|
||||||
|
q, err := i.GetQueueInfo(qname)
|
||||||
|
if err != nil {
|
||||||
|
errorCh <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
queueCh <- q
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *dataFetcher) fetchGroups(qname string) {
|
||||||
|
var (
|
||||||
|
i = f.inspector
|
||||||
|
groupsCh = f.groupsCh
|
||||||
|
errorCh = f.errorCh
|
||||||
|
queueCh = f.queueCh
|
||||||
|
)
|
||||||
|
go fetchGroups(i, qname, groupsCh, errorCh)
|
||||||
|
go fetchQueueInfo(i, qname, queueCh, errorCh)
|
||||||
|
}
|
||||||
|
|
||||||
|
func fetchGroups(i *asynq.Inspector, qname string, groupsCh chan<- []*asynq.GroupInfo, errorCh chan<- error) {
|
||||||
|
groups, err := i.Groups(qname)
|
||||||
|
if err != nil {
|
||||||
|
errorCh <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
groupsCh <- groups
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *dataFetcher) fetchAggregatingTasks(qname, group string, pageSize, pageNum int) {
|
||||||
|
var (
|
||||||
|
i = f.inspector
|
||||||
|
tasksCh = f.tasksCh
|
||||||
|
errorCh = f.errorCh
|
||||||
|
queueCh = f.queueCh
|
||||||
|
)
|
||||||
|
go fetchAggregatingTasks(i, qname, group, pageSize, pageNum, tasksCh, errorCh)
|
||||||
|
go fetchQueueInfo(i, qname, queueCh, errorCh)
|
||||||
|
}
|
||||||
|
|
||||||
|
func fetchAggregatingTasks(i *asynq.Inspector, qname, group string, pageSize, pageNum int,
|
||||||
|
tasksCh chan<- []*asynq.TaskInfo, errorCh chan<- error) {
|
||||||
|
tasks, err := i.ListAggregatingTasks(qname, group, asynq.PageSize(pageSize), asynq.Page(pageNum))
|
||||||
|
if err != nil {
|
||||||
|
errorCh <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tasksCh <- tasks
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *dataFetcher) fetchTasks(qname string, taskState asynq.TaskState, pageSize, pageNum int) {
|
||||||
|
var (
|
||||||
|
i = f.inspector
|
||||||
|
tasksCh = f.tasksCh
|
||||||
|
errorCh = f.errorCh
|
||||||
|
queueCh = f.queueCh
|
||||||
|
)
|
||||||
|
go fetchTasks(i, qname, taskState, pageSize, pageNum, tasksCh, errorCh)
|
||||||
|
go fetchQueueInfo(i, qname, queueCh, errorCh)
|
||||||
|
}
|
||||||
|
|
||||||
|
func fetchTasks(i *asynq.Inspector, qname string, taskState asynq.TaskState, pageSize, pageNum int,
|
||||||
|
tasksCh chan<- []*asynq.TaskInfo, errorCh chan<- error) {
|
||||||
|
var (
|
||||||
|
tasks []*asynq.TaskInfo
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
opts := []asynq.ListOption{asynq.PageSize(pageSize), asynq.Page(pageNum)}
|
||||||
|
switch taskState {
|
||||||
|
case asynq.TaskStateActive:
|
||||||
|
tasks, err = i.ListActiveTasks(qname, opts...)
|
||||||
|
case asynq.TaskStatePending:
|
||||||
|
tasks, err = i.ListPendingTasks(qname, opts...)
|
||||||
|
case asynq.TaskStateScheduled:
|
||||||
|
tasks, err = i.ListScheduledTasks(qname, opts...)
|
||||||
|
case asynq.TaskStateRetry:
|
||||||
|
tasks, err = i.ListRetryTasks(qname, opts...)
|
||||||
|
case asynq.TaskStateArchived:
|
||||||
|
tasks, err = i.ListArchivedTasks(qname, opts...)
|
||||||
|
case asynq.TaskStateCompleted:
|
||||||
|
tasks, err = i.ListCompletedTasks(qname, opts...)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
errorCh <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tasksCh <- tasks
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *dataFetcher) fetchTaskInfo(qname, taskID string) {
|
||||||
|
var (
|
||||||
|
i = f.inspector
|
||||||
|
taskCh = f.taskCh
|
||||||
|
errorCh = f.errorCh
|
||||||
|
)
|
||||||
|
go fetchTaskInfo(i, qname, taskID, taskCh, errorCh)
|
||||||
|
}
|
||||||
|
|
||||||
|
func fetchTaskInfo(i *asynq.Inspector, qname, taskID string, taskCh chan<- *asynq.TaskInfo, errorCh chan<- error) {
|
||||||
|
info, err := i.GetTaskInfo(qname, taskID)
|
||||||
|
if err != nil {
|
||||||
|
errorCh <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
taskCh <- info
|
||||||
|
}
|
||||||
317
tools/asynq/cmd/dash/key_event.go
Normal file
317
tools/asynq/cmd/dash/key_event.go
Normal file
@@ -0,0 +1,317 @@
|
|||||||
|
// Copyright 2022 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package dash
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gdamore/tcell/v2"
|
||||||
|
"github.com/hibiken/asynq"
|
||||||
|
)
|
||||||
|
|
||||||
|
// keyEventHandler handles keyboard events and updates the state.
|
||||||
|
// It delegates data fetching to fetcher and UI rendering to drawer.
|
||||||
|
type keyEventHandler struct {
|
||||||
|
s tcell.Screen
|
||||||
|
state *State
|
||||||
|
done chan struct{}
|
||||||
|
|
||||||
|
fetcher fetcher
|
||||||
|
drawer drawer
|
||||||
|
|
||||||
|
ticker *time.Ticker
|
||||||
|
pollInterval time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *keyEventHandler) quit() {
|
||||||
|
h.s.Fini()
|
||||||
|
close(h.done)
|
||||||
|
os.Exit(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *keyEventHandler) HandleKeyEvent(ev *tcell.EventKey) {
|
||||||
|
if ev.Key() == tcell.KeyEscape || ev.Rune() == 'q' {
|
||||||
|
h.goBack() // Esc and 'q' key have "go back" semantics
|
||||||
|
} else if ev.Key() == tcell.KeyCtrlC {
|
||||||
|
h.quit()
|
||||||
|
} else if ev.Key() == tcell.KeyCtrlL {
|
||||||
|
h.s.Sync()
|
||||||
|
} else if ev.Key() == tcell.KeyDown || ev.Rune() == 'j' {
|
||||||
|
h.handleDownKey()
|
||||||
|
} else if ev.Key() == tcell.KeyUp || ev.Rune() == 'k' {
|
||||||
|
h.handleUpKey()
|
||||||
|
} else if ev.Key() == tcell.KeyRight || ev.Rune() == 'l' {
|
||||||
|
h.handleRightKey()
|
||||||
|
} else if ev.Key() == tcell.KeyLeft || ev.Rune() == 'h' {
|
||||||
|
h.handleLeftKey()
|
||||||
|
} else if ev.Key() == tcell.KeyEnter {
|
||||||
|
h.handleEnterKey()
|
||||||
|
} else if ev.Rune() == '?' {
|
||||||
|
h.showHelp()
|
||||||
|
} else if ev.Rune() == 'n' {
|
||||||
|
h.nextPage()
|
||||||
|
} else if ev.Rune() == 'p' {
|
||||||
|
h.prevPage()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *keyEventHandler) goBack() {
|
||||||
|
var (
|
||||||
|
state = h.state
|
||||||
|
d = h.drawer
|
||||||
|
f = h.fetcher
|
||||||
|
)
|
||||||
|
if state.view == viewTypeHelp {
|
||||||
|
state.view = state.prevView // exit help
|
||||||
|
f.Fetch(state)
|
||||||
|
h.resetTicker()
|
||||||
|
d.Draw(state)
|
||||||
|
} else if state.view == viewTypeQueueDetails {
|
||||||
|
// if task modal is open close it; otherwise go back to the previous view
|
||||||
|
if state.taskID != "" {
|
||||||
|
state.taskID = ""
|
||||||
|
state.selectedTask = nil
|
||||||
|
d.Draw(state)
|
||||||
|
} else {
|
||||||
|
state.view = viewTypeQueues
|
||||||
|
f.Fetch(state)
|
||||||
|
h.resetTicker()
|
||||||
|
d.Draw(state)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
h.quit()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *keyEventHandler) handleDownKey() {
|
||||||
|
switch h.state.view {
|
||||||
|
case viewTypeQueues:
|
||||||
|
h.downKeyQueues()
|
||||||
|
case viewTypeQueueDetails:
|
||||||
|
h.downKeyQueueDetails()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *keyEventHandler) downKeyQueues() {
|
||||||
|
if h.state.queueTableRowIdx < len(h.state.queues) {
|
||||||
|
h.state.queueTableRowIdx++
|
||||||
|
} else {
|
||||||
|
h.state.queueTableRowIdx = 0 // loop back
|
||||||
|
}
|
||||||
|
h.drawer.Draw(h.state)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *keyEventHandler) downKeyQueueDetails() {
|
||||||
|
s, state := h.s, h.state
|
||||||
|
if shouldShowGroupTable(state) {
|
||||||
|
if state.groupTableRowIdx < groupPageSize(s) {
|
||||||
|
state.groupTableRowIdx++
|
||||||
|
} else {
|
||||||
|
state.groupTableRowIdx = 0 // loop back
|
||||||
|
}
|
||||||
|
} else if state.taskID == "" {
|
||||||
|
if state.taskTableRowIdx < len(state.tasks) {
|
||||||
|
state.taskTableRowIdx++
|
||||||
|
} else {
|
||||||
|
state.taskTableRowIdx = 0 // loop back
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h.drawer.Draw(state)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *keyEventHandler) handleUpKey() {
|
||||||
|
switch h.state.view {
|
||||||
|
case viewTypeQueues:
|
||||||
|
h.upKeyQueues()
|
||||||
|
case viewTypeQueueDetails:
|
||||||
|
h.upKeyQueueDetails()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *keyEventHandler) upKeyQueues() {
|
||||||
|
state := h.state
|
||||||
|
if state.queueTableRowIdx == 0 {
|
||||||
|
state.queueTableRowIdx = len(state.queues)
|
||||||
|
} else {
|
||||||
|
state.queueTableRowIdx--
|
||||||
|
}
|
||||||
|
h.drawer.Draw(state)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *keyEventHandler) upKeyQueueDetails() {
|
||||||
|
s, state := h.s, h.state
|
||||||
|
if shouldShowGroupTable(state) {
|
||||||
|
if state.groupTableRowIdx == 0 {
|
||||||
|
state.groupTableRowIdx = groupPageSize(s)
|
||||||
|
} else {
|
||||||
|
state.groupTableRowIdx--
|
||||||
|
}
|
||||||
|
} else if state.taskID == "" {
|
||||||
|
if state.taskTableRowIdx == 0 {
|
||||||
|
state.taskTableRowIdx = len(state.tasks)
|
||||||
|
} else {
|
||||||
|
state.taskTableRowIdx--
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h.drawer.Draw(state)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *keyEventHandler) handleEnterKey() {
|
||||||
|
switch h.state.view {
|
||||||
|
case viewTypeQueues:
|
||||||
|
h.enterKeyQueues()
|
||||||
|
case viewTypeQueueDetails:
|
||||||
|
h.enterKeyQueueDetails()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *keyEventHandler) resetTicker() {
|
||||||
|
h.ticker.Reset(h.pollInterval)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *keyEventHandler) enterKeyQueues() {
|
||||||
|
var (
|
||||||
|
state = h.state
|
||||||
|
f = h.fetcher
|
||||||
|
d = h.drawer
|
||||||
|
)
|
||||||
|
if state.queueTableRowIdx != 0 {
|
||||||
|
state.selectedQueue = state.queues[state.queueTableRowIdx-1]
|
||||||
|
state.view = viewTypeQueueDetails
|
||||||
|
state.taskState = asynq.TaskStateActive
|
||||||
|
state.tasks = nil
|
||||||
|
state.pageNum = 1
|
||||||
|
f.Fetch(state)
|
||||||
|
h.resetTicker()
|
||||||
|
d.Draw(state)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *keyEventHandler) enterKeyQueueDetails() {
|
||||||
|
var (
|
||||||
|
state = h.state
|
||||||
|
f = h.fetcher
|
||||||
|
d = h.drawer
|
||||||
|
)
|
||||||
|
if shouldShowGroupTable(state) && state.groupTableRowIdx != 0 {
|
||||||
|
state.selectedGroup = state.groups[state.groupTableRowIdx-1]
|
||||||
|
state.tasks = nil
|
||||||
|
state.pageNum = 1
|
||||||
|
f.Fetch(state)
|
||||||
|
h.resetTicker()
|
||||||
|
d.Draw(state)
|
||||||
|
} else if !shouldShowGroupTable(state) && state.taskTableRowIdx != 0 {
|
||||||
|
task := state.tasks[state.taskTableRowIdx-1]
|
||||||
|
state.selectedTask = task
|
||||||
|
state.taskID = task.ID
|
||||||
|
f.Fetch(state)
|
||||||
|
h.resetTicker()
|
||||||
|
d.Draw(state)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *keyEventHandler) handleLeftKey() {
|
||||||
|
var (
|
||||||
|
state = h.state
|
||||||
|
f = h.fetcher
|
||||||
|
d = h.drawer
|
||||||
|
)
|
||||||
|
if state.view == viewTypeQueueDetails && state.taskID == "" {
|
||||||
|
state.taskState = prevTaskState(state.taskState)
|
||||||
|
state.pageNum = 1
|
||||||
|
state.taskTableRowIdx = 0
|
||||||
|
state.tasks = nil
|
||||||
|
state.selectedGroup = nil
|
||||||
|
f.Fetch(state)
|
||||||
|
h.resetTicker()
|
||||||
|
d.Draw(state)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *keyEventHandler) handleRightKey() {
|
||||||
|
var (
|
||||||
|
state = h.state
|
||||||
|
f = h.fetcher
|
||||||
|
d = h.drawer
|
||||||
|
)
|
||||||
|
if state.view == viewTypeQueueDetails && state.taskID == "" {
|
||||||
|
state.taskState = nextTaskState(state.taskState)
|
||||||
|
state.pageNum = 1
|
||||||
|
state.taskTableRowIdx = 0
|
||||||
|
state.tasks = nil
|
||||||
|
state.selectedGroup = nil
|
||||||
|
f.Fetch(state)
|
||||||
|
h.resetTicker()
|
||||||
|
d.Draw(state)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *keyEventHandler) nextPage() {
|
||||||
|
var (
|
||||||
|
s = h.s
|
||||||
|
state = h.state
|
||||||
|
f = h.fetcher
|
||||||
|
d = h.drawer
|
||||||
|
)
|
||||||
|
if state.view == viewTypeQueueDetails {
|
||||||
|
if shouldShowGroupTable(state) {
|
||||||
|
pageSize := groupPageSize(s)
|
||||||
|
total := len(state.groups)
|
||||||
|
start := (state.pageNum - 1) * pageSize
|
||||||
|
end := start + pageSize
|
||||||
|
if end <= total {
|
||||||
|
state.pageNum++
|
||||||
|
d.Draw(state)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
pageSize := taskPageSize(s)
|
||||||
|
totalCount := getTaskCount(state.selectedQueue, state.taskState)
|
||||||
|
if (state.pageNum-1)*pageSize+len(state.tasks) < totalCount {
|
||||||
|
state.pageNum++
|
||||||
|
f.Fetch(state)
|
||||||
|
h.resetTicker()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *keyEventHandler) prevPage() {
|
||||||
|
var (
|
||||||
|
s = h.s
|
||||||
|
state = h.state
|
||||||
|
f = h.fetcher
|
||||||
|
d = h.drawer
|
||||||
|
)
|
||||||
|
if state.view == viewTypeQueueDetails {
|
||||||
|
if shouldShowGroupTable(state) {
|
||||||
|
pageSize := groupPageSize(s)
|
||||||
|
start := (state.pageNum - 1) * pageSize
|
||||||
|
if start > 0 {
|
||||||
|
state.pageNum--
|
||||||
|
d.Draw(state)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if state.pageNum > 1 {
|
||||||
|
state.pageNum--
|
||||||
|
f.Fetch(state)
|
||||||
|
h.resetTicker()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *keyEventHandler) showHelp() {
|
||||||
|
var (
|
||||||
|
state = h.state
|
||||||
|
d = h.drawer
|
||||||
|
)
|
||||||
|
if state.view != viewTypeHelp {
|
||||||
|
state.prevView = state.view
|
||||||
|
state.view = viewTypeHelp
|
||||||
|
d.Draw(state)
|
||||||
|
}
|
||||||
|
}
|
||||||
234
tools/asynq/cmd/dash/key_event_test.go
Normal file
234
tools/asynq/cmd/dash/key_event_test.go
Normal file
@@ -0,0 +1,234 @@
|
|||||||
|
// Copyright 2022 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package dash
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gdamore/tcell/v2"
|
||||||
|
"github.com/google/go-cmp/cmp"
|
||||||
|
"github.com/hibiken/asynq"
|
||||||
|
)
|
||||||
|
|
||||||
|
func makeKeyEventHandler(t *testing.T, state *State) *keyEventHandler {
|
||||||
|
ticker := time.NewTicker(time.Second)
|
||||||
|
t.Cleanup(func() { ticker.Stop() })
|
||||||
|
return &keyEventHandler{
|
||||||
|
s: tcell.NewSimulationScreen("UTF-8"),
|
||||||
|
state: state,
|
||||||
|
done: make(chan struct{}),
|
||||||
|
fetcher: &fakeFetcher{},
|
||||||
|
drawer: &fakeDrawer{},
|
||||||
|
ticker: ticker,
|
||||||
|
pollInterval: time.Second,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type keyEventHandlerTest struct {
|
||||||
|
desc string // test description
|
||||||
|
state *State // initial state, to be mutated by the handler
|
||||||
|
events []*tcell.EventKey // keyboard events
|
||||||
|
wantState State // expected state after the events
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestKeyEventHandler(t *testing.T) {
|
||||||
|
tests := []*keyEventHandlerTest{
|
||||||
|
{
|
||||||
|
desc: "navigates to help view",
|
||||||
|
state: &State{view: viewTypeQueues},
|
||||||
|
events: []*tcell.EventKey{tcell.NewEventKey(tcell.KeyRune, '?', tcell.ModNone)},
|
||||||
|
wantState: State{view: viewTypeHelp},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "navigates to queue details view",
|
||||||
|
state: &State{
|
||||||
|
view: viewTypeQueues,
|
||||||
|
queues: []*asynq.QueueInfo{
|
||||||
|
{Queue: "default", Size: 100, Active: 10, Pending: 40, Scheduled: 40, Completed: 10},
|
||||||
|
},
|
||||||
|
queueTableRowIdx: 0,
|
||||||
|
},
|
||||||
|
events: []*tcell.EventKey{
|
||||||
|
tcell.NewEventKey(tcell.KeyRune, 'j', tcell.ModNone), // down
|
||||||
|
tcell.NewEventKey(tcell.KeyEnter, '\n', tcell.ModNone), // Enter
|
||||||
|
},
|
||||||
|
wantState: State{
|
||||||
|
view: viewTypeQueueDetails,
|
||||||
|
queues: []*asynq.QueueInfo{
|
||||||
|
{Queue: "default", Size: 100, Active: 10, Pending: 40, Scheduled: 40, Completed: 10},
|
||||||
|
},
|
||||||
|
selectedQueue: &asynq.QueueInfo{Queue: "default", Size: 100, Active: 10, Pending: 40, Scheduled: 40, Completed: 10},
|
||||||
|
queueTableRowIdx: 1,
|
||||||
|
taskState: asynq.TaskStateActive,
|
||||||
|
pageNum: 1,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "does nothing if no queues are present",
|
||||||
|
state: &State{
|
||||||
|
view: viewTypeQueues,
|
||||||
|
queues: []*asynq.QueueInfo{}, // empty
|
||||||
|
queueTableRowIdx: 0,
|
||||||
|
},
|
||||||
|
events: []*tcell.EventKey{
|
||||||
|
tcell.NewEventKey(tcell.KeyRune, 'j', tcell.ModNone), // down
|
||||||
|
tcell.NewEventKey(tcell.KeyEnter, '\n', tcell.ModNone), // Enter
|
||||||
|
},
|
||||||
|
wantState: State{
|
||||||
|
view: viewTypeQueues,
|
||||||
|
queues: []*asynq.QueueInfo{},
|
||||||
|
queueTableRowIdx: 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "opens task info modal",
|
||||||
|
state: &State{
|
||||||
|
view: viewTypeQueueDetails,
|
||||||
|
queues: []*asynq.QueueInfo{
|
||||||
|
{Queue: "default", Size: 500, Active: 10, Pending: 40},
|
||||||
|
},
|
||||||
|
queueTableRowIdx: 1,
|
||||||
|
selectedQueue: &asynq.QueueInfo{Queue: "default", Size: 50, Active: 10, Pending: 40},
|
||||||
|
taskState: asynq.TaskStatePending,
|
||||||
|
pageNum: 1,
|
||||||
|
tasks: []*asynq.TaskInfo{
|
||||||
|
{ID: "xxxx", Type: "foo"},
|
||||||
|
{ID: "yyyy", Type: "bar"},
|
||||||
|
{ID: "zzzz", Type: "baz"},
|
||||||
|
},
|
||||||
|
taskTableRowIdx: 2,
|
||||||
|
},
|
||||||
|
events: []*tcell.EventKey{
|
||||||
|
tcell.NewEventKey(tcell.KeyEnter, '\n', tcell.ModNone), // Enter
|
||||||
|
},
|
||||||
|
wantState: State{
|
||||||
|
view: viewTypeQueueDetails,
|
||||||
|
queues: []*asynq.QueueInfo{
|
||||||
|
{Queue: "default", Size: 500, Active: 10, Pending: 40},
|
||||||
|
},
|
||||||
|
queueTableRowIdx: 1,
|
||||||
|
selectedQueue: &asynq.QueueInfo{Queue: "default", Size: 50, Active: 10, Pending: 40},
|
||||||
|
taskState: asynq.TaskStatePending,
|
||||||
|
pageNum: 1,
|
||||||
|
tasks: []*asynq.TaskInfo{
|
||||||
|
{ID: "xxxx", Type: "foo"},
|
||||||
|
{ID: "yyyy", Type: "bar"},
|
||||||
|
{ID: "zzzz", Type: "baz"},
|
||||||
|
},
|
||||||
|
taskTableRowIdx: 2,
|
||||||
|
// new states
|
||||||
|
taskID: "yyyy",
|
||||||
|
selectedTask: &asynq.TaskInfo{ID: "yyyy", Type: "bar"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "Esc closes task info modal",
|
||||||
|
state: &State{
|
||||||
|
view: viewTypeQueueDetails,
|
||||||
|
queues: []*asynq.QueueInfo{
|
||||||
|
{Queue: "default", Size: 500, Active: 10, Pending: 40},
|
||||||
|
},
|
||||||
|
queueTableRowIdx: 1,
|
||||||
|
selectedQueue: &asynq.QueueInfo{Queue: "default", Size: 50, Active: 10, Pending: 40},
|
||||||
|
taskState: asynq.TaskStatePending,
|
||||||
|
pageNum: 1,
|
||||||
|
tasks: []*asynq.TaskInfo{
|
||||||
|
{ID: "xxxx", Type: "foo"},
|
||||||
|
{ID: "yyyy", Type: "bar"},
|
||||||
|
{ID: "zzzz", Type: "baz"},
|
||||||
|
},
|
||||||
|
taskTableRowIdx: 2,
|
||||||
|
taskID: "yyyy", // presence of this field opens the modal
|
||||||
|
},
|
||||||
|
events: []*tcell.EventKey{
|
||||||
|
tcell.NewEventKey(tcell.KeyEscape, ' ', tcell.ModNone), // Esc
|
||||||
|
},
|
||||||
|
wantState: State{
|
||||||
|
view: viewTypeQueueDetails,
|
||||||
|
queues: []*asynq.QueueInfo{
|
||||||
|
{Queue: "default", Size: 500, Active: 10, Pending: 40},
|
||||||
|
},
|
||||||
|
queueTableRowIdx: 1,
|
||||||
|
selectedQueue: &asynq.QueueInfo{Queue: "default", Size: 50, Active: 10, Pending: 40},
|
||||||
|
taskState: asynq.TaskStatePending,
|
||||||
|
pageNum: 1,
|
||||||
|
tasks: []*asynq.TaskInfo{
|
||||||
|
{ID: "xxxx", Type: "foo"},
|
||||||
|
{ID: "yyyy", Type: "bar"},
|
||||||
|
{ID: "zzzz", Type: "baz"},
|
||||||
|
},
|
||||||
|
taskTableRowIdx: 2,
|
||||||
|
taskID: "", // this field should be unset
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "Arrow keys are disabled while task info modal is open",
|
||||||
|
state: &State{
|
||||||
|
view: viewTypeQueueDetails,
|
||||||
|
queues: []*asynq.QueueInfo{
|
||||||
|
{Queue: "default", Size: 500, Active: 10, Pending: 40},
|
||||||
|
},
|
||||||
|
queueTableRowIdx: 1,
|
||||||
|
selectedQueue: &asynq.QueueInfo{Queue: "default", Size: 50, Active: 10, Pending: 40},
|
||||||
|
taskState: asynq.TaskStatePending,
|
||||||
|
pageNum: 1,
|
||||||
|
tasks: []*asynq.TaskInfo{
|
||||||
|
{ID: "xxxx", Type: "foo"},
|
||||||
|
{ID: "yyyy", Type: "bar"},
|
||||||
|
{ID: "zzzz", Type: "baz"},
|
||||||
|
},
|
||||||
|
taskTableRowIdx: 2,
|
||||||
|
taskID: "yyyy", // presence of this field opens the modal
|
||||||
|
},
|
||||||
|
events: []*tcell.EventKey{
|
||||||
|
tcell.NewEventKey(tcell.KeyLeft, ' ', tcell.ModNone),
|
||||||
|
},
|
||||||
|
|
||||||
|
// no change
|
||||||
|
wantState: State{
|
||||||
|
view: viewTypeQueueDetails,
|
||||||
|
queues: []*asynq.QueueInfo{
|
||||||
|
{Queue: "default", Size: 500, Active: 10, Pending: 40},
|
||||||
|
},
|
||||||
|
queueTableRowIdx: 1,
|
||||||
|
selectedQueue: &asynq.QueueInfo{Queue: "default", Size: 50, Active: 10, Pending: 40},
|
||||||
|
taskState: asynq.TaskStatePending,
|
||||||
|
pageNum: 1,
|
||||||
|
tasks: []*asynq.TaskInfo{
|
||||||
|
{ID: "xxxx", Type: "foo"},
|
||||||
|
{ID: "yyyy", Type: "bar"},
|
||||||
|
{ID: "zzzz", Type: "baz"},
|
||||||
|
},
|
||||||
|
taskTableRowIdx: 2,
|
||||||
|
taskID: "yyyy", // presence of this field opens the modal
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// TODO: Add more tests
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
t.Run(tc.desc, func(t *testing.T) {
|
||||||
|
h := makeKeyEventHandler(t, tc.state)
|
||||||
|
for _, e := range tc.events {
|
||||||
|
h.HandleKeyEvent(e)
|
||||||
|
}
|
||||||
|
if diff := cmp.Diff(tc.wantState, *tc.state, cmp.AllowUnexported(State{})); diff != "" {
|
||||||
|
t.Errorf("after state was %+v, want %+v: (-want,+got)\n%s", *tc.state, tc.wantState, diff)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/*** fake implementation for tests ***/
|
||||||
|
|
||||||
|
type fakeFetcher struct{}
|
||||||
|
|
||||||
|
func (f *fakeFetcher) Fetch(s *State) {}
|
||||||
|
|
||||||
|
type fakeDrawer struct{}
|
||||||
|
|
||||||
|
func (d *fakeDrawer) Draw(s *State) {}
|
||||||
100
tools/asynq/cmd/dash/screen_drawer.go
Normal file
100
tools/asynq/cmd/dash/screen_drawer.go
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
// Copyright 2022 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package dash
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/gdamore/tcell/v2"
|
||||||
|
"github.com/mattn/go-runewidth"
|
||||||
|
)
|
||||||
|
|
||||||
|
/*** Screen Drawer ***/
|
||||||
|
|
||||||
|
// ScreenDrawer is used to draw contents on screen.
|
||||||
|
//
|
||||||
|
// Usage example:
|
||||||
|
// d := NewScreenDrawer(s)
|
||||||
|
// d.Println("Hello world", mystyle)
|
||||||
|
// d.NL() // adds newline
|
||||||
|
// d.Print("foo", mystyle.Bold(true))
|
||||||
|
// d.Print("bar", mystyle.Italic(true))
|
||||||
|
type ScreenDrawer struct {
|
||||||
|
l *LineDrawer
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewScreenDrawer(s tcell.Screen) *ScreenDrawer {
|
||||||
|
return &ScreenDrawer{l: NewLineDrawer(0, s)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *ScreenDrawer) Print(s string, style tcell.Style) {
|
||||||
|
d.l.Draw(s, style)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *ScreenDrawer) Println(s string, style tcell.Style) {
|
||||||
|
d.Print(s, style)
|
||||||
|
d.NL()
|
||||||
|
}
|
||||||
|
|
||||||
|
// FillLine prints the given rune until the end of the current line
|
||||||
|
// and adds a newline.
|
||||||
|
func (d *ScreenDrawer) FillLine(r rune, style tcell.Style) {
|
||||||
|
w, _ := d.Screen().Size()
|
||||||
|
if w-d.l.col < 0 {
|
||||||
|
d.NL()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s := strings.Repeat(string(r), w-d.l.col)
|
||||||
|
d.Print(s, style)
|
||||||
|
d.NL()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *ScreenDrawer) FillUntil(r rune, style tcell.Style, limit int) {
|
||||||
|
if d.l.col > limit {
|
||||||
|
return // already passed the limit
|
||||||
|
}
|
||||||
|
s := strings.Repeat(string(r), limit-d.l.col)
|
||||||
|
d.Print(s, style)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NL adds a newline (i.e., moves to the next line).
|
||||||
|
func (d *ScreenDrawer) NL() {
|
||||||
|
d.l.row++
|
||||||
|
d.l.col = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *ScreenDrawer) Screen() tcell.Screen {
|
||||||
|
return d.l.s
|
||||||
|
}
|
||||||
|
|
||||||
|
// Goto moves the screendrawer to the specified cell.
|
||||||
|
func (d *ScreenDrawer) Goto(x, y int) {
|
||||||
|
d.l.row = y
|
||||||
|
d.l.col = x
|
||||||
|
}
|
||||||
|
|
||||||
|
// Go to the bottom of the screen.
|
||||||
|
func (d *ScreenDrawer) GoToBottom() {
|
||||||
|
_, h := d.Screen().Size()
|
||||||
|
d.l.row = h - 1
|
||||||
|
d.l.col = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
type LineDrawer struct {
|
||||||
|
s tcell.Screen
|
||||||
|
row int
|
||||||
|
col int
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewLineDrawer(row int, s tcell.Screen) *LineDrawer {
|
||||||
|
return &LineDrawer{row: row, col: 0, s: s}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *LineDrawer) Draw(s string, style tcell.Style) {
|
||||||
|
for _, r := range s {
|
||||||
|
d.s.SetContent(d.col, d.row, r, nil, style)
|
||||||
|
d.col += runewidth.RuneWidth(r)
|
||||||
|
}
|
||||||
|
}
|
||||||
70
tools/asynq/cmd/dash/table.go
Normal file
70
tools/asynq/cmd/dash/table.go
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
// Copyright 2022 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package dash
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gdamore/tcell/v2"
|
||||||
|
"github.com/mattn/go-runewidth"
|
||||||
|
)
|
||||||
|
|
||||||
|
type columnAlignment int
|
||||||
|
|
||||||
|
const (
|
||||||
|
alignRight columnAlignment = iota
|
||||||
|
alignLeft
|
||||||
|
)
|
||||||
|
|
||||||
|
type columnConfig[V any] struct {
|
||||||
|
name string
|
||||||
|
alignment columnAlignment
|
||||||
|
displayFn func(v V) string
|
||||||
|
}
|
||||||
|
|
||||||
|
type column[V any] struct {
|
||||||
|
*columnConfig[V]
|
||||||
|
width int
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper to draw a table.
|
||||||
|
func drawTable[V any](d *ScreenDrawer, style tcell.Style, configs []*columnConfig[V], data []V, highlightRowIdx int) {
|
||||||
|
const colBuffer = " " // extra buffer between columns
|
||||||
|
cols := make([]*column[V], len(configs))
|
||||||
|
for i, cfg := range configs {
|
||||||
|
cols[i] = &column[V]{cfg, runewidth.StringWidth(cfg.name)}
|
||||||
|
}
|
||||||
|
// adjust the column width to accommodate the widest value.
|
||||||
|
for _, v := range data {
|
||||||
|
for _, col := range cols {
|
||||||
|
if w := runewidth.StringWidth(col.displayFn(v)); col.width < w {
|
||||||
|
col.width = w
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// print header
|
||||||
|
headerStyle := style.Background(tcell.ColorDimGray).Foreground(tcell.ColorWhite)
|
||||||
|
for _, col := range cols {
|
||||||
|
if col.alignment == alignLeft {
|
||||||
|
d.Print(rpad(col.name, col.width)+colBuffer, headerStyle)
|
||||||
|
} else {
|
||||||
|
d.Print(lpad(col.name, col.width)+colBuffer, headerStyle)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
d.FillLine(' ', headerStyle)
|
||||||
|
// print body
|
||||||
|
for i, v := range data {
|
||||||
|
rowStyle := style
|
||||||
|
if highlightRowIdx == i {
|
||||||
|
rowStyle = style.Background(tcell.ColorDarkOliveGreen)
|
||||||
|
}
|
||||||
|
for _, col := range cols {
|
||||||
|
if col.alignment == alignLeft {
|
||||||
|
d.Print(rpad(col.displayFn(v), col.width)+colBuffer, rowStyle)
|
||||||
|
} else {
|
||||||
|
d.Print(lpad(col.displayFn(v), col.width)+colBuffer, rowStyle)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
d.FillLine(' ', rowStyle)
|
||||||
|
}
|
||||||
|
}
|
||||||
52
tools/asynq/cmd/group.go
Normal file
52
tools/asynq/cmd/group.go
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
// Copyright 2022 Kentaro Hibino. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT license
|
||||||
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package cmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"github.com/MakeNowJust/heredoc/v2"
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
rootCmd.AddCommand(groupCmd)
|
||||||
|
groupCmd.AddCommand(groupListCmd)
|
||||||
|
groupListCmd.Flags().StringP("queue", "q", "", "queue to inspect")
|
||||||
|
groupListCmd.MarkFlagRequired("queue")
|
||||||
|
}
|
||||||
|
|
||||||
|
var groupCmd = &cobra.Command{
|
||||||
|
Use: "group <command> [flags]",
|
||||||
|
Short: "Manage groups",
|
||||||
|
Example: heredoc.Doc(`
|
||||||
|
$ asynq group list --queue=myqueue`),
|
||||||
|
}
|
||||||
|
|
||||||
|
var groupListCmd = &cobra.Command{
|
||||||
|
Use: "list",
|
||||||
|
Aliases: []string{"ls"},
|
||||||
|
Short: "List groups",
|
||||||
|
Args: cobra.NoArgs,
|
||||||
|
Run: groupLists,
|
||||||
|
}
|
||||||
|
|
||||||
|
func groupLists(cmd *cobra.Command, args []string) {
|
||||||
|
qname, err := cmd.Flags().GetString("queue")
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
inspector := createInspector()
|
||||||
|
groups, err := inspector.Groups(qname)
|
||||||
|
if len(groups) == 0 {
|
||||||
|
fmt.Printf("No groups found in queue %q\n", qname)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, g := range groups {
|
||||||
|
fmt.Println(g.Group)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,389 +0,0 @@
|
|||||||
// Copyright 2020 Kentaro Hibino. All rights reserved.
|
|
||||||
// Use of this source code is governed by a MIT license
|
|
||||||
// that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package cmd
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/go-redis/redis/v7"
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"github.com/hibiken/asynq/internal/base"
|
|
||||||
"github.com/spf13/cast"
|
|
||||||
"github.com/spf13/cobra"
|
|
||||||
"github.com/spf13/viper"
|
|
||||||
)
|
|
||||||
|
|
||||||
var migrateCmd = &cobra.Command{
|
|
||||||
Use: "migrate",
|
|
||||||
Short: fmt.Sprintf("Migrate all tasks to be compatible with asynq v%s", base.Version),
|
|
||||||
Args: cobra.NoArgs,
|
|
||||||
Run: migrate,
|
|
||||||
}
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
rootCmd.AddCommand(migrateCmd)
|
|
||||||
}
|
|
||||||
|
|
||||||
func migrate(cmd *cobra.Command, args []string) {
|
|
||||||
c := redis.NewClient(&redis.Options{
|
|
||||||
Addr: viper.GetString("uri"),
|
|
||||||
DB: viper.GetInt("db"),
|
|
||||||
Password: viper.GetString("password"),
|
|
||||||
})
|
|
||||||
r := createRDB()
|
|
||||||
|
|
||||||
/*** Migrate from 0.9 to 0.10, 0.11 compatible ***/
|
|
||||||
lists := []string{"asynq:in_progress"}
|
|
||||||
allQueues, err := c.SMembers(base.AllQueues).Result()
|
|
||||||
if err != nil {
|
|
||||||
printError(fmt.Errorf("could not read all queues: %v", err))
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
lists = append(lists, allQueues...)
|
|
||||||
for _, key := range lists {
|
|
||||||
if err := migrateList(c, key); err != nil {
|
|
||||||
printError(err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
zsets := []string{"asynq:scheduled", "asynq:retry", "asynq:dead"}
|
|
||||||
for _, key := range zsets {
|
|
||||||
if err := migrateZSet(c, key); err != nil {
|
|
||||||
printError(err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/*** Migrate from 0.11 to 0.12 compatible ***/
|
|
||||||
if err := createBackup(c, base.AllQueues); err != nil {
|
|
||||||
printError(err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
for _, qkey := range allQueues {
|
|
||||||
qname := strings.TrimPrefix(qkey, "asynq:queues:")
|
|
||||||
if err := c.SAdd(base.AllQueues, qname).Err(); err != nil {
|
|
||||||
err = fmt.Errorf("could not add queue name %q to %q set: %v\n",
|
|
||||||
qname, base.AllQueues, err)
|
|
||||||
printError(err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := deleteBackup(c, base.AllQueues); err != nil {
|
|
||||||
printError(err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, qkey := range allQueues {
|
|
||||||
qname := strings.TrimPrefix(qkey, "asynq:queues:")
|
|
||||||
if exists := c.Exists(qkey).Val(); exists == 1 {
|
|
||||||
if err := c.Rename(qkey, base.QueueKey(qname)).Err(); err != nil {
|
|
||||||
printError(fmt.Errorf("could not rename key %q: %v\n", qkey, err))
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := partitionZSetMembersByQueue(c, "asynq:scheduled", base.ScheduledKey); err != nil {
|
|
||||||
printError(err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
if err := partitionZSetMembersByQueue(c, "asynq:retry", base.RetryKey); err != nil {
|
|
||||||
printError(err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
// Note: base.DeadKey function was renamed in v0.14. We define the legacy function here since we need it for this migration script.
|
|
||||||
deadKeyFunc := func(qname string) string { return fmt.Sprintf("asynq:{%s}:dead", qname) }
|
|
||||||
if err := partitionZSetMembersByQueue(c, "asynq:dead", deadKeyFunc); err != nil {
|
|
||||||
printError(err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
if err := partitionZSetMembersByQueue(c, "asynq:deadlines", base.DeadlinesKey); err != nil {
|
|
||||||
printError(err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
if err := partitionListMembersByQueue(c, "asynq:in_progress", base.ActiveKey); err != nil {
|
|
||||||
printError(err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
paused, err := c.SMembers("asynq:paused").Result()
|
|
||||||
if err != nil {
|
|
||||||
printError(fmt.Errorf("command SMEMBERS asynq:paused failed: %v", err))
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
for _, qkey := range paused {
|
|
||||||
qname := strings.TrimPrefix(qkey, "asynq:queues:")
|
|
||||||
if err := r.Pause(qname); err != nil {
|
|
||||||
printError(err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := deleteKey(c, "asynq:paused"); err != nil {
|
|
||||||
printError(err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := deleteKey(c, "asynq:servers"); err != nil {
|
|
||||||
printError(err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
if err := deleteKey(c, "asynq:workers"); err != nil {
|
|
||||||
printError(err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
/*** Migrate from 0.13 to 0.14 compatible ***/
|
|
||||||
|
|
||||||
// Move all dead tasks to archived ZSET.
|
|
||||||
for _, qname := range allQueues {
|
|
||||||
zs, err := c.ZRangeWithScores(deadKeyFunc(qname), 0, -1).Result()
|
|
||||||
if err != nil {
|
|
||||||
printError(err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
for _, z := range zs {
|
|
||||||
if err := c.ZAdd(base.ArchivedKey(qname), &z).Err(); err != nil {
|
|
||||||
printError(err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := deleteKey(c, deadKeyFunc(qname)); err != nil {
|
|
||||||
printError(err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func backupKey(key string) string {
|
|
||||||
return fmt.Sprintf("%s:backup", key)
|
|
||||||
}
|
|
||||||
|
|
||||||
func createBackup(c *redis.Client, key string) error {
|
|
||||||
err := c.Rename(key, backupKey(key)).Err()
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("could not rename key %q: %v", key, err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func deleteBackup(c *redis.Client, key string) error {
|
|
||||||
return deleteKey(c, backupKey(key))
|
|
||||||
}
|
|
||||||
|
|
||||||
func deleteKey(c *redis.Client, key string) error {
|
|
||||||
exists := c.Exists(key).Val()
|
|
||||||
if exists == 0 {
|
|
||||||
// key does not exist
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
err := c.Del(key).Err()
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("could not delete key %q: %v", key, err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func printError(err error) {
|
|
||||||
fmt.Println(err)
|
|
||||||
fmt.Println()
|
|
||||||
fmt.Println("Migrate command error")
|
|
||||||
fmt.Println("Please file an issue on Github at https://github.com/hibiken/asynq/issues/new/choose")
|
|
||||||
}
|
|
||||||
|
|
||||||
func partitionZSetMembersByQueue(c *redis.Client, key string, newKeyFunc func(string) string) error {
|
|
||||||
zs, err := c.ZRangeWithScores(key, 0, -1).Result()
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("command ZRANGE %s 0 -1 WITHSCORES failed: %v", key, err)
|
|
||||||
}
|
|
||||||
for _, z := range zs {
|
|
||||||
s := cast.ToString(z.Member)
|
|
||||||
msg, err := base.DecodeMessage(s)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("could not decode message from %q: %v", key, err)
|
|
||||||
}
|
|
||||||
if err := c.ZAdd(newKeyFunc(msg.Queue), &z).Err(); err != nil {
|
|
||||||
return fmt.Errorf("could not add %v to %q: %v", z, newKeyFunc(msg.Queue))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := deleteKey(c, key); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func partitionListMembersByQueue(c *redis.Client, key string, newKeyFunc func(string) string) error {
|
|
||||||
data, err := c.LRange(key, 0, -1).Result()
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("command LRANGE %s 0 -1 failed: %v", key, err)
|
|
||||||
}
|
|
||||||
for _, s := range data {
|
|
||||||
msg, err := base.DecodeMessage(s)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("could not decode message from %q: %v", key, err)
|
|
||||||
}
|
|
||||||
if err := c.LPush(newKeyFunc(msg.Queue), s).Err(); err != nil {
|
|
||||||
return fmt.Errorf("could not add %v to %q: %v", s, newKeyFunc(msg.Queue))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := deleteKey(c, key); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type oldTaskMessage struct {
|
|
||||||
// Unchanged
|
|
||||||
Type string
|
|
||||||
Payload map[string]interface{}
|
|
||||||
ID uuid.UUID
|
|
||||||
Queue string
|
|
||||||
Retry int
|
|
||||||
Retried int
|
|
||||||
ErrorMsg string
|
|
||||||
UniqueKey string
|
|
||||||
|
|
||||||
// Following fields have changed.
|
|
||||||
|
|
||||||
// Deadline specifies the deadline for the task.
|
|
||||||
// Task won't be processed if it exceeded its deadline.
|
|
||||||
// The string shoulbe be in RFC3339 format.
|
|
||||||
//
|
|
||||||
// time.Time's zero value means no deadline.
|
|
||||||
Timeout string
|
|
||||||
|
|
||||||
// Deadline specifies the deadline for the task.
|
|
||||||
// Task won't be processed if it exceeded its deadline.
|
|
||||||
// The string shoulbe be in RFC3339 format.
|
|
||||||
//
|
|
||||||
// time.Time's zero value means no deadline.
|
|
||||||
Deadline string
|
|
||||||
}
|
|
||||||
|
|
||||||
var defaultTimeout = 30 * time.Minute
|
|
||||||
|
|
||||||
func convertMessage(old *oldTaskMessage) (*base.TaskMessage, error) {
|
|
||||||
timeout, err := time.ParseDuration(old.Timeout)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("could not parse Timeout field of %+v", old)
|
|
||||||
}
|
|
||||||
deadline, err := time.Parse(time.RFC3339, old.Deadline)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("could not parse Deadline field of %+v", old)
|
|
||||||
}
|
|
||||||
if timeout == 0 && deadline.IsZero() {
|
|
||||||
timeout = defaultTimeout
|
|
||||||
}
|
|
||||||
if deadline.IsZero() {
|
|
||||||
// Zero value used to be time.Time{},
|
|
||||||
// in the new schema zero value is represented by
|
|
||||||
// zero in Unix time.
|
|
||||||
deadline = time.Unix(0, 0)
|
|
||||||
}
|
|
||||||
return &base.TaskMessage{
|
|
||||||
Type: old.Type,
|
|
||||||
Payload: old.Payload,
|
|
||||||
ID: uuid.New(),
|
|
||||||
Queue: old.Queue,
|
|
||||||
Retry: old.Retry,
|
|
||||||
Retried: old.Retried,
|
|
||||||
ErrorMsg: old.ErrorMsg,
|
|
||||||
UniqueKey: old.UniqueKey,
|
|
||||||
Timeout: int64(timeout.Seconds()),
|
|
||||||
Deadline: deadline.Unix(),
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func deserialize(s string) (*base.TaskMessage, error) {
|
|
||||||
// Try deserializing as old message.
|
|
||||||
d := json.NewDecoder(strings.NewReader(s))
|
|
||||||
d.UseNumber()
|
|
||||||
var old *oldTaskMessage
|
|
||||||
if err := d.Decode(&old); err != nil {
|
|
||||||
// Try deserializing as new message.
|
|
||||||
d = json.NewDecoder(strings.NewReader(s))
|
|
||||||
d.UseNumber()
|
|
||||||
var msg *base.TaskMessage
|
|
||||||
if err := d.Decode(&msg); err != nil {
|
|
||||||
return nil, fmt.Errorf("could not deserialize %s into task message: %v", s, err)
|
|
||||||
}
|
|
||||||
return msg, nil
|
|
||||||
}
|
|
||||||
return convertMessage(old)
|
|
||||||
}
|
|
||||||
|
|
||||||
func migrateZSet(c *redis.Client, key string) error {
|
|
||||||
if c.Exists(key).Val() == 0 {
|
|
||||||
// skip if key doesn't exist.
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
res, err := c.ZRangeWithScores(key, 0, -1).Result()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var msgs []*redis.Z
|
|
||||||
for _, z := range res {
|
|
||||||
s, err := cast.ToStringE(z.Member)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("could not cast to string: %v", err)
|
|
||||||
}
|
|
||||||
msg, err := deserialize(s)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
encoded, err := base.EncodeMessage(msg)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("could not encode message from %q: %v", key, err)
|
|
||||||
}
|
|
||||||
msgs = append(msgs, &redis.Z{Score: z.Score, Member: encoded})
|
|
||||||
}
|
|
||||||
if err := c.Rename(key, key+":backup").Err(); err != nil {
|
|
||||||
return fmt.Errorf("could not rename key %q: %v", key, err)
|
|
||||||
}
|
|
||||||
if err := c.ZAdd(key, msgs...).Err(); err != nil {
|
|
||||||
return fmt.Errorf("could not write new messages to %q: %v", key, err)
|
|
||||||
}
|
|
||||||
if err := c.Del(key + ":backup").Err(); err != nil {
|
|
||||||
return fmt.Errorf("could not delete back up key %q: %v", key+":backup", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func migrateList(c *redis.Client, key string) error {
|
|
||||||
if c.Exists(key).Val() == 0 {
|
|
||||||
// skip if key doesn't exist.
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
res, err := c.LRange(key, 0, -1).Result()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var msgs []interface{}
|
|
||||||
for _, s := range res {
|
|
||||||
msg, err := deserialize(s)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
encoded, err := base.EncodeMessage(msg)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("could not encode message from %q: %v", key, err)
|
|
||||||
}
|
|
||||||
msgs = append(msgs, encoded)
|
|
||||||
}
|
|
||||||
if err := c.Rename(key, key+":backup").Err(); err != nil {
|
|
||||||
return fmt.Errorf("could not rename key %q: %v", key, err)
|
|
||||||
}
|
|
||||||
if err := c.LPush(key, msgs...).Err(); err != nil {
|
|
||||||
return fmt.Errorf("could not write new messages to %q: %v", key, err)
|
|
||||||
}
|
|
||||||
if err := c.Del(key + ":backup").Err(); err != nil {
|
|
||||||
return fmt.Errorf("could not delete back up key %q: %v", key+":backup", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -9,9 +9,10 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
|
"github.com/MakeNowJust/heredoc/v2"
|
||||||
"github.com/fatih/color"
|
"github.com/fatih/color"
|
||||||
"github.com/hibiken/asynq/inspeq"
|
"github.com/hibiken/asynq"
|
||||||
"github.com/hibiken/asynq/internal/rdb"
|
"github.com/hibiken/asynq/internal/errors"
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -31,58 +32,82 @@ func init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var queueCmd = &cobra.Command{
|
var queueCmd = &cobra.Command{
|
||||||
Use: "queue",
|
Use: "queue <command> [flags]",
|
||||||
Short: "Manage queues",
|
Short: "Manage queues",
|
||||||
|
Example: heredoc.Doc(`
|
||||||
|
$ asynq queue ls
|
||||||
|
$ asynq queue inspect myqueue
|
||||||
|
$ asynq queue pause myqueue`),
|
||||||
}
|
}
|
||||||
|
|
||||||
var queueListCmd = &cobra.Command{
|
var queueListCmd = &cobra.Command{
|
||||||
Use: "ls",
|
Use: "list",
|
||||||
Short: "List queues",
|
Short: "List queues",
|
||||||
|
Aliases: []string{"ls"},
|
||||||
// TODO: Use RunE instead?
|
// TODO: Use RunE instead?
|
||||||
Run: queueList,
|
Run: queueList,
|
||||||
}
|
}
|
||||||
|
|
||||||
var queueInspectCmd = &cobra.Command{
|
var queueInspectCmd = &cobra.Command{
|
||||||
Use: "inspect QUEUE [QUEUE...]",
|
Use: "inspect <queue> [<queue>...]",
|
||||||
Short: "Display detailed information on one or more queues",
|
Short: "Display detailed information on one or more queues",
|
||||||
Args: cobra.MinimumNArgs(1),
|
Args: cobra.MinimumNArgs(1),
|
||||||
// TODO: Use RunE instead?
|
// TODO: Use RunE instead?
|
||||||
Run: queueInspect,
|
Run: queueInspect,
|
||||||
|
Example: heredoc.Doc(`
|
||||||
|
$ asynq queue inspect myqueue
|
||||||
|
$ asynq queue inspect queue1 queue2 queue3`),
|
||||||
}
|
}
|
||||||
|
|
||||||
var queueHistoryCmd = &cobra.Command{
|
var queueHistoryCmd = &cobra.Command{
|
||||||
Use: "history QUEUE [QUEUE...]",
|
Use: "history <queue> [<queue>...]",
|
||||||
Short: "Display historical aggregate data from one or more queues",
|
Short: "Display historical aggregate data from one or more queues",
|
||||||
Args: cobra.MinimumNArgs(1),
|
Args: cobra.MinimumNArgs(1),
|
||||||
Run: queueHistory,
|
Run: queueHistory,
|
||||||
|
Example: heredoc.Doc(`
|
||||||
|
$ asynq queue history myqueue
|
||||||
|
$ asynq queue history queue1 queue2 queue3
|
||||||
|
$ asynq queue history myqueue --days=90`),
|
||||||
}
|
}
|
||||||
|
|
||||||
var queuePauseCmd = &cobra.Command{
|
var queuePauseCmd = &cobra.Command{
|
||||||
Use: "pause QUEUE [QUEUE...]",
|
Use: "pause <queue> [<queue>...]",
|
||||||
Short: "Pause one or more queues",
|
Short: "Pause one or more queues",
|
||||||
Args: cobra.MinimumNArgs(1),
|
Args: cobra.MinimumNArgs(1),
|
||||||
Run: queuePause,
|
Run: queuePause,
|
||||||
|
Example: heredoc.Doc(`
|
||||||
|
$ asynq queue pause myqueue
|
||||||
|
$ asynq queue pause queue1 queue2 queue3`),
|
||||||
}
|
}
|
||||||
|
|
||||||
var queueUnpauseCmd = &cobra.Command{
|
var queueUnpauseCmd = &cobra.Command{
|
||||||
Use: "unpause QUEUE [QUEUE...]",
|
Use: "resume <queue> [<queue>...]",
|
||||||
Short: "Unpause one or more queues",
|
Short: "Resume (unpause) one or more queues",
|
||||||
Args: cobra.MinimumNArgs(1),
|
Args: cobra.MinimumNArgs(1),
|
||||||
Run: queueUnpause,
|
Aliases: []string{"unpause"},
|
||||||
|
Run: queueUnpause,
|
||||||
|
Example: heredoc.Doc(`
|
||||||
|
$ asynq queue resume myqueue
|
||||||
|
$ asynq queue resume queue1 queue2 queue3`),
|
||||||
}
|
}
|
||||||
|
|
||||||
var queueRemoveCmd = &cobra.Command{
|
var queueRemoveCmd = &cobra.Command{
|
||||||
Use: "rm QUEUE [QUEUE...]",
|
Use: "remove <queue> [<queue>...]",
|
||||||
Short: "Remove one or more queues",
|
Short: "Remove one or more queues",
|
||||||
Args: cobra.MinimumNArgs(1),
|
Aliases: []string{"rm", "delete"},
|
||||||
Run: queueRemove,
|
Args: cobra.MinimumNArgs(1),
|
||||||
|
Run: queueRemove,
|
||||||
|
Example: heredoc.Doc(`
|
||||||
|
$ asynq queue rm myqueue
|
||||||
|
$ asynq queue rm queue1 queue2 queue3
|
||||||
|
$ asynq queue rm myqueue --force`),
|
||||||
}
|
}
|
||||||
|
|
||||||
func queueList(cmd *cobra.Command, args []string) {
|
func queueList(cmd *cobra.Command, args []string) {
|
||||||
type queueInfo struct {
|
type queueInfo struct {
|
||||||
name string
|
name string
|
||||||
keyslot int64
|
keyslot int64
|
||||||
nodes []inspeq.ClusterNode
|
nodes []*asynq.ClusterNode
|
||||||
}
|
}
|
||||||
inspector := createInspector()
|
inspector := createInspector()
|
||||||
queues, err := inspector.Queues()
|
queues, err := inspector.Queues()
|
||||||
@@ -90,7 +115,7 @@ func queueList(cmd *cobra.Command, args []string) {
|
|||||||
fmt.Printf("error: Could not fetch list of queues: %v\n", err)
|
fmt.Printf("error: Could not fetch list of queues: %v\n", err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
var qs []queueInfo
|
var qs []*queueInfo
|
||||||
for _, qname := range queues {
|
for _, qname := range queues {
|
||||||
q := queueInfo{name: qname}
|
q := queueInfo{name: qname}
|
||||||
if useRedisCluster {
|
if useRedisCluster {
|
||||||
@@ -107,7 +132,7 @@ func queueList(cmd *cobra.Command, args []string) {
|
|||||||
}
|
}
|
||||||
q.nodes = nodes
|
q.nodes = nodes
|
||||||
}
|
}
|
||||||
qs = append(qs, q)
|
qs = append(qs, &q)
|
||||||
}
|
}
|
||||||
if useRedisCluster {
|
if useRedisCluster {
|
||||||
printTable(
|
printTable(
|
||||||
@@ -129,43 +154,43 @@ func queueInspect(cmd *cobra.Command, args []string) {
|
|||||||
inspector := createInspector()
|
inspector := createInspector()
|
||||||
for i, qname := range args {
|
for i, qname := range args {
|
||||||
if i > 0 {
|
if i > 0 {
|
||||||
fmt.Printf("\n%s\n", separator)
|
fmt.Printf("\n%s\n\n", separator)
|
||||||
}
|
}
|
||||||
fmt.Println()
|
info, err := inspector.GetQueueInfo(qname)
|
||||||
stats, err := inspector.CurrentStats(qname)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("error: %v\n", err)
|
fmt.Printf("error: %v\n", err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
printQueueStats(stats)
|
printQueueInfo(info)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func printQueueStats(s *inspeq.QueueStats) {
|
func printQueueInfo(info *asynq.QueueInfo) {
|
||||||
bold := color.New(color.Bold)
|
bold := color.New(color.Bold)
|
||||||
bold.Println("Queue Info")
|
bold.Println("Queue Info")
|
||||||
fmt.Printf("Name: %s\n", s.Queue)
|
fmt.Printf("Name: %s\n", info.Queue)
|
||||||
fmt.Printf("Size: %d\n", s.Size)
|
fmt.Printf("Size: %d\n", info.Size)
|
||||||
fmt.Printf("Paused: %t\n\n", s.Paused)
|
fmt.Printf("Groups: %d\n", info.Groups)
|
||||||
|
fmt.Printf("Paused: %t\n\n", info.Paused)
|
||||||
bold.Println("Task Count by State")
|
bold.Println("Task Count by State")
|
||||||
printTable(
|
printTable(
|
||||||
[]string{"active", "pending", "scheduled", "retry", "archived"},
|
[]string{"active", "pending", "aggregating", "scheduled", "retry", "archived", "completed"},
|
||||||
func(w io.Writer, tmpl string) {
|
func(w io.Writer, tmpl string) {
|
||||||
fmt.Fprintf(w, tmpl, s.Active, s.Pending, s.Scheduled, s.Retry, s.Archived)
|
fmt.Fprintf(w, tmpl, info.Active, info.Pending, info.Aggregating, info.Scheduled, info.Retry, info.Archived, info.Completed)
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
fmt.Println()
|
fmt.Println()
|
||||||
bold.Printf("Daily Stats %s UTC\n", s.Timestamp.UTC().Format("2006-01-02"))
|
bold.Printf("Daily Stats %s UTC\n", info.Timestamp.UTC().Format("2006-01-02"))
|
||||||
printTable(
|
printTable(
|
||||||
[]string{"processed", "failed", "error rate"},
|
[]string{"processed", "failed", "error rate"},
|
||||||
func(w io.Writer, tmpl string) {
|
func(w io.Writer, tmpl string) {
|
||||||
var errRate string
|
var errRate string
|
||||||
if s.Processed == 0 {
|
if info.Processed == 0 {
|
||||||
errRate = "N/A"
|
errRate = "N/A"
|
||||||
} else {
|
} else {
|
||||||
errRate = fmt.Sprintf("%.2f%%", float64(s.Failed)/float64(s.Processed)*100)
|
errRate = fmt.Sprintf("%.2f%%", float64(info.Failed)/float64(info.Processed)*100)
|
||||||
}
|
}
|
||||||
fmt.Fprintf(w, tmpl, s.Processed, s.Failed, errRate)
|
fmt.Fprintf(w, tmpl, info.Processed, info.Failed, errRate)
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -179,9 +204,9 @@ func queueHistory(cmd *cobra.Command, args []string) {
|
|||||||
inspector := createInspector()
|
inspector := createInspector()
|
||||||
for i, qname := range args {
|
for i, qname := range args {
|
||||||
if i > 0 {
|
if i > 0 {
|
||||||
fmt.Printf("\n%s\n", separator)
|
fmt.Printf("\n%s\n\n", separator)
|
||||||
}
|
}
|
||||||
fmt.Printf("\nQueue: %s\n\n", qname)
|
fmt.Printf("Queue: %s\n\n", qname)
|
||||||
stats, err := inspector.History(qname, days)
|
stats, err := inspector.History(qname, days)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("error: %v\n", err)
|
fmt.Printf("error: %v\n", err)
|
||||||
@@ -191,7 +216,7 @@ func queueHistory(cmd *cobra.Command, args []string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func printDailyStats(stats []*inspeq.DailyStats) {
|
func printDailyStats(stats []*asynq.DailyStats) {
|
||||||
printTable(
|
printTable(
|
||||||
[]string{"date (UTC)", "processed", "failed", "error rate"},
|
[]string{"date (UTC)", "processed", "failed", "error rate"},
|
||||||
func(w io.Writer, tmpl string) {
|
func(w io.Writer, tmpl string) {
|
||||||
@@ -244,7 +269,7 @@ func queueRemove(cmd *cobra.Command, args []string) {
|
|||||||
for _, qname := range args {
|
for _, qname := range args {
|
||||||
err = r.RemoveQueue(qname, force)
|
err = r.RemoveQueue(qname, force)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if _, ok := err.(*rdb.ErrQueueNotEmpty); ok {
|
if errors.IsQueueNotEmpty(err) {
|
||||||
fmt.Printf("error: %v\nIf you are sure you want to delete it, run 'asynq queue rm --force %s'\n", err, qname)
|
fmt.Printf("error: %v\nIf you are sure you want to delete it, run 'asynq queue rm --force %s'\n", err, qname)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,13 +11,18 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
"text/tabwriter"
|
"text/tabwriter"
|
||||||
|
"unicode"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
"github.com/go-redis/redis/v7"
|
"github.com/MakeNowJust/heredoc/v2"
|
||||||
|
"github.com/fatih/color"
|
||||||
"github.com/hibiken/asynq"
|
"github.com/hibiken/asynq"
|
||||||
"github.com/hibiken/asynq/inspeq"
|
|
||||||
"github.com/hibiken/asynq/internal/base"
|
"github.com/hibiken/asynq/internal/base"
|
||||||
"github.com/hibiken/asynq/internal/rdb"
|
"github.com/hibiken/asynq/internal/rdb"
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
"github.com/spf13/pflag"
|
||||||
|
"golang.org/x/exp/utf8string"
|
||||||
|
|
||||||
homedir "github.com/mitchellh/go-homedir"
|
homedir "github.com/mitchellh/go-homedir"
|
||||||
"github.com/spf13/viper"
|
"github.com/spf13/viper"
|
||||||
@@ -38,10 +43,22 @@ var (
|
|||||||
|
|
||||||
// rootCmd represents the base command when called without any subcommands
|
// rootCmd represents the base command when called without any subcommands
|
||||||
var rootCmd = &cobra.Command{
|
var rootCmd = &cobra.Command{
|
||||||
Use: "asynq",
|
Use: "asynq <command> <subcommand> [flags]",
|
||||||
Short: "A monitoring tool for asynq queues",
|
Short: "Asynq CLI",
|
||||||
Long: `Asynq is a montoring CLI to inspect tasks and queues managed by asynq.`,
|
Long: `Command line tool to inspect tasks and queues managed by Asynq`,
|
||||||
Version: base.Version,
|
Version: base.Version,
|
||||||
|
|
||||||
|
SilenceUsage: true,
|
||||||
|
SilenceErrors: true,
|
||||||
|
|
||||||
|
Example: heredoc.Doc(`
|
||||||
|
$ asynq stats
|
||||||
|
$ asynq queue pause myqueue
|
||||||
|
$ asynq task list --queue=myqueue --state=archived`),
|
||||||
|
Annotations: map[string]string{
|
||||||
|
"help:feedback": heredoc.Doc(`
|
||||||
|
Open an issue at https://github.com/hibiken/asynq/issues/new/choose`),
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
var versionOutput = fmt.Sprintf("asynq version %s\n", base.Version)
|
var versionOutput = fmt.Sprintf("asynq version %s\n", base.Version)
|
||||||
@@ -63,22 +80,239 @@ func Execute() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func isRootCmd(cmd *cobra.Command) bool {
|
||||||
|
return cmd != nil && !cmd.HasParent()
|
||||||
|
}
|
||||||
|
|
||||||
|
// displayLine represents a line displayed in the output as '<name> <desc>',
|
||||||
|
// where pad is used to pad the name from desc.
|
||||||
|
type displayLine struct {
|
||||||
|
name string
|
||||||
|
desc string
|
||||||
|
pad int // number of rpad
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *displayLine) String() string {
|
||||||
|
return rpad(l.name, l.pad) + l.desc
|
||||||
|
}
|
||||||
|
|
||||||
|
type displayLines []*displayLine
|
||||||
|
|
||||||
|
func (dls displayLines) String() string {
|
||||||
|
var lines []string
|
||||||
|
for _, dl := range dls {
|
||||||
|
lines = append(lines, dl.String())
|
||||||
|
}
|
||||||
|
return strings.Join(lines, "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Capitalize the first word in the given string.
|
||||||
|
func capitalize(s string) string {
|
||||||
|
str := utf8string.NewString(s)
|
||||||
|
if str.RuneCount() == 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString(strings.ToUpper(string(str.At(0))))
|
||||||
|
b.WriteString(str.Slice(1, str.RuneCount()))
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func rootHelpFunc(cmd *cobra.Command, args []string) {
|
||||||
|
// Display helpful error message when user mistypes a subcommand (e.g. 'asynq queue lst').
|
||||||
|
if isRootCmd(cmd.Parent()) && len(args) >= 2 && args[1] != "--help" && args[1] != "-h" {
|
||||||
|
printSubcommandSuggestions(cmd, args[1])
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var lines []*displayLine
|
||||||
|
var commands []*displayLine
|
||||||
|
for _, c := range cmd.Commands() {
|
||||||
|
if c.Hidden || c.Short == "" || c.Name() == "help" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
l := &displayLine{name: c.Name() + ":", desc: capitalize(c.Short)}
|
||||||
|
commands = append(commands, l)
|
||||||
|
lines = append(lines, l)
|
||||||
|
}
|
||||||
|
var localFlags []*displayLine
|
||||||
|
cmd.LocalFlags().VisitAll(func(f *pflag.Flag) {
|
||||||
|
l := &displayLine{name: "--" + f.Name, desc: capitalize(f.Usage)}
|
||||||
|
localFlags = append(localFlags, l)
|
||||||
|
lines = append(lines, l)
|
||||||
|
})
|
||||||
|
var inheritedFlags []*displayLine
|
||||||
|
cmd.InheritedFlags().VisitAll(func(f *pflag.Flag) {
|
||||||
|
l := &displayLine{name: "--" + f.Name, desc: capitalize(f.Usage)}
|
||||||
|
inheritedFlags = append(inheritedFlags, l)
|
||||||
|
lines = append(lines, l)
|
||||||
|
})
|
||||||
|
adjustPadding(lines...)
|
||||||
|
|
||||||
|
type helpEntry struct {
|
||||||
|
Title string
|
||||||
|
Body string
|
||||||
|
}
|
||||||
|
var helpEntries []*helpEntry
|
||||||
|
desc := cmd.Long
|
||||||
|
if desc == "" {
|
||||||
|
desc = cmd.Short
|
||||||
|
}
|
||||||
|
if desc != "" {
|
||||||
|
helpEntries = append(helpEntries, &helpEntry{"", desc})
|
||||||
|
}
|
||||||
|
helpEntries = append(helpEntries, &helpEntry{"USAGE", cmd.UseLine()})
|
||||||
|
if len(commands) > 0 {
|
||||||
|
helpEntries = append(helpEntries, &helpEntry{"COMMANDS", displayLines(commands).String()})
|
||||||
|
}
|
||||||
|
if cmd.LocalFlags().HasFlags() {
|
||||||
|
helpEntries = append(helpEntries, &helpEntry{"FLAGS", displayLines(localFlags).String()})
|
||||||
|
}
|
||||||
|
if cmd.InheritedFlags().HasFlags() {
|
||||||
|
helpEntries = append(helpEntries, &helpEntry{"INHERITED FLAGS", displayLines(inheritedFlags).String()})
|
||||||
|
}
|
||||||
|
if cmd.Example != "" {
|
||||||
|
helpEntries = append(helpEntries, &helpEntry{"EXAMPLES", cmd.Example})
|
||||||
|
}
|
||||||
|
helpEntries = append(helpEntries, &helpEntry{"LEARN MORE", heredoc.Doc(`
|
||||||
|
Use 'asynq <command> <subcommand> --help' for more information about a command.`)})
|
||||||
|
if s, ok := cmd.Annotations["help:feedback"]; ok {
|
||||||
|
helpEntries = append(helpEntries, &helpEntry{"FEEDBACK", s})
|
||||||
|
}
|
||||||
|
|
||||||
|
out := cmd.OutOrStdout()
|
||||||
|
bold := color.New(color.Bold)
|
||||||
|
for _, e := range helpEntries {
|
||||||
|
if e.Title != "" {
|
||||||
|
// If there is a title, add indentation to each line in the body
|
||||||
|
bold.Fprintln(out, e.Title)
|
||||||
|
fmt.Fprintln(out, indent(e.Body, 2 /* spaces */))
|
||||||
|
} else {
|
||||||
|
// If there is no title, print the body as is
|
||||||
|
fmt.Fprintln(out, e.Body)
|
||||||
|
}
|
||||||
|
fmt.Fprintln(out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func rootUsageFunc(cmd *cobra.Command) error {
|
||||||
|
out := cmd.OutOrStdout()
|
||||||
|
fmt.Fprintf(out, "Usage: %s", cmd.UseLine())
|
||||||
|
if subcmds := cmd.Commands(); len(subcmds) > 0 {
|
||||||
|
fmt.Fprint(out, "\n\nAvailable commands:\n")
|
||||||
|
for _, c := range subcmds {
|
||||||
|
if c.Hidden {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
fmt.Fprintf(out, " %s\n", c.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var localFlags []*displayLine
|
||||||
|
cmd.LocalFlags().VisitAll(func(f *pflag.Flag) {
|
||||||
|
localFlags = append(localFlags, &displayLine{name: "--" + f.Name, desc: capitalize(f.Usage)})
|
||||||
|
})
|
||||||
|
adjustPadding(localFlags...)
|
||||||
|
if len(localFlags) > 0 {
|
||||||
|
fmt.Fprint(out, "\n\nFlags:\n")
|
||||||
|
for _, l := range localFlags {
|
||||||
|
fmt.Fprintf(out, " %s\n", l.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func printSubcommandSuggestions(cmd *cobra.Command, arg string) {
|
||||||
|
out := cmd.OutOrStdout()
|
||||||
|
fmt.Fprintf(out, "unknown command %q for %q\n", arg, cmd.CommandPath())
|
||||||
|
if cmd.SuggestionsMinimumDistance <= 0 {
|
||||||
|
cmd.SuggestionsMinimumDistance = 2
|
||||||
|
}
|
||||||
|
candidates := cmd.SuggestionsFor(arg)
|
||||||
|
if len(candidates) > 0 {
|
||||||
|
fmt.Fprint(out, "\nDid you mean this?\n")
|
||||||
|
for _, c := range candidates {
|
||||||
|
fmt.Fprintf(out, "\t%s\n", c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fmt.Fprintln(out)
|
||||||
|
rootUsageFunc(cmd)
|
||||||
|
}
|
||||||
|
|
||||||
|
func adjustPadding(lines ...*displayLine) {
|
||||||
|
// find the maximum width of the name
|
||||||
|
max := 0
|
||||||
|
for _, l := range lines {
|
||||||
|
if n := utf8.RuneCountInString(l.name); n > max {
|
||||||
|
max = n
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, l := range lines {
|
||||||
|
l.pad = max
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// rpad adds padding to the right of a string.
|
||||||
|
func rpad(s string, padding int) string {
|
||||||
|
tmpl := fmt.Sprintf("%%-%ds ", padding)
|
||||||
|
return fmt.Sprintf(tmpl, s)
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// lpad adds padding to the left of a string.
|
||||||
|
func lpad(s string, padding int) string {
|
||||||
|
tmpl := fmt.Sprintf("%%%ds ", padding)
|
||||||
|
return fmt.Sprintf(tmpl, s)
|
||||||
|
}
|
||||||
|
|
||||||
|
// indent indents the given text by given spaces.
|
||||||
|
func indent(text string, space int) string {
|
||||||
|
if len(text) == 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
var b strings.Builder
|
||||||
|
indentation := strings.Repeat(" ", space)
|
||||||
|
lastRune := '\n'
|
||||||
|
for _, r := range text {
|
||||||
|
if lastRune == '\n' {
|
||||||
|
b.WriteString(indentation)
|
||||||
|
}
|
||||||
|
b.WriteRune(r)
|
||||||
|
lastRune = r
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// dedent removes any indentation from the given text.
|
||||||
|
func dedent(text string) string {
|
||||||
|
lines := strings.Split(text, "\n")
|
||||||
|
var b strings.Builder
|
||||||
|
for _, l := range lines {
|
||||||
|
b.WriteString(strings.TrimLeftFunc(l, unicode.IsSpace))
|
||||||
|
b.WriteRune('\n')
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
cobra.OnInitialize(initConfig)
|
cobra.OnInitialize(initConfig)
|
||||||
|
|
||||||
|
rootCmd.SetHelpFunc(rootHelpFunc)
|
||||||
|
rootCmd.SetUsageFunc(rootUsageFunc)
|
||||||
|
|
||||||
rootCmd.AddCommand(versionCmd)
|
rootCmd.AddCommand(versionCmd)
|
||||||
rootCmd.SetVersionTemplate(versionOutput)
|
rootCmd.SetVersionTemplate(versionOutput)
|
||||||
|
|
||||||
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file to set flag defaut values (default is $HOME/.asynq.yaml)")
|
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "Config file to set flag defaut values (default is $HOME/.asynq.yaml)")
|
||||||
rootCmd.PersistentFlags().StringVarP(&uri, "uri", "u", "127.0.0.1:6379", "redis server URI")
|
rootCmd.PersistentFlags().StringVarP(&uri, "uri", "u", "127.0.0.1:6379", "Redis server URI")
|
||||||
rootCmd.PersistentFlags().IntVarP(&db, "db", "n", 0, "redis database number (default is 0)")
|
rootCmd.PersistentFlags().IntVarP(&db, "db", "n", 0, "Redis database number (default is 0)")
|
||||||
rootCmd.PersistentFlags().StringVarP(&password, "password", "p", "", "password to use when connecting to redis server")
|
rootCmd.PersistentFlags().StringVarP(&password, "password", "p", "", "Password to use when connecting to redis server")
|
||||||
rootCmd.PersistentFlags().BoolVar(&useRedisCluster, "cluster", false, "connect to redis cluster")
|
rootCmd.PersistentFlags().BoolVar(&useRedisCluster, "cluster", false, "Connect to redis cluster")
|
||||||
rootCmd.PersistentFlags().StringVar(&clusterAddrs, "cluster_addrs",
|
rootCmd.PersistentFlags().StringVar(&clusterAddrs, "cluster_addrs",
|
||||||
"127.0.0.1:7000,127.0.0.1:7001,127.0.0.1:7002,127.0.0.1:7003,127.0.0.1:7004,127.0.0.1:7005",
|
"127.0.0.1:7000,127.0.0.1:7001,127.0.0.1:7002,127.0.0.1:7003,127.0.0.1:7004,127.0.0.1:7005",
|
||||||
"list of comma-separated redis server addresses")
|
"List of comma-separated redis server addresses")
|
||||||
rootCmd.PersistentFlags().StringVar(&tlsServerName, "tls_server",
|
rootCmd.PersistentFlags().StringVar(&tlsServerName, "tls_server",
|
||||||
"", "server name for TLS validation")
|
"", "Server name for TLS validation")
|
||||||
// Bind flags with config.
|
// Bind flags with config.
|
||||||
viper.BindPFlag("uri", rootCmd.PersistentFlags().Lookup("uri"))
|
viper.BindPFlag("uri", rootCmd.PersistentFlags().Lookup("uri"))
|
||||||
viper.BindPFlag("db", rootCmd.PersistentFlags().Lookup("db"))
|
viper.BindPFlag("db", rootCmd.PersistentFlags().Lookup("db"))
|
||||||
@@ -117,7 +351,7 @@ func initConfig() {
|
|||||||
// createRDB creates a RDB instance using flag values and returns it.
|
// createRDB creates a RDB instance using flag values and returns it.
|
||||||
func createRDB() *rdb.RDB {
|
func createRDB() *rdb.RDB {
|
||||||
var c redis.UniversalClient
|
var c redis.UniversalClient
|
||||||
if useRedisCluster {
|
if viper.GetBool("cluster") {
|
||||||
addrs := strings.Split(viper.GetString("cluster_addrs"), ",")
|
addrs := strings.Split(viper.GetString("cluster_addrs"), ",")
|
||||||
c = redis.NewClusterClient(&redis.ClusterOptions{
|
c = redis.NewClusterClient(&redis.ClusterOptions{
|
||||||
Addrs: addrs,
|
Addrs: addrs,
|
||||||
@@ -135,25 +369,26 @@ func createRDB() *rdb.RDB {
|
|||||||
return rdb.NewRDB(c)
|
return rdb.NewRDB(c)
|
||||||
}
|
}
|
||||||
|
|
||||||
// createRDB creates a Inspector instance using flag values and returns it.
|
// createInspector creates a Inspector instance using flag values and returns it.
|
||||||
func createInspector() *inspeq.Inspector {
|
func createInspector() *asynq.Inspector {
|
||||||
var connOpt asynq.RedisConnOpt
|
return asynq.NewInspector(getRedisConnOpt())
|
||||||
if useRedisCluster {
|
}
|
||||||
|
|
||||||
|
func getRedisConnOpt() asynq.RedisConnOpt {
|
||||||
|
if viper.GetBool("cluster") {
|
||||||
addrs := strings.Split(viper.GetString("cluster_addrs"), ",")
|
addrs := strings.Split(viper.GetString("cluster_addrs"), ",")
|
||||||
connOpt = asynq.RedisClusterClientOpt{
|
return asynq.RedisClusterClientOpt{
|
||||||
Addrs: addrs,
|
Addrs: addrs,
|
||||||
Password: viper.GetString("password"),
|
Password: viper.GetString("password"),
|
||||||
TLSConfig: getTLSConfig(),
|
TLSConfig: getTLSConfig(),
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
connOpt = asynq.RedisClientOpt{
|
|
||||||
Addr: viper.GetString("uri"),
|
|
||||||
DB: viper.GetInt("db"),
|
|
||||||
Password: viper.GetString("password"),
|
|
||||||
TLSConfig: getTLSConfig(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return inspeq.New(connOpt)
|
return asynq.RedisClientOpt{
|
||||||
|
Addr: viper.GetString("uri"),
|
||||||
|
DB: viper.GetInt("db"),
|
||||||
|
Password: viper.GetString("password"),
|
||||||
|
TLSConfig: getTLSConfig(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func getTLSConfig() *tls.Config {
|
func getTLSConfig() *tls.Config {
|
||||||
@@ -196,3 +431,28 @@ func printTable(cols []string, printRows func(w io.Writer, tmpl string)) {
|
|||||||
printRows(tw, format)
|
printRows(tw, format)
|
||||||
tw.Flush()
|
tw.Flush()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// sprintBytes returns a string representation of the given byte slice if data is printable.
|
||||||
|
// If data is not printable, it returns a string describing it is not printable.
|
||||||
|
func sprintBytes(payload []byte) string {
|
||||||
|
if !isPrintable(payload) {
|
||||||
|
return "non-printable bytes"
|
||||||
|
}
|
||||||
|
return string(payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
func isPrintable(data []byte) bool {
|
||||||
|
if !utf8.Valid(data) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
isAllSpace := true
|
||||||
|
for _, r := range string(data) {
|
||||||
|
if !unicode.IsPrint(r) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if !unicode.IsSpace(r) {
|
||||||
|
isAllSpace = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return !isAllSpace
|
||||||
|
}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/MakeNowJust/heredoc/v2"
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -21,13 +22,16 @@ func init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var serverCmd = &cobra.Command{
|
var serverCmd = &cobra.Command{
|
||||||
Use: "server",
|
Use: "server <command> [flags]",
|
||||||
Short: "Manage servers",
|
Short: "Manage servers",
|
||||||
|
Example: heredoc.Doc(`
|
||||||
|
$ asynq server list`),
|
||||||
}
|
}
|
||||||
|
|
||||||
var serverListCmd = &cobra.Command{
|
var serverListCmd = &cobra.Command{
|
||||||
Use: "ls",
|
Use: "list",
|
||||||
Short: "List servers",
|
Aliases: []string{"ls"},
|
||||||
|
Short: "List servers",
|
||||||
Long: `Server list (asynq server ls) shows all running worker servers
|
Long: `Server list (asynq server ls) shows all running worker servers
|
||||||
pulling tasks from the given redis instance.
|
pulling tasks from the given redis instance.
|
||||||
|
|
||||||
@@ -35,11 +39,11 @@ The command shows the following for each server:
|
|||||||
* Host and PID of the process in which the server is running
|
* Host and PID of the process in which the server is running
|
||||||
* Number of active workers out of worker pool
|
* Number of active workers out of worker pool
|
||||||
* Queue configuration
|
* Queue configuration
|
||||||
* State of the worker server ("running" | "quiet")
|
* State of the worker server ("active" | "stopped")
|
||||||
* Time the server was started
|
* Time the server was started
|
||||||
|
|
||||||
A "running" server is pulling tasks from queues and processing them.
|
A "active" server is pulling tasks from queues and processing them.
|
||||||
A "quiet" server is no longer pulling new tasks from queues`,
|
A "stopped" server is no longer pulling new tasks from queues`,
|
||||||
Run: serverList,
|
Run: serverList,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,14 +5,18 @@
|
|||||||
package cmd
|
package cmd
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"math"
|
||||||
"os"
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"text/tabwriter"
|
"text/tabwriter"
|
||||||
"time"
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/MakeNowJust/heredoc/v2"
|
||||||
"github.com/fatih/color"
|
"github.com/fatih/color"
|
||||||
"github.com/hibiken/asynq/internal/rdb"
|
"github.com/hibiken/asynq/internal/rdb"
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
@@ -21,25 +25,24 @@ import (
|
|||||||
// statsCmd represents the stats command
|
// statsCmd represents the stats command
|
||||||
var statsCmd = &cobra.Command{
|
var statsCmd = &cobra.Command{
|
||||||
Use: "stats",
|
Use: "stats",
|
||||||
Short: "Shows current state of the tasks and queues",
|
Short: "View current state",
|
||||||
Long: `Stats (aysnqmon stats) will show the overview of tasks and queues at that instant.
|
Long: heredoc.Doc(`
|
||||||
|
Stats shows the overview of tasks and queues at that instant.
|
||||||
|
|
||||||
Specifically, the command shows the following:
|
The command shows the following:
|
||||||
* Number of tasks in each state
|
* Number of tasks in each state
|
||||||
* Number of tasks in each queue
|
* Number of tasks in each queue
|
||||||
* Aggregate data for the current day
|
* Aggregate data for the current day
|
||||||
* Basic information about the running redis instance
|
* Basic information about the running redis instance`),
|
||||||
|
|
||||||
To monitor the tasks continuously, it's recommended that you run this
|
|
||||||
command in conjunction with the watch command.
|
|
||||||
|
|
||||||
Example: watch -n 3 asynq stats -> Shows current state of tasks every three seconds`,
|
|
||||||
Args: cobra.NoArgs,
|
Args: cobra.NoArgs,
|
||||||
Run: stats,
|
Run: stats,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var jsonFlag bool
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
rootCmd.AddCommand(statsCmd)
|
rootCmd.AddCommand(statsCmd)
|
||||||
|
statsCmd.Flags().BoolVar(&jsonFlag, "json", false, "Output stats in JSON format.")
|
||||||
|
|
||||||
// Here you will define your flags and configuration settings.
|
// Here you will define your flags and configuration settings.
|
||||||
|
|
||||||
@@ -53,14 +56,22 @@ func init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type AggregateStats struct {
|
type AggregateStats struct {
|
||||||
Active int
|
Active int `json:"active"`
|
||||||
Pending int
|
Pending int `json:"pending"`
|
||||||
Scheduled int
|
Aggregating int `json:"aggregating"`
|
||||||
Retry int
|
Scheduled int `json:"scheduled"`
|
||||||
Archived int
|
Retry int `json:"retry"`
|
||||||
Processed int
|
Archived int `json:"archived"`
|
||||||
Failed int
|
Completed int `json:"completed"`
|
||||||
Timestamp time.Time
|
Processed int `json:"processed"`
|
||||||
|
Failed int `json:"failed"`
|
||||||
|
Timestamp time.Time `json:"timestamp"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type FullStats struct {
|
||||||
|
Aggregate AggregateStats `json:"aggregate"`
|
||||||
|
QueueStats []*rdb.Stats `json:"queues"`
|
||||||
|
RedisInfo map[string]string `json:"redis"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func stats(cmd *cobra.Command, args []string) {
|
func stats(cmd *cobra.Command, args []string) {
|
||||||
@@ -82,9 +93,11 @@ func stats(cmd *cobra.Command, args []string) {
|
|||||||
}
|
}
|
||||||
aggStats.Active += s.Active
|
aggStats.Active += s.Active
|
||||||
aggStats.Pending += s.Pending
|
aggStats.Pending += s.Pending
|
||||||
|
aggStats.Aggregating += s.Aggregating
|
||||||
aggStats.Scheduled += s.Scheduled
|
aggStats.Scheduled += s.Scheduled
|
||||||
aggStats.Retry += s.Retry
|
aggStats.Retry += s.Retry
|
||||||
aggStats.Archived += s.Archived
|
aggStats.Archived += s.Archived
|
||||||
|
aggStats.Completed += s.Completed
|
||||||
aggStats.Processed += s.Processed
|
aggStats.Processed += s.Processed
|
||||||
aggStats.Failed += s.Failed
|
aggStats.Failed += s.Failed
|
||||||
aggStats.Timestamp = s.Timestamp
|
aggStats.Timestamp = s.Timestamp
|
||||||
@@ -100,6 +113,23 @@ func stats(cmd *cobra.Command, args []string) {
|
|||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if jsonFlag {
|
||||||
|
statsJSON, err := json.Marshal(FullStats{
|
||||||
|
Aggregate: aggStats,
|
||||||
|
QueueStats: stats,
|
||||||
|
RedisInfo: info,
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println(string(statsJSON))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
bold := color.New(color.Bold)
|
bold := color.New(color.Bold)
|
||||||
bold.Println("Task Count by State")
|
bold.Println("Task Count by State")
|
||||||
printStatsByState(&aggStats)
|
printStatsByState(&aggStats)
|
||||||
@@ -124,22 +154,50 @@ func stats(cmd *cobra.Command, args []string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func printStatsByState(s *AggregateStats) {
|
func printStatsByState(s *AggregateStats) {
|
||||||
format := strings.Repeat("%v\t", 5) + "\n"
|
format := strings.Repeat("%v\t", 7) + "\n"
|
||||||
tw := new(tabwriter.Writer).Init(os.Stdout, 0, 8, 2, ' ', 0)
|
tw := new(tabwriter.Writer).Init(os.Stdout, 0, 8, 2, ' ', 0)
|
||||||
fmt.Fprintf(tw, format, "active", "pending", "scheduled", "retry", "archived")
|
fmt.Fprintf(tw, format, "active", "pending", "aggregating", "scheduled", "retry", "archived", "completed")
|
||||||
fmt.Fprintf(tw, format, "----------", "--------", "---------", "-----", "----")
|
width := maxInt(9 /* defaultWidth */, maxWidthOf(s.Active, s.Pending, s.Aggregating, s.Scheduled, s.Retry, s.Archived, s.Completed)) // length of widest column
|
||||||
fmt.Fprintf(tw, format, s.Active, s.Pending, s.Scheduled, s.Retry, s.Archived)
|
sep := strings.Repeat("-", width)
|
||||||
|
fmt.Fprintf(tw, format, sep, sep, sep, sep, sep, sep, sep)
|
||||||
|
fmt.Fprintf(tw, format, s.Active, s.Pending, s.Aggregating, s.Scheduled, s.Retry, s.Archived, s.Completed)
|
||||||
tw.Flush()
|
tw.Flush()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// numDigits returns the number of digits in n.
|
||||||
|
func numDigits(n int) int {
|
||||||
|
return len(strconv.Itoa(n))
|
||||||
|
}
|
||||||
|
|
||||||
|
// maxWidthOf returns the max number of digits amount the provided vals.
|
||||||
|
func maxWidthOf(vals ...int) int {
|
||||||
|
max := 0
|
||||||
|
for _, v := range vals {
|
||||||
|
if vw := numDigits(v); vw > max {
|
||||||
|
max = vw
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return max
|
||||||
|
}
|
||||||
|
|
||||||
|
func maxInt(a, b int) int {
|
||||||
|
return int(math.Max(float64(a), float64(b)))
|
||||||
|
}
|
||||||
|
|
||||||
func printStatsByQueue(stats []*rdb.Stats) {
|
func printStatsByQueue(stats []*rdb.Stats) {
|
||||||
var headers, seps, counts []string
|
var headers, seps, counts []string
|
||||||
|
maxHeaderWidth := 0
|
||||||
for _, s := range stats {
|
for _, s := range stats {
|
||||||
title := queueTitle(s)
|
title := queueTitle(s)
|
||||||
headers = append(headers, title)
|
headers = append(headers, title)
|
||||||
seps = append(seps, strings.Repeat("-", len(title)))
|
if w := utf8.RuneCountInString(title); w > maxHeaderWidth {
|
||||||
|
maxHeaderWidth = w
|
||||||
|
}
|
||||||
counts = append(counts, strconv.Itoa(s.Size))
|
counts = append(counts, strconv.Itoa(s.Size))
|
||||||
}
|
}
|
||||||
|
for i := 0; i < len(headers); i++ {
|
||||||
|
seps = append(seps, strings.Repeat("-", maxHeaderWidth))
|
||||||
|
}
|
||||||
format := strings.Repeat("%v\t", len(headers)) + "\n"
|
format := strings.Repeat("%v\t", len(headers)) + "\n"
|
||||||
tw := new(tabwriter.Writer).Init(os.Stdout, 0, 8, 2, ' ', 0)
|
tw := new(tabwriter.Writer).Init(os.Stdout, 0, 8, 2, ' ', 0)
|
||||||
fmt.Fprintf(tw, format, toInterfaceSlice(headers)...)
|
fmt.Fprintf(tw, format, toInterfaceSlice(headers)...)
|
||||||
|
|||||||
@@ -10,136 +10,175 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/hibiken/asynq/inspeq"
|
"github.com/MakeNowJust/heredoc/v2"
|
||||||
|
"github.com/fatih/color"
|
||||||
|
"github.com/hibiken/asynq"
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
rootCmd.AddCommand(taskCmd)
|
rootCmd.AddCommand(taskCmd)
|
||||||
taskCmd.AddCommand(taskListCmd)
|
taskCmd.AddCommand(taskListCmd)
|
||||||
taskListCmd.Flags().StringP("queue", "q", "", "queue to inspect")
|
taskListCmd.Flags().StringP("queue", "q", "", "queue to inspect (required)")
|
||||||
taskListCmd.Flags().StringP("state", "s", "", "state of the tasks to inspect")
|
taskListCmd.Flags().StringP("state", "s", "", "state of the tasks; one of { active | pending | aggregating | scheduled | retry | archived | completed } (required)")
|
||||||
taskListCmd.Flags().Int("page", 1, "page number")
|
taskListCmd.Flags().Int("page", 1, "page number")
|
||||||
taskListCmd.Flags().Int("size", 30, "page size")
|
taskListCmd.Flags().Int("size", 30, "page size")
|
||||||
|
taskListCmd.Flags().StringP("group", "g", "", "group to inspect (required for listing aggregating tasks)")
|
||||||
taskListCmd.MarkFlagRequired("queue")
|
taskListCmd.MarkFlagRequired("queue")
|
||||||
taskListCmd.MarkFlagRequired("state")
|
taskListCmd.MarkFlagRequired("state")
|
||||||
|
|
||||||
taskCmd.AddCommand(taskCancelCmd)
|
taskCmd.AddCommand(taskCancelCmd)
|
||||||
|
|
||||||
|
taskCmd.AddCommand(taskInspectCmd)
|
||||||
|
taskInspectCmd.Flags().StringP("queue", "q", "", "queue to which the task belongs (required)")
|
||||||
|
taskInspectCmd.Flags().StringP("id", "i", "", "id of the task (required)")
|
||||||
|
taskInspectCmd.MarkFlagRequired("queue")
|
||||||
|
taskInspectCmd.MarkFlagRequired("id")
|
||||||
|
|
||||||
taskCmd.AddCommand(taskArchiveCmd)
|
taskCmd.AddCommand(taskArchiveCmd)
|
||||||
taskArchiveCmd.Flags().StringP("queue", "q", "", "queue to which the task belongs")
|
taskArchiveCmd.Flags().StringP("queue", "q", "", "queue to which the task belongs (required)")
|
||||||
taskArchiveCmd.Flags().StringP("key", "k", "", "key of the task")
|
taskArchiveCmd.Flags().StringP("id", "i", "", "id of the task (required)")
|
||||||
taskArchiveCmd.MarkFlagRequired("queue")
|
taskArchiveCmd.MarkFlagRequired("queue")
|
||||||
taskArchiveCmd.MarkFlagRequired("key")
|
taskArchiveCmd.MarkFlagRequired("id")
|
||||||
|
|
||||||
taskCmd.AddCommand(taskDeleteCmd)
|
taskCmd.AddCommand(taskDeleteCmd)
|
||||||
taskDeleteCmd.Flags().StringP("queue", "q", "", "queue to which the task belongs")
|
taskDeleteCmd.Flags().StringP("queue", "q", "", "queue to which the task belongs (required)")
|
||||||
taskDeleteCmd.Flags().StringP("key", "k", "", "key of the task")
|
taskDeleteCmd.Flags().StringP("id", "i", "", "id of the task (required)")
|
||||||
taskDeleteCmd.MarkFlagRequired("queue")
|
taskDeleteCmd.MarkFlagRequired("queue")
|
||||||
taskDeleteCmd.MarkFlagRequired("key")
|
taskDeleteCmd.MarkFlagRequired("id")
|
||||||
|
|
||||||
taskCmd.AddCommand(taskRunCmd)
|
taskCmd.AddCommand(taskRunCmd)
|
||||||
taskRunCmd.Flags().StringP("queue", "q", "", "queue to which the task belongs")
|
taskRunCmd.Flags().StringP("queue", "q", "", "queue to which the task belongs (required)")
|
||||||
taskRunCmd.Flags().StringP("key", "k", "", "key of the task")
|
taskRunCmd.Flags().StringP("id", "i", "", "id of the task (required)")
|
||||||
taskRunCmd.MarkFlagRequired("queue")
|
taskRunCmd.MarkFlagRequired("queue")
|
||||||
taskRunCmd.MarkFlagRequired("key")
|
taskRunCmd.MarkFlagRequired("id")
|
||||||
|
|
||||||
taskCmd.AddCommand(taskArchiveAllCmd)
|
taskCmd.AddCommand(taskArchiveAllCmd)
|
||||||
taskArchiveAllCmd.Flags().StringP("queue", "q", "", "queue to which the tasks belong")
|
taskArchiveAllCmd.Flags().StringP("queue", "q", "", "queue to which the tasks belong (required)")
|
||||||
taskArchiveAllCmd.Flags().StringP("state", "s", "", "state of the tasks")
|
taskArchiveAllCmd.Flags().StringP("state", "s", "", "state of the tasks; one of { pending | aggregating | scheduled | retry } (required)")
|
||||||
taskArchiveAllCmd.MarkFlagRequired("queue")
|
taskArchiveAllCmd.MarkFlagRequired("queue")
|
||||||
taskArchiveAllCmd.MarkFlagRequired("state")
|
taskArchiveAllCmd.MarkFlagRequired("state")
|
||||||
|
taskArchiveAllCmd.Flags().StringP("group", "g", "", "group to which the tasks belong (required for archiving aggregating tasks)")
|
||||||
|
|
||||||
taskCmd.AddCommand(taskDeleteAllCmd)
|
taskCmd.AddCommand(taskDeleteAllCmd)
|
||||||
taskDeleteAllCmd.Flags().StringP("queue", "q", "", "queue to which the tasks belong")
|
taskDeleteAllCmd.Flags().StringP("queue", "q", "", "queue to which the tasks belong (required)")
|
||||||
taskDeleteAllCmd.Flags().StringP("state", "s", "", "state of the tasks")
|
taskDeleteAllCmd.Flags().StringP("state", "s", "", "state of the tasks; one of { pending | aggregating | scheduled | retry | archived | completed } (required)")
|
||||||
taskDeleteAllCmd.MarkFlagRequired("queue")
|
taskDeleteAllCmd.MarkFlagRequired("queue")
|
||||||
taskDeleteAllCmd.MarkFlagRequired("state")
|
taskDeleteAllCmd.MarkFlagRequired("state")
|
||||||
|
taskDeleteAllCmd.Flags().StringP("group", "g", "", "group to which the tasks belong (required for deleting aggregating tasks)")
|
||||||
|
|
||||||
taskCmd.AddCommand(taskRunAllCmd)
|
taskCmd.AddCommand(taskRunAllCmd)
|
||||||
taskRunAllCmd.Flags().StringP("queue", "q", "", "queue to which the tasks belong")
|
taskRunAllCmd.Flags().StringP("queue", "q", "", "queue to which the tasks belong (required)")
|
||||||
taskRunAllCmd.Flags().StringP("state", "s", "", "state of the tasks")
|
taskRunAllCmd.Flags().StringP("state", "s", "", "state of the tasks; one of { scheduled | retry | archived } (required)")
|
||||||
taskRunAllCmd.MarkFlagRequired("queue")
|
taskRunAllCmd.MarkFlagRequired("queue")
|
||||||
taskRunAllCmd.MarkFlagRequired("state")
|
taskRunAllCmd.MarkFlagRequired("state")
|
||||||
|
taskRunAllCmd.Flags().StringP("group", "g", "", "group to which the tasks belong (required for running aggregating tasks)")
|
||||||
}
|
}
|
||||||
|
|
||||||
var taskCmd = &cobra.Command{
|
var taskCmd = &cobra.Command{
|
||||||
Use: "task",
|
Use: "task <command> [flags]",
|
||||||
Short: "Manage tasks",
|
Short: "Manage tasks",
|
||||||
|
Example: heredoc.Doc(`
|
||||||
|
$ asynq task list --queue=myqueue --state=scheduled
|
||||||
|
$ asynq task inspect --queue=myqueue --id=7837f142-6337-4217-9276-8f27281b67d1
|
||||||
|
$ asynq task delete --queue=myqueue --id=7837f142-6337-4217-9276-8f27281b67d1
|
||||||
|
$ asynq task deleteall --queue=myqueue --state=archived`),
|
||||||
}
|
}
|
||||||
|
|
||||||
var taskListCmd = &cobra.Command{
|
var taskListCmd = &cobra.Command{
|
||||||
Use: "ls --queue=QUEUE --state=STATE",
|
Use: "list --queue=<queue> --state=<state> [flags]",
|
||||||
Short: "List tasks",
|
Aliases: []string{"ls"},
|
||||||
Long: `List tasks of the given state from the specified queue.
|
Short: "List tasks",
|
||||||
|
Long: heredoc.Doc(`
|
||||||
|
List tasks of the given state from the specified queue.
|
||||||
|
|
||||||
The value for the state flag should be one of:
|
The --queue and --state flags are required.
|
||||||
- active
|
|
||||||
- pending
|
|
||||||
- scheduled
|
|
||||||
- retry
|
|
||||||
- archived
|
|
||||||
|
|
||||||
List opeartion paginates the result set.
|
Note: For aggregating tasks, additional --group flag is required.
|
||||||
By default, the command fetches the first 30 tasks.
|
|
||||||
Use --page and --size flags to specify the page number and size.
|
|
||||||
|
|
||||||
Example:
|
List opeartion paginates the result set. By default, the command fetches the first 30 tasks.
|
||||||
To list pending tasks from "default" queue, run
|
Use --page and --size flags to specify the page number and size.`),
|
||||||
asynq task ls --queue=default --state=pending
|
Example: heredoc.Doc(`
|
||||||
|
$ asynq task list --queue=myqueue --state=pending
|
||||||
To list the tasks from the second page, run
|
$ asynq task list --queue=myqueue --state=aggregating --group=mygroup
|
||||||
asynq task ls --queue=default --state=pending --page=1`,
|
$ asynq task list --queue=myqueue --state=scheduled --page=2`),
|
||||||
Run: taskList,
|
Run: taskList,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var taskInspectCmd = &cobra.Command{
|
||||||
|
Use: "inspect --queue=<queue> --id=<task_id>",
|
||||||
|
Short: "Display detailed information on the specified task",
|
||||||
|
Args: cobra.NoArgs,
|
||||||
|
Run: taskInspect,
|
||||||
|
Example: heredoc.Doc(`
|
||||||
|
$ asynq task inspect --queue=myqueue --id=f1720682-f5a6-4db1-8953-4f48ae541d0f`),
|
||||||
|
}
|
||||||
|
|
||||||
var taskCancelCmd = &cobra.Command{
|
var taskCancelCmd = &cobra.Command{
|
||||||
Use: "cancel TASK_ID [TASK_ID...]",
|
Use: "cancel <task_id> [<task_id>...]",
|
||||||
Short: "Cancel one or more active tasks",
|
Short: "Cancel one or more active tasks",
|
||||||
Args: cobra.MinimumNArgs(1),
|
Args: cobra.MinimumNArgs(1),
|
||||||
Run: taskCancel,
|
Run: taskCancel,
|
||||||
|
Example: heredoc.Doc(`
|
||||||
|
$ asynq task cancel f1720682-f5a6-4db1-8953-4f48ae541d0f`),
|
||||||
}
|
}
|
||||||
|
|
||||||
var taskArchiveCmd = &cobra.Command{
|
var taskArchiveCmd = &cobra.Command{
|
||||||
Use: "archive --queue=QUEUE --key=KEY",
|
Use: "archive --queue=<queue> --id=<task_id>",
|
||||||
Short: "Archive a task with the given key",
|
Short: "Archive a task with the given id",
|
||||||
Args: cobra.NoArgs,
|
Args: cobra.NoArgs,
|
||||||
Run: taskArchive,
|
Run: taskArchive,
|
||||||
|
Example: heredoc.Doc(`
|
||||||
|
$ asynq task archive --queue=myqueue --id=f1720682-f5a6-4db1-8953-4f48ae541d0f`),
|
||||||
}
|
}
|
||||||
|
|
||||||
var taskDeleteCmd = &cobra.Command{
|
var taskDeleteCmd = &cobra.Command{
|
||||||
Use: "delete --queue=QUEUE --key=KEY",
|
Use: "delete --queue=<queue> --id=<task_id>",
|
||||||
Short: "Delete a task with the given key",
|
Aliases: []string{"remove", "rm"},
|
||||||
Args: cobra.NoArgs,
|
Short: "Delete a task with the given id",
|
||||||
Run: taskDelete,
|
Args: cobra.NoArgs,
|
||||||
|
Run: taskDelete,
|
||||||
|
Example: heredoc.Doc(`
|
||||||
|
$ asynq task delete --queue=myqueue --id=f1720682-f5a6-4db1-8953-4f48ae541d0f`),
|
||||||
}
|
}
|
||||||
|
|
||||||
var taskRunCmd = &cobra.Command{
|
var taskRunCmd = &cobra.Command{
|
||||||
Use: "run --queue=QUEUE --key=KEY",
|
Use: "run --queue=<queue> --id=<task_id>",
|
||||||
Short: "Run a task with the given key",
|
Short: "Run a task with the given id",
|
||||||
Args: cobra.NoArgs,
|
Args: cobra.NoArgs,
|
||||||
Run: taskRun,
|
Run: taskRun,
|
||||||
|
Example: heredoc.Doc(`
|
||||||
|
$ asynq task run --queue=myqueue --id=f1720682-f5a6-4db1-8953-4f48ae541d0f`),
|
||||||
}
|
}
|
||||||
|
|
||||||
var taskArchiveAllCmd = &cobra.Command{
|
var taskArchiveAllCmd = &cobra.Command{
|
||||||
Use: "archive-all --queue=QUEUE --state=STATE",
|
Use: "archiveall --queue=<queue> --state=<state>",
|
||||||
Short: "Archive all tasks in the given state",
|
Short: "Archive all tasks in the given state",
|
||||||
Args: cobra.NoArgs,
|
Args: cobra.NoArgs,
|
||||||
Run: taskArchiveAll,
|
Run: taskArchiveAll,
|
||||||
|
Example: heredoc.Doc(`
|
||||||
|
$ asynq task archiveall --queue=myqueue --state=retry
|
||||||
|
$ asynq task archiveall --queue=myqueue --state=aggregating --group=mygroup`),
|
||||||
}
|
}
|
||||||
|
|
||||||
var taskDeleteAllCmd = &cobra.Command{
|
var taskDeleteAllCmd = &cobra.Command{
|
||||||
Use: "delete-all --queue=QUEUE --key=KEY",
|
Use: "deleteall --queue=<queue> --state=<state>",
|
||||||
Short: "Delete all tasks in the given state",
|
Short: "Delete all tasks in the given state",
|
||||||
Args: cobra.NoArgs,
|
Args: cobra.NoArgs,
|
||||||
Run: taskDeleteAll,
|
Run: taskDeleteAll,
|
||||||
|
Example: heredoc.Doc(`
|
||||||
|
$ asynq task deleteall --queue=myqueue --state=archived
|
||||||
|
$ asynq task deleteall --queue=myqueue --state=aggregating --group=mygroup`),
|
||||||
}
|
}
|
||||||
|
|
||||||
var taskRunAllCmd = &cobra.Command{
|
var taskRunAllCmd = &cobra.Command{
|
||||||
Use: "run-all --queue=QUEUE --key=KEY",
|
Use: "runall --queue=<queue> --state=<state>",
|
||||||
Short: "Run all tasks in the given state",
|
Short: "Run all tasks in the given state",
|
||||||
Args: cobra.NoArgs,
|
Args: cobra.NoArgs,
|
||||||
Run: taskRunAll,
|
Run: taskRunAll,
|
||||||
|
Example: heredoc.Doc(`
|
||||||
|
$ asynq task runall --queue=myqueue --state=retry
|
||||||
|
$ asynq task runall --queue=myqueue --state=aggregating --group=mygroup`),
|
||||||
}
|
}
|
||||||
|
|
||||||
func taskList(cmd *cobra.Command, args []string) {
|
func taskList(cmd *cobra.Command, args []string) {
|
||||||
@@ -175,6 +214,19 @@ func taskList(cmd *cobra.Command, args []string) {
|
|||||||
listRetryTasks(qname, pageNum, pageSize)
|
listRetryTasks(qname, pageNum, pageSize)
|
||||||
case "archived":
|
case "archived":
|
||||||
listArchivedTasks(qname, pageNum, pageSize)
|
listArchivedTasks(qname, pageNum, pageSize)
|
||||||
|
case "completed":
|
||||||
|
listCompletedTasks(qname, pageNum, pageSize)
|
||||||
|
case "aggregating":
|
||||||
|
group, err := cmd.Flags().GetString("group")
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
if group == "" {
|
||||||
|
fmt.Println("Flag --group is required for listing aggregating tasks")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
listAggregatingTasks(qname, group, pageNum, pageSize)
|
||||||
default:
|
default:
|
||||||
fmt.Printf("error: state=%q is not supported\n", state)
|
fmt.Printf("error: state=%q is not supported\n", state)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
@@ -183,7 +235,7 @@ func taskList(cmd *cobra.Command, args []string) {
|
|||||||
|
|
||||||
func listActiveTasks(qname string, pageNum, pageSize int) {
|
func listActiveTasks(qname string, pageNum, pageSize int) {
|
||||||
i := createInspector()
|
i := createInspector()
|
||||||
tasks, err := i.ListActiveTasks(qname, inspeq.PageSize(pageSize), inspeq.Page(pageNum))
|
tasks, err := i.ListActiveTasks(qname, asynq.PageSize(pageSize), asynq.Page(pageNum))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
@@ -196,7 +248,7 @@ func listActiveTasks(qname string, pageNum, pageSize int) {
|
|||||||
[]string{"ID", "Type", "Payload"},
|
[]string{"ID", "Type", "Payload"},
|
||||||
func(w io.Writer, tmpl string) {
|
func(w io.Writer, tmpl string) {
|
||||||
for _, t := range tasks {
|
for _, t := range tasks {
|
||||||
fmt.Fprintf(w, tmpl, t.ID, t.Type, t.Payload)
|
fmt.Fprintf(w, tmpl, t.ID, t.Type, sprintBytes(t.Payload))
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -204,7 +256,7 @@ func listActiveTasks(qname string, pageNum, pageSize int) {
|
|||||||
|
|
||||||
func listPendingTasks(qname string, pageNum, pageSize int) {
|
func listPendingTasks(qname string, pageNum, pageSize int) {
|
||||||
i := createInspector()
|
i := createInspector()
|
||||||
tasks, err := i.ListPendingTasks(qname, inspeq.PageSize(pageSize), inspeq.Page(pageNum))
|
tasks, err := i.ListPendingTasks(qname, asynq.PageSize(pageSize), asynq.Page(pageNum))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
@@ -214,10 +266,10 @@ func listPendingTasks(qname string, pageNum, pageSize int) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
printTable(
|
printTable(
|
||||||
[]string{"Key", "Type", "Payload"},
|
[]string{"ID", "Type", "Payload"},
|
||||||
func(w io.Writer, tmpl string) {
|
func(w io.Writer, tmpl string) {
|
||||||
for _, t := range tasks {
|
for _, t := range tasks {
|
||||||
fmt.Fprintf(w, tmpl, t.Key(), t.Type, t.Payload)
|
fmt.Fprintf(w, tmpl, t.ID, t.Type, sprintBytes(t.Payload))
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -225,7 +277,7 @@ func listPendingTasks(qname string, pageNum, pageSize int) {
|
|||||||
|
|
||||||
func listScheduledTasks(qname string, pageNum, pageSize int) {
|
func listScheduledTasks(qname string, pageNum, pageSize int) {
|
||||||
i := createInspector()
|
i := createInspector()
|
||||||
tasks, err := i.ListScheduledTasks(qname, inspeq.PageSize(pageSize), inspeq.Page(pageNum))
|
tasks, err := i.ListScheduledTasks(qname, asynq.PageSize(pageSize), asynq.Page(pageNum))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
@@ -235,20 +287,29 @@ func listScheduledTasks(qname string, pageNum, pageSize int) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
printTable(
|
printTable(
|
||||||
[]string{"Key", "Type", "Payload", "Process In"},
|
[]string{"ID", "Type", "Payload", "Process In"},
|
||||||
func(w io.Writer, tmpl string) {
|
func(w io.Writer, tmpl string) {
|
||||||
for _, t := range tasks {
|
for _, t := range tasks {
|
||||||
processIn := fmt.Sprintf("%.0f seconds",
|
fmt.Fprintf(w, tmpl, t.ID, t.Type, sprintBytes(t.Payload), formatProcessAt(t.NextProcessAt))
|
||||||
t.NextProcessAt.Sub(time.Now()).Seconds())
|
|
||||||
fmt.Fprintf(w, tmpl, t.Key(), t.Type, t.Payload, processIn)
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// formatProcessAt formats next process at time to human friendly string.
|
||||||
|
// If processAt time is in the past, returns "right now".
|
||||||
|
// If processAt time is in the future, returns "in xxx" where xxx is the duration from now.
|
||||||
|
func formatProcessAt(processAt time.Time) string {
|
||||||
|
d := processAt.Sub(time.Now())
|
||||||
|
if d < 0 {
|
||||||
|
return "right now"
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("in %v", d.Round(time.Second))
|
||||||
|
}
|
||||||
|
|
||||||
func listRetryTasks(qname string, pageNum, pageSize int) {
|
func listRetryTasks(qname string, pageNum, pageSize int) {
|
||||||
i := createInspector()
|
i := createInspector()
|
||||||
tasks, err := i.ListRetryTasks(qname, inspeq.PageSize(pageSize), inspeq.Page(pageNum))
|
tasks, err := i.ListRetryTasks(qname, asynq.PageSize(pageSize), asynq.Page(pageNum))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
@@ -258,16 +319,11 @@ func listRetryTasks(qname string, pageNum, pageSize int) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
printTable(
|
printTable(
|
||||||
[]string{"Key", "Type", "Payload", "Next Retry", "Last Error", "Retried", "Max Retry"},
|
[]string{"ID", "Type", "Payload", "Next Retry", "Last Error", "Last Failed", "Retried", "Max Retry"},
|
||||||
func(w io.Writer, tmpl string) {
|
func(w io.Writer, tmpl string) {
|
||||||
for _, t := range tasks {
|
for _, t := range tasks {
|
||||||
var nextRetry string
|
fmt.Fprintf(w, tmpl, t.ID, t.Type, sprintBytes(t.Payload), formatProcessAt(t.NextProcessAt),
|
||||||
if d := t.NextProcessAt.Sub(time.Now()); d > 0 {
|
t.LastErr, formatPastTime(t.LastFailedAt), t.Retried, t.MaxRetry)
|
||||||
nextRetry = fmt.Sprintf("in %v", d.Round(time.Second))
|
|
||||||
} else {
|
|
||||||
nextRetry = "right now"
|
|
||||||
}
|
|
||||||
fmt.Fprintf(w, tmpl, t.Key(), t.Type, t.Payload, nextRetry, t.LastError, t.Retried, t.MaxRetry)
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -275,7 +331,7 @@ func listRetryTasks(qname string, pageNum, pageSize int) {
|
|||||||
|
|
||||||
func listArchivedTasks(qname string, pageNum, pageSize int) {
|
func listArchivedTasks(qname string, pageNum, pageSize int) {
|
||||||
i := createInspector()
|
i := createInspector()
|
||||||
tasks, err := i.ListArchivedTasks(qname, inspeq.PageSize(pageSize), inspeq.Page(pageNum))
|
tasks, err := i.ListArchivedTasks(qname, asynq.PageSize(pageSize), asynq.Page(pageNum))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
@@ -285,19 +341,59 @@ func listArchivedTasks(qname string, pageNum, pageSize int) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
printTable(
|
printTable(
|
||||||
[]string{"Key", "Type", "Payload", "Last Failed", "Last Error"},
|
[]string{"ID", "Type", "Payload", "Last Failed", "Last Error"},
|
||||||
func(w io.Writer, tmpl string) {
|
func(w io.Writer, tmpl string) {
|
||||||
for _, t := range tasks {
|
for _, t := range tasks {
|
||||||
fmt.Fprintf(w, tmpl, t.Key(), t.Type, t.Payload, t.LastFailedAt, t.LastError)
|
fmt.Fprintf(w, tmpl, t.ID, t.Type, sprintBytes(t.Payload), formatPastTime(t.LastFailedAt), t.LastErr)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func listCompletedTasks(qname string, pageNum, pageSize int) {
|
||||||
|
i := createInspector()
|
||||||
|
tasks, err := i.ListCompletedTasks(qname, asynq.PageSize(pageSize), asynq.Page(pageNum))
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
if len(tasks) == 0 {
|
||||||
|
fmt.Printf("No completed tasks in %q queue\n", qname)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
printTable(
|
||||||
|
[]string{"ID", "Type", "Payload", "CompletedAt", "Result"},
|
||||||
|
func(w io.Writer, tmpl string) {
|
||||||
|
for _, t := range tasks {
|
||||||
|
fmt.Fprintf(w, tmpl, t.ID, t.Type, sprintBytes(t.Payload), formatPastTime(t.CompletedAt), sprintBytes(t.Result))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func listAggregatingTasks(qname, group string, pageNum, pageSize int) {
|
||||||
|
i := createInspector()
|
||||||
|
tasks, err := i.ListAggregatingTasks(qname, group, asynq.PageSize(pageSize), asynq.Page(pageNum))
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
if len(tasks) == 0 {
|
||||||
|
fmt.Printf("No aggregating tasks in group %q \n", group)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
printTable(
|
||||||
|
[]string{"ID", "Type", "Payload", "Group"},
|
||||||
|
func(w io.Writer, tmpl string) {
|
||||||
|
for _, t := range tasks {
|
||||||
|
fmt.Fprintf(w, tmpl, t.ID, t.Type, sprintBytes(t.Payload), t.Group)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
func taskCancel(cmd *cobra.Command, args []string) {
|
func taskCancel(cmd *cobra.Command, args []string) {
|
||||||
r := createRDB()
|
i := createInspector()
|
||||||
for _, id := range args {
|
for _, id := range args {
|
||||||
err := r.PublishCancelation(id)
|
if err := i.CancelProcessing(id); err != nil {
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("error: could not send cancelation signal: %v\n", err)
|
fmt.Printf("error: could not send cancelation signal: %v\n", err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -305,20 +401,77 @@ func taskCancel(cmd *cobra.Command, args []string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func taskInspect(cmd *cobra.Command, args []string) {
|
||||||
|
qname, err := cmd.Flags().GetString("queue")
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
id, err := cmd.Flags().GetString("id")
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
i := createInspector()
|
||||||
|
info, err := i.GetTaskInfo(qname, id)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
printTaskInfo(info)
|
||||||
|
}
|
||||||
|
|
||||||
|
func printTaskInfo(info *asynq.TaskInfo) {
|
||||||
|
bold := color.New(color.Bold)
|
||||||
|
bold.Println("Task Info")
|
||||||
|
fmt.Printf("Queue: %s\n", info.Queue)
|
||||||
|
fmt.Printf("ID: %s\n", info.ID)
|
||||||
|
fmt.Printf("Type: %s\n", info.Type)
|
||||||
|
fmt.Printf("State: %v\n", info.State)
|
||||||
|
fmt.Printf("Retried: %d/%d\n", info.Retried, info.MaxRetry)
|
||||||
|
fmt.Println()
|
||||||
|
fmt.Printf("Next process time: %s\n", formatNextProcessAt(info.NextProcessAt))
|
||||||
|
if len(info.LastErr) != 0 {
|
||||||
|
fmt.Println()
|
||||||
|
bold.Println("Last Failure")
|
||||||
|
fmt.Printf("Failed at: %s\n", formatPastTime(info.LastFailedAt))
|
||||||
|
fmt.Printf("Error message: %s\n", info.LastErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func formatNextProcessAt(processAt time.Time) string {
|
||||||
|
if processAt.IsZero() || processAt.Unix() == 0 {
|
||||||
|
return "n/a"
|
||||||
|
}
|
||||||
|
if processAt.Before(time.Now()) {
|
||||||
|
return "now"
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%s (in %v)", processAt.Format(time.UnixDate), processAt.Sub(time.Now()).Round(time.Second))
|
||||||
|
}
|
||||||
|
|
||||||
|
// formatPastTime takes t which is time in the past and returns a user-friendly string.
|
||||||
|
func formatPastTime(t time.Time) string {
|
||||||
|
if t.IsZero() || t.Unix() == 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return t.Format(time.UnixDate)
|
||||||
|
}
|
||||||
|
|
||||||
func taskArchive(cmd *cobra.Command, args []string) {
|
func taskArchive(cmd *cobra.Command, args []string) {
|
||||||
qname, err := cmd.Flags().GetString("queue")
|
qname, err := cmd.Flags().GetString("queue")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("error: %v\n", err)
|
fmt.Printf("error: %v\n", err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
key, err := cmd.Flags().GetString("key")
|
id, err := cmd.Flags().GetString("id")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("error: %v\n", err)
|
fmt.Printf("error: %v\n", err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
i := createInspector()
|
i := createInspector()
|
||||||
err = i.ArchiveTaskByKey(qname, key)
|
err = i.ArchiveTask(qname, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("error: %v\n", err)
|
fmt.Printf("error: %v\n", err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
@@ -332,14 +485,14 @@ func taskDelete(cmd *cobra.Command, args []string) {
|
|||||||
fmt.Printf("error: %v\n", err)
|
fmt.Printf("error: %v\n", err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
key, err := cmd.Flags().GetString("key")
|
id, err := cmd.Flags().GetString("id")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("error: %v\n", err)
|
fmt.Printf("error: %v\n", err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
i := createInspector()
|
i := createInspector()
|
||||||
err = i.DeleteTaskByKey(qname, key)
|
err = i.DeleteTask(qname, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("error: %v\n", err)
|
fmt.Printf("error: %v\n", err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
@@ -353,14 +506,14 @@ func taskRun(cmd *cobra.Command, args []string) {
|
|||||||
fmt.Printf("error: %v\n", err)
|
fmt.Printf("error: %v\n", err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
key, err := cmd.Flags().GetString("key")
|
id, err := cmd.Flags().GetString("id")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("error: %v\n", err)
|
fmt.Printf("error: %v\n", err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
i := createInspector()
|
i := createInspector()
|
||||||
err = i.RunTaskByKey(qname, key)
|
err = i.RunTask(qname, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("error: %v\n", err)
|
fmt.Printf("error: %v\n", err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
@@ -389,6 +542,17 @@ func taskArchiveAll(cmd *cobra.Command, args []string) {
|
|||||||
n, err = i.ArchiveAllScheduledTasks(qname)
|
n, err = i.ArchiveAllScheduledTasks(qname)
|
||||||
case "retry":
|
case "retry":
|
||||||
n, err = i.ArchiveAllRetryTasks(qname)
|
n, err = i.ArchiveAllRetryTasks(qname)
|
||||||
|
case "aggregating":
|
||||||
|
group, err := cmd.Flags().GetString("group")
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
if group == "" {
|
||||||
|
fmt.Println("error: Flag --group is required for aggregating tasks")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
n, err = i.ArchiveAllAggregatingTasks(qname, group)
|
||||||
default:
|
default:
|
||||||
fmt.Printf("error: unsupported state %q\n", state)
|
fmt.Printf("error: unsupported state %q\n", state)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
@@ -423,6 +587,19 @@ func taskDeleteAll(cmd *cobra.Command, args []string) {
|
|||||||
n, err = i.DeleteAllRetryTasks(qname)
|
n, err = i.DeleteAllRetryTasks(qname)
|
||||||
case "archived":
|
case "archived":
|
||||||
n, err = i.DeleteAllArchivedTasks(qname)
|
n, err = i.DeleteAllArchivedTasks(qname)
|
||||||
|
case "completed":
|
||||||
|
n, err = i.DeleteAllCompletedTasks(qname)
|
||||||
|
case "aggregating":
|
||||||
|
group, err := cmd.Flags().GetString("group")
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
if group == "" {
|
||||||
|
fmt.Println("error: Flag --group is required for aggregating tasks")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
n, err = i.DeleteAllAggregatingTasks(qname, group)
|
||||||
default:
|
default:
|
||||||
fmt.Printf("error: unsupported state %q\n", state)
|
fmt.Printf("error: unsupported state %q\n", state)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
@@ -455,6 +632,17 @@ func taskRunAll(cmd *cobra.Command, args []string) {
|
|||||||
n, err = i.RunAllRetryTasks(qname)
|
n, err = i.RunAllRetryTasks(qname)
|
||||||
case "archived":
|
case "archived":
|
||||||
n, err = i.RunAllArchivedTasks(qname)
|
n, err = i.RunAllArchivedTasks(qname)
|
||||||
|
case "aggregating":
|
||||||
|
group, err := cmd.Flags().GetString("group")
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
if group == "" {
|
||||||
|
fmt.Println("error: Flag --group is required for aggregating tasks")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
n, err = i.RunAllAggregatingTasks(qname, group)
|
||||||
default:
|
default:
|
||||||
fmt.Printf("error: unsupported state %q\n", state)
|
fmt.Printf("error: unsupported state %q\n", state)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
|
|||||||
57
tools/go.mod
57
tools/go.mod
@@ -1,22 +1,55 @@
|
|||||||
module github.com/hibiken/asynq/tools
|
module github.com/hibiken/asynq/tools
|
||||||
|
|
||||||
go 1.13
|
go 1.20
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6 // indirect
|
github.com/MakeNowJust/heredoc/v2 v2.0.1
|
||||||
github.com/coreos/go-etcd v2.0.0+incompatible // indirect
|
|
||||||
github.com/cpuguy83/go-md2man v1.0.10 // indirect
|
|
||||||
github.com/fatih/color v1.9.0
|
github.com/fatih/color v1.9.0
|
||||||
github.com/go-redis/redis/v7 v7.4.0
|
github.com/gdamore/tcell/v2 v2.5.1
|
||||||
github.com/google/uuid v1.1.1
|
github.com/google/go-cmp v0.5.9
|
||||||
github.com/hibiken/asynq v0.14.0
|
github.com/hibiken/asynq v0.24.1
|
||||||
|
github.com/hibiken/asynq/x v0.0.0-20220131170841-349f4c50fb1d
|
||||||
|
github.com/mattn/go-runewidth v0.0.13
|
||||||
github.com/mitchellh/go-homedir v1.1.0
|
github.com/mitchellh/go-homedir v1.1.0
|
||||||
github.com/spf13/cast v1.3.1
|
github.com/prometheus/client_golang v1.11.1
|
||||||
|
github.com/redis/go-redis/v9 v9.0.5
|
||||||
github.com/spf13/cobra v1.1.1
|
github.com/spf13/cobra v1.1.1
|
||||||
|
github.com/spf13/pflag v1.0.5
|
||||||
github.com/spf13/viper v1.7.0
|
github.com/spf13/viper v1.7.0
|
||||||
github.com/ugorji/go v1.1.4 // indirect
|
golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136
|
||||||
github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8 // indirect
|
|
||||||
github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77 // indirect
|
|
||||||
)
|
)
|
||||||
|
|
||||||
replace github.com/hibiken/asynq => ./..
|
require (
|
||||||
|
github.com/beorn7/perks v1.0.1 // indirect
|
||||||
|
github.com/cespare/xxhash/v2 v2.2.0 // indirect
|
||||||
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||||
|
github.com/fsnotify/fsnotify v1.4.9 // indirect
|
||||||
|
github.com/gdamore/encoding v1.0.0 // indirect
|
||||||
|
github.com/golang/protobuf v1.5.3 // indirect
|
||||||
|
github.com/google/uuid v1.3.0 // indirect
|
||||||
|
github.com/hashicorp/hcl v1.0.0 // indirect
|
||||||
|
github.com/inconshreveable/mousetrap v1.0.0 // indirect
|
||||||
|
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
|
||||||
|
github.com/magiconair/properties v1.8.1 // indirect
|
||||||
|
github.com/mattn/go-colorable v0.1.4 // indirect
|
||||||
|
github.com/mattn/go-isatty v0.0.11 // indirect
|
||||||
|
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
|
||||||
|
github.com/mitchellh/mapstructure v1.1.2 // indirect
|
||||||
|
github.com/pelletier/go-toml v1.2.0 // indirect
|
||||||
|
github.com/prometheus/client_model v0.2.0 // indirect
|
||||||
|
github.com/prometheus/common v0.26.0 // indirect
|
||||||
|
github.com/prometheus/procfs v0.6.0 // indirect
|
||||||
|
github.com/rivo/uniseg v0.2.0 // indirect
|
||||||
|
github.com/robfig/cron/v3 v3.0.1 // indirect
|
||||||
|
github.com/spf13/afero v1.1.2 // indirect
|
||||||
|
github.com/spf13/cast v1.5.1 // indirect
|
||||||
|
github.com/spf13/jwalterweatherman v1.0.0 // indirect
|
||||||
|
github.com/subosito/gotenv v1.2.0 // indirect
|
||||||
|
golang.org/x/sys v0.10.0 // indirect
|
||||||
|
golang.org/x/term v0.0.0-20201210144234-2321bbc49cbf // indirect
|
||||||
|
golang.org/x/text v0.3.8 // indirect
|
||||||
|
golang.org/x/time v0.3.0 // indirect
|
||||||
|
google.golang.org/protobuf v1.31.0 // indirect
|
||||||
|
gopkg.in/ini.v1 v1.51.0 // indirect
|
||||||
|
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||||
|
)
|
||||||
|
|||||||
251
tools/go.sum
251
tools/go.sum
@@ -14,49 +14,72 @@ dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7
|
|||||||
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
|
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
|
||||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||||
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
||||||
|
github.com/MakeNowJust/heredoc/v2 v2.0.1 h1:rlCHh70XXXv7toz95ajQWOWQnN4WNLt0TdpZYIR/J6A=
|
||||||
|
github.com/MakeNowJust/heredoc/v2 v2.0.1/go.mod h1:6/2Abh5s+hc3g9nbWLe9ObDIOhaRrqsyY9MWy+4JdRM=
|
||||||
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
|
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
|
||||||
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
|
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
|
||||||
|
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
|
||||||
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
|
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
|
||||||
|
github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
|
||||||
|
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho=
|
||||||
github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o=
|
github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o=
|
||||||
github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8=
|
|
||||||
github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY=
|
github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY=
|
||||||
github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
|
github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
|
||||||
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
|
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
|
||||||
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
|
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
|
||||||
|
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||||
|
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||||
github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=
|
github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=
|
||||||
github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84=
|
github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84=
|
||||||
|
github.com/bsm/ginkgo/v2 v2.7.0 h1:ItPMPH90RbmZJt5GtkcNvIRuGEdwlBItdNVoyzaNQao=
|
||||||
|
github.com/bsm/ginkgo/v2 v2.7.0/go.mod h1:AiKlXPm7ItEHNc/2+OkrNG4E0ITzojb9/xWzvQ9XZ9w=
|
||||||
|
github.com/bsm/gomega v1.26.0 h1:LhQm+AFcgV2M0WyKroMASzAzCAJVpAxQXv4SaI9a69Y=
|
||||||
|
github.com/bsm/gomega v1.26.0/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||||
|
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
|
||||||
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
|
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
|
||||||
|
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
|
github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
|
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
|
||||||
|
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
|
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
|
||||||
github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk=
|
github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk=
|
||||||
github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
|
|
||||||
github.com/coreos/etcd v3.3.13+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
|
github.com/coreos/etcd v3.3.13+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
|
||||||
github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk=
|
|
||||||
github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
|
|
||||||
github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
|
github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
|
||||||
github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
|
github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
|
||||||
github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA=
|
github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA=
|
||||||
github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE=
|
|
||||||
github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
|
github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
|
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
|
||||||
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||||
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||||
github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
|
github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
|
||||||
|
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||||
|
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
||||||
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
|
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
|
||||||
github.com/fatih/color v1.9.0 h1:8xPHl4/q1VyqGIPif1F+1V3Y3lSmrq01EabUW3CoW5s=
|
github.com/fatih/color v1.9.0 h1:8xPHl4/q1VyqGIPif1F+1V3Y3lSmrq01EabUW3CoW5s=
|
||||||
github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU=
|
github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU=
|
||||||
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
|
github.com/frankban/quicktest v1.14.4 h1:g2rn0vABPOOXmZUj+vbmUp0lPoXEMuhTpIluN0XL9UY=
|
||||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||||
|
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
|
||||||
|
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
|
||||||
|
github.com/gdamore/encoding v1.0.0 h1:+7OoQ1Bc6eTm5niUzBa0Ctsh6JbMW6Ra+YNuAtDBdko=
|
||||||
|
github.com/gdamore/encoding v1.0.0/go.mod h1:alR0ol34c49FCSBLjhosxzcPHQbf2trDkoo5dl+VrEg=
|
||||||
|
github.com/gdamore/tcell/v2 v2.5.1 h1:zc3LPdpK184lBW7syF2a5C6MV827KmErk9jGVnmsl/I=
|
||||||
|
github.com/gdamore/tcell/v2 v2.5.1/go.mod h1:wSkrPaXoiIWZqW/g7Px4xc79di6FTcpB8tvaKJ6uGBo=
|
||||||
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
|
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
|
||||||
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
|
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
|
||||||
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
|
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
|
||||||
|
github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
|
||||||
|
github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY=
|
||||||
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
|
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
|
||||||
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
|
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
|
||||||
github.com/go-redis/redis/v7 v7.2.0 h1:CrCexy/jYWZjW0AyVoHlcJUeZN19VWlbepTh1Vq6dJs=
|
github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A=
|
||||||
github.com/go-redis/redis/v7 v7.2.0/go.mod h1:JDNMw23GTyLNC4GZu9njt15ctBQVn7xjRfnwdHj/Dcg=
|
github.com/go-redis/redis/v8 v8.11.2/go.mod h1:DLomh7y2e3ggQXQLd1YgmvIfecPJoFl7WU5SOQ/r06M=
|
||||||
github.com/go-redis/redis/v7 v7.4.0 h1:7obg6wUoj05T0EpY0o8B59S9w5yeMWql7sw2kwNW1x4=
|
github.com/go-redis/redis/v8 v8.11.4/go.mod h1:2Z2wHZXdQpCDXEGzqMockDpNyYvi2l4Pxt6RJr792+w=
|
||||||
github.com/go-redis/redis/v7 v7.4.0/go.mod h1:JDNMw23GTyLNC4GZu9njt15ctBQVn7xjRfnwdHj/Dcg=
|
|
||||||
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
|
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
|
||||||
|
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE=
|
||||||
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
|
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
|
||||||
github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4=
|
github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4=
|
||||||
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
||||||
@@ -66,25 +89,43 @@ github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfb
|
|||||||
github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y=
|
github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y=
|
||||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||||
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||||
github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs=
|
|
||||||
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||||
|
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
|
||||||
|
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
|
||||||
|
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
|
||||||
|
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
|
||||||
|
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
|
||||||
|
github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8=
|
||||||
|
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||||
|
github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||||
|
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||||
|
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||||
|
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
|
||||||
|
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||||
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
|
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
|
||||||
github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
|
github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
|
||||||
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
|
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
|
||||||
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||||
github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4=
|
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||||
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
|
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
|
github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
|
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
|
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
|
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
|
||||||
|
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||||
|
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||||
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
|
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
|
||||||
github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
|
github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
|
||||||
github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
|
github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
|
||||||
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
|
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
|
||||||
github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY=
|
github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
|
||||||
|
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
|
github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
|
||||||
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
|
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
|
||||||
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8=
|
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8=
|
||||||
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
|
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
|
||||||
github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
|
|
||||||
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||||
github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
|
github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
|
||||||
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk=
|
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk=
|
||||||
@@ -110,26 +151,36 @@ github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO
|
|||||||
github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ=
|
github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ=
|
||||||
github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I=
|
github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I=
|
||||||
github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc=
|
github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc=
|
||||||
github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
|
github.com/hibiken/asynq v0.19.0/go.mod h1:tyc63ojaW8SJ5SBm8mvI4DDONsguP5HE85EEl4Qr5Ig=
|
||||||
|
github.com/hibiken/asynq v0.24.1 h1:+5iIEAyA9K/lcSPvx3qoPtsKJeKI5u9aOIvUmSsazEw=
|
||||||
|
github.com/hibiken/asynq v0.24.1/go.mod h1:u5qVeSbrnfT+vtG5Mq8ZPzQu/BmCKMHvTGb91uy9Tts=
|
||||||
|
github.com/hibiken/asynq/x v0.0.0-20220131170841-349f4c50fb1d h1:Er+U+9PmnyRHRDQjSjRQ24HoWvOY7w9Pk7bUPYM3Ags=
|
||||||
|
github.com/hibiken/asynq/x v0.0.0-20220131170841-349f4c50fb1d/go.mod h1:VmxwMfMKyb6gyv8xG0oOBMXIhquWKPx+zPtbVBd2Q1s=
|
||||||
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
||||||
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
|
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
|
||||||
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
|
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
|
||||||
github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
|
github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
|
||||||
|
github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4=
|
||||||
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
|
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
|
||||||
|
github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
||||||
|
github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
||||||
github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
|
github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
|
||||||
github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=
|
github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=
|
||||||
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
|
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
|
||||||
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
|
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
|
||||||
|
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
|
||||||
github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q=
|
github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q=
|
||||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||||
|
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||||
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
|
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
|
||||||
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
|
|
||||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||||
|
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||||
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
|
|
||||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||||
github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
|
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||||
|
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
|
||||||
|
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||||
github.com/magiconair/properties v1.8.1 h1:ZC2Vc7/ZFkGmsVC9KvOjumD+G5lXy2RtTKyzRKO2BQ4=
|
github.com/magiconair/properties v1.8.1 h1:ZC2Vc7/ZFkGmsVC9KvOjumD+G5lXy2RtTKyzRKO2BQ4=
|
||||||
github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
|
github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
|
||||||
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
|
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
|
||||||
@@ -139,6 +190,9 @@ github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNx
|
|||||||
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
|
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
|
||||||
github.com/mattn/go-isatty v0.0.11 h1:FxPOTFNqGkuDUGi3H/qkUbQO4ZiBa2brKq5r0l8TGeM=
|
github.com/mattn/go-isatty v0.0.11 h1:FxPOTFNqGkuDUGi3H/qkUbQO4ZiBa2brKq5r0l8TGeM=
|
||||||
github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE=
|
github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE=
|
||||||
|
github.com/mattn/go-runewidth v0.0.13 h1:lTGmDsbAYt5DmK6OnoV7EuIF1wEIFAcxld6ypU4OSgU=
|
||||||
|
github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||||
|
github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU=
|
||||||
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
|
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
|
||||||
github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
|
github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
|
||||||
github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc=
|
github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc=
|
||||||
@@ -151,42 +205,74 @@ github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0Qu
|
|||||||
github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
|
github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
|
||||||
github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
|
github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
|
||||||
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
|
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
|
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
|
||||||
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
|
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
|
||||||
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
|
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
|
||||||
|
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
|
||||||
|
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
|
||||||
|
github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
|
||||||
github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
|
github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
|
||||||
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||||
github.com/onsi/ginkgo v1.10.1 h1:q/mM8GF/n0shIN8SaAZ0V+jnLPzen6WIVZdiwrRlMlo=
|
github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=
|
||||||
github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
github.com/onsi/ginkgo v1.15.0/go.mod h1:hF8qUzuuC8DJGygJH3726JnCZX4MYbRB8yFfISqnKUg=
|
||||||
github.com/onsi/gomega v1.7.0 h1:XPnZz8VVBHjVsy1vzJmRwIcSwiUO+JFfrv/xGiigmME=
|
github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0=
|
||||||
github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
|
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
|
||||||
|
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
|
||||||
|
github.com/onsi/gomega v1.10.5/go.mod h1:gza4q3jKQJijlu05nKWRCW/GavJumGt8aNRxWg7mt48=
|
||||||
|
github.com/onsi/gomega v1.16.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY=
|
||||||
github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
|
github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
|
||||||
github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc=
|
github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc=
|
||||||
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
|
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
|
||||||
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
|
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI=
|
github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI=
|
||||||
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
|
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
|
||||||
github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso=
|
github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso=
|
||||||
|
github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo=
|
||||||
|
github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M=
|
||||||
|
github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0=
|
||||||
|
github.com/prometheus/client_golang v1.11.1 h1:+4eQaD7vAZ6DsfsxB15hbE0odUjGI5ARs9yskGu1v4s=
|
||||||
|
github.com/prometheus/client_golang v1.11.1/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0=
|
||||||
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
|
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
|
||||||
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||||
|
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||||
|
github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M=
|
||||||
|
github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||||
github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro=
|
github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro=
|
||||||
github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
|
github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
|
||||||
|
github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
|
||||||
|
github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo=
|
||||||
|
github.com/prometheus/common v0.26.0 h1:iMAkS2TDoNWnKM+Kopnx/8tnEStIfpYA0ur0xQzzhMQ=
|
||||||
|
github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc=
|
||||||
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
|
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
|
||||||
github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
|
github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
|
||||||
|
github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
|
||||||
|
github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU=
|
||||||
|
github.com/prometheus/procfs v0.6.0 h1:mxy4L2jP6qMonqmq+aTtOx1ifVWUgG/TAmntgbh3xv4=
|
||||||
|
github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
|
||||||
github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU=
|
github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU=
|
||||||
|
github.com/redis/go-redis/v9 v9.0.3/go.mod h1:WqMKv5vnQbRuZstUwxQI195wHy+t4PuXDOjzMvcuQHk=
|
||||||
|
github.com/redis/go-redis/v9 v9.0.5 h1:CuQcn5HIEeK7BgElubPP8CGtE0KakrnbBSTLjathl5o=
|
||||||
|
github.com/redis/go-redis/v9 v9.0.5/go.mod h1:WqMKv5vnQbRuZstUwxQI195wHy+t4PuXDOjzMvcuQHk=
|
||||||
|
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
|
||||||
|
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||||
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
||||||
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
||||||
github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=
|
github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=
|
||||||
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
||||||
github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
|
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
|
||||||
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||||
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
|
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
|
||||||
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
|
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
|
||||||
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
|
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
|
||||||
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
|
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
|
||||||
|
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
|
||||||
|
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
|
||||||
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM=
|
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM=
|
||||||
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
|
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
|
||||||
github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s=
|
github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s=
|
||||||
@@ -196,55 +282,54 @@ github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasO
|
|||||||
github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI=
|
github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI=
|
||||||
github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
|
github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
|
||||||
github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
|
github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
|
||||||
github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng=
|
|
||||||
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
|
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
|
||||||
github.com/spf13/cobra v0.0.5 h1:f0B+LkLX6DtmRH1isoNA9VTtNUK9K8xYd28JNNfOv/s=
|
github.com/spf13/cast v1.5.1 h1:R+kOtfhWQE6TVQzY+4D7wJLBgkdVasCEFxSUBYBYIlA=
|
||||||
github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU=
|
github.com/spf13/cast v1.5.1/go.mod h1:b9PdjNptOpzXr7Rq1q9gJML/2cdGQAo69NKzQ10KN48=
|
||||||
github.com/spf13/cobra v1.0.0 h1:6m/oheQuQ13N9ks4hubMG6BnvwOeaJrqSPLahSnczz8=
|
|
||||||
github.com/spf13/cobra v1.0.0/go.mod h1:/6GTrnGXV9HjY+aR4k0oJ5tcvakLuG6EuKReYlHNrgE=
|
|
||||||
github.com/spf13/cobra v1.1.1 h1:KfztREH0tPxJJ+geloSLaAkaPkr4ki2Er5quFV1TDo4=
|
github.com/spf13/cobra v1.1.1 h1:KfztREH0tPxJJ+geloSLaAkaPkr4ki2Er5quFV1TDo4=
|
||||||
github.com/spf13/cobra v1.1.1/go.mod h1:WnodtKOvamDL/PwE2M4iKs8aMDBZ5Q5klgD3qfVJQMI=
|
github.com/spf13/cobra v1.1.1/go.mod h1:WnodtKOvamDL/PwE2M4iKs8aMDBZ5Q5klgD3qfVJQMI=
|
||||||
github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk=
|
github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk=
|
||||||
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
|
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
|
||||||
github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg=
|
|
||||||
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
|
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
|
||||||
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
||||||
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||||
github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s=
|
|
||||||
github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE=
|
|
||||||
github.com/spf13/viper v1.6.2 h1:7aKfF+e8/k68gda3LOjo5RxiUqddoFxVq4BKBPrxk5E=
|
|
||||||
github.com/spf13/viper v1.6.2/go.mod h1:t3iDnF5Jlj76alVNuyFBk5oUMCvsrkbvZK0WQdfDi5k=
|
|
||||||
github.com/spf13/viper v1.7.0 h1:xVKxvI7ouOI5I+U9s2eeiUfMaWBVoXA3AWskkrqK0VM=
|
github.com/spf13/viper v1.7.0 h1:xVKxvI7ouOI5I+U9s2eeiUfMaWBVoXA3AWskkrqK0VM=
|
||||||
github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg=
|
github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg=
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
|
|
||||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
|
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||||
|
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
||||||
|
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||||
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s=
|
github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s=
|
||||||
github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
|
github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
|
||||||
github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
|
github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
|
||||||
github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc=
|
|
||||||
github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0=
|
|
||||||
github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU=
|
github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU=
|
||||||
github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q=
|
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||||
|
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
|
||||||
go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
|
go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
|
||||||
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
|
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
|
||||||
go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
|
go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
|
||||||
go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
|
go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
|
||||||
go.uber.org/goleak v0.10.0/go.mod h1:VCZuO8V8mFPlL0F5J5GK1rtHV3DrFcQ1R8ryq7FK0aI=
|
go.uber.org/goleak v0.10.0/go.mod h1:VCZuO8V8mFPlL0F5J5GK1rtHV3DrFcQ1R8ryq7FK0aI=
|
||||||
|
go.uber.org/goleak v1.1.12 h1:gZAh5/EyT/HQwlpkCy6wTpqfH9H8Lz8zbm3dZh+OyzA=
|
||||||
|
go.uber.org/goleak v1.1.12/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ=
|
||||||
go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
|
go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
|
||||||
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
|
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
|
||||||
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||||
golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||||
golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
|
||||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||||
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||||
|
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||||
|
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||||
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||||
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
|
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
|
||||||
golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek=
|
golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek=
|
||||||
|
golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136 h1:A1gGSx58LAGVHUUsOf7IiR0u8Xb6W51gRwfDBhkdcaw=
|
||||||
golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY=
|
golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY=
|
||||||
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
|
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
|
||||||
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
||||||
@@ -259,6 +344,8 @@ golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU
|
|||||||
golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o=
|
golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o=
|
||||||
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
|
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
|
||||||
golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY=
|
golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY=
|
||||||
|
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||||
|
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||||
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
@@ -272,11 +359,15 @@ golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn
|
|||||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||||
golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||||
golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||||
golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
|
|
||||||
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
|
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
|
||||||
|
golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
golang.org/x/net v0.0.0-20190923162816-aa69164e4478 h1:l5EDrHhldLYb3ZRHDUhXF7Om7MvYXnkV9/iQNo1lX6g=
|
golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
|
||||||
golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
|
||||||
|
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||||
|
golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||||
|
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
|
||||||
|
golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk=
|
||||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||||
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||||
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||||
@@ -285,6 +376,10 @@ golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJ
|
|||||||
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
@@ -292,26 +387,50 @@ golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5h
|
|||||||
golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
|
||||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20191010194322-b09406accb47/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e h1:9vRrk9YW2BTzLP0VCB9ZDjU4cPqkg+IDWL7XgxA1yxQ=
|
golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20220318055525-2edf467146b5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA=
|
||||||
|
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
|
golang.org/x/term v0.0.0-20201210144234-2321bbc49cbf h1:MZ2shdL+ZM/XzY3ZGOnh4Nlpnxz5GSOhOmtHo3iPU6M=
|
||||||
|
golang.org/x/term v0.0.0-20201210144234-2321bbc49cbf/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||||
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||||
golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
|
|
||||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||||
|
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||||
|
golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY=
|
||||||
|
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
|
||||||
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||||
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4 h1:SvFZT6jyqRaOeXpc5h/JSfZenJ2O330aBsf7JfSUXmQ=
|
|
||||||
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||||
|
golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4=
|
||||||
|
golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||||
golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
@@ -322,6 +441,7 @@ golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3
|
|||||||
golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||||
golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
||||||
golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
||||||
|
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
||||||
golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
|
golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
|
||||||
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
|
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
|
||||||
golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
|
golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
|
||||||
@@ -329,9 +449,13 @@ golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtn
|
|||||||
golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
|
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
|
golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||||
|
golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
|
||||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE=
|
google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE=
|
||||||
google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M=
|
google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M=
|
||||||
google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg=
|
google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg=
|
||||||
@@ -350,33 +474,50 @@ google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98
|
|||||||
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
|
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
|
||||||
google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8=
|
google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8=
|
||||||
google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
|
google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
|
||||||
|
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
|
||||||
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
|
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
|
||||||
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
|
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
|
||||||
google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
|
|
||||||
google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
|
google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
|
||||||
|
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
|
||||||
|
google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
|
||||||
|
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
|
||||||
|
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
|
||||||
|
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
|
||||||
|
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
|
||||||
|
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
|
||||||
|
google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||||
|
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||||
|
google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||||
|
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
|
||||||
|
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||||
|
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
||||||
|
google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=
|
||||||
|
google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
|
||||||
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
|
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
|
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
|
||||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
||||||
gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=
|
|
||||||
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
|
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
|
||||||
gopkg.in/ini.v1 v1.51.0 h1:AQvPpx3LzTDM0AjnIRlVFwFFGC+npRopjZxLJj6gdno=
|
gopkg.in/ini.v1 v1.51.0 h1:AQvPpx3LzTDM0AjnIRlVFwFFGC+npRopjZxLJj6gdno=
|
||||||
gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
||||||
gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo=
|
gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo=
|
||||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
|
|
||||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||||
gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74=
|
gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74=
|
||||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
gopkg.in/yaml.v2 v2.2.7 h1:VUgggvou5XRW9mHwD/yXxIYSMtY0zoKQf/v226p2nyo=
|
gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
|
||||||
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
|
|
||||||
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
|
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
|
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||||
|
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||||
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||||
honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||||
|
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||||
honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
|
honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
|
||||||
rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8=
|
rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8=
|
||||||
|
|||||||
56
tools/metrics_exporter/main.go
Normal file
56
tools/metrics_exporter/main.go
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/hibiken/asynq"
|
||||||
|
"github.com/hibiken/asynq/x/metrics"
|
||||||
|
"github.com/prometheus/client_golang/prometheus"
|
||||||
|
"github.com/prometheus/client_golang/prometheus/collectors"
|
||||||
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Declare command-line flags.
|
||||||
|
// These variables are binded to flags in init().
|
||||||
|
var (
|
||||||
|
flagRedisAddr string
|
||||||
|
flagRedisDB int
|
||||||
|
flagRedisPassword string
|
||||||
|
flagRedisUsername string
|
||||||
|
flagPort int
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
flag.StringVar(&flagRedisAddr, "redis-addr", "127.0.0.1:6379", "host:port of redis server to connect to")
|
||||||
|
flag.IntVar(&flagRedisDB, "redis-db", 0, "redis DB number to use")
|
||||||
|
flag.StringVar(&flagRedisPassword, "redis-password", "", "password used to connect to redis server")
|
||||||
|
flag.StringVar(&flagRedisUsername, "redis-username", "", "username used to connect to redis server")
|
||||||
|
flag.IntVar(&flagPort, "port", 9876, "port to use for the HTTP server")
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
flag.Parse()
|
||||||
|
// Using NewPedanticRegistry here to test the implementation of Collectors and Metrics.
|
||||||
|
reg := prometheus.NewPedanticRegistry()
|
||||||
|
|
||||||
|
inspector := asynq.NewInspector(asynq.RedisClientOpt{
|
||||||
|
Addr: flagRedisAddr,
|
||||||
|
DB: flagRedisDB,
|
||||||
|
Password: flagRedisPassword,
|
||||||
|
Username: flagRedisUsername,
|
||||||
|
})
|
||||||
|
|
||||||
|
reg.MustRegister(
|
||||||
|
metrics.NewQueueMetricsCollector(inspector),
|
||||||
|
// Add the standard process and go metrics to the registry
|
||||||
|
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
|
||||||
|
collectors.NewGoCollector(),
|
||||||
|
)
|
||||||
|
|
||||||
|
http.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))
|
||||||
|
log.Printf("exporter server is listening on port: %d\n", flagPort)
|
||||||
|
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", flagPort), nil))
|
||||||
|
}
|
||||||
26
x/go.mod
Normal file
26
x/go.mod
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
module github.com/hibiken/asynq/x
|
||||||
|
|
||||||
|
go 1.20
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/google/uuid v1.4.0
|
||||||
|
github.com/hibiken/asynq v0.24.1
|
||||||
|
github.com/prometheus/client_golang v1.11.1
|
||||||
|
github.com/redis/go-redis/v9 v9.3.0
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/beorn7/perks v1.0.1 // indirect
|
||||||
|
github.com/cespare/xxhash/v2 v2.2.0 // indirect
|
||||||
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||||
|
github.com/golang/protobuf v1.5.3 // indirect
|
||||||
|
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
|
||||||
|
github.com/prometheus/client_model v0.2.0 // indirect
|
||||||
|
github.com/prometheus/common v0.26.0 // indirect
|
||||||
|
github.com/prometheus/procfs v0.6.0 // indirect
|
||||||
|
github.com/robfig/cron/v3 v3.0.1 // indirect
|
||||||
|
github.com/spf13/cast v1.6.0 // indirect
|
||||||
|
golang.org/x/sys v0.15.0 // indirect
|
||||||
|
golang.org/x/time v0.5.0 // indirect
|
||||||
|
google.golang.org/protobuf v1.31.0 // indirect
|
||||||
|
)
|
||||||
197
x/go.sum
Normal file
197
x/go.sum
Normal file
@@ -0,0 +1,197 @@
|
|||||||
|
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||||
|
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
|
||||||
|
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
|
||||||
|
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
|
||||||
|
github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
|
||||||
|
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho=
|
||||||
|
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
|
||||||
|
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
|
||||||
|
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||||
|
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||||
|
github.com/bsm/ginkgo/v2 v2.7.0/go.mod h1:AiKlXPm7ItEHNc/2+OkrNG4E0ITzojb9/xWzvQ9XZ9w=
|
||||||
|
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||||
|
github.com/bsm/gomega v1.26.0/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||||
|
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||||
|
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
|
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
|
||||||
|
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||||
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||||
|
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||||
|
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
|
||||||
|
github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
|
||||||
|
github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY=
|
||||||
|
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
|
||||||
|
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
|
||||||
|
github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A=
|
||||||
|
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
|
||||||
|
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
|
||||||
|
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||||
|
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||||
|
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||||
|
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
|
||||||
|
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
|
||||||
|
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
|
||||||
|
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
|
||||||
|
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
|
||||||
|
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||||
|
github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||||
|
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||||
|
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||||
|
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
|
||||||
|
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||||
|
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||||
|
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||||
|
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
|
github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
|
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
|
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
|
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
|
||||||
|
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||||
|
github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
|
github.com/google/uuid v1.4.0 h1:MtMxsa51/r9yyhkyLsVeVt0B+BGQZzpQiTQ4eHZ8bc4=
|
||||||
|
github.com/google/uuid v1.4.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
|
github.com/hibiken/asynq v0.24.1 h1:+5iIEAyA9K/lcSPvx3qoPtsKJeKI5u9aOIvUmSsazEw=
|
||||||
|
github.com/hibiken/asynq v0.24.1/go.mod h1:u5qVeSbrnfT+vtG5Mq8ZPzQu/BmCKMHvTGb91uy9Tts=
|
||||||
|
github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4=
|
||||||
|
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
|
||||||
|
github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
||||||
|
github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
||||||
|
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
|
||||||
|
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
|
||||||
|
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||||
|
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||||
|
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
|
||||||
|
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||||
|
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||||
|
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||||
|
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||||
|
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||||
|
github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU=
|
||||||
|
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
|
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
|
||||||
|
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
|
||||||
|
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
|
||||||
|
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
|
||||||
|
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
|
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
|
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
|
||||||
|
github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo=
|
||||||
|
github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M=
|
||||||
|
github.com/prometheus/client_golang v1.11.1 h1:+4eQaD7vAZ6DsfsxB15hbE0odUjGI5ARs9yskGu1v4s=
|
||||||
|
github.com/prometheus/client_golang v1.11.1/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0=
|
||||||
|
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
|
||||||
|
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||||
|
github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M=
|
||||||
|
github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||||
|
github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
|
||||||
|
github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo=
|
||||||
|
github.com/prometheus/common v0.26.0 h1:iMAkS2TDoNWnKM+Kopnx/8tnEStIfpYA0ur0xQzzhMQ=
|
||||||
|
github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc=
|
||||||
|
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
|
||||||
|
github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
|
||||||
|
github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU=
|
||||||
|
github.com/prometheus/procfs v0.6.0 h1:mxy4L2jP6qMonqmq+aTtOx1ifVWUgG/TAmntgbh3xv4=
|
||||||
|
github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
|
||||||
|
github.com/redis/go-redis/v9 v9.0.3/go.mod h1:WqMKv5vnQbRuZstUwxQI195wHy+t4PuXDOjzMvcuQHk=
|
||||||
|
github.com/redis/go-redis/v9 v9.3.0 h1:RiVDjmig62jIWp7Kk4XVLs0hzV6pI3PyTnnL0cnn0u0=
|
||||||
|
github.com/redis/go-redis/v9 v9.3.0/go.mod h1:hdY0cQFCN4fnSYT6TkisLufl/4W5UIXyv0b/CLO2V2M=
|
||||||
|
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
||||||
|
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
||||||
|
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
|
||||||
|
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
|
||||||
|
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
|
||||||
|
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
|
||||||
|
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
|
||||||
|
github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0=
|
||||||
|
github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
|
||||||
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||||
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
|
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||||
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
|
||||||
|
go.uber.org/goleak v1.1.12 h1:gZAh5/EyT/HQwlpkCy6wTpqfH9H8Lz8zbm3dZh+OyzA=
|
||||||
|
go.uber.org/goleak v1.1.12/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ=
|
||||||
|
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||||
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
|
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||||
|
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||||
|
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||||
|
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||||
|
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
|
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
|
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
|
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||||
|
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||||
|
golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
|
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
|
golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
|
||||||
|
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
|
||||||
|
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||||
|
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
|
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
|
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
|
||||||
|
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
|
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||||
|
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||||
|
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||||
|
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
|
||||||
|
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
||||||
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
|
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||||
|
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
|
golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
|
||||||
|
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||||
|
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
|
||||||
|
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
|
||||||
|
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
|
||||||
|
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
|
||||||
|
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
|
||||||
|
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||||
|
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||||
|
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
||||||
|
google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=
|
||||||
|
google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
|
||||||
|
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
|
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
|
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
|
gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
|
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
190
x/metrics/metrics.go
Normal file
190
x/metrics/metrics.go
Normal file
@@ -0,0 +1,190 @@
|
|||||||
|
// Package metrics provides implementations of prometheus.Collector to collect Asynq queue metrics.
|
||||||
|
package metrics
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
|
||||||
|
"github.com/hibiken/asynq"
|
||||||
|
"github.com/prometheus/client_golang/prometheus"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Namespace used in fully-qualified metrics names.
|
||||||
|
const namespace = "asynq"
|
||||||
|
|
||||||
|
// QueueMetricsCollector gathers queue metrics.
|
||||||
|
// It implements prometheus.Collector interface.
|
||||||
|
//
|
||||||
|
// All metrics exported from this collector have prefix "asynq".
|
||||||
|
type QueueMetricsCollector struct {
|
||||||
|
inspector *asynq.Inspector
|
||||||
|
}
|
||||||
|
|
||||||
|
// collectQueueInfo gathers QueueInfo of all queues.
|
||||||
|
// Since this operation is expensive, it must be called once per collection.
|
||||||
|
func (qmc *QueueMetricsCollector) collectQueueInfo() ([]*asynq.QueueInfo, error) {
|
||||||
|
qnames, err := qmc.inspector.Queues()
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to get queue names: %v", err)
|
||||||
|
}
|
||||||
|
infos := make([]*asynq.QueueInfo, len(qnames))
|
||||||
|
for i, qname := range qnames {
|
||||||
|
qinfo, err := qmc.inspector.GetQueueInfo(qname)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to get queue info: %v", err)
|
||||||
|
}
|
||||||
|
infos[i] = qinfo
|
||||||
|
}
|
||||||
|
return infos, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Descriptors used by QueueMetricsCollector
|
||||||
|
var (
|
||||||
|
tasksQueuedDesc = prometheus.NewDesc(
|
||||||
|
prometheus.BuildFQName(namespace, "", "tasks_enqueued_total"),
|
||||||
|
"Number of tasks enqueued; broken down by queue and state.",
|
||||||
|
[]string{"queue", "state"}, nil,
|
||||||
|
)
|
||||||
|
|
||||||
|
queueSizeDesc = prometheus.NewDesc(
|
||||||
|
prometheus.BuildFQName(namespace, "", "queue_size"),
|
||||||
|
"Number of tasks in a queue",
|
||||||
|
[]string{"queue"}, nil,
|
||||||
|
)
|
||||||
|
|
||||||
|
queueLatencyDesc = prometheus.NewDesc(
|
||||||
|
prometheus.BuildFQName(namespace, "", "queue_latency_seconds"),
|
||||||
|
"Number of seconds the oldest pending task is waiting in pending state to be processed.",
|
||||||
|
[]string{"queue"}, nil,
|
||||||
|
)
|
||||||
|
|
||||||
|
queueMemUsgDesc = prometheus.NewDesc(
|
||||||
|
prometheus.BuildFQName(namespace, "", "queue_memory_usage_approx_bytes"),
|
||||||
|
"Number of memory used by a given queue (approximated number by sampling).",
|
||||||
|
[]string{"queue"}, nil,
|
||||||
|
)
|
||||||
|
|
||||||
|
tasksProcessedTotalDesc = prometheus.NewDesc(
|
||||||
|
prometheus.BuildFQName(namespace, "", "tasks_processed_total"),
|
||||||
|
"Number of tasks processed (both succeeded and failed); broken down by queue",
|
||||||
|
[]string{"queue"}, nil,
|
||||||
|
)
|
||||||
|
|
||||||
|
tasksFailedTotalDesc = prometheus.NewDesc(
|
||||||
|
prometheus.BuildFQName(namespace, "", "tasks_failed_total"),
|
||||||
|
"Number of tasks failed; broken down by queue",
|
||||||
|
[]string{"queue"}, nil,
|
||||||
|
)
|
||||||
|
|
||||||
|
pausedQueues = prometheus.NewDesc(
|
||||||
|
prometheus.BuildFQName(namespace, "", "queue_paused_total"),
|
||||||
|
"Number of queues paused",
|
||||||
|
[]string{"queue"}, nil,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
func (qmc *QueueMetricsCollector) Describe(ch chan<- *prometheus.Desc) {
|
||||||
|
prometheus.DescribeByCollect(qmc, ch)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (qmc *QueueMetricsCollector) Collect(ch chan<- prometheus.Metric) {
|
||||||
|
queueInfos, err := qmc.collectQueueInfo()
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Failed to collect metrics data: %v", err)
|
||||||
|
}
|
||||||
|
for _, info := range queueInfos {
|
||||||
|
ch <- prometheus.MustNewConstMetric(
|
||||||
|
tasksQueuedDesc,
|
||||||
|
prometheus.GaugeValue,
|
||||||
|
float64(info.Active),
|
||||||
|
info.Queue,
|
||||||
|
"active",
|
||||||
|
)
|
||||||
|
ch <- prometheus.MustNewConstMetric(
|
||||||
|
tasksQueuedDesc,
|
||||||
|
prometheus.GaugeValue,
|
||||||
|
float64(info.Pending),
|
||||||
|
info.Queue,
|
||||||
|
"pending",
|
||||||
|
)
|
||||||
|
ch <- prometheus.MustNewConstMetric(
|
||||||
|
tasksQueuedDesc,
|
||||||
|
prometheus.GaugeValue,
|
||||||
|
float64(info.Scheduled),
|
||||||
|
info.Queue,
|
||||||
|
"scheduled",
|
||||||
|
)
|
||||||
|
ch <- prometheus.MustNewConstMetric(
|
||||||
|
tasksQueuedDesc,
|
||||||
|
prometheus.GaugeValue,
|
||||||
|
float64(info.Retry),
|
||||||
|
info.Queue,
|
||||||
|
"retry",
|
||||||
|
)
|
||||||
|
ch <- prometheus.MustNewConstMetric(
|
||||||
|
tasksQueuedDesc,
|
||||||
|
prometheus.GaugeValue,
|
||||||
|
float64(info.Archived),
|
||||||
|
info.Queue,
|
||||||
|
"archived",
|
||||||
|
)
|
||||||
|
ch <- prometheus.MustNewConstMetric(
|
||||||
|
tasksQueuedDesc,
|
||||||
|
prometheus.GaugeValue,
|
||||||
|
float64(info.Completed),
|
||||||
|
info.Queue,
|
||||||
|
"completed",
|
||||||
|
)
|
||||||
|
|
||||||
|
ch <- prometheus.MustNewConstMetric(
|
||||||
|
queueSizeDesc,
|
||||||
|
prometheus.GaugeValue,
|
||||||
|
float64(info.Size),
|
||||||
|
info.Queue,
|
||||||
|
)
|
||||||
|
|
||||||
|
ch <- prometheus.MustNewConstMetric(
|
||||||
|
queueLatencyDesc,
|
||||||
|
prometheus.GaugeValue,
|
||||||
|
info.Latency.Seconds(),
|
||||||
|
info.Queue,
|
||||||
|
)
|
||||||
|
|
||||||
|
ch <- prometheus.MustNewConstMetric(
|
||||||
|
queueMemUsgDesc,
|
||||||
|
prometheus.GaugeValue,
|
||||||
|
float64(info.MemoryUsage),
|
||||||
|
info.Queue,
|
||||||
|
)
|
||||||
|
|
||||||
|
ch <- prometheus.MustNewConstMetric(
|
||||||
|
tasksProcessedTotalDesc,
|
||||||
|
prometheus.CounterValue,
|
||||||
|
float64(info.ProcessedTotal),
|
||||||
|
info.Queue,
|
||||||
|
)
|
||||||
|
|
||||||
|
ch <- prometheus.MustNewConstMetric(
|
||||||
|
tasksFailedTotalDesc,
|
||||||
|
prometheus.CounterValue,
|
||||||
|
float64(info.FailedTotal),
|
||||||
|
info.Queue,
|
||||||
|
)
|
||||||
|
|
||||||
|
pausedValue := 0 // zero to indicate "not paused"
|
||||||
|
if info.Paused {
|
||||||
|
pausedValue = 1
|
||||||
|
}
|
||||||
|
ch <- prometheus.MustNewConstMetric(
|
||||||
|
pausedQueues,
|
||||||
|
prometheus.GaugeValue,
|
||||||
|
float64(pausedValue),
|
||||||
|
info.Queue,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewQueueMetricsCollector returns a collector that exports metrics about Asynq queues.
|
||||||
|
func NewQueueMetricsCollector(inspector *asynq.Inspector) *QueueMetricsCollector {
|
||||||
|
return &QueueMetricsCollector{inspector: inspector}
|
||||||
|
}
|
||||||
40
x/rate/example_test.go
Normal file
40
x/rate/example_test.go
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
package rate_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/hibiken/asynq"
|
||||||
|
"github.com/hibiken/asynq/x/rate"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RateLimitError struct {
|
||||||
|
RetryIn time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *RateLimitError) Error() string {
|
||||||
|
return fmt.Sprintf("rate limited (retry in %v)", e.RetryIn)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleNewSemaphore() {
|
||||||
|
redisConnOpt := asynq.RedisClientOpt{Addr: ":6379"}
|
||||||
|
sema := rate.NewSemaphore(redisConnOpt, "my_queue", 10)
|
||||||
|
// call sema.Close() when appropriate
|
||||||
|
|
||||||
|
_ = asynq.HandlerFunc(func(ctx context.Context, task *asynq.Task) error {
|
||||||
|
ok, err := sema.Acquire(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
return &RateLimitError{RetryIn: 30 * time.Second}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make sure to release the token once we're done.
|
||||||
|
defer sema.Release(ctx)
|
||||||
|
|
||||||
|
// Process task
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user