Skip to content

Commit

Permalink
add remove hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
jsbroks committed Nov 15, 2024
1 parent d4b9f30 commit c0f88bf
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 16 deletions.
19 changes: 15 additions & 4 deletions apps/pty-proxy/src/controller/agent-socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,12 @@ import { can, getUser } from "@ctrlplane/auth/utils";
import { eq } from "@ctrlplane/db";
import { db } from "@ctrlplane/db/client";
import * as schema from "@ctrlplane/db/schema";
import { upsertResources } from "@ctrlplane/job-dispatch";
import { deleteResources, upsertResources } from "@ctrlplane/job-dispatch";
import { logger } from "@ctrlplane/logger";
import { Permission } from "@ctrlplane/validators/auth";
import { agentConnect, agentHeartbeat } from "@ctrlplane/validators/session";

import { agents } from "./sockets.js";
import { ifMessage } from "./utils.js";

export class AgentSocket {
Expand Down Expand Up @@ -84,14 +85,16 @@ export class AgentSocket {
this.socket.on(
"message",
ifMessage()
.is(agentConnect, (data) =>
.is(agentConnect, (data) => {
this.updateResource({
updatedAt: new Date(),
config: data.config,
metadata: data.metadata,
}),
)
});
})
.is(agentHeartbeat, () =>
this.updateResource({
updatedAt: new Date(),
metadata: {
...(this.resource?.metadata ?? {}),
["last-heartbeat"]: new Date().toISOString(),
Expand All @@ -100,6 +103,14 @@ export class AgentSocket {
)
.handle(),
);

this.socket.on("close", () => {
logger.info("Agent disconnected", { agentName: this.name });
if (this.resource?.id == null) return;

agents.delete(this.resource.id);
deleteResources(db, [this.resource.id]);
});
}

async updateResource(
Expand Down
29 changes: 17 additions & 12 deletions packages/job-dispatch/src/resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,18 +320,13 @@ export const upsertResources = async (
);

if (resourcesToDelete.length > 0) {
await tx
.delete(resource)
.where(
inArray(
resource.id,
resourcesToDelete.map((r) => r.id),
),
)
.catch((err) => {
log.error("Error deleting resources", { error: err });
throw err;
});
await deleteResources(
tx,
resourcesToDelete.map((r) => r.id),
).catch((err) => {
log.error("Error deleting resources", { error: err });
throw err;
});

log.info(`Deleted ${resourcesToDelete.length} resources`, {
resourcesToDelete,
Expand All @@ -344,3 +339,13 @@ export const upsertResources = async (
throw err;
}
};

/**
* Delete resources from the database.
*
* @param tx - The transaction to use.
* @param resourceIds - The ids of the resources to delete.
*/
export const deleteResources = async (tx: Tx, resourceIds: string[]) => {
await tx.delete(resource).where(inArray(resource.id, resourceIds));
};

0 comments on commit c0f88bf

Please sign in to comment.