-
Notifications
You must be signed in to change notification settings - Fork 0
[LFXV2-1084] Add NATS KV Event Processing to Survey Service #4
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
Merged
+2,723
−134
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
ac9fa69
Implement NATS KV bucket event processing for survey service
andrest50 321ec69
Add comprehensive event processing documentation
andrest50 cb92a7e
Add script to delete survey documents from OpenSearch
andrest50 6b74a5c
Fix config validation, graceful shutdown, and script error handling
andrest50 a4461f4
Merge branch 'main' of ssh://github.com/linuxfoundation/lfx-v2-survey…
andrest50 e6569e3
Fix markdown formatting in event processing documentation
andrest50 38ac5b6
Add UnmarshalJSON methods for flexible type conversion in event proce…
andrest50 d33265d
Add retry logic with exponential backoff for survey response parent d…
andrest50 a5f1ed3
Refactor to use standard library functions for better performance
andrest50 c074ea5
Merge branch 'main' of ssh://github.com/linuxfoundation/lfx-v2-survey…
andrest50 3369615
Merge branch 'main' into andrest50/events-processing
andrest50 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,156 @@ | ||
| // Copyright The Linux Foundation and each contributor to LFX. | ||
| // SPDX-License-Identifier: MIT | ||
|
|
||
| package eventing | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "log/slog" | ||
| "time" | ||
|
|
||
| "github.com/linuxfoundation/lfx-v2-survey-service/internal/domain" | ||
| "github.com/linuxfoundation/lfx-v2-survey-service/internal/infrastructure/eventing" | ||
| "github.com/nats-io/nats.go" | ||
| "github.com/nats-io/nats.go/jetstream" | ||
| ) | ||
|
|
||
| const ( | ||
| V1MappingsBucket = "v1-mappings" | ||
| ) | ||
|
|
||
| // EventProcessor handles NATS KV bucket event processing | ||
| type EventProcessor struct { | ||
| natsConn *nats.Conn | ||
| jsInstance jetstream.JetStream | ||
| consumer jetstream.Consumer | ||
| consumeCtx jetstream.ConsumeContext | ||
| publisher domain.EventPublisher | ||
| idMapper domain.IDMapper | ||
| mappingsKV jetstream.KeyValue | ||
| logger *slog.Logger | ||
| config eventing.Config | ||
| } | ||
|
|
||
| // NewEventProcessor creates a new event processor | ||
| func NewEventProcessor( | ||
| cfg eventing.Config, | ||
| idMapper domain.IDMapper, | ||
| logger *slog.Logger, | ||
| ) (*EventProcessor, error) { | ||
| // Connect to NATS | ||
| conn, err := nats.Connect(cfg.NATSURL, | ||
| nats.DrainTimeout(30*time.Second), | ||
| nats.ErrorHandler(func(nc *nats.Conn, sub *nats.Subscription, err error) { | ||
| if sub != nil { | ||
| logger.With("error", err, "subject", sub.Subject).Error("NATS async error encountered") | ||
| } else { | ||
| logger.With("error", err).Error("NATS async error encountered") | ||
| } | ||
| }), | ||
| nats.ClosedHandler(func(nc *nats.Conn) { | ||
| logger.Warn("NATS connection closed") | ||
| }), | ||
| ) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to connect to NATS: %w", err) | ||
| } | ||
|
|
||
| // Create JetStream context | ||
| jsContext, err := jetstream.New(conn) | ||
| if err != nil { | ||
| conn.Close() | ||
| return nil, fmt.Errorf("failed to create JetStream context: %w", err) | ||
| } | ||
|
|
||
| // Initialize publisher | ||
| publisher := eventing.NewNATSPublisher(conn, logger) | ||
|
|
||
| // Access the V1 mappings KV bucket | ||
| mappingsKV, err := jsContext.KeyValue(context.Background(), V1MappingsBucket) | ||
| if err != nil { | ||
| conn.Close() | ||
| return nil, fmt.Errorf("failed to access %s KV bucket: %w", V1MappingsBucket, err) | ||
| } | ||
|
|
||
| return &EventProcessor{ | ||
| natsConn: conn, | ||
| jsInstance: jsContext, | ||
| publisher: publisher, | ||
| idMapper: idMapper, | ||
| mappingsKV: mappingsKV, | ||
| logger: logger, | ||
| config: cfg, | ||
| }, nil | ||
| } | ||
|
|
||
| // Start starts the event processor | ||
| func (ep *EventProcessor) Start(ctx context.Context) error { | ||
| ep.logger.Info("Starting event processor", "consumer_name", ep.config.ConsumerName) | ||
|
|
||
| // Create or update consumer | ||
| consumer, err := ep.jsInstance.CreateOrUpdateConsumer(ctx, ep.config.StreamName, jetstream.ConsumerConfig{ | ||
| Name: ep.config.ConsumerName, | ||
| Durable: ep.config.ConsumerName, | ||
| DeliverPolicy: jetstream.DeliverLastPerSubjectPolicy, | ||
| AckPolicy: jetstream.AckExplicitPolicy, | ||
| FilterSubject: ep.config.FilterSubject, | ||
| MaxDeliver: ep.config.MaxDeliver, | ||
| AckWait: ep.config.AckWait, | ||
| MaxAckPending: ep.config.MaxAckPending, | ||
| Description: "Durable/shared KV bucket watcher for survey service", | ||
| }) | ||
| if err != nil { | ||
| return fmt.Errorf("failed to create or update consumer: %w", err) | ||
| } | ||
| ep.consumer = consumer | ||
|
|
||
| // Start consuming messages | ||
| consumeCtx, err := consumer.Consume(func(msg jetstream.Msg) { | ||
| kvMessageHandler(ctx, msg, ep.publisher, ep.idMapper, ep.mappingsKV, ep.logger) | ||
| }, jetstream.ConsumeErrHandler(func(_ jetstream.ConsumeContext, err error) { | ||
| ep.logger.With("error", err).Error("KV consumer error encountered") | ||
| })) | ||
| if err != nil { | ||
| return fmt.Errorf("failed to start consuming messages: %w", err) | ||
| } | ||
| ep.consumeCtx = consumeCtx | ||
|
|
||
| ep.logger.Info("Event processor started successfully") | ||
|
|
||
| // Block until context is cancelled | ||
| <-ctx.Done() | ||
|
|
||
| ep.logger.Info("Event processor context cancelled") | ||
| return nil | ||
| } | ||
|
|
||
| // Stop stops the event processor gracefully | ||
| func (ep *EventProcessor) Stop() error { | ||
| ep.logger.Info("Stopping event processor...") | ||
|
|
||
| // Stop the consumer | ||
| if ep.consumeCtx != nil { | ||
| ep.consumeCtx.Stop() | ||
| ep.logger.Info("Consumer stopped") | ||
| } | ||
|
|
||
| // Drain and close the NATS connection | ||
| if ep.natsConn != nil { | ||
| if err := ep.natsConn.Drain(); err != nil { | ||
| ep.logger.With("error", err).Error("Error draining NATS connection") | ||
| } | ||
| ep.natsConn.Close() | ||
| ep.logger.Info("NATS connection closed") | ||
| } | ||
|
|
||
| // Close the publisher | ||
| if ep.publisher != nil { | ||
| if err := ep.publisher.Close(); err != nil { | ||
| ep.logger.With("error", err).Error("Error closing publisher") | ||
| } | ||
| } | ||
|
|
||
| ep.logger.Info("Event processor stopped successfully") | ||
| return nil | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.