forked from automuteus/utils
/
jobs.go
77 lines (62 loc) · 1.73 KB
/
jobs.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package task
import (
"context"
"encoding/json"
"github.com/automuteus/utils/pkg/rediskey"
"github.com/go-redis/redis/v8"
"time"
)
type JobType int
const (
ConnectionJob JobType = iota
LobbyJob
StateJob
PlayerJob
GameOverJob
)
type Job struct {
JobType JobType `json:"type"`
Payload interface{} `json:"payload"`
}
const JobTTLSeconds = 3600
func PushJob(ctx context.Context, redis *redis.Client, connCode string, jobType JobType, payload string) error {
job := Job{
JobType: jobType,
Payload: payload,
}
jBytes, err := json.Marshal(job)
if err != nil {
return err
}
count, err := redis.RPush(ctx, rediskey.JobNamespace+connCode, string(jBytes)).Result()
if err == nil {
notify(ctx, redis, connCode)
}
// new list
if count < 2 {
// log.Printf("Set TTL for List")
redis.Expire(ctx, rediskey.JobNamespace+connCode, JobTTLSeconds*time.Second)
}
return err
}
func notify(ctx context.Context, redis *redis.Client, connCode string) {
redis.Publish(ctx, rediskey.JobNamespace+connCode+":notify", true)
}
func Subscribe(ctx context.Context, redis *redis.Client, connCode string) *redis.PubSub {
return redis.Subscribe(ctx, rediskey.JobNamespace+connCode+":notify")
}
func PopJob(ctx context.Context, redis *redis.Client, connCode string) (Job, error) {
str, err := redis.LPop(ctx, rediskey.JobNamespace+connCode).Result()
j := Job{}
if err != nil {
return j, err
}
err = json.Unmarshal([]byte(str), &j)
return j, err
}
func Ack(ctx context.Context, redis *redis.Client, connCode string) {
redis.Publish(ctx, rediskey.JobNamespace+connCode+":ack", true)
}
func AckSubscribe(ctx context.Context, redis *redis.Client, connCode string) *redis.PubSub {
return redis.Subscribe(ctx, rediskey.JobNamespace+connCode+":ack")
}