🚧 Add message delete
This commit is contained in:
@@ -116,6 +116,7 @@ Authentication is layered:
|
||||
| Read messages/devices/attributes/users | ✓ | ✓ | ✓ | ✓ |
|
||||
| Write devices, settings, attribute timelines, configs, tokens | — 403 | ✓ | ✓ | ✓ |
|
||||
| Import messages | — 403 | ✓ | ✓ | ✓ |
|
||||
| Delete / restore messages | — 403 | ✓ | ✓ | ✓ |
|
||||
| Add users | — 403 | ✓ — only role `user` | ✓ any role | ✓ |
|
||||
| Modify/delete users | — 403 | ✓ — only `user`-role accounts | ✓ (never the last admin) | ✓ |
|
||||
|
||||
@@ -128,6 +129,10 @@ The first admin is seeded from `BOOTSTRAP_ADMIN_USER`/`BOOTSTRAP_ADMIN_PASSWORD`
|
||||
| `GET /messages` | token | List messages, newest first. The device's **current settings document** (from `imei_map`) is merged into each item's `payload`; on duplicate keys the stored payload wins. Each item also carries an **`attributes`** sibling field with the device's time-varying attributes **resolved as of the message's device time** (`payload_time`, `received_at` as the fallback) — apply the offsets to the payload values yourself (e.g. `payload[k] + attributes[k]`). Query parameters: `imei`, `device` (exact-match filters), `from`/`to` (ISO 8601 range on `received_at` — server receipt time; inclusive; naive values treated as UTC), `payload_from`/`payload_to` (same but on `payload_time` — the device timestamp extracted from the JSON; messages without one are excluded; ordering switches to `payload_time DESC`), `limit` (default 100, capped at `API_MAX_LIMIT`), `offset` for paging. The response carries a **filter-aware `total`** (the count over the same filters as `items`, so pagers can show "page X of Y" and jump to the last page) alongside `limit`/`offset`. Reversed ranges return 422 |
|
||||
| `GET /messages/export` | token | **Export selected messages as stored** (raw rows, no read-time settings merge, no resolved attributes). Query: repeatable `ids` (e.g. `?ids=1&ids=2`; at least one, capped at `API_MAX_LIMIT`). Returns a JSON array of `{id, received_at, topic, imei, device, payload, payload_time}` in the order the ids were given; unknown ids are skipped. Empty/oversized id lists → 422 |
|
||||
| `POST /messages/import` | superuser+ | **Import previously exported messages**: body is the JSON array from `GET /messages/export` (a single message object is accepted too). Rows are inserted as-is (original payload/timestamps/topic; `topic` defaults to `/import/<imei>`, absent `received_at` becomes now). The exported **`id` is ignored** — the database assigns fresh BIGSERIAL ids, so re-importing a file (or importing into the source database) never collides. Per-row validation → 422 with `row N` positions; max 10000 rows per request. Returns `{"status": "imported", "imported": n}` |
|
||||
| `POST /messages/delete` | superuser+ | **Soft-delete the selected messages**: moves them (same ids) into retention where they stay restorable for `RETENTION_DAYS` (env, default 30), then are purged. Body `{"ids": [...]}` (at least one, ≤ 10000; unknown ids skipped). The session username is recorded as `deleted_by` (NULL for app tokens). Returns `{"status": "deleted", "deleted": n}` |
|
||||
| `GET /messages/retention/count` | token | `{"count": n}` — retained messages right now (the Messages view banner); expired rows are purged first |
|
||||
| `GET /messages/retention` | token | One page of retained messages (newest deletions first): export shape plus `deleted_at`, `deleted_by`, `expires_at`, with a `total` for the pager. `limit` (default 100, capped at `API_MAX_LIMIT`) and `offset` |
|
||||
| `POST /messages/retention/restore` | superuser+ | Move retained messages back into `mqtt_messages` **with their original ids**. Body `{"ids": [...]}`; unknown ids (e.g. already purged) are skipped. Returns `{"status": "restored", "restored": n}` |
|
||||
| `GET /configs/{name}` | token | Read a config as JSON. `name`: `app_tokens` (secrets are not recoverable — app names with `null` placeholders) or `imei_map` (all device settings documents) |
|
||||
| `PUT/POST /configs/{name}` | token | **Bulk replace** a config in the database (delete + insert, transactional). Body **must be a JSON object**; per-config schema is validated (`imei_map` keys must be 15-digit IMEIs, values are settings documents — flat `"name"` values are promoted to `{"device": "name"}`; `app_tokens` must keep the `{"tokens": {name: secret}}` shape). Invalid payloads → 422, unknown names → 404. `app_tokens` changes take effect immediately; `imei_map` changes are picked up by the listener within ~5 seconds |
|
||||
| `GET /devices` | token | All devices, each as `{"imei": ..., **settings}` |
|
||||
@@ -257,9 +262,9 @@ Example response:
|
||||
- [ ] Change messages in tables to display information about the entire messege, not only the payload.
|
||||
- [X] Fix facet counts on Messages show 1 per device.
|
||||
- [x] Add ability to select how many rows to show in tables except the last messages table in the dashboard. Make it possible to select 10, 25, 50, 100, 200 or manual entry. Default to 25. (→ shared `Pager.vue` footer on Messages (server-side), Devices and Users (client-side via `useTable`); presets 10/25/50/100/200 + "custom…" manual entry clamped to `API_MAX_LIMIT`, default 25, persisted in localStorage; the dashboard's fixed 5-row list is untouched)
|
||||
- [ ] Add operations button in messages view for import/export or deletion of selected messages. (→ export + import landed: per-row checkboxes + header select-all + "Export JSON" download; superuser+ "Import" dialog (paste/file, array or single object). Delete operation still open)
|
||||
- [X] Add operations button in messages view for import/export or deletion of selected messages. (→ all three landed: per-row checkboxes + header select-all, "Export JSON" download, superuser+ "Import" dialog (paste/file, array or single object) and superuser+ **Delete** with confirm. The delete moves messages to retention — see the next line)
|
||||
- [x] Export option will export selected messages as they are stored in the database, without added parameters/features. (→ `GET /messages/export?ids=…` returns raw `mqtt_messages` rows — no settings merge, no attributes — and the UI downloads the JSON array; ids keep the caller's order)
|
||||
- [ ] Delete option will, after warning and user confirmation, move the deleted messages to retention. Where to see and be able to select messages to restore from retention? Rention lasts for 30 days. Add some kind of notification in the message view if messages are retained. Make it possible to view retained messages. Make it possible to recover retained messages.
|
||||
- [x] Delete option will, after warning and user confirmation, move the deleted messages to retention. Where to see and be able to select messages to restore from retention? Rention lasts for 30 days. Add some kind of notification in the message view if messages are retained. Make it possible to view retained messages in the messages view. Make it possible to recover retained messages. (→ **Delete** button in the selection toolbar (superuser+), confirm dialog, moves rows to `mqtt_messages_retention` keeping their ids; retention period = `RETENTION_DAYS` env (default 30), expired rows purged automatically. A **banner** in the Messages view shows the retained count and opens a **retention dialog**: the retained rows (deleted at/by, purge date, payload) with per-row selection, header select-all and **Restore selected** (superuser+). Viewers see the banner and the dialog but no delete/restore controls)
|
||||
- [ ] Add payload timestamp as column in messages view. The from/to field would be able to select if it is received or payload timestamp that is used for framing the loaded messages.
|
||||
- [x] Add table navigastion buttons for jumping to first or last page. Add manual navigation textfield/dropdown to all tables exept dashboard last messages table. (→ the shared `Pager.vue`: « first / ‹ prev / page-number textfield (clamped, Enter or blur to apply) / › next / » last buttons + "page X of Y" + "n–m of total"; works on Messages (server-side offset/limit) and the client-side tables (Devices/Users via `useTable` pagination). `GET /messages` now returns a filter-aware `total` to power it)
|
||||
- [ ] Add versioning of UI and API, show versions on bottom left.
|
||||
+246
@@ -754,6 +754,144 @@ class DeviceRenameStore:
|
||||
conn.close()
|
||||
|
||||
|
||||
class MessageRetentionPolicy:
|
||||
"""Soft-delete retention for messages: "deleting" MOVES rows into
|
||||
mqtt_messages_retention (same id), restorable until expires_at, purged
|
||||
afterwards. All moves are single atomic CTE statements — an id can
|
||||
never exist in both tables. Expired rows are purged LAZILY on every
|
||||
read/write below (no scheduler needed; the expires_at index makes it a
|
||||
cheap indexed delete)."""
|
||||
|
||||
def __init__(self, dsn: str, retention_days: int = 30) -> None:
|
||||
self._dsn = dsn
|
||||
self._retention_days = retention_days
|
||||
|
||||
def _purge_expired(self, cur: psycopg.Cursor) -> None:
|
||||
cur.execute("DELETE FROM mqtt_messages_retention WHERE expires_at < now()")
|
||||
|
||||
def delete(self, ids: list[int], deleted_by: str | None) -> int:
|
||||
"""Move rows out of mqtt_messages into retention. Unknown ids are
|
||||
skipped (a selection can go stale under live traffic). Returns the
|
||||
number of rows moved."""
|
||||
conn = psycopg.connect(self._dsn, autocommit=True)
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
self._purge_expired(cur)
|
||||
# single atomic move: DELETE ... RETURNING feeds the INSERT
|
||||
cur.execute(
|
||||
"""
|
||||
WITH moved AS (
|
||||
DELETE FROM mqtt_messages
|
||||
WHERE id = ANY(%s)
|
||||
RETURNING id, received_at, topic, imei, device,
|
||||
payload, payload_time
|
||||
), ins AS (
|
||||
INSERT INTO mqtt_messages_retention
|
||||
(id, received_at, topic, imei, device, payload,
|
||||
payload_time, deleted_by, expires_at)
|
||||
SELECT id, received_at, topic, imei, device, payload,
|
||||
payload_time, %s,
|
||||
now() + make_interval(days => %s)
|
||||
FROM moved
|
||||
RETURNING id
|
||||
)
|
||||
SELECT count(*) FROM ins
|
||||
""",
|
||||
(ids, deleted_by, self._retention_days),
|
||||
)
|
||||
return cur.fetchone()[0]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def restore(self, ids: list[int]) -> int:
|
||||
"""Move retained rows back into mqtt_messages with their ORIGINAL
|
||||
ids. Unknown ids are skipped. A plain INSERT (no ON CONFLICT): an
|
||||
id collision would mean a genuine anomaly and should fail loudly."""
|
||||
conn = psycopg.connect(self._dsn, autocommit=True)
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
self._purge_expired(cur)
|
||||
cur.execute(
|
||||
"""
|
||||
WITH moved AS (
|
||||
DELETE FROM mqtt_messages_retention
|
||||
WHERE id = ANY(%s)
|
||||
RETURNING id, received_at, topic, imei, device,
|
||||
payload, payload_time
|
||||
), ins AS (
|
||||
INSERT INTO mqtt_messages
|
||||
(id, received_at, topic, imei, device, payload,
|
||||
payload_time)
|
||||
SELECT id, received_at, topic, imei, device, payload,
|
||||
payload_time
|
||||
FROM moved
|
||||
RETURNING id
|
||||
)
|
||||
SELECT count(*) FROM ins
|
||||
""",
|
||||
(ids,),
|
||||
)
|
||||
return cur.fetchone()[0]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def count(self) -> int:
|
||||
"""Number of retained rows (expired ones purged first)."""
|
||||
# autocommit: the purge is a write too - on a plain connection it
|
||||
# would roll back on close (the count would still be correct within
|
||||
# the connection, but the expired rows would survive).
|
||||
conn = psycopg.connect(self._dsn, autocommit=True)
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
self._purge_expired(cur)
|
||||
cur.execute("SELECT count(*) FROM mqtt_messages_retention")
|
||||
return cur.fetchone()[0]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def list(self, limit: int, offset: int) -> tuple[list[dict[str, Any]], int]:
|
||||
"""One page of retained rows (newest deletions first) + the total,
|
||||
for the pager. Expired rows are purged first (persistently - see
|
||||
count())."""
|
||||
conn = psycopg.connect(self._dsn, autocommit=True)
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
self._purge_expired(cur)
|
||||
cur.execute("SELECT count(*) FROM mqtt_messages_retention")
|
||||
total = cur.fetchone()[0]
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, received_at, topic, imei, device, payload,
|
||||
payload_time, deleted_at, deleted_by, expires_at
|
||||
FROM mqtt_messages_retention
|
||||
ORDER BY deleted_at DESC, id DESC
|
||||
LIMIT %s OFFSET %s
|
||||
""",
|
||||
(limit, offset),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
finally:
|
||||
conn.close()
|
||||
return (
|
||||
[
|
||||
{
|
||||
"id": row[0],
|
||||
"received_at": row[1].isoformat(),
|
||||
"topic": row[2],
|
||||
"imei": row[3],
|
||||
"device": row[4],
|
||||
"payload": row[5],
|
||||
"payload_time": row[6].isoformat() if row[6] is not None else None,
|
||||
"deleted_at": row[7].isoformat(),
|
||||
"deleted_by": row[8],
|
||||
"expires_at": row[9].isoformat(),
|
||||
}
|
||||
for row in rows
|
||||
],
|
||||
total,
|
||||
)
|
||||
|
||||
|
||||
def _validate_rename_body(
|
||||
data: dict[str, Any], source: str
|
||||
) -> tuple[str, datetime | None, datetime | None, bool]:
|
||||
@@ -848,6 +986,26 @@ def _validate_attribute_body(
|
||||
return key.strip(), data["value"], effective_from, note
|
||||
|
||||
|
||||
def _validate_id_list(data: object, source: str) -> list[int]:
|
||||
"""Validate a {"ids": [...]} request body for delete/restore: a JSON
|
||||
object whose "ids" holds a non-empty list of integers, capped at
|
||||
API_MAX_LIMIT-equivalent 10000. Raises ValueError with a descriptive
|
||||
message otherwise."""
|
||||
if not isinstance(data, dict) or not isinstance(data.get("ids"), list):
|
||||
raise ValueError(f'{source}: expected JSON on the form {{"ids": [1, 2, ...]}}')
|
||||
ids = data["ids"]
|
||||
if not ids:
|
||||
raise ValueError(f"{source}: \"ids\" must not be empty")
|
||||
for i, value in enumerate(ids):
|
||||
if not isinstance(value, int) or isinstance(value, bool):
|
||||
raise ValueError(f"{source}: ids[{i}] must be an integer")
|
||||
if len(ids) > 10000:
|
||||
raise ValueError(
|
||||
f"{source}: too many ids ({len(ids)}); the limit is 10000"
|
||||
)
|
||||
return ids
|
||||
|
||||
|
||||
def _validate_import_rows(data: object, source: str) -> list[dict[str, Any]]:
|
||||
"""Validate an import body: a JSON array of exported-message objects
|
||||
(the GET /messages/export shape) — a single object is accepted too.
|
||||
@@ -958,6 +1116,7 @@ def create_app(
|
||||
user_store: UserStore | None = None,
|
||||
session_store: SessionStore | None = None,
|
||||
rename_store: DeviceRenameStore | None = None,
|
||||
retention_policy: MessageRetentionPolicy | None = None,
|
||||
) -> FastAPI:
|
||||
"""Build the API application.
|
||||
|
||||
@@ -974,6 +1133,7 @@ def create_app(
|
||||
|
||||
dsn = _env("DB_DSN")
|
||||
max_limit = int(_env("API_MAX_LIMIT", "10000"))
|
||||
retention_days = int(_env("RETENTION_DAYS", "30"))
|
||||
config = AppConfig(dsn=dsn, max_limit=max_limit)
|
||||
if token_store is None:
|
||||
token_store = TokenStore(
|
||||
@@ -995,6 +1155,8 @@ def create_app(
|
||||
session_store = SessionStore(dsn)
|
||||
if rename_store is None:
|
||||
rename_store = DeviceRenameStore(dsn)
|
||||
if retention_policy is None:
|
||||
retention_policy = MessageRetentionPolicy(dsn, retention_days=retention_days)
|
||||
|
||||
# Brute-force lockout state (in-process, per username).
|
||||
login_attempts: dict[str, dict[str, float]] = {}
|
||||
@@ -1936,6 +2098,90 @@ def create_app(
|
||||
logger.info("imported %d message(s)", imported)
|
||||
return {"status": "imported", "imported": imported}
|
||||
|
||||
# --- soft-delete retention ---------------------------------------------
|
||||
# "Deleting" selected messages MOVES them to mqtt_messages_retention
|
||||
# (same id, original columns untouched) where they stay restorable for
|
||||
# RETENTION_DAYS (env, default 30). Expired rows are purged lazily by
|
||||
# every retention operation below - no scheduler, and an expired row can
|
||||
# never be seen or restored. Delete/restore are superuser+; the reads
|
||||
# (banner count, dialog listing) are open to every authenticated role -
|
||||
# retained messages are the same messages they can already read.
|
||||
|
||||
@app.post(
|
||||
"/messages/delete",
|
||||
tags=["data"],
|
||||
dependencies=[Depends(authenticate), Depends(require_level("superuser"))],
|
||||
)
|
||||
def delete_messages(body: Any = Body(...), request: Request = None) -> dict[str, Any]:
|
||||
"""Move the selected messages to retention. Body: {"ids": [...]} (at
|
||||
least one, capped at 10000; unknown ids are skipped - a selection can
|
||||
go stale under live traffic). The session username is recorded as
|
||||
deleted_by (NULL for app tokens).
|
||||
|
||||
FastAPI injects the real Request for any parameter annotated with
|
||||
the Request type - the `= None` default is for tests only, never
|
||||
used at runtime."""
|
||||
deleted_by = getattr(request.state, "username", None) if request is not None else None
|
||||
try:
|
||||
ids = _validate_id_list(body, "request body")
|
||||
deleted = retention_policy.delete(ids, deleted_by)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=str(exc),
|
||||
) from exc
|
||||
except psycopg.Error as exc:
|
||||
raise _db_unavailable(exc) from exc
|
||||
logger.info("moved %d message(s) to retention (by %s)", deleted, deleted_by)
|
||||
return {"status": "deleted", "deleted": deleted}
|
||||
|
||||
@app.get(
|
||||
"/messages/retention/count", tags=["data"], dependencies=[Depends(authenticate)]
|
||||
)
|
||||
def retention_count() -> dict[str, int]:
|
||||
"""Retained rows right now, for the Messages view's banner."""
|
||||
try:
|
||||
return {"count": retention_policy.count()}
|
||||
except psycopg.Error as exc:
|
||||
raise _db_unavailable(exc) from exc
|
||||
|
||||
@app.get("/messages/retention", tags=["data"], dependencies=[Depends(authenticate)])
|
||||
def list_retention(
|
||||
limit: int = Query(100, gt=0, description="Page size"),
|
||||
offset: int = Query(0, ge=0, description="Page offset"),
|
||||
) -> dict[str, Any]:
|
||||
"""One page of retained messages (newest deletions first), export
|
||||
shape plus deleted_at/deleted_by/expires_at, with a filter-free
|
||||
total for the pager."""
|
||||
limit = min(limit, config.max_limit)
|
||||
try:
|
||||
items, total = retention_policy.list(limit, offset)
|
||||
except psycopg.Error as exc:
|
||||
raise _db_unavailable(exc) from exc
|
||||
return {"total": total, "limit": limit, "offset": offset, "items": items}
|
||||
|
||||
@app.post(
|
||||
"/messages/retention/restore",
|
||||
tags=["data"],
|
||||
dependencies=[Depends(authenticate), Depends(require_level("superuser"))],
|
||||
)
|
||||
def restore_messages(body: Any = Body(...)) -> dict[str, Any]:
|
||||
"""Move retained messages back into mqtt_messages with their
|
||||
ORIGINAL ids. Body: {"ids": [...]}; unknown ids are skipped (e.g.
|
||||
already purged). Returns {"status": "restored", "restored": n}."""
|
||||
try:
|
||||
ids = _validate_id_list(body, "request body")
|
||||
restored = retention_policy.restore(ids)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=str(exc),
|
||||
) from exc
|
||||
except psycopg.Error as exc:
|
||||
raise _db_unavailable(exc) from exc
|
||||
logger.info("restored %d message(s) from retention", restored)
|
||||
return {"status": "restored", "restored": restored}
|
||||
|
||||
return app
|
||||
|
||||
|
||||
|
||||
@@ -87,6 +87,10 @@ services:
|
||||
BOOTSTRAP_ADMIN_USER: ${BOOTSTRAP_ADMIN_USER:-}
|
||||
BOOTSTRAP_ADMIN_PASSWORD: ${BOOTSTRAP_ADMIN_PASSWORD:-}
|
||||
API_MAX_LIMIT: ${API_MAX_LIMIT:-10000}
|
||||
# How long soft-deleted messages stay in retention (days) before
|
||||
# being purged. Env-configurable, no schema impact (expires_at is
|
||||
# computed per delete).
|
||||
RETENTION_DAYS: ${RETENTION_DAYS:-30}
|
||||
LOG_LEVEL: ${LOG_LEVEL:-INFO}
|
||||
TZ: ${TZ:-Europe/Stockholm}
|
||||
ports:
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
<script setup lang="ts">
|
||||
// Retention dialog for the Messages view: lists soft-deleted messages
|
||||
// (moved to retention by "Delete"), newest deletions first, with their own
|
||||
// selection checkboxes. Superuser+ users can Restore selected rows back
|
||||
// into mqtt_messages (with their original ids). Read-only viewers can see
|
||||
// the list but get no restore controls (the API 403s regardless).
|
||||
import { ref, watch } from 'vue'
|
||||
import { ArchiveRestore, Trash2 } from 'lucide-vue-next'
|
||||
import { api } from '../api'
|
||||
import { canEdit, showError, toast } from '../store'
|
||||
import { formatTime } from '../format'
|
||||
import Pager from './Pager.vue'
|
||||
|
||||
export interface RetainedMessage {
|
||||
id: number
|
||||
received_at: string
|
||||
topic: string
|
||||
imei: string
|
||||
device: string
|
||||
payload: Record<string, unknown>
|
||||
payload_time: string | null
|
||||
deleted_at: string
|
||||
deleted_by: string | null
|
||||
expires_at: string
|
||||
}
|
||||
|
||||
interface RetentionPage {
|
||||
total: number
|
||||
limit: number
|
||||
offset: number
|
||||
items: RetainedMessage[]
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean
|
||||
pageSize: number
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'close'): void
|
||||
(e: 'restored', count: number): void
|
||||
}>()
|
||||
|
||||
const page = ref<RetentionPage | null>(null)
|
||||
const loading = ref(false)
|
||||
const offset = ref(0)
|
||||
const selected = ref(new Set<number>())
|
||||
const restoring = ref(false)
|
||||
|
||||
function load(): void {
|
||||
loading.value = true
|
||||
api<RetentionPage>(`/api/messages/retention?limit=${props.pageSize}&offset=${offset.value}`)
|
||||
.then((body) => {
|
||||
page.value = body
|
||||
})
|
||||
.catch((e) => showError(e))
|
||||
.finally(() => {
|
||||
loading.value = false
|
||||
})
|
||||
}
|
||||
|
||||
// parent opens/closes via the open prop; (re)opening resets the selection
|
||||
// and reloads the first page (retention contents change constantly).
|
||||
watch(
|
||||
() => props.open,
|
||||
(open, wasOpen) => {
|
||||
if (open && !wasOpen) {
|
||||
offset.value = 0
|
||||
selected.value = new Set()
|
||||
load()
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
function allChecked(): boolean {
|
||||
const items = page.value?.items ?? []
|
||||
return items.length > 0 && items.every((m) => selected.value.has(m.id))
|
||||
}
|
||||
|
||||
function toggleAll(): void {
|
||||
const items = page.value?.items ?? []
|
||||
if (!items.length) return
|
||||
const next = new Set(selected.value)
|
||||
if (allChecked()) {
|
||||
for (const m of items) next.delete(m.id)
|
||||
} else {
|
||||
for (const m of items) next.add(m.id)
|
||||
}
|
||||
selected.value = next
|
||||
}
|
||||
|
||||
function toggleRow(m: RetainedMessage, checked: boolean): void {
|
||||
const next = new Set(selected.value)
|
||||
if (checked) next.add(m.id)
|
||||
else next.delete(m.id)
|
||||
selected.value = next
|
||||
}
|
||||
|
||||
async function restoreSelected(): Promise<void> {
|
||||
if (!selected.value.size || restoring.value) return
|
||||
restoring.value = true
|
||||
try {
|
||||
const result = await api<{ status: string; restored: number }>(
|
||||
'/api/messages/retention/restore',
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ ids: [...selected.value] }),
|
||||
},
|
||||
)
|
||||
toast('success', `restored ${result.restored} message${result.restored === 1 ? '' : 's'}`)
|
||||
emit('restored', result.restored)
|
||||
offset.value = 0
|
||||
selected.value = new Set()
|
||||
load()
|
||||
} catch (e) {
|
||||
showError(e)
|
||||
} finally {
|
||||
restoring.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="open" class="card">
|
||||
<div class="row" style="justify-content: space-between; margin-bottom: 0.5rem">
|
||||
<div>
|
||||
<strong>Retained messages</strong>
|
||||
<span class="muted" style="margin-left: 0.5rem">
|
||||
soft-deleted; auto-purged 30 days after deletion; restore returns them
|
||||
with their original ids
|
||||
</span>
|
||||
</div>
|
||||
<button class="ghost" style="padding: 0.1rem 0.4rem" @click="emit('close')">✕</button>
|
||||
</div>
|
||||
|
||||
<div v-if="loading" class="skeleton line" />
|
||||
<div v-else-if="page && !page.items.length" class="empty">
|
||||
<Trash2 :size="28" />
|
||||
<span>Nothing is in retention.</span>
|
||||
</div>
|
||||
<template v-if="page && page.items.length">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width: 1%">
|
||||
<input
|
||||
type="checkbox"
|
||||
title="Select/deselect all on this page"
|
||||
:checked="allChecked()"
|
||||
@change="toggleAll"
|
||||
/>
|
||||
</th>
|
||||
<th>Deleted</th>
|
||||
<th>Received</th>
|
||||
<th>IMEI</th>
|
||||
<th>Device</th>
|
||||
<th>Purged</th>
|
||||
<th>Deleted by</th>
|
||||
<th>Payload</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="m in page.items" :key="m.id">
|
||||
<td>
|
||||
<input
|
||||
type="checkbox"
|
||||
title="Select this message"
|
||||
:checked="selected.has(m.id)"
|
||||
@change="toggleRow(m, ($event.target as HTMLInputElement).checked)"
|
||||
/>
|
||||
</td>
|
||||
<td class="mono">{{ formatTime(m.deleted_at) }}</td>
|
||||
<td class="mono">{{ formatTime(m.received_at) }}</td>
|
||||
<td class="mono">
|
||||
<router-link :to="`/devices/${m.imei}`">{{ m.imei }}</router-link>
|
||||
</td>
|
||||
<td>{{ m.device }}</td>
|
||||
<td class="mono">{{ formatTime(m.expires_at) }}</td>
|
||||
<td>{{ m.deleted_by ?? '—' }}</td>
|
||||
<td>
|
||||
<details>
|
||||
<summary class="muted">payload</summary>
|
||||
<pre class="json">{{ JSON.stringify(m.payload, null, 2) }}</pre>
|
||||
</details>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="row" style="justify-content: space-between; margin-top: 0.5rem">
|
||||
<span v-if="canEdit() && selected.size" class="muted">
|
||||
{{ selected.size }} selected
|
||||
</span>
|
||||
<span v-else></span>
|
||||
<button
|
||||
v-if="canEdit()"
|
||||
class="primary"
|
||||
:disabled="restoring || !selected.size"
|
||||
@click="restoreSelected"
|
||||
>
|
||||
<ArchiveRestore :size="15" />
|
||||
{{ restoring ? 'Restoring…' : 'Restore selected' }}
|
||||
</button>
|
||||
</div>
|
||||
<Pager
|
||||
:offset="offset"
|
||||
:limit="pageSize"
|
||||
:total="page?.total ?? 0"
|
||||
:loading="loading"
|
||||
@update:offset="(v) => { offset = v; load() }"
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { Download, Inbox, Upload } from 'lucide-vue-next'
|
||||
import { ArchiveRestore, Download, Inbox, Trash2, Upload } from 'lucide-vue-next'
|
||||
import { api } from '../api'
|
||||
import type { Device, MessageItem, MessagePage } from '../api'
|
||||
import { formatTime } from '../format'
|
||||
@@ -8,6 +8,7 @@ import { canEdit, showError, toast } from '../store'
|
||||
import { loadPageSize } from '../prefs'
|
||||
import TableHeader from '../components/TableHeader.vue'
|
||||
import Pager from '../components/Pager.vue'
|
||||
import RetentionDialog from '../components/RetentionDialog.vue'
|
||||
|
||||
const page = ref<MessagePage | null>(null)
|
||||
const loading = ref(false)
|
||||
@@ -119,6 +120,58 @@ function toggleRow(m: MessageItem, checked: boolean): void {
|
||||
selected.value = next
|
||||
}
|
||||
|
||||
// --- retention (soft delete) ---------------------------------------------
|
||||
// "Delete" moves the selected messages to retention (same id, restorable
|
||||
// for RETENTION_DAYS); the banner shows the current retained count and
|
||||
// opens the RetentionDialog.
|
||||
const retentionCount = ref(0)
|
||||
const retentionOpen = ref(false)
|
||||
const deleting = ref(false)
|
||||
|
||||
async function loadRetentionCount(): Promise<void> {
|
||||
try {
|
||||
const body = await api<{ count: number }>('/api/messages/retention/count')
|
||||
retentionCount.value = body.count
|
||||
} catch {
|
||||
// the banner simply stays hidden when the count is unknown
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteSelected(): Promise<void> {
|
||||
if (!selected.value.size || deleting.value) return
|
||||
if (!confirm(`Move ${selected.value.size} message${selected.value.size === 1 ? '' : 's'} to retention? They are restorable there for 30 days.`)) {
|
||||
return
|
||||
}
|
||||
deleting.value = true
|
||||
try {
|
||||
const result = await api<{ status: string; deleted: number }>(
|
||||
'/api/messages/delete',
|
||||
{ method: 'POST', body: JSON.stringify({ ids: [...selected.value] }) },
|
||||
)
|
||||
toast('success', `moved ${result.deleted} message${result.deleted === 1 ? '' : 's'} to retention`)
|
||||
selected.value = new Set()
|
||||
// if the current page became empty and we are not on the first page,
|
||||
// step back one page (the total shrank)
|
||||
const items = page.value?.items ?? []
|
||||
if (offset.value > 0 && items.length && result.deleted >= items.length) {
|
||||
offset.value = Math.max(0, offset.value - limit.value)
|
||||
}
|
||||
load()
|
||||
loadRetentionCount()
|
||||
} catch (e) {
|
||||
showError(e)
|
||||
} finally {
|
||||
deleting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function onRestored(count: number): void {
|
||||
// messages came back: refresh both lists
|
||||
load()
|
||||
loadRetentionCount()
|
||||
if (count) toast('success', `${count} message${count === 1 ? '' : 's'} back in the list`)
|
||||
}
|
||||
|
||||
// Export the selected messages RAW (as stored: no settings merge, no
|
||||
// attributes) as a JSON file download. The ids are sent as repeatable
|
||||
// query params; the response is a JSON array in the caller's order.
|
||||
@@ -251,6 +304,7 @@ function onLimit(newLimit: number): void {
|
||||
|
||||
onMounted(async () => {
|
||||
load()
|
||||
loadRetentionCount()
|
||||
try {
|
||||
devices.value = await api<Device[]>('/api/devices')
|
||||
} catch {
|
||||
@@ -277,6 +331,19 @@ onMounted(async () => {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="retentionCount > 0" class="card row" style="justify-content: space-between">
|
||||
<span class="muted">
|
||||
<ArchiveRestore :size="15" />
|
||||
{{ retentionCount }} message{{ retentionCount === 1 ? '' : 's' }} in retention
|
||||
(auto-purged after 30 days)
|
||||
</span>
|
||||
<button class="ghost" style="padding: 0.15rem 0.5rem" @click="retentionOpen = true">
|
||||
View / restore…
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<RetentionDialog :open="retentionOpen" :page-size="limit" @close="retentionOpen = false" @restored="onRestored" />
|
||||
|
||||
<div v-if="importOpen" class="card row" style="align-items: flex-start">
|
||||
<div style="flex: 1; min-width: 0">
|
||||
<div class="row" style="justify-content: space-between; margin-bottom: 0.5rem">
|
||||
@@ -339,6 +406,15 @@ onMounted(async () => {
|
||||
<Download :size="15" />
|
||||
{{ exporting ? 'Exporting…' : 'Export JSON' }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canEdit()"
|
||||
class="danger"
|
||||
:disabled="deleting"
|
||||
@click="deleteSelected"
|
||||
>
|
||||
<Trash2 :size="15" />
|
||||
{{ deleting ? 'Moving…' : 'Delete' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -107,6 +107,41 @@ COMMENT ON TABLE imei_attributes IS
|
||||
COMMENT ON COLUMN imei_attributes.effective_from IS
|
||||
'Time from which the value applies; backdating allowed. Resolved against the device timestamp (payload_time, received_at fallback) in GET /messages.';
|
||||
|
||||
-- Soft-delete retention for mqtt_messages: a "delete" MOVES the row here
|
||||
-- (unchanged, including its ORIGINAL id) instead of dropping it. Retained
|
||||
-- rows are auto-purged when expires_at passes (the API purges expired rows
|
||||
-- lazily on every retention read). Restoring moves the row back with the
|
||||
-- SAME id - safe by construction: the move is a single atomic statement,
|
||||
-- so an id never exists in both tables, and the BIGSERIAL never regenerates
|
||||
-- an id that was handed out. NOT BIGSERIAL here: ids always come from the
|
||||
-- original mqtt_messages row. A separate mirror table (not a flag column)
|
||||
-- keeps every existing read path (GET /messages, counts, facets, export,
|
||||
-- rename, attribute resolution) untouched.
|
||||
CREATE TABLE IF NOT EXISTS mqtt_messages_retention (
|
||||
id BIGINT PRIMARY KEY,
|
||||
received_at TIMESTAMPTZ NOT NULL,
|
||||
topic TEXT NOT NULL,
|
||||
imei TEXT NOT NULL,
|
||||
device TEXT NOT NULL,
|
||||
payload JSONB NOT NULL,
|
||||
payload_time TIMESTAMPTZ,
|
||||
deleted_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
deleted_by TEXT,
|
||||
expires_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
|
||||
-- the lazy purge is a single indexed comparison
|
||||
CREATE INDEX IF NOT EXISTS idx_retention_expires
|
||||
ON mqtt_messages_retention (expires_at);
|
||||
-- newest deletions first (the dialog lists recent deletions)
|
||||
CREATE INDEX IF NOT EXISTS idx_retention_deleted_at
|
||||
ON mqtt_messages_retention (deleted_at DESC);
|
||||
|
||||
COMMENT ON TABLE mqtt_messages_retention IS
|
||||
'Messages soft-deleted from mqtt_messages: moved here (same id) on delete, restorable until expires_at, auto-purged by the API afterwards.';
|
||||
COMMENT ON COLUMN mqtt_messages_retention.deleted_by IS
|
||||
'Username of the deleting session user; NULL when deleted via an app token.';
|
||||
|
||||
-- Interactive users for the management UI: username/password login with a
|
||||
-- role. 'admin' (level 2) manages everything incl. users; 'superuser'
|
||||
-- (level 1) configures devices/configs/tokens and manages day-to-day
|
||||
|
||||
@@ -22,10 +22,12 @@ from api.app import ( # noqa: E402
|
||||
DeviceRenameStore,
|
||||
ImeiAttributesStore,
|
||||
ImeiMapStore,
|
||||
MessageRetentionPolicy,
|
||||
SessionStore,
|
||||
TokenStore,
|
||||
UserStore,
|
||||
_validate_attribute_body,
|
||||
_validate_id_list,
|
||||
_validate_rename_body,
|
||||
_validate_token_body,
|
||||
hash_password,
|
||||
@@ -1053,6 +1055,217 @@ class TestMessageImport:
|
||||
)
|
||||
assert r.status_code == 503 # validation passed; fails on the DB
|
||||
|
||||
|
||||
class TestValidateIdList:
|
||||
"""_validate_id_list: {"ids": [...]} body for delete/restore."""
|
||||
|
||||
def _validate(self, data: object) -> list[int]:
|
||||
from api.app import _validate_id_list
|
||||
|
||||
return _validate_id_list(data, "request body")
|
||||
|
||||
def test_valid_list(self) -> None:
|
||||
assert self._validate({"ids": [1, 5, 9]}) == [1, 5, 9]
|
||||
|
||||
def test_rejects_non_object(self) -> None:
|
||||
with pytest.raises(ValueError, match="ids"):
|
||||
self._validate([1, 2, 3])
|
||||
|
||||
def test_rejects_missing_ids(self) -> None:
|
||||
with pytest.raises(ValueError, match="ids"):
|
||||
self._validate({})
|
||||
|
||||
def test_rejects_empty_list(self) -> None:
|
||||
with pytest.raises(ValueError, match="empty"):
|
||||
self._validate({"ids": []})
|
||||
|
||||
def test_rejects_non_int_entries(self) -> None:
|
||||
with pytest.raises(ValueError, match="ids\[2\] must be an integer"):
|
||||
self._validate({"ids": [1, 2, "three"]})
|
||||
|
||||
def test_rejects_booleans(self) -> None:
|
||||
# bool is an int subclass - must still be rejected explicitly
|
||||
with pytest.raises(ValueError, match="must be an integer"):
|
||||
self._validate({"ids": [True]})
|
||||
|
||||
def test_rejects_oversized_list(self) -> None:
|
||||
with pytest.raises(ValueError, match="too many"):
|
||||
self._validate({"ids": list(range(10001))})
|
||||
|
||||
|
||||
class FakeRetentionPolicy(MessageRetentionPolicy):
|
||||
"""In-memory retention policy: records calls; the real CTE moves are
|
||||
exercised in the e2e against a throwaway postgres."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__("postgresql://unused")
|
||||
self.deleted: list[tuple[list[int], str | None]] = []
|
||||
self.restored: list[list[int]] = []
|
||||
|
||||
def delete(self, ids: list[int], deleted_by: str | None) -> int:
|
||||
self.deleted.append((list(ids), deleted_by))
|
||||
return len(ids)
|
||||
|
||||
def restore(self, ids: list[int]) -> int:
|
||||
self.restored.append(list(ids))
|
||||
return len(ids)
|
||||
|
||||
def count(self) -> int:
|
||||
return 3
|
||||
|
||||
def list(self, limit: int, offset: int) -> tuple[list[dict[str, Any]], int]:
|
||||
return (
|
||||
[
|
||||
{
|
||||
"id": 7,
|
||||
"received_at": "2026-09-06T12:00:00+00:00",
|
||||
"topic": "/vivab/350123456789012",
|
||||
"imei": "350123456789012",
|
||||
"device": "Dev",
|
||||
"payload": {"temp": 1},
|
||||
"payload_time": None,
|
||||
"deleted_at": "2026-09-06T13:00:00+00:00",
|
||||
"deleted_by": "admin1",
|
||||
"expires_at": "2026-10-06T13:00:00+00:00",
|
||||
}
|
||||
],
|
||||
3,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def retention_api(app_module):
|
||||
"""App wired with the fake retention policy AND the fake user stores
|
||||
(session users resolve their role from the store); yields (app, policy)."""
|
||||
policy = FakeRetentionPolicy()
|
||||
users = FakeUserStore(
|
||||
{
|
||||
"admin1": ("admin-pass", "admin"),
|
||||
"viewer1": ("viewer-pass", "user"),
|
||||
}
|
||||
)
|
||||
app = app_module.create_app(
|
||||
token_store=FakeTokenStore({"test-app": "secret-abc"}),
|
||||
imei_store=FakeImeiMapStore({}),
|
||||
retention_policy=policy,
|
||||
user_store=users,
|
||||
session_store=FakeSessionStore(users),
|
||||
)
|
||||
return app, policy
|
||||
|
||||
|
||||
class TestRetentionEndpoints:
|
||||
"""POST /messages/delete, GET /messages/retention(+count), POST
|
||||
/messages/retention/restore — auth, role gating, body validation,
|
||||
deleted_by plumbing. The CTE move semantics live in the e2e."""
|
||||
|
||||
APP = {"X-App-Token": "secret-abc"}
|
||||
|
||||
@pytest.fixture()
|
||||
def client_and_policy(self, retention_api):
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
app, policy = retention_api
|
||||
return TestClient(app), policy
|
||||
|
||||
def test_delete_requires_token(self, client_and_policy) -> None:
|
||||
client, _ = client_and_policy
|
||||
assert (
|
||||
client.post("/messages/delete", json={"ids": [1]}).status_code == 401
|
||||
)
|
||||
|
||||
def test_delete_viewer_role_forbidden(self, client_and_policy) -> None:
|
||||
client, policy = client_and_policy
|
||||
r = client.post(
|
||||
"/auth/login", json={"username": "viewer1", "password": "viewer-pass"}
|
||||
)
|
||||
token = r.json()["token"]
|
||||
r = client.post(
|
||||
"/messages/delete",
|
||||
json={"ids": [1]},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
)
|
||||
assert r.status_code == 403
|
||||
assert policy.deleted == [] # nothing reached the store
|
||||
|
||||
def test_delete_session_user_recorded(self, client_and_policy) -> None:
|
||||
client, policy = client_and_policy
|
||||
r = client.post(
|
||||
"/auth/login", json={"username": "admin1", "password": "admin-pass"}
|
||||
)
|
||||
token = r.json()["token"]
|
||||
r = client.post(
|
||||
"/messages/delete",
|
||||
json={"ids": [11, 12]},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
assert r.json() == {"status": "deleted", "deleted": 2}
|
||||
# the session username is recorded as deleted_by
|
||||
assert policy.deleted == [([11, 12], "admin1")]
|
||||
|
||||
def test_delete_empty_ids_rejected(self, client_and_policy) -> None:
|
||||
client, _ = client_and_policy
|
||||
r = client.post("/messages/delete", json={"ids": []}, headers=self.APP)
|
||||
assert r.status_code == 422
|
||||
assert "empty" in r.json()["detail"]
|
||||
|
||||
def test_delete_bad_body_rejected(self, client_and_policy) -> None:
|
||||
client, _ = client_and_policy
|
||||
r = client.post("/messages/delete", json={"ids": "nope"}, headers=self.APP)
|
||||
assert r.status_code == 422
|
||||
|
||||
def test_delete_app_token_records_null_user(self, client_and_policy) -> None:
|
||||
client, policy = client_and_policy
|
||||
r = client.post("/messages/delete", json={"ids": [4, 8]}, headers=self.APP)
|
||||
assert r.status_code == 200
|
||||
assert r.json() == {"status": "deleted", "deleted": 2}
|
||||
assert policy.deleted == [([4, 8], None)]
|
||||
|
||||
def test_retention_count(self, client_and_policy) -> None:
|
||||
client, _ = client_and_policy
|
||||
r = client.get("/messages/retention/count", headers=self.APP)
|
||||
assert r.status_code == 200
|
||||
assert r.json() == {"count": 3}
|
||||
|
||||
def test_retention_list_shape(self, client_and_policy) -> None:
|
||||
client, _ = client_and_policy
|
||||
r = client.get("/messages/retention", headers=self.APP)
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["total"] == 3
|
||||
assert body["limit"] == 100
|
||||
assert body["offset"] == 0
|
||||
row = body["items"][0]
|
||||
assert row["id"] == 7
|
||||
assert row["deleted_by"] == "admin1"
|
||||
assert "expires_at" in row
|
||||
|
||||
def test_restore_requires_token(self, client_and_policy) -> None:
|
||||
client, _ = client_and_policy
|
||||
assert (
|
||||
client.post(
|
||||
"/messages/retention/restore", json={"ids": [1]}
|
||||
).status_code
|
||||
== 401
|
||||
)
|
||||
|
||||
def test_restore_app_token_works(self, client_and_policy) -> None:
|
||||
client, policy = client_and_policy
|
||||
r = client.post(
|
||||
"/messages/retention/restore", json={"ids": [7]}, headers=self.APP
|
||||
)
|
||||
assert r.status_code == 200
|
||||
assert r.json() == {"status": "restored", "restored": 1}
|
||||
assert policy.restored == [[7]]
|
||||
|
||||
def test_restore_bad_body_rejected(self, client_and_policy) -> None:
|
||||
client, _ = client_and_policy
|
||||
r = client.post(
|
||||
"/messages/retention/restore", json={"ids": {}}, headers=self.APP
|
||||
)
|
||||
assert r.status_code == 422
|
||||
|
||||
def test_valid_request_reaches_db(self, api) -> None:
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
@@ -1799,6 +2012,8 @@ class TestAuthorizationMatrix:
|
||||
"POST",
|
||||
{"imei": "350123456789012", "device": "X", "payload": {}},
|
||||
),
|
||||
("/messages/delete", "POST", {"ids": [1]}),
|
||||
("/messages/retention/restore", "POST", {"ids": [1]}),
|
||||
]
|
||||
|
||||
def test_viewer_role_cannot_write(self, client_and_stores) -> None:
|
||||
|
||||
Reference in New Issue
Block a user