Compare commits
2 Commits
feature/cl
...
feat/cl4-s
| Author | SHA1 | Date | |
|---|---|---|---|
| 9deac1388d | |||
| e87f86ae86 |
@@ -4,7 +4,6 @@ SUPABASE_SERVICE_ROLE_KEY=
|
|||||||
|
|
||||||
NEXT_PUBLIC_APP_URL=http://localhost:3000
|
NEXT_PUBLIC_APP_URL=http://localhost:3000
|
||||||
JOB_SECRET=
|
JOB_SECRET=
|
||||||
CRON_SECRET=
|
|
||||||
|
|
||||||
ENCRYPTION_KEY=
|
ENCRYPTION_KEY=
|
||||||
PLESK_CRED_ENC_KEY=
|
PLESK_CRED_ENC_KEY=
|
||||||
|
|||||||
37
README.md
37
README.md
@@ -63,9 +63,7 @@ values ('<agency_uuid>', '<auth_user_uuid>', 'owner');
|
|||||||
|
|
||||||
- `POST /api/plesk/instances` — create + validate Plesk connection
|
- `POST /api/plesk/instances` — create + validate Plesk connection
|
||||||
- `POST /api/plesk/instances/:id/sync` — pull/sync subscriptions + domains from one Plesk instance
|
- `POST /api/plesk/instances/:id/sync` — pull/sync subscriptions + domains from one Plesk instance
|
||||||
- `POST /api/plesk/instances/:id/autosync` — update auto-sync enabled/frequency for one Plesk instance
|
|
||||||
- `POST /api/jobs/plesk-sync-all` — background sync job for all connected instances (requires `X-JOB-SECRET`)
|
- `POST /api/jobs/plesk-sync-all` — background sync job for all connected instances (requires `X-JOB-SECRET`)
|
||||||
- `POST /api/cron/autosync` — scheduled auto-sync tick (requires `X-CRON-SECRET`)
|
|
||||||
- `POST /api/plesk/subscriptions/:id/action` — suspend or unsuspend
|
- `POST /api/plesk/subscriptions/:id/action` — suspend or unsuspend
|
||||||
- `POST /api/stripe/checkout` — create Stripe Checkout session
|
- `POST /api/stripe/checkout` — create Stripe Checkout session
|
||||||
- `POST /api/stripe/portal` — create Stripe Customer Portal session
|
- `POST /api/stripe/portal` — create Stripe Customer Portal session
|
||||||
@@ -76,7 +74,6 @@ values ('<agency_uuid>', '<auth_user_uuid>', 'owner');
|
|||||||
- Set a strong `ENCRYPTION_KEY`; it encrypts stored Plesk auth secrets.
|
- Set a strong `ENCRYPTION_KEY`; it encrypts stored Plesk auth secrets.
|
||||||
- Set a strong `PLESK_CRED_ENC_KEY` (32-byte base64 or 64-char hex) for Plesk credential encryption.
|
- Set a strong `PLESK_CRED_ENC_KEY` (32-byte base64 or 64-char hex) for Plesk credential encryption.
|
||||||
- Set `JOB_SECRET` for internal cron-triggered job auth.
|
- Set `JOB_SECRET` for internal cron-triggered job auth.
|
||||||
- Set `CRON_SECRET` for `/api/cron/autosync` auth.
|
|
||||||
- `/api/stripe/webhook` is excluded from auth middleware for Stripe signature verification.
|
- `/api/stripe/webhook` is excluded from auth middleware for Stripe signature verification.
|
||||||
- Current implementation is intentionally MVP-focused; add stronger validation, retries, idempotency keys, and richer error observability for production.
|
- Current implementation is intentionally MVP-focused; add stronger validation, retries, idempotency keys, and richer error observability for production.
|
||||||
|
|
||||||
@@ -100,37 +97,3 @@ Notes:
|
|||||||
- Job uses DB lock (`job_locks`) to avoid overlapping runs.
|
- Job uses DB lock (`job_locks`) to avoid overlapping runs.
|
||||||
- Job processes at most 10 connected instances per run.
|
- Job processes at most 10 connected instances per run.
|
||||||
- Instances synced in the last 3 minutes are skipped.
|
- Instances synced in the last 3 minutes are skipped.
|
||||||
|
|
||||||
## 6) Auto Sync Worker (CL6)
|
|
||||||
|
|
||||||
New scheduler fields live on `plesk_instances`:
|
|
||||||
|
|
||||||
- `auto_sync_enabled`
|
|
||||||
- `auto_sync_frequency_minutes`
|
|
||||||
- `last_auto_sync_at`
|
|
||||||
- `next_auto_sync_at`
|
|
||||||
- `auto_sync_lock_until`
|
|
||||||
- `auto_sync_lock_token`
|
|
||||||
|
|
||||||
Endpoint for periodic worker ticks:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
curl -sS -X POST http://localhost:3000/api/cron/autosync \
|
|
||||||
-H "X-CRON-SECRET: <CRON_SECRET>"
|
|
||||||
```
|
|
||||||
|
|
||||||
Recommended system cron (every 5 minutes):
|
|
||||||
|
|
||||||
```cron
|
|
||||||
*/5 * * * * curl -sS -X POST https://<your-host>/api/cron/autosync -H "X-CRON-SECRET: ${CRON_SECRET}"
|
|
||||||
```
|
|
||||||
|
|
||||||
Or schedule the same call from Jenkins.
|
|
||||||
|
|
||||||
Worker safety behavior:
|
|
||||||
|
|
||||||
- processes at most 5 instances per tick
|
|
||||||
- concurrency limited to 2 at a time
|
|
||||||
- per-instance lock lease 15 minutes
|
|
||||||
- per-instance timeout guard 14 minutes
|
|
||||||
- per-instance failures are isolated and logged to `actions_log`
|
|
||||||
|
|||||||
@@ -1,38 +0,0 @@
|
|||||||
import { NextResponse } from "next/server";
|
|
||||||
|
|
||||||
import { env } from "@/lib/env";
|
|
||||||
import { runAutoSyncTick } from "@/lib/plesk/auto-sync";
|
|
||||||
import { createSupabaseAdminClient } from "@/lib/supabase/admin";
|
|
||||||
|
|
||||||
export async function POST(req: Request) {
|
|
||||||
const startedAt = Date.now();
|
|
||||||
|
|
||||||
try {
|
|
||||||
const secret = req.headers.get("x-cron-secret");
|
|
||||||
if (!env.cronSecret || !secret || secret !== env.cronSecret) {
|
|
||||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const supabase = createSupabaseAdminClient() as any;
|
|
||||||
const summary = await runAutoSyncTick(supabase);
|
|
||||||
|
|
||||||
return NextResponse.json({
|
|
||||||
...summary,
|
|
||||||
duration_ms: Date.now() - startedAt,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error("[autosync cron] failed", error);
|
|
||||||
|
|
||||||
return NextResponse.json(
|
|
||||||
{
|
|
||||||
error: "Auto-sync job failed",
|
|
||||||
instances_considered: 0,
|
|
||||||
locks_acquired: 0,
|
|
||||||
succeeded: 0,
|
|
||||||
failed: 0,
|
|
||||||
duration_ms: Date.now() - startedAt,
|
|
||||||
},
|
|
||||||
{ status: 500 },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -5,54 +5,15 @@ import { assertAgencyAdmin, getRouteAgencyContextOrThrow } from "@/lib/agency";
|
|||||||
import { assertRateLimit } from "@/lib/api/rate-limit";
|
import { assertRateLimit } from "@/lib/api/rate-limit";
|
||||||
import { assertSameOrigin } from "@/lib/api/security";
|
import { assertSameOrigin } from "@/lib/api/security";
|
||||||
import {
|
import {
|
||||||
parseSubscriptionStatusDetailsFromInfo,
|
suspendPleskSubscription,
|
||||||
pleskCliCall,
|
unsuspendPleskSubscription,
|
||||||
} from "@/lib/plesk/client";
|
} from "@/lib/plesk/client";
|
||||||
import { createSupabaseRouteClient } from "@/lib/supabase/route";
|
import { createSupabaseRouteClient } from "@/lib/supabase/route";
|
||||||
|
|
||||||
const actionSchema = z.object({
|
const actionSchema = z.object({
|
||||||
action: z.enum(["suspend", "unsuspend"]),
|
action: z.enum(["suspend", "unsuspend"]),
|
||||||
subscription_id: z.string().uuid().optional(),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const LOG_EXCERPT_LIMIT = 500;
|
|
||||||
|
|
||||||
const DOMAIN_ACTION_EVENTS = {
|
|
||||||
suspend: {
|
|
||||||
requested: "domain_suspend_requested",
|
|
||||||
succeeded: "domain_suspend_succeeded",
|
|
||||||
failed: "domain_suspend_failed",
|
|
||||||
},
|
|
||||||
unsuspend: {
|
|
||||||
requested: "domain_unsuspend_requested",
|
|
||||||
succeeded: "domain_unsuspend_succeeded",
|
|
||||||
failed: "domain_unsuspend_failed",
|
|
||||||
},
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
function excerpt(value: string | null | undefined) {
|
|
||||||
if (!value) return null;
|
|
||||||
const trimmed = value.trim();
|
|
||||||
if (!trimmed) return null;
|
|
||||||
return trimmed.length > LOG_EXCERPT_LIMIT
|
|
||||||
? `${trimmed.slice(0, LOG_EXCERPT_LIMIT)}…`
|
|
||||||
: trimmed;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function insertActionLogBestEffort(
|
|
||||||
supabase: any,
|
|
||||||
payload: Record<string, unknown>,
|
|
||||||
) {
|
|
||||||
try {
|
|
||||||
const { error } = await supabase.from("actions_log").insert(payload);
|
|
||||||
if (error) {
|
|
||||||
console.error("[actions_log] insert failed", error.message);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error("[actions_log] insert threw", error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function POST(
|
export async function POST(
|
||||||
req: Request,
|
req: Request,
|
||||||
{ params }: { params: { id: string } },
|
{ params }: { params: { id: string } },
|
||||||
@@ -61,13 +22,8 @@ export async function POST(
|
|||||||
let context: Awaited<ReturnType<typeof getRouteAgencyContextOrThrow>> | null =
|
let context: Awaited<ReturnType<typeof getRouteAgencyContextOrThrow>> | null =
|
||||||
null;
|
null;
|
||||||
let domain: { id: string; subscription_id: string | null } | null = null;
|
let domain: { id: string; subscription_id: string | null } | null = null;
|
||||||
let subscription: {
|
let subscription: { id: string; plesk_subscription_id: string } | null = null;
|
||||||
id: string;
|
|
||||||
plesk_subscription_id: string;
|
|
||||||
plesk_instance_id: string;
|
|
||||||
} | null = null;
|
|
||||||
let requestedAction: "suspend" | "unsuspend" | null = null;
|
let requestedAction: "suspend" | "unsuspend" | null = null;
|
||||||
const startedAt = Date.now();
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
assertSameOrigin(req);
|
assertSameOrigin(req);
|
||||||
@@ -76,8 +32,7 @@ export async function POST(
|
|||||||
assertAgencyAdmin(context);
|
assertAgencyAdmin(context);
|
||||||
assertRateLimit(`plesk-domain-action:${context.userId}`, 10, 60_000);
|
assertRateLimit(`plesk-domain-action:${context.userId}`, 10, 60_000);
|
||||||
|
|
||||||
const payload = actionSchema.parse(await req.json());
|
const { action } = actionSchema.parse(await req.json());
|
||||||
const { action } = payload;
|
|
||||||
requestedAction = action;
|
requestedAction = action;
|
||||||
|
|
||||||
const { data: domainRow, error: domainError } = await supabase
|
const { data: domainRow, error: domainError } = await supabase
|
||||||
@@ -91,23 +46,21 @@ export async function POST(
|
|||||||
throw new Error("Domain not found");
|
throw new Error("Domain not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
const resolvedSubscriptionId =
|
|
||||||
payload.subscription_id ??
|
|
||||||
(domainRow.subscription_id ? String(domainRow.subscription_id) : null);
|
|
||||||
|
|
||||||
domain = {
|
domain = {
|
||||||
id: String(domainRow.id),
|
id: String(domainRow.id),
|
||||||
subscription_id: resolvedSubscriptionId,
|
subscription_id: domainRow.subscription_id
|
||||||
|
? String(domainRow.subscription_id)
|
||||||
|
: null,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!resolvedSubscriptionId) {
|
if (!domain.subscription_id) {
|
||||||
throw new Error("Domain is not linked to a subscription");
|
throw new Error("Domain is not linked to a subscription");
|
||||||
}
|
}
|
||||||
|
|
||||||
const { data: subscriptionRow, error: subscriptionError } = await supabase
|
const { data: subscriptionRow, error: subscriptionError } = await supabase
|
||||||
.from("plesk_subscriptions")
|
.from("plesk_subscriptions")
|
||||||
.select("id, plesk_subscription_id, plesk_instance_id")
|
.select("id, plesk_subscription_id, plesk_instance_id")
|
||||||
.eq("id", resolvedSubscriptionId)
|
.eq("id", domain.subscription_id)
|
||||||
.eq("agency_id", context.agencyId)
|
.eq("agency_id", context.agencyId)
|
||||||
.single();
|
.single();
|
||||||
|
|
||||||
@@ -118,7 +71,6 @@ export async function POST(
|
|||||||
subscription = {
|
subscription = {
|
||||||
id: String(subscriptionRow.id),
|
id: String(subscriptionRow.id),
|
||||||
plesk_subscription_id: String(subscriptionRow.plesk_subscription_id),
|
plesk_subscription_id: String(subscriptionRow.plesk_subscription_id),
|
||||||
plesk_instance_id: String(subscriptionRow.plesk_instance_id),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const { data: instance, error: instanceError } = await supabase
|
const { data: instance, error: instanceError } = await supabase
|
||||||
@@ -138,117 +90,29 @@ export async function POST(
|
|||||||
encryptedSecret: instance.encrypted_secret,
|
encryptedSecret: instance.encrypted_secret,
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
const domainIdentifier = subscription.plesk_subscription_id;
|
if (action === "suspend") {
|
||||||
const siteArgs =
|
await suspendPleskSubscription(
|
||||||
action === "suspend"
|
connection,
|
||||||
? ["--suspend", domainIdentifier]
|
subscription.plesk_subscription_id,
|
||||||
: ["--on", domainIdentifier];
|
);
|
||||||
|
} else {
|
||||||
await insertActionLogBestEffort(supabase, {
|
await unsuspendPleskSubscription(
|
||||||
agency_id: context.agencyId,
|
connection,
|
||||||
actor_user_id: context.userId,
|
subscription.plesk_subscription_id,
|
||||||
target_type: "plesk_domain",
|
|
||||||
target_id: domain.id,
|
|
||||||
action: DOMAIN_ACTION_EVENTS[action].requested,
|
|
||||||
status: "pending",
|
|
||||||
metadata: {
|
|
||||||
domain_id: domain.id,
|
|
||||||
subscription_id: subscription.id,
|
|
||||||
plesk_instance_id: subscription.plesk_instance_id,
|
|
||||||
plesk_subscription_id: subscription.plesk_subscription_id,
|
|
||||||
cli_command: "site",
|
|
||||||
cli_args: siteArgs,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const siteResult = await pleskCliCall(connection, "site", siteArgs);
|
|
||||||
|
|
||||||
const fallbackStatus = action === "suspend" ? "suspended" : "active";
|
|
||||||
let refreshedStatus = fallbackStatus;
|
|
||||||
let refreshedStatusRaw: string | null = null;
|
|
||||||
let refreshErrorMessage: string | null = null;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const infoResult = await pleskCliCall(connection, "subscription", [
|
|
||||||
"--info",
|
|
||||||
domainIdentifier,
|
|
||||||
]);
|
|
||||||
|
|
||||||
const parsed = parseSubscriptionStatusDetailsFromInfo(
|
|
||||||
infoResult.stdout ?? "",
|
|
||||||
);
|
);
|
||||||
refreshedStatus = parsed.status;
|
|
||||||
refreshedStatusRaw = parsed.statusRaw;
|
|
||||||
|
|
||||||
if (
|
|
||||||
action === "unsuspend" &&
|
|
||||||
refreshedStatus === "suspended" &&
|
|
||||||
(refreshedStatusRaw ?? "").toLowerCase().includes("subscriber")
|
|
||||||
) {
|
|
||||||
throw new Error(
|
|
||||||
"Domain remains suspended because its subscriber/customer account is suspended.",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} catch (refreshError) {
|
|
||||||
refreshErrorMessage =
|
|
||||||
refreshError instanceof Error
|
|
||||||
? refreshError.message.slice(0, 1000)
|
|
||||||
: "subscription_status_refresh_failed";
|
|
||||||
|
|
||||||
await insertActionLogBestEffort(supabase, {
|
|
||||||
agency_id: context.agencyId,
|
|
||||||
actor_user_id: context.userId,
|
|
||||||
target_type: "plesk_subscription",
|
|
||||||
target_id: subscription.id,
|
|
||||||
action: "subscription_status_refresh_failed",
|
|
||||||
status: "failed",
|
|
||||||
error_message: refreshErrorMessage,
|
|
||||||
metadata: {
|
|
||||||
subscription_id: subscription.id,
|
|
||||||
plesk_subscription_id: subscription.plesk_subscription_id,
|
|
||||||
plesk_instance_id: subscription.plesk_instance_id,
|
|
||||||
source: "domain_action",
|
|
||||||
domain_id: domain.id,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await supabase
|
await supabase.from("actions_log").insert({
|
||||||
.from("plesk_subscriptions")
|
|
||||||
.update({
|
|
||||||
status: refreshedStatus,
|
|
||||||
status_raw: refreshedStatusRaw,
|
|
||||||
last_status_sync_at: new Date().toISOString(),
|
|
||||||
})
|
|
||||||
.eq("id", subscription.id)
|
|
||||||
.eq("agency_id", context.agencyId);
|
|
||||||
|
|
||||||
await supabase
|
|
||||||
.from("plesk_domains")
|
|
||||||
.update({ status: refreshedStatus })
|
|
||||||
.eq("agency_id", context.agencyId)
|
|
||||||
.eq("subscription_id", subscription.id);
|
|
||||||
|
|
||||||
await insertActionLogBestEffort(supabase, {
|
|
||||||
agency_id: context.agencyId,
|
agency_id: context.agencyId,
|
||||||
actor_user_id: context.userId,
|
actor_user_id: context.userId,
|
||||||
target_type: "plesk_domain",
|
target_type: "plesk_domain",
|
||||||
target_id: domain.id,
|
target_id: domain.id,
|
||||||
action: DOMAIN_ACTION_EVENTS[action].succeeded,
|
action: `domain_${action}`,
|
||||||
status: "success",
|
status: "success",
|
||||||
metadata: {
|
metadata: {
|
||||||
duration_ms: Date.now() - startedAt,
|
|
||||||
domain_id: domain.id,
|
domain_id: domain.id,
|
||||||
subscription_id: subscription.id,
|
subscription_id: subscription.id,
|
||||||
plesk_instance_id: subscription.plesk_instance_id,
|
|
||||||
plesk_subscription_id: subscription.plesk_subscription_id,
|
plesk_subscription_id: subscription.plesk_subscription_id,
|
||||||
cli_command: "site",
|
|
||||||
cli_args: siteArgs,
|
|
||||||
cli_exit_code: siteResult.code,
|
|
||||||
cli_stdout_excerpt: excerpt(siteResult.stdout),
|
|
||||||
cli_stderr_excerpt: excerpt(siteResult.stderr),
|
|
||||||
refreshed_status: refreshedStatus,
|
|
||||||
refresh_error: refreshErrorMessage,
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -257,41 +121,20 @@ export async function POST(
|
|||||||
if (context && domain) {
|
if (context && domain) {
|
||||||
const message =
|
const message =
|
||||||
error instanceof Error ? error.message : "Domain action failed";
|
error instanceof Error ? error.message : "Domain action failed";
|
||||||
if (requestedAction) {
|
await supabase.from("actions_log").insert({
|
||||||
await insertActionLogBestEffort(supabase, {
|
agency_id: context.agencyId,
|
||||||
agency_id: context.agencyId,
|
actor_user_id: context.userId,
|
||||||
actor_user_id: context.userId,
|
target_type: "plesk_domain",
|
||||||
target_type: "plesk_domain",
|
target_id: domain.id,
|
||||||
target_id: domain.id,
|
action: requestedAction ? `domain_${requestedAction}` : "domain_action",
|
||||||
action: DOMAIN_ACTION_EVENTS[requestedAction].failed,
|
status: "failed",
|
||||||
status: "failed",
|
error_message: message,
|
||||||
error_message: message,
|
metadata: {
|
||||||
metadata: {
|
domain_id: domain.id,
|
||||||
duration_ms: Date.now() - startedAt,
|
subscription_id: subscription?.id ?? domain.subscription_id,
|
||||||
domain_id: domain.id,
|
plesk_subscription_id: subscription?.plesk_subscription_id ?? null,
|
||||||
subscription_id: subscription?.id ?? domain.subscription_id,
|
},
|
||||||
plesk_instance_id: subscription?.plesk_instance_id ?? null,
|
});
|
||||||
plesk_subscription_id: subscription?.plesk_subscription_id ?? null,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
await insertActionLogBestEffort(supabase, {
|
|
||||||
agency_id: context.agencyId,
|
|
||||||
actor_user_id: context.userId,
|
|
||||||
target_type: "plesk_domain",
|
|
||||||
target_id: domain.id,
|
|
||||||
action: "domain_action_failed",
|
|
||||||
status: "failed",
|
|
||||||
error_message: message,
|
|
||||||
metadata: {
|
|
||||||
duration_ms: Date.now() - startedAt,
|
|
||||||
domain_id: domain.id,
|
|
||||||
subscription_id: subscription?.id ?? domain.subscription_id,
|
|
||||||
plesk_instance_id: subscription?.plesk_instance_id ?? null,
|
|
||||||
plesk_subscription_id: subscription?.plesk_subscription_id ?? null,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
|
|||||||
@@ -1,87 +0,0 @@
|
|||||||
import { NextResponse } from "next/server";
|
|
||||||
import { z } from "zod";
|
|
||||||
|
|
||||||
import { assertAgencyAdmin, getRouteAgencyContextOrThrow } from "@/lib/agency";
|
|
||||||
import { assertRateLimit } from "@/lib/api/rate-limit";
|
|
||||||
import { assertSameOrigin } from "@/lib/api/security";
|
|
||||||
import { createSupabaseRouteClient } from "@/lib/supabase/route";
|
|
||||||
|
|
||||||
const autosyncSchema = z.object({
|
|
||||||
auto_sync_enabled: z.boolean(),
|
|
||||||
auto_sync_frequency_minutes: z.number().int().min(5).max(10080).optional(),
|
|
||||||
});
|
|
||||||
|
|
||||||
export async function POST(
|
|
||||||
req: Request,
|
|
||||||
{ params }: { params: { id: string } },
|
|
||||||
) {
|
|
||||||
try {
|
|
||||||
assertSameOrigin(req);
|
|
||||||
|
|
||||||
const context = await getRouteAgencyContextOrThrow();
|
|
||||||
assertAgencyAdmin(context);
|
|
||||||
assertRateLimit(`plesk-autosync-settings:${context.userId}`, 20, 60_000);
|
|
||||||
|
|
||||||
const input = autosyncSchema.parse(await req.json());
|
|
||||||
const frequency = input.auto_sync_frequency_minutes ?? 60;
|
|
||||||
const nowIso = new Date().toISOString();
|
|
||||||
const nextAtIso = new Date(
|
|
||||||
Date.now() + frequency * 60 * 1000,
|
|
||||||
).toISOString();
|
|
||||||
|
|
||||||
const supabase = createSupabaseRouteClient() as any;
|
|
||||||
|
|
||||||
const updates = {
|
|
||||||
auto_sync_enabled: input.auto_sync_enabled,
|
|
||||||
auto_sync_frequency_minutes: frequency,
|
|
||||||
next_auto_sync_at: input.auto_sync_enabled ? nextAtIso : null,
|
|
||||||
auto_sync_lock_until: null,
|
|
||||||
auto_sync_lock_token: null,
|
|
||||||
last_auto_sync_at: input.auto_sync_enabled ? undefined : null,
|
|
||||||
} as Record<string, unknown>;
|
|
||||||
|
|
||||||
const { data: instance, error } = await supabase
|
|
||||||
.from("plesk_instances")
|
|
||||||
.update(updates)
|
|
||||||
.eq("id", params.id)
|
|
||||||
.eq("agency_id", context.agencyId)
|
|
||||||
.select(
|
|
||||||
"id, auto_sync_enabled, auto_sync_frequency_minutes, last_auto_sync_at, next_auto_sync_at, auto_sync_lock_until",
|
|
||||||
)
|
|
||||||
.single();
|
|
||||||
|
|
||||||
if (error || !instance) {
|
|
||||||
throw new Error(error?.message ?? "Plesk instance not found");
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
await supabase.from("actions_log").insert({
|
|
||||||
agency_id: context.agencyId,
|
|
||||||
actor_user_id: context.userId,
|
|
||||||
target_type: "plesk_instance",
|
|
||||||
target_id: params.id,
|
|
||||||
action: "autosync_settings_updated",
|
|
||||||
status: "success",
|
|
||||||
metadata: {
|
|
||||||
auto_sync_enabled: input.auto_sync_enabled,
|
|
||||||
auto_sync_frequency_minutes: frequency,
|
|
||||||
updated_at: nowIso,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} catch {
|
|
||||||
// best effort logging
|
|
||||||
}
|
|
||||||
|
|
||||||
return NextResponse.json({ instance });
|
|
||||||
} catch (error) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{
|
|
||||||
error:
|
|
||||||
error instanceof Error
|
|
||||||
? error.message
|
|
||||||
: "Failed to update auto-sync settings",
|
|
||||||
},
|
|
||||||
{ status: 400 },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
import { NextResponse } from "next/server";
|
|
||||||
|
|
||||||
import { assertAgencyAdmin, getRouteAgencyContextOrThrow } from "@/lib/agency";
|
|
||||||
import { assertRateLimit } from "@/lib/api/rate-limit";
|
|
||||||
import { assertSameOrigin } from "@/lib/api/security";
|
|
||||||
import { backfillDomainSubscriptionLinks } from "@/lib/plesk/sync";
|
|
||||||
import { createSupabaseRouteClient } from "@/lib/supabase/route";
|
|
||||||
|
|
||||||
export async function POST(
|
|
||||||
req: Request,
|
|
||||||
{ params }: { params: { id: string } },
|
|
||||||
) {
|
|
||||||
try {
|
|
||||||
assertSameOrigin(req);
|
|
||||||
|
|
||||||
const context = await getRouteAgencyContextOrThrow();
|
|
||||||
assertAgencyAdmin(context);
|
|
||||||
assertRateLimit(`plesk-backfill-links:${context.userId}`, 5, 60_000);
|
|
||||||
|
|
||||||
const supabase = createSupabaseRouteClient() as any;
|
|
||||||
|
|
||||||
const { data: instance, error: instanceError } = await supabase
|
|
||||||
.from("plesk_instances")
|
|
||||||
.select("id")
|
|
||||||
.eq("id", params.id)
|
|
||||||
.eq("agency_id", context.agencyId)
|
|
||||||
.single();
|
|
||||||
|
|
||||||
if (instanceError || !instance) {
|
|
||||||
throw new Error("Plesk instance not found");
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = await backfillDomainSubscriptionLinks(supabase, {
|
|
||||||
agencyId: context.agencyId,
|
|
||||||
instanceId: params.id,
|
|
||||||
actorUserId: context.userId,
|
|
||||||
});
|
|
||||||
|
|
||||||
return NextResponse.json({ ok: true, ...result });
|
|
||||||
} catch (error) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{
|
|
||||||
error:
|
|
||||||
error instanceof Error
|
|
||||||
? error.message
|
|
||||||
: "Backfill domain links failed",
|
|
||||||
},
|
|
||||||
{ status: 400 },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -5,8 +5,6 @@ import { assertAgencyAdmin, getRouteAgencyContextOrThrow } from "@/lib/agency";
|
|||||||
import { assertRateLimit } from "@/lib/api/rate-limit";
|
import { assertRateLimit } from "@/lib/api/rate-limit";
|
||||||
import { assertSameOrigin } from "@/lib/api/security";
|
import { assertSameOrigin } from "@/lib/api/security";
|
||||||
import {
|
import {
|
||||||
parseSubscriptionStatusDetailsFromInfo,
|
|
||||||
pleskCliCall,
|
|
||||||
suspendPleskSubscription,
|
suspendPleskSubscription,
|
||||||
unsuspendPleskSubscription,
|
unsuspendPleskSubscription,
|
||||||
} from "@/lib/plesk/client";
|
} from "@/lib/plesk/client";
|
||||||
@@ -16,44 +14,6 @@ const actionSchema = z.object({
|
|||||||
action: z.enum(["suspend", "unsuspend"]),
|
action: z.enum(["suspend", "unsuspend"]),
|
||||||
});
|
});
|
||||||
|
|
||||||
const LOG_EXCERPT_LIMIT = 500;
|
|
||||||
|
|
||||||
const SUBSCRIPTION_ACTION_EVENTS = {
|
|
||||||
suspend: {
|
|
||||||
requested: "subscription_suspend_requested",
|
|
||||||
succeeded: "subscription_suspend_succeeded",
|
|
||||||
failed: "subscription_suspend_failed",
|
|
||||||
},
|
|
||||||
unsuspend: {
|
|
||||||
requested: "subscription_unsuspend_requested",
|
|
||||||
succeeded: "subscription_unsuspend_succeeded",
|
|
||||||
failed: "subscription_unsuspend_failed",
|
|
||||||
},
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
function excerpt(value: string | null | undefined) {
|
|
||||||
if (!value) return null;
|
|
||||||
const trimmed = value.trim();
|
|
||||||
if (!trimmed) return null;
|
|
||||||
return trimmed.length > LOG_EXCERPT_LIMIT
|
|
||||||
? `${trimmed.slice(0, LOG_EXCERPT_LIMIT)}…`
|
|
||||||
: trimmed;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function insertActionLogBestEffort(
|
|
||||||
supabase: any,
|
|
||||||
payload: Record<string, unknown>,
|
|
||||||
) {
|
|
||||||
try {
|
|
||||||
const { error } = await supabase.from("actions_log").insert(payload);
|
|
||||||
if (error) {
|
|
||||||
console.error("[actions_log] insert failed", error.message);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error("[actions_log] insert threw", error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function POST(
|
export async function POST(
|
||||||
req: Request,
|
req: Request,
|
||||||
{ params }: { params: { id: string } },
|
{ params }: { params: { id: string } },
|
||||||
@@ -67,7 +27,6 @@ export async function POST(
|
|||||||
plesk_subscription_id: string;
|
plesk_subscription_id: string;
|
||||||
plesk_instance_id: string;
|
plesk_instance_id: string;
|
||||||
} | null = null;
|
} | null = null;
|
||||||
const startedAt = Date.now();
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
assertSameOrigin(req);
|
assertSameOrigin(req);
|
||||||
@@ -109,153 +68,58 @@ export async function POST(
|
|||||||
encryptedSecret: instance.encrypted_secret,
|
encryptedSecret: instance.encrypted_secret,
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
const cliArgs =
|
if (payload.action === "suspend") {
|
||||||
payload.action === "suspend"
|
await suspendPleskSubscription(
|
||||||
? ["--webspace-off", subscription.plesk_subscription_id]
|
connection,
|
||||||
: ["--unsuspend", subscription.plesk_subscription_id];
|
subscription.plesk_subscription_id,
|
||||||
|
);
|
||||||
await insertActionLogBestEffort(supabase, {
|
} else {
|
||||||
agency_id: context.agencyId,
|
await unsuspendPleskSubscription(
|
||||||
actor_user_id: context.userId,
|
connection,
|
||||||
target_type: "plesk_subscription",
|
|
||||||
target_id: subscription.id,
|
|
||||||
action: SUBSCRIPTION_ACTION_EVENTS[payload.action].requested,
|
|
||||||
status: "pending",
|
|
||||||
metadata: {
|
|
||||||
subscription_id: subscription.id,
|
|
||||||
plesk_instance_id: subscription.plesk_instance_id,
|
|
||||||
plesk_subscription_id: subscription.plesk_subscription_id,
|
|
||||||
cli_command: "subscription",
|
|
||||||
cli_args: cliArgs,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const actionCliResult =
|
|
||||||
payload.action === "suspend"
|
|
||||||
? await suspendPleskSubscription(
|
|
||||||
connection,
|
|
||||||
subscription.plesk_subscription_id,
|
|
||||||
)
|
|
||||||
: await unsuspendPleskSubscription(
|
|
||||||
connection,
|
|
||||||
subscription.plesk_subscription_id,
|
|
||||||
);
|
|
||||||
|
|
||||||
const fallbackStatus =
|
|
||||||
payload.action === "suspend" ? "suspended" : "active";
|
|
||||||
let refreshedStatus = fallbackStatus;
|
|
||||||
let refreshedStatusRaw: string | null = null;
|
|
||||||
let refreshErrorMessage: string | null = null;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const infoResult = await pleskCliCall(connection, "subscription", [
|
|
||||||
"--info",
|
|
||||||
subscription.plesk_subscription_id,
|
subscription.plesk_subscription_id,
|
||||||
]);
|
|
||||||
const parsed = parseSubscriptionStatusDetailsFromInfo(
|
|
||||||
infoResult.stdout ?? "",
|
|
||||||
);
|
);
|
||||||
refreshedStatus = parsed.status;
|
|
||||||
refreshedStatusRaw = parsed.statusRaw;
|
|
||||||
} catch (refreshError) {
|
|
||||||
refreshErrorMessage =
|
|
||||||
refreshError instanceof Error
|
|
||||||
? refreshError.message.slice(0, 1000)
|
|
||||||
: "subscription_status_refresh_failed";
|
|
||||||
|
|
||||||
await insertActionLogBestEffort(supabase, {
|
|
||||||
agency_id: context.agencyId,
|
|
||||||
actor_user_id: context.userId,
|
|
||||||
target_type: "plesk_subscription",
|
|
||||||
target_id: subscription.id,
|
|
||||||
action: "subscription_status_refresh_failed",
|
|
||||||
status: "failed",
|
|
||||||
error_message: refreshErrorMessage,
|
|
||||||
metadata: {
|
|
||||||
subscription_id: subscription.id,
|
|
||||||
plesk_subscription_id: subscription.plesk_subscription_id,
|
|
||||||
plesk_instance_id: subscription.plesk_instance_id,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const newStatus = payload.action === "suspend" ? "suspended" : "active";
|
||||||
const { error: updateError } = await supabase
|
const { error: updateError } = await supabase
|
||||||
.from("plesk_subscriptions")
|
.from("plesk_subscriptions")
|
||||||
.update({
|
.update({ status: newStatus })
|
||||||
status: refreshedStatus,
|
|
||||||
status_raw: refreshedStatusRaw,
|
|
||||||
last_status_sync_at: new Date().toISOString(),
|
|
||||||
})
|
|
||||||
.eq("id", subscription.id);
|
.eq("id", subscription.id);
|
||||||
|
|
||||||
await supabase
|
await supabase.from("actions_log").insert({
|
||||||
.from("plesk_domains")
|
|
||||||
.update({ status: refreshedStatus })
|
|
||||||
.eq("agency_id", context.agencyId)
|
|
||||||
.eq("subscription_id", subscription.id);
|
|
||||||
|
|
||||||
await insertActionLogBestEffort(supabase, {
|
|
||||||
agency_id: context.agencyId,
|
agency_id: context.agencyId,
|
||||||
actor_user_id: context.userId,
|
actor_user_id: context.userId,
|
||||||
target_type: "plesk_subscription",
|
target_type: "plesk_subscription",
|
||||||
target_id: subscription.id,
|
target_id: subscription.id,
|
||||||
action: SUBSCRIPTION_ACTION_EVENTS[payload.action].succeeded,
|
action: payload.action,
|
||||||
status: "success",
|
status: "success",
|
||||||
metadata: {
|
metadata: {
|
||||||
duration_ms: Date.now() - startedAt,
|
|
||||||
cli_command: "subscription",
|
|
||||||
cli_args: cliArgs,
|
|
||||||
plesk_subscription_id: subscription.plesk_subscription_id,
|
plesk_subscription_id: subscription.plesk_subscription_id,
|
||||||
refreshed_status: refreshedStatus,
|
|
||||||
refresh_error: refreshErrorMessage,
|
|
||||||
cli_exit_code: actionCliResult.code,
|
|
||||||
cli_stdout_excerpt: excerpt(actionCliResult.stdout),
|
|
||||||
cli_stderr_excerpt: excerpt(actionCliResult.stderr),
|
|
||||||
db_status_update_error: updateError?.message ?? null,
|
db_status_update_error: updateError?.message ?? null,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
ok: true,
|
ok: true,
|
||||||
status: refreshedStatus,
|
status: newStatus,
|
||||||
dbStatusUpdated: !updateError,
|
dbStatusUpdated: !updateError,
|
||||||
refreshError: refreshErrorMessage,
|
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (supabase && context && subscription) {
|
if (supabase && context && subscription) {
|
||||||
const message =
|
const message =
|
||||||
error instanceof Error ? error.message : "Subscription action failed";
|
error instanceof Error ? error.message : "Subscription action failed";
|
||||||
if (requestedAction) {
|
await supabase.from("actions_log").insert({
|
||||||
await insertActionLogBestEffort(supabase, {
|
agency_id: context.agencyId,
|
||||||
agency_id: context.agencyId,
|
actor_user_id: context.userId,
|
||||||
actor_user_id: context.userId,
|
target_type: "plesk_subscription",
|
||||||
target_type: "plesk_subscription",
|
target_id: subscription.id,
|
||||||
target_id: subscription.id,
|
action: requestedAction ?? "subscription_action",
|
||||||
action: SUBSCRIPTION_ACTION_EVENTS[requestedAction].failed,
|
status: "failed",
|
||||||
status: "failed",
|
error_message: message,
|
||||||
error_message: message,
|
metadata: {
|
||||||
metadata: {
|
plesk_subscription_id: subscription.plesk_subscription_id,
|
||||||
duration_ms: Date.now() - startedAt,
|
},
|
||||||
plesk_subscription_id: subscription.plesk_subscription_id,
|
});
|
||||||
plesk_instance_id: subscription.plesk_instance_id,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
await insertActionLogBestEffort(supabase, {
|
|
||||||
agency_id: context.agencyId,
|
|
||||||
actor_user_id: context.userId,
|
|
||||||
target_type: "plesk_subscription",
|
|
||||||
target_id: subscription.id,
|
|
||||||
action: "subscription_action_failed",
|
|
||||||
status: "failed",
|
|
||||||
error_message: message,
|
|
||||||
metadata: {
|
|
||||||
duration_ms: Date.now() - startedAt,
|
|
||||||
plesk_subscription_id: subscription.plesk_subscription_id,
|
|
||||||
plesk_instance_id: subscription.plesk_instance_id,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
|
|||||||
@@ -17,26 +17,6 @@ type ActionLogSummary = Pick<
|
|||||||
"target_id" | "status" | "action" | "created_at" | "error_message"
|
"target_id" | "status" | "action" | "created_at" | "error_message"
|
||||||
>;
|
>;
|
||||||
|
|
||||||
function normalizeDomainLike(value: string) {
|
|
||||||
return value.trim().toLowerCase().replace(/\.$/, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
function findBestSuffixStatusMatch(
|
|
||||||
normalizedDomain: string,
|
|
||||||
candidates: Array<{ normalizedName: string; status: string | null }>,
|
|
||||||
) {
|
|
||||||
let best: { normalizedName: string; status: string | null } | null = null;
|
|
||||||
|
|
||||||
for (const candidate of candidates) {
|
|
||||||
if (!normalizedDomain.endsWith(`.${candidate.normalizedName}`)) continue;
|
|
||||||
if (!best || candidate.normalizedName.length > best.normalizedName.length) {
|
|
||||||
best = candidate;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return best?.status ?? null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default async function DashboardPage() {
|
export default async function DashboardPage() {
|
||||||
const context = await getServerAgencyContextOrRedirect();
|
const context = await getServerAgencyContextOrRedirect();
|
||||||
const supabase = createSupabaseServerClient() as any;
|
const supabase = createSupabaseServerClient() as any;
|
||||||
@@ -57,7 +37,7 @@ export default async function DashboardPage() {
|
|||||||
supabase
|
supabase
|
||||||
.from("plesk_instances")
|
.from("plesk_instances")
|
||||||
.select(
|
.select(
|
||||||
"id, name, base_url, auth_type, status, error_message, last_connected_at, last_sync_at, last_sync_status, last_sync_error, last_sync_subscriptions, last_sync_domains, auto_sync_enabled, auto_sync_frequency_minutes, last_auto_sync_at, next_auto_sync_at, auto_sync_lock_until",
|
"id, name, base_url, auth_type, status, error_message, last_connected_at, last_sync_at, last_sync_status, last_sync_error, last_sync_subscriptions, last_sync_domains",
|
||||||
)
|
)
|
||||||
.eq("agency_id", context.agencyId)
|
.eq("agency_id", context.agencyId)
|
||||||
.order("created_at", { ascending: false }),
|
.order("created_at", { ascending: false }),
|
||||||
@@ -70,7 +50,7 @@ export default async function DashboardPage() {
|
|||||||
supabase
|
supabase
|
||||||
.from("plesk_domains")
|
.from("plesk_domains")
|
||||||
.select(
|
.select(
|
||||||
"id, plesk_instance_id, subscription_id, external_subscription_id, status, domain_name, hosting_type, source_created_at, aliases_count, updated_at",
|
"id, plesk_instance_id, subscription_id, domain_name, status, hosting_type, source_created_at, aliases_count, updated_at",
|
||||||
)
|
)
|
||||||
.eq("agency_id", context.agencyId)
|
.eq("agency_id", context.agencyId)
|
||||||
.order("updated_at", { ascending: false })
|
.order("updated_at", { ascending: false })
|
||||||
@@ -104,11 +84,6 @@ export default async function DashboardPage() {
|
|||||||
last_sync_error: string | null;
|
last_sync_error: string | null;
|
||||||
last_sync_subscriptions: number;
|
last_sync_subscriptions: number;
|
||||||
last_sync_domains: number;
|
last_sync_domains: number;
|
||||||
auto_sync_enabled: boolean;
|
|
||||||
auto_sync_frequency_minutes: number;
|
|
||||||
last_auto_sync_at: string | null;
|
|
||||||
next_auto_sync_at: string | null;
|
|
||||||
auto_sync_lock_until: string | null;
|
|
||||||
}> | null;
|
}> | null;
|
||||||
error: { message: string } | null;
|
error: { message: string } | null;
|
||||||
},
|
},
|
||||||
@@ -126,7 +101,6 @@ export default async function DashboardPage() {
|
|||||||
id: string;
|
id: string;
|
||||||
plesk_instance_id: string;
|
plesk_instance_id: string;
|
||||||
subscription_id: string | null;
|
subscription_id: string | null;
|
||||||
external_subscription_id: string | null;
|
|
||||||
domain_name: string;
|
domain_name: string;
|
||||||
status: string | null;
|
status: string | null;
|
||||||
hosting_type: string | null;
|
hosting_type: string | null;
|
||||||
@@ -139,82 +113,6 @@ export default async function DashboardPage() {
|
|||||||
{ data: ActionLogSummary[] | null },
|
{ data: ActionLogSummary[] | null },
|
||||||
];
|
];
|
||||||
|
|
||||||
const domainInstanceIds = Array.from(
|
|
||||||
new Set((domains ?? []).map((domain) => domain.plesk_instance_id)),
|
|
||||||
);
|
|
||||||
|
|
||||||
const { data: domainSubscriptions } =
|
|
||||||
domainInstanceIds.length > 0
|
|
||||||
? await supabase
|
|
||||||
.from("plesk_subscriptions")
|
|
||||||
.select("id, plesk_instance_id, plesk_subscription_id, name, status")
|
|
||||||
.eq("agency_id", context.agencyId)
|
|
||||||
.in("plesk_instance_id", domainInstanceIds)
|
|
||||||
: { data: [] };
|
|
||||||
|
|
||||||
const subscriptionStatusById = new Map<string, string | null>(
|
|
||||||
(domainSubscriptions ?? []).map((subscription: any) => [
|
|
||||||
String(subscription.id),
|
|
||||||
subscription?.status ? String(subscription.status) : null,
|
|
||||||
]),
|
|
||||||
);
|
|
||||||
|
|
||||||
const subscriptionDisplayNameById = new Map<string, string>(
|
|
||||||
(domainSubscriptions ?? [])
|
|
||||||
.filter((subscription: any) => subscription?.id)
|
|
||||||
.map((subscription: any) => [
|
|
||||||
String(subscription.id),
|
|
||||||
String(
|
|
||||||
subscription?.name ||
|
|
||||||
subscription?.plesk_subscription_id ||
|
|
||||||
subscription?.id,
|
|
||||||
),
|
|
||||||
]),
|
|
||||||
);
|
|
||||||
|
|
||||||
const subscriptionStatusByExternalId = new Map<string, string | null>(
|
|
||||||
(domainSubscriptions ?? [])
|
|
||||||
.filter((subscription: any) =>
|
|
||||||
Boolean(
|
|
||||||
subscription?.plesk_instance_id &&
|
|
||||||
subscription?.plesk_subscription_id,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.map((subscription: any) => [
|
|
||||||
`${String(subscription.plesk_instance_id)}:${String(subscription.plesk_subscription_id)}`,
|
|
||||||
subscription?.status ? String(subscription.status) : null,
|
|
||||||
]),
|
|
||||||
);
|
|
||||||
|
|
||||||
const subscriptionStatusByInstanceAndName = new Map<string, string | null>(
|
|
||||||
(domainSubscriptions ?? [])
|
|
||||||
.filter((subscription: any) =>
|
|
||||||
Boolean(subscription?.plesk_instance_id && subscription?.name),
|
|
||||||
)
|
|
||||||
.map((subscription: any) => [
|
|
||||||
`${String(subscription.plesk_instance_id)}:${normalizeDomainLike(String(subscription.name))}`,
|
|
||||||
subscription?.status ? String(subscription.status) : null,
|
|
||||||
]),
|
|
||||||
);
|
|
||||||
|
|
||||||
const subscriptionStatusNameCandidatesByInstance = new Map<
|
|
||||||
string,
|
|
||||||
Array<{ normalizedName: string; status: string | null }>
|
|
||||||
>();
|
|
||||||
|
|
||||||
for (const subscription of domainSubscriptions ?? []) {
|
|
||||||
if (!subscription?.plesk_instance_id || !subscription?.name) continue;
|
|
||||||
|
|
||||||
const instanceId = String(subscription.plesk_instance_id);
|
|
||||||
const existing =
|
|
||||||
subscriptionStatusNameCandidatesByInstance.get(instanceId) ?? [];
|
|
||||||
existing.push({
|
|
||||||
normalizedName: normalizeDomainLike(String(subscription.name)),
|
|
||||||
status: subscription?.status ? String(subscription.status) : null,
|
|
||||||
});
|
|
||||||
subscriptionStatusNameCandidatesByInstance.set(instanceId, existing);
|
|
||||||
}
|
|
||||||
|
|
||||||
const autoSyncByInstance = new Map<
|
const autoSyncByInstance = new Map<
|
||||||
string,
|
string,
|
||||||
{ status: string; created_at: string; error_message: string | null }
|
{ status: string; created_at: string; error_message: string | null }
|
||||||
@@ -269,39 +167,7 @@ export default async function DashboardPage() {
|
|||||||
<DashboardControls
|
<DashboardControls
|
||||||
instances={instances ?? []}
|
instances={instances ?? []}
|
||||||
subscriptions={subscriptions ?? []}
|
subscriptions={subscriptions ?? []}
|
||||||
domains={(domains ?? []).map((domain) => {
|
domains={domains ?? []}
|
||||||
const joinedStatusByLocalId = domain.subscription_id
|
|
||||||
? subscriptionStatusById.get(domain.subscription_id)
|
|
||||||
: null;
|
|
||||||
const joinedStatusByExternalId = domain.external_subscription_id
|
|
||||||
? subscriptionStatusByExternalId.get(
|
|
||||||
`${domain.plesk_instance_id}:${domain.external_subscription_id}`,
|
|
||||||
)
|
|
||||||
: null;
|
|
||||||
const joinedStatusByName = subscriptionStatusByInstanceAndName.get(
|
|
||||||
`${domain.plesk_instance_id}:${normalizeDomainLike(domain.domain_name)}`,
|
|
||||||
);
|
|
||||||
const joinedStatusBySuffix = findBestSuffixStatusMatch(
|
|
||||||
normalizeDomainLike(domain.domain_name),
|
|
||||||
subscriptionStatusNameCandidatesByInstance.get(
|
|
||||||
domain.plesk_instance_id,
|
|
||||||
) ?? [],
|
|
||||||
);
|
|
||||||
const joinedStatus =
|
|
||||||
joinedStatusByLocalId ??
|
|
||||||
joinedStatusByExternalId ??
|
|
||||||
joinedStatusByName ??
|
|
||||||
joinedStatusBySuffix;
|
|
||||||
|
|
||||||
return {
|
|
||||||
...domain,
|
|
||||||
status: joinedStatus ?? "unknown",
|
|
||||||
subscription_name: domain.subscription_id
|
|
||||||
? (subscriptionDisplayNameById.get(domain.subscription_id) ??
|
|
||||||
null)
|
|
||||||
: null,
|
|
||||||
};
|
|
||||||
})}
|
|
||||||
autoSyncByInstance={Object.fromEntries(autoSyncByInstance.entries())}
|
autoSyncByInstance={Object.fromEntries(autoSyncByInstance.entries())}
|
||||||
/>
|
/>
|
||||||
</main>
|
</main>
|
||||||
|
|||||||
@@ -18,11 +18,6 @@ type Instance = {
|
|||||||
last_sync_error: string | null;
|
last_sync_error: string | null;
|
||||||
last_sync_subscriptions: number;
|
last_sync_subscriptions: number;
|
||||||
last_sync_domains: number;
|
last_sync_domains: number;
|
||||||
auto_sync_enabled: boolean;
|
|
||||||
auto_sync_frequency_minutes: number;
|
|
||||||
last_auto_sync_at: string | null;
|
|
||||||
next_auto_sync_at: string | null;
|
|
||||||
auto_sync_lock_until: string | null;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
type Subscription = {
|
type Subscription = {
|
||||||
@@ -37,7 +32,6 @@ type Domain = {
|
|||||||
id: string;
|
id: string;
|
||||||
plesk_instance_id: string;
|
plesk_instance_id: string;
|
||||||
subscription_id: string | null;
|
subscription_id: string | null;
|
||||||
subscription_name?: string | null;
|
|
||||||
domain_name: string;
|
domain_name: string;
|
||||||
status: string | null;
|
status: string | null;
|
||||||
hosting_type: string | null;
|
hosting_type: string | null;
|
||||||
@@ -78,23 +72,6 @@ function getDomainStatusBadge(status: string | null) {
|
|||||||
return "bg-slate-100 text-slate-600";
|
return "bg-slate-100 text-slate-600";
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatDomainStatusLabel(status: string | null) {
|
|
||||||
const normalized = (status ?? "unknown").toLowerCase();
|
|
||||||
|
|
||||||
if (normalized.includes("suspend")) return "Suspended";
|
|
||||||
if (normalized.includes("disabled")) return "Disabled";
|
|
||||||
if (normalized.includes("expired")) return "Expired";
|
|
||||||
if (
|
|
||||||
normalized.includes("active") ||
|
|
||||||
normalized.includes("ok") ||
|
|
||||||
normalized.includes("enabled")
|
|
||||||
) {
|
|
||||||
return "Active";
|
|
||||||
}
|
|
||||||
|
|
||||||
return "Unknown";
|
|
||||||
}
|
|
||||||
|
|
||||||
function isDomainSuspended(status: string | null) {
|
function isDomainSuspended(status: string | null) {
|
||||||
const normalized = (status ?? "unknown").toLowerCase();
|
const normalized = (status ?? "unknown").toLowerCase();
|
||||||
return normalized.includes("suspend") || normalized.includes("disabled");
|
return normalized.includes("suspend") || normalized.includes("disabled");
|
||||||
@@ -121,7 +98,6 @@ export function DashboardControls({
|
|||||||
domains,
|
domains,
|
||||||
autoSyncByInstance,
|
autoSyncByInstance,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
const autoSyncFrequencyOptions = [15, 30, 60, 180, 360, 1440];
|
|
||||||
const [instanceName, setInstanceName] = useState("");
|
const [instanceName, setInstanceName] = useState("");
|
||||||
const [baseUrl, setBaseUrl] = useState("");
|
const [baseUrl, setBaseUrl] = useState("");
|
||||||
const [authType, setAuthType] = useState<"api_key" | "basic">("api_key");
|
const [authType, setAuthType] = useState<"api_key" | "basic">("api_key");
|
||||||
@@ -245,25 +221,6 @@ export function DashboardControls({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onUpdateAutoSync(
|
|
||||||
instanceId: string,
|
|
||||||
input: { auto_sync_enabled: boolean; auto_sync_frequency_minutes: number },
|
|
||||||
) {
|
|
||||||
setLoading(true);
|
|
||||||
setMessage(null);
|
|
||||||
try {
|
|
||||||
await runRequest(`/api/plesk/instances/${instanceId}/autosync`, input);
|
|
||||||
setMessage("Auto-sync settings updated.");
|
|
||||||
window.location.reload();
|
|
||||||
} catch (error) {
|
|
||||||
setMessage(
|
|
||||||
error instanceof Error ? error.message : "Auto-sync update failed",
|
|
||||||
);
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function onSubscriptionAction() {
|
async function onSubscriptionAction() {
|
||||||
if (!actionSubId) return;
|
if (!actionSubId) return;
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
@@ -282,23 +239,13 @@ export function DashboardControls({
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function onDomainAction(
|
async function onDomainAction(
|
||||||
domain: Domain,
|
domainId: string,
|
||||||
action: "suspend" | "unsuspend",
|
action: "suspend" | "unsuspend",
|
||||||
) {
|
) {
|
||||||
if (!domain.subscription_id) {
|
|
||||||
setMessage(
|
|
||||||
"Domain is not linked to a subscription yet. Run Sync Now (or backfill links) and try again.",
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setMessage(null);
|
setMessage(null);
|
||||||
try {
|
try {
|
||||||
await runRequest(`/api/plesk/domains/${domain.id}/action`, {
|
await runRequest(`/api/plesk/domains/${domainId}/action`, { action });
|
||||||
action,
|
|
||||||
subscription_id: domain.subscription_id,
|
|
||||||
});
|
|
||||||
setMessage("Domain action completed.");
|
setMessage("Domain action completed.");
|
||||||
window.location.reload();
|
window.location.reload();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -495,30 +442,6 @@ export function DashboardControls({
|
|||||||
? formatDateTime(instance.last_connected_at)
|
? formatDateTime(instance.last_connected_at)
|
||||||
: "never"}
|
: "never"}
|
||||||
</p>
|
</p>
|
||||||
<p className="text-xs text-slate-500">
|
|
||||||
Auto-sync:{" "}
|
|
||||||
{instance.auto_sync_enabled ? "Enabled" : "Disabled"}
|
|
||||||
</p>
|
|
||||||
<p className="text-xs text-slate-500">
|
|
||||||
Auto-sync frequency:{" "}
|
|
||||||
{instance.auto_sync_frequency_minutes ?? 60} min
|
|
||||||
</p>
|
|
||||||
<p className="text-xs text-slate-500">
|
|
||||||
Last auto-sync:{" "}
|
|
||||||
{formatDateTime(instance.last_auto_sync_at)}
|
|
||||||
</p>
|
|
||||||
<p className="text-xs text-slate-500">
|
|
||||||
Next auto-sync:{" "}
|
|
||||||
{formatDateTime(instance.next_auto_sync_at)}
|
|
||||||
</p>
|
|
||||||
<p className="text-xs text-slate-500">
|
|
||||||
Lock status:{" "}
|
|
||||||
{instance.auto_sync_lock_until &&
|
|
||||||
new Date(instance.auto_sync_lock_until).getTime() >
|
|
||||||
Date.now()
|
|
||||||
? "Sync in progress"
|
|
||||||
: "Idle"}
|
|
||||||
</p>
|
|
||||||
{autoSyncByInstance[instance.id] ? (
|
{autoSyncByInstance[instance.id] ? (
|
||||||
<p className="text-xs text-slate-500">
|
<p className="text-xs text-slate-500">
|
||||||
Last auto-sync:{" "}
|
Last auto-sync:{" "}
|
||||||
@@ -545,42 +468,6 @@ export function DashboardControls({
|
|||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col gap-2">
|
<div className="flex flex-col gap-2">
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<label className="text-xs text-slate-600">
|
|
||||||
Auto-sync
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={instance.auto_sync_enabled}
|
|
||||||
onChange={(e: ChangeEvent<HTMLInputElement>) =>
|
|
||||||
onUpdateAutoSync(instance.id, {
|
|
||||||
auto_sync_enabled: e.target.checked,
|
|
||||||
auto_sync_frequency_minutes:
|
|
||||||
instance.auto_sync_frequency_minutes ?? 60,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
disabled={loading}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<select
|
|
||||||
value={String(
|
|
||||||
instance.auto_sync_frequency_minutes ?? 60,
|
|
||||||
)}
|
|
||||||
onChange={(e: ChangeEvent<HTMLSelectElement>) =>
|
|
||||||
onUpdateAutoSync(instance.id, {
|
|
||||||
auto_sync_enabled: instance.auto_sync_enabled,
|
|
||||||
auto_sync_frequency_minutes: Number(e.target.value),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
disabled={loading}
|
|
||||||
className="rounded border px-2 py-1 text-xs"
|
|
||||||
>
|
|
||||||
{autoSyncFrequencyOptions.map((minutes) => (
|
|
||||||
<option key={minutes} value={minutes}>
|
|
||||||
Every {minutes} min
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
<button
|
<button
|
||||||
onClick={() => onTestConnection(instance.id)}
|
onClick={() => onTestConnection(instance.id)}
|
||||||
disabled={loading}
|
disabled={loading}
|
||||||
@@ -721,26 +608,16 @@ export function DashboardControls({
|
|||||||
{domain.domain_name}
|
{domain.domain_name}
|
||||||
</a>
|
</a>
|
||||||
{domain.subscription_id ? (
|
{domain.subscription_id ? (
|
||||||
<p
|
<p className="text-xs font-normal text-slate-500">
|
||||||
className="text-xs font-normal text-slate-500"
|
Subscription: {domain.subscription_id}
|
||||||
title={`Subscription UUID: ${domain.subscription_id}`}
|
|
||||||
>
|
|
||||||
Subscription: {domain.subscription_name ?? "Linked"}
|
|
||||||
</p>
|
</p>
|
||||||
) : (
|
) : null}
|
||||||
<p
|
|
||||||
className="text-xs font-normal text-amber-700"
|
|
||||||
title="Run sync to link this domain to a subscription"
|
|
||||||
>
|
|
||||||
Subscription: Unlinked
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</td>
|
</td>
|
||||||
<td className="px-2 py-2">
|
<td className="px-2 py-2">
|
||||||
<span
|
<span
|
||||||
className={`inline-flex rounded px-2 py-0.5 text-xs font-medium ${getDomainStatusBadge(domain.status)}`}
|
className={`inline-flex rounded px-2 py-0.5 text-xs font-medium ${getDomainStatusBadge(domain.status)}`}
|
||||||
>
|
>
|
||||||
{formatDomainStatusLabel(domain.status)}
|
{domain.status ?? "unknown"}
|
||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td className="px-2 py-2">
|
<td className="px-2 py-2">
|
||||||
@@ -756,33 +633,19 @@ export function DashboardControls({
|
|||||||
<td className="px-2 py-2">
|
<td className="px-2 py-2">
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<button
|
<button
|
||||||
onClick={() => onDomainAction(domain, "suspend")}
|
onClick={() => onDomainAction(domain.id, "suspend")}
|
||||||
disabled={
|
disabled={
|
||||||
loading ||
|
loading || isDomainSuspended(domain.status)
|
||||||
!domain.subscription_id ||
|
|
||||||
isDomainSuspended(domain.status)
|
|
||||||
}
|
|
||||||
title={
|
|
||||||
!domain.subscription_id
|
|
||||||
? "Not linked to a subscription yet — run sync"
|
|
||||||
: undefined
|
|
||||||
}
|
}
|
||||||
className="rounded border border-rose-300 px-2 py-1 text-xs text-rose-700 disabled:cursor-not-allowed disabled:opacity-60"
|
className="rounded border border-rose-300 px-2 py-1 text-xs text-rose-700 disabled:cursor-not-allowed disabled:opacity-60"
|
||||||
>
|
>
|
||||||
Suspend
|
Suspend
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={() => onDomainAction(domain, "unsuspend")}
|
onClick={() =>
|
||||||
disabled={
|
onDomainAction(domain.id, "unsuspend")
|
||||||
loading ||
|
|
||||||
!domain.subscription_id ||
|
|
||||||
isDomainActive(domain.status)
|
|
||||||
}
|
|
||||||
title={
|
|
||||||
!domain.subscription_id
|
|
||||||
? "Not linked to a subscription yet — run sync"
|
|
||||||
: undefined
|
|
||||||
}
|
}
|
||||||
|
disabled={loading || isDomainActive(domain.status)}
|
||||||
className="rounded border border-emerald-300 px-2 py-1 text-xs text-emerald-700 disabled:cursor-not-allowed disabled:opacity-60"
|
className="rounded border border-emerald-300 px-2 py-1 text-xs text-emerald-700 disabled:cursor-not-allowed disabled:opacity-60"
|
||||||
>
|
>
|
||||||
Unsuspend
|
Unsuspend
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ for (const key of requiredEnvs) {
|
|||||||
export const env = {
|
export const env = {
|
||||||
appUrl: process.env.NEXT_PUBLIC_APP_URL ?? "http://localhost:3000",
|
appUrl: process.env.NEXT_PUBLIC_APP_URL ?? "http://localhost:3000",
|
||||||
jobSecret: process.env.JOB_SECRET ?? "",
|
jobSecret: process.env.JOB_SECRET ?? "",
|
||||||
cronSecret: process.env.CRON_SECRET ?? "",
|
|
||||||
encryptionKey: process.env.ENCRYPTION_KEY ?? "",
|
encryptionKey: process.env.ENCRYPTION_KEY ?? "",
|
||||||
pleskCredEncKey: process.env.PLESK_CRED_ENC_KEY ?? "",
|
pleskCredEncKey: process.env.PLESK_CRED_ENC_KEY ?? "",
|
||||||
stripeSecretKey: process.env.STRIPE_SECRET_KEY ?? "",
|
stripeSecretKey: process.env.STRIPE_SECRET_KEY ?? "",
|
||||||
|
|||||||
@@ -1,232 +0,0 @@
|
|||||||
import { randomUUID } from "crypto";
|
|
||||||
|
|
||||||
import { syncPleskInstance } from "@/lib/plesk/sync";
|
|
||||||
|
|
||||||
type SupabaseLike = any;
|
|
||||||
|
|
||||||
type AutoSyncInstance = {
|
|
||||||
id: string;
|
|
||||||
agency_id: string;
|
|
||||||
base_url: string;
|
|
||||||
auth_type: "api_key" | "basic";
|
|
||||||
encrypted_secret: string;
|
|
||||||
last_connected_at: string | null;
|
|
||||||
auto_sync_enabled: boolean;
|
|
||||||
auto_sync_frequency_minutes: number | null;
|
|
||||||
next_auto_sync_at: string | null;
|
|
||||||
auto_sync_lock_until: string | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
type AutoSyncSummary = {
|
|
||||||
instances_considered: number;
|
|
||||||
locks_acquired: number;
|
|
||||||
succeeded: number;
|
|
||||||
failed: number;
|
|
||||||
duration_ms: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
const MAX_INSTANCES_PER_TICK = 5;
|
|
||||||
const MAX_CONCURRENCY = 2;
|
|
||||||
const LOCK_LEASE_SECONDS = 15 * 60;
|
|
||||||
const INSTANCE_TIMEOUT_MS = 14 * 60 * 1000;
|
|
||||||
|
|
||||||
function isDue(instance: AutoSyncInstance, now: number) {
|
|
||||||
if (!instance.next_auto_sync_at) return true;
|
|
||||||
const dueAt = new Date(instance.next_auto_sync_at).getTime();
|
|
||||||
return Number.isFinite(dueAt) && dueAt <= now;
|
|
||||||
}
|
|
||||||
|
|
||||||
function isUnlocked(instance: AutoSyncInstance, now: number) {
|
|
||||||
if (!instance.auto_sync_lock_until) return true;
|
|
||||||
const lockUntil = new Date(instance.auto_sync_lock_until).getTime();
|
|
||||||
return !Number.isFinite(lockUntil) || lockUntil <= now;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function insertActionLogBestEffort(
|
|
||||||
supabase: SupabaseLike,
|
|
||||||
payload: Record<string, unknown>,
|
|
||||||
) {
|
|
||||||
try {
|
|
||||||
const { error } = await supabase.from("actions_log").insert(payload);
|
|
||||||
if (error) {
|
|
||||||
console.error("[autosync] actions_log insert failed", error.message);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error("[autosync] actions_log insert threw", error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function withTimeout<T>(
|
|
||||||
promise: Promise<T>,
|
|
||||||
timeoutMs: number,
|
|
||||||
): Promise<T> {
|
|
||||||
let timeout: ReturnType<typeof setTimeout> | null = null;
|
|
||||||
|
|
||||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
|
||||||
timeout = setTimeout(() => {
|
|
||||||
reject(new Error("Auto-sync timed out"));
|
|
||||||
}, timeoutMs);
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
return await Promise.race([promise, timeoutPromise]);
|
|
||||||
} finally {
|
|
||||||
if (timeout) clearTimeout(timeout);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function runAutoSyncTick(
|
|
||||||
supabase: SupabaseLike,
|
|
||||||
): Promise<AutoSyncSummary> {
|
|
||||||
const startedAt = Date.now();
|
|
||||||
const now = Date.now();
|
|
||||||
|
|
||||||
const { data: rows, error } = await supabase
|
|
||||||
.from("plesk_instances")
|
|
||||||
.select(
|
|
||||||
"id, agency_id, base_url, auth_type, encrypted_secret, last_connected_at, auto_sync_enabled, auto_sync_frequency_minutes, next_auto_sync_at, auto_sync_lock_until",
|
|
||||||
)
|
|
||||||
.eq("status", "connected")
|
|
||||||
.eq("auto_sync_enabled", true)
|
|
||||||
.order("next_auto_sync_at", { ascending: true, nullsFirst: true })
|
|
||||||
.limit(50);
|
|
||||||
|
|
||||||
if (error) {
|
|
||||||
throw new Error(error.message);
|
|
||||||
}
|
|
||||||
|
|
||||||
const eligible = ((rows ?? []) as AutoSyncInstance[])
|
|
||||||
.filter((instance) => isDue(instance, now) && isUnlocked(instance, now))
|
|
||||||
.slice(0, MAX_INSTANCES_PER_TICK);
|
|
||||||
|
|
||||||
let locksAcquired = 0;
|
|
||||||
let succeeded = 0;
|
|
||||||
let failed = 0;
|
|
||||||
|
|
||||||
const queue = [...eligible];
|
|
||||||
|
|
||||||
async function processInstance(instance: AutoSyncInstance) {
|
|
||||||
const lockToken = randomUUID();
|
|
||||||
const { data: lockAcquired, error: lockError } = await supabase.rpc(
|
|
||||||
"acquire_instance_auto_sync_lock",
|
|
||||||
{
|
|
||||||
p_instance_id: instance.id,
|
|
||||||
p_lock_token: lockToken,
|
|
||||||
p_ttl_seconds: LOCK_LEASE_SECONDS,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
if (lockError || !lockAcquired) return;
|
|
||||||
locksAcquired += 1;
|
|
||||||
|
|
||||||
const perInstanceStartedAt = Date.now();
|
|
||||||
const frequencyMinutes = Math.max(
|
|
||||||
instance.auto_sync_frequency_minutes ?? 60,
|
|
||||||
5,
|
|
||||||
);
|
|
||||||
|
|
||||||
await insertActionLogBestEffort(supabase, {
|
|
||||||
agency_id: instance.agency_id,
|
|
||||||
actor_user_id: null,
|
|
||||||
target_type: "plesk_instance",
|
|
||||||
target_id: instance.id,
|
|
||||||
action: "autosync_started",
|
|
||||||
status: "pending",
|
|
||||||
metadata: {
|
|
||||||
instance_id: instance.id,
|
|
||||||
lock_token: lockToken,
|
|
||||||
frequency_minutes: frequencyMinutes,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
await withTimeout(
|
|
||||||
syncPleskInstance(supabase, instance, null, "autosync"),
|
|
||||||
INSTANCE_TIMEOUT_MS,
|
|
||||||
);
|
|
||||||
|
|
||||||
succeeded += 1;
|
|
||||||
|
|
||||||
await insertActionLogBestEffort(supabase, {
|
|
||||||
agency_id: instance.agency_id,
|
|
||||||
actor_user_id: null,
|
|
||||||
target_type: "plesk_instance",
|
|
||||||
target_id: instance.id,
|
|
||||||
action: "autosync_completed",
|
|
||||||
status: "success",
|
|
||||||
metadata: {
|
|
||||||
instance_id: instance.id,
|
|
||||||
lock_token: lockToken,
|
|
||||||
duration_ms: Date.now() - perInstanceStartedAt,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} catch (syncError) {
|
|
||||||
failed += 1;
|
|
||||||
|
|
||||||
const errorMessage =
|
|
||||||
syncError instanceof Error
|
|
||||||
? syncError.message.slice(0, 500)
|
|
||||||
: "autosync_failed";
|
|
||||||
|
|
||||||
await insertActionLogBestEffort(supabase, {
|
|
||||||
agency_id: instance.agency_id,
|
|
||||||
actor_user_id: null,
|
|
||||||
target_type: "plesk_instance",
|
|
||||||
target_id: instance.id,
|
|
||||||
action: "autosync_failed",
|
|
||||||
status: "failed",
|
|
||||||
error_message: errorMessage,
|
|
||||||
metadata: {
|
|
||||||
instance_id: instance.id,
|
|
||||||
lock_token: lockToken,
|
|
||||||
duration_ms: Date.now() - perInstanceStartedAt,
|
|
||||||
error_summary: errorMessage,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
const nowIso = new Date().toISOString();
|
|
||||||
const nextAutoSyncAtIso = new Date(
|
|
||||||
Date.now() + frequencyMinutes * 60 * 1000,
|
|
||||||
).toISOString();
|
|
||||||
|
|
||||||
const { error: scheduleError } = await supabase
|
|
||||||
.from("plesk_instances")
|
|
||||||
.update({
|
|
||||||
last_auto_sync_at: nowIso,
|
|
||||||
next_auto_sync_at: nextAutoSyncAtIso,
|
|
||||||
auto_sync_lock_until: null,
|
|
||||||
auto_sync_lock_token: null,
|
|
||||||
})
|
|
||||||
.eq("id", instance.id)
|
|
||||||
.eq("auto_sync_lock_token", lockToken);
|
|
||||||
|
|
||||||
if (scheduleError) {
|
|
||||||
console.error(
|
|
||||||
"[autosync] schedule update failed",
|
|
||||||
scheduleError.message,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const workers = Array.from(
|
|
||||||
{ length: Math.min(MAX_CONCURRENCY, queue.length) },
|
|
||||||
async () => {
|
|
||||||
while (queue.length > 0) {
|
|
||||||
const instance = queue.shift();
|
|
||||||
if (!instance) break;
|
|
||||||
await processInstance(instance);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
await Promise.all(workers);
|
|
||||||
|
|
||||||
return {
|
|
||||||
instances_considered: eligible.length,
|
|
||||||
locks_acquired: locksAcquired,
|
|
||||||
succeeded,
|
|
||||||
failed,
|
|
||||||
duration_ms: Date.now() - startedAt,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -289,7 +289,7 @@ export async function unsuspendPleskSubscription(
|
|||||||
subscriptionName: string,
|
subscriptionName: string,
|
||||||
) {
|
) {
|
||||||
return pleskCliCall(connection, "subscription", [
|
return pleskCliCall(connection, "subscription", [
|
||||||
"--unsuspend",
|
"--webspace-on",
|
||||||
subscriptionName,
|
subscriptionName,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,34 +22,8 @@ type InstanceRow = Pick<
|
|||||||
| "last_connected_at"
|
| "last_connected_at"
|
||||||
>;
|
>;
|
||||||
|
|
||||||
type LocalSubscriptionLookupRow = {
|
|
||||||
id: string;
|
|
||||||
plesk_subscription_id: string;
|
|
||||||
name: string | null;
|
|
||||||
status: string | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
const MIN_INTERVAL_MS = 3 * 60 * 1000;
|
const MIN_INTERVAL_MS = 3 * 60 * 1000;
|
||||||
|
|
||||||
function normalizeDomainLike(value: string) {
|
|
||||||
return value.trim().toLowerCase().replace(/\.$/, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
function findBestSuffixSubscriptionMatch<
|
|
||||||
T extends { normalizedName: string; id: string; status: string | null },
|
|
||||||
>(normalizedDomain: string, candidates: T[]) {
|
|
||||||
let best: T | undefined;
|
|
||||||
|
|
||||||
for (const candidate of candidates) {
|
|
||||||
if (!normalizedDomain.endsWith(`.${candidate.normalizedName}`)) continue;
|
|
||||||
if (!best || candidate.normalizedName.length > best.normalizedName.length) {
|
|
||||||
best = candidate;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return best;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function syncPleskInstance(
|
export async function syncPleskInstance(
|
||||||
supabase: SupabaseLike,
|
supabase: SupabaseLike,
|
||||||
instance: InstanceRow,
|
instance: InstanceRow,
|
||||||
@@ -182,7 +156,7 @@ export async function syncPleskInstance(
|
|||||||
const { data: localSubscriptions, error: localSubscriptionsError } =
|
const { data: localSubscriptions, error: localSubscriptionsError } =
|
||||||
await supabase
|
await supabase
|
||||||
.from("plesk_subscriptions")
|
.from("plesk_subscriptions")
|
||||||
.select("id, plesk_subscription_id, name, status")
|
.select("id, plesk_subscription_id, status")
|
||||||
.eq("agency_id", instance.agency_id)
|
.eq("agency_id", instance.agency_id)
|
||||||
.eq("plesk_instance_id", instance.id);
|
.eq("plesk_instance_id", instance.id);
|
||||||
|
|
||||||
@@ -190,116 +164,33 @@ export async function syncPleskInstance(
|
|||||||
throw new Error(localSubscriptionsError.message);
|
throw new Error(localSubscriptionsError.message);
|
||||||
}
|
}
|
||||||
|
|
||||||
const subscriptionsIndexed = ((localSubscriptions ?? []) as Array<any>)
|
|
||||||
.filter((row): row is LocalSubscriptionLookupRow =>
|
|
||||||
Boolean(row?.plesk_subscription_id && row?.id),
|
|
||||||
)
|
|
||||||
.map((row) => ({
|
|
||||||
id: String(row.id),
|
|
||||||
pleskSubscriptionId: String(row.plesk_subscription_id),
|
|
||||||
status: row?.status ? String(row.status) : null,
|
|
||||||
name: row?.name ? String(row.name) : null,
|
|
||||||
}));
|
|
||||||
|
|
||||||
const subscriptionByExternalId = new Map<
|
const subscriptionByExternalId = new Map<
|
||||||
string,
|
string,
|
||||||
{
|
{ id: string; status: string | null }
|
||||||
id: string;
|
|
||||||
pleskSubscriptionId: string;
|
|
||||||
status: string | null;
|
|
||||||
name: string | null;
|
|
||||||
}
|
|
||||||
>(subscriptionsIndexed.map((row) => [row.pleskSubscriptionId, row]));
|
|
||||||
|
|
||||||
const subscriptionByLocalId = new Map<
|
|
||||||
string,
|
|
||||||
{
|
|
||||||
id: string;
|
|
||||||
pleskSubscriptionId: string;
|
|
||||||
status: string | null;
|
|
||||||
name: string | null;
|
|
||||||
}
|
|
||||||
>(subscriptionsIndexed.map((row) => [row.id, row]));
|
|
||||||
|
|
||||||
const subscriptionByName = new Map<
|
|
||||||
string,
|
|
||||||
{
|
|
||||||
id: string;
|
|
||||||
pleskSubscriptionId: string;
|
|
||||||
status: string | null;
|
|
||||||
name: string | null;
|
|
||||||
}
|
|
||||||
>(
|
>(
|
||||||
subscriptionsIndexed
|
(localSubscriptions ?? [])
|
||||||
.filter((row) => row.name)
|
.filter((row: any) => row?.plesk_subscription_id && row?.id)
|
||||||
.map((row) => [normalizeDomainLike(String(row.name)), row]),
|
.map((row: any) => [
|
||||||
|
String(row.plesk_subscription_id),
|
||||||
|
{
|
||||||
|
id: String(row.id),
|
||||||
|
status: row?.status ? String(row.status) : null,
|
||||||
|
},
|
||||||
|
]),
|
||||||
);
|
);
|
||||||
|
|
||||||
const subscriptionNameCandidates: Array<{
|
|
||||||
id: string;
|
|
||||||
pleskSubscriptionId: string;
|
|
||||||
status: string | null;
|
|
||||||
normalizedName: string;
|
|
||||||
}> = subscriptionsIndexed
|
|
||||||
.filter((row) => row.name)
|
|
||||||
.map((row) => ({
|
|
||||||
id: row.id,
|
|
||||||
pleskSubscriptionId: row.pleskSubscriptionId,
|
|
||||||
status: row.status,
|
|
||||||
normalizedName: normalizeDomainLike(String(row.name)),
|
|
||||||
}));
|
|
||||||
|
|
||||||
const domainsForUpsert = domainsRaw
|
const domainsForUpsert = domainsRaw
|
||||||
.map((item: any) => {
|
.map((item: any) => {
|
||||||
const domainId = item?.id ?? item?.guid ?? item?.name;
|
const domainId = item?.id ?? item?.guid ?? item?.name;
|
||||||
const domainName = item?.name ?? item?.domain_name ?? item?.domain;
|
const domainName = item?.name ?? item?.domain_name ?? item?.domain;
|
||||||
const normalizedDomainName = domainName
|
|
||||||
? normalizeDomainLike(String(domainName))
|
|
||||||
: null;
|
|
||||||
const subExternalId =
|
const subExternalId =
|
||||||
item?.subscription?.id ?? item?.subscription_id ?? item?.webspace_id;
|
item?.subscription?.id ?? item?.subscription_id ?? item?.webspace_id;
|
||||||
const rawExternalSubscriptionId = subExternalId
|
const externalSubscriptionId = subExternalId
|
||||||
? String(subExternalId)
|
? String(subExternalId)
|
||||||
: null;
|
: null;
|
||||||
const subscriptionNameHint =
|
const localSubscription = externalSubscriptionId
|
||||||
item?.subscription?.name ??
|
? subscriptionByExternalId.get(externalSubscriptionId)
|
||||||
item?.subscription_name ??
|
|
||||||
item?.webspace_name ??
|
|
||||||
item?.webspace ??
|
|
||||||
null;
|
|
||||||
|
|
||||||
const localSubscriptionByExternal = rawExternalSubscriptionId
|
|
||||||
? subscriptionByExternalId.get(rawExternalSubscriptionId)
|
|
||||||
: undefined;
|
: undefined;
|
||||||
const localSubscriptionByLocalId = rawExternalSubscriptionId
|
|
||||||
? subscriptionByLocalId.get(rawExternalSubscriptionId)
|
|
||||||
: undefined;
|
|
||||||
const localSubscriptionByName = subscriptionNameHint
|
|
||||||
? subscriptionByName.get(
|
|
||||||
normalizeDomainLike(String(subscriptionNameHint)),
|
|
||||||
)
|
|
||||||
: undefined;
|
|
||||||
const localSubscriptionByDomainName = normalizedDomainName
|
|
||||||
? subscriptionByName.get(normalizedDomainName)
|
|
||||||
: undefined;
|
|
||||||
const localSubscriptionBySuffix = normalizedDomainName
|
|
||||||
? findBestSuffixSubscriptionMatch(
|
|
||||||
normalizedDomainName,
|
|
||||||
subscriptionNameCandidates,
|
|
||||||
)
|
|
||||||
: undefined;
|
|
||||||
const localSubscription =
|
|
||||||
localSubscriptionByExternal ??
|
|
||||||
localSubscriptionByLocalId ??
|
|
||||||
localSubscriptionByName ??
|
|
||||||
localSubscriptionByDomainName ??
|
|
||||||
localSubscriptionBySuffix;
|
|
||||||
|
|
||||||
const externalSubscriptionId = localSubscription
|
|
||||||
? localSubscription.pleskSubscriptionId
|
|
||||||
: subscriptionNameHint
|
|
||||||
? String(subscriptionNameHint)
|
|
||||||
: rawExternalSubscriptionId;
|
|
||||||
const rawCreated = item?.created_at ?? item?.created;
|
const rawCreated = item?.created_at ?? item?.created;
|
||||||
const sourceCreatedAt = rawCreated
|
const sourceCreatedAt = rawCreated
|
||||||
? new Date(String(rawCreated)).toISOString()
|
? new Date(String(rawCreated)).toISOString()
|
||||||
@@ -328,10 +219,6 @@ export async function syncPleskInstance(
|
|||||||
})
|
})
|
||||||
.filter(Boolean) as Array<Record<string, unknown>>;
|
.filter(Boolean) as Array<Record<string, unknown>>;
|
||||||
|
|
||||||
const unlinkedDomains = domainsForUpsert.filter(
|
|
||||||
(domain) => !domain.subscription_id,
|
|
||||||
);
|
|
||||||
|
|
||||||
if (domainsForUpsert.length > 0) {
|
if (domainsForUpsert.length > 0) {
|
||||||
const { error } = await supabase
|
const { error } = await supabase
|
||||||
.from("plesk_domains")
|
.from("plesk_domains")
|
||||||
@@ -366,10 +253,6 @@ export async function syncPleskInstance(
|
|||||||
metadata: {
|
metadata: {
|
||||||
subscriptions_seen: subscriptionsRaw.length,
|
subscriptions_seen: subscriptionsRaw.length,
|
||||||
domains_seen: domainsRaw.length,
|
domains_seen: domainsRaw.length,
|
||||||
unlinked_domains: unlinkedDomains.length,
|
|
||||||
unlinked_domain_samples: unlinkedDomains
|
|
||||||
.slice(0, 25)
|
|
||||||
.map((domain) => String(domain.domain_name ?? "unknown")),
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -442,146 +325,3 @@ export async function syncPleskInstance(
|
|||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function backfillDomainSubscriptionLinks(
|
|
||||||
supabase: SupabaseLike,
|
|
||||||
input: {
|
|
||||||
agencyId: string;
|
|
||||||
instanceId: string;
|
|
||||||
actorUserId?: string | null;
|
|
||||||
},
|
|
||||||
) {
|
|
||||||
const { agencyId, instanceId, actorUserId } = input;
|
|
||||||
|
|
||||||
const { data: subscriptions, error: subscriptionsError } = await supabase
|
|
||||||
.from("plesk_subscriptions")
|
|
||||||
.select("id, plesk_subscription_id, name, status")
|
|
||||||
.eq("agency_id", agencyId)
|
|
||||||
.eq("plesk_instance_id", instanceId);
|
|
||||||
|
|
||||||
if (subscriptionsError) {
|
|
||||||
throw new Error(subscriptionsError.message);
|
|
||||||
}
|
|
||||||
|
|
||||||
const { data: domains, error: domainsError } = await supabase
|
|
||||||
.from("plesk_domains")
|
|
||||||
.select("id, domain_name, external_subscription_id, subscription_id")
|
|
||||||
.eq("agency_id", agencyId)
|
|
||||||
.eq("plesk_instance_id", instanceId)
|
|
||||||
.is("subscription_id", null);
|
|
||||||
|
|
||||||
if (domainsError) {
|
|
||||||
throw new Error(domainsError.message);
|
|
||||||
}
|
|
||||||
|
|
||||||
const subscriptionByExternalId = new Map<
|
|
||||||
string,
|
|
||||||
{ id: string; status: string }
|
|
||||||
>(
|
|
||||||
(subscriptions ?? [])
|
|
||||||
.filter((subscription: any) => subscription?.plesk_subscription_id)
|
|
||||||
.map((subscription: any) => [
|
|
||||||
String(subscription.plesk_subscription_id),
|
|
||||||
{
|
|
||||||
id: String(subscription.id),
|
|
||||||
status: subscription?.status
|
|
||||||
? String(subscription.status)
|
|
||||||
: "unknown",
|
|
||||||
},
|
|
||||||
]),
|
|
||||||
);
|
|
||||||
|
|
||||||
const subscriptionByName = new Map<string, { id: string; status: string }>(
|
|
||||||
(subscriptions ?? [])
|
|
||||||
.filter((subscription: any) => subscription?.name)
|
|
||||||
.map((subscription: any) => [
|
|
||||||
normalizeDomainLike(String(subscription.name)),
|
|
||||||
{
|
|
||||||
id: String(subscription.id),
|
|
||||||
status: subscription?.status
|
|
||||||
? String(subscription.status)
|
|
||||||
: "unknown",
|
|
||||||
},
|
|
||||||
]),
|
|
||||||
);
|
|
||||||
|
|
||||||
const subscriptionNameCandidates: Array<{
|
|
||||||
id: string;
|
|
||||||
status: string;
|
|
||||||
normalizedName: string;
|
|
||||||
}> = (subscriptions ?? [])
|
|
||||||
.filter((subscription: any) => subscription?.name)
|
|
||||||
.map((subscription: any) => ({
|
|
||||||
id: String(subscription.id),
|
|
||||||
status: subscription?.status ? String(subscription.status) : "unknown",
|
|
||||||
normalizedName: normalizeDomainLike(String(subscription.name)),
|
|
||||||
}));
|
|
||||||
|
|
||||||
let linkedCount = 0;
|
|
||||||
const failures: Array<{ domain_id: string; error: string }> = [];
|
|
||||||
|
|
||||||
for (const domain of domains ?? []) {
|
|
||||||
const matchByExternal = domain?.external_subscription_id
|
|
||||||
? subscriptionByExternalId.get(String(domain.external_subscription_id))
|
|
||||||
: undefined;
|
|
||||||
const matchByDomainName = domain?.domain_name
|
|
||||||
? subscriptionByName.get(normalizeDomainLike(String(domain.domain_name)))
|
|
||||||
: undefined;
|
|
||||||
const normalizedDomainName = domain?.domain_name
|
|
||||||
? normalizeDomainLike(String(domain.domain_name))
|
|
||||||
: null;
|
|
||||||
const matchBySuffix = normalizedDomainName
|
|
||||||
? findBestSuffixSubscriptionMatch(
|
|
||||||
normalizedDomainName,
|
|
||||||
subscriptionNameCandidates,
|
|
||||||
)
|
|
||||||
: undefined;
|
|
||||||
const linkedSubscription =
|
|
||||||
matchByExternal ?? matchByDomainName ?? matchBySuffix;
|
|
||||||
|
|
||||||
if (!linkedSubscription) continue;
|
|
||||||
|
|
||||||
const { error: updateError } = await supabase
|
|
||||||
.from("plesk_domains")
|
|
||||||
.update({
|
|
||||||
subscription_id: linkedSubscription.id,
|
|
||||||
status: linkedSubscription.status,
|
|
||||||
})
|
|
||||||
.eq("id", domain.id)
|
|
||||||
.eq("agency_id", agencyId);
|
|
||||||
|
|
||||||
if (updateError) {
|
|
||||||
failures.push({
|
|
||||||
domain_id: String(domain.id),
|
|
||||||
error: updateError.message,
|
|
||||||
});
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
linkedCount += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
await supabase.from("actions_log").insert({
|
|
||||||
agency_id: agencyId,
|
|
||||||
actor_user_id: actorUserId ?? null,
|
|
||||||
target_type: "plesk_instance",
|
|
||||||
target_id: instanceId,
|
|
||||||
action: "domain_subscription_backfill",
|
|
||||||
status: failures.length > 0 ? "failed" : "success",
|
|
||||||
error_message:
|
|
||||||
failures.length > 0
|
|
||||||
? `${failures.length} domain links failed during backfill`
|
|
||||||
: null,
|
|
||||||
metadata: {
|
|
||||||
attempted: (domains ?? []).length,
|
|
||||||
linked: linkedCount,
|
|
||||||
failures: failures.slice(0, 25),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
attempted: (domains ?? []).length,
|
|
||||||
linked: linkedCount,
|
|
||||||
failed: failures.length,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|||||||
18
lib/types.ts
18
lib/types.ts
@@ -83,12 +83,6 @@ export type Database = {
|
|||||||
last_sync_error: string | null;
|
last_sync_error: string | null;
|
||||||
last_sync_subscriptions: number;
|
last_sync_subscriptions: number;
|
||||||
last_sync_domains: number;
|
last_sync_domains: number;
|
||||||
auto_sync_enabled: boolean;
|
|
||||||
auto_sync_frequency_minutes: number;
|
|
||||||
last_auto_sync_at: string | null;
|
|
||||||
next_auto_sync_at: string | null;
|
|
||||||
auto_sync_lock_until: string | null;
|
|
||||||
auto_sync_lock_token: string | null;
|
|
||||||
created_at: string;
|
created_at: string;
|
||||||
};
|
};
|
||||||
Insert: {
|
Insert: {
|
||||||
@@ -107,12 +101,6 @@ export type Database = {
|
|||||||
last_sync_error?: string | null;
|
last_sync_error?: string | null;
|
||||||
last_sync_subscriptions?: number;
|
last_sync_subscriptions?: number;
|
||||||
last_sync_domains?: number;
|
last_sync_domains?: number;
|
||||||
auto_sync_enabled?: boolean;
|
|
||||||
auto_sync_frequency_minutes?: number;
|
|
||||||
last_auto_sync_at?: string | null;
|
|
||||||
next_auto_sync_at?: string | null;
|
|
||||||
auto_sync_lock_until?: string | null;
|
|
||||||
auto_sync_lock_token?: string | null;
|
|
||||||
created_at?: string;
|
created_at?: string;
|
||||||
};
|
};
|
||||||
Update: {
|
Update: {
|
||||||
@@ -131,12 +119,6 @@ export type Database = {
|
|||||||
last_sync_error?: string | null;
|
last_sync_error?: string | null;
|
||||||
last_sync_subscriptions?: number;
|
last_sync_subscriptions?: number;
|
||||||
last_sync_domains?: number;
|
last_sync_domains?: number;
|
||||||
auto_sync_enabled?: boolean;
|
|
||||||
auto_sync_frequency_minutes?: number;
|
|
||||||
last_auto_sync_at?: string | null;
|
|
||||||
next_auto_sync_at?: string | null;
|
|
||||||
auto_sync_lock_until?: string | null;
|
|
||||||
auto_sync_lock_token?: string | null;
|
|
||||||
created_at?: string;
|
created_at?: string;
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,62 +0,0 @@
|
|||||||
-- CL6: auto-sync worker scheduling fields + per-instance lock helpers
|
|
||||||
|
|
||||||
alter table public.plesk_instances
|
|
||||||
add column if not exists auto_sync_enabled boolean not null default false,
|
|
||||||
add column if not exists auto_sync_frequency_minutes integer not null default 60,
|
|
||||||
add column if not exists last_auto_sync_at timestamptz,
|
|
||||||
add column if not exists next_auto_sync_at timestamptz,
|
|
||||||
add column if not exists auto_sync_lock_until timestamptz,
|
|
||||||
add column if not exists auto_sync_lock_token text;
|
|
||||||
|
|
||||||
alter table public.plesk_instances
|
|
||||||
drop constraint if exists plesk_instances_auto_sync_frequency_minutes_check;
|
|
||||||
|
|
||||||
alter table public.plesk_instances
|
|
||||||
add constraint plesk_instances_auto_sync_frequency_minutes_check
|
|
||||||
check (auto_sync_frequency_minutes between 5 and 10080);
|
|
||||||
|
|
||||||
create index if not exists idx_plesk_instances_auto_sync_due
|
|
||||||
on public.plesk_instances (auto_sync_enabled, next_auto_sync_at);
|
|
||||||
|
|
||||||
create or replace function public.acquire_instance_auto_sync_lock(
|
|
||||||
p_instance_id uuid,
|
|
||||||
p_lock_token text,
|
|
||||||
p_ttl_seconds integer default 900
|
|
||||||
)
|
|
||||||
returns boolean
|
|
||||||
language plpgsql
|
|
||||||
security definer
|
|
||||||
set search_path = public
|
|
||||||
as $$
|
|
||||||
declare
|
|
||||||
v_acquired boolean := false;
|
|
||||||
begin
|
|
||||||
update public.plesk_instances
|
|
||||||
set
|
|
||||||
auto_sync_lock_until = now() + make_interval(secs => p_ttl_seconds),
|
|
||||||
auto_sync_lock_token = p_lock_token
|
|
||||||
where id = p_instance_id
|
|
||||||
and auto_sync_enabled = true
|
|
||||||
and (next_auto_sync_at is null or next_auto_sync_at <= now())
|
|
||||||
and (auto_sync_lock_until is null or auto_sync_lock_until < now());
|
|
||||||
|
|
||||||
get diagnostics v_acquired = row_count;
|
|
||||||
return v_acquired;
|
|
||||||
end;
|
|
||||||
$$;
|
|
||||||
|
|
||||||
create or replace function public.release_instance_auto_sync_lock(
|
|
||||||
p_instance_id uuid,
|
|
||||||
p_lock_token text
|
|
||||||
)
|
|
||||||
returns void
|
|
||||||
language sql
|
|
||||||
security definer
|
|
||||||
set search_path = public
|
|
||||||
as $$
|
|
||||||
update public.plesk_instances
|
|
||||||
set auto_sync_lock_until = null,
|
|
||||||
auto_sync_lock_token = null
|
|
||||||
where id = p_instance_id
|
|
||||||
and auto_sync_lock_token = p_lock_token;
|
|
||||||
$$;
|
|
||||||
Reference in New Issue
Block a user