github.com/asynkron/protoactor-go@v0.0.0-20240308120642-ef91a6abee75/cluster/pubsub_publisher.go (about)

     1  package cluster
     2  
     3  import (
     4  	"context"
     5  	"log/slog"
     6  	"time"
     7  
     8  	"google.golang.org/protobuf/proto"
     9  	"google.golang.org/protobuf/types/known/durationpb"
    10  )
    11  
    12  type PublisherConfig struct {
    13  	IdleTimeout time.Duration
    14  }
    15  
    16  type Publisher interface {
    17  	// Initialize the internal mechanisms of this publisher.
    18  	Initialize(ctx context.Context, topic string, config PublisherConfig) (*Acknowledge, error)
    19  
    20  	// PublishBatch publishes a batch of messages to the topic.
    21  	PublishBatch(ctx context.Context, topic string, batch *PubSubBatch, opts ...GrainCallOption) (*PublishResponse, error)
    22  
    23  	// Publish publishes a single message to the topic.
    24  	Publish(ctx context.Context, topic string, message proto.Message, opts ...GrainCallOption) (*PublishResponse, error)
    25  
    26  	Logger() *slog.Logger
    27  }
    28  
    29  type defaultPublisher struct {
    30  	cluster *Cluster
    31  }
    32  
    33  func NewPublisher(cluster *Cluster) Publisher {
    34  	return &defaultPublisher{
    35  		cluster: cluster,
    36  	}
    37  }
    38  
    39  func (p *defaultPublisher) Logger() *slog.Logger {
    40  	return p.cluster.Logger()
    41  }
    42  
    43  func (p *defaultPublisher) Initialize(ctx context.Context, topic string, config PublisherConfig) (*Acknowledge, error) {
    44  	select {
    45  	case <-ctx.Done():
    46  		return nil, ctx.Err()
    47  	default:
    48  		res, err := p.cluster.Request(topic, TopicActorKind, &Initialize{
    49  			IdleTimeout: durationpb.New(config.IdleTimeout),
    50  		})
    51  		if err != nil {
    52  			return nil, err
    53  		}
    54  		return res.(*Acknowledge), err
    55  	}
    56  }
    57  
    58  func (p *defaultPublisher) PublishBatch(ctx context.Context, topic string, batch *PubSubBatch, opts ...GrainCallOption) (*PublishResponse, error) {
    59  	select {
    60  	case <-ctx.Done():
    61  		return nil, ctx.Err()
    62  	default:
    63  		res, err := p.cluster.Request(topic, TopicActorKind, batch, opts...)
    64  		if err != nil {
    65  			return nil, err
    66  		}
    67  		return res.(*PublishResponse), err
    68  	}
    69  }
    70  
    71  func (p *defaultPublisher) Publish(ctx context.Context, topic string, message proto.Message, opts ...GrainCallOption) (*PublishResponse, error) {
    72  	return p.PublishBatch(ctx, topic, &PubSubBatch{
    73  		Envelopes: []proto.Message{message},
    74  	}, opts...)
    75  }