Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 8 additions & 37 deletions examples/AwsLambda.Host.Example.Events/Program.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
ο»Ώusing System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
using Amazon.Lambda.SQSEvents;
using AwsLambda.Host;
using AwsLambda.Host.Envelopes.ApiGateway;
using AwsLambda.Host.Envelopes.Sqs;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

Expand All @@ -25,43 +24,17 @@

var lambda = builder.Build();

// lambda.MapHandler(
// ([Event] APIGatewayRequestEnvelope<Request> request, ILogger<Program> logger) =>
// {
// logger.LogInformation("In Handler. Payload: {payload}", request.Body);
//
// return new APIGatewayResponseEnvelope<Response>
// {
// BodyContent = new Response($"Hello {request.BodyContent?.Name}!", DateTime.UtcNow),
// StatusCode = 201,
// Headers = new Dictionary<string, string> { ["Content-Type"] = "application/json" },
// };
// }
// );

// this wont compile as we can only have a single handler per lambda function
lambda.MapHandler(
([Event] SqsEnvelope<Request> sqsEnvelope, ILogger<Program> logger) =>
([Event] ApiGatewayRequestEnvelope<Request> request, ILogger<Program> logger) =>
{
var responses = new SQSBatchResponse();
logger.LogInformation("In Handler. Payload: {Payload}", request.Body);

foreach (var record in sqsEnvelope.Records)
return new ApiGatewayResponseEnvelope<Response>
{
// simulate failure if we get bad data
if (record.BodyContent?.Name is null or "john")
{
responses.BatchItemFailures.Add(
new SQSBatchResponse.BatchItemFailure { ItemIdentifier = record.MessageId }
);

continue;
}

// otherwise, log the message
logger.LogInformation("Hello {name}!", record.BodyContent.Name);
}

return responses;
BodyContent = new Response($"Hello {request.BodyContent?.Name}!", DateTime.UtcNow),
StatusCode = 201,
Headers = new Dictionary<string, string> { ["Content-Type"] = "application/json" },
};
}
);

Expand All @@ -75,6 +48,4 @@ internal record Request(string Name);
[JsonSerializable(typeof(ApiGatewayResponseEnvelope<Response>))]
[JsonSerializable(typeof(Request))]
[JsonSerializable(typeof(Response))]
[JsonSerializable(typeof(SqsEnvelope<Request>))]
[JsonSerializable(typeof(SQSBatchResponse))]
internal partial class SerializerContext : JsonSerializerContext;
12 changes: 6 additions & 6 deletions scripts/validate-version.sh
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,23 @@ PACKAGE_ID=$(grep -o '<PackageId>[^<]*</PackageId>' *.csproj | head -1 | sed 's/
# Extract version from Directory.Build.props (BSD grep compatible)
VERSION=$(grep -o '<VersionPrefix>[^<]*</VersionPrefix>' ../../Directory.Build.props | head -1 | sed 's/<VersionPrefix>\(.*\)<\/VersionPrefix>/\1/')

if [ -z "$PACKAGE_ID" ] || [ -z "$VERSION" ]; then
echo "Error: Could not extract PackageId or VersionPrefix"
if [[ -z "$PACKAGE_ID" ]] || [[ -z "$VERSION" ]]; then
echo "Error: Could not extract PackageId or VersionPrefix" >&2
exit 1
fi

echo "Checking if $PACKAGE_ID v$VERSION already exists on NuGet..."
echo "Checking if $PACKAGE_ID v$VERSION already exists on NuGet..."

# Convert package ID to lowercase (compatible with bash 3.2)
PACKAGE_ID_LOWER=$(echo "$PACKAGE_ID" | tr '[:upper:]' '[:lower:]')

# Check if package version exists on NuGet
STATUS_CODE=$(curl -s -o /dev/null -w "%{http_code}" "https://api.nuget.org/v3-flatcontainer/$PACKAGE_ID_LOWER/$VERSION/$PACKAGE_ID_LOWER.$VERSION.nupkg")

if [ "$STATUS_CODE" = "200" ]; then
echo "Error: $PACKAGE_ID v$VERSION already exists on NuGet.org"
if [[ "$STATUS_CODE" = "200" ]]; then
echo "Error: $PACKAGE_ID v$VERSION already exists on NuGet.org" >&2
exit 1
elif [ "$STATUS_CODE" = "404" ]; then
elif [[ "$STATUS_CODE" = "404" ]]; then
echo "βœ“ $PACKAGE_ID v$VERSION is available (not published yet)"
exit 0
else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,15 +156,15 @@ CancellationToken cancellationToken
if (flusherTask.Status != TaskStatus.RanToCompletion)
{
logger.LogWarning(
"OpenTelemetry {providerName} provider force flush failed to complete within allocated time",
"OpenTelemetry {ProviderName} provider force flush failed to complete within allocated time",
providerName
);

return;
}

logger.LogInformation(
"OpenTelemetry {providerName} provider force flush {status}",
"OpenTelemetry {ProviderName} provider force flush {Status}",
providerName,
flusherTask.Result ? "succeeded" : "failed"
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,7 @@ public LambdaCancellationTokenSourceFactory(TimeSpan bufferDuration)
/// </exception>
public CancellationTokenSource NewCancellationTokenSource(ILambdaContext context)
{
if (context is null)
throw new ArgumentNullException(nameof(context));
ArgumentNullException.ThrowIfNull(context);

if (context.RemainingTime <= TimeSpan.Zero)
throw new InvalidOperationException("Lambda context has no remaining time");
Expand Down
15 changes: 4 additions & 11 deletions src/AwsLambda.Host/Runtime/LambdaHostedService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public void Dispose()
return;

if (_executeTask?.IsCompleted == true)
_executeTask?.Dispose();
_executeTask.Dispose();

_stoppingCts?.Dispose();

Expand Down Expand Up @@ -93,15 +93,9 @@ public async Task StopAsync(CancellationToken cancellationToken)
return;

// Signal cancellation to the executing method. If disposed or called, this might throw.
try
{
// ReSharper disable once MethodHasAsyncOverload
_stoppingCts?.Cancel();
}
catch
{
// ignored
}
await (_stoppingCts?.CancelAsync() ?? Task.CompletedTask).ConfigureAwait(
ConfigureAwaitOptions.SuppressThrowing
);

// Wait until the lambda task completes or the stop token triggers
try
Expand Down Expand Up @@ -147,7 +141,6 @@ public async Task StopAsync(CancellationToken cancellationToken)
private async Task ExecuteAsync(CancellationToken stoppingToken)
{
// Create a fully composed handler with middleware and request processing.
// throw new Exception("ExecuteAsync error");
var requestHandler = _handlerFactory.CreateHandler(stoppingToken);

var onInitHandler = _lifecycle.OnInit(stoppingToken);
Expand Down
4 changes: 2 additions & 2 deletions src/AwsLambda.Host/Runtime/LambdaLifecycleOrchestrator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ IOptions<LambdaHostOptions> lambdaHostSettings
/// aggregated, and any false value will result in false being returned to the Lambda runtime. If
/// no initialization handlers are registered, the initializer returns true immediately.
/// </remarks>
public LambdaBootstrapInitializer OnInit(CancellationToken stoppingToken)
public LambdaBootstrapInitializer OnInit(CancellationToken cancellationToken)
{
return Initializer;

Expand All @@ -58,7 +58,7 @@ async Task<bool> Initializer()
if (_delegateHolder.InitHandlers.Count == 0)
return true;

using var cts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken);
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(_settings.InitTimeout);

var tasks = _delegateHolder.InitHandlers.Select(h => RunInitHandler(h, cts.Token));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
<PackageReference Include="NSubstitute" />
<PackageReference Include="AutoFixture" />
<PackageReference Include="AwesomeAssertions" />
<PackageReference Include="coverlet.collector" />
<PackageReference Include="xunit.runner.visualstudio">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,7 @@
<Folder Include="Snapshots\" />
<Folder Include="\Snapshots\" />
</ItemGroup>
<PropertyGroup>
<ExcludeByFile>**/Scriban/**/*.cs</ExcludeByFile>
</PropertyGroup>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="NSubstitute" />
<PackageReference Include="AwesomeAssertions" />
<PackageReference Include="coverlet.collector" />
<PackageReference Include="xunit.runner.visualstudio">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -958,7 +958,7 @@ List<int> executionOrder
) =>
async (_, _) =>
{
await Task.Delay(delayMs);
await Task.Delay(delayMs, CancellationToken.None);
executionOrder.Add(handlerId);
};

Expand All @@ -974,7 +974,7 @@ List<int> executionOrder
) =>
async (_, _) =>
{
await Task.Delay(delayMs);
await Task.Delay(delayMs, CancellationToken.None);
executionOrder.Add(handlerId);
return true;
};
Expand Down
Loading