comentado código

master
dev 1 year ago
parent 2e1316e5b7
commit 8e9c967867

@ -1,92 +0,0 @@
// =============================================================================
// Active-GO Framework
// Copyright (c) 2025 ActiveThing (https://activething.com)
// Author: Juan V. Navarro juanvnl@activething.com
// =============================================================================
//
// 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.
//
// =============================================================================
// Date Create 19/05/2025
// =============================================================================
package errs
import (
"fmt"
"sync"
)
type (
Dispatcher struct {
mu sync.RWMutex
processors map[string]Processor
formatters map[string]Formatter
bufferSize int
cacheMu sync.Mutex
cacheEnable map[string]struct{}
formatCache map[string]map[uintptr][]byte
}
DispatcherFnc func (dispatcher *Dispatcher) error
)
func NewDispatcher(options ...DispatcherFnc) (*Dispatcher,error) {
dp := &Dispatcher{
processors : make(map[string]Processor),
formatters : make(map[string]Formatter),
formatCache: make(map[string]map[uintptr][]byte),
cacheEnable: make(map[string]struct{}),
}
for _,o := range options {
if e := o(dp); e != nil {
return nil,e
}
}
return dp,nil
}
func (d *Dispatcher) RegisterProcessor(processor Processor, options ...ProcessorEntryFnc) error {
d.mu.Lock()
defer d.mu.Unlock()
if processor == nil {
return CreateParamNilErr("processor")
}
if _,ex := d.formatters[processor.FormatterID()]; !ex {
//
//todo create newerror formatter_not_registered
}
if _,ex := d.processors[processor.ID()]; ex {
//
//todo create newerror processor_registered
}
pe,er := NewProcessorEntry(options...)
if er != nil {
return er
}
d.processors[processor.ID()] = pe
return nil
}

@ -1,8 +0,0 @@
go 1.24
use (
app
core
tests
.
)

@ -0,0 +1,35 @@
# **GOAT: Go Active Thing Framework**
![GOAT Logo](/docs/img/goat-logo.png "GOAT")
## **Bienvenido a GOAT** — **Go Active Thing Framework**.
GOAT es un framework moderno y potente para el desarrollo de aplicaciones en Go, concebido para afrontar los retos más exigentes de los sistemas distribuidos y concurrentes actuales. Desde su núcleo, está diseñado para ofrecer una experiencia de desarrollo donde la **observabilidad**, la **resiliencia** y el **rendimiento extremo** no son añadidos, sino fundamentos.
Con GOAT, no solo construyes sistemas que escalan: creas software que **respira con claridad**, **resiste con elegancia** y **corre con velocidad**. Es un framework nacido de la experiencia real en ActiveThing.com, donde lidiar con sistemas complejos es el día a día. GOAT no se limita a seguir buenas prácticas: las redefine con herramientas que van más allá de lo convencional.
---
## **🐐 Filosofía y Principios Fundamentales**
En el corazón de GOAT está una convicción: la complejidad debe enfrentarse con diseño inteligente, no con capas de parches. Por eso se apoya en cinco pilares esenciales:
- **Observabilidad sin fisuras:** Transforma errores y logs en datos estructurados y trazables, dándote visibilidad total para detectar, entender y solucionar cualquier anomalía.
- **Resiliencia de fábrica:** Permite construir sistemas que absorben fallos, se adaptan y continúan funcionando con gracia ante lo inesperado.
- **Rendimiento al límite:** Minimiza la presión sobre la memoria y el recolector de basura, alcanzando una eficiencia digna de entornos críticos.
- **Composición flexible:** Ofrece componentes modulares y reutilizables que se adaptan a tu arquitectura, en lugar de imponer una.
- **Claridad sin concesiones:** Favorece patrones idiomáticos de Go, priorizando la legibilidad, el mantenimiento y la colaboración.
---
## **🌟 Módulos Clave**
GOAT se estructura en módulos especializados que abordan con precisión quirúrgica los aspectos críticos del desarrollo moderno...
## **📜 Licencia**
GOAT (Go Active Thing Framework) se distribuye bajo la **Licencia MIT**. Esto significa que tienes la libertad de usar, copiar, modificar, fusionar, publicar, distribuir, sublicenciar y/o vender copias del software, siempre que incluyas el aviso de copyright y el permiso en todas las copias sustanciales.
¡Esperamos sinceramente que GOAT te ayude a construir aplicaciones Go más **robustas, observables y eficientes**\!
Copyright (c) 2025 ActiveThing (https://activething.com)

@ -100,9 +100,9 @@ var (
// InvalidNilCause indicates that a nil cause was provided where not allowed. // InvalidNilCause indicates that a nil cause was provided where not allowed.
InvalidNilCause Err InvalidNilCause Err
}{ }{
Multiple: Err(moduleName + "multiple_errors"), Multiple: Err(moduleName + "multiple_errors"),
InvalidErrValue: Err(moduleName + "invalid_err_name"), InvalidErrValue: Err(moduleName + "invalid_err_name"),
InvalidClass: Err(moduleName + "invalid_class"), InvalidClass: Err(moduleName + "invalid_class"),
InvalidNilError: Err(moduleName + "invalid_nil_error"), InvalidNilError: Err(moduleName + "invalid_nil_error"),
InvalidMetaName: Err(moduleName + "invalid_meta_name"), InvalidMetaName: Err(moduleName + "invalid_meta_name"),
InvalidMetaType: Err(moduleName + "invalid_meta_type"), InvalidMetaType: Err(moduleName + "invalid_meta_type"),

@ -34,7 +34,7 @@ type (
// ErrorWithCauses is a type that wraps an error and associates it with multiple underlying causes. // ErrorWithCauses is a type that wraps an error and associates it with multiple underlying causes.
// This is useful for aggregating errors from parallel operations. // This is useful for aggregating errors from parallel operations.
ErrorWithCauses struct { ErrorWithCauses struct {
error // The wrapped error error // The wrapped error
causes ErrorList // The list of underlying errors that caused the wrapped error causes ErrorList // The list of underlying errors that caused the wrapped error
} }
) )

@ -33,9 +33,9 @@ import "fmt"
// ErrorWithMetas is a type that wraps an error and associates it with multiple arbitrary metadata items. // ErrorWithMetas is a type that wraps an error and associates it with multiple arbitrary metadata items.
// This is a more general way to add context compared to specific ErrorWithX types. // This is a more general way to add context compared to specific ErrorWithX types.
type ErrorWithMetas struct { type ErrorWithMetas struct {
error // The wrapped error error // The wrapped error
types MetaSelector // A selector indicating the types of metas stored in this error types MetaSelector // A selector indicating the types of metas stored in this error
metas []Meta // The slice of metadata items metas []Meta // The slice of metadata items
} }
// WithMetas creates a Composer that adds multiple metadata items to an error. // WithMetas creates a Composer that adds multiple metadata items to an error.

@ -33,7 +33,7 @@ import "fmt"
// ErrorWithSeverity is a type that wraps an error and adds a Severity level. // ErrorWithSeverity is a type that wraps an error and adds a Severity level.
// This allows classifying the importance of an error. // This allows classifying the importance of an error.
type ErrorWithSeverity struct { type ErrorWithSeverity struct {
error // The wrapped error error // The wrapped error
severity Severity // The severity level of the error severity Severity // The severity level of the error
} }

@ -37,7 +37,7 @@ type (
// ErrorWithStack is a type that wraps an error and adds a stack trace. // ErrorWithStack is a type that wraps an error and adds a stack trace.
// This helps pinpoint the location in the code where the error was created or composed. // This helps pinpoint the location in the code where the error was created or composed.
ErrorWithStack struct { ErrorWithStack struct {
error // The wrapped error error // The wrapped error
stack excs.Stack // The captured stack trace stack excs.Stack // The captured stack trace
} }
) )

@ -53,7 +53,7 @@ func defaultFormatError(w io.Writer, err error, opts *FormatOptions, level int,
return return
} }
var el []error // Slice to collect wrapped errors (causes) for recursive formatting var el []error // Slice to collect wrapped errors (causes) for recursive formatting
var stack *Meta // Pointer to store the stack trace metadata if found var stack *Meta // Pointer to store the stack trace metadata if found
// Determine which metadata to select based on show options. // Determine which metadata to select based on show options.

@ -41,7 +41,7 @@ type (
func (f FormatFnc) Format (err error) ([]byte,error) { return f(err) } func (f FormatFnc) Format (err error) ([]byte,error) { return f(err) }

@ -26,8 +26,8 @@ type (
// Meta represents a single piece of metadata associated with an error. // Meta represents a single piece of metadata associated with an error.
// It consists of a name (key), a value, and a type. // It consists of a name (key), a value, and a type.
Meta struct { Meta struct {
name string // The name or key of the metadata (e.g., "userId", "fileName") name string // The name or key of the metadata (e.g., "userId", "fileName")
value any // The value associated with the metadata (can be of any type) value any // The value associated with the metadata (can be of any type)
mType MetaType // The type of the metadata value mType MetaType // The type of the metadata value
} }
) )

@ -30,15 +30,15 @@ package errs
const ( const (
// Scalar Types // Scalar Types
MetaTypeAny MetaType = iota // 0 - Any type (fallback) MetaTypeAny MetaType = iota // 0 - Any type (fallback)
MetaTypeString // UTF-8 string MetaTypeString // UTF-8 string
MetaTypeInt // Signed integer (64-bit) MetaTypeInt // Signed integer (64-bit)
MetaTypeUInt // Unsigned integer (64-bit) MetaTypeUInt // Unsigned integer (64-bit)
MetaTypeFloat // Floating-point number (64-bit) MetaTypeFloat // Floating-point number (64-bit)
MetaTypeBool // Boolean MetaTypeBool // Boolean
MetaTypeBytes // Arbitrary binary data (base64 in serialization) MetaTypeBytes // Arbitrary binary data (base64 in serialization)
MetaTypeTime // Time (RFC3339 / Unix) MetaTypeTime // Time (RFC3339 / Unix)
MetaTypeDuration // Duration MetaTypeDuration // Duration
// Composite Types // Composite Types
MetaTypeList // Ordered list of elements MetaTypeList // Ordered list of elements

@ -37,7 +37,7 @@ type (
// PanicErr is an error type that wraps a recovered panic. // PanicErr is an error type that wraps a recovered panic.
// It allows treating a panic as a structured error. // It allows treating a panic as a structured error.
PanicErr struct { PanicErr struct {
Err // Embeds the Err type to inherit its methods and basic structure. Err // Embeds the Err type to inherit its methods and basic structure.
cause error // cause stores the recovered panic value, converted to an error type. cause error // cause stores the recovered panic value, converted to an error type.
} }
) )
@ -46,8 +46,8 @@ type (
// It converts the panic value to an error type using ToError. // It converts the panic value to an error type using ToError.
func CreatePanicErr(cause any) PanicErr { func CreatePanicErr(cause any) PanicErr {
return PanicErr{ return PanicErr{
Err: CreateErr(errPanic), // Creates a base error with the "panic" class. Err: CreateErr(errPanic), // Creates a base error with the "panic" class.
cause: ToError(cause), // Converts the panic value to an error. cause: ToError(cause), // Converts the panic value to an error.
} }
} }

@ -0,0 +1,203 @@
// =============================================================================
// Active-GO Framework
// Copyright (c) 2025 ActiveThing (https://activething.com)
// Author: Juan V. Navarro juanvnl@activething.com
// =============================================================================
//
// 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.
//
// =============================================================================
// Date Create 19/05/2025
// =============================================================================
package logs
import (
"context"
"core/errs"
"fmt"
"reflect"
"sync"
)
type (
Dispatcher struct {
mu sync.RWMutex
processors map[string]*ProcessorEntry
formatters map[string]errs.Formatter
bufferSize int
cacheMu sync.Mutex
cacheEnabled map[string]struct{}
formatCache map[string]map[uintptr][]byte
inputChan chan error
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
}
DispatcherFnc func (dispatcher *Dispatcher) error
)
func NewDispatcher(options ...DispatcherFnc) (*Dispatcher,error) {
dp := &Dispatcher{
processors : make(map[string]*ProcessorEntry),
formatters : make(map[string]errs.Formatter),
formatCache: make(map[string]map[uintptr][]byte),
cacheEnabled: make(map[string]struct{}),
inputChan : make(chan error,100),
}
for _,o := range options {
if e := o(dp); e != nil {
return nil,e
}
}
return dp,nil
}
func (d *Dispatcher) Start () {
d.mu.Lock()
defer d.mu.Unlock()
if d.ctx != nil {
//todo
//panic dispatcher already started
}
d.ctx,d.cancel = context.WithCancel(context.Background())
d.wg.Add(1)
go d.run()
for _,entry := range d.processors {
d.wg.Add(1)
go d.processErrors(d.ctx, entry)
}
}
func (d *Dispatcher) RegisterProcessor(processor Processor, options ...ProcessorEntryFnc) error {
d.mu.Lock()
defer d.mu.Unlock()
if processor == nil {
return errs.CreateParamNilErr("processor")
}
if _,ex := d.formatters[processor.FormatterID()]; !ex {
//
//todo create newerror formatter_not_registered
}
if _,ex := d.processors[processor.ID()]; ex {
//
//todo create newerror processor_registered
}
pe,er := NewProcessorEntry(options...)
if er != nil {
return er
}
d.processors[processor.ID()] = pe
return nil
}
func (d *Dispatcher) processErrors (entry *ProcessorEntry) {
defer d.wg.Done()
for {
select {
case <- d.ctx.Done():
// todo existing
//
case er,ok := <-entry.channel:
if !ok {
// channel closed
return
}
fi := entry.Processor.FormatterID()
}
}
}
// getFormattedError retrieves the formatted error from the cache or formats it if not found.
// It uses the dispatcher's formatters and cache.
// This function is called by the processor's dedicated goroutine.
func (d *Dispatcher) getFormattedError(err error, formatterID string) ([]byte, error) {
// Use the error's underlying value's pointer address as a unique identifier for this specific error instance.
// This is the correct and idiomatic way to get a stable ID for caching error instances.
errID := reflect.ValueOf(err).Pointer() // Using reflect.ValueOf().Pointer() for errID
// Check if caching is enabled for this formatter ID.
d.mu.RLock() // Use RLock to check cacheEnabled map
_, cachingEnabled := d.cacheEnabled[formatterID]
d.mu.RUnlock() // Release RLock
if cachingEnabled {
d.cacheMu.Lock() // Acquire cache lock to read from cache
// Check if the formatted error is already in the cache for this formatter ID and error.
if formatterCache, ok := d.formatCache[formatterID]; ok {
if formatted, ok := formatterCache[errID]; ok {
d.cacheMu.Unlock() // Release cache lock before returning
return formatted, nil // Found in cache
}
}
d.cacheMu.Unlock() // Release cache lock before accessing formatters (which require d.mu)
}
// Formatted error not in cache or caching is disabled, find the formatter and format it.
d.mu.RLock() // Need RLock to access the formatters map
formatter, exists := d.formatters[formatterID]
d.mu.RUnlock() // Release RLock
if !exists {
// This should ideally not happen if RegisterProcessor checks were sufficient,
// but handle defensively.
return nil, fmt.Errorf("formatter with ID '%s' not found", formatterID)
}
// Format the error using the found formatter.
formatted, formatErr := formatter.Format(err)
if formatErr != nil {
return nil, fmt.Errorf("failed to format error using formatter '%s': %w", formatterID, formatErr)
}
// Store the formatted error in the cache only if caching is enabled for this formatter.
if cachingEnabled {
d.cacheMu.Lock() // Acquire cache lock to write to cache
if _, ok := d.formatCache[formatterID]; !ok {
d.formatCache[formatterID] = make(map[uintptr][]byte)
}
d.formatCache[formatterID][errID] = formatted
d.cacheMu.Unlock() // Release cache lock after writing to cache
}
return formatted, nil
}

@ -26,7 +26,7 @@
// Date Create 19/05/2025 // Date Create 19/05/2025
// ============================================================================= // =============================================================================
package errs package logs
type ( type (

@ -26,17 +26,17 @@
// Date Create 20/05/2025 // Date Create 20/05/2025
// ============================================================================= // =============================================================================
package errs package logs
import "time" import "time"
type ( type (
ProcessorEntry struct { ProcessorEntry struct {
processor Processor Processor
channel chan error channel chan error
state ProcessorState state ProcessorState
failures int failures int
maxFailures int maxFailures int
blockedTime time.Time blockedTime time.Time
blockTime time.Time blockTime time.Time
@ -48,7 +48,7 @@ type (
func NewProcessorEntry (options...ProcessorEntryFnc) (*ProcessorEntry,error) { func NewProcessorEntry (options...ProcessorEntryFnc) (*ProcessorEntry,error) {
pe := &ProcessorEntry { pe := &ProcessorEntry{
} }
return pe,nil return pe,nil

@ -26,7 +26,7 @@
// Date Create 19/05/2025 // Date Create 19/05/2025
// ============================================================================= // =============================================================================
package errs package logs

@ -0,0 +1,8 @@
go 1.24
use (
./app
./src/core
./src/tests
.
)
Loading…
Cancel
Save

Powered by TurnKey Linux.