forked from googleapis/google-cloud-go
/
service.go
284 lines (251 loc) · 8.69 KB
/
service.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
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
// Copyright 2016 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 pubsub
import (
"encoding/base64"
"fmt"
"net/http"
"time"
"golang.org/x/net/context"
"google.golang.org/api/googleapi"
raw "google.golang.org/api/pubsub/v1"
)
// service provides an internal abstraction to isolate the generated
// PubSub API; most of this package uses this interface instead.
// The single implementation, *apiService, contains all the knowledge
// of the generated PubSub API (except for that present in legacy code).
type service interface {
createSubscription(ctx context.Context, topicName, subName string, ackDeadline time.Duration, pushConfig *PushConfig) error
getSubscriptionConfig(ctx context.Context, subName string) (*SubscriptionConfig, string, error)
listProjectSubscriptions(ctx context.Context, projName string) ([]string, error)
deleteSubscription(ctx context.Context, name string) error
subscriptionExists(ctx context.Context, name string) (bool, error)
modifyPushConfig(ctx context.Context, subName string, conf *PushConfig) error
createTopic(ctx context.Context, name string) error
deleteTopic(ctx context.Context, name string) error
topicExists(ctx context.Context, name string) (bool, error)
listProjectTopics(ctx context.Context, projName string) ([]string, error)
listTopicSubscriptions(ctx context.Context, topicName string) ([]string, error)
modifyAckDeadline(ctx context.Context, subName string, deadline time.Duration, ackIDs []string) error
fetchMessages(ctx context.Context, subName string, maxMessages int64) ([]*Message, error)
publishMessages(ctx context.Context, topicName string, msgs []*Message) ([]string, error)
// splitAckIDs divides ackIDs into
// * a batch of a size which is suitable for passing to acknowledge, and
// * the rest.
splitAckIDs(ackIDs []string) ([]string, []string)
// acknowledge ACKs the IDs in ackIDs.
acknowledge(ctx context.Context, subName string, ackIDs []string) error
}
type apiService struct {
s *raw.Service
}
func newPubSubService(client *http.Client, endpoint string) (*apiService, error) {
s, err := raw.New(client)
if err != nil {
return nil, err
}
s.BasePath = endpoint
return &apiService{s: s}, nil
}
func (s *apiService) createSubscription(ctx context.Context, topicName, subName string, ackDeadline time.Duration, pushConfig *PushConfig) error {
var rawPushConfig *raw.PushConfig
if pushConfig != nil {
rawPushConfig = &raw.PushConfig{
Attributes: pushConfig.Attributes,
PushEndpoint: pushConfig.Endpoint,
}
}
rawSub := &raw.Subscription{
AckDeadlineSeconds: int64(ackDeadline.Seconds()),
PushConfig: rawPushConfig,
Topic: topicName,
}
_, err := s.s.Projects.Subscriptions.Create(subName, rawSub).Context(ctx).Do()
return err
}
func (s *apiService) getSubscriptionConfig(ctx context.Context, subName string) (*SubscriptionConfig, string, error) {
rawSub, err := s.s.Projects.Subscriptions.Get(subName).Context(ctx).Do()
if err != nil {
return nil, "", err
}
sub := &SubscriptionConfig{
AckDeadline: time.Second * time.Duration(rawSub.AckDeadlineSeconds),
PushConfig: PushConfig{
Endpoint: rawSub.PushConfig.PushEndpoint,
Attributes: rawSub.PushConfig.Attributes,
},
}
return sub, rawSub.Topic, err
}
func (s *apiService) listProjectSubscriptions(ctx context.Context, projName string) ([]string, error) {
subs := []string{}
err := s.s.Projects.Subscriptions.List(projName).
Pages(ctx, func(res *raw.ListSubscriptionsResponse) error {
for _, s := range res.Subscriptions {
subs = append(subs, s.Name)
}
return nil
})
if err != nil {
return nil, err
}
return subs, nil
}
func (s *apiService) deleteSubscription(ctx context.Context, name string) error {
_, err := s.s.Projects.Subscriptions.Delete(name).Context(ctx).Do()
return err
}
func (s *apiService) subscriptionExists(ctx context.Context, name string) (bool, error) {
_, err := s.s.Projects.Subscriptions.Get(name).Context(ctx).Do()
if err == nil {
return true, nil
}
if e, ok := err.(*googleapi.Error); ok && e.Code == http.StatusNotFound {
return false, nil
}
return false, err
}
func (s *apiService) createTopic(ctx context.Context, name string) error {
// Note: The raw API expects a Topic body, but ignores it.
_, err := s.s.Projects.Topics.Create(name, &raw.Topic{}).
Context(ctx).
Do()
return err
}
func (s *apiService) listProjectTopics(ctx context.Context, projName string) ([]string, error) {
topics := []string{}
err := s.s.Projects.Topics.List(projName).
Pages(ctx, func(res *raw.ListTopicsResponse) error {
for _, topic := range res.Topics {
topics = append(topics, topic.Name)
}
return nil
})
if err != nil {
return nil, err
}
return topics, nil
}
func (s *apiService) deleteTopic(ctx context.Context, name string) error {
_, err := s.s.Projects.Topics.Delete(name).Context(ctx).Do()
return err
}
func (s *apiService) topicExists(ctx context.Context, name string) (bool, error) {
_, err := s.s.Projects.Topics.Get(name).Context(ctx).Do()
if err == nil {
return true, nil
}
if e, ok := err.(*googleapi.Error); ok && e.Code == http.StatusNotFound {
return false, nil
}
return false, err
}
func (s *apiService) listTopicSubscriptions(ctx context.Context, topicName string) ([]string, error) {
subs := []string{}
err := s.s.Projects.Topics.Subscriptions.List(topicName).
Pages(ctx, func(res *raw.ListTopicSubscriptionsResponse) error {
for _, s := range res.Subscriptions {
subs = append(subs, s)
}
return nil
})
if err != nil {
return nil, err
}
return subs, nil
}
func (s *apiService) modifyAckDeadline(ctx context.Context, subName string, deadline time.Duration, ackIDs []string) error {
req := &raw.ModifyAckDeadlineRequest{
AckDeadlineSeconds: int64(deadline.Seconds()),
AckIds: ackIDs,
}
_, err := s.s.Projects.Subscriptions.ModifyAckDeadline(subName, req).
Context(ctx).
Do()
return err
}
// maxPayload is the maximum number of bytes to devote to actual ids in
// acknowledgement requests. Note that there is ~1K of constant overhead, plus
// 3 bytes per ID (two quotes and a comma). The total payload size may not exceed 512K.
const maxPayload = 500 * 1024
const overheadPerID = 3 // 3 bytes of JSON
// splitAckIDs splits ids into two slices, the first of which contains at most maxPayload bytes of ackID data.
func (s *apiService) splitAckIDs(ids []string) ([]string, []string) {
total := 0
for i, id := range ids {
total += len(id) + overheadPerID
if total > maxPayload {
return ids[:i], ids[i:]
}
}
return ids, nil
}
func (s *apiService) acknowledge(ctx context.Context, subName string, ackIDs []string) error {
req := &raw.AcknowledgeRequest{
AckIds: ackIDs,
}
_, err := s.s.Projects.Subscriptions.Acknowledge(subName, req).
Context(ctx).
Do()
return err
}
func (s *apiService) fetchMessages(ctx context.Context, subName string, maxMessages int64) ([]*Message, error) {
req := &raw.PullRequest{
MaxMessages: maxMessages,
}
resp, err := s.s.Projects.Subscriptions.Pull(subName, req).
Context(ctx).
Do()
if err != nil {
return nil, err
}
msgs := make([]*Message, 0, len(resp.ReceivedMessages))
for i, m := range resp.ReceivedMessages {
msg, err := toMessage(m)
if err != nil {
return nil, fmt.Errorf("pubsub: cannot decode the retrieved message at index: %d, message: %+v", i, m)
}
msgs = append(msgs, msg)
}
return msgs, nil
}
func (s *apiService) publishMessages(ctx context.Context, topicName string, msgs []*Message) ([]string, error) {
rawMsgs := make([]*raw.PubsubMessage, len(msgs))
for i, msg := range msgs {
rawMsgs[i] = &raw.PubsubMessage{
Data: base64.StdEncoding.EncodeToString(msg.Data),
Attributes: msg.Attributes,
}
}
req := &raw.PublishRequest{Messages: rawMsgs}
resp, err := s.s.Projects.Topics.Publish(topicName, req).
Context(ctx).
Do()
if err != nil {
return nil, err
}
return resp.MessageIds, nil
}
func (s *apiService) modifyPushConfig(ctx context.Context, subName string, conf *PushConfig) error {
req := &raw.ModifyPushConfigRequest{
PushConfig: &raw.PushConfig{
Attributes: conf.Attributes,
PushEndpoint: conf.Endpoint,
},
}
_, err := s.s.Projects.Subscriptions.ModifyPushConfig(subName, req).
Context(ctx).
Do()
return err
}