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

Nats stream output #49

Merged
merged 5 commits into from
Nov 16, 2024
Merged

Nats stream output #49

merged 5 commits into from
Nov 16, 2024

Conversation

urumo
Copy link
Contributor

@urumo urumo commented Nov 16, 2024

Summary by CodeRabbit

  • New Features
    • Updated connection strings for improved service integration, including new entries for NATS and ClickHouse.
  • Bug Fixes
    • Corrected the data type for the SomeInput record, enhancing serialization and deserialization processes.
  • Refactor
    • Restructured the NATS adapter for clearer separation of message handling and queue adapter functionality.
    • Adjusted service lifetimes to ensure persistent availability throughout the application's runtime.
  • Chores
    • Reorganized the solution structure for better clarity and management of project files.

Copy link

coderabbitai bot commented Nov 16, 2024

Walkthrough

The changes in this pull request involve modifications to the Argon.Server.sln solution file, primarily relocating the docker-compose.yaml file to a new path. Additionally, the docker-compose.yaml file has been deleted, removing several services and volumes defined within it. The src/AppHost/Program.cs file has been updated to ensure services have a persistent lifetime. The NatsAdapterFactory class has been restructured into two classes, and various changes have been made to the ITestGrain interface and related grain classes to adjust data types and improve streaming operations.

Changes

File Path Change Summary
Argon.Server.sln Relocated docker-compose.yaml from Solution Items to src\AppHost\aspirate-output\docker-compose.yaml.
docker-compose.yaml Deleted file; removed services: smtpdev, cache, rmq, pg, clickhouse and volumes: apphost-rmq-data, apphost-pg-data, clickhouse-data, logs.
src/AppHost/Program.cs Added WithLifetime(ContainerLifetime.Persistent) to Redis, NATS, PostgreSQL, and Clickhouse service configurations.
src/Argon.Api/Features/OrleansStreamingProviders/NatsAdapterFactory.cs Split NatsAdapterFactory into NatsMsgExtension and NatsAdapterFactory; added new methods and updated internal logic.
src/Argon.Api/Grains.Interfaces/ITestGrain.cs Updated property type a in SomeInput from int to long.
src/Argon.Api/Grains/TestGrain.cs Changed stream types in StreamProducerGrain and StreamConsumerGrain from long to SomeInput.
src/Argon.Api/appsettings.json Updated cache connection string and added new connection strings for nats and clickhouse.

Possibly related PRs

  • Cut client\server\grains\fusion #39: Involves changes to the Argon.Server.sln file, specifically the relocation of the docker-compose.yaml file, similar to the structural changes in this PR.
  • Redis storage provider #32: Introduces new package references related to Redis, relevant to the changes in service integration within the solution.
  • Fixes #16: Focuses on modifications to the MetadataController, which could relate to the overall organization and structure of the API.

Suggested reviewers

  • 0xF6

Poem

🐇 In the meadow, changes bloom,
Files shuffled, making room.
Services now, with lifetimes long,
In the code, we sing our song.
Docker's gone, but fear not,
New paths lead to a brighter spot! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@urumo urumo requested a review from 0xF6 November 16, 2024 06:42
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 7

🧹 Outside diff range and nitpick comments (8)
src/Argon.Api/Grains.Interfaces/ITestGrain.cs (2)

Line range hint 1-35: Consider removing or documenting the DEBUG directive

The entire interface is wrapped in a #if DEBUG directive. This suggests the code might only be available in debug builds, which could cause issues in production environments.

Consider either:

  1. Removing the DEBUG directive if this code should be available in all builds
  2. Adding documentation explaining why this code should only be available in debug builds
  3. Creating separate debug/release implementations if different behavior is needed

Line range hint 3-9: Consider consolidating serialization frameworks

The SomeInput record uses multiple serialization frameworks (DataContract, MemoryPack, MessagePack, Orleans). While this provides flexibility, it increases maintenance overhead and potential for serialization mismatches.

Consider documenting which serialization framework is used in which scenario, or consolidate to fewer frameworks if possible.

src/Argon.Api/Grains/TestGrain.cs (2)

Line range hint 42-42: Add explanation to Obsolete attribute

The Obsolete attribute should include a message explaining why the method is obsolete and what alternatives should be used.

-    [Obsolete("Obsolete")]
+    [Obsolete("This method will be removed in the next major version. Use ProduceAsync instead.")]

Line range hint 80-85: Add error handling and proper cleanup to stream subscription

The stream type change is correct, but the implementation needs improvements:

 public class StreamConsumerGrain(ILogger<StreamConsumerGrain> logger) : Grain, IStreamConsumerGrain
 {
+    private IAsyncStream<SomeInput>? _stream;
+    private StreamSubscriptionHandle<SomeInput>? _subscription;
+
     public async Task Consume()
     {
-        var guid = Guid.Parse("d97e7fb1-e2f6-4803-b66c-965bc5d1d099");
+        var streamId = StreamId.Create(IArgonEvent.Namespace, this.GetPrimaryKey());
         var streamProvider = this.GetStreamProvider(IArgonEvent.ProviderId);
-        var streamId = StreamId.Create(IArgonEvent.Namespace, guid);
-        var stream = streamProvider.GetStream<SomeInput>(streamId);
-        await stream.SubscribeAsync((data, token) =>
+        _stream = streamProvider.GetStream<SomeInput>(streamId);
+        _subscription = await _stream.SubscribeAsync(OnNextAsync);
+    }
+
+    private Task OnNextAsync(SomeInput data, StreamSequenceToken? token)
+    {
+        try
         {
             logger.LogCritical(data.ToString());
             return Task.CompletedTask;
-        });
+        }
+        catch (Exception ex)
+        {
+            logger.LogError(ex, "Error processing stream message: {Data}", data);
+            return Task.CompletedTask;
+        }
     }
+
+    public override async Task OnDeactivateAsync(DeactivationReason reason, CancellationToken token)
+    {
+        if (_subscription is not null)
+        {
+            await _subscription.UnsubscribeAsync();
+        }
+        await base.OnDeactivateAsync(reason, token);
+    }
 }

Improvements:

  1. Use grain's primary key instead of hardcoded GUID
  2. Store stream and subscription references
  3. Add error handling to message processing
  4. Add cleanup in OnDeactivateAsync
  5. Move message handling to a separate method for better organization
src/AppHost/Program.cs (3)

17-17: Consider adding health checks and resource limits for KeyDB

While the persistent lifetime is appropriate for a cache service, consider enhancing the configuration for production readiness:

-var cache = builder.AddRedis("cache", 6379).WithImage("eqalpha/keydb").WithDataVolume().WithLifetime(ContainerLifetime.Persistent);
+var cache = builder.AddRedis("cache", 6379)
+    .WithImage("eqalpha/keydb")
+    .WithDataVolume()
+    .WithLifetime(ContainerLifetime.Persistent)
+    .WithEnvironment("MAXMEMORY", "2gb")
+    .WithEnvironment("MAXMEMORY_POLICY", "allkeys-lru")
+    .WithHealthCheck("/health");

18-18: Enable NATS monitoring and verify JetStream persistence

While the configuration includes JetStream and persistence, consider adding monitoring capabilities:

-var nats = builder.AddNats("nats", 4222).WithDataVolume().WithJetStream().WithLifetime(ContainerLifetime.Persistent);
+var nats = builder.AddNats("nats", 4222)
+    .WithDataVolume()
+    .WithJetStream()
+    .WithLifetime(ContainerLifetime.Persistent)
+    .WithEndpoint(8222, 8222, "monitoring")
+    .WithEnvironment("JS_MAX_MEMORY_STORE", "1GB")
+    .WithEnvironment("JS_MAX_FILE_STORE", "10GB");

22-26: Enhance ClickHouse configuration and improve readability

The configuration should be more readable and include important ClickHouse settings:

-var clickhouse = builder.AddResource(clickhouseResource).WithImage("clickhouse/clickhouse-server")
-   .WithVolume("clickhouse-data", "/var/lib/clickhouse").WithVolume("logs", "/var/log/clickhouse-server")
-   .WithEnvironment("CLICKHOUSE_USER", username).WithEnvironment("CLICKHOUSE_PASSWORD", password).WithEnvironment("CLICKHOUSE_DB", username)
-   .WithEnvironment("CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT", "1").WithHttpEndpoint(8123, 8123)
-   .WithEndpoint(9000, 9000).WithLifetime(ContainerLifetime.Persistent);
+var clickhouse = builder.AddResource(clickhouseResource)
+    .WithImage("clickhouse/clickhouse-server")
+    .WithVolume("clickhouse-data", "/var/lib/clickhouse")
+    .WithVolume("logs", "/var/log/clickhouse-server")
+    .WithEnvironment(new Dictionary<string, string> {
+        ["CLICKHOUSE_USER"] = username,
+        ["CLICKHOUSE_PASSWORD"] = password,
+        ["CLICKHOUSE_DB"] = username,
+        ["CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT"] = "1",
+        ["CLICKHOUSE_MAX_MEMORY_USAGE"] = "10000000000",  // 10GB
+        ["CLICKHOUSE_MAX_SERVER_MEMORY_USAGE"] = "0",
+        ["CLICKHOUSE_MAX_CONCURRENT_QUERIES"] = "100"
+    })
+    .WithHttpEndpoint(8123, 8123)
+    .WithEndpoint(9000, 9000)
+    .WithLifetime(ContainerLifetime.Persistent);
src/Argon.Api/Features/OrleansStreamingProviders/NatsAdapterFactory.cs (1)

145-158: Optimize header construction and ensure safe token usage

The current construction of NatsHeaders can be optimized for clarity and safety, and there is a potential risk if token is null.

Refactor the header initialization for improved readability and safety:

- var headers = new NatsHeaders
- {
-     {
-         "streamId", streamId.ToString()
-     },
-     {
-         "eventInd", token?.EventIndex.ToString() ?? "0"
-     },
-     {
-         "seq", token?.SequenceNumber.ToString() ?? "0"
-     }
- };
+ var headers = new NatsHeaders
+ {
+     ["streamId"] = streamId.ToString(),
+     ["eventInd"] = (token?.EventIndex ?? 0).ToString(),
+     ["seq"] = (token?.SequenceNumber ?? 0).ToString()
+ };

This approach simplifies the initialization and ensures that default values are correctly assigned if token is null.

Additionally, consider verifying that token is not required to be non-null for the subsequent operations, and handle any cases where a non-null token is essential.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 31bf9ca and fb4946c.

📒 Files selected for processing (7)
  • Argon.Server.sln (1 hunks)
  • docker-compose.yaml (0 hunks)
  • src/AppHost/Program.cs (1 hunks)
  • src/Argon.Api/Features/OrleansStreamingProviders/NatsAdapterFactory.cs (2 hunks)
  • src/Argon.Api/Grains.Interfaces/ITestGrain.cs (1 hunks)
  • src/Argon.Api/Grains/TestGrain.cs (3 hunks)
  • src/Argon.Api/appsettings.json (1 hunks)
💤 Files with no reviewable changes (1)
  • docker-compose.yaml
✅ Files skipped from review due to trivial changes (1)
  • Argon.Server.sln
🔇 Additional comments (6)
src/Argon.Api/Grains.Interfaces/ITestGrain.cs (1)

7-7: Verify the impact of changing property type from int to long

The type change from int to long for property a could have several implications:

  1. Existing persisted data may need migration
  2. Consumers of this interface may need updates
  3. Serialized messages in transit might be affected
✅ Verification successful

Type change from int to long appears safe to proceed

The change appears to have minimal impact because:

  1. The code is wrapped in #if DEBUG, indicating it's only used in development
  2. Data is stored in Redis which handles type conversions well
  3. All usages are contained within test/debug code:
    • TestGrain.cs uses it for debug streaming and Redis storage
    • TestController.cs only creates test data with small integer values (1, 12)
  4. No production dependencies were found using this type

The change from int to long is a safe widening conversion and the existing integer values (1, 12) will work perfectly with long.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usages of SomeInput to identify potential impact areas
rg -l "SomeInput" --type cs

# Look for persistence implementations that might need migration
ast-grep --pattern 'class $_ : IGrainStorage {
  $$$
  ReadStateAsync<SomeInput>($$$) {
    $$$
  }
  $$$
}'

Length of output: 262


Script:

#!/bin/bash
# Check the implementation and usage context
rg "SomeInput" -A 5 -B 5 src/Argon.Api/Grains/TestGrain.cs
rg "SomeInput" -A 5 -B 5 src/Argon.Api/Controllers/TestController.cs

# Check if there are any database or storage related configurations
rg "TestGrain" -A 5 -B 5 --type json
rg "TestGrain" -A 5 -B 5 --type xml

# Look for any persistence providers or storage configurations
rg "IGrainStorage|IStorageProvider" --type cs

Length of output: 4738

src/Argon.Api/appsettings.json (1)

4-4: LGTM! Standard Redis port is now used.

The change to port 6379 aligns with Redis default configuration, making it more standardized and easier to maintain.

src/Argon.Api/Grains/TestGrain.cs (2)

5-5: LGTM: Required import for EventSequenceTokenV2


55-55: Verify stream type change impact

The stream type change from long to SomeInput needs verification across the codebase.

Also applies to: 80-80

✅ Verification successful

Stream type changes are consistent across the codebase

The verification shows that all stream usages are type-safe and properly configured:

  • All GetStream<> calls use their respective specific types (SomeInput, IArgonEvent, FusionGrainEventKind, OnChannelUserChangedState)
  • Proper serialization is configured with MemoryPack as the primary serializer
  • The SomeInput type is properly decorated with serialization attributes: [DataContract, MemoryPackable(GenerateType.VersionTolerant), MessagePackObject, Serializable, GenerateSerializer]
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other stream producers/consumers to ensure consistent type usage
rg -l "GetStream<" | xargs rg "GetStream<(?!SomeInput>)"

# Search for serialization configuration that might need updates
rg -l "AddStreaming|ConfigureServices" | xargs rg "serializ|json|protobuf"

Length of output: 373


Script:

#!/bin/bash
# Search for stream producers/consumers with proper regex
rg "GetStream<.*?>" -A 2

# Search for streaming configuration
rg "AddStreaming" -A 5

# Search for serialization settings in startup/configuration files
fd -e cs -e json | xargs rg "(?i)(serializ|json|protobuf)"

Length of output: 20315

src/AppHost/Program.cs (1)

Line range hint 31-41: Overall structure and dependencies look good

The API configuration correctly references all services and includes appropriate wait dependencies. The startup order is well-defined, and environment variables are properly configured.

src/Argon.Api/Features/OrleansStreamingProviders/NatsAdapterFactory.cs (1)

112-126: Ensure proper initialization of services and logging

Review the constructor to confirm that all services are correctly initialized and that the logging configuration aligns with application standards.

Run the following script to check the initialization of services and the creation of loggers:

Ensure that the output confirms the appropriate setup of services and that no misconfigurations exist.

✅ Verification successful

Let me gather more information about the service registration and configuration to ensure everything is properly set up.

This will help us verify:

  1. How HashRingStreamQueueMapperOptions is configured
  2. How NATS is registered in the service collection
  3. The complete interface/implementation of INatsConnection

Let me verify one more aspect regarding the HashRingStreamQueueMapperOptions configuration.

This will help us understand:

  1. How HashRingStreamQueueMapperOptions is used and configured throughout the codebase
  2. If there are any named configurations for NATS services

Based on the gathered information, I can now provide the final response:

Service initialization and logging configuration is properly implemented

The verification shows that:

  • NATS services are correctly registered using AddNatsClient and AddNatsJetStream
  • INatsConnection is properly injected via GetRequiredService
  • Logger factory is correctly used to create typed loggers
  • Queue mapper options are retrieved using the appropriate named configuration pattern
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all required services and loggers are properly configured.

# Check for the existence and registration of INatsConnection
grep -r "INatsConnection" src/

# Check for the usage of ILoggerFactory and the creation of loggers
grep -r "CreateLogger" src/

# Verify that GetOptionsByName is used correctly
grep -r "GetOptionsByName" src/

Length of output: 1072


Script:

#!/bin/bash
# Check service registration and configuration
rg -A 5 "services\.Configure.*HashRingStreamQueueMapperOptions" src/
rg "AddNats" src/
rg -A 3 "INatsConnection" src/ --type cs

Length of output: 2090


Script:

#!/bin/bash
# Check for HashRingStreamQueueMapperOptions configuration
rg -B 3 -A 3 "HashRingStreamQueueMapperOptions" src/
rg -B 2 -A 2 "services\.Configure.*name.*nats" src/

Length of output: 2321

"cache": "localhost:6379",
"rmq": "amqp://svck:Password123@localhost:5672",
"nats": "nats://localhost:4222",
"clickhouse": "http://postgres:postgres@localhost:8123"
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Potential issue

Clickhouse credentials in appsettings.json need to be updated to match container configuration

The verification reveals that the Clickhouse credentials in appsettings.json are incorrectly using PostgreSQL credentials. The manifest.json shows that Clickhouse is properly configured to use parameterized credentials through environment variables:

"clickhouse": {
  "type": "container.v0",
  "connectionString": "http://{username.value}:{password.value}@{clickhouse.bindings.http.host}:{clickhouse.bindings.http.port}",
  "env": {
    "CLICKHOUSE_USER": "{username.value}",
    "CLICKHOUSE_PASSWORD": "{password.value}",
    "CLICKHOUSE_DB": "{username.value}"
  }
}

The connection string in appsettings.json should be updated to use the same parameterized credentials as defined in the container configuration, not the PostgreSQL credentials.

🔗 Analysis chain

Review Clickhouse connection string credentials.

The connection string uses postgres credentials which seems unusual for Clickhouse. This might be:

  1. A copy-paste error from the PostgreSQL connection string
  2. A security concern if these aren't the intended credentials

Please verify if these are the correct credentials for your Clickhouse instance.


Let me check the content of these files to better understand the Clickhouse configuration patterns.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential credential leaks or misconfigurations

# Look for other instances of postgres credentials in config files
echo "Searching for other postgres credential usage..."
rg -l 'postgres.*postgres' --type json

# Look for other Clickhouse connection strings for comparison
echo "Searching for other Clickhouse connection patterns..."
rg -l 'clickhouse|:8123' --type json

Length of output: 423


Script:

#!/bin/bash
# Check the content of the found files focusing on clickhouse configurations
echo "Content of src/Argon.Api/appsettings.json:"
cat src/Argon.Api/appsettings.json

echo -e "\nContent of src/AppHost/manifest.json:"
cat src/AppHost/manifest.json

echo -e "\nContent of src/AppHost/aspirate-state.json:"
cat src/AppHost/aspirate-state.json

Length of output: 13269

@@ -51,12 +52,13 @@ public Task Produce()
var guid = Guid.Parse("d97e7fb1-e2f6-4803-b66c-965bc5d1d099");
var streamProvider = this.GetStreamProvider(IArgonEvent.ProviderId);
var streamId = StreamId.Create(IArgonEvent.Namespace, guid);
var stream = streamProvider.GetStream<long>(streamId);
var stream = streamProvider.GetStream<SomeInput>(streamId);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Stream type change looks good, but consider improving the implementation.

The change from long to SomeInput is implemented correctly, but there are several areas for improvement:

 public class StreamProducerGrain : Grain, IStreamProducerGrain
 {
+    private IDisposable? _timer;
+    
     [Obsolete("Obsolete")]
     public Task Produce()
     {
-        var guid = Guid.Parse("d97e7fb1-e2f6-4803-b66c-965bc5d1d099");
+        var streamId = StreamId.Create(IArgonEvent.Namespace, this.GetPrimaryKey());
         var streamProvider = this.GetStreamProvider(IArgonEvent.ProviderId);
-        var streamId = StreamId.Create(IArgonEvent.Namespace, guid);
         var stream = streamProvider.GetStream<SomeInput>(streamId);

-        RegisterTimer(_ =>
+        _timer = RegisterTimer(_ =>
         {
             var unixEpochNow = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
             var payload = new SomeInput(unixEpochNow, "test");
-            return stream.OnNextAsync(payload, new EventSequenceTokenV2());
+            return stream.OnNextAsync(payload, new EventSequenceTokenV2(unixEpochNow));
         }, null, TimeSpan.FromMilliseconds(1_000), TimeSpan.FromMilliseconds(1_000));

         return Task.CompletedTask;
     }
+
+    public override Task OnDeactivateAsync(DeactivationReason reason, CancellationToken token)
+    {
+        _timer?.Dispose();
+        return base.OnDeactivateAsync(reason, token);
+    }
 }

Improvements:

  1. Use grain's primary key instead of hardcoded GUID
  2. Store timer reference for proper cleanup
  3. Use timestamp as sequence number for better message ordering
  4. Add cleanup in OnDeactivateAsync

Also applies to: 60-61


var cache = builder.AddRedis("cache", 6379).WithImage("eqalpha/keydb").WithDataVolume().WithLifetime(ContainerLifetime.Persistent);
var nats = builder.AddNats("nats", 4222).WithDataVolume().WithJetStream().WithLifetime(ContainerLifetime.Persistent);
var db = builder.AddPostgres("pg", port: 5432, userName: username, password: password).WithDataVolume().WithLifetime(ContainerLifetime.Persistent);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Optimize PostgreSQL configuration for production use

Consider adding important PostgreSQL parameters for better performance and stability:

-var db = builder.AddPostgres("pg", port: 5432, userName: username, password: password).WithDataVolume().WithLifetime(ContainerLifetime.Persistent);
+var db = builder.AddPostgres("pg", port: 5432, userName: username, password: password)
+    .WithDataVolume()
+    .WithLifetime(ContainerLifetime.Persistent)
+    .WithEnvironment("POSTGRES_MAX_CONNECTIONS", "100")
+    .WithEnvironment("POSTGRES_SHARED_BUFFERS", "1GB")
+    .WithEnvironment("POSTGRES_EFFECTIVE_CACHE_SIZE", "3GB")
+    .WithEnvironment("POSTGRES_WORK_MEM", "16MB")
+    .WithEnvironment("POSTGRES_MAINTENANCE_WORK_MEM", "256MB");
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
var db = builder.AddPostgres("pg", port: 5432, userName: username, password: password).WithDataVolume().WithLifetime(ContainerLifetime.Persistent);
var db = builder.AddPostgres("pg", port: 5432, userName: username, password: password)
.WithDataVolume()
.WithLifetime(ContainerLifetime.Persistent)
.WithEnvironment("POSTGRES_MAX_CONNECTIONS", "100")
.WithEnvironment("POSTGRES_SHARED_BUFFERS", "1GB")
.WithEnvironment("POSTGRES_EFFECTIVE_CACHE_SIZE", "3GB")
.WithEnvironment("POSTGRES_WORK_MEM", "16MB")
.WithEnvironment("POSTGRES_MAINTENANCE_WORK_MEM", "256MB");

Comment on lines +36 to +41
Data = [data];
SequenceToken = eventToken;
}

private List<object> Data { get; }
private Type dataType { get; }
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Correct the initialization of the 'Data' property

The assignment Data = [data]; is not valid C# syntax for initializing a List<object> with a single item.

Update the code to properly initialize the list and ensure that the Data property has a corresponding setter or is initialized appropriately:

- Data = [data];
+ Data = new List<object> { data };

Additionally, modify the Data property to allow initialization:

- private List<object> Data { get; }
+ private List<object> Data { get; set; }

Or initialize the property inline if it's read-only:

private List<object> Data { get; } = new List<object>();

Ensure consistency between property definitions and their initialization.

Comment on lines +86 to +87
public async Task<IList<IBatchContainer>> GetQueueMessagesAsync(int maxCount) => await connection.SubscribeAsync<string>(providerName)
.Select(natsMsg => natsMsg.ToBatch(serializationManager)).Select(IBatchContainer (batch) => batch).ToListAsync();
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix incorrect lambda expression syntax in 'GetQueueMessagesAsync'

The lambda expression Select(IBatchContainer (batch) => batch) uses incorrect syntax and will result in a compilation error.

Correct the syntax to properly cast each batch to IBatchContainer:

- .Select(natsMsg => natsMsg.ToBatch(serializationManager)).Select(IBatchContainer (batch) => batch).ToListAsync();
+ .Select(natsMsg => natsMsg.ToBatch(serializationManager))
+ .Select(batch => (IBatchContainer)batch)
+ .ToListAsync();

This ensures that each batch is correctly cast to IBatchContainer and the method compiles successfully.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public async Task<IList<IBatchContainer>> GetQueueMessagesAsync(int maxCount) => await connection.SubscribeAsync<string>(providerName)
.Select(natsMsg => natsMsg.ToBatch(serializationManager)).Select(IBatchContainer (batch) => batch).ToListAsync();
public async Task<IList<IBatchContainer>> GetQueueMessagesAsync(int maxCount) => await connection.SubscribeAsync<string>(providerName)
.Select(natsMsg => natsMsg.ToBatch(serializationManager))
.Select(batch => (IBatchContainer)batch)
.ToListAsync();

Comment on lines +48 to +50
var sequenceToken = (EventSequenceTokenV2)SequenceToken;

return Task.FromResult<object>(true);
return Data.OfType<T>().Select((@event, i) => Tuple.Create<T, StreamSequenceToken?>(@event, sequenceToken.CreateSequenceTokenForEvent(i)));
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add null check for 'SequenceToken' before casting

Casting SequenceToken to EventSequenceTokenV2 without checking for null can result in a NullReferenceException if SequenceToken is null.

Introduce a null check before the casting operation:

- var sequenceToken = (EventSequenceTokenV2)SequenceToken;
+ if (SequenceToken is not EventSequenceTokenV2 sequenceToken)
+ {
+     // Handle the null or unexpected token case appropriately
+     throw new InvalidOperationException("SequenceToken is null or not of type EventSequenceTokenV2.");
+ }

Alternatively, if a null SequenceToken is acceptable, adjust the logic accordingly to handle that scenario without throwing an exception.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
var sequenceToken = (EventSequenceTokenV2)SequenceToken;
return Task.FromResult<object>(true);
return Data.OfType<T>().Select((@event, i) => Tuple.Create<T, StreamSequenceToken?>(@event, sequenceToken.CreateSequenceTokenForEvent(i)));
if (SequenceToken is not EventSequenceTokenV2 sequenceToken)
{
// Handle the null or unexpected token case appropriately
throw new InvalidOperationException("SequenceToken is null or not of type EventSequenceTokenV2.");
}
return Data.OfType<T>().Select((@event, i) => Tuple.Create<T, StreamSequenceToken?>(@event, sequenceToken.CreateSequenceTokenForEvent(i)));

Comment on lines +15 to +22
var data = serializationManager.Deserialize(typeof(object), msg.Data);
var stream = msg.Headers?["streamId"][0];
var streamId = StreamId.Parse(Encoding.UTF8.GetBytes(stream));
var eventIndex = int.TryParse(msg.Headers?["eventInd"][0], out var index);
var seq = int.TryParse(msg.Headers?["seq"][0], out var sequence);
StreamSequenceToken? token = null;
if (eventIndex && seq) token = new EventSequenceTokenV2(index, sequence);
return new ArgonEventBatch(streamId, data, data.GetType(), token);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Prevent NullReferenceExceptions by safely accessing message headers

Accessing msg.Headers?["streamId"][0] and similar expressions without thorough null checks may lead to NullReferenceException if the headers are missing, the keys are absent, or the header arrays are empty.

Modify the code to include comprehensive null checks to ensure safe access:

- var stream = msg.Headers?["streamId"][0];
+ var stream = msg.Headers != null && msg.Headers.TryGetValue("streamId", out var streamValues) && streamValues.Length > 0
+     ? streamValues[0]
+     : default; // Handle the absence of "streamId" as appropriate

- var eventIndex = int.TryParse(msg.Headers?["eventInd"][0], out var index);
+ var eventIndex = msg.Headers != null && msg.Headers.TryGetValue("eventInd", out var eventIndValues) && eventIndValues.Length > 0
+     && int.TryParse(eventIndValues[0], out var index);

- var seq = int.TryParse(msg.Headers?["seq"][0], out var sequence);
+ var seq = msg.Headers != null && msg.Headers.TryGetValue("seq", out var seqValues) && seqValues.Length > 0
+     && int.TryParse(seqValues[0], out var sequence);

Ensure that each header is checked for existence and that the arrays contain at least one element before accessing [0].

Committable suggestion skipped: line range outside the PR's diff.

@0xF6 0xF6 merged commit 8f6f778 into master Nov 16, 2024
2 checks passed
@0xF6 0xF6 deleted the feature/nats-stream-output branch November 16, 2024 07:53
@0xF6 0xF6 restored the feature/nats-stream-output branch November 16, 2024 07:53
@0xF6 0xF6 deleted the feature/nats-stream-output branch November 16, 2024 07:53
@argon-chat argon-chat locked and limited conversation to collaborators Nov 16, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants