Skip to content

Added ApiGateway and Docker to ApiGateway#248

Open
Kindzerskyi wants to merge 1 commit into
devfrom
add/Docker/to/ApiGateway/#214
Open

Added ApiGateway and Docker to ApiGateway#248
Kindzerskyi wants to merge 1 commit into
devfrom
add/Docker/to/ApiGateway/#214

Conversation

@Kindzerskyi
Copy link
Copy Markdown
Contributor

@Kindzerskyi Kindzerskyi commented Oct 3, 2025

dev

JIRA

Code reviewers

Second Level Review

Summary of issue

No ApiGateway and Docker in it

Summary of change

Added ApiGateway and Docker to ApiGateway

CHECK LIST

  • СI passed
  • Сode coverage >=95%
  • PR is reviewed manually again (to make sure you have 100% ready code)
  • All reviewers agreed to merge the PR
  • I've checked new feature as logged in and logged out user if needed
  • PR meets all conventions

Summary by CodeRabbit

  • New Features

    • Introduced an API Gateway to centralize routing to backend services, supporting GET/POST/PUT/DELETE.
    • Added response caching (60s TTL) and resilience policies for more reliable requests.
    • Exposes upstream routes under /streetcode/api/{controller}/{action} on port 5001.
  • Chores

    • Added Dockerfile for containerized deployment.
    • Updated docker-compose with an apigateway service, networking, and port mapping.
    • Added development launch profile with HTTP/HTTPS URLs and environment configuration.

@Kindzerskyi Kindzerskyi self-assigned this Oct 3, 2025
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Oct 3, 2025

Walkthrough

Introduces a new Ocelot-based API Gateway project targeting .NET 8, adds its Dockerfile, gateway configuration (ocelot.json), development launch settings, and integrates the service into docker-compose. The gateway configures caching and Polly support, exposes port 5001 via compose, and routes to the downstream streetcode-back service.

Changes

Cohort / File(s) Summary
ApiGateway project scaffolding
Streetcode/ApiGateway/ApiGateway.csproj, Streetcode/ApiGateway/Program.cs, Streetcode/ApiGateway/Properties/launchSettings.json
Adds a new .NET 8 Web project with Ocelot, Polly, and cache manager packages; minimal Program.cs wiring Ocelot middleware; development launch profile.
Gateway configuration
Streetcode/ApiGateway/ocelot.json
Defines upstream route /streetcode/api/{controller}/{action} to downstream streetcode-back:80, methods GET/POST/PUT/DELETE, response cache TTL 60s, base URL http://localhost:5001.
Containerization & orchestration
Streetcode/ApiGateway/Dockerfile, docker-compose.yml
Multi-stage Dockerfile (build/publish/runtime) exposing 80/5001; compose service apigateway builds from project, maps 5001:80, depends on streetcode-back and redis, sets ASPNETCORE_URLS.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant C as Client
    participant G as ApiGateway (Ocelot)
    participant K as Cache
    participant D as Downstream (streetcode-back)

    Note over G: Base URL: http://localhost:5001
    C->>G: HTTP request /streetcode/api/{controller}/{action}
    G->>K: Check cached response (TTL 60s)
    alt Cache hit
        K-->>G: Cached response
        G-->>C: 200 OK (cached)
    else Cache miss
        rect rgba(230,240,255,0.6)
        Note over G,D: Polly policies applied around downstream call
        G->>D: Forward request to streetcode-back:80
        D-->>G: Downstream response
        end
        G->>K: Store response (TTL 60s)
        G-->>C: 2xx/4xx/5xx
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

I hop between the routes so neat,
A gateway’s path beneath my feet.
With Polly’s poise and caches tight,
I ferry bytes by day and night.
Ports ajar, compose in tow—
Carrots queued, requests now flow! 🥕🧭

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The description includes the JIRA link, reviewers, issue summary, change summary, and check list but omits the required “Testing approach” section specified in the repository template. Please add a “Testing approach” section detailing how to validate the ApiGateway and Docker setup, including specific test steps or commands.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The title directly references adding the ApiGateway service and Docker support, accurately reflecting the main change set, though its phrasing is slightly redundant.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch add/Docker/to/ApiGateway/#214

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@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: 4

🧹 Nitpick comments (6)
docker-compose.yml (1)

18-31: LGTM! Consider adding health checks for improved orchestration.

The apigateway service configuration is correct and properly integrated with the existing services. The dependency on streetcode-back and redis aligns with the Ocelot configuration that routes to streetcode-back and uses caching.

Consider adding health checks to improve container orchestration:

   apigateway:
     build:
       context: ./Streetcode/ApiGateway
       dockerfile: Dockerfile
     ports:
       - "5001:80" 
     depends_on:
       - streetcode-back
       - redis
     networks:
       - streetcodeapp
     environment:
       - ASPNETCORE_URLS=http://+:80
     restart: on-failure
+    healthcheck:
+      test: ["CMD", "curl", "-f", "http://localhost:80/health"]
+      interval: 30s
+      timeout: 10s
+      retries: 3
+      start_period: 40s

Note: This requires adding a health endpoint in your ApiGateway application and ensuring curl is available in the container.

Streetcode/ApiGateway/Dockerfile (2)

3-4: Redundant EXPOSE directive for port 5001.

Line 4 exposes port 5001, but the docker-compose configuration (line 23) maps external port 5001 to internal port 80. The EXPOSE directive is purely documentary and doesn't affect runtime port mapping. Since the container internally runs on port 80 (as configured by ASPNETCORE_URLS in docker-compose line 30), EXPOSE 5001 is unnecessary and may cause confusion.

Apply this diff to remove the redundant EXPOSE:

 FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
 WORKDIR /app
 EXPOSE 80
-EXPOSE 5001

13-16: Consider adding a non-root user for security hardening.

The container runs as root by default, which increases the attack surface if the application is compromised. ASP.NET Core can run as a non-root user.

Apply this diff to run as a non-root user:

 FROM base AS final
 WORKDIR /app
 COPY --from=build /app/publish .
+RUN adduser --disabled-password --gecos '' appuser && chown -R appuser /app
+USER appuser
 ENTRYPOINT ["dotnet", "ApiGateway.dll"]
Streetcode/ApiGateway/Program.cs (2)

13-18: Consider using Redis for distributed caching.

The current configuration uses an in-memory dictionary cache (line 16), which won't scale horizontally across multiple gateway instances. Since docker-compose includes a Redis dependency (line 26 in docker-compose.yml), consider using Redis for distributed caching to support multiple gateway replicas.

Apply this diff to use Redis:

+using Ocelot.Cache;
+using Microsoft.Extensions.Caching.StackExchangeRedis;
+
 var builder = WebApplication.CreateBuilder(args);
 
+builder.Services.AddStackExchangeRedisCache(options =>
+{
+    options.Configuration = "redis:6379";
+    options.InstanceName = "streetcode_";
+});
+
 builder.Configuration
     .SetBasePath(Directory.GetCurrentDirectory())
     .AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);
 
 builder.Services.AddOcelot()
-    .AddCacheManager(settings =>
-    {
-        settings.WithDictionaryHandle();
-    })
     .AddPolly();

Then add the StackExchangeRedis package to ApiGateway.csproj:

<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="8.0.0" />

Note: Remove the Ocelot.Cache.CacheManager package as Ocelot supports IDistributedCache natively for caching when configured.


1-1: MMLib.SwaggerForOcelot package included but not configured.

The ApiGateway.csproj includes MMLib.SwaggerForOcelot (version 9.0.0), but there's no Swagger configuration in Program.cs. This package remains unused, adding unnecessary bloat to the container image.

If Swagger UI for the gateway is desired, add the configuration:

 using MMLib.SwaggerForOcelot.DependencyInjection;
 using Ocelot.Cache.CacheManager;
 using Ocelot.DependencyInjection;
 using Ocelot.Middleware;
 using Ocelot.Provider.Polly;
 
 var builder = WebApplication.CreateBuilder(args);
 
+builder.Services.AddSwaggerForOcelot(builder.Configuration);
+
 builder.Configuration
     .SetBasePath(Directory.GetCurrentDirectory())
     .AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);
 
 builder.Services.AddOcelot()
     .AddCacheManager(settings =>
     {
         settings.WithDictionaryHandle();
     })
     .AddPolly();
 
 var app = builder.Build();
 
+app.UseSwaggerForOcelotUI(opt =>
+{
+    opt.PathToSwaggerGenerator = "/swagger/docs";
+});
+
 await app.UseOcelot();
 
 app.Run();

Otherwise, remove the package reference from ApiGateway.csproj to reduce image size.

Streetcode/ApiGateway/ApiGateway.csproj (1)

10-10: Align package version with target framework
Downgrade Microsoft.Extensions.Configuration.Json from 9.0.5 to the latest 8.x release (8.0.1) for net8.0 compatibility; no known security advisories on this or related packages.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between debe7bf and 64987d8.

📒 Files selected for processing (6)
  • Streetcode/ApiGateway/ApiGateway.csproj (1 hunks)
  • Streetcode/ApiGateway/Dockerfile (1 hunks)
  • Streetcode/ApiGateway/Program.cs (1 hunks)
  • Streetcode/ApiGateway/Properties/launchSettings.json (1 hunks)
  • Streetcode/ApiGateway/ocelot.json (1 hunks)
  • docker-compose.yml (1 hunks)

Comment thread Streetcode/ApiGateway/ocelot.json
Comment thread Streetcode/ApiGateway/ocelot.json
Comment thread Streetcode/ApiGateway/Program.cs
Comment thread Streetcode/ApiGateway/Properties/launchSettings.json
@sonarqubecloud
Copy link
Copy Markdown

sonarqubecloud Bot commented Oct 3, 2025

Quality Gate Failed Quality Gate failed

Failed conditions
2 Security Hotspots

See analysis details on SonarQube Cloud

@Kindzerskyi Kindzerskyi linked an issue Oct 3, 2025 that may be closed by this pull request
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Enhancement] Add Docker to ApiGateway

1 participant