Build out the admin panel
- Overview: users, organizations, workspaces, spaces, pages, files and storage (org admins see their organization), plus pages open right now, the search index size, and version, uptime and database health. - Users: invite people by email (with resend, revoke and a copyable link when mail fails) and send a password-reset email. - Authentication: sign-up on or off, the email-domain allow-list, and sign-in links by email. - Branding: instance name, accent colour and logo. The web app shows them on the sign-in pages and applies the accent colour everywhere. - Email and Storage: SMTP and S3 settings with test buttons. - Maintenance: create, download and delete database backups, and a view of the background jobs with their last run, duration and errors. On the server, a small jobs registry records each search-indexing pass, and "search.rebuild" replaces the separate reindex endpoint. A new instance package serves the dashboard numbers, health and backups. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
92cd81fd96
commit
ffc6cc4fbc
31 files changed
+2326
-134
No files matched your search
@@ -17,6 +17,7 @@ const nav = computed(() => [
|
||||
...(isSuperadmin.value
|
||||
? [
|
||||
{ to: "/authentication", label: "Authentication" },
|
||||
{ to: "/branding", label: "Branding" },
|
||||
{ to: "/storage", label: "Storage" },
|
||||
{ to: "/email", label: "Email" },
|
||||
{ to: "/maintenance", label: "Maintenance" },
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import type { Invite, Organization, Role } from "@docwell/api-client";
|
||||
import { DwBadge, DwButton, DwCallout } from "@docwell/ui";
|
||||
import { computed, onMounted, reactive, ref } from "vue";
|
||||
import { api, errorMessage, isSuperadmin } from "../session";
|
||||
|
||||
// Invite people by email into an organization. The person picks their own
|
||||
// name and password when they accept.
|
||||
const props = defineProps<{ orgs: Organization[] }>();
|
||||
const emit = defineEmits<{ accepted: [] }>();
|
||||
|
||||
const invites = ref<Invite[]>([]);
|
||||
const form = reactive({ email: "", role: "user" as Role, organization: "" });
|
||||
const error = ref("");
|
||||
const result = ref<Invite | null>(null);
|
||||
const busy = ref(false);
|
||||
const copied = ref(false);
|
||||
|
||||
const roles = computed<Role[]>(() => (isSuperadmin.value ? ["user", "admin", "superadmin"] : ["user", "admin"]));
|
||||
const roleLabel: Record<string, string> = { user: "User", admin: "Admin", superadmin: "Superadmin" };
|
||||
|
||||
async function load() {
|
||||
invites.value = (await api.invites.list()).filter((i) => !i.workspace);
|
||||
}
|
||||
onMounted(() => load().catch((e) => (error.value = errorMessage(e))));
|
||||
|
||||
async function run(action: () => Promise<void>) {
|
||||
busy.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
await action();
|
||||
await load();
|
||||
emit("accepted");
|
||||
} catch (e) {
|
||||
error.value = errorMessage(e);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const invite = () =>
|
||||
run(async () => {
|
||||
result.value = await api.invites.create({
|
||||
email: form.email,
|
||||
role: form.role,
|
||||
organization: isSuperadmin.value ? form.organization : undefined,
|
||||
});
|
||||
form.email = "";
|
||||
});
|
||||
const resend = (i: Invite) =>
|
||||
run(async () => {
|
||||
result.value = await api.invites.resend(i.id);
|
||||
});
|
||||
const revoke = (i: Invite) => run(() => api.invites.revoke(i.id));
|
||||
|
||||
async function copy(link: string) {
|
||||
await navigator.clipboard.writeText(link);
|
||||
copied.value = true;
|
||||
setTimeout(() => (copied.value = false), 2000);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="mt-6 dw-card" data-testid="invites">
|
||||
<h2 class="text-ui-lg">Invite people</h2>
|
||||
<form class="mt-3 flex flex-wrap gap-2" @submit.prevent="invite">
|
||||
<input
|
||||
v-model="form.email"
|
||||
type="email"
|
||||
required
|
||||
placeholder="name@example.com"
|
||||
aria-label="Email to invite"
|
||||
class="dw-input min-w-56 flex-1"
|
||||
/>
|
||||
<select v-model="form.role" aria-label="Role" class="dw-input">
|
||||
<option v-for="r in roles" :key="r" :value="r">{{ roleLabel[r] }}</option>
|
||||
</select>
|
||||
<select v-if="isSuperadmin" v-model="form.organization" aria-label="Organization" class="dw-input">
|
||||
<option value="">No organization</option>
|
||||
<option v-for="o in props.orgs" :key="o.id" :value="o.id">{{ o.name }}</option>
|
||||
</select>
|
||||
<DwButton type="submit" variant="primary" :disabled="busy || !form.email">Send invite</DwButton>
|
||||
</form>
|
||||
<DwCallout v-if="error" tone="danger" size="ui" class="mt-3">{{ error }}</DwCallout>
|
||||
<DwCallout v-else-if="result" :tone="result.mailed ? 'success' : 'warning'" size="ui" class="mt-3">
|
||||
<span class="flex flex-wrap items-center gap-2">
|
||||
{{
|
||||
result.mailed
|
||||
? `An invitation is on its way to ${result.email}.`
|
||||
: `${result.email} is invited, but the email could not be sent. Send them the link yourself.`
|
||||
}}
|
||||
<button v-if="result.link && !result.mailed" class="dw-link" @click="copy(result.link)">
|
||||
{{ copied ? "Copied" : "Copy link" }}
|
||||
</button>
|
||||
</span>
|
||||
</DwCallout>
|
||||
|
||||
<ul v-if="invites.length" class="mt-4 divide-y divide-line">
|
||||
<li v-for="i in invites" :key="i.id" class="flex flex-wrap items-center justify-between gap-2 py-2">
|
||||
<div class="min-w-0">
|
||||
<p class="truncate font-medium">{{ i.email }}</p>
|
||||
<p class="truncate text-ui-sm text-ink-muted">
|
||||
{{ roleLabel[i.role] }}<template v-if="i.organizationName"> · {{ i.organizationName }}</template> · invited
|
||||
by {{ i.invitedBy || "someone" }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<DwBadge v-if="i.status === 'expired'" tone="danger">Expired</DwBadge>
|
||||
<DwButton variant="ghost" size="sm" :disabled="busy" @click="resend(i)">Resend</DwButton>
|
||||
<DwButton variant="ghost" size="sm" class="!text-danger" :disabled="busy" @click="revoke(i)">Revoke</DwButton>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</template>
|
||||
+13
-12
@@ -16,26 +16,27 @@ const router = createRouter({
|
||||
{
|
||||
path: "/authentication",
|
||||
name: "authentication",
|
||||
component: () => import("./views/PlaceholderView.vue"),
|
||||
meta: { title: "Authentication", superadmin: true },
|
||||
component: () => import("./views/AuthenticationView.vue"),
|
||||
meta: { superadmin: true },
|
||||
},
|
||||
{
|
||||
path: "/branding",
|
||||
name: "branding",
|
||||
component: () => import("./views/BrandingView.vue"),
|
||||
meta: { superadmin: true },
|
||||
},
|
||||
{
|
||||
path: "/storage",
|
||||
name: "storage",
|
||||
component: () => import("./views/PlaceholderView.vue"),
|
||||
meta: { title: "Storage", superadmin: true },
|
||||
},
|
||||
{
|
||||
path: "/email",
|
||||
name: "email",
|
||||
component: () => import("./views/PlaceholderView.vue"),
|
||||
meta: { title: "Email", superadmin: true },
|
||||
component: () => import("./views/StorageView.vue"),
|
||||
meta: { superadmin: true },
|
||||
},
|
||||
{ path: "/email", name: "email", component: () => import("./views/EmailView.vue"), meta: { superadmin: true } },
|
||||
{
|
||||
path: "/maintenance",
|
||||
name: "maintenance",
|
||||
component: () => import("./views/PlaceholderView.vue"),
|
||||
meta: { title: "Maintenance", superadmin: true },
|
||||
component: () => import("./views/MaintenanceView.vue"),
|
||||
meta: { superadmin: true },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import type { InstanceSettings, InstanceSettingsUpdate } from "@docwell/api-client";
|
||||
import { onMounted, ref } from "vue";
|
||||
import { api, errorMessage } from "./session";
|
||||
|
||||
/** Loads the instance settings and saves one section at a time. */
|
||||
export function useInstanceSettings() {
|
||||
const settings = ref<InstanceSettings | null>(null);
|
||||
const error = ref("");
|
||||
const saved = ref(false);
|
||||
const busy = ref(false);
|
||||
|
||||
async function load() {
|
||||
error.value = "";
|
||||
try {
|
||||
settings.value = await api.settings.get();
|
||||
} catch (e) {
|
||||
error.value = errorMessage(e);
|
||||
}
|
||||
}
|
||||
onMounted(load);
|
||||
|
||||
async function save(patch: InstanceSettingsUpdate) {
|
||||
busy.value = true;
|
||||
error.value = "";
|
||||
saved.value = false;
|
||||
try {
|
||||
settings.value = await api.settings.update(patch);
|
||||
saved.value = true;
|
||||
setTimeout(() => (saved.value = false), 2500);
|
||||
} catch (e) {
|
||||
error.value = errorMessage(e);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
return { settings, error, saved, busy, load, save };
|
||||
}
|
||||
|
||||
/** Bytes as KB/MB/GB for people. */
|
||||
export function formatBytes(n: number): string {
|
||||
if (n < 1024) return `${n} B`;
|
||||
const units = ["KB", "MB", "GB", "TB"];
|
||||
let v = n / 1024;
|
||||
let i = 0;
|
||||
while (v >= 1024 && i < units.length - 1) {
|
||||
v /= 1024;
|
||||
i++;
|
||||
}
|
||||
return `${v.toFixed(v < 10 ? 1 : 0)} ${units[i]}`;
|
||||
}
|
||||
|
||||
/** Hands a downloaded file to the browser. */
|
||||
export function saveBlob(blob: Blob, filename: string) {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
document.body.append(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import { DwButton, DwCallout } from "@docwell/ui";
|
||||
import { ref, watch } from "vue";
|
||||
import { useInstanceSettings } from "../settings";
|
||||
|
||||
// Who may create an account, and how people sign in.
|
||||
const { settings, error, saved, busy, save } = useInstanceSettings();
|
||||
const signupEnabled = ref(true);
|
||||
const domains = ref("");
|
||||
const magicLink = ref(false);
|
||||
|
||||
watch(settings, (s) => {
|
||||
if (!s) return;
|
||||
signupEnabled.value = s.signup.enabled;
|
||||
domains.value = s.signup.domains.join("\n");
|
||||
magicLink.value = s.auth.magicLink;
|
||||
});
|
||||
|
||||
function submit() {
|
||||
save({
|
||||
signup: { enabled: signupEnabled.value, domains: domains.value.split(/[\s,;]+/).filter(Boolean) },
|
||||
auth: { magicLink: magicLink.value },
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<h1 class="text-2xl font-semibold tracking-tight">Authentication</h1>
|
||||
<p class="mt-1 text-ink-muted">Who can create an account, and how people sign in.</p>
|
||||
<DwCallout v-if="error" tone="danger" size="ui" class="mt-4">{{ error }}</DwCallout>
|
||||
<DwCallout v-if="saved" tone="success" size="ui" class="mt-4">Saved.</DwCallout>
|
||||
|
||||
<form v-if="settings" class="mt-6 max-w-xl space-y-6" @submit.prevent="submit">
|
||||
<section class="dw-card space-y-4">
|
||||
<h2 class="text-ui-lg">Sign-up</h2>
|
||||
<label class="flex items-start gap-3">
|
||||
<input v-model="signupEnabled" type="checkbox" class="mt-1 accent-primary" data-testid="signup-enabled" />
|
||||
<span>
|
||||
<span class="font-medium">Anyone can create an account</span>
|
||||
<span class="block text-ui-sm text-ink-muted">
|
||||
Off: only invited people can join. The very first account can always sign up.
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">Allowed email domains</span>
|
||||
<textarea
|
||||
v-model="domains"
|
||||
rows="3"
|
||||
class="dw-input font-mono"
|
||||
placeholder="example.com"
|
||||
data-testid="signup-domains"
|
||||
/>
|
||||
<span class="text-ui-sm text-ink-muted"
|
||||
>One per line. Empty allows every domain. Invites ignore this list.</span
|
||||
>
|
||||
</label>
|
||||
</section>
|
||||
|
||||
<section class="dw-card space-y-4">
|
||||
<h2 class="text-ui-lg">Sign-in methods</h2>
|
||||
<p class="text-ui-md">Email and password is always on.</p>
|
||||
<label class="flex items-start gap-3">
|
||||
<input v-model="magicLink" type="checkbox" class="mt-1 accent-primary" data-testid="magic-link" />
|
||||
<span>
|
||||
<span class="font-medium">Sign-in links by email</span>
|
||||
<span class="block text-ui-sm text-ink-muted">
|
||||
People can ask for a link and a one-time code instead of typing their password. Needs working email.
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
</section>
|
||||
|
||||
<DwButton type="submit" variant="primary" :disabled="busy">Save</DwButton>
|
||||
</form>
|
||||
</template>
|
||||
@@ -0,0 +1,98 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import { DwButton, DwCallout } from "@docwell/ui";
|
||||
import { ref, watch } from "vue";
|
||||
import { useInstanceSettings } from "../settings";
|
||||
|
||||
// The server's name, accent colour and logo, shown on the sign-in pages and in emails.
|
||||
const { settings, error, saved, busy, save } = useInstanceSettings();
|
||||
const appName = ref("");
|
||||
const accent = ref("");
|
||||
const logo = ref("");
|
||||
const fileError = ref("");
|
||||
|
||||
watch(settings, (s) => {
|
||||
if (!s) return;
|
||||
appName.value = s.branding.appName;
|
||||
accent.value = s.branding.accentColor;
|
||||
logo.value = s.branding.logo;
|
||||
});
|
||||
|
||||
const maxLogo = 190 * 1024;
|
||||
|
||||
function pickLogo(e: Event) {
|
||||
const input = e.target as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
input.value = "";
|
||||
fileError.value = "";
|
||||
if (!file) return;
|
||||
if (!/^image\/(png|jpeg|webp|svg\+xml)$/.test(file.type)) {
|
||||
fileError.value = "Use a PNG, JPEG, WebP or SVG image.";
|
||||
return;
|
||||
}
|
||||
if (file.size > maxLogo) {
|
||||
fileError.value = "The logo must be smaller than 190 KB.";
|
||||
return;
|
||||
}
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => (logo.value = String(reader.result));
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
|
||||
function submit() {
|
||||
save({ branding: { appName: appName.value, accentColor: accent.value, logo: logo.value } });
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<h1 class="text-2xl font-semibold tracking-tight">Branding</h1>
|
||||
<p class="mt-1 text-ink-muted">How this server presents itself on the sign-in pages and in emails.</p>
|
||||
<DwCallout v-if="error" tone="danger" size="ui" class="mt-4">{{ error }}</DwCallout>
|
||||
<DwCallout v-if="saved" tone="success" size="ui" class="mt-4">Saved.</DwCallout>
|
||||
|
||||
<form v-if="settings" class="mt-6 max-w-xl space-y-4 dw-card" @submit.prevent="submit">
|
||||
<label class="flex flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">Name</span>
|
||||
<input v-model="appName" required maxlength="60" class="dw-input" data-testid="app-name" />
|
||||
</label>
|
||||
<div class="flex flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">Accent colour</span>
|
||||
<div class="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
:value="accent || '#2f7d6d'"
|
||||
aria-label="Pick the accent colour"
|
||||
class="h-control-md w-12 cursor-pointer rounded-sm border border-line bg-surface"
|
||||
@input="accent = ($event.target as HTMLInputElement).value"
|
||||
/>
|
||||
<input
|
||||
v-model="accent"
|
||||
placeholder="#2f7d6d"
|
||||
maxlength="7"
|
||||
class="dw-input w-32 font-mono"
|
||||
aria-label="Accent colour"
|
||||
/>
|
||||
<DwButton v-if="accent" variant="ghost" size="sm" @click="accent = ''">Use default</DwButton>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">Logo</span>
|
||||
<div class="flex flex-wrap items-center gap-3">
|
||||
<img
|
||||
v-if="logo"
|
||||
:src="logo"
|
||||
alt="Current logo"
|
||||
class="h-10 max-w-48 rounded-sm border border-line bg-surface p-1"
|
||||
/>
|
||||
<span v-else class="text-ui-sm text-ink-muted">The Docwell logo.</span>
|
||||
<label class="cursor-pointer text-ui-md font-semibold text-accent hover:underline">
|
||||
Upload…
|
||||
<input type="file" accept="image/png,image/jpeg,image/webp,image/svg+xml" class="hidden" @change="pickLogo" />
|
||||
</label>
|
||||
<DwButton v-if="logo" variant="ghost" size="sm" @click="logo = ''">Remove</DwButton>
|
||||
</div>
|
||||
<span v-if="fileError" class="text-ui-sm text-danger">{{ fileError }}</span>
|
||||
</div>
|
||||
<DwButton type="submit" variant="primary" :disabled="busy">Save</DwButton>
|
||||
</form>
|
||||
</template>
|
||||
@@ -0,0 +1,112 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import { DwButton, DwCallout } from "@docwell/ui";
|
||||
import { reactive, ref, watch } from "vue";
|
||||
import { useInstanceSettings } from "../settings";
|
||||
import { api, currentUser, errorMessage } from "../session";
|
||||
|
||||
// Outgoing mail: verification, password reset, invites and sign-in links.
|
||||
const { settings, error, saved, busy, save } = useInstanceSettings();
|
||||
const form = reactive({
|
||||
enabled: false,
|
||||
host: "",
|
||||
port: 587,
|
||||
username: "",
|
||||
password: "",
|
||||
tls: false,
|
||||
senderName: "",
|
||||
senderAddress: "",
|
||||
});
|
||||
const testTo = ref("");
|
||||
const testState = ref<{ ok: boolean; text: string } | null>(null);
|
||||
|
||||
watch(settings, (s) => {
|
||||
if (!s) return;
|
||||
Object.assign(form, { ...s.smtp, password: "" });
|
||||
testTo.value ||= currentUser.value?.email ?? "";
|
||||
});
|
||||
|
||||
function submit() {
|
||||
// An empty password keeps the stored one.
|
||||
const { password, ...rest } = form;
|
||||
save({ smtp: { ...rest, passwordSet: false, ...(password ? { password } : {}) } });
|
||||
}
|
||||
|
||||
async function sendTest() {
|
||||
testState.value = null;
|
||||
try {
|
||||
await api.settings.testEmail(testTo.value);
|
||||
testState.value = { ok: true, text: `Sent to ${testTo.value}. Check the inbox (and the spam folder).` };
|
||||
} catch (e) {
|
||||
testState.value = { ok: false, text: errorMessage(e) };
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<h1 class="text-2xl font-semibold tracking-tight">Email</h1>
|
||||
<p class="mt-1 text-ink-muted">
|
||||
Docwell sends verification, password reset, invite and sign-in emails through this server.
|
||||
</p>
|
||||
<DwCallout v-if="error" tone="danger" size="ui" class="mt-4">{{ error }}</DwCallout>
|
||||
<DwCallout v-if="saved" tone="success" size="ui" class="mt-4">Saved.</DwCallout>
|
||||
<DwCallout size="ui" class="mt-4 max-w-xl">
|
||||
If DOCWELL_SMTP_HOST is set for docwell-db, those environment values are applied again whenever it starts.
|
||||
</DwCallout>
|
||||
|
||||
<form v-if="settings" class="mt-6 grid max-w-xl gap-4 dw-card sm:grid-cols-2" @submit.prevent="submit">
|
||||
<label class="flex items-center gap-3 sm:col-span-2">
|
||||
<input v-model="form.enabled" type="checkbox" class="accent-primary" />
|
||||
<span class="font-medium">Send email through an SMTP server</span>
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">Host</span>
|
||||
<input v-model="form.host" :required="form.enabled" class="dw-input" placeholder="smtp.example.com" />
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">Port</span>
|
||||
<input v-model.number="form.port" type="number" min="1" max="65535" class="dw-input" />
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">Username</span>
|
||||
<input v-model="form.username" autocomplete="off" class="dw-input" />
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">Password</span>
|
||||
<input
|
||||
v-model="form.password"
|
||||
type="password"
|
||||
autocomplete="new-password"
|
||||
class="dw-input"
|
||||
:placeholder="settings.smtp.passwordSet ? 'Unchanged' : ''"
|
||||
/>
|
||||
</label>
|
||||
<label class="flex items-center gap-3 sm:col-span-2">
|
||||
<input v-model="form.tls" type="checkbox" class="accent-primary" />
|
||||
<span>Use TLS from the start (usually port 465; port 587 upgrades on its own)</span>
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">Sender name</span>
|
||||
<input v-model="form.senderName" class="dw-input" />
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">Sender address</span>
|
||||
<input v-model="form.senderAddress" type="email" required class="dw-input" />
|
||||
</label>
|
||||
<div class="sm:col-span-2">
|
||||
<DwButton type="submit" variant="primary" :disabled="busy">Save</DwButton>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<section v-if="settings" class="mt-6 max-w-xl dw-card">
|
||||
<h2 class="text-ui-lg">Test</h2>
|
||||
<p class="mt-1 text-ui-sm text-ink-muted">Sends a short email with the saved settings.</p>
|
||||
<form class="mt-3 flex flex-wrap gap-2" @submit.prevent="sendTest">
|
||||
<input v-model="testTo" type="email" required class="dw-input min-w-48 flex-1" aria-label="Send the test to" />
|
||||
<DwButton type="submit">Send test email</DwButton>
|
||||
</form>
|
||||
<DwCallout v-if="testState" :tone="testState.ok ? 'success' : 'danger'" size="ui" class="mt-3">
|
||||
{{ testState.text }}
|
||||
</DwCallout>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,163 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import type { Backup, Job } from "@docwell/api-client";
|
||||
import { DwBadge, DwButton, DwCallout } from "@docwell/ui";
|
||||
import { onBeforeUnmount, onMounted, ref } from "vue";
|
||||
import { formatBytes, saveBlob } from "../settings";
|
||||
import { api, errorMessage } from "../session";
|
||||
|
||||
// Backups of docwell-db and the server's background jobs.
|
||||
const backups = ref<Backup[]>([]);
|
||||
const jobs = ref<Job[]>([]);
|
||||
const error = ref("");
|
||||
const busy = ref("");
|
||||
|
||||
async function loadBackups() {
|
||||
backups.value = (await api.admin.backups()).sort((a, b) => b.modified.localeCompare(a.modified));
|
||||
}
|
||||
async function loadJobs() {
|
||||
jobs.value = await api.admin.jobs();
|
||||
}
|
||||
|
||||
async function run(what: string, action: () => Promise<unknown>) {
|
||||
busy.value = what;
|
||||
error.value = "";
|
||||
try {
|
||||
await action();
|
||||
} catch (e) {
|
||||
error.value = errorMessage(e);
|
||||
} finally {
|
||||
busy.value = "";
|
||||
}
|
||||
}
|
||||
|
||||
// Jobs change on their own; refresh while the page is open.
|
||||
let timer: ReturnType<typeof setInterval> | undefined;
|
||||
onMounted(() => {
|
||||
run("load", () => Promise.all([loadBackups(), loadJobs()]));
|
||||
timer = setInterval(() => loadJobs().catch(() => {}), 5000);
|
||||
});
|
||||
onBeforeUnmount(() => clearInterval(timer));
|
||||
|
||||
const createBackup = () =>
|
||||
run("create", async () => {
|
||||
await api.admin.createBackup();
|
||||
await loadBackups();
|
||||
});
|
||||
const download = (b: Backup) =>
|
||||
run(b.key, async () => {
|
||||
const { blob, filename } = await api.admin.downloadBackup(b.key);
|
||||
saveBlob(blob, filename);
|
||||
});
|
||||
const remove = (b: Backup) => {
|
||||
if (!confirm(`Delete the backup ${b.key}?`)) return;
|
||||
run(b.key, async () => {
|
||||
await api.admin.deleteBackup(b.key);
|
||||
await loadBackups();
|
||||
});
|
||||
};
|
||||
const runJob = (j: Job) =>
|
||||
run(j.name, async () => {
|
||||
await api.admin.runJob(j.name);
|
||||
await loadJobs();
|
||||
});
|
||||
|
||||
const when = (s: string) => (s ? new Date(s.replace(" ", "T")).toLocaleString() : "—");
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<h1 class="text-2xl font-semibold tracking-tight">Maintenance</h1>
|
||||
<DwCallout v-if="error" tone="danger" size="ui" class="mt-4">{{ error }}</DwCallout>
|
||||
|
||||
<section class="mt-6" data-testid="backups">
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<div>
|
||||
<h2 class="text-ui-lg">Backups</h2>
|
||||
<p class="text-ui-sm text-ink-muted">
|
||||
A backup holds the whole database and its files. To restore one, stop Docwell and replace docwell-db's data
|
||||
with the archive's contents.
|
||||
</p>
|
||||
</div>
|
||||
<DwButton variant="primary" :disabled="!!busy" @click="createBackup">
|
||||
{{ busy === "create" ? "Creating…" : "Create backup" }}
|
||||
</DwButton>
|
||||
</div>
|
||||
<div class="mt-3 overflow-x-auto rounded-md border border-line bg-surface-raised">
|
||||
<table class="w-full text-left text-ui-md">
|
||||
<thead class="bg-surface-sunken text-ui-xs uppercase text-ink-muted">
|
||||
<tr>
|
||||
<th class="px-4 py-2 font-medium">File</th>
|
||||
<th class="px-4 py-2 font-medium">Size</th>
|
||||
<th class="px-4 py-2 font-medium">Created</th>
|
||||
<th class="px-4 py-2"><span class="sr-only">Actions</span></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="b in backups" :key="b.key" class="border-t border-line">
|
||||
<td class="px-4 py-2 font-mono text-ui-sm">{{ b.key }}</td>
|
||||
<td class="px-4 py-2 tabular-nums">{{ formatBytes(b.size) }}</td>
|
||||
<td class="px-4 py-2">{{ when(b.modified) }}</td>
|
||||
<td class="px-4 py-2 text-right whitespace-nowrap">
|
||||
<DwButton variant="ghost" size="sm" icon="download" :disabled="!!busy" @click="download(b)"
|
||||
>Download</DwButton
|
||||
>
|
||||
<DwButton variant="ghost" size="sm" class="!text-danger" :disabled="!!busy" @click="remove(b)"
|
||||
>Delete</DwButton
|
||||
>
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-if="!backups.length">
|
||||
<td colspan="4" class="px-4 py-6 text-center text-ink-muted">No backups yet.</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="mt-10" data-testid="jobs">
|
||||
<h2 class="text-ui-lg">Background jobs</h2>
|
||||
<p class="text-ui-sm text-ink-muted">Counted since the server started.</p>
|
||||
<div class="mt-3 overflow-x-auto rounded-md border border-line bg-surface-raised">
|
||||
<table class="w-full text-left text-ui-md">
|
||||
<thead class="bg-surface-sunken text-ui-xs uppercase text-ink-muted">
|
||||
<tr>
|
||||
<th class="px-4 py-2 font-medium">Job</th>
|
||||
<th class="px-4 py-2 font-medium">Runs</th>
|
||||
<th class="px-4 py-2 font-medium">Last run</th>
|
||||
<th class="px-4 py-2 font-medium">Status</th>
|
||||
<th class="px-4 py-2"><span class="sr-only">Actions</span></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="j in jobs" :key="j.name" class="border-t border-line align-top">
|
||||
<td class="px-4 py-2">
|
||||
<div class="font-mono text-ui-sm">{{ j.name }}</div>
|
||||
<div class="text-ui-sm text-ink-muted">
|
||||
{{ j.description }}<template v-if="j.every"> · every {{ j.every }}</template>
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-4 py-2 tabular-nums">
|
||||
{{ j.runs }}<span v-if="j.failures" class="text-danger"> ({{ j.failures }} failed)</span>
|
||||
</td>
|
||||
<td class="px-4 py-2">
|
||||
{{ when(j.lastStarted) }}
|
||||
<div v-if="j.lastStarted" class="text-ui-sm text-ink-muted">{{ j.lastDurationMs }} ms</div>
|
||||
</td>
|
||||
<td class="px-4 py-2">
|
||||
<DwBadge v-if="j.running" tone="accent">Running</DwBadge>
|
||||
<DwBadge v-else-if="j.lastError" tone="danger" :title="j.lastError">Failed</DwBadge>
|
||||
<DwBadge v-else-if="j.runs" tone="success">OK</DwBadge>
|
||||
<span v-else class="text-ink-muted">—</span>
|
||||
<div v-if="j.lastError" class="mt-1 max-w-64 text-ui-sm break-words text-danger">{{ j.lastError }}</div>
|
||||
</td>
|
||||
<td class="px-4 py-2 text-right">
|
||||
<DwButton v-if="j.runnable" size="sm" :disabled="!!busy || j.running" @click="runJob(j)"
|
||||
>Run now</DwButton
|
||||
>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -1,56 +1,92 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import { ApiError, type Status, type Version } from "@docwell/api-client";
|
||||
import type { AdminHealth, AdminStats } from "@docwell/api-client";
|
||||
import { DwCallout } from "@docwell/ui";
|
||||
import { onMounted, ref } from "vue";
|
||||
import { api } from "../session";
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { formatBytes } from "../settings";
|
||||
import { api, errorMessage, isSuperadmin } from "../session";
|
||||
|
||||
const version = ref<Version | null>(null);
|
||||
const readiness = ref<Status | null>(null);
|
||||
const userCount = ref<number | null>(null);
|
||||
const error = ref<string | null>(null);
|
||||
const stats = ref<AdminStats | null>(null);
|
||||
const health = ref<AdminHealth | null>(null);
|
||||
const error = ref("");
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
version.value = await api.version();
|
||||
stats.value = await api.admin.stats();
|
||||
if (isSuperadmin.value) health.value = await api.admin.health();
|
||||
} catch (e) {
|
||||
error.value = e instanceof Error ? e.message : String(e);
|
||||
error.value = errorMessage(e);
|
||||
}
|
||||
try {
|
||||
readiness.value = await api.readiness();
|
||||
} catch (e) {
|
||||
readiness.value = e instanceof ApiError ? (e.body as Status) : { status: "unavailable" };
|
||||
}
|
||||
userCount.value = await api.users
|
||||
.list({ perPage: 1 })
|
||||
.then((l) => l.totalItems)
|
||||
.catch(() => null);
|
||||
});
|
||||
|
||||
const cards = computed(() => {
|
||||
const s = stats.value;
|
||||
if (!s) return [];
|
||||
const list = [
|
||||
{ label: "Users", value: String(s.users), to: "/users" },
|
||||
...(s.scope === "instance"
|
||||
? [{ label: "Organizations", value: String(s.organizations), to: "/organizations" }]
|
||||
: []),
|
||||
{ label: "Workspaces", value: String(s.workspaces) },
|
||||
{ label: "Spaces", value: String(s.spaces) },
|
||||
{ label: "Pages", value: String(s.pages) },
|
||||
{ label: "Files", value: `${s.attachments} · ${formatBytes(s.storageBytes)}` },
|
||||
];
|
||||
if (s.scope === "instance") {
|
||||
list.push(
|
||||
{ label: "Open now", value: `${s.rooms} page(s) · ${s.editors} editor(s)` },
|
||||
{ label: "Search index", value: `${s.indexed} page(s)`, to: "/maintenance" },
|
||||
);
|
||||
}
|
||||
return list;
|
||||
});
|
||||
|
||||
function uptime(sec: number) {
|
||||
const d = Math.floor(sec / 86400);
|
||||
const h = Math.floor((sec % 86400) / 3600);
|
||||
const m = Math.floor((sec % 3600) / 60);
|
||||
return d ? `${d} d ${h} h` : h ? `${h} h ${m} min` : `${m} min`;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<h1 class="text-2xl font-semibold tracking-tight">Overview</h1>
|
||||
<p v-if="stats" class="mt-1 text-ink-muted">
|
||||
{{ stats.scope === "instance" ? "The whole server." : "Your organization." }}
|
||||
</p>
|
||||
<DwCallout v-if="error" tone="danger" size="ui" class="mt-4">{{ error }}</DwCallout>
|
||||
<div class="mt-6 grid gap-4 sm:grid-cols-3">
|
||||
<div class="rounded-md border border-line bg-surface-raised p-4">
|
||||
<div class="text-ui-sm text-ink-muted">Server version</div>
|
||||
<div class="mt-1 text-ui-lg">{{ version?.version ?? "…" }}</div>
|
||||
</div>
|
||||
<div class="rounded-md border border-line bg-surface-raised p-4">
|
||||
<div class="text-ui-sm text-ink-muted">Database</div>
|
||||
<div
|
||||
class="mt-1 text-ui-lg"
|
||||
:class="readiness?.status === 'ok' ? 'text-success' : readiness ? 'text-danger' : ''"
|
||||
>
|
||||
{{ readiness ? (readiness.status === "ok" ? "Connected" : "Unavailable") : "…" }}
|
||||
</div>
|
||||
</div>
|
||||
<RouterLink
|
||||
to="/users"
|
||||
class="rounded-md border border-line bg-surface-raised p-4 transition-colors duration-[120ms] hover:border-line-strong"
|
||||
|
||||
<div class="mt-6 grid gap-4 sm:grid-cols-2 lg:grid-cols-4" data-testid="stats">
|
||||
<component
|
||||
:is="c.to ? 'RouterLink' : 'div'"
|
||||
v-for="c in cards"
|
||||
:key="c.label"
|
||||
:to="c.to"
|
||||
class="rounded-md border border-line bg-surface-raised p-4"
|
||||
:class="{ 'transition-colors duration-[120ms] hover:border-line-strong': c.to }"
|
||||
>
|
||||
<div class="text-ui-sm text-ink-muted">Users</div>
|
||||
<div class="mt-1 text-ui-lg" data-testid="user-count">{{ userCount ?? "…" }}</div>
|
||||
</RouterLink>
|
||||
<div class="text-ui-sm text-ink-muted">{{ c.label }}</div>
|
||||
<div class="mt-1 text-ui-lg tabular-nums">{{ c.value }}</div>
|
||||
</component>
|
||||
</div>
|
||||
|
||||
<section v-if="health" class="mt-8" data-testid="health">
|
||||
<h2 class="text-ui-lg">System</h2>
|
||||
<dl class="mt-3 grid gap-x-8 gap-y-2 text-ui-md sm:grid-cols-[max-content_1fr]">
|
||||
<dt class="text-ink-muted">Version</dt>
|
||||
<dd>
|
||||
{{ health.version }} <span class="text-ink-muted">({{ health.goVersion }})</span>
|
||||
</dd>
|
||||
<dt class="text-ink-muted">Up for</dt>
|
||||
<dd>{{ uptime(health.uptimeSeconds) }}</dd>
|
||||
<dt class="text-ink-muted">Database</dt>
|
||||
<dd :class="health.database.ok ? 'text-success' : 'text-danger'">
|
||||
{{
|
||||
health.database.ok ? `Connected · ${health.database.latencyMs} ms` : health.database.error || "Unavailable"
|
||||
}}
|
||||
</dd>
|
||||
<dt class="text-ink-muted">Memory</dt>
|
||||
<dd>{{ health.memoryMb }} MB · {{ health.goroutines }} goroutines</dd>
|
||||
</dl>
|
||||
</section>
|
||||
</template>
|
||||
@@ -1,5 +0,0 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<template>
|
||||
<h1 class="text-2xl font-semibold tracking-tight">{{ $route.meta.title }}</h1>
|
||||
<p class="mt-2 text-ui-md text-ink-muted">Not built yet. See docs/PLAN.md, section 8.</p>
|
||||
</template>
|
||||
@@ -0,0 +1,101 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import { DwButton, DwCallout } from "@docwell/ui";
|
||||
import { reactive, ref, watch } from "vue";
|
||||
import { useInstanceSettings } from "../settings";
|
||||
import { api, errorMessage } from "../session";
|
||||
|
||||
// Where uploaded files live: docwell-db's disk, or an S3-compatible bucket.
|
||||
const { settings, error, saved, busy, save } = useInstanceSettings();
|
||||
const form = reactive({
|
||||
s3: false,
|
||||
bucket: "",
|
||||
region: "",
|
||||
endpoint: "",
|
||||
accessKey: "",
|
||||
secret: "",
|
||||
forcePathStyle: false,
|
||||
});
|
||||
const testState = ref<{ ok: boolean; text: string } | null>(null);
|
||||
|
||||
watch(settings, (s) => {
|
||||
if (s) Object.assign(form, { ...s.storage, secret: "" });
|
||||
});
|
||||
|
||||
function submit() {
|
||||
const { secret, ...rest } = form;
|
||||
save({ storage: { ...rest, secretSet: false, ...(secret ? { secret } : {}) } });
|
||||
}
|
||||
|
||||
async function test() {
|
||||
testState.value = null;
|
||||
try {
|
||||
await api.settings.testStorage();
|
||||
testState.value = { ok: true, text: "The bucket is reachable." };
|
||||
} catch (e) {
|
||||
testState.value = { ok: false, text: errorMessage(e) };
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<h1 class="text-2xl font-semibold tracking-tight">Storage</h1>
|
||||
<p class="mt-1 text-ink-muted">Where images and attachments are kept.</p>
|
||||
<DwCallout v-if="error" tone="danger" size="ui" class="mt-4">{{ error }}</DwCallout>
|
||||
<DwCallout v-if="saved" tone="success" size="ui" class="mt-4">Saved.</DwCallout>
|
||||
<DwCallout tone="warning" size="ui" class="mt-4 max-w-xl">
|
||||
Switching storage does not move existing files. Files uploaded before the switch stay where they were and cannot be
|
||||
opened until they are copied over.
|
||||
</DwCallout>
|
||||
|
||||
<form v-if="settings" class="mt-6 grid max-w-xl gap-4 dw-card sm:grid-cols-2" @submit.prevent="submit">
|
||||
<fieldset class="space-y-2 sm:col-span-2">
|
||||
<legend class="text-ui-sm font-semibold">Keep files</legend>
|
||||
<label class="flex items-center gap-2"
|
||||
><input v-model="form.s3" type="radio" :value="false" class="accent-primary" /> On docwell-db's disk</label
|
||||
>
|
||||
<label class="flex items-center gap-2"
|
||||
><input v-model="form.s3" type="radio" :value="true" class="accent-primary" /> In an S3-compatible bucket</label
|
||||
>
|
||||
</fieldset>
|
||||
<template v-if="form.s3">
|
||||
<label class="flex flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">Endpoint</span>
|
||||
<input v-model="form.endpoint" required class="dw-input" placeholder="https://s3.eu-central-1.amazonaws.com" />
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">Bucket</span>
|
||||
<input v-model="form.bucket" required class="dw-input" />
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">Region</span>
|
||||
<input v-model="form.region" class="dw-input" />
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">Access key</span>
|
||||
<input v-model="form.accessKey" autocomplete="off" class="dw-input" />
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5 sm:col-span-2">
|
||||
<span class="text-ui-sm font-semibold">Secret</span>
|
||||
<input
|
||||
v-model="form.secret"
|
||||
type="password"
|
||||
autocomplete="new-password"
|
||||
class="dw-input"
|
||||
:placeholder="settings.storage.secretSet ? 'Unchanged' : ''"
|
||||
/>
|
||||
</label>
|
||||
<label class="flex items-center gap-3 sm:col-span-2">
|
||||
<input v-model="form.forcePathStyle" type="checkbox" class="accent-primary" />
|
||||
Path-style addressing (MinIO and some other servers need it)
|
||||
</label>
|
||||
</template>
|
||||
<div class="flex gap-2 sm:col-span-2">
|
||||
<DwButton type="submit" variant="primary" :disabled="busy">Save</DwButton>
|
||||
<DwButton v-if="settings.storage.s3" @click="test">Test the saved bucket</DwButton>
|
||||
</div>
|
||||
<DwCallout v-if="testState" :tone="testState.ok ? 'success' : 'danger'" size="ui" class="sm:col-span-2">
|
||||
{{ testState.text }}
|
||||
</DwCallout>
|
||||
</form>
|
||||
</template>
|
||||
@@ -3,6 +3,7 @@
|
||||
import type { Organization, Role, User, UserList } from "@docwell/api-client";
|
||||
import { DwBadge, DwButton, DwCallout } from "@docwell/ui";
|
||||
import { computed, onMounted, reactive, ref, watch } from "vue";
|
||||
import InvitesPanel from "../components/InvitesPanel.vue";
|
||||
import { api, currentUser, errorMessage, isSuperadmin } from "../session";
|
||||
|
||||
// Mirrors the server's rules so the form only offers what will be accepted:
|
||||
@@ -107,6 +108,21 @@ async function save() {
|
||||
}
|
||||
}
|
||||
|
||||
const notice = ref("");
|
||||
async function sendReset(u: User) {
|
||||
busy.value = true;
|
||||
error.value = "";
|
||||
notice.value = "";
|
||||
try {
|
||||
await api.users.sendPasswordReset(u.id);
|
||||
notice.value = `A password reset link is on its way to ${u.email}.`;
|
||||
} catch (e) {
|
||||
error.value = errorMessage(e);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(u: User) {
|
||||
if (!confirm(`Delete ${u.email}? This cannot be undone.`)) return;
|
||||
busy.value = true;
|
||||
@@ -148,7 +164,10 @@ async function remove(u: User) {
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<InvitesPanel :orgs="orgs" @accepted="load" />
|
||||
|
||||
<DwCallout v-if="error" tone="danger" size="ui" class="mt-4">{{ error }}</DwCallout>
|
||||
<DwCallout v-if="notice" tone="success" size="ui" class="mt-4">{{ notice }}</DwCallout>
|
||||
|
||||
<form v-if="editing" class="mt-4 grid gap-3 dw-card !p-4 sm:grid-cols-2" @submit.prevent="save">
|
||||
<h2 class="text-ui-lg sm:col-span-2">{{ editing === "new" ? "New user" : `Edit ${editing.email}` }}</h2>
|
||||
@@ -228,6 +247,7 @@ async function remove(u: User) {
|
||||
<td class="px-4 py-2 text-right whitespace-nowrap">
|
||||
<template v-if="canEdit(u)">
|
||||
<DwButton variant="ghost" size="sm" @click="startEdit(u)">Edit</DwButton>
|
||||
<DwButton variant="ghost" size="sm" :disabled="busy" @click="sendReset(u)">Reset password</DwButton>
|
||||
<DwButton
|
||||
v-if="u.id !== currentUser?.id"
|
||||
variant="ghost"
|
||||
|
||||
@@ -21,6 +21,8 @@ import (
|
||||
"docwell/server/internal/config"
|
||||
"docwell/server/internal/directory"
|
||||
"docwell/server/internal/httpapi"
|
||||
"docwell/server/internal/instance"
|
||||
"docwell/server/internal/jobs"
|
||||
"docwell/server/internal/mail"
|
||||
"docwell/server/internal/search"
|
||||
"docwell/server/internal/settings"
|
||||
@@ -72,6 +74,11 @@ func run(log *slog.Logger) error {
|
||||
return err
|
||||
}
|
||||
defer index.Close()
|
||||
reg := jobs.New()
|
||||
reg.Register("search.index", "Adds changed pages to the search index", 3*time.Second, nil)
|
||||
reg.Register("search.sweep", "Removes deleted pages from the search index", 10*time.Minute, index.Sweep)
|
||||
reg.Register("search.rebuild", "Rebuilds the whole search index from the database", 0, index.Rebuild)
|
||||
index.Track(reg.Track)
|
||||
indexCtx, stopIndex := context.WithCancel(context.Background())
|
||||
defer stopIndex()
|
||||
go index.Run(indexCtx, 3*time.Second, 10*time.Minute)
|
||||
@@ -96,7 +103,7 @@ func run(log *slog.Logger) error {
|
||||
// without another secret to configure.
|
||||
FileTokens: auth.NewFileTokens(cfg.PocketBasePassword, time.Hour),
|
||||
MaxUpload: int64(cfg.MaxUploadMB) << 20,
|
||||
Search: index,
|
||||
Instance: instance.New(db, Version, hub, index, reg),
|
||||
Collab: hub,
|
||||
Admin: admin.Handler("/admin"),
|
||||
Log: log,
|
||||
|
||||
@@ -4,9 +4,29 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
openapi_types "github.com/oapi-codegen/runtime/types"
|
||||
)
|
||||
|
||||
// Defines values for AdminStatsScope.
|
||||
const (
|
||||
AdminStatsScopeInstance AdminStatsScope = "instance"
|
||||
AdminStatsScopeOrganization AdminStatsScope = "organization"
|
||||
)
|
||||
|
||||
// Valid indicates whether the value is a known member of the AdminStatsScope enum.
|
||||
func (e AdminStatsScope) Valid() bool {
|
||||
switch e {
|
||||
case AdminStatsScopeInstance:
|
||||
return true
|
||||
case AdminStatsScopeOrganization:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Defines values for InviteStatus.
|
||||
const (
|
||||
Added InviteStatus = "added"
|
||||
@@ -214,6 +234,49 @@ func (e ExportPageParamsFormat) Valid() bool {
|
||||
}
|
||||
}
|
||||
|
||||
// AdminHealth defines model for AdminHealth.
|
||||
type AdminHealth struct {
|
||||
Database struct {
|
||||
Error *string `json:"error,omitempty"`
|
||||
LatencyMs int `json:"latencyMs"`
|
||||
Ok bool `json:"ok"`
|
||||
} `json:"database"`
|
||||
GoVersion string `json:"goVersion"`
|
||||
Goroutines int `json:"goroutines"`
|
||||
MemoryMb int `json:"memoryMb"`
|
||||
Started time.Time `json:"started"`
|
||||
UptimeSeconds int `json:"uptimeSeconds"`
|
||||
Version string `json:"version"`
|
||||
}
|
||||
|
||||
// AdminStats defines model for AdminStats.
|
||||
type AdminStats struct {
|
||||
Attachments int `json:"attachments"`
|
||||
|
||||
// Editors People connected to those pages (instance scope only)
|
||||
Editors int `json:"editors"`
|
||||
|
||||
// Indexed Pages in the search index (instance scope only)
|
||||
Indexed int `json:"indexed"`
|
||||
Organizations int `json:"organizations"`
|
||||
|
||||
// Pages Pages outside the trash
|
||||
Pages int `json:"pages"`
|
||||
|
||||
// Rooms Pages open for editing now (instance scope only)
|
||||
Rooms int `json:"rooms"`
|
||||
Scope AdminStatsScope `json:"scope"`
|
||||
Spaces int `json:"spaces"`
|
||||
|
||||
// StorageBytes Total size of attachments
|
||||
StorageBytes int `json:"storageBytes"`
|
||||
Users int `json:"users"`
|
||||
Workspaces int `json:"workspaces"`
|
||||
}
|
||||
|
||||
// AdminStatsScope defines model for AdminStats.Scope.
|
||||
type AdminStatsScope string
|
||||
|
||||
// Attachment defines model for Attachment.
|
||||
type Attachment struct {
|
||||
Created string `json:"created"`
|
||||
@@ -246,6 +309,13 @@ type AuthSettings struct {
|
||||
MagicLink bool `json:"magicLink"`
|
||||
}
|
||||
|
||||
// Backup defines model for Backup.
|
||||
type Backup struct {
|
||||
Key string `json:"key"`
|
||||
Modified string `json:"modified"`
|
||||
Size int `json:"size"`
|
||||
}
|
||||
|
||||
// BrandingSettings defines model for BrandingSettings.
|
||||
type BrandingSettings struct {
|
||||
AccentColor string `json:"accentColor"`
|
||||
@@ -391,6 +461,28 @@ type InviteInfo struct {
|
||||
WorkspaceName string `json:"workspaceName"`
|
||||
}
|
||||
|
||||
// Job defines model for Job.
|
||||
type Job struct {
|
||||
Description string `json:"description"`
|
||||
|
||||
// Every How often it runs on its own (Go duration); empty when only on demand
|
||||
Every string `json:"every"`
|
||||
Failures int `json:"failures"`
|
||||
LastDurationMs int `json:"lastDurationMs"`
|
||||
LastError string `json:"lastError"`
|
||||
|
||||
// LastStarted RFC 3339; empty before the first run
|
||||
LastStarted string `json:"lastStarted"`
|
||||
Name string `json:"name"`
|
||||
|
||||
// Runnable Can be started by hand
|
||||
Runnable bool `json:"runnable"`
|
||||
Running bool `json:"running"`
|
||||
|
||||
// Runs Runs since the server started
|
||||
Runs int `json:"runs"`
|
||||
}
|
||||
|
||||
// LoginRequest defines model for LoginRequest.
|
||||
type LoginRequest struct {
|
||||
Email openapi_types.Email `json:"email"`
|
||||
|
||||
@@ -73,6 +73,29 @@ func (h *Hub) Close(ctx context.Context) error {
|
||||
}
|
||||
}
|
||||
|
||||
// Stats counts the open pages and their connected editors.
|
||||
type Stats struct {
|
||||
Rooms int `json:"rooms"`
|
||||
Peers int `json:"peers"`
|
||||
}
|
||||
|
||||
// Stats reports what is open right now (for the admin dashboard).
|
||||
func (h *Hub) Stats() Stats {
|
||||
h.mu.Lock()
|
||||
rooms := make([]*room, 0, len(h.rooms))
|
||||
for _, r := range h.rooms {
|
||||
rooms = append(rooms, r)
|
||||
}
|
||||
h.mu.Unlock()
|
||||
st := Stats{Rooms: len(rooms)}
|
||||
for _, r := range rooms {
|
||||
r.mu.Lock()
|
||||
st.Peers += len(r.sessions)
|
||||
r.mu.Unlock()
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
// Peer is the sending side of one connection. Send must not block; it returns
|
||||
// false when the peer cannot keep up and is being disconnected.
|
||||
type Peer interface {
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/instance"
|
||||
"docwell/server/internal/jobs"
|
||||
)
|
||||
|
||||
// InstanceService is the admin panel's view of the server (instance.Service).
|
||||
type InstanceService interface {
|
||||
Stats(ctx context.Context, c access.Caller) (instance.Stats, error)
|
||||
Health(ctx context.Context, c access.Caller) (instance.Health, error)
|
||||
Jobs(c access.Caller) ([]jobs.Job, error)
|
||||
RunJob(c access.Caller, name string) error
|
||||
ListBackups(ctx context.Context, c access.Caller) ([]instance.Backup, error)
|
||||
CreateBackup(ctx context.Context, c access.Caller) error
|
||||
DeleteBackup(ctx context.Context, c access.Caller, key string) error
|
||||
OpenBackup(ctx context.Context, c access.Caller, key string) (*http.Response, error)
|
||||
}
|
||||
|
||||
func (a *api) adminRoutes(mux *routeMux) {
|
||||
mux.HandleFunc("GET /api/v1/admin/stats", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
|
||||
st, err := a.instance.Stats(r.Context(), caller(r))
|
||||
a.respond(w, st, err)
|
||||
}))
|
||||
mux.HandleFunc("GET /api/v1/admin/health", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
|
||||
h, err := a.instance.Health(r.Context(), caller(r))
|
||||
a.respond(w, h, err)
|
||||
}))
|
||||
mux.HandleFunc("GET /api/v1/admin/jobs", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
|
||||
list, err := a.instance.Jobs(caller(r))
|
||||
a.respond(w, list, err)
|
||||
}))
|
||||
mux.HandleFunc("POST /api/v1/admin/jobs/{name}/run", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := a.instance.RunJob(caller(r), r.PathValue("name")); err != nil {
|
||||
a.writeError(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
}))
|
||||
|
||||
mux.HandleFunc("GET /api/v1/admin/backups", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
|
||||
list, err := a.instance.ListBackups(r.Context(), caller(r))
|
||||
a.respond(w, list, err)
|
||||
}))
|
||||
mux.HandleFunc("POST /api/v1/admin/backups", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
|
||||
a.respondNoContent(w, a.instance.CreateBackup(r.Context(), caller(r)))
|
||||
}))
|
||||
mux.HandleFunc("DELETE /api/v1/admin/backups/{key}", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
|
||||
a.respondNoContent(w, a.instance.DeleteBackup(r.Context(), caller(r), r.PathValue("key")))
|
||||
}))
|
||||
mux.HandleFunc("GET /api/v1/admin/backups/{key}", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
|
||||
resp, err := a.instance.OpenBackup(r.Context(), caller(r), r.PathValue("key"))
|
||||
if err != nil {
|
||||
a.writeError(w, err)
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
h := w.Header()
|
||||
h.Set("Content-Type", "application/zip")
|
||||
h.Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": r.PathValue("key")}))
|
||||
if n := resp.Header.Get("Content-Length"); n != "" {
|
||||
h.Set("Content-Length", n)
|
||||
}
|
||||
_, _ = io.Copy(w, resp.Body)
|
||||
}))
|
||||
}
|
||||
@@ -42,7 +42,7 @@ type api struct {
|
||||
dir DirectoryService
|
||||
settings SettingsService
|
||||
files *auth.FileTokens
|
||||
index SearchIndex
|
||||
instance InstanceService
|
||||
collab CollabHub
|
||||
log *slog.Logger
|
||||
}
|
||||
@@ -152,6 +152,7 @@ func (a *api) routes(mux *routeMux) {
|
||||
a.transferRoutes(mux)
|
||||
a.shareRoutes(mux)
|
||||
a.commentRoutes(mux)
|
||||
a.adminRoutes(mux)
|
||||
}
|
||||
|
||||
func (a *api) decode(w http.ResponseWriter, r *http.Request, v any) bool {
|
||||
|
||||
@@ -28,8 +28,8 @@ type Deps struct {
|
||||
Settings SettingsService
|
||||
// FileTokens signs the ?token= of file links; nil allows only bearer tokens.
|
||||
FileTokens *auth.FileTokens
|
||||
// Search is the full-text index (admin reindex); nil disables it.
|
||||
Search SearchIndex
|
||||
// Instance serves the admin dashboard, health, jobs and backups.
|
||||
Instance InstanceService
|
||||
// MaxUpload caps one attachment in bytes.
|
||||
MaxUpload int64
|
||||
// Collab serves /collab; nil disables live editing.
|
||||
@@ -60,7 +60,7 @@ func NewRouter(d Deps) http.Handler {
|
||||
|
||||
func newMux(d Deps) *routeMux {
|
||||
mux := &routeMux{ServeMux: http.NewServeMux()}
|
||||
a := &api{auth: d.Auth, dir: d.Directory, settings: d.Settings, files: d.FileTokens, index: d.Search, collab: d.Collab, log: d.Log}
|
||||
a := &api{auth: d.Auth, dir: d.Directory, settings: d.Settings, files: d.FileTokens, instance: d.Instance, collab: d.Collab, log: d.Log}
|
||||
a.routes(mux)
|
||||
a.fileRoutes(mux, max(d.MaxUpload, 1<<20))
|
||||
a.collabRoute(mux, d.CORSOrigins)
|
||||
|
||||
@@ -16,12 +16,6 @@ type SearchService interface {
|
||||
Search(ctx context.Context, c access.Caller, wsID, text string, limit int) (directory.SearchResult, error)
|
||||
}
|
||||
|
||||
// SearchIndex is the index maintenance the admin panel can trigger.
|
||||
type SearchIndex interface {
|
||||
Rebuild(ctx context.Context) error
|
||||
Count() (uint64, error)
|
||||
}
|
||||
|
||||
func (a *api) searchRoutes(mux *routeMux) {
|
||||
mux.HandleFunc("GET /api/v1/workspaces/{id}/search", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
@@ -29,21 +23,4 @@ func (a *api) searchRoutes(mux *routeMux) {
|
||||
res, err := a.dir.Search(r.Context(), caller(r), r.PathValue("id"), q.Get("q"), min(max(limit, 0), 50))
|
||||
a.respond(w, res, err)
|
||||
}))
|
||||
mux.HandleFunc("POST /api/v1/admin/search/reindex", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := access.ManageInstance(caller(r)); err != nil {
|
||||
a.writeError(w, err)
|
||||
return
|
||||
}
|
||||
if a.index == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "unavailable"})
|
||||
return
|
||||
}
|
||||
// Rebuilding can take a while; it runs on after the response.
|
||||
go func() {
|
||||
if err := a.index.Rebuild(context.WithoutCancel(r.Context())); err != nil {
|
||||
a.log.Error("search: rebuild failed", "err", err)
|
||||
}
|
||||
}()
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// Package instance serves the admin panel's view of the whole server: the
|
||||
// dashboard numbers, system health, background jobs and database backups.
|
||||
package instance
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/apperr"
|
||||
"docwell/server/internal/collab"
|
||||
"docwell/server/internal/jobs"
|
||||
"docwell/server/internal/store/pocketbase"
|
||||
)
|
||||
|
||||
// Live is what the collaboration hub reports.
|
||||
type Live interface{ Stats() collab.Stats }
|
||||
|
||||
// Indexed is what the search index reports.
|
||||
type Indexed interface{ Count() (uint64, error) }
|
||||
|
||||
type Service struct {
|
||||
pb *pocketbase.Client
|
||||
version string
|
||||
started time.Time
|
||||
live Live
|
||||
index Indexed
|
||||
jobs *jobs.Registry
|
||||
}
|
||||
|
||||
func New(pb *pocketbase.Client, version string, live Live, index Indexed, reg *jobs.Registry) *Service {
|
||||
return &Service{pb: pb, version: version, started: time.Now(), live: live, index: index, jobs: reg}
|
||||
}
|
||||
|
||||
// Stats are the dashboard numbers; an org admin sees their organization's.
|
||||
type Stats struct {
|
||||
// Scope is "instance" for superadmins, "organization" for org admins.
|
||||
Scope string `json:"scope"`
|
||||
Users int `json:"users"`
|
||||
Organizations int `json:"organizations"`
|
||||
Workspaces int `json:"workspaces"`
|
||||
Spaces int `json:"spaces"`
|
||||
Pages int `json:"pages"`
|
||||
Attachments int `json:"attachments"`
|
||||
StorageBytes int64 `json:"storageBytes"`
|
||||
// Rooms and Editors are pages open right now and the people in them
|
||||
// (instance-wide only).
|
||||
Rooms int `json:"rooms"`
|
||||
Editors int `json:"editors"`
|
||||
// Indexed is the number of pages in the search index (instance-wide only).
|
||||
Indexed int `json:"indexed"`
|
||||
}
|
||||
|
||||
func (s *Service) count(ctx context.Context, collection, filter string) (int, error) {
|
||||
res, err := pocketbase.List[struct{}](ctx, s.pb, collection, pocketbase.ListOptions{PerPage: 1, Filter: filter, Fields: "id"})
|
||||
return res.TotalItems, err
|
||||
}
|
||||
|
||||
// Stats counts what c manages.
|
||||
func (s *Service) Stats(ctx context.Context, c access.Caller) (Stats, error) {
|
||||
all, org, err := access.UserScope(c)
|
||||
if err != nil {
|
||||
return Stats{}, err
|
||||
}
|
||||
st := Stats{Scope: "instance"}
|
||||
f := map[string]string{"users": "", "organizations": "", "workspaces": "", "spaces": "", "pages": "deleted_at = ''", "attachments": ""}
|
||||
if !all {
|
||||
st.Scope = "organization"
|
||||
if org == "" {
|
||||
return st, nil
|
||||
}
|
||||
f = map[string]string{
|
||||
"users": fmt.Sprintf("organization = '%s'", org),
|
||||
"organizations": fmt.Sprintf("id = '%s'", org),
|
||||
"workspaces": fmt.Sprintf("organization = '%s'", org),
|
||||
"spaces": fmt.Sprintf("workspace.organization = '%s'", org),
|
||||
"pages": fmt.Sprintf("deleted_at = '' && workspace.organization = '%s'", org),
|
||||
"attachments": fmt.Sprintf("workspace.organization = '%s'", org),
|
||||
}
|
||||
}
|
||||
for name, dst := range map[string]*int{
|
||||
"users": &st.Users, "organizations": &st.Organizations, "workspaces": &st.Workspaces,
|
||||
"spaces": &st.Spaces, "pages": &st.Pages, "attachments": &st.Attachments,
|
||||
} {
|
||||
if *dst, err = s.count(ctx, name, f[name]); err != nil {
|
||||
return Stats{}, err
|
||||
}
|
||||
}
|
||||
// Storage is the sum of attachment sizes; PocketBase has no aggregate
|
||||
// query over REST, so it pages through the size column.
|
||||
for page := 1; ; page++ {
|
||||
res, err := pocketbase.List[struct {
|
||||
Size int64 `json:"size"`
|
||||
}](ctx, s.pb, "attachments", pocketbase.ListOptions{Page: page, PerPage: 1000, Fields: "size", Filter: f["attachments"]})
|
||||
if err != nil {
|
||||
return Stats{}, err
|
||||
}
|
||||
for _, a := range res.Items {
|
||||
st.StorageBytes += a.Size
|
||||
}
|
||||
if page >= res.TotalPages || len(res.Items) == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if all {
|
||||
if s.live != nil {
|
||||
live := s.live.Stats()
|
||||
st.Rooms, st.Editors = live.Rooms, live.Peers
|
||||
}
|
||||
if s.index != nil {
|
||||
if n, err := s.index.Count(); err == nil {
|
||||
st.Indexed = int(min(n, 1<<31-1))
|
||||
}
|
||||
}
|
||||
}
|
||||
return st, nil
|
||||
}
|
||||
|
||||
// Health describes the running server (superadmin).
|
||||
type Health struct {
|
||||
Version string `json:"version"`
|
||||
GoVersion string `json:"goVersion"`
|
||||
Started string `json:"started"`
|
||||
UptimeSec int64 `json:"uptimeSeconds"`
|
||||
Database struct {
|
||||
OK bool `json:"ok"`
|
||||
LatencyMs int64 `json:"latencyMs"`
|
||||
Error string `json:"error,omitempty"`
|
||||
} `json:"database"`
|
||||
Goroutines int `json:"goroutines"`
|
||||
MemoryMB uint64 `json:"memoryMb"`
|
||||
}
|
||||
|
||||
func (s *Service) Health(ctx context.Context, c access.Caller) (Health, error) {
|
||||
if err := access.ManageInstance(c); err != nil {
|
||||
return Health{}, err
|
||||
}
|
||||
h := Health{
|
||||
Version: s.version, GoVersion: runtime.Version(), Started: s.started.UTC().Format(time.RFC3339),
|
||||
UptimeSec: int64(time.Since(s.started).Seconds()), Goroutines: runtime.NumGoroutine(),
|
||||
}
|
||||
var mem runtime.MemStats
|
||||
runtime.ReadMemStats(&mem)
|
||||
h.MemoryMB = mem.Sys >> 20
|
||||
start := time.Now()
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
err := s.pb.Health(ctx)
|
||||
h.Database.LatencyMs = time.Since(start).Milliseconds()
|
||||
h.Database.OK = err == nil
|
||||
if err != nil {
|
||||
h.Database.Error = err.Error()
|
||||
}
|
||||
return h, nil
|
||||
}
|
||||
|
||||
// Jobs lists the background jobs (superadmin).
|
||||
func (s *Service) Jobs(c access.Caller) ([]jobs.Job, error) {
|
||||
if err := access.ManageInstance(c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.jobs.List(), nil
|
||||
}
|
||||
|
||||
// RunJob starts a job by hand (superadmin).
|
||||
func (s *Service) RunJob(c access.Caller, name string) error {
|
||||
if err := access.ManageInstance(c); err != nil {
|
||||
return err
|
||||
}
|
||||
switch err := s.jobs.Run(name); {
|
||||
case errors.Is(err, jobs.ErrUnknown):
|
||||
return apperr.NotFound("no job can be started with that name")
|
||||
case errors.Is(err, jobs.ErrBusy):
|
||||
return apperr.Conflict("the job is already running")
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Backups ---------------------------------------------------------------
|
||||
|
||||
// Backup is one PocketBase backup archive (the whole database and its files).
|
||||
type Backup struct {
|
||||
Key string `json:"key"`
|
||||
Size int64 `json:"size"`
|
||||
Modified string `json:"modified"`
|
||||
}
|
||||
|
||||
var backupKey = regexp.MustCompile(`^[a-z0-9_.-]{1,150}\.zip$`)
|
||||
|
||||
func backupError(err error) error {
|
||||
var pbErr *pocketbase.Error
|
||||
if errors.As(err, &pbErr) {
|
||||
switch pbErr.Status {
|
||||
case http.StatusNotFound:
|
||||
return apperr.NotFound("backup not found")
|
||||
case http.StatusBadRequest:
|
||||
return apperr.Invalid(pbErr.Message)
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Service) ListBackups(ctx context.Context, c access.Caller) ([]Backup, error) {
|
||||
if err := access.ManageInstance(c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := []Backup{}
|
||||
err := s.pb.Do(ctx, http.MethodGet, "/api/backups", nil, &out)
|
||||
return out, backupError(err)
|
||||
}
|
||||
|
||||
// CreateBackup asks PocketBase to write a new archive. It can take a while
|
||||
// on large instances; PocketBase answers when the archive is complete.
|
||||
func (s *Service) CreateBackup(ctx context.Context, c access.Caller) error {
|
||||
if err := access.ManageInstance(c); err != nil {
|
||||
return err
|
||||
}
|
||||
name := "docwell-" + time.Now().UTC().Format("20060102-150405") + ".zip"
|
||||
return backupError(s.pb.Do(ctx, http.MethodPost, "/api/backups", map[string]string{"name": name}, nil))
|
||||
}
|
||||
|
||||
func (s *Service) DeleteBackup(ctx context.Context, c access.Caller, key string) error {
|
||||
if err := access.ManageInstance(c); err != nil {
|
||||
return err
|
||||
}
|
||||
if !backupKey.MatchString(key) {
|
||||
return apperr.NotFound("backup not found")
|
||||
}
|
||||
return backupError(s.pb.Do(ctx, http.MethodDelete, "/api/backups/"+key, nil, nil))
|
||||
}
|
||||
|
||||
// OpenBackup streams an archive; the caller closes the body.
|
||||
func (s *Service) OpenBackup(ctx context.Context, c access.Caller, key string) (*http.Response, error) {
|
||||
if err := access.ManageInstance(c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !backupKey.MatchString(key) {
|
||||
return nil, apperr.NotFound("backup not found")
|
||||
}
|
||||
resp, err := s.pb.OpenBackup(ctx, key)
|
||||
return resp, backupError(err)
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// Package jobs tracks docwell-server's background work (search indexing and
|
||||
// the like) so the admin panel can show when each job last ran, how long it
|
||||
// took and whether it failed, and run some of them on demand.
|
||||
package jobs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ErrUnknown is returned for a job name that was never registered.
|
||||
var ErrUnknown = errors.New("unknown job")
|
||||
|
||||
// ErrBusy is returned when a job is asked to run while it is running.
|
||||
var ErrBusy = errors.New("job is already running")
|
||||
|
||||
// Job is one kind of background work, as the admin panel shows it.
|
||||
type Job struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
// Every is how often it runs on its own ("" = only on demand).
|
||||
Every string `json:"every"`
|
||||
Runnable bool `json:"runnable"`
|
||||
Running bool `json:"running"`
|
||||
Runs int `json:"runs"`
|
||||
Failures int `json:"failures"`
|
||||
LastStarted string `json:"lastStarted"`
|
||||
LastDuration int64 `json:"lastDurationMs"`
|
||||
LastError string `json:"lastError"`
|
||||
}
|
||||
|
||||
type entry struct {
|
||||
Job
|
||||
run func(ctx context.Context) error
|
||||
}
|
||||
|
||||
type Registry struct {
|
||||
mu sync.Mutex
|
||||
jobs map[string]*entry
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func New() *Registry {
|
||||
return &Registry{jobs: map[string]*entry{}, now: time.Now}
|
||||
}
|
||||
|
||||
// Register declares a job. run, when not nil, lets admins start it by hand.
|
||||
func (r *Registry) Register(name, description string, every time.Duration, run func(ctx context.Context) error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
e := &entry{Job: Job{Name: name, Description: description, Runnable: run != nil}, run: run}
|
||||
if every > 0 {
|
||||
e.Every = every.String()
|
||||
}
|
||||
r.jobs[name] = e
|
||||
}
|
||||
|
||||
// Track runs fn as one run of job name and records the outcome. Unknown
|
||||
// names are registered on the fly, so callers never lose a report.
|
||||
func (r *Registry) Track(name string, fn func() error) error {
|
||||
r.mu.Lock()
|
||||
e, ok := r.jobs[name]
|
||||
if !ok {
|
||||
e = &entry{Job: Job{Name: name}}
|
||||
r.jobs[name] = e
|
||||
}
|
||||
start := r.now()
|
||||
e.Running = true
|
||||
r.mu.Unlock()
|
||||
|
||||
err := fn()
|
||||
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
e.Running = false
|
||||
e.Runs++
|
||||
e.LastStarted = start.UTC().Format(time.RFC3339)
|
||||
e.LastDuration = r.now().Sub(start).Milliseconds()
|
||||
e.LastError = ""
|
||||
if err != nil {
|
||||
e.Failures++
|
||||
e.LastError = err.Error()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// List returns every job, by name.
|
||||
func (r *Registry) List() []Job {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
out := make([]Job, 0, len(r.jobs))
|
||||
for _, e := range r.jobs {
|
||||
out = append(out, e.Job)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
||||
return out
|
||||
}
|
||||
|
||||
// Run starts a runnable job in the background.
|
||||
func (r *Registry) Run(name string) error {
|
||||
r.mu.Lock()
|
||||
e, ok := r.jobs[name]
|
||||
switch {
|
||||
case !ok || e.run == nil:
|
||||
r.mu.Unlock()
|
||||
return ErrUnknown
|
||||
case e.Running:
|
||||
r.mu.Unlock()
|
||||
return ErrBusy
|
||||
}
|
||||
run := e.run
|
||||
r.mu.Unlock()
|
||||
go func() { _ = r.Track(name, func() error { return run(context.Background()) }) }()
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package jobs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTrackAndRun(t *testing.T) {
|
||||
r := New()
|
||||
ran := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
r.Register("index", "Indexes pages", 3*time.Second, func(context.Context) error {
|
||||
close(ran)
|
||||
<-release
|
||||
return nil
|
||||
})
|
||||
|
||||
if err := r.Track("index", func() error { return errors.New("boom") }); err == nil {
|
||||
t.Fatal("Track must return fn's error")
|
||||
}
|
||||
j := r.List()[0]
|
||||
if j.Runs != 1 || j.Failures != 1 || j.LastError != "boom" || j.Every != "3s" || !j.Runnable {
|
||||
t.Errorf("after a failure: %+v", j)
|
||||
}
|
||||
|
||||
if err := r.Run("index"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
<-ran
|
||||
if err := r.Run("index"); !errors.Is(err, ErrBusy) {
|
||||
t.Errorf("second run while busy = %v", err)
|
||||
}
|
||||
close(release)
|
||||
for i := 0; i < 100 && r.List()[0].Running; i++ {
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
if j := r.List()[0]; j.Running || j.Runs != 2 || j.LastError != "" {
|
||||
t.Errorf("after a good run: %+v", j)
|
||||
}
|
||||
if err := r.Run("nope"); !errors.Is(err, ErrUnknown) {
|
||||
t.Errorf("unknown = %v", err)
|
||||
}
|
||||
_ = r.Track("adhoc", func() error { return nil })
|
||||
if len(r.List()) != 2 {
|
||||
t.Error("unregistered jobs are tracked too")
|
||||
}
|
||||
}
|
||||
@@ -58,7 +58,18 @@ type Index struct {
|
||||
pb *pocketbase.Client
|
||||
log *slog.Logger
|
||||
|
||||
mu sync.Mutex // serializes indexing passes
|
||||
mu sync.Mutex // serializes indexing passes
|
||||
track func(name string, fn func() error) error
|
||||
}
|
||||
|
||||
// Track reports each indexing pass to fn (the admin panel's job list).
|
||||
func (x *Index) Track(fn func(name string, run func() error) error) { x.track = fn }
|
||||
|
||||
func (x *Index) tracked(name string, fn func() error) error {
|
||||
if x.track == nil {
|
||||
return fn()
|
||||
}
|
||||
return x.track(name, fn)
|
||||
}
|
||||
|
||||
const checkpointKey = "checkpoint"
|
||||
@@ -136,11 +147,11 @@ func (x *Index) Run(ctx context.Context, interval, sweepEvery time.Duration) {
|
||||
defer tick.Stop()
|
||||
lastSweep := time.Time{}
|
||||
for {
|
||||
if err := x.CatchUp(ctx); err != nil && ctx.Err() == nil {
|
||||
if err := x.tracked("search.index", func() error { return x.CatchUp(ctx) }); err != nil && ctx.Err() == nil {
|
||||
x.log.Warn("search: indexing failed", "err", err)
|
||||
}
|
||||
if time.Since(lastSweep) >= sweepEvery {
|
||||
if err := x.Sweep(ctx); err != nil && ctx.Err() == nil {
|
||||
if err := x.tracked("search.sweep", func() error { return x.Sweep(ctx) }); err != nil && ctx.Err() == nil {
|
||||
x.log.Warn("search: sweep failed", "err", err)
|
||||
}
|
||||
lastSweep = time.Now()
|
||||
|
||||
@@ -323,6 +323,34 @@ func (c *Client) OpenFile(ctx context.Context, collection, recordID, filename st
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// OpenBackup streams a PocketBase backup archive. The caller closes the body.
|
||||
func (c *Client) OpenBackup(ctx context.Context, key string) (*http.Response, error) {
|
||||
token, err := c.authToken(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var ft struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if err := c.send(ctx, http.MethodPost, "/api/files/token", token, nil, &ft); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet,
|
||||
c.baseURL+"/api/backups/"+url.PathEscape(key)+"?token="+url.QueryEscape(ft.Token), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := (&http.Client{}).Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.StatusCode >= 400 {
|
||||
defer resp.Body.Close()
|
||||
return nil, &Error{Status: resp.StatusCode, Message: "backup download failed"}
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// raw sends a request with a non-JSON body and returns the response for a
|
||||
// 2xx status; errors are decoded like send's.
|
||||
func (c *Client) raw(ctx context.Context, method, path, token string, body io.Reader, contentType string) (*http.Response, error) {
|
||||
|
||||
Reference in new issue
Block a user