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 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/sender/main.go
https://github.com/cloudevents/sdk-go/blob/master/samples/amqp/sender/main.go
Apache-2.0
func (*Sample) Descriptor() ([]byte, []int) { return file_sample_proto_rawDescGZIP(), []int{0} }
Deprecated: Use Sample.ProtoReflect.Descriptor instead.
Descriptor
go
cloudevents/sdk-go
samples/http/receiver-protobuf/sample.pb.go
https://github.com/cloudevents/sdk-go/blob/master/samples/http/receiver-protobuf/sample.pb.go
Apache-2.0
func (*Sample) Descriptor() ([]byte, []int) { return file_sample_proto_rawDescGZIP(), []int{0} }
Deprecated: Use Sample.ProtoReflect.Descriptor instead.
Descriptor
go
cloudevents/sdk-go
samples/http/sender-protobuf/sample.pb.go
https://github.com/cloudevents/sdk-go/blob/master/samples/http/sender-protobuf/sample.pb.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 testClient(t testing.TB) sarama.Client { t.Helper() s := os.Getenv("TEST_KAFKA_BOOTSTRAP_SERVER") if s == "" { s = "localhost:9092" } config := sarama.NewConfig() config.Version = sarama.V2_0_0_0 config.Producer.Return.Successes = true config.Producer.Return.Errors = true config.Consumer.Offsets.Initial = sarama.OffsetOldest client, err := sarama.NewClient(strings.Split(s, ","), config) if err != nil { t.Skipf("Cannot create sarama client to servers [%s]: %v", s, err) } return client }
To start a local environment for testing: docker run --rm --net=host -e ADV_HOST=localhost -e SAMPLEDATA=0 lensesio/fast-data-dev
testClient
go
cloudevents/sdk-go
test/integration/kafka_sarama/kafka_test.go
https://github.com/cloudevents/sdk-go/blob/master/test/integration/kafka_sarama/kafka_test.go
Apache-2.0
func testClient(t testing.TB) sarama.Client { t.Helper() s := os.Getenv("TEST_KAFKA_BOOTSTRAP_SERVER") if s == "" { s = "localhost:9092" } config := sarama.NewConfig() config.Version = sarama.V2_0_0_0 config.Producer.Return.Successes = true config.Producer.Return.Errors = true config.Consumer.Offsets.Initial = sarama.OffsetOldest client, err := sarama.NewClient(strings.Split(s, ","), config) if err != nil { t.Skipf("Cannot create sarama client to servers [%s]: %v", s, err) } return client }
To start a local environment for testing: docker run --rm --net=host -e ADV_HOST=localhost -e SAMPLEDATA=0 lensesio/fast-data-dev
testClient
go
cloudevents/sdk-go
test/integration/kafka_sarama_binding/kafka_test.go
https://github.com/cloudevents/sdk-go/blob/master/test/integration/kafka_sarama_binding/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
func (v *version) HasPrefix(name string) bool { return strings.HasPrefix(strings.ToLower(name), v.prefix) }
HasPrefix is a case-insensitive prefix check.
HasPrefix
go
cloudevents/sdk-go
v2/binding/spec/spec.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/spec/spec.go
Apache-2.0
func WithPrefix(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{ newVersion(prefix, 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), ), newVersion(prefix, 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 }
WithPrefix returns a set of versions with prefix added to all attribute names.
WithPrefix
go
cloudevents/sdk-go
v2/binding/spec/spec.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/spec/spec.go
Apache-2.0
func MustCreateMockBinaryMessage(e event.Event) binding.Message { version := spec.VS.Version(e.SpecVersion()) m := MockBinaryMessage{ Version: version, Metadata: make(map[spec.Attribute]interface{}), Extensions: make(map[string]interface{}), } for _, attribute := range version.Attributes() { val := attribute.Get(e.Context) if val != nil { m.Metadata[attribute] = val } } for k, v := range e.Extensions() { m.Extensions[k] = v } m.Body = e.Data() return &m }
MustCreateMockBinaryMessage creates a new MockBinaryMessage starting from an event.Event. Panics in case of error
MustCreateMockBinaryMessage
go
cloudevents/sdk-go
v2/binding/test/mock_binary_message.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/test/mock_binary_message.go
Apache-2.0
func MustCreateMockStructuredMessage(t testing.TB, e event.Event) binding.Message { return &MockStructuredMessage{ Bytes: test.MustJSON(t, e), Format: format.JSON, } }
MustCreateMockStructuredMessage creates a new MockStructuredMessage starting from an event.Event. Panics in case of error.
MustCreateMockStructuredMessage
go
cloudevents/sdk-go
v2/binding/test/mock_structured_message.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/test/mock_structured_message.go
Apache-2.0
func AddAttribute(attributeKind spec.Kind, value interface{}) binding.TransformerFunc { return SetAttribute(attributeKind, func(i2 interface{}) (i interface{}, err error) { if types.IsZero(i2) { return value, nil } return i2, nil }) }
AddAttribute adds a cloudevents attribute (if missing) during the encoding process
AddAttribute
go
cloudevents/sdk-go
v2/binding/transformer/add_metadata.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/transformer/add_metadata.go
Apache-2.0
func AddExtension(name string, value interface{}) binding.TransformerFunc { return SetExtension(name, func(i2 interface{}) (i interface{}, err error) { if types.IsZero(i2) { return value, nil } return i2, nil }) }
AddExtension adds a cloudevents extension (if missing) during the encoding process
AddExtension
go
cloudevents/sdk-go
v2/binding/transformer/add_metadata.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/transformer/add_metadata.go
Apache-2.0
func DeleteAttribute(attributeKind spec.Kind) binding.TransformerFunc { return SetAttribute(attributeKind, func(i2 interface{}) (i interface{}, err error) { return nil, nil }) }
DeleteAttribute deletes a cloudevents attribute during the encoding process
DeleteAttribute
go
cloudevents/sdk-go
v2/binding/transformer/delete_metadata.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/transformer/delete_metadata.go
Apache-2.0
func DeleteExtension(name string) binding.TransformerFunc { return SetExtension(name, func(i2 interface{}) (i interface{}, err error) { return nil, nil }) }
DeleteExtension deletes a cloudevents extension during the encoding process
DeleteExtension
go
cloudevents/sdk-go
v2/binding/transformer/delete_metadata.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/transformer/delete_metadata.go
Apache-2.0
func SetAttribute(attribute spec.Kind, updater func(interface{}) (interface{}, error)) binding.TransformerFunc { return func(reader binding.MessageMetadataReader, writer binding.MessageMetadataWriter) error { attr, oldVal := reader.GetAttribute(attribute) if attr == nil { // The spec version of this message doesn't support this attribute, skip this return nil } newVal, err := updater(oldVal) if err != nil { return err } return writer.SetAttribute(attr, newVal) } }
SetAttribute sets a cloudevents attribute using the provided function. updater gets a zero value as input if no previous value was found. To test a zero value, use types.IsZero(). updater must return nil, nil if the user wants to remove the attribute
SetAttribute
go
cloudevents/sdk-go
v2/binding/transformer/set_metadata.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/transformer/set_metadata.go
Apache-2.0
func SetExtension(name string, updater func(interface{}) (interface{}, error)) binding.TransformerFunc { return func(reader binding.MessageMetadataReader, writer binding.MessageMetadataWriter) error { oldVal := reader.GetExtension(name) newVal, err := updater(oldVal) if err != nil { return err } return writer.SetExtension(name, newVal) } }
SetExtension sets a cloudevents extension using the provided function. updater gets a zero value as input if no previous value was found. To test a zero value, use types.IsZero() updater must return nil, nil if the user wants to remove the extension
SetExtension
go
cloudevents/sdk-go
v2/binding/transformer/set_metadata.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/transformer/set_metadata.go
Apache-2.0
func TestSetExtension(t *testing.T) { e := MinEvent() e.Context = e.Context.AsV1() extName := "exnum" extInitialValue := "1" exUpdatedValue := "2" eventWithInitialValue := e.Clone() require.NoError(t, eventWithInitialValue.Context.SetExtension(extName, extInitialValue)) eventWithUpdatedValue := e.Clone() require.NoError(t, eventWithUpdatedValue.Context.SetExtension(extName, exUpdatedValue)) transformers := SetExtension(extName, func(i2 interface{}) (i interface{}, err error) { if types.IsZero(i2) { return extInitialValue, nil } str, err := types.Format(i2) if err != nil { return nil, err } n, err := strconv.Atoi(str) if err != nil { return nil, err } n++ return strconv.Itoa(n), nil }) RunTransformerTests(t, context.Background(), []TransformerTestArgs{ { Name: "Add exnum to Mock Structured message", InputMessage: MustCreateMockStructuredMessage(t, e), WantEvent: eventWithInitialValue, Transformers: binding.Transformers{transformers}, }, { Name: "Add exnum to Mock Binary message", InputMessage: MustCreateMockBinaryMessage(e), WantEvent: eventWithInitialValue, Transformers: binding.Transformers{transformers}, }, { Name: "Add exnum to Event message", InputEvent: e, WantEvent: eventWithInitialValue, Transformers: binding.Transformers{transformers}, }, { Name: "Update exnum in Mock Structured message", InputMessage: MustCreateMockStructuredMessage(t, eventWithInitialValue), WantEvent: eventWithUpdatedValue, Transformers: binding.Transformers{transformers}, }, { Name: "Update exnum in Mock Binary message", InputMessage: MustCreateMockBinaryMessage(eventWithInitialValue), WantEvent: eventWithUpdatedValue, Transformers: binding.Transformers{transformers}, }, { Name: "Update exnum in Event message", InputEvent: eventWithInitialValue, WantEvent: eventWithUpdatedValue, Transformers: binding.Transformers{transformers}, }, }) }
Test a common flow: If the metadata is not existing, initialize with a value. Otherwise, update it
TestSetExtension
go
cloudevents/sdk-go
v2/binding/transformer/set_metadata_test.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/transformer/set_metadata_test.go
Apache-2.0
func Version(newVersion spec.Version) binding.TransformerFunc { return func(reader binding.MessageMetadataReader, writer binding.MessageMetadataWriter) error { _, sv := reader.GetAttribute(spec.SpecVersion) if newVersion.String() == sv { return nil } for _, newAttr := range newVersion.Attributes() { oldAttr, val := reader.GetAttribute(newAttr.Kind()) if oldAttr != nil && val != nil { // Erase old attr err := writer.SetAttribute(oldAttr, nil) if err != nil { return nil } if newAttr.Kind() == spec.SpecVersion { err = writer.SetAttribute(newAttr, newVersion.String()) if err != nil { return nil } } else { err = writer.SetAttribute(newAttr, val) if err != nil { return nil } } } } return nil } }
Version converts the event context version to the specified one.
Version
go
cloudevents/sdk-go
v2/binding/transformer/version.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/transformer/version.go
Apache-2.0
func NewStructuredMessage(format format.Format, reader io.Reader) *genericStructuredMessage { return &genericStructuredMessage{reader: reader, format: format} }
NewStructuredMessage wraps a format and an io.Reader returning an implementation of Message This message *cannot* be read several times safely
NewStructuredMessage
go
cloudevents/sdk-go
v2/binding/utils/structured_message.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/utils/structured_message.go
Apache-2.0
func WriteStructured(ctx context.Context, m binding.Message, writer io.Writer, transformers ...binding.Transformer) error { _, err := binding.Write( ctx, m, wsMessageWriter{writer}, nil, transformers..., ) return err }
WriteStructured fills the provided io.Writer with the binding.Message m in structured mode. Using context you can tweak the encoding processing (more details on binding.Write documentation).
WriteStructured
go
cloudevents/sdk-go
v2/binding/utils/write_structured_message.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/utils/write_structured_message.go
Apache-2.0
func New(obj interface{}, opts ...Option) (Client, error) { c := &ceClient{ // Running runtime.GOMAXPROCS(0) doesn't update the value, just returns the current one pollGoroutines: runtime.GOMAXPROCS(0), observabilityService: noopObservabilityService{}, } if p, ok := obj.(protocol.Sender); ok { c.sender = p } if p, ok := obj.(protocol.Requester); ok { c.requester = p } if p, ok := obj.(protocol.Responder); ok { c.responder = p } if p, ok := obj.(protocol.Receiver); ok { c.receiver = p } if p, ok := obj.(protocol.Opener); ok { c.opener = p } if err := c.applyOptions(opts...); err != nil { return nil, err } return c, nil }
New produces a new client with the provided transport object and applied client options.
New
go
cloudevents/sdk-go
v2/client/client.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/client.go
Apache-2.0
func (c *ceClient) StartReceiver(ctx context.Context, fn interface{}) error { ctx, cancel := context.WithCancel(ctx) defer cancel() c.receiverMu.Lock() defer c.receiverMu.Unlock() if c.invoker != nil { return fmt.Errorf("client already has a receiver") } invoker, err := newReceiveInvoker( fn, c.observabilityService, c.inboundContextDecorators, c.eventDefaulterFns, c.ackMalformedEvent, ) if err != nil { return err } if invoker.IsReceiver() && c.receiver == nil { return fmt.Errorf("mismatched receiver callback without protocol.Receiver supported by protocol") } if invoker.IsResponder() && c.responder == nil { return fmt.Errorf("mismatched receiver callback without protocol.Responder supported by protocol") } c.invoker = invoker if c.responder == nil && c.receiver == nil { return errors.New("responder nor receiver set") } defer func() { c.invoker = nil }() // Start Polling. wg := sync.WaitGroup{} for i := 0; i < c.pollGoroutines; i++ { wg.Add(1) go func() { defer wg.Done() for { var msg binding.Message var respFn protocol.ResponseFn var err error if c.responder != nil { msg, respFn, err = c.responder.Respond(ctx) } else if c.receiver != nil { msg, err = c.receiver.Receive(ctx) respFn = noRespFn } if err == io.EOF { // Normal close return } if err != nil { cecontext.LoggerFrom(ctx).Warn("Error while receiving a message: ", err) continue } callback := func() { if err := c.invoker.Invoke(ctx, msg, respFn); err != nil { cecontext.LoggerFrom(ctx).Warn("Error while handling a message: ", err) } } if c.blockingCallback { callback() } else { // Do not block on the invoker. wg.Add(1) go func() { defer wg.Done() callback() }() } } }() } // Start the opener, if set. if c.opener != nil { if err = c.opener.OpenInbound(ctx); err != nil { err = fmt.Errorf("error while opening the inbound connection: %w", err) cancel() } } wg.Wait() return err }
StartReceiver sets up the given fn to handle Receive. See Client.StartReceiver for details. This is a blocking call.
StartReceiver
go
cloudevents/sdk-go
v2/client/client.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/client.go
Apache-2.0
func noRespFn(_ context.Context, _ binding.Message, r protocol.Result, _ ...binding.Transformer) error { return r }
noRespFn is used to simply forward the protocol.Result for receivers that aren't responders
noRespFn
go
cloudevents/sdk-go
v2/client/client.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/client.go
Apache-2.0
func NewHTTP(opts ...http.Option) (Client, error) { p, err := http.New(opts...) if err != nil { return nil, err } c, err := New(p, WithTimeNow(), WithUUIDs()) if err != nil { return nil, err } return c, nil }
NewHTTP provides the good defaults for the common case using an HTTP Protocol client. The WithTimeNow, and WithUUIDs client options are also applied to the client, all outbound events will have a time and id set if not already present.
NewHTTP
go
cloudevents/sdk-go
v2/client/client_http.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/client_http.go
Apache-2.0
func DefaultIDToUUIDIfNotSet(ctx context.Context, event event.Event) event.Event { if event.Context != nil { if event.ID() == "" { event.Context = event.Context.Clone() event.SetID(uuid.New().String()) } } return event }
DefaultIDToUUIDIfNotSet will inspect the provided event and assign a UUID to context.ID if it is found to be empty.
DefaultIDToUUIDIfNotSet
go
cloudevents/sdk-go
v2/client/defaulters.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/defaulters.go
Apache-2.0
func DefaultTimeToNowIfNotSet(ctx context.Context, event event.Event) event.Event { if event.Context != nil { if event.Time().IsZero() { event.Context = event.Context.Clone() event.SetTime(time.Now()) } } return event }
DefaultTimeToNowIfNotSet will inspect the provided event and assign a new Timestamp to context.Time if it is found to be nil or zero.
DefaultTimeToNowIfNotSet
go
cloudevents/sdk-go
v2/client/defaulters.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/defaulters.go
Apache-2.0
func NewDefaultDataContentTypeIfNotSet(contentType string) EventDefaulter { return func(ctx context.Context, event event.Event) event.Event { if event.Context != nil { if event.DataContentType() == "" { event.SetDataContentType(contentType) } } return event } }
NewDefaultDataContentTypeIfNotSet returns a defaulter that will inspect the provided event and set the provided content type if content type is found to be empty.
NewDefaultDataContentTypeIfNotSet
go
cloudevents/sdk-go
v2/client/defaulters.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/defaulters.go
Apache-2.0
func WithEventDefaulter(fn EventDefaulter) Option { return func(i interface{}) error { if c, ok := i.(*ceClient); ok { if fn == nil { return fmt.Errorf("client option was given an nil event defaulter") } c.eventDefaulterFns = append(c.eventDefaulterFns, fn) } return nil } }
WithEventDefaulter adds an event defaulter to the end of the defaulter chain.
WithEventDefaulter
go
cloudevents/sdk-go
v2/client/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/options.go
Apache-2.0
func WithUUIDs() Option { return func(i interface{}) error { if c, ok := i.(*ceClient); ok { c.eventDefaulterFns = append(c.eventDefaulterFns, DefaultIDToUUIDIfNotSet) } return nil } }
WithUUIDs adds DefaultIDToUUIDIfNotSet event defaulter to the end of the defaulter chain.
WithUUIDs
go
cloudevents/sdk-go
v2/client/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/options.go
Apache-2.0
func WithTimeNow() Option { return func(i interface{}) error { if c, ok := i.(*ceClient); ok { c.eventDefaulterFns = append(c.eventDefaulterFns, DefaultTimeToNowIfNotSet) } return nil } }
WithTimeNow adds DefaultTimeToNowIfNotSet event defaulter to the end of the defaulter chain.
WithTimeNow
go
cloudevents/sdk-go
v2/client/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/options.go
Apache-2.0
func WithTracePropagation() Option { return func(i interface{}) error { return nil } }
WithTracePropagation enables trace propagation via the distributed tracing extension. Deprecated: this is now noop and will be removed in future releases. Don't use distributed tracing extension to propagate traces: https://github.com/cloudevents/spec/blob/v1.0.1/extensions/distributed-tracing.md#using-the-distributed-tracing-extension
WithTracePropagation
go
cloudevents/sdk-go
v2/client/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/options.go
Apache-2.0
func WithPollGoroutines(pollGoroutines int) Option { return func(i interface{}) error { if c, ok := i.(*ceClient); ok { c.pollGoroutines = pollGoroutines } return nil } }
WithPollGoroutines configures how much goroutines should be used to poll the Receiver/Responder/Protocol implementations. Default value is GOMAXPROCS
WithPollGoroutines
go
cloudevents/sdk-go
v2/client/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/options.go
Apache-2.0
func WithObservabilityService(service ObservabilityService) Option { return func(i interface{}) error { if c, ok := i.(*ceClient); ok { c.observabilityService = service c.inboundContextDecorators = append(c.inboundContextDecorators, service.InboundContextDecorators()...) } return nil } }
WithObservabilityService configures the observability service to use to record traces and metrics
WithObservabilityService
go
cloudevents/sdk-go
v2/client/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/options.go
Apache-2.0
func WithInboundContextDecorator(dec func(context.Context, binding.Message) context.Context) Option { return func(i interface{}) error { if c, ok := i.(*ceClient); ok { c.inboundContextDecorators = append(c.inboundContextDecorators, dec) } return nil } }
WithInboundContextDecorator configures a new inbound context decorator. Inbound context decorators are invoked to wrap additional informations from the binding.Message and propagate these informations in the context passed to the event receiver.
WithInboundContextDecorator
go
cloudevents/sdk-go
v2/client/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/options.go
Apache-2.0
func WithBlockingCallback() Option { return func(i interface{}) error { if c, ok := i.(*ceClient); ok { c.blockingCallback = true } return nil } }
WithBlockingCallback makes the callback passed into StartReceiver is executed as a blocking call, i.e. in each poll go routine, the next event will not be received until the callback on current event completes. To make event processing serialized (no concurrency), use this option along with WithPollGoroutines(1)
WithBlockingCallback
go
cloudevents/sdk-go
v2/client/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/options.go
Apache-2.0
func WithAckMalformedEvent() Option { return func(i interface{}) error { if c, ok := i.(*ceClient); ok { c.ackMalformedEvent = true } return nil } }
WithAckMalformedevents causes malformed events received within StartReceiver to be acknowledged rather than being permanently not-acknowledged. This can be useful when a protocol does not provide a responder implementation and would otherwise cause the receiver to be partially or fully stuck.
WithAckMalformedEvent
go
cloudevents/sdk-go
v2/client/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/options.go
Apache-2.0
func receiver(fn interface{}) (*receiverFn, error) { fnType := reflect.TypeOf(fn) if fnType.Kind() != reflect.Func { return nil, errors.New("must pass a function to handle events") } r := &receiverFn{ fnValue: reflect.ValueOf(fn), numIn: fnType.NumIn(), numOut: fnType.NumOut(), } if err := r.validate(fnType); err != nil { return nil, err } return r, nil }
receiver creates a receiverFn wrapper class that is used by the client to validate and invoke the provided function. Valid fn signatures are: * func() * func() protocol.Result * func(context.Context) * func(context.Context) protocol.Result * func(event.Event) * func(event.Event) transport.Result * func(context.Context, event.Event) * func(context.Context, event.Event) protocol.Result * func(event.Event) *event.Event * func(event.Event) (*event.Event, protocol.Result) * func(context.Context, event.Event) *event.Event * func(context.Context, event.Event) (*event.Event, protocol.Result)
receiver
go
cloudevents/sdk-go
v2/client/receiver.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/receiver.go
Apache-2.0
func (r *receiverFn) validateInParamSignature(fnType reflect.Type) error { r.hasContextIn = false r.hasEventIn = false switch fnType.NumIn() { case 2: // has to be (context.Context, event.Event) if !eventType.ConvertibleTo(fnType.In(1)) { return fmt.Errorf("%s; cannot convert parameter 2 to %s from event.Event", inParamUsage, fnType.In(1)) } else { r.hasEventIn = true } fallthrough case 1: if !contextType.ConvertibleTo(fnType.In(0)) { if !eventType.ConvertibleTo(fnType.In(0)) { return fmt.Errorf("%s; cannot convert parameter 1 to %s from context.Context or event.Event", inParamUsage, fnType.In(0)) } else if r.hasEventIn { return fmt.Errorf("%s; duplicate parameter of type event.Event", inParamUsage) } else { r.hasEventIn = true } } else { r.hasContextIn = true } fallthrough case 0: return nil default: return fmt.Errorf("%s; function has too many parameters (%d)", inParamUsage, fnType.NumIn()) } }
Verifies that the inputs to a function have a valid signature Valid input is to be [0, all] of context.Context, event.Event in this order.
validateInParamSignature
go
cloudevents/sdk-go
v2/client/receiver.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/receiver.go
Apache-2.0
func (r *receiverFn) validateOutParamSignature(fnType reflect.Type) error { r.hasEventOut = false r.hasResultOut = false switch fnType.NumOut() { case 2: // has to be (*event.Event, transport.Result) if !fnType.Out(1).ConvertibleTo(resultType) { return fmt.Errorf("%s; cannot convert parameter 2 from %s to event.Response", outParamUsage, fnType.Out(1)) } else { r.hasResultOut = true } fallthrough case 1: if !fnType.Out(0).ConvertibleTo(resultType) { if !fnType.Out(0).ConvertibleTo(eventPtrType) { return fmt.Errorf("%s; cannot convert parameter 1 from %s to *event.Event or transport.Result", outParamUsage, fnType.Out(0)) } else { r.hasEventOut = true } } else if r.hasResultOut { return fmt.Errorf("%s; duplicate parameter of type event.Response", outParamUsage) } else { r.hasResultOut = true } fallthrough case 0: return nil default: return fmt.Errorf("%s; function has too many return types (%d)", outParamUsage, fnType.NumOut()) } }
Verifies that the outputs of a function have a valid signature Valid output signatures to be [0, all] of *event.Event, transport.Result in this order
validateOutParamSignature
go
cloudevents/sdk-go
v2/client/receiver.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/receiver.go
Apache-2.0
func (r *receiverFn) validate(fnType reflect.Type) error { if err := r.validateInParamSignature(fnType); err != nil { return err } if err := r.validateOutParamSignature(fnType); err != nil { return err } return nil }
validateReceiverFn validates that a function has the right number of in and out params and that they are of allowed types.
validate
go
cloudevents/sdk-go
v2/client/receiver.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/receiver.go
Apache-2.0
func NewMockSenderClient(t *testing.T, chanSize int, opts ...client.Option) (client.Client, <-chan event.Event) { require.NotZero(t, chanSize) eventCh := make(chan event.Event, chanSize) messageCh := make(chan binding.Message) // Output piping go func(messageCh <-chan binding.Message, eventCh chan<- event.Event) { for m := range messageCh { e, err := binding.ToEvent(context.TODO(), m) require.NoError(t, err) eventCh <- *e } }(messageCh, eventCh) c, err := client.New(gochan.Sender(messageCh), opts...) require.NoError(t, err) return c, eventCh }
NewMockSenderClient returns a client that can Send() event. All sent messages are delivered to the returned channel.
NewMockSenderClient
go
cloudevents/sdk-go
v2/client/test/mock_client.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/test/mock_client.go
Apache-2.0
func NewMockRequesterClient(t *testing.T, chanSize int, replierFn func(inMessage event.Event) (*event.Event, protocol.Result), opts ...client.Option) (client.Client, <-chan event.Event) { require.NotZero(t, chanSize) require.NotNil(t, replierFn) eventCh := make(chan event.Event, chanSize) messageCh := make(chan binding.Message) replier := func(inMessage binding.Message) (binding.Message, error) { inEvent, err := binding.ToEvent(context.TODO(), inMessage) require.NoError(t, err) outEvent, err := replierFn(*inEvent) if outEvent != nil { return binding.ToMessage(outEvent), err } return nil, err } chanRequester := gochan.Requester{ Ch: messageCh, Reply: replier, } // Output piping go func(messageCh <-chan binding.Message, eventCh chan<- event.Event) { for m := range messageCh { e, err := binding.ToEvent(context.TODO(), m) require.NoError(t, err) eventCh <- *e } }(messageCh, eventCh) c, err := client.New(&chanRequester, opts...) require.NoError(t, err) return c, eventCh }
NewMockRequesterClient returns a client that can perform Send() event and Request() event. All sent messages are delivered to the returned channel.
NewMockRequesterClient
go
cloudevents/sdk-go
v2/client/test/mock_client.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/test/mock_client.go
Apache-2.0
func NewMockReceiverClient(t *testing.T, chanSize int, opts ...client.Option) (client.Client, chan<- event.Event) { require.NotZero(t, chanSize) eventCh := make(chan event.Event, chanSize) messageCh := make(chan binding.Message) // Input piping go func(messageCh chan<- binding.Message, eventCh <-chan event.Event) { for e := range eventCh { messageCh <- binding.ToMessage(&e) } }(messageCh, eventCh) c, err := client.New(gochan.Receiver(messageCh), opts...) require.NoError(t, err) return c, eventCh }
NewMockReceiverClient returns a client that can Receive events, without replying. The returned channel is the channel for sending messages to the client
NewMockReceiverClient
go
cloudevents/sdk-go
v2/client/test/mock_client.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/test/mock_client.go
Apache-2.0
func NewMockResponderClient(t *testing.T, chanSize int, opts ...client.Option) (client.Client, chan<- event.Event, <-chan ClientMockResponse) { require.NotZero(t, chanSize) inEventCh := make(chan event.Event, chanSize) inMessageCh := make(chan binding.Message) outEventCh := make(chan ClientMockResponse, chanSize) outMessageCh := make(chan gochan.ChanResponderResponse) // Input piping go func(messageCh chan<- binding.Message, eventCh <-chan event.Event) { for e := range eventCh { messageCh <- binding.ToMessage(&e) } }(inMessageCh, inEventCh) // Output piping go func(messageCh <-chan gochan.ChanResponderResponse, eventCh chan<- ClientMockResponse) { for m := range messageCh { if m.Message != nil { e, err := binding.ToEvent(context.TODO(), m.Message) require.NoError(t, err) require.NoError(t, m.Message.Finish(nil)) eventCh <- ClientMockResponse{ Event: *e, Result: m.Result, } } eventCh <- ClientMockResponse{Result: m.Result} } }(outMessageCh, outEventCh) c, err := client.New(&gochan.Responder{In: inMessageCh, Out: outMessageCh}, opts...) require.NoError(t, err) return c, inEventCh, outEventCh }
NewMockResponderClient returns a client that can Receive events and reply. The first returned channel is the channel for sending messages to the client, while the second one contains the eventual responses.
NewMockResponderClient
go
cloudevents/sdk-go
v2/client/test/mock_client.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/test/mock_client.go
Apache-2.0
func SendReceive(t *testing.T, protocolFactory func() interface{}, in event.Event, outAssert func(e event.Event), opts ...client.Option) { t.Helper() pf := protocolFactory() // Create a sender and receiver client since we can't assume it's safe // to use the same one for both roles sender, err := client.New(pf, opts...) require.NoError(t, err) receiver, err := client.New(pf, opts...) require.NoError(t, err) wg := sync.WaitGroup{} wg.Add(2) receiverReady := make(chan bool) go func() { ctx, cancel := context.WithCancel(context.TODO()) inCh := make(chan event.Event) defer func(channel chan event.Event) { cancel() close(channel) wg.Done() }(inCh) go func(channel chan event.Event) { receiverReady <- true err := receiver.StartReceiver(ctx, func(e event.Event) { channel <- e }) if err != nil { require.NoError(t, err) } }(inCh) e := <-inCh outAssert(e) }() // Wait for receiver to be setup. Not 100% perefect but the channel + the // sleep should do it <-receiverReady time.Sleep(2 * time.Second) go func() { defer wg.Done() err := sender.Send(context.Background(), in) require.NoError(t, err) }() wg.Wait() if closer, ok := pf.(protocol.Closer); ok { require.NoError(t, closer.Close(context.TODO())) } }
SendReceive does client.Send(in), then it receives the message using client.StartReceiver() and executes outAssert Halt test on error.
SendReceive
go
cloudevents/sdk-go
v2/client/test/test.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/test/test.go
Apache-2.0
func WithTarget(ctx context.Context, target string) context.Context { return context.WithValue(ctx, targetKey, target) }
WithTarget returns back a new context with the given target. Target is intended to be transport dependent. For http transport, `target` should be a full URL and will be injected into the outbound http request.
WithTarget
go
cloudevents/sdk-go
v2/context/context.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/context.go
Apache-2.0
func TargetFrom(ctx context.Context) *url.URL { c := ctx.Value(targetKey) if c != nil { if s, ok := c.(string); ok && s != "" { if target, err := url.Parse(s); err == nil { return target } } } return nil }
TargetFrom looks in the given context and returns `target` as a parsed url if found and valid, otherwise nil.
TargetFrom
go
cloudevents/sdk-go
v2/context/context.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/context.go
Apache-2.0
func WithTopic(ctx context.Context, topic string) context.Context { return context.WithValue(ctx, topicKey, topic) }
WithTopic returns back a new context with the given topic. Topic is intended to be transport dependent. For pubsub transport, `topic` should be a Pub/Sub Topic ID.
WithTopic
go
cloudevents/sdk-go
v2/context/context.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/context.go
Apache-2.0
func TopicFrom(ctx context.Context) string { c := ctx.Value(topicKey) if c != nil { if s, ok := c.(string); ok { return s } } return "" }
TopicFrom looks in the given context and returns `topic` as a string if found and valid, otherwise "".
TopicFrom
go
cloudevents/sdk-go
v2/context/context.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/context.go
Apache-2.0
func WithRetriesConstantBackoff(ctx context.Context, delay time.Duration, maxTries int) context.Context { return WithRetryParams(ctx, &RetryParams{ Strategy: BackoffStrategyConstant, Period: delay, MaxTries: maxTries, }) }
WithRetriesConstantBackoff returns back a new context with retries parameters using constant backoff strategy. MaxTries is the maximum number for retries and delay is the time interval between retries
WithRetriesConstantBackoff
go
cloudevents/sdk-go
v2/context/context.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/context.go
Apache-2.0
func WithRetriesLinearBackoff(ctx context.Context, delay time.Duration, maxTries int) context.Context { return WithRetryParams(ctx, &RetryParams{ Strategy: BackoffStrategyLinear, Period: delay, MaxTries: maxTries, }) }
WithRetriesLinearBackoff returns back a new context with retries parameters using linear backoff strategy. MaxTries is the maximum number for retries and delay*tries is the time interval between retries
WithRetriesLinearBackoff
go
cloudevents/sdk-go
v2/context/context.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/context.go
Apache-2.0
func WithRetriesExponentialBackoff(ctx context.Context, period time.Duration, maxTries int) context.Context { return WithRetryParams(ctx, &RetryParams{ Strategy: BackoffStrategyExponential, Period: period, MaxTries: maxTries, }) }
WithRetriesExponentialBackoff returns back a new context with retries parameters using exponential backoff strategy. MaxTries is the maximum number for retries and period is the amount of time to wait, used as `period * 2^retries`.
WithRetriesExponentialBackoff
go
cloudevents/sdk-go
v2/context/context.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/context.go
Apache-2.0
func WithRetryParams(ctx context.Context, rp *RetryParams) context.Context { return context.WithValue(ctx, retriesKey, rp) }
WithRetryParams returns back a new context with retries parameters.
WithRetryParams
go
cloudevents/sdk-go
v2/context/context.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/context.go
Apache-2.0
func RetriesFrom(ctx context.Context) *RetryParams { c := ctx.Value(retriesKey) if c != nil { if s, ok := c.(*RetryParams); ok { return s } } return &DefaultRetryParams }
RetriesFrom looks in the given context and returns the retries parameters if found. Otherwise returns the default retries configuration (ie. no retries).
RetriesFrom
go
cloudevents/sdk-go
v2/context/context.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/context.go
Apache-2.0
func ValuesDelegating(child, parent context.Context) context.Context { return &valuesDelegating{ Context: child, parent: parent, } }
ValuesDelegating wraps a child and parent context. It will perform Value() lookups first on the child, and then fall back to the child. All other calls go solely to the child context.
ValuesDelegating
go
cloudevents/sdk-go
v2/context/delegating.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/delegating.go
Apache-2.0
func WithLogger(ctx context.Context, logger *zap.SugaredLogger) context.Context { if logger == nil { return context.WithValue(ctx, loggerKey, fallbackLogger) } return context.WithValue(ctx, loggerKey, logger) }
WithLogger returns a new context with the logger injected into the given context.
WithLogger
go
cloudevents/sdk-go
v2/context/logger.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/logger.go
Apache-2.0
func LoggerFrom(ctx context.Context) *zap.SugaredLogger { l := ctx.Value(loggerKey) if l != nil { if logger, ok := l.(*zap.SugaredLogger); ok { return logger } } return fallbackLogger }
LoggerFrom returns the logger stored in context.
LoggerFrom
go
cloudevents/sdk-go
v2/context/logger.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/logger.go
Apache-2.0
func (r *RetryParams) BackoffFor(tries int) time.Duration { switch r.Strategy { case BackoffStrategyConstant: return r.Period case BackoffStrategyLinear: return r.Period * time.Duration(tries) case BackoffStrategyExponential: exp := math.Exp2(float64(tries)) return r.Period * time.Duration(exp) case BackoffStrategyNone: fallthrough // default default: return r.Period } }
BackoffFor tries will return the time duration that should be used for this current try count. `tries` is assumed to be the number of times the caller has already retried.
BackoffFor
go
cloudevents/sdk-go
v2/context/retry.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/retry.go
Apache-2.0
func (r *RetryParams) Backoff(ctx context.Context, tries int) error { if tries > r.MaxTries { return errors.New("too many retries") } ticker := time.NewTicker(r.BackoffFor(tries)) select { case <-ctx.Done(): ticker.Stop() return errors.New("context has been cancelled") case <-ticker.C: ticker.Stop() } return nil }
Backoff is a blocking call to wait for the correct amount of time for the retry. `tries` is assumed to be the number of times the caller has already retried.
Backoff
go
cloudevents/sdk-go
v2/context/retry.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/retry.go
Apache-2.0
func isJSON(contentType string) bool { switch contentType { case ApplicationJSON, TextJSON, ApplicationCloudEventsJSON, ApplicationCloudEventsBatchJSON: return true case "": return true // Empty content type assumes json default: return false } }
isJSON returns true if the content type is a JSON type.
isJSON
go
cloudevents/sdk-go
v2/event/content_type.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/content_type.go
Apache-2.0
func StringOfApplicationJSON() *string { a := ApplicationJSON return &a }
StringOfApplicationJSON returns a string pointer to "application/json"
StringOfApplicationJSON
go
cloudevents/sdk-go
v2/event/content_type.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/content_type.go
Apache-2.0
func StringOfApplicationXML() *string { a := ApplicationXML return &a }
StringOfApplicationXML returns a string pointer to "application/xml"
StringOfApplicationXML
go
cloudevents/sdk-go
v2/event/content_type.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/content_type.go
Apache-2.0
func StringOfTextPlain() *string { a := TextPlain return &a }
StringOfTextPlain returns a string pointer to "text/plain"
StringOfTextPlain
go
cloudevents/sdk-go
v2/event/content_type.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/content_type.go
Apache-2.0
func StringOfApplicationCloudEventsJSON() *string { a := ApplicationCloudEventsJSON return &a }
StringOfApplicationCloudEventsJSON returns a string pointer to "application/cloudevents+json"
StringOfApplicationCloudEventsJSON
go
cloudevents/sdk-go
v2/event/content_type.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/content_type.go
Apache-2.0
func StringOfApplicationCloudEventsBatchJSON() *string { a := ApplicationCloudEventsBatchJSON return &a }
StringOfApplicationCloudEventsBatchJSON returns a string pointer to "application/cloudevents-batch+json"
StringOfApplicationCloudEventsBatchJSON
go
cloudevents/sdk-go
v2/event/content_type.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/content_type.go
Apache-2.0
func New(version ...string) Event { specVersion := defaultEventVersion if len(version) >= 1 { specVersion = version[0] } e := &Event{} e.SetSpecVersion(specVersion) return *e }
New returns a new Event, an optional version can be passed to change the default spec version from 1.0 to the provided version.
New
go
cloudevents/sdk-go
v2/event/event.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/event.go
Apache-2.0
func (e Event) ExtensionAs(name string, obj interface{}) error { return e.Context.ExtensionAs(name, obj) }
ExtensionAs is deprecated: access extensions directly via the e.Extensions() map. Use functions in the types package to convert extension values. For example replace this: var i int err := e.ExtensionAs("foo", &i) With this: i, err := types.ToInteger(e.Extensions["foo"])
ExtensionAs
go
cloudevents/sdk-go
v2/event/event.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/event.go
Apache-2.0