-
Notifications
You must be signed in to change notification settings - Fork 260
/
Copy pathtopic_mgt.go
190 lines (170 loc) · 5.21 KB
/
topic_mgt.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
// Copyright 2019 Google Inc. All Rights Reserved.
//
// 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 messaging
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"firebase.google.com/go/internal"
)
const (
iidEndpoint = "https://iid.googleapis.com/iid/v1"
iidSubscribe = "batchAdd"
iidUnsubscribe = "batchRemove"
)
var iidErrorCodes = map[string]struct{ Code, Msg string }{
"INVALID_ARGUMENT": {
invalidArgument,
"request contains an invalid argument; code: " + invalidArgument,
},
"NOT_FOUND": {
registrationTokenNotRegistered,
"request contains an invalid argument; code: " + registrationTokenNotRegistered,
},
"INTERNAL": {
internalError,
"server encountered an internal error; code: " + internalError,
},
"TOO_MANY_TOPICS": {
tooManyTopics,
"client exceeded the number of allowed topics; code: " + tooManyTopics,
},
}
// TopicManagementResponse is the result produced by topic management operations.
//
// TopicManagementResponse provides an overview of how many input tokens were successfully handled,
// and how many failed. In case of failures, the Errors list provides specific details concerning
// each error.
type TopicManagementResponse struct {
SuccessCount int
FailureCount int
Errors []*ErrorInfo
}
func newTopicManagementResponse(resp *iidResponse) *TopicManagementResponse {
tmr := &TopicManagementResponse{}
for idx, res := range resp.Results {
if len(res) == 0 {
tmr.SuccessCount++
} else {
tmr.FailureCount++
code := res["error"].(string)
info, ok := iidErrorCodes[code]
var reason string
if ok {
reason = info.Msg
} else {
reason = unknownError
}
tmr.Errors = append(tmr.Errors, &ErrorInfo{
Index: idx,
Reason: reason,
})
}
}
return tmr
}
type iidClient struct {
iidEndpoint string
httpClient *internal.HTTPClient
}
func newIIDClient(hc *http.Client) *iidClient {
client := internal.WithDefaultRetryConfig(hc)
client.CreateErrFn = handleIIDError
client.SuccessFn = internal.HasSuccessStatus
client.Opts = []internal.HTTPOption{internal.WithHeader("access_token_auth", "true")}
return &iidClient{
iidEndpoint: iidEndpoint,
httpClient: client,
}
}
// SubscribeToTopic subscribes a list of registration tokens to a topic.
//
// The tokens list must not be empty, and have at most 1000 tokens.
func (c *iidClient) SubscribeToTopic(ctx context.Context, tokens []string, topic string) (*TopicManagementResponse, error) {
req := &iidRequest{
Topic: topic,
Tokens: tokens,
op: iidSubscribe,
}
return c.makeTopicManagementRequest(ctx, req)
}
// UnsubscribeFromTopic unsubscribes a list of registration tokens from a topic.
//
// The tokens list must not be empty, and have at most 1000 tokens.
func (c *iidClient) UnsubscribeFromTopic(ctx context.Context, tokens []string, topic string) (*TopicManagementResponse, error) {
req := &iidRequest{
Topic: topic,
Tokens: tokens,
op: iidUnsubscribe,
}
return c.makeTopicManagementRequest(ctx, req)
}
type iidRequest struct {
Topic string `json:"to"`
Tokens []string `json:"registration_tokens"`
op string
}
type iidResponse struct {
Results []map[string]interface{} `json:"results"`
}
type iidError struct {
Error string `json:"error"`
}
func (c *iidClient) makeTopicManagementRequest(ctx context.Context, req *iidRequest) (*TopicManagementResponse, error) {
if len(req.Tokens) == 0 {
return nil, fmt.Errorf("no tokens specified")
}
if len(req.Tokens) > 1000 {
return nil, fmt.Errorf("tokens list must not contain more than 1000 items")
}
for _, token := range req.Tokens {
if token == "" {
return nil, fmt.Errorf("tokens list must not contain empty strings")
}
}
if req.Topic == "" {
return nil, fmt.Errorf("topic name not specified")
}
if !topicNamePattern.MatchString(req.Topic) {
return nil, fmt.Errorf("invalid topic name: %q", req.Topic)
}
if !strings.HasPrefix(req.Topic, "/topics/") {
req.Topic = "/topics/" + req.Topic
}
request := &internal.Request{
Method: http.MethodPost,
URL: fmt.Sprintf("%s:%s", c.iidEndpoint, req.op),
Body: internal.NewJSONEntity(req),
}
var result iidResponse
if _, err := c.httpClient.DoAndUnmarshal(ctx, request, &result); err != nil {
return nil, err
}
return newTopicManagementResponse(&result), nil
}
func handleIIDError(resp *internal.Response) error {
var ie iidError
json.Unmarshal(resp.Body, &ie) // ignore any json parse errors at this level
var clientCode, msg string
info, ok := iidErrorCodes[ie.Error]
if ok {
clientCode, msg = info.Code, info.Msg
} else {
clientCode = unknownError
msg = fmt.Sprintf("client encountered an unknown error; response: %s", string(resp.Body))
}
return internal.Errorf(clientCode, "http error status: %d; reason: %s", resp.Status, msg)
}