-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcloudtasks.go
217 lines (195 loc) · 5.29 KB
/
cloudtasks.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
package gasync
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"log"
"net/http"
"time"
"github.com/gorchestrate/async"
cloudtasks "google.golang.org/api/cloudtasks/v2beta3"
)
type GTasksScheduler struct {
Engine *FirestoreEngine
C *cloudtasks.Service
Collection string
ProjectID string
LocationID string
QueueName string
ResumeURL string
CallbackURL string
Secret string
}
type ResumeRequest struct {
ID string
Signature string
}
func (req ResumeRequest) HMAC(secret []byte) string {
h := hmac.New(sha256.New, secret)
h.Write([]byte(req.ID))
return hex.EncodeToString(h.Sum(nil))
}
func (mgr *GTasksScheduler) ResumeHandler(w http.ResponseWriter, r *http.Request) {
var req ResumeRequest
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
log.Printf("err: %v", err)
return
}
if req.HMAC([]byte(mgr.Secret)) != req.Signature {
w.WriteHeader(403)
fmt.Fprintf(w, "signature invalid")
return
}
err = mgr.Engine.Resume(r.Context(), req.ID)
if err != nil {
log.Printf("err: %v", err)
w.WriteHeader(500)
return
}
}
// in this demo we resume workflows right inside the http handler.
// we use this scheduler only for redundancy in case resume will fail for some reason in http handler.
func (mgr *GTasksScheduler) Schedule(ctx context.Context, id string, delay time.Duration) error {
defer logTime("schedule")()
req := ResumeRequest{
ID: id,
}
req.Signature = req.HMAC([]byte(mgr.Secret))
body, err := json.Marshal(req)
if err != nil {
panic(err)
}
sTime := time.Now().Add(delay).Format(time.RFC3339)
_, err = mgr.C.Projects.Locations.Queues.Tasks.Create(
fmt.Sprintf("projects/%v/locations/%v/queues/%v",
mgr.ProjectID, mgr.LocationID, mgr.QueueName),
&cloudtasks.CreateTaskRequest{
Task: &cloudtasks.Task{
ScheduleTime: sTime,
HttpRequest: &cloudtasks.HttpRequest{
Url: mgr.ResumeURL,
HttpMethod: "POST",
Body: base64.StdEncoding.EncodeToString(body),
},
},
}).Context(ctx).Do()
return err
}
func (s *Server) Timeout(name string, dur time.Duration, stmts ...async.Stmt) async.Event {
return async.On(name, &TimeoutHandler{
Duration: dur,
scheduler: s.Scheduler,
}, stmts...)
}
type TimeoutHandler struct {
Duration time.Duration
scheduler *GTasksScheduler
}
func (s TimeoutHandler) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type string
Duration string
}{
Type: "timeout",
Duration: fmt.Sprintf("%v sec", s.Duration.Seconds()),
})
}
func (t *TimeoutHandler) Handle(ctx context.Context, req async.CallbackRequest, input interface{}) (interface{}, error) {
return nil, nil
}
func (t *TimeoutHandler) Setup(ctx context.Context, req async.CallbackRequest) (string, error) {
defer logTime("timeout setup")()
return t.scheduler.Setup(ctx, req, t.Duration)
}
func (t *TimeoutHandler) Teardown(ctx context.Context, req async.CallbackRequest, handled bool) error {
defer logTime("timeout teardown")()
return t.scheduler.Teardown(ctx, req, handled)
}
type TimeoutReq struct {
Req async.CallbackRequest
Signature string
}
func (req TimeoutReq) HMAC(secret []byte) string {
h := hmac.New(sha256.New, secret)
h.Write([]byte(req.Req.Name))
h.Write([]byte(req.Req.ThreadID))
h.Write([]byte(req.Req.WorkflowID))
h.Write([]byte(fmt.Sprint(req.Req.PC)))
return hex.EncodeToString(h.Sum(nil))
}
func (mgr *GTasksScheduler) TimeoutHandler(w http.ResponseWriter, r *http.Request) {
defer logTime("timeout handler")()
var req TimeoutReq
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
w.WriteHeader(400)
fmt.Fprintf(w, "json parse: %v", err)
return
}
if req.HMAC([]byte(mgr.Secret)) != req.Signature {
w.WriteHeader(403)
fmt.Fprintf(w, "signature invalid")
return
}
_, err = mgr.Engine.HandleCallback(r.Context(), req.Req.WorkflowID, req.Req, nil)
if err != nil {
log.Printf("err: %v", err)
w.WriteHeader(500)
return
}
}
type GTasksSchedulerData struct {
ID string
}
func (mgr *GTasksScheduler) Setup(ctx context.Context, r async.CallbackRequest, del time.Duration) (string, error) {
req := TimeoutReq{
Req: r,
}
req.Signature = req.HMAC([]byte(mgr.Secret))
body, err := json.Marshal(req)
if err != nil {
panic(err)
}
sTime := time.Now().Add(del).Format(time.RFC3339)
resp, err := mgr.C.Projects.Locations.Queues.Tasks.Create(
fmt.Sprintf("projects/%v/locations/%v/queues/%v",
mgr.ProjectID, mgr.LocationID, mgr.QueueName),
&cloudtasks.CreateTaskRequest{
Task: &cloudtasks.Task{
ScheduleTime: sTime,
HttpRequest: &cloudtasks.HttpRequest{
Url: mgr.CallbackURL,
HttpMethod: "POST",
Body: base64.StdEncoding.EncodeToString(body),
},
},
}).Do()
if err != nil {
return "", err
}
d, err := json.Marshal(GTasksSchedulerData{
ID: resp.Name,
})
return string(d), err
}
func (mgr *GTasksScheduler) Teardown(ctx context.Context, req async.CallbackRequest, handled bool) error {
if handled {
log.Printf("skipping teardown for task that was already handled")
return nil
}
var data GTasksSchedulerData
err := json.Unmarshal([]byte(req.SetupData), &data)
if err != nil {
return err
}
_, err = mgr.C.Projects.Locations.Queues.Tasks.Delete(data.ID).Do()
if err != nil {
log.Printf("delete task err: %v", err)
}
return nil
}