Dataset Viewer
Auto-converted to Parquet
code
stringlengths
22
3.95M
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 Show(f func(dx, dy int) [][]uint8) { const ( dx = 256 dy = 256 ) data := f(dx, dy) m := image.NewNRGBA(image.Rect(0, 0, dx, dy)) for y := 0; y < dy; y++ { for x := 0; x < dx; x++ { v := data[y][x] i := y*m.Stride + x*4 m.Pix[i] = v m.Pix[i+1] = v m.Pix[i+2] = 255 m.Pix[i+3] = 255 } } ShowImage(m) }
Show displays a picture defined by the function f when executed on the Go Playground. f should return a slice of length dy, each element of which is a slice of dx 8-bit unsigned int. The integers are interpreted as bluescale values, where the value 0 means full blue, and the value 255 means full white.
Show
go
golang/tour
pic/pic.go
https://github.com/golang/tour/blob/master/pic/pic.go
BSD-3-Clause
func ShowImage(m image.Image) { w := bufio.NewWriter(os.Stdout) defer w.Flush() io.WriteString(w, "IMAGE:") b64 := base64.NewEncoder(base64.StdEncoding, w) err := (&png.Encoder{CompressionLevel: png.BestCompression}).Encode(b64, m) if err != nil { panic(err) } b64.Close() io.WriteString(w, "\n") }
ShowImage displays the image m when executed on the Go Playground.
ShowImage
go
golang/tour
pic/pic.go
https://github.com/golang/tour/blob/master/pic/pic.go
BSD-3-Clause
func New(k int) *Tree { var t *Tree for _, v := range rand.Perm(10) { t = insert(t, (1+v)*k) } return t }
New returns a new, random binary tree holding the values k, 2k, ..., 10k.
New
go
golang/tour
tree/tree.go
https://github.com/golang/tour/blob/master/tree/tree.go
BSD-3-Clause
func DecodeData(ctx context.Context, in []byte, out interface{}) error { outmsg, ok := out.(proto.Message) if !ok { return fmt.Errorf("can only decode protobuf into proto.Message. got %T", out) } if err := proto.Unmarshal(in, outmsg); err != nil { return fmt.Errorf("failed to unmarshal message: %s", err) } return nil }
DecodeData converts an encoded protobuf message back into the message (out). The message must be a type compatible with whatever was given to EncodeData.
DecodeData
go
cloudevents/sdk-go
binding/format/protobuf/v2/datacodec.go
https://github.com/cloudevents/sdk-go/blob/master/binding/format/protobuf/v2/datacodec.go
Apache-2.0
func EncodeData(ctx context.Context, in interface{}) ([]byte, error) { if b, ok := in.([]byte); ok { return b, nil } var pbmsg proto.Message var ok bool if pbmsg, ok = in.(proto.Message); !ok { return nil, fmt.Errorf("protobuf encoding only works with protobuf messages. got %T", in) } return proto.Marshal(pbmsg) }
EncodeData a protobuf message to bytes. Like the official datacodec implementations, this one returns the given value as-is if it is already a byte slice.
EncodeData
go
cloudevents/sdk-go
binding/format/protobuf/v2/datacodec.go
https://github.com/cloudevents/sdk-go/blob/master/binding/format/protobuf/v2/datacodec.go
Apache-2.0
func StringOfApplicationCloudEventsProtobuf() *string { a := ApplicationCloudEventsProtobuf return &a }
StringOfApplicationCloudEventsProtobuf returns a string pointer to "application/cloudevents+protobuf"
StringOfApplicationCloudEventsProtobuf
go
cloudevents/sdk-go
binding/format/protobuf/v2/protobuf.go
https://github.com/cloudevents/sdk-go/blob/master/binding/format/protobuf/v2/protobuf.go
Apache-2.0
func ToProto(e *event.Event) (*pb.CloudEvent, error) { container := &pb.CloudEvent{ Id: e.ID(), Source: e.Source(), SpecVersion: e.SpecVersion(), Type: e.Type(), Attributes: make(map[string]*pb.CloudEventAttributeValue), } if e.DataContentType() != "" { container.Attributes[datacontenttype], _ = attributeFor(e.DataContentType()) } if e.DataSchema() != "" { dataSchemaStr := e.DataSchema() uri, err := url.Parse(dataSchemaStr) if err != nil { return nil, fmt.Errorf("failed to url.Parse %s: %w", dataSchemaStr, err) } container.Attributes[dataschema], _ = attributeFor(uri) } if e.Subject() != "" { container.Attributes[subject], _ = attributeFor(e.Subject()) } if e.Time() != zeroTime { container.Attributes[time], _ = attributeFor(e.Time()) } for name, value := range e.Extensions() { attr, err := attributeFor(value) if err != nil { return nil, fmt.Errorf("failed to encode attribute %s: %s", name, err) } container.Attributes[name] = attr } container.Data = &pb.CloudEvent_BinaryData{ BinaryData: e.Data(), } if e.DataContentType() == ContentTypeProtobuf { anymsg := &anypb.Any{ TypeUrl: e.DataSchema(), Value: e.Data(), } container.Data = &pb.CloudEvent_ProtoData{ ProtoData: anymsg, } } return container, nil }
convert an SDK event to a protobuf variant of the event that can be marshaled.
ToProto
go
cloudevents/sdk-go
binding/format/protobuf/v2/protobuf.go
https://github.com/cloudevents/sdk-go/blob/master/binding/format/protobuf/v2/protobuf.go
Apache-2.0
func FromProto(container *pb.CloudEvent) (*event.Event, error) { e := event.New() e.SetID(container.Id) e.SetSource(container.Source) e.SetSpecVersion(container.SpecVersion) e.SetType(container.Type) // NOTE: There are some issues around missing data content type values that // are still unresolved. It is an optional field and if unset then it is // implied that the encoding used for the envelope was also used for the // data. However, there is no mapping that exists between data content types // and the envelope content types. For example, how would this system know // that receiving an envelope in application/cloudevents+protobuf know that // the implied data content type if missing is application/protobuf. // // It is also not clear what should happen if the data content type is unset // but it is known that the data content type is _not_ the same as the // envelope. For example, a JSON encoded data value would be stored within // the BinaryData attribute of the protobuf formatted envelope. Protobuf // data values, however, are _always_ stored as a protobuf encoded Any type // within the ProtoData field. Any use of the BinaryData or TextData fields // means the value is _not_ protobuf. If content type is not set then have // no way of knowing what the data encoding actually is. Currently, this // code does not address this and only loads explicitly set data content // type values. contentType := "" if container.Attributes != nil { attr := container.Attributes[datacontenttype] if attr != nil { if stattr, ok := attr.Attr.(*pb.CloudEventAttributeValue_CeString); ok { contentType = stattr.CeString } } } switch dt := container.Data.(type) { case *pb.CloudEvent_BinaryData: e.DataEncoded = dt.BinaryData // NOTE: If we use SetData then the current implementation always sets // the Base64 bit to true. Direct assignment appears to be the only way // to set non-base64 encoded binary data. // if err := e.SetData(contentType, dt.BinaryData); err != nil { // return nil, fmt.Errorf("failed to convert binary type (%s) data: %s", contentType, err) // } case *pb.CloudEvent_TextData: if err := e.SetData(contentType, dt.TextData); err != nil { return nil, fmt.Errorf("failed to convert text type (%s) data: %s", contentType, err) } case *pb.CloudEvent_ProtoData: e.SetDataContentType(ContentTypeProtobuf) e.DataEncoded = dt.ProtoData.Value } for name, value := range container.Attributes { v, err := valueFrom(value) if err != nil { return nil, fmt.Errorf("failed to convert attribute %s: %s", name, err) } switch name { case datacontenttype: vs, _ := v.(string) e.SetDataContentType(vs) case dataschema: vs, _ := v.(types.URI) e.SetDataSchema(vs.String()) case subject: vs, _ := v.(string) e.SetSubject(vs) case time: vs, _ := v.(types.Timestamp) e.SetTime(vs.Time) default: e.SetExtension(name, v) } } return &e, nil }
Convert from a protobuf variant into the generic, SDK event.
FromProto
go
cloudevents/sdk-go
binding/format/protobuf/v2/protobuf.go
https://github.com/cloudevents/sdk-go/blob/master/binding/format/protobuf/v2/protobuf.go
Apache-2.0
func (*CloudEvent) Descriptor() ([]byte, []int) { return file_cloudevent_proto_rawDescGZIP(), []int{0} }
Deprecated: Use CloudEvent.ProtoReflect.Descriptor instead.
Descriptor
go
cloudevents/sdk-go
binding/format/protobuf/v2/pb/cloudevent.pb.go
https://github.com/cloudevents/sdk-go/blob/master/binding/format/protobuf/v2/pb/cloudevent.pb.go
Apache-2.0
func (*CloudEventAttributeValue) Descriptor() ([]byte, []int) { return file_cloudevent_proto_rawDescGZIP(), []int{1} }
Deprecated: Use CloudEventAttributeValue.ProtoReflect.Descriptor instead.
Descriptor
go
cloudevents/sdk-go
binding/format/protobuf/v2/pb/cloudevent.pb.go
https://github.com/cloudevents/sdk-go/blob/master/binding/format/protobuf/v2/pb/cloudevent.pb.go
Apache-2.0
func NewReporter(ctx context.Context, on Observable) (context.Context, Reporter) { r := &reporter{ ctx: ctx, on: on, start: time.Now(), } r.tagMethod() return ctx, r }
NewReporter creates and returns a reporter wrapping the provided Observable.
NewReporter
go
cloudevents/sdk-go
observability/opencensus/v2/client/reporter.go
https://github.com/cloudevents/sdk-go/blob/master/observability/opencensus/v2/client/reporter.go
Apache-2.0
func (r *reporter) Error() { r.once.Do(func() { r.result(ResultError) }) }
Error records the result as an error.
Error
go
cloudevents/sdk-go
observability/opencensus/v2/client/reporter.go
https://github.com/cloudevents/sdk-go/blob/master/observability/opencensus/v2/client/reporter.go
Apache-2.0
func (r *reporter) OK() { r.once.Do(func() { r.result(ResultOK) }) }
OK records the result as a success.
OK
go
cloudevents/sdk-go
observability/opencensus/v2/client/reporter.go
https://github.com/cloudevents/sdk-go/blob/master/observability/opencensus/v2/client/reporter.go
Apache-2.0
func NewObservedHTTP(opts ...cehttp.Option) (*cehttp.Protocol, error) { return cehttp.New(append( []cehttp.Option{ cehttp.WithRoundTripperDecorator(roundtripperDecorator), cehttp.WithMiddleware(tracecontextMiddleware), }, opts..., )...) }
NewObservedHTTP creates an HTTP protocol with trace propagating middleware.
NewObservedHTTP
go
cloudevents/sdk-go
observability/opencensus/v2/http/http.go
https://github.com/cloudevents/sdk-go/blob/master/observability/opencensus/v2/http/http.go
Apache-2.0
func NewClientHTTP(topt []cehttp.Option, copt []client.Option, obsOpts ...OTelObservabilityServiceOption) (client.Client, error) { t, err := obshttp.NewObservedHTTP(topt...) if err != nil { return nil, err } copt = append( copt, client.WithTimeNow(), client.WithUUIDs(), client.WithObservabilityService(NewOTelObservabilityService(obsOpts...)), ) c, err := client.New(t, copt...) if err != nil { return nil, err } return c, nil }
NewClientHTTP produces a new client instrumented with OpenTelemetry.
NewClientHTTP
go
cloudevents/sdk-go
observability/opentelemetry/v2/client/client.go
https://github.com/cloudevents/sdk-go/blob/master/observability/opentelemetry/v2/client/client.go
Apache-2.0
func NewCloudEventCarrier() CloudEventCarrier { return CloudEventCarrier{Extension: &extensions.DistributedTracingExtension{}} }
NewCloudEventCarrier creates a new CloudEventCarrier with an empty distributed tracing extension.
NewCloudEventCarrier
go
cloudevents/sdk-go
observability/opentelemetry/v2/client/cloudevents_carrier.go
https://github.com/cloudevents/sdk-go/blob/master/observability/opentelemetry/v2/client/cloudevents_carrier.go
Apache-2.0
func NewCloudEventCarrierWithEvent(ctx context.Context, event cloudevents.Event) CloudEventCarrier { var te, ok = extensions.GetDistributedTracingExtension(event) if !ok { cecontext.LoggerFrom(ctx).Warn("Could not get the distributed tracing extension from the event.") return CloudEventCarrier{Extension: &extensions.DistributedTracingExtension{}} } return CloudEventCarrier{Extension: &te} }
NewCloudEventCarrierWithEvent creates a new CloudEventCarrier with a distributed tracing extension populated with the trace data from the event.
NewCloudEventCarrierWithEvent
go
cloudevents/sdk-go
observability/opentelemetry/v2/client/cloudevents_carrier.go
https://github.com/cloudevents/sdk-go/blob/master/observability/opentelemetry/v2/client/cloudevents_carrier.go
Apache-2.0
func (cec CloudEventCarrier) Get(key string) string { switch key { case extensions.TraceParentExtension: return cec.Extension.TraceParent case extensions.TraceStateExtension: return cec.Extension.TraceState default: return "" } }
Get returns the value associated with the passed key.
Get
go
cloudevents/sdk-go
observability/opentelemetry/v2/client/cloudevents_carrier.go
https://github.com/cloudevents/sdk-go/blob/master/observability/opentelemetry/v2/client/cloudevents_carrier.go
Apache-2.0
func (cec CloudEventCarrier) Set(key string, value string) { switch key { case extensions.TraceParentExtension: cec.Extension.TraceParent = value case extensions.TraceStateExtension: cec.Extension.TraceState = value } }
Set stores the key-value pair.
Set
go
cloudevents/sdk-go
observability/opentelemetry/v2/client/cloudevents_carrier.go
https://github.com/cloudevents/sdk-go/blob/master/observability/opentelemetry/v2/client/cloudevents_carrier.go
Apache-2.0
func (cec CloudEventCarrier) Keys() []string { return []string{extensions.TraceParentExtension, extensions.TraceStateExtension} }
Keys lists the keys stored in this carrier.
Keys
go
cloudevents/sdk-go
observability/opentelemetry/v2/client/cloudevents_carrier.go
https://github.com/cloudevents/sdk-go/blob/master/observability/opentelemetry/v2/client/cloudevents_carrier.go
Apache-2.0
func InjectDistributedTracingExtension(ctx context.Context, event cloudevents.Event) { tc := propagation.TraceContext{} carrier := NewCloudEventCarrier() tc.Inject(ctx, carrier) carrier.Extension.AddTracingAttributes(&event) }
InjectDistributedTracingExtension injects the tracecontext from the context into the event as a DistributedTracingExtension If a DistributedTracingExtension is present in the provided event, its current value is replaced with the tracecontext obtained from the context.
InjectDistributedTracingExtension
go
cloudevents/sdk-go
observability/opentelemetry/v2/client/cloudevents_carrier.go
https://github.com/cloudevents/sdk-go/blob/master/observability/opentelemetry/v2/client/cloudevents_carrier.go
Apache-2.0
func ExtractDistributedTracingExtension(ctx context.Context, event cloudevents.Event) context.Context { tc := propagation.TraceContext{} carrier := NewCloudEventCarrierWithEvent(ctx, event) return tc.Extract(ctx, carrier) }
ExtractDistributedTracingExtension extracts the tracecontext from the cloud event into the context. Calling this method will always replace the tracecontext in the context with the one extracted from the event. In case this is undesired, check first if the context has a recording span with: `trace.SpanFromContext(ctx)`
ExtractDistributedTracingExtension
go
cloudevents/sdk-go
observability/opentelemetry/v2/client/cloudevents_carrier.go
https://github.com/cloudevents/sdk-go/blob/master/observability/opentelemetry/v2/client/cloudevents_carrier.go
Apache-2.0
func NewOTelObservabilityService(opts ...OTelObservabilityServiceOption) *OTelObservabilityService { tracerProvider := otel.GetTracerProvider() o := &OTelObservabilityService{ tracer: tracerProvider.Tracer( instrumentationName, // TODO: Can we have the package version here? // trace.WithInstrumentationVersion("1.0.0"), ), spanNameFormatter: defaultSpanNameFormatter, } // apply passed options for _, opt := range opts { opt(o) } return o }
NewOTelObservabilityService returns an OpenTelemetry-enabled observability service
NewOTelObservabilityService
go
cloudevents/sdk-go
observability/opentelemetry/v2/client/otel_observability_service.go
https://github.com/cloudevents/sdk-go/blob/master/observability/opentelemetry/v2/client/otel_observability_service.go
Apache-2.0
func (o OTelObservabilityService) InboundContextDecorators() []func(context.Context, binding.Message) context.Context { return []func(context.Context, binding.Message) context.Context{tracePropagatorContextDecorator} }
InboundContextDecorators returns a decorator function that allows enriching the context with the incoming parent trace. This method gets invoked automatically by passing the option 'WithObservabilityService' when creating the cloudevents HTTP client.
InboundContextDecorators
go
cloudevents/sdk-go
observability/opentelemetry/v2/client/otel_observability_service.go
https://github.com/cloudevents/sdk-go/blob/master/observability/opentelemetry/v2/client/otel_observability_service.go
Apache-2.0
func (o OTelObservabilityService) RecordReceivedMalformedEvent(ctx context.Context, err error) { spanName := observability.ClientSpanName + ".malformed receive" _, span := o.tracer.Start( ctx, spanName, trace.WithSpanKind(trace.SpanKindConsumer), trace.WithAttributes(attribute.String(string(semconv.CodeFunctionKey), getFuncName()))) recordSpanError(span, err) span.End() }
RecordReceivedMalformedEvent records the error from a malformed event in the span.
RecordReceivedMalformedEvent
go
cloudevents/sdk-go
observability/opentelemetry/v2/client/otel_observability_service.go
https://github.com/cloudevents/sdk-go/blob/master/observability/opentelemetry/v2/client/otel_observability_service.go
Apache-2.0
func (o OTelObservabilityService) RecordCallingInvoker(ctx context.Context, event *cloudevents.Event) (context.Context, func(errOrResult error)) { spanName := o.getSpanName(event, "process") ctx, span := o.tracer.Start( ctx, spanName, trace.WithSpanKind(trace.SpanKindConsumer), trace.WithAttributes(GetDefaultSpanAttributes(event, getFuncName())...)) if span.IsRecording() && o.spanAttributesGetter != nil { span.SetAttributes(o.spanAttributesGetter(*event)...) } return ctx, func(errOrResult error) { recordSpanError(span, errOrResult) span.End() } }
RecordCallingInvoker starts a new span before calling the invoker upon a received event. In case the operation fails, the error is recorded and the span is marked as failed.
RecordCallingInvoker
go
cloudevents/sdk-go
observability/opentelemetry/v2/client/otel_observability_service.go
https://github.com/cloudevents/sdk-go/blob/master/observability/opentelemetry/v2/client/otel_observability_service.go
Apache-2.0
func (o OTelObservabilityService) RecordSendingEvent(ctx context.Context, event cloudevents.Event) (context.Context, func(errOrResult error)) { spanName := o.getSpanName(&event, "send") ctx, span := o.tracer.Start( ctx, spanName, trace.WithSpanKind(trace.SpanKindProducer), trace.WithAttributes(GetDefaultSpanAttributes(&event, getFuncName())...)) if span.IsRecording() && o.spanAttributesGetter != nil { span.SetAttributes(o.spanAttributesGetter(event)...) } return ctx, func(errOrResult error) { recordSpanError(span, errOrResult) span.End() } }
RecordSendingEvent starts a new span before sending the event. In case the operation fails, the error is recorded and the span is marked as failed.
RecordSendingEvent
go
cloudevents/sdk-go
observability/opentelemetry/v2/client/otel_observability_service.go
https://github.com/cloudevents/sdk-go/blob/master/observability/opentelemetry/v2/client/otel_observability_service.go
Apache-2.0
func GetDefaultSpanAttributes(e *cloudevents.Event, method string) []attribute.KeyValue { attr := []attribute.KeyValue{ attribute.String(string(semconv.CodeFunctionKey), method), attribute.String(observability.SpecversionAttr, e.SpecVersion()), attribute.String(observability.IdAttr, e.ID()), attribute.String(observability.TypeAttr, e.Type()), attribute.String(observability.SourceAttr, e.Source()), } if sub := e.Subject(); sub != "" { attr = append(attr, attribute.String(observability.SubjectAttr, sub)) } if dct := e.DataContentType(); dct != "" { attr = append(attr, attribute.String(observability.DatacontenttypeAttr, dct)) } return attr }
GetDefaultSpanAttributes returns the attributes that are always added to the spans created by the OTelObservabilityService.
GetDefaultSpanAttributes
go
cloudevents/sdk-go
observability/opentelemetry/v2/client/otel_observability_service.go
https://github.com/cloudevents/sdk-go/blob/master/observability/opentelemetry/v2/client/otel_observability_service.go
Apache-2.0
func tracePropagatorContextDecorator(ctx context.Context, msg binding.Message) context.Context { var messageCtx context.Context if mctx, ok := msg.(binding.MessageContext); ok { messageCtx = mctx.Context() } else if mctx, ok := binding.UnwrapMessage(msg).(binding.MessageContext); ok { messageCtx = mctx.Context() } if messageCtx == nil { return ctx } span := trace.SpanFromContext(messageCtx) if span == nil { return ctx } return trace.ContextWithSpan(ctx, span) }
Extracts the traceparent from the msg and enriches the context to enable propagation
tracePropagatorContextDecorator
go
cloudevents/sdk-go
observability/opentelemetry/v2/client/otel_observability_service.go
https://github.com/cloudevents/sdk-go/blob/master/observability/opentelemetry/v2/client/otel_observability_service.go
Apache-2.0
func (o OTelObservabilityService) getSpanName(e *cloudevents.Event, suffix string) string { name := o.spanNameFormatter(*e) // make sure the span name ends with the suffix from the semantic conventions (receive, send, process) if !strings.HasSuffix(name, suffix) { return name + " " + suffix } return name }
getSpanName Returns the name of the span. When no spanNameFormatter is present in OTelObservabilityService, the default name will be "cloudevents.client.<eventtype> prefix" e.g. cloudevents.client.get.customers send. The prefix is always added at the end of the span name. This follows the semantic conventions for messasing systems as defined in https://github.com/open-telemetry/opentelemetry-specification/blob/v1.6.1/specification/trace/semantic_conventions/messaging.md#operation-names
getSpanName
go
cloudevents/sdk-go
observability/opentelemetry/v2/client/otel_observability_service.go
https://github.com/cloudevents/sdk-go/blob/master/observability/opentelemetry/v2/client/otel_observability_service.go
Apache-2.0
func WithSpanAttributesGetter(attrGetter func(cloudevents.Event) []attribute.KeyValue) OTelObservabilityServiceOption { return func(os *OTelObservabilityService) { if attrGetter != nil { os.spanAttributesGetter = attrGetter } } }
WithSpanAttributesGetter appends the returned attributes from the function to the span.
WithSpanAttributesGetter
go
cloudevents/sdk-go
observability/opentelemetry/v2/client/otel_options.go
https://github.com/cloudevents/sdk-go/blob/master/observability/opentelemetry/v2/client/otel_options.go
Apache-2.0
func WithSpanNameFormatter(nameFormatter func(cloudevents.Event) string) OTelObservabilityServiceOption { return func(os *OTelObservabilityService) { if nameFormatter != nil { os.spanNameFormatter = nameFormatter } } }
WithSpanNameFormatter replaces the default span name with the string returned from the function
WithSpanNameFormatter
go
cloudevents/sdk-go
observability/opentelemetry/v2/client/otel_options.go
https://github.com/cloudevents/sdk-go/blob/master/observability/opentelemetry/v2/client/otel_options.go
Apache-2.0
func NewObservedHTTP(opts ...cehttp.Option) (*cehttp.Protocol, error) { // appends the OpenTelemetry Http transport + Middleware wrapper // to properly trace outgoing and incoming requests from the client using this protocol return cehttp.New(append( []cehttp.Option{ cehttp.WithRoundTripper(otelhttp.NewTransport(http.DefaultTransport)), cehttp.WithMiddleware(func(next http.Handler) http.Handler { return otelhttp.NewHandler(next, "cloudevents.http.receiver") }), }, opts..., )...) }
NewObservedHTTP creates an HTTP protocol with OTel trace propagating middleware.
NewObservedHTTP
go
cloudevents/sdk-go
observability/opentelemetry/v2/http/http.go
https://github.com/cloudevents/sdk-go/blob/master/observability/opentelemetry/v2/http/http.go
Apache-2.0
func NewMessage(message *amqp.Message, receiver *amqp.Receiver) *Message { var vn spec.Version var fmt format.Format if message.Properties != nil && message.Properties.ContentType != nil && format.IsFormat(*message.Properties.ContentType) { fmt = format.Lookup(*message.Properties.ContentType) } else if sv := getSpecVersion(message); sv != nil { vn = sv } return &Message{AMQP: message, AMQPrcv: receiver, format: fmt, version: vn} }
NewMessage wrap an *amqp.Message in a binding.Message. The returned message *can* be read several times safely
NewMessage
go
cloudevents/sdk-go
protocol/amqp/v2/message.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/amqp/v2/message.go
Apache-2.0
func (m *Message) getAmqpData() []byte { var data []byte amqpData := m.AMQP.Data // TODO: replace with slices.Concat once go mod bumped to 1.22 for idx := range amqpData { data = append(data, amqpData[idx]...) } return data }
fixes: github.com/cloudevents/spec/issues/1275
getAmqpData
go
cloudevents/sdk-go
protocol/amqp/v2/message.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/amqp/v2/message.go
Apache-2.0
func WithConnOpt(opt amqp.ConnOption) Option { return func(t *Protocol) error { t.connOpts = append(t.connOpts, opt) return nil } }
WithConnOpt sets a connection option for amqp
WithConnOpt
go
cloudevents/sdk-go
protocol/amqp/v2/options.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/amqp/v2/options.go
Apache-2.0
func WithConnSASLPlain(username, password string) Option { return WithConnOpt(amqp.ConnSASLPlain(username, password)) }
WithConnSASLPlain sets SASLPlain connection option for amqp
WithConnSASLPlain
go
cloudevents/sdk-go
protocol/amqp/v2/options.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/amqp/v2/options.go
Apache-2.0
func WithSessionOpt(opt amqp.SessionOption) Option { return func(t *Protocol) error { t.sessionOpts = append(t.sessionOpts, opt) return nil } }
WithSessionOpt sets a session option for amqp
WithSessionOpt
go
cloudevents/sdk-go
protocol/amqp/v2/options.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/amqp/v2/options.go
Apache-2.0
func WithSenderLinkOption(opt amqp.LinkOption) Option { return func(t *Protocol) error { t.senderLinkOpts = append(t.senderLinkOpts, opt) return nil } }
WithSenderLinkOption sets a link option for amqp
WithSenderLinkOption
go
cloudevents/sdk-go
protocol/amqp/v2/options.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/amqp/v2/options.go
Apache-2.0
func WithReceiverLinkOption(opt amqp.LinkOption) Option { return func(t *Protocol) error { t.receiverLinkOpts = append(t.receiverLinkOpts, opt) return nil } }
WithReceiverLinkOption sets a link option for amqp
WithReceiverLinkOption
go
cloudevents/sdk-go
protocol/amqp/v2/options.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/amqp/v2/options.go
Apache-2.0
func NewSenderProtocolFromClient(client *amqp.Client, session *amqp.Session, address string, opts ...Option) (*Protocol, error) { t := &Protocol{ Node: address, senderLinkOpts: []amqp.LinkOption(nil), receiverLinkOpts: []amqp.LinkOption(nil), Client: client, Session: session, } if err := t.applyOptions(opts...); err != nil { return nil, err } t.senderLinkOpts = append(t.senderLinkOpts, amqp.LinkTargetAddress(address)) // Create a sender amqpSender, err := session.NewSender(t.senderLinkOpts...) if err != nil { _ = client.Close() _ = session.Close(context.Background()) return nil, err } t.Sender = NewSender(amqpSender).(*sender) t.SenderContextDecorators = []func(context.Context) context.Context{} return t, nil }
NewSenderProtocolFromClient creates a new amqp sender transport.
NewSenderProtocolFromClient
go
cloudevents/sdk-go
protocol/amqp/v2/protocol.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/amqp/v2/protocol.go
Apache-2.0
func NewReceiverProtocolFromClient(client *amqp.Client, session *amqp.Session, address string, opts ...Option) (*Protocol, error) { t := &Protocol{ Node: address, senderLinkOpts: []amqp.LinkOption(nil), receiverLinkOpts: []amqp.LinkOption(nil), Client: client, Session: session, } if err := t.applyOptions(opts...); err != nil { return nil, err } t.Node = address t.receiverLinkOpts = append(t.receiverLinkOpts, amqp.LinkSourceAddress(address)) amqpReceiver, err := t.Session.NewReceiver(t.receiverLinkOpts...) if err != nil { return nil, err } t.Receiver = NewReceiver(amqpReceiver).(*receiver) return t, nil }
NewReceiverProtocolFromClient creates a new receiver amqp transport.
NewReceiverProtocolFromClient
go
cloudevents/sdk-go
protocol/amqp/v2/protocol.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/amqp/v2/protocol.go
Apache-2.0
func NewSenderProtocol(server, address string, connOption []amqp.ConnOption, sessionOption []amqp.SessionOption, opts ...Option) (*Protocol, error) { client, err := amqp.Dial(server, connOption...) if err != nil { return nil, err } // Open a session session, err := client.NewSession(sessionOption...) if err != nil { _ = client.Close() return nil, err } p, err := NewSenderProtocolFromClient(client, session, address, opts...) if err != nil { return nil, err } p.ownedClient = true return p, nil }
NewSenderProtocol creates a new sender amqp transport.
NewSenderProtocol
go
cloudevents/sdk-go
protocol/amqp/v2/protocol.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/amqp/v2/protocol.go
Apache-2.0
func NewReceiverProtocol(server, address string, connOption []amqp.ConnOption, sessionOption []amqp.SessionOption, opts ...Option) (*Protocol, error) { client, err := amqp.Dial(server, connOption...) if err != nil { return nil, err } // Open a session session, err := client.NewSession(sessionOption...) if err != nil { _ = client.Close() return nil, err } p, err := NewReceiverProtocolFromClient(client, session, address, opts...) if err != nil { return nil, err } p.ownedClient = true return p, nil }
NewReceiverProtocol creates a new receiver amqp transport.
NewReceiverProtocol
go
cloudevents/sdk-go
protocol/amqp/v2/protocol.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/amqp/v2/protocol.go
Apache-2.0
func NewReceiver(amqp *amqp.Receiver) protocol.Receiver { return &receiver{amqp: amqp} }
NewReceiver create a new Receiver which wraps an amqp.Receiver in a binding.Receiver
NewReceiver
go
cloudevents/sdk-go
protocol/amqp/v2/receiver.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/amqp/v2/receiver.go
Apache-2.0
func NewSender(amqpSender *amqp.Sender, options ...SenderOptionFunc) protocol.Sender { s := &sender{amqp: amqpSender} for _, o := range options { o(s) } return s }
NewSender creates a new Sender which wraps an amqp.Sender in a binding.Sender
NewSender
go
cloudevents/sdk-go
protocol/amqp/v2/sender.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/amqp/v2/sender.go
Apache-2.0
func WriteMessage(ctx context.Context, m binding.Message, amqpMessage *amqp.Message, transformers ...binding.Transformer) error { structuredWriter := (*amqpMessageWriter)(amqpMessage) binaryWriter := (*amqpMessageWriter)(amqpMessage) _, err := binding.Write( ctx, m, structuredWriter, binaryWriter, transformers..., ) return err }
WriteMessage fills the provided amqpMessage with the message m. Using context you can tweak the encoding processing (more details on binding.Write documentation).
WriteMessage
go
cloudevents/sdk-go
protocol/amqp/v2/write_message.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/amqp/v2/write_message.go
Apache-2.0
func NewMessage(msg *kafka.Message) *Message { if msg == nil { panic("the kafka.Message shouldn't be nil") } if msg.TopicPartition.Topic == nil { panic("the topic of kafka.Message shouldn't be nil") } if msg.TopicPartition.Partition < 0 || msg.TopicPartition.Offset < 0 { panic("the partition or offset of the kafka.Message must be non-negative") } var contentType, contentVersion string properties := make(map[string][]byte, len(msg.Headers)+3) for _, header := range msg.Headers { k := strings.ToLower(string(header.Key)) if k == strings.ToLower(contentTypeKey) { contentType = string(header.Value) } if k == specs.PrefixedSpecVersionName() { contentVersion = string(header.Value) } properties[k] = header.Value } // add the kafka message key, topic, partition and partition key to the properties properties[prefix+KafkaOffsetKey] = []byte(strconv.FormatInt(int64(msg.TopicPartition.Offset), 10)) properties[prefix+KafkaPartitionKey] = []byte(strconv.FormatInt(int64(msg.TopicPartition.Partition), 10)) properties[prefix+KafkaTopicKey] = []byte(*msg.TopicPartition.Topic) if msg.Key != nil { properties[prefix+KafkaMessageKey] = msg.Key } message := &Message{ internal: msg, properties: properties, } if ft := format.Lookup(contentType); ft != nil { message.format = ft } else if v := specs.Version(contentVersion); v != nil { message.version = v } return message }
NewMessage returns a binding.Message that holds the provided kafka.Message. The returned binding.Message *can* be read several times safely This function *doesn't* guarantee that the returned binding.Message is always a kafka_sarama.Message instance
NewMessage
go
cloudevents/sdk-go
protocol/kafka_confluent/v2/message.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_confluent/v2/message.go
Apache-2.0
func WithConfigMap(config *kafka.ConfigMap) Option { return func(p *Protocol) error { if config == nil { return errors.New("the kafka.ConfigMap option must not be nil") } p.kafkaConfigMap = config return nil } }
WithConfigMap sets the configMap to init the kafka client.
WithConfigMap
go
cloudevents/sdk-go
protocol/kafka_confluent/v2/option.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_confluent/v2/option.go
Apache-2.0
func WithSenderTopic(defaultTopic string) Option { return func(p *Protocol) error { if defaultTopic == "" { return errors.New("the producer topic option must not be nil") } p.producerDefaultTopic = defaultTopic return nil } }
WithSenderTopic sets the defaultTopic for the kafka.Producer.
WithSenderTopic
go
cloudevents/sdk-go
protocol/kafka_confluent/v2/option.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_confluent/v2/option.go
Apache-2.0
func WithReceiverTopics(topics []string) Option { return func(p *Protocol) error { if topics == nil { return errors.New("the consumer topics option must not be nil") } p.consumerTopics = topics return nil } }
WithReceiverTopics sets the topics for the kafka.Consumer.
WithReceiverTopics
go
cloudevents/sdk-go
protocol/kafka_confluent/v2/option.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_confluent/v2/option.go
Apache-2.0
func WithRebalanceCallBack(rebalanceCb kafka.RebalanceCb) Option { return func(p *Protocol) error { if rebalanceCb == nil { return errors.New("the consumer group rebalance callback must not be nil") } p.consumerRebalanceCb = rebalanceCb return nil } }
WithRebalanceCallBack sets the callback for rebalancing of the consumer group.
WithRebalanceCallBack
go
cloudevents/sdk-go
protocol/kafka_confluent/v2/option.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_confluent/v2/option.go
Apache-2.0
func WithPollTimeout(timeoutMs int) Option { return func(p *Protocol) error { p.consumerPollTimeout = timeoutMs return nil } }
WithPollTimeout sets timeout of the consumer polling for message or events, return nil on timeout.
WithPollTimeout
go
cloudevents/sdk-go
protocol/kafka_confluent/v2/option.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_confluent/v2/option.go
Apache-2.0
func WithSender(producer *kafka.Producer) Option { return func(p *Protocol) error { if producer == nil { return errors.New("the producer option must not be nil") } p.producer = producer return nil } }
WithSender set a kafka.Producer instance to init the client directly.
WithSender
go
cloudevents/sdk-go
protocol/kafka_confluent/v2/option.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_confluent/v2/option.go
Apache-2.0
func WithErrorHandler(handler func(ctx context.Context, err kafka.Error)) Option { return func(p *Protocol) error { p.consumerErrorHandler = handler return nil } }
WithErrorHandler provide a func on how to handle the kafka.Error which the kafka.Consumer has polled.
WithErrorHandler
go
cloudevents/sdk-go
protocol/kafka_confluent/v2/option.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_confluent/v2/option.go
Apache-2.0
func WithReceiver(consumer *kafka.Consumer) Option { return func(p *Protocol) error { if consumer == nil { return errors.New("the consumer option must not be nil") } p.consumer = consumer return nil } }
WithReceiver set a kafka.Consumer instance to init the client directly.
WithReceiver
go
cloudevents/sdk-go
protocol/kafka_confluent/v2/option.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_confluent/v2/option.go
Apache-2.0
func WithTopicPartitionOffsets(ctx context.Context, topicPartitionOffsets []kafka.TopicPartition) context.Context { if len(topicPartitionOffsets) == 0 { panic("the topicPartitionOffsets cannot be empty") } for _, offset := range topicPartitionOffsets { if offset.Topic == nil || *(offset.Topic) == "" { panic("the kafka topic cannot be nil or empty") } if offset.Partition < 0 || offset.Offset < 0 { panic("the kafka partition/offset must be non-negative") } } return context.WithValue(ctx, offsetKey, topicPartitionOffsets) }
WithTopicPartitionOffsets will set the positions where the consumer starts consuming from.
WithTopicPartitionOffsets
go
cloudevents/sdk-go
protocol/kafka_confluent/v2/option.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_confluent/v2/option.go
Apache-2.0
func TopicPartitionOffsetsFrom(ctx context.Context) []kafka.TopicPartition { c := ctx.Value(offsetKey) if c != nil { if s, ok := c.([]kafka.TopicPartition); ok { return s } } return nil }
TopicPartitionOffsetsFrom looks in the given context and returns []kafka.TopicPartition or nil if not set
TopicPartitionOffsetsFrom
go
cloudevents/sdk-go
protocol/kafka_confluent/v2/option.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_confluent/v2/option.go
Apache-2.0
func WithMessageKey(ctx context.Context, messageKey string) context.Context { return context.WithValue(ctx, keyForMessageKey, messageKey) }
WithMessageKey returns back a new context with the given messageKey.
WithMessageKey
go
cloudevents/sdk-go
protocol/kafka_confluent/v2/option.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_confluent/v2/option.go
Apache-2.0
func MessageKeyFrom(ctx context.Context) string { c := ctx.Value(keyForMessageKey) if c != nil { if s, ok := c.(string); ok { return s } } return "" }
MessageKeyFrom looks in the given context and returns `messageKey` as a string if found and valid, otherwise "".
MessageKeyFrom
go
cloudevents/sdk-go
protocol/kafka_confluent/v2/option.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_confluent/v2/option.go
Apache-2.0
func (p *Protocol) Events() (chan kafka.Event, error) { if p.producer == nil { return nil, errors.New("producer not set") } return p.producer.Events(), nil }
Events returns the events channel used by Confluent Kafka to deliver the result from a produce, i.e., send, operation. When using this SDK to produce (send) messages, this channel must be monitored to avoid resource leaks and this channel becoming full. See Confluent SDK for Go for details on the implementation.
Events
go
cloudevents/sdk-go
protocol/kafka_confluent/v2/protocol.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_confluent/v2/protocol.go
Apache-2.0
func (p *Protocol) Send(ctx context.Context, in binding.Message, transformers ...binding.Transformer) (err error) { if p.producer == nil { return errors.New("producer client must be set") } p.closerMux.Lock() defer p.closerMux.Unlock() if p.producer.IsClosed() { return errors.New("producer is closed") } defer in.Finish(err) kafkaMsg := &kafka.Message{ TopicPartition: kafka.TopicPartition{ Topic: &p.producerDefaultTopic, Partition: kafka.PartitionAny, }, } if topic := cecontext.TopicFrom(ctx); topic != "" { kafkaMsg.TopicPartition.Topic = &topic } if messageKey := MessageKeyFrom(ctx); messageKey != "" { kafkaMsg.Key = []byte(messageKey) } if err = WriteProducerMessage(ctx, in, kafkaMsg, transformers...); err != nil { return fmt.Errorf("create producer message: %w", err) } if err = p.producer.Produce(kafkaMsg, nil); err != nil { return fmt.Errorf("produce message: %w", err) } return nil }
Send message by kafka.Producer. You must monitor the Events() channel when using this function.
Send
go
cloudevents/sdk-go
protocol/kafka_confluent/v2/protocol.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_confluent/v2/protocol.go
Apache-2.0
func (p *Protocol) Close(ctx context.Context) error { p.closerMux.Lock() defer p.closerMux.Unlock() logger := cecontext.LoggerFrom(ctx) if p.consumerCancel != nil { p.consumerCancel() } if p.producer != nil && !p.producer.IsClosed() { // Flush and close the producer with a 10 seconds timeout (closes Events channel) for p.producer.Flush(10000) > 0 { logger.Info("Flushing outstanding messages") } p.producer.Close() } return nil }
Close cleans up resources after use. Must be called to properly close underlying Kafka resources and avoid resource leaks
Close
go
cloudevents/sdk-go
protocol/kafka_confluent/v2/protocol.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_confluent/v2/protocol.go
Apache-2.0
func WriteProducerMessage(ctx context.Context, in binding.Message, kafkaMsg *kafka.Message, transformers ...binding.Transformer, ) error { structuredWriter := (*kafkaMessageWriter)(kafkaMsg) binaryWriter := (*kafkaMessageWriter)(kafkaMsg) _, err := binding.Write( ctx, in, structuredWriter, binaryWriter, transformers..., ) return err }
WriteProducerMessage fills the provided pubMessage with the message m. Using context you can tweak the encoding processing (more details on binding.Write documentation).
WriteProducerMessage
go
cloudevents/sdk-go
protocol/kafka_confluent/v2/write_producer_message.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_confluent/v2/write_producer_message.go
Apache-2.0
func NewMessageFromConsumerMessage(cm *sarama.ConsumerMessage) *Message { var contentType string headers := make(map[string][]byte, len(cm.Headers)+3) for _, r := range cm.Headers { k := strings.ToLower(string(r.Key)) if k == contentTypeHeader { contentType = string(r.Value) } headers[k] = r.Value } headers[prefix+"kafkaoffset"] = []byte(strconv.FormatInt(cm.Offset, 10)) headers[prefix+"kafkapartition"] = []byte(strconv.FormatInt(int64(cm.Partition), 10)) headers[prefix+"kafkatopic"] = []byte(cm.Topic) return NewMessage(cm.Value, contentType, headers) }
NewMessageFromConsumerMessage returns a binding.Message that holds the provided ConsumerMessage. The returned binding.Message *can* be read several times safely This function *doesn't* guarantee that the returned binding.Message is always a kafka_sarama.Message instance
NewMessageFromConsumerMessage
go
cloudevents/sdk-go
protocol/kafka_sarama/v2/message.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_sarama/v2/message.go
Apache-2.0
func NewMessage(value []byte, contentType string, headers map[string][]byte) *Message { if ft := format.Lookup(contentType); ft != nil { return &Message{ Value: value, ContentType: contentType, Headers: headers, format: ft, } } else if v := specs.Version(string(headers[specs.PrefixedSpecVersionName()])); v != nil { return &Message{ Value: value, ContentType: contentType, Headers: headers, version: v, } } return &Message{ Value: value, ContentType: contentType, Headers: headers, } }
NewMessage returns a binding.Message that holds the provided kafka message components. The returned binding.Message *can* be read several times safely This function *doesn't* guarantee that the returned binding.Message is always a kafka_sarama.Message instance
NewMessage
go
cloudevents/sdk-go
protocol/kafka_sarama/v2/message.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_sarama/v2/message.go
Apache-2.0
func NewProtocolFromClient(client sarama.Client, sendToTopic string, receiveFromTopic string, opts ...ProtocolOptionFunc) (*Protocol, error) { p := &Protocol{ Client: client, SenderContextDecorators: make([]func(context.Context) context.Context, 0), receiverGroupId: defaultGroupId, senderTopic: sendToTopic, receiverTopic: receiveFromTopic, ownsClient: false, } var err error if err = p.applyOptions(opts...); err != nil { return nil, err } if p.senderTopic == "" { return nil, errors.New("you didn't specify the topic to send to") } p.Sender, err = NewSenderFromClient(p.Client, p.senderTopic) if err != nil { return nil, err } if p.receiverTopic == "" { return nil, errors.New("you didn't specify the topic to receive from") } p.Consumer = NewConsumerFromClient(p.Client, p.receiverGroupId, p.receiverTopic) return p, nil }
NewProtocolFromClient creates a new kafka transport starting from a sarama.Client
NewProtocolFromClient
go
cloudevents/sdk-go
protocol/kafka_sarama/v2/protocol.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_sarama/v2/protocol.go
Apache-2.0
func (p *Protocol) OpenInbound(ctx context.Context) error { p.consumerMux.Lock() defer p.consumerMux.Unlock() logger := cecontext.LoggerFrom(ctx) logger.Infof("Starting consumer group to topic %s and group id %s", p.receiverTopic, p.receiverGroupId) return p.Consumer.OpenInbound(ctx) }
OpenInbound implements Opener.OpenInbound NOTE: This is a blocking call.
OpenInbound
go
cloudevents/sdk-go
protocol/kafka_sarama/v2/protocol.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_sarama/v2/protocol.go
Apache-2.0
func NewReceiver() *Receiver { return &Receiver{ incoming: make(chan msgErr), } }
NewReceiver creates a Receiver which implements sarama.ConsumerGroupHandler The sarama.ConsumerGroup must be started invoking. If you need a Receiver which also manage the ConsumerGroup, use NewConsumer After the first invocation of Receiver.Receive(), the sarama.ConsumerGroup is created and started.
NewReceiver
go
cloudevents/sdk-go
protocol/kafka_sarama/v2/receiver.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_sarama/v2/receiver.go
Apache-2.0
func (r *Receiver) ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error { // NOTE: // Do not move the code below to a goroutine. // The `ConsumeClaim` itself is called within a goroutine, see: // https://github.com/Shopify/sarama/blob/main/consumer_group.go#L27-L29 for { select { case msg, ok := <-claim.Messages(): if !ok { return nil } m := NewMessageFromConsumerMessage(msg) msgErrObj := msgErr{ msg: binding.WithFinish(m, func(err error) { if protocol.IsACK(err) { session.MarkMessage(msg, "") } }), } // Need to use select clause here, otherwise r.incoming <- msgErrObj can become a blocking operation, // resulting in never reaching outside block's case <-session.Context().Done() select { case r.incoming <- msgErrObj: // do nothing case <-session.Context().Done(): return nil } // Should return when `session.Context()` is done. // If not, will raise `ErrRebalanceInProgress` or `read tcp <ip>:<port>: i/o timeout` when kafka rebalance. see: // https://github.com/Shopify/sarama/issues/1192 // https://github.com/Shopify/sarama/issues/2118 // Also checked Shopify/sarama code which calls this ConsumeClaim method, and don't see if there is any difference // whether this method returns error or not. If it returns the error, as per current implementation, it could // get printed in logs and later drained when the ConsumerGroup gets closed. // For now, to be on safer side, returning nil instead of session.Context().Err() as suggested in // https://github.com/Shopify/sarama/blob/5e2c2ef0e429f895c86152189f625bfdad7d3452/examples/consumergroup/main.go case <-session.Context().Done(): return nil } } }
ConsumeClaim must start a consumer loop of ConsumerGroupClaim's Messages(). Also the method should return when `session.Context()` is done. Refer - https://github.com/Shopify/sarama/blob/5e2c2ef0e429f895c86152189f625bfdad7d3452/examples/consumergroup/main.go#L177
ConsumeClaim
go
cloudevents/sdk-go
protocol/kafka_sarama/v2/receiver.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_sarama/v2/receiver.go
Apache-2.0
func NewSender(brokers []string, saramaConfig *sarama.Config, topic string, options ...SenderOptionFunc) (*Sender, error) { // Force this setting because it's required by sarama SyncProducer saramaConfig.Producer.Return.Successes = true producer, err := sarama.NewSyncProducer(brokers, saramaConfig) if err != nil { return nil, err } return makeSender(producer, topic, options...), nil }
NewSender returns a binding.Sender that sends messages to a specific receiverTopic using sarama.SyncProducer
NewSender
go
cloudevents/sdk-go
protocol/kafka_sarama/v2/sender.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_sarama/v2/sender.go
Apache-2.0
func NewSenderFromClient(client sarama.Client, topic string, options ...SenderOptionFunc) (*Sender, error) { producer, err := sarama.NewSyncProducerFromClient(client) if err != nil { return nil, err } return makeSender(producer, topic, options...), nil }
NewSenderFromClient returns a binding.Sender that sends messages to a specific receiverTopic using sarama.SyncProducer
NewSenderFromClient
go
cloudevents/sdk-go
protocol/kafka_sarama/v2/sender.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_sarama/v2/sender.go
Apache-2.0
func NewSenderFromSyncProducer(topic string, syncProducer sarama.SyncProducer, options ...SenderOptionFunc) (*Sender, error) { return makeSender(syncProducer, topic, options...), nil }
NewSenderFromSyncProducer returns a binding.Sender that sends messages to a specific topic using sarama.SyncProducer
NewSenderFromSyncProducer
go
cloudevents/sdk-go
protocol/kafka_sarama/v2/sender.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_sarama/v2/sender.go
Apache-2.0
func WithMessageKey(ctx context.Context, key sarama.Encoder) context.Context { return context.WithValue(ctx, withMessageKey{}, key) }
WithMessageKey allows to set the key used when sending the producer message
WithMessageKey
go
cloudevents/sdk-go
protocol/kafka_sarama/v2/sender.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_sarama/v2/sender.go
Apache-2.0
func WriteProducerMessage(ctx context.Context, m binding.Message, producerMessage *sarama.ProducerMessage, transformers ...binding.Transformer) error { writer := (*kafkaProducerMessageWriter)(producerMessage) skipKey := binding.GetOrDefaultFromCtx(ctx, skipKeyKey{}, false).(bool) var key string // If skipKey = false, then we add a transformer that extracts the key if !skipKey { transformers = append(transformers, binding.TransformerFunc(func(r binding.MessageMetadataReader, w binding.MessageMetadataWriter) error { ext := r.GetExtension(partitionKey) if !types.IsZero(ext) { extStr, err := types.Format(ext) if err != nil { return err } key = extStr } return nil })) } _, err := binding.Write( ctx, m, writer, writer, transformers..., ) if key != "" { producerMessage.Key = sarama.StringEncoder(key) } return err }
WriteProducerMessage fills the provided producerMessage with the message m. Using context you can tweak the encoding processing (more details on binding.Write documentation). By default, this function implements the key mapping, trying to set the key of the message based on partitionKey extension. If you want to disable the Key Mapping, decorate the context with `WithSkipKeyMapping`
WriteProducerMessage
go
cloudevents/sdk-go
protocol/kafka_sarama/v2/write_producer_message.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/kafka_sarama/v2/write_producer_message.go
Apache-2.0
func WithConnect(connOpt *paho.Connect) Option { return func(p *Protocol) error { if connOpt == nil { return fmt.Errorf("the paho.Connect option must not be nil") } p.connOption = connOpt return nil } }
WithConnect sets the paho.Connect configuration for the client. This option is not required.
WithConnect
go
cloudevents/sdk-go
protocol/mqtt_paho/v2/option.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/mqtt_paho/v2/option.go
Apache-2.0
func WithPublish(publishOpt *paho.Publish) Option { return func(p *Protocol) error { if publishOpt == nil { return fmt.Errorf("the paho.Publish option must not be nil") } p.publishOption = publishOpt return nil } }
WithPublish sets the paho.Publish configuration for the client. This option is required if you want to send messages.
WithPublish
go
cloudevents/sdk-go
protocol/mqtt_paho/v2/option.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/mqtt_paho/v2/option.go
Apache-2.0
func WithSubscribe(subscribeOpt *paho.Subscribe) Option { return func(p *Protocol) error { if subscribeOpt == nil { return fmt.Errorf("the paho.Subscribe option must not be nil") } p.subscribeOption = subscribeOpt return nil } }
WithSubscribe sets the paho.Subscribe configuration for the client. This option is required if you want to receive messages.
WithSubscribe
go
cloudevents/sdk-go
protocol/mqtt_paho/v2/option.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/mqtt_paho/v2/option.go
Apache-2.0
func (p *Protocol) publishMsg() *paho.Publish { return &paho.Publish{ QoS: p.publishOption.QoS, Retain: p.publishOption.Retain, Topic: p.publishOption.Topic, Properties: p.publishOption.Properties, } }
publishMsg generate a new paho.Publish message from the p.publishOption
publishMsg
go
cloudevents/sdk-go
protocol/mqtt_paho/v2/protocol.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/mqtt_paho/v2/protocol.go
Apache-2.0
func WritePubMessage(ctx context.Context, m binding.Message, pubMessage *paho.Publish, transformers ...binding.Transformer) error { structuredWriter := (*pubMessageWriter)(pubMessage) binaryWriter := (*pubMessageWriter)(pubMessage) _, err := binding.Write( ctx, m, structuredWriter, binaryWriter, transformers..., ) return err }
WritePubMessage fills the provided pubMessage with the message m. Using context you can tweak the encoding processing (more details on binding.Write documentation).
WritePubMessage
go
cloudevents/sdk-go
protocol/mqtt_paho/v2/write_message.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/mqtt_paho/v2/write_message.go
Apache-2.0
func NewMessage(msg *nats.Msg) *Message { return &Message{Msg: msg, encoding: binding.EncodingStructured} }
NewMessage wraps an *nats.Msg in a binding.Message. The returned message *can* be read several times safely
NewMessage
go
cloudevents/sdk-go
protocol/nats/v2/message.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats/v2/message.go
Apache-2.0
func NewReceiver() *Receiver { return &Receiver{ incoming: make(chan msgErr), } }
NewReceiver creates a new protocol.Receiver responsible for receiving messages.
NewReceiver
go
cloudevents/sdk-go
protocol/nats_jetstream/v2/receiver.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v2/receiver.go
Apache-2.0
func (s *Sender) Send(ctx context.Context, in binding.Message, transformers ...binding.Transformer) (err error) { defer func() { if err2 := in.Finish(err); err2 != nil { if err == nil { err = err2 } else { err = fmt.Errorf("failed to call in.Finish() when error already occurred: %s: %w", err2.Error(), err) } } }() writer := new(bytes.Buffer) header, err := WriteMsg(ctx, in, writer, transformers...) if err != nil { return err } natsMsg := &nats.Msg{ Subject: s.Subject, Data: writer.Bytes(), Header: header, } _, err = s.Jsm.PublishMsg(natsMsg) return err }
Close implements Sender.Sender Sender sends messages.
Send
go
cloudevents/sdk-go
protocol/nats_jetstream/v2/sender.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v2/sender.go
Apache-2.0
func WithURL(url string) ProtocolOption { return func(p *Protocol) error { p.url = url return nil } }
WithURL creates a connection to be used in the protocol sender and receiver. This option is mutually exclusive with WithConnection.
WithURL
go
cloudevents/sdk-go
protocol/nats_jetstream/v3/options.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/options.go
Apache-2.0
func WithNatsOptions(natsOpts []nats.Option) ProtocolOption { return func(p *Protocol) error { p.natsOpts = natsOpts return nil } }
WithNatsOptions can be used together with WithURL() to specify NATS connection options
WithNatsOptions
go
cloudevents/sdk-go
protocol/nats_jetstream/v3/options.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/options.go
Apache-2.0
func WithConnection(conn *nats.Conn) ProtocolOption { return func(p *Protocol) error { p.conn = conn return nil } }
WithConnection uses the provided connection in the protocol sender and receiver This option is mutually exclusive with WithURL.
WithConnection
go
cloudevents/sdk-go
protocol/nats_jetstream/v3/options.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/options.go
Apache-2.0
func WithJetStreamOptions(jetStreamOpts []jetstream.JetStreamOpt) ProtocolOption { return func(p *Protocol) error { p.jetStreamOpts = jetStreamOpts return nil } }
WithJetStreamOptions sets jetstream options used in the protocol sender and receiver
WithJetStreamOptions
go
cloudevents/sdk-go
protocol/nats_jetstream/v3/options.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/options.go
Apache-2.0
func WithPublishOptions(publishOpts []jetstream.PublishOpt) ProtocolOption { return func(p *Protocol) error { p.publishOpts = publishOpts return nil } }
WithPublishOptions sets publish options used in the protocol sender
WithPublishOptions
go
cloudevents/sdk-go
protocol/nats_jetstream/v3/options.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/options.go
Apache-2.0
func WithSendSubject(sendSubject string) ProtocolOption { return func(p *Protocol) error { p.sendSubject = sendSubject return nil } }
WithSendSubject sets the subject used in the protocol sender
WithSendSubject
go
cloudevents/sdk-go
protocol/nats_jetstream/v3/options.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/options.go
Apache-2.0
func WithConsumerConfig(consumerConfig *jetstream.ConsumerConfig) ProtocolOption { return func(p *Protocol) error { p.consumerConfig = consumerConfig return nil } }
WithConsumerConfig creates a unordered consumer used in the protocol receiver. This option is mutually exclusive with WithOrderedConsumerConfig.
WithConsumerConfig
go
cloudevents/sdk-go
protocol/nats_jetstream/v3/options.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/options.go
Apache-2.0
func WithOrderedConsumerConfig(orderedConsumerConfig *jetstream.OrderedConsumerConfig) ProtocolOption { return func(p *Protocol) error { p.orderedConsumerConfig = orderedConsumerConfig return nil } }
WithOrderedConsumerConfig creates a ordered consumer used in the protocol receiver. This option is mutually exclusive with WithConsumerConfig.
WithOrderedConsumerConfig
go
cloudevents/sdk-go
protocol/nats_jetstream/v3/options.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/options.go
Apache-2.0
func WithPullConsumerOptions(pullConsumeOpts []jetstream.PullConsumeOpt) ProtocolOption { return func(p *Protocol) error { p.pullConsumeOpts = pullConsumeOpts return nil } }
WithPullConsumerOptions sets pull options used in the protocol receiver.
WithPullConsumerOptions
go
cloudevents/sdk-go
protocol/nats_jetstream/v3/options.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/options.go
Apache-2.0
func WithSubject(ctx context.Context, subject string) context.Context { return context.WithValue(ctx, ctxKeySubject, subject) }
WithSubject returns a new context with the subject set to the provided value. This subject will be used when sending or receiving messages and overrides the default.
WithSubject
go
cloudevents/sdk-go
protocol/nats_jetstream/v3/protocol.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/protocol.go
Apache-2.0
func (p *Protocol) Send(ctx context.Context, in binding.Message, transformers ...binding.Transformer) (err error) { subject := p.getSendSubject(ctx) if subject == "" { return newValidationError(fieldSendSubject, messageNoSendSubject) } defer func() { if err2 := in.Finish(err); err2 != nil { if err == nil { err = err2 } else { err = fmt.Errorf("failed to call in.Finish() when error already occurred: %s: %w", err2.Error(), err) } } }() if _, err = p.jetStream.StreamNameBySubject(ctx, subject); err != nil { return err } writer := new(bytes.Buffer) header, err := WriteMsg(ctx, in, writer, transformers...) if err != nil { return err } natsMsg := &nats.Msg{ Subject: subject, Data: writer.Bytes(), Header: header, } _, err = p.jetStream.PublishMsg(ctx, natsMsg, p.publishOpts...) return err }
Send sends messages. Send implements Sender.Sender
Send
go
cloudevents/sdk-go
protocol/nats_jetstream/v3/protocol.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/protocol.go
Apache-2.0
func (p *Protocol) Close(ctx context.Context) error { // Before closing, let's be sure OpenInbound completes // We send a signal to close and then we lock on subMtx in order // to wait OpenInbound to finish draining the queue p.internalClose <- struct{}{} p.subMtx.Lock() defer p.subMtx.Unlock() // if an URL was provided, then we must close the internally opened NATS connection // since the connection is not exposed. // If the connection was passed in, then leave the connection available. if p.url != "" && p.conn != nil { p.conn.Close() } close(p.internalClose) return nil }
Close must be called after use to releases internal resources. If WithURL option was used, the NATS connection internally opened will be closed.
Close
go
cloudevents/sdk-go
protocol/nats_jetstream/v3/protocol.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/protocol.go
Apache-2.0
func (p *Protocol) applyOptions(opts ...ProtocolOption) error { for _, fn := range opts { if err := fn(p); err != nil { return err } } return nil }
applyOptions at the protocol layer should run before the sender and receiver are created. This allows the protocol to create a nats connection that can be shared for both the sender and receiver.
applyOptions
go
cloudevents/sdk-go
protocol/nats_jetstream/v3/protocol.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/protocol.go
Apache-2.0
func (p *Protocol) createJetstreamConsumer(ctx context.Context) error { var err error var stream string if stream, err = p.getStreamFromSubjects(ctx); err != nil { return err } var consumerErr error if p.consumerConfig != nil { p.jetstreamConsumer, consumerErr = p.jetStream.CreateOrUpdateConsumer(ctx, stream, *p.consumerConfig) } else if p.orderedConsumerConfig != nil { p.jetstreamConsumer, consumerErr = p.jetStream.OrderedConsumer(ctx, stream, *p.orderedConsumerConfig) } else { return newValidationError(fieldConsumerConfig, messageNoConsumerConfig) } return consumerErr }
createJetstreamConsumer creates a consumer based on the configured consumer config
createJetstreamConsumer
go
cloudevents/sdk-go
protocol/nats_jetstream/v3/protocol.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/protocol.go
Apache-2.0
func (p *Protocol) getStreamFromSubjects(ctx context.Context) (string, error) { var subjects []string if p.consumerConfig != nil && p.consumerConfig.FilterSubject != "" { subjects = []string{p.consumerConfig.FilterSubject} } if p.consumerConfig != nil && len(p.consumerConfig.FilterSubjects) > 0 { subjects = p.consumerConfig.FilterSubjects } if p.orderedConsumerConfig != nil && len(p.orderedConsumerConfig.FilterSubjects) > 0 { subjects = p.orderedConsumerConfig.FilterSubjects } if len(subjects) == 0 { return "", newValidationError(fieldFilterSubjects, messageNoFilterSubjects) } var finalStream string for i, subject := range subjects { currentStream, err := p.jetStream.StreamNameBySubject(ctx, subject) if err != nil { return "", err } if i == 0 { finalStream = currentStream continue } if finalStream != currentStream { return "", newValidationError(fieldFilterSubjects, messageMoreThanOneStream) } } return finalStream, nil }
getStreamFromSubjects finds the unique stream for the set of filter subjects If more than one stream is found, returns ErrMoreThanOneStream
getStreamFromSubjects
go
cloudevents/sdk-go
protocol/nats_jetstream/v3/protocol.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/protocol.go
Apache-2.0
func validateOptions(p *Protocol) error { if p.url == "" && p.conn == nil { return newValidationError(fieldURL, messageNoConnection) } if p.url != "" && p.conn != nil { return newValidationError(fieldURL, messageConflictingConnection) } consumerConfigOptions := 0 if p.consumerConfig != nil { consumerConfigOptions++ } if p.orderedConsumerConfig != nil { consumerConfigOptions++ } if consumerConfigOptions > 1 { return newValidationError(fieldConsumerConfig, messageMoreThanOneConsumerConfig) } if len(p.pullConsumeOpts) > 0 && consumerConfigOptions == 0 { return newValidationError(fieldPullConsumerOpts, messageReceiverOptionsWithoutConfig) } if len(p.publishOpts) > 0 && p.sendSubject == "" { return newValidationError(fieldPublishOptions, messageSenderOptionsWithoutSubject) } return nil }
validateOptions runs after all options have been applied and makes sure needed options were set correctly.
validateOptions
go
cloudevents/sdk-go
protocol/nats_jetstream/v3/validation.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/validation.go
Apache-2.0
func (v validationError) Error() string { return fmt.Sprintf("invalid parameters provided: %q: %s", v.field, v.message) }
Error returns a message indicating an error condition, with the nil value representing no error.
Error
go
cloudevents/sdk-go
protocol/nats_jetstream/v3/validation.go
https://github.com/cloudevents/sdk-go/blob/master/protocol/nats_jetstream/v3/validation.go
Apache-2.0
End of preview. Expand in Data Studio

Go CodeSearch Dataset (Shuu12121/go-treesitter-dedupe_doc-filtered-dataset)

Dataset Description

This dataset contains Go functions and methods paired with their GoDoc comments, extracted from open-source Go repositories on GitHub. It is formatted similarly to the CodeSearchNet challenge dataset.

Each entry includes:

  • code: The source code of a go function or method.
  • docstring: The docstring or Javadoc associated with the function/method.
  • func_name: The name of the function/method.
  • language: The programming language (always "go").
  • repo: The GitHub repository from which the code was sourced (e.g., "owner/repo").
  • path: The file path within the repository where the function/method is located.
  • url: A direct URL to the function/method's source file on GitHub (approximated to master/main branch).
  • license: The SPDX identifier of the license governing the source repository (e.g., "MIT", "Apache-2.0"). Additional metrics if available (from Lizard tool):
  • ccn: Cyclomatic Complexity Number.
  • params: Number of parameters of the function/method.
  • nloc: Non-commenting lines of code.
  • token_count: Number of tokens in the function/method.

Dataset Structure

The dataset is divided into the following splits:

  • train: 3,444,966 examples
  • validation: 38,764 examples
  • test: 114,948 examples

Data Collection

The data was collected by:

  1. Identifying popular and relevant Go repositories on GitHub.
  2. Cloning these repositories.
  3. Parsing Go files (.go) using tree-sitter to extract functions/methods and their docstrings/Javadoc.
  4. Filtering functions/methods based on code length and presence of a non-empty docstring/Javadoc.
  5. Using the lizard tool to calculate code metrics (CCN, NLOC, params).
  6. Storing the extracted data in JSONL format, including repository and license information.
  7. Splitting the data by repository to ensure no data leakage between train, validation, and test sets.

Intended Use

This dataset can be used for tasks such as:

  • Training and evaluating models for code search (natural language to code).
  • Code summarization / docstring generation (code to natural language).
  • Studies on Go code practices and documentation habits.

Licensing

The code examples within this dataset are sourced from repositories with permissive licenses (typically MIT, Apache-2.0, BSD). Each sample includes its original license information in the license field. The dataset compilation itself is provided under a permissive license (e.g., MIT or CC-BY-SA-4.0), but users should respect the original licenses of the underlying code.

Example Usage

from datasets import load_dataset

# Load the dataset
dataset = load_dataset("Shuu12121/go-treesitter-dedupe_doc-filtered-dataset")

# Access a split (e.g., train)
train_data = dataset["train"]

# Print the first example
print(train_data[0])
Downloads last month
47

Models trained or fine-tuned on Shuu12121/go-treesitter-dedupe_doc-filtered-dataset

Collection including Shuu12121/go-treesitter-dedupe_doc-filtered-dataset