Receive Adapter Implementation and Design

Receive Adapter cmd

Similar to the controller, we’ll need an injection based main.go similar to the controller under cmd/receiver_adapter/main.go

  1. // This Adapter generates events at a regular interval.
  2. package main
  3. import (
  4. "knative.dev/eventing/pkg/adapter"
  5. myadapter "knative.dev/sample-source/pkg/adapter"
  6. )
  7. func main() {
  8. adapter.Main("sample-source", myadapter.NewEnv, myadapter.NewAdapter)
  9. }

Defining NewAdapter implementation and Start function

The adapter’s pkg implementation consists of two main functions;

  1. A NewAdapter(ctx context.Context, aEnv adapter.EnvConfigAccessor, ceClient cloudevents.Client) adapter.Adapter {} call, which creates the new adapter with passed variables via the EnvConfigAccessor. The created adapter will be passed the cloudevents client (which is where the events are forwarded to). This is sometimes referred to as a sink, or ceClient in the Knative ecosystem. The return value is a reference to the adapter as defined by the adapter’s local struct.

In our sample-source’s case;

  1. // Adapter generates events at a regular interval.
  2. type Adapter struct {
  3. logger *zap.Logger
  4. interval time.Duration
  5. nextID int
  6. client cloudevents.Client
  7. }
  1. Start function implemented as an interface to the adapter struct.
  1. func (a *Adapter) Start(stopCh <-chan struct{}) error {

stopCh is the signal to stop the Adapter. Otherwise the role of the function is to process the next event. In the case of the sample-source, it creates an event to forward to the specified cloudevent sink/client every X interval, as specified by the loaded EnvConfigAccessor (loaded via the resource yaml).

  1. func (a *Adapter) Start(stopCh <-chan struct{}) error {
  2. a.logger.Infow("Starting heartbeat", zap.String("interval", a.interval.String()))
  3. for {
  4. select {
  5. case <-time.After(a.interval):
  6. event := a.newEvent()
  7. a.logger.Infow("Sending new event", zap.String("event", event.String()))
  8. if result := a.client.Send(context.Background(), event); !cloudevents.IsACK(result) {
  9. a.logger.Infow("failed to send event", zap.String("event", event.String()), zap.Error(result))
  10. // We got an error but it could be transient, try again next interval.
  11. continue
  12. }
  13. case <-stopCh:
  14. a.logger.Info("Shutting down...")
  15. return nil
  16. }
  17. }
  18. }