refactor(services): update service creation logic and enhance service group schema
- Changed service creation to default `enabled` to true in the database schema. - Updated service group schema to set default values for `icon`, `domain`, and health check parameters. - Refactored service routes to use `await` for fetching service views, ensuring proper asynchronous handling. - Improved error handling in service groups query to provide clearer feedback on response validation. This commit enhances the overall service management experience by ensuring services are enabled by default and improving the robustness of the service group schema.
This commit is contained in:
@@ -40,7 +40,7 @@ export async function serviceRoutes(app: FastifyInstance) {
|
||||
body.service_group_id,
|
||||
);
|
||||
}
|
||||
const view = serviceConfig.getView(request.server.db, service.id);
|
||||
const view = await serviceConfig.getView(request.server.db, service.id);
|
||||
recordAudit(request.server, request, {
|
||||
action: "service.create",
|
||||
targetType: "app_resource",
|
||||
@@ -56,6 +56,7 @@ export async function serviceRoutes(app: FastifyInstance) {
|
||||
return serviceConfig.getView(request.server.db, Number(id));
|
||||
});
|
||||
|
||||
|
||||
app.patch("/services/:id", async (request) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const body = updateServiceConfigSchema.parse(request.body);
|
||||
@@ -77,7 +78,7 @@ export async function serviceRoutes(app: FastifyInstance) {
|
||||
|
||||
app.delete("/services/:id", async (request) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const view = serviceConfig.getView(request.server.db, Number(id));
|
||||
const view = await serviceConfig.getView(request.server.db, Number(id));
|
||||
repos.deleteService(request.server.db, Number(id));
|
||||
recordAudit(request.server, request, {
|
||||
action: "service.delete",
|
||||
|
||||
@@ -823,49 +823,6 @@ async function findOrImportDnsARecord(
|
||||
);
|
||||
}
|
||||
|
||||
async function serviceBindingsExistInDns(
|
||||
db: Db,
|
||||
cf: CloudflareClient,
|
||||
serviceId: number,
|
||||
): Promise<boolean> {
|
||||
const bindings = repos.listBindingsByService(db, serviceId);
|
||||
if (bindings.length === 0) return false;
|
||||
|
||||
for (const binding of bindings) {
|
||||
const cnameTarget = binding.cname_target?.trim() || null;
|
||||
if (cnameTarget) {
|
||||
const record = await findOrImportDnsRecord(
|
||||
db,
|
||||
cf,
|
||||
binding.domain_id,
|
||||
binding.zone_name,
|
||||
binding.hostname,
|
||||
"CNAME",
|
||||
cnameTarget,
|
||||
);
|
||||
if (!record) return false;
|
||||
continue;
|
||||
}
|
||||
|
||||
const targetIps = repos.listBindingIps(db, binding.id);
|
||||
if (targetIps.length === 0) return false;
|
||||
|
||||
for (const ip of targetIps) {
|
||||
const record = await findOrImportDnsARecord(
|
||||
db,
|
||||
cf,
|
||||
binding.domain_id,
|
||||
binding.zone_name,
|
||||
binding.hostname,
|
||||
ip,
|
||||
);
|
||||
if (!record) return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
async function syncServiceBindingsToDns(
|
||||
db: Db,
|
||||
cf: CloudflareClient,
|
||||
@@ -1281,20 +1238,24 @@ export async function updateConfig(
|
||||
|
||||
service = repos.getService(db, id);
|
||||
const remainingBindings = repos.listBindingsByService(db, id);
|
||||
|
||||
// Creating/editing with FQDN bindings should publish DNS. Previously a
|
||||
// disabled service stayed off unless records already existed in Cloudflare
|
||||
// (chicken-and-egg for brand-new services).
|
||||
if (
|
||||
req.domains &&
|
||||
req.domains.length > 0 &&
|
||||
!service.enabled
|
||||
) {
|
||||
repos.setServiceEnabled(db, id, true);
|
||||
service = repos.getService(db, id);
|
||||
}
|
||||
|
||||
if (shouldPushDns(db, service)) {
|
||||
if (remainingBindings.length > 0) {
|
||||
await syncServiceBindingsToDns(db, cf, id);
|
||||
}
|
||||
await syncGroupDomainForService(db, cf, id);
|
||||
} else if (
|
||||
req.domains &&
|
||||
req.domains.length > 0 &&
|
||||
!service.enabled &&
|
||||
(await serviceBindingsExistInDns(db, cf, id))
|
||||
) {
|
||||
repos.setServiceEnabled(db, id, true);
|
||||
await syncServiceBindingsToDns(db, cf, id);
|
||||
await syncGroupDomainForService(db, cf, id);
|
||||
}
|
||||
|
||||
void syncServiceToVpsTracker(db, id, removedBindingIds);
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { serviceGroupsResponseSchema } from "@cfdm/shared";
|
||||
import { repos } from "@cfdm/db";
|
||||
import type { CloudflareClient } from "../src/lib/cf-client.js";
|
||||
import { buildApp } from "../src/app.js";
|
||||
import { loadConfig } from "../src/config.js";
|
||||
import {
|
||||
listGroupViews,
|
||||
updateConfig,
|
||||
} from "../src/services/service-config-service.js";
|
||||
|
||||
function mockCf(): CloudflareClient {
|
||||
return {
|
||||
listDnsRecords: async () => [],
|
||||
createDnsRecord: async (_zoneId: string, payload: { type: string; name: string; content: string }) => ({
|
||||
id: `cf-${payload.name}`,
|
||||
type: payload.type,
|
||||
name: payload.name,
|
||||
content: payload.content,
|
||||
ttl: 1,
|
||||
proxied: false,
|
||||
}),
|
||||
updateDnsRecord: async (
|
||||
_zoneId: string,
|
||||
id: string,
|
||||
payload: { type: string; name: string; content: string },
|
||||
) => ({
|
||||
id,
|
||||
type: payload.type,
|
||||
name: payload.name,
|
||||
content: payload.content,
|
||||
ttl: 1,
|
||||
proxied: false,
|
||||
}),
|
||||
deleteDnsRecord: async () => undefined,
|
||||
verifyToken: async () => true,
|
||||
listZones: async () => [{ id: "zone-1", name: "example.com", status: "active" }],
|
||||
} as unknown as CloudflareClient;
|
||||
}
|
||||
|
||||
async function authHeaders(app: Awaited<ReturnType<typeof buildApp>>) {
|
||||
const config = loadConfig();
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/auth/login",
|
||||
payload: { username: config.adminUsername, password: "admin" },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const { token } = res.json() as { token: string };
|
||||
return { authorization: `Bearer ${token}` };
|
||||
}
|
||||
|
||||
describe("create service then list groups", () => {
|
||||
it("create + updateConfig then listGroupViews parses with shared Zod schema", async () => {
|
||||
const app = await buildApp({
|
||||
config: { ...loadConfig(), staticDir: null },
|
||||
memory: true,
|
||||
});
|
||||
const headers = await authHeaders(app);
|
||||
const cf = mockCf();
|
||||
|
||||
repos.createDomain(app.db, null, "example.com", "zone-1");
|
||||
const group = repos.createServiceGroup(
|
||||
app.db,
|
||||
"VPN",
|
||||
"vpn",
|
||||
null,
|
||||
"vpn.example.com",
|
||||
);
|
||||
|
||||
const createRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/services",
|
||||
headers,
|
||||
payload: {
|
||||
name: "Panel",
|
||||
slug: "panel",
|
||||
service_group_id: group.id,
|
||||
},
|
||||
});
|
||||
expect(createRes.statusCode).toBe(200);
|
||||
const created = createRes.json() as {
|
||||
id: number;
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
};
|
||||
expect(created.id).toBeTypeOf("number");
|
||||
expect(created.enabled).toBe(true);
|
||||
|
||||
await updateConfig(app.db, cf, created.id, {
|
||||
ips: ["1.2.3.4"],
|
||||
service_group_id: group.id,
|
||||
domains: [
|
||||
{
|
||||
fqdn: "panel.example.com",
|
||||
target_ips: ["1.2.3.4"],
|
||||
target_ip_weights: { "1.2.3.4": 1 },
|
||||
target_ip_priorities: { "1.2.3.4": 1 },
|
||||
lb_mode: "round_robin",
|
||||
health_check_enabled: true,
|
||||
health_check_type: "tcp",
|
||||
health_check_port: 443,
|
||||
health_check_path: null,
|
||||
health_check_expected_status: null,
|
||||
health_check_interval_sec: 30,
|
||||
health_check_timeout_ms: 3000,
|
||||
health_check_verify_tls: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const body = await listGroupViews(app.db);
|
||||
const parsed = serviceGroupsResponseSchema.safeParse(body);
|
||||
expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true);
|
||||
|
||||
const listRes = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/service-groups",
|
||||
headers,
|
||||
});
|
||||
expect(listRes.statusCode).toBe(200);
|
||||
const httpParsed = serviceGroupsResponseSchema.safeParse(listRes.json());
|
||||
expect(httpParsed.success, JSON.stringify(httpParsed.error?.issues)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
httpParsed.data!.groups
|
||||
.find((g) => g.id === group.id)
|
||||
?.services.some((s) => s.id === created.id),
|
||||
).toBe(true);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("POST /services returns resolved ServiceView with numeric id", async () => {
|
||||
const app = await buildApp({
|
||||
config: { ...loadConfig(), staticDir: null },
|
||||
memory: true,
|
||||
});
|
||||
const headers = await authHeaders(app);
|
||||
|
||||
const createRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/services",
|
||||
headers,
|
||||
payload: { name: "Bare", slug: "bare" },
|
||||
});
|
||||
expect(createRes.statusCode).toBe(200);
|
||||
const created = createRes.json() as Record<string, unknown>;
|
||||
expect(typeof created.id).toBe("number");
|
||||
expect(created.name).toBe("Bare");
|
||||
expect(created.enabled).toBe(true);
|
||||
expect(Array.isArray(created.ips)).toBe(true);
|
||||
expect(Array.isArray(created.domains)).toBe(true);
|
||||
|
||||
const listRes = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/service-groups",
|
||||
headers,
|
||||
});
|
||||
expect(listRes.statusCode).toBe(200);
|
||||
const parsed = serviceGroupsResponseSchema.safeParse(listRes.json());
|
||||
expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true);
|
||||
expect(parsed.data!.ungrouped.some((s) => s.slug === "bare")).toBe(true);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user