Skip to content

Commit fa7b00f

Browse files
committed
feat(template): optimize template API with README cache and env control
1 parent eb7d152 commit fa7b00f

File tree

4 files changed

+74
-13
lines changed

4 files changed

+74
-13
lines changed

frontend/providers/template/src/pages/api/getTemplateSource.ts

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,21 +16,22 @@ import { replaceRawWithCDN } from './listTemplate';
1616
import { getTemplateEnvs } from '@/utils/tools';
1717
import { getResourceUsage, ResourceUsage } from '@/utils/usage';
1818
import { generateYamlData, getTemplateDefaultValues } from '@/utils/template';
19+
import { readmeCache } from '@/utils/readmeCache';
1920

2021
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
2122
try {
22-
const {
23-
templateName,
24-
locale = 'en',
25-
includeReadme = 'true'
26-
} = req.query as {
23+
const envEnableReadme = process.env.ENABLE_README_FETCH;
24+
const queryIncludeReadme = req.query.includeReadme !== 'false';
25+
26+
const includeReadme =
27+
envEnableReadme === 'false' ? 'false' : queryIncludeReadme ? 'true' : 'true';
28+
29+
const { templateName, locale = 'en' } = req.query as {
2730
templateName: string;
2831
locale: string;
29-
includeReadme: string;
3032
};
3133

3234
let user_namespace = '';
33-
3435
try {
3536
const { namespace } = await getK8s({
3637
kubeconfig: await authSession(req.headers)
@@ -109,7 +110,7 @@ export async function GetTemplateByName({
109110
namespace,
110111
templateName,
111112
locale = 'en',
112-
includeReadme = 'true'
113+
includeReadme = 'false'
113114
}: {
114115
namespace: string;
115116
templateName: string;
@@ -123,7 +124,7 @@ export async function GetTemplateByName({
123124

124125
const originalPath = process.cwd();
125126
const targetPath = path.resolve(originalPath, 'templates', targetFolder);
126-
// Query by file name in template details
127+
127128
const jsonPath = path.resolve(originalPath, 'templates.json');
128129
const jsonData: TemplateType[] = JSON.parse(fs.readFileSync(jsonPath, 'utf8'));
129130
const _tempalte = jsonData.find((item) => item.metadata.name === templateName);
@@ -133,13 +134,15 @@ export async function GetTemplateByName({
133134
: fs.readFileSync(`${targetPath}/${_tempalteName}`, 'utf-8');
134135

135136
let { appYaml, templateYaml } = getYamlTemplate(yamlString);
137+
136138
if (!templateYaml) {
137139
return {
138140
code: 40000,
139141
message: 'Lack of kind template'
140142
};
141143
}
142144
templateYaml.spec.deployCount = _tempalte?.spec?.deployCount;
145+
143146
if (cdnUrl) {
144147
templateYaml.spec.readme = replaceRawWithCDN(templateYaml.spec.readme, cdnUrl);
145148
templateYaml.spec.icon = replaceRawWithCDN(templateYaml.spec.icon, cdnUrl);
@@ -158,7 +161,6 @@ export async function GetTemplateByName({
158161
templateYaml = parseTemplateVariable(templateYaml, TemplateEnvs);
159162
const dataSource = getTemplateDataSource(templateYaml);
160163

161-
// Convert template to instance
162164
const instanceName = dataSource?.defaults?.['app_name']?.value;
163165
if (!instanceName) {
164166
return {
@@ -172,7 +174,7 @@ export async function GetTemplateByName({
172174
let readmeContent = '';
173175
let readUrl = '';
174176

175-
if (includeReadme) {
177+
if (includeReadme === 'true') {
176178
readUrl = templateYaml?.spec?.i18n?.[locale]?.readme || templateYaml?.spec?.readme || '';
177179
if (readUrl) {
178180
try {
@@ -198,6 +200,11 @@ export async function GetTemplateByName({
198200
async function fetchReadmeContentWithRetry(url: string): Promise<string> {
199201
if (!url) return '';
200202

203+
const cachedContent = readmeCache.get(url);
204+
if (cachedContent !== null) {
205+
return cachedContent;
206+
}
207+
201208
let retryCount = 0;
202209
const maxRetries = 3;
203210

@@ -218,7 +225,9 @@ async function fetchReadmeContentWithRetry(url: string): Promise<string> {
218225
throw new Error(`HTTP error! status: ${response.status}`);
219226
}
220227

221-
return await response.text();
228+
const content = await response.text();
229+
readmeCache.set(url, content);
230+
return content;
222231
} catch (err) {
223232
retryCount++;
224233
if (retryCount === maxRetries) {
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
class ReadmeCache {
2+
private cache: Map<string, string>;
3+
private readonly maxSize: number;
4+
5+
constructor(maxSize: number = 10) {
6+
this.cache = new Map();
7+
this.maxSize = maxSize;
8+
}
9+
10+
get(url: string): string | null {
11+
if (!url) return null;
12+
13+
const content = this.cache.get(url);
14+
if (content !== undefined) {
15+
this.cache.delete(url);
16+
this.cache.set(url, content);
17+
return content;
18+
}
19+
return null;
20+
}
21+
22+
set(url: string, content: string): void {
23+
if (!url || !content) return;
24+
25+
if (this.cache.has(url)) {
26+
this.cache.delete(url);
27+
} else if (this.cache.size >= this.maxSize) {
28+
const firstKey = this.cache.keys().next().value;
29+
if (firstKey) {
30+
this.cache.delete(firstKey);
31+
}
32+
}
33+
34+
this.cache.set(url, content);
35+
}
36+
37+
clear(): void {
38+
this.cache.clear();
39+
}
40+
41+
size(): number {
42+
return this.cache.size;
43+
}
44+
}
45+
46+
export const readmeCache = new ReadmeCache(10);

frontend/providers/template/src/utils/template.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,10 @@ export const generateYamlData = (
5151
isDevelop: boolean = false
5252
): YamlItemType[] => {
5353
if (!templateSource) return [];
54+
5455
const app_name = templateSource?.source?.defaults?.app_name?.value;
5556
const { defaults, defaultInputs } = getTemplateValues(templateSource);
57+
5658
const data = {
5759
...platformEnvs,
5860
...templateSource?.source,
@@ -62,6 +64,7 @@ export const generateYamlData = (
6264
},
6365
defaults: defaults
6466
};
67+
6568
const generateStr = parseTemplateString(templateSource.appYaml, data);
6669

6770
return isDevelop

frontend/providers/template/src/utils/usage.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,11 @@ export function getResourceUsage(yamlList: string[]): ResourceUsage {
1818
let totalNodeport = 0;
1919

2020
for (const yaml of yamlList) {
21-
for (const yamlObj of JsYaml.loadAll(yaml)) {
21+
const yamlObjs = JsYaml.loadAll(yaml);
22+
23+
for (const yamlObj of yamlObjs) {
2224
const resource = parseResourceUsage(yamlObj);
25+
2326
totalCpuMin += resource.cpu.min;
2427
totalCpuMax += resource.cpu.max;
2528
totalMemoryMin += resource.memory.min;

0 commit comments

Comments
 (0)