Floc: Orchestrate goroutines with ease.

Gopher Floc Control

go-floc

Floc: Orchestrate goroutines with ease.

GoDoc Build Status Coverage Status Go Report Card Join the chat at https://gitter.im/go-floc/Lobby License

The goal of the project is to make the process of running goroutines in parallel and synchronizing them easy.

Announcements

Hooray! The new version v2 is released on the 1st of December, 2017!

Installation and requirements

The package requires Go v1.8 or later.

To install the package use go get gopkg.in/workanator/go-floc.v2

Documentation and examples

Please refer Godoc reference of the package for more details.

Some examples are available at the Godoc reference. Additional examples can be found in go-floc-showcase.

Features

  • Easy to use functional interface.
  • Simple parallelism and synchronization of jobs.
  • As little overhead as possible, in comparison to direct use of goroutines and sync primitives.
  • Provide better control over execution with one entry point and one exit point.

Introduction

Floc introduces some terms which are widely used through the package.

Flow

Flow is the overall process which can be controlled through floc.Flow. Flow can be canceled or completed with any arbitrary data at any point of execution. Flow has only one enter point and only one exit point.

// Design the job
flow := run.Sequence(do, something, here, ...)

// The enter point: Run the job
result, data, err := floc.Run(flow)

// The exit point: Check the result of the job.
if err != nil {
	// Handle the error
} else if result.IsCompleted() {
	// Handle the success
} else {
	// Handle other cases
}

Job

Job in Floc is a smallest piece of flow. The prototype of job function is floc.Job. Each job can read/write data with floc.Context and control the flow with floc.Control.

Cancel(), Complete(), Fail() methods of floc.Flow has permanent effect. Once finished flow cannot be canceled or completed anymore. Calling Fail and returning error from job is almost equal.

func ValidateContentLength(ctx floc.Context, ctrl floc.Control) error {
  request := ctx.Value("request").(http.Request)

  // Cancel the flow with error if request body size is too big
  if request.ContentLength > MaxContentLength {
    return errors.New("content is too big")
  }
  
  return nil
}

Example

Lets have some fun and write a simple example which calculates some statistics on text given.

const Text = `Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
  do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
  veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
  consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum
  dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident,
  sunt in culpa qui officia deserunt mollit anim id est laborum.`
  
const keyStatistics = 1

var sanitizeWordRe = regexp.MustCompile(`\W`)

type Statistics struct {
  Words      []string
  Characters int
  Occurrence map[string]int
}

// Split to words and sanitize them
SplitToWords := func(ctx floc.Context, ctrl floc.Control) error {
  statistics := ctx.Value(keyStatistics).(*Statistics)

  statistics.Words = strings.Split(Text, " ")
  for i, word := range statistics.Words {
    statistics.Words[i] = sanitizeWordRe.ReplaceAllString(word, "")
  }
  
  return nil
}

// Count and sum the number of characters in the each word
CountCharacters := func(ctx floc.Context, ctrl floc.Control) error {
  statistics := ctx.Value(keyStatistics).(*Statistics)

  for _, word := range statistics.Words {
    statistics.Characters += len(word)
  }
  
  return nil
}

// Count the number of unique words
CountUniqueWords := func(ctx floc.Context, ctrl floc.Control) error {
  statistics := ctx.Value(keyStatistics).(*Statistics)

  statistics.Occurrence = make(map[string]int)
  for _, word := range statistics.Words {
    statistics.Occurrence[word] = statistics.Occurrence[word] + 1
  }
  
  return nil
}

// Print result
PrintResult := func(ctx floc.Context, ctrl floc.Control) error {
  statistics := ctx.Value(keyStatistics).(*Statistics)

  fmt.Printf("Words Total       : %d\n", len(statistics.Words))
  fmt.Printf("Unique Word Count : %d\n", len(statistics.Occurrence))
  fmt.Printf("Character Count   : %d\n", statistics.Characters)
  
  return nil
}

// Design the flow and run it
flow := run.Sequence(
  SplitToWords,
  run.Parallel(
    CountCharacters,
    CountUniqueWords,
  ),
  PrintResult,
)

ctx := floc.NewContext()
ctx.AddValue(keyStatistics, new(Statistics))

ctrl := floc.NewControl(ctx)

_, _, err := floc.RunWith(ctx, ctrl, flow)
if err != nil {
	panic(err)
}

// Output:
// Words Total       : 64
// Unique Word Count : 60
// Character Count   : 370

Contributing

Please found information about contributing in CONTRIBUTING.md and the list of bravers who spent their priceless time and effort to make the project better in CONTRIBUTORS.md.

Owner
Similar Resources

Парсер технологического журнала, основанный на стеке технологий Golang goroutines + Redis + Elasticsearch.

Парсер технологического журнала, основанный на стеке технологий Golang goroutines + Redis + Elasticsearch.

go-techLog1C Парсер технологического журнала, основанный на стеке технологий Golang goroutines + Redis + Elasticsearch. Стек является кросс-платформен

Nov 30, 2022

SizedWaitGroup has the same role and close to the same API as the Golang sync.WaitGroup but it adds a limit on the amount of goroutines started concurrently.

SizedWaitGroup SizedWaitGroup has the same role and API as sync.WaitGroup but it adds a limit of the amount of goroutines started concurrently. SizedW

Jan 8, 2023

Discrete-event simulation in Go using goroutines

SimGo SimGo is a discrete event simulation framework for Go. It is similar to SimPy and aims to be easy to set up and use. Processes are defined as si

Sep 6, 2022

Package gostackparse parses goroutines stack traces as produced by panic() or debug.Stack() at ~300 MiB/s.

gostackparse Package gostackparse parses goroutines stack traces as produced by panic() or debug.Stack() at ~300 MiB/s. Parsing this data can be usefu

Dec 1, 2022

Command line monitoring for goroutines

Command line monitoring for goroutines

grmon Command line monitoring for goroutines Install go get -u github.com/bcicen/grmon Usage Simply import and call grmon.Start() somewhere in your co

Dec 30, 2022

How to work with channels, goroutines, tickers, mutexes and context cancelation

Concurrency tasks This page holds 4 concurrency practical tasks to help you to understand how to write concurrent code. They will help you to understa

Nov 9, 2021

The MapReduce pattern with Goroutines and channels to count n-grams in a directory of text files

MapReduce Ngram This Golang program implements the MapReduce pattern with Goroutines and channels to count n-grams in a directory of text files. Usage

Dec 16, 2021

Supports the safe and convenient execution of asynchronous computations with goroutines and provides facilities for the safe retrieval of the computation results.

Rendezvous The Rendezvous library supports the safe and convenient execution of asynchronous computations with goroutines and provides facilities for

Dec 29, 2021

GopherTalk: a multi-user chat powered by GO to explore its standard library and features like sockets, goroutines, channels and sync package

GopherTalk: a multi-user chat powered by GO to explore its standard library and features like sockets, goroutines, channels and sync package

GopherTalk GopherTalk is a multi-user chat powered by GO to explore its standard

Jun 6, 2022

run/stop goroutines/tasks securely, recursively

grunner - run/stop goroutines/tasks securely, recursively. s1 := grunner.New() s1.Defer(func() { fmt.Println("s1 stopped 2") }) s1.Defer(func() {

Apr 22, 2022

Go-concurrency-patterns - Sample concurrency patterns with Goroutines

About This sample project provides some concurrency pattern examples in Go using

Feb 21, 2022

Some tests and examples with goroutines and channels

goroutine-playground Some tests and examples with goroutines and channels simpleAsyncCalls Runs functions in background and doesn't wait for results a

Feb 9, 2022

Sample code snippet to familiarize golang . Concept of goroutines , channels, concurrency is implemented in a sample scenario

go-mysql-goroutines-channel Sample code snippet to familiarize golang . Concept of goroutines , channels, concurrency , interface, slice, error handli

May 29, 2022

A fast subdomain enumerator for web URLs using the power of Goroutines.

A fast subdomain enumerator for web URLs using the power of Goroutines.

gosublister A fast subdomain enumerator for web URLs written in go with goroutines. Options Usage: gosublister -u [URL] [Other Flags] Flags: -u,

May 7, 2023

A lightweight eventbus that simplifies communication between goroutines,

English | 简体中文 eventbus A lightweight eventbus that simplifies communication between goroutines, it supports synchronous and asynchronous message publ

Apr 28, 2023

A package to allow one to concurrently go through a filesystem with ease

skywalker Skywalker is a package to allow one to concurrently go through a filesystem with ease. Features Concurrency BlackList filtering WhiteList fi

Nov 14, 2022

go library for image programming (merge, crop, resize, watermark, animate, ease, transit)

go library for image programming (merge, crop, resize, watermark, animate, ease, transit)

Result Terminal Code mergi -t TT -i https://raw.githubusercontent.com/ashleymcnamara/gophers/master/Facepalm_Gopher.png -r "131 131" -i https://raw.gi

Jan 6, 2023

Build event-driven and event streaming applications with ease

Commander 🚀 Commander is Go library for writing event-driven applications. Enabling event sourcing, RPC over messages, SAGA's, bidirectional streamin

Dec 19, 2022

GraphQL server with a focus on ease of use

GraphQL server with a focus on ease of use

graphql-go The goal of this project is to provide full support of the GraphQL draft specification with a set of idiomatic, easy to use Go packages. Wh

Dec 31, 2022
Comments
  • Add a Gitter chat badge to README.md

    Add a Gitter chat badge to README.md

    workanator/go-floc now has a Chat Room on Gitter

    @workanator has just created a chat room. You can visit it here: https://gitter.im/go-floc/Lobby.

    This pull-request adds this badge to your README.md:

    Gitter

    If my aim is a little off, please let me know.

    Happy chatting.

    PS: Click here if you would prefer not to receive automatic pull-requests from Gitter in future.

  • 🐛 bug fixes

    🐛 bug fixes

    Screenshot 2021-08-10 at 12 16 12 PM Screenshot 2021-08-10 at 12 12 38 PM

    We have several issue on the v3 released

    • Checksum mismatch (after investigation, this is probably due to some breaking changes on go 1.11.3 and go 1.11.4)
    • Improper test case (test doesn't handle correctly, the routine will escape the test result)

    Basically, my PR will fixed the checksum mismatch and test case issue, this had been tested and proved to work.

Limits the number of goroutines that are allowed to run concurrently

Golang Concurrency Manager Golang Concurrency Manager package limits the number of goroutines that are allowed to run concurrently. Installation Run t

Dec 12, 2022
gpool - a generic context-aware resizable goroutines pool to bound concurrency based on semaphore.

gpool - a generic context-aware resizable goroutines pool to bound concurrency. Installation $ go get github.com/sherifabdlnaby/gpool import "github.c

Oct 31, 2022
FLoC Simulator
FLoC Simulator

FLoC Simulator Command line FLoC simulator to calculate CohortID with using host list and cluster data. Build and Run Demo $ cd $ cd demos/floc_sampl

May 5, 2022
DepCharge is a tool designed to help orchestrate the execution of commands across many directories at once.

DepCharge DepCharge is a tool that helps orchestrate the execution of commands across the many dependencies and directories in larger projects. It als

Sep 27, 2022
Kubedock is a minimal implementation of the docker api that will orchestrate containers on a Kubernetes cluster, rather than running containers locally.

Kubedock Kubedock is an minimal implementation of the docker api that will orchestrate containers on a kubernetes cluster, rather than running contain

Nov 11, 2022
Aceptadora provides the boilerplate to orchestrate the containers for an acceptance test.

aceptadora Aceptadora provides the boilerplate to orchestrate the containers for an acceptance test. Aceptadora is a replacement for docker-compose in

Nov 16, 2022
Pipelines using goroutines

pipeline This package provides a simplistic implementation of Go pipelines as outlined in Go Concurrency Patterns: Pipelines and cancellation. Docs Go

Oct 5, 2022
Simply way to control goroutines execution order based on dependencies
Simply way to control goroutines execution order based on dependencies

Goflow Goflow is a simply package to control goroutines execution order based on dependencies. It works similar to async.auto from node.js async packa

Dec 8, 2022
Limits the number of goroutines that are allowed to run concurrently

Golang Concurrency Manager Golang Concurrency Manager package limits the number of goroutines that are allowed to run concurrently. Installation Run t

Dec 12, 2022
gpool - a generic context-aware resizable goroutines pool to bound concurrency based on semaphore.

gpool - a generic context-aware resizable goroutines pool to bound concurrency. Installation $ go get github.com/sherifabdlnaby/gpool import "github.c

Oct 31, 2022