feat(studio): drop 3D Poster Lab and ship Multi-Tenant Multi-Expert Brain OS, Live Playground & n8n Playbooks
This commit is contained in:
+61
-7
@@ -43,7 +43,7 @@ function readJson(request, maxBytes) {
|
||||
});
|
||||
}
|
||||
|
||||
function createApiHandler({ resolveWorkspace, store, scrape, imageHandler, getConnected, publicOrigin, maxBodyBytes = 32768, maxConcurrentImports = 1, maxImportsPerMinute = 5 }) {
|
||||
function createApiHandler({ resolveWorkspace, store, scrape, imageHandler, getConnected, engineProxy, publicOrigin, maxBodyBytes = 32768, maxConcurrentImports = 1, maxImportsPerMinute = 5 }) {
|
||||
const configured = new URL(publicOrigin);
|
||||
if (!['http:', 'https:'].includes(configured.protocol) || configured.pathname !== '/' || configured.search || configured.hash || configured.username || configured.password) {
|
||||
throw new Error('A public Studio origin without path or credentials is required');
|
||||
@@ -79,14 +79,31 @@ function createApiHandler({ resolveWorkspace, store, scrape, imageHandler, getCo
|
||||
try {
|
||||
const pathname = new URL(request.url, origin).pathname;
|
||||
const routes = {
|
||||
'/api/workspace': 'GET', '/api/brand': 'POST', '/api/catalog-image': 'GET',
|
||||
'/api/get-synced-stores': 'GET', '/api/sync-store': 'POST', '/api/delete-synced-store': 'POST'
|
||||
'/api/workspace': ['GET'],
|
||||
'/api/brand': ['POST'],
|
||||
'/api/catalog-image': ['GET'],
|
||||
'/api/get-synced-stores': ['GET'],
|
||||
'/api/sync-store': ['POST'],
|
||||
'/api/delete-synced-store': ['POST'],
|
||||
'/api/experts': ['GET', 'POST'],
|
||||
'/api/experts/simulate': ['POST'],
|
||||
'/api/experts/generate-content': ['POST'],
|
||||
'/api/playbooks': ['GET', 'POST'],
|
||||
'/api/playbooks/test': ['POST']
|
||||
};
|
||||
if (!routes[pathname]) return sendJson(response, 404, { success: false, code: 'NOT_FOUND', error: 'API পাওয়া যায়নি।' });
|
||||
if (request.method !== routes[pathname]) return sendJson(response, 405, { success: false, code: 'METHOD_NOT_ALLOWED', error: 'এই method সমর্থিত নয়।' });
|
||||
if (request.method === 'POST') writeOrigin(request);
|
||||
const expertDeleteMatch = !routes[pathname] ? /^\/api\/experts\/([a-zA-Z0-9_-]{1,80})$/.exec(pathname) : null;
|
||||
const allowedMethods = routes[pathname] || (expertDeleteMatch ? ['DELETE'] : null);
|
||||
if (!allowedMethods) return sendJson(response, 404, { success: false, code: 'NOT_FOUND', error: 'API পাওয়া যায়নি।' });
|
||||
if (!allowedMethods.includes(request.method)) return sendJson(response, 405, { success: false, code: 'METHOD_NOT_ALLOWED', error: 'এই method সমর্থিত নয়।' });
|
||||
if (request.method === 'POST' || request.method === 'DELETE') writeOrigin(request);
|
||||
const workspace = await resolveWorkspace(request);
|
||||
const publicWorkspace = { clientId: workspace.clientId, name: workspace.displayName, tenant: workspace.tenant, canWriteProducts: workspace.canWriteProducts };
|
||||
const publicWorkspace = {
|
||||
clientId: workspace.clientId,
|
||||
name: workspace.displayName,
|
||||
tenant: workspace.tenant,
|
||||
canWriteProducts: workspace.canWriteProducts,
|
||||
multiExpertEnabled: Boolean(engineProxy && engineProxy.isConfigured())
|
||||
};
|
||||
if (pathname === '/api/workspace') {
|
||||
publicWorkspace.brand = normalizeBrand(await store.readBrand(workspace) || {}, workspace.displayName);
|
||||
return sendJson(response, 200, { success: true, workspace: publicWorkspace });
|
||||
@@ -95,6 +112,43 @@ function createApiHandler({ resolveWorkspace, store, scrape, imageHandler, getCo
|
||||
if (!imageHandler) throw fail(503, 'IMAGE_UNAVAILABLE', 'Product image এখন পাওয়া যাচ্ছে না।');
|
||||
return await imageHandler(request, response, workspace);
|
||||
}
|
||||
|
||||
// ── Multi-Tenant Multi-Expert Brain & n8n Playbooks Proxy Routes ───────
|
||||
if (pathname === '/api/experts' || expertDeleteMatch || pathname.startsWith('/api/experts/') || pathname === '/api/playbooks' || pathname.startsWith('/api/playbooks/')) {
|
||||
if (!engineProxy || !engineProxy.isConfigured()) {
|
||||
throw fail(503, 'ENGINE_NOT_CONFIGURED', 'Multi-Expert AI Engine সংযুক্ত নয়।');
|
||||
}
|
||||
if (pathname === '/api/experts' && request.method === 'GET') {
|
||||
return sendJson(response, 200, await engineProxy.listExperts(workspace));
|
||||
}
|
||||
if (pathname === '/api/playbooks' && request.method === 'GET') {
|
||||
return sendJson(response, 200, await engineProxy.listPlaybooks(workspace));
|
||||
}
|
||||
if (expertDeleteMatch && request.method === 'DELETE') {
|
||||
requireProductWrite(workspace);
|
||||
return sendJson(response, 200, await engineProxy.deleteExpert(workspace, expertDeleteMatch[1]));
|
||||
}
|
||||
const body = await readJson(request, maxBodyBytes);
|
||||
if (pathname === '/api/experts' && request.method === 'POST') {
|
||||
requireProductWrite(workspace);
|
||||
return sendJson(response, 200, await engineProxy.saveExpert(workspace, body));
|
||||
}
|
||||
if (pathname === '/api/experts/simulate') {
|
||||
return sendJson(response, 200, await engineProxy.simulate(workspace, body));
|
||||
}
|
||||
if (pathname === '/api/experts/generate-content') {
|
||||
return sendJson(response, 200, await engineProxy.generateContent(workspace, body));
|
||||
}
|
||||
if (pathname === '/api/playbooks' && request.method === 'POST') {
|
||||
requireProductWrite(workspace);
|
||||
return sendJson(response, 200, await engineProxy.savePlaybook(workspace, body));
|
||||
}
|
||||
if (pathname === '/api/playbooks/test') {
|
||||
if (!body.dry_run) requireProductWrite(workspace);
|
||||
return sendJson(response, 200, await engineProxy.testPlaybook(workspace, body));
|
||||
}
|
||||
}
|
||||
|
||||
if (request.method === 'GET') {
|
||||
const records = await store.read(workspace);
|
||||
if (getConnected) records.unshift(await getConnected(workspace));
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
const { fail } = require('./workspace.cjs');
|
||||
|
||||
const SAFE_ID_RE = /^[a-zA-Z0-9_-]{1,80}$/;
|
||||
|
||||
function createEngineProxy({ baseUrl, serviceKey, fetchImpl = fetch, timeoutMs = 35000 } = {}) {
|
||||
const configuredUrl = String(baseUrl || '').trim().replace(/\/+$/, '');
|
||||
const configuredKey = String(serviceKey || '').trim();
|
||||
|
||||
function isConfigured() {
|
||||
return Boolean(configuredUrl && configuredKey);
|
||||
}
|
||||
|
||||
function assertConfigured() {
|
||||
if (!isConfigured()) {
|
||||
throw fail(503, 'ENGINE_NOT_CONFIGURED', 'Multi-Expert AI Engine সংযুক্ত নয়। অনুগ্রহ করে অ্যাডমিনের সাথে যোগাযোগ করুন।');
|
||||
}
|
||||
}
|
||||
|
||||
function cleanBody(body) {
|
||||
if (!body || typeof body !== 'object' || Array.isArray(body)) return {};
|
||||
const out = { ...body };
|
||||
delete out.tenant;
|
||||
delete out.tenant_id;
|
||||
delete out.clientId;
|
||||
delete out.client_id;
|
||||
return out;
|
||||
}
|
||||
|
||||
async function forward(workspace, method, enginePath, body = null) {
|
||||
assertConfigured();
|
||||
if (!workspace || !workspace.tenant || !workspace.clientId) {
|
||||
throw fail(401, 'WORKSPACE_REQUIRED', 'বৈধ workspace প্রয়োজন।');
|
||||
}
|
||||
|
||||
const url = configuredUrl + enginePath;
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||||
const headers = {
|
||||
Authorization: 'Bearer ' + configuredKey,
|
||||
'x-aura-tenant': workspace.tenant,
|
||||
'x-aura-client-id': workspace.clientId,
|
||||
Accept: 'application/json'
|
||||
};
|
||||
const init = { method, headers, signal: controller.signal };
|
||||
if (body !== null && method !== 'GET' && method !== 'HEAD') {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
init.body = JSON.stringify(cleanBody(body));
|
||||
}
|
||||
|
||||
try {
|
||||
const upstream = await fetchImpl(url, init);
|
||||
const rawText = await upstream.text();
|
||||
let parsed;
|
||||
try { parsed = rawText ? JSON.parse(rawText) : {}; }
|
||||
catch { parsed = { success: false, error: 'Engine returned invalid JSON' }; }
|
||||
if (!upstream.ok) {
|
||||
throw fail(
|
||||
upstream.status >= 400 && upstream.status < 600 ? upstream.status : 502,
|
||||
parsed.code || 'ENGINE_UPSTREAM_ERROR',
|
||||
parsed.error || 'AI Engine অনুরোধটি সম্পন্ন করতে পারেনি।'
|
||||
);
|
||||
}
|
||||
return parsed;
|
||||
} catch (err) {
|
||||
if (err && Number.isInteger(err.status)) throw err;
|
||||
if (err && err.name === 'AbortError') {
|
||||
throw fail(504, 'ENGINE_TIMEOUT', 'AI Engine উত্তর দিতে বেশি সময় নিচ্ছে। একটু পরে আবার চেষ্টা করুন।');
|
||||
}
|
||||
throw fail(502, 'ENGINE_UNREACHABLE', 'Multi-Expert AI Engine-এর সাথে সংযোগ পাওয়া যায়নি।');
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
isConfigured,
|
||||
listExperts: workspace => forward(workspace, 'GET', '/api/experts'),
|
||||
saveExpert: (workspace, body) => forward(workspace, 'POST', '/api/experts', body),
|
||||
deleteExpert: (workspace, id) => {
|
||||
if (!SAFE_ID_RE.test(String(id || ''))) {
|
||||
throw fail(400, 'INVALID_EXPERT_ID', 'সঠিক Expert ID দিন।');
|
||||
}
|
||||
return forward(workspace, 'DELETE', '/api/experts/' + encodeURIComponent(id));
|
||||
},
|
||||
simulate: (workspace, body) => forward(workspace, 'POST', '/api/experts/simulate', body),
|
||||
generateContent: (workspace, body) => forward(workspace, 'POST', '/api/experts/generate-content', body),
|
||||
listPlaybooks: workspace => forward(workspace, 'GET', '/api/playbooks'),
|
||||
savePlaybook: (workspace, body) => forward(workspace, 'POST', '/api/playbooks', body),
|
||||
testPlaybook: (workspace, body) => forward(workspace, 'POST', '/api/playbooks/test', body)
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { createEngineProxy, SAFE_ID_RE };
|
||||
+6
-2
@@ -5,6 +5,7 @@ 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');
|
||||
@@ -21,7 +22,8 @@ function createStudioServer(config) {
|
||||
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 api = createApiHandler({ resolveWorkspace, store, scrape, imageHandler, getConnected, publicOrigin: config.publicOrigin, ...config.apiLimits });
|
||||
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 {
|
||||
@@ -41,7 +43,7 @@ function createStudioServer(config) {
|
||||
}
|
||||
});
|
||||
server.headersTimeout = 15000;
|
||||
server.requestTimeout = 20000;
|
||||
server.requestTimeout = 45000;
|
||||
server.keepAliveTimeout = 5000;
|
||||
server.maxHeadersCount = 50;
|
||||
return server;
|
||||
@@ -66,6 +68,8 @@ if (require.main === module) {
|
||||
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'),
|
||||
|
||||
Reference in New Issue
Block a user