Padrão Observer em GO


Resumo
// Package pubsub implementa um Pub/Sub intra-processo baseado em canais, // ideal para fan-out de eventos dentro do mesmo binário, sem dependências externas. package pubsub import ( "context" "sync" ) // subscription é um identificador interno + canal de leitura que o assinante usa. type subscription[T any] struct { id int ch <-chan T } // subscribeReq encapsula um pedido de inscrição feito ao hub. type subscribeReq[T any] struct { buf int // tamanho do buffer do canal deste inscrito (backpressure local) resp chan subscription[T] // resposta: id + canal criado para o inscrito } // PubSub gerencia publicações e assinaturas por meio de um hub (uma goroutine). // Não requer mutexes; todo o estado é manipulado dentro do loop do hub. type PubSub[T any] struct { // Canais internos do hub pub chan T // recebe mensagens a serem entregues a todos os inscritos subReq chan subscribeReq[T] // recebe pedidos de nova assinatura unsubReq chan int // recebe pedidos de cancelamento por id de inscrição stop chan struct{} // sinaliza encerramento do hub once sync.Once // garante Close idempotente } // New cria a estrutura e inicia o loop do hub. // Use sempre New para garantir que o hub foi iniciado. func New[T any]() *PubSub[T] { ps := &PubSub[T]{ pub: make(chan T), subReq: make(chan subscribeReq[T]), unsubReq: make(chan int), stop: make(chan struct{}), } go ps.loop() return ps } // loop é a "central de eventos". Roda numa única goroutine. // Ele: // - cria canais por inscrito (com buffer customizável) // - entrega mensagens para todos os inscritos // - cancela inscrições e fecha os canais dos inscritos // - fecha tudo ao receber stop func (ps *PubSub[T]) loop() { subs := make(map[int]chan T) // id -> canal do inscrito (somente o hub escreve/fecha) nextID := 1 for { select { case req := <-ps.subReq: // Novo inscrito: cria um canal somente deste inscrito. id := nextID nextID++ ch := make(chan T, req.buf) // buffer escolhido pelo cliente subs[id] = ch // Responde com id e o canal de leitura. req.resp <- subscription[T]{id: id, ch: ch} case id := <-ps.unsubReq: // Cancelamento: o hub é o único que fecha o canal do inscrito. if ch, ok := subs[id]; ok { close(ch) delete(subs, id) } case msg := <-ps.pub: // Fan-out: tenta enviar para todos os inscritos. // Política: se o canal do inscrito estiver cheio, descartamos a mensagem para aquele inscrito, // evitando bloquear o hub (e, por consequência, todos os demais). for id, ch := range subs { select { case ch <- msg: // entregue com sucesso default: // Canal cheio: descartamos para este inscrito. // Em produção, incremente uma métrica (ex.: drops_total{subscriber_id}++). _ = id } } case <-ps.stop: // Encerramento: fecha todos os canais de inscritos, então sai. for id, ch := range subs { close(ch) delete(subs, id) } return } } } // Publish envia um evento para o hub. Retorna false se o PubSub já foi fechado. // Observação: a publicação pode bloquear se o hub estiver momentaneamente ocupado lendo outros casos. func (ps *PubSub[T]) Publish(msg T) bool { // Caminho rápido: se já fechou, não publique. select { case <-ps.stop: return false default: } // Tenta publicar, mas também aborta se fechar no meio do caminho. select { case ps.pub <- msg: return true case <-ps.stop: return false } } // Subscribe registra um novo inscrito com buffer 'buf'. // Retorna: // - ch: canal somente leitura com os eventos // - cancel: função para desinscrever; o hub fechará 'ch' func (ps *PubSub[T]) Subscribe(buf int) (ch <-chan T, cancel func()) { req := subscribeReq[T]{buf: buf, resp: make(chan subscription[T])} // 1) Envia a solicitação de inscrição, a menos que o hub já tenha sido fechado. select { case ps.subReq <- req: case <-ps.stop: // Se já fechou, retorne um canal fechado para não bloquear quem fizer range. c := make(chan T) close(c) return c, func() {} } // 2) Aguarda o retorno do hub com o id + canal do inscrito. var sub subscription[T] select { case sub = <-req.resp: case <-ps.stop: // Se fechar nesse meio tempo, retorne um canal fechado. c := make(chan T) close(c) return c, func() {} } // cancel informa ao hub que este inscrito não quer mais receber eventos. return sub.ch, func() { select { case ps.unsubReq <- sub.id: case <-ps.stop: } } } // SubscribeWithContext faz Subscribe e desinscreve automaticamente quando ctx.Done(). // Útil para vincular o ciclo de vida do inscrito ao de uma requisição/worker. func (ps *PubSub[T]) SubscribeWithContext(ctx context.Context, buf int) (ch <-chan T) { ch, cancel := ps.Subscribe(buf) go func() { <-ctx.Done() cancel() }() return ch } // Close encerra o hub e fecha todos os canais dos inscritos (via loop). // É seguro chamar múltiplas vezes. func (ps *PubSub[T]) Close() { ps.once.Do(func() { close(ps.stop) }) }
package main import ( "context" "fmt" "time" "example.com/williammacarini/pubsub" ) // Exemplo de payload do evento: atualização de preço. type PriceUpdate struct { SKU string Price float64 Time time.Time } func main() { // Cria o PubSub (genérico) para PriceUpdate. ps := pubsub.New[PriceUpdate]() defer ps.Close() // garante fechamento ao sair (fecha canais dos inscritos) // Inscrito "rápido": buffer maior => menor chance de drops. fastCh, fastCancel := ps.Subscribe(16) defer fastCancel() // cancela inscrição ao final // Inscrito "lento": buffer pequeno => tende a saturar e sofrer drops. ctx, cancel := context.WithCancel(context.Background()) defer cancel() slowCh := ps.SubscribeWithContext(ctx, 2) // Consumer rápido: processa imediatamente (não dorme). go func() { for e := range fastCh { // range fecha naturalmente quando hub encerrar ou cancelar inscrição fmt.Printf("[FAST] %s -> %.2f\n", e.SKU, e.Price) } fmt.Println("[FAST] encerrado") }() // Consumer lento: simula trabalho custoso e acumula fila. go func() { for e := range slowCh { fmt.Printf(" [SLOW] %s -> %.2f\n", e.SKU, e.Price) time.Sleep(80 * time.Millisecond) // simula processamento lento (causa backpressure) } fmt.Println(" [SLOW] encerrado") }() // Publisher: gera 20 eventos rapidamente (mais rápido que o consumidor lento consegue processar). for i := 0; i < 20; i++ { ok := ps.Publish(PriceUpdate{ SKU: "ABC-123", Price: 100 + float64(i), Time: time.Now(), }) if !ok { // Se false, o hub foi fechado e não vale mais publicar. break } time.Sleep(10 * time.Millisecond) // pequena pausa entre eventos } // Cancela o inscrito lento após um tempo (dispara ctx.Done()). time.Sleep(500 * time.Millisecond) cancel() // Dá tempo para drenar as mensagens e imprimir a saída antes de encerrar. time.Sleep(300 * time.Millisecond) }
Saída esperada (aproximada)
O padrão Observer em Go fica simples, performático e seguro quando modelado com um hub baseado em canais. A abordagem proposta elimina mutexes no caminho crítico, oferece tipagem forte com generics e permite controlar backpressure por inscrito. Em cenários intra-processo, esse pub/sub cobre a maioria dos casos de fan-out com baixo acoplamento e cancelamento limpo via context. Se houver necessidade de durabilidade, reprocessamento ou múltiplos serviços, é hora de migrar para um broker externo. Como próximos passos, escolha a política de backpressure adequada ao seu SLA e instrumente métricas (publicadas, entregues e descartadas) para operar o sistema com confiança.
Summary
// Package pubsub implements an in-process Pub/Sub using channels, // ideal for event fan-out within a single binary without external dependencies. package pubsub import ( "context" "sync" ) // subscription holds the internal id and the read-only channel a subscriber consumes from. type subscription[T any] struct { id int ch <-chan T } // subscribeReq wraps a subscription request sent to the hub. type subscribeReq[T any] struct { buf int // buffer size for this subscriber's channel (local backpressure) resp chan subscription[T] // response: id + created channel for the subscriber } // PubSub manages publications and subscriptions through a hub (single goroutine). // No mutexes required; all state is mutated inside the hub loop. type PubSub[T any] struct { // Hub internal channels pub chan T // receives messages to be delivered to all subscribers subReq chan subscribeReq[T] // receives new subscription requests unsubReq chan int // receives unsubscribe requests by subscription id stop chan struct{} // signals hub shutdown once sync.Once // ensures idempotent Close } // New creates the structure and starts the hub loop. // Always use New to ensure the hub is running. func New[T any]() *PubSub[T] { ps := &PubSub[T]{ pub: make(chan T), subReq: make(chan subscribeReq[T]), unsubReq: make(chan int), stop: make(chan struct{}), } go ps.loop() return ps } // loop is the "event center". It runs on a single goroutine. // Responsibilities: // - create per-subscriber channels (with custom buffer) // - deliver messages to all subscribers // - unsubscribe and close subscriber channels // - close everything when stop is signaled func (ps *PubSub[T]) loop() { subs := make(map[int]chan T) // id -> subscriber channel (only the hub writes/closes) nextID := 1 for { select { case req := <-ps.subReq: // New subscriber: create a dedicated channel. id := nextID nextID++ ch := make(chan T, req.buf) // buffer chosen by the client subs[id] = ch // Reply with id and read-only channel. req.resp <- subscription[T]{id: id, ch: ch} case id := <-ps.unsubReq: // Unsubscribe: the hub is the only one that closes subscriber channels. if ch, ok := subs[id]; ok { close(ch) delete(subs, id) } case msg := <-ps.pub: // Fan-out: try to send to all subscribers. // Policy: if a subscriber's channel is full, drop the message for that subscriber // to avoid blocking the hub (and thus everyone else). for id, ch := range subs { select { case ch <- msg: // delivered default: // Channel full: we drop for this subscriber. // In production, increment a metric (e.g., drops_total{subscriber_id}++). _ = id } } case <-ps.stop: // Shutdown: close all subscriber channels, then exit. for id, ch := range subs { close(ch) delete(subs, id) } return } } } // Publish sends an event to the hub. Returns false if the PubSub has been closed. // Note: publish can block briefly if the hub is busy on other cases. func (ps *PubSub[T]) Publish(msg T) bool { // Fast path: if already closed, don't publish. select { case <-ps.stop: return false default: } // Try to publish, but abort if closed in the meantime. select { case ps.pub <- msg: return true case <-ps.stop: return false } } // Subscribe registers a new subscriber with buffer 'buf'. // Returns: // - ch: read-only channel with events // - cancel: function to unsubscribe; the hub will close 'ch' func (ps *PubSub[T]) Subscribe(buf int) (ch <-chan T, cancel func()) { req := subscribeReq[T]{buf: buf, resp: make(chan subscription[T])} // 1) Send subscription request unless the hub is already closed. select { case ps.subReq <- req: case <-ps.stop: // If closed, return a closed channel so ranging over it doesn't block. c := make(chan T) close(c) return c, func() {} } // 2) Wait for hub to reply with id + channel. var sub subscription[T] select { case sub = <-req.resp: case <-ps.stop: // If it closes in the meantime, return a closed channel. c := make(chan T) close(c) return c, func() {} } // cancel notifies the hub this subscriber no longer wants events. return sub.ch, func() { select { case ps.unsubReq <- sub.id: case <-ps.stop: } } } // SubscribeWithContext does Subscribe and automatically unsubscribes when ctx.Done(). // Handy to bind a subscriber's lifecycle to a request/worker context. func (ps *PubSub[T]) SubscribeWithContext(ctx context.Context, buf int) (ch <-chan T) { ch, cancel := ps.Subscribe(buf) go func() { <-ctx.Done() cancel() }() return ch } // Close shuts down the hub and closes all subscriber channels (via loop). // Safe to call multiple times. func (ps *PubSub[T]) Close() { ps.once.Do(func() { close(ps.stop) }) }
package main import ( "context" "fmt" "time" "example.com/williammacarini/pubsub" ) // Example event payload: price update. type PriceUpdate struct { SKU string Price float64 Time time.Time } func main() { // Create generic PubSub for PriceUpdate. ps := pubsub.New[PriceUpdate]() defer ps.Close() // ensure hub shutdown on exit (closes subscriber channels) // "Fast" subscriber: larger buffer => fewer drops. fastCh, fastCancel := ps.Subscribe(16) defer fastCancel() // unsubscribe at the end // "Slow" subscriber: small buffer => more likely to saturate and drop. ctx, cancel := context.WithCancel(context.Background()) defer cancel() slowCh := ps.SubscribeWithContext(ctx, 2) // Fast consumer: processes immediately (no sleep). go func() { for e := range fastCh { // range ends when the hub closes or we unsubscribe fmt.Printf("[FAST] %s -> %.2f\n", e.SKU, e.Price) } fmt.Println("[FAST] closed") }() // Slow consumer: simulates expensive work and builds up a queue. go func() { for e := range slowCh { fmt.Printf(" [SLOW] %s -> %.2f\n", e.SKU, e.Price) time.Sleep(80 * time.Millisecond) // simulate slow processing (causes backpressure) } fmt.Println(" [SLOW] closed") }() // Publisher: produce 20 events quickly (faster than the slow consumer can process). for i := 0; i < 20; i++ { ok := ps.Publish(PriceUpdate{ SKU: "ABC-123", Price: 100 + float64(i), Time: time.Now(), }) if !ok { // If false, hub is closed and we should stop publishing. break } time.Sleep(10 * time.Millisecond) // short pause between events } // Cancel the slow subscriber after a while (triggers ctx.Done()). time.Sleep(500 * time.Millisecond) cancel() // Give time to drain messages and print before exit. time.Sleep(300 * time.Millisecond) }
Expected output (approximate)
The Observer pattern in Go becomes simple, fast, and safe when modeled with a channel-based hub. This approach removes mutexes from the hot path, provides strong typing via generics, and lets you control per-subscriber backpressure. For in-process scenarios, this pub/sub design covers most fan-out needs with low coupling and clean context-driven cancellation. If you need durability, replays, or multi-service delivery, it’s time to move to an external broker. Next steps: pick the backpressure policy that matches your SLA and instrument metrics (published, delivered, dropped) to operate the system with confidence.