machine

package module
v0.8.2 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2020 License: MIT Imports: 15 Imported by: 13

README

Go GoDoc Go Report Card Codacy Badge Codacy Badge Gitter chat

Machine is a library for creating data workflows. These workflows can be either very concise or quite complex, even allowing for cycles for flows that need retry or self healing mechanisms.

Installation

  go get -u github.com/whitaker-io/machine

Usage Overview

Usage

Basic receive -> process -> send Flow

  m := NewStream("unique_id1", func(c context.Context) chan []Data {
    channel := make(chan []Data)
  
    //setup channel to collect data as long as the context has not completed

    return channel
  },
    &Option{FIFO: boolP(false)},
    &Option{Metrics: boolP(true)},
    &Option{Span: boolP(false)},
  )

  m.Builder().
    Map("unique_id2", func(m Data) error {
      var err error

      // ...do some processing

      return err
    }).
    Transmit("unique_id3", func(d []Data) error {
      // send a copy of the data somewhere

      return nil
    })

  if err := m.Run(context.Background()); err != nil {
    // Run will return an error in the case that one of the paths is not terminated
    panic(err)
  }

Machine can also duplicate the data and send it down multiple paths

  m := NewStream("unique_id1", func(c context.Context) chan []Data {
    channel := make(chan []Data)
  
    //setup channel to collect data as long as the context has not completed

    return channel
  },
    &Option{FIFO: boolP(false)},
    &Option{Metrics: boolP(true)},
    &Option{Span: boolP(false)},
  )

  left, right := m.Builder().Fork("unique_id2", ForkDuplicate)
  
  left.Transmit("unique_id3", func(d []Data) error {
    // send a copy of the data somewhere

    return nil
  })

  right.Transmit("unique_id4", func(d []Data) error {
    // send a copy of the data somewhere else

    return nil
  })

  if err := m.Run(context.Background()); err != nil {
    // Run will return an error in the case that one of the paths is not terminated
    panic(err)
  }

Incase of errors you can also route the errors down their own path with more complex flows having retry loops

  m := NewStream("unique_id1", func(c context.Context) chan []Data {
    channel := make(chan []Data)
  
    //setup channel to collect data as long as the context has not completed

    return channel
  },
    &Option{FIFO: boolP(false)},
    &Option{Metrics: boolP(true)},
    &Option{Span: boolP(false)},
  )

  left, right := m.Builder().Fork("unique_id2", ForkError)
  
  left.Transmit("unique_id3", func(d []Data) error {
    // send a copy of the data somewhere

    return nil
  })

  right.Transmit("unique_id4", func(d []Data) error {
    // send the error somewhere else

    return nil
  })

  if err := m.Run(context.Background()); err != nil {
    // Run will return an error in the case that one of the paths is not terminated
    panic(err)
  }

Routing based on filtering the data is also possible with ForkRule

  m := NewStream("unique_id1", func(c context.Context) chan []Data {
    channel := make(chan []Data)
  
    //setup channel to collect data as long as the context has not completed

    return channel
  },
    &Option{FIFO: boolP(false)},
    &Option{Metrics: boolP(true)},
    &Option{Span: boolP(false)},
  )

  left, right := right.Fork("unique_id2", ForkRule(func(d Data) bool {
    //Data is a wrapper on typed.Typed see https://github.com/karlseguin/typed
    if val, ok := d["some_value"]; !ok {
      return false
    }

    return true
  }).Handler)
  
  left.Transmit("unique_id3", func(d []Data) error {
    // send a copy of the data somewhere

    return nil
  })

  right.Transmit("unique_id4", func(d []Data) error {
    // send the error somewhere else

    return nil
  })

  if err := machineInstance.Run(context.Background()); err != nil {
    // Run will return an error in the case that one of the paths is not terminated
    panic(err)
  }

machine also supports FoldLeft and FoldRight operations

  m := NewStream("unique_id1", func(c context.Context) chan []Data {
    channel := make(chan []Data)
  
    //setup channel to collect data as long as the context has not completed

    return channel
  },
    &Option{FIFO: boolP(false)},
    &Option{Metrics: boolP(true)},
    &Option{Span: boolP(false)},
  ).FoldLeft("unique_id2", func(aggragate, value Data) Data {
    // do something to fold in the value or combine in some way

    // FoldLeft acts on the data from left to right

    // FoldRight acts on the data from right to left

    return aggragate
  }).Transmit("unique_id3", func(d []Data) error {
    // send a copy of the data somewhere

    return nil
  })

  if err := machineInstance.Run(context.Background()); err != nil {
    // Run will return an error in the case that one of the paths is not terminated
    panic(err)
  }

using Link you can create loops to previous vertacies (use with care)

  m := NewStream("machine_id", func(c context.Context) chan []Data {
    channel := make(chan []Data)
    go func() {
      for n := 0; n < count; n++ {
        channel <- testList
      }
    }()
    return channel
  },
    &Option{FIFO: boolP(false)},
    &Option{Idempotent: boolP(true)},
    &Option{Metrics: boolP(true)},
    &Option{Span: boolP(false)},
    &Option{BufferSize: intP(0)},
  )

  left, right := m.Builder().
    Map("unique_id2", func(m Data) error {
      var err error

      // ...do some processing

      return err
    }).
    Fork("fork_id", ForkRule(func(d Data) bool {
      // example counting logic for looping
      if val := typed.Typed(d).IntOr("__loops", 0); val > 4 {
        return true
      } else {
        d["__loops"] = val + 1
      }

      return false
    }).Handler)

  left.Transmit("sender_id", func(d []Data) error {
    out <- d
    return nil
  })

  right.Link("link_id", "map_id")

  if err := machineInstance.Run(context.Background()); err != nil {
    // Run will return an error in the case that one of the paths is not terminated
    panic(err)
  }

License

Machine is provided under the MIT License.

The MIT License (MIT)

Copyright (c) 2020 Jonathan Whitaker

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Applicative added in v0.3.0

type Applicative func(Data) error

Applicative type for applying a change to a typed.Typed

type Builder

type Builder interface {
	Map(id string, a Applicative, options ...*Option) Builder
	FoldLeft(id string, f Fold, options ...*Option) Builder
	FoldRight(id string, f Fold, options ...*Option) Builder
	Fork(id string, f Fork, options ...*Option) (Builder, Builder)
	Link(id, target string, options ...*Option)
	Transmit(id string, s Sender, options ...*Option)
}

Builder interface for plotting out the data flow of the system

type Data added in v0.4.0

type Data typed.Typed

Data wrapper on typed.Typed

type Fold added in v0.5.0

type Fold func(Data, Data) Data

Fold type for folding a 2 Data into a single element

type Fork added in v0.5.0

type Fork func(list []*Packet) (a, b []*Packet)

Fork func for splitting a payload into 2

var (
	// ForkDuplicate is a SplitHandler that sends data to both outputs
	ForkDuplicate Fork = func(payload []*Packet) (a, b []*Packet) {
		payload2 := []*Packet{}
		buf := &bytes.Buffer{}
		enc, dec := gob.NewEncoder(buf), gob.NewDecoder(buf)

		_ = enc.Encode(payload)
		_ = dec.Decode(&payload2)

		for i, packet := range payload {
			payload2[i].span = packet.span
		}

		return payload, payload2
	}

	// ForkError is a SplitHandler for splitting errors from successes
	ForkError Fork = func(payload []*Packet) (s, f []*Packet) {
		s = []*Packet{}
		f = []*Packet{}

		for _, packet := range payload {
			if packet.Error != nil {
				f = append(f, packet)
			} else {
				s = append(s, packet)
			}
		}

		return s, f
	}
)

type ForkRule added in v0.5.0

type ForkRule func(Data) bool

ForkRule provides a SplitHandler for splitting based on the return bool

func (ForkRule) Handler added in v0.5.0

func (r ForkRule) Handler(payload []*Packet) (t, f []*Packet)

Handler func for providing a SplitHandler

type HealthInfo added in v0.7.0

type HealthInfo struct {
	StreamID    string    `json:"stream_id"`
	LastPayload time.Time `json:"last_payload"`
	// contains filtered or unexported fields
}

HealthInfo type for giving info on the stream

type InjectionCallback added in v0.7.0

type InjectionCallback func(logs ...*Log)

InjectionCallback func to run when the LogStore decides to restart the flow of orphaned Data

type Log added in v0.7.0

type Log struct {
	OwnerID    string    `json:"owner_id"`
	StreamID   string    `json:"stream_id"`
	VertexID   string    `json:"vertex_id"`
	VertexType string    `json:"vertex_type"`
	State      string    `json:"state"`
	Packet     *Packet   `json:"packet"`
	When       time.Time `json:"when"`
}

Log type for holding the data that is recorded from the streams

type LogStore added in v0.7.0

type LogStore interface {
	Join(id string, callback InjectionCallback, streamIDs ...string) error
	Write(logs ...*Log)
	Leave(id string) error
}

LogStore type for managing cluster state

type Logger added in v0.7.0

type Logger interface {
	Error(...interface{})
	Info(...interface{})
}

Logger type for accepting log messages

type Option added in v0.2.0

type Option struct {
	FIFO       *bool
	Injectable *bool
	BufferSize *int
	Span       *bool
	Metrics    *bool
}

Option type for holding machine settings

type Packet

type Packet struct {
	ID    string `json:"id"`
	Data  Data   `json:"data"`
	Error error  `json:"error"`
	// contains filtered or unexported fields
}

Packet type that holds information traveling through the machine

type Pipe added in v0.7.0

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

Pipe type for holding the server information for running http servers

func NewPipe added in v0.7.0

func NewPipe(id string, logger Logger, store LogStore, config ...fiber.Config) *Pipe

NewPipe func for creating a new server instance

func (*Pipe) Run added in v0.7.0

func (pipe *Pipe) Run(ctx context.Context, port string, gracePeriod time.Duration) error

Run func to start the server

func (*Pipe) Stream added in v0.8.0

func (pipe *Pipe) Stream(stream Stream) Builder

Stream func for registering a Stream with the Pipe

func (*Pipe) StreamHTTP added in v0.7.0

func (pipe *Pipe) StreamHTTP(id string, opts ...*Option) Builder

StreamHTTP func for creating a Stream at the path /stream/<id>

func (*Pipe) StreamSubscription added in v0.7.0

func (pipe *Pipe) StreamSubscription(id string, sub Subscription, interval time.Duration, opts ...*Option) Builder

StreamSubscription func for creating a Stream at the that reads from a subscription

func (*Pipe) Use added in v0.7.0

func (pipe *Pipe) Use(args ...interface{})

Use Wraps fiber.App.Use

Use registers a middleware route that will match requests with the provided prefix (which is optional and defaults to "/").

app.Use(func(c *fiber.Ctx) error {
   return c.Next()
})
app.Use("/api", func(c *fiber.Ctx) error {
   return c.Next()
})
app.Use("/api", handler, func(c *fiber.Ctx) error {
   return c.Next()
})

This method will match all HTTP verbs: GET, POST, PUT, HEAD etc...

type Retriever added in v0.3.0

type Retriever func(context.Context) chan []Data

Retriever type for providing the data to flow into the system

type Sender added in v0.3.0

type Sender func([]Data) error

Sender type for sending data out of the system

type Stream added in v0.5.0

type Stream interface {
	ID() string
	Run(ctx context.Context, recorders ...recorder) error
	Inject(ctx context.Context, events map[string][]*Packet)
	Builder() Builder
}

Stream interface for Running and injecting data

func NewStream added in v0.5.0

func NewStream(id string, retriever Retriever, options ...*Option) Stream

NewStream func for providing a Stream

type Subscription added in v0.7.0

type Subscription interface {
	Read(ctx context.Context) []Data
	Close() error
}

Subscription interface for creating a pull based stream

Directories

Path Synopsis
cmd module
common module
edge
http module
pubsub module
telemetry module

Jump to

Keyboard shortcuts

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