Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

improvements: address feedback

Scott Wilson64e0f849e699
diff --git a/backend/scripts/bake-announcements.ts b/backend/scripts/bake-announcements.ts
index 4fae4621d5..96f01fd0db 100644
--- a/backend/scripts/bake-announcements.ts
+++ b/backend/scripts/bake-announcements.ts
@@ -54,7 +54,11 @@ async function downloadAsset(url: string, assetId: string): Promise<{ filename:
}
const buf = Buffer.from(await res.arrayBuffer());
const hash = crypto.createHash("sha256").update(buf).digest("hex").slice(0, 16);
- const ext = path.extname(new URL(url).pathname).toLowerCase() || ".bin";
+ const ext = path.extname(new URL(url).pathname).toLowerCase();
+ if (!ext) {
+ console.warn(`[bake-announcements] skipping ${url}: no file extension`);
+ return null;
+ }
const filename = `${hash}${ext}`;
await fs.writeFile(path.join(IMAGE_DIR, filename), buf);
console.log(`[bake-announcements] asset ${assetId} -> ${filename} (${buf.length} bytes)`);
@@ -92,10 +96,12 @@ async function main() {
}
const downloaded = new Map<string, string>(); // assetId -> local filename
- for (const [assetId, remoteUrl] of assetMap) {
- const result = await downloadAsset(remoteUrl, assetId);
- if (result) downloaded.set(assetId, result.filename);
- }
+ await Promise.all(
+ Array.from(assetMap, async ([assetId, remoteUrl]) => {
+ const result = await downloadAsset(remoteUrl, assetId);
+ if (result) downloaded.set(assetId, result.filename);
+ })
+ );
const announcements = data.items.flatMap((entry) => {
if (!entry?.fields?.title || !entry.fields.body || !entry.fields.published) return [];
diff --git a/backend/src/services/announcement/announcement-service.ts b/backend/src/services/announcement/announcement-service.ts
index b43660d058..3484b6a157 100644
--- a/backend/src/services/announcement/announcement-service.ts
+++ b/backend/src/services/announcement/announcement-service.ts
@@ -4,9 +4,9 @@ import path from "node:path";
import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
import { withCache } from "@app/lib/cache/with-cache";
import { getConfig } from "@app/lib/config/env";
-import { request } from "@app/lib/config/request";
import { NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
+import { safeRequest } from "@app/lib/validator";
import { TUserDALFactory } from "@app/services/user/user-dal";
import { TAnnouncement, TContentfulEntriesResponse } from "./announcement-types";
@@ -14,6 +14,9 @@ import { TAnnouncement, TContentfulEntriesResponse } from "./announcement-types"
const CONTENT_TYPE = "featureUpdate";
const RECENT_LIMIT = 5;
const CACHE_TTL_SECONDS = 60 * 60;
+// Shorter TTL for empty results so a Contentful outage doesn't lock /recent
+// into "empty" for the full hour after recovery.
+const NEGATIVE_CACHE_TTL_SECONDS = 5 * 60;
// New users get a 7-day grace period before any announcements surface — avoids
// hitting them with marketing modals during onboarding.
const NEW_USER_GRACE_PERIOD_MS = 7 * 24 * 60 * 60 * 1000;
@@ -34,28 +37,32 @@ export type TAnnouncementServiceFactory = ReturnType<typeof announcementServiceF
export const announcementServiceFactory = ({ userDAL, keyStore }: TAnnouncementServiceFactoryDep) => {
let hasLoggedFetchError = false;
- // null = not yet checked, [] = no bundle present, [...] = bundled announcements
- let bundled: TAnnouncement[] | null = null;
- let bundleChecked = false;
-
- const loadBundled = async (): Promise<TAnnouncement[] | null> => {
- if (bundleChecked) return bundled;
- bundleChecked = true;
- try {
- const raw = await fs.readFile(BUNDLED_JSON_PATH, "utf8");
- bundled = JSON.parse(raw) as TAnnouncement[];
- logger.info(
- `Loaded ${bundled.length} bundled announcement(s) from ${BUNDLED_JSON_PATH} — Contentful fetches disabled`
- );
- return bundled;
- } catch (err) {
- const { code } = err as NodeJS.ErrnoException;
- if (code !== "ENOENT") {
- logger.warn({ err }, `Failed to read bundled announcements at ${BUNDLED_JSON_PATH}`);
+ // Single-flight promise: bundled JSON is read at most once per process lifetime,
+ // and concurrent first callers await the same load (avoids a check-then-set race
+ // where a request entering during the fs.readFile yield would otherwise see a
+ // half-initialized `null` and fall through to Contentful).
+ // To swap the bundled JSON in a self-hosted deployment, restart the backend.
+ let bundlePromise: Promise<TAnnouncement[] | null> | null = null;
+
+ const loadBundled = (): Promise<TAnnouncement[] | null> => {
+ if (bundlePromise) return bundlePromise;
+ bundlePromise = (async () => {
+ try {
+ const raw = await fs.readFile(BUNDLED_JSON_PATH, "utf8");
+ const parsed = JSON.parse(raw) as TAnnouncement[];
+ logger.info(
+ `Loaded ${parsed.length} bundled announcement(s) from ${BUNDLED_JSON_PATH} — Contentful fetches disabled`
+ );
+ return parsed;
+ } catch (err) {
+ const { code } = err as NodeJS.ErrnoException;
+ if (code !== "ENOENT") {
+ logger.warn({ err }, `Failed to read bundled announcements at ${BUNDLED_JSON_PATH}`);
+ }
+ return null;
}
- bundled = null;
- return null;
- }
+ })();
+ return bundlePromise;
};
const fetchRecent = async (): Promise<TAnnouncement[]> => {
@@ -67,45 +74,61 @@ export const announcementServiceFactory = ({ userDAL, keyStore }: TAnnouncementS
const url = `https://cdn.contentful.com/spaces/${appCfg.CONTENTFUL_SPACE_ID}/environments/${appCfg.CONTENTFUL_ENVIRONMENT}/entries`;
- const { data } = await request.get<TContentfulEntriesResponse>(url, {
- params: {
- content_type: CONTENT_TYPE,
- order: "-fields.published",
- limit: RECENT_LIMIT,
- include: 1
- },
- headers: {
- Authorization: `Bearer ${appCfg.CONTENTFUL_DELIVERY_TOKEN}`
- },
- timeout: 5000
- });
+ try {
+ const { data } = await safeRequest.get<TContentfulEntriesResponse>(url, {
+ params: {
+ content_type: CONTENT_TYPE,
+ order: "-fields.published",
+ limit: RECENT_LIMIT,
+ include: 1
+ },
+ headers: {
+ Authorization: `Bearer ${appCfg.CONTENTFUL_DELIVERY_TOKEN}`
+ },
+ timeout: 5000
+ });
- const assetById = new Map<string, string>();
- for (const asset of data.includes?.Asset ?? []) {
- const fileUrl = asset.fields?.file?.url;
- if (fileUrl) {
- assetById.set(asset.sys.id, fileUrl.startsWith("//") ? `https:${fileUrl}` : fileUrl);
- }
- }
+ hasLoggedFetchError = false;
- return data.items.flatMap<TAnnouncement>((entry) => {
- if (!entry?.fields?.title || !entry.fields.body || !entry.fields.published) return [];
-
- const imageAssetId = entry.fields.image?.sys?.id;
- const imageUrl = imageAssetId ? (assetById.get(imageAssetId) ?? null) : null;
-
- return [
- {
- id: entry.sys.id,
- title: entry.fields.title,
- body: entry.fields.body,
- imageUrl,
- link: entry.fields.link ?? null,
- linkLabel: entry.fields.linkLabel ?? null,
- published: entry.fields.published
+ const assetById = new Map<string, string>();
+ for (const asset of data.includes?.Asset ?? []) {
+ const fileUrl = asset.fields?.file?.url;
+ if (fileUrl) {
+ assetById.set(asset.sys.id, fileUrl.startsWith("//") ? `https:${fileUrl}` : fileUrl);
}
- ];
- });
+ }
+
+ return data.items.flatMap<TAnnouncement>((entry) => {
+ if (!entry?.fields?.title || !entry.fields.body || !entry.fields.published) return [];
+
+ const imageAssetId = entry.fields.image?.sys?.id;
+ const imageUrl = imageAssetId ? (assetById.get(imageAssetId) ?? null) : null;
+
+ return [
+ {
+ id: entry.sys.id,
+ title: entry.fields.title,
+ body: entry.fields.body,
+ imageUrl,
+ link: entry.fields.link ?? null,
+ linkLabel: entry.fields.linkLabel ?? null,
+ published: entry.fields.published
+ }
+ ];
+ });
+ } catch (err) {
+ // Returning [] (instead of throwing) lets withCache write a negative entry,
+ // so a Contentful outage doesn't trigger a fresh 4-attempt axios-retry burst
+ // on every /recent request for the duration of the outage.
+ if (!hasLoggedFetchError) {
+ logger.warn(
+ { err },
+ "Failed to fetch announcements — returning empty list (will retry after negative-cache TTL)"
+ );
+ hasLoggedFetchError = true;
+ }
+ return [];
+ }
};
const getAnnouncements = async (): Promise<TAnnouncement[]> => {
@@ -118,7 +141,7 @@ export const announcementServiceFactory = ({ userDAL, keyStore }: TAnnouncementS
return withCache({
keyStore,
key: KeyStorePrefixes.RecentAnnouncements,
- ttlSeconds: CACHE_TTL_SECONDS,
+ ttlSeconds: (result) => (result.length === 0 ? NEGATIVE_CACHE_TTL_SECONDS : CACHE_TTL_SECONDS),
fetcher: fetchRecent
});
};
@@ -135,17 +158,8 @@ export const announcementServiceFactory = ({ userDAL, keyStore }: TAnnouncementS
return { announcements: [], lastSeenAnnouncementId };
}
- try {
- const announcements = await getAnnouncements();
- hasLoggedFetchError = false;
- return { announcements, lastSeenAnnouncementId };
- } catch (err) {
- if (!hasLoggedFetchError) {
- logger.warn({ err }, "Failed to fetch announcements — feature will be hidden until next attempt");
- hasLoggedFetchError = true;
- }
- return { announcements: [], lastSeenAnnouncementId };
- }
+ const announcements = await getAnnouncements();
+ return { announcements, lastSeenAnnouncementId };
};
const markAnnouncementSeen = async ({ userId, announcementId }: { userId: string; announcementId: string }) => {
diff --git a/frontend/src/components/announcements/AnnouncementModal.tsx b/frontend/src/components/announcements/AnnouncementModal.tsx
index 11c020cbe9..9d22c4ee8b 100644
--- a/frontend/src/components/announcements/AnnouncementModal.tsx
+++ b/frontend/src/components/announcements/AnnouncementModal.tsx
@@ -36,14 +36,15 @@ export const AnnouncementModal = ({ announcements, isOpen, onOpenChange }: Props
if (isOpen) setIndex(0);
}, [isOpen]);
- const announcement = announcements[index];
+ const total = announcements.length;
+ const safeIndex = Math.min(index, total - 1);
+ const announcement = announcements[safeIndex];
if (!announcement) return null;
const ctaLabel = announcement.linkLabel || (announcement.link ? "Learn more" : null);
const publishedLabel = formatPublished(announcement.published);
- const total = announcements.length;
- const hasPrev = index > 0;
- const hasNext = index < total - 1;
+ const hasPrev = safeIndex > 0;
+ const hasNext = safeIndex < total - 1;
const showPager = total > 1;
return (
@@ -92,19 +93,19 @@ export const AnnouncementModal = ({ announcements, isOpen, onOpenChange }: Props
variant="ghost"
size="xs"
aria-label="Previous announcement"
- onClick={() => setIndex((i) => Math.max(0, i - 1))}
+ onClick={() => setIndex(Math.max(0, safeIndex - 1))}
isDisabled={!hasPrev}
>
<ChevronLeft />
</IconButton>
<span className="tabular-nums">
- {index + 1} / {total}
+ {safeIndex + 1} / {total}
</span>
<IconButton
variant="ghost"
size="xs"
aria-label="Next announcement"
- onClick={() => setIndex((i) => Math.min(total - 1, i + 1))}
+ onClick={() => setIndex(Math.min(total - 1, safeIndex + 1))}
isDisabled={!hasNext}
>
<ChevronRight />
diff --git a/frontend/src/hooks/api/announcement/queries.tsx b/frontend/src/hooks/api/announcement/queries.tsx
index 4ecc87cf0d..bec378b140 100644
--- a/frontend/src/hooks/api/announcement/queries.tsx
+++ b/frontend/src/hooks/api/announcement/queries.tsx
@@ -9,7 +9,7 @@ export const announcementKeys = {
recent: () => [...announcementKeys.all, "recent"] as const
};
-export const useGetRecentAnnouncements = (enabled = true) => {
+export const useGetRecentAnnouncements = () => {
return useQuery({
queryKey: announcementKeys.recent(),
queryFn: async () => {
@@ -22,7 +22,6 @@ export const useGetRecentAnnouncements = (enabled = true) => {
// the user picks it up on the next hard reload or new tab.
staleTime: Infinity,
refetchOnMount: false,
- refetchOnReconnect: false,
- enabled
+ refetchOnReconnect: false
});
};
diff --git a/frontend/src/pages/organization/ProjectsPage/ProjectsPage.tsx b/frontend/src/pages/organization/ProjectsPage/ProjectsPage.tsx
index 21b5224201..3b2242206b 100644
--- a/frontend/src/pages/organization/ProjectsPage/ProjectsPage.tsx
+++ b/frontend/src/pages/organization/ProjectsPage/ProjectsPage.tsx
@@ -55,17 +55,17 @@ export const ProjectsPage = () => {
"upgradePlan"
] as const);
- const { data: announcementData } = useGetRecentAnnouncements(!hasChildRoute);
+ const { data: announcementData } = useGetRecentAnnouncements();
const announcements = announcementData?.announcements;
const latestAnnouncement = announcements?.[0];
const { hasUnseen, markSeen } = useAnnouncementSeen();
const [isAnnouncementOpen, setIsAnnouncementOpen] = useState(false);
+ const shouldAutoOpen = Boolean(latestAnnouncement && hasUnseen(latestAnnouncement.id));
+
useEffect(() => {
- if (latestAnnouncement && hasUnseen(latestAnnouncement.id)) {
- setIsAnnouncementOpen(true);
- }
- }, [latestAnnouncement?.id]);
+ if (shouldAutoOpen) setIsAnnouncementOpen(true);
+ }, [shouldAutoOpen]);
const handleAnnouncementOpenChange = (open: boolean) => {
setIsAnnouncementOpen(open);