Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Kauehmoreno/v1 proposal #1

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

Conversation

kauehmoreno
Copy link

@kauehmoreno kauehmoreno commented Jan 26, 2024

What it does?

This PR apply new proposal of lib. This version is break change, if accepts it will apply a v1.0.0! So for those who are using it.

We will also keep the v0 available to fix vulnerability and bug's updates. A new branch v0 will be create if this version is accept to keep both v0 and v1 available to all clients.

NEW README


google pubsub

Visão Geral

Este projeto em Go implementa um sistema de publicação e subscrição (PubSub) utilizando a biblioteca Google PubSub.
Ele consiste em três componentes principais: PubSub, Publisher e Subscriber.

Configuração

Pré-Requisitos

  • Go instalado (versão 1.x)
  • Variáveis de ambiente configuradas para Google Cloud (PROJECT_ID, PUBSUB_EMULATOR_HOST, etc.)

Instalação

  • Clone o repositório e instale as dependências necessárias.
Copy code
git clone [URL_DO_REPOSITORIO]
cd [NOME_DO_REPOSITORIO]
go get .

Utilização

Inicialização do PubSub

Para iniciar uma instância do PubSub, utilize a função ConnectPubSub. Esta função aceita opções de configuração que podem ser customizadas, como LoadFromEnv, para carregar configurações do ambiente.

pubsubInstance, err := ConnectPubSub(LoadFromEnv)
if err != nil {
    log.Fatalf("Erro ao conectar ao PubSub: %v", err)
}
defer pubsubInstance.Close(context.Background())

Publicação de Mensagens

Para publicar mensagens, primeiro crie uma instância do Publisher a partir da instância do PubSub e então utilize o método Send.

publisher := pubsubInstance.Publisher()

msg := &Message{
    Topic:   "seu-topico",
    Content: NewContent().Marshal("my custom message"),
}

err := publisher.Send(context.Background(), msg)
if err != nil {
    log.Fatalf("Erro ao enviar mensagem: %v", err)
}

Subscrição e Processamento de Mensagens

Para subscrever a tópicos e processar mensagens, defina uma função Subscriber e registre-a usando o método Register da instância do Subscription.

subscriptionInstance := pubsubInstance.Subscription()
subscriber := OrderSub(logger)

err := subscriptionInstance.Register(context.Background(), subscriber)
if err != nil {
    log.Fatalf("Erro ao registrar subscriber: %v", err)
}

Encerramento e Liberação de Recursos

Utilize o método Close para fechar conexões e liberar recursos.

err := pubsubInstance.Close(context.Background())
if err != nil {
    log.Fatalf("Erro ao fechar conexões do PubSub: %v", err)
}

Exemplo de Subscriber

func OrderSub(logger Logger) pubsub.Subscriber {
    return pubsub.Subscriber{
        Config: pubsub.SubscriptionConfig{
            Topic:           "order-created",
            SubscriptionID:  "order-created-group",
            PullingQuantity: 10,
            TickerTime:      time.Second,
            EarlyAck:        false,
        },
        Handler: func(ctx context.Context, message *Message) error {
            var expectedValue map[string]any
            if err := message.Content.Unmarshal(&expectedValue); err != nil {
                return err
            }           
            logger.Info(ctx, string(expectedValue))
            return nil
        },
        OnError: func(ctx context.Context, err error, header Header) {
            logger.Error(ctx, err.Error())
        },
    }
}

Utilize este exemplo para criar um subscriber para o tópico "order-created".

@kauehmoreno kauehmoreno added the enhancement New feature or request label Jan 26, 2024
@kauehmoreno kauehmoreno requested a review from a team January 26, 2024 21:43
@kauehmoreno kauehmoreno self-assigned this Jan 26, 2024
Copy link

@andrewsmedina andrewsmedina left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe that this change will make easier to write new subs. But I'm -1 for break compatibility changes.

I believe that we should find a way to do it in a partial way. We can use interfaces or new methods to achieve that.

Beside it, is not clear the goal of all changes. It would be nice to know why about these changes.

Comment on lines +88 to +90
OnError: func(ctx context.Context, err error, header Header) {
logger.Error(ctx, err.Error())
},

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Almost all subs have the same implementation of this method. So, why not to automatic log the handler error and remove this?

Comment on lines +76 to +77
PullingQuantity: 10,
TickerTime: time.Second,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why the subscriber should customize this config?

Config: pubsub.SubscriptionConfig{
Topic: "order-created",
SubscriptionID: "order-created-group",
PullingQuantity: 10,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why the subscriber should customize this config?

@kauehmoreno
Copy link
Author

kauehmoreno commented Jan 26, 2024

About transitioning I was think in some strategies, but I would like to focus first on the new Api proposal.

But I Will share my thought:

Once we agree I would create v1 o module and would creat a subscription function that allow old version to fullfil new requirements. And than we would change one by one without any peoblem. After all, we would change to subscritption that not support legacy.

The reason I think its a good option is because we new v1 mod we Will be Abel to import both version on the same project

func (e *Event) Subscribe(listeners ...Listener) {
e.listeners = append(e.listeners, listeners...)
func (e *Event) Subscribe(listeners ...LocalSubscriber) {
e.subscriptions = append(e.subscriptions, listeners...)
}

// Dispatch event based on event name

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Dispatch event based on event name
// Send event based on event name

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants