| 1 |
// Copyright 2018 The Go Cloud Development Kit Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
// Package mempubsub provides an in-memory pubsub implementation. |
| 16 |
// Use NewTopic to construct a *pubsub.Topic, and/or NewSubscription |
| 17 |
// to construct a *pubsub.Subscription. |
| 18 |
// |
| 19 |
// mempubsub should not be used for production: it is intended for local |
| 20 |
// development and testing. |
| 21 |
// |
| 22 |
// # URLs |
| 23 |
// |
| 24 |
// For pubsub.OpenTopic and pubsub.OpenSubscription, mempubsub registers |
| 25 |
// for the scheme "mem". |
| 26 |
// To customize the URL opener, or for more details on the URL format, |
| 27 |
// see URLOpener. |
| 28 |
// See https://gocloud.dev/concepts/urls/ for background information. |
| 29 |
// |
| 30 |
// # Message Delivery Semantics |
| 31 |
// |
| 32 |
// mempubsub supports at-least-once semantics; applications must |
| 33 |
// call Message.Ack after processing a message, or it will be redelivered. |
| 34 |
// See https://godoc.org/gocloud.dev/pubsub#hdr-At_most_once_and_At_least_once_Delivery |
| 35 |
// for more background. |
| 36 |
// |
| 37 |
// # As |
| 38 |
// |
| 39 |
// mempubsub does not support any types for As. |
| 40 |
package mempubsub // import "gocloud.dev/pubsub/mempubsub" |
| 41 |
|
| 42 |
import ( |
| 43 |
"context" |
| 44 |
"errors" |
| 45 |
"fmt" |
| 46 |
"log" |
| 47 |
"net/url" |
| 48 |
"path" |
| 49 |
"sync" |
| 50 |
"time" |
| 51 |
|
| 52 |
"gocloud.dev/gcerrors" |
| 53 |
"gocloud.dev/pubsub" |
| 54 |
"gocloud.dev/pubsub/batcher" |
| 55 |
"gocloud.dev/pubsub/driver" |
| 56 |
) |
| 57 |
|
| 58 |
func init() { |
| 59 |
o := new(URLOpener) |
| 60 |
pubsub.DefaultURLMux().RegisterTopic(Scheme, o) |
| 61 |
pubsub.DefaultURLMux().RegisterSubscription(Scheme, o) |
| 62 |
} |
| 63 |
|
| 64 |
// Scheme is the URL scheme mempubsub registers its URLOpeners under on pubsub.DefaultMux. |
| 65 |
const Scheme = "mem" |
| 66 |
|
| 67 |
// URLOpener opens mempubsub URLs like "mem://topic". |
| 68 |
// |
| 69 |
// The URL's host+path is used as the topic to create or subscribe to. |
| 70 |
// |
| 71 |
// Query parameters: |
| 72 |
// - ackdeadline: The ack deadline for OpenSubscription, in time.ParseDuration formats. |
| 73 |
// Defaults to 1m. |
| 74 |
type URLOpener struct { |
| 75 |
mu sync.Mutex |
| 76 |
topics map[string]*pubsub.Topic |
| 77 |
} |
| 78 |
|
| 79 |
// OpenTopicURL opens a pubsub.Topic based on u. |
| 80 |
func (o *URLOpener) OpenTopicURL(ctx context.Context, u *url.URL) (*pubsub.Topic, error) { |
| 81 |
for param := range u.Query() { |
| 82 |
return nil, fmt.Errorf("open topic %v: invalid query parameter %q", u, param) |
| 83 |
} |
| 84 |
topicName := path.Join(u.Host, u.Path) |
| 85 |
o.mu.Lock() |
| 86 |
defer o.mu.Unlock() |
| 87 |
if o.topics == nil { |
| 88 |
o.topics = map[string]*pubsub.Topic{} |
| 89 |
} |
| 90 |
t := o.topics[topicName] |
| 91 |
if t == nil { |
| 92 |
t = NewTopic() |
| 93 |
o.topics[topicName] = t |
| 94 |
} |
| 95 |
return t, nil |
| 96 |
} |
| 97 |
|
| 98 |
// OpenSubscriptionURL opens a pubsub.Subscription based on u. |
| 99 |
func (o *URLOpener) OpenSubscriptionURL(ctx context.Context, u *url.URL) (*pubsub.Subscription, error) { |
| 100 |
q := u.Query() |
| 101 |
|
| 102 |
ackDeadline := 1 * time.Minute |
| 103 |
if s := q.Get("ackdeadline"); s != "" { |
| 104 |
var err error |
| 105 |
ackDeadline, err = time.ParseDuration(s) |
| 106 |
if err != nil { |
| 107 |
return nil, fmt.Errorf("open subscription %v: invalid ackdeadline %q: %v", u, s, err) |
| 108 |
} |
| 109 |
q.Del("ackdeadline") |
| 110 |
} |
| 111 |
for param := range q { |
| 112 |
return nil, fmt.Errorf("open subscription %v: invalid query parameter %q", u, param) |
| 113 |
} |
| 114 |
topicName := path.Join(u.Host, u.Path) |
| 115 |
o.mu.Lock() |
| 116 |
defer o.mu.Unlock() |
| 117 |
if o.topics == nil { |
| 118 |
o.topics = map[string]*pubsub.Topic{} |
| 119 |
} |
| 120 |
t := o.topics[topicName] |
| 121 |
if t == nil { |
| 122 |
return nil, fmt.Errorf("open subscription %v: no topic %q has been created", u, topicName) |
| 123 |
} |
| 124 |
return NewSubscription(t, ackDeadline), nil |
| 125 |
} |
| 126 |
|
| 127 |
var errNotExist = errors.New("mempubsub: topic does not exist") |
| 128 |
|
| 129 |
type topic struct { |
| 130 |
mu sync.Mutex |
| 131 |
subs []*subscription |
| 132 |
nextAckID int |
| 133 |
} |
| 134 |
|
| 135 |
// TopicOptions contains configuration options for topics. |
| 136 |
type TopicOptions struct { |
| 137 |
// BatcherOptions adds constraints to the default batching done for sends. |
| 138 |
BatcherOptions batcher.Options |
| 139 |
} |
| 140 |
|
| 141 |
// NewTopic creates a new in-memory topic. |
| 142 |
func NewTopic() *pubsub.Topic { |
| 143 |
return NewTopicWithOptions(nil) |
| 144 |
} |
| 145 |
|
| 146 |
// NewTopicWithOptions is similar to NewTopic, but supports TopicOptions. |
| 147 |
func NewTopicWithOptions(opts *TopicOptions) *pubsub.Topic { |
| 148 |
if opts == nil { |
| 149 |
opts = &TopicOptions{} |
| 150 |
} |
| 151 |
return pubsub.NewTopic(&topic{}, &opts.BatcherOptions) |
| 152 |
} |
| 153 |
|
| 154 |
// SendBatch implements driver.Topic.SendBatch. |
| 155 |
// It is error if the topic is closed or has no subscriptions. |
| 156 |
func (t *topic) SendBatch(ctx context.Context, ms []*driver.Message) error { |
| 157 |
if err := ctx.Err(); err != nil { |
| 158 |
return err |
| 159 |
} |
| 160 |
if t == nil { |
| 161 |
return errNotExist |
| 162 |
} |
| 163 |
t.mu.Lock() |
| 164 |
defer t.mu.Unlock() |
| 165 |
|
| 166 |
// Log a warning if there are no subscribers. |
| 167 |
if len(t.subs) == 0 { |
| 168 |
log.Print("warning: message sent to topic with no subscribers") |
| 169 |
} |
| 170 |
|
| 171 |
// Associate ack IDs with messages here. It would be a bit better if each subscription's |
| 172 |
// messages had their own ack IDs, so we could catch one subscription using ack IDs from another, |
| 173 |
// but that would require copying all the messages. |
| 174 |
for i, m := range ms { |
| 175 |
m.AckID = t.nextAckID + i |
| 176 |
m.LoggableID = fmt.Sprintf("msg #%d", m.AckID) |
| 177 |
m.AsFunc = func(any) bool { return false } |
| 178 |
|
| 179 |
if m.BeforeSend != nil { |
| 180 |
if err := m.BeforeSend(func(any) bool { return false }); err != nil { |
| 181 |
return err |
| 182 |
} |
| 183 |
} |
| 184 |
if m.AfterSend != nil { |
| 185 |
if err := m.AfterSend(func(any) bool { return false }); err != nil { |
| 186 |
return err |
| 187 |
} |
| 188 |
} |
| 189 |
} |
| 190 |
t.nextAckID += len(ms) |
| 191 |
for _, s := range t.subs { |
| 192 |
s.add(ms) |
| 193 |
} |
| 194 |
return nil |
| 195 |
} |
| 196 |
|
| 197 |
// IsRetryable implements driver.Topic.IsRetryable. |
| 198 |
func (*topic) IsRetryable(error) bool { return false } |
| 199 |
|
| 200 |
// As implements driver.Topic.As. |
| 201 |
// It supports *topic so that NewSubscription can recover a *topic |
| 202 |
// from the portable type (see below). External users won't be able |
| 203 |
// to use As because topic isn't exported. |
| 204 |
func (t *topic) As(i any) bool { |
| 205 |
x, ok := i.(**topic) |
| 206 |
if !ok { |
| 207 |
return false |
| 208 |
} |
| 209 |
*x = t |
| 210 |
return true |
| 211 |
} |
| 212 |
|
| 213 |
// ErrorAs implements driver.Topic.ErrorAs |
| 214 |
func (*topic) ErrorAs(error, any) bool { |
| 215 |
return false |
| 216 |
} |
| 217 |
|
| 218 |
// ErrorCode implements driver.Topic.ErrorCode |
| 219 |
func (*topic) ErrorCode(err error) gcerrors.ErrorCode { |
| 220 |
if err == errNotExist { |
| 221 |
return gcerrors.NotFound |
| 222 |
} |
| 223 |
return gcerrors.Unknown |
| 224 |
} |
| 225 |
|
| 226 |
// Close implements driver.Topic.Close. |
| 227 |
func (*topic) Close() error { return nil } |
| 228 |
|
| 229 |
// SubscriptionOptions will contain configuration for subscriptions. |
| 230 |
type SubscriptionOptions struct { |
| 231 |
// ReceiveBatcherOptions adds constraints to the default batching done for receives. |
| 232 |
ReceiveBatcherOptions batcher.Options |
| 233 |
|
| 234 |
// AckBatcherOptions adds constraints to the default batching done for acks. |
| 235 |
AckBatcherOptions batcher.Options |
| 236 |
} |
| 237 |
|
| 238 |
type subscription struct { |
| 239 |
mu sync.Mutex |
| 240 |
topic *topic |
| 241 |
ackDeadline time.Duration |
| 242 |
msgs map[driver.AckID]*message // all unacknowledged messages |
| 243 |
} |
| 244 |
|
| 245 |
// NewSubscription creates a new subscription for the given topic. |
| 246 |
// It panics if the given topic did not come from mempubsub. |
| 247 |
// If a message is not acked within in the given ack deadline from when |
| 248 |
// it is received, then it will be redelivered. |
| 249 |
func NewSubscription(pstopic *pubsub.Topic, ackDeadline time.Duration) *pubsub.Subscription { |
| 250 |
return NewSubscriptionWithOptions(pstopic, ackDeadline, nil) |
| 251 |
} |
| 252 |
|
| 253 |
// NewSubscriptionWithOptions is similar to NewSubscription, but supports SubscriptionOptions. |
| 254 |
func NewSubscriptionWithOptions(pstopic *pubsub.Topic, ackDeadline time.Duration, opts *SubscriptionOptions) *pubsub.Subscription { |
| 255 |
if opts == nil { |
| 256 |
opts = &SubscriptionOptions{} |
| 257 |
} |
| 258 |
var t *topic |
| 259 |
if !pstopic.As(&t) { |
| 260 |
panic("mempubsub: NewSubscription passed a Topic not from mempubsub") |
| 261 |
} |
| 262 |
return pubsub.NewSubscription(newSubscription(t, ackDeadline), &opts.ReceiveBatcherOptions, &opts.AckBatcherOptions) |
| 263 |
} |
| 264 |
|
| 265 |
func newSubscription(topic *topic, ackDeadline time.Duration) *subscription { |
| 266 |
s := &subscription{ |
| 267 |
topic: topic, |
| 268 |
ackDeadline: ackDeadline, |
| 269 |
msgs: map[driver.AckID]*message{}, |
| 270 |
} |
| 271 |
if topic != nil { |
| 272 |
topic.mu.Lock() |
| 273 |
defer topic.mu.Unlock() |
| 274 |
topic.subs = append(topic.subs, s) |
| 275 |
} |
| 276 |
return s |
| 277 |
} |
| 278 |
|
| 279 |
type message struct { |
| 280 |
msg *driver.Message |
| 281 |
expiration time.Time |
| 282 |
} |
| 283 |
|
| 284 |
func (s *subscription) add(ms []*driver.Message) { |
| 285 |
s.mu.Lock() |
| 286 |
defer s.mu.Unlock() |
| 287 |
for _, m := range ms { |
| 288 |
// The new message will expire at the zero time, which means it will be |
| 289 |
// immediately eligible for delivery. |
| 290 |
s.msgs[m.AckID] = &message{msg: m} |
| 291 |
} |
| 292 |
} |
| 293 |
|
| 294 |
// Collect some messages available for delivery. Since we're iterating over a map, |
| 295 |
// the order of the messages won't match the publish order, which mimics the actual |
| 296 |
// behavior of most pub/sub services. |
| 297 |
func (s *subscription) receiveNoWait(now time.Time, max int) []*driver.Message { |
| 298 |
var msgs []*driver.Message |
| 299 |
s.mu.Lock() |
| 300 |
defer s.mu.Unlock() |
| 301 |
for _, m := range s.msgs { |
| 302 |
if now.After(m.expiration) { |
| 303 |
msgs = append(msgs, m.msg) |
| 304 |
m.expiration = now.Add(s.ackDeadline) |
| 305 |
if len(msgs) == max { |
| 306 |
return msgs |
| 307 |
} |
| 308 |
} |
| 309 |
} |
| 310 |
return msgs |
| 311 |
} |
| 312 |
|
| 313 |
// How long ReceiveBatch should wait if no messages are available, to avoid |
| 314 |
// spinning. |
| 315 |
const pollDuration = 250 * time.Millisecond |
| 316 |
|
| 317 |
// ReceiveBatch implements driver.ReceiveBatch. |
| 318 |
func (s *subscription) ReceiveBatch(ctx context.Context, maxMessages int) ([]*driver.Message, error) { |
| 319 |
// Check for closed or cancelled before doing any work. |
| 320 |
if err := s.wait(ctx, 0); err != nil { |
| 321 |
return nil, err |
| 322 |
} |
| 323 |
msgs := s.receiveNoWait(time.Now(), maxMessages) |
| 324 |
if len(msgs) == 0 { |
| 325 |
// When we return no messages and no error, the portable type will call |
| 326 |
// ReceiveBatch again immediately. Sleep for a bit to avoid spinning. |
| 327 |
time.Sleep(pollDuration) |
| 328 |
} |
| 329 |
return msgs, nil |
| 330 |
} |
| 331 |
|
| 332 |
func (s *subscription) wait(ctx context.Context, dur time.Duration) error { |
| 333 |
if s.topic == nil { |
| 334 |
return errNotExist |
| 335 |
} |
| 336 |
select { |
| 337 |
case <-ctx.Done(): |
| 338 |
return ctx.Err() |
| 339 |
case <-time.After(dur): |
| 340 |
return nil |
| 341 |
} |
| 342 |
} |
| 343 |
|
| 344 |
// SendAcks implements driver.SendAcks. |
| 345 |
func (s *subscription) SendAcks(ctx context.Context, ackIDs []driver.AckID) error { |
| 346 |
if s.topic == nil { |
| 347 |
return errNotExist |
| 348 |
} |
| 349 |
// Check for context done before doing any work. |
| 350 |
if err := ctx.Err(); err != nil { |
| 351 |
return err |
| 352 |
} |
| 353 |
// Acknowledge messages by removing them from the map. |
| 354 |
// Since there is a single map, this correctly handles the case where a message |
| 355 |
// is redelivered, but the first receiver acknowledges it. |
| 356 |
s.mu.Lock() |
| 357 |
defer s.mu.Unlock() |
| 358 |
for _, id := range ackIDs { |
| 359 |
// It is OK if the message is not in the map; that just means it has been |
| 360 |
// previously acked. |
| 361 |
delete(s.msgs, id) |
| 362 |
} |
| 363 |
return nil |
| 364 |
} |
| 365 |
|
| 366 |
// CanNack implements driver.CanNack. |
| 367 |
func (s *subscription) CanNack() bool { return true } |
| 368 |
|
| 369 |
// SendNacks implements driver.SendNacks. |
| 370 |
func (s *subscription) SendNacks(ctx context.Context, ackIDs []driver.AckID) error { |
| 371 |
if s.topic == nil { |
| 372 |
return errNotExist |
| 373 |
} |
| 374 |
// Check for context done before doing any work. |
| 375 |
if err := ctx.Err(); err != nil { |
| 376 |
return err |
| 377 |
} |
| 378 |
// Nack messages by setting their expiration to the zero time. |
| 379 |
s.mu.Lock() |
| 380 |
defer s.mu.Unlock() |
| 381 |
for _, id := range ackIDs { |
| 382 |
if m := s.msgs[id]; m != nil { |
| 383 |
m.expiration = time.Time{} |
| 384 |
} |
| 385 |
} |
| 386 |
return nil |
| 387 |
} |
| 388 |
|
| 389 |
// IsRetryable implements driver.Subscription.IsRetryable. |
| 390 |
func (*subscription) IsRetryable(error) bool { return false } |
| 391 |
|
| 392 |
// As implements driver.Subscription.As. |
| 393 |
func (s *subscription) As(i any) bool { return false } |
| 394 |
|
| 395 |
// ErrorAs implements driver.Subscription.ErrorAs |
| 396 |
func (*subscription) ErrorAs(error, any) bool { |
| 397 |
return false |
| 398 |
} |
| 399 |
|
| 400 |
// ErrorCode implements driver.Subscription.ErrorCode |
| 401 |
func (*subscription) ErrorCode(err error) gcerrors.ErrorCode { |
| 402 |
if err == errNotExist { |
| 403 |
return gcerrors.NotFound |
| 404 |
} |
| 405 |
return gcerrors.Unknown |
| 406 |
} |
| 407 |
|
| 408 |
// Close implements driver.Subscription.Close. |
| 409 |
func (*subscription) Close() error { return nil } |