code
stringlengths
22
960k
docstring
stringlengths
20
17.8k
func_name
stringlengths
1
245
language
stringclasses
1 value
repo
stringlengths
6
57
path
stringlengths
4
226
url
stringlengths
43
277
license
stringclasses
7 values
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 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 main() { saramaConfig := sarama.NewConfig() saramaConfig.Version = sarama.V2_0_0_0 ctx := context.Background() // With NewProtocol you can use the same client both to send and receive. protocol, err := kafka_sarama.NewProtocol([]string{"127.0.0.1:9092"}, saramaConfig, "output-topic", "input-topic") if err != nil { log.Fatalf("failed to create protocol: %s", err.Error()) } defer protocol.Close(context.Background()) // Pipe all incoming message, eventually transforming them go func() { for { // Blocking call to wait for new messages from protocol inputMessage, err := protocol.Receive(ctx) if err != nil { if err == io.EOF { return // Context closed and/or receiver closed } log.Printf("Error while receiving a inputMessage: %s", err.Error()) continue } defer inputMessage.Finish(nil) outputMessage := inputMessage // If encoding is unknown, then the inputMessage is a non cloudevent // and we need to convert it if inputMessage.ReadEncoding() == binding.EncodingUnknown { // We need to get the inputMessage internals // Because the message could be wrapped by the protocol implementation // we need to unwrap it and then cast to the message representation // specific to the protocol kafkaMessage := binding.UnwrapMessage(inputMessage).(*kafka_sarama.Message) // Now let's create a new event event := cloudevents.NewEvent() event.SetID(uuid.New().String()) event.SetTime(time.Now()) event.SetType("generated.examples") event.SetSource("https://github.com/cloudevents/sdk-go/samples/kafka/message-handle-non-cloudevents") err = event.SetData(kafkaMessage.ContentType, kafkaMessage.Value) if err != nil { log.Printf("Error while setting the event data: %s", err.Error()) continue } outputMessage = binding.ToMessage(&event) } // Send outputMessage directly to output-topic err = protocol.Send(ctx, outputMessage) if err != nil { log.Printf("Error while forwarding the inputMessage: %s", err.Error()) } } }() // Start the Kafka Consumer Group invoking OpenInbound() go func() { if err := protocol.OpenInbound(ctx); err != nil { log.Printf("failed to StartHTTPReceiver, %v", err) } }() <-ctx.Done() }
In order to run this test, look at documentation in https://github.com/cloudevents/sdk-go/blob/main/samples/kafka/README.md
main
go
cloudevents/sdk-go
samples/kafka/message-handle-non-cloudevents/main.go
https://github.com/cloudevents/sdk-go/blob/master/samples/kafka/message-handle-non-cloudevents/main.go
Apache-2.0
func buildSubject(base string, i int) string { n := "even" if i%2 != 0 { n = "odd" } return fmt.Sprintf("%s.%s.%d", base, n, i) }
buildSubject using base and message index. `<base>.[odd|even].<index>`
buildSubject
go
cloudevents/sdk-go
samples/nats_jetstream/v3/sender/main.go
https://github.com/cloudevents/sdk-go/blob/master/samples/nats_jetstream/v3/sender/main.go
Apache-2.0
func CESQLParserLexerInit() { staticData := &cesqlparserlexerLexerStaticData staticData.once.Do(cesqlparserlexerLexerInit) }
CESQLParserLexerInit initializes any static state used to implement CESQLParserLexer. By default the static state used to implement the lexer is lazily initialized during the first call to NewCESQLParserLexer(). You can call this function if you wish to initialize the static state ahead of time.
CESQLParserLexerInit
go
cloudevents/sdk-go
sql/v2/gen/cesqlparser_lexer.go
https://github.com/cloudevents/sdk-go/blob/master/sql/v2/gen/cesqlparser_lexer.go
Apache-2.0
func NewCESQLParserLexer(input antlr.CharStream) *CESQLParserLexer { CESQLParserLexerInit() l := new(CESQLParserLexer) l.BaseLexer = antlr.NewBaseLexer(input) staticData := &cesqlparserlexerLexerStaticData l.Interpreter = antlr.NewLexerATNSimulator(l, staticData.atn, staticData.decisionToDFA, staticData.predictionContextCache) l.channelNames = staticData.channelNames l.modeNames = staticData.modeNames l.RuleNames = staticData.ruleNames l.LiteralNames = staticData.literalNames l.SymbolicNames = staticData.symbolicNames l.GrammarFileName = "CESQLParser.g4" // TODO: l.EOF = antlr.TokenEOF return l }
NewCESQLParserLexer produces a new lexer instance for the optional input antlr.CharStream.
NewCESQLParserLexer
go
cloudevents/sdk-go
sql/v2/gen/cesqlparser_lexer.go
https://github.com/cloudevents/sdk-go/blob/master/sql/v2/gen/cesqlparser_lexer.go
Apache-2.0
func CESQLParserParserInit() { staticData := &cesqlparserParserStaticData staticData.once.Do(cesqlparserParserInit) }
CESQLParserParserInit initializes any static state used to implement CESQLParserParser. By default the static state used to implement the parser is lazily initialized during the first call to NewCESQLParserParser(). You can call this function if you wish to initialize the static state ahead of time.
CESQLParserParserInit
go
cloudevents/sdk-go
sql/v2/gen/cesqlparser_parser.go
https://github.com/cloudevents/sdk-go/blob/master/sql/v2/gen/cesqlparser_parser.go
Apache-2.0
func NewCESQLParserParser(input antlr.TokenStream) *CESQLParserParser { CESQLParserParserInit() this := new(CESQLParserParser) this.BaseParser = antlr.NewBaseParser(input) staticData := &cesqlparserParserStaticData this.Interpreter = antlr.NewParserATNSimulator(this, staticData.atn, staticData.decisionToDFA, staticData.predictionContextCache) this.RuleNames = staticData.ruleNames this.LiteralNames = staticData.literalNames this.SymbolicNames = staticData.symbolicNames this.GrammarFileName = "CESQLParser.g4" return this }
NewCESQLParserParser produces a new parser instance for the optional input antlr.TokenStream.
NewCESQLParserParser
go
cloudevents/sdk-go
sql/v2/gen/cesqlparser_parser.go
https://github.com/cloudevents/sdk-go/blob/master/sql/v2/gen/cesqlparser_parser.go
Apache-2.0
func NewCaseChangingStream(in antlr.CharStream, upper bool) *CaseChangingStream { return &CaseChangingStream{in, upper} }
NewCaseChangingStream returns a new CaseChangingStream that forces all tokens read from the underlying stream to be either upper case or lower case based on the upper argument.
NewCaseChangingStream
go
cloudevents/sdk-go
sql/v2/parser/case_changing_stream.go
https://github.com/cloudevents/sdk-go/blob/master/sql/v2/parser/case_changing_stream.go
Apache-2.0
func (is *CaseChangingStream) LA(offset int) int { in := is.CharStream.LA(offset) if in < 0 { // Such as antlr.TokenEOF which is -1 return in } if is.upper { return int(unicode.ToUpper(rune(in))) } return int(unicode.ToLower(rune(in))) }
LA gets the value of the symbol at offset from the current position from the underlying CharStream and converts it to either upper case or lower case.
LA
go
cloudevents/sdk-go
sql/v2/parser/case_changing_stream.go
https://github.com/cloudevents/sdk-go/blob/master/sql/v2/parser/case_changing_stream.go
Apache-2.0
func benchmarkClient(cases []e2e.BenchmarkCase, requestFactory func([]byte) *nethttp.Request) e2e.BenchmarkResults { var results e2e.BenchmarkResults random := rand.New(rand.NewSource(time.Now().Unix())) for _, c := range cases { fmt.Printf("%+v\n", c) //_, mockedReceiverProtocol, mockedReceiverTransport := MockedClient() senderClients := make([]cloudevents.Client, c.OutputSenders) for i := 0; i < c.OutputSenders; i++ { senderClients[i], _ = MockedClient() } //mockedReceiverTransport.SetDelivery(dispatchReceiver(senderClients, c.OutputSenders)) buffer := make([]byte, c.PayloadSize) fillRandom(buffer, random) runtime.GC() result := testing.Benchmark(func(b *testing.B) { b.SetParallelism(c.Parallelism) b.RunParallel(func(pb *testing.PB) { for pb.Next() { //w := httptest.NewRecorder() //mockedReceiverProtocol.ServeHTTP(w, requestFactory(buffer)) } }) }) results = append(results, e2e.BenchmarkResult{BenchmarkCase: c, BenchmarkResult: result}) runtime.GC() } return results }
type benchDelivery struct { fn transport.DeliveryFunc } func (b *benchDelivery) Delivery(ctx context.Context, e event.Event) (*event.Event, transport.Result) { return b.fn(ctx, e) } func dispatchReceiver(clients []cloudevents.Client, outputSenders int) transport.Delivery { return &benchDelivery{fn: func(ctx context.Context, e cloudevents.Event) (*cloudevents.Event, error) { var wg sync.WaitGroup for i := 0; i < outputSenders; i++ { wg.Add(1) go func(client cloudevents.Client) { _ = client.Send(ctx, e) wg.Done() }(clients[i]) } wg.Wait() return nil, nil }} }
benchmarkClient
go
cloudevents/sdk-go
test/benchmark/e2e/http/main.go
https://github.com/cloudevents/sdk-go/blob/master/test/benchmark/e2e/http/main.go
Apache-2.0
func AlwaysThen(then time.Time) client.EventDefaulter { return func(ctx context.Context, event cloudevents.Event) cloudevents.Event { if event.Context != nil { _ = event.Context.SetTime(then) } return event } }
Loopback Test: Obj -> Send -> Wire Format -> Receive -> Got Given: ^ ^ ^==Want Obj is an event of a version. Client is a set to binary or
AlwaysThen
go
cloudevents/sdk-go
test/integration/http/loopback.go
https://github.com/cloudevents/sdk-go/blob/master/test/integration/http/loopback.go
Apache-2.0
func printTap(t *testing.T, tap *tapHandler, testID string) { if r, ok := tap.req[testID]; ok { t.Log("tap request ", r.URI, r.Method) if r.ContentLength > 0 { t.Log(" .body: ", r.Body) } else { t.Log("tap request had no body.") } if len(r.Header) > 0 { for h, vs := range r.Header { for _, v := range vs { t.Logf(" .header %s: %s", h, v) } } } else { t.Log("tap request had no headers.") } } if r, ok := tap.resp[testID]; ok { t.Log("tap response.status: ", r.Status) if r.ContentLength > 0 { t.Log(" .body: ", r.Body) } else { t.Log("tap response had no body.") } if len(r.Header) > 0 { for h, vs := range r.Header { for _, v := range vs { t.Logf(" .header %s: %s", h, v) } } } else { t.Log("tap response had no headers.") } } }
To help with debug, if needed.
printTap
go
cloudevents/sdk-go
test/integration/http/tap_handler.go
https://github.com/cloudevents/sdk-go/blob/master/test/integration/http/tap_handler.go
Apache-2.0
func protocolFactory(sendTopic string, receiveTopic []string, ) (*confluent.Protocol, error) { var p *confluent.Protocol var err error if receiveTopic != nil { p, err = confluent.New(confluent.WithConfigMap(&kafka.ConfigMap{ "bootstrap.servers": BOOTSTRAP_SERVER, "group.id": TEST_GROUP_ID, "auto.offset.reset": "earliest", "enable.auto.commit": "true", }), confluent.WithReceiverTopics(receiveTopic)) } if sendTopic != "" { p, err = confluent.New(confluent.WithConfigMap(&kafka.ConfigMap{ "bootstrap.servers": BOOTSTRAP_SERVER, "go.delivery.reports": false, }), confluent.WithSenderTopic(sendTopic)) } return p, err }
To start a local environment for testing: Option 1: Start it on port 9092 docker run --rm --net=host -p 9092:9092 confluentinc/confluent-local Option 2: Start it on port 9192 docker run --rm \ --name broker \ --hostname broker \ -p 9192:9192 \ -e KAFKA_ADVERTISED_LISTENERS='PLAINTEXT://broker:29192,PLAINTEXT_HOST://localhost:9192' \ -e KAFKA_CONTROLLER_QUORUM_VOTERS='1@broker:29193' \ -e KAFKA_LISTENERS='PLAINTEXT://broker:29192,CONTROLLER://broker:29193,PLAINTEXT_HOST://0.0.0.0:9192' \ confluentinc/confluent-local:latest
protocolFactory
go
cloudevents/sdk-go
test/integration/kafka_confluent/kafka_test.go
https://github.com/cloudevents/sdk-go/blob/master/test/integration/kafka_confluent/kafka_test.go
Apache-2.0
func protocolFactory(ctx context.Context, t testing.TB, topicName string) *mqtt_paho.Protocol { broker := "127.0.0.1:1883" conn, err := net.Dial("tcp", broker) require.NoError(t, err) config := &paho.ClientConfig{ Conn: conn, } connOpt := &paho.Connect{ KeepAlive: 30, CleanStart: true, } publishOpt := &paho.Publish{ Topic: topicName, QoS: 0, } subscribeOpt := &paho.Subscribe{ Subscriptions: []paho.SubscribeOptions{ { Topic: topicName, QoS: 0, }, }, } p, err := mqtt_paho.New(ctx, config, mqtt_paho.WithConnect(connOpt), mqtt_paho.WithPublish(publishOpt), mqtt_paho.WithSubscribe(subscribeOpt)) require.NoError(t, err) return p }
To start a local environment for testing: docker run -it --rm --name mosquitto -p 1883:1883 eclipse-mosquitto:2.0 mosquitto -c /mosquitto-no-auth.conf the protocolFactory will generate a unique connection clientId when it be invoked
protocolFactory
go
cloudevents/sdk-go
test/integration/mqtt_paho/mqtt_test.go
https://github.com/cloudevents/sdk-go/blob/master/test/integration/mqtt_paho/mqtt_test.go
Apache-2.0
func UseFormatForEvent(ctx context.Context, f format.Format) context.Context { return context.WithValue(ctx, formatEventStructured, f) }
UseFormatForEvent configures which format to use when marshalling the event to structured mode
UseFormatForEvent
go
cloudevents/sdk-go
v2/binding/event_message.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/event_message.go
Apache-2.0
func WithFinish(m Message, finish func(error)) Message { return &finishMessage{Message: m, finish: finish} }
WithFinish returns a wrapper for m that calls finish() and m.Finish() in its Finish(). Allows code to be notified when a message is Finished.
WithFinish
go
cloudevents/sdk-go
v2/binding/finish_message.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/finish_message.go
Apache-2.0
func ToEvent(ctx context.Context, message MessageReader, transformers ...Transformer) (*event.Event, error) { if message == nil { return nil, nil } messageEncoding := message.ReadEncoding() if messageEncoding == EncodingEvent { m := message for m != nil { switch mt := m.(type) { case *EventMessage: e := (*event.Event)(mt) return e, Transformers(transformers).Transform(mt, (*messageToEventBuilder)(e)) case MessageWrapper: m = mt.GetWrappedMessage() default: break } } return nil, ErrCannotConvertToEvent } e := event.New() encoder := (*messageToEventBuilder)(&e) _, err := DirectWrite( context.Background(), message, encoder, encoder, ) if err != nil { return nil, err } return &e, Transformers(transformers).Transform((*EventMessage)(&e), encoder) }
ToEvent translates a Message with a valid Structured or Binary representation to an Event. This function returns the Event generated from the Message and the original encoding of the message or an error that points the conversion error. transformers can be nil and this function guarantees that they are invoked only once during the encoding process.
ToEvent
go
cloudevents/sdk-go
v2/binding/to_event.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/to_event.go
Apache-2.0
func ToEvents(ctx context.Context, message MessageReader, body io.Reader) ([]event.Event, error) { messageEncoding := message.ReadEncoding() if messageEncoding != EncodingBatch { return nil, ErrCannotConvertToEvents } // Since Format doesn't support batch Marshalling, and we know it's structured batch json, we'll go direct to the // json.UnMarshall(), since that is the best way to support batch operations for now. var events []event.Event return events, json.NewDecoder(body).Decode(&events) }
ToEvents translates a Batch Message and corresponding Reader data to a slice of Events. This function returns the Events generated from the body data, or an error that points to the conversion issue.
ToEvents
go
cloudevents/sdk-go
v2/binding/to_event.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/to_event.go
Apache-2.0
func DirectWrite( ctx context.Context, message MessageReader, structuredWriter StructuredWriter, binaryWriter BinaryWriter, transformers ...Transformer, ) (Encoding, error) { if structuredWriter != nil && len(transformers) == 0 && !GetOrDefaultFromCtx(ctx, skipDirectStructuredEncoding, false).(bool) { if err := message.ReadStructured(ctx, structuredWriter); err == nil { return EncodingStructured, nil } else if err != ErrNotStructured { return EncodingStructured, err } } if binaryWriter != nil && !GetOrDefaultFromCtx(ctx, skipDirectBinaryEncoding, false).(bool) && message.ReadEncoding() == EncodingBinary { return EncodingBinary, writeBinaryWithTransformer(ctx, message, binaryWriter, transformers) } return EncodingUnknown, ErrUnknownEncoding }
DirectWrite invokes the encoders. structuredWriter and binaryWriter could be nil if the protocol doesn't support it. transformers can be nil and this function guarantees that they are invoked only once during the encoding process. This function MUST be invoked only if message.ReadEncoding() == EncodingBinary or message.ReadEncoding() == EncodingStructured Returns: * EncodingStructured, nil if message is correctly encoded in structured encoding * EncodingBinary, nil if message is correctly encoded in binary encoding * EncodingStructured, err if message was structured but error happened during the encoding * EncodingBinary, err if message was binary but error happened during the encoding * EncodingUnknown, ErrUnknownEncoding if message is not a structured or a binary Message
DirectWrite
go
cloudevents/sdk-go
v2/binding/write.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/write.go
Apache-2.0
func Write( ctx context.Context, message MessageReader, structuredWriter StructuredWriter, binaryWriter BinaryWriter, transformers ...Transformer, ) (Encoding, error) { enc := message.ReadEncoding() var err error // Skip direct encoding if the event is an event message if enc != EncodingEvent { enc, err = DirectWrite(ctx, message, structuredWriter, binaryWriter, transformers...) if enc != EncodingUnknown { // Message directly encoded, nothing else to do here return enc, err } } var e *event.Event e, err = ToEvent(ctx, message, transformers...) if err != nil { return enc, err } message = (*EventMessage)(e) if GetOrDefaultFromCtx(ctx, preferredEventEncoding, EncodingBinary).(Encoding) == EncodingStructured { if structuredWriter != nil { return EncodingStructured, message.ReadStructured(ctx, structuredWriter) } if binaryWriter != nil { return EncodingBinary, writeBinary(ctx, message, binaryWriter) } } else { if binaryWriter != nil { return EncodingBinary, writeBinary(ctx, message, binaryWriter) } if structuredWriter != nil { return EncodingStructured, message.ReadStructured(ctx, structuredWriter) } } return EncodingUnknown, ErrUnknownEncoding }
Write executes the full algorithm to encode a Message using transformers: 1. It first tries direct encoding using DirectWrite 2. If no direct encoding is possible, it uses ToEvent to generate an Event representation 3. From the Event, the message is encoded back to the provided structured or binary encoders You can tweak the encoding process using the context decorators WithForceStructured, WithForceStructured, etc. transformers can be nil and this function guarantees that they are invoked only once during the encoding process. Returns: * EncodingStructured, nil if message is correctly encoded in structured encoding * EncodingBinary, nil if message is correctly encoded in binary encoding * EncodingUnknown, ErrUnknownEncoding if message.ReadEncoding() == EncodingUnknown * _, err if error happened during the encoding
Write
go
cloudevents/sdk-go
v2/binding/write.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/write.go
Apache-2.0
func WithSkipDirectStructuredEncoding(ctx context.Context, skip bool) context.Context { return context.WithValue(ctx, skipDirectStructuredEncoding, skip) }
WithSkipDirectStructuredEncoding skips direct structured to structured encoding during the encoding process
WithSkipDirectStructuredEncoding
go
cloudevents/sdk-go
v2/binding/write.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/write.go
Apache-2.0
func WithSkipDirectBinaryEncoding(ctx context.Context, skip bool) context.Context { return context.WithValue(ctx, skipDirectBinaryEncoding, skip) }
WithSkipDirectBinaryEncoding skips direct binary to binary encoding during the encoding process
WithSkipDirectBinaryEncoding
go
cloudevents/sdk-go
v2/binding/write.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/write.go
Apache-2.0
func WithPreferredEventEncoding(ctx context.Context, enc Encoding) context.Context { return context.WithValue(ctx, preferredEventEncoding, enc) }
WithPreferredEventEncoding defines the preferred encoding from event to message during the encoding process
WithPreferredEventEncoding
go
cloudevents/sdk-go
v2/binding/write.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/write.go
Apache-2.0
func WithForceStructured(ctx context.Context) context.Context { return context.WithValue(context.WithValue(ctx, preferredEventEncoding, EncodingStructured), skipDirectBinaryEncoding, true) }
WithForceStructured forces structured encoding during the encoding process
WithForceStructured
go
cloudevents/sdk-go
v2/binding/write.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/write.go
Apache-2.0
func WithForceBinary(ctx context.Context) context.Context { return context.WithValue(context.WithValue(ctx, preferredEventEncoding, EncodingBinary), skipDirectStructuredEncoding, true) }
WithForceBinary forces binary encoding during the encoding process
WithForceBinary
go
cloudevents/sdk-go
v2/binding/write.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/write.go
Apache-2.0
func GetOrDefaultFromCtx(ctx context.Context, key interface{}, def interface{}) interface{} { if val := ctx.Value(key); val != nil { return val } else { return def } }
GetOrDefaultFromCtx gets a configuration value from the provided context
GetOrDefaultFromCtx
go
cloudevents/sdk-go
v2/binding/write.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/write.go
Apache-2.0
func WithAcksBeforeFinish(m binding.Message, requiredAcks int) binding.Message { return &acksMessage{Message: m, requiredAcks: int32(requiredAcks)} }
WithAcksBeforeFinish returns a wrapper for m that calls m.Finish() only after the specified number of acks are received. Use it when you need to dispatch a Message using several Sender instances
WithAcksBeforeFinish
go
cloudevents/sdk-go
v2/binding/buffering/acks_before_finish_message.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/buffering/acks_before_finish_message.go
Apache-2.0
func BufferMessage(ctx context.Context, m binding.Message, transformers ...binding.Transformer) (binding.Message, error) { result, err := CopyMessage(ctx, m, transformers...) if err != nil { return nil, err } return binding.WithFinish(result, func(err error) { _ = m.Finish(err) }), nil }
BufferMessage works the same as CopyMessage and it also bounds the original Message lifecycle to the newly created message: calling Finish() on the returned message calls m.Finish(). transformers can be nil and this function guarantees that they are invoked only once during the encoding process.
BufferMessage
go
cloudevents/sdk-go
v2/binding/buffering/copy_message.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/buffering/copy_message.go
Apache-2.0
func CopyMessage(ctx context.Context, m binding.Message, transformers ...binding.Transformer) (binding.Message, error) { originalMessageEncoding := m.ReadEncoding() if originalMessageEncoding == binding.EncodingUnknown { return nil, binding.ErrUnknownEncoding } if originalMessageEncoding == binding.EncodingEvent { e, err := binding.ToEvent(ctx, m, transformers...) if err != nil { return nil, err } return (*binding.EventMessage)(e), nil } sm := structBufferedMessage{} bm := binaryBufferedMessage{} encoding, err := binding.DirectWrite(ctx, m, &sm, &bm, transformers...) switch encoding { case binding.EncodingStructured: return &sm, err case binding.EncodingBinary: return &bm, err default: e, err := binding.ToEvent(ctx, m, transformers...) if err != nil { return nil, err } return (*binding.EventMessage)(e), nil } }
CopyMessage reads m once and creates an in-memory copy depending on the encoding of m. The returned copy is not dependent on any transport and can be visited many times. When the copy can be forgot, the copied message must be finished with Finish() message to release the memory. transformers can be nil and this function guarantees that they are invoked only once during the encoding process.
CopyMessage
go
cloudevents/sdk-go
v2/binding/buffering/copy_message.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/buffering/copy_message.go
Apache-2.0
func (m *structBufferedMessage) ReadStructured(ctx context.Context, enc binding.StructuredWriter) error { return enc.SetStructuredEvent(ctx, m.Format, bytes.NewReader(m.Bytes.B)) }
Structured copies structured data to a StructuredWriter
ReadStructured
go
cloudevents/sdk-go
v2/binding/buffering/struct_buffer_message.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/buffering/struct_buffer_message.go
Apache-2.0
func (jb jsonBatchFmt) Marshal(e *event.Event) ([]byte, error) { return nil, errors.New("not supported for batch events") }
Marshal will return an error for jsonBatchFmt since the Format interface doesn't support batch Marshalling, and we know it's structured batch json, we'll go direct to the json.UnMarshall() (see `ToEvents()`) since that is the best way to support batch operations for now.
Marshal
go
cloudevents/sdk-go
v2/binding/format/format.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/format/format.go
Apache-2.0
func Lookup(contentType string) Format { i := strings.IndexRune(contentType, ';') if i == -1 { i = len(contentType) } contentType = strings.TrimSpace(strings.ToLower(contentType[0:i])) return formats[contentType] }
Lookup returns the format for contentType, or nil if not found.
Lookup
go
cloudevents/sdk-go
v2/binding/format/format.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/format/format.go
Apache-2.0
func Marshal(mediaType string, e *event.Event) ([]byte, error) { if f := formats[mediaType]; f != nil { return f.Marshal(e) } return nil, unknown(mediaType) }
Marshal an event to bytes using the mediaType event format.
Marshal
go
cloudevents/sdk-go
v2/binding/format/format.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/format/format.go
Apache-2.0
func Unmarshal(mediaType string, b []byte, e *event.Event) error { if f := formats[mediaType]; f != nil { return f.Unmarshal(b, e) } return unknown(mediaType) }
Unmarshal bytes to an event using the mediaType event format.
Unmarshal
go
cloudevents/sdk-go
v2/binding/format/format.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/format/format.go
Apache-2.0
func WithPrefixMatchExact(attributeNameMatchMapper func(string) string, prefix string) *Versions { attr := func(name string, kind Kind) *attribute { return &attribute{accessor: acc[kind], name: name} } vs := &Versions{ m: map[string]Version{}, prefix: prefix, all: []Version{ newMatchExactVersionVersion(prefix, attributeNameMatchMapper, event.EventContextV1{}.AsV1(), func(c event.EventContextConverter) event.EventContext { return c.AsV1() }, attr("id", ID), attr("source", Source), attr("specversion", SpecVersion), attr("type", Type), attr("datacontenttype", DataContentType), attr("dataschema", DataSchema), attr("subject", Subject), attr("time", Time), ), newMatchExactVersionVersion(prefix, attributeNameMatchMapper, event.EventContextV03{}.AsV03(), func(c event.EventContextConverter) event.EventContext { return c.AsV03() }, attr("specversion", SpecVersion), attr("type", Type), attr("source", Source), attr("schemaurl", DataSchema), attr("subject", Subject), attr("id", ID), attr("time", Time), attr("datacontenttype", DataContentType), ), }, } for _, v := range vs.all { vs.m[v.String()] = v } return vs }
WithPrefixMatchExact returns a set of versions with prefix added to all attribute names.
WithPrefixMatchExact
go
cloudevents/sdk-go
v2/binding/spec/match_exact_version.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/spec/match_exact_version.go
Apache-2.0