cloudeventprovider

package module
v0.1.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 20, 2025 License: Apache-2.0 Imports: 28 Imported by: 12 modules, 23 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Introduction

This library is used for abstracting messaging. The purpose of this library shall be to decapsulate message bus technologies from their usage. So it's doesnt matter if nats, kafka or anything else supported is used.

Usage

Get started

Add the module as dependency using go mod:

go get github.com/eclipse-xfsc/cloud-event-provider

And import the module in your code:

import "github.com/eclipse-xfsc/cloud-event-provider"

Configure protocol and corresponding config with yaml File

messaging:
  protocol: nats
  nats:
    url: http://localhost:4222
    queueGroup: logger #optional
    timeoutInSec: 10 #optional

EnvConfig can also be used by tagging the config:

Nats      cloudeventprovider.NatsConfig `envconfig:"NATS"`

And using ENVs like NATS_REQUEST_TIMEOUT (e.g. 10s), NATS_URL, NATS_QUEUE_GROUP

Send an Cloudevent

type message struct {
    Receiver string `json:"receiver"`
    Text string `json:"text"`
}

func main() {
    topic := "events"
    client, err := cloudeventprovider.New(cloudeventprovider.Config{
		Protocol: cloudeventprovider.ProtocolTypeNats,
		Settings: cloudeventprovider.NatsConfig{
			Url:          config.Nats.Url,
			QueueGroup:   config.Nats.QueueGroup,
			TimeoutInSec: config.Nats.TimeoutInSec,
		},
	}, cloudeventprovider.Pub, retrieval.TopicRetrevialPublication)

	if err != nil {
		return err
	}
    defer c.Close()

    pubMessage := message{
        Receiver: "Timo",
        Text:     "Hello, my friend",
    }

    data, err := json.Marshal(pubMessage)
    if err != nil {
        log.Fatal(err)
    }
    event, err := cloudeventprovider.NewEvent("event", retrieval.EventTypeRetrievalReceivedNotification, b)
    if err != nil {
        log.Fatal(err)
    }

    if err := c.Pub(event); err != nil {
        log.Fatalf("failed to send, %v", err)
    }
}

Receive an Cloudevent

func StartMessageSubscription(log *logPkg.Logger) {
	var wg sync.WaitGroup
	wg.Add(1)
	defer wg.Done()
	log.Info("start messaging!")

	client, err := cloudeventprovider.New(cloudeventprovider.Config{
		Protocol: cloudeventprovider.ProtocolTypeNats,
		Settings: cloudeventprovider.NatsConfig{
			Url:          config.Nats.Url,
			QueueGroup:   config.Nats.QueueGroup,
			TimeoutInSec: config.Nats.TimeoutInSec,
		},
	}, cloudeventprovider.Sub, config.OfferingTopic)
	if err != nil {
		log.Error(err, "")
		os.Exit(1)
	}

	defer func() {
		if err := client.Close(); err != nil {
			log.Error(err, "error while closing client")
			os.Exit(1)
		}
	}()

	err = client.Sub(handleMessage)
	if err != nil {
		log.Error(err, "")
		os.Exit(1)
	}
	wg.Wait()
}

Supported protocols

  • Nats
  • NatsJetstream
  • Kafka
  • Http
  • Mqtt
  • Amqp

Trouble Shooting

Nats Timeout: If a nats time out error is arising during the sending of a message, check if the handler function was beforehand crashed by an fatal exception. In this case the responder is on the nats bus, but the handler is broken.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrConfigKeyMissing = errors.New("required configKey is not set")
View Source
var ErrInvalidConfig = errors.New("invalid config (type of Config.Settings does not match Config.Protocol)")

Functions

func NewEvent

func NewEvent(eventSource string, eventType string, data json.RawMessage) (event.Event, error)

NewEvent initializes an event.Event ready to be submitted

Types

type AmqpConfig

type AmqpConfig struct {
	Url string `mapstructure:"url" envconfig:"URL" default:"127.0.0.1"`
}

type CloudEventProvider

type CloudEventProvider interface {
	Close() error
	Alive() bool
	Pub(event event.Event) error
	PubCtx(ctx context.Context, event event.Event) error
	Sub(fn func(event event.Event)) error
	SubCtx(ctx context.Context, fn func(event event.Event)) error
	Request(event event.Event, timeOut time.Duration) (*event.Event, error)
	RequestCtx(ctx context.Context, event event.Event) (*event.Event, error)
	Reply(responseFunc func(ctx context.Context, event event.Event) (*event.Event, error)) error
	ReplyCtx(ctx context.Context, responseFunc func(ctx context.Context, event event.Event) (*event.Event, error)) error
}

type CloudEventProviderClient

type CloudEventProviderClient struct {
	// contains filtered or unexported fields
}

func New

func New(conf Config, conType ConnectionType, topic string) (*CloudEventProviderClient, error)

New initializes a CloudEventProviderClient using the passed Config. In contrast to NewClient, it does not rely on a configuration other than the one provided.

func NewClient

func NewClient(connectionType ConnectionType, topic string) (*CloudEventProviderClient, error)

NewClient initializes a CloudEventProviderClient. It uses viper.Viper as the config library and might make assumptions about your config.yaml

func (*CloudEventProviderClient) Alive

func (c *CloudEventProviderClient) Alive() bool

func (*CloudEventProviderClient) Close

func (c *CloudEventProviderClient) Close() error

func (*CloudEventProviderClient) Pub

func (c *CloudEventProviderClient) Pub(event event.Event) error

Pub publishes the given event.Event DEPRECATED: Use PubCtx

func (*CloudEventProviderClient) PubCtx

func (c *CloudEventProviderClient) PubCtx(ctx context.Context, event event.Event) error

PubCtx publishes the given event.Event

func (*CloudEventProviderClient) Reply

func (c *CloudEventProviderClient) Reply(responseFunc func(ctx context.Context, event event.Event) (*event.Event, error)) error

Reply method is blocking. Use it in a goroutine DEPRECATED: Use ReplyCtx

func (*CloudEventProviderClient) ReplyCtx

func (c *CloudEventProviderClient) ReplyCtx(ctx context.Context, responseFunc func(ctx context.Context, event event.Event) (*event.Event, error)) error

ReplyCtx method is blocking. Use it in a goroutine

func (*CloudEventProviderClient) Request

func (c *CloudEventProviderClient) Request(event event.Event, timeOut time.Duration) (*event.Event, error)

Request sends the given event.Event as a request and returns the response DEPRECATED: Use RequestCtx

func (*CloudEventProviderClient) RequestCtx

func (c *CloudEventProviderClient) RequestCtx(ctx context.Context, event event.Event) (*event.Event, error)

RequestCtx sends the given event.Event as a request and returns the response

func (*CloudEventProviderClient) Sub

func (c *CloudEventProviderClient) Sub(fn func(event event.Event)) error

Sub Subscribes the client and calls the given fn on receive DEPRECATED: Use SubCtx

func (*CloudEventProviderClient) SubCtx

func (c *CloudEventProviderClient) SubCtx(ctx context.Context, fn func(event event.Event)) error

SubCtx Subscribes the client and calls the given fn on receive

type Config

type Config struct {
	Protocol ProtocolType `mapstructure:"protocol"`
	Settings protocolConfig
}

type ConnectionType

type ConnectionType string
const (
	ConnectionTypePub ConnectionType = "pub"
	ConnectionTypeSub ConnectionType = "sub"
	ConnectionTypeReq ConnectionType = "req"
	ConnectionTypeRep ConnectionType = "rep"
)
const (
	Pub ConnectionType = "pub"
	Sub ConnectionType = "sub"
	Req ConnectionType = "req"
	Rep ConnectionType = "rep"
)

Deprecated, use ConnectionType*

type HttpConfig

type HttpConfig struct {
	Url  string `mapstructure:"url" envconfig:"URL" default:"127.0.0.1"`
	Port int    `mapstructure:"port" envconfig:"PORT" default:"8080"`
	Path string `mapstructure:"path" envconfig:"PATH"`
}

type KafkaConfig

type KafkaConfig struct {
	Url      string `mapstructure:"url" envconfig:"URL" default:"127.0.0.1"`
	GroupId  string `mapstructure:"groupId,omitempty" envconfig:"GROUP_ID"`
	ClientId string `mapstructure:"clientId" envconfig:"CLIENT_ID"`
}

type MqttConfig

type MqttConfig struct {
	Url      string `mapstructure:"url" envconfig:"URL" default:"127.0.0.1"`
	ClientId string `mapstructure:"clientId" envconfig:"CLIENT_ID"`
}

type NatsConfig

type NatsConfig struct {
	Url          string        `mapstructure:"url" envconfig:"URL" default:"127.0.0.1"`
	QueueGroup   string        `mapstructure:"queueGroup,omitempty" envconfig:"QUEUE_GROUP"`
	TimeoutInSec time.Duration `mapstructure:"timeoutInSec,omitempty" envconfig:"REQUEST_TIMEOUT"`
}

type NatsJetstreamConfig

type NatsJetstreamConfig struct {
	Url          string        `mapstructure:"url" envconfig:"URL" default:"127.0.0.1"`
	QueueGroup   string        `mapstructure:"queueGroup,omitempty" envconfig:"QUEUE_GROUP"`
	StreamType   string        `mapstructure:"streamType" envconfig:"STREAM_TYPE"`
	TimeoutInSec time.Duration `mapstructure:"timeoutInSec,omitempty" envconfig:"REQUEST_TIMEOUT"`
}

type ProtocolType

type ProtocolType string
const (
	ProtocolTypeHttp          ProtocolType = "http"
	ProtocolTypeKafka         ProtocolType = "kafka"
	ProtocolTypeNats          ProtocolType = "nats"
	ProtocolTypeNatsJetstream ProtocolType = "natsJetstream"
	ProtocolTypeMqtt          ProtocolType = "mqtt"
	ProtocolTypeAmqp          ProtocolType = "amqp"
)
const (
	Http          ProtocolType = "http"
	Kafka         ProtocolType = "kafka"
	Nats          ProtocolType = "nats"
	NatsJetstream ProtocolType = "natsJetstream"
	Mqtt          ProtocolType = "mqtt"
	Amqp          ProtocolType = "amqp"
)

Deprecated, use ProtocolType*

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址