code
stringlengths 22
3.95M
| docstring
stringlengths 20
17.8k
| func_name
stringlengths 1
472
| language
stringclasses 1
value | repo
stringlengths 6
57
| path
stringlengths 4
226
| url
stringlengths 43
277
| license
stringclasses 7
values |
|---|---|---|---|---|---|---|---|
func NewSenderFromConn(conn *nats.Conn, stream, subject string, jsmOpts []nats.JSOpt, opts ...SenderOption) (*Sender, error) {
jsm, err := conn.JetStream(jsmOpts...)
if err != nil {
return nil, err
}
streamInfo, err := jsm.StreamInfo(stream, jsmOpts...)
if streamInfo == nil || err != nil && err.Error() == "stream not found" {
_, err = jsm.AddStream(&nats.StreamConfig{
Name: stream,
Subjects: []string{stream + ".*"},
})
if err != nil {
return nil, err
}
}
s := &Sender{
Jsm: jsm,
Conn: conn,
Stream: stream,
Subject: subject,
}
err = s.applyOptions(opts...)
if err != nil {
return nil, err
}
return s, nil
}
|
NewSenderFromConn creates a new protocol.Sender which leaves responsibility for opening and closing the NATS
connection to the caller
|
NewSenderFromConn
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v2/sender.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v2/sender.go
|
Apache-2.0
|
func (s *Sender) Send(ctx context.Context, in binding.Message, transformers ...binding.Transformer) (err error) {
defer func() {
if err2 := in.Finish(err); err2 != nil {
if err == nil {
err = err2
} else {
err = fmt.Errorf("failed to call in.Finish() when error already occurred: %s: %w", err2.Error(), err)
}
}
}()
writer := new(bytes.Buffer)
header, err := WriteMsg(ctx, in, writer, transformers...)
if err != nil {
return err
}
natsMsg := &nats.Msg{
Subject: s.Subject,
Data: writer.Bytes(),
Header: header,
}
_, err = s.Jsm.PublishMsg(natsMsg)
return err
}
|
Close implements Sender.Sender
Sender sends messages.
|
Send
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v2/sender.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v2/sender.go
|
Apache-2.0
|
func (s *Sender) Close(_ context.Context) error {
if s.connOwned {
s.Conn.Close()
}
return nil
}
|
Close implements Closer.Close
This method only closes the connection if the Sender opened it
|
Close
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v2/sender.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v2/sender.go
|
Apache-2.0
|
func WriteMsg(ctx context.Context, m binding.Message, writer io.ReaderFrom, transformers ...binding.Transformer) (nats.Header, error) {
structuredWriter := &natsMessageWriter{writer}
binaryWriter := &natsBinaryMessageWriter{ReaderFrom: writer}
_, err := binding.Write(
ctx,
m,
structuredWriter,
binaryWriter,
transformers...,
)
natsHeader := binaryWriter.header
return natsHeader, err
}
|
WriteMsg fills the provided writer with the bindings.Message m.
Using context you can tweak the encoding processing (more details on binding.Write documentation).
The nats.Header returned is not deep-copied. The header values should be deep-copied to an event object.
|
WriteMsg
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v2/write_message.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v2/write_message.go
|
Apache-2.0
|
func NewMessage(msg jetstream.Msg) *Message {
encoding := binding.EncodingStructured
if msg.Headers() != nil {
if msg.Headers().Get(specs.PrefixedSpecVersionName()) != "" {
encoding = binding.EncodingBinary
}
}
return &Message{Msg: msg, encoding: encoding}
}
|
NewMessage wraps an *nats.Msg in a binding.Message.
The returned message *can* be read several times safely
The default encoding returned is EncodingStructured unless the NATS message contains a specversion header.
|
NewMessage
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/message.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/message.go
|
Apache-2.0
|
func (m *Message) ReadEncoding() binding.Encoding {
return m.encoding
}
|
ReadEncoding return the type of the message Encoding.
|
ReadEncoding
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/message.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/message.go
|
Apache-2.0
|
func (m *Message) ReadStructured(ctx context.Context, encoder binding.StructuredWriter) error {
if m.encoding != binding.EncodingStructured {
return binding.ErrNotStructured
}
return encoder.SetStructuredEvent(ctx, format.JSON, bytes.NewReader(m.Msg.Data()))
}
|
ReadStructured transfers a structured-mode event to a StructuredWriter.
|
ReadStructured
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/message.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/message.go
|
Apache-2.0
|
func (m *Message) ReadBinary(ctx context.Context, encoder binding.BinaryWriter) error {
if m.encoding != binding.EncodingBinary {
return binding.ErrNotBinary
}
version := m.GetVersion()
if version == nil {
return ErrNoVersion
}
var err error
for k, v := range m.Msg.Headers() {
headerValue := v[0]
if strings.HasPrefix(k, prefix) {
attr := version.Attribute(k)
if attr != nil {
err = encoder.SetAttribute(attr, headerValue)
} else {
err = encoder.SetExtension(strings.TrimPrefix(k, prefix), headerValue)
}
} else if k == contentTypeHeader {
err = encoder.SetAttribute(version.AttributeFromKind(spec.DataContentType), headerValue)
}
if err != nil {
return err
}
}
if m.Msg.Data() != nil {
err = encoder.SetData(bytes.NewBuffer(m.Msg.Data()))
}
return err
}
|
ReadBinary transfers a binary-mode event to an BinaryWriter.
|
ReadBinary
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/message.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/message.go
|
Apache-2.0
|
func (m *Message) Finish(err error) error {
// Ack and Nak first checks to see if the message has been acknowleged
// and if Ack/Nak was done, it immediately returns an error without applying any logic to the message on the server.
// Nak will only be sent if the error given is explictly a NACK error(protocol.ResultNACK).
// AckPolicy effects if an explict Ack/Nak is needed.
// AckExplicit: The default policy. Each individual message must be acknowledged.
// Recommended for most reliability and functionality.
// AckNone: No acknowledgment needed; the server assumes acknowledgment on delivery.
// AckAll: Acknowledge only the last message received in a series; all previous messages are automatically acknowledged.
// Will acknowledge all pending messages for all subscribers for Pull Consumer.
// see: github.com/nats-io/nats.go/jetstream/ConsumerConfig.AckPolicy
if m.Msg == nil {
return nil
}
if protocol.IsNACK(err) {
if err = m.Msg.Nak(); err != jetstream.ErrMsgAlreadyAckd {
return err
}
}
if protocol.IsACK(err) {
if err = m.Msg.Ack(); err != jetstream.ErrMsgAlreadyAckd {
return err
}
}
// In the case that we receive an unknown error, the intent of whether the message should Ack/Nak is unknown.
// When this happens, the ack/nak behavior will be based on the consumer configuration. There are several options such as:
// AckPolicy, AckWait, MaxDeliver, MaxAckPending
// that determine how messages would be redelivered by the server.
// [consumers configuration]: https://docs.nats.io/nats-concepts/jetstream/consumers#configuration
return nil
}
|
Finish *must* be called when message from a Receiver can be forgotten by the receiver.
|
Finish
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/message.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/message.go
|
Apache-2.0
|
func (m *Message) GetVersion() spec.Version {
if m.Msg.Headers() == nil {
return nil
}
versionValue := m.Msg.Headers().Get(specs.PrefixedSpecVersionName())
if versionValue == "" {
return nil
}
return specs.Version(versionValue)
}
|
GetVersion looks for specVersion header and returns a Version object
|
GetVersion
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/message.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/message.go
|
Apache-2.0
|
func withPrefix(attributeName string) string {
return fmt.Sprintf("%s%s", prefix, attributeName)
}
|
withPrefix prepends the prefix to the attribute name
|
withPrefix
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/message.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/message.go
|
Apache-2.0
|
func WithURL(url string) ProtocolOption {
return func(p *Protocol) error {
p.url = url
return nil
}
}
|
WithURL creates a connection to be used in the protocol sender and receiver.
This option is mutually exclusive with WithConnection.
|
WithURL
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/options.go
|
Apache-2.0
|
func WithNatsOptions(natsOpts []nats.Option) ProtocolOption {
return func(p *Protocol) error {
p.natsOpts = natsOpts
return nil
}
}
|
WithNatsOptions can be used together with WithURL() to specify NATS connection options
|
WithNatsOptions
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/options.go
|
Apache-2.0
|
func WithConnection(conn *nats.Conn) ProtocolOption {
return func(p *Protocol) error {
p.conn = conn
return nil
}
}
|
WithConnection uses the provided connection in the protocol sender and receiver
This option is mutually exclusive with WithURL.
|
WithConnection
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/options.go
|
Apache-2.0
|
func WithJetStreamOptions(jetStreamOpts []jetstream.JetStreamOpt) ProtocolOption {
return func(p *Protocol) error {
p.jetStreamOpts = jetStreamOpts
return nil
}
}
|
WithJetStreamOptions sets jetstream options used in the protocol sender and receiver
|
WithJetStreamOptions
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/options.go
|
Apache-2.0
|
func WithPublishOptions(publishOpts []jetstream.PublishOpt) ProtocolOption {
return func(p *Protocol) error {
p.publishOpts = publishOpts
return nil
}
}
|
WithPublishOptions sets publish options used in the protocol sender
|
WithPublishOptions
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/options.go
|
Apache-2.0
|
func WithSendSubject(sendSubject string) ProtocolOption {
return func(p *Protocol) error {
p.sendSubject = sendSubject
return nil
}
}
|
WithSendSubject sets the subject used in the protocol sender
|
WithSendSubject
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/options.go
|
Apache-2.0
|
func WithConsumerConfig(consumerConfig *jetstream.ConsumerConfig) ProtocolOption {
return func(p *Protocol) error {
p.consumerConfig = consumerConfig
return nil
}
}
|
WithConsumerConfig creates a unordered consumer used in the protocol receiver.
This option is mutually exclusive with WithOrderedConsumerConfig.
|
WithConsumerConfig
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/options.go
|
Apache-2.0
|
func WithOrderedConsumerConfig(orderedConsumerConfig *jetstream.OrderedConsumerConfig) ProtocolOption {
return func(p *Protocol) error {
p.orderedConsumerConfig = orderedConsumerConfig
return nil
}
}
|
WithOrderedConsumerConfig creates a ordered consumer used in the protocol receiver.
This option is mutually exclusive with WithConsumerConfig.
|
WithOrderedConsumerConfig
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/options.go
|
Apache-2.0
|
func WithPullConsumerOptions(pullConsumeOpts []jetstream.PullConsumeOpt) ProtocolOption {
return func(p *Protocol) error {
p.pullConsumeOpts = pullConsumeOpts
return nil
}
}
|
WithPullConsumerOptions sets pull options used in the protocol receiver.
|
WithPullConsumerOptions
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/options.go
|
Apache-2.0
|
func WithSubject(ctx context.Context, subject string) context.Context {
return context.WithValue(ctx, ctxKeySubject, subject)
}
|
WithSubject returns a new context with the subject set to the provided value.
This subject will be used when sending or receiving messages and overrides the default.
|
WithSubject
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/protocol.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/protocol.go
|
Apache-2.0
|
func (p *Protocol) Send(ctx context.Context, in binding.Message, transformers ...binding.Transformer) (err error) {
subject := p.getSendSubject(ctx)
if subject == "" {
return newValidationError(fieldSendSubject, messageNoSendSubject)
}
defer func() {
if err2 := in.Finish(err); err2 != nil {
if err == nil {
err = err2
} else {
err = fmt.Errorf("failed to call in.Finish() when error already occurred: %s: %w", err2.Error(), err)
}
}
}()
if _, err = p.jetStream.StreamNameBySubject(ctx, subject); err != nil {
return err
}
writer := new(bytes.Buffer)
header, err := WriteMsg(ctx, in, writer, transformers...)
if err != nil {
return err
}
natsMsg := &nats.Msg{
Subject: subject,
Data: writer.Bytes(),
Header: header,
}
_, err = p.jetStream.PublishMsg(ctx, natsMsg, p.publishOpts...)
return err
}
|
Send sends messages. Send implements Sender.Sender
|
Send
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/protocol.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/protocol.go
|
Apache-2.0
|
func (p *Protocol) MsgHandler(msg jetstream.Msg) {
p.incoming <- msgErr{msg: NewMessage(msg)}
}
|
MsgHandler implements nats.MsgHandler and publishes messages onto our internal incoming channel to be delivered
via r.Receive(ctx)
|
MsgHandler
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/protocol.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/protocol.go
|
Apache-2.0
|
func (p *Protocol) Close(ctx context.Context) error {
// Before closing, let's be sure OpenInbound completes
// We send a signal to close and then we lock on subMtx in order
// to wait OpenInbound to finish draining the queue
p.internalClose <- struct{}{}
p.subMtx.Lock()
defer p.subMtx.Unlock()
// if an URL was provided, then we must close the internally opened NATS connection
// since the connection is not exposed.
// If the connection was passed in, then leave the connection available.
if p.url != "" && p.conn != nil {
p.conn.Close()
}
close(p.internalClose)
return nil
}
|
Close must be called after use to releases internal resources.
If WithURL option was used, the NATS connection internally opened will be closed.
|
Close
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/protocol.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/protocol.go
|
Apache-2.0
|
func (p *Protocol) applyOptions(opts ...ProtocolOption) error {
for _, fn := range opts {
if err := fn(p); err != nil {
return err
}
}
return nil
}
|
applyOptions at the protocol layer should run before the sender and receiver are created.
This allows the protocol to create a nats connection that can be shared for both the sender and receiver.
|
applyOptions
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/protocol.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/protocol.go
|
Apache-2.0
|
func (p *Protocol) createJetstreamConsumer(ctx context.Context) error {
var err error
var stream string
if stream, err = p.getStreamFromSubjects(ctx); err != nil {
return err
}
var consumerErr error
if p.consumerConfig != nil {
p.jetstreamConsumer, consumerErr = p.jetStream.CreateOrUpdateConsumer(ctx, stream, *p.consumerConfig)
} else if p.orderedConsumerConfig != nil {
p.jetstreamConsumer, consumerErr = p.jetStream.OrderedConsumer(ctx, stream, *p.orderedConsumerConfig)
} else {
return newValidationError(fieldConsumerConfig, messageNoConsumerConfig)
}
return consumerErr
}
|
createJetstreamConsumer creates a consumer based on the configured consumer config
|
createJetstreamConsumer
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/protocol.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/protocol.go
|
Apache-2.0
|
func (p *Protocol) getStreamFromSubjects(ctx context.Context) (string, error) {
var subjects []string
if p.consumerConfig != nil && p.consumerConfig.FilterSubject != "" {
subjects = []string{p.consumerConfig.FilterSubject}
}
if p.consumerConfig != nil && len(p.consumerConfig.FilterSubjects) > 0 {
subjects = p.consumerConfig.FilterSubjects
}
if p.orderedConsumerConfig != nil && len(p.orderedConsumerConfig.FilterSubjects) > 0 {
subjects = p.orderedConsumerConfig.FilterSubjects
}
if len(subjects) == 0 {
return "", newValidationError(fieldFilterSubjects, messageNoFilterSubjects)
}
var finalStream string
for i, subject := range subjects {
currentStream, err := p.jetStream.StreamNameBySubject(ctx, subject)
if err != nil {
return "", err
}
if i == 0 {
finalStream = currentStream
continue
}
if finalStream != currentStream {
return "", newValidationError(fieldFilterSubjects, messageMoreThanOneStream)
}
}
return finalStream, nil
}
|
getStreamFromSubjects finds the unique stream for the set of filter subjects
If more than one stream is found, returns ErrMoreThanOneStream
|
getStreamFromSubjects
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/protocol.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/protocol.go
|
Apache-2.0
|
func validateOptions(p *Protocol) error {
if p.url == "" && p.conn == nil {
return newValidationError(fieldURL, messageNoConnection)
}
if p.url != "" && p.conn != nil {
return newValidationError(fieldURL, messageConflictingConnection)
}
consumerConfigOptions := 0
if p.consumerConfig != nil {
consumerConfigOptions++
}
if p.orderedConsumerConfig != nil {
consumerConfigOptions++
}
if consumerConfigOptions > 1 {
return newValidationError(fieldConsumerConfig, messageMoreThanOneConsumerConfig)
}
if len(p.pullConsumeOpts) > 0 && consumerConfigOptions == 0 {
return newValidationError(fieldPullConsumerOpts, messageReceiverOptionsWithoutConfig)
}
if len(p.publishOpts) > 0 && p.sendSubject == "" {
return newValidationError(fieldPublishOptions, messageSenderOptionsWithoutSubject)
}
return nil
}
|
validateOptions runs after all options have been applied and makes sure needed options were set correctly.
|
validateOptions
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/validation.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/validation.go
|
Apache-2.0
|
func (v validationError) Error() string {
return fmt.Sprintf("invalid parameters provided: %q: %s", v.field, v.message)
}
|
Error returns a message indicating an error condition, with the nil value representing no error.
|
Error
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/validation.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/validation.go
|
Apache-2.0
|
func WriteMsg(ctx context.Context, m binding.Message, writer io.ReaderFrom, transformers ...binding.Transformer) (nats.Header, error) {
structuredWriter := &natsMessageWriter{writer}
binaryWriter := &natsBinaryMessageWriter{ReaderFrom: writer}
_, err := binding.Write(
ctx,
m,
structuredWriter,
binaryWriter,
transformers...,
)
natsHeader := binaryWriter.header
return natsHeader, err
}
|
WriteMsg fills the provided writer with the bindings.Message m.
Using context you can tweak the encoding processing (more details on binding.Write documentation).
The nats.Header returned is not deep-copied. The header values should be deep-copied to an event object.
|
WriteMsg
|
go
|
cloudevents/sdk-go
|
protocol/nats_jetstream/v3/write_message.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/write_message.go
|
Apache-2.0
|
func WithCustomAttributes(ctx context.Context, attrs map[string]string) context.Context {
return context.WithValue(ctx, withCustomAttributes{}, attrs)
}
|
WithCustomAttributes sets Message Attributes without any CloudEvent logic.
Note that this function is not intended for CloudEvent Extensions or any `ce-`-prefixed Attributes.
For these please see `Event` and `Event.SetExtension`.
|
WithCustomAttributes
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/attributes.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/attributes.go
|
Apache-2.0
|
func NewMessage(pm *pubsub.Message) *Message {
var f format.Format = nil
var version spec.Version = nil
if pm.Attributes != nil {
// Use Content-type attr to determine if message is structured and
// set format.
if s := pm.Attributes[contentType]; format.IsFormat(s) {
f = format.Lookup(s)
}
// Binary v0.3:
if s := pm.Attributes[specs.PrefixedSpecVersionName()]; s != "" {
version = specs.Version(s)
}
}
return &Message{
internal: pm,
format: f,
version: version,
}
}
|
NewMessage returns a binding.Message with data and attributes.
This message *can* be read several times safely
|
NewMessage
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/message.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/message.go
|
Apache-2.0
|
func (m *Message) Finish(err error) error {
if protocol.IsACK(err) {
m.internal.Ack()
} else {
m.internal.Nack()
}
return err
}
|
Finish marks the message to be forgotten and returns the provided error without modification.
If err is nil or of type protocol.ResultACK the PubSub message will be acknowledged, otherwise nack-ed.
|
Finish
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/message.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/message.go
|
Apache-2.0
|
func WithClient(client *pubsub.Client) Option {
return func(t *Protocol) error {
t.client = client
return nil
}
}
|
WithClient sets the pubsub client for pubsub transport. Use this for explicit
auth setup. Otherwise the env var 'GOOGLE_APPLICATION_CREDENTIALS' is used.
See https://cloud.google.com/docs/authentication/production for more details.
|
WithClient
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/options.go
|
Apache-2.0
|
func WithProjectID(projectID string) Option {
return func(t *Protocol) error {
t.projectID = projectID
return nil
}
}
|
WithProjectID sets the project ID for pubsub transport.
|
WithProjectID
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/options.go
|
Apache-2.0
|
func WithProjectIDFromEnv(key string) Option {
return func(t *Protocol) error {
v := os.Getenv(key)
if v == "" {
return fmt.Errorf("unable to load project id, %q environment variable not set", key)
}
t.projectID = v
return nil
}
}
|
WithProjectIDFromEnv sets the project ID for pubsub transport from a
given environment variable name.
|
WithProjectIDFromEnv
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/options.go
|
Apache-2.0
|
func WithProjectIDFromDefaultEnv() Option {
return WithProjectIDFromEnv(DefaultProjectEnvKey)
}
|
WithProjectIDFromDefaultEnv sets the project ID for pubsub transport from
the environment variable named 'GOOGLE_CLOUD_PROJECT'.
|
WithProjectIDFromDefaultEnv
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/options.go
|
Apache-2.0
|
func WithTopicID(topicID string) Option {
return func(t *Protocol) error {
t.topicID = topicID
return nil
}
}
|
WithTopicID sets the topic ID for pubsub transport.
|
WithTopicID
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/options.go
|
Apache-2.0
|
func WithTopicIDFromEnv(key string) Option {
return func(t *Protocol) error {
v := os.Getenv(key)
if v == "" {
return fmt.Errorf("unable to load topic id, %q environment variable not set", key)
}
t.topicID = v
return nil
}
}
|
WithTopicIDFromEnv sets the topic ID for pubsub transport from a given
environment variable name.
|
WithTopicIDFromEnv
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/options.go
|
Apache-2.0
|
func WithTopicIDFromDefaultEnv() Option {
return WithTopicIDFromEnv(DefaultTopicEnvKey)
}
|
WithTopicIDFromDefaultEnv sets the topic ID for pubsub transport from the
environment variable named 'PUBSUB_TOPIC'.
|
WithTopicIDFromDefaultEnv
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/options.go
|
Apache-2.0
|
func WithSubscriptionID(subscriptionID string) Option {
return func(t *Protocol) error {
if t.subscriptions == nil {
t.subscriptions = make([]subscriptionWithTopic, 0)
}
t.subscriptions = append(t.subscriptions, subscriptionWithTopic{
subscriptionID: subscriptionID,
})
return nil
}
}
|
WithSubscriptionID sets the subscription ID for pubsub transport.
This option can be used multiple times.
|
WithSubscriptionID
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/options.go
|
Apache-2.0
|
func WithSubscriptionAndTopicID(subscriptionID, topicID string) Option {
return func(t *Protocol) error {
if t.subscriptions == nil {
t.subscriptions = make([]subscriptionWithTopic, 0)
}
t.subscriptions = append(t.subscriptions, subscriptionWithTopic{
subscriptionID: subscriptionID,
topicID: topicID,
})
return nil
}
}
|
WithSubscriptionAndTopicID sets the subscription and topic IDs for pubsub transport.
This option can be used multiple times.
|
WithSubscriptionAndTopicID
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/options.go
|
Apache-2.0
|
func WithSubscriptionIDAndFilter(subscriptionID, filter string) Option {
return func(t *Protocol) error {
if t.subscriptions == nil {
t.subscriptions = make([]subscriptionWithTopic, 0)
}
t.subscriptions = append(t.subscriptions, subscriptionWithTopic{
subscriptionID: subscriptionID,
filter: filter,
})
return nil
}
}
|
WithSubscriptionIDAndFilter sets the subscription and topic IDs for pubsub transport.
This option can be used multiple times.
|
WithSubscriptionIDAndFilter
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/options.go
|
Apache-2.0
|
func WithSubscriptionTopicIDAndFilter(subscriptionID, topicID, filter string) Option {
return func(t *Protocol) error {
if t.subscriptions == nil {
t.subscriptions = make([]subscriptionWithTopic, 0)
}
t.subscriptions = append(t.subscriptions, subscriptionWithTopic{
subscriptionID: subscriptionID,
topicID: topicID,
filter: filter,
})
return nil
}
}
|
WithSubscriptionTopicIDAndFilter sets the subscription with filter option and topic IDs for pubsub transport.
This option can be used multiple times.
|
WithSubscriptionTopicIDAndFilter
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/options.go
|
Apache-2.0
|
func WithSubscriptionIDFromEnv(key string) Option {
return func(t *Protocol) error {
v := os.Getenv(key)
if v == "" {
return fmt.Errorf("unable to load subscription id, %q environment variable not set", key)
}
opt := WithSubscriptionID(v)
return opt(t)
}
}
|
WithSubscriptionIDFromEnv sets the subscription ID for pubsub transport from
a given environment variable name.
|
WithSubscriptionIDFromEnv
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/options.go
|
Apache-2.0
|
func WithSubscriptionIDFromDefaultEnv() Option {
return WithSubscriptionIDFromEnv(DefaultSubscriptionEnvKey)
}
|
WithSubscriptionIDFromDefaultEnv sets the subscription ID for pubsub
transport from the environment variable named 'PUBSUB_SUBSCRIPTION'.
|
WithSubscriptionIDFromDefaultEnv
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/options.go
|
Apache-2.0
|
func WithFilter(filter string) Option {
return func(t *Protocol) error {
if t.subscriptions == nil {
t.subscriptions = make([]subscriptionWithTopic, 0)
}
t.subscriptions = append(t.subscriptions, subscriptionWithTopic{
filter: filter,
})
return nil
}
}
|
WithFilter sets the subscription filter for pubsub transport.
|
WithFilter
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/options.go
|
Apache-2.0
|
func WithFilterFromEnv(key string) Option {
return func(t *Protocol) error {
v := os.Getenv(key)
if v == "" {
return fmt.Errorf("unable to load subscription filter, %q environment variable not set", key)
}
opt := WithFilter(v)
return opt(t)
}
}
|
WithFilterFromEnv sets the subscription filter for pubsub transport from
a given environment variable name.
|
WithFilterFromEnv
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/options.go
|
Apache-2.0
|
func AllowCreateTopic(allow bool) Option {
return func(t *Protocol) error {
t.AllowCreateTopic = allow
return nil
}
}
|
AllowCreateTopic sets if the transport can create a topic if it does not
exist.
|
AllowCreateTopic
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/options.go
|
Apache-2.0
|
func AllowCreateSubscription(allow bool) Option {
return func(t *Protocol) error {
t.AllowCreateSubscription = allow
return nil
}
}
|
AllowCreateSubscription sets if the transport can create a subscription if
it does not exist.
|
AllowCreateSubscription
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/options.go
|
Apache-2.0
|
func WithReceiveSettings(rs *pubsub.ReceiveSettings) Option {
return func(t *Protocol) error {
t.ReceiveSettings = rs
return nil
}
}
|
WithReceiveSettings sets the Pubsub ReceiveSettings for pull subscriptions.
|
WithReceiveSettings
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/options.go
|
Apache-2.0
|
func WithMessageOrdering() Option {
return func(t *Protocol) error {
t.MessageOrdering = true
return nil
}
}
|
WithMessageOrdering enables message ordering for all topics and subscriptions.
|
WithMessageOrdering
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/options.go
|
Apache-2.0
|
func WithMessageOrderingFromEnv(key string) Option {
return func(t *Protocol) error {
if v := os.Getenv(key); v != "" {
t.MessageOrdering = true
}
return nil
}
}
|
WithMessageOrderingFromEnv enables message ordering for all topics and
subscriptions from a given environment variable name.
|
WithMessageOrderingFromEnv
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/options.go
|
Apache-2.0
|
func WithMessageOrderingFromDefaultEnv() Option {
return WithMessageOrderingFromEnv(DefaultMessageOrderingEnvKey)
}
|
WithMessageOrderingFromDefaultEnv enables message ordering for all topics and
subscriptions from the environment variable named 'PUBSUB_MESSAGE_ORDERING'.
|
WithMessageOrderingFromDefaultEnv
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/options.go
|
Apache-2.0
|
func WithOrderingKey(ctx context.Context, key string) context.Context {
return context.WithValue(ctx, withOrderingKey{}, key)
}
|
WithOrderingKey allows to set the Pub/Sub ordering key for publishing events.
|
WithOrderingKey
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/protocol.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/protocol.go
|
Apache-2.0
|
func WritePubSubMessage(ctx context.Context, m binding.Message, pubsubMessage *pubsub.Message, transformers ...binding.Transformer) error {
structuredWriter := (*pubsubMessagePublisher)(pubsubMessage)
binaryWriter := (*pubsubMessagePublisher)(pubsubMessage)
_, err := binding.Write(
ctx,
m,
structuredWriter,
binaryWriter,
transformers...,
)
return err
}
|
WritePubSubMessage fills the provided pubsubMessage with the message m.
Using context you can tweak the encoding processing (more details on binding.Write documentation).
|
WritePubSubMessage
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/write_pubsub_message.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/write_pubsub_message.go
|
Apache-2.0
|
func NewProtocolContext(project, topic, subscription, method string, msg *pubsub.Message) ProtocolContext {
var tx *ProtocolContext
if msg != nil {
tx = &ProtocolContext{
ID: msg.ID,
PublishTime: msg.PublishTime,
Project: project,
Topic: topic,
Subscription: subscription,
Method: method,
}
} else {
tx = &ProtocolContext{}
}
return *tx
}
|
NewProtocolContext creates a new ProtocolContext from a pubsub.Message.
|
NewProtocolContext
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/context/context.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/context/context.go
|
Apache-2.0
|
func (tx ProtocolContext) String() string {
b := strings.Builder{}
b.WriteString("Transport Context,\n")
if tx.ID != "" {
b.WriteString(" ID: " + tx.ID + "\n")
}
if !tx.PublishTime.IsZero() {
b.WriteString(" PublishTime: " + tx.PublishTime.String() + "\n")
}
if tx.Project != "" {
b.WriteString(" Project: " + tx.Project + "\n")
}
if tx.Topic != "" {
b.WriteString(" Topic: " + tx.Topic + "\n")
}
if tx.Subscription != "" {
b.WriteString(" Subscription: " + tx.Subscription + "\n")
}
if tx.Method != "" {
b.WriteString(" Method: " + tx.Method + "\n")
}
return b.String()
}
|
String generates a pretty-printed version of the resource as a string.
|
String
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/context/context.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/context/context.go
|
Apache-2.0
|
func WithProtocolContext(ctx context.Context, tcxt ProtocolContext) context.Context {
return context.WithValue(ctx, protocolContextKey, tcxt)
}
|
WithProtocolContext return a context with the given ProtocolContext into the provided context object.
|
WithProtocolContext
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/context/context.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/context/context.go
|
Apache-2.0
|
func ProtocolContextFrom(ctx context.Context) ProtocolContext {
tctx := ctx.Value(protocolContextKey)
if tctx != nil {
if tx, ok := tctx.(ProtocolContext); ok {
return tx
}
if tx, ok := tctx.(*ProtocolContext); ok {
return *tx
}
}
return ProtocolContext{}
}
|
ProtocolContextFrom pulls a ProtocolContext out of a context. Always
returns a non-nil object.
|
ProtocolContextFrom
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/context/context.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/context/context.go
|
Apache-2.0
|
func (c *Connection) Publish(ctx context.Context, msg *pubsub.Message) (*binding.Message, error) {
topic, err := c.getOrCreateTopic(ctx, false)
if err != nil {
return nil, err
}
r := topic.Publish(ctx, msg)
_, err = r.Get(ctx)
return nil, err
}
|
Publish publishes a message to the connection's topic
|
Publish
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/internal/connection.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/internal/connection.go
|
Apache-2.0
|
func (c *Connection) Receive(ctx context.Context, fn func(context.Context, *pubsub.Message)) error {
sub, err := c.getOrCreateSubscription(ctx, false)
if err != nil {
return err
}
// Ok, ready to start pulling.
return sub.Receive(ctx, func(ctx context.Context, m *pubsub.Message) {
ctx = pscontext.WithProtocolContext(ctx, pscontext.NewProtocolContext(c.ProjectID, c.TopicID, c.SubscriptionID, "pull", m))
fn(ctx, m)
})
}
|
Receive begins pulling messages.
NOTE: This is a blocking call.
|
Receive
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/internal/connection.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/internal/connection.go
|
Apache-2.0
|
func (pc *testPubsubClient) New(ctx context.Context, projectID string, failureMap map[string][]failPattern) (*pubsub.Client, error) {
pc.srv = pstest.NewServer()
var err error
var conn *grpc.ClientConn
if len(failureMap) == 0 {
conn, err = grpc.Dial(pc.srv.Addr, grpc.WithInsecure())
} else {
conn, err = grpc.Dial(pc.srv.Addr, grpc.WithInsecure(), grpc.WithUnaryInterceptor(makeFailureIntercept(failureMap)))
}
if err != nil {
return nil, err
}
pc.conn = conn
return pubsub.NewClient(ctx, projectID, option.WithGRPCConn(conn))
}
|
Create a pubsub client. If failureMap is provided, it gives a set of failures to induce in specific methods.
failureMap is modified by the event processor and should not be read or modified after calling New()
|
New
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/internal/connection_test.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/internal/connection_test.go
|
Apache-2.0
|
func makeFailureIntercept(failureMap map[string][]failPattern) grpc.UnaryClientInterceptor {
var lock sync.Mutex
return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
var injectedErr error
var delay time.Duration
lock.Lock()
if failureMap != nil {
fpArr := failureMap[method]
if len(fpArr) != 0 {
injectedErr = fpArr[0].ErrReturn
delay = fpArr[0].Delay
if fpArr[0].Count != 0 {
fpArr[0].Count--
if fpArr[0].Count == 0 {
failureMap[method] = fpArr[1:]
}
}
}
}
lock.Unlock()
if delay != 0 {
time.Sleep(delay)
}
if injectedErr != nil {
return injectedErr
} else {
return invoker(ctx, method, req, reply, cc, opts...)
}
}
}
|
Make a grpc failure injector that failes the specified methods with the
specified rates.
|
makeFailureIntercept
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/internal/connection_test.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/internal/connection_test.go
|
Apache-2.0
|
func verifyTopicDeleteWorks(t *testing.T, client *pubsub.Client, psconn *Connection, topicID string) {
ctx := context.Background()
if ok, err := client.Topic(topicID).Exists(ctx); err != nil || !ok {
t.Errorf("topic id=%s got exists=%v want=true, err=%v", topicID, ok, err)
}
if err := psconn.DeleteTopic(ctx); err != nil {
t.Errorf("delete topic failed: %v", err)
}
if ok, err := client.Topic(topicID).Exists(ctx); err != nil || ok {
t.Errorf("topic id=%s got exists=%v want=false, err=%v", topicID, ok, err)
}
}
|
Verify that the topic exists prior to the call, deleting it via psconn succeeds, and
the topic does not exist after the call.
|
verifyTopicDeleteWorks
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/internal/connection_test.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/internal/connection_test.go
|
Apache-2.0
|
func verifyTopicDeleteFails(t *testing.T, client *pubsub.Client, psconn *Connection, topicID string) {
ctx := context.Background()
if ok, err := client.Topic(topicID).Exists(ctx); err != nil || !ok {
t.Errorf("topic id=%s got exists=%v want=true, err=%v", topicID, ok, err)
}
if err := psconn.DeleteTopic(ctx); err == nil {
t.Errorf("delete topic succeeded unexpectedly")
}
if ok, err := client.Topic(topicID).Exists(ctx); err != nil || !ok {
t.Errorf("topic id=%s after delete got exists=%v want=true, err=%v", topicID, ok, err)
}
}
|
Verify that the topic exists before and after the call, and that deleting it via psconn fails
|
verifyTopicDeleteFails
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/internal/connection_test.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/internal/connection_test.go
|
Apache-2.0
|
func TestPublishExistingTopic(t *testing.T) {
for _, allowCreate := range []bool{true, false} {
t.Run(fmt.Sprintf("allowCreate_%v", allowCreate), func(t *testing.T) {
ctx := context.Background()
pc := &testPubsubClient{}
defer pc.Close()
projectID, topicID, subID := "test-project", "test-topic", "test-sub"
client, err := pc.New(ctx, projectID, nil)
if err != nil {
t.Fatalf("failed to create pubsub client: %v", err)
}
defer client.Close()
psconn := &Connection{
AllowCreateSubscription: true,
AllowCreateTopic: allowCreate,
Client: client,
ProjectID: projectID,
TopicID: topicID,
SubscriptionID: subID,
}
topic, err := client.CreateTopic(ctx, topicID)
if err != nil {
t.Fatalf("failed to pre-create topic: %v", err)
}
topic.Stop()
msg := &pubsub.Message{
ID: "msg-id-1",
Data: []byte("msg-data-1"),
}
if _, err := psconn.Publish(ctx, msg); err != nil {
t.Errorf("failed to publish message: %v", err)
}
verifyTopicDeleteFails(t, client, psconn, topicID)
})
}
}
|
Test that publishing to an already created topic works and doesn't allow topic deletion
|
TestPublishExistingTopic
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/internal/connection_test.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/internal/connection_test.go
|
Apache-2.0
|
func TestPublishAfterPublishFailure(t *testing.T) {
for _, failureMethod := range []string{
"/google.pubsub.v1.Publisher/GetTopic",
"/google.pubsub.v1.Publisher/CreateTopic",
"/google.pubsub.v1.Publisher/Publish"} {
t.Run(failureMethod, func(t *testing.T) {
ctx := context.Background()
pc := &testPubsubClient{}
defer pc.Close()
projectID, topicID, subID := "test-project", "test-topic", "test-sub"
failureMap := make(map[string][]failPattern)
failureMap[failureMethod] = []failPattern{{
ErrReturn: fmt.Errorf("Injected error"),
Count: 1,
Delay: 0}}
client, err := pc.New(ctx, projectID, failureMap)
if err != nil {
t.Fatalf("failed to create pubsub client: %v", err)
}
defer client.Close()
psconn := &Connection{
AllowCreateSubscription: true,
AllowCreateTopic: true,
Client: client,
ProjectID: projectID,
TopicID: topicID,
SubscriptionID: subID,
}
msg := &pubsub.Message{
ID: "msg-id-1",
Data: []byte("msg-data-1"),
}
// Fails due to injected failure
if _, err := psconn.Publish(ctx, msg); err == nil {
t.Errorf("Expected publish failure, but didn't see it: %v", err)
}
// Succeeds
if _, err := psconn.Publish(ctx, msg); err != nil {
t.Errorf("failed to publish message: %v", err)
}
verifyTopicDeleteWorks(t, client, psconn, topicID)
})
}
}
|
Make sure that Publishing works if the original publish failed due to an
error in one of the pubsub calls.
|
TestPublishAfterPublishFailure
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/internal/connection_test.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/internal/connection_test.go
|
Apache-2.0
|
func TestPublishCreateTopicAfterDelete(t *testing.T) {
ctx := context.Background()
pc := &testPubsubClient{}
defer pc.Close()
projectID, topicID, subID := "test-project", "test-topic", "test-sub"
client, err := pc.New(ctx, projectID, nil)
if err != nil {
t.Fatalf("failed to create pubsub client: %v", err)
}
defer client.Close()
psconn := &Connection{
AllowCreateSubscription: true,
AllowCreateTopic: true,
Client: client,
ProjectID: projectID,
TopicID: topicID,
SubscriptionID: subID,
}
msg := &pubsub.Message{
ID: "msg-id-1",
Data: []byte("msg-data-1"),
}
if _, err := psconn.Publish(ctx, msg); err != nil {
t.Errorf("failed to publish message: %v", err)
}
verifyTopicDeleteWorks(t, client, psconn, topicID)
if _, err := psconn.Publish(ctx, msg); err != nil {
t.Errorf("failed to publish message: %v", err)
}
verifyTopicDeleteWorks(t, client, psconn, topicID)
}
|
Test Publishing after Deleting a first version of a topic
|
TestPublishCreateTopicAfterDelete
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/internal/connection_test.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/internal/connection_test.go
|
Apache-2.0
|
func TestPublishCreateTopicNotAllowedFails(t *testing.T) {
ctx := context.Background()
pc := &testPubsubClient{}
defer pc.Close()
projectID, topicID, subID := "test-project", "test-topic", "test-sub"
client, err := pc.New(ctx, projectID, nil)
if err != nil {
t.Fatalf("failed to create pubsub client: %v", err)
}
defer client.Close()
psconn := &Connection{
AllowCreateSubscription: true,
AllowCreateTopic: false,
Client: client,
ProjectID: projectID,
TopicID: topicID,
SubscriptionID: subID,
}
msg := &pubsub.Message{
ID: "msg-id-1",
Data: []byte("msg-data-1"),
}
if _, err := psconn.Publish(ctx, msg); err == nil {
t.Errorf("publish succeeded unexpectedly")
}
if ok, err := client.Topic(topicID).Exists(ctx); err == nil && ok {
t.Errorf("topic id=%s got exists=%v want=false, err=%v", topicID, ok, err)
}
}
|
Test that publishing fails if a topic doesn't exist and topic creation isn't allowed
|
TestPublishCreateTopicNotAllowedFails
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/internal/connection_test.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/internal/connection_test.go
|
Apache-2.0
|
func TestPublishParallelFailure(t *testing.T) {
// This test is racy since it relies on a delay on one goroutine to
// ensure a second hits a sync.Once while the other is still processing
// it. Optimistically try with a short delay, but retry with longer
// ones so a failure is almost certainly a real failure, not a race.
var overallError error
for _, delay := range []time.Duration{time.Second / 4, 2 * time.Second, 10 * time.Second, 40 * time.Second} {
overallError = func() error {
failureMethod := "/google.pubsub.v1.Publisher/GetTopic"
ctx := context.Background()
pc := &testPubsubClient{}
defer pc.Close()
projectID, topicID, subID := "test-project", "test-topic", "test-sub"
// Inject a failure, but also add a delay to the call sees the error
failureMap := make(map[string][]failPattern)
failureMap[failureMethod] = []failPattern{{
ErrReturn: fmt.Errorf("Injected error"),
Count: 1,
Delay: delay}}
client, err := pc.New(ctx, projectID, failureMap)
if err != nil {
t.Fatalf("failed to create pubsub client: %v", err)
}
defer client.Close()
psconn := &Connection{
AllowCreateSubscription: true,
AllowCreateTopic: true,
Client: client,
ProjectID: projectID,
TopicID: topicID,
SubscriptionID: subID,
}
msg := &pubsub.Message{
ID: "msg-id-1",
Data: []byte("msg-data-1"),
}
resChan := make(chan error)
// Try a publish. We want this to be the first to try to create the channel
go func() {
_, err := psconn.Publish(ctx, msg)
resChan <- err
}()
// Try a second publish. We hope the above has hit it's critical section before
// this starts so that this reports out the error returned above.
_, errPub1 := psconn.Publish(ctx, msg)
errPub2 := <-resChan
if errPub1 == nil || errPub2 == nil {
return fmt.Errorf("expected dual expected failure, saw (%v) (%v) last run", errPub1, errPub2)
} else if errPub1 == nil && errPub2 == nil {
t.Fatalf("Dual success when expecting at least one failure, delay %v", delay)
}
return nil
}()
// Saw a successfull run, no retry needed.
if overallError == nil {
break
}
// Failure. The loop will bump the delay and try again(unless we've hit the max reasonable delay)
}
if overallError != nil {
t.Errorf(overallError.Error())
}
}
|
Test that failures of racing topic opens are reported out
|
TestPublishParallelFailure
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/internal/connection_test.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/internal/connection_test.go
|
Apache-2.0
|
func TestReceiveCreateTopicAndSubscription(t *testing.T) {
ctx := context.Background()
pc := &testPubsubClient{}
defer pc.Close()
projectID, topicID, subID := "test-project", "test-topic", "test-sub"
client, err := pc.New(ctx, projectID, nil)
if err != nil {
t.Fatalf("failed to create pubsub client: %v", err)
}
defer client.Close()
psconn := &Connection{
AllowCreateSubscription: true,
AllowCreateTopic: true,
Client: client,
ProjectID: projectID,
TopicID: topicID,
SubscriptionID: subID,
}
ctx2, cancel := context.WithCancel(ctx)
go psconn.Receive(ctx2, func(_ context.Context, msg *pubsub.Message) {
msg.Ack()
})
// Sleep waiting for the goroutine to create the topic and subscription
// If it takes over a minute, run the test anyway to get failure logging
for _, delay := range []time.Duration{time.Second / 4, time.Second, 20 * time.Second, 40 * time.Second} {
time.Sleep(delay)
ok, err := client.Subscription(subID).Exists(ctx)
if ok == true && err == nil {
break
}
}
if ok, err := client.Topic(topicID).Exists(ctx); err != nil || !ok {
t.Errorf("topic id=%s got exists=%v want=true, err=%v", topicID, ok, err)
}
if ok, err := client.Subscription(subID).Exists(ctx); err != nil || !ok {
t.Errorf("subscription id=%s got exists=%v want=true, err=%v", subID, ok, err)
}
si, err := psconn.getOrCreateSubscriptionInfo(context.Background(), true)
if err != nil {
t.Errorf("error getting subscription info %v", err)
}
if si.sub.ReceiveSettings.NumGoroutines != DefaultReceiveSettings.NumGoroutines {
t.Errorf("subscription receive settings have NumGoroutines=%d, want %d",
si.sub.ReceiveSettings.NumGoroutines, DefaultReceiveSettings.NumGoroutines)
}
cancel()
if err := psconn.DeleteSubscription(ctx); err != nil {
t.Errorf("delete subscription failed: %v", err)
}
if ok, err := client.Subscription(subID).Exists(ctx); err != nil || ok {
t.Errorf("subscription id=%s got exists=%v want=false, err=%v", subID, ok, err)
}
verifyTopicDeleteWorks(t, client, psconn, topicID)
}
|
Test that creating a subscription also creates the topic and subscription
|
TestReceiveCreateTopicAndSubscription
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/internal/connection_test.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/internal/connection_test.go
|
Apache-2.0
|
func TestReceiveExistingTopic(t *testing.T) {
for _, allow := range [](struct{ Sub, Topic bool }){{true, true}, {true, false}, {false, true}, {false, false}} {
t.Run(fmt.Sprintf("sub_%v__topic_%v", allow.Sub, allow.Topic), func(t *testing.T) {
ctx := context.Background()
pc := &testPubsubClient{}
defer pc.Close()
projectID, topicID, subID := "test-project", "test-topic", "test-sub"
client, err := pc.New(ctx, projectID, nil)
if err != nil {
t.Fatalf("failed to create pubsub client: %v", err)
}
defer client.Close()
psconn := &Connection{
AllowCreateSubscription: allow.Sub,
AllowCreateTopic: allow.Topic,
Client: client,
ProjectID: projectID,
TopicID: topicID,
SubscriptionID: subID,
}
topic, err := client.CreateTopic(ctx, topicID)
if err != nil {
pc.Close()
t.Fatalf("failed to pre-create topic: %v", err)
}
_, err = client.CreateSubscription(ctx, subID, pubsub.SubscriptionConfig{
Topic: topic,
AckDeadline: DefaultAckDeadline,
RetentionDuration: DefaultRetentionDuration,
})
topic.Stop()
if err != nil {
pc.Close()
t.Fatalf("failed to pre-createsubscription: %v", err)
}
ctx2, cancel := context.WithCancel(ctx)
go psconn.Receive(ctx2, func(_ context.Context, msg *pubsub.Message) {
msg.Ack()
})
// Block waiting for receive to succeed
si, err := psconn.getOrCreateSubscriptionInfo(context.Background(), false)
if err != nil {
t.Errorf("error getting subscription info %v", err)
}
if si.sub.ReceiveSettings.NumGoroutines != DefaultReceiveSettings.NumGoroutines {
t.Errorf("subscription receive settings have NumGoroutines=%d, want %d",
si.sub.ReceiveSettings.NumGoroutines, DefaultReceiveSettings.NumGoroutines)
}
cancel()
if err := psconn.DeleteSubscription(ctx); err == nil {
t.Errorf("delete subscription unexpectedly succeeded")
}
if ok, err := client.Subscription(subID).Exists(ctx); err != nil || !ok {
t.Errorf("subscription id=%s got exists=%v want=true, err=%v", subID, ok, err)
}
verifyTopicDeleteFails(t, client, psconn, topicID)
})
}
}
|
Test receive on an existing topic and subscription also works.
|
TestReceiveExistingTopic
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/internal/connection_test.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/internal/connection_test.go
|
Apache-2.0
|
func TestReceiveCreateSubscriptionAfterFailure(t *testing.T) {
for _, failureMethod := range []string{
"/google.pubsub.v1.Publisher/GetTopic",
"/google.pubsub.v1.Publisher/CreateTopic",
"/google.pubsub.v1.Subscriber/GetSubscription",
"/google.pubsub.v1.Subscriber/CreateSubscription"} {
t.Run(failureMethod, func(t *testing.T) {
ctx := context.Background()
pc := &testPubsubClient{}
defer pc.Close()
projectID, topicID, subID := "test-project", "test-topic", "test-sub"
failureMap := make(map[string][]failPattern)
failureMap[failureMethod] = []failPattern{{
ErrReturn: fmt.Errorf("Injected error"),
Count: 1,
Delay: 0}}
client, err := pc.New(ctx, projectID, failureMap)
if err != nil {
t.Fatalf("failed to create pubsub client: %v", err)
}
defer client.Close()
psconn := &Connection{
AllowCreateSubscription: true,
AllowCreateTopic: true,
Client: client,
ProjectID: projectID,
TopicID: topicID,
SubscriptionID: subID,
}
// We expect this receive to fail due to the injected error
ctx2, cancel := context.WithCancel(ctx)
errRet := make(chan error)
go func() {
errRet <- psconn.Receive(ctx2, func(_ context.Context, msg *pubsub.Message) {
msg.Ack()
})
}()
select {
case err := <-errRet:
if err == nil {
t.Fatalf("unexpected nil error from Receive")
}
case <-time.After(time.Minute):
cancel()
t.Fatalf("timeout waiting for receive error")
}
// We expect this receive to succeed
errRet2 := make(chan error)
ctx2, cancel = context.WithCancel(context.Background())
go func() {
errRet2 <- psconn.Receive(ctx2, func(_ context.Context, msg *pubsub.Message) {
msg.Ack()
})
}()
// Sleep waiting for the goroutine to create the topic and subscription
// If it takes over a minute, run the test anyway to get failure logging
for _, delay := range []time.Duration{time.Second / 4, time.Second, 20 * time.Second, 40 * time.Second} {
time.Sleep(delay)
ok, err := client.Subscription(subID).Exists(ctx)
if ok == true && err == nil {
break
}
}
select {
case err := <-errRet2:
t.Errorf("unexpected error from Receive: %v", err)
default:
}
if ok, err := client.Topic(topicID).Exists(ctx); err != nil || !ok {
t.Errorf("topic id=%s got exists=%v want=true, err=%v", topicID, ok, err)
}
if ok, err := client.Subscription(subID).Exists(ctx); err != nil || !ok {
t.Errorf("subscription id=%s got exists=%v want=true, err=%v", subID, ok, err)
}
cancel()
})
}
}
|
Test that creating a subscription after a failed attempt to create a subsciption works
|
TestReceiveCreateSubscriptionAfterFailure
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/internal/connection_test.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/internal/connection_test.go
|
Apache-2.0
|
func TestReceiveCreateDisallowedFail(t *testing.T) {
ctx := context.Background()
pc := &testPubsubClient{}
defer pc.Close()
for _, allow := range [](struct{ Sub, Topic bool }){{false, true}, {true, false}, {false, false}} {
t.Run(fmt.Sprintf("sub_%v__topic_%v", allow.Sub, allow.Topic), func(t *testing.T) {
projectID, topicID, subID := "test-project", "test-topic", "test-sub"
client, err := pc.New(ctx, projectID, nil)
if err != nil {
t.Fatalf("failed to create pubsub client: %v", err)
}
defer client.Close()
psconn := &Connection{
AllowCreateSubscription: allow.Sub,
AllowCreateTopic: allow.Topic,
Client: client,
ProjectID: projectID,
TopicID: topicID,
SubscriptionID: subID,
}
ctx2, cancel := context.WithCancel(ctx)
errRet := make(chan error)
go func() {
errRet <- psconn.Receive(ctx2, func(_ context.Context, msg *pubsub.Message) {
msg.Ack()
})
}()
select {
case err := <-errRet:
if err == nil {
t.Fatalf("unexpected nil error from Receive")
}
case <-time.After(time.Minute):
cancel()
t.Fatalf("timeout waiting for receive error")
}
cancel()
})
}
}
|
Test that lack of create privileges for topic or subscription causes a receive to fail for
a non-existing subscription and topic
|
TestReceiveCreateDisallowedFail
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/internal/connection_test.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/internal/connection_test.go
|
Apache-2.0
|
func TestPublishReceiveRoundtrip(t *testing.T) {
ctx := context.Background()
pc := &testPubsubClient{}
defer pc.Close()
projectID, topicID, subID := "test-project", "test-topic", "test-sub"
client, err := pc.New(ctx, projectID, nil)
if err != nil {
t.Fatalf("failed to create pubsub client: %v", err)
}
defer client.Close()
psconn := &Connection{
AllowCreateSubscription: true,
AllowCreateTopic: true,
Client: client,
ProjectID: projectID,
TopicID: topicID,
SubscriptionID: subID,
}
wantMsgs := make(map[string]string)
gotMsgs := make(map[string]string)
wg := &sync.WaitGroup{}
ctx2, cancel := context.WithCancel(ctx)
mux := &sync.Mutex{}
// Pubsub will drop all messages if there is no subscription.
// Call Receive first so that subscription can be created before
// we publish any message.
go psconn.Receive(ctx2, func(_ context.Context, msg *pubsub.Message) {
mux.Lock()
defer mux.Unlock()
gotMsgs[string(msg.Data)] = string(msg.Data)
msg.Ack()
wg.Done()
})
// Wait a little bit for the subscription creation to complete.
time.Sleep(time.Second)
for i := 0; i < 10; i++ {
data := fmt.Sprintf("data-%d", i)
wantMsgs[data] = data
if _, err := psconn.Publish(ctx, &pubsub.Message{Data: []byte(data)}); err != nil {
t.Errorf("failed to publish message: %v", err)
}
wg.Add(1)
}
wg.Wait()
cancel()
if diff := cmp.Diff(gotMsgs, wantMsgs); diff != "" {
t.Errorf("received unexpected messages (-want +got):\n%s", diff)
}
}
|
Test a full round trip of a message
|
TestPublishReceiveRoundtrip
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/internal/connection_test.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/internal/connection_test.go
|
Apache-2.0
|
func TestPublishReceiveRoundtripWithOrderingKey(t *testing.T) {
ctx := context.Background()
pc := &testPubsubClient{}
defer pc.Close()
projectID, topicID, subID := "test-project", "test-topic", "test-sub"
client, err := pc.New(ctx, projectID, nil)
if err != nil {
t.Fatalf("failed to create pubsub client: %v", err)
}
defer client.Close()
psconn := &Connection{
MessageOrdering: true,
AllowCreateSubscription: true,
AllowCreateTopic: true,
Client: client,
ProjectID: projectID,
TopicID: topicID,
SubscriptionID: subID,
}
wantMsgs := make(map[string]string)
wantMsgsOrdering := make(map[string]string)
gotMsgs := make(map[string]string)
gotMsgsOrdering := make(map[string]string)
wg := &sync.WaitGroup{}
ctx2, cancel := context.WithCancel(ctx)
mux := &sync.Mutex{}
// Pubsub will drop all messages if there is no subscription.
// Call Receive first so that subscription can be created before
// we publish any message.
go psconn.Receive(ctx2, func(_ context.Context, msg *pubsub.Message) {
mux.Lock()
defer mux.Unlock()
gotMsgs[string(msg.Data)] = string(msg.Data)
gotMsgsOrdering[string(msg.Data)] = string(msg.OrderingKey)
msg.Ack()
wg.Done()
})
// Wait a little bit for the subscription creation to complete.
time.Sleep(time.Second)
for i := 0; i < 10; i++ {
data := fmt.Sprintf("data-%d", i)
wantMsgs[data] = data
order := fmt.Sprintf("order-%d", i)
wantMsgsOrdering[data] = order
if _, err := psconn.Publish(ctx, &pubsub.Message{Data: []byte(data), OrderingKey: order}); err != nil {
t.Errorf("failed to publish message: %v", err)
}
wg.Add(1)
}
wg.Wait()
cancel()
if diff := cmp.Diff(gotMsgs, wantMsgs); diff != "" {
t.Errorf("received unexpected messages (-want +got):\n%s", diff)
}
if diff := cmp.Diff(gotMsgsOrdering, wantMsgsOrdering); diff != "" {
t.Errorf("received unexpected message ordering keys (-want +got):\n%s", diff)
}
}
|
Test a full round trip of a message with ordering key
|
TestPublishReceiveRoundtripWithOrderingKey
|
go
|
cloudevents/sdk-go
|
protocol/pubsub/v2/internal/connection_test.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/pubsub/v2/internal/connection_test.go
|
Apache-2.0
|
func MetadataContextDecorator() func(context.Context, binding.Message) context.Context {
return func(ctx context.Context, m binding.Message) context.Context {
if msg, ok := m.(*Message); ok {
return context.WithValue(ctx, msgKey, MsgMetadata{
Sequence: msg.Msg.Sequence,
Redelivered: msg.Msg.Redelivered,
RedeliveryCount: msg.Msg.RedeliveryCount,
})
}
return ctx
}
}
|
MetadataContextDecorator returns an inbound context decorator which adds STAN message metadata to
the current context. If the inbound message is not a *stan.Message then this decorator is a no-op.
|
MetadataContextDecorator
|
go
|
cloudevents/sdk-go
|
protocol/stan/v2/context.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/stan/v2/context.go
|
Apache-2.0
|
func MessageMetadataFrom(ctx context.Context) (MsgMetadata, bool) {
if v, ok := ctx.Value(msgKey).(MsgMetadata); ok {
return v, true
}
return MsgMetadata{}, false
}
|
MessageMetadataFrom extracts the STAN message metadata from the provided ctx. The bool return parameter is true if
the metadata was set on the context, or false otherwise.
|
MessageMetadataFrom
|
go
|
cloudevents/sdk-go
|
protocol/stan/v2/context.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/stan/v2/context.go
|
Apache-2.0
|
func newSTANMessage(msg *stan.Msg) binding.Message {
m, _ := NewMessage(msg)
return m
}
|
newMessage wraps NewMessage and ignores any errors
|
newSTANMessage
|
go
|
cloudevents/sdk-go
|
protocol/stan/v2/context_test.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/stan/v2/context_test.go
|
Apache-2.0
|
func NewMessage(msg *stan.Msg, opts ...MessageOption) (*Message, error) {
m := &Message{Msg: msg}
err := m.applyOptions(opts...)
if err != nil {
return nil, err
}
return m, nil
}
|
NewMessage wraps a *nats.Msg in a binding.Message.
The returned message *can* be read several times safely
|
NewMessage
|
go
|
cloudevents/sdk-go
|
protocol/stan/v2/message.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/stan/v2/message.go
|
Apache-2.0
|
func StanOptions(opts ...stan.Option) []stan.Option {
return opts
}
|
StanOptions is a helper function to group a variadic stan.Option into []stan.Option
|
StanOptions
|
go
|
cloudevents/sdk-go
|
protocol/stan/v2/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/stan/v2/options.go
|
Apache-2.0
|
func WithQueueSubscriber(queue string) ConsumerOption {
return func(p *Consumer) error {
if queue == "" {
return ErrInvalidQueueName
}
p.Subscriber = &QueueSubscriber{queue}
return nil
}
}
|
WithQueueSubscriber configures the transport to create a queue subscription instead of a standard subscription.
|
WithQueueSubscriber
|
go
|
cloudevents/sdk-go
|
protocol/stan/v2/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/stan/v2/options.go
|
Apache-2.0
|
func WithSubscriptionOptions(opts ...stan.SubscriptionOption) ConsumerOption {
return func(p *Consumer) error {
p.subscriptionOptions = opts
return nil
}
}
|
WithSubscriptionOptions sets options to configure the STAN subscription.
|
WithSubscriptionOptions
|
go
|
cloudevents/sdk-go
|
protocol/stan/v2/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/stan/v2/options.go
|
Apache-2.0
|
func WithUnsubscribeOnClose() ConsumerOption {
return func(p *Consumer) error {
p.UnsubscribeOnClose = true
return nil
}
}
|
WithUnsubscribeOnClose configures the Consumer to unsubscribe when OpenInbound context is cancelled or when Consumer.Close() is invoked.
This causes durable subscriptions to be forgotten by the STAN service and recreated durable subscriptions will
act like they are newly created.
|
WithUnsubscribeOnClose
|
go
|
cloudevents/sdk-go
|
protocol/stan/v2/options.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/stan/v2/options.go
|
Apache-2.0
|
func NewProtocol(clusterID, clientID, sendSubject, receiveSubject string, stanOpts []stan.Option, opts ...ProtocolOption) (*Protocol, error) {
conn, err := stan.Connect(clusterID, clientID, stanOpts...)
if err != nil {
return nil, err
}
p, err := NewProtocolFromConn(conn, sendSubject, receiveSubject, opts...)
if err != nil {
if err2 := conn.Close(); err2 != nil {
return nil, fmt.Errorf("failed to close conn: %s, when recovering from err: %w", err2, err)
}
return nil, err
}
p.connOwned = true
return p, nil
}
|
NewProtocol creates a new STAN protocol including managing the lifecycle of the connection
|
NewProtocol
|
go
|
cloudevents/sdk-go
|
protocol/stan/v2/protocol.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/stan/v2/protocol.go
|
Apache-2.0
|
func NewProtocolFromConn(conn stan.Conn, sendSubject, receiveSubject string, opts ...ProtocolOption) (*Protocol, error) {
var err error
p := &Protocol{
Conn: conn,
}
if err := p.applyOptions(opts...); err != nil {
return nil, err
}
if p.Consumer, err = NewConsumerFromConn(conn, receiveSubject, p.consumerOptions...); err != nil {
return nil, err
}
if p.Sender, err = NewSenderFromConn(conn, sendSubject, p.senderOptions...); err != nil {
return nil, err
}
return p, nil
}
|
NewProtocolFromConn creates a new STAN protocol but leaves managing the lifecycle of the connection up to the caller
|
NewProtocolFromConn
|
go
|
cloudevents/sdk-go
|
protocol/stan/v2/protocol.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/stan/v2/protocol.go
|
Apache-2.0
|
func (r *Receiver) MsgHandler(msg *stan.Msg) {
m, err := NewMessage(msg, r.messageOpts...)
r.incoming <- msgErr{msg: m, err: err}
}
|
MsgHandler implements stan.MsgHandler
This function is passed to the call to stan.Conn.Subscribe so that we can stream messages to be delivered
via Receive()
|
MsgHandler
|
go
|
cloudevents/sdk-go
|
protocol/stan/v2/receiver.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/stan/v2/receiver.go
|
Apache-2.0
|
func (r *Receiver) Receive(ctx context.Context) (binding.Message, error) {
select {
case msgErr, ok := <-r.incoming:
if !ok {
return nil, io.EOF
}
return msgErr.msg, msgErr.err
case <-ctx.Done():
return nil, io.EOF
}
}
|
Receive implements Receiver.Receive
This should probably not be invoked directly by applications or library code, but instead invoked via
Protocol.Receive
|
Receive
|
go
|
cloudevents/sdk-go
|
protocol/stan/v2/receiver.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/stan/v2/receiver.go
|
Apache-2.0
|
func (c *Consumer) Close(_ context.Context) error {
// Before closing, let's be sure OpenInbound completes
// We send a signal to close and then we lock on subMtx in order
// to wait OpenInbound to finish draining the queue
c.internalClose <- struct{}{}
c.subMtx.Lock()
defer c.subMtx.Unlock()
if c.connOwned {
return c.Conn.Close()
}
close(c.internalClose)
return nil
}
|
Close implements Closer.Close.
This method only closes the connection if the Consumer opened it. Subscriptions are closed/unsubscribed dependent
on the UnsubscribeOnClose field.
|
Close
|
go
|
cloudevents/sdk-go
|
protocol/stan/v2/receiver.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/stan/v2/receiver.go
|
Apache-2.0
|
func (c *Consumer) createReceiverOptions() ([]ReceiverOption, error) {
// receivers need to know whether or not the subscription is configured in ManualAck-mode,
// as such we must build the options in the same way as stan does since their API doesn't
// expose this information
subOpts, err := c.subOptionsLazy()
if err != nil {
return nil, err
}
opts := make([]ReceiverOption, 0)
if subOpts.ManualAcks {
opts = append(opts, WithMessageOptions(WithManualAcks()))
}
return opts, nil
}
|
createReceiverOptions builds an array of ReceiverOption used to configure the receiver.
|
createReceiverOptions
|
go
|
cloudevents/sdk-go
|
protocol/stan/v2/receiver.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/stan/v2/receiver.go
|
Apache-2.0
|
func (c *Consumer) subOptionsLazy() (*stan.SubscriptionOptions, error) {
if c.appliedSubOpts != nil {
return c.appliedSubOpts, nil
}
subOpts := stan.DefaultSubscriptionOptions
for _, fn := range c.subscriptionOptions {
err := fn(&subOpts)
if err != nil {
return nil, err
}
}
c.appliedSubOpts = &subOpts
return c.appliedSubOpts, nil
}
|
subOptionsLazy calculates the SubscriptionOptions based on an array of SubscriptionOption and stores the result on
the struct to prevent repeated calculations
|
subOptionsLazy
|
go
|
cloudevents/sdk-go
|
protocol/stan/v2/receiver.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/stan/v2/receiver.go
|
Apache-2.0
|
func NewSender(clusterID, clientID, subject string, stanOpts []stan.Option, opts ...SenderOption) (*Sender, error) {
conn, err := stan.Connect(clusterID, clientID, stanOpts...)
if err != nil {
return nil, err
}
s, err := NewSenderFromConn(conn, subject, opts...)
if err != nil {
if err2 := conn.Close(); err2 != nil {
return nil, fmt.Errorf("failed to close conn: %s, when recovering from err: %w", err2, err)
}
return nil, err
}
s.connOwned = true
return s, nil
}
|
NewSender creates a new protocol.Sender responsible for opening and closing the STAN connection
|
NewSender
|
go
|
cloudevents/sdk-go
|
protocol/stan/v2/sender.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/stan/v2/sender.go
|
Apache-2.0
|
func NewSenderFromConn(conn stan.Conn, subject string, opts ...SenderOption) (*Sender, error) {
s := &Sender{
Conn: conn,
Subject: subject,
}
err := s.applyOptions(opts...)
if err != nil {
return nil, err
}
return s, nil
}
|
NewSenderFromConn creates a new protocol.Sender which leaves responsibility for opening and closing the STAN
connection to the caller
|
NewSenderFromConn
|
go
|
cloudevents/sdk-go
|
protocol/stan/v2/sender.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/stan/v2/sender.go
|
Apache-2.0
|
func (s *Sender) Close(_ context.Context) error {
if s.connOwned {
return s.Conn.Close()
}
return nil
}
|
Close implements Closer.Close
This method only closes the connection if the Sender opened it
|
Close
|
go
|
cloudevents/sdk-go
|
protocol/stan/v2/sender.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/stan/v2/sender.go
|
Apache-2.0
|
func WriteMsg(ctx context.Context, m binding.Message, writer io.ReaderFrom, transformers ...binding.Transformer) error {
structuredWriter := &stanMessageWriter{writer}
_, err := binding.Write(
ctx,
m,
structuredWriter,
nil,
transformers...,
)
return err
}
|
WriteMsg fills the provided writer with the bindings.Message m.
Using context you can tweak the encoding processing (more details on binding.Write documentation).
|
WriteMsg
|
go
|
cloudevents/sdk-go
|
protocol/stan/v2/write_message.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/stan/v2/write_message.go
|
Apache-2.0
|
func Dial(ctx context.Context, u string, opts *websocket.DialOptions) (*ClientProtocol, error) {
if opts == nil {
opts = &websocket.DialOptions{}
}
opts.Subprotocols = SupportedSubprotocols
c, _, err := websocket.Dial(ctx, u, opts)
if err != nil {
return nil, err
}
p, err := NewClientProtocol(c)
if err != nil {
return nil, err
}
p.connOwned = true
return p, nil
}
|
Dial wraps websocket.Dial and creates the ClientProtocol.
|
Dial
|
go
|
cloudevents/sdk-go
|
protocol/ws/v2/client_protocol.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/ws/v2/client_protocol.go
|
Apache-2.0
|
func NewClientProtocol(c *websocket.Conn) (*ClientProtocol, error) {
f, messageType, err := resolveFormat(c.Subprotocol())
if err != nil {
return nil, err
}
return &ClientProtocol{
conn: c,
format: f,
messageType: messageType,
connOwned: false,
}, nil
}
|
NewClientProtocol wraps a websocket.Conn in a type that implements protocol.Receiver, protocol.Sender and protocol.Closer.
Look at ClientProtocol for more details.
|
NewClientProtocol
|
go
|
cloudevents/sdk-go
|
protocol/ws/v2/client_protocol.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/ws/v2/client_protocol.go
|
Apache-2.0
|
func (c *ClientProtocol) UnsafeReceive(ctx context.Context) (binding.Message, error) {
messageType, reader, err := c.conn.Reader(ctx)
if errors.Is(err, io.EOF) || errors.Is(err, websocket.CloseError{}) || (ctx.Err() != nil && errors.Is(err, ctx.Err())) {
return nil, io.EOF
}
if err != nil {
return nil, err
}
if messageType != c.messageType {
// We need to consume the stream, otherwise it won't be possible to consume the stream
consumeStream(reader)
return nil, fmt.Errorf("wrong message type: %s, expected %s", messageType, c.messageType)
}
return utils.NewStructuredMessage(c.format, reader), nil
}
|
UnsafeReceive is like Receive, except it doesn't guard from multiple invocations
from different goroutines.
|
UnsafeReceive
|
go
|
cloudevents/sdk-go
|
protocol/ws/v2/client_protocol.go
|
https://github.com/cloudevents/sdk-go/blob/master/protocol/ws/v2/client_protocol.go
|
Apache-2.0
|
func sampleConfig() (server, node string, opts []ceamqp.Option) {
env := os.Getenv("AMQP_URL")
if env == "" {
env = "/test"
}
u, err := url.Parse(env)
if err != nil {
log.Fatal(err)
}
if u.User != nil {
user := u.User.Username()
pass, _ := u.User.Password()
opts = append(opts, ceamqp.WithConnOpt(amqp.ConnSASLPlain(user, pass)))
}
return env, strings.TrimPrefix(u.Path, "/"), opts
}
|
Parse AMQP_URL env variable. Return server URL, AMQP node (from path) and SASLPlain
option if user/pass are present.
|
sampleConfig
|
go
|
cloudevents/sdk-go
|
samples/amqp/receiver/main.go
|
https://github.com/cloudevents/sdk-go/blob/master/samples/amqp/receiver/main.go
|
Apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.