-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathresults.go
97 lines (78 loc) · 1.98 KB
/
results.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package nats
import (
"context"
"fmt"
"log/slog"
"github.com/nats-io/nats.go"
)
const (
resultPrefix = "tasqueue-results-"
kvBucket = "tasqueue"
)
type Results struct {
opt Options
lo *slog.Logger
conn nats.KeyValue
}
type Options struct {
URL string
EnabledAuth bool
Username string
Password string
}
// New() returns a new instance of nats-jetstream broker.
func New(cfg Options, lo *slog.Logger) (*Results, error) {
opt := []nats.Option{}
if cfg.EnabledAuth {
opt = append(opt, nats.UserInfo(cfg.Username, cfg.Password))
}
conn, err := nats.Connect(cfg.URL, opt...)
if err != nil {
return nil, fmt.Errorf("error connecting to nats : %w", err)
}
// Get jet stream context
js, err := conn.JetStream()
if err != nil {
return nil, fmt.Errorf("error creating jetstream context : %w", err)
}
kv, err := js.KeyValue(kvBucket)
if err != nil {
return nil, fmt.Errorf("error creating key/value bucket : %w", err)
}
return &Results{
opt: cfg,
lo: lo,
conn: kv,
}, nil
}
func (r *Results) Get(_ context.Context, id string) ([]byte, error) {
rs, err := r.conn.Get(resultPrefix + id)
if err != nil {
return nil, err
}
return rs.Value(), nil
}
func (r *Results) NilError() error {
return nats.ErrKeyNotFound
}
func (r *Results) Set(_ context.Context, id string, b []byte) error {
if _, err := r.conn.Put(resultPrefix+id, b); err != nil {
return err
}
return nil
}
func (r *Results) SetSuccess(_ context.Context, id string) error {
return fmt.Errorf("method not implemented")
}
func (r *Results) SetFailed(_ context.Context, id string) error {
return fmt.Errorf("method not implemented")
}
func (r *Results) GetSuccess(_ context.Context) ([]string, error) {
return nil, fmt.Errorf("method not implemented")
}
func (r *Results) GetFailed(_ context.Context) ([]string, error) {
return nil, fmt.Errorf("method not implemented")
}
func (r *Results) DeleteJob(_ context.Context, id string) error {
return r.conn.Delete(resultPrefix + id)
}