outis

package module
v1.4.1 Latest Latest
Warning

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

Go to latest
Published: May 23, 2025 License: MIT Imports: 17 Imported by: 0

README

Outis

A biblioteca outis ajuda você a criar e gerenciar rotinas, programar tempo de execução e controlar a concorrência entre outros processos.

Exemplo de como utilizar

package main

import (
	"errors"
	"time"

	"github.com/Brisanet/outis"
)

func main() {
	// Inicializa o log
	log, err := outis.NewLogger("scriptName", outis.Options{
		Level: outis.DebugLevel,
	})
	if err != nil {
		log.Fatal(err.Error())
	}

	// Inicializa o outis para receber rotinas
	watch := outis.Watcher("8b1d6a18-5f3d-4482-a574-35d3965c8783", "scriptName",
		// Passa o log personalizado, se não informado é criado um log padrão
		outis.Logger(log),
	)

	watch.Go(
		// Identificador de rotina para executar controle de concorrência
		outis.WithID("422138b3-c721-4021-97ab-8cf7e174fb4f"),

		outis.WithName("Here is the name of my routine"),
		outis.WithDesc("Here is the description of my routine"),

		// Executará a cada 10 segundos
		outis.WithInterval(time.Second),

		// Executará de 12pm a 4pm.
		// por padrão, não há restrições de tempo.
		// outis.WithHours(12, 16),

		// Executará somente uma vez
		// outis.WithNotUseLoop(),

		// Aqui é passada a função do script que será executada
		outis.WithScript(func(ctx *outis.Context) error {
			ctx.LogInfo("this is an information message")
			ctx.LogError(errors.New("this is an error message"))

			ctx = ctx.AddSingleMetadata("client_ids", []int64{234234})
			ctx = ctx.AddMetadata(outis.Metadata{"notification": outis.Metadata{
				"client_id": 234234,
				"message":   "Hi, we are notifying you.",
				"fcm":       "231223",
			}})

			ctx.LogDebug("this is an debug message with metadata")

			return nil
		}),
	)

	// Método que mantém a rotina no processo
	watch.Wait()
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Wait

func Wait()

Wait responsible for keeping routines running

Types

type Context

type Context interface {
	Context() context.Context
	Cancel()
	Done() <-chan struct{}
	Err() error
	Copy(baseCtxIn ...context.Context) Context
	GetLatency() float64
	LogInfo(msg string, fields ...LogFields)
	LogError(err error, fields ...LogFields)
	LogErrorMsg(msg string, fields ...LogFields)
	LogFatal(msg string, fields ...LogFields)
	LogPanic(msg string, fields ...LogFields)
	LogDebug(msg string, fields ...LogFields)
	LogWarn(msg string, fields ...LogFields)
	AddSingleMetadata(key string, args interface{}) Context
	AddMetadata(metadata Metadata) Context

	Name() string
	RoutineID() ID
	ID() ID
}

Context defines the data structure of the routine context.

type ContextImpl added in v1.4.0

type ContextImpl struct {
	Desc string

	Interval time.Duration
	Path     string
	RunAt    time.Time
	Watcher  Watch
	// contains filtered or unexported fields
}

ContextImpl implements context interface

func (*ContextImpl) AddMetadata added in v1.4.0

func (ctx *ContextImpl) AddMetadata(metadata Metadata) Context

AddMetadata método adiciona metadata no contexto.

func (*ContextImpl) AddSingleMetadata added in v1.4.0

func (ctx *ContextImpl) AddSingleMetadata(key string, args interface{}) Context

AddSingleMetadata método adiciona 1 metadata no contexto.

func (*ContextImpl) Cancel added in v1.4.0

func (ctx *ContextImpl) Cancel()

Cancel cancela o contexto.

func (*ContextImpl) Context added in v1.4.0

func (ctx *ContextImpl) Context() context.Context

Context retorna o context.Context.

func (*ContextImpl) Copy added in v1.4.0

func (ctx *ContextImpl) Copy(baseCtxIn ...context.Context) Context

Copy cria um cópia do contexto atual.

func (*ContextImpl) Done added in v1.4.0

func (ctx *ContextImpl) Done() <-chan struct{}

Done retorna um canal que espera o canal ser finalizado.

func (*ContextImpl) Err added in v1.4.0

func (ctx *ContextImpl) Err() error

Err retorna o erro no contexto.

func (*ContextImpl) GetLatency added in v1.4.0

func (ctx *ContextImpl) GetLatency() float64

GetLatency get script execution latency (in seconds).

func (*ContextImpl) ID added in v1.4.0

func (ctx *ContextImpl) ID() ID

ID returns the execution ID of the routine

func (*ContextImpl) LogDebug added in v1.4.0

func (ctx *ContextImpl) LogDebug(msg string, fields ...LogFields)

LogDebug executa a função Debug do log do contexto.

func (*ContextImpl) LogError added in v1.4.0

func (ctx *ContextImpl) LogError(err error, fields ...LogFields)

LogError executa a função Error do log do contexto.

func (*ContextImpl) LogErrorMsg added in v1.4.0

func (ctx *ContextImpl) LogErrorMsg(msg string, fields ...LogFields)

LogErrorMsg executa a função ErrorMsg do log do contexto com uma mensagem de erro.

func (*ContextImpl) LogFatal added in v1.4.0

func (ctx *ContextImpl) LogFatal(msg string, fields ...LogFields)

LogFatal executa a função Fatal do log do contexto.

func (*ContextImpl) LogInfo added in v1.4.0

func (ctx *ContextImpl) LogInfo(msg string, fields ...LogFields)

LogInfo executa a função Info do log do contexto.

func (*ContextImpl) LogPanic added in v1.4.0

func (ctx *ContextImpl) LogPanic(msg string, fields ...LogFields)

LogPanic executa a função Panic do log do contexto.

func (*ContextImpl) LogWarn added in v1.4.0

func (ctx *ContextImpl) LogWarn(msg string, fields ...LogFields)

LogWarn executa a função Warn do log do contexto.

func (*ContextImpl) Name added in v1.4.0

func (ctx *ContextImpl) Name() string

Name returns the name of the routine

func (*ContextImpl) NewHistogram added in v1.4.0

func (ctx *ContextImpl) NewHistogram(key string) *Histogram

NewHistogram creates a new histogram.

func (*ContextImpl) NewIndicator added in v1.4.0

func (ctx *ContextImpl) NewIndicator(key string) *Indicator

NewIndicator creates a new indicator.

func (*ContextImpl) Retry added in v1.4.0

func (ctx *ContextImpl) Retry(retries int8) *retry

Go returns the settings for using the Attempt method

func (*ContextImpl) RoutineID added in v1.4.0

func (ctx *ContextImpl) RoutineID() ID

RoutineID returns the ID of the routine

type Event

type Event interface{}

Event sets the type for the event structure

type EventMetric

type EventMetric struct {
	ID         string
	Latency    time.Duration
	StartedAt  time.Time
	FinishedAt time.Time
	Watcher    WatcherMetric
	Routine    RoutineMetric
	Metadata   Metadata
	Indicators []*Indicator
	Histograms []*Histogram
}

EventMetric defines the type of metric sent in the event

type Histogram added in v1.3.4

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

func (*Histogram) Add added in v1.3.4

func (h *Histogram) Add(value float64)

Add add a value to the histogram.

func (*Histogram) GetKey added in v1.3.4

func (h *Histogram) GetKey() string

GetKey get the key value of an histogram.

func (*Histogram) GetValues added in v1.3.4

func (h *Histogram) GetValues() (values []float64, times []time.Time)

GetValue get the values of an histogram.

func (*Histogram) Inc added in v1.3.4

func (h *Histogram) Inc()

Inc increments the histogram data.

type ID

type ID string

ID defines the type of identifier

func (ID) ToString

func (id ID) ToString() string

ToString return the identifier as a string

type ILogger

type ILogger interface {
	Level() LogLevel
	Info(msg string, fields ...LogFields)
	Error(erro error, fields ...LogFields)
	ErrorMsg(errorMsg string, fields ...LogFields)
	Fatal(msg string, fields ...LogFields)
	Panic(msg string, fields ...LogFields)
	Debug(msg string, fields ...LogFields)
	Warn(msg string, fields ...LogFields)
	AddFields(fields ...LogFields) ILogger
	AddField(key string, value interface{}) ILogger
}

ILogger methods for logging messages.

func NewLogger added in v1.3.4

func NewLogger(appName string, optionsIn ...LogOptions) (ILogger, error)

NewLogger cria um novo logger

type IOutis

type IOutis interface {
	Go(fn func() error)
	Wait() error

	Init(ctx Context) error
	Before(ctx Context) error
	After(ctx Context) error
	Event(ctx Context, event Event)
}

IOutis is the main interface for implementing the outis lib.

type Indicator added in v1.3.4

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

func (*Indicator) Add added in v1.3.4

func (i *Indicator) Add(value float64)

Add add a value to the indicator.

func (*Indicator) GetCreatedAt added in v1.3.4

func (i *Indicator) GetCreatedAt() time.Time

GetCreatedAt get the creation date of an indicator.

func (*Indicator) GetKey added in v1.3.4

func (i *Indicator) GetKey() string

GetKey get the key value of an indicator.

func (*Indicator) GetValue added in v1.3.4

func (i *Indicator) GetValue() float64

GetValue get the value of an indicator.

func (*Indicator) Inc added in v1.3.4

func (i *Indicator) Inc()

Inc increments the indicator data.

type LogFields added in v1.3.4

type LogFields map[string]interface{}

LogFields representa os campos do log

type LogLevel added in v1.3.4

type LogLevel string

LogLevel representa o level do log

const (
	// DebugLevel representa o nível de debug do Log
	DebugLevel LogLevel = "DebugLevel"
	// InfoLevel representa o nível de info do Log
	InfoLevel LogLevel = "InfoLevel"
	// WarnLevel representa o nível de warn do Log
	WarnLevel LogLevel = "WarnLevel"
	// ErrorLevel representa o nível de error do Log
	ErrorLevel LogLevel = "ErrorLevel"
	// DPanicLevel representa o nível de dpanic do Log
	DPanicLevel LogLevel = "DPanicLevel"
	// PanicLevel representa o nível de panic do Log
	PanicLevel LogLevel = "PanicLevel"
	// FatalLevel representa o nível de fatal do Log
	FatalLevel LogLevel = "FatalLevel"
)

type LogOptions added in v1.3.4

type LogOptions struct {
	Level            LogLevel
	Dev              bool
	OutputPaths      []string
	ErrorOutputPaths []string
}

LogOptions representa as opções de configuração do log

type Metadata

type Metadata map[string]interface{}

Metadata defines type of metadata used in metrics

func (Metadata) GetBytes

func (md Metadata) GetBytes() []byte

GetBytes return the routine metadata in bytes

func (Metadata) Set

func (md Metadata) Set(value string, args interface{})

Set add data to metadata

type Option

type Option func(*ContextImpl)

Option defines the option type of a routine

func WithDesc

func WithDesc(desc string) Option

WithDesc defines the description of a routine

func WithExecuteFirstTimeBeforeInterval added in v1.3.9

func WithExecuteFirstTimeBeforeInterval() Option

WithExecuteFirstTimeNow define that the routine will execute first time when Watcher.Go is called

func WithHours

func WithHours(start, end uint) Option

WithHours sets the start and end time of script execution

func WithID

func WithID(id ID) Option

WithID defines a routine's identifier

func WithInterval

func WithInterval(duration time.Duration) Option

WithInterval defines the interval at which the script will be executed

func WithMinutes

func WithMinutes(start, end uint) Option

WithMinutes sets the start and end minutes of script execution

func WithName

func WithName(name string) Option

WithName defines the name of a routine

func WithNotUseLoop

func WithNotUseLoop() Option

WithNotUseLoop define that the routine will not enter a loop

func WithScript

func WithScript(fn func(Context) error) Option

WithScript defines the script function that will be executed

type RoutineMetric

type RoutineMetric struct {
	ID        string
	Name      string
	Path      string
	StartedAt time.Time
}

RoutineMetric defines the type of metric of a routine sent in the event

type Watch

type Watch struct {
	Id    ID        `json:"id"`
	Name  string    `json:"name"`
	RunAt time.Time `json:"run_at"`
	// contains filtered or unexported fields
}

Watch defines the type of the watcher structure

func Watcher

func Watcher(id, name string, opts ...WatcherOption) *Watch

Watcher initializes a new watcher

func (*Watch) Go

func (watch *Watch) Go(opts ...Option)

Go create a new routine in the watcher

func (*Watch) Wait

func (watch *Watch) Wait()

Wait method responsible for keeping routines running

type WatcherMetric

type WatcherMetric struct {
	ID    string
	Name  string
	RunAt time.Time
}

WatcherMetric defines the type of metric of a watcher sent in the event

type WatcherOption

type WatcherOption func(*Watch)

WatcherOption defines the option type of a watcher

func Impl

func Impl(outis IOutis) WatcherOption

Impl defines the implementation of the main interface

func Logger

func Logger(logger ILogger) WatcherOption

Logger defines the implementation of the log interface

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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