Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

fix: codeRabbit suggetions applied

tiran133ebdd2085d6db
diff --git a/apps/api/src/comment/controllers/create-comment.ts b/apps/api/src/comment/controllers/create-comment.ts
index afc2894b5..a6091c4f4 100644
--- a/apps/api/src/comment/controllers/create-comment.ts
+++ b/apps/api/src/comment/controllers/create-comment.ts
@@ -30,6 +30,7 @@ async function createComment(taskId: string, userId: string, content: string) {
await publishEvent("comment.created", {
...comment,
+ taskId: comment.taskId,
projectId: task.projectId,
userId,
});
diff --git a/apps/api/src/comment/controllers/delete-comment.ts b/apps/api/src/comment/controllers/delete-comment.ts
index 92dbbd262..339283fa4 100644
--- a/apps/api/src/comment/controllers/delete-comment.ts
+++ b/apps/api/src/comment/controllers/delete-comment.ts
@@ -39,6 +39,7 @@ async function deleteComment(userId: string, id: string) {
if (task) {
await publishEvent("comment.deleted", {
...deleted,
+ taskId: deleted.taskId,
projectId: task.projectId,
userId,
});
diff --git a/apps/api/src/comment/controllers/update-comment.ts b/apps/api/src/comment/controllers/update-comment.ts
index 44e6164e6..35a2d9703 100644
--- a/apps/api/src/comment/controllers/update-comment.ts
+++ b/apps/api/src/comment/controllers/update-comment.ts
@@ -40,6 +40,7 @@ async function updateComment(userId: string, id: string, content: string) {
if (task) {
await publishEvent("comment.updated", {
...updated,
+ taskId: updated.taskId,
projectId: task.projectId,
userId,
});
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index 02a4963bc..cfba58d77 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -523,11 +523,9 @@ export function createApp() {
"/ws/:projectId",
upgradeWebSocket(async (c) => {
const projectId = c.req.param("projectId");
- let userId = "anonymous";
try {
await authenticateApiRequest(c);
- userId = c.get("userId");
} catch (error) {
if (error instanceof HTTPException) {
throw error;
@@ -536,6 +534,7 @@ export function createApp() {
throw new HTTPException(500, { message: "Internal Server Error" });
}
+ const userId = c.get("userId");
const windowId = c.req.query("windowId");
const initiatorId = windowId ? `${userId}:${windowId}` : userId;
let conn: ReturnType<typeof addConnection> | null = null;
diff --git a/apps/api/src/label/controllers/delete-label.ts b/apps/api/src/label/controllers/delete-label.ts
index e6f8ca505..963f31ea3 100644
--- a/apps/api/src/label/controllers/delete-label.ts
+++ b/apps/api/src/label/controllers/delete-label.ts
@@ -60,9 +60,9 @@ async function deleteLabel(id: string, userId: string) {
await publishEvent("task.label_deleted", {
label: deletedLabel,
- task,
+ task: task,
projectId: task.projectId,
- taskId: task,
+ taskId: task.id,
userId: userId,
type: "label_deleted",
});
diff --git a/apps/api/src/redis/index.ts b/apps/api/src/redis/index.ts
index 411bc20ec..bc5d9456b 100644
--- a/apps/api/src/redis/index.ts
+++ b/apps/api/src/redis/index.ts
@@ -31,13 +31,13 @@ export function getRedisSub(): Redis {
return _redisSub;
}
-export function closeRedis(): void {
+export async function closeRedis(): Promise<void> {
if (_redisPub) {
- _redisPub.disconnect();
+ await _redisPub.quit();
_redisPub = null;
}
if (_redisSub) {
- _redisSub.disconnect();
+ await _redisSub.quit();
_redisSub = null;
}
}
diff --git a/apps/api/src/ws/index.ts b/apps/api/src/ws/index.ts
index 92a14decc..c359841c5 100644
--- a/apps/api/src/ws/index.ts
+++ b/apps/api/src/ws/index.ts
@@ -38,29 +38,48 @@ let adapter: BroadcastAdapter | null = null;
export async function initializeWebSocketAdapter() {
if (adapter) return;
- adapter = process.env.REDIS_URL
+ const nextAdapter = process.env.REDIS_URL
? new RedisBroadcastAdapter()
: new InMemoryBroadcastAdapter();
- await adapter.subscribe((msg: BroadcastMessage) => {
- deliverToLocalConnections(
- msg.projectId,
- msg.message,
- msg.excludeInitiatorId,
- );
- });
+ try {
+ await nextAdapter.subscribe((msg: BroadcastMessage) => {
+ deliverToLocalConnections(
+ msg.projectId,
+ msg.message,
+ msg.excludeInitiatorId,
+ );
+ });
+ } catch (err) {
+ await nextAdapter.shutdown().catch(() => {});
+ throw err;
+ }
+ adapter = nextAdapter;
console.log(`📡 WebSockets Initialized using: "${adapter.constructor.name}"`);
}
export async function shutdownWebSocketAdapter() {
+ const pendingQueues = [...projectBroadcastQueues.entries()];
+
for (const timeout of projectBroadcastTimeouts.values()) {
clearTimeout(timeout);
}
projectBroadcastTimeouts.clear();
projectBroadcastQueues.clear();
- await adapter?.shutdown();
+ const currentAdapter = adapter;
+ if (currentAdapter) {
+ await Promise.allSettled(
+ pendingQueues.flatMap(([projectId, queue]) =>
+ [...queue.values()].map(({ message, excludeInitiatorId }) =>
+ currentAdapter.publish({ projectId, message, excludeInitiatorId }),
+ ),
+ ),
+ );
+ }
+
+ await currentAdapter?.shutdown();
adapter = null;
}
@@ -78,9 +97,12 @@ function deliverToLocalConnections(
try {
conn.ws.send(payload);
} catch {
- // Connection might be closed, will be cleaned up on close event
+ connections.delete(conn);
}
}
+ if (connections.size === 0) {
+ projectConnections.delete(projectId);
+ }
}
export function addConnection(
diff --git a/apps/api/src/ws/redis-broadcast-adapter.ts b/apps/api/src/ws/redis-broadcast-adapter.ts
index 18bfadc8c..b8a966584 100644
--- a/apps/api/src/ws/redis-broadcast-adapter.ts
+++ b/apps/api/src/ws/redis-broadcast-adapter.ts
@@ -20,6 +20,9 @@ const broadcastMessageSchema = v.object({
export class RedisBroadcastAdapter implements BroadcastAdapter {
private subscribed = false;
+ private _pmessageHandler:
+ | ((pattern: string, channel: string, data: string) => void)
+ | null = null;
async publish(msg: BroadcastMessage): Promise<void> {
await getRedisPub().publish(
@@ -36,27 +39,34 @@ export class RedisBroadcastAdapter implements BroadcastAdapter {
await getRedisSub().psubscribe(CHANNEL_PATTERN);
// "pmessage" fires for pattern subscriptions (not "message")
- getRedisSub().on(
- "pmessage",
- (_pattern: string, _channel: string, data: string) => {
- try {
- const parsed = v.safeParse(broadcastMessageSchema, JSON.parse(data));
- if (!parsed.success) {
- console.error("Invalid broadcast message:", parsed.issues);
- return;
- }
- handler(parsed.output);
- } catch (err) {
- console.error("Failed to parse broadcast message:", err);
+ this._pmessageHandler = (
+ _pattern: string,
+ _channel: string,
+ data: string,
+ ) => {
+ try {
+ const parsed = v.safeParse(broadcastMessageSchema, JSON.parse(data));
+ if (!parsed.success) {
+ console.error("Invalid broadcast message:", parsed.issues);
+ return;
}
- },
- );
+ handler(parsed.output);
+ } catch (err) {
+ console.error("Failed to parse broadcast message:", err);
+ }
+ };
+ getRedisSub().on("pmessage", this._pmessageHandler);
}
async shutdown(): Promise<void> {
+ if (this._pmessageHandler) {
+ getRedisSub().off("pmessage", this._pmessageHandler);
+ this._pmessageHandler = null;
+ }
// Unsubscribe from the pattern — covers all project channels
await getRedisSub().punsubscribe(CHANNEL_PATTERN);
- closeRedis();
+ this.subscribed = false;
+ await closeRedis();
}
private channelForProject(projectId: string): string {
diff --git a/tests/api/events/publish-event.test.ts b/tests/api/events/publish-event.test.ts
index b3fcc6898..33a3c3a46 100644
--- a/tests/api/events/publish-event.test.ts
+++ b/tests/api/events/publish-event.test.ts
@@ -40,7 +40,10 @@ describe("publishEvent / subscribeToEvent", () => {
});
expect(received).toHaveLength(1);
- expect(received[0]?.initiatorId).toBe("user-abc");
+ expect(received[0]).toMatchObject({
+ taskId: "t1",
+ initiatorId: "user-abc",
+ });
});
it("sets initiatorId to undefined when no eventContext store exists", async () => {