-
Notifications
You must be signed in to change notification settings - Fork 185
Expand file tree
/
Copy pathtopic.go
More file actions
452 lines (407 loc) · 13.4 KB
/
topic.go
File metadata and controls
452 lines (407 loc) · 13.4 KB
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package http
import (
"encoding/base64"
"encoding/json"
"errors"
"io"
"net/http"
"github.com/go-chi/chi/v5"
actorErr "github.com/dapr/go-sdk/actor/error"
"github.com/dapr/go-sdk/actor/runtime"
"github.com/dapr/go-sdk/service/common"
"github.com/dapr/go-sdk/service/internal"
)
const (
// PubSubHandlerSuccessStatusCode is the successful ack code for pubsub event appcallback response.
PubSubHandlerSuccessStatusCode int = http.StatusOK
// PubSubHandlerRetryStatusCode is the error response code (nack) pubsub event appcallback response.
PubSubHandlerRetryStatusCode int = http.StatusInternalServerError
// PubSubHandlerDropStatusCode is the pubsub event appcallback response code indicating that Dapr should drop that message.
PubSubHandlerDropStatusCode int = http.StatusSeeOther
)
// topicEventJSON is identical to `common.TopicEvent`
// except for it treats `data` as a json.RawMessage so it can
// be used as bytes or interface{}.
// Merge itemMap into topicEventJSON
type topicEventJSON struct {
// ID identifies the event.
ID string `json:"id"`
// The version of the CloudEvents specification.
SpecVersion string `json:"specversion"`
// The type of event related to the originating occurrence.
Type string `json:"type"`
// Source identifies the context in which an event happened.
Source string `json:"source"`
// The content type of data value.
DataContentType string `json:"datacontenttype"`
// The content of the event.
// Note, this is why the gRPC and HTTP implementations need separate structs for cloud events.
Data json.RawMessage `json:"data"`
// The base64 encoding content of the event.
// Note, this is processing rawPayload and binary content types.
DataBase64 string `json:"data_base64,omitempty"`
// Cloud event subject
Subject string `json:"subject"`
// The pubsub topic which publisher sent to.
Topic string `json:"topic"`
// PubsubName is name of the pub/sub this message came from
PubsubName string `json:"pubsubname"`
}
func (in topicEventJSON) getData() (data any, rawData []byte) {
var (
err error
v any
)
if len(in.Data) > 0 {
rawData = []byte(in.Data)
data = rawData
// We can assume that rawData is valid JSON
// without checking in.DataContentType == "application/json".
if err = json.Unmarshal(rawData, &v); err == nil {
data = v
// Handling of JSON base64 encoded or escaped in a string.
if str, ok := v.(string); ok {
// This is the path that will most likely succeed.
var (
vString any
decoded []byte
)
if err = json.Unmarshal([]byte(str), &vString); err == nil {
data = vString
} else if decoded, err = base64.StdEncoding.DecodeString(str); err == nil {
// Decoded Base64 encoded JSON does not seem to be in the spec
// but it is in existing unit tests so this handles that case.
var vBase64 any
if err = json.Unmarshal(decoded, &vBase64); err == nil {
data = vBase64
}
}
}
}
} else if in.DataBase64 != "" {
rawData, err = base64.StdEncoding.DecodeString(in.DataBase64)
if err == nil {
data = rawData
if in.DataContentType == "application/json" {
if err = json.Unmarshal(rawData, &v); err == nil {
data = v
}
}
}
}
return data, rawData
}
type AppResponseStatus string
const (
// Success means the message is received and processed correctly.
Success AppResponseStatus = "SUCCESS"
// Retry means the message is received but could not be processed and must be retried.
Retry AppResponseStatus = "RETRY"
// Drop means the message is received but should not be processed.
Drop AppResponseStatus = "DROP"
)
type BulkSubscribeResponseEntry struct {
// The id of the bulk subscribe entry
EntryId string `json:"entryId"` //nolint:stylecheck
// The response status of the bulk subscribe entry
Status AppResponseStatus `json:"status"`
}
type BulkSubscribeResponse struct {
Statuses []BulkSubscribeResponseEntry `json:"statuses"`
}
func (s *Server) registerBaseHandler() {
// register subscribe handler
f := func(w http.ResponseWriter, r *http.Request) {
subs := make([]*internal.TopicSubscription, 0, len(s.topicRegistrar))
for _, s := range s.topicRegistrar {
subs = append(subs, s.Subscription)
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(subs); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
s.mux.HandleFunc("/dapr/subscribe", f)
// register health check handler
fHealth := func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
s.mux.Get("/healthz", fHealth)
// register actor config handler
fRegister := func(w http.ResponseWriter, r *http.Request) {
data, err := runtime.GetActorRuntimeInstanceContext().GetJSONSerializedConfig()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
if _, err = w.Write(data); err != nil {
return
}
}
s.mux.Get("/dapr/config", fRegister)
// register actor method invoke handler
fInvoke := func(w http.ResponseWriter, r *http.Request) {
actorType := chi.URLParam(r, "actorType")
actorID := chi.URLParam(r, "actorId")
methodName := chi.URLParam(r, "methodName")
reqData, _ := io.ReadAll(r.Body)
rspData, err := runtime.GetActorRuntimeInstanceContext().InvokeActorMethod(r.Context(), actorType, actorID, methodName, reqData)
if err == actorErr.ErrActorTypeNotFound {
w.WriteHeader(http.StatusNotFound)
return
}
if err != actorErr.Success {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write(rspData)
}
s.mux.Put("/actors/{actorType}/{actorId}/method/{methodName}", fInvoke)
// register deactivate actor handler
fDelete := func(w http.ResponseWriter, r *http.Request) {
actorType := chi.URLParam(r, "actorType")
actorID := chi.URLParam(r, "actorId")
err := runtime.GetActorRuntimeInstanceContext().Deactivate(r.Context(), actorType, actorID)
if err == actorErr.ErrActorTypeNotFound || err == actorErr.ErrActorIDNotFound {
w.WriteHeader(http.StatusNotFound)
}
if err != actorErr.Success {
w.WriteHeader(http.StatusInternalServerError)
}
w.WriteHeader(http.StatusOK)
}
s.mux.Delete("/actors/{actorType}/{actorId}", fDelete)
// register actor reminder invoke handler
fReminder := func(w http.ResponseWriter, r *http.Request) {
actorType := chi.URLParam(r, "actorType")
actorID := chi.URLParam(r, "actorId")
reminderName := chi.URLParam(r, "reminderName")
reqData, _ := io.ReadAll(r.Body)
err := runtime.GetActorRuntimeInstanceContext().InvokeReminder(r.Context(), actorType, actorID, reminderName, reqData)
if err == actorErr.ErrActorTypeNotFound {
w.WriteHeader(http.StatusNotFound)
}
if err != actorErr.Success {
w.WriteHeader(http.StatusInternalServerError)
}
w.WriteHeader(http.StatusOK)
}
s.mux.Put("/actors/{actorType}/{actorId}/method/remind/{reminderName}", fReminder)
// register actor timer invoke handler
fTimer := func(w http.ResponseWriter, r *http.Request) {
actorType := chi.URLParam(r, "actorType")
actorID := chi.URLParam(r, "actorId")
timerName := chi.URLParam(r, "timerName")
reqData, _ := io.ReadAll(r.Body)
err := runtime.GetActorRuntimeInstanceContext().InvokeTimer(r.Context(), actorType, actorID, timerName, reqData)
if err == actorErr.ErrActorTypeNotFound {
w.WriteHeader(http.StatusNotFound)
}
if err != actorErr.Success {
w.WriteHeader(http.StatusInternalServerError)
}
w.WriteHeader(http.StatusOK)
}
s.mux.Put("/actors/{actorType}/{actorId}/method/timer/{timerName}", fTimer)
}
// AddTopicEventHandler appends provided event handler with it's name to the service.
func (s *Server) AddTopicEventHandler(sub *common.Subscription, fn common.TopicEventHandler) error {
if sub == nil {
return errors.New("subscription required")
}
// Route is only required for HTTP but should be specified for the
// app protocol to be interchangeable.
if sub.Route == "" {
return errors.New("handler route name")
}
if err := s.topicRegistrar.AddSubscription(sub, fn); err != nil {
return err
}
s.mux.Handle(sub.Route, optionsHandler(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
// check for post with no data
var (
body []byte
err error
)
if r.Body != nil {
body, err = io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), PubSubHandlerDropStatusCode)
return
}
}
if len(body) == 0 {
http.Error(w, "nil content", PubSubHandlerDropStatusCode)
return
}
// deserialize the event
var in topicEventJSON
if err = json.Unmarshal(body, &in); err != nil {
http.Error(w, err.Error(), PubSubHandlerDropStatusCode)
return
}
if in.PubsubName == "" {
in.Topic = sub.PubsubName
}
if in.Topic == "" {
in.Topic = sub.Topic
}
data, rawData := in.getData()
te := common.TopicEvent{
ID: in.ID,
SpecVersion: in.SpecVersion,
Type: in.Type,
Source: in.Source,
DataContentType: in.DataContentType,
Data: data,
RawData: rawData,
DataBase64: in.DataBase64,
Subject: in.Subject,
PubsubName: in.PubsubName,
Topic: in.Topic,
}
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
// execute user handler
retry, err := fn(r.Context(), &te)
if err == nil {
writeStatus(w, common.SubscriptionResponseStatusSuccess)
return
}
if retry {
writeStatus(w, common.SubscriptionResponseStatusRetry)
return
}
writeStatus(w, common.SubscriptionResponseStatusDrop)
})))
return nil
}
func (s *Server) AddBulkTopicEventHandler(sub *common.Subscription, fn common.TopicEventHandler, maxMessagesCount, maxAwaitDurationMs int32) error {
if sub == nil {
return errors.New("subscription required")
}
// Route is only required for HTTP but should be specified for the
// app protocol to be interchangeable.
if sub.Route == "" {
return errors.New("handler route name")
}
if err := s.topicRegistrar.AddBulkSubscription(sub, fn, maxMessagesCount, maxAwaitDurationMs); err != nil {
return err
}
s.mux.Handle(sub.Route, optionsHandler(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
// check for post with no data
var (
body []byte
err error
)
if r.Body != nil {
body, err = io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), PubSubHandlerDropStatusCode)
return
}
}
if len(body) == 0 {
http.Error(w, "nil content", PubSubHandlerDropStatusCode)
return
}
// deserialize the event
var ins internal.BulkSubscribeEnvelope
if err = json.Unmarshal(body, &ins); err != nil {
http.Error(w, err.Error(), PubSubHandlerDropStatusCode)
return
}
statuses := make([]BulkSubscribeResponseEntry, 0, len(ins.Entries))
for _, entry := range ins.Entries {
itemJSON, entryErr := json.Marshal(entry.Event)
if entryErr != nil {
http.Error(w, entryErr.Error(), PubSubHandlerDropStatusCode)
return
}
var in topicEventJSON
if err = json.Unmarshal(itemJSON, &in); err != nil {
http.Error(w, err.Error(), PubSubHandlerDropStatusCode)
return
}
if in.PubsubName == "" {
in.Topic = sub.PubsubName
}
if in.Topic == "" {
in.Topic = sub.Topic
}
data, rawData := in.getData()
te := common.TopicEvent{
ID: in.ID,
SpecVersion: in.SpecVersion,
Type: in.Type,
Source: in.Source,
DataContentType: in.DataContentType,
Data: data,
RawData: rawData,
DataBase64: in.DataBase64,
Subject: in.Subject,
PubsubName: in.PubsubName,
Topic: in.Topic,
}
retry, funcErr := fn(r.Context(), &te)
if funcErr == nil {
statuses = append(statuses, BulkSubscribeResponseEntry{
EntryId: entry.EntryId,
Status: Success,
},
)
} else if retry {
statuses = append(statuses, BulkSubscribeResponseEntry{
EntryId: entry.EntryId,
Status: Retry,
},
)
} else {
statuses = append(statuses, BulkSubscribeResponseEntry{
EntryId: entry.EntryId,
Status: Drop,
},
)
}
}
resp := BulkSubscribeResponse{
Statuses: statuses,
}
if err != nil {
http.Error(w, err.Error(), PubSubHandlerDropStatusCode)
return
}
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
writeBulkStatus(w, resp)
})))
return nil
}
func writeStatus(w http.ResponseWriter, s string) {
status := &common.SubscriptionResponse{Status: s}
if err := json.NewEncoder(w).Encode(status); err != nil {
http.Error(w, err.Error(), PubSubHandlerRetryStatusCode)
}
}
func writeBulkStatus(w http.ResponseWriter, s BulkSubscribeResponse) {
if err := json.NewEncoder(w).Encode(s); err != nil {
http.Error(w, err.Error(), PubSubHandlerRetryStatusCode)
}
}