Compare commits
8 Commits
main
...
c1e1f74557
| Author | SHA1 | Date | |
|---|---|---|---|
| c1e1f74557 | |||
| b2c349fc8e | |||
| 9adefbb9b2 | |||
| bb485706e3 | |||
| bcdd543916 | |||
| d7ff6f112a | |||
| f0dd1e32a1 | |||
| f2d02a23ec |
@@ -0,0 +1,5 @@
|
|||||||
|
**/obj/
|
||||||
|
**/bin/
|
||||||
|
**/.git/
|
||||||
|
**/.vs/
|
||||||
|
**/node_modules/
|
||||||
+4
-3
@@ -1,4 +1,5 @@
|
|||||||
bin
|
**/bin/
|
||||||
obj
|
**/obj/
|
||||||
node_modules
|
**/node_modules/
|
||||||
.env
|
.env
|
||||||
|
**/Publish/
|
||||||
+30
-58
@@ -1,98 +1,70 @@
|
|||||||
# ─────────────────────────────────────────────────────────────────────────────
|
# ─────────────────────────────────────────────────────────────────────────────
|
||||||
# Stage 1 — npm install (Tailwind CLI)
|
# Stage 1 — npm install (Tailwind CLI)
|
||||||
# The .NET SDK stage needs node_modules present before running dotnet publish
|
# Uses node:24-alpine for a small image. npm ci is used for reproducible,
|
||||||
# because the MSBuild Tailwind target calls `npx @tailwindcss/cli` during build.
|
# fast installs from the lockfile.
|
||||||
#
|
|
||||||
# We use the official node:24-slim image here. This means the npm that ships
|
|
||||||
# with Node 24 (npm 10.x) is used as-is — we deliberately do NOT run
|
|
||||||
# `npm install -g npm@latest` anywhere. Running a global npm self-upgrade
|
|
||||||
# inside a Debian container is a known reliability hazard: npm replaces its
|
|
||||||
# own running binaries mid-flight, which can cause EBUSY / ENOENT failures
|
|
||||||
# that corrupt the install. The bundled npm is current enough.
|
|
||||||
# ─────────────────────────────────────────────────────────────────────────────
|
# ─────────────────────────────────────────────────────────────────────────────
|
||||||
FROM node:24-slim AS npm-install
|
FROM node:24-alpine AS npm-install
|
||||||
|
|
||||||
WORKDIR /npm
|
WORKDIR /npm
|
||||||
COPY Htmx.ApiDemo/package.json .
|
COPY Htmx.ApiDemo/package.json Htmx.ApiDemo/package-lock.json* ./
|
||||||
# npm ci requires package-lock.json; if it doesn't exist yet, run
|
|
||||||
# `npm install` locally first to generate it, then commit it to the repo.
|
|
||||||
COPY Htmx.ApiDemo/package-lock.json* ./
|
|
||||||
# ci is preferred over install in CI/Docker contexts: respects package-lock,
|
|
||||||
# clean installs, and is faster.
|
|
||||||
RUN npm ci
|
RUN npm ci
|
||||||
|
|
||||||
# ─────────────────────────────────────────────────────────────────────────────
|
# ─────────────────────────────────────────────────────────────────────────────
|
||||||
# Stage 2 — AOT publish
|
# Stage 2 — AOT publish
|
||||||
# Uses the full .NET 10 SDK image. Node/npx must also be present here so the
|
# Uses the Alpine SDK image so the binary is linked against musl libc,
|
||||||
# Tailwind MSBuild target can run. We install Node 24 from NodeSource using
|
# making it compatible with the Alpine runtime image in Stage 3.
|
||||||
# the official setup script and then immediately install nodejs via apt — no
|
#
|
||||||
# subsequent `npm install -g npm` step, for the same reason as above.
|
# Alpine packages are cached via BuildKit mount cache — after the first build
|
||||||
|
# `apk add` is near-instant because the package index and downloads are
|
||||||
|
# reused from the local cache rather than re-fetched from the network.
|
||||||
# ─────────────────────────────────────────────────────────────────────────────
|
# ─────────────────────────────────────────────────────────────────────────────
|
||||||
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS publish
|
FROM mcr.microsoft.com/dotnet/sdk:10.0-alpine AS publish
|
||||||
|
|
||||||
# Install Node.js 24 (required by the Tailwind MSBuild target at publish time).
|
# Install AOT linker tools and Node.js (for the Tailwind MSBuild target).
|
||||||
# We download the NodeSource setup script to a file first so we can inspect it
|
# --mount=type=cache keeps the apk package cache between builds on this machine.
|
||||||
# if needed, then run it. Using `| bash -` directly is convenient but hides
|
RUN --mount=type=cache,target=/var/cache/apk \
|
||||||
# the script from audit — the two-step form is safer in CI/CD contexts.
|
apk add --no-cache clang lld musl-dev build-base nodejs npm
|
||||||
RUN apt-get update && \
|
|
||||||
apt-get install -y --no-install-recommends curl ca-certificates && \
|
|
||||||
curl -fsSL https://deb.nodesource.com/setup_24.x -o /tmp/nodesource_setup.sh && \
|
|
||||||
bash /tmp/nodesource_setup.sh && \
|
|
||||||
apt-get install -y --no-install-recommends nodejs && \
|
|
||||||
rm /tmp/nodesource_setup.sh && \
|
|
||||||
rm -rf /var/lib/apt/lists/*
|
|
||||||
# Intentionally no `npm install -g npm` — see Stage 1 note above.
|
|
||||||
|
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
|
|
||||||
# Copy solution and project files first so NuGet restore is cached separately
|
# Copy project files first — NuGet restore layer is cached until these change.
|
||||||
COPY Htmx.slnx .
|
COPY Htmx.slnx .
|
||||||
COPY Htmx.ApiDemo/Htmx.ApiDemo.csproj Htmx.ApiDemo/
|
COPY Htmx.ApiDemo/Htmx.ApiDemo.csproj Htmx.ApiDemo/
|
||||||
COPY Htmx.SourceGenerator/Htmx.SourceGenerator.csproj Htmx.SourceGenerator/
|
COPY Htmx.SourceGenerator/Htmx.SourceGenerator.csproj Htmx.SourceGenerator/
|
||||||
|
|
||||||
RUN dotnet restore Htmx.ApiDemo/Htmx.ApiDemo.csproj
|
RUN dotnet restore Htmx.ApiDemo/Htmx.ApiDemo.csproj -r linux-musl-x64
|
||||||
|
|
||||||
# Bring in the pre-installed node_modules from Stage 1.
|
# Bring in pre-installed node_modules from Stage 1.
|
||||||
# These were installed with `npm ci` on Node 24 — no npm upgrade was performed.
|
|
||||||
COPY --from=npm-install /npm/node_modules Htmx.ApiDemo/node_modules
|
COPY --from=npm-install /npm/node_modules Htmx.ApiDemo/node_modules
|
||||||
|
|
||||||
# Copy the rest of the source
|
# Copy the rest of the source
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
# AOT publish — output goes to /publish
|
# AOT publish targeting musl so the binary runs on Alpine.
|
||||||
RUN dotnet publish Htmx.ApiDemo/Htmx.ApiDemo.csproj \
|
RUN dotnet publish Htmx.ApiDemo/Htmx.ApiDemo.csproj \
|
||||||
-c Release \
|
-c Release \
|
||||||
|
-r linux-musl-x64 \
|
||||||
--no-restore \
|
--no-restore \
|
||||||
|
--self-contained true \
|
||||||
-o /publish
|
-o /publish
|
||||||
|
|
||||||
# ─────────────────────────────────────────────────────────────────────────────
|
# ─────────────────────────────────────────────────────────────────────────────
|
||||||
# Stage 3 — Runtime image
|
# Stage 3 — Runtime image (~12 MB base vs ~100 MB on Debian)
|
||||||
# runtime-deps provides the native library dependencies (libc, libssl, libicu)
|
# runtime-deps:alpine provides only the native libs the AOT binary needs.
|
||||||
# that the AOT binary links against at runtime — no .NET runtime needed.
|
# No .NET runtime is included — the binary is fully self-contained.
|
||||||
# ─────────────────────────────────────────────────────────────────────────────
|
# ─────────────────────────────────────────────────────────────────────────────
|
||||||
FROM mcr.microsoft.com/dotnet/runtime-deps:10.0 AS runtime
|
FROM mcr.microsoft.com/dotnet/runtime-deps:10.0-alpine AS runtime
|
||||||
|
|
||||||
# Run as non-root for security hardening (recommended by Cloud Run docs)
|
|
||||||
RUN addgroup --system appgroup && adduser --system --ingroup appgroup appuser
|
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
COPY --from=publish /publish .
|
COPY --from=publish /publish .
|
||||||
|
|
||||||
# Ensure the binary is executable
|
|
||||||
RUN chmod +x ./Htmx.ApiDemo
|
|
||||||
|
|
||||||
# Cloud Run injects PORT (default 8080).
|
# Cloud Run injects PORT (default 8080).
|
||||||
# ASP.NET Core reads ASPNETCORE_HTTP_PORTS, not PORT directly, so we set it.
|
# ASP.NET Core reads ASPNETCORE_HTTP_PORTS directly — no entrypoint script needed.
|
||||||
# The entrypoint script below maps $PORT → ASPNETCORE_HTTP_PORTS at startup.
|
ENV ASPNETCORE_HTTP_PORTS=8080
|
||||||
COPY GCR/entrypoint.sh /entrypoint.sh
|
|
||||||
RUN chmod +x /entrypoint.sh
|
|
||||||
|
|
||||||
# Transfer ownership so the app can write temp files if needed
|
# Use the built-in non-root user provided by the official .NET Alpine image.
|
||||||
RUN chown -R appuser:appgroup /app
|
USER $APP_UID
|
||||||
|
|
||||||
USER appuser
|
|
||||||
|
|
||||||
EXPOSE 8080
|
EXPOSE 8080
|
||||||
|
|
||||||
ENTRYPOINT ["/entrypoint.sh"]
|
ENTRYPOINT ["./Htmx.ApiDemo"]
|
||||||
|
|||||||
+13
-11
@@ -1,11 +1,12 @@
|
|||||||
#Requires -Version 5.1
|
#Requires -Version 5.1
|
||||||
Set-StrictMode -Version Latest
|
|
||||||
$ErrorActionPreference = 'Stop'
|
|
||||||
|
|
||||||
param(
|
param(
|
||||||
[switch]$Yes
|
[switch]$Yes
|
||||||
)
|
)
|
||||||
|
|
||||||
|
Set-StrictMode -Version Latest
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
|
||||||
$RootDir = Split-Path -Parent $MyInvocation.MyCommand.Path
|
$RootDir = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||||
$EnvFile = Join-Path $RootDir ".env"
|
$EnvFile = Join-Path $RootDir ".env"
|
||||||
|
|
||||||
@@ -63,7 +64,8 @@ function Test-Login {
|
|||||||
$dockerCfg = if ($env:DOCKER_CONFIG) { Join-Path $env:DOCKER_CONFIG "config.json" } else { Join-Path $HOME ".docker\config.json" }
|
$dockerCfg = if ($env:DOCKER_CONFIG) { Join-Path $env:DOCKER_CONFIG "config.json" } else { Join-Path $HOME ".docker\config.json" }
|
||||||
$dockerOk = $false
|
$dockerOk = $false
|
||||||
if (Test-Path $dockerCfg) {
|
if (Test-Path $dockerCfg) {
|
||||||
$dockerOk = (Select-String -Path $dockerCfg -Pattern "\"$($Cfg['GCP_REGION'])-docker.pkg.dev\"" -SimpleMatch -Quiet)
|
$dockerPattern = "`"$($Cfg['GCP_REGION'])-docker.pkg.dev`""
|
||||||
|
$dockerOk = (Select-String -Path $dockerCfg -Pattern $dockerPattern -SimpleMatch -Quiet)
|
||||||
}
|
}
|
||||||
|
|
||||||
return (-not [string]::IsNullOrWhiteSpace($activeAccount)) -and
|
return (-not [string]::IsNullOrWhiteSpace($activeAccount)) -and
|
||||||
@@ -75,7 +77,7 @@ function Test-Login {
|
|||||||
function Test-ProjectSetup {
|
function Test-ProjectSetup {
|
||||||
param([hashtable]$Cfg)
|
param([hashtable]$Cfg)
|
||||||
|
|
||||||
$billingEnabled = (gcloud billing projects describe $Cfg['GCP_PROJECT_ID'] --format="value(billingEnabled)" 2>$null)
|
$billingEnabled = (gcloud billing projects describe $Cfg['GCP_PROJECT_ID'] --format='value(billingEnabled)' 2>$null)
|
||||||
if ($billingEnabled -ne 'True') { return $false }
|
if ($billingEnabled -ne 'True') { return $false }
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -85,7 +87,7 @@ function Test-ProjectSetup {
|
|||||||
}
|
}
|
||||||
|
|
||||||
foreach ($api in @('run.googleapis.com', 'artifactregistry.googleapis.com', 'secretmanager.googleapis.com', 'cloudresourcemanager.googleapis.com')) {
|
foreach ($api in @('run.googleapis.com', 'artifactregistry.googleapis.com', 'secretmanager.googleapis.com', 'cloudresourcemanager.googleapis.com')) {
|
||||||
$enabled = gcloud services list --enabled --project=$Cfg['GCP_PROJECT_ID'] --format="value(config.name)" 2>$null | Select-String -Pattern "^$([regex]::Escape($api))$"
|
$enabled = gcloud services list --enabled --project=$Cfg['GCP_PROJECT_ID'] --format='value(config.name)' 2>$null | Select-String -Pattern "^$([regex]::Escape($api))$"
|
||||||
if (-not $enabled) { return $false }
|
if (-not $enabled) { return $false }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,14 +103,14 @@ function Test-SecretsSetup {
|
|||||||
return $false
|
return $false
|
||||||
}
|
}
|
||||||
|
|
||||||
$serviceAccount = "serviceAccount:$($Cfg['GCP_PROJECT_ID'])@appspot.gserviceaccount.com"
|
# Check if any service account has secretAccessor access (not just @appspot)
|
||||||
$binding = gcloud secrets get-iam-policy mongodb-connection-string `
|
$bindings = gcloud secrets get-iam-policy mongodb-connection-string `
|
||||||
--project=$Cfg['GCP_PROJECT_ID'] `
|
--project=$Cfg['GCP_PROJECT_ID'] `
|
||||||
--flatten="bindings[].members" `
|
--flatten='bindings[].members' `
|
||||||
--filter="bindings.role=roles/secretmanager.secretAccessor AND bindings.members=$serviceAccount" `
|
--filter='bindings.role=roles/secretmanager.secretAccessor' `
|
||||||
--format="value(bindings.members)" 2>$null
|
--format='value(bindings.members)' 2>$null
|
||||||
|
|
||||||
return ($binding -match [regex]::Escape($serviceAccount))
|
return (-not [string]::IsNullOrWhiteSpace($bindings))
|
||||||
}
|
}
|
||||||
|
|
||||||
function Test-DeployDone {
|
function Test-DeployDone {
|
||||||
|
|||||||
@@ -28,8 +28,8 @@ foreach ($line in Get-Content $EnvFile) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$GCP_PROJECT_ID = $config['GCP_PROJECT_ID'] ?? ''
|
$GCP_PROJECT_ID = if ($config['GCP_PROJECT_ID']) { $config['GCP_PROJECT_ID'] } else { '' }
|
||||||
$GCP_REGION = $config['GCP_REGION'] ?? ''
|
$GCP_REGION = if ($config['GCP_REGION']) { $config['GCP_REGION'] } else { '' }
|
||||||
|
|
||||||
if (-not $GCP_PROJECT_ID) { Write-Error "GCP_PROJECT_ID is not set in .env"; exit 1 }
|
if (-not $GCP_PROJECT_ID) { Write-Error "GCP_PROJECT_ID is not set in .env"; exit 1 }
|
||||||
if (-not $GCP_REGION) { Write-Error "GCP_REGION is not set in .env"; exit 1 }
|
if (-not $GCP_REGION) { Write-Error "GCP_REGION is not set in .env"; exit 1 }
|
||||||
@@ -57,6 +57,6 @@ gcloud auth configure-docker "$GCP_REGION-docker.pkg.dev" --quiet
|
|||||||
|
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host ">>> Login complete. You are now authenticated as:"
|
Write-Host ">>> Login complete. You are now authenticated as:"
|
||||||
gcloud auth list --filter=status:ACTIVE --format="value(account)"
|
gcloud auth list --filter=status:ACTIVE --format='value(account)'
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host ">>> Next step: run GCR\scripts\02-setup-project.ps1"
|
Write-Host ">>> Next step: run GCR\scripts\02-setup-project.ps1"
|
||||||
|
|||||||
@@ -1,126 +1,71 @@
|
|||||||
# =============================================================================
|
#Requires -Version 5.1
|
||||||
# 02-setup-project.ps1 (Windows)
|
param()
|
||||||
# One-time GCP project setup:
|
|
||||||
# - Links a billing account to the project
|
|
||||||
# - Enables required APIs (Cloud Run, Artifact Registry, Secret Manager)
|
|
||||||
# - Creates an Artifact Registry Docker repository
|
|
||||||
# - Grants the current user the minimum required IAM roles
|
|
||||||
#
|
|
||||||
# Safe to re-run — most operations are idempotent.
|
|
||||||
# Linux users: run GCR/scripts/02-setup-project.sh instead.
|
|
||||||
# =============================================================================
|
|
||||||
#Requires -Version 5.1
|
|
||||||
Set-StrictMode -Version Latest
|
Set-StrictMode -Version Latest
|
||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Continue'
|
||||||
|
|
||||||
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
|
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||||
$EnvFile = Join-Path $ScriptDir "..\\.env"
|
$EnvFile = Join-Path $ScriptDir "..\\.env"
|
||||||
|
if (-not (Test-Path $EnvFile)) { Write-Error "ERROR: $EnvFile not found."; exit 1 }
|
||||||
# ── Load .env ─────────────────────────────────────────────────────────────────
|
|
||||||
if (-not (Test-Path $EnvFile)) {
|
|
||||||
Write-Error "ERROR: $EnvFile not found.`nCopy GCR\.env.example to GCR\.env and fill in your values first."
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
|
|
||||||
$config = @{}
|
$config = @{}
|
||||||
foreach ($line in Get-Content $EnvFile) {
|
foreach ($line in Get-Content $EnvFile) {
|
||||||
if ($line -match '^\s*$' -or $line -match '^\s*#') { continue }
|
if ($line -match '^\s*$' -or $line -match '^\s*#') { continue }
|
||||||
if ($line -match '^([^=]+)=(.*)$') {
|
if ($line -match '^([^=]+)=(.*)$') { $config[$Matches[1].Trim()] = $Matches[2].Trim() }
|
||||||
$config[$Matches[1].Trim()] = $Matches[2].Trim()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$GCP_PROJECT_ID = $config['GCP_PROJECT_ID'] ?? ''
|
$GCP_PROJECT_ID = if ($config['GCP_PROJECT_ID']) { $config['GCP_PROJECT_ID'] } else { '' }
|
||||||
$GCP_REGION = $config['GCP_REGION'] ?? ''
|
$GCP_REGION = if ($config['GCP_REGION']) { $config['GCP_REGION'] } else { '' }
|
||||||
$GCP_REPOSITORY = $config['GCP_REPOSITORY'] ?? ''
|
$GCP_REPOSITORY = if ($config['GCP_REPOSITORY']) { $config['GCP_REPOSITORY'] } else { '' }
|
||||||
|
if (-not $GCP_PROJECT_ID) { Write-Error "GCP_PROJECT_ID not set"; exit 1 }
|
||||||
if (-not $GCP_PROJECT_ID) { Write-Error "GCP_PROJECT_ID is not set in .env"; exit 1 }
|
if (-not $GCP_REGION) { Write-Error "GCP_REGION not set"; exit 1 }
|
||||||
if (-not $GCP_REGION) { Write-Error "GCP_REGION is not set in .env"; exit 1 }
|
if (-not $GCP_REPOSITORY) { Write-Error "GCP_REPOSITORY not set"; exit 1 }
|
||||||
if (-not $GCP_REPOSITORY) { Write-Error "GCP_REPOSITORY is not set in .env"; exit 1 }
|
|
||||||
|
|
||||||
Write-Host ">>> Active project: $GCP_PROJECT_ID"
|
Write-Host ">>> Active project: $GCP_PROJECT_ID"
|
||||||
Write-Host ">>> Region: $GCP_REGION"
|
Write-Host ">>> Region: $GCP_REGION"
|
||||||
Write-Host ">>> AR repository: $GCP_REPOSITORY"
|
Write-Host ">>> AR repository: $GCP_REPOSITORY"
|
||||||
|
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
|
Write-Host ">>> Checking billing..."
|
||||||
# ── Step 1: Link billing account ──────────────────────────────────────────────
|
$billing = gcloud billing projects describe $GCP_PROJECT_ID --format='value(billingEnabled)' 2>$null
|
||||||
Write-Host ">>> Checking billing status..."
|
if ($billing -eq 'True') {
|
||||||
$billingOutput = gcloud billing projects describe $GCP_PROJECT_ID --format="value(billingEnabled)" 2>$null
|
Write-Host " Billing already enabled."
|
||||||
$billingEnabled = ($billingOutput -eq "True")
|
|
||||||
|
|
||||||
if ($billingEnabled) {
|
|
||||||
Write-Host " Billing is already enabled — skipping."
|
|
||||||
} else {
|
} else {
|
||||||
Write-Host ""
|
Write-Host " Billing NOT enabled. Listing accounts..."
|
||||||
Write-Host " Billing is NOT enabled on this project."
|
gcloud billing accounts list --format='table(name,displayName,open)' 2>$null
|
||||||
Write-Host " Listing available billing accounts..."
|
$BILLING_ACCOUNT_ID = Read-Host " Enter BILLING_ACCOUNT_ID"
|
||||||
Write-Host ""
|
gcloud billing projects link $GCP_PROJECT_ID --billing-account=$BILLING_ACCOUNT_ID 2>$null
|
||||||
gcloud billing accounts list --format="table(name,displayName,open)"
|
if ($LASTEXITCODE -ne 0) { Write-Error "Failed to link billing."; exit 1 }
|
||||||
Write-Host ""
|
|
||||||
$BILLING_ACCOUNT_ID = Read-Host " Enter the BILLING_ACCOUNT_ID from the list above (format: XXXXXX-XXXXXX-XXXXXX)"
|
|
||||||
gcloud billing projects link $GCP_PROJECT_ID --billing-account=$BILLING_ACCOUNT_ID
|
|
||||||
Write-Host " Billing linked."
|
Write-Host " Billing linked."
|
||||||
}
|
}
|
||||||
|
|
||||||
# ── Step 2: Enable required APIs ─────────────────────────────────────────────
|
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host ">>> Enabling required Google Cloud APIs (this may take a minute)..."
|
Write-Host ">>> Enabling required APIs..."
|
||||||
gcloud services enable `
|
gcloud services enable run.googleapis.com artifactregistry.googleapis.com secretmanager.googleapis.com cloudresourcemanager.googleapis.com --project=$GCP_PROJECT_ID 2>$null
|
||||||
run.googleapis.com `
|
if ($LASTEXITCODE -ne 0) { Write-Error "Failed to enable APIs."; exit 1 }
|
||||||
artifactregistry.googleapis.com `
|
|
||||||
secretmanager.googleapis.com `
|
|
||||||
cloudresourcemanager.googleapis.com `
|
|
||||||
--project=$GCP_PROJECT_ID
|
|
||||||
Write-Host " APIs enabled."
|
Write-Host " APIs enabled."
|
||||||
|
|
||||||
# ── Step 3: Create Artifact Registry Docker repository ───────────────────────
|
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host ">>> Creating Artifact Registry repository: $GCP_REPOSITORY ..."
|
Write-Host ">>> Checking Artifact Registry repository: $GCP_REPOSITORY ..."
|
||||||
$repoExists = $false
|
gcloud artifacts repositories describe $GCP_REPOSITORY --location=$GCP_REGION --project=$GCP_PROJECT_ID 2>$null | Out-Null
|
||||||
try {
|
if ($LASTEXITCODE -eq 0) {
|
||||||
gcloud artifacts repositories describe $GCP_REPOSITORY `
|
Write-Host " Repository already exists."
|
||||||
--location=$GCP_REGION `
|
|
||||||
--project=$GCP_PROJECT_ID 2>$null | Out-Null
|
|
||||||
$repoExists = $true
|
|
||||||
} catch { }
|
|
||||||
|
|
||||||
if ($repoExists) {
|
|
||||||
Write-Host " Repository already exists — skipping."
|
|
||||||
} else {
|
} else {
|
||||||
gcloud artifacts repositories create $GCP_REPOSITORY `
|
Write-Host " Creating repository..."
|
||||||
--repository-format=docker `
|
gcloud artifacts repositories create $GCP_REPOSITORY --repository-format=docker --location=$GCP_REGION --description="Container images for Htmx app" --project=$GCP_PROJECT_ID 2>$null
|
||||||
--location=$GCP_REGION `
|
if ($LASTEXITCODE -ne 0) { Write-Error "Failed to create repository."; exit 1 }
|
||||||
--description="Container images for Htmx app" `
|
|
||||||
--project=$GCP_PROJECT_ID
|
|
||||||
Write-Host " Repository created."
|
Write-Host " Repository created."
|
||||||
}
|
}
|
||||||
|
|
||||||
# ── Step 4: Grant current user the minimum required IAM roles ─────────────────
|
$CURRENT_USER = (gcloud config get-value account 2>$null).Trim()
|
||||||
$CURRENT_USER = (gcloud config get-value account).Trim()
|
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host ">>> Granting IAM roles to $CURRENT_USER ..."
|
Write-Host ">>> Granting IAM roles to $CURRENT_USER ..."
|
||||||
|
foreach ($role in @("roles/run.developer","roles/artifactregistry.writer","roles/iam.serviceAccountUser","roles/secretmanager.admin","roles/secretmanager.secretAccessor","roles/secretmanager.secretVersionAdder")) {
|
||||||
foreach ($role in @(
|
Write-Host " $role"
|
||||||
"roles/run.developer",
|
gcloud projects add-iam-policy-binding $GCP_PROJECT_ID --member="user:$CURRENT_USER" --role=$role --quiet 2>$null | Out-Null
|
||||||
"roles/artifactregistry.writer",
|
|
||||||
"roles/iam.serviceAccountUser",
|
|
||||||
"roles/secretmanager.admin",
|
|
||||||
"roles/secretmanager.secretAccessor",
|
|
||||||
"roles/secretmanager.secretVersionAdder"
|
|
||||||
)) {
|
|
||||||
Write-Host " Adding role: $role"
|
|
||||||
gcloud projects add-iam-policy-binding $GCP_PROJECT_ID `
|
|
||||||
--member="user:$CURRENT_USER" `
|
|
||||||
--role=$role `
|
|
||||||
--quiet
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host ">>> Project setup complete."
|
Write-Host ">>> Project setup complete."
|
||||||
Write-Host ""
|
|
||||||
Write-Host ">>> Summary:"
|
|
||||||
Write-Host " Project ID: $GCP_PROJECT_ID"
|
|
||||||
Write-Host " Region: $GCP_REGION"
|
|
||||||
Write-Host " Artifact Registry: $GCP_REGION-docker.pkg.dev/$GCP_PROJECT_ID/$GCP_REPOSITORY"
|
|
||||||
Write-Host ""
|
|
||||||
Write-Host ">>> Next step: run GCR\scripts\03-create-secrets.ps1"
|
Write-Host ">>> Next step: run GCR\scripts\03-create-secrets.ps1"
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,122 +1,57 @@
|
|||||||
# =============================================================================
|
#Requires -Version 5.1
|
||||||
# 03-create-secrets.ps1 (Windows)
|
param()
|
||||||
# Creates and configures secrets in Google Cloud Secret Manager.
|
|
||||||
#
|
|
||||||
# Run this after 02-setup-project.ps1 to set up sensitive configuration
|
|
||||||
# values (e.g., MongoDB connection string).
|
|
||||||
#
|
|
||||||
# Linux users: run GCR/scripts/03-create-secrets.sh instead.
|
|
||||||
# =============================================================================
|
|
||||||
#Requires -Version 5.1
|
|
||||||
Set-StrictMode -Version Latest
|
Set-StrictMode -Version Latest
|
||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Continue'
|
||||||
|
|
||||||
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
|
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||||
$EnvFile = Join-Path $ScriptDir "..\\.env"
|
$EnvFile = Join-Path $ScriptDir "..\\.env"
|
||||||
|
if (-not (Test-Path $EnvFile)) { Write-Error "ERROR: $EnvFile not found."; exit 1 }
|
||||||
# ── Load .env ─────────────────────────────────────────────────────────────────
|
|
||||||
if (-not (Test-Path $EnvFile)) {
|
|
||||||
Write-Error "ERROR: $EnvFile not found.`nCopy GCR\.env.example to GCR\.env and fill in your values first."
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
|
|
||||||
$config = @{}
|
$config = @{}
|
||||||
foreach ($line in Get-Content $EnvFile) {
|
foreach ($line in Get-Content $EnvFile) {
|
||||||
if ($line -match '^\s*$' -or $line -match '^\s*#') { continue }
|
if ($line -match '^\s*$' -or $line -match '^\s*#') { continue }
|
||||||
if ($line -match '^([^=]+)=(.*)$') {
|
if ($line -match '^([^=]+)=(.*)$') { $config[$Matches[1].Trim()] = $Matches[2].Trim() }
|
||||||
$config[$Matches[1].Trim()] = $Matches[2].Trim()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$GCP_PROJECT_ID = $config['GCP_PROJECT_ID'] ?? ''
|
$GCP_PROJECT_ID = if ($config['GCP_PROJECT_ID']) { $config['GCP_PROJECT_ID'] } else { '' }
|
||||||
if (-not $GCP_PROJECT_ID) { Write-Error "GCP_PROJECT_ID is not set in .env"; exit 1 }
|
if (-not $GCP_PROJECT_ID) { Write-Error "GCP_PROJECT_ID not set"; exit 1 }
|
||||||
|
|
||||||
Write-Host "================================================================"
|
Write-Host "================================================================"
|
||||||
Write-Host " Google Cloud Secret Manager setup"
|
Write-Host " Google Cloud Secret Manager setup - Project: $GCP_PROJECT_ID"
|
||||||
Write-Host "================================================================"
|
Write-Host "================================================================"
|
||||||
Write-Host " Project: $GCP_PROJECT_ID"
|
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
|
|
||||||
# ── Helper function to create or update a secret ──────────────────────────────
|
$SecretName = "mongodb-connection-string"
|
||||||
function New-OrUpdateSecret {
|
Write-Host ">>> Secret: $SecretName"
|
||||||
param(
|
Write-Host " MongoDB connection URI (e.g. mongodb+srv://user:pass@cluster.mongodb.net)"
|
||||||
[string]$SecretName,
|
$val = Read-Host " Enter value" -AsSecureString
|
||||||
[string]$SecretPrompt
|
$plain = [System.Net.NetworkCredential]::new("", $val).Password
|
||||||
)
|
$tmp = [System.IO.Path]::GetTempFileName()
|
||||||
|
try {
|
||||||
Write-Host ">>> Setting up secret: $SecretName"
|
[System.IO.File]::WriteAllText($tmp, $plain, [System.Text.Encoding]::UTF8)
|
||||||
Write-Host " $SecretPrompt"
|
|
||||||
|
|
||||||
# Read secret without echo
|
|
||||||
$SecretValue = Read-Host " Enter value (will not be echoed)" -AsSecureString
|
|
||||||
$PlainValue = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto(
|
|
||||||
[System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUni($SecretValue)
|
|
||||||
)
|
|
||||||
|
|
||||||
# Write to temp file without trailing newline to avoid contaminating the secret
|
|
||||||
$TempFile = [System.IO.Path]::GetTempFileName()
|
|
||||||
try {
|
|
||||||
[System.IO.File]::WriteAllText($TempFile, $PlainValue, [System.Text.Encoding]::UTF8)
|
|
||||||
|
|
||||||
$secretExists = $false
|
|
||||||
try {
|
|
||||||
gcloud secrets describe $SecretName --project=$GCP_PROJECT_ID 2>$null | Out-Null
|
gcloud secrets describe $SecretName --project=$GCP_PROJECT_ID 2>$null | Out-Null
|
||||||
$secretExists = $true
|
if ($LASTEXITCODE -eq 0) {
|
||||||
} catch { }
|
gcloud secrets versions add $SecretName --data-file=$tmp --project=$GCP_PROJECT_ID 2>$null | Out-Null
|
||||||
|
|
||||||
if ($secretExists) {
|
|
||||||
Write-Host " Secret already exists — creating new version..."
|
|
||||||
gcloud secrets versions add $SecretName `
|
|
||||||
--data-file=$TempFile `
|
|
||||||
--project=$GCP_PROJECT_ID
|
|
||||||
} else {
|
} else {
|
||||||
Write-Host " Creating new secret..."
|
gcloud secrets create $SecretName --data-file=$tmp --replication-policy=automatic --project=$GCP_PROJECT_ID 2>$null | Out-Null
|
||||||
gcloud secrets create $SecretName `
|
|
||||||
--data-file=$TempFile `
|
|
||||||
--replication-policy="automatic" `
|
|
||||||
--project=$GCP_PROJECT_ID
|
|
||||||
}
|
}
|
||||||
} finally {
|
if ($LASTEXITCODE -ne 0) { Write-Error "Failed to save secret."; exit 1 }
|
||||||
Remove-Item $TempFile -Force -ErrorAction SilentlyContinue
|
} finally {
|
||||||
}
|
Remove-Item $tmp -Force -ErrorAction SilentlyContinue
|
||||||
|
|
||||||
Write-Host " ✓ Secret '$SecretName' ready."
|
|
||||||
Write-Host ""
|
|
||||||
}
|
}
|
||||||
|
Write-Host " Secret saved."
|
||||||
|
Write-Host ""
|
||||||
|
|
||||||
# ── Step 1: Create MongoDB connection string secret ──────────────────────────
|
|
||||||
New-OrUpdateSecret `
|
|
||||||
"mongodb-connection-string" `
|
|
||||||
"MongoDB Atlas or self-hosted connection URI (e.g., mongodb+srv://user:pass@cluster.mongodb.net)"
|
|
||||||
|
|
||||||
# ── Step 2: Grant Cloud Run service account access to secrets ─────────────────
|
|
||||||
Write-Host ">>> Granting Cloud Run service account access to secrets..."
|
Write-Host ">>> Granting Cloud Run service account access to secrets..."
|
||||||
Write-Host ""
|
$PROJECT_NUMBER = (gcloud projects describe $GCP_PROJECT_ID --format='value(projectNumber)' 2>$null).Trim()
|
||||||
|
$APPENGINE_SA = "$GCP_PROJECT_ID@appspot.gserviceaccount.com"
|
||||||
# Get the default Cloud Run service account for this project
|
$COMPUTE_SA = "$PROJECT_NUMBER-compute@developer.gserviceaccount.com"
|
||||||
$SERVICE_ACCOUNT = "$GCP_PROJECT_ID@appspot.gserviceaccount.com"
|
gcloud iam service-accounts describe $APPENGINE_SA --project=$GCP_PROJECT_ID 2>$null | Out-Null
|
||||||
|
$SA = if ($LASTEXITCODE -eq 0) { $APPENGINE_SA } else { $COMPUTE_SA }
|
||||||
foreach ($SECRET_NAME in @("mongodb-connection-string")) {
|
Write-Host " Granting secretAccessor on '$SecretName' to: $SA"
|
||||||
Write-Host " Granting Secret Accessor role for '$SECRET_NAME' to $SERVICE_ACCOUNT"
|
gcloud secrets add-iam-policy-binding $SecretName --member="serviceAccount:$SA" --role=roles/secretmanager.secretAccessor --project=$GCP_PROJECT_ID --quiet 2>$null | Out-Null
|
||||||
gcloud secrets add-iam-policy-binding $SECRET_NAME `
|
if ($LASTEXITCODE -ne 0) { Write-Error "Failed to grant access."; exit 1 }
|
||||||
--member="serviceAccount:$SERVICE_ACCOUNT" `
|
|
||||||
--role="roles/secretmanager.secretAccessor" `
|
|
||||||
--project=$GCP_PROJECT_ID `
|
|
||||||
--quiet
|
|
||||||
}
|
|
||||||
|
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host "================================================================"
|
Write-Host ">>> Secrets setup complete."
|
||||||
Write-Host " Secret Manager setup complete!"
|
|
||||||
Write-Host "================================================================"
|
|
||||||
Write-Host ""
|
|
||||||
Write-Host ">>> Summary:"
|
|
||||||
Write-Host " Secrets created:"
|
|
||||||
Write-Host " • mongodb-connection-string"
|
|
||||||
Write-Host ""
|
|
||||||
Write-Host " Service account granted access:"
|
|
||||||
Write-Host " • $SERVICE_ACCOUNT"
|
|
||||||
Write-Host ""
|
|
||||||
Write-Host ">>> Next step: run GCR\scripts\04-deploy.ps1"
|
Write-Host ">>> Next step: run GCR\scripts\04-deploy.ps1"
|
||||||
Write-Host " (The deploy script will automatically inject secrets into"
|
|
||||||
Write-Host " the running container.)"
|
|
||||||
|
|||||||
+52
-151
@@ -1,112 +1,54 @@
|
|||||||
# =============================================================================
|
#Requires -Version 5.1
|
||||||
# 04-deploy.ps1 (Windows)
|
param([string]$Tag)
|
||||||
# Builds the Docker image, pushes it to Artifact Registry, and deploys it
|
|
||||||
# to Cloud Run — all in one command.
|
|
||||||
#
|
|
||||||
# Usage:
|
|
||||||
# .\GCR\scripts\04-deploy.ps1 # deploy with tag = git short SHA
|
|
||||||
# .\GCR\scripts\04-deploy.ps1 -Tag my-tag # deploy with a custom tag
|
|
||||||
#
|
|
||||||
# Prerequisites:
|
|
||||||
# 1. GCR\.env exists and is filled in (copy from GCR\.env.example)
|
|
||||||
# 2. 01-login.ps1 has been run (gcloud auth + Docker configured)
|
|
||||||
# 3. 02-setup-project.ps1 has been run (APIs enabled, repo created)
|
|
||||||
# 4. 03-create-secrets.ps1 has been run (MongoDB secret created)
|
|
||||||
# 5. Docker Desktop is running
|
|
||||||
#
|
|
||||||
# Linux users: run GCR/scripts/04-deploy.sh instead.
|
|
||||||
# =============================================================================
|
|
||||||
#Requires -Version 5.1
|
|
||||||
[CmdletBinding()]
|
|
||||||
param(
|
|
||||||
[string]$Tag = ""
|
|
||||||
)
|
|
||||||
Set-StrictMode -Version Latest
|
Set-StrictMode -Version Latest
|
||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Continue'
|
||||||
|
|
||||||
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
|
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||||
$RepoRoot = (Resolve-Path (Join-Path $ScriptDir "..\..")).Path
|
|
||||||
$EnvFile = Join-Path $ScriptDir "..\\.env"
|
$EnvFile = Join-Path $ScriptDir "..\\.env"
|
||||||
|
if (-not (Test-Path $EnvFile)) { Write-Error "ERROR: $EnvFile not found."; exit 1 }
|
||||||
# ── Load .env ─────────────────────────────────────────────────────────────────
|
|
||||||
if (-not (Test-Path $EnvFile)) {
|
|
||||||
Write-Error "ERROR: $EnvFile not found.`nCopy GCR\.env.example to GCR\.env and fill in your values first."
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
|
|
||||||
$config = @{}
|
$config = @{}
|
||||||
foreach ($line in Get-Content $EnvFile) {
|
foreach ($line in Get-Content $EnvFile) {
|
||||||
if ($line -match '^\s*$' -or $line -match '^\s*#') { continue }
|
if ($line -match '^\s*$' -or $line -match '^\s*#') { continue }
|
||||||
if ($line -match '^([^=]+)=(.*)$') {
|
if ($line -match '^([^=]+)=(.*)$') { $config[$Matches[1].Trim()] = $Matches[2].Trim() }
|
||||||
$config[$Matches[1].Trim()] = $Matches[2].Trim()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$GCP_PROJECT_ID = $config['GCP_PROJECT_ID'] ?? ''
|
$GCP_PROJECT_ID = if ($config['GCP_PROJECT_ID']) { $config['GCP_PROJECT_ID'] } else { '' }
|
||||||
$GCP_REGION = $config['GCP_REGION'] ?? ''
|
$GCP_REGION = if ($config['GCP_REGION']) { $config['GCP_REGION'] } else { '' }
|
||||||
$GCP_REPOSITORY = $config['GCP_REPOSITORY'] ?? ''
|
$GCP_REPOSITORY = if ($config['GCP_REPOSITORY']) { $config['GCP_REPOSITORY'] } else { '' }
|
||||||
$SERVICE_NAME = $config['SERVICE_NAME'] ?? ''
|
$SERVICE_NAME = if ($config['SERVICE_NAME']) { $config['SERVICE_NAME'] } else { '' }
|
||||||
$MONGODB_DATABASE_NAME = $config['MONGODB_DATABASE_NAME'] ?? 'HtmxAppDb'
|
$MONGODB_DATABASE_NAME = if ($config['MONGODB_DATABASE_NAME']) { $config['MONGODB_DATABASE_NAME'] } else { 'HtmxAppDb' }
|
||||||
|
|
||||||
# Note: MONGODB_CONNECTION_STRING is stored in Secret Manager (mongodb-connection-string)
|
if (-not $GCP_PROJECT_ID) { Write-Error "GCP_PROJECT_ID not set"; exit 1 }
|
||||||
|
if (-not $GCP_REGION) { Write-Error "GCP_REGION not set"; exit 1 }
|
||||||
|
if (-not $GCP_REPOSITORY) { Write-Error "GCP_REPOSITORY not set"; exit 1 }
|
||||||
|
if (-not $SERVICE_NAME) { Write-Error "SERVICE_NAME not set"; exit 1 }
|
||||||
|
|
||||||
if (-not $GCP_PROJECT_ID) { Write-Error "GCP_PROJECT_ID is not set in .env"; exit 1 }
|
gcloud secrets describe mongodb-connection-string --project=$GCP_PROJECT_ID 2>$null | Out-Null
|
||||||
if (-not $GCP_REGION) { Write-Error "GCP_REGION is not set in .env"; exit 1 }
|
if ($LASTEXITCODE -ne 0) {
|
||||||
if (-not $GCP_REPOSITORY) { Write-Error "GCP_REPOSITORY is not set in .env"; exit 1 }
|
Write-Host ">>> Required secrets not configured."
|
||||||
if (-not $SERVICE_NAME) { Write-Error "SERVICE_NAME is not set in .env"; exit 1 }
|
$ans = Read-Host " Run 03-create-secrets.ps1 now? [y/N]"
|
||||||
|
if ($ans -match '^[Yy]$') {
|
||||||
# Note: MONGODB_CONNECTION_STRING is stored in Secret Manager
|
|
||||||
|
|
||||||
function Test-SecretsReady {
|
|
||||||
$serviceAccount = "serviceAccount:$GCP_PROJECT_ID@appspot.gserviceaccount.com"
|
|
||||||
|
|
||||||
try {
|
|
||||||
gcloud secrets describe mongodb-connection-string --project=$GCP_PROJECT_ID 2>$null | Out-Null
|
|
||||||
} catch {
|
|
||||||
return $false
|
|
||||||
}
|
|
||||||
|
|
||||||
$binding = gcloud secrets get-iam-policy mongodb-connection-string `
|
|
||||||
--project=$GCP_PROJECT_ID `
|
|
||||||
--flatten="bindings[].members" `
|
|
||||||
--filter="bindings.role=roles/secretmanager.secretAccessor AND bindings.members=$serviceAccount" `
|
|
||||||
--format="value(bindings.members)" 2>$null
|
|
||||||
|
|
||||||
return ($binding -match [regex]::Escape($serviceAccount))
|
|
||||||
}
|
|
||||||
|
|
||||||
if (-not (Test-SecretsReady)) {
|
|
||||||
Write-Host ""
|
|
||||||
Write-Host ">>> Required secrets are not fully configured yet."
|
|
||||||
$runSecretSetup = Read-Host " Run GCR\scripts\03-create-secrets.ps1 now? [y/N]"
|
|
||||||
if ($runSecretSetup -match '^[Yy]$') {
|
|
||||||
& (Join-Path $ScriptDir "03-create-secrets.ps1")
|
& (Join-Path $ScriptDir "03-create-secrets.ps1")
|
||||||
|
gcloud secrets describe mongodb-connection-string --project=$GCP_PROJECT_ID 2>$null | Out-Null
|
||||||
|
if ($LASTEXITCODE -ne 0) { Write-Error "Secret setup failed."; exit 1 }
|
||||||
} else {
|
} else {
|
||||||
Write-Host ""
|
Write-Error "Run 03-create-secrets.ps1 first."; exit 1
|
||||||
Write-Error "Deployment requires secret setup first. Run: .\GCR\scripts\03-create-secrets.ps1"
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
|
|
||||||
if (-not (Test-SecretsReady)) {
|
|
||||||
Write-Host ""
|
|
||||||
Write-Error "Secret setup check still failing after running 03-create-secrets.ps1."
|
|
||||||
exit 1
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
$bindings = gcloud secrets get-iam-policy mongodb-connection-string --project=$GCP_PROJECT_ID --flatten='bindings[].members' --filter='bindings.role=roles/secretmanager.secretAccessor' --format='value(bindings.members)' 2>$null
|
||||||
|
if ([string]::IsNullOrWhiteSpace($bindings)) {
|
||||||
|
Write-Error "No service account has secretAccessor access. Run 03-create-secrets.ps1 first."
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
# ── Determine image tag ────────────────────────────────────────────────────────
|
|
||||||
if (-not $Tag) {
|
if (-not $Tag) {
|
||||||
# Default to git short SHA if inside a git repo; otherwise use timestamp
|
try { $Tag = (git rev-parse --short HEAD 2>$null).Trim() } catch { }
|
||||||
try {
|
if ([string]::IsNullOrWhiteSpace($Tag)) { $Tag = (Get-Date -Format "yyyyMMdd-HHmmss") }
|
||||||
$Tag = (git -C $RepoRoot rev-parse --short HEAD 2>$null).Trim()
|
|
||||||
} catch { }
|
|
||||||
if (-not $Tag) {
|
|
||||||
$Tag = (Get-Date -Format "yyyyMMddHHmmss")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$REGISTRY = "$GCP_REGION-docker.pkg.dev"
|
$IMAGE = "$GCP_REGION-docker.pkg.dev/$GCP_PROJECT_ID/$GCP_REPOSITORY/htmx-demo-app:$Tag"
|
||||||
$IMAGE_URI = "$REGISTRY/$GCP_PROJECT_ID/$GCP_REPOSITORY/${SERVICE_NAME}:$Tag"
|
$contextDir = Split-Path -Parent (Split-Path -Parent $ScriptDir)
|
||||||
|
|
||||||
Write-Host "================================================================"
|
Write-Host "================================================================"
|
||||||
Write-Host " Htmx -> Cloud Run deployment"
|
Write-Host " Htmx -> Cloud Run deployment"
|
||||||
@@ -114,81 +56,40 @@ Write-Host "================================================================"
|
|||||||
Write-Host " Project: $GCP_PROJECT_ID"
|
Write-Host " Project: $GCP_PROJECT_ID"
|
||||||
Write-Host " Region: $GCP_REGION"
|
Write-Host " Region: $GCP_REGION"
|
||||||
Write-Host " Service: $SERVICE_NAME"
|
Write-Host " Service: $SERVICE_NAME"
|
||||||
Write-Host " Image: $IMAGE_URI"
|
Write-Host " Image: $IMAGE"
|
||||||
Write-Host "================================================================"
|
Write-Host "================================================================"
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
|
|
||||||
# ── Step 1: Ensure package-lock.json exists (required for `npm ci`) ───────────
|
docker info 2>$null | Out-Null
|
||||||
$LockFile = Join-Path $RepoRoot "Htmx.ApiDemo\package-lock.json"
|
if ($LASTEXITCODE -ne 0) {
|
||||||
if (-not (Test-Path $LockFile)) {
|
Write-Error "Docker is not running. Start Docker Desktop first."
|
||||||
Write-Host ">>> package-lock.json not found. Generating it now..."
|
exit 1
|
||||||
Write-Host " (This requires node + npm to be installed locally)"
|
|
||||||
Push-Location (Join-Path $RepoRoot "Htmx.ApiDemo")
|
|
||||||
npm install --package-lock-only
|
|
||||||
Pop-Location
|
|
||||||
Write-Host " package-lock.json generated. Commit it to the repository."
|
|
||||||
Write-Host ""
|
|
||||||
}
|
}
|
||||||
|
|
||||||
# ── Step 2: Build the Docker image ────────────────────────────────────────────
|
|
||||||
Write-Host ">>> Building Docker image..."
|
Write-Host ">>> Building Docker image..."
|
||||||
Write-Host " Context: $RepoRoot"
|
$env:DOCKER_BUILDKIT = "1"
|
||||||
Write-Host " Dockerfile: GCR\Dockerfile"
|
docker build -t $IMAGE -f "$contextDir\GCR\Dockerfile" $contextDir
|
||||||
Write-Host ""
|
if ($LASTEXITCODE -ne 0) { Write-Error "Docker build failed."; exit 1 }
|
||||||
|
Write-Host ">>> Image built: $IMAGE"
|
||||||
# Build from repo root so COPY instructions can reach both project directories.
|
|
||||||
# Docker on Windows accepts forward slashes in --file.
|
|
||||||
$DockerFile = Join-Path $RepoRoot "GCR\Dockerfile"
|
|
||||||
docker build --file $DockerFile --tag $IMAGE_URI $RepoRoot
|
|
||||||
|
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host ">>> Image built: $IMAGE_URI"
|
Write-Host ">>> Pushing to Artifact Registry..."
|
||||||
|
docker push $IMAGE
|
||||||
# ── Step 3: Push image to Artifact Registry ───────────────────────────────────
|
if ($LASTEXITCODE -ne 0) { Write-Error "Docker push failed."; exit 1 }
|
||||||
Write-Host ""
|
|
||||||
Write-Host ">>> Pushing image to Artifact Registry..."
|
|
||||||
docker push $IMAGE_URI
|
|
||||||
Write-Host ">>> Push complete."
|
Write-Host ">>> Push complete."
|
||||||
|
|
||||||
# ── Step 4: Deploy to Cloud Run via docker-compose.yml ───────────────────────
|
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host ">>> Deploying to Cloud Run..."
|
Write-Host ">>> Deploying to Cloud Run..."
|
||||||
|
gcloud run services update $SERVICE_NAME --project=$GCP_PROJECT_ID --region=$GCP_REGION --image=$IMAGE --set-env-vars=MONGODB_DATABASE_NAME=$MONGODB_DATABASE_NAME --set-secrets=ConnectionStrings__DefaultConnection=mongodb-connection-string:latest --allow-unauthenticated 2>$null
|
||||||
|
if ($LASTEXITCODE -ne 0) {
|
||||||
|
Write-Host " Service not found, creating..."
|
||||||
|
gcloud run deploy $SERVICE_NAME --project=$GCP_PROJECT_ID --region=$GCP_REGION --image=$IMAGE --set-env-vars=MONGODB_DATABASE_NAME=$MONGODB_DATABASE_NAME --set-secrets=ConnectionStrings__DefaultConnection=mongodb-connection-string:latest --allow-unauthenticated 2>$null
|
||||||
|
if ($LASTEXITCODE -ne 0) { Write-Error "Deployment failed."; exit 1 }
|
||||||
|
}
|
||||||
|
Write-Host ">>> Deployment complete."
|
||||||
|
|
||||||
# Set env vars consumed by docker-compose.yml variable substitution
|
$SERVICE_URL = (gcloud run services describe $SERVICE_NAME --region=$GCP_REGION --project=$GCP_PROJECT_ID --format='value(status.url)' 2>$null).Trim()
|
||||||
$env:IMAGE_URI = $IMAGE_URI
|
|
||||||
$env:MONGODB_DATABASE_NAME = $MONGODB_DATABASE_NAME
|
|
||||||
|
|
||||||
$ComposeFile = Join-Path $RepoRoot "GCR\docker-compose.yml"
|
|
||||||
gcloud run services replace $ComposeFile `
|
|
||||||
--region=$GCP_REGION `
|
|
||||||
--project=$GCP_PROJECT_ID
|
|
||||||
|
|
||||||
# ── Step 4b: Inject MongoDB connection string from Secret Manager ────────────
|
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host ">>> Injecting MongoDB connection string from Secret Manager..."
|
|
||||||
gcloud run services update $SERVICE_NAME `
|
|
||||||
--region=$GCP_REGION `
|
|
||||||
--project=$GCP_PROJECT_ID `
|
|
||||||
--set-secrets="ConnectionStrings__DefaultConnection=mongodb-connection-string:latest"
|
|
||||||
|
|
||||||
# ── Step 5: Make the service publicly accessible ──────────────────────────────
|
|
||||||
# Remove this block if you want the service to require authentication.
|
|
||||||
Write-Host ""
|
|
||||||
Write-Host ">>> Allowing public (unauthenticated) access to the service..."
|
|
||||||
gcloud run services add-iam-policy-binding $SERVICE_NAME `
|
|
||||||
--region=$GCP_REGION `
|
|
||||||
--project=$GCP_PROJECT_ID `
|
|
||||||
--member="allUsers" `
|
|
||||||
--role="roles/run.invoker"
|
|
||||||
|
|
||||||
# ── Print service URL ─────────────────────────────────────────────────────────
|
|
||||||
Write-Host ""
|
|
||||||
$SERVICE_URL = (gcloud run services describe $SERVICE_NAME `
|
|
||||||
--region=$GCP_REGION `
|
|
||||||
--project=$GCP_PROJECT_ID `
|
|
||||||
--format="value(status.url)").Trim()
|
|
||||||
|
|
||||||
Write-Host "================================================================"
|
Write-Host "================================================================"
|
||||||
Write-Host " Deployment complete!"
|
Write-Host " Done! Service URL: $SERVICE_URL"
|
||||||
Write-Host " Service URL: $SERVICE_URL"
|
|
||||||
Write-Host "================================================================"
|
Write-Host "================================================================"
|
||||||
|
|||||||
@@ -1,13 +1,10 @@
|
|||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
using Htmx.ApiDemo.Templates;
|
using Htmx.ApiDemo.Templates;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
|
||||||
namespace Htmx.ApiDemo;
|
namespace Htmx.ApiDemo;
|
||||||
|
|
||||||
[JsonSerializable(typeof(string))]
|
[JsonSerializable(typeof(string))]
|
||||||
[JsonSerializable(typeof(PostLoginHandler.Command), TypeInfoPropertyName = "LoginCommand")]
|
|
||||||
[JsonSerializable(typeof(PostRegisterHandler.Command), TypeInfoPropertyName = "RegisterCommand")]
|
|
||||||
[JsonSerializable(typeof(PostLogoutHandler.Command), TypeInfoPropertyName = "LogoutCommand")]
|
|
||||||
internal partial class AppJsonSerializerContext : JsonSerializerContext
|
internal partial class AppJsonSerializerContext : JsonSerializerContext
|
||||||
{
|
{
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -10,7 +10,7 @@ namespace Htmx.ApiDemo.Data;
|
|||||||
/// No EF Core, no LINQ-to-SQL, no RelationalModel fully NativeAOT safe.
|
/// No EF Core, no LINQ-to-SQL, no RelationalModel fully NativeAOT safe.
|
||||||
/// IPasswordHasher is pure PBKDF2 crypto with no dynamic IL.
|
/// IPasswordHasher is pure PBKDF2 crypto with no dynamic IL.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class AuthService(
|
public sealed class AppAuthService(
|
||||||
MongoDbService mongo,
|
MongoDbService mongo,
|
||||||
IPasswordHasher<AppUser> passwordHasher,
|
IPasswordHasher<AppUser> passwordHasher,
|
||||||
IHttpContextAccessor httpContextAccessor)
|
IHttpContextAccessor httpContextAccessor)
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
namespace Htmx.ApiDemo;
|
||||||
|
|
||||||
|
public static class HtmxExtensions
|
||||||
|
{
|
||||||
|
public static void HtmxAwareWriteToBody(
|
||||||
|
this IHtmxComponent component, HttpContext context, string title, string appName, string pageTitle)
|
||||||
|
{
|
||||||
|
// If not a HX-Request, render the component inside main layout
|
||||||
|
if (!context.Request.Headers.ContainsKey("HX-Request"))
|
||||||
|
{
|
||||||
|
var layout = new MainLayout(component, title: title, appName: appName, pageTitle: pageTitle,
|
||||||
|
userName: context.User.Identity?.IsAuthenticated == true ? context.User.Identity.Name : null);
|
||||||
|
|
||||||
|
context.Response.ContentType = "text/html; charset=utf-8";
|
||||||
|
var renderContext = new HtmxRenderContext(context.Response.BodyWriter);
|
||||||
|
layout.Render(renderContext);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
//Else only render the component
|
||||||
|
component.WriteToResponseBody(context);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
using Htmx.ApiDemo.Data;
|
||||||
|
|
||||||
|
namespace Htmx.ApiDemo;
|
||||||
|
|
||||||
|
public static partial class RouteMap
|
||||||
|
{
|
||||||
|
public static void MapHtmxRoutes(this WebApplication app)
|
||||||
|
{
|
||||||
|
MapGetIndex(app);
|
||||||
|
MapGetGreet(app);
|
||||||
|
GetRegister(app);
|
||||||
|
PostRegister(app);
|
||||||
|
PostLogout(app);
|
||||||
|
GetLogin(app);
|
||||||
|
PostLogin(app);
|
||||||
|
GetUiDemo(app);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void PostLogout(WebApplication app)
|
||||||
|
=> app.MapPost("/logout", async (HttpContext context, AppAuthService authService) =>
|
||||||
|
{
|
||||||
|
await authService.SignOutAsync();
|
||||||
|
return Results.Redirect("/login");
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -10,11 +10,15 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<EnableRequestDelegateGenerator>true</EnableRequestDelegateGenerator>
|
|
||||||
<PublishAot>true</PublishAot>
|
<PublishAot>true</PublishAot>
|
||||||
<InterceptorsPreviewNamespaces>$(InterceptorsPreviewNamespaces);Immediate.Apis.Generators</InterceptorsPreviewNamespaces>
|
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<TrimmerRootAssembly Include="MongoDB.Bson" />
|
||||||
|
<TrimmerRootAssembly Include="Htmx.ApiDemo" />
|
||||||
|
<TrimmerRootAssembly Include="Microsoft.Extensions.Primitives" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<CompilerVisibleProperty Include="RootNamespace" />
|
<CompilerVisibleProperty Include="RootNamespace" />
|
||||||
<CompilerVisibleProperty Include="MSBuildProjectDirectory" />
|
<CompilerVisibleProperty Include="MSBuildProjectDirectory" />
|
||||||
@@ -22,14 +26,11 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Content Update="wwwroot\**" CopyToPublishDirectory="Always" />
|
<Content Update="wwwroot\**" CopyToPublishDirectory="Always" />
|
||||||
<Content Remove="wwwroot\css\output.css" />
|
|
||||||
<AdditionalFiles Include="**/*.htmx" />
|
<AdditionalFiles Include="**/*.htmx" />
|
||||||
<None Remove="**/*.htmx" />
|
<None Remove="**/*.htmx" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Immediate.Apis" Version="4.2.0" />
|
|
||||||
<PackageReference Include="Immediate.Handlers" Version="3.5.0" />
|
|
||||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.7" />
|
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.7" />
|
||||||
<PackageReference Include="MongoDB.Driver" Version="3.4.0" />
|
<PackageReference Include="MongoDB.Driver" Version="3.4.0" />
|
||||||
<ProjectReference Include="..\Htmx.SourceGenerator\Htmx.SourceGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
|
<ProjectReference Include="..\Htmx.SourceGenerator\Htmx.SourceGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
|
||||||
|
|||||||
@@ -1,11 +0,0 @@
|
|||||||
@Htmx.ApiDemo_HostAddress = http://localhost:5120
|
|
||||||
|
|
||||||
GET {{Htmx.ApiDemo_HostAddress}}/todos/
|
|
||||||
Accept: application/json
|
|
||||||
|
|
||||||
###
|
|
||||||
|
|
||||||
GET {{Htmx.ApiDemo_HostAddress}}/todos/1
|
|
||||||
Accept: application/json
|
|
||||||
|
|
||||||
###
|
|
||||||
@@ -19,6 +19,6 @@ Global
|
|||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||||
SolutionGuid = {B66FEAA2-59A2-4489-9AEB-ED875EEE5D3E}
|
SolutionGuid = {61C4ACCC-FDDE-4F92-B2A9-A5744496122B}
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
EndGlobal
|
EndGlobal
|
||||||
|
|||||||
@@ -1,44 +0,0 @@
|
|||||||
using Microsoft.AspNetCore.Antiforgery;
|
|
||||||
|
|
||||||
namespace Htmx.ApiDemo;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Renders a full page or just the body component depending on whether
|
|
||||||
/// the request was made by HTMX (HX-Request header present).
|
|
||||||
///
|
|
||||||
/// Full request → wraps body in MainLayout (complete HTML page)
|
|
||||||
/// HTMX request → renders body only + sets HX-Title so the browser
|
|
||||||
/// tab title still updates
|
|
||||||
/// </summary>
|
|
||||||
public static class HtmxPageExtensions
|
|
||||||
{
|
|
||||||
public static void WriteHtmxPage(
|
|
||||||
this HttpContext ctx,
|
|
||||||
IHtmxComponent body,
|
|
||||||
string title = "App",
|
|
||||||
string appName = "HtmxApp",
|
|
||||||
string pageTitle = "")
|
|
||||||
{
|
|
||||||
if (ctx.Request.Headers.ContainsKey("HX-Request"))
|
|
||||||
{
|
|
||||||
// Partial swap: tell HTMX to update the browser <title> tag
|
|
||||||
ctx.Response.Headers["HX-Title"] = title;
|
|
||||||
ctx.WriteHtmxBody(body);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
// Resolve display name: prefer DisplayName claim, fall back to email/name
|
|
||||||
string? userName = ctx.User.Identity?.IsAuthenticated == true
|
|
||||||
? (ctx.User.FindFirst("DisplayName")?.Value
|
|
||||||
?? ctx.User.FindFirst(System.Security.Claims.ClaimTypes.Name)?.Value)
|
|
||||||
: null;
|
|
||||||
|
|
||||||
// Resolve antiforgery token for the logout form in the layout
|
|
||||||
var antiforgery = ctx.RequestServices.GetRequiredService<IAntiforgery>();
|
|
||||||
var afTokens = antiforgery.GetAndStoreTokens(ctx);
|
|
||||||
|
|
||||||
// Full page load: wrap in the shell layout
|
|
||||||
ctx.WriteHtmxBody(new Templates.MainLayout(body, title, appName, pageTitle, userName, afTokens.RequestToken));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+13
-26
@@ -1,17 +1,26 @@
|
|||||||
using Htmx.ApiDemo;
|
using Htmx.ApiDemo;
|
||||||
using Htmx.ApiDemo.Data;
|
using Htmx.ApiDemo.Data;
|
||||||
using Immediate.Apis;
|
using Htmx.ApiDemo.Templates;
|
||||||
using Immediate.Apis.Shared;
|
using Microsoft.AspNetCore.Antiforgery;
|
||||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.AspNetCore.Identity;
|
using Microsoft.AspNetCore.Identity;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using MongoDB.Bson;
|
using MongoDB.Bson;
|
||||||
using MongoDB.Bson.Serialization;
|
using MongoDB.Bson.Serialization;
|
||||||
using MongoDB.Bson.Serialization.Serializers;
|
using MongoDB.Bson.Serialization.Serializers;
|
||||||
using MongoDB.Driver;
|
using MongoDB.Driver;
|
||||||
|
|
||||||
|
// ── Explicit serializer registrations — force AOT to preserve constructors ─
|
||||||
|
BsonSerializer.RegisterSerializer(new ObjectIdSerializer());
|
||||||
|
BsonSerializer.RegisterSerializer(new StringSerializer());
|
||||||
|
BsonSerializer.RegisterSerializer(new DateTimeSerializer());
|
||||||
|
BsonSerializer.RegisterSerializer(new BooleanSerializer());
|
||||||
|
BsonSerializer.RegisterSerializer(new NullableSerializer<DateTime>(new DateTimeSerializer()));
|
||||||
// ── Explicit BsonClassMap — no AutoMap() reflection, fully AOT-safe ───────
|
// ── Explicit BsonClassMap — no AutoMap() reflection, fully AOT-safe ───────
|
||||||
BsonClassMap.RegisterClassMap<AppUser>(cm =>
|
BsonClassMap.RegisterClassMap<AppUser>(cm =>
|
||||||
{
|
{
|
||||||
|
cm.AutoMap();
|
||||||
cm.MapIdProperty(u => u.Id).SetSerializer(new ObjectIdSerializer());
|
cm.MapIdProperty(u => u.Id).SetSerializer(new ObjectIdSerializer());
|
||||||
cm.MapProperty(u => u.Email).SetElementName("email");
|
cm.MapProperty(u => u.Email).SetElementName("email");
|
||||||
cm.MapProperty(u => u.NormalizedEmail).SetElementName("normalizedEmail");
|
cm.MapProperty(u => u.NormalizedEmail).SetElementName("normalizedEmail");
|
||||||
@@ -52,13 +61,10 @@ builder.Services
|
|||||||
});
|
});
|
||||||
|
|
||||||
builder.Services.AddScoped<IPasswordHasher<AppUser>, PasswordHasher<AppUser>>();
|
builder.Services.AddScoped<IPasswordHasher<AppUser>, PasswordHasher<AppUser>>();
|
||||||
builder.Services.AddScoped<AuthService>();
|
builder.Services.AddScoped<AppAuthService>();
|
||||||
|
|
||||||
// ── App services ──────────────────────────────────────────────────────────
|
// ── App services ──────────────────────────────────────────────────────────
|
||||||
builder.Services.AddHttpContextAccessor();
|
builder.Services.AddHttpContextAccessor();
|
||||||
builder.Services
|
|
||||||
.AddHtmxApiDemoBehaviors()
|
|
||||||
.AddHtmxApiDemoHandlers();
|
|
||||||
builder.Services.AddOpenApi();
|
builder.Services.AddOpenApi();
|
||||||
builder.Services.AddAuthorization();
|
builder.Services.AddAuthorization();
|
||||||
|
|
||||||
@@ -76,25 +82,6 @@ app.UseAuthentication();
|
|||||||
app.UseAuthorization();
|
app.UseAuthorization();
|
||||||
app.UseAntiforgery();
|
app.UseAntiforgery();
|
||||||
|
|
||||||
// ── Guard: redirect unauthenticated users to /login ───────────────────────
|
app.MapHtmxRoutes();
|
||||||
app.Use(async (context, next) =>
|
|
||||||
{
|
|
||||||
var path = context.Request.Path.Value ?? "";
|
|
||||||
bool isPublic = path.StartsWith("/login", StringComparison.OrdinalIgnoreCase)
|
|
||||||
|| path.StartsWith("/register", StringComparison.OrdinalIgnoreCase)
|
|
||||||
|| path.StartsWith("/logout", StringComparison.OrdinalIgnoreCase)
|
|
||||||
|| path.StartsWith("/css/", StringComparison.OrdinalIgnoreCase)
|
|
||||||
|| path.StartsWith("/js/", StringComparison.OrdinalIgnoreCase);
|
|
||||||
|
|
||||||
if (!isPublic && context.User.Identity?.IsAuthenticated != true)
|
|
||||||
{
|
|
||||||
context.Response.Redirect("/login");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await next();
|
|
||||||
});
|
|
||||||
|
|
||||||
app.MapHtmxApiDemoEndpoints();
|
|
||||||
|
|
||||||
app.Run();
|
app.Run();
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
<div id="Greeting-$$GreetingId$$" class="greeting">
|
<div id="Greeting-$$GreetingId$$" class="greeting">
|
||||||
<h1>Hello, $$User$$!</h1>
|
<h1>Hello, $$User$$!</h1>
|
||||||
<p>Welcome to high-performance htmx rendering.</p>
|
<p class="pb-2">Welcome to high-performance htmx rendering.</p>
|
||||||
|
$$Separator$$
|
||||||
<button hx-get="/greet/$$User$$/$$Count$$/$$GreetingId$$" hx-target="#Greeting-$$GreetingId$$" hx-swap="outerHTML">Click to increase count $$Count$$</button>
|
<div class="m-3">
|
||||||
|
$$CountButton$$
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -1,38 +1,30 @@
|
|||||||
using Immediate.Apis.Shared;
|
using Htmx.ApiDemo.Templates.Components;
|
||||||
using Immediate.Handlers.Shared;
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
namespace Htmx.ApiDemo.Templates;
|
namespace Htmx.ApiDemo.Templates;
|
||||||
|
|
||||||
public sealed class Greeting : GreetingBase
|
public sealed class Greeting : GreetingBase
|
||||||
{
|
{
|
||||||
private byte[] _userData = [];
|
public required int Count { get; init; }
|
||||||
private byte[] _countData = [];
|
public required string Username { get; init; }
|
||||||
private byte[] _greetingIdData = [];
|
public required Guid GreetingId { get; init; }
|
||||||
public required string Username { init => _userData = value.ToUtf8Bytes(); }
|
|
||||||
public required int Count { init => _countData = $"{value}".ToUtf8Bytes(); }
|
|
||||||
public required Guid GreetingId { init => _greetingIdData = $"{value}".ToUtf8Bytes(); }
|
|
||||||
|
|
||||||
protected override void RenderCount(HtmxRenderContext context) => context.Writer.WriteUtf8(_countData);
|
protected override void RenderCountButton(HtmxRenderContext context)
|
||||||
protected override void RenderGreetingId(HtmxRenderContext context) => context.Writer.WriteUtf8(_greetingIdData);
|
|
||||||
protected override void RenderUser(HtmxRenderContext context) => context.Writer.WriteUtf8(_userData);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Handler]
|
|
||||||
[MapGet("/greet/{username}/{count?}/{id?}")]
|
|
||||||
public static partial class GetGreetingHandler
|
|
||||||
{
|
|
||||||
public record Query(string Username, int? Count, Guid? Id);
|
|
||||||
|
|
||||||
private static ValueTask HandleAsync(
|
|
||||||
Query query,
|
|
||||||
IHttpContextAccessor httpContextAccessor,
|
|
||||||
CancellationToken token)
|
|
||||||
{
|
{
|
||||||
var context = httpContextAccessor.HttpContext
|
var button = new Button(
|
||||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
$"Click to increase count {Count}",
|
||||||
|
"outline",
|
||||||
var template = new Greeting { Username = query.Username, Count = query.Count + 1 ?? 0, GreetingId = query.Id ?? Guid.NewGuid() };
|
hxAttrs: $"hx-get=\"/greet/{Username}/{Count}/{GreetingId}\"" +
|
||||||
context.WriteHtmxBody(template);
|
$" hx-target=\"#Greeting-{GreetingId}\" hx-swap=\"outerHTML\""
|
||||||
return ValueTask.CompletedTask;
|
);
|
||||||
|
button.Render(context);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected override void RenderUser(HtmxRenderContext context)
|
||||||
|
=> context.Writer.WriteUtf8(Username.ToUtf8Bytes());
|
||||||
|
protected override void RenderGreetingId(HtmxRenderContext context)
|
||||||
|
=> context.Writer.WriteUtf8(GreetingId.ToString().ToUtf8Bytes());
|
||||||
|
protected override void RenderSeparator(HtmxRenderContext context)
|
||||||
|
=> new Separator().Render(context);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
using Htmx.ApiDemo.Templates;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.Net.Http.Headers;
|
||||||
|
|
||||||
|
namespace Htmx.ApiDemo;
|
||||||
|
|
||||||
|
public static partial class RouteMap
|
||||||
|
{
|
||||||
|
public static void MapGetIndex(WebApplication app)
|
||||||
|
=> app.MapGet("/", (IHttpContextAccessor contextAccessor) =>
|
||||||
|
{
|
||||||
|
var context = contextAccessor.HttpContext
|
||||||
|
?? throw new InvalidOperationException("HttpContext is not available.");
|
||||||
|
|
||||||
|
var isAuthenticate = context.User.Identity?.IsAuthenticated ?? false;
|
||||||
|
var JohnDoe = "John Doe";
|
||||||
|
var claimedName = context.User.Claims.FirstOrDefault(c => c.Type == "DisplayName")?.Value ?? JohnDoe;
|
||||||
|
string name =
|
||||||
|
isAuthenticate && claimedName is not null ? claimedName : JohnDoe;
|
||||||
|
|
||||||
|
var greet = new Greeting { Username = name, Count = 0, GreetingId = Guid.NewGuid() };
|
||||||
|
greet.HtmxAwareWriteToBody(
|
||||||
|
context: context,
|
||||||
|
title: "Home",
|
||||||
|
appName: "HtmxApp",
|
||||||
|
pageTitle: "Home"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
private static void MapGetGreet(WebApplication app)
|
||||||
|
=> app.MapGet("/greet/{name}/{count}/{greetid}",
|
||||||
|
(
|
||||||
|
[FromRoute] string name,
|
||||||
|
[FromRoute] int count,
|
||||||
|
[FromRoute] string greetid,
|
||||||
|
[FromServices] IHttpContextAccessor contextAccessor
|
||||||
|
) =>
|
||||||
|
{
|
||||||
|
var context = contextAccessor.HttpContext
|
||||||
|
?? throw new InvalidOperationException("HttpContext is not available.");
|
||||||
|
|
||||||
|
var id = Guid.TryParse(greetid, out var parsedId) ? parsedId : Guid.NewGuid();
|
||||||
|
var greet = new Greeting { Username = name, Count = ++count, GreetingId = id };
|
||||||
|
greet.HtmxAwareWriteToBody(
|
||||||
|
context: context,
|
||||||
|
title: "Greet",
|
||||||
|
appName: "HtmxApp",
|
||||||
|
pageTitle: "Greet"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
using Htmx.ApiDemo.Data;
|
using Htmx.ApiDemo.Data;
|
||||||
using Immediate.Apis.Shared;
|
|
||||||
using Immediate.Handlers.Shared;
|
|
||||||
using Microsoft.AspNetCore.Antiforgery;
|
using Microsoft.AspNetCore.Antiforgery;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
namespace Htmx.ApiDemo.Templates;
|
namespace Htmx.ApiDemo.Templates;
|
||||||
@@ -25,64 +24,3 @@ public sealed class Login : LoginBase
|
|||||||
protected override void RenderErrorMessage(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_errorData);
|
protected override void RenderErrorMessage(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_errorData);
|
||||||
protected override void RenderAntiforgeryToken(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_afTokenData);
|
protected override void RenderAntiforgeryToken(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_afTokenData);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
[Handler]
|
|
||||||
[MapGet("/login")]
|
|
||||||
public static partial class GetLoginHandler
|
|
||||||
{
|
|
||||||
public record Query;
|
|
||||||
|
|
||||||
private static ValueTask HandleAsync(
|
|
||||||
Query _,
|
|
||||||
IHttpContextAccessor httpContextAccessor,
|
|
||||||
IAntiforgery antiforgery,
|
|
||||||
CancellationToken token)
|
|
||||||
{
|
|
||||||
var ctx = httpContextAccessor.HttpContext
|
|
||||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
|
||||||
|
|
||||||
if (ctx.User.Identity?.IsAuthenticated == true)
|
|
||||||
{
|
|
||||||
ctx.Response.Redirect("/");
|
|
||||||
return ValueTask.CompletedTask;
|
|
||||||
}
|
|
||||||
|
|
||||||
var afTokens = antiforgery.GetAndStoreTokens(ctx);
|
|
||||||
ctx.WriteHtmxPage(new Login(afToken: afTokens.RequestToken), title: "Sign in", appName: "HtmxApp", pageTitle: "Sign in");
|
|
||||||
return ValueTask.CompletedTask;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
[Handler]
|
|
||||||
[MapPost("/login")]
|
|
||||||
public static partial class PostLoginHandler
|
|
||||||
{
|
|
||||||
public record Command(
|
|
||||||
[property: FromForm] string Email,
|
|
||||||
[property: FromForm] string Password
|
|
||||||
);
|
|
||||||
|
|
||||||
private static async ValueTask HandleAsync(
|
|
||||||
[AsParameters] Command command,
|
|
||||||
IHttpContextAccessor httpContextAccessor,
|
|
||||||
IAntiforgery antiforgery,
|
|
||||||
AuthService authService,
|
|
||||||
CancellationToken token)
|
|
||||||
{
|
|
||||||
var ctx = httpContextAccessor.HttpContext
|
|
||||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
|
||||||
|
|
||||||
var (success, error) = await authService.LoginAsync(command.Email, command.Password);
|
|
||||||
|
|
||||||
if (success)
|
|
||||||
{
|
|
||||||
ctx.Response.Redirect("/");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var afTokens = antiforgery.GetAndStoreTokens(ctx);
|
|
||||||
ctx.WriteHtmxPage(new Login(error, afToken: afTokens.RequestToken), title: "Sign in", appName: "HtmxApp", pageTitle: "Sign in");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
using Microsoft.AspNetCore.Antiforgery;
|
||||||
|
using Htmx.ApiDemo.Templates;
|
||||||
|
using Htmx.ApiDemo.Data;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
|
namespace Htmx.ApiDemo;
|
||||||
|
|
||||||
|
public static partial class RouteMap
|
||||||
|
{
|
||||||
|
private static void GetLogin(WebApplication app)
|
||||||
|
=> app.MapGet("/login", (IHttpContextAccessor contextAccessor, IAntiforgery antiforgery) =>
|
||||||
|
{
|
||||||
|
var context = contextAccessor.HttpContext
|
||||||
|
?? throw new InvalidOperationException("HttpContext is not available.");
|
||||||
|
|
||||||
|
if (context.User.Identity?.IsAuthenticated == true)
|
||||||
|
{
|
||||||
|
context.Response.Redirect("/");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var afToken = antiforgery.GetAndStoreTokens(context).RequestToken;
|
||||||
|
var loginComponent = new Login(afToken: afToken);
|
||||||
|
loginComponent.HtmxAwareWriteToBody(
|
||||||
|
context: context,
|
||||||
|
title: "Login",
|
||||||
|
appName: "HtmxApp",
|
||||||
|
pageTitle: "Welcome back"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
private static void PostLogin(WebApplication app)
|
||||||
|
=> app.MapPost("/login", async ValueTask
|
||||||
|
(
|
||||||
|
[FromForm] string email,
|
||||||
|
[FromForm] string password,
|
||||||
|
[FromServices] IHttpContextAccessor httpContextAccessor,
|
||||||
|
[FromServices] IAntiforgery antiforgery,
|
||||||
|
[FromServices] AppAuthService authService
|
||||||
|
) =>
|
||||||
|
{
|
||||||
|
var context = httpContextAccessor.HttpContext
|
||||||
|
?? throw new InvalidOperationException("HttpContext is not available.");
|
||||||
|
|
||||||
|
var afToken = antiforgery.GetAndStoreTokens(context).RequestToken;
|
||||||
|
|
||||||
|
var (success, error) = await authService.LoginAsync(email, password);
|
||||||
|
|
||||||
|
if (success)
|
||||||
|
{
|
||||||
|
context.Response.Redirect("/");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var loginComponent = new Login(error, afToken: afToken);
|
||||||
|
loginComponent.HtmxAwareWriteToBody(
|
||||||
|
context: context,
|
||||||
|
title: "Login",
|
||||||
|
appName: "HtmxApp",
|
||||||
|
pageTitle: "Welcome back"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
using Htmx.ApiDemo.Data;
|
|
||||||
using Immediate.Apis.Shared;
|
|
||||||
using Immediate.Handlers.Shared;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
|
|
||||||
namespace Htmx.ApiDemo.Templates;
|
|
||||||
|
|
||||||
[Handler]
|
|
||||||
[MapPost("/logout")]
|
|
||||||
public static partial class PostLogoutHandler
|
|
||||||
{
|
|
||||||
// Empty command — [AsParameters] ensures form content-type is accepted
|
|
||||||
// and antiforgery token in the form is validated by the middleware.
|
|
||||||
public record Command;
|
|
||||||
|
|
||||||
private static async ValueTask HandleAsync(
|
|
||||||
[AsParameters] Command _,
|
|
||||||
AuthService authService,
|
|
||||||
IHttpContextAccessor httpContextAccessor,
|
|
||||||
CancellationToken token)
|
|
||||||
{
|
|
||||||
await authService.SignOutAsync();
|
|
||||||
|
|
||||||
var ctx = httpContextAccessor.HttpContext
|
|
||||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
|
||||||
ctx.Response.Redirect("/login");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -55,7 +55,7 @@
|
|||||||
|
|
||||||
<!-- Sidebar footer -->
|
<!-- Sidebar footer -->
|
||||||
<div class="border-t border-border px-5 py-3 text-xs text-muted-foreground">
|
<div class="border-t border-border px-5 py-3 text-xs text-muted-foreground">
|
||||||
© 2026 $$AppName$$
|
© 2026 $$AppName$$ - Enciphered
|
||||||
</div>
|
</div>
|
||||||
</aside>
|
</aside>
|
||||||
<!-- ── /Sidebar ── -->
|
<!-- ── /Sidebar ── -->
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
using Htmx.ApiDemo;
|
using Htmx.ApiDemo;
|
||||||
using Htmx.ApiDemo.Templates.Components;
|
using Htmx.ApiDemo.Templates.Components;
|
||||||
using Immediate.Apis.Shared;
|
using Microsoft.AspNetCore.Http;
|
||||||
using Immediate.Handlers.Shared;
|
|
||||||
|
|
||||||
namespace Htmx.ApiDemo.Templates;
|
namespace Htmx.ApiDemo;
|
||||||
|
|
||||||
public sealed class MainLayout : MainLayoutBase
|
public sealed class MainLayout : Templates.MainLayoutBase
|
||||||
{
|
{
|
||||||
private byte[] _titleData = [];
|
private byte[] _titleData = [];
|
||||||
private byte[] _appNameData = [];
|
private byte[] _appNameData = [];
|
||||||
@@ -67,25 +66,3 @@ public sealed class MainLayout : MainLayoutBase
|
|||||||
protected override void RenderPageTitle(HtmxRenderContext context) => context.Writer.WriteUtf8(_pageTitleData);
|
protected override void RenderPageTitle(HtmxRenderContext context) => context.Writer.WriteUtf8(_pageTitleData);
|
||||||
protected override void RenderUserSection(HtmxRenderContext context) => context.Writer.WriteUtf8(_userSectionData);
|
protected override void RenderUserSection(HtmxRenderContext context) => context.Writer.WriteUtf8(_userSectionData);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
[Handler]
|
|
||||||
[MapGet("/")]
|
|
||||||
public static partial class GetIndexHandler
|
|
||||||
{
|
|
||||||
public record Command;
|
|
||||||
|
|
||||||
private static ValueTask HandleAsync(
|
|
||||||
Command command,
|
|
||||||
IHttpContextAccessor httpContextAccessor,
|
|
||||||
CancellationToken token)
|
|
||||||
{
|
|
||||||
var context = httpContextAccessor.HttpContext
|
|
||||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
|
||||||
|
|
||||||
var greet = new Greeting { Username = "Enciphered", Count = 0, GreetingId = Guid.NewGuid() };
|
|
||||||
context.WriteHtmxPage(greet, title: "Home", appName: "HtmxApp", pageTitle: "Home");
|
|
||||||
|
|
||||||
return ValueTask.CompletedTask;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
using Htmx.ApiDemo.Data;
|
using Htmx.ApiDemo.Data;
|
||||||
using Immediate.Apis.Shared;
|
|
||||||
using Immediate.Handlers.Shared;
|
|
||||||
using Microsoft.AspNetCore.Antiforgery;
|
using Microsoft.AspNetCore.Antiforgery;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
namespace Htmx.ApiDemo.Templates;
|
namespace Htmx.ApiDemo.Templates;
|
||||||
@@ -25,75 +24,3 @@ public sealed class Register : RegisterBase
|
|||||||
protected override void RenderErrorMessage(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_errorData);
|
protected override void RenderErrorMessage(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_errorData);
|
||||||
protected override void RenderAntiforgeryToken(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_afTokenData);
|
protected override void RenderAntiforgeryToken(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_afTokenData);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
[Handler]
|
|
||||||
[MapGet("/register")]
|
|
||||||
public static partial class GetRegisterHandler
|
|
||||||
{
|
|
||||||
public record Query;
|
|
||||||
|
|
||||||
private static ValueTask HandleAsync(
|
|
||||||
Query _,
|
|
||||||
IHttpContextAccessor httpContextAccessor,
|
|
||||||
IAntiforgery antiforgery,
|
|
||||||
CancellationToken token)
|
|
||||||
{
|
|
||||||
var ctx = httpContextAccessor.HttpContext
|
|
||||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
|
||||||
|
|
||||||
if (ctx.User.Identity?.IsAuthenticated == true)
|
|
||||||
{
|
|
||||||
ctx.Response.Redirect("/");
|
|
||||||
return ValueTask.CompletedTask;
|
|
||||||
}
|
|
||||||
|
|
||||||
var afTokens = antiforgery.GetAndStoreTokens(ctx);
|
|
||||||
ctx.WriteHtmxPage(new Register(afToken: afTokens.RequestToken), title: "Register", appName: "HtmxApp", pageTitle: "Create account");
|
|
||||||
return ValueTask.CompletedTask;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
[Handler]
|
|
||||||
[MapPost("/register")]
|
|
||||||
public static partial class PostRegisterHandler
|
|
||||||
{
|
|
||||||
public record Command(
|
|
||||||
[property: FromForm] string Email,
|
|
||||||
[property: FromForm] string Password,
|
|
||||||
[property: FromForm] string ConfirmPassword,
|
|
||||||
[property: FromForm] string? DisplayName
|
|
||||||
);
|
|
||||||
|
|
||||||
private static async ValueTask HandleAsync(
|
|
||||||
[AsParameters] Command command,
|
|
||||||
IHttpContextAccessor httpContextAccessor,
|
|
||||||
IAntiforgery antiforgery,
|
|
||||||
AuthService authService,
|
|
||||||
CancellationToken token)
|
|
||||||
{
|
|
||||||
var ctx = httpContextAccessor.HttpContext
|
|
||||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
|
||||||
|
|
||||||
if (command.Password != command.ConfirmPassword)
|
|
||||||
{
|
|
||||||
var afTokens1 = antiforgery.GetAndStoreTokens(ctx);
|
|
||||||
ctx.WriteHtmxPage(new Register("Passwords do not match.", afToken: afTokens1.RequestToken),
|
|
||||||
title: "Register", appName: "HtmxApp", pageTitle: "Create account");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var (success, error) = await authService.RegisterAsync(command.Email, command.Password, command.DisplayName);
|
|
||||||
|
|
||||||
if (success)
|
|
||||||
{
|
|
||||||
ctx.Response.Redirect("/");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var afTokens2 = antiforgery.GetAndStoreTokens(ctx);
|
|
||||||
ctx.WriteHtmxPage(new Register(error, afToken: afTokens2.RequestToken),
|
|
||||||
title: "Register", appName: "HtmxApp", pageTitle: "Create account");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
using Htmx.ApiDemo.Templates;
|
||||||
|
using Microsoft.AspNetCore.Antiforgery;
|
||||||
|
using Htmx.ApiDemo.Data;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
|
namespace Htmx.ApiDemo;
|
||||||
|
|
||||||
|
public static partial class RouteMap
|
||||||
|
{
|
||||||
|
private static void GetRegister(WebApplication app)
|
||||||
|
=> app.MapGet("/register", (IHttpContextAccessor contextAccessor, IAntiforgery antiforgery) =>
|
||||||
|
{
|
||||||
|
var context = contextAccessor.HttpContext
|
||||||
|
?? throw new InvalidOperationException("HttpContext is not available.");
|
||||||
|
|
||||||
|
if (context.User.Identity?.IsAuthenticated == true)
|
||||||
|
{
|
||||||
|
context.Response.Redirect("/");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var afTokens = antiforgery.GetAndStoreTokens(context);
|
||||||
|
var registerComponent = new Register(afToken: afTokens.RequestToken);
|
||||||
|
registerComponent.HtmxAwareWriteToBody(
|
||||||
|
context: context,
|
||||||
|
title: "Register",
|
||||||
|
appName: "HtmxApp",
|
||||||
|
pageTitle: "Create account"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
private static void PostRegister(WebApplication app)
|
||||||
|
=> app.MapPost("/register", async ValueTask
|
||||||
|
(
|
||||||
|
[FromForm] string email,
|
||||||
|
[FromForm] string password,
|
||||||
|
[FromForm] string confirmPassword,
|
||||||
|
[FromForm] string? displayName,
|
||||||
|
[FromServices] IHttpContextAccessor httpContextAccessor,
|
||||||
|
[FromServices] IAntiforgery antiforgery,
|
||||||
|
[FromServices] AppAuthService authService
|
||||||
|
) =>
|
||||||
|
{
|
||||||
|
var context = httpContextAccessor.HttpContext
|
||||||
|
?? throw new InvalidOperationException("HttpContext is not available.");
|
||||||
|
|
||||||
|
var afToken = antiforgery.GetAndStoreTokens(context).RequestToken;
|
||||||
|
|
||||||
|
if (password != confirmPassword)
|
||||||
|
{
|
||||||
|
var errorComponent = new Register("Passwords do not match.", afToken: afToken);
|
||||||
|
errorComponent.HtmxAwareWriteToBody(
|
||||||
|
context: context,
|
||||||
|
title: "Register",
|
||||||
|
appName: "HtmxApp",
|
||||||
|
pageTitle: "Create account"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
var (success, error) = await authService.RegisterAsync(email, password, displayName);
|
||||||
|
|
||||||
|
if (success)
|
||||||
|
{
|
||||||
|
context.Response.Redirect("/");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var registerComponent = new Register(error, afToken: afToken);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
using Htmx.ApiDemo.Templates.Components;
|
using Htmx.ApiDemo.Templates.Components;
|
||||||
using Immediate.Apis.Shared;
|
using Microsoft.AspNetCore.Http;
|
||||||
using Immediate.Handlers.Shared;
|
|
||||||
|
|
||||||
namespace Htmx.ApiDemo.Templates;
|
namespace Htmx.ApiDemo.Templates;
|
||||||
|
|
||||||
@@ -364,25 +363,3 @@ public sealed class UiDemo : UiDemoBase
|
|||||||
|
|
||||||
protected override void RenderToastViewportDemo(HtmxRenderContext ctx) => ToastViewportDemo.Render(ctx);
|
protected override void RenderToastViewportDemo(HtmxRenderContext ctx) => ToastViewportDemo.Render(ctx);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
[Handler]
|
|
||||||
[MapGet("/ui-demo")]
|
|
||||||
public static partial class GetUiDemoHandler
|
|
||||||
{
|
|
||||||
public record Query;
|
|
||||||
|
|
||||||
private static ValueTask HandleAsync(
|
|
||||||
Query query,
|
|
||||||
IHttpContextAccessor httpContextAccessor,
|
|
||||||
CancellationToken token)
|
|
||||||
{
|
|
||||||
var context = httpContextAccessor.HttpContext
|
|
||||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
|
||||||
|
|
||||||
var page = new UiDemo();
|
|
||||||
context.WriteHtmxPage(page, title: "UI Demo", appName: "HtmxApp", pageTitle: "UI Components");
|
|
||||||
|
|
||||||
return ValueTask.CompletedTask;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
using Htmx.ApiDemo.Templates;
|
||||||
|
|
||||||
|
namespace Htmx.ApiDemo;
|
||||||
|
|
||||||
|
public static partial class RouteMap
|
||||||
|
{
|
||||||
|
private static void GetUiDemo(WebApplication app)
|
||||||
|
=> app.MapGet("/ui-demo", (IHttpContextAccessor contextAccessor) =>
|
||||||
|
{
|
||||||
|
var context = contextAccessor.HttpContext
|
||||||
|
?? throw new InvalidOperationException("HttpContext is not available.");
|
||||||
|
|
||||||
|
if (context.User.Identity?.IsAuthenticated == false)
|
||||||
|
{
|
||||||
|
context.Response.Redirect("/login");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var uiDemoComponent = new UiDemo();
|
||||||
|
uiDemoComponent.HtmxAwareWriteToBody(
|
||||||
|
context: context,
|
||||||
|
title: "UI Demo",
|
||||||
|
appName: "HtmxApp",
|
||||||
|
pageTitle: "Htmx UI Demo"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -4,5 +4,9 @@
|
|||||||
"Default": "Information",
|
"Default": "Information",
|
||||||
"Microsoft.AspNetCore": "Warning"
|
"Microsoft.AspNetCore": "Warning"
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
"ConnectionStrings": {
|
||||||
|
"DefaultConnection": "mongodb://localhost:27017/"
|
||||||
|
},
|
||||||
|
"MongoDbName": "HtmxDemoDb"
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -25,6 +25,8 @@ namespace Htmx.SourceGenerator
|
|||||||
using System;
|
using System;
|
||||||
using System.Buffers;
|
using System.Buffers;
|
||||||
using System.Runtime.CompilerServices;
|
using System.Runtime.CompilerServices;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
|
||||||
namespace {opt.RootNamespace};
|
namespace {opt.RootNamespace};
|
||||||
|
|
||||||
@@ -67,11 +69,11 @@ public static class HtmxGeneratedExtensions
|
|||||||
writer.Advance(data.Length);
|
writer.Advance(data.Length);
|
||||||
}}
|
}}
|
||||||
|
|
||||||
public static void WriteHtmxBody(this HttpContext context, IHtmxComponent component)
|
public static void WriteToResponseBody(this IHtmxComponent component, HttpContext context)
|
||||||
{{
|
{{
|
||||||
context.Response.ContentType = ""text/html; charset=utf-8"";
|
context.Response.ContentType = ""text/html; charset=utf-8"";
|
||||||
var writerContext = new HtmxRenderContext(context.Response.BodyWriter);
|
var renderContext = new HtmxRenderContext(context.Response.BodyWriter);
|
||||||
component.Render(writerContext);
|
component.Render(renderContext);
|
||||||
}}
|
}}
|
||||||
}}";
|
}}";
|
||||||
spc.AddSource("HtmxInfrastructure.g.cs", SourceText.From(infrastructureSource, Encoding.UTF8));
|
spc.AddSource("HtmxInfrastructure.g.cs", SourceText.From(infrastructureSource, Encoding.UTF8));
|
||||||
|
|||||||
@@ -0,0 +1,97 @@
|
|||||||
|
# AOT Testing Guide
|
||||||
|
|
||||||
|
This directory contains scripts for building and testing the Htmx.ApiDemo application with Ahead-of-Time (AOT) compilation enabled. AOT compilation helps identify potential trimming issues that may occur at runtime.
|
||||||
|
|
||||||
|
## Directory Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
Testing/
|
||||||
|
└── AOT/
|
||||||
|
├── build-aot.ps1 # Windows PowerShell script
|
||||||
|
├── build-aot.sh # Linux/POP_OS bash script
|
||||||
|
├── Publish/ # Output directory (created during build)
|
||||||
|
└── README.md # This file
|
||||||
|
```
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
- .NET SDK (version 10.0 or later)
|
||||||
|
- For Windows: PowerShell 5.1 or later
|
||||||
|
- For Linux/POP_OS: Bash shell
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
### Windows (PowerShell)
|
||||||
|
|
||||||
|
**Build and Run:**
|
||||||
|
```powershell
|
||||||
|
.\build-aot.ps1
|
||||||
|
```
|
||||||
|
|
||||||
|
**Build Only:**
|
||||||
|
```powershell
|
||||||
|
.\build-aot.ps1 -BuildOnly
|
||||||
|
```
|
||||||
|
|
||||||
|
**Run Only (if already built):**
|
||||||
|
```powershell
|
||||||
|
.\build-aot.ps1 -RunOnly
|
||||||
|
```
|
||||||
|
|
||||||
|
### Linux/POP_OS (Bash)
|
||||||
|
|
||||||
|
Make the script executable first:
|
||||||
|
```bash
|
||||||
|
chmod +x build-aot.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
**Build and Run:**
|
||||||
|
```bash
|
||||||
|
./build-aot.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
**Build Only:**
|
||||||
|
```bash
|
||||||
|
./build-aot.sh --build-only
|
||||||
|
```
|
||||||
|
|
||||||
|
**Run Only (if already built):**
|
||||||
|
```bash
|
||||||
|
./build-aot.sh --run-only
|
||||||
|
```
|
||||||
|
|
||||||
|
## What These Scripts Do
|
||||||
|
|
||||||
|
1. **Clean**: Removes any previous publish directory
|
||||||
|
2. **Build**: Publishes the application with the following AOT settings:
|
||||||
|
- `PublishAot=true` - Enables AOT compilation
|
||||||
|
- `TrimMode=link` - Uses link-time trimming
|
||||||
|
- `PublishTrimmed=true` - Enables trimming
|
||||||
|
- `SelfContained=true` - Creates a self-contained executable
|
||||||
|
- Debug symbols are disabled for optimized output
|
||||||
|
|
||||||
|
3. **Run**: Launches the compiled application to test for any trimming-related issues
|
||||||
|
|
||||||
|
## Output
|
||||||
|
|
||||||
|
The compiled application and all dependencies are published to the `Testing/AOT/Publish` directory.
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### Build Failures
|
||||||
|
|
||||||
|
If the AOT build fails, check the error messages for:
|
||||||
|
- **Trimming issues**: Indicates code that cannot be safely trimmed
|
||||||
|
- **Reflection warnings**: APIs that use reflection may not work properly
|
||||||
|
- **Missing dependencies**: Required libraries that aren't properly configured
|
||||||
|
|
||||||
|
### Common Issues
|
||||||
|
|
||||||
|
1. **"Executable not found"**: The build may have failed silently. Check the build output for errors.
|
||||||
|
2. **Runtime crashes**: Trimming may have removed necessary code. Consider adding trimming configuration in your project file or using `[DynamicallyAccessedMembers]` attributes.
|
||||||
|
|
||||||
|
## Related Documentation
|
||||||
|
|
||||||
|
- [AOT Deployment](https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/)
|
||||||
|
- [Trimming .NET Applications](https://learn.microsoft.com/en-us/dotnet/core/deploying/trimming/trim-self-contained)
|
||||||
|
- [Reflections and Trimming](https://learn.microsoft.com/en-us/dotnet/core/deploying/trimming/trim-self-contained#reflections)
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
# AOT Build and Test Script for Windows PowerShell
|
||||||
|
# This script builds the Htmx.ApiDemo application with AOT compilation enabled
|
||||||
|
# and runs the application to check for trimming issues
|
||||||
|
|
||||||
|
param(
|
||||||
|
[switch]$RunOnly,
|
||||||
|
[switch]$BuildOnly
|
||||||
|
)
|
||||||
|
|
||||||
|
# Set error handling
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
|
||||||
|
# Define paths
|
||||||
|
$ProjectRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
|
||||||
|
$ApiDemoProject = Join-Path $ProjectRoot "Htmx.ApiDemo"
|
||||||
|
$PublishPath = Join-Path $PSScriptRoot "Publish"
|
||||||
|
|
||||||
|
Write-Host "========================================" -ForegroundColor Cyan
|
||||||
|
Write-Host "AOT Build and Test Script" -ForegroundColor Cyan
|
||||||
|
Write-Host "========================================" -ForegroundColor Cyan
|
||||||
|
Write-Host ""
|
||||||
|
|
||||||
|
if (-not $RunOnly) {
|
||||||
|
Write-Host "Starting AOT Build Process..." -ForegroundColor Yellow
|
||||||
|
Write-Host "Project Path: $ApiDemoProject" -ForegroundColor Gray
|
||||||
|
Write-Host "Publish Path: $PublishPath" -ForegroundColor Gray
|
||||||
|
Write-Host ""
|
||||||
|
|
||||||
|
# Kill any running instance of the app before cleaning (it locks the publish folder)
|
||||||
|
$AppName = "Htmx.ApiDemo"
|
||||||
|
$Running = Get-Process -Name $AppName -ErrorAction SilentlyContinue
|
||||||
|
if ($Running) {
|
||||||
|
Write-Host "Stopping running instance of $AppName..." -ForegroundColor Yellow
|
||||||
|
$Running | Stop-Process -Force
|
||||||
|
Start-Sleep -Milliseconds 500
|
||||||
|
}
|
||||||
|
|
||||||
|
# Clean previous publish folder if it exists
|
||||||
|
if (Test-Path $PublishPath) {
|
||||||
|
Write-Host "Cleaning previous publish folder..." -ForegroundColor Yellow
|
||||||
|
Remove-Item -Path $PublishPath -Recurse -Force
|
||||||
|
}
|
||||||
|
|
||||||
|
# Create publish folder
|
||||||
|
New-Item -Path $PublishPath -ItemType Directory -Force | Out-Null
|
||||||
|
|
||||||
|
try {
|
||||||
|
# Run dotnet publish with AOT enabled
|
||||||
|
# PublishAot=true is already set in the .csproj
|
||||||
|
# A Runtime Identifier (RID) is required for AOT compilation
|
||||||
|
Write-Host "Publishing with AOT compilation enabled (win-x64)..." -ForegroundColor Yellow
|
||||||
|
Push-Location $ApiDemoProject
|
||||||
|
|
||||||
|
dotnet publish -c Release -r win-x64 -o $PublishPath `
|
||||||
|
-p:DebugSymbols=false `
|
||||||
|
-p:DebugType=none
|
||||||
|
|
||||||
|
if ($LASTEXITCODE -ne 0) {
|
||||||
|
Write-Host "Build failed!" -ForegroundColor Red
|
||||||
|
Pop-Location
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
Pop-Location
|
||||||
|
Write-Host "AOT build completed successfully!" -ForegroundColor Green
|
||||||
|
Write-Host ""
|
||||||
|
|
||||||
|
# Copy appsettings.Development.json over appsettings.json in the publish folder
|
||||||
|
# so the AOT executable has the correct connection strings for local testing
|
||||||
|
$DevSettings = Join-Path $ApiDemoProject "appsettings.Development.json"
|
||||||
|
$PublishedSettings = Join-Path $PublishPath "appsettings.json"
|
||||||
|
if (Test-Path $DevSettings) {
|
||||||
|
Write-Host "Copying appsettings.Development.json -> appsettings.json in publish folder..." -ForegroundColor Yellow
|
||||||
|
Copy-Item -Path $DevSettings -Destination $PublishedSettings -Force
|
||||||
|
Write-Host "Done." -ForegroundColor Green
|
||||||
|
Write-Host ""
|
||||||
|
} else {
|
||||||
|
Write-Host "Warning: appsettings.Development.json not found, skipping copy." -ForegroundColor DarkYellow
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
Write-Host "Error during build: $_" -ForegroundColor Red
|
||||||
|
Pop-Location
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (-not $BuildOnly) {
|
||||||
|
Write-Host "Starting Application..." -ForegroundColor Yellow
|
||||||
|
Write-Host ""
|
||||||
|
|
||||||
|
# Find the executable
|
||||||
|
$Executable = Get-ChildItem -Path $PublishPath -Filter "*.exe" -Recurse | Select-Object -First 1
|
||||||
|
|
||||||
|
if (-not $Executable) {
|
||||||
|
Write-Host "Executable not found in publish directory!" -ForegroundColor Red
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host "Running: $($Executable.FullName)" -ForegroundColor Yellow
|
||||||
|
Write-Host "Press Ctrl+C to stop the application" -ForegroundColor Gray
|
||||||
|
Write-Host ""
|
||||||
|
|
||||||
|
try {
|
||||||
|
# Use Start-Process with WorkingDirectory so appsettings.json is found,
|
||||||
|
# and the shell CWD is never changed (safe against Ctrl+C)
|
||||||
|
$proc = Start-Process -FilePath $Executable.FullName `
|
||||||
|
-WorkingDirectory $PublishPath `
|
||||||
|
-NoNewWindow `
|
||||||
|
-PassThru
|
||||||
|
$proc.WaitForExit()
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
Write-Host "Error running application: $_" -ForegroundColor Red
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "========================================" -ForegroundColor Cyan
|
||||||
|
Write-Host "AOT Test Complete" -ForegroundColor Cyan
|
||||||
|
Write-Host "========================================" -ForegroundColor Cyan
|
||||||
Executable
+114
@@ -0,0 +1,114 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# AOT Build and Test Script for POP_OS/Linux
|
||||||
|
# This script builds the Htmx.ApiDemo application with AOT compilation enabled
|
||||||
|
# and runs the application to check for trimming issues
|
||||||
|
|
||||||
|
# Set error handling
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Initialize flags
|
||||||
|
RUN_ONLY=false
|
||||||
|
BUILD_ONLY=false
|
||||||
|
|
||||||
|
# Parse command line arguments
|
||||||
|
while [[ $# -gt 0 ]]; do
|
||||||
|
case $1 in
|
||||||
|
--run-only)
|
||||||
|
RUN_ONLY=true
|
||||||
|
shift
|
||||||
|
;;
|
||||||
|
--build-only)
|
||||||
|
BUILD_ONLY=true
|
||||||
|
shift
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "Unknown option: $1"
|
||||||
|
echo "Usage: $0 [--run-only] [--build-only]"
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# Define paths
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
|
||||||
|
API_DEMO_PROJECT="$PROJECT_ROOT/Htmx.ApiDemo"
|
||||||
|
PUBLISH_PATH="$SCRIPT_DIR/Publish"
|
||||||
|
|
||||||
|
echo "========================================"
|
||||||
|
echo "AOT Build and Test Script"
|
||||||
|
echo "========================================"
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
if [ "$RUN_ONLY" = false ]; then
|
||||||
|
echo "Starting AOT Build Process..."
|
||||||
|
echo "Project Path: $API_DEMO_PROJECT"
|
||||||
|
echo "Publish Path: $PUBLISH_PATH"
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
# Clean previous publish folder if it exists
|
||||||
|
if [ -d "$PUBLISH_PATH" ]; then
|
||||||
|
echo "Cleaning previous publish folder..."
|
||||||
|
rm -rf "$PUBLISH_PATH"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Create publish folder
|
||||||
|
mkdir -p "$PUBLISH_PATH"
|
||||||
|
|
||||||
|
# Navigate to project directory
|
||||||
|
cd "$API_DEMO_PROJECT" || exit 1
|
||||||
|
|
||||||
|
# Run dotnet publish with AOT enabled
|
||||||
|
# PublishAot=true is already set in the .csproj
|
||||||
|
# A Runtime Identifier (RID) is required for AOT compilation
|
||||||
|
echo "Publishing with AOT compilation enabled (linux-x64)..."
|
||||||
|
|
||||||
|
if ! dotnet publish -c Release -r linux-x64 -o "$PUBLISH_PATH" \
|
||||||
|
-p:DebugSymbols=false \
|
||||||
|
-p:DebugType=none; then
|
||||||
|
echo "Build failed!"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "AOT build completed successfully!"
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
# Copy appsettings.Development.json over appsettings.json in the publish folder
|
||||||
|
# so the AOT executable has the correct connection strings for local testing
|
||||||
|
DEV_SETTINGS="$API_DEMO_PROJECT/appsettings.Development.json"
|
||||||
|
PUBLISHED_SETTINGS="$PUBLISH_PATH/appsettings.json"
|
||||||
|
if [ -f "$DEV_SETTINGS" ]; then
|
||||||
|
echo "Copying appsettings.Development.json -> appsettings.json in publish folder..."
|
||||||
|
cp -f "$DEV_SETTINGS" "$PUBLISHED_SETTINGS"
|
||||||
|
echo "Done."
|
||||||
|
echo ""
|
||||||
|
else
|
||||||
|
echo "Warning: appsettings.Development.json not found, skipping copy."
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$BUILD_ONLY" = false ]; then
|
||||||
|
echo "Starting Application..."
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
# Find the executable
|
||||||
|
EXECUTABLE=$(find "$PUBLISH_PATH" -type f -perm /u+x ! -name "*.so" ! -name "*.a" ! -name "*.o" | head -n 1)
|
||||||
|
|
||||||
|
if [ -z "$EXECUTABLE" ]; then
|
||||||
|
echo "Executable not found in publish directory!"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Running: $EXECUTABLE"
|
||||||
|
echo "Press Ctrl+C to stop the application"
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
# cd into publish dir so appsettings.json is found relative to the executable
|
||||||
|
cd "$PUBLISH_PATH" || exit 1
|
||||||
|
"$EXECUTABLE"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "========================================"
|
||||||
|
echo "AOT Test Complete"
|
||||||
|
echo "========================================"
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
using Microsoft.Playwright;
|
||||||
|
|
||||||
|
const string defaultSelector = "button:has-text('Click to')";
|
||||||
|
|
||||||
|
var targetUrl = PromptForTargetUrl();
|
||||||
|
var options = StressOptions.Parse(args, defaultSelector, targetUrl);
|
||||||
|
|
||||||
|
Console.WriteLine($"URL: {options.TargetUrl}");
|
||||||
|
Console.WriteLine($"Instances: {options.InstanceCount}");
|
||||||
|
Console.WriteLine($"Interval: {options.IntervalMs}ms");
|
||||||
|
Console.WriteLine($"Selector: {options.ButtonSelector}");
|
||||||
|
Console.WriteLine($"Headless: {options.Headless}");
|
||||||
|
Console.WriteLine("Press Ctrl+C to stop.");
|
||||||
|
|
||||||
|
using var cts = new CancellationTokenSource();
|
||||||
|
Console.CancelKeyPress += (_, eventArgs) =>
|
||||||
|
{
|
||||||
|
eventArgs.Cancel = true;
|
||||||
|
cts.Cancel();
|
||||||
|
};
|
||||||
|
|
||||||
|
var workers = Enumerable.Range(1, options.InstanceCount)
|
||||||
|
.Select(instanceId => RunWorkerAsync(instanceId, options, cts.Token))
|
||||||
|
.ToArray();
|
||||||
|
|
||||||
|
await Task.WhenAll(workers);
|
||||||
|
|
||||||
|
static string PromptForTargetUrl()
|
||||||
|
{
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
Console.Write("Enter target URL: ");
|
||||||
|
var input = Console.ReadLine();
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(input)
|
||||||
|
&& Uri.TryCreate(input, UriKind.Absolute, out var uri)
|
||||||
|
&& (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps))
|
||||||
|
{
|
||||||
|
return uri.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
Console.WriteLine("Invalid URL. Please enter a full http/https URL.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async Task RunWorkerAsync(int instanceId, StressOptions options, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var playwright = await Playwright.CreateAsync();
|
||||||
|
await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
|
||||||
|
{
|
||||||
|
Headless = options.Headless
|
||||||
|
});
|
||||||
|
|
||||||
|
var page = await browser.NewPageAsync();
|
||||||
|
await page.GotoAsync(options.TargetUrl, new PageGotoOptions
|
||||||
|
{
|
||||||
|
WaitUntil = WaitUntilState.DOMContentLoaded,
|
||||||
|
Timeout = 30000
|
||||||
|
});
|
||||||
|
|
||||||
|
Console.WriteLine($"[{instanceId}] connected");
|
||||||
|
var clickCount = 0;
|
||||||
|
|
||||||
|
while (!cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// HTMX can replace the button after each request, so resolve it fresh every loop.
|
||||||
|
var button = page.Locator(options.ButtonSelector).First;
|
||||||
|
await button.WaitForAsync(new LocatorWaitForOptions
|
||||||
|
{
|
||||||
|
State = WaitForSelectorState.Visible,
|
||||||
|
Timeout = 5000
|
||||||
|
});
|
||||||
|
await button.ClickAsync(new LocatorClickOptions
|
||||||
|
{
|
||||||
|
Timeout = 5000,
|
||||||
|
Force = true
|
||||||
|
});
|
||||||
|
|
||||||
|
clickCount += 1;
|
||||||
|
if (clickCount % 25 == 0)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"[{instanceId}] clicks sent: {clickCount}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (TimeoutException)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"[{instanceId}] click timeout");
|
||||||
|
}
|
||||||
|
catch (PlaywrightException ex)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"[{instanceId}] click error: {ex.Message}");
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await Task.Delay(options.IntervalMs, cancellationToken);
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await page.CloseAsync();
|
||||||
|
Console.WriteLine($"[{instanceId}] stopped");
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"[{instanceId}] canceled");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"[{instanceId}] fatal: {ex.Message}");
|
||||||
|
if (ex.Message.Contains("Executable doesn't exist", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
Console.WriteLine("Install browser binaries first:");
|
||||||
|
Console.WriteLine("./bin/Debug/net10.0/.playwright/node/linux-x64/node ./bin/Debug/net10.0/.playwright/package/cli.js install chromium");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed record StressOptions(
|
||||||
|
string TargetUrl,
|
||||||
|
int InstanceCount,
|
||||||
|
int IntervalMs,
|
||||||
|
string ButtonSelector,
|
||||||
|
bool Headless)
|
||||||
|
{
|
||||||
|
public static StressOptions Parse(string[] args, string defaultSelector, string targetUrl)
|
||||||
|
{
|
||||||
|
var instanceCount = ParsePositiveInt(Environment.GetEnvironmentVariable("INSTANCE_COUNT"), 20);
|
||||||
|
var intervalMs = ParsePositiveInt(Environment.GetEnvironmentVariable("CLICK_INTERVAL_MS"), 200);
|
||||||
|
var buttonSelector = Environment.GetEnvironmentVariable("BUTTON_SELECTOR") ?? defaultSelector;
|
||||||
|
var headless = ParseBool(Environment.GetEnvironmentVariable("HEADLESS"), true);
|
||||||
|
|
||||||
|
foreach (var arg in args)
|
||||||
|
{
|
||||||
|
var split = arg.Split('=', 2, StringSplitOptions.TrimEntries);
|
||||||
|
if (split.Length != 2)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var key = split[0].TrimStart('-', '/').ToLowerInvariant();
|
||||||
|
var value = split[1];
|
||||||
|
|
||||||
|
switch (key)
|
||||||
|
{
|
||||||
|
case "instances":
|
||||||
|
case "instancecount":
|
||||||
|
instanceCount = ParsePositiveInt(value, instanceCount);
|
||||||
|
break;
|
||||||
|
case "interval":
|
||||||
|
case "intervalms":
|
||||||
|
intervalMs = ParsePositiveInt(value, intervalMs);
|
||||||
|
break;
|
||||||
|
case "selector":
|
||||||
|
case "buttonselector":
|
||||||
|
buttonSelector = value;
|
||||||
|
break;
|
||||||
|
case "headless":
|
||||||
|
headless = ParseBool(value, headless);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new StressOptions(targetUrl, instanceCount, intervalMs, buttonSelector, headless);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int ParsePositiveInt(string? rawValue, int fallback)
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrWhiteSpace(rawValue) && int.TryParse(rawValue, out var parsed) && parsed > 0)
|
||||||
|
{
|
||||||
|
return parsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool ParseBool(string? rawValue, bool fallback)
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrWhiteSpace(rawValue) && bool.TryParse(rawValue, out var parsed))
|
||||||
|
{
|
||||||
|
return parsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
# stress-test-01
|
||||||
|
|
||||||
|
C# .NET console app that launches 20 Playwright Chromium instances, navigates to the deployed URL, and clicks a button every 200ms.
|
||||||
|
|
||||||
|
## Defaults
|
||||||
|
|
||||||
|
- URL: prompted from user input every run
|
||||||
|
- Instances: `20`
|
||||||
|
- Interval: `200` ms
|
||||||
|
- Button selector: `button:visible` (first match)
|
||||||
|
- Headless: `true`
|
||||||
|
|
||||||
|
## Run
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd Testing/stress-test-01
|
||||||
|
dotnet restore
|
||||||
|
dotnet build
|
||||||
|
./bin/Debug/net10.0/.playwright/node/linux-x64/node ./bin/Debug/net10.0/.playwright/package/cli.js install chromium
|
||||||
|
dotnet run
|
||||||
|
```
|
||||||
|
|
||||||
|
PowerShell alternative:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pwsh bin/Debug/net10.0/playwright.ps1 install chromium
|
||||||
|
```
|
||||||
|
|
||||||
|
The app will prompt:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Enter target URL:
|
||||||
|
```
|
||||||
|
|
||||||
|
## Optional overrides
|
||||||
|
|
||||||
|
Use either environment variables or CLI args:
|
||||||
|
|
||||||
|
- `INSTANCE_COUNT` or `--instances=<value>`
|
||||||
|
- `CLICK_INTERVAL_MS` or `--intervalms=<value>`
|
||||||
|
- `BUTTON_SELECTOR` or `--selector=<value>`
|
||||||
|
- `HEADLESS` or `--headless=<true|false>`
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
INSTANCE_COUNT=20 CLICK_INTERVAL_MS=200 dotnet run
|
||||||
|
```
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
<PropertyGroup>
|
||||||
|
<OutputType>Exe</OutputType>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<LangVersion>latest</LangVersion>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Playwright" Version="1.54.0" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
Reference in New Issue
Block a user