hap

package module
v0.0.0-...-ffebef2 Latest Latest
Warning

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

Go to latest
Published: Jan 20, 2023 License: MIT Imports: 14 Imported by: 0

README

hap

Go version hap tests

hap, like in what's happening, is a generic event system aimed towards simplicity and performance.

Goals

  • Simple
  • Fast
  • Type-Safe
  • Reliable

Installation

go get -u github.com/mgjules/hap

Usage example

examples/simple.go:

package main

import (
	"context"
	"fmt"
	"os"
	"time"

	"github.com/mgjules/hap"
	"go.uber.org/zap"
)

func main() {
	type userCreatedEventData struct {
		// Embed to satisfy the necessary constraints.
		*hap.Metadata

		ID        string
		FirstName string
		LastName  string
		CreatedAt time.Time
	}

	logger, err := zap.NewDevelopment()
	if err != nil {
		fmt.Printf("Error creating logger: %v\n", err)
		os.Exit(1)
	}
	sugaredLogger := logger.Sugar()

	// Create the event.
	userCreatedEvent := hap.NewEvent[userCreatedEventData](sugaredLogger)

	ctx := context.Background()

	received := make(chan struct{})

	// Add handlers to the event.
	// If you don't specify an id, a random uuid will be generated.
	removeHandler := userCreatedEvent.AddHandler(
		ctx,
		"",
		func(data *userCreatedEventData) {
			// Do something with the user created event data.
			sugaredLogger.Debugf("User created event: %#v", data)
			received <- struct{}{}
		},
	)
	defer removeHandler()

	// Trigger the event.
	userCreatedEvent.Trigger(ctx, userCreatedEventData{
		Metadata:  hap.MetadataFromContext(ctx),
		ID:        "4a2d6247-cf07-5eb8-b8fd-a27c37aaecfa",
		FirstName: "John",
		LastName:  "Doe",
		CreatedAt: time.Now(),
	})

	<-received
}

Note: You can also add buffered handlers to capture a series of events.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ContextKeyPublisherID = contextKey("publisher_id")

Functions

func DeepCopy

func DeepCopy[T any](t *T) T

DeepCopy returns a deep copy of T.

func GetFunctionName

func GetFunctionName(i interface{}) string

GetFunctionName returns the function name.

func ToSnakeCase

func ToSnakeCase(str string) string

ToSnakeCase transforms str to snake case.

Types

type Event

type Event[D EventData] struct {
	// contains filtered or unexported fields
}

func NewEvent

func NewEvent[D EventData](logger Logger) *Event[D]

func (*Event[D]) AddBufferedHandler

func (e *Event[D]) AddBufferedHandler(ctx context.Context, id string, fn func([]*D), size uint, timeout time.Duration) RemoveHandlerFn

AddBufferedHandler registers a new buffered handler with a unique id, function fn, size and timeout.

If id is empty, a uuidV4 will be generated instead. If size is zero, a default value of 100 is used. If timeout is zero, a default value of 1 second is used. Events are buffered and sent when either size or timeout is reached.

IMPORTANT:

  • ctx must be property hydrated with the customer metadata.
  • fn is not nil.
  • fn must not block forever as we have a limited amount of goroutines in our pool.

func (*Event[D]) AddHandler

func (e *Event[D]) AddHandler(ctx context.Context, id string, fn func(*D)) RemoveHandlerFn

AddHandler registers a new handler with a unique id and function fn.

If id is empty, a uuidV4 will be generated instead.

IMPORTANT:

  • ctx must be property hydrated with the customer metadata.
  • fn is not nil.
  • fn must not block forever as we have a limited amount of goroutines in our pool.

func (*Event[D]) NumHandlers

func (e *Event[D]) NumHandlers() int

func (*Event[D]) Topic

func (e *Event[D]) Topic() string

func (*Event[D]) Trigger

func (e *Event[D]) Trigger(ctx context.Context, data D)

Trigger executes the registered handlers.

func (*Event[D]) WaitForBufferedData

func (e *Event[D]) WaitForBufferedData(ctx context.Context, selector func(*D) bool, size uint, timeout time.Duration) (<-chan []*D, RemoveHandlerFn)

WaitForBufferedData adds a convenience handler for synchronous buffered event subscription.

func (*Event[D]) WaitForData

func (e *Event[D]) WaitForData(ctx context.Context, selector func(*D) bool) (<-chan *D, RemoveHandlerFn)

WaitForData adds a convenience handler for synchronous event subscription.

type EventData

type EventData interface {
	GetMetadata() Metadata
}

type Logger

type Logger interface {
	Debug(args ...interface{})
	Info(args ...interface{})
	Warn(args ...interface{})
	Error(args ...interface{})
	Fatal(args ...interface{})
	Debugf(template string, args ...interface{})
	Infof(template string, args ...interface{})
	Warnf(template string, args ...interface{})
	Errorf(template string, args ...interface{})
	Fatalf(template string, args ...interface{})
}

type Metadata

type Metadata struct {
	// EventID is the unique identifier of the event.
	EventID string

	// PublisherID is the account which produced the event.
	PublisherID string

	// Time event was produced.
	Time time.Time
}

func MetadataFromContext

func MetadataFromContext(ctx context.Context) *Metadata

func (Metadata) GetMetadata

func (m Metadata) GetMetadata() Metadata

type RemoveHandlerFn

type RemoveHandlerFn func()

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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