@jeffusion/bungee-core 6.17.0 → 6.19.0

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,218 @@
1
+ <script lang="ts">
2
+ import { locale } from 'svelte-i18n';
3
+ import Activity from 'lucide-svelte/icons/activity';
4
+ import RefreshCw from 'lucide-svelte/icons/refresh-cw';
5
+ import Replace from 'lucide-svelte/icons/replace';
6
+ import ShieldCheck from 'lucide-svelte/icons/shield-check';
7
+ import { requestPluginControl } from '@bungee/plugin-sdk';
8
+ import { KpiCard, LoadingIndicator, PanelCard, SectionDivider, SystemAlertBar } from '$components/industrial';
9
+ import { Button } from '$components/ui/button';
10
+
11
+ let { pluginName = 'request-body-redaction', refreshSignal = 0, onbusy }: {
12
+ pluginName?: string;
13
+ refreshSignal?: number;
14
+ onbusy?: (busy: boolean) => void;
15
+ } = $props();
16
+
17
+ const copy = $derived($locale?.startsWith('zh') ? {
18
+ title: '全局脱敏统计',
19
+ scope: '跨所有工作进程累计,按脱敏执行次数计,不代表上游请求成功数。',
20
+ processedRequests: '执行次数',
21
+ redactedRequests: '命中替换次数',
22
+ replacements: '累计替换处数',
23
+ unitRuns: 'RUNS',
24
+ unitHits: 'HITS',
25
+ unitReplaced: 'REPLACED',
26
+ footRuns: '汇总全部工作进程执行计数',
27
+ footHitRate: (rate: string) => `命中率 ${rate}`,
28
+ footNoHits: '尚未触发文本替换',
29
+ footAvg: (avg: string) => `平均 ${avg} 处 / 命中`,
30
+ footReplaced: '实际改写字符串值总处数',
31
+ load: '正在加载全局统计…',
32
+ refresh: '刷新统计',
33
+ error: '无法加载脱敏统计,请稍后重试。',
34
+ retry: '重试',
35
+ incompleteTitle: '统计数据可能不完整',
36
+ incomplete: '部分工作进程上报失败或异常退出,当前计数可能低于实际执行值(不作为审计依据)。',
37
+ } : {
38
+ title: 'Global Redaction Telemetry',
39
+ scope: 'Aggregated across workers by redaction runs; does not reflect upstream request success.',
40
+ processedRequests: 'Redaction Runs',
41
+ redactedRequests: 'Runs With Matches',
42
+ replacements: 'Total Replacements',
43
+ unitRuns: 'RUNS',
44
+ unitHits: 'HITS',
45
+ unitReplaced: 'REPLACED',
46
+ footRuns: 'Cumulative across all workers',
47
+ footHitRate: (rate: string) => `Hit rate ${rate}`,
48
+ footNoHits: 'No text replacements yet',
49
+ footAvg: (avg: string) => `Avg ${avg} per matched run`,
50
+ footReplaced: 'Actual modified text spans',
51
+ load: 'Loading telemetry…',
52
+ refresh: 'Refresh',
53
+ error: 'Could not load redaction statistics.',
54
+ retry: 'Retry',
55
+ incompleteTitle: 'Statistics may be incomplete',
56
+ incomplete: 'Some worker reports failed or exited early; counts may be lower than actual executions.',
57
+ });
58
+
59
+ const metrics = ['processedRequests', 'redactedRequests', 'replacements'] as const;
60
+ type Stats = Record<typeof metrics[number], number> & { reportingIncomplete: boolean };
61
+
62
+ let stats = $state<Stats | null>(null);
63
+ let failed = $state(false);
64
+ let loading = $state(true);
65
+ let revision = $state(0);
66
+
67
+ const hitRateLabel = $derived.by(() => {
68
+ if (!stats || stats.processedRequests <= 0) return copy.footNoHits;
69
+ const pct = (stats.redactedRequests / stats.processedRequests) * 100;
70
+ const formatted = pct === 0 || pct === 100 ? pct.toFixed(0) : pct.toFixed(1);
71
+ return copy.footHitRate(`${formatted}%`);
72
+ });
73
+
74
+ const avgReplacementsLabel = $derived.by(() => {
75
+ if (!stats || stats.redactedRequests <= 0) return copy.footReplaced;
76
+ const avg = stats.replacements / stats.redactedRequests;
77
+ const formatted = Number.isInteger(avg) ? String(avg) : avg.toFixed(1);
78
+ return copy.footAvg(formatted);
79
+ });
80
+
81
+ $effect(() => {
82
+ onbusy?.(loading);
83
+ });
84
+
85
+ $effect(() => {
86
+ const name = pluginName;
87
+ void revision;
88
+ void refreshSignal;
89
+ const controller = new AbortController();
90
+ loading = true;
91
+ failed = false;
92
+ void requestPluginControl<Stats>(name, '/stats', 'GET', undefined, controller.signal)
93
+ .then(result => {
94
+ if (controller.signal.aborted) return;
95
+ if (!result || !metrics.every(key => Number.isSafeInteger(result[key]) && result[key] >= 0)
96
+ || typeof result.reportingIncomplete !== 'boolean') {
97
+ stats = null;
98
+ failed = true;
99
+ return;
100
+ }
101
+ stats = result;
102
+ })
103
+ .catch(() => {
104
+ if (!controller.signal.aborted) {
105
+ stats = null;
106
+ failed = true;
107
+ }
108
+ })
109
+ .finally(() => {
110
+ if (!controller.signal.aborted) loading = false;
111
+ });
112
+ return () => controller.abort();
113
+ });
114
+
115
+ function triggerRefresh() {
116
+ if (!loading) revision++;
117
+ }
118
+ </script>
119
+
120
+ <section class="min-w-0 space-y-3" data-testid="request-body-redaction-stats" aria-busy={loading}>
121
+ <SectionDivider label={copy.title}>
122
+ <div slot="actions" class="flex items-center gap-3">
123
+ <span class="hidden text-xs text-zinc-500 md:inline">{copy.scope}</span>
124
+ <Button
125
+ variant="ghost"
126
+ size="sm"
127
+ disabled={loading}
128
+ onclick={triggerRefresh}
129
+ aria-label={failed ? copy.retry : copy.refresh}
130
+ >
131
+ <RefreshCw class="mr-1.5 h-3.5 w-3.5 {loading ? 'motion-safe:animate-spin' : ''}" aria-hidden="true" />
132
+ {failed ? copy.retry : copy.refresh}
133
+ </Button>
134
+ </div>
135
+ </SectionDivider>
136
+ <p class="text-xs text-zinc-500 md:hidden">{copy.scope}</p>
137
+
138
+ {#if failed}
139
+ <PanelCard headless corners={false} stripe="red">
140
+ <div class="flex flex-wrap items-center justify-between gap-3">
141
+ <p role="alert" class="text-sm text-red-300">{copy.error}</p>
142
+ <Button variant="ghost" size="sm" onclick={triggerRefresh}>{copy.retry}</Button>
143
+ </div>
144
+ </PanelCard>
145
+ {:else if !stats}
146
+ <div class="grid grid-cols-1 gap-3 sm:grid-cols-3">
147
+ {#each metrics as key (key)}
148
+ <KpiCard label={copy[key]} fillHeight reserveFooter class="min-h-[136px]">
149
+ <LoadingIndicator label={copy.load} size="sm" height="none" centered={false} />
150
+ </KpiCard>
151
+ {/each}
152
+ </div>
153
+ {:else}
154
+ {#if stats.reportingIncomplete}
155
+ <SystemAlertBar tone="warn" title={copy.incompleteTitle} subtitle={copy.incomplete} />
156
+ {/if}
157
+
158
+ {#snippet runsIcon()}
159
+ <Activity class="h-3.5 w-3.5 text-zinc-400" aria-hidden="true" />
160
+ {/snippet}
161
+ {#snippet hitsIcon()}
162
+ <ShieldCheck class="h-3.5 w-3.5 {stats.redactedRequests > 0 ? 'text-nexus-400' : 'text-zinc-400'}" aria-hidden="true" />
163
+ {/snippet}
164
+ {#snippet replacedIcon()}
165
+ <Replace class="h-3.5 w-3.5 {stats.replacements > 0 ? 'text-emerald-400' : 'text-zinc-400'}" aria-hidden="true" />
166
+ {/snippet}
167
+
168
+ <div class="grid grid-cols-1 gap-3 sm:grid-cols-3">
169
+ <KpiCard
170
+ label={copy.processedRequests}
171
+ value={stats.processedRequests.toLocaleString($locale ?? undefined)}
172
+ unit={copy.unitRuns}
173
+ icon-head={runsIcon}
174
+ fillHeight
175
+ reserveFooter
176
+ class="min-h-[136px]"
177
+ >
178
+ {#snippet foot()}
179
+ <span class="font-mono text-[10px] tracking-command text-zinc-400">{copy.footRuns}</span>
180
+ {/snippet}
181
+ </KpiCard>
182
+
183
+ <KpiCard
184
+ label={copy.redactedRequests}
185
+ value={stats.redactedRequests.toLocaleString($locale ?? undefined)}
186
+ unit={copy.unitHits}
187
+ tone={stats.redactedRequests > 0 ? 'accent' : 'auto'}
188
+ icon-head={hitsIcon}
189
+ fillHeight
190
+ reserveFooter
191
+ class="min-h-[136px]"
192
+ >
193
+ {#snippet foot()}
194
+ <span class="font-mono text-[10px] tracking-command {stats.redactedRequests > 0 ? 'text-nexus-300' : 'text-zinc-400'}">
195
+ {hitRateLabel}
196
+ </span>
197
+ {/snippet}
198
+ </KpiCard>
199
+
200
+ <KpiCard
201
+ label={copy.replacements}
202
+ value={stats.replacements.toLocaleString($locale ?? undefined)}
203
+ unit={copy.unitReplaced}
204
+ tone={stats.replacements > 0 ? 'ok' : 'auto'}
205
+ icon-head={replacedIcon}
206
+ fillHeight
207
+ reserveFooter
208
+ class="min-h-[136px]"
209
+ >
210
+ {#snippet foot()}
211
+ <span class="font-mono text-[10px] tracking-command {stats.replacements > 0 ? 'text-emerald-300' : 'text-zinc-400'}">
212
+ {avgReplacementsLabel}
213
+ </span>
214
+ {/snippet}
215
+ </KpiCard>
216
+ </div>
217
+ {/if}
218
+ </section>
@@ -0,0 +1,69 @@
1
+ import type { ConfigurationRoute, PluginBinding, PluginConfigValue } from '@jeffusion/bungee-types';
2
+ import { cloneDeep, isEqual } from 'lodash-es';
3
+ import { v4 as uuidv4 } from 'uuid';
4
+ import { ConfigurationStaleError, getConfigSnapshot } from '$api/config';
5
+ import { saveLogicalConfiguration } from '$api/configuration-save';
6
+ import { configurationWrite } from '$stores/configuration-write';
7
+ import { get } from 'svelte/store';
8
+ import { compileRedactionRules } from '../rules';
9
+
10
+ const pluginName = 'request-body-redaction';
11
+ export { configurationWrite as redactionConfigurationWrite };
12
+
13
+ export interface RedactionRouteBinding {
14
+ id: string;
15
+ path: string;
16
+ binding: { id: string; enabled: boolean; rules: unknown } | null;
17
+ }
18
+
19
+ export class RedactionRouteConflictError extends Error {}
20
+
21
+ function project(route: ConfigurationRoute): RedactionRouteBinding {
22
+ const binding = route.plugins.find(plugin => plugin.name === pluginName);
23
+ return {
24
+ id: route.id,
25
+ path: route.path,
26
+ binding: binding ? { id: binding.id, enabled: binding.enabled, rules: binding.options?.rules } : null,
27
+ };
28
+ }
29
+
30
+ export async function loadRedactionRoutes(): Promise<RedactionRouteBinding[]> {
31
+ return (await getConfigSnapshot()).config.logical_configuration.routes.map(project);
32
+ }
33
+
34
+ export async function saveRedactionRouteBinding(
35
+ baseline: RedactionRouteBinding, rules: unknown[] | null,
36
+ ): Promise<RedactionRouteBinding> {
37
+ baseline = cloneDeep(baseline);
38
+ // Preserve omitted replacements and avoid reading a reactive draft after the await.
39
+ const nextRules = rules === null ? null : JSON.parse(JSON.stringify(rules)) as PluginConfigValue[];
40
+ if (nextRules !== null && !compileRedactionRules(nextRules)) throw new Error('invalid_redaction_rules');
41
+ const snapshot = await getConfigSnapshot();
42
+ const logical = snapshot.config.logical_configuration;
43
+ const route = logical.routes.find(candidate => candidate.id === baseline.id);
44
+ if (!route || !snapshot.config.plugin_activations.some(plugin => plugin.plugin_name === pluginName)
45
+ || !isEqual(project(route), baseline)) throw new RedactionRouteConflictError();
46
+ const current = route.plugins.filter(plugin => plugin.name === pluginName);
47
+ if (current.length > 1) throw new RedactionRouteConflictError();
48
+
49
+ const replacement: PluginBinding | null = nextRules === null ? null : {
50
+ name: pluginName,
51
+ id: current[0]?.id ?? uuidv4(),
52
+ position: current[0]?.position ?? route.plugins.reduce((max, plugin) => Math.max(max, plugin.position), -1) + 1,
53
+ enabled: true,
54
+ options: { ...current[0]?.options, rules: nextRules },
55
+ };
56
+ const plugins = current.length
57
+ ? route.plugins.flatMap(plugin => plugin.id !== current[0]?.id ? [plugin] : replacement ? [replacement] : [])
58
+ : replacement ? [...route.plugins, replacement] : route.plugins;
59
+ const nextRoute = { ...route, plugins };
60
+ const { pending, corrupt } = get(configurationWrite);
61
+ if (corrupt || pending && !pending.accepted) throw new Error('configuration_write_unconfirmed');
62
+ try {
63
+ await saveLogicalConfiguration(snapshot, { ...logical, routes: logical.routes.map(item => item.id === route.id ? nextRoute : item) });
64
+ } catch (error) {
65
+ if (error instanceof ConfigurationStaleError) throw new RedactionRouteConflictError();
66
+ throw error;
67
+ }
68
+ return project(nextRoute);
69
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jeffusion/bungee-core",
3
- "version": "6.17.0",
3
+ "version": "6.19.0",
4
4
  "description": "Bungee reverse proxy core engine",
5
5
  "main": "./dist/main.js",
6
6
  "types": "./dist/main.d.ts",
@@ -16,7 +16,7 @@
16
16
  "@iconify-json/lucide": "^1.2.145",
17
17
  "@iconify-json/tabler": "^1.2.42",
18
18
  "@iconify/utils": "^3.1.7",
19
- "@jeffusion/bungee-types": "^6.17.0",
19
+ "@jeffusion/bungee-types": "^6.19.0",
20
20
  "@types/lodash-es": "^4.17.12",
21
21
  "@types/ws": "^8.18.1",
22
22
  "acorn": "^8.15.0",