|
| 1 | +import net from 'node:net' |
| 2 | + |
| 3 | +import type { PluginOption, ViteDevServer } from 'vite' |
| 4 | + |
| 5 | +import { getConfig } from '@cedarjs/project-config' |
| 6 | + |
| 7 | +let waitingPromise: Promise<void> | null = null |
| 8 | +let serverHasBeenUp = false |
| 9 | + |
| 10 | +export function cedarWaitForApiServer(): PluginOption { |
| 11 | + const cedarConfig = getConfig() |
| 12 | + const apiPort = cedarConfig.api.port |
| 13 | + const apiHost = cedarConfig.api.host || 'localhost' |
| 14 | + |
| 15 | + return { |
| 16 | + name: 'cedar-wait-for-api-server', |
| 17 | + apply: 'serve', |
| 18 | + configureServer(server: ViteDevServer) { |
| 19 | + server.middlewares.use(async (req, res, next) => { |
| 20 | + const url = req.originalUrl |
| 21 | + |
| 22 | + const apiUrl = cedarConfig.web.apiUrl.replace(/\/$/, '') |
| 23 | + // By default the GraphQL API URL is apiUrl + '/graphql'. It is |
| 24 | + // however possible to configure it to something completely different, |
| 25 | + // so we have to check it separately |
| 26 | + const apiGqlUrl = cedarConfig.web.apiGraphQLUrl ?? apiUrl + '/graphql' |
| 27 | + |
| 28 | + const isApiRequest = |
| 29 | + url && |
| 30 | + (url.startsWith(apiUrl) || |
| 31 | + // Only match on .../graphql not on .../graphql-foo. That's why I |
| 32 | + // don't use startsWith here |
| 33 | + url === apiGqlUrl || |
| 34 | + // The two checks below are for when we support GraphQL-over-HTTP |
| 35 | + url.startsWith(apiGqlUrl + '/') || |
| 36 | + url.startsWith(apiGqlUrl + '?')) |
| 37 | + |
| 38 | + if (!isApiRequest || serverHasBeenUp) { |
| 39 | + return next() |
| 40 | + } |
| 41 | + |
| 42 | + try { |
| 43 | + // Reuse existing promise if already waiting |
| 44 | + if (!waitingPromise) { |
| 45 | + waitingPromise = waitForPort(apiPort, apiHost).finally(() => { |
| 46 | + // Clear once resolved (success or failure) so future requests |
| 47 | + // after a timeout can retry |
| 48 | + waitingPromise = null |
| 49 | + }) |
| 50 | + } |
| 51 | + |
| 52 | + await waitingPromise |
| 53 | + |
| 54 | + // Once we've confirmed that the server is listening for requests we |
| 55 | + // don't want to wait again. This ensures we fail fast and let Vite's |
| 56 | + // regular error handling take over if the server crashes mid-session |
| 57 | + serverHasBeenUp = true |
| 58 | + } catch { |
| 59 | + const message = |
| 60 | + 'Vite timed out waiting for the Cedar API server ' + |
| 61 | + `at ${apiHost}:${apiPort}` + |
| 62 | + '\n' + |
| 63 | + 'Please manually refresh the page when the server is ready' |
| 64 | + |
| 65 | + // The `console.error` call here makes the error show in the terminal. |
| 66 | + // The response we send further down makes the error show in the |
| 67 | + // browser. |
| 68 | + console.error(message) |
| 69 | + |
| 70 | + // This heuristic isn't perfect. It's written to handle dbAuth. |
| 71 | + // But it's very unlikely the user would have code that does |
| 72 | + // this exact request without it being a auth token request. |
| 73 | + // We need this special handling because we don't want the error |
| 74 | + // message below to be used as the auth token. |
| 75 | + const isAuthTokenRequest = url === apiUrl + '/auth?method=getToken' |
| 76 | + |
| 77 | + const responseBody = { |
| 78 | + errors: [{ message }], |
| 79 | + } |
| 80 | + |
| 81 | + // drain any incoming request body so the socket isn't left with |
| 82 | + // unread bytes |
| 83 | + req.resume() |
| 84 | + |
| 85 | + const body = JSON.stringify(responseBody) |
| 86 | + |
| 87 | + // Use 203 to indicate that the response was modified by a proxy |
| 88 | + res.writeHead(203, { |
| 89 | + 'Content-Type': 'application/json', |
| 90 | + 'Cache-Control': 'no-cache', |
| 91 | + ...(!isAuthTokenRequest && { |
| 92 | + 'Content-Length': Buffer.byteLength(body), |
| 93 | + }), |
| 94 | + Connection: 'close', |
| 95 | + }) |
| 96 | + |
| 97 | + return isAuthTokenRequest ? res.end() : res.end(body) |
| 98 | + } |
| 99 | + |
| 100 | + next() |
| 101 | + }) |
| 102 | + }, |
| 103 | + } |
| 104 | +} |
| 105 | + |
| 106 | +const ONE_MINUTE_IN_MS = 60000 |
| 107 | + |
| 108 | +async function waitForPort(port: number, host: string) { |
| 109 | + const start = Date.now() |
| 110 | + let lastLogTime = Date.now() |
| 111 | + while (Date.now() - start < ONE_MINUTE_IN_MS) { |
| 112 | + const isOpen = await checkPort(port, host) |
| 113 | + |
| 114 | + if (isOpen) { |
| 115 | + if (lastLogTime - start >= 6000) { |
| 116 | + console.log('✅ API server is ready') |
| 117 | + } |
| 118 | + |
| 119 | + return |
| 120 | + } |
| 121 | + |
| 122 | + // Only log every 6 seconds, i.e. 10 times per minute |
| 123 | + const now = Date.now() |
| 124 | + if (now - lastLogTime >= 6000) { |
| 125 | + console.log('⏳ Waiting for API server...') |
| 126 | + lastLogTime = now |
| 127 | + } |
| 128 | + |
| 129 | + await new Promise((resolve) => setTimeout(resolve, 500)) |
| 130 | + } |
| 131 | + |
| 132 | + throw new Error('Timeout waiting for port') |
| 133 | +} |
| 134 | + |
| 135 | +function checkPort(port: number, host: string) { |
| 136 | + return new Promise((resolve) => { |
| 137 | + const socket = new net.Socket() |
| 138 | + |
| 139 | + socket.setTimeout(200) |
| 140 | + |
| 141 | + socket.on('connect', () => { |
| 142 | + socket.destroy() |
| 143 | + resolve(true) |
| 144 | + }) |
| 145 | + |
| 146 | + socket.on('timeout', () => { |
| 147 | + socket.destroy() |
| 148 | + resolve(false) |
| 149 | + }) |
| 150 | + |
| 151 | + socket.on('error', () => { |
| 152 | + socket.destroy() |
| 153 | + resolve(false) |
| 154 | + }) |
| 155 | + |
| 156 | + socket.connect(port, host) |
| 157 | + }) |
| 158 | +} |
0 commit comments