@cardinali-studio/adminkit 2.2.39 → 2.2.41
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.
- package/README.md +55 -0
- package/dist/app/App.js +4 -3
- package/dist/app/app.css +49 -0
- package/dist/app/delivery.js +5 -3
- package/dist/app/routes/Deliveries.js +2 -2
- package/dist/app/routes/DeliveryDashboard.d.ts +4 -0
- package/dist/app/routes/DeliveryDashboard.js +50 -0
- package/dist/functions/_shared/b2.js +67 -5
- package/dist/functions/_shared/delivery-manifest.js +2 -1
- package/dist/functions/_shared/delivery-purge.js +100 -66
- package/dist/functions/_shared/delivery-storage-dashboard.js +100 -0
- package/dist/functions/api/deliveries.js +14 -3
- package/dist/functions/api/delivery/multipart.js +4 -1
- package/dist/functions/delivery-public/index.js +2 -12
- package/dist/functions/delivery-public/migrations/0010_delivery_storage_cleanup.sql +19 -0
- package/dist/functions/delivery-public/migrations/0011_delivery_storage_dashboard.sql +14 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -204,6 +204,40 @@ Persistent checkpoints record `store-header-v1`. Checkpoints from earlier releas
|
|
|
204
204
|
|
|
205
205
|
The regression includes 208 synthetic members with the collision at member 53, streaming and indexed readers, ZIP64 offsets, and byte-identical resume against fixtures from 2.2.37.
|
|
206
206
|
|
|
207
|
+
## Permanent delivery storage cleanup
|
|
208
|
+
|
|
209
|
+
Delivery cleanup permanently deletes **all versions and delete markers** in the
|
|
210
|
+
removed package's exact storage prefix, and aborts unfinished multipart uploads.
|
|
211
|
+
Successful deletion requires a subsequent empty listing; a failed or partial sweep
|
|
212
|
+
keeps the database work for retry. No bucket-wide cleanup or lifecycle is installed.
|
|
213
|
+
|
|
214
|
+
Apply `dist/functions/delivery-public/migrations/0010_delivery_storage_cleanup.sql`
|
|
215
|
+
to the consumer's delivery D1 **before** deploying this code. The new
|
|
216
|
+
`delivery_storage_cleanup` table has no foreign keys: its scoped tombstones survive
|
|
217
|
+
removal of a delivery, so a PUT or multipart completion already in flight cannot
|
|
218
|
+
become permanently untracked. The housekeeping caller must continue invoking
|
|
219
|
+
`purgeDue` independently of visits to the admin or public pages. Scopes are checked
|
|
220
|
+
again after 15 minutes in the first hour, then daily, subject to the caller's request
|
|
221
|
+
budget and backlog. Tombstones are deliberately retained indefinitely. `last_error`
|
|
222
|
+
records failed sweeps; `last_checked_at` records successful empty verification.
|
|
223
|
+
|
|
224
|
+
Expired deliveries cannot request new upload signatures or start/finalize new
|
|
225
|
+
packages. An uploading package retains its one-hour metadata grace period;
|
|
226
|
+
its durable scope also catches requests finishing after that grace period.
|
|
227
|
+
A late write can occupy space temporarily until the next successful sweep.
|
|
228
|
+
|
|
229
|
+
The opt-in live regression `scripts/verify-delivery-storage.mjs` uses a new random
|
|
230
|
+
prefix and an in-memory D1 database. It creates versions, a delete marker, an
|
|
231
|
+
unfinished multipart upload, and a PUT authorized before deletion. It checks zero
|
|
232
|
+
remaining versions/bytes/uploads after both deletion and expiration, and compares
|
|
233
|
+
all pre-existing version IDs before and after. Every mutation outside the new
|
|
234
|
+
prefix is refused. Configuration and secret-file paths are arguments; credentials
|
|
235
|
+
are never printed. This test does not deploy a Worker or change lifecycle rules.
|
|
236
|
+
|
|
237
|
+
Do not deploy this cleanup against a populated production bucket when existing
|
|
238
|
+
objects must be preserved: pending/expired deliveries would become eligible for
|
|
239
|
+
permanent deletion. The migration alone is additive and does not enqueue old data.
|
|
240
|
+
|
|
207
241
|
## Development
|
|
208
242
|
|
|
209
243
|
```sh
|
|
@@ -219,3 +253,24 @@ Generated files live in `dist/` and are the only application files included in t
|
|
|
219
253
|
## License
|
|
220
254
|
|
|
221
255
|
[0BSD](./LICENSE). Use it, copy it, change it, ship it. Attribution is appreciated but not required.
|
|
256
|
+
|
|
257
|
+
## Delivery dashboard
|
|
258
|
+
|
|
259
|
+
The delivery overview reads download **requests**, not completed downloads. Active
|
|
260
|
+
transfers have ready packages, unexpired files and at least one valid link.
|
|
261
|
+
|
|
262
|
+
Before enabling `DELIVERY_STORAGE_DASHBOARD=true`, apply
|
|
263
|
+
`dist/functions/delivery-public/migrations/0011_delivery_storage_dashboard.sql` to
|
|
264
|
+
the consumer's delivery D1 database. In the consumer's existing scheduled handler,
|
|
265
|
+
call `verifyDeliveryStorage(env, {maxCalls: 4})` from
|
|
266
|
+
`@cardinali-studio/adminkit/functions/_shared/delivery-storage-dashboard.js` after
|
|
267
|
+
housekeeping. Run the handler every 15 minutes: completed inventories refresh
|
|
268
|
+
hourly; larger inventories resume across invocations. Admin polling also resumes
|
|
269
|
+
due work, and “Verifica ora” forces a fresh check.
|
|
270
|
+
|
|
271
|
+
The read-only scan sums all B2 object versions and uploaded multipart parts,
|
|
272
|
+
including hidden versions and unassigned keys. It stores only complete totals,
|
|
273
|
+
retaining the previous snapshot on failure, and shows the last completion time.
|
|
274
|
+
Concurrent B2 writes can change storage during the scan; this is a measured
|
|
275
|
+
inventory, not the provider's billing statement. Dashboard checks never delete
|
|
276
|
+
objects. The existing preservation policy remains independent of this feature.
|
package/dist/app/App.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
|
+
import { DeliveryDashboard } from "./routes/DeliveryDashboard.js";
|
|
2
3
|
/* Il guscio del pannello: tre colonne fisse.
|
|
3
4
|
*
|
|
4
5
|
* 1. dove sono la navigazione principale — non cambia mai
|
|
@@ -91,7 +92,7 @@ function CurrentAdminApp({ adminInterface, setAdminInterface, }) {
|
|
|
91
92
|
const requests = useRequests();
|
|
92
93
|
const publish = usePublish();
|
|
93
94
|
const deliverySettingsOpen = section === "deliveries" && route[1] === "settings";
|
|
94
|
-
const activeDeliveryId = section === "deliveries" && !deliverySettingsOpen ? route[1] : undefined;
|
|
95
|
+
const activeDeliveryId = section === "deliveries" && !deliverySettingsOpen && route[1] !== "new" ? route[1] : undefined;
|
|
95
96
|
/* Come Richieste, Consegne carica subito l'elenco: il badge "in scadenza" deve
|
|
96
97
|
esistere prima di entrare nella sezione. Il dettaglio resta pigro. */
|
|
97
98
|
const deliveries = useDeliveries(activeDeliveryId);
|
|
@@ -296,7 +297,7 @@ function CurrentAdminApp({ adminInterface, setAdminInterface, }) {
|
|
|
296
297
|
}) }) })] })), section === "deliveries" && (_jsxs(_Fragment, { children: [_jsxs("div", { className: "col-head col-head-actions", children: [_jsx("span", { className: "col-title", children: "Transfer" }), _jsx(NewDeliveryButton, { onCreate: () => {
|
|
297
298
|
setQuickSelectedId(undefined);
|
|
298
299
|
setQuickKey((value) => value + 1);
|
|
299
|
-
go("/deliveries");
|
|
300
|
+
go("/deliveries/new");
|
|
300
301
|
} })] }), _jsx("div", { className: "col-body", children: deliveries.error ? _jsx("p", { className: "ak-error", children: deliveries.error })
|
|
301
302
|
: !deliveries.rows ? _jsx("p", { className: "ak-hint", children: "Carico\u2026" })
|
|
302
303
|
: deliveries.rows.length === 0 ? _jsx("p", { className: "ak-hint", children: "Nessun transfer, per ora." })
|
|
@@ -340,7 +341,7 @@ function CurrentAdminApp({ adminInterface, setAdminInterface, }) {
|
|
|
340
341
|
: _jsx(MediaGrid, { lib: media })), view === "trash" && _jsx(Trash, {}), section === "requests" && (requests.error ? _jsx("p", { className: "ak-error", children: requests.error })
|
|
341
342
|
: openReq ? (_jsx(RequestDetail, { row: openReq, onMark: (h) => void requests.mark([openReq.id], h), onRemove: () => { void requests.remove([openReq.id]); go("/requests"); } }))
|
|
342
343
|
: _jsx("p", { className: "pane-empty ak-hint", children: requests.rows?.length ? "Scegli una richiesta dall'elenco." : "" })), section === "deliveries" && (deliveries.error ? _jsx("p", { className: "ak-error", children: deliveries.error })
|
|
343
|
-
: deliverySettingsOpen ? (_jsx(DeliverySettings, { settings: deliveries.settings, onAction: deliveries.action, pickMedia: pickMedia })) : activeDeliveryId && !deliveries.detail ? (_jsx("p", { className: "pane-empty ak-hint", children: "Carico\u2026" })) : (
|
|
344
|
+
: deliverySettingsOpen ? (_jsx(DeliverySettings, { settings: deliveries.settings, onAction: deliveries.action, pickMedia: pickMedia })) : activeDeliveryId && !deliveries.detail ? (_jsx("p", { className: "pane-empty ak-hint", children: "Carico\u2026" })) : !activeDeliveryId && route[1] !== "new" ? (_jsx(DeliveryDashboard, { onCreate: () => { setQuickSelectedId(undefined); setQuickKey(v => v + 1); go("/deliveries/new"); }, onOpen: id => go(`/deliveries/${id}`) })) : (
|
|
344
345
|
/* Un transfer nuovo e uno già spedito sono la stessa schermata: cambia solo se
|
|
345
346
|
arriva già con dei dati. La `key` la rimonta quando si passa da un transfer
|
|
346
347
|
all'altro, e quando «Nuovo transfer» chiede di ricominciare da capo. */
|
package/dist/app/app.css
CHANGED
|
@@ -2360,3 +2360,52 @@ body:has(.uk) .pane-body { padding-bottom: 190px; }
|
|
|
2360
2360
|
}
|
|
2361
2361
|
:root[data-admin-interface="next"] .rail-foot > .ak-release-control.ak-release-control{width:auto;height:auto;overflow:visible}
|
|
2362
2362
|
:root[data-admin-interface="next"] .rail-foot > .ak-release-control.ak-release-control > .ak-release-trigger{width:auto;min-width:104px;display:inline-flex;gap:9px;padding:0 14px;color:var(--ak-rail-ink-on);font:600 12px/1 var(--ak-font);overflow:visible}
|
|
2363
|
+
|
|
2364
|
+
/* Consegne: panoramica e inventario B2, con dati di verifica separati dai contatori. */
|
|
2365
|
+
.dd-dashboard { max-width: 1440px; width: 100%; min-width: 0; margin: 0 auto; display: grid; gap: 22px; padding: 8px 0 28px; }
|
|
2366
|
+
.dd-dashboard>* { min-width: 0; }
|
|
2367
|
+
.dd-heading>div,.dd-storage-head>div { min-width: 0; }
|
|
2368
|
+
.dd-heading h2,.dd-metric>span { overflow-wrap: anywhere; }
|
|
2369
|
+
.dd-heading,.dd-storage-head { display: flex; gap: 20px; align-items: center; justify-content: space-between; }
|
|
2370
|
+
.dd-heading h2 { margin: 5px 0 8px; font-size: 28px; font-weight: 600; letter-spacing: -.7px; }
|
|
2371
|
+
.dd-heading p,.dd-storage-head p { margin: 0; color: var(--ak-ink-quiet); font-size: 12px; line-height: 1.6; }
|
|
2372
|
+
.dd-heading .dd-eyebrow { text-transform: uppercase; letter-spacing: 1.5px; font-size: 10px; font-weight: 600; }
|
|
2373
|
+
.dd-metrics,.dd-storage-grid { display: grid; grid-template-columns: repeat(4,minmax(0,1fr)); gap: 12px; }
|
|
2374
|
+
.dd-metrics>.dd-metric,.dd-storage,.dd-transfers { background: var(--ak-panel); border: 1px solid var(--ak-line); border-radius: var(--ak-radius); }
|
|
2375
|
+
.dd-metric { padding: 19px; min-width: 0; }
|
|
2376
|
+
.dd-metric>span { display: block; color: var(--ak-ink-quiet); font-size: 11px; }
|
|
2377
|
+
.dd-metric>strong { display: block; font-size: clamp(23px,2.1vw,34px); line-height: 1.2; font-weight: 550; letter-spacing: -.7px; margin: 13px 0 10px; font-variant-numeric: tabular-nums; }
|
|
2378
|
+
.dd-metric>p { margin: 0; font-size: 10px; line-height: 1.6; color: var(--ak-ink-quiet); }
|
|
2379
|
+
.dd-storage-head { padding: 20px; border-bottom: 1px solid var(--ak-line); }
|
|
2380
|
+
.dd-title-row { display: flex; align-items: center; flex-wrap: wrap; gap: 10px; }
|
|
2381
|
+
.dd-title-row h3 { font-size: 14px; font-weight: 600; margin: 0; }
|
|
2382
|
+
.dd-title-row>span { font-size: 11px; color: var(--ak-ink-quiet); }
|
|
2383
|
+
.dd-status { padding: 4px 9px; border-radius: 30px; background: color-mix(in srgb,#2b825d 10%,var(--ak-panel)); color: #28744f !important; }
|
|
2384
|
+
.dd-status.is-running { color: var(--ak-ink) !important; background: var(--ak-bg); }
|
|
2385
|
+
.dd-status.is-error { background: color-mix(in srgb,#bd6d2a 12%,var(--ak-panel)); color: #aa612a !important; }
|
|
2386
|
+
.dd-storage-head p { margin-top: 8px; font-size: 11px; }
|
|
2387
|
+
.dd-storage-grid { gap: 0; }
|
|
2388
|
+
.dd-storage-grid>.dd-metric+ .dd-metric { border-left: 1px solid var(--ak-line); }
|
|
2389
|
+
.dd-storage-grid .dd-metric>strong { font-size: 25px; }
|
|
2390
|
+
.dd-footnote { font-size: 10px; color: var(--ak-ink-quiet); margin: 0; line-height: 1.7; }
|
|
2391
|
+
.dd-storage>.dd-footnote { border-top: 1px solid var(--ak-line); padding: 12px 20px; }
|
|
2392
|
+
.dd-transfers { padding: 20px; }
|
|
2393
|
+
.dd-transfers>.dd-title-row { justify-content: space-between; margin-bottom: 8px; }
|
|
2394
|
+
.dd-table-wrap { overflow-x: auto; margin-top: 18px; }
|
|
2395
|
+
.dd-table-wrap table { width: 100%; border-collapse: collapse; text-align: left; font-size: 12px; }
|
|
2396
|
+
.dd-table-wrap th { font-size: 10px; font-weight: 500; color: var(--ak-ink-quiet); padding: 0 12px 12px; white-space: nowrap; }
|
|
2397
|
+
.dd-table-wrap td { padding: 13px 12px; border-top: 1px solid var(--ak-line); font-variant-numeric: tabular-nums; }
|
|
2398
|
+
.dd-table-wrap th:first-child,.dd-table-wrap td:first-child { padding-left: 0; }
|
|
2399
|
+
.dd-transfer-link { border: 0; padding: 0; background: transparent; cursor: pointer; color: var(--ak-ink); text-align: left; font: inherit; }
|
|
2400
|
+
.dd-transfer-link strong { display: block; font-size: 12px; font-weight: 550; }
|
|
2401
|
+
.dd-transfer-link span { display: block; font-size: 10px; margin-top: 4px; color: var(--ak-ink-quiet); }
|
|
2402
|
+
.dd-transfer-link:hover strong { text-decoration: underline; }
|
|
2403
|
+
.dd-request { display: inline-block; white-space: nowrap; font-size: 10px; color: #28744f; }
|
|
2404
|
+
.dd-request.is-pending { color: var(--ak-ink-quiet); }
|
|
2405
|
+
:root[data-theme="dark"] .dd-status:not(.is-running):not(.is-error),:root[data-theme="dark"] .dd-request:not(.is-pending) { color: #80c7a0 !important; }
|
|
2406
|
+
:root[data-theme="dark"] .dd-status.is-error { color: #eeb177 !important; }
|
|
2407
|
+
.dd-notice,.dd-error { margin: 0; padding: 12px 20px; font-size: 12px; line-height: 1.6; color: var(--ak-ink-quiet); }
|
|
2408
|
+
.dd-empty { padding: 25px 0; color: var(--ak-ink-quiet); font-size: 12px; }
|
|
2409
|
+
@media(max-width:1100px) { .dd-metrics,.dd-storage-grid { grid-template-columns: repeat(2,minmax(0,1fr)); } .dd-storage-grid>.dd-metric:nth-child(3) { border-left: 0; } .dd-storage-grid>.dd-metric:nth-child(n+3) { border-top: 1px solid var(--ak-line); } }
|
|
2410
|
+
@media(max-width:600px) { .dd-heading,.dd-storage-head { align-items: flex-start; flex-direction: column; gap: 12px; } .dd-heading h2 { font-size: 25px; } .dd-dashboard { gap: 16px; } .dd-metric { padding: 14px; } .dd-table-wrap table { min-width: 600px; } }
|
|
2411
|
+
@media(max-width:700px) { .app:has(.dd-dashboard)>.col { display: none; } .app:has(.dd-dashboard)>.pane { grid-column: 2 / -1; } }
|
package/dist/app/delivery.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { DeliveryDashboard } from "./routes/DeliveryDashboard.js";
|
|
2
3
|
import { StrictMode, useEffect, useState } from "react";
|
|
3
4
|
import { createRoot } from "react-dom/client";
|
|
4
5
|
import { setStoragePrefix } from "../index.js";
|
|
@@ -22,7 +23,7 @@ export function mountDeliveryAdmin(options) {
|
|
|
22
23
|
}
|
|
23
24
|
function DeliveryAdmin({ name, websiteUrl }) {
|
|
24
25
|
const [route, go] = useHashRoute();
|
|
25
|
-
const id = route[0] === "deliveries" ? route[1] : undefined;
|
|
26
|
+
const id = route[0] === "deliveries" && route[1] !== "new" ? route[1] : undefined;
|
|
26
27
|
const api = useDeliveries(id);
|
|
27
28
|
const { theme, toggle } = useTheme();
|
|
28
29
|
const completions = useUploadCompletions();
|
|
@@ -39,8 +40,9 @@ function DeliveryAdmin({ name, websiteUrl }) {
|
|
|
39
40
|
const open = (value) => { setSelectedId(undefined); go(`/deliveries/${value}`); };
|
|
40
41
|
// Never render the previous transfer while the requested detail is loading.
|
|
41
42
|
const detail = id && api.detail?.id === id ? api.detail : null;
|
|
42
|
-
return _jsxs("div", { className: "app", children: [_jsxs("nav", { className: "rail", "aria-label": "Navigazione", children: [_jsxs("div", { className: "rail-brand", children: [_jsx("span", { className: "rail-brand-name", children: name }), _jsx("span", { className: "rail-brand-role", children: "Consegne" })] }), _jsx("button", { className: "rail-item is-on", onClick: () => go("/deliveries"), children: "Transfer" }), _jsxs("div", { className: "rail-foot", children: [websiteUrl && _jsx("a", { className: "rail-item", href: websiteUrl, target: "_blank", rel: "noreferrer", children: "Sito dello studio" }), _jsx("button", { className: "rail-item", onClick: toggle, children: theme === "dark" ? "Tema chiaro" : "Tema scuro" })] })] }), _jsxs("aside", { className: "col", "aria-label": "Elenco transfer", children: [_jsxs("div", { className: "col-head col-head-actions", children: [_jsx("span", { className: "col-title", children: "Transfer" }), _jsx(NewDeliveryButton, { onCreate: () => { setSelectedId(undefined); setDraftKey(v => v + 1); go("/deliveries"); } })] }), _jsx("div", { className: "col-body", children: !api.rows ? _jsx("p", { className: "ak-hint", children: "Carico\u2026" }) : api.rows.length === 0 ? _jsx("p", { className: "ak-hint", children: "Nessun transfer, per ora." })
|
|
43
|
+
return _jsxs("div", { className: "app", children: [_jsxs("nav", { className: "rail", "aria-label": "Navigazione", children: [_jsxs("div", { className: "rail-brand", children: [_jsx("span", { className: "rail-brand-name", children: name }), _jsx("span", { className: "rail-brand-role", children: "Consegne" })] }), _jsx("button", { className: "rail-item is-on", onClick: () => go("/deliveries"), children: "Transfer" }), _jsxs("div", { className: "rail-foot", children: [websiteUrl && _jsx("a", { className: "rail-item", href: websiteUrl, target: "_blank", rel: "noreferrer", children: "Sito dello studio" }), _jsx("button", { className: "rail-item", onClick: toggle, children: theme === "dark" ? "Tema chiaro" : "Tema scuro" })] })] }), _jsxs("aside", { className: "col", "aria-label": "Elenco transfer", children: [_jsxs("div", { className: "col-head col-head-actions", children: [_jsx("span", { className: "col-title", children: "Transfer" }), _jsx(NewDeliveryButton, { onCreate: () => { setSelectedId(undefined); setDraftKey(v => v + 1); go("/deliveries/new"); } })] }), _jsx("div", { className: "col-body", children: !api.rows ? _jsx("p", { className: "ak-hint", children: "Carico\u2026" }) : api.rows.length === 0 ? _jsx("p", { className: "ak-hint", children: "Nessun transfer, per ora." })
|
|
43
44
|
: _jsx(DeliveriesList, { rows: api.rows, current: id || selectedId, onOpen: open }) }), _jsx("div", { className: "dl-col-foot", children: api.rows && _jsx(DeliveriesTotal, { rows: api.rows }) })] }), _jsx("main", { className: "pane", children: _jsx("div", { className: "pane-body", children: api.error ? _jsxs("div", { role: "alert", children: [_jsx("p", { className: "ak-error", children: api.error }), _jsx("button", { className: "ak-btn", onClick: () => void api.refresh(), children: "Riprova" })] })
|
|
44
45
|
: id && !detail ? _jsx("p", { className: "ak-hint", children: "Carico\u2026" })
|
|
45
|
-
:
|
|
46
|
+
: !id && route[1] !== "new" ? _jsx(DeliveryDashboard, { onCreate: () => { setSelectedId(undefined); setDraftKey(v => v + 1); go("/deliveries/new"); }, onOpen: open })
|
|
47
|
+
: _jsx(DeliveryWorkspace, { delivery: detail, busy: api.busy, onAction: api.action, onRefresh: api.refresh, onReload: api.load, onRead: api.read, onDeleted: () => go("/deliveries"), onOpen: open, onSelected: setSelectedId }, id || `new-${draftKey}`) }) }), _jsx(UploadDock, {})] });
|
|
46
48
|
}
|
|
@@ -407,7 +407,7 @@ export function DeliveryWorkspace({ delivery: fromServer, busy, onAction, onRefr
|
|
|
407
407
|
}
|
|
408
408
|
}, children: "Accorcia link" })), _jsx("button", { className: "ak-btn ak-btn-primary", onClick: () => void copy(link.url, "link"), children: copied === "link" ? "Copiato" : "Copia il link" }), _jsx("button", { className: "ak-btn", onClick: () => void copy(messageFor(draft, link, expiry), "messaggio"), children: copied === "messaggio" ? "Copiato" : "Copia il messaggio" }), _jsx("a", { className: "ak-btn", target: "_blank", rel: "noreferrer", href: `https://wa.me/?text=${encodeURIComponent(messageFor(draft, link, expiry))}`, children: "Apri in WhatsApp" })] }), _jsx("p", { className: "dl-link-stats", children: linkStory(link) }), draft.pin && (_jsxs("p", { className: "dl-link-stats", children: ["Codice di accesso ", _jsx("strong", { children: draft.pin }), " \u2014 \u00E8 gi\u00E0 dentro il messaggio."] }))] })) : (_jsxs("section", { className: "dl-card dl-get", children: [_jsx("button", { className: "ak-btn ak-btn-primary dl-get-btn", disabled: !delivery || saving || busy, onClick: () => void save(), children: saving ? "Preparo…" : "Ottieni il link" }), _jsx("p", { children: delivery
|
|
409
409
|
? "Il link vale già mentre l'upload continua: chi lo apre vede che i file stanno arrivando."
|
|
410
|
-
: "Aggiungi i file: il caricamento parte subito e il resto si compila mentre va." })] }))] }), _jsxs("div", { className: "dl-side", children: [_jsxs(Group, { title: "Chi pu\u00F2 aprirlo", children: [_jsxs("label", { className: "dl-radio", children: [_jsx("input", { type: "radio", name: "dl-access", checked: !draft.pin, onChange: () => change({ pin: "" }) }), _jsxs("span", { children: [_jsx("strong", { children: "Chiunque abbia il link" }), _jsx("small", { children: "Il link \u00E8 lungo e casuale: non si indovina." })] })] }), _jsxs("label", { className: "dl-radio", children: [_jsx("input", { type: "radio", name: "dl-access", checked: !!draft.pin, onChange: () => change({ pin: draft.pin || makeCode() }) }), _jsxs("span", { children: [_jsx("strong", { children: "Serve anche un codice" }), _jsx("small", { children: "Da mandare insieme al link. Dopo dieci errori si blocca per un'ora." })] })] }), !!draft.pin && (_jsxs("div", { className: "dl-code", children: [_jsx("input", { value: draft.pin, spellCheck: false, onChange: (e) => change({ pin: e.target.value.toUpperCase() }) }), _jsx("button", { className: "ak-btn", onClick: () => change({ pin: makeCode() }), children: "Altro" })] }))] }), _jsxs(Group, { title: "Richiedi pagamento", children: [_jsx("span", { className: "dl-payment-status", children: "Chiedi di attivare la funzione" }), _jsxs("label", { className: "dl-check dl-payment-disabled", children: [_jsx("input", { type: "checkbox", checked: false, disabled: true, "aria-describedby": "dl-payment-description" }), _jsxs("span", { children: [_jsx("strong", { children: "Sblocca gallery e download al saldo" }), _jsx("small", { id: "dl-payment-description", children: "Potrai impostare l\u2019importo da incassare per questa consegna. Il cliente pagher\u00E0 una sola volta per sbloccare la galleria e scaricare i file." })] })] }), _jsx("p", { className: "dl-note", children: "Questa opzione non \u00E8 ancora disponibile: il transfer non richiede pagamenti e segue le impostazioni di accesso qui sopra." })] }), _jsxs(Group, { title: "Cosa riceve", note: packages.length
|
|
410
|
+
: "Aggiungi i file: il caricamento parte subito e il resto si compila mentre va." })] }))] }), _jsxs("div", { className: "dl-side", children: [_jsxs(Group, { title: "Chi pu\u00F2 aprirlo", children: [_jsxs("label", { className: "dl-radio", children: [_jsx("input", { type: "radio", name: "dl-access", checked: !draft.pin, onChange: () => change({ pin: "" }) }), _jsxs("span", { children: [_jsx("strong", { children: "Chiunque abbia il link" }), _jsx("small", { children: "Il link \u00E8 lungo e casuale: non si indovina." })] })] }), _jsxs("label", { className: "dl-radio", children: [_jsx("input", { type: "radio", name: "dl-access", checked: !!draft.pin, onChange: () => change({ pin: draft.pin || makeCode() }) }), _jsxs("span", { children: [_jsx("strong", { children: "Serve anche un codice" }), _jsx("small", { children: "Da mandare insieme al link. Dopo dieci errori si blocca per un'ora." })] })] }), !!draft.pin && (_jsxs("div", { className: "dl-code", children: [_jsx("input", { value: draft.pin, spellCheck: false, onChange: (e) => change({ pin: e.target.value.toUpperCase() }) }), _jsx("button", { className: "ak-btn", onClick: () => change({ pin: makeCode() }), children: "Altro" })] }))] }), _jsxs(Group, { title: "Richiedi pagamento", children: [_jsx("span", { className: "dl-payment-status", children: "Chiedi di attivare la funzione" }), _jsxs("label", { className: "dl-check dl-payment-disabled", children: [_jsx("input", { type: "checkbox", checked: false, disabled: true, "aria-describedby": "dl-payment-description" }), _jsxs("span", { children: [_jsx("strong", { children: "Sblocca gallery e download al saldo" }), _jsx("small", { id: "dl-payment-description", children: "Potrai impostare l\u2019importo da incassare per questa consegna. Il cliente pagher\u00E0 una sola volta per sbloccare la galleria e scaricare i file." })] })] }), _jsx("p", { className: "dl-note", children: "Questa opzione non \u00E8 ancora disponibile: il transfer non richiede pagamenti e segue le impostazioni di accesso qui sopra." })] }), _jsxs(Group, { title: "Selezione del cliente", children: [_jsx("span", { className: "dl-payment-status", children: "Chiedi di attivare la funzione" }), _jsxs("label", { className: "dl-check dl-payment-disabled", children: [_jsx("input", { type: "checkbox", checked: false, disabled: true, "aria-describedby": "dl-selection-description" }), _jsxs("span", { children: [_jsx("strong", { children: "Consenti al cliente di scegliere le foto" }), _jsx("small", { id: "dl-selection-description", children: "Il cliente potr\u00E0 indicare nella galleria quali foto entrano nella sua selezione." })] })] }), _jsx("p", { className: "dl-note", children: "Questa opzione non \u00E8 ancora disponibile: al momento il cliente pu\u00F2 consultare la galleria, se abilitata, ma non salvare una selezione." })] }), _jsxs(Group, { title: "Cosa riceve", note: packages.length
|
|
411
411
|
? "Si decide prima di caricare: per cambiarle bisognerebbe ricaricare i file."
|
|
412
412
|
: undefined, children: [_jsxs("label", { className: "dl-check", children: [_jsx("input", { type: "checkbox", checked: draft.gallery, disabled: !!packages.length, onChange: (e) => change({ gallery: e.target.checked }) }), _jsxs("span", { children: [_jsx("strong", { children: "Vede le foto sulla pagina" }), _jsx("small", { children: "Anteprime e ingrandimento, senza scaricare niente. Da telefono \u00E8 la differenza fra un link e un Transfer." })] })] }), _jsxs("label", { className: "dl-check", children: [_jsx("input", { type: "checkbox", checked: draft.light, disabled: !!packages.length, onChange: (e) => change({ light: e.target.checked }) }), _jsxs("span", { children: [_jsx("strong", { children: "Pu\u00F2 scaricare una versione leggera" }), _jsx("small", { children: "Un secondo download, adatto a social e web. Gli originali ci sono sempre." })] })] }), draft.light && (_jsxs("label", { className: "dl-field", children: [_jsx("span", { children: "Formato della versione leggera" }), _jsxs("select", { className: "dl-select", "aria-label": "Formato della versione leggera", value: draft.webFormat, disabled: !!packages.length || uploading, onChange: (e) => change({ webFormat: e.target.value === "jpg" ? "jpg" : "webp" }), children: [_jsx("option", { value: "webp", children: "WebP \u2014 file pi\u00F9 piccoli" }), _jsx("option", { value: "jpg", disabled: !jpegEnabled && draft.webFormat !== "jpg", children: "JPG \u2014 massima compatibilit\u00E0" })] }), _jsxs("small", { children: ["2048 px sul lato lungo, senza ingrandire le foto pi\u00F9 piccole. Qualit\u00E0 ", draft.webFormat === "jpg" ? "82%" : "80%", "."] })] }))] }), downloadLabelsEnabled && (_jsxs(Group, { title: "Testi dei pulsanti di download", note: "Lascia vuoto per usare il testo predefinito. Puoi cambiarli anche dopo l\u2019invio, senza ricaricare i file.", children: [delivery?.status !== "archived" && (_jsx(Field, { label: "Pulsante degli originali", children: _jsx("input", { value: draft.downloadOriginalsLabel, maxLength: 80, placeholder: "Scarica i file", onChange: (e) => change({ downloadOriginalsLabel: e.target.value }) }) })), (packages.length ? packages.some(pkg => pkg.webEnabled) : draft.light) && (_jsx(Field, { label: "Pulsante della versione leggera", children: _jsx("input", { value: draft.downloadWebLabel, maxLength: 80, placeholder: "Versione leggera", onChange: (e) => change({ downloadWebLabel: e.target.value }) }) }))] })), _jsxs(Group, { title: "Per quanto resta scaricabile", children: [_jsxs("select", { className: "dl-select", value: draft.duration, onChange: (e) => change({ duration: e.target.value }), children: [delivery && _jsx("option", { value: "keep", children: delivery.filesExpiresAt
|
|
413
413
|
? `Fino al ${formatDate(delivery.filesExpiresAt)}`
|
|
@@ -425,7 +425,7 @@ export function DeliveryWorkspace({ delivery: fromServer, busy, onAction, onRefr
|
|
|
425
425
|
return (_jsxs("button", { type: "button", className: chosen ? "is-chosen" : "", disabled: saving, "aria-pressed": chosen, onClick: () => toggleCover(pkg.id, image.index, image.previewUrl), children: [_jsx("img", { src: previewAttempt ? `${image.previewUrl}&previewRetry=${previewAttempt}` : image.previewUrl, alt: image.name, width: image.width, height: image.height, loading: "lazy" }), chosen && _jsx("em", { "aria-hidden": "true", children: "\u2713" })] }, `${pkg.id}-${image.index}`));
|
|
426
426
|
}) })) : (_jsx("p", { className: "dl-note dl-cover-empty", children: heroes.some((item) => item.type === "object")
|
|
427
427
|
? `${heroes.length} immagini caricate a mano.`
|
|
428
|
-
: "Questo transfer non ha anteprime da cui scegliere: carica un'immagine, oppure resta quella predefinita." }))] })), !!delivery && (_jsxs("section", { className: "dl-danger", children: [_jsxs("div", { children: [_jsx("button", { className: "ak-btn ak-btn-quiet", disabled: busy, onClick: () => void duplicate(), children: "Usa come modello" }), delivery.status === "active" && (_jsx("button", { className: "ak-btn ak-btn-quiet", disabled: busy, onClick: () => void run({ action: "archive", id: delivery.id }, "Originali tolti: recuperabili per sette giorni"), children: "Libera spazio: togli gli originali" }))] }), confirmDelete ? (_jsxs("div", { className: "dl-confirm", children: [_jsxs("p", { children: ["Elimino ", _jsx("strong", { children: delivery.title }), photos.length ? ` (${countPhotos(packages)} file, ${formatBytes(delivery.storedBytes)})` : "", "? Il link smette subito di funzionare
|
|
428
|
+
: "Questo transfer non ha anteprime da cui scegliere: carica un'immagine, oppure resta quella predefinita." }))] })), !!delivery && (_jsxs("section", { className: "dl-danger", children: [_jsxs("div", { children: [_jsx("button", { className: "ak-btn ak-btn-quiet", disabled: busy, onClick: () => void duplicate(), children: "Usa come modello" }), delivery.status === "active" && (_jsx("button", { className: "ak-btn ak-btn-quiet", disabled: busy, onClick: () => void run({ action: "archive", id: delivery.id }, "Originali tolti: recuperabili per sette giorni"), children: "Libera spazio: togli gli originali" }))] }), confirmDelete ? (_jsxs("div", { className: "dl-confirm", children: [_jsxs("p", { children: ["Elimino ", _jsx("strong", { children: delivery.title }), photos.length ? ` (${countPhotos(packages)} file, ${formatBytes(delivery.storedBytes)})` : "", "? Il link smette subito di funzionare. La rimozione dei file e degli upload residui viene completata in background. Non si torna indietro."] }), _jsx("button", { className: "ak-btn", onClick: () => setConfirmDelete(false), children: "Annulla" }), _jsx("button", { className: "ak-btn dl-danger-btn", onClick: () => void remove(), children: "S\u00EC, elimina" })] })) : (_jsx("button", { className: "ak-btn ak-btn-quiet", onClick: () => setConfirmDelete(true), children: "Elimina il transfer" }))] }))] }));
|
|
429
429
|
}
|
|
430
430
|
/* ============================================================================================
|
|
431
431
|
Impostazioni
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { useCallback, useEffect, useRef, useState } from "react";
|
|
3
|
+
const bytes = (value) => {
|
|
4
|
+
if (value == null)
|
|
5
|
+
return "—";
|
|
6
|
+
if (!value)
|
|
7
|
+
return "0 B";
|
|
8
|
+
const power = Math.min(4, Math.floor(Math.log(value) / Math.log(1000)));
|
|
9
|
+
return `${new Intl.NumberFormat("it-IT", { maximumFractionDigits: power ? 2 : 0 }).format(value / 1000 ** power)} ${["B", "KB", "MB", "GB", "TB"][power]}`;
|
|
10
|
+
};
|
|
11
|
+
const date = (value) => new Intl.DateTimeFormat("it-IT", { dateStyle: "short", timeStyle: "short" }).format(new Date(value));
|
|
12
|
+
export function DeliveryDashboard({ onCreate, onOpen }) {
|
|
13
|
+
const [data, setData] = useState(null);
|
|
14
|
+
const [error, setError] = useState(null);
|
|
15
|
+
const [checking, setChecking] = useState(false);
|
|
16
|
+
const mounted = useRef(false);
|
|
17
|
+
const load = useCallback(async (verify = false) => {
|
|
18
|
+
if (verify)
|
|
19
|
+
setChecking(true);
|
|
20
|
+
try {
|
|
21
|
+
const response = await fetch(verify ? "/admin/api/deliveries" : "/admin/api/deliveries?dashboard=1", {
|
|
22
|
+
credentials: "same-origin", ...(verify ? { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "verifyStorage" }) } : {}),
|
|
23
|
+
});
|
|
24
|
+
const body = await response.json();
|
|
25
|
+
if (!response.ok || !body.ok)
|
|
26
|
+
throw new Error(body.error || "La dashboard non è disponibile. Riprova.");
|
|
27
|
+
if (mounted.current) {
|
|
28
|
+
setData(body.dashboard);
|
|
29
|
+
setError(null);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
catch (err) {
|
|
33
|
+
if (mounted.current)
|
|
34
|
+
setError(err instanceof Error ? err.message : "Verifica non disponibile");
|
|
35
|
+
}
|
|
36
|
+
finally {
|
|
37
|
+
if (mounted.current && verify)
|
|
38
|
+
setChecking(false);
|
|
39
|
+
}
|
|
40
|
+
}, []);
|
|
41
|
+
useEffect(() => { mounted.current = true; void load(); return () => { mounted.current = false; }; }, [load]);
|
|
42
|
+
const running = checking || data?.storage.status === "running";
|
|
43
|
+
useEffect(() => { const timer = setTimeout(() => void load(), running || (data?.storage.enabled && !data.storage.checkedAt) ? 3000 : 60_000); return () => clearTimeout(timer); }, [data, running, load]);
|
|
44
|
+
const storage = data?.storage, snapshot = storage?.snapshot;
|
|
45
|
+
return _jsxs("section", { className: "dd-dashboard", "aria-label": "Dashboard consegne", children: [_jsxs("header", { className: "dd-heading", children: [_jsxs("div", { children: [_jsx("p", { className: "dd-eyebrow", children: "Consegne" }), _jsx("h2", { children: "Panoramica transfer" }), _jsx("p", { children: "Disponibilit\u00E0, richieste di download e spazio realmente occupato." })] }), _jsx("button", { className: "ak-btn ak-btn-primary", onClick: onCreate, children: "Nuovo transfer" })] }), error && _jsxs("div", { className: "dd-error", role: "alert", children: [error, " ", _jsx("button", { className: "ak-btn", onClick: () => void load(), children: "Riprova" })] }), _jsxs("div", { className: "dd-metrics", children: [_jsx(Metric, { label: "Transfer attivi", value: data?.active, note: "Pubblicati, disponibili e con un link valido" }), _jsx(Metric, { label: "Spazio transfer attivi", value: bytes(storage?.activeBytes), note: storage?.checkedAt ? "Rilevato su B2 · " + date(storage.checkedAt) : "In attesa della prima verifica B2" }), _jsx(Metric, { label: "Con download richiesto", value: data?.withRequests, note: "Almeno una richiesta di download" }), _jsx(Metric, { label: "Senza richieste", value: data?.withoutRequests, note: "Nessuna richiesta di download registrata" })] }), _jsxs("section", { className: "dd-storage", "aria-label": "Spazio reale su B2", children: [_jsxs("div", { className: "dd-storage-head", children: [_jsxs("div", { children: [_jsxs("div", { className: "dd-title-row", children: [_jsx("h3", { children: "Spazio reale su B2" }), _jsx("span", { className: "dd-status" + (running ? " is-running" : storage?.error ? " is-error" : ""), children: running ? "Verifica in corso" : storage?.error ? "Verifica non riuscita" : storage?.checkedAt ? "Verificato" : "Da verificare" })] }), _jsx("p", { children: storage?.checkedAt ? `Ultima verifica completata: ${date(storage.checkedAt)}. Controllo automatico ogni ora.` : "L’inventario legge gli oggetti e gli upload presenti sul bucket, senza scaricare i file." })] }), _jsx("button", { className: "ak-btn", disabled: running || !storage?.enabled, onClick: () => void load(true), children: running ? "Verifica in corso…" : "Verifica ora" })] }), !storage?.enabled && data && _jsx("p", { className: "dd-notice", children: "La verifica B2 sar\u00E0 disponibile dopo l\u2019abilitazione di questa funzione sul server." }), storage?.error && _jsxs("p", { className: "dd-notice", role: "status", children: [storage.error, ". ", snapshot ? "Rimane visibile l’ultimo inventario completo." : "Nessun inventario completo disponibile."] }), _jsxs("div", { className: "dd-storage-grid", children: [_jsx(Metric, { label: "Totale del bucket", value: bytes(snapshot?.totalBytes), note: snapshot ? `${snapshot.currentObjects} oggetti correnti · ${snapshot.objectVersions} versioni` : "Nessun risultato ancora disponibile" }), _jsx(Metric, { label: "Versioni nascoste", value: bytes(snapshot?.hiddenBytes), note: "Byte conservati nelle versioni precedenti" }), _jsx(Metric, { label: "Upload incompleti", value: bytes(snapshot?.incompleteBytes), note: snapshot ? `${snapshot.incompleteUploads} caricamenti da completare` : "Parti già caricate su B2" }), _jsx(Metric, { label: "Senza consegna associata", value: bytes(snapshot?.unassignedBytes), note: "Dati senza un riferimento nei transfer" })] }), _jsx("p", { className: "dd-footnote", children: "Versioni nascoste e upload incompleti sono inclusi nel totale. I dati senza consegna possono includerli. La verifica non elimina alcun file." })] }), _jsxs("section", { className: "dd-transfers", children: [_jsxs("div", { className: "dd-title-row", children: [_jsx("h3", { children: "Transfer attivi" }), _jsxs("span", { children: [data?.requestedDownloads ?? "—", " richieste di download complessive"] })] }), _jsx("p", { className: "dd-footnote", children: "Una richiesta indica l\u2019uso del pulsante di download; non conferma che il file sia stato ricevuto per intero." }), !data ? _jsx("p", { className: "ak-hint", role: "status", children: "Carico la panoramica\u2026" }) : !data.transfers.length ? _jsx("p", { className: "dd-empty", children: "Nessun transfer attivo. Crea un nuovo transfer per iniziare." }) :
|
|
46
|
+
_jsx("div", { className: "dd-table-wrap", children: _jsxs("table", { children: [_jsx("thead", { children: _jsxs("tr", { children: [_jsx("th", { children: "Transfer" }), _jsx("th", { children: "Spazio su B2" }), _jsx("th", { children: "Download richiesti" }), _jsx("th", { children: "Scadenza file" })] }) }), _jsx("tbody", { children: data.transfers.map(t => _jsxs("tr", { children: [_jsx("td", { children: _jsxs("button", { className: "dd-transfer-link", onClick: () => onOpen(t.id), children: [_jsx("strong", { children: t.clientName || t.title }), t.clientName && _jsx("span", { children: t.title })] }) }), _jsx("td", { children: bytes(t.storedBytes) }), _jsx("td", { children: _jsx("span", { className: "dd-request" + (!t.downloadCount ? " is-pending" : ""), children: t.downloadCount ? `${t.downloadCount} ${t.downloadCount === 1 ? "richiesta" : "richieste"}` : "Nessuna richiesta" }) }), _jsx("td", { children: t.expiresAt ? new Intl.DateTimeFormat("it-IT", { dateStyle: "medium" }).format(new Date(t.expiresAt)) : "Senza scadenza" })] }, t.id)) })] }) })] })] });
|
|
47
|
+
}
|
|
48
|
+
function Metric({ label, value, note }) {
|
|
49
|
+
return _jsxs("div", { className: "dd-metric", children: [_jsx("span", { children: label }), _jsx("strong", { children: value ?? "—" }), _jsx("p", { children: note })] });
|
|
50
|
+
}
|
|
@@ -50,7 +50,8 @@ export async function b2Request(env, method, key, options = {}) {
|
|
|
50
50
|
`AWS4-HMAC-SHA256 Credential=${env.B2_APPLICATION_KEY_ID}/${scope}, ` +
|
|
51
51
|
`SignedHeaders=${signedNames.join(";")}, Signature=${signature}`);
|
|
52
52
|
|
|
53
|
-
|
|
53
|
+
const listing = options.query && ("versions" in options.query || "uploads" in options.query);
|
|
54
|
+
return fetch(url, { method, headers, body, signal: method === "GET" && !options.query?.uploadId && !listing ? undefined : AbortSignal.timeout(60_000) });
|
|
54
55
|
}
|
|
55
56
|
|
|
56
57
|
export async function b2PresignUploadPart(env, key, uploadId, partNumber, expires = 900) {
|
|
@@ -208,11 +209,72 @@ export async function multipartEtag(parts) {
|
|
|
208
209
|
return `${hex(await crypto.subtle.digest("MD5", binary))}-${parts.length}`;
|
|
209
210
|
}
|
|
210
211
|
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
212
|
+
// Each LIST and DELETE consumes the caller's budget. Re-listing from the start
|
|
213
|
+
// after deletion makes retries independent of a stale pagination cursor.
|
|
214
|
+
export async function b2PurgeScope(env, key, calls = { left: 24 }, prefix = false) {
|
|
215
|
+
if (!key || (prefix && (!key.startsWith("deliveries/") || !key.endsWith("/") || key.split("/").length < 4))) {
|
|
216
|
+
throw new Error("Ambito di pulizia B2 non valido");
|
|
217
|
+
}
|
|
218
|
+
if (await b2ScopePreserved(env, key, prefix)) {
|
|
219
|
+
throw Object.assign(new Error("Oggetto B2 conservato dal blocco sui dati preesistenti"), { code: "DELIVERY_STORAGE_PRESERVED" });
|
|
215
220
|
}
|
|
221
|
+
const matches = value => prefix ? value.startsWith(key) : value === key;
|
|
222
|
+
for (const kind of ["uploads", "versions"]) {
|
|
223
|
+
let marker = {};
|
|
224
|
+
while (calls.left > 0) {
|
|
225
|
+
calls.left--;
|
|
226
|
+
const res = await b2Request(env, "GET", "", { query: {
|
|
227
|
+
[kind]: "", prefix: key, [kind === "uploads" ? "max-uploads" : "max-keys"]: "100", ...marker,
|
|
228
|
+
} });
|
|
229
|
+
const body = await res.text();
|
|
230
|
+
const root = kind === "uploads" ? "ListMultipartUploadsResult" : "ListVersionsResult";
|
|
231
|
+
if (!res.ok || !body.includes(`<${root}`)) throw new Error(`B2 list ${kind} ${res.status}: ${body.slice(0, 200)}`);
|
|
232
|
+
const blocks = kind === "uploads" ? /<Upload>([\s\S]*?)<\/Upload>/g : /<(?:Version|DeleteMarker)>([\s\S]*?)<\/(?:Version|DeleteMarker)>/g;
|
|
233
|
+
let removedCount = 0;
|
|
234
|
+
for (const block of body.matchAll(blocks)) {
|
|
235
|
+
const objectKey = decodeXml(xml(block[1], "Key"));
|
|
236
|
+
if (!matches(objectKey)) continue;
|
|
237
|
+
const id = decodeXml(xml(block[1], kind === "uploads" ? "UploadId" : "VersionId"));
|
|
238
|
+
if (!id) throw new Error("B2 elenco senza identificativo di versione/upload");
|
|
239
|
+
if (calls.left <= 0) return false;
|
|
240
|
+
calls.left--;
|
|
241
|
+
const removed = await b2Request(env, "DELETE", objectKey, {
|
|
242
|
+
query: { [kind === "uploads" ? "uploadId" : "versionId"]: id },
|
|
243
|
+
});
|
|
244
|
+
if (!removed.ok && removed.status !== 404) throw new Error(`B2 purge ${removed.status}: ${(await removed.text()).slice(0, 200)}`);
|
|
245
|
+
removedCount++;
|
|
246
|
+
}
|
|
247
|
+
if (xml(body, "IsTruncated") !== "false" && xml(body, "IsTruncated") !== "true") throw new Error("B2 elenco senza stato di paginazione");
|
|
248
|
+
if (removedCount) { marker = {}; if (calls.left <= 0) return false; continue; }
|
|
249
|
+
if (xml(body, "IsTruncated") !== "true") break;
|
|
250
|
+
const next = decodeXml(xml(body, "NextKeyMarker"));
|
|
251
|
+
if (!next) throw new Error("B2 elenco troncato senza marker");
|
|
252
|
+
marker = { "key-marker": next, [kind === "uploads" ? "upload-id-marker" : "version-id-marker"]:
|
|
253
|
+
decodeXml(xml(body, kind === "uploads" ? "NextUploadIdMarker" : "NextVersionIdMarker")) };
|
|
254
|
+
if (calls.left <= 0) return false;
|
|
255
|
+
}
|
|
256
|
+
if (calls.left <= 0) return false;
|
|
257
|
+
}
|
|
258
|
+
return true;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export async function b2ScopePreserved(env, key, prefix = false) {
|
|
262
|
+
if (env.DELIVERY_STORAGE_PRESERVATION !== "required") return false;
|
|
263
|
+
if (!env.DB) throw new Error("Database del blocco di conservazione non disponibile");
|
|
264
|
+
const sql = prefix
|
|
265
|
+
? "SELECT 1 n FROM delivery_storage_preserved WHERE substr(object_key,1,length(?))=? LIMIT 1"
|
|
266
|
+
: "SELECT 1 n FROM delivery_storage_preserved WHERE object_key=? LIMIT 1";
|
|
267
|
+
return !!await env.DB.prepare(sql).bind(...(prefix ? [key, key] : [key])).first();
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
export function b2Delete(env, key, calls) {
|
|
271
|
+
return b2PurgeScope(env, key, calls, false);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function decodeXml(value) {
|
|
275
|
+
return value.replace(/&#x([0-9a-f]+);/gi, (_, n) => String.fromCodePoint(parseInt(n, 16)))
|
|
276
|
+
.replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n)))
|
|
277
|
+
.replaceAll("<", "<").replaceAll(">", ">").replaceAll(""", '"').replaceAll("'", "'").replaceAll("&", "&");
|
|
216
278
|
}
|
|
217
279
|
|
|
218
280
|
function assertConfig(env) {
|
|
@@ -41,7 +41,8 @@ export async function readManifestPage(env, pkg, after = -1, limit = 100, images
|
|
|
41
41
|
}
|
|
42
42
|
async function activePackage(env, body, write = false) {
|
|
43
43
|
const pkg = await env.DB.prepare(`SELECT p.* FROM delivery_packages p JOIN deliveries d ON d.id=p.delivery_id
|
|
44
|
-
WHERE p.id=? AND p.delivery_id=? AND p.state IN ('uploading','ready') AND d.status!='deleted'
|
|
44
|
+
WHERE p.id=? AND p.delivery_id=? AND p.state IN ('uploading','ready') AND d.status!='deleted'
|
|
45
|
+
AND (d.files_expires_at IS NULL OR d.files_expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now'))`)
|
|
45
46
|
.bind(String(body.packageId || ''), String(body.id || '')).first();
|
|
46
47
|
if (!pkg || manifestVersion(pkg) !== 2) throw fail('Pacchetto v2 non disponibile', 409);
|
|
47
48
|
if (write) await assertManifestWriter(env, pkg.id, body.writerToken);
|
|
@@ -12,76 +12,92 @@
|
|
|
12
12
|
* nudo, con le sole `env.DB` e le variabili B2.
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
|
-
import {
|
|
16
|
-
import { b2AbortMultipart, b2Delete, b2ObjectKey } from "./b2.js";
|
|
15
|
+
import { b2Delete, b2PurgeScope, b2ScopePreserved } from "./b2.js";
|
|
17
16
|
|
|
18
17
|
const DAY = 86_400_000;
|
|
18
|
+
const packageNotPreserved = alias => `NOT EXISTS (SELECT 1 FROM delivery_storage_preserved held
|
|
19
|
+
WHERE substr(held.object_key,1,length(${alias}.storage_prefix)+1)=${alias}.storage_prefix||'/')`;
|
|
20
|
+
const objectNotPreserved = expression => `NOT EXISTS (SELECT 1 FROM delivery_storage_preserved held WHERE held.object_key=${expression})`;
|
|
19
21
|
|
|
20
22
|
/* Ogni oggetto tolto da B2 è una sottorichiesta, e il tetto è per invocazione:
|
|
21
23
|
* da qui il vecchio «due pacchetti per giro», che era un limite di piattaforma
|
|
22
24
|
* travestito da LIMIT. Il budget lo dice esplicitamente e lo rende regolabile —
|
|
23
25
|
* stretto quando c'è un utente che aspetta la risposta, largo nel cron.
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
+
* Anche LIST e cancellazioni delle singole versioni consumano budget. Una
|
|
27
|
+
* pulizia parziale conserva le righe e riparte al giro successivo. */
|
|
26
28
|
export const B2_CALLS_PER_REQUEST = 24;
|
|
27
29
|
export const budget = (left = B2_CALLS_PER_REQUEST) => ({ left });
|
|
28
30
|
|
|
29
|
-
/*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
|
|
31
|
+
/* A durable scope survives the D1 records and catches late PUT/complete/manifest
|
|
32
|
+
* writes, including ones that finish after a signed URL has expired. Scopes are
|
|
33
|
+
* never retired automatically: every day they are checked again, without listing
|
|
34
|
+
* or deleting unrelated bucket contents. During the first hour checks are frequent. */
|
|
35
|
+
export async function rememberCleanup(env, objectKey, isPrefix = false) {
|
|
36
|
+
const now = new Date().toISOString();
|
|
37
|
+
await env.DB.prepare(`INSERT INTO delivery_storage_cleanup(object_key,is_prefix,created_at,next_check_at)
|
|
38
|
+
VALUES (?,?,?,?) ON CONFLICT(object_key,is_prefix) DO NOTHING`)
|
|
39
|
+
.bind(objectKey, Number(isPrefix), now, now).run();
|
|
40
|
+
}
|
|
41
|
+
|
|
34
42
|
async function purgePackages(env, rows, calls) {
|
|
35
43
|
for (const pkg of rows) {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
// Una PUT firmata prima dell’annullamento può ancora terminare: conserva la tombstone.
|
|
47
|
-
if (pkg.purge_after && pkg.purge_after > new Date().toISOString()) return false;
|
|
48
|
-
if (manifestVersion(pkg) === 2) {
|
|
49
|
-
const pages = await env.DB.prepare("SELECT page_number,object_key FROM delivery_manifest_objects WHERE package_id=? LIMIT ?")
|
|
50
|
-
.bind(pkg.id, Math.max(0, calls.left)).all();
|
|
51
|
-
for (const page of pages.results || []) {
|
|
52
|
-
calls.left -= 1;
|
|
53
|
-
await b2Delete(env, page.object_key);
|
|
54
|
-
await env.DB.prepare("DELETE FROM delivery_manifest_objects WHERE package_id=? AND page_number=?")
|
|
55
|
-
.bind(pkg.id, page.page_number).run();
|
|
56
|
-
}
|
|
57
|
-
const remaining = await env.DB.prepare("SELECT 1 n FROM delivery_manifest_objects WHERE package_id=? LIMIT 1").bind(pkg.id).first();
|
|
58
|
-
if (remaining || calls.left <= 0) return false;
|
|
59
|
-
}
|
|
60
|
-
const keys = new Set([
|
|
61
|
-
pkg.originals_key, pkg.web_key, pkg.thumbs_key, pkg.manifest_key,
|
|
62
|
-
...["originals.zip", "web.zip", "thumbs.zip", "manifest.json"].map((name) => b2ObjectKey(pkg.storage_prefix, name)),
|
|
63
|
-
...(uploads.results || []).map((upload) => upload.object_key),
|
|
64
|
-
].filter(Boolean));
|
|
44
|
+
const prefix = String(pkg.storage_prefix).replace(/\/+$/, "") + "/";
|
|
45
|
+
if (await b2ScopePreserved(env, prefix, true)) return false;
|
|
46
|
+
await rememberCleanup(env, prefix, true);
|
|
47
|
+
if (!await b2PurgeScope(env, prefix, calls, true)) return false;
|
|
48
|
+
// Compatibility: older rows may refer to objects outside the package prefix.
|
|
49
|
+
const uploads = await env.DB.prepare("SELECT object_key FROM delivery_uploads WHERE package_id=?").bind(pkg.id).all();
|
|
50
|
+
const keys = new Set([pkg.originals_key, pkg.web_key, pkg.thumbs_key, pkg.manifest_key,
|
|
51
|
+
...(uploads.results || []).map(u => u.object_key)].filter(k => k && !k.startsWith(prefix)));
|
|
65
52
|
for (const key of keys) {
|
|
66
|
-
|
|
67
|
-
await b2Delete(env, key);
|
|
53
|
+
await rememberCleanup(env, key);
|
|
54
|
+
if (!await b2Delete(env, key, calls)) return false;
|
|
68
55
|
}
|
|
69
|
-
|
|
70
|
-
|
|
56
|
+
// Preserve pending metadata until the existing signed upload URLs have elapsed.
|
|
57
|
+
// The durable scope above also covers arbitrarily slow in-flight requests.
|
|
58
|
+
if (pkg.purge_after && pkg.purge_after > new Date().toISOString()) return false;
|
|
59
|
+
await env.DB.prepare("DELETE FROM delivery_packages WHERE id=? AND state='deleted'").bind(pkg.id).run();
|
|
71
60
|
}
|
|
72
61
|
return true;
|
|
73
62
|
}
|
|
74
63
|
|
|
75
64
|
async function purgeHeroes(env, rows, calls) {
|
|
76
65
|
for (const hero of rows) {
|
|
77
|
-
if (
|
|
78
|
-
|
|
79
|
-
await b2Delete(env, hero.object_key);
|
|
66
|
+
if (await b2ScopePreserved(env, hero.object_key)) return false;
|
|
67
|
+
await rememberCleanup(env, hero.object_key);
|
|
68
|
+
if (!await b2Delete(env, hero.object_key, calls)) return false;
|
|
80
69
|
await env.DB.prepare("DELETE FROM delivery_hero_objects WHERE id=?").bind(hero.id).run();
|
|
81
70
|
}
|
|
82
71
|
return true;
|
|
83
72
|
}
|
|
84
73
|
|
|
74
|
+
export async function sweepCleanupScopes(env, calls = budget()) {
|
|
75
|
+
const now = new Date().toISOString();
|
|
76
|
+
const rows = await env.DB.prepare(`SELECT * FROM delivery_storage_cleanup
|
|
77
|
+
WHERE next_check_at<=? AND NOT EXISTS (SELECT 1 FROM delivery_storage_preserved held
|
|
78
|
+
WHERE (delivery_storage_cleanup.is_prefix=1 AND substr(held.object_key,1,length(delivery_storage_cleanup.object_key))=delivery_storage_cleanup.object_key)
|
|
79
|
+
OR (delivery_storage_cleanup.is_prefix=0 AND held.object_key=delivery_storage_cleanup.object_key))
|
|
80
|
+
ORDER BY next_check_at,object_key LIMIT 8`).bind(now).all();
|
|
81
|
+
let complete = true;
|
|
82
|
+
for (const row of rows.results || []) {
|
|
83
|
+
if (calls.left <= 0) return false;
|
|
84
|
+
try {
|
|
85
|
+
if (!await b2PurgeScope(env, row.object_key, calls, !!row.is_prefix)) return false;
|
|
86
|
+
} catch (error) {
|
|
87
|
+
complete = false;
|
|
88
|
+
console.error("delivery storage cleanup:", error);
|
|
89
|
+
await env.DB.prepare(`UPDATE delivery_storage_cleanup SET last_error=?,next_check_at=?
|
|
90
|
+
WHERE object_key=? AND is_prefix=?`)
|
|
91
|
+
.bind(String(error.message || error).slice(0, 500), new Date(Date.now() + 15 * 60_000).toISOString(), row.object_key, row.is_prefix).run();
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
const interval = Date.now() - Date.parse(row.created_at) < 60 * 60_000 ? 15 * 60_000 : DAY;
|
|
95
|
+
await env.DB.prepare(`UPDATE delivery_storage_cleanup SET last_checked_at=?,next_check_at=?,last_error=NULL
|
|
96
|
+
WHERE object_key=? AND is_prefix=?`).bind(now, new Date(Date.now() + interval).toISOString(), row.object_key, row.is_prefix).run();
|
|
97
|
+
}
|
|
98
|
+
return complete && (rows.results || []).length < 8;
|
|
99
|
+
}
|
|
100
|
+
|
|
85
101
|
/* Cancellazione immediata di quanto è già marcato `deleted` per un transfer.
|
|
86
102
|
* Torna false se è rimasto indietro qualcosa — un errore su B2, o un transfer
|
|
87
103
|
* così grande da esaurire il budget: le tombstone hanno `purge_after` nel
|
|
@@ -122,7 +138,7 @@ export async function purgePackageNow(env, packageId, calls = budget()) {
|
|
|
122
138
|
const pkg = await env.DB.prepare(
|
|
123
139
|
"SELECT * FROM delivery_packages WHERE id=? AND state='deleted'"
|
|
124
140
|
).bind(packageId).first();
|
|
125
|
-
if (pkg) return purgePackages(env, [pkg], calls);
|
|
141
|
+
if (pkg) return await purgePackages(env, [pkg], calls);
|
|
126
142
|
return true;
|
|
127
143
|
} catch (error) {
|
|
128
144
|
console.error("package purge now:", error);
|
|
@@ -130,6 +146,24 @@ export async function purgePackageNow(env, packageId, calls = budget()) {
|
|
|
130
146
|
}
|
|
131
147
|
}
|
|
132
148
|
|
|
149
|
+
export async function markExpiredFiles(env, deliveryId) {
|
|
150
|
+
const now = new Date().toISOString();
|
|
151
|
+
const grace = new Date(Date.now() + 60 * 60_000).toISOString();
|
|
152
|
+
await env.DB.batch([
|
|
153
|
+
env.DB.prepare(`UPDATE delivery_packages SET state='deleted',deleted_at=?,
|
|
154
|
+
purge_after=CASE WHEN state='uploading' THEN ? ELSE ? END,updated_at=?
|
|
155
|
+
WHERE delivery_id=? AND state!='deleted'
|
|
156
|
+
AND ${packageNotPreserved('delivery_packages')}
|
|
157
|
+
AND EXISTS(SELECT 1 FROM deliveries WHERE id=delivery_id AND files_expires_at<=?)`)
|
|
158
|
+
.bind(now, grace, now, now, deliveryId, now),
|
|
159
|
+
env.DB.prepare(`UPDATE delivery_hero_objects SET state='deleted',purge_after=?,updated_at=?
|
|
160
|
+
WHERE delivery_id=? AND state!='deleted'
|
|
161
|
+
AND ${objectNotPreserved('delivery_hero_objects.object_key')}
|
|
162
|
+
AND EXISTS(SELECT 1 FROM deliveries WHERE id=delivery_id AND files_expires_at<=?)`)
|
|
163
|
+
.bind(now, now, deliveryId, now),
|
|
164
|
+
]);
|
|
165
|
+
}
|
|
166
|
+
|
|
133
167
|
/* Un giro di housekeeping. Le cancellazioni chieste a mano non passano di qui —
|
|
134
168
|
* avvengono nella loro richiesta — ma se una si era fermata a metà è questo giro
|
|
135
169
|
* a finirla, perché la sua `purge_after` è già scaduta. Un solo budget per tutte
|
|
@@ -138,31 +172,28 @@ export async function purgePackageNow(env, packageId, calls = budget()) {
|
|
|
138
172
|
export async function purgeDue(env, calls = budget()) {
|
|
139
173
|
const now = new Date().toISOString();
|
|
140
174
|
const stale = new Date(Date.now() - 7 * DAY).toISOString();
|
|
175
|
+
// Reserve most of the invocation for new expiry/deletion work. A growing
|
|
176
|
+
// history of empty scopes must not starve today's deliveries.
|
|
177
|
+
const recurring = budget(Math.min(6, Math.max(0, calls.left - 6)));
|
|
178
|
+
const recurringLimit = recurring.left;
|
|
179
|
+
const cleanupDrained = await sweepCleanupScopes(env, recurring);
|
|
180
|
+
calls.left -= recurringLimit - recurring.left;
|
|
181
|
+
if (calls.left <= 0) return false;
|
|
141
182
|
const expiredFiles = await env.DB.prepare(`
|
|
142
183
|
SELECT id FROM deliveries
|
|
143
184
|
WHERE files_expires_at IS NOT NULL AND files_expires_at<=?
|
|
144
185
|
AND status IN ('uploading','active','archived')
|
|
145
|
-
AND EXISTS (
|
|
146
|
-
SELECT 1 FROM
|
|
147
|
-
WHERE p.delivery_id=deliveries.id AND p.state!='deleted'
|
|
148
|
-
)
|
|
186
|
+
AND (EXISTS (SELECT 1 FROM delivery_packages p WHERE p.delivery_id=deliveries.id AND p.state!='deleted' AND ${packageNotPreserved('p')})
|
|
187
|
+
OR EXISTS (SELECT 1 FROM delivery_hero_objects h WHERE h.delivery_id=deliveries.id AND h.state!='deleted' AND ${objectNotPreserved('h.object_key')}))
|
|
149
188
|
ORDER BY files_expires_at LIMIT 10
|
|
150
189
|
`).bind(now).all();
|
|
151
190
|
for (const delivery of (expiredFiles.results || [])) {
|
|
152
|
-
await env.
|
|
153
|
-
|
|
154
|
-
UPDATE delivery_packages SET state='deleted',deleted_at=?,purge_after=?,updated_at=?
|
|
155
|
-
WHERE delivery_id=? AND state!='deleted'
|
|
156
|
-
`).bind(now, now, now, delivery.id),
|
|
157
|
-
env.DB.prepare(`
|
|
158
|
-
UPDATE delivery_hero_objects SET state='deleted',purge_after=?,updated_at=?
|
|
159
|
-
WHERE delivery_id=? AND state!='deleted'
|
|
160
|
-
`).bind(now, now, delivery.id),
|
|
161
|
-
]);
|
|
191
|
+
await markExpiredFiles(env, delivery.id);
|
|
192
|
+
if (!await purgeDeliveryNow(env, delivery.id, calls) && calls.left <= 0) return false;
|
|
162
193
|
}
|
|
163
194
|
await env.DB.prepare(`
|
|
164
195
|
UPDATE delivery_packages SET state='deleted',deleted_at=?,purge_after=?,updated_at=?
|
|
165
|
-
WHERE state='uploading' AND updated_at<=?
|
|
196
|
+
WHERE state='uploading' AND updated_at<=? AND ${packageNotPreserved('delivery_packages')}
|
|
166
197
|
AND NOT EXISTS (
|
|
167
198
|
SELECT 1 FROM delivery_uploads u
|
|
168
199
|
WHERE u.package_id=delivery_packages.id AND u.updated_at>?
|
|
@@ -190,8 +221,9 @@ export async function purgeDue(env, calls = budget()) {
|
|
|
190
221
|
}
|
|
191
222
|
const staleHeroes = await env.DB.prepare(`
|
|
192
223
|
SELECT id,object_key FROM delivery_hero_objects
|
|
193
|
-
WHERE (state='pending' AND updated_at<=?)
|
|
194
|
-
OR (state='deleted' AND purge_after IS NOT NULL AND purge_after<=?)
|
|
224
|
+
WHERE ((state='pending' AND updated_at<=?)
|
|
225
|
+
OR (state='deleted' AND purge_after IS NOT NULL AND purge_after<=?))
|
|
226
|
+
AND ${objectNotPreserved('delivery_hero_objects.object_key')}
|
|
195
227
|
ORDER BY updated_at LIMIT 10
|
|
196
228
|
`).bind(new Date(Date.now() - DAY).toISOString(), now).all();
|
|
197
229
|
if (!await purgeHeroes(env, staleHeroes.results || [], calls)) return false;
|
|
@@ -200,13 +232,14 @@ export async function purgeDue(env, calls = budget()) {
|
|
|
200
232
|
FROM delivery_packages p
|
|
201
233
|
LEFT JOIN delivery_uploads u ON u.package_id=p.id AND u.variant='originals'
|
|
202
234
|
WHERE p.state='ready' AND p.originals_key IS NOT NULL
|
|
235
|
+
AND ${packageNotPreserved('p')} AND ${objectNotPreserved('p.originals_key')}
|
|
203
236
|
AND p.originals_purge_after IS NOT NULL AND p.originals_purge_after<=?
|
|
204
237
|
ORDER BY p.originals_purge_after LIMIT 4
|
|
205
238
|
`).bind(now).all();
|
|
206
239
|
for (const pkg of (archived.results || [])) {
|
|
207
240
|
if (calls.left <= 0) return false;
|
|
208
|
-
|
|
209
|
-
await b2Delete(env, pkg.originals_key);
|
|
241
|
+
await rememberCleanup(env, pkg.originals_key);
|
|
242
|
+
if (!await b2Delete(env, pkg.originals_key, calls)) return false;
|
|
210
243
|
await env.DB.batch([
|
|
211
244
|
env.DB.prepare(`
|
|
212
245
|
UPDATE delivery_packages SET originals_key=NULL,originals_purge_after=NULL,
|
|
@@ -219,6 +252,7 @@ export async function purgeDue(env, calls = budget()) {
|
|
|
219
252
|
const { results } = await env.DB.prepare(`
|
|
220
253
|
SELECT * FROM delivery_packages
|
|
221
254
|
WHERE state='deleted' AND purge_after IS NOT NULL AND purge_after<=?
|
|
255
|
+
AND ${packageNotPreserved('delivery_packages')}
|
|
222
256
|
ORDER BY purge_after LIMIT 8
|
|
223
257
|
`).bind(now).all();
|
|
224
258
|
if (!await purgePackages(env, results || [], calls)) return false;
|
|
@@ -230,7 +264,7 @@ export async function purgeDue(env, calls = budget()) {
|
|
|
230
264
|
`).bind(now).run();
|
|
231
265
|
/* Una fase che ha riempito la sua LIMIT probabilmente ha ancora coda: chi
|
|
232
266
|
* chiama in loop (il cron) sa che deve rifare un giro. */
|
|
233
|
-
return (expiredFiles.results || []).length < 10 &&
|
|
267
|
+
return cleanupDrained && (expiredFiles.results || []).length < 10 &&
|
|
234
268
|
(abandoned.results || []).length < 10 &&
|
|
235
269
|
(staleHeroes.results || []).length < 10 &&
|
|
236
270
|
(archived.results || []).length < 4 &&
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/* Read-only, paginated B2 inventory. Partial work never replaces a valid snapshot. */
|
|
2
|
+
import { b2Request } from './b2.js';
|
|
3
|
+
const HOUR = 3_600_000;
|
|
4
|
+
const enabled = env => env.DELIVERY_STORAGE_DASHBOARD === 'true';
|
|
5
|
+
const decode = s => s.replace(/&#x([0-9a-f]+);/gi,(_,n)=>String.fromCodePoint(parseInt(n,16))).replace(/&#(\d+);/g,(_,n)=>String.fromCodePoint(+n)).replaceAll('<','<').replaceAll('>','>').replaceAll('"','"').replaceAll(''',"'").replaceAll('&','&');
|
|
6
|
+
const xml = (s,n) => decode(s.match(new RegExp(`<${n}>([\\s\\S]*?)<\\/${n}>`))?.[1] || '');
|
|
7
|
+
function number(s,n){const v=xml(s,n);if(!/^\d+$/.test(v)||!Number.isSafeInteger(+v))throw Error('Dimensione B2 non valida');return +v;}
|
|
8
|
+
function truncated(s){const v=xml(s,'IsTruncated');if(!['true','false'].includes(v))throw Error('Paginazione B2 non valida');return v==='true';}
|
|
9
|
+
async function listing(env,key,query,root){const r=await b2Request(env,'GET',key,{query});const s=await r.text();if(!r.ok||!s.includes('<'+root))throw Error(`Verifica B2 non riuscita (${r.status})`);return s;}
|
|
10
|
+
export async function deliveryDashboardStats(env){
|
|
11
|
+
const now=new Date().toISOString();
|
|
12
|
+
const {results}=await env.DB.prepare(`SELECT d.id,d.title,d.client_name,d.files_expires_at,
|
|
13
|
+
(SELECT COALESCE(SUM(l.download_count),0) FROM delivery_links l WHERE l.delivery_id=d.id) download_count
|
|
14
|
+
FROM deliveries d WHERE d.status IN ('active','archived')
|
|
15
|
+
AND (d.files_expires_at IS NULL OR d.files_expires_at>?) AND (d.expires_at IS NULL OR d.expires_at>?)
|
|
16
|
+
AND EXISTS(SELECT 1 FROM delivery_packages p WHERE p.delivery_id=d.id AND p.state='ready')
|
|
17
|
+
AND EXISTS(SELECT 1 FROM delivery_links l WHERE l.delivery_id=d.id AND l.revoked_at IS NULL AND (l.expires_at IS NULL OR l.expires_at>?))
|
|
18
|
+
ORDER BY d.updated_at DESC`).bind(now,now,now).all();
|
|
19
|
+
const rows=results||[];
|
|
20
|
+
return {active:rows.length,withRequests:rows.filter(r=>Number(r.download_count)>0).length,withoutRequests:rows.filter(r=>!Number(r.download_count)).length,
|
|
21
|
+
requestedDownloads:rows.reduce((n,r)=>n+Number(r.download_count),0),transfers:rows.map(r=>({id:r.id,title:r.title,clientName:r.client_name,expiresAt:r.files_expires_at,downloadCount:Number(r.download_count)}))};
|
|
22
|
+
}
|
|
23
|
+
async function owners(env){
|
|
24
|
+
const p=await env.DB.prepare('SELECT storage_prefix,delivery_id FROM delivery_packages').all();
|
|
25
|
+
const h=await env.DB.prepare('SELECT object_key,delivery_id FROM delivery_hero_objects').all();
|
|
26
|
+
const u=await env.DB.prepare('SELECT object_key,delivery_id FROM delivery_uploads').all();
|
|
27
|
+
return {prefixes:(p.results||[]).filter(p=>p.storage_prefix).map(p=>[p.storage_prefix.replace(/\/+$/,'')+'/',p.delivery_id]).sort((a,b)=>b[0].length-a[0].length),
|
|
28
|
+
exact:Object.fromEntries([...(h.results||[]),...(u.results||[])].filter(r=>r.object_key&&r.delivery_id).map(r=>[r.object_key,r.delivery_id]))};
|
|
29
|
+
}
|
|
30
|
+
function add(state,key,bytes){
|
|
31
|
+
if(!Number.isSafeInteger(state.totalBytes+bytes))throw Error('Inventario B2 troppo grande');
|
|
32
|
+
const owner=state.owners.exact[key] || state.owners.prefixes.find(([prefix])=>key.startsWith(prefix))?.[1];
|
|
33
|
+
state.totalBytes+=bytes;
|
|
34
|
+
if(owner)state.byDelivery[owner]=(state.byDelivery[owner]||0)+bytes;else state.unassignedBytes+=bytes;
|
|
35
|
+
}
|
|
36
|
+
async function step(env,s){
|
|
37
|
+
if(s.phase==='versions'){
|
|
38
|
+
const body=await listing(env,'',{versions:'','max-keys':'1000',...s.marker},'ListVersionsResult');
|
|
39
|
+
for(const m of body.matchAll(/<(Version|DeleteMarker)>([\s\S]*?)<\/\1>/g)){
|
|
40
|
+
if(m[1]==='DeleteMarker'){s.deleteMarkers++;continue;}
|
|
41
|
+
const key=xml(m[2],'Key');if(!key)throw Error('Oggetto B2 senza chiave');
|
|
42
|
+
const bytes=number(m[2],'Size'),latest=xml(m[2],'IsLatest');if(!['true','false'].includes(latest))throw Error('Versione B2 senza stato');
|
|
43
|
+
add(s,key,bytes);s.objectVersions++;if(latest==='false')s.hiddenBytes+=bytes;else s.currentObjects++;
|
|
44
|
+
}
|
|
45
|
+
if(truncated(body)){const k=xml(body,'NextKeyMarker'),v=xml(body,'NextVersionIdMarker');if(!k)throw Error('Marker B2 mancante');
|
|
46
|
+
const next={'key-marker':k,'version-id-marker':v};if(JSON.stringify(next)===JSON.stringify(s.marker))throw Error('Inventario B2 bloccato');s.marker=next;
|
|
47
|
+
}else{s.phase='uploads';s.marker={};}
|
|
48
|
+
}else if(s.phase==='uploads'){
|
|
49
|
+
const body=await listing(env,'',{uploads:'','max-uploads':'100',...s.marker},'ListMultipartUploadsResult');
|
|
50
|
+
s.uploads=[...body.matchAll(/<Upload>([\s\S]*?)<\/Upload>/g)].map(m=>{const key=xml(m[1],'Key'),id=xml(m[1],'UploadId');if(!key||!id)throw Error('Upload B2 incompleto');return {key,id};});
|
|
51
|
+
s.incompleteUploads+=s.uploads.length;s.uploadIndex=0;s.partMarker='';s.moreUploads=truncated(body);
|
|
52
|
+
if(s.moreUploads){const k=xml(body,'NextKeyMarker'),u=xml(body,'NextUploadIdMarker');if(!k||!u)throw Error('Marker multipart mancante');const next={'key-marker':k,'upload-id-marker':u};if(JSON.stringify(next)===JSON.stringify(s.marker))throw Error('Elenco multipart bloccato');s.marker=next;}
|
|
53
|
+
s.phase=s.uploads.length?'parts':s.moreUploads?'uploads':'done';
|
|
54
|
+
}else if(s.phase==='parts'){
|
|
55
|
+
const u=s.uploads[s.uploadIndex];const query={uploadId:u.id,'max-parts':'1000'};if(s.partMarker)query['part-number-marker']=s.partMarker;
|
|
56
|
+
const body=await listing(env,u.key,query,'ListPartsResult');
|
|
57
|
+
for(const m of body.matchAll(/<Part>([\s\S]*?)<\/Part>/g)){const bytes=number(m[1],'Size');add(s,u.key,bytes);s.incompleteBytes+=bytes;}
|
|
58
|
+
if(truncated(body)){const next=xml(body,'NextPartNumberMarker');if(!next||next===s.partMarker)throw Error('Marker parti mancante');s.partMarker=next;}
|
|
59
|
+
else{s.uploadIndex++;s.partMarker='';if(s.uploadIndex>=s.uploads.length){s.uploads=[];s.phase=s.moreUploads?'uploads':'done';}}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
export async function verifyDeliveryStorage(env,{force=false,maxCalls=4}={}){
|
|
63
|
+
if(!enabled(env))return;
|
|
64
|
+
const token=crypto.randomUUID(),now=Date.now();
|
|
65
|
+
const claimed=await env.DB.prepare(`UPDATE delivery_storage_dashboard SET lease_token=?,lease_until=? WHERE id=1 AND lease_until<?`).bind(token,now+5*60_000,now).run();
|
|
66
|
+
if(claimed.meta?.changes!==1)return;
|
|
67
|
+
try{
|
|
68
|
+
const row=await env.DB.prepare('SELECT * FROM delivery_storage_dashboard WHERE id=1').first();
|
|
69
|
+
const previous=row.snapshot_json?JSON.parse(row.snapshot_json):null;
|
|
70
|
+
const sameBucket=value=>value?.bucket===env.B2_BUCKET && value?.endpoint===env.B2_ENDPOINT;
|
|
71
|
+
if(row.status!=='running'&&!force&&row.next_check_at&&Date.parse(row.next_check_at)>now&&(!previous||sameBucket(previous)))return;
|
|
72
|
+
let state=row.status==='running'&&row.state_json?JSON.parse(row.state_json):null;
|
|
73
|
+
if(state&&!sameBucket(state))state=null;
|
|
74
|
+
if(!state){state={bucket:env.B2_BUCKET,endpoint:env.B2_ENDPOINT,phase:'versions',marker:{},owners:await owners(env),byDelivery:{},totalBytes:0,hiddenBytes:0,incompleteBytes:0,unassignedBytes:0,incompleteUploads:0,objectVersions:0,currentObjects:0,deleteMarkers:0,startedAt:new Date().toISOString()};
|
|
75
|
+
await env.DB.prepare(`UPDATE delivery_storage_dashboard SET status='running',started_at=?,last_error=NULL WHERE id=1 AND lease_token=?`).bind(state.startedAt,token).run();}
|
|
76
|
+
for(let n=0;n<Math.min(8,Math.max(1,maxCalls))&&state.phase!=='done';n++){
|
|
77
|
+
await step(env,state);
|
|
78
|
+
const serialized=JSON.stringify(state);if(serialized.length>1_000_000)throw Error('Inventario troppo esteso per questo controllo');
|
|
79
|
+
await env.DB.prepare('UPDATE delivery_storage_dashboard SET state_json=? WHERE id=1 AND lease_token=?').bind(serialized,token).run();
|
|
80
|
+
}
|
|
81
|
+
if(state.phase==='done'){
|
|
82
|
+
const {owners:unused,...snapshot}=state;const checked=new Date().toISOString();
|
|
83
|
+
await env.DB.prepare(`UPDATE delivery_storage_dashboard SET status='complete',snapshot_json=?,state_json=NULL,checked_at=?,next_check_at=?,last_error=NULL WHERE id=1 AND lease_token=?`)
|
|
84
|
+
.bind(JSON.stringify(snapshot),checked,new Date(Date.now()+HOUR).toISOString(),token).run();
|
|
85
|
+
}
|
|
86
|
+
}catch(error){
|
|
87
|
+
await env.DB.prepare(`UPDATE delivery_storage_dashboard SET status='failed',state_json=NULL,last_error=?,next_check_at=? WHERE id=1 AND lease_token=?`)
|
|
88
|
+
.bind(String(error.message||error).slice(0,300),new Date(Date.now()+15*60_000).toISOString(),token).run();
|
|
89
|
+
}finally{await env.DB.prepare('UPDATE delivery_storage_dashboard SET lease_token=NULL,lease_until=0 WHERE id=1 AND lease_token=?').bind(token).run();}
|
|
90
|
+
}
|
|
91
|
+
export async function readDeliveryDashboard(env){
|
|
92
|
+
const stats=await deliveryDashboardStats(env);
|
|
93
|
+
if(!enabled(env))return {...stats,storage:{enabled:false,status:'unavailable',snapshot:null}};
|
|
94
|
+
const row=await env.DB.prepare('SELECT status,snapshot_json,checked_at,next_check_at,last_error,started_at FROM delivery_storage_dashboard WHERE id=1').first();
|
|
95
|
+
const saved=row.snapshot_json?JSON.parse(row.snapshot_json):null;
|
|
96
|
+
const snapshot=saved?.bucket===env.B2_BUCKET&&saved?.endpoint===env.B2_ENDPOINT?saved:null;
|
|
97
|
+
return {...stats,transfers:stats.transfers.map(t=>({...t,storedBytes:snapshot?snapshot.byDelivery[t.id]||0:null})),
|
|
98
|
+
storage:{enabled:true,status:!snapshot&&saved?'idle':row.status,checkedAt:snapshot?row.checked_at:null,startedAt:row.started_at,nextCheckAt:row.next_check_at,error:row.last_error,
|
|
99
|
+
activeBytes:snapshot?stats.transfers.reduce((n,t)=>n+(snapshot.byDelivery[t.id]||0),0):null,snapshot}};
|
|
100
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { readDeliveryDashboard, verifyDeliveryStorage } from "../_shared/delivery-storage-dashboard.js";
|
|
1
2
|
/* CRUD immediato delle consegne.
|
|
2
3
|
*
|
|
3
4
|
* Sta sotto /admin/: Access + verifica JWT sono già applicati dal middleware.
|
|
@@ -21,11 +22,15 @@ const DAY = 86_400_000;
|
|
|
21
22
|
|
|
22
23
|
export async function onRequestGet({ request, env, waitUntil }) {
|
|
23
24
|
if (!env.DB) return json({ ok: false, error: "Il servizio dei transfer non è configurato" }, 500);
|
|
24
|
-
if (typeof waitUntil === "function") {
|
|
25
|
+
if (typeof waitUntil === "function" && new URL(request.url).searchParams.get("dashboard") !== "1") {
|
|
25
26
|
waitUntil(purgeDue(env).catch((error) => console.error("delivery purge:", error)));
|
|
26
27
|
}
|
|
27
28
|
const id = new URL(request.url).searchParams.get("id");
|
|
28
29
|
try {
|
|
30
|
+
if (new URL(request.url).searchParams.get("dashboard") === "1") {
|
|
31
|
+
if (typeof waitUntil === "function") waitUntil(verifyDeliveryStorage(env));
|
|
32
|
+
return json({ ok: true, dashboard: await readDeliveryDashboard(env) });
|
|
33
|
+
}
|
|
29
34
|
if (new URL(request.url).searchParams.get("capabilities") === "1") return json({ ok: true, manifestVersion: v2Enabled(env) ? 2 : 1, jpegEnabled: env.DELIVERY_JPEG_ENABLED === "true", downloadLabelsEnabled: env.DELIVERY_DOWNLOAD_LABELS === "true" });
|
|
30
35
|
if (id) {
|
|
31
36
|
const delivery = await deliveryDetail(env, id, new URL(request.url).origin);
|
|
@@ -61,6 +66,10 @@ export async function onRequestPost({ request, env }) {
|
|
|
61
66
|
const action = String(body?.action || "");
|
|
62
67
|
try {
|
|
63
68
|
switch (action) {
|
|
69
|
+
case "verifyStorage": {
|
|
70
|
+
await verifyDeliveryStorage(env, { force: true });
|
|
71
|
+
return json({ ok: true, dashboard: await readDeliveryDashboard(env) });
|
|
72
|
+
}
|
|
64
73
|
case "capabilities": return json({ ok: true, manifestVersion: v2Enabled(env) ? 2 : 1, jpegEnabled: env.DELIVERY_JPEG_ENABLED === "true", downloadLabelsEnabled: env.DELIVERY_DOWNLOAD_LABELS === "true" });
|
|
65
74
|
case "create": return json({ ok: true, delivery: await createDelivery(env, body, new URL(request.url).origin) });
|
|
66
75
|
case "quickCreate": return json({ ok: true, delivery: await createQuickDelivery(env, body, new URL(request.url).origin) });
|
|
@@ -287,7 +296,7 @@ async function createPackage(env, body) {
|
|
|
287
296
|
const sourceBytes = validateDeliverySourceBytes(body.sourceBytes);
|
|
288
297
|
if (!Number.isSafeInteger(body.fileCount) || body.fileCount < 1) throw new InputError("Numero dei file non valido");
|
|
289
298
|
const deliveryId = required(body.id, "id del transfer mancante");
|
|
290
|
-
const delivery = await env.DB.prepare("SELECT id,status FROM deliveries WHERE id=? AND status!='deleted'")
|
|
299
|
+
const delivery = await env.DB.prepare("SELECT id,status FROM deliveries WHERE id=? AND status!='deleted' AND (files_expires_at IS NULL OR files_expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now'))")
|
|
291
300
|
.bind(deliveryId).first();
|
|
292
301
|
if (!delivery) throw new InputError("Transfer non trovato");
|
|
293
302
|
const id = crypto.randomUUID();
|
|
@@ -324,7 +333,9 @@ async function finalizePackage(env, body) {
|
|
|
324
333
|
const deliveryId = required(body.id, "id del transfer mancante");
|
|
325
334
|
const packageId = required(body.packageId, "id dei file mancante");
|
|
326
335
|
const pkg = await env.DB.prepare(
|
|
327
|
-
|
|
336
|
+
`SELECT p.* FROM delivery_packages p JOIN deliveries d ON d.id=p.delivery_id
|
|
337
|
+
WHERE p.id=? AND p.delivery_id=? AND p.state IN ('uploading','ready') AND d.status!='deleted'
|
|
338
|
+
AND (d.files_expires_at IS NULL OR d.files_expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now'))`
|
|
328
339
|
).bind(packageId, deliveryId).first();
|
|
329
340
|
if (!pkg) throw new InputError("Non trovo il caricamento da completare");
|
|
330
341
|
if (manifestVersion(pkg) === 2) throw new ConflictError("Usa il completamento a passi per questo pacchetto");
|
|
@@ -51,8 +51,9 @@ async function heroPresign(env, body) {
|
|
|
51
51
|
const pkg = await env.DB.prepare(`
|
|
52
52
|
SELECT p.* FROM delivery_packages p JOIN deliveries d ON d.id=p.delivery_id
|
|
53
53
|
WHERE p.id=? AND p.delivery_id=? AND p.state IN ('uploading','ready') AND d.status!='deleted'
|
|
54
|
+
AND (d.files_expires_at IS NULL OR d.files_expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now'))
|
|
54
55
|
`).bind(packageId, deliveryId).first();
|
|
55
|
-
if (!pkg) throw
|
|
56
|
+
if (!pkg) throw invalid("pacchetto per la hero non trovato o scaduto");
|
|
56
57
|
const heroId = crypto.randomUUID();
|
|
57
58
|
const key = b2ObjectKey(pkg.storage_prefix, `heroes/${heroId}.webp`);
|
|
58
59
|
const now = new Date().toISOString();
|
|
@@ -355,6 +356,7 @@ async function packageFor(env, body) {
|
|
|
355
356
|
const pkg = await env.DB.prepare(`
|
|
356
357
|
SELECT p.* FROM delivery_packages p JOIN deliveries d ON d.id=p.delivery_id
|
|
357
358
|
WHERE p.id=? AND p.delivery_id=? AND p.state='uploading' AND d.status!='deleted'
|
|
359
|
+
AND (d.files_expires_at IS NULL OR d.files_expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now'))
|
|
358
360
|
`).bind(String(body.packageId || ""), String(body.id || "")).first();
|
|
359
361
|
if (!pkg) throw invalid("pacchetto in caricamento non trovato");
|
|
360
362
|
validateDeliverySourceBytes(pkg.source_bytes ?? 0);
|
|
@@ -369,6 +371,7 @@ async function uploadFor(env, body, required = true, allowCompleted = false) {
|
|
|
369
371
|
JOIN deliveries d ON d.id=u.delivery_id
|
|
370
372
|
WHERE u.id=? AND u.state IN (${allowCompleted ? "'uploading','completed'" : "'uploading'"})
|
|
371
373
|
AND p.state IN (${allowCompleted ? "'uploading','ready'" : "'uploading'"}) AND d.status!='deleted'
|
|
374
|
+
AND (${body.action === 'abort' ? '1' : "d.files_expires_at IS NULL OR d.files_expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now')"})
|
|
372
375
|
`).bind(String(body.uploadId || "")).first();
|
|
373
376
|
if (!upload && required) throw invalid("sessione multipart non trovata");
|
|
374
377
|
// L'annullamento deve restare disponibile anche per vecchie sessioni fuori limite.
|
|
@@ -19,7 +19,7 @@ import {
|
|
|
19
19
|
} from "../_shared/delivery-crypto.js";
|
|
20
20
|
|
|
21
21
|
import { readManifestEntry, readManifestPage } from "../_shared/delivery-manifest.js";
|
|
22
|
-
import { purgeDeliveryNow } from "../_shared/delivery-purge.js";
|
|
22
|
+
import { purgeDeliveryNow, markExpiredFiles } from "../_shared/delivery-purge.js";
|
|
23
23
|
|
|
24
24
|
const COOKIE = "adminkit_delivery";
|
|
25
25
|
const HOUR = 3_600_000;
|
|
@@ -530,17 +530,7 @@ async function resolveHeroes(env, value, packages) {
|
|
|
530
530
|
}
|
|
531
531
|
|
|
532
532
|
async function purgeExpiredBytes(env, deliveryId) {
|
|
533
|
-
|
|
534
|
-
await env.DB.batch([
|
|
535
|
-
env.DB.prepare(`
|
|
536
|
-
UPDATE delivery_packages SET state='deleted',deleted_at=?,purge_after=?,updated_at=?
|
|
537
|
-
WHERE delivery_id=? AND state!='deleted' AND EXISTS(SELECT 1 FROM deliveries WHERE id=delivery_id AND files_expires_at<=?)
|
|
538
|
-
`).bind(now, now, now, deliveryId, now),
|
|
539
|
-
env.DB.prepare(`
|
|
540
|
-
UPDATE delivery_hero_objects SET state='deleted',purge_after=?,updated_at=?
|
|
541
|
-
WHERE delivery_id=? AND state!='deleted' AND EXISTS(SELECT 1 FROM deliveries WHERE id=delivery_id AND files_expires_at<=?)
|
|
542
|
-
`).bind(now, now, deliveryId, now),
|
|
543
|
-
]);
|
|
533
|
+
await markExpiredFiles(env, deliveryId);
|
|
544
534
|
await purgeDeliveryNow(env, deliveryId);
|
|
545
535
|
}
|
|
546
536
|
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
-- Durable, bucket-local scopes. No FK: these must outlive deleted deliveries.
|
|
2
|
+
-- Never seed from the bucket: only explicitly removed application assets enter here.
|
|
3
|
+
CREATE TABLE IF NOT EXISTS delivery_storage_cleanup (
|
|
4
|
+
object_key TEXT NOT NULL,
|
|
5
|
+
is_prefix INTEGER NOT NULL CHECK(is_prefix IN (0,1)),
|
|
6
|
+
created_at TEXT NOT NULL,
|
|
7
|
+
next_check_at TEXT NOT NULL,
|
|
8
|
+
last_checked_at TEXT,
|
|
9
|
+
last_error TEXT,
|
|
10
|
+
PRIMARY KEY(object_key,is_prefix)
|
|
11
|
+
);
|
|
12
|
+
CREATE INDEX IF NOT EXISTS delivery_storage_cleanup_due ON delivery_storage_cleanup(next_check_at);
|
|
13
|
+
|
|
14
|
+
-- Deployment inventory: existing objects are held until separately approved.
|
|
15
|
+
CREATE TABLE IF NOT EXISTS delivery_storage_preserved (
|
|
16
|
+
object_key TEXT PRIMARY KEY,
|
|
17
|
+
captured_at TEXT NOT NULL,
|
|
18
|
+
reason TEXT NOT NULL DEFAULT 'pre-deploy inventory'
|
|
19
|
+
);
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
-- One resumable, read-only B2 inventory per consumer database.
|
|
2
|
+
CREATE TABLE IF NOT EXISTS delivery_storage_dashboard (
|
|
3
|
+
id INTEGER PRIMARY KEY CHECK(id=1),
|
|
4
|
+
status TEXT NOT NULL DEFAULT 'idle',
|
|
5
|
+
state_json TEXT,
|
|
6
|
+
snapshot_json TEXT,
|
|
7
|
+
started_at TEXT,
|
|
8
|
+
checked_at TEXT,
|
|
9
|
+
next_check_at TEXT,
|
|
10
|
+
last_error TEXT,
|
|
11
|
+
lease_token TEXT,
|
|
12
|
+
lease_until INTEGER NOT NULL DEFAULT 0
|
|
13
|
+
);
|
|
14
|
+
INSERT OR IGNORE INTO delivery_storage_dashboard(id) VALUES (1);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cardinali-studio/adminkit",
|
|
3
|
-
"version": "2.2.
|
|
3
|
+
"version": "2.2.41",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Motore riusabile di un pannello di amministrazione per siti Hugo su Cloudflare Pages: codec del front matter guidato dallo schema, form React, libreria media su R2. NIENTE di specifico di un sito qui dentro.",
|
|
6
6
|
"license": "0BSD",
|