Added service ID fallback

X-Lovable-Edit-ID: edt-a6eb016d-cb4b-4203-9617-fc18dfba438b
Co-authored-by: domfelipe <53182096+domfelipe@users.noreply.github.com>
This commit is contained in:
gpt-engineer-app[bot] 2026-04-27 15:20:31 +00:00
commit 3c1323bf19
2 changed files with 52 additions and 6 deletions

View file

@ -229,6 +229,31 @@ export async function setHermesSuspended(opts: {
});
}
/** Busca o ID de um serviço pelo nome dentro de um projeto. Retorna null se não existir. */
export async function findRailwayServiceByName(opts: {
token: string;
projectId: string;
name: string;
}): Promise<string | null> {
const query = `
query Project($id: String!) {
project(id: $id) {
services { edges { node { id name } } }
}
}
`;
const res = await railwayQuery<{
project: { services: { edges: { node: { id: string; name: string } }[] } };
}>(query, { id: opts.projectId }, opts.token);
if (res.errors?.length) {
console.error("findRailwayServiceByName errors:", JSON.stringify(res.errors));
return null;
}
const edges = res.data?.project?.services?.edges ?? [];
const match = edges.find((e) => e.node.name === opts.name);
return match?.node.id ?? null;
}
/** Busca env+project IDs do primeiro deployment de um serviço. Útil quando vps_pool_id está null. */
export async function getServiceContext(opts: {
token: string;

View file

@ -11,6 +11,7 @@ import {
deployRailwayService,
deleteTelegramWebhook,
getServiceContext,
findRailwayServiceByName,
upsertRailwayVariableCollection,
} from "../_shared/railway.ts";
@ -240,6 +241,7 @@ Deno.serve(async (req) => {
console.log(`[provision-agent] criando serviço Railway: ${serviceName}`);
let railwayServiceId: string;
try {
try {
railwayServiceId = await createRailwayService({
token: RAILWAY_API_TOKEN,
@ -247,6 +249,25 @@ Deno.serve(async (req) => {
name: serviceName,
});
console.log(`[provision-agent] serviço criado: ${railwayServiceId}`);
} catch (createErr) {
const msg = createErr instanceof Error ? createErr.message : String(createErr);
// Recover from "service already exists" — provavelmente sobra de attempt anterior
if (msg.includes("already exists")) {
console.warn(`[provision-agent] serviço já existe, tentando recuperar ID por nome: ${serviceName}`);
const existingId = await findRailwayServiceByName({
token: RAILWAY_API_TOKEN,
projectId: pool.railway_project_id,
name: serviceName,
});
if (!existingId) {
throw new Error(`Service "${serviceName}" exists but could not be located via API`);
}
railwayServiceId = existingId;
console.log(`[provision-agent] serviço existente recuperado: ${railwayServiceId}`);
} else {
throw createErr;
}
}
await configureRailwayService({
token: RAILWAY_API_TOKEN,