93 lines
5.3 KiB
JavaScript
93 lines
5.3 KiB
JavaScript
const http = require('node:http');
|
|
const path = require('node:path');
|
|
const { createWorkspaceResolver } = require('./workspace.cjs');
|
|
const { createStore } = require('./store.cjs');
|
|
const { createPublicFetcher } = require('./public-fetch.cjs');
|
|
const { createScraper } = require('./scraper.cjs');
|
|
const { createApiHandler } = require('./api.cjs');
|
|
const { createEngineProxy } = require('./engine-proxy.cjs');
|
|
const { createImageHandler } = require('./images.cjs');
|
|
const { createConnectedCatalog } = require('./connected.cjs');
|
|
const { createStaticHandler } = require('./static.cjs');
|
|
|
|
function createStudioServer(config) {
|
|
let loginUrl = null;
|
|
if (config.loginUrl) {
|
|
const parsed = new URL(config.loginUrl);
|
|
if (!['https:', 'http:'].includes(parsed.protocol) || parsed.username || parsed.password || parsed.hash) throw new Error('Invalid public login URL');
|
|
loginUrl = parsed.href;
|
|
}
|
|
const resolveWorkspace = createWorkspaceResolver({ authMeUrl: config.authMeUrl, clientMeUrl: config.clientMeUrl, clientCatalogUrl: config.clientCatalogUrl });
|
|
const getConnected = config.clientCatalogUrl ? createConnectedCatalog({ publicClientOrigin: config.publicClientOrigin }) : undefined;
|
|
const store = createStore(config.dataDirectory);
|
|
const scrape = createScraper({ fetchPublic: createPublicFetcher(config.fetchLimits), ...config.importLimits });
|
|
const imageHandler = createImageHandler({ store, getConnected, fetchPublic: createPublicFetcher({ maxBytes: 5 * 1024 * 1024, timeoutMs: 10000 }) });
|
|
const engineProxy = createEngineProxy({ baseUrl: config.auraEngineUrl, serviceKey: config.auraEngineServiceKey });
|
|
const api = createApiHandler({ resolveWorkspace, store, scrape, imageHandler, getConnected, engineProxy, publicOrigin: config.publicOrigin, ...config.apiLimits });
|
|
const staticFiles = createStaticHandler(config.publicDirectory);
|
|
const server = http.createServer({ maxHeaderSize: 16384 }, async (req, res) => {
|
|
try {
|
|
const pathname = new URL(req.url, config.publicOrigin).pathname;
|
|
if (pathname === '/api/studio-config' && req.method === 'GET') {
|
|
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
|
|
return res.end(JSON.stringify({ loginUrl }));
|
|
}
|
|
if (pathname === '/health' && ['GET', 'HEAD'].includes(req.method)) {
|
|
res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
|
|
return res.end(req.method === 'HEAD' ? undefined : JSON.stringify({ ok: true, service: 'aura-studio' }));
|
|
}
|
|
if (pathname === '/api' || pathname.startsWith('/api/')) return await api(req, res);
|
|
return await staticFiles(req, res);
|
|
} catch {
|
|
if (!res.destroyed && !res.writableEnded) { res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' }); res.end('Request failed'); }
|
|
}
|
|
});
|
|
server.headersTimeout = 15000;
|
|
server.requestTimeout = 45000;
|
|
server.keepAliveTimeout = 5000;
|
|
server.maxHeadersCount = 50;
|
|
return server;
|
|
}
|
|
|
|
if (require.main === module) {
|
|
try {
|
|
const required = ['STUDIO_PUBLIC_ORIGIN', 'STUDIO_LOGIN_URL', 'STUDIO_AUTH_ME_URL', 'STUDIO_CLIENT_ME_URL', 'STUDIO_CLIENT_CATALOG_URL', 'STUDIO_CLIENT_PUBLIC_ORIGIN', 'STUDIO_DATA_DIR'];
|
|
if (required.some(name => !process.env[name])) throw new Error('Required Studio service configuration is missing');
|
|
const port = Number(process.env.PORT || 3000);
|
|
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('Invalid Studio port');
|
|
function limit(name, minimum = 1) {
|
|
if (process.env[name] === undefined) return undefined;
|
|
const n = Number(process.env[name]);
|
|
if (!Number.isInteger(n) || n < minimum) throw new Error('Invalid Studio resource limit');
|
|
return n;
|
|
}
|
|
const server = createStudioServer({
|
|
publicOrigin: process.env.STUDIO_PUBLIC_ORIGIN,
|
|
loginUrl: process.env.STUDIO_LOGIN_URL,
|
|
authMeUrl: process.env.STUDIO_AUTH_ME_URL, clientMeUrl: process.env.STUDIO_CLIENT_ME_URL,
|
|
clientCatalogUrl: process.env.STUDIO_CLIENT_CATALOG_URL, publicClientOrigin: process.env.STUDIO_CLIENT_PUBLIC_ORIGIN,
|
|
dataDirectory: process.env.STUDIO_DATA_DIR,
|
|
publicDirectory: process.env.STUDIO_PUBLIC_DIR || path.join(__dirname, '../public'),
|
|
auraEngineUrl: process.env.AURA_ENGINE_URL || '',
|
|
auraEngineServiceKey: process.env.AURA_ENGINE_SERVICE_KEY || '',
|
|
fetchLimits: { maxBytes: limit('STUDIO_MAX_SOURCE_BYTES'), timeoutMs: limit('STUDIO_SOURCE_TIMEOUT_MS') },
|
|
importLimits: {
|
|
maxPages: limit('STUDIO_MAX_IMPORT_PAGES'), maxProducts: limit('STUDIO_MAX_PRODUCTS'),
|
|
maxRequests: limit('STUDIO_MAX_SOURCE_REQUESTS'), timeoutMs: limit('STUDIO_IMPORT_TIMEOUT_MS'),
|
|
pageDelayMs: limit('STUDIO_PAGE_DELAY_MS', 0)
|
|
},
|
|
apiLimits: { maxImportsPerMinute: limit('STUDIO_IMPORTS_PER_MINUTE'), maxConcurrentImports: limit('STUDIO_MAX_PARALLEL_IMPORTS') }
|
|
});
|
|
server.listen(port, '0.0.0.0', () => console.log('Aura Studio service started'));
|
|
process.on('SIGTERM', () => {
|
|
server.close();
|
|
setTimeout(() => server.closeAllConnections(), 10000).unref();
|
|
});
|
|
} catch {
|
|
console.error('Aura Studio startup failed: verify required service URLs, data directory and port');
|
|
process.exitCode = 1;
|
|
}
|
|
}
|
|
|
|
module.exports = { createStudioServer };
|