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

feat: Create new version that make easier to create subscriber as well as keep retro compability #2

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

kauehmoreno
Copy link

@kauehmoreno kauehmoreno commented May 15, 2024

What for ?

Create new version that make easier to create subscriber as well as keep retro compatibility and allow on subscriber handle multiple topics.

With that new version subscribers will be able to listen to many topic with a unique subscriber allowing not repeat many subs per topic.

We have included testcontainer to be able to create integration test on both subscriber and publisher.

Older version on change the way it applies subscriptions.


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.

]

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

err := pubsubInstance.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.

subscriber := OrderSub(logger)

err := pubsubInstance.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",
            AckDeadline:      time.Second,
            EarlyAck:        false,
           EnableMessageOrdering: 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 May 15, 2024
@kauehmoreno kauehmoreno requested a review from a team May 15, 2024 02:49
@kauehmoreno kauehmoreno self-assigned this May 15, 2024
publisher.go Outdated Show resolved Hide resolved
publisher.go Outdated Show resolved Hide resolved
subscriber.go Outdated Show resolved Hide resolved
@andrewsmedina
Copy link

andrewsmedina commented May 15, 2024

I believe that this PR does a lot of things including changing the dispatch and subscribe contracts. I believe that we should consider the impact of these changes before to go with this PR.

I suggest to we add these proposal in an incremental way

@kauehmoreno
Copy link
Author

The point is:

  • We need to enable on subscriber to able to listen more than one topic.

The current way using interface, we cannot! If we include one more method we will break all implementations.

So my idea was to refactor, and keep compatibility with legacy usage(interface) .
The integration tests has guarantee that everything works, I can create more cases to stress it out.

One idea is: I can create a beta version and then I test it with a specifc realease on inda_api pointing to this beta! Just to complement the tests.

…l as keep retro compatibility and allow on subscriber handle multiple topics
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