geist

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: May 1, 2022 License: MIT Imports: 4 Imported by: 2 modules, 1 package

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

Generic Event Ingestion and Stream Transloading (GEIST)

Geist provides cost-efficient high-performance capabilities to develop generic (or specific) services executing an arbitrary number of event streams between various sources and sinks, with a set of built-in single message transforms. It's an alternative to other more heavy-weight, constrained and/or costly products, although with a more slim feature scope.

Use cases include consuming events from Kafka or Pubsub and store them, or chosen parts of them, into BigTable, Firestore or BigQuery, with a schema as specified in a dynamically registered stream spec via Geist API.

It also provides Geist API as a Source with which it is possible for external services to publish events to a registered Geist stream, which then transforms and stores them into a chosen Sink.

Geist can concurrently execute an arbitrary amount of different registered stream specs, in the same instance/pod. E.g. one stream with Kafka → BigTable and another with Pubsub → BigQuery, etc.

Although single event transform capabilities are provided, Geist is not meant to support complex stream processing, including stream joins and aggregations. That is better handled in products such as Spark, Kafka Streams, Dataflow/Beam, Flink, etc.

Its main purpose is to efficiently load streaming data into a sink, where the analytical processing and enrichment is done with other more appropriate products.

Quick Start

Prerequisites: Go 1.18

Install with:

go get -u github.com/zpiroux/geist

Example of simplified Geist test usage (error handling omitted) with an interactive stream where the sink outputs event data to console.

func main() {
	ctx := context.Background()
	geist, err := geist.New(ctx, geist.Config{})

	go func() {
		streamId, err := geist.RegisterStream(ctx, spec)
		resId, err := geist.Publish(ctx, streamId, []byte("Hi there!"))
		geist.Shutdown(ctx)
	}()

	geist.Run(ctx)
}

var spec = []byte(`{
    {
        "namespace": "my",
        "streamIdSuffix": "tiny-stream",
        "description": "Tiny test stream logging event data to console.",
        "version": 1,
        "source": {
            "type": "geistapi"
        },
        "transform": {
            "extractFields": [
                {
                    "fields": [
                        {
                            "id": "rawEvent"
                        }
                    ]
                }
            ]
        },
        "sink": {
            "type": "void",
            "config": {
                "properties": [
                    {
                        "key": "logEventData",
                        "value": "true"
                    }
                ]
            }
        }
    }
`)

Stream Categories

The quick start example showed one category of streams (interactive) where the Geist client can publish events explicitly.

The other category is when a Geist client sets up an autonomous stream between a source and sink.

Autonomous streams

Source set to kafka or pubsub.

The host service sets up a fully automated stream between a source and sink, with geist.RegisterStream(), e.g. consuming from Kafka and inserting into BigTable, and only manage start and stop of the stream.

Interactive streams

Source set to geistapi.

The host service has its own API or logic on top and explicitly publish events to the Geist stream with geist.Publish(), for further transformation and insertion into the chosen sink, as specified in the stream spec when registering the stream with geist.RegisterStream(). One example could be a thin REST API service using Geist to publish events to Kafka or any other sink.

Service modes of operation

There are two main types of service use-cases or deployment setup types for the hosting service using Geist.

Service with specific use-case with self-contained stream specs

This is the simplest mode and useful for small dedicated services.

Example use case: A service receiving (or producing) certain type of events that needs to be published to Kafka and/or stored in BigTable (etc.).

In this mode Geist merely works as a generic adaptor for the sinks. The stream specs to be used could be built-in in the hosting service and registered during startup.

Generic stream platform service with stream spec persistence

This is the mode for which Geist was developed in the first place, and is meant to run as a Kubernetes deployment.

In this mode Geist functions as a generic run-time and stream management service, with an external wrapper API, e.g. REST API, provided by the hosting service, with which other services dynamically could register and deploy their own streams without any downtime or re-deployment of Geist or its hosting service.

Registered specs are persisted by Geist with an internally defined (but customizable) Stream Spec. The default/native sink in this spec is GCP Firestore. When a Geist host pod is started, either from a new deployment or pod scaling, all registered specs are fetched from the native sink storage and booted up. The default native spec is found in regspec.go.

Any cross-pod synchronization, e.g. notification of newly updated stream specs, is done with an internal admin stream. It is managed in similar fashion as the Reg Spec and the default native one is using GCP Pubsub and found in adminspec.go.

Supported sources

  • Kafka (vanilla and Confluent)
  • Pubsub (GCP)
  • Geist API

Supported sinks

  • Kafka (vanilla and Confluent)
  • Firestore (GCP)
  • BigTable (GCP)
  • BigQuery (GCP)
  • (Pubsub - todo)

Stream Spec Format

A stream spec has the following main fields/parts (additional fields are described further below):

{
  "namespace": "<service or feature acting as stream owner>",
  "streamIdSuffix": "<stream subtype>",
  "version": <stream spec version, of int type>,
  "description": "<description of the spec>",
  "source": {
    <source spec>
  },
  "transform": {
    <transform spec>
  },
  "sink": {
    <sink spec>
  }
}

The ID of the new stream returned from geist.RegisterStream() in a successful registration is always constructed as:

<"namespace">-<"streamIdSuffix">

For full spec structure with all optional and additional fields, see specmodel.go.

The Stream Spec struct is exposed as geist.StreamSpec into which a json bytes spec can be unmarshalled if needed.

Example spec

The simple spec below exemplifies an autonomous stream using Kafka as source and BigTable as sink, inserting raw events in a table with a single column named event, row-key as <fooId>#<barType>, and a TTL of 31 days.

{
    "namespace": "my",
    "streamIdSuffix": "kafkabigtable-stream",
    "description": "Example of a simple stream spec Kafka --> BigTable",
    "version": 1,
    "ops": {
        "streamsPerPod": 2
    },
    "source": {
        "type": "kafka",
        "config": {
            "provider": "confluent",
            "topics": [
                {
                    "env": "all",
                    "names": [
                        "foo.events"
                    ]
                }
            ],
            "properties": [
                {
                    "key": "group.id",
                    "value": "my-kafkabigtable-stream"
                }
            ]
        }
    },
    "transform": {
        "extractFields": [
            {
                "fields": [
                    {
                        "id": "someField",
                        "jsonPath": "data.fooId"
                    },
                    {
                        "id": "someOtherField",
                        "jsonPath": "data.barType"
                    },
                    {
                        "id": "rawEvent"
                    }
                ]
            }
        ]
    },
    "sink": {
        "type": "bigtable",
        "config": {
            "tables": [
                {
                    "name": "foo_events",
                    "rowKey": {
                        "keys": [
                            "someField",
                            "someOtherField"
                        ],
                        "delimiter": "#"
                    },
                    "columnFamilies": [
                        {
                            "name": "d",
                            "garbageCollectionPolicy": {
                                "type": "maxAge",
                                "value": 744
                            },
                            "columnQualifiers": [
                                {
                                    "id": "rawEvent",
                                    "name": "event"
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    }
}

More example specs, with more sink, source and transform types, can be found in test/specs.

Updating or disabling a stream

A running stream can be updated dynamically with a new call to geist.RegisterStream() provided the spec's mandatory version number field is incremented. The provided modified spec will fully replace the existing one. This will seamlessly cause an internal restart of the stream's executors using the updated spec.

To disable a spec it needs to have the root field "disabled" added and set to true. This will shut down all the stream's executors directly. To enable the stream again, do a new update of spec (increase version number) and set "disabled" to false.

Getting information about/from streams

The following data can be retrieved:

  • The full list of specs for all registered streams.
  • The full list of stream IDs together with status on enabled/disabled.
  • The spec for a single stream from a stream ID.
  • All the events stored in a stream. Note that this is only meant for small datasets, and for now only supported when using Firestore or BigTable as sink.
  • Single event key-value lookup, retrieving the event stored in the sink with a given key/ID, provided it was stored in key/value mode. Only supported by Firestore and BigTable sink.

Although functional, data retrieval is currently only used internally and not yet exposed by a Geist wrapper function.

Performance Characteristics and Tuning

Geist has several stream config parameters exposed via the Stream Spec, to enable high-performance operation and stream throughput.

The main one governing concurrency is Ops.StreamsPerPod. This defines the amount of internal stream executors that will execute the full stream concurrently, for that particular stream.

As an example, say we have Kafka as a source, and a topic with 32 partitions. To maximize throughput (and/or minimize latency) the total number of stream executors should be 32 as well (or in practice less, since it's usually enough having each stream instance consuming from several partitions each). If the service using Geist is meant to run with two pods, the Ops.StreamsPerPod should be set to 16. There are no significant disadvantages with having the total amount of stream executors higher than the number of partitions, so having pods auto-scaled (creating more than two pods) will not be an issue.

Since each stream executor runs as a light-weight Goroutine, thousands of stream executors can easily be handled by a single pod, obviously provided pod resources are meant for the particular type of stream processing logic.

But it's usually a good approach to start with a low number of streams per pod, and increase based on test results.

Further parameters can be found in the stream spec definition (specmodel.go), with general ones in the Ops struct and Source/Sink specific ones in respective SourceConfig and SinkConfig struct.

Limitations and improvement areas

Although Geist has been run in production with heavy load, no data-loss, and zero downtime for ~two years, it makes no guarantees that all combinations of stream spec options will work fully in all cases.

The following types of streams have been run extensively and concurrently with high throughput:

  • Kafka (Confluent) → BigTable
  • Kafka (Confluent) → BigQuery

Additionally, Pubsub as source and Firestore as sink have been used extensively but with limited traffic.

Transforms

The current transform package provides features as required by a set of use cases. Its implementation could easily be replaced or extended in code, but there is currently no mechanism to replace or extend transformation logic in a plug-in fashion without rebuilding.

Chaining of transforms could be improved.

Although functional, regex transform options have some remaining todos.

Geist is not meant to support complex stream processing, including stream joins and aggregations. That is better handled in products such as Spark, Kafka Streams, Dataflow/Beam, Flink, etc.

Event schema

Only JSON currently supported.

Kafka Sink entity

Although the Kafka Source entity exhibits high performance and guaranteed delivery, the Kafka Sink entity has lower throughput.

There is an option in the Stream Spec to increase the sink throughput for a given stream, but that will disable guaranteed delivery, e.g. in case of Geist host crashing, so should only be used for non-critical streams.

To fix this, message batching in the sink should be added.

Kafka providers

Secure access is enabled when using spec provider option "confluent", where API key and secret are provided in geist.Config.Kafka when creating Geist with geist.New().

If using vanilla Kafka with spec option "native" it only supports plain access without authentication.

Pubsub extractor DLQ

The Kafka Extractor supports automated DLQ handling of unretryable events (e.g. corrupt events that can't be transformed or processed by the Sink), if that option ("dlq") is chosen in the Stream Spec, but the Pubsub Extractor currently only supports the options "discard" and "fail".

Using Pubsub's built-in dead-letter topic option in the subscription as a work-around until this feature is added in the Extractor will currently not have the intended effect.

Logging configurability

Internal logging could be made more configurable externally.

Log level is based on environment variable LOG_LEVEL. If not set, INFO will be used.

Contact

info @ zpiroux . com

License

Geist source code is available under the MIT License.

Documentation

Index

Constants

View Source
const (
	ErrGeistNotInitialized    = "geist not initialized"
	ErrSpecAlreadyExists      = "stream ID already exists with that version - increment version number to upgrade"
	ErrInvalidStreamSpec      = "stream Specification is not valid"
	ErrInvalidStreamId        = "invalid Stream ID"
	ErrProtectedStreamId      = "spec format is valid but but stream ID is protected and cannot be used"
	ErrCodeInvalidSpecRegOp   = "use RegisterStream() instead to register new streams"
	ErrInternalDataProcessing = "internal data processing error"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AdminStreamConfig

type AdminStreamConfig struct {
	StreamSpec []byte
}

AdminStreamConfig specifies how the internal cross-pod admin event propagation should be set up. Providing a custom admin spec is advanced usage and should be done with care. It is only required to be filled in if diverting from default behavior, which is the following:

  • If SpecRegistryConfig.StorageMode is set to "inmemory" (default), the admin stream is disabled (cross-pod sync not needed)
  • If SpecRegistryConfig.StorageMode is set to "native" (firestore) or "custom", the admin stream will use GCP Pubsub for event propagation (pubsub set as its stream source type).

For complete customization, set StorageMode to "custom" and provide both a Stream and an Admin Spec.

type BigQueryConfig

type BigQueryConfig struct {
	Enabled bool // Set to true if BigQuery used in any registered stream
}

type BigTableConfig

type BigTableConfig struct {
	Enabled    bool // Set to true if Big Table used in any registered stream
	InstanceId string
}

type Config

type Config struct {
	Registry    SpecRegistryConfig
	AdminStream AdminStreamConfig
	Ops         OpsConfig
	Gcp         GcpConfig
	Kafka       KafkaConfig // GEIST specs can override this
	BigTable    BigTableConfig
	BigQuery    BigQueryConfig
	Firestore   FirestoreConfig
	Pubsub      PubsubConfig
}

type FirestoreConfig

type FirestoreConfig struct {
	Enabled bool // Set to true if Firestore used in any registered stream, or if using "native" storage mode
}

type GcpConfig

type GcpConfig struct {
	ProjectId string
}

type Geist

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

func New

func New(ctx context.Context, config Config) (g *Geist, err error)

New creates and configures Geist's internal services and all previously registered streams, based on the provided config.

func (*Geist) GetStreamSpec

func (g *Geist) GetStreamSpec(streamId string) (specData []byte, err error)

func (*Geist) GetStreamSpecs

func (g *Geist) GetStreamSpecs(ctx context.Context) (specs map[string][]byte, err error)

func (*Geist) Publish

func (g *Geist) Publish(ctx context.Context, streamId string, event []byte) (id string, err error)

Publish sends the provided event to the source extractor of the stream as identified by streamId. This is currently only supported by streams with "geistapi" or "pubsub" set as source type.

The returned ID string (or resource ID) is dependent on the sink type, but is defined as the key to be used for key lookups of the event. It is created based on the Sink configuration in the Stream Spec for sink types supporting it:

Firestore: ID is the generated Firestore entity name, as specified in the entityNameFromIds section of the sink spec.
BigTable: ID is the generated row-key, as specified in the rowKey section of the sink spec.
Others: currently <noResourceId> or empty string (to be improved in a future update)

func (*Geist) RegisterStream

func (g *Geist) RegisterStream(ctx context.Context, specData []byte) (id string, err error)

RegisterStream validates and persist the stream spec in the chosen registry implementation. If successful, the registered stream is started up immediately, and the generated ID of the stream is returned.

func (*Geist) Run

func (g *Geist) Run(ctx context.Context) (err error)

Run starts up Geist's internal services and all previously registered streams (if Geist configured to use persistent registry), as prepared by New(). It is a blocking call until Geist is shut down, from a call to Shutdown. Geist must be up and running prior to usage of the other Geist API functions.

func (*Geist) Shutdown

func (g *Geist) Shutdown(ctx context.Context) (err error)

func (*Geist) ValidateStreamSpec

func (g *Geist) ValidateStreamSpec(specData []byte) (specId string, err error)

type KafkaConfig

type KafkaConfig struct {
	Enabled                  bool   // Set to true if Kafka used in any registered stream
	BootstrapServers         string // Default servers, can be overriden in GEIST specs
	ConfluentBootstrapServer string // Default server, can be overriden in GEIST specs
	ConfluentApiKey          string
	ConfluentApiSecret       string `json:"-"`
	PollTimeoutMs            int    // Default poll timeout, can be overridden in GEIST specs
	QueuedMaxMessagesKb      int    // Events consumed and processed before commit
}

type OpsConfig

type OpsConfig struct {
	Env                       string // Available values: "dev", "stage", "prod", "all"
	EventLogInterval          int    // TODO: change all the int types to string to understand if it's been set by client, and if not, apply an appropriate internal default value
	MaxStreamRetryIntervalSec int
}

type PubsubConfig

type PubsubConfig struct {
	Enabled                bool // Set to true if Pubsub used in any registered stream
	MaxOutstandingMessages int
	MaxOutstandingBytes    int
}

type SpecRegistryConfig

type SpecRegistryConfig struct {

	// StorageMode specifies how Geist should store stream specs to be run.
	// The follow values are available:
	//
	// 	"inmemory": (default) registered specs are stored in memory only
	// 	"native":   specs are persisted in the sink specified in the native stream spec for the
	//              spec registration stream (using Firestore as default sink)
	// 	"custom":   the client of Geist need to provide a Stream Spec for the Spec Registration Stream
	//              in the RegSpec field (advanced usage)
	StorageMode string

	// StreamSpec specifies the Stream Spec for the internal stream, handling Stream Spec registrations,
	// if StorageMode is set to "custom".
	StreamSpec []byte
}

SpecRegistryConfig is only required to be filled in if persistance of specs is required. Normally only StorageMode field is needed for setting up intended behaviour, switching from in-mem storage to native persistance. Future updates might add more built-in "native" storage modes.

type StreamSpec

type StreamSpec struct {
	model.Spec
}

Jump to

Keyboard shortcuts

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