diff --git a/apps/http-backend/src/routes/google_callback.ts b/apps/http-backend/src/routes/google_callback.ts index 2b1e9ba..70cae62 100644 --- a/apps/http-backend/src/routes/google_callback.ts +++ b/apps/http-backend/src/routes/google_callback.ts @@ -6,6 +6,7 @@ import { Router, Request, Response } from "express"; import dotenv from "dotenv"; import { fileURLToPath } from "url"; import { dirname, join } from "path"; +import { statusCodes } from "@repo/common/zod"; // Get the directory of this file const __filename = fileURLToPath(import.meta.url); @@ -190,7 +191,7 @@ googleAuth.get('/debug/config', async(req: Request, res: Response)=>{ : "❌ Redirect URI mismatch detected!" }); } catch (err) { - return res.status(500).json({ + return res.status(statusCodes.INTERNAL_SERVER_ERROR).json({ error: err instanceof Error ? err.message : 'Unknown error', stack: err instanceof Error ? err.stack : undefined }); @@ -232,6 +233,6 @@ googleAuth.get('/debug/credentials', async(req: Request, res: Response)=>{ return res.json({ credentials: debugInfo }); } catch (err) { - return res.status(500).json({ error: err instanceof Error ? err.message : 'Unknown error' }); + return res.status(statusCodes.INTERNAL_SERVER_ERROR).json({ error: err instanceof Error ? err.message : 'Unknown error' }); } }); diff --git a/apps/http-backend/src/routes/sheet.routes.ts b/apps/http-backend/src/routes/sheet.routes.ts index 85c68ad..3b00c25 100644 --- a/apps/http-backend/src/routes/sheet.routes.ts +++ b/apps/http-backend/src/routes/sheet.routes.ts @@ -13,10 +13,10 @@ sheetRouter.get( try { if (!req.user) return res - .status(statusCodes.BAD_GATEWAY) + .status(statusCodes.UNAUTHORIZED) .json({ message: "User isnot logged in /not authorized" }); - const credId = req.params.cred; - if (!credId) { + const credentialId = req.params.cred; + if (!credentialId) { return res .status(statusCodes.BAD_REQUEST) .json({ message: "credentials id not provided" }); @@ -29,7 +29,7 @@ sheetRouter.get( .json({ message: "User id not provided" }); const sheets = await sheetExecutor.getSheets({ userId: userId, - credId: credId, + credentialId: credentialId, }); if ((sheets as any)?.success === false) { return res.status(statusCodes.NOT_FOUND).json({ @@ -61,11 +61,11 @@ sheetRouter.get( const userId = req.user?.sub; if (!userId) return res - .status(statusCodes.BAD_GATEWAY) + .status(statusCodes.UNAUTHORIZED) .json({ message: "User isnot logged in /not authorized" }); - const credId = req.params.cred; + const credentialId = req.params.cred; const sheetId = req.params.sheetId; - if (!credId || !sheetId) { + if (!credentialId || !sheetId) { return res .status(statusCodes.BAD_REQUEST) .json({ message: `credentials id not provided ` }); @@ -76,7 +76,7 @@ sheetRouter.get( }); } const sheets = await sheetExecutor.getSheetTabs( - { userId: userId, credId: credId }, + { userId: userId, credentialId: credentialId }, sheetId ); diff --git a/apps/http-backend/src/routes/userRoutes/executionRoutes.ts b/apps/http-backend/src/routes/userRoutes/executionRoutes.ts index 0d8abd4..c2c77ad 100644 --- a/apps/http-backend/src/routes/userRoutes/executionRoutes.ts +++ b/apps/http-backend/src/routes/userRoutes/executionRoutes.ts @@ -33,7 +33,7 @@ execRouter.post('/node', userMiddleware, async(req: AuthRequest, res: Response) // if(nodeData.CredentialsID) const context = { userId: req.user.sub, - config: config , + config: config , // credentialsId: nodeData.CredentialsID || "" } const executionResult = await ExecutionRegister.execute(type, context) diff --git a/apps/http-backend/src/routes/userRoutes/userMiddleware.ts b/apps/http-backend/src/routes/userRoutes/userMiddleware.ts index 2333a5b..9b34470 100644 --- a/apps/http-backend/src/routes/userRoutes/userMiddleware.ts +++ b/apps/http-backend/src/routes/userRoutes/userMiddleware.ts @@ -35,7 +35,7 @@ export async function userMiddleware( req.user = payload; return next(); } catch (e) { - return res.status(401).json({ + return res.status(statusCodes.UNAUTHORIZED).json({ message: `Invalid token: ${e instanceof Error ? e.message : "Unknown error"}`, }); } diff --git a/apps/http-backend/src/routes/userRoutes/userRoutes.ts b/apps/http-backend/src/routes/userRoutes/userRoutes.ts index f61963b..8c9c781 100644 --- a/apps/http-backend/src/routes/userRoutes/userRoutes.ts +++ b/apps/http-backend/src/routes/userRoutes/userRoutes.ts @@ -17,7 +17,7 @@ import { HOOKS_URL, } from "@repo/common/zod"; import { GoogleSheetsNodeExecutor } from "@repo/nodes"; -import axios, { Axios } from "axios"; +import axios from "axios"; const router: Router = Router(); router.post("/createAvaliableNode", async (req: AuthRequest, res: Response) => { @@ -60,7 +60,7 @@ router.get( message: "User has to be logged in , This is from getNodesEnd pont", }); } - const userID = req.user.id; + // const userID = req.user.id; // console.log(userID) try { const Data = await prismaClient.availableNode.findMany(); @@ -120,7 +120,7 @@ router.get( console.log("RequestRecieved from the frontend"); if (!req.user) return res - .status(statusCodes.BAD_GATEWAY) + .status(statusCodes.UNAUTHORIZED) .json({ message: "User isnot logged in /not authorized" }); const Data = await prismaClient.availableTrigger.findMany(); @@ -141,7 +141,7 @@ router.get( router.get( "/getCredentials/:type", userMiddleware, - async (req: AuthRequest, res) => { + async (req: AuthRequest, res: Response) => { try { // console.log("user from getcredentials: ", req.user); if (!req.user) { @@ -186,12 +186,12 @@ router.get( // Data: credentials, // }); if (credentials.length === 0) { - return res.status(200).json({ + return res.status(statusCodes.OK).json({ message: "No credentials found", }); } - return res.status(200).json({ + return res.status(statusCodes.OK).json({ message: "Credentials fetched", data: credentials, hasCredentials: true, @@ -244,7 +244,7 @@ router.get( router.post( "/create/workflow", userMiddleware, - async (req: AuthRequest, res) => { + async (req: AuthRequest, res: Response) => { if (!req.user) { return res.status(statusCodes.BAD_REQUEST).json({ @@ -253,7 +253,7 @@ router.post( } const Data = req.body; const ParsedData = WorkflowSchema.safeParse(Data); - const UserID = req.user.id; + const UserID = req.user.sub; // const UserID = "343c9a0a-9c3f-40d0-81de-9a5969e03f92"; // Ensure that the required fields are present in the parsed data and create the workflow properly. if (!ParsedData.success) { @@ -298,7 +298,7 @@ router.get( return res .status(statusCodes.UNAUTHORIZED) .json({ message: "User is not logged in /not authorized" }); - const userId = req.user.id; + const userId = req.user.sub; const workflows = await prismaClient.workflow.findMany({ where: { @@ -313,7 +313,7 @@ router.get( console.log("The error is from getting wrkflows", error.message); return res.status(statusCodes.INTERNAL_SERVER_ERROR).json({ - meesage: "Internal Server Error From getting workflows for the user", + message: "Internal Server Error From getting workflows for the user", }); } } @@ -328,7 +328,7 @@ router.get( return res .status(statusCodes.UNAUTHORIZED) .json({ message: "User is not logged in /not authorized" }); - const userId = req.user.id; + const userId = req.user.sub; const workflow = await prismaClient.workflow.findFirst({ where: { userId: userId, @@ -348,7 +348,7 @@ router.get( ); return res.status(statusCodes.INTERNAL_SERVER_ERROR).json({ - meesage: "Internal Server Error From getting workflows for the user", + message: "Internal Server Error From getting workflows for the user", }); } } @@ -363,7 +363,7 @@ router.get( return res .status(statusCodes.BAD_GATEWAY) .json({ message: "User isnot logged in /not authorized" }); - const userId = req.user.id; + const userId = req.user.sub; const workflowId = req.params.workflowId; const getWorkflow = await prismaClient.workflow.findFirst({ @@ -411,7 +411,7 @@ router.put("/workflow/update", userMiddleware, async (req: AuthRequest, res: Res message: "User Not Authenticated" }) } - const userId = req.user.id + const userId = req.user.sub try { const workflowValid = await prismaClient.workflow.findFirst({ where: { id: workflowId, userId: userId } @@ -637,7 +637,7 @@ router.put( } ); -router.post("/executeWorkflow", userMiddleware, async (req: AuthRequest, res) => { +router.post("/executeWorkflow", userMiddleware, async (req: AuthRequest, res: Response) => { console.log("REcieved REquest to the execute route ") const Data = req.body if (!req.user) { @@ -654,7 +654,7 @@ router.post("/executeWorkflow", userMiddleware, async (req: AuthRequest, res) => }) } const workflowId = parsedData.data.workflowId; - const userId = req.user.id + const userId = req.user.sub try { const trigger = await prismaClient.workflow.findFirst({ where: { id: workflowId, userId: userId }, @@ -684,7 +684,7 @@ router.post("/executeWorkflow", userMiddleware, async (req: AuthRequest, res) => } ) } - return res.status(200).json({ + return res.status(statusCodes.OK).json({ success: true, workflowExecutionId: data.data.workflowExecutionId }); diff --git a/apps/processor/src/lib/retry.ts b/apps/processor/src/lib/retry.ts index bb0797c..67ef8ba 100644 --- a/apps/processor/src/lib/retry.ts +++ b/apps/processor/src/lib/retry.ts @@ -7,7 +7,7 @@ export async function retryLogic( const result = await fn(); return result; } catch (error) { - if (attempt === maxRetries - 1) + if (attempt === maxRetries) throw Error("Max Retries Reached. Try again after some time"); const delay = Math.pow(2, attempt) * 1000; diff --git a/apps/worker/src/engine/executor.ts b/apps/worker/src/engine/executor.ts index 3b06575..9e82125 100644 --- a/apps/worker/src/engine/executor.ts +++ b/apps/worker/src/engine/executor.ts @@ -62,16 +62,36 @@ export async function executeWorkflow( : String(currentInputData); nodeConfig.body = nodeConfig.body + inputStr; } + if(!node.CredentialsID){ + await prismaClient.workflowExecution.update({ + where: { id: workflowExecutionId }, + data: { + status: "Failed", + error: "Credential id not found", + completedAt: new Date(), + }, + }); + + await prismaClient.nodeExecution.update({ + where: {id: nodeExecution.id}, + data:{ + status: "Failed", + error: "Credential id not found", + completedAt: new Date() + } + }) + return; + } const context = { // nodeId: node.id, userId: data.workflow.userId, - credId: node.CredentialsID, + credentialId: node.CredentialsID, // config: node.config as Record, config: nodeConfig, inputData: currentInputData, }; console.log(`Executing with context: ${JSON.stringify(context)}`); - console.log(`Executing with context: ${context.credId}`); + console.log(`Executing with context: ${context.credentialId}`); const execute = await ExecutionRegister.execute(nodeType, context); if (!execute.success) { diff --git a/apps/worker/src/engine/registory.ts b/apps/worker/src/engine/registory.ts deleted file mode 100644 index d4ba2a5..0000000 --- a/apps/worker/src/engine/registory.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { ExecutionContext, ExecutionResult, NodeExecutor } from "../types.js"; -import { GmailExecutor } from "@repo/nodes/nodeClient"; -import {GoogleSheetsNodeExecutor} from "@repo/nodes/nodeClient"; -class ExecutionRegistry { - private executors = new Map(); - - register(nodeType: string, executor: NodeExecutor) { - this.executors.set(nodeType, executor); - } - - async execute( - nodeType: string, - context: ExecutionContext - ): Promise { - const executor = this.executors.get(nodeType); - if (!executor) { - return { - success: false, - error: `No Executor found for ${nodeType}`, - }; - } - try { - const result = await executor.execute(context) - console.log("Execute result:", result); - - return result; - } catch (error: any) { - return { - success: false, - error: error, - }; - } - } - initialize() { - // TODO: Ensure GmailExecutor implements NodeExecutor and is compatible with ExecutionContext - // If needed, adapt/extract a compatible Executor for registration. - // For now, this cast suppresses the type error. Refactor as soon as possible! - - - //wehen visits this next time make sure chang gmail executor implements NodeExecutor - this.register("gmail", new GmailExecutor() as unknown as NodeExecutor); - this.register("google_sheet", new GoogleSheetsNodeExecutor() as unknown as NodeExecutor) - console.log(`The current Executors are ${this.executors.size}`); - } -} - -export const register = new ExecutionRegistry(); diff --git a/apps/worker/src/tests/test.ts b/apps/worker/src/tests/test.ts index 0183313..31e0225 100644 --- a/apps/worker/src/tests/test.ts +++ b/apps/worker/src/tests/test.ts @@ -1,6 +1,6 @@ import { executeWorkflow } from "../engine/executor.js"; -import { register } from "../engine/registory.js"; - +// import { register } from "../engine/registory.js"; +import { ExecutionRegister as register } from "@repo/nodes"; async function testDirect() { console.log("🧪 Testing Gmail integration directly...\n"); diff --git a/apps/worker/src/types.ts b/apps/worker/src/types.ts deleted file mode 100644 index 34ab9bc..0000000 --- a/apps/worker/src/types.ts +++ /dev/null @@ -1,16 +0,0 @@ -export interface ExecutionContext { - nodeId?: string; - userId: string; - credentialsId?: string; - config: Record; - inputData: any; -} -export interface ExecutionResult { - success: boolean; - output?: any; - error?: string; - metadata?: Record; -} -export interface NodeExecutor { - execute(context: ExecutionContext): Promise; -} diff --git a/packages/nodes/src/common/google-oauth-service.ts b/packages/nodes/src/common/google-oauth-service.ts index dec8e01..0d06ee4 100644 --- a/packages/nodes/src/common/google-oauth-service.ts +++ b/packages/nodes/src/common/google-oauth-service.ts @@ -85,13 +85,13 @@ class GoogleOAuthService { async getCredentials( userId: string, - credId: string + credentialId: string ): Promise<{ id: string; tokens: OAuthTokens } | null> { try { - console.log("user id: ", userId, " & ", credId, " from oauth service"); + console.log("user id: ", userId, " & ", credentialId, " from oauth service"); const credentials = await this.prisma.credential.findFirst({ where: { - id: credId, + id: credentialId, // userId: userId, type: "google_oauth", }, diff --git a/packages/nodes/src/gmail/gmail.executor.ts b/packages/nodes/src/gmail/gmail.executor.ts index 9efc990..310f7e9 100644 --- a/packages/nodes/src/gmail/gmail.executor.ts +++ b/packages/nodes/src/gmail/gmail.executor.ts @@ -2,7 +2,7 @@ import { GoogleOAuthService } from "../common/google-oauth-service.js"; import { GmailService, GmailCredentials } from "./gmail.service.js"; interface NodeExecutionContext { - credId: string; + credentialId: string; userId: string; config?: any; inputData?: any; @@ -27,7 +27,7 @@ class GmailExecutor { // Get credentials const credentials = await this.oauthService.getCredentials( context.userId, - context.credId + context.credentialId ); if (!credentials) { diff --git a/packages/nodes/src/google-sheets/google-sheets.executor.ts b/packages/nodes/src/google-sheets/google-sheets.executor.ts index 0889b0d..675ebb5 100644 --- a/packages/nodes/src/google-sheets/google-sheets.executor.ts +++ b/packages/nodes/src/google-sheets/google-sheets.executor.ts @@ -3,7 +3,7 @@ import { GoogleOAuthService } from "../common/google-oauth-service.js"; import { GoogleSheetsService, GoogleSheetsCredentials } from "./google-sheets.service.js"; interface NodeExecutionContext{ - credId: string, + credentialId: string, userId: string, config?: any, //sheet id / range... inputData?: any // previous node data @@ -88,7 +88,7 @@ class GoogleSheetsNodeExecutor{ private async ensureSheetService(context: NodeExecutionContext): Promise<{ credentialId: string } | NodeExecutionResult> { try { - const credentials = await this.oauthService.getCredentials(context.userId, context.credId); + const credentials = await this.oauthService.getCredentials(context.userId, context.credentialId); console.log("credentails from sheet.executor: ",credentials) if (!credentials) { return { diff --git a/packages/nodes/src/registry/Execution.config.types.ts b/packages/nodes/src/registry/Execution.config.types.ts index 106f6aa..fb6d12b 100644 --- a/packages/nodes/src/registry/Execution.config.types.ts +++ b/packages/nodes/src/registry/Execution.config.types.ts @@ -1,7 +1,7 @@ export interface ExecutionContext { nodeId?: string; userId: string; - credentialsId?: string; + credentialId?: string; config: Record; inputData?: any; }