bunqueue-dashboard 0.0.30 → 0.0.32

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.
Files changed (84) hide show
  1. package/agent/db.ts +178 -40
  2. package/agent/dbQueryWorker.ts +14 -6
  3. package/agent/index.ts +4 -1
  4. package/agent/manager.ts +97 -12
  5. package/agent/server.ts +11 -5
  6. package/dist/.vite/manifest.json +200 -151
  7. package/dist/assets/AddJob-Dvpp--yq.js +3 -0
  8. package/dist/assets/{Alerts-GhRfE6uG.js → Alerts-CR9jgCCs.js} +1 -1
  9. package/dist/assets/{AreaChart-Dl_9G6GH.js → AreaChart-2gM0YoZT.js} +1 -1
  10. package/dist/assets/Benchmark-CkL-Ee-M.js +1 -0
  11. package/dist/assets/BulkAddJobs-wI6cRZnX.js +5 -0
  12. package/dist/assets/CopilotPanel-DPZV9opm.js +44 -0
  13. package/dist/assets/{Cron-BqKxXt_G.js → Cron-gWVkYWad.js} +1 -1
  14. package/dist/assets/CronManager-BvfW219u.js +1 -0
  15. package/dist/assets/Database-D2T_ZIGA.js +3 -0
  16. package/dist/assets/Diagnostics-C2goqq5h.js +1 -0
  17. package/dist/assets/Dlq-Q4TmmZrK.js +1 -0
  18. package/dist/assets/{DlqControl-B0VILOwI.js → DlqControl-C5BfE7Gq.js} +1 -1
  19. package/dist/assets/{DlqPro-D8POex8v.js → DlqPro-ClPNmw-X.js} +1 -1
  20. package/dist/assets/Flows-DbhMbvSG.js +1 -0
  21. package/dist/assets/JobInspector-CO_zKjSX.js +2 -0
  22. package/dist/assets/Jobs-D2rDHPM_.js +1 -0
  23. package/dist/assets/JobsPro-Drdgdj3s.js +1 -0
  24. package/dist/assets/Logs-DjwGuRLi.js +1 -0
  25. package/dist/assets/LogsPro-7uTBjPWX.js +1 -0
  26. package/dist/assets/{McpServer-CI9Z61Lm.js → McpServer-DAklQDB5.js} +1 -1
  27. package/dist/assets/{Metrics-qsVJt17r.js → Metrics-Dup9Zinh.js} +1 -1
  28. package/dist/assets/{MetricsPro-BMNObO4L.js → MetricsPro-PP3TymeP.js} +1 -1
  29. package/dist/assets/Overview-C7RCDE6r.js +1 -0
  30. package/dist/assets/{Pagination-EJ2HGoqv.js → Pagination-B9JDi5MI.js} +1 -1
  31. package/dist/assets/QueueActions-DJTw0h2g.js +1 -0
  32. package/dist/assets/{QueueControl-2NXIrJqi.js → QueueControl-CxKjUjF-.js} +1 -1
  33. package/dist/assets/{QueueDetail-7EEYk51J.js → QueueDetail-bf2n-r2h.js} +1 -1
  34. package/dist/assets/{QueueDetailPro-DDB6mrh6.js → QueueDetailPro-C-XLWFBa.js} +1 -1
  35. package/dist/assets/Queues-CMQW89J9.js +1 -0
  36. package/dist/assets/{QueuesOverview-CzbHoeuS.js → QueuesOverview-x7-akDzf.js} +1 -1
  37. package/dist/assets/{S3Backup-ETwjL2TD.js → S3Backup-1jAySC9R.js} +1 -1
  38. package/dist/assets/{S3BackupPro-DwX9b_1u.js → S3BackupPro-BG_0OHW7.js} +1 -1
  39. package/dist/assets/{ServerControl-BOh2ncLo.js → ServerControl-DohTB--h.js} +3 -3
  40. package/dist/assets/{Settings-_aPq2yDv.js → Settings-CnS5PjNe.js} +1 -1
  41. package/dist/assets/Usage-C3H0hMSA.js +1 -0
  42. package/dist/assets/{UsagePro-Dv0izJVc.js → UsagePro-CdnQkP9o.js} +1 -1
  43. package/dist/assets/Webhooks-CAwVmIEZ.js +1 -0
  44. package/dist/assets/{Workers-CXwdSXup.js → Workers-lvujKZwF.js} +1 -1
  45. package/dist/assets/{WorkersPro-BBnrgBbn.js → WorkersPro-CIJKl7U1.js} +1 -1
  46. package/dist/assets/{connectionStore-B-hNUqwK.js → connectionStore-DO6xQY7h.js} +1 -1
  47. package/dist/assets/dist-1f1fMHVO.js +11 -0
  48. package/dist/assets/dist-BlWBaCN6.js +11 -0
  49. package/dist/assets/dist-DZL8soAh.js +79 -0
  50. package/dist/assets/dist-DjvZiKhB.js +2 -0
  51. package/dist/assets/dist-DpZcbP9W.js +11 -0
  52. package/dist/assets/{exportFile-tdUeW5m5.js → exportFile-C7xhE8Yh.js} +1 -1
  53. package/dist/assets/{form-C-zZyKfB.js → form-DGinTEEb.js} +1 -1
  54. package/dist/assets/index-DcVOpnSj.css +1 -0
  55. package/dist/assets/index-r1ZMLIZ9.js +8 -0
  56. package/dist/assets/{install-DhTYJCUC.js → install-BIVfix28.js} +1 -1
  57. package/dist/assets/{react-vendor-B68RYDeC.js → react-vendor-BcouBxpZ.js} +2 -2
  58. package/dist/assets/useThroughputSeries-CVKzWzdv.js +1 -0
  59. package/dist/index.html +4 -4
  60. package/package.json +5 -5
  61. package/scripts/embedded.gen.ts +122 -112
  62. package/scripts/serve.ts +300 -88
  63. package/dist/assets/AddJob-Bsc2w6F0.js +0 -3
  64. package/dist/assets/Benchmark-Bc_ZEM87.js +0 -1
  65. package/dist/assets/BulkAddJobs-B9q81JAq.js +0 -5
  66. package/dist/assets/CopilotPanel-DL61f5jW.js +0 -152
  67. package/dist/assets/CronManager-DuWur13m.js +0 -1
  68. package/dist/assets/Database-DSpCA3w7.js +0 -3
  69. package/dist/assets/Diagnostics-DsBFg_-t.js +0 -1
  70. package/dist/assets/Dlq-BAQfqBgy.js +0 -1
  71. package/dist/assets/Flows-BEafLVu_.js +0 -1
  72. package/dist/assets/JobInspector-Du4zhHVo.js +0 -2
  73. package/dist/assets/Jobs-9VzulNrm.js +0 -1
  74. package/dist/assets/JobsPro-YebB40C-.js +0 -1
  75. package/dist/assets/Logs-DtV3k05m.js +0 -1
  76. package/dist/assets/LogsPro-C9VmsZL-.js +0 -1
  77. package/dist/assets/Overview-DtVeV_uf.js +0 -1
  78. package/dist/assets/QueueActions-qd4d3da3.js +0 -1
  79. package/dist/assets/Queues-ClEE2_8g.js +0 -1
  80. package/dist/assets/Usage-B6ESpkgj.js +0 -1
  81. package/dist/assets/Webhooks-Cs-DqyhB.js +0 -1
  82. package/dist/assets/index-BFRKPhvf.js +0 -8
  83. package/dist/assets/index-mF63w920.css +0 -1
  84. package/dist/assets/useThroughputSeries-BzUriOcf.js +0 -1
package/scripts/serve.ts CHANGED
@@ -13,81 +13,100 @@
13
13
  * SPA finds the agent regardless of AGENT_PORT and even from a remote
14
14
  * browser, where loopback :6800 would be unreachable.
15
15
  *
16
+ * Control-plane exposure rule (the agent can spawn processes):
17
+ * - Loopback bind (the default): /agent/* is bridged, and the loopback :6800
18
+ * listener keeps its Host allowlist (DNS-rebinding defense).
19
+ * - Non-loopback bind (BIND_ADDR=0.0.0.0): the bridge would hand the whole
20
+ * LAN an unauthenticated process spawner (the agent's Origin gate lets an
21
+ * Origin-less curl through by design), so it is REFUSED with 403 unless the
22
+ * operator opts in with AGENT_TOKEN (recommended — it gates every mutation)
23
+ * or AGENT_ALLOW_REMOTE_CONTROL=1 (explicit, unauthenticated).
24
+ *
16
25
  * Env: PORT (dashboard, default 8080) · BIND_ADDR (default 127.0.0.1) ·
17
- * BUNQUEUE_URL · AGENT_PORT · AGENT_ALLOWED_ORIGINS · AGENT_TOKEN ·
18
- * BUNQUEUE_START_CMD · HTTP_PORT · TCP_PORT · BUNQUEUE_DATA_PATH ·
19
- * LOG_LEVEL (pino level, default info)
26
+ * BUNQUEUE_URL · AGENT_PORT · AGENT_ALLOWED_ORIGINS · AGENT_ALLOWED_HOSTS ·
27
+ * AGENT_TOKEN · AGENT_ALLOW_REMOTE_CONTROL · TRUST_PROXY · BUNQUEUE_START_CMD ·
28
+ * HTTP_PORT · TCP_PORT · BUNQUEUE_DATA_PATH · LOG_LEVEL (pino level, info)
20
29
  */
21
30
  import { logger } from '../agent/logger';
22
- import { ProcessManager } from '../agent/manager';
31
+ import { setQueryWorkerUrl } from '../agent/db';
23
32
  import {
24
33
  createFetchHandler,
25
34
  isHostAllowed,
35
+ isOriginAllowed,
26
36
  resolveAllowedHosts,
27
37
  resolveAllowedOrigins,
28
38
  } from '../agent/server';
29
- import { ASSETS } from './embedded.gen';
30
-
31
- const PORT = Number(process.env.PORT) || 8080;
32
- // Bind loopback by default: the /api proxy forwards to bunqueue's admin API, so
33
- // listening on all interfaces would expose it to the whole network. Set
34
- // BIND_ADDR=0.0.0.0 for direct LAN access (e.g. no reverse proxy in front).
35
- const HOST = process.env.BIND_ADDR || '127.0.0.1';
36
- const API = (process.env.BUNQUEUE_URL || 'http://localhost:6790').replace(/\/$/, '');
37
- const AGENT_PORT = Number(process.env.AGENT_PORT) || 6800;
38
-
39
- // Control agent — loopback only, allowlisted CORS; the origins this binary
40
- // serves the dashboard from are allowed automatically.
41
- const allowedOrigins = Array.from(
42
- new Set([
43
- ...resolveAllowedOrigins(),
44
- `http://localhost:${PORT}`,
45
- `http://127.0.0.1:${PORT}`,
46
- ])
47
- );
48
-
49
- // DNS-rebinding defense (see agent/server.ts). Only enforced when bound to
50
- // loopback — the common "looks safe" case where a rebound page could reach the
51
- // /api proxy and /agent inspector over same-origin GETs. When the user binds a
52
- // non-loopback interface (BIND_ADDR=0.0.0.0) they opted into network exposure,
53
- // where a fixed host allowlist would break legitimate LAN-IP access; leave it
54
- // off there (configure a reverse proxy / AGENT_ALLOWED_HOSTS instead).
55
- const loopbackBind = HOST === '127.0.0.1' || HOST === '::1' || HOST === 'localhost';
56
- const originHosts = allowedOrigins
57
- .map((o) => {
58
- try {
59
- return new URL(o).hostname;
60
- } catch {
61
- return '';
62
- }
63
- })
64
- .filter(Boolean);
65
- const allowedHosts = loopbackBind ? resolveAllowedHosts(process.env, originHosts) : undefined;
66
-
67
- const mgr = new ProcessManager();
68
- const agentHandle = createFetchHandler(mgr, {
69
- allowedOrigins,
70
- allowedHosts,
71
- token: process.env.AGENT_TOKEN || undefined,
72
- });
73
- Bun.serve({ port: AGENT_PORT, hostname: '127.0.0.1', fetch: agentHandle });
74
-
75
- // index.html with the runtime agent base injected, prepared once at startup.
76
- // The SPA's lib/bq.ts reads window.__BUNQUEUE_AGENT_URL__ before its baked-in
77
- // default, so Server Control works whatever AGENT_PORT is — the /agent/*
78
- // route below forwards to the in-process agent handler.
79
- const INDEX_HTML = (await Bun.file(ASSETS['/index.html']).text()).replace(
80
- '</head>',
81
- "<script>window.__BUNQUEUE_AGENT_URL__='/agent'</script></head>"
82
- );
83
- const indexResponse = () =>
84
- new Response(INDEX_HTML, { headers: { 'content-type': 'text/html; charset=utf-8' } });
85
-
86
- // Dashboard + /api proxy + same-origin /agent proxy.
87
- Bun.serve({
88
- port: PORT,
89
- hostname: HOST,
90
- async fetch(req) {
39
+
40
+ /** Hostnames that mean "only this machine can reach the listener". */
41
+ export function isLoopbackBind(host: string): boolean {
42
+ return host === '127.0.0.1' || host === '::1' || host === 'localhost';
43
+ }
44
+
45
+ /**
46
+ * May the process-spawning control plane be reachable over the network?
47
+ * Loopback always yes; a non-loopback bind requires an explicit opt-in.
48
+ */
49
+ export function remoteControlEnabled(
50
+ loopbackBind: boolean,
51
+ env: Record<string, string | undefined> = process.env
52
+ ): boolean {
53
+ if (loopbackBind) return true;
54
+ return Boolean(env.AGENT_TOKEN) || env.AGENT_ALLOW_REMOTE_CONTROL === '1';
55
+ }
56
+
57
+ /**
58
+ * Build the inner agent URL from the bridged path. `new URL(rest, base)` throws
59
+ * on a path like `//x:y/z` (it reads `//` as an authority); assigning .pathname
60
+ * never reinterprets it, so a hostile path can't crash the handler.
61
+ */
62
+ export function agentSubUrl(pathname: string, search: string): URL {
63
+ const rest = pathname.slice('/agent'.length) || '/';
64
+ const sub = new URL('http://agent.internal');
65
+ sub.pathname = rest.startsWith('/') ? rest : `/${rest}`;
66
+ sub.search = search;
67
+ return sub;
68
+ }
69
+
70
+ export interface ServeHandlerOptions {
71
+ /** bunqueue base URL the /api prefix proxies to (no trailing slash). */
72
+ api: string;
73
+ /** index.html with the agent base already injected. */
74
+ indexHtml: string;
75
+ /** embedded dist assets: request path → on-disk path. */
76
+ assets: Record<string, string>;
77
+ /** in-process control agent handler. */
78
+ agentHandle: (req: Request) => Response | Promise<Response>;
79
+ allowedOrigins: string[];
80
+ allowedHosts?: string[];
81
+ /** false → /agent/* is refused (non-loopback bind without opt-in). */
82
+ agentBridge: boolean;
83
+ /**
84
+ * TRUST_PROXY=1 — a reverse proxy in front of us owns X-Forwarded-Host, so it
85
+ * may be believed. Off by default: the header is otherwise client-settable
86
+ * and would let any direct caller declare itself same-origin.
87
+ */
88
+ trustProxy?: boolean;
89
+ }
90
+
91
+ /**
92
+ * The dashboard listener: static assets + /api proxy + same-origin /agent
93
+ * bridge. Factored out of the Bun.serve call so the policy is unit-testable.
94
+ */
95
+ export function createServeHandler(opts: ServeHandlerOptions) {
96
+ const {
97
+ api,
98
+ indexHtml,
99
+ assets,
100
+ agentHandle,
101
+ allowedOrigins,
102
+ allowedHosts,
103
+ agentBridge,
104
+ trustProxy = false,
105
+ } = opts;
106
+ const indexResponse = () =>
107
+ new Response(indexHtml, { headers: { 'content-type': 'text/html; charset=utf-8' } });
108
+
109
+ return async function handle(req: Request): Promise<Response> {
91
110
  const url = new URL(req.url);
92
111
 
93
112
  // DNS-rebinding defense across every route (/api proxy, /agent, assets):
@@ -97,25 +116,88 @@ Bun.serve({
97
116
  return new Response('Host not allowed', { status: 403 });
98
117
  }
99
118
 
119
+ // A request whose Origin is the origin this listener serves from is by
120
+ // definition not the cross-site case the allowlist exists for. It is what a
121
+ // LAN browser sends (http://<lan-ip>:PORT), which no static allowlist can
122
+ // predict — treat it as allowed everywhere below.
123
+ //
124
+ // Compared by HOST, not by full origin: this listener only ever speaks
125
+ // plain http, so behind a TLS-terminating reverse proxy the browser sends
126
+ // `https://dash.example.com` while req.url reads `http://dash.example.com`.
127
+ // A full-origin compare would 403 every mutation on a proxied deployment
128
+ // while read-only GETs (which carry no Origin) kept working — a dashboard
129
+ // that looks healthy and fails on click. The host is the part that
130
+ // identifies a cross-site page (its Origin carries its OWN host), so it is
131
+ // the part worth comparing. x-forwarded-host is honoured for proxies that
132
+ // rewrite Host.
133
+ const origin = req.headers.get('origin');
134
+ let originHost = '';
135
+ try {
136
+ originHost = origin ? new URL(origin).host.toLowerCase() : '';
137
+ } catch {
138
+ originHost = ''; // unparseable Origin — treat as cross-site
139
+ }
140
+ // X-Forwarded-Host is attacker-controlled unless something in front of us
141
+ // is guaranteed to overwrite it: a direct caller can send
142
+ // `Origin: https://evil.example` + `x-forwarded-host: evil.example` and
143
+ // declare ITSELF same-origin. So it is consulted only when the operator
144
+ // sets TRUST_PROXY=1, which asserts a reverse proxy owns that header.
145
+ // Without it, a proxy that preserves Host still works (the Host compare
146
+ // below covers it); only a Host-REWRITING proxy needs the opt-in.
147
+ const fwd = trustProxy ? req.headers.get('x-forwarded-host')?.split(',') : undefined;
148
+ const forwardedHost = fwd?.[fwd.length - 1]?.trim().toLowerCase();
149
+ const sameOrigin =
150
+ originHost !== '' &&
151
+ (originHost === url.host.toLowerCase() || originHost === forwardedHost);
152
+
100
153
  // Same-origin bridge to the control agent: strip the /agent prefix and
101
154
  // hand the request to the in-process agent handler (no loopback hop).
102
155
  // The agent's own Origin allowlist + optional AGENT_TOKEN still apply —
103
156
  // this changes reachability, not authorization.
104
157
  if (url.pathname === '/agent' || url.pathname.startsWith('/agent/')) {
105
- const sub = new URL(url.pathname.slice('/agent'.length) || '/', 'http://agent.internal');
106
- sub.search = url.search;
107
- return agentHandle(new Request(sub.href, req));
158
+ if (!agentBridge) {
159
+ return Response.json(
160
+ {
161
+ ok: false,
162
+ error:
163
+ 'Control agent disabled on a non-loopback bind. Set AGENT_TOKEN (recommended) or AGENT_ALLOW_REMOTE_CONTROL=1 to expose it.',
164
+ },
165
+ { status: 403 }
166
+ );
167
+ }
168
+ const sub = agentSubUrl(url.pathname, url.search);
169
+ const headers = new Headers(req.headers);
170
+ // Drop a same-origin Origin the agent's static allowlist cannot know
171
+ // (a LAN IP / hostname alias). Loopback origins are already allowlisted,
172
+ // so they are forwarded untouched and CORS behaviour is unchanged.
173
+ if (sameOrigin && origin && !isOriginAllowed(origin, allowedOrigins)) headers.delete('origin');
174
+ return agentHandle(new Request(sub.href, { method: req.method, headers, body: req.body }));
108
175
  }
109
176
 
110
177
  // Same-origin proxy to the bunqueue server (mirrors the Vite dev proxy).
111
178
  if (url.pathname === '/api' || url.pathname.startsWith('/api/')) {
112
- const target = API + (url.pathname.slice(4) || '/') + url.search;
113
- const res = await fetch(target, {
114
- method: req.method,
115
- headers: req.headers,
116
- body: req.body,
117
- redirect: 'manual',
118
- });
179
+ // The proxy talks to bunqueue's admin API, so it needs the same drive-by
180
+ // CSRF gate as the agent: a cross-site page must not reach it.
181
+ if (!sameOrigin && !isOriginAllowed(origin, allowedOrigins)) {
182
+ return Response.json({ ok: false, error: 'Origin not allowed' }, { status: 403 });
183
+ }
184
+ const target = api + (url.pathname.slice(4) || '/') + url.search;
185
+ let res: Response;
186
+ try {
187
+ res = await fetch(target, {
188
+ method: req.method,
189
+ headers: req.headers,
190
+ body: req.body,
191
+ redirect: 'manual',
192
+ });
193
+ } catch (err) {
194
+ // bunqueue not running / wrong BUNQUEUE_URL: answer in the shape the
195
+ // dashboard parses instead of letting Bun render an HTML error page.
196
+ return Response.json(
197
+ { ok: false, error: `bunqueue unreachable at ${api}: ${(err as Error).message}` },
198
+ { status: 502 }
199
+ );
200
+ }
119
201
  // Bun's fetch advertises accept-encoding upstream and transparently
120
202
  // DECOMPRESSES the body, but leaves the upstream headers intact. If the
121
203
  // bunqueue server sits behind any gzip-compressing proxy, forwarding
@@ -134,18 +216,148 @@ Bun.serve({
134
216
  // index.html (direct or via fallback) is served from the injected copy.
135
217
  const key = url.pathname === '/' ? '/index.html' : url.pathname;
136
218
  if (key === '/index.html') return indexResponse();
137
- const asset = ASSETS[key];
219
+ const asset = assets[key];
138
220
  if (asset) return new Response(Bun.file(asset));
139
221
  if (url.pathname.startsWith('/assets/')) return new Response('Not found', { status: 404 });
140
222
  return indexResponse();
141
- },
142
- });
143
-
144
- logger.info(
145
- {
146
- dashboard: `http://${HOST}:${PORT}`,
147
- apiProxy: API,
148
- agent: `http://127.0.0.1:${AGENT_PORT}/control`,
149
- },
150
- 'bunqueue dashboard (standalone) ready'
151
- );
223
+ };
224
+ }
225
+
226
+ async function main(): Promise<void> {
227
+ // Bun emits secondary TypeScript entrypoints under /$bunfs/root as JavaScript.
228
+ // Point db.ts at that embedded path in a compiled executable; when this npm bin
229
+ // runs from source, use the real TypeScript module beside agent/db.ts.
230
+ const compiled = import.meta.url.includes('/$bunfs/');
231
+ setQueryWorkerUrl(
232
+ compiled
233
+ ? new URL('/$bunfs/root/agent/dbQueryWorker.js', 'file:///').href
234
+ : new URL('../agent/dbQueryWorker.ts', import.meta.url).href
235
+ );
236
+
237
+ const PORT = Number(process.env.PORT) || 8080;
238
+ // Bind loopback by default: the /api proxy forwards to bunqueue's admin API, so
239
+ // listening on all interfaces would expose it to the whole network. Set
240
+ // BIND_ADDR=0.0.0.0 for direct LAN access (e.g. no reverse proxy in front).
241
+ const HOST = process.env.BIND_ADDR || '127.0.0.1';
242
+ const API = (process.env.BUNQUEUE_URL || 'http://localhost:6790').replace(/\/$/, '');
243
+ const AGENT_PORT = Number(process.env.AGENT_PORT) || 6800;
244
+
245
+ // Control agent — loopback only, allowlisted CORS; the origins this binary
246
+ // serves the dashboard from are allowed automatically.
247
+ const allowedOrigins = Array.from(
248
+ new Set([
249
+ ...resolveAllowedOrigins(),
250
+ `http://localhost:${PORT}`,
251
+ `http://127.0.0.1:${PORT}`,
252
+ ])
253
+ );
254
+
255
+ // DNS-rebinding defense (see agent/server.ts). Always enforced on the loopback
256
+ // :6800 listener. On the public dashboard listener it is only enforced for a
257
+ // loopback bind — when the user binds a non-loopback interface
258
+ // (BIND_ADDR=0.0.0.0) a fixed host allowlist would break legitimate LAN-IP
259
+ // access, and the control plane there is gated by remoteControlEnabled()
260
+ // instead (AGENT_TOKEN / AGENT_ALLOW_REMOTE_CONTROL).
261
+ const loopbackBind = isLoopbackBind(HOST);
262
+ const originHosts = allowedOrigins
263
+ .map((o) => {
264
+ try {
265
+ return new URL(o).hostname;
266
+ } catch {
267
+ return '';
268
+ }
269
+ })
270
+ .filter(Boolean);
271
+ const agentHosts = resolveAllowedHosts(process.env, originHosts);
272
+ const allowedHosts = loopbackBind ? agentHosts : undefined;
273
+
274
+ // Imported here rather than at module scope: this file's exported policy
275
+ // helpers are unit-tested, and a top-level import would pull the whole
276
+ // ProcessManager into every test that touches them — which, besides being
277
+ // wasteful, makes Bun attribute a barely-executed copy of agent/manager.ts to
278
+ // the coverage report and hides that module's real coverage.
279
+ const { ProcessManager } = await import('../agent/manager');
280
+ const mgr = new ProcessManager();
281
+ const token = process.env.AGENT_TOKEN || undefined;
282
+ // Two handlers, same manager: the loopback :6800 listener keeps the Host gate
283
+ // unconditionally (it is always reached as localhost/127.0.0.1), while the
284
+ // bridged one sees the dashboard client's Host and follows `allowedHosts`.
285
+ const agentHandle = createFetchHandler(mgr, { allowedOrigins, allowedHosts, token });
286
+ const loopbackAgentHandle = createFetchHandler(mgr, {
287
+ allowedOrigins,
288
+ allowedHosts: agentHosts,
289
+ token,
290
+ });
291
+ // `error` is a backstop: without it an unexpected throw renders Bun's HTML
292
+ // error page (with a stack trace) to the client instead of a plain 500.
293
+ const onError = () => new Response('Internal error', { status: 500 });
294
+ Bun.serve({
295
+ port: AGENT_PORT,
296
+ hostname: '127.0.0.1',
297
+ fetch: loopbackAgentHandle,
298
+ error: onError,
299
+ });
300
+
301
+ const agentBridge = remoteControlEnabled(loopbackBind, process.env);
302
+ if (!agentBridge) {
303
+ logger.warn(
304
+ { bind: HOST },
305
+ 'non-loopback bind without AGENT_TOKEN / AGENT_ALLOW_REMOTE_CONTROL=1 — /agent is disabled (403)'
306
+ );
307
+ }
308
+
309
+ // index.html with the runtime agent base injected, prepared once at startup.
310
+ // The SPA's lib/bq.ts reads window.__BUNQUEUE_AGENT_URL__ before its baked-in
311
+ // default, so Server Control works whatever AGENT_PORT is — the /agent/*
312
+ // route below forwards to the in-process agent handler.
313
+ const { ASSETS } = await import('./embedded.gen');
314
+ const indexHtml = (await Bun.file(ASSETS['/index.html']).text()).replace(
315
+ '</head>',
316
+ "<script>window.__BUNQUEUE_AGENT_URL__='/agent'</script></head>"
317
+ );
318
+
319
+ // Dashboard + /api proxy + same-origin /agent proxy.
320
+ Bun.serve({
321
+ port: PORT,
322
+ hostname: HOST,
323
+ fetch: createServeHandler({
324
+ api: API,
325
+ indexHtml,
326
+ assets: ASSETS,
327
+ agentHandle,
328
+ allowedOrigins,
329
+ allowedHosts,
330
+ agentBridge,
331
+ trustProxy: process.env.TRUST_PROXY === '1',
332
+ }),
333
+ error: onError,
334
+ });
335
+
336
+ // Stop the managed server before exiting — without this, Ctrl-C / SIGTERM on
337
+ // the binary orphans the spawned bunqueue child (it reparents to PID 1 and
338
+ // keeps holding the ports and the SQLite db, so the next start fails).
339
+ let shuttingDown = false;
340
+ const shutdown = (signal: string) => {
341
+ if (shuttingDown) return;
342
+ shuttingDown = true;
343
+ logger.info({ signal }, 'signal received, stopping managed server');
344
+ // shutdown(), not stop(): it latches, so a restart() already in flight
345
+ // can't spawn a fresh child after we've stopped the old one (mirrors
346
+ // agent/index.ts).
347
+ void mgr.shutdown().finally(() => process.exit(0));
348
+ };
349
+ process.on('SIGINT', () => shutdown('SIGINT'));
350
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
351
+
352
+ logger.info(
353
+ {
354
+ dashboard: `http://${HOST}:${PORT}`,
355
+ apiProxy: API,
356
+ agent: `http://127.0.0.1:${AGENT_PORT}/control`,
357
+ agentBridge,
358
+ },
359
+ 'bunqueue dashboard (standalone) ready'
360
+ );
361
+ }
362
+
363
+ if (import.meta.main) await main();
@@ -1,3 +0,0 @@
1
- import{r as e}from"./cn-CMFYpumL.js";import{h as t,l as n,r,t as i}from"./react-vendor-B68RYDeC.js";import{A as a,C as o,S as s,h as c,nt as l,rt as u,w as d}from"./index-BFRKPhvf.js";import{a as f,n as p,o as m,t as h}from"./form-C-zZyKfB.js";var g=e(t(),1),_=i(),v=e=>e==null?``:String(e);function y(){let{data:e}=a(()=>l.queues(),[],{intervalMs:3e4}),t=n().state?.clone,i=t?.options??{},[m,y]=(0,g.useState)(t?.queue??``),[x,ee]=(0,g.useState)(t?.dataText??`{
2
- "hello": "world"
3
- }`),[S,te]=(0,g.useState)(`1`),[C,ne]=(0,g.useState)(v(i.priority)),[w,re]=(0,g.useState)(``),[T,E]=(0,g.useState)(``),[D,ie]=(0,g.useState)(v(i.maxAttempts)),[O,k]=(0,g.useState)(v(typeof i.backoff==`number`?i.backoff:void 0)),[A,j]=(0,g.useState)(v(i.timeout)),[M,ae]=(0,g.useState)(``),[N,oe]=(0,g.useState)(i.removeOnComplete??!1),[P,se]=(0,g.useState)(i.removeOnFail??!1),[F,I]=(0,g.useState)(!1),[L,R]=(0,g.useState)(!1),[z,B]=(0,g.useState)(``),[V,H]=(0,g.useState)(``),[U,W]=(0,g.useState)(``),[G,ce]=(0,g.useState)(``),[K,le]=(0,g.useState)(``),[q,J]=(0,g.useState)(!1),[Y,X]=(0,g.useState)(null),[Z,Q]=(0,g.useState)(null),$=e=>{let t=Number(e);return e.trim()!==``&&Number.isFinite(t)?t:void 0},ue=async()=>{if(X(null),Q(null),!m.trim()){X({ok:!1,msg:`Choose a queue`});return}let e;try{e=JSON.parse(x)}catch(e){Q(`Invalid JSON: ${e.message}`);return}let t=$(w);if(T.trim()){let e=new Date(T).getTime();if(!Number.isFinite(e)){X({ok:!1,msg:`Run at is not a valid date/time`});return}t=Math.max(0,e-Date.now())}let n=$(O),r=n==null?void 0:z?{type:z,delay:n}:n,i=V.split(`,`).map(e=>e.trim()).filter(Boolean),a=G.split(`,`).map(e=>e.trim()).filter(Boolean),o={data:e,priority:$(C),delay:t,maxAttempts:$(D),backoff:r,timeout:$(A),jobId:M.trim()||void 0,removeOnComplete:N||void 0,removeOnFail:P||void 0,durable:F||void 0,lifo:L||void 0,tags:i.length?i:void 0,groupId:U.trim()||void 0,dependsOn:a.length?a:void 0,uniqueKey:K.trim()||void 0},s=$(S)??1;if(!Number.isInteger(s)||s<1){X({ok:!1,msg:`Count must be an integer of at least 1`});return}if(s>1e4){X({ok:!1,msg:`Count must be 10000 or fewer`});return}J(!0);try{if(s===1){let e=await l.addJob(m,o);X({ok:!0,msg:`Created job ${e.id}`}),u.success(`Job created`,`${m} · ${e.id}`)}else{let e=await l.addJobsBulk(m,Array.from({length:s},()=>o)),t=new Set(e.ids).size;X({ok:!0,msg:`Created ${t} job${t===1?``:`s`}`}),u.success(`Created ${t} job${t===1?``:`s`}`,`in ${m}`)}}catch(e){X({ok:!1,msg:e.message}),u.error(`Add job failed`,e.message)}finally{J(!1)}};return(0,_.jsxs)(`div`,{children:[(0,_.jsx)(c,{title:`Add Job`,description:`Enqueue a job with full options.`,actions:(0,_.jsx)(r,{to:`/jobs/bulk-add`,className:`rounded-lg border border-line px-3 py-1.5 text-sm text-muted hover:bg-surface-2 hover:text-fg`,children:`Bulk import`})}),t&&(0,_.jsx)(`div`,{className:`mb-4 flex items-center gap-2 rounded-lg border border-accent/30 bg-accent/[0.06] px-4 py-2 text-sm text-accent`,children:`Pre-filled from an existing job. Review the data and options, then enqueue a fresh job.`}),(0,_.jsxs)(`form`,{className:`grid grid-cols-1 gap-6 lg:grid-cols-2`,onSubmit:e=>{e.preventDefault(),ue()},children:[(0,_.jsxs)(s,{children:[(0,_.jsx)(o,{title:`Job`}),(0,_.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,_.jsxs)(h,{label:`Queue`,children:[(0,_.jsx)(p,{list:`queue-options`,value:m,onChange:e=>y(e.target.value),placeholder:`queue name (existing or new)`}),(0,_.jsx)(`datalist`,{id:`queue-options`,children:(e?.queues??[]).map(e=>(0,_.jsx)(`option`,{value:e.name},e.name))})]}),(0,_.jsxs)(`div`,{children:[(0,_.jsx)(h,{label:`Data (JSON)`,children:(0,_.jsx)(`textarea`,{value:x,onChange:e=>ee(e.target.value),onBlur:()=>{try{JSON.parse(x),Q(null)}catch(e){Q(`Invalid JSON: ${e.message}`)}},spellCheck:!1,rows:7,className:`w-full rounded-lg border border-line bg-surface-2 p-3 font-mono text-sm text-fg focus:border-accent/60 focus:outline-none focus:ring-2 focus:ring-accent/30`})}),Z&&(0,_.jsx)(`p`,{className:`mt-2 text-xs text-danger`,children:Z})]})]})]}),(0,_.jsxs)(s,{children:[(0,_.jsx)(o,{title:`Options`}),(0,_.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 md:grid-cols-3`,children:[(0,_.jsx)(h,{label:`Priority`,children:(0,_.jsx)(p,{type:`number`,value:C,onChange:e=>ne(e.target.value),placeholder:`0`})}),(0,_.jsx)(h,{label:`Delay (ms)`,children:(0,_.jsx)(p,{type:`number`,min:0,value:w,onChange:e=>re(e.target.value),placeholder:`0`,disabled:T.trim()!==``})}),(0,_.jsx)(h,{label:`Run at`,hint:T.trim()?`Overrides Delay — derived from this time (local time).`:`(local time)`,children:(0,_.jsx)(p,{type:`datetime-local`,value:T,onChange:e=>E(e.target.value)})}),(0,_.jsx)(h,{label:`Max attempts`,hint:`blank = server default`,children:(0,_.jsx)(p,{type:`number`,min:1,value:D,onChange:e=>ie(e.target.value),placeholder:`3`})}),(0,_.jsx)(h,{label:`Backoff (ms)`,hint:`blank = server default`,children:(0,_.jsx)(p,{type:`number`,min:0,value:O,onChange:e=>k(e.target.value),placeholder:`1000`})}),(0,_.jsx)(h,{label:`Backoff strategy`,hint:`flat delay unless set`,children:(0,_.jsxs)(f,{value:z,onChange:e=>B(e.target.value),children:[(0,_.jsx)(`option`,{value:``,children:`flat`}),(0,_.jsx)(`option`,{value:`fixed`,children:`fixed`}),(0,_.jsx)(`option`,{value:`exponential`,children:`exponential`})]})}),(0,_.jsx)(h,{label:`Timeout (ms)`,children:(0,_.jsx)(p,{type:`number`,min:0,value:A,onChange:e=>j(e.target.value),placeholder:`—`})}),(0,_.jsx)(h,{label:`Custom job ID`,children:(0,_.jsx)(p,{value:M,onChange:e=>ae(e.target.value),placeholder:`idempotency key`})})]}),(0,_.jsxs)(`div`,{className:`mt-4 flex flex-wrap gap-6`,children:[(0,_.jsx)(b,{label:`removeOnComplete`,checked:N,onChange:oe}),(0,_.jsx)(b,{label:`removeOnFail`,checked:P,onChange:se}),(0,_.jsx)(b,{label:`durable`,checked:F,onChange:I}),(0,_.jsx)(b,{label:`lifo`,checked:L,onChange:R})]}),(0,_.jsxs)(`div`,{className:`mt-4 border-t border-line pt-4`,children:[(0,_.jsx)(`div`,{className:`mb-3 text-[11px] uppercase tracking-wider text-faint`,children:`Advanced`}),(0,_.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 md:grid-cols-3`,children:[(0,_.jsx)(h,{label:`Tags`,hint:`comma-separated`,children:(0,_.jsx)(p,{value:V,onChange:e=>H(e.target.value),placeholder:`email, urgent`})}),(0,_.jsx)(h,{label:`Group ID`,children:(0,_.jsx)(p,{value:U,onChange:e=>W(e.target.value),placeholder:`—`})}),(0,_.jsx)(h,{label:`Unique key`,hint:`dedup key`,children:(0,_.jsx)(p,{value:K,onChange:e=>le(e.target.value),placeholder:`—`})}),(0,_.jsx)(h,{label:`Depends on`,hint:`parent job ids, comma-separated`,children:(0,_.jsx)(p,{value:G,onChange:e=>ce(e.target.value),placeholder:`job-id-1, job-id-2`})})]})]})]}),(0,_.jsxs)(`div`,{className:`flex flex-wrap items-end gap-3 lg:col-span-2`,children:[(0,_.jsx)(`div`,{className:`w-28`,children:(0,_.jsx)(h,{label:`Count`,hint:`1–10000`,children:(0,_.jsx)(p,{type:`number`,min:1,value:S,onChange:e=>te(e.target.value)})})}),(0,_.jsx)(d,{type:`submit`,variant:`accent`,disabled:q,children:q?`Adding…`:`Add job`}),Y&&(0,_.jsx)(`span`,{role:`status`,className:Y.ok?`text-sm text-success`:`text-sm text-danger`,children:Y.msg})]})]})]})}function b({label:e,checked:t,onChange:n}){return(0,_.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,_.jsx)(m,{checked:t,onChange:n,label:e}),(0,_.jsx)(`span`,{className:`font-mono text-xs text-muted`,children:e})]})}export{y as AddJob};
@@ -1 +0,0 @@
1
- import{r as e,t}from"./cn-CMFYpumL.js";import{h as n,t as r}from"./react-vendor-B68RYDeC.js";import{r as i}from"./connectionStore-B-hNUqwK.js";import{A as a,C as o,O as s,S as c,U as l,W as u,c as d,h as f,m as p,nt as m,r as h,s as g,w as _}from"./index-BFRKPhvf.js";import{i as v,n as y,o as b,t as x}from"./form-C-zZyKfB.js";import{t as S}from"./AreaChart-Dl_9G6GH.js";var C=e(n(),1),w={total:1e6,batch:5e3,producers:64,payload:65536,workers:64,workerBatch:1e3,processMs:6e4,durationS:600},T={queue:`benchmark`,mode:`count`,total:5e3,durationS:30,batch:100,producers:4,payload:128,workers:4,workerBatch:100,processMs:5,durable:!1,removeOnComplete:!0},E={Smoke:{mode:`count`,total:200,batch:50,producers:2,workers:1,workerBatch:50,processMs:0},Standard:{mode:`count`,total:5e3,batch:100,producers:4,workers:4,workerBatch:100,processMs:5},Stress:{mode:`count`,total:5e4,batch:500,producers:16,workers:16,workerBatch:200,processMs:0},Soak:{mode:`duration`,durationS:30,batch:100,producers:4,workers:8,workerBatch:100,processMs:10}},D=(e,t,n)=>Number.isFinite(e)?Math.max(t,Math.min(n,Math.floor(e))):t,O=(e,t)=>e.length?e[Math.min(e.length-1,Math.floor(t/100*e.length))]:0,k=(e,t,n,r,i)=>Array.from({length:t},(t,a)=>({data:{i:e+a,blob:n},durable:r,removeOnComplete:i})),A=e=>new Promise(t=>setTimeout(t,e)),j=async(e,t)=>{let n=performance.now()+e;for(;t()&&performance.now()<n;)await A(Math.min(100,Math.max(0,n-performance.now())))},M=e=>e instanceof Error?e.message:String(e),N=e=>e>=1e6?`${(e/1e6).toFixed(2)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:`${Math.round(e)}`,P=r();function F({history:e,onClear:t}){if(!e.length)return null;let n=JSON.stringify(e,null,2);return(0,P.jsxs)(c,{padded:!1,className:`mt-6 overflow-hidden`,children:[(0,P.jsxs)(`div`,{className:`flex items-center justify-between border-b border-line px-5 py-3`,children:[(0,P.jsx)(`h3`,{className:`text-base font-semibold text-fg`,children:`Run history`}),(0,P.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,P.jsx)(s,{value:n}),(0,P.jsx)(_,{size:`sm`,variant:`ghost`,onClick:()=>{let e=new Blob([n],{type:`application/json`}),t=URL.createObjectURL(e),r=document.createElement(`a`);r.href=t,r.download=`benchmark-history-${Date.now()}.json`,r.click(),URL.revokeObjectURL(t)},children:`Export JSON`}),(0,P.jsx)(_,{size:`sm`,variant:`ghost`,onClick:t,children:`Clear`})]})]}),(0,P.jsx)(`div`,{className:`overflow-x-auto`,children:(0,P.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,P.jsx)(`thead`,{children:(0,P.jsxs)(`tr`,{className:`border-b border-line text-left text-[11px] uppercase tracking-wider text-faint`,children:[(0,P.jsx)(`th`,{className:`px-5 py-2 font-medium`,children:`Mode`}),(0,P.jsx)(`th`,{className:`px-5 py-2 text-right font-medium`,children:`Prod`}),(0,P.jsx)(`th`,{className:`px-5 py-2 text-right font-medium`,children:`Wkr`}),(0,P.jsx)(`th`,{className:`px-5 py-2 text-right font-medium`,children:`Pushed`}),(0,P.jsx)(`th`,{className:`px-5 py-2 text-right font-medium`,children:`Done`}),(0,P.jsx)(`th`,{className:`px-5 py-2 text-right font-medium`,children:`Push/s`}),(0,P.jsx)(`th`,{className:`px-5 py-2 text-right font-medium`,children:`Done/s`}),(0,P.jsx)(`th`,{className:`px-5 py-2 text-right font-medium`,children:`p95`}),(0,P.jsx)(`th`,{className:`px-5 py-2 text-right font-medium`,children:`Dur`})]})}),(0,P.jsx)(`tbody`,{children:e.map(e=>(0,P.jsxs)(`tr`,{className:`border-b border-line last:border-0 hover:bg-surface-2/40`,children:[(0,P.jsx)(`td`,{className:`px-5 py-2 capitalize text-muted`,children:e.mode}),(0,P.jsx)(`td`,{className:`px-5 py-2 text-right tnum text-muted`,children:e.producers}),(0,P.jsx)(`td`,{className:`px-5 py-2 text-right tnum text-muted`,children:e.workers}),(0,P.jsx)(`td`,{className:`px-5 py-2 text-right tnum text-fg`,children:d(e.pushed)}),(0,P.jsx)(`td`,{className:`px-5 py-2 text-right tnum text-success`,children:d(e.completed)}),(0,P.jsxs)(`td`,{className:`px-5 py-2 text-right tnum text-accent`,children:[N(e.pushPerSec),`/s`]}),(0,P.jsxs)(`td`,{className:`px-5 py-2 text-right tnum text-success`,children:[N(e.donePerSec),`/s`]}),(0,P.jsx)(`td`,{className:`px-5 py-2 text-right tnum text-muted`,children:g(e.p95)}),(0,P.jsx)(`td`,{className:`px-5 py-2 text-right tnum text-muted`,children:g(e.durationMs)})]},e.id))})]})})]})}var I={pushed:0,completed:0,pushFailed:0,ackFailed:0,bytes:0,elapsedMs:0,pushPerSec:0,donePerSec:0,activeWorkers:0,pushSeries:[],doneSeries:[],etaMs:null,error:null},L=()=>({pushed:0,completed:0,pushFailed:0,ackFailed:0,bytes:0,assigned:0,startedAt:0,pushLat:[],activeWorkers:0,error:null,lastAt:0,lastPushed:0,lastDone:0,pushSeries:[],doneSeries:[]}),R=0;function z(){let[e,t]=(0,C.useState)(`idle`),[n,r]=(0,C.useState)(I),[i,a]=(0,C.useState)(null),[o,s]=(0,C.useState)([]),[c,l]=(0,C.useState)(null),u=(0,C.useRef)(!1),d=(0,C.useRef)(!1),f=(0,C.useRef)(!1),p=(0,C.useRef)(null),h=(0,C.useRef)(`idle`);h.current=e;let g=(0,C.useRef)(L());return(0,C.useEffect)(()=>()=>{u.current=!0},[]),(0,C.useEffect)(()=>{if(e!==`running`&&e!==`draining`)return;let t=setInterval(()=>{let e=g.current,t=performance.now(),n=t-e.startedAt,i=(t-e.lastAt)/1e3,a=i>0?Math.max(0,(e.pushed-e.lastPushed)/i):0,o=i>0?Math.max(0,(e.completed-e.lastDone)/i):0;e.lastAt=t,e.lastPushed=e.pushed,e.lastDone=e.completed,e.pushSeries=[...e.pushSeries,a].slice(-60),e.doneSeries=[...e.doneSeries,o].slice(-60);let s=null,c=p.current;if(c&&c.mode===`count`){let t=D(c.total,1,w.total);if(h.current===`draining`){let r=e.doneSeries.slice(-10),i=r.length?r.reduce((e,t)=>e+t,0)/r.length:0;i<=0&&n>0&&(i=e.completed/(n/1e3)),i>0&&(s=Math.max(0,t-e.completed)/i*1e3)}else a>0&&(s=Math.max(0,t-e.pushed)/a*1e3)}else c&&c.mode===`duration`&&(s=Math.max(0,D(c.durationS,1,w.durationS)*1e3-n));r({pushed:e.pushed,completed:e.completed,pushFailed:e.pushFailed,ackFailed:e.ackFailed,bytes:e.bytes,elapsedMs:n,pushPerSec:a,donePerSec:o,activeWorkers:e.activeWorkers,pushSeries:e.pushSeries,doneSeries:e.doneSeries,etaMs:s,error:e.error})},200);return()=>clearInterval(t)},[e]),{phase:e,live:n,summary:i,history:o,runCfg:c,run:async e=>{if(!d.current){d.current=!0;try{a(null);let n=e.queue.trim();if(!n){r({...I,error:`Queue name is required.`}),t(`error`);return}try{await m.overview()}catch(e){r({...I,error:`Server unreachable — start it on the Server page first. (${M(e)})`}),t(`error`);return}let i=D(e.total,1,w.total),o=D(e.durationS,1,w.durationS)*1e3,c=D(e.batch,1,w.batch),d=D(e.producers,e.mode===`duration`?0:1,w.producers),_=D(e.payload,0,w.payload),v=D(e.workers,0,w.workers),y=D(e.workerBatch,1,w.workerBatch),b=D(e.processMs,0,w.processMs);u.current=!1,f.current=!1,p.current=e,l(e),g.current=L(),g.current.startedAt=performance.now(),g.current.lastAt=performance.now(),r({...I}),t(`running`);let x=`x`.repeat(_),S=performance.now()+o,C=async()=>{for(;!u.current;){let t;if(e.mode===`count`){if(g.current.assigned>=i)break;t=Math.min(c,i-g.current.assigned)}else{if(performance.now()>=S)break;t=c}let r=g.current.assigned;g.current.assigned+=t;let a=k(r,t,x,e.durable,e.removeOnComplete),o=performance.now();try{await m.addJobsBulk(n,a),g.current.pushed+=t,g.current.bytes+=t*_}catch(e){g.current.pushFailed+=t,g.current.error??=M(e)}g.current.pushLat.push(performance.now()-o)}},T=async()=>{for(;!u.current&&!(e.mode===`duration`&&performance.now()>=S||e.mode===`count`&&g.current.completed>=i);){g.current.activeWorkers++;let t=[];try{try{t=(await m.pullBatch(n,y)).jobs??[]}catch(e){g.current.error??=M(e)}if(t.length>0){b>0&&await j(b,()=>!u.current);try{await m.ackBatch(t.map(e=>e.id)),g.current.completed+=t.length}catch(e){g.current.ackFailed+=t.length,g.current.error??=M(e)}}}finally{g.current.activeWorkers--}if(t.length===0){if(e.mode===`count`&&f.current)break;await A(50)}}},E=Array.from({length:d},C),N=Array.from({length:v},T),P=Promise.all(E).then(()=>{f.current=!0,!u.current&&e.mode===`count`&&v>0&&h.current===`running`&&t(`draining`)});await Promise.all([P,...N]);let F=g.current,z=performance.now()-F.startedAt,B=z/1e3||1,V=[...F.pushLat].sort((e,t)=>e-t),H={pushed:F.pushed,completed:F.completed,pushFailed:F.pushFailed,ackFailed:F.ackFailed,bytes:F.bytes,durationMs:z,pushPerSec:F.pushed/B,donePerSec:F.completed/B,mbPerSec:F.bytes/B,avg:V.length?V.reduce((e,t)=>e+t,0)/V.length:0,p50:O(V,50),p95:O(V,95),p99:O(V,99),max:V.length?V[V.length-1]:0,error:F.error};a(H),r(e=>({...e,pushed:F.pushed,completed:F.completed,elapsedMs:z,pushPerSec:0,donePerSec:0,activeWorkers:0,etaMs:0})),s(t=>[{...H,id:++R,at:Date.now(),mode:e.mode,producers:d,workers:v},...t].slice(0,12)),t(u.current?`stopped`:`done`)}finally{d.current=!1}}},stop:()=>{u.current=!0,(h.current===`running`||h.current===`draining`)&&t(`stopping`)},reset:()=>{u.current=!0,a(null),r(I),t(`idle`)},clearHistory:()=>s([])}}var B=[`count`,`duration`],V=[`total`,`durationS`,`batch`,`producers`,`payload`,`workers`,`workerBatch`,`processMs`],H=e=>({...e,total:String(e.total),durationS:String(e.durationS),batch:String(e.batch),producers:String(e.producers),payload:String(e.payload),workers:String(e.workers),workerBatch:String(e.workerBatch),processMs:String(e.processMs)}),U=e=>({...e,total:Number(e.total),durationS:Number(e.durationS),batch:Number(e.batch),producers:Number(e.producers),payload:Number(e.payload),workers:Number(e.workers),workerBatch:Number(e.workerBatch),processMs:Number(e.processMs)});function W(){let[e,n]=(0,C.useState)(()=>H(T)),r=z(),{phase:s,live:O,summary:k,history:A}=r,j=s===`running`||s===`draining`||s===`stopping`,M=(e,t)=>n(n=>({...n,[e]:t})),I=e=>t=>M(e,t.target.value),L=e=>n(t=>{let n={...t};for(let[t,r]of Object.entries(e))n[t]=V.includes(t)?String(r):r;return n}),[R,W]=(0,C.useState)(T.queue);(0,C.useEffect)(()=>{let t=setTimeout(()=>W(e.queue.trim()||T.queue),400);return()=>clearTimeout(t)},[e.queue]);let{data:ee,error:te}=a(()=>m.counts(R),[R],{intervalMs:1e3}),q=ee?.counts??null,[J,Y]=(0,C.useState)(!1),[X,Z]=(0,C.useState)(null),ne=async()=>{let t=e.queue.trim();if(J||!t)return;let n=q&&R===t?` Currently ${d(q.waiting??0)} waiting / ${d(q.completed??0)} completed.`:``;if(window.confirm(`Remove benchmark jobs from "${t}"?${n}`)){Y(!0),Z(null);try{let e=null;for(let n of[`waiting`,`completed`,`failed`,`delayed`])try{await m.clean(t,{state:n,limit:w.total})}catch(t){e=t.message}let n=await m.counts(t).catch(t=>(e=t.message,null));Z(n==null?{error:e??`server unreachable — could not verify`}:{remaining:n.counts?.active??0})}finally{Y(!1)}}},Q=r.runCfg??U(e),$=D(Q.total,1,w.total),re=D(Q.workers,0,w.workers),ie=Q.mode===`count`&&(j||k)?Math.min(100,O.pushed/$*100):0,ae=Q.mode===`count`&&(j||k)?Math.min(100,O.completed/$*100):0,oe=Q.mode===`duration`?Math.min(100,O.elapsedMs/(D(Q.durationS,1,w.durationS)*1e3)*100):0,se=s===`running`?Q.mode===`duration`?`Running…`:`Producing…`:s===`draining`?`Draining…`:s===`stopping`?`Stopping…`:s===`error`?`Error`:k?`Result`:`Ready`,ce=(s===`running`||s===`draining`)&&O.etaMs!=null?O.etaMs>0?`ETA ${g(O.etaMs)}`:`finishing…`:s===`stopped`?`stopped early`:s===`done`?`complete`:``;return(0,P.jsxs)(`div`,{children:[(0,P.jsx)(f,{title:`Benchmark`,description:`Drive real load against the server — producers bulk-enqueue jobs while simulated workers pull, process and ack them. Throughput is measured client-side; the queue genuinely fills and drains.`,actions:s===`stopping`?(0,P.jsxs)(_,{variant:`warning`,size:`sm`,disabled:!0,children:[(0,P.jsx)(l,{className:`size-3.5`}),` Stopping…`]}):j?(0,P.jsxs)(_,{variant:`warning`,size:`sm`,onClick:r.stop,children:[(0,P.jsx)(l,{className:`size-3.5`}),` Stop`]}):(0,P.jsxs)(_,{variant:`success`,size:`sm`,onClick:()=>{let t=U(e),n=t.queue.trim()||T.queue;window.confirm(`Enqueue real jobs into "${n}" on ${i()}?`)&&r.run(t)},children:[(0,P.jsx)(u,{className:`size-3.5`}),` Run benchmark`]})}),O.error&&(0,P.jsx)(`div`,{className:`mb-4 rounded-lg border border-red-500/20 bg-red-500/5 px-4 py-2 text-sm text-danger`,children:O.error}),(0,P.jsxs)(`div`,{className:`mb-4 flex flex-wrap items-center gap-2`,children:[(0,P.jsx)(`span`,{className:`text-xs font-medium uppercase tracking-wider text-faint`,children:`Presets`}),Object.keys(E).map(e=>(0,P.jsx)(`button`,{type:`button`,disabled:j,onClick:()=>L(E[e]),className:`rounded-md border border-line bg-surface-2 px-2.5 py-1 text-xs text-muted transition-colors hover:border-line-strong hover:text-fg disabled:opacity-40`,children:e},e))]}),(0,P.jsxs)(`div`,{className:`grid grid-cols-1 gap-6 lg:grid-cols-3`,children:[(0,P.jsxs)(c,{className:`lg:col-span-1`,children:[(0,P.jsx)(o,{title:`Configuration`}),(0,P.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,P.jsx)(x,{label:`Queue`,hint:`Jobs are enqueued here (created on first push).`,children:(0,P.jsx)(y,{value:e.queue,disabled:j,onChange:e=>M(`queue`,e.target.value)})}),(0,P.jsx)(x,{label:`Mode`,hint:e.mode===`count`?`Push a fixed number of jobs.`:`Run producers + workers for a fixed time.`,children:(0,P.jsx)(v,{options:B,value:e.mode,onChange:e=>M(`mode`,e),disabled:j})}),e.mode===`count`?(0,P.jsx)(x,{label:`Total jobs`,hint:`max ${d(w.total)}`,children:(0,P.jsx)(y,{type:`number`,min:1,max:w.total,value:e.total,disabled:j,onChange:I(`total`)})}):(0,P.jsx)(x,{label:`Duration (s)`,hint:`max ${w.durationS}s`,children:(0,P.jsx)(y,{type:`number`,min:1,max:w.durationS,value:e.durationS,disabled:j,onChange:I(`durationS`)})}),(0,P.jsx)(`div`,{className:`mt-1 text-[11px] font-semibold uppercase tracking-wider text-faint`,children:`Producers`}),(0,P.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,P.jsx)(x,{label:`Producers`,hint:`parallel, max ${w.producers}`,children:(0,P.jsx)(y,{type:`number`,min:e.mode===`duration`?0:1,max:w.producers,value:e.producers,disabled:j,onChange:I(`producers`)})}),(0,P.jsx)(x,{label:`Push batch`,hint:`jobs/req, max ${w.batch}`,children:(0,P.jsx)(y,{type:`number`,min:1,max:w.batch,value:e.batch,disabled:j,onChange:I(`batch`)})}),(0,P.jsx)(x,{label:`Payload`,hint:`bytes/job, max ${d(w.payload)}`,children:(0,P.jsx)(y,{type:`number`,min:0,max:w.payload,value:e.payload,disabled:j,onChange:I(`payload`)})})]}),(0,P.jsx)(`div`,{className:`mt-1 text-[11px] font-semibold uppercase tracking-wider text-faint`,children:`Workers (simulated)`}),(0,P.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,P.jsx)(x,{label:`Workers`,hint:`0 = produce only, max ${w.workers}`,children:(0,P.jsx)(y,{type:`number`,min:0,max:w.workers,value:e.workers,disabled:j,onChange:I(`workers`)})}),(0,P.jsx)(x,{label:`Pull batch`,hint:`jobs/pull, max ${w.workerBatch}`,children:(0,P.jsx)(y,{type:`number`,min:1,max:w.workerBatch,value:e.workerBatch,disabled:j,onChange:I(`workerBatch`)})}),(0,P.jsx)(x,{label:`Process (ms)`,hint:`simulated work per pull`,children:(0,P.jsx)(y,{type:`number`,min:0,max:w.processMs,value:e.processMs,disabled:j,onChange:I(`processMs`)})})]}),(0,P.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2`,children:[(0,P.jsx)(b,{checked:e.durable,onChange:e=>M(`durable`,e),disabled:j}),(0,P.jsx)(`span`,{className:`text-sm text-muted`,children:`Durable (fsync each job)`})]}),(0,P.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2`,children:[(0,P.jsx)(b,{checked:e.removeOnComplete,onChange:e=>M(`removeOnComplete`,e),disabled:j}),(0,P.jsx)(`span`,{className:`text-sm text-muted`,children:`Remove on complete`})]}),(0,P.jsxs)(`div`,{className:`flex items-center gap-3 pt-1`,children:[(0,P.jsx)(_,{variant:`ghost`,size:`sm`,disabled:j||J,onClick:ne,children:J?`Cleaning…`:`Clean queue`}),X&&(`error`in X?(0,P.jsxs)(`span`,{className:`text-xs text-danger`,children:[`Clean unverified — `,X.error]}):(0,P.jsx)(`span`,{className:t(`text-xs`,X.remaining>0?`text-warning`:`text-success`),children:X.remaining>0?`Cleaned — ${d(X.remaining)} active job(s) remain (requeued after the stall timeout)`:`Cleaned — 0 jobs remain`}))]})]})]}),(0,P.jsxs)(`div`,{className:`flex flex-col gap-6 lg:col-span-2`,children:[(0,P.jsxs)(c,{children:[(0,P.jsxs)(`div`,{className:`mb-3 flex items-center justify-between`,children:[(0,P.jsx)(`h3`,{className:`text-base font-semibold text-fg`,children:se}),(0,P.jsx)(`span`,{className:`text-xs text-faint`,children:ce})]}),(0,P.jsx)(G,{label:Q.mode===`duration`?`Elapsed`:`Produced`,pct:Q.mode===`duration`?oe:ie,tone:`accent`}),re>0&&Q.mode===`count`&&(0,P.jsx)(G,{label:`Completed`,pct:ae,tone:`emerald`}),(0,P.jsxs)(`div`,{className:`mt-4 grid grid-cols-2 gap-4 md:grid-cols-4`,children:[(0,P.jsx)(p,{label:`Pushed`,value:d(O.pushed),tone:`accent`,compact:!0}),(0,P.jsx)(p,{label:`Completed`,value:d(O.completed),tone:`green`,compact:!0}),(0,P.jsx)(p,{label:`Push/sec`,value:N(O.pushPerSec),compact:!0}),(0,P.jsx)(p,{label:`Done/sec`,value:N(O.donePerSec),tone:`green`,compact:!0}),(0,P.jsx)(p,{label:`Elapsed`,value:g(O.elapsedMs),compact:!0}),(0,P.jsx)(p,{label:`Active workers`,value:`${O.activeWorkers}/${re}`,tone:`blue`,compact:!0}),(0,P.jsx)(p,{label:`Data`,value:h(k?.bytes??O.bytes),compact:!0}),(0,P.jsx)(p,{label:`Errors`,value:d((k?.pushFailed??O.pushFailed)+(k?.ackFailed??O.ackFailed)),tone:O.pushFailed+O.ackFailed?`red`:`default`,compact:!0})]})]}),(0,P.jsxs)(c,{children:[(0,P.jsx)(o,{title:`Throughput`}),(0,P.jsx)(`p`,{className:`-mt-3 mb-4 text-xs text-faint`,children:`Enqueue (client → server) vs completion (workers) per second`}),(0,P.jsx)(S,{series:[{label:`Push/sec`,color:`#38bdf8`,points:O.pushSeries,area:!0},{label:`Done/sec`,color:`#34d399`,points:O.doneSeries,area:!0}]}),(0,P.jsxs)(`div`,{className:`mt-2 flex items-center gap-4 font-mono text-[11px] text-faint`,children:[(0,P.jsx)(K,{color:`#38bdf8`,label:`Push/sec`,value:O.pushPerSec}),(0,P.jsx)(K,{color:`#34d399`,label:`Done/sec`,value:O.donePerSec})]})]})]})]}),k&&(0,P.jsxs)(c,{className:`mt-6`,children:[(0,P.jsx)(o,{title:`Summary`}),(0,P.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 md:grid-cols-4 xl:grid-cols-8`,children:[(0,P.jsx)(p,{label:`Pushed`,value:d(k.pushed),tone:`accent`,compact:!0}),(0,P.jsx)(p,{label:`Completed`,value:d(k.completed),tone:`green`,compact:!0}),(0,P.jsx)(p,{label:`Duration`,value:g(k.durationMs),compact:!0}),(0,P.jsx)(p,{label:`Avg push/s`,value:N(k.pushPerSec),tone:`accent`,compact:!0}),(0,P.jsx)(p,{label:`Avg done/s`,value:N(k.donePerSec),tone:`green`,compact:!0}),(0,P.jsx)(p,{label:`Data rate`,value:`${h(k.mbPerSec)}/s`,compact:!0}),(0,P.jsx)(p,{label:`Push p95`,value:g(k.p95),compact:!0}),(0,P.jsx)(p,{label:`Push p99`,value:g(k.p99),compact:!0})]}),(0,P.jsxs)(`p`,{className:`mt-3 text-xs text-faint`,children:[`Push-batch latency avg `,g(k.avg),` · p50 `,g(k.p50),` · p95`,` `,g(k.p95),` · p99 `,g(k.p99),` · max `,g(k.max),`.`,k.error?` First error: ${k.error}`:``]})]}),(0,P.jsxs)(c,{className:`mt-6`,children:[(0,P.jsx)(o,{title:`Server queue: ${R}`,action:te?(0,P.jsx)(`span`,{className:`text-xs font-medium text-warning`,children:`stale — server unreachable`}):void 0}),(0,P.jsx)(`p`,{className:`-mt-3 mb-4 text-xs text-faint`,children:`Live counts from the server (poll 1s).`}),q?(0,P.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 md:grid-cols-5`,children:[(0,P.jsx)(p,{label:`Waiting`,value:d(q.waiting??0),tone:`amber`,compact:!0}),(0,P.jsx)(p,{label:`Active`,value:d(q.active??0),tone:`blue`,compact:!0}),(0,P.jsx)(p,{label:`Completed`,value:d(q.completed??0),tone:`green`,compact:!0}),(0,P.jsx)(p,{label:`Failed`,value:d(q.failed??0),tone:q.failed?`red`:`default`,compact:!0}),(0,P.jsx)(p,{label:`Delayed`,value:d(q.delayed??0),compact:!0})]}):(0,P.jsx)(`p`,{className:`text-sm text-faint`,children:`No counts yet — waiting for the server to answer for this queue.`})]}),(0,P.jsx)(F,{history:A,onClear:r.clearHistory})]})}function G({label:e,pct:n,tone:r}){return(0,P.jsxs)(`div`,{className:`mb-2`,children:[(0,P.jsxs)(`div`,{className:`mb-1 flex items-center justify-between text-[11px] text-faint`,children:[(0,P.jsx)(`span`,{children:e}),(0,P.jsxs)(`span`,{className:`tnum`,children:[n.toFixed(0),`%`]})]}),(0,P.jsx)(`div`,{className:`h-1.5 overflow-hidden rounded-full bg-surface-2`,children:(0,P.jsx)(`div`,{className:t(`h-full rounded-full transition-all`,r===`accent`?`bg-accent`:`bg-emerald-500`),style:{width:`${n}%`}})})]})}function K({color:e,label:t,value:n}){return(0,P.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,P.jsx)(`span`,{className:`size-2 rounded-full`,style:{background:e}}),t,` `,(0,P.jsxs)(`span`,{className:`text-fg`,children:[N(n),`/s`]})]})}export{W as Benchmark};
@@ -1,5 +0,0 @@
1
- import{r as e}from"./cn-CMFYpumL.js";import{h as t,t as n}from"./react-vendor-B68RYDeC.js";import{A as r,C as i,S as a,h as o,nt as s,rt as c,w as l}from"./index-BFRKPhvf.js";import{i as u,n as d,t as f}from"./form-C-zZyKfB.js";var p=e(t(),1),m=n(),h=1e4,g=`[
2
- { "data": { "to": "a@example.com", "template": "welcome" }, "priority": 1 },
3
- { "data": { "to": "b@example.com", "template": "welcome" } }
4
- ]`,_=e=>{let t=Number(e);return e.trim()!==``&&Number.isFinite(t)?t:void 0},v=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,y=e=>typeof e==`boolean`?e:void 0,b=e=>typeof e==`string`&&e!==``?e:void 0;function x(e,t,n){if(n===`spec`&&e&&typeof e==`object`&&!Array.isArray(e)&&`data`in e){let n=e;return{data:n.data,priority:v(n.priority)??t.priority,delay:v(n.delay),maxAttempts:v(n.maxAttempts)??t.maxAttempts,backoff:v(n.backoff)??t.backoff,timeout:v(n.timeout)??t.timeout,jobId:b(n.jobId),removeOnComplete:y(n.removeOnComplete),removeOnFail:y(n.removeOnFail),durable:y(n.durable),lifo:y(n.lifo),ttl:v(n.ttl),uniqueKey:b(n.uniqueKey)}}return{data:e,...t}}var S=new Set([`data`,`priority`,`delay`,`maxAttempts`,`backoff`,`timeout`,`jobId`,`removeOnComplete`,`removeOnFail`,`durable`,`lifo`,`ttl`,`uniqueKey`]);function C(e){return e.some(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`data`in e&&Object.keys(e).some(e=>!S.has(e)))}function w(e){let t=e.trim();if(!t)return{items:[],error:null};try{let e=JSON.parse(t);return Array.isArray(e)?{items:e,error:null}:{items:[e],error:null}}catch{}let n=[],r=t.split(`
5
- `);for(let e=0;e<r.length;e++){let t=r[e].trim();if(t)try{n.push(JSON.parse(t))}catch(t){return{items:[],error:`Line ${e+1}: ${t.message}`}}}return{items:n,error:null}}function T(){let{data:e}=r(()=>s.queues(),[],{intervalMs:3e4}),[t,n]=(0,p.useState)(``),[v,y]=(0,p.useState)(``),[b,S]=(0,p.useState)(`spec`),[T,E]=(0,p.useState)(``),[D,O]=(0,p.useState)(``),[k,A]=(0,p.useState)(``),[j,M]=(0,p.useState)(``),[N,P]=(0,p.useState)(!1),[F,I]=(0,p.useState)(null),{items:L,error:R}=(0,p.useMemo)(()=>w(v),[v]),z=b===`spec`&&!R&&C(L);return(0,m.jsxs)(`div`,{children:[(0,m.jsx)(o,{title:`Bulk Add Jobs`,description:`Import many distinct jobs at once from a JSON array, NDJSON, or a file.`}),(0,m.jsxs)(`div`,{className:`grid grid-cols-1 gap-6 lg:grid-cols-3`,children:[(0,m.jsxs)(a,{className:`lg:col-span-2`,children:[(0,m.jsx)(i,{title:`Jobs`,action:(0,m.jsxs)(`label`,{className:`cursor-pointer rounded-lg border border-line px-3 py-1.5 text-xs text-muted hover:bg-surface-2 hover:text-fg`,children:[`Upload file`,(0,m.jsx)(`input`,{type:`file`,accept:`.json,.ndjson,.txt,application/json`,onChange:e=>{let t=e.target.files?.[0];if(!t)return;if(v.trim()!==``&&!window.confirm(`Replace the current input with "${t.name}"?`)){e.target.value=``;return}let n=new FileReader;n.onload=()=>y(String(n.result??``)),n.onerror=()=>I({ok:!1,msg:`Could not read file`}),n.readAsText(t),e.target.value=``},className:`hidden`})]})}),(0,m.jsx)(`textarea`,{value:v,onChange:e=>y(e.target.value),spellCheck:!1,rows:16,placeholder:g,"aria-label":`Jobs JSON`,className:`w-full rounded-lg border border-line bg-surface-2 p-3 font-mono text-xs text-fg placeholder:text-faint focus:border-accent/60 focus:outline-none focus:ring-2 focus:ring-accent/30`}),(0,m.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-3`,children:[(0,m.jsx)(`span`,{className:`text-xs font-medium text-faint`,children:`Interpret each item as`}),(0,m.jsx)(u,{options:[`spec`,`raw`],value:b,onChange:S}),(0,m.jsx)(`span`,{className:`text-xs text-faint`,children:b===`spec`?`job spec: an object with a "data" key sets options from its sibling fields.`:`raw data: the whole item becomes the job payload, untouched.`})]}),(0,m.jsx)(`p`,{className:`mt-2 text-xs text-faint`,children:`Accepts a JSON array, a single object, or newline-delimited JSON.`}),(0,m.jsx)(`div`,{className:`mt-2 text-sm`,children:R?(0,m.jsx)(`span`,{className:`text-danger`,children:R}):L.length>0?(0,m.jsxs)(`span`,{className:`text-success`,children:[L.length,` job(s) parsed ✓`]}):(0,m.jsx)(`span`,{className:`text-faint`,children:`Nothing parsed yet.`})}),z&&(0,m.jsx)(`p`,{className:`mt-2 text-xs text-warning`,children:`Some items carry keys beyond the known job options — in “spec” mode those keys are dropped. Switch to “raw” to keep every field as the job's data.`})]}),(0,m.jsxs)(a,{children:[(0,m.jsx)(i,{title:`Target & defaults`}),(0,m.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,m.jsxs)(f,{label:`Queue`,children:[(0,m.jsx)(d,{list:`bulk-queue-options`,value:t,onChange:e=>n(e.target.value),placeholder:`queue name (existing or new)`}),(0,m.jsx)(`datalist`,{id:`bulk-queue-options`,children:(e?.queues??[]).map(e=>(0,m.jsx)(`option`,{value:e.name},e.name))})]}),(0,m.jsx)(`p`,{className:`-mt-2 text-xs text-faint`,children:`Defaults below fill any field an item omits.`}),(0,m.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,m.jsx)(f,{label:`Priority`,children:(0,m.jsx)(d,{type:`number`,value:T,onChange:e=>E(e.target.value),placeholder:`0`})}),(0,m.jsx)(f,{label:`Max attempts`,children:(0,m.jsx)(d,{type:`number`,min:0,value:D,onChange:e=>O(e.target.value),placeholder:`3`})}),(0,m.jsx)(f,{label:`Backoff (ms)`,children:(0,m.jsx)(d,{type:`number`,min:0,value:k,onChange:e=>A(e.target.value),placeholder:`1000`})}),(0,m.jsx)(f,{label:`Timeout (ms)`,children:(0,m.jsx)(d,{type:`number`,min:0,value:j,onChange:e=>M(e.target.value),placeholder:`—`})})]}),(0,m.jsx)(`div`,{className:`flex items-center gap-3`,children:(0,m.jsx)(l,{variant:`accent`,disabled:N||L.length===0||R!=null,onClick:async()=>{if(I(null),!t.trim()){I({ok:!1,msg:`Choose a queue`});return}if(R){I({ok:!1,msg:R});return}if(L.length===0){I({ok:!1,msg:`Nothing to enqueue — paste a JSON array or NDJSON.`});return}if(L.length>h){I({ok:!1,msg:`Too many jobs (${L.length}). Limit is ${h}.`});return}let e=e=>e!=null&&e<0?0:e,n={priority:_(T),maxAttempts:e(_(D)),backoff:e(_(k)),timeout:e(_(j))},r=L.map(e=>x(e,n,b));P(!0);try{let e=await s.addJobsBulk(t,r),n=new Set(e.ids).size,i=`Created ${n} job${n===1?``:`s`} in ${t}`;I({ok:!0,msg:i}),c.success(i)}catch(e){let t=e.message;I({ok:!1,msg:t}),c.error(`Bulk import failed`,t)}finally{P(!1)}},children:N?`Importing…`:`Import ${L.length||``}`})}),F&&(0,m.jsx)(`span`,{role:`status`,className:F.ok?`text-sm text-success`:`text-sm text-danger`,children:F.msg})]})]})]})]})}export{T as BulkAddJobs};