|
| 1 | +const path = require('path'); |
| 2 | +const fs = require('fs'); |
| 3 | + |
| 4 | +const run = async () => { |
| 5 | + // 1. Resolve Dependencies from CWD (User's Function Context) |
| 6 | + // This logic ensures we find express/graphql-request in the function's node_modules, |
| 7 | + // regardless of where runner.js is located (Local Dev vs Docker). |
| 8 | + const resolveDep = (name) => { |
| 9 | + try { |
| 10 | + return require(require.resolve(name, { paths: [process.cwd()] })); |
| 11 | + } catch (e) { |
| 12 | + console.error(`[runner] Failed to resolve dependency '${name}' from ${process.cwd()}`); |
| 13 | + console.error(e.message); |
| 14 | + process.exit(1); |
| 15 | + } |
| 16 | + }; |
| 17 | + |
| 18 | + const express = resolveDep('express'); |
| 19 | + const bodyParser = resolveDep('body-parser'); |
| 20 | + const { GraphQLClient } = resolveDep('graphql-request'); |
| 21 | + const http = require('http'); |
| 22 | + const https = require('https'); |
| 23 | + const { URL } = require('url'); |
| 24 | + |
| 25 | + // 2. Resolve User Handler |
| 26 | + const relativePath = process.argv[2] || 'dist/index.js'; |
| 27 | + const absolutePath = path.resolve(process.cwd(), relativePath); |
| 28 | + |
| 29 | + let userModule; |
| 30 | + try { |
| 31 | + userModule = require(absolutePath); |
| 32 | + } catch (e) { |
| 33 | + console.error(`[runner] Failed to load function at ${absolutePath}`); |
| 34 | + console.error(e.message); |
| 35 | + process.exit(1); |
| 36 | + } |
| 37 | + |
| 38 | + const handler = userModule.default || userModule; |
| 39 | + |
| 40 | + if (typeof handler !== 'function') { |
| 41 | + console.error(`[runner] Export at ${absolutePath} is not a function.`); |
| 42 | + process.exit(1); |
| 43 | + } |
| 44 | + |
| 45 | + // 3. Setup App & Helper Functions (Ported from knative-job-fn/src/index.ts) |
| 46 | + // We implement a simplified version of the logic to avoid needing deep imports. |
| 47 | + // However, since we are replacing the shim which used `express` directly usually, |
| 48 | + // or `knative-job-fn` library... |
| 49 | + // Correct approach: The shim used `app` from `@constructive-io/knative-job-fn`. |
| 50 | + // We should try to use THAT if available, to preserve exact behavior (headers, logging). |
| 51 | + |
| 52 | + let app; |
| 53 | + try { |
| 54 | + // Try to load the standard wrapper if present |
| 55 | + const jobFn = resolveDep('@constructive-io/knative-job-fn'); |
| 56 | + // The library usually exports { default: { post: ..., listen: ... } } or similar? |
| 57 | + // Let's check how functions imported it: "import app from '@constructive-io/knative-job-fn';" |
| 58 | + // It exports 'default'. |
| 59 | + const lib = jobFn.default || jobFn; |
| 60 | + |
| 61 | + // The library exposes an 'app' like object but 'listen' is the main entry. |
| 62 | + // But we want to inject our handler into a route. |
| 63 | + // Library usage in shim: `app.post('/', ...)` |
| 64 | + // Library implementation: `app` IS express() basically, but wrapped. |
| 65 | + |
| 66 | + // Actually the library exports an object: { post: ..., listen: ... } |
| 67 | + // We can use it directly. |
| 68 | + app = lib; |
| 69 | + } catch (e) { |
| 70 | + // Fallback to raw express if wrapper missing (unlikely given package.json) |
| 71 | + console.warn('[runner] @constructive-io/knative-job-fn not found, falling back to raw express'); |
| 72 | + app = express(); |
| 73 | + app.use(bodyParser.json()); |
| 74 | + } |
| 75 | + |
| 76 | + // 4. Setup GraphQL Client |
| 77 | + const graphqlEndpoint = process.env.GRAPHQL_ENDPOINT || 'http://constructive-server:3000/graphql'; |
| 78 | + if (!process.env.GRAPHQL_ENDPOINT) { |
| 79 | + // Warn if falling back, to aid debugging |
| 80 | + console.warn(`[runner] GRAPHQL_ENDPOINT not set, defaulting to internal k8s service: ${graphqlEndpoint}`); |
| 81 | + } |
| 82 | + const client = new GraphQLClient(graphqlEndpoint); |
| 83 | + |
| 84 | + // 5. Setup Route |
| 85 | + app.post('/', async (req, res) => { |
| 86 | + try { |
| 87 | + const result = await handler(req.body, { client, headers: req.headers }); |
| 88 | + |
| 89 | + // Standard Shim Error Handling Heuristics |
| 90 | + if (result && result.error) { |
| 91 | + // Heuristics for 400 vs 500 |
| 92 | + if (['Missing prompt', 'Unsupported provider', 'Missing "query" in payload', |
| 93 | + 'Missing repoName or githubToken', 'Missing X-Database-Id header or DEFAULT_DATABASE_ID', |
| 94 | + 'Missing required field', "Either 'html' or 'text' must be provided", |
| 95 | + "Missing address, message, or signature"].some(s => result.error.includes(s) || s === result.error)) { |
| 96 | + return res.status(400).json(result); |
| 97 | + } |
| 98 | + return res.status(500).json(result); |
| 99 | + } |
| 100 | + |
| 101 | + res.status(200).json(result); |
| 102 | + } catch (e) { |
| 103 | + console.error(e); |
| 104 | + res.status(500).json({ error: e.message }); |
| 105 | + } |
| 106 | + }); |
| 107 | + |
| 108 | + // 6. Start Server |
| 109 | + const port = Number(process.env.PORT ?? 8080); |
| 110 | + app.listen(port, () => { |
| 111 | + console.log(`[runner] Function '${relativePath}' listening on port ${port}`); |
| 112 | + }); |
| 113 | +}; |
| 114 | + |
| 115 | +run().catch(e => { |
| 116 | + console.error('[runner] Fatal:', e); |
| 117 | + process.exit(1); |
| 118 | +}); |
0 commit comments