jskelet 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,595 @@
1
+ /**
2
+ * Cloudflare'in cache yüzeyi: purge, zone ayarları ve cache analitiği.
3
+ *
4
+ * Neden framework'te: JSkelet'in önbelleği **origin** önbelleği. Bir içerik
5
+ * güncellendiğinde `invalidateHtmlCache()` origin'i tazeliyor ama CDN'de duran
6
+ * kopya TTL'ini bekliyor; ziyaretçinin gördüğü HTML orada. İki katmanı ayrı
7
+ * ayrı yönetmek, purge'ü unutulan bir katman bırakıyor.
8
+ *
9
+ * ## Ne yapılabilir, ne yapılamaz
10
+ *
11
+ * Cloudflare API'sinin **verdiği** şeyler burada var: `purge_everything`, URL /
12
+ * prefix / host / cache-tag ile hedefli purge, cache ile ilgili zone ayarları
13
+ * (cache level, browser TTL, development mode, tiered cache, cache reserve) ve
14
+ * GraphQL analitiğinden cache durumu kırılımı.
15
+ *
16
+ * **Vermediği** iki şey var ve panelde de bu böyle yazıyor:
17
+ *
18
+ * 1. "Şu URL şu an kaç edge'de duruyor" sorusunun cevabı yok. Cloudflare
19
+ * yüzlerce şehirde bağımsız önbellekler tutuyor ve hiçbir uç bir objenin
20
+ * envanterini vermiyor. En yakın cevap **gözlem**: GraphQL'de son N saatte
21
+ * hangi kolodan kaç `hit`/`miss` geldiği. `fetchPathEdges()` bunu döner —
22
+ * "kaç edge'de var" değil, "kaç edge o yolu cache'ten servis etti".
23
+ * 2. Bir edge'i uzaktan ısıtmanın yolu yok. Bir obje ancak o koloya düşen
24
+ * gerçek bir istekle cache'e giriyor; sunucudan seçtiğiniz bir şehri
25
+ * ısıtamazsınız. Pratik karşılığı origin'i ısıtmak (`prewarm`) ve
26
+ * Tiered Cache / Cache Reserve açmak: ilk istek yine o edge'e gidiyor ama
27
+ * arkadaki katman origin'e kadar inmiyor.
28
+ *
29
+ * Sözleşme: bu modüldeki hiçbir fonksiyon fırlatmaz. Token yoksa, ağ düşerse
30
+ * ya da Cloudflare hata dönerse sonuç `{ ok: false, error }` olur ve panel
31
+ * bunu gösterir. Token hiçbir dönüş değerinde yer almaz.
32
+ */
33
+ import process from "node:process";
34
+ import { getConfig } from "../config/index.js";
35
+ import { DEFAULT_CLOUDFLARE } from "../config/defaults.js";
36
+
37
+ const API = "https://api.cloudflare.com/client/v4";
38
+ const GRAPHQL = "https://api.cloudflare.com/client/v4/graphql";
39
+
40
+ /**
41
+ * Tek bir çağrının en fazla bekletebileceği süre. Panel bir teşhis aracı;
42
+ * Cloudflare yavaşladığında sayfayı süresiz açık tutmasın.
43
+ */
44
+ const TIMEOUT_MS = 8000;
45
+
46
+ /**
47
+ * Purge isteğinde tek seferde gönderilebilecek anahtar sayısı. Cloudflare'in
48
+ * sınırı istek başına 100 (Enterprise'da tek dosya purge'ünde 500); en düşük
49
+ * ortak değeri kullanmak her planda çalışan tek davranış.
50
+ */
51
+ const PURGE_BATCH = 100;
52
+
53
+ /** Genel bakış birkaç uca gidiyor; panel her açılışta hepsini yenilemesin. */
54
+ const OVERVIEW_TTL_MS = 30_000;
55
+
56
+ /** @type {{ at: number, value: object } | null} */
57
+ let overviewCache = null;
58
+
59
+ /**
60
+ * Etkin ayarlar. Token **config'ten ya da env'den** okunur; env öncelikli,
61
+ * çünkü sır config dosyasına yazılmamalı.
62
+ *
63
+ * @returns {{ configured: boolean, zoneId: string | null,
64
+ * token: string | null, source: "env" | "config" | null,
65
+ * hostname: string | null, analyticsHours: number, enabled: boolean }}
66
+ */
67
+ function settings() {
68
+ /** @type {Record<string, any>} */
69
+ let configured = {};
70
+ try {
71
+ configured = getConfig().cloudflare ?? {};
72
+ } catch {
73
+ configured = { ...DEFAULT_CLOUDFLARE };
74
+ }
75
+
76
+ const envToken = process.env.JSKELET_CLOUDFLARE_KEY || null;
77
+ const token = envToken ?? configured.apiToken ?? null;
78
+ const zoneId =
79
+ process.env.JSKELET_CLOUDFLARE_ZONE_ID || configured.zoneId || null;
80
+ const hostname =
81
+ process.env.JSKELET_CLOUDFLARE_HOSTNAME || configured.hostname || null;
82
+
83
+ const enabled = configured.enabled !== false;
84
+
85
+ return {
86
+ enabled,
87
+ zoneId,
88
+ token,
89
+ source: token ? (envToken ? "env" : "config") : null,
90
+ hostname,
91
+ analyticsHours: Number(configured.analyticsHours) || DEFAULT_CLOUDFLARE.analyticsHours,
92
+ // Zone kimliği olmadan hiçbir uç çağrılamaz; ikisi birlikte "kurulu"
93
+ // sayılmanın koşulu.
94
+ configured: enabled && Boolean(token && zoneId),
95
+ };
96
+ }
97
+
98
+ /** @returns {boolean} */
99
+ export function cloudflareConfigured() {
100
+ return settings().configured;
101
+ }
102
+
103
+ /**
104
+ * Panelin gösterdiği kurulum özeti. Token'ın kendisi değil, **nereden
105
+ * geldiği** döner.
106
+ *
107
+ * @returns {{ configured: boolean, enabled: boolean, zoneId: string | null,
108
+ * tokenSource: "env" | "config" | null, hostname: string | null }}
109
+ */
110
+ export function getCloudflareStatus() {
111
+ const config = settings();
112
+
113
+ return {
114
+ configured: config.configured,
115
+ enabled: config.enabled,
116
+ // Zone kimliği sır değil (URL'lerde de geçiyor) ama tamamını basmanın da
117
+ // faydası yok; son dört hane hangi zone'a bağlı olduğunu doğrulamaya yeter.
118
+ zoneId: config.zoneId ? `…${config.zoneId.slice(-4)}` : null,
119
+ tokenSource: config.source,
120
+ hostname: config.hostname,
121
+ };
122
+ }
123
+
124
+ /**
125
+ * Cloudflare REST çağrısı. Hata **fırlatılmaz**: teşhis ucu bir arıza anında
126
+ * çağrılıyor ve Cloudflare'in 403'ü paneli düşürmemeli.
127
+ *
128
+ * @param {string} path
129
+ * @param {{ method?: string, body?: unknown }} [options]
130
+ * @returns {Promise<{ ok: boolean, result?: any, error?: string }>}
131
+ */
132
+ async function call(path, options = {}) {
133
+ const config = settings();
134
+ if (!config.configured) return { ok: false, error: "Cloudflare is not configured" };
135
+
136
+ try {
137
+ const response = await fetch(`${API}/zones/${config.zoneId}${path}`, {
138
+ method: options.method ?? "GET",
139
+ headers: {
140
+ Authorization: `Bearer ${config.token}`,
141
+ "Content-Type": "application/json",
142
+ },
143
+ body: options.body === undefined ? undefined : JSON.stringify(options.body),
144
+ signal: AbortSignal.timeout(TIMEOUT_MS),
145
+ });
146
+
147
+ const payload = await response.json().catch(() => null);
148
+
149
+ if (!response.ok || payload?.success === false) {
150
+ return { ok: false, error: describe(payload, response.status) };
151
+ }
152
+
153
+ return { ok: true, result: payload?.result };
154
+ } catch (error) {
155
+ return { ok: false, error: reason(error) };
156
+ }
157
+ }
158
+
159
+ /**
160
+ * @param {any} payload
161
+ * @param {number} status
162
+ * @returns {string}
163
+ */
164
+ function describe(payload, status) {
165
+ const first = Array.isArray(payload?.errors) ? payload.errors[0] : null;
166
+ if (first?.message) {
167
+ // Kod da yazılır: 10000 (yetki) ile 1012 (geçersiz zone) çok farklı iki
168
+ // düzeltme demek ve mesajlar birbirine benziyor.
169
+ return first.code ? `${first.message} (${first.code})` : String(first.message);
170
+ }
171
+ return `HTTP ${status}`;
172
+ }
173
+
174
+ /**
175
+ * @param {unknown} error
176
+ * @returns {string}
177
+ */
178
+ function reason(error) {
179
+ if (error instanceof Error) {
180
+ return error.name === "TimeoutError" ? `timed out after ${TIMEOUT_MS}ms` : error.message;
181
+ }
182
+ return String(error);
183
+ }
184
+
185
+ /* --------------------------------------------------------------- genel bakış */
186
+
187
+ /**
188
+ * Zone künyesi + cache ile ilgili ayarlar.
189
+ *
190
+ * Ayarlar tek tek değil, tek `GET /settings` turuyla okunur ve ilgili olanlar
191
+ * ayıklanır. Tiered Cache ve Cache Reserve ayrı uçlarda yaşıyor; ikisi de
192
+ * planla sınırlı olduğu için hataları **yok sayılır**, yalnızca `null` olurlar
193
+ * — Free bir zone'da panel yine açılmalı.
194
+ *
195
+ * @param {{ force?: boolean }} [options]
196
+ * @returns {Promise<object>}
197
+ */
198
+ export async function fetchCloudflareOverview(options = {}) {
199
+ const config = settings();
200
+ if (!config.configured) {
201
+ return { ok: false, status: getCloudflareStatus(), error: "not configured" };
202
+ }
203
+
204
+ if (!options.force && overviewCache && Date.now() - overviewCache.at < OVERVIEW_TTL_MS) {
205
+ return overviewCache.value;
206
+ }
207
+
208
+ const [zone, zoneSettings, tiered, reserve, regional] = await Promise.all([
209
+ call(""),
210
+ call("/settings"),
211
+ call("/argo/tiered_caching"),
212
+ call("/cache/cache_reserve"),
213
+ call("/cache/regional_tiered_cache"),
214
+ ]);
215
+
216
+ if (!zone.ok && !zoneSettings.ok) {
217
+ // İkisi de başarısızsa sorun tek bir uçta değil: token ya da zone yanlış.
218
+ const value = {
219
+ ok: false,
220
+ status: getCloudflareStatus(),
221
+ error: zone.error ?? zoneSettings.error,
222
+ };
223
+ overviewCache = { at: Date.now(), value };
224
+ return value;
225
+ }
226
+
227
+ const map = new Map(
228
+ (Array.isArray(zoneSettings.result) ? zoneSettings.result : []).map(
229
+ (/** @type {any} */ entry) => [entry.id, entry],
230
+ ),
231
+ );
232
+
233
+ /** @param {string} id */
234
+ const setting = (id) => map.get(id) ?? null;
235
+
236
+ const development = setting("development_mode");
237
+
238
+ const value = {
239
+ ok: true,
240
+ fetchedAt: Date.now(),
241
+ status: getCloudflareStatus(),
242
+ zone: zone.ok
243
+ ? {
244
+ name: zone.result?.name ?? null,
245
+ plan: zone.result?.plan?.name ?? null,
246
+ status: zone.result?.status ?? null,
247
+ paused: zone.result?.paused === true,
248
+ }
249
+ : null,
250
+ settings: {
251
+ cacheLevel: setting("cache_level")?.value ?? null,
252
+ browserCacheTtl: setting("browser_cache_ttl")?.value ?? null,
253
+ edgeCacheTtl: setting("edge_cache_ttl")?.value ?? null,
254
+ sortQueryString: setting("sort_query_string_for_cache")?.value ?? null,
255
+ alwaysOnline: setting("always_online")?.value ?? null,
256
+ developmentMode: development?.value ?? null,
257
+ // Development mode üç saat sonra kendiliğinden kapanıyor; kalan süre
258
+ // "neden hiçbir şey cache'lenmiyor" sorusunun en sık cevabı.
259
+ developmentModeRemaining: Number(development?.time_remaining) || 0,
260
+ tieredCaching: tiered.ok ? tiered.result?.value ?? null : null,
261
+ cacheReserve: reserve.ok ? reserve.result?.value ?? null : null,
262
+ regionalTieredCache: regional.ok ? regional.result?.value ?? null : null,
263
+ },
264
+ };
265
+
266
+ overviewCache = { at: Date.now(), value };
267
+ return value;
268
+ }
269
+
270
+ /* ------------------------------------------------------------------ analitik */
271
+
272
+ /**
273
+ * GraphQL sorgusu. Analitik ayrı bir uçta (`/graphql`) yaşadığı için `call()`
274
+ * kullanılmıyor.
275
+ *
276
+ * @param {string} query
277
+ * @param {Record<string, unknown>} variables
278
+ * @returns {Promise<{ ok: boolean, data?: any, error?: string }>}
279
+ */
280
+ async function graphql(query, variables) {
281
+ const config = settings();
282
+ if (!config.configured) return { ok: false, error: "Cloudflare is not configured" };
283
+
284
+ try {
285
+ const response = await fetch(GRAPHQL, {
286
+ method: "POST",
287
+ headers: {
288
+ Authorization: `Bearer ${config.token}`,
289
+ "Content-Type": "application/json",
290
+ },
291
+ body: JSON.stringify({ query, variables }),
292
+ signal: AbortSignal.timeout(TIMEOUT_MS),
293
+ });
294
+
295
+ const payload = await response.json().catch(() => null);
296
+ const error = Array.isArray(payload?.errors) ? payload.errors[0]?.message : null;
297
+
298
+ if (!response.ok || error) {
299
+ return { ok: false, error: error ?? `HTTP ${response.status}` };
300
+ }
301
+
302
+ return { ok: true, data: payload?.data };
303
+ } catch (error) {
304
+ return { ok: false, error: reason(error) };
305
+ }
306
+ }
307
+
308
+ /**
309
+ * @param {number} hours
310
+ * @returns {string} ISO zaman damgası
311
+ */
312
+ function since(hours) {
313
+ return new Date(Date.now() - hours * 3600_000).toISOString();
314
+ }
315
+
316
+ /**
317
+ * Zone'un cache durumu kırılımı: `hit`, `miss`, `dynamic`, `expired`… her biri
318
+ * için istek sayısı ve edge'den giden bayt.
319
+ *
320
+ * `httpRequestsAdaptiveGroups` bilinçli seçildi: `cacheStatus` boyutu eski
321
+ * `httpRequests1hGroups` veri kümesinde yok ve pek çok hesapta hata veriyor.
322
+ * Adaptive küme örnekleme kullanıyor, yani sayılar **tahmindir** — oranlar
323
+ * doğru, mutlak değerler yaklaşık.
324
+ *
325
+ * @param {{ hours?: number }} [options]
326
+ * @returns {Promise<{ ok: boolean, hours: number, sampled: boolean,
327
+ * rows: { status: string, requests: number, bytes: number }[],
328
+ * error?: string }>}
329
+ */
330
+ export async function fetchCacheAnalytics(options = {}) {
331
+ const config = settings();
332
+ const hours = Math.max(1, Math.min(72, options.hours ?? config.analyticsHours));
333
+
334
+ const query = `
335
+ query CacheStatus($zone: String!, $since: Time!) {
336
+ viewer {
337
+ zones(filter: { zoneTag: $zone }) {
338
+ httpRequestsAdaptiveGroups(
339
+ filter: { datetime_geq: $since }
340
+ limit: 50
341
+ orderBy: [count_DESC]
342
+ ) {
343
+ count
344
+ sum { edgeResponseBytes }
345
+ dimensions { cacheStatus }
346
+ }
347
+ }
348
+ }
349
+ }`;
350
+
351
+ const response = await graphql(query, { zone: config.zoneId, since: since(hours) });
352
+ if (!response.ok) return { ok: false, hours, sampled: true, rows: [], error: response.error };
353
+
354
+ const groups = response.data?.viewer?.zones?.[0]?.httpRequestsAdaptiveGroups ?? [];
355
+
356
+ return {
357
+ ok: true,
358
+ hours,
359
+ sampled: true,
360
+ rows: groups.map((/** @type {any} */ group) => ({
361
+ status: group.dimensions?.cacheStatus ?? "unknown",
362
+ requests: Number(group.count) || 0,
363
+ bytes: Number(group.sum?.edgeResponseBytes) || 0,
364
+ })),
365
+ };
366
+ }
367
+
368
+ /**
369
+ * Bir yolun **kolo bazında** cache kırılımı.
370
+ *
371
+ * Bu, "kaç edge'de bu sayfanın kopyası var" sorusunun API'nin verdiği en yakın
372
+ * cevabı: son `hours` saatte hangi Cloudflare şehri o yolu kaç kez cache'ten
373
+ * (`hit`) ya da origin'den (`miss`, `expired`, `dynamic`) servis etti. Envanter
374
+ * değil, gözlem — hiç istek almamış bir edge listede görünmez, kopyası olsa da.
375
+ *
376
+ * @param {{ path: string, hours?: number }} options
377
+ * @returns {Promise<{ ok: boolean, path: string, hours: number,
378
+ * colos: { colo: string, hits: number, misses: number }[],
379
+ * hits: number, misses: number, error?: string }>}
380
+ */
381
+ export async function fetchPathEdges({ path, hours }) {
382
+ const config = settings();
383
+ const window = Math.max(1, Math.min(72, hours ?? config.analyticsHours));
384
+
385
+ const query = `
386
+ query PathEdges($zone: String!, $since: Time!, $path: String!) {
387
+ viewer {
388
+ zones(filter: { zoneTag: $zone }) {
389
+ httpRequestsAdaptiveGroups(
390
+ filter: { datetime_geq: $since, clientRequestPath: $path }
391
+ limit: 500
392
+ orderBy: [count_DESC]
393
+ ) {
394
+ count
395
+ dimensions { coloCode cacheStatus }
396
+ }
397
+ }
398
+ }
399
+ }`;
400
+
401
+ const response = await graphql(query, {
402
+ zone: config.zoneId,
403
+ since: since(window),
404
+ path,
405
+ });
406
+
407
+ if (!response.ok) {
408
+ return { ok: false, path, hours: window, colos: [], hits: 0, misses: 0, error: response.error };
409
+ }
410
+
411
+ const groups = response.data?.viewer?.zones?.[0]?.httpRequestsAdaptiveGroups ?? [];
412
+
413
+ /** @type {Map<string, { colo: string, hits: number, misses: number }>} */
414
+ const colos = new Map();
415
+ let hits = 0;
416
+ let misses = 0;
417
+
418
+ for (const group of groups) {
419
+ const colo = group.dimensions?.coloCode ?? "??";
420
+ const status = String(group.dimensions?.cacheStatus ?? "");
421
+ const count = Number(group.count) || 0;
422
+
423
+ const entry = colos.get(colo) ?? { colo, hits: 0, misses: 0 };
424
+ // `hit` dışındaki her şey (miss, expired, dynamic, bypass) origin'e giden
425
+ // ya da hiç cache'lenmeyen istek; panelde tek kolonda toplanıyor.
426
+ if (status === "hit") {
427
+ entry.hits += count;
428
+ hits += count;
429
+ } else {
430
+ entry.misses += count;
431
+ misses += count;
432
+ }
433
+ colos.set(colo, entry);
434
+ }
435
+
436
+ return {
437
+ ok: true,
438
+ path,
439
+ hours: window,
440
+ hits,
441
+ misses,
442
+ colos: [...colos.values()].sort((a, b) => b.hits + b.misses - (a.hits + a.misses)),
443
+ };
444
+ }
445
+
446
+ /* --------------------------------------------------------------------- purge */
447
+
448
+ /**
449
+ * Cloudflare önbelleğini düşürür.
450
+ *
451
+ * Dört hedefleme biçimi de API'nin verdiği hâliyle: `files` (tam URL),
452
+ * `prefixes`, `hosts`, `tags`. Hepsi artık her planda çalışıyor ama istek
453
+ * başına en fazla 100 anahtar kabul ediliyor; uzun listeler burada parçalanır
454
+ * ve **sırayla** gönderilir — paralel göndermek Free planda dakikada beş
455
+ * istekle sınırlı olan hız freni yüzünden yarısı reddedilen bir tur demek.
456
+ *
457
+ * @param {{ everything?: boolean, files?: string[], prefixes?: string[],
458
+ * hosts?: string[], tags?: string[] }} target
459
+ * @returns {Promise<{ ok: boolean, purged: number, batches: number,
460
+ * error?: string }>}
461
+ */
462
+ export async function purgeCloudflare(target) {
463
+ if (target.everything) {
464
+ const response = await call("/purge_cache", {
465
+ method: "POST",
466
+ body: { purge_everything: true },
467
+ });
468
+ return { ok: response.ok, purged: 0, batches: 1, error: response.error };
469
+ }
470
+
471
+ /** @type {[string, string[]][]} */
472
+ const kinds = [
473
+ ["files", target.files ?? []],
474
+ ["prefixes", target.prefixes ?? []],
475
+ ["hosts", target.hosts ?? []],
476
+ ["tags", target.tags ?? []],
477
+ ];
478
+
479
+ let purged = 0;
480
+ let batches = 0;
481
+
482
+ for (const [kind, values] of kinds) {
483
+ const unique = [...new Set(values.filter((value) => typeof value === "string" && value))];
484
+
485
+ for (let index = 0; index < unique.length; index += PURGE_BATCH) {
486
+ const slice = unique.slice(index, index + PURGE_BATCH);
487
+ const response = await call("/purge_cache", {
488
+ method: "POST",
489
+ body: { [kind]: slice },
490
+ });
491
+
492
+ batches += 1;
493
+ if (!response.ok) return { ok: false, purged, batches, error: response.error };
494
+ purged += slice.length;
495
+ }
496
+ }
497
+
498
+ if (!batches) return { ok: false, purged: 0, batches: 0, error: "nothing to purge" };
499
+ return { ok: true, purged, batches };
500
+ }
501
+
502
+ /**
503
+ * Yolları tam URL'e çevirir. Cloudflare `files` purge'ü şemayı da içeren tam
504
+ * URL istiyor; panel elinde yol (`/haber/abc`) tutuyor.
505
+ *
506
+ * @param {string[]} paths
507
+ * @param {string} [fallbackOrigin] `cloudflare.hostname` verilmediğinde
508
+ * kullanılacak kök (panelin açıldığı origin).
509
+ * @returns {string[]}
510
+ */
511
+ export function toCloudflareUrls(paths, fallbackOrigin) {
512
+ // Yapılandırılmış site adı önce gelir: panel bir iç adresten (ör.
513
+ // `http://10.0.0.4:3000`) açılmış olabilir ve o adresin Cloudflare'de
514
+ // karşılığı yok.
515
+ const hostname = settings().hostname;
516
+ const base = hostname ? `https://${hostname}` : (fallbackOrigin ?? null);
517
+ if (!base) return [];
518
+
519
+ return paths
520
+ .map((path) => {
521
+ try {
522
+ return new URL(path, base).href;
523
+ } catch {
524
+ return null;
525
+ }
526
+ })
527
+ .filter((url) => url !== null);
528
+ }
529
+
530
+ /* ------------------------------------------------------------------- ayarlar */
531
+
532
+ /**
533
+ * Cache ile ilgili bir zone ayarını değiştirir.
534
+ *
535
+ * Yalnızca beyaz listedeki ayarlar: panelin işi cache, ve bir teşhis
536
+ * arayüzünden zone'un tamamını yeniden yapılandırılabilir yapmak gereksiz bir
537
+ * yüzey.
538
+ *
539
+ * @param {"development_mode" | "cache_level" | "browser_cache_ttl" |
540
+ * "always_online" | "sort_query_string_for_cache"} id
541
+ * @param {string | number} value
542
+ * @returns {Promise<{ ok: boolean, value?: unknown, error?: string }>}
543
+ */
544
+ export async function setCloudflareSetting(id, value) {
545
+ const allowed = new Set([
546
+ "development_mode",
547
+ "cache_level",
548
+ "browser_cache_ttl",
549
+ "always_online",
550
+ "sort_query_string_for_cache",
551
+ ]);
552
+
553
+ if (!allowed.has(id)) return { ok: false, error: `setting not allowed: ${id}` };
554
+
555
+ const response = await call(`/settings/${id}`, { method: "PATCH", body: { value } });
556
+ // Ayar değiştiyse önbelleğe alınmış genel bakış eskidi.
557
+ overviewCache = null;
558
+
559
+ return { ok: response.ok, value: response.result?.value, error: response.error };
560
+ }
561
+
562
+ /**
563
+ * Tiered Cache ya da Cache Reserve'ü açar/kapatır. İkisi de ayrı uçlarda ve
564
+ * planla sınırlı; kapalı bir planda Cloudflare açıklayıcı bir hata döner ve
565
+ * panel onu gösterir.
566
+ *
567
+ * @param {"tiered_caching" | "cache_reserve" | "regional_tiered_cache"} feature
568
+ * @param {"on" | "off"} value
569
+ * @returns {Promise<{ ok: boolean, error?: string }>}
570
+ */
571
+ export async function setCloudflareFeature(feature, value) {
572
+ const path =
573
+ feature === "tiered_caching"
574
+ ? "/argo/tiered_caching"
575
+ : feature === "cache_reserve"
576
+ ? "/cache/cache_reserve"
577
+ : "/cache/regional_tiered_cache";
578
+
579
+ const response = await call(path, { method: "PATCH", body: { value } });
580
+ overviewCache = null;
581
+
582
+ return { ok: response.ok, error: response.error };
583
+ }
584
+
585
+ /**
586
+ * Cache Reserve'ü (R2'deki kalıcı kopya) boşaltır. Purge'den ayrı bir işlem:
587
+ * `purge_everything` edge önbelleklerini düşürüyor, Cache Reserve'deki kopya
588
+ * kalıyor.
589
+ *
590
+ * @returns {Promise<{ ok: boolean, error?: string }>}
591
+ */
592
+ export async function clearCloudflareCacheReserve() {
593
+ const response = await call("/cache/cache_reserve_clear", { method: "POST" });
594
+ return { ok: response.ok, error: response.error };
595
+ }
@@ -11,6 +11,8 @@
11
11
  * 4. staticPrecompressed → express.static — build'de üretilmiş `.br`/`.gz`
12
12
  * kopyalar varsa onlar servis edilir (kalite 11), yoksa istek altındaki
13
13
  * static'e düşer ve middleware anında sıkıştırır (kalite 5).
14
+ * 4b. cache paneli (açıksa) — statikten sonra, route'lardan önce: kendi
15
+ * gövde ayrıştırıcısını taşır ve uygulama yolunu gölgeleyemez.
14
16
  * 5. body parser'lar — statikten sonra: görsel isteklerinde gövde ayrıştırma
15
17
  * maliyeti ödenmesin.
16
18
  * 6. csrf — body parser'lardan sonra olmalı: token form alanından okunuyor.
@@ -35,6 +37,7 @@ import { renderNotFound } from "./render.js";
35
37
  import { renderStatusPage, statusFromError } from "./status-page.js";
36
38
  import { isPrewarmRequest, notePrewarmError, startPrewarm } from "./prewarm.js";
37
39
  import { trackUpstreamFetch } from "./upstream-tracking.js";
40
+ import { configureUpstreamLimiter } from "./upstream-limiter.js";
38
41
  import { connectRedis, disconnectRedis } from "./redis.js";
39
42
  import { isNotFoundError, isRedirectError } from "../http/control-flow.js";
40
43
 
@@ -52,6 +55,10 @@ export async function createApp(options = {}) {
52
55
  // ilk kurulduğu istek de kapsanmalı.
53
56
  if (config.trackUpstream) trackUpstreamFetch();
54
57
 
58
+ // Hız freni sarmalayıcının içinden okunuyor; ayarı ona vermek yeterli.
59
+ // `cache().upstream.rate` verilmedikçe hiçbir istek beklemez.
60
+ configureUpstreamLimiter(config.upstream);
61
+
55
62
  // Önbelleğin ikinci kademesi route'lardan önce kurulmalı: ilk istek de
56
63
  // paylaşımlı kopyayı görebilsin. Bağlanamazsa uyarı basılır ve uygulama
57
64
  // bellek içi önbellekle çalışmaya devam eder — middleware sırasına
@@ -103,6 +110,15 @@ export async function createApp(options = {}) {
103
110
  mountDevtools(app);
104
111
  }
105
112
 
113
+ // Önbellek paneli ortama bakmaz, config'e bakar: açıkça etkinleştirilmedikçe
114
+ // modül hiç yüklenmez ve yol da yoktur. Kendi gövde ayrıştırıcısını
115
+ // taşıdığı için aşağıdaki parser'lardan önce durabiliyor; route'lardan
116
+ // önce olması gerekiyor ki uygulama aynı yolu gölgeleyemesin.
117
+ if (config.cachePanel.enabled) {
118
+ const { mountCachePanel } = await import("./cache-panel.js");
119
+ mountCachePanel(app);
120
+ }
121
+
106
122
  app.use(express.urlencoded({ extended: false, limit: "64kb" }));
107
123
  app.use(express.json({ limit: "256kb" }));
108
124