fix(stage): route blog revalidation to Next and omit unrelated article media
Deploy Canina / deploy (push) Successful in 3m16s
Deploy Canina / deploy (push) Successful in 3m16s
This commit is contained in:
1 parent
85ef01d337
commit
55d11fa597
8 files changed
+106
-15
No files matched your search
@@ -0,0 +1,27 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
vi.mock('../../../lib/seo', () => ({ getSeoConfig: async () => ({brandNameFa:'Canina', ogImageUrl:'https://example.org/unrelated.webp'}), formatPageTitle: (s:string) => s }));
|
||||
vi.mock('../../../components/BlogPostClient', () => ({default: () => null}));
|
||||
vi.mock('next/navigation', () => ({notFound: () => {throw Error('404')}}));
|
||||
import Page, {generateMetadata} from './page';
|
||||
const base = {title:'Existing article',content:'Body',slug:'existing',publishedAt:'2026-11-15T05:41:53Z'};
|
||||
let blog: any;
|
||||
beforeEach(() => {blog={...base}; vi.stubGlobal('fetch',vi.fn(async () => ({ok:true,json:async () => blog})));});
|
||||
describe('article-owned media', () => {
|
||||
it.each([null,undefined,'',' '])('omits unrelated imagery for %s', async (image) => {
|
||||
blog.imageUrl=image; blog.ogImage=image;
|
||||
const metadata:any=await generateMetadata({params:Promise.resolve({slug:'existing'})});
|
||||
expect(metadata.openGraph.images).toEqual([]);
|
||||
expect(metadata.twitter.images).toEqual([]);
|
||||
expect(metadata.twitter.card).toBe('summary');
|
||||
const page:any=await Page({params:Promise.resolve({slug:'existing'})});
|
||||
const schema=JSON.parse(page.props.children[0].props.dangerouslySetInnerHTML.__html);
|
||||
expect(schema).not.toHaveProperty('image');
|
||||
});
|
||||
it('retains authored OG precedence and Article image', async () => {
|
||||
blog.imageUrl='/uploads/article.webp'; blog.ogImage='/uploads/social.webp';
|
||||
const metadata:any=await generateMetadata({params:Promise.resolve({slug:'existing'})});
|
||||
expect(metadata.openGraph.images[0].url).toBe('/uploads/social.webp');
|
||||
const page:any=await Page({params:Promise.resolve({slug:'existing'})});
|
||||
expect(JSON.parse(page.props.children[0].props.dangerouslySetInnerHTML.__html).image[0]).toContain('/uploads/article.webp');
|
||||
});
|
||||
});
|
||||
@@ -77,7 +77,7 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
|
||||
(typeof blog.content === 'string' ? blog.content.substring(0, 155).replace(/<[^>]+>/g, '') : '') ||
|
||||
config.defaultMetaDescription;
|
||||
const canonicalUrl = blog.canonicalUrl ? blog.canonicalUrl.replace(/\/+$/, '') : `${siteUrl}/blog/${slug}`;
|
||||
const ogImageUrl = blog.ogImage || blog.imageUrl || config.ogImageUrl;
|
||||
const ogImageUrl = (typeof blog.ogImage === 'string' ? blog.ogImage.trim() : '') || (typeof blog.imageUrl === 'string' ? blog.imageUrl.trim() : '');
|
||||
const ogTitle = blog.ogTitle || title;
|
||||
const ogDesc = blog.ogDescription || description;
|
||||
|
||||
@@ -133,14 +133,14 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
|
||||
openGraph: {
|
||||
title: ogTitle,
|
||||
description: ogDesc,
|
||||
images: [
|
||||
images: ogImageUrl ? [
|
||||
{
|
||||
url: ogImageUrl,
|
||||
width: 1200,
|
||||
height: 630,
|
||||
alt: blog.imageAlt || blog.title || title,
|
||||
},
|
||||
],
|
||||
] : [],
|
||||
url: canonicalUrl,
|
||||
siteName: config.brandNameFa,
|
||||
type: "article",
|
||||
@@ -150,10 +150,10 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
|
||||
tags: blog.tags?.map((t: any) => typeof t === 'string' ? t : t?.name).filter(Boolean) || [],
|
||||
},
|
||||
twitter: {
|
||||
card: "summary_large_image",
|
||||
card: ogImageUrl ? "summary_large_image" : "summary",
|
||||
title: ogTitle,
|
||||
description: ogDesc,
|
||||
images: [ogImageUrl],
|
||||
images: ogImageUrl ? [ogImageUrl] : [],
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -205,9 +205,9 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
|
||||
},
|
||||
headline: blog.title,
|
||||
description: blog.excerpt || blog.metaDescription || blog.title,
|
||||
image: blog.imageUrl
|
||||
? [blog.imageUrl.startsWith('http') ? blog.imageUrl : `${siteUrl}${blog.imageUrl.startsWith('/') ? '' : '/'}${blog.imageUrl}`]
|
||||
: [config.ogImageUrl.startsWith('http') ? config.ogImageUrl : `${siteUrl}${config.ogImageUrl.startsWith('/') ? '' : '/'}${config.ogImageUrl}`],
|
||||
...(typeof blog.imageUrl === 'string' && blog.imageUrl.trim()
|
||||
? { image: [new URL(blog.imageUrl.trim(), siteUrl).href] }
|
||||
: {}),
|
||||
datePublished: publishedIso,
|
||||
dateModified: modifiedIso,
|
||||
author: authorSchema,
|
||||
|
||||
@@ -74,6 +74,15 @@
|
||||
}
|
||||
}
|
||||
|
||||
/* Authored body links remain recognizable without relying on color alone. */
|
||||
.article-html-content a {
|
||||
color: var(--color-canina-blue);
|
||||
font-weight: 700;
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 4px;
|
||||
}
|
||||
.article-html-content a:hover { color: var(--color-medical-gray-900); }
|
||||
|
||||
/* Sonner Toasts Vazirmatn Font & Mobile Offset */
|
||||
[data-sonner-toaster] {
|
||||
font-family: "Vazirmatn", sans-serif !important;
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# Stage-only storefront repair; retain the deployed admin and nginx artifacts.
|
||||
ARG STAGE_BASE_IMAGE
|
||||
FROM node:20-alpine AS app-builder
|
||||
WORKDIR /app
|
||||
ARG NPM_REGISTRY=https://registry.parsaaghayi.ir/repository/npm/
|
||||
RUN npm config set registry "$NPM_REGISTRY" && npm config set strict-ssl false
|
||||
COPY frontend/application/package*.json ./
|
||||
RUN npm ci --include=dev --prefer-offline --no-audit
|
||||
COPY frontend/application ./
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
ENV NEXT_PUBLIC_API_URL=https://stageapi.canina.ir/api
|
||||
ENV NEXT_PUBLIC_SITE_URL=https://stage.canina.ir
|
||||
ENV NEXT_PUBLIC_APP_ENV=staging
|
||||
RUN npm run build
|
||||
FROM ${STAGE_BASE_IMAGE}
|
||||
WORKDIR /app
|
||||
COPY --from=app-builder /app ./
|
||||
ENV NEXT_PUBLIC_SITE_URL=https://stage.canina.ir
|
||||
ENV NEXT_PUBLIC_APP_ENV=staging
|
||||
@@ -105,24 +105,36 @@ mkdir -p "$RELEASE_ROOT"
|
||||
TARGET_DIR=$(mktemp -d "$RELEASE_ROOT/$DEPLOY_SHA.corporate.XXXXXXXX")
|
||||
git archive "$DEPLOY_SHA" | tar -x -C "$TARGET_DIR"
|
||||
command -v python3 >/dev/null || apk add --no-cache python3
|
||||
export TARGET_DIR DEPLOY_SHA
|
||||
# Pin the existing frontend solely to retain operational nginx/admin artifacts.
|
||||
STAGE_BASE_IMAGE="canina-stage-blog-base:$DEPLOY_SHA"
|
||||
docker tag "$(docker inspect -f '{{.Image}}' canino_frontend_stage)" "$STAGE_BASE_IMAGE"
|
||||
export TARGET_DIR DEPLOY_SHA STAGE_BASE_IMAGE
|
||||
python3 - <<'PY'
|
||||
import json, os, hashlib
|
||||
from pathlib import Path
|
||||
root=Path(os.environ['TARGET_DIR']); sha=os.environ['DEPLOY_SHA']
|
||||
files={str(p.relative_to(root)):hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(root.rglob('*')) if p.is_file() and not p.is_symlink()}
|
||||
(root/'.release-manifest.json').write_text(json.dumps({'sha':sha,'files':files},sort_keys=True))
|
||||
# Only backend code is changed. Preserve every operational runtime/env file.
|
||||
# Preserve operational runtime/env files; override only the incorrect Stage route.
|
||||
service={'build':{'context':str(root/'backend'),'labels':{'org.opencontainers.image.revision':sha},'args':{'NPM_REGISTRY':'https://registry.parsaaghayi.ir/repository/npm/'}},'labels':{'ir.canina.release.sha':sha},'command':['node','dist/main.js']}
|
||||
(root/'release.override.json').write_text(json.dumps({'services':{'backend_stage':service}}))
|
||||
service['environment']={'FRONTEND_INTERNAL_URL':'http://frontend_stage:3000'}
|
||||
frontend={'build':{'context':str(root),'dockerfile':'scripts/Dockerfile.blog-stage','args':{'STAGE_BASE_IMAGE':os.environ['STAGE_BASE_IMAGE']},'labels':{'org.opencontainers.image.revision':sha}},'labels':{'ir.canina.release.sha':sha}}
|
||||
(root/'release.override.json').write_text(json.dumps({'services':{'backend_stage':service,'frontend_stage':frontend}}))
|
||||
PY
|
||||
compose=(docker compose -p stage --project-directory "$STAGE_DIR" -f "$STAGE_DIR/docker-compose.yml" -f "$TARGET_DIR/release.override.json")
|
||||
timeout --foreground --kill-after=2s 60 "${compose[@]}" config --quiet
|
||||
check_stage_lock
|
||||
timeout --foreground --kill-after=2s 1800 "${compose[@]}" --progress plain build backend_stage
|
||||
timeout --foreground --kill-after=2s 1800 "${compose[@]}" --progress plain build backend_stage frontend_stage
|
||||
check_stage_lock
|
||||
# No migrations, seed, DB/Redis/frontend/bot recreation or runtime config edits.
|
||||
timeout --foreground --kill-after=2s 120 "${compose[@]}" up -d --no-deps --force-recreate backend_stage
|
||||
# Fail closed without exposing either service's shared secret.
|
||||
python3 - <<'PY'
|
||||
import json, subprocess
|
||||
containers=json.loads(subprocess.check_output(['docker','inspect','canino_backend_stage','canino_frontend_stage']))
|
||||
envs=[dict(v.split('=',1) for v in c['Config']['Env']) for c in containers]
|
||||
assert envs[0].get('REVALIDATION_SECRET') and envs[0]['REVALIDATION_SECRET']==envs[1].get('REVALIDATION_SECRET'), 'Stage revalidation secret absent or mismatched'
|
||||
PY
|
||||
# No migrations, seed, DB/Redis/bot recreation or host runtime file edits.
|
||||
timeout --foreground --kill-after=2s 120 "${compose[@]}" up -d --no-deps --force-recreate backend_stage frontend_stage
|
||||
ready=false
|
||||
for attempt in {1..30}; do
|
||||
check_stage_lock
|
||||
@@ -137,6 +149,17 @@ done
|
||||
[[ $(timeout --foreground --kill-after=2s 10 docker inspect -f '{{index .Config.Labels "ir.canina.release.sha"}}' canino_backend_stage) == "$DEPLOY_SHA" ]]
|
||||
image=$(timeout --foreground --kill-after=2s 10 docker inspect -f '{{.Image}}' canino_backend_stage)
|
||||
[[ $(timeout --foreground --kill-after=2s 10 docker image inspect -f '{{index .Config.Labels "org.opencontainers.image.revision"}}' "$image") == "$DEPLOY_SHA" ]]
|
||||
printf 'Corporate Stage backend release complete: %s image=%s (route guarded; authenticated acceptance separate)\n' "$DEPLOY_SHA" "$image"
|
||||
# Exercise the real consumer-to-Next route without resaving any article.
|
||||
for attempt in {1..30}; do
|
||||
if timeout --foreground --kill-after=2s 15 docker exec canino_backend_stage node -e '
|
||||
const {RevalidationService}=require("./dist/common/revalidation/revalidation.service");
|
||||
(async()=>{const s=new RevalidationService(); for(const tag of ["blogs","home-data","blog-senior-dog-l-carnitine-myocardial-energy-evidence"]) if(!await s.revalidateTag(tag)) process.exit(1); for(const path of ["/blog","/blog/senior-dog-l-carnitine-myocardial-energy-evidence"]) if(!await s.revalidatePath(path)) process.exit(1);})().catch(()=>process.exit(1));'; then break; fi
|
||||
[[ $attempt != 30 ]] || exit 1
|
||||
sleep 2
|
||||
done
|
||||
[[ $(docker inspect -f '{{index .Config.Labels "ir.canina.release.sha"}}' canino_frontend_stage) == "$DEPLOY_SHA" ]]
|
||||
frontend_image=$(docker inspect -f '{{.Image}}' canino_frontend_stage)
|
||||
[[ $(docker image inspect -f '{{index .Config.Labels "org.opencontainers.image.revision"}}' "$frontend_image") == "$DEPLOY_SHA" ]]
|
||||
printf 'Stage blog/corporate release complete: %s backend=%s frontend=%s\n' "$DEPLOY_SHA" "$image" "$frontend_image"
|
||||
}
|
||||
supervise_release release_stage
|
||||
@@ -0,0 +1,4 @@
|
||||
# Plan and diagnosis
|
||||
Active failure: backend create-time revalidation at 05:41:53Z returned Nest 404 for every tag/path. Runtime FRONTEND_INTERNAL_URL absent; FRONTEND_URL=https://stage.canina.ir routes /api to Nest. Both runtime secrets present. Fix Stage backend environment in the official code-only release override to frontend_stage:3000, not generic public FRONTEND_URL. Preserve operational Compose/env files. Extend existing serialized CI to build/recreate only backend/frontend from immutable source; reuse live admin artifacts in a build stage to avoid unrelated admin build. Compare secrets privately before deployment and invoke authorized cache-only existing-record invalidation through backend RevalidationService after readiness.
|
||||
Metadata removes config fallback and explicitly empty social arrays; body-only link rule. RED/GREEN focused regressions before release. No schema operations.
|
||||
Graph SHA256 6a73473cee9e207543fdeeb668bea544f766200a1b16b8a3a9ce18d4e42e51af queried at base 85ef01d3; binding unknown and locations stale, navigation only. Direct source confirms admin BlogsService -> RevalidationService -> Next handler; blog route -> metadata/JSONLD/BlogPostClient. No corporate source changes.
|
||||
@@ -0,0 +1,3 @@
|
||||
# Stage publication repair
|
||||
Preserve existing article 97b81659-4496-4fcc-9bbc-2403150e84ae and all corporate restoration contracts from 85ef01d33782eb422d5eb80fb531bb0b2ae2b08e. No article writes, duplicates, Production, schema, schedules or model changes.
|
||||
Acceptance: existing slug appears in settled /blog; empty article image fields produce no unrelated OG/Twitter/Article image; authored images retain precedence; body links are blue, bold and underlined. Stage antiindex remains intact. Exact pushed develop SHA must pass official CI and match both running images.
|
||||
@@ -0,0 +1,6 @@
|
||||
# Tasks
|
||||
1. Record sanitized runtime routing failure and inspect dependency scope (done).
|
||||
2. Run focused RED regression for media absence, body links and tracked Stage routing (pending).
|
||||
3. Apply smallest route metadata/CSS and official Stage-only CI override (pending).
|
||||
4. Run focused GREEN, typecheck and release-script tests (pending).
|
||||
5. Commit/push develop; verify official terminal CI, immutable image parity and public existing-record acceptance (pending).
|
||||
Reference in new issue
Block a user