Skip to content

Commit

Permalink
Merge test changes to main - v0.44.0-pre.35d18bc (#270)
Browse files Browse the repository at this point in the history
Automatically created pull-request in order to merge changes that were
recently pushed to the test branch, back to main
  • Loading branch information
hwinther authored Sep 21, 2024
2 parents 80c5074 + 35d18bc commit fe04193
Show file tree
Hide file tree
Showing 39 changed files with 2,204 additions and 1,417 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/terraform-update-documentation.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ jobs:
git config user.email "${{ github.actor }}@users.noreply.github.com"
- name: Generate TF Docs
uses: terraform-docs/gh-actions@v1.2.0
uses: terraform-docs/gh-actions@v1.3.0
with:
find-dir: ${{ env.TERRAFORM_PATH }}
output-file: USAGE.md
Expand Down
8 changes: 4 additions & 4 deletions src/backend/.config/dotnet-tools.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,28 @@
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "8.0.4",
"version": "8.0.7",
"commands": [
"dotnet-ef"
],
"rollForward": false
},
"dotnet-reportgenerator-globaltool": {
"version": "5.3.7",
"version": "5.3.9",
"commands": [
"reportgenerator"
],
"rollForward": false
},
"swashbuckle.aspnetcore.cli": {
"version": "6.6.2",
"version": "6.7.3",
"commands": [
"swagger"
],
"rollForward": false
},
"dotnet-stryker": {
"version": "4.0.6",
"version": "4.2.0",
"commands": [
"dotnet-stryker"
],
Expand Down
13 changes: 13 additions & 0 deletions src/backend/.runsettings
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
<DataCollectionRunSettings>
<DataCollectors>
<DataCollector friendlyName="XPlat code coverage">
<Configuration>
<Format>cobertura</Format>
<ExcludeByFile>"**/*Migrations/*.cs"</ExcludeByFile>
</Configuration>
</DataCollector>
</DataCollectors>
</DataCollectionRunSettings>
</RunSettings>
1 change: 1 addition & 0 deletions src/backend/Backend.sln
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{9EBA80A2-4F3D-4EBC-AC53-3D4DE1719443}"
ProjectSection(SolutionItems) = preProject
..\..\.gitignore = ..\..\.gitignore
.runsettings = .runsettings
..\..\README.md = ..\..\README.md
EndProjectSection
EndProject
Expand Down
2 changes: 2 additions & 0 deletions src/backend/Backend.sln.DotSettings
Original file line number Diff line number Diff line change
Expand Up @@ -2189,6 +2189,7 @@
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpKeepExistingMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpPlaceEmbeddedOnSameLineMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpUseContinuousIndentInsideBracesMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002EMemberReordering_002EMigrations_002ECSharpFileLayoutPatternRemoveIsAttributeUpgrade/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateBlankLinesAroundFieldToBlankLinesAroundProperty/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EPredefinedNamingRulesToUserRulesUpgrade/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/InstalledDictionaries/InstalledDictionaries/=nb_002Edic/@EntryIndexedValue">True</s:Boolean>
Expand Down Expand Up @@ -2240,6 +2241,7 @@
<s:Boolean x:Key="/Default/UserDictionary/Words/=Lanegiver/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Lanesaldo/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Leverandorgjeld/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Loblaw_0027s/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Lonn/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Lonnskostnader/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Lonnstilskudd/@EntryIndexedValue">True</s:Boolean>
Expand Down
4 changes: 2 additions & 2 deletions src/backend/WebApi/Controllers/BloggingController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public async Task<ActionResult<BlogDto>> GetBlog(int id, CancellationToken cance
public async Task<ActionResult<BlogDto>> PostBlog(BlogDto blog, CancellationToken cancellationToken)
{
logger.LogInformation("PostBlog was called");
var blogEntry = await bloggingRepository.AddBlogAsync(blog, cancellationToken);
var blogEntry = await bloggingRepository.AddOrUpdateBlogAsync(blog, cancellationToken);
if (blogEntry == null)
return NotFound();

Expand Down Expand Up @@ -97,7 +97,7 @@ public async Task<ActionResult<PostDto>> GetPost(int id, CancellationToken cance
public async Task<ActionResult<PostDto>> PostPost(PostDto post, CancellationToken cancellationToken)
{
logger.LogInformation("PostPost was called");
var postEntry = await bloggingRepository.AddPostAsync(post, cancellationToken);
var postEntry = await bloggingRepository.AddOrUpdatePostAsync(post, cancellationToken);
if (postEntry == null)
return NotFound();

Expand Down
9 changes: 7 additions & 2 deletions src/backend/WebApi/Controllers/SendMessageController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0

using Microsoft.AspNetCore.Mvc;
using WebApi.Entities;
using WebApi.Messaging;

namespace WebApi.Controllers;
Expand All @@ -15,12 +16,16 @@ namespace WebApi.Controllers;
/// <param name="messageSender">The service used for sending messages.</param>
[ApiController]
[Route("[controller]")]
public class SendMessageController(MessageSender messageSender) : ControllerBase
public class SendMessageController(IMessageSender messageSender) : ControllerBase
{
/// <summary>
/// Sends a message using the MessageSender service.
/// </summary>
/// <returns>A string indicating the result of the message sending operation.</returns>
[HttpGet]
public string Get() => messageSender.SendMessage();
public Task<ActionResult<GenericValue<string>>> Get() =>
Task.FromResult<ActionResult<GenericValue<string>>>(Ok(new GenericValue<string>
{
Value = messageSender.SendMessage()
}));
}
2 changes: 1 addition & 1 deletion src/backend/WebApi/Entities/BlogDto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public IEnumerable<ValidationResult> Validate(ValidationContext validationContex
if (string.IsNullOrEmpty(Title))
yield return new ValidationResult($"{nameof(Title)} must be set");

if (Title.Length > 1000)
if (Title.Length > 500)
yield return new ValidationResult($"{nameof(Title)} is longer than the maximum amount of characters (500)");

if (string.IsNullOrEmpty(Url))
Expand Down
3 changes: 3 additions & 0 deletions src/backend/WebApi/Entities/PostDto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ public IEnumerable<ValidationResult> Validate(ValidationContext validationContex

if (Content.Length > 8000)
yield return new ValidationResult($"{nameof(Content)} is longer than the maximum amount of characters (8000)");

if (BlogId == default)
yield return new ValidationResult($"{nameof(BlogId)} must be set");
}

/// <summary>
Expand Down
3 changes: 2 additions & 1 deletion src/backend/WebApi/Filters/ValidateModelAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
namespace WebApi.Filters;

/// <summary>
/// TODO: document
/// An action filter attribute that validates the model state before the action method is executed.
/// If the model state is invalid, it returns a BadRequestObjectResult with the model state errors.
/// </summary>
public class ValidateModelAttribute : ActionFilterAttribute
{
Expand Down
25 changes: 18 additions & 7 deletions src/backend/WebApi/Messaging/MessageSender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ namespace WebApi.Messaging;
/// context.
/// Implements IDisposable to ensure that resources are released properly when the object is no longer needed.
/// </summary>
public sealed class MessageSender : IDisposable
public sealed class MessageSender : IMessageSender, IDisposable
{
private static readonly ActivitySource ActivitySource = new(nameof(MessageSender));
private static readonly TextMapPropagator Propagator = Propagators.DefaultTextMapPropagator;
Expand Down Expand Up @@ -44,10 +44,8 @@ public void Dispose()
_connection.Dispose();
}

/// <summary>
/// Sends a message to a RabbitMQ queue, including propagating the OpenTelemetry trace context.
/// </summary>
/// <returns>A string representing the message that was sent.</returns>
/// <inheritdoc />
/// <remarks>Including propagating the OpenTelemetry trace context.</remarks>
public string SendMessage()
{
try
Expand Down Expand Up @@ -89,9 +87,9 @@ public string SendMessage()

return body;
}
catch (Exception ex)
catch (Exception exception)
{
_logger.LogError(ex, "Message publishing failed.");
_logger.LogError(exception, "Message publishing failed.");
throw;
}
}
Expand All @@ -116,4 +114,17 @@ private void InjectTraceContextIntoBasicProperties(IBasicProperties props, strin
_logger.LogError(ex, "Failed to inject trace context.");
}
}
}

/// <summary>
/// Defines functionality to send messages to a RabbitMQ queue
/// See also: <seealso cref="MessageSender">MessageSender</seealso>
/// </summary>
public interface IMessageSender
{
/// <summary>
/// Sends a message to a RabbitMQ queue
/// </summary>
/// <returns>A string representing the message that was sent.</returns>
public string SendMessage();
}
2 changes: 1 addition & 1 deletion src/backend/WebApi/Messaging/RabbitMqHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ public static class RabbitMqHelper
private static readonly ConnectionFactory ConnectionFactory = new()
{
HostName = Environment.GetEnvironmentVariable("RABBITMQ_HOSTNAME") ?? "localhost",
Port = int.TryParse(Environment.GetEnvironmentVariable("RABBITMQ_PORT"), out var port) ? port : 5672,
UserName = Environment.GetEnvironmentVariable("RABBITMQ_DEFAULT_USER") ?? "guest",
Password = Environment.GetEnvironmentVariable("RABBITMQ_DEFAULT_PASS") ?? "guest",
Port = 5672,
RequestedConnectionTimeout = TimeSpan.FromMilliseconds(3000)
};

Expand Down
23 changes: 12 additions & 11 deletions src/backend/WebApi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@

const string serviceName = "Test.WebApi";

builder.Services.AddSingleton<MessageSender>();
builder.Services.AddSingleton<IMessageSender, MessageSender>();

builder.Logging.AddOpenTelemetry(static options =>
{
Expand Down Expand Up @@ -104,16 +104,17 @@

var app = builder.Build();

try
{
using var serviceScope = app.Services.CreateScope();
var bloggingContext = serviceScope.ServiceProvider.GetRequiredService<BloggingContext>();
bloggingContext.Database.Migrate();
}
catch (Exception exception)
{
Console.WriteLine($"Migration exception: {exception.Message}");
}
if (!app.Environment.IsEnvironment("Swagger") && !EF.IsDesignTime)
try
{
using var serviceScope = app.Services.CreateScope();
var bloggingContext = serviceScope.ServiceProvider.GetRequiredService<BloggingContext>();
bloggingContext.Database.Migrate();
}
catch (Exception exception)
{
Console.WriteLine($"Migration exception: {exception.Message}");
}

if (app.Environment.IsDevelopment())
{
Expand Down
21 changes: 9 additions & 12 deletions src/backend/WebApi/Repository/BloggingRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public interface IBloggingRepository
/// <param name="blog">The blog to add.</param>
/// <param name="cancellationToken">A token to cancel the asynchronous operation.</param>
/// <returns>A task that represents the asynchronous operation. The task result contains the added <see cref="BlogDto" />.</returns>
Task<BlogDto?> AddBlogAsync(BlogDto blog, CancellationToken cancellationToken);
Task<BlogDto?> AddOrUpdateBlogAsync(BlogDto blog, CancellationToken cancellationToken);

/// <summary>
/// Lists all posts asynchronously.
Expand Down Expand Up @@ -67,7 +67,7 @@ public interface IBloggingRepository
/// <param name="post">The post to add.</param>
/// <param name="cancellationToken">A token to cancel the asynchronous operation.</param>
/// <returns>A task that represents the asynchronous operation. The task result contains the added <see cref="PostDto" />.</returns>
Task<PostDto?> AddPostAsync(PostDto post, CancellationToken cancellationToken);
Task<PostDto?> AddOrUpdatePostAsync(PostDto post, CancellationToken cancellationToken);
}

/// <summary>
Expand All @@ -91,7 +91,7 @@ public class BloggingRepository(BloggingContext bloggingContext) : IBloggingRepo
}

/// <inheritdoc />
public async Task<BlogDto?> AddBlogAsync(BlogDto blog, CancellationToken cancellationToken)
public async Task<BlogDto?> AddOrUpdateBlogAsync(BlogDto blog, CancellationToken cancellationToken)
{
if (blog.BlogId != 0)
{
Expand All @@ -104,6 +104,7 @@ public class BloggingRepository(BloggingContext bloggingContext) : IBloggingRepo
return null;

// Update
blogEntity.Title = blog.Title;
blogEntity.Url = blog.Url;

await bloggingContext.SaveChangesAsync(cancellationToken);
Expand All @@ -122,14 +123,10 @@ public class BloggingRepository(BloggingContext bloggingContext) : IBloggingRepo
}

/// <inheritdoc />
public async Task<IEnumerable<PostDto>> ListPostsAsync(int blogId, CancellationToken cancellationToken)
{
var posts = await bloggingContext.Posts
.Where(p => p.BlogId == blogId)
.ToListAsync(cancellationToken);

return posts.Select(PostDto.FromEntity);
}
public async Task<IEnumerable<PostDto>> ListPostsAsync(int blogId, CancellationToken cancellationToken) =>
PostDto.FromEntity(await bloggingContext.Posts
.Where(p => p.BlogId == blogId)
.ToListAsync(cancellationToken));

/// <inheritdoc />
public async Task<PostDto?> GetPostAsync(int id, CancellationToken cancellationToken)
Expand All @@ -143,7 +140,7 @@ public async Task<IEnumerable<PostDto>> ListPostsAsync(int blogId, CancellationT
}

/// <inheritdoc />
public async Task<PostDto?> AddPostAsync(PostDto post, CancellationToken cancellationToken)
public async Task<PostDto?> AddOrUpdatePostAsync(PostDto post, CancellationToken cancellationToken)
{
if (post.PostId != 0)
{
Expand Down
14 changes: 7 additions & 7 deletions src/backend/WebApi/WebApi.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.6">
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.8" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.8">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.8" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.0" />
<PackageReference Include="OpenTelemetry.Exporter.Console" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.9.0" />
Expand All @@ -29,22 +29,22 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
<PackageReference Include="Swashbuckle.AspNetCore.ReDoc" Version="6.6.2" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.7.3" />
<PackageReference Include="Swashbuckle.AspNetCore.ReDoc" Version="6.7.3" />
</ItemGroup>

<ItemGroup>
<InternalsVisibleTo Include="WebApi.Tests" />
</ItemGroup>

<Target Name="RestoreDotnetTools" BeforeTargets="Restore">
<Target Name="RestoreDotnetTools" BeforeTargets="CollectPackageReferences">
<Message Text="Restoring dotnet tools" Importance="High" />
<Exec Command="dotnet tool restore --tool-manifest $(ProjectDir)/../.config/dotnet-tools.json" />
</Target>

<Target Name="CreateSwaggerJson" AfterTargets="Build" Condition="$(Configuration)=='Debug'">
<Message Text="Updating swagger schema file" Importance="High" />
<Exec Command="dotnet swagger tofile --output swagger.json $(OutputPath)$(AssemblyName).dll v1" WorkingDirectory="$(ProjectDir)" />
<Exec EnvironmentVariables="DOTNET_ENVIRONMENT=Swagger;ASPNETCORE_ENVIRONMENT=Swagger" Command="dotnet swagger tofile --output swagger.json $(OutputPath)$(AssemblyName).dll v1" WorkingDirectory="$(ProjectDir)" />
</Target>

</Project>
Loading

0 comments on commit fe04193

Please sign in to comment.