-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
472 lines (396 loc) · 16.2 KB
/
Copy pathserver.ts
File metadata and controls
472 lines (396 loc) · 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
import express, { Request, Response } from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import path from 'path';
import fs from 'fs';
import dotenv from 'dotenv';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
// ESM __dirname polyfill
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
import { sendSSEUpdate, addSSEClient, removeSSEClient, sendStageUpdate, sendPaymentUpdate } from './stage.js';
// ATXP client SDK imports (will be dynamically imported due to ES module compatibility)
// Import ATXP utility functions
import { getATXPConnectionString, findATXPAccount, validateATXPConnectionString } from './atxp-utils.js';
// Load environment variables
// In production, __dirname points to dist/, but .env is in the parent directory
const envPath = process.env.NODE_ENV === 'production'
? path.join(__dirname, '../.env')
: path.join(__dirname, '.env');
dotenv.config({ path: envPath });
// Create the Express app
const app = express();
const PORT = process.env.PORT || 3001;
const FRONTEND_PORT = process.env.FRONTEND_PORT || 3000;
// Set up CORS and body parsing middleware
app.use(cors({
origin: [`http://localhost:${FRONTEND_PORT}`, `http://localhost:${PORT}`],
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'Cache-Control', 'x-atxp-connection-string']
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Define the Text interface
interface Text {
id: number;
text: string;
timestamp: string;
imageUrl: string;
fileName: string;
fileId?: string;
status?: 'pending' | 'processing' | 'completed' | 'failed';
taskId?: string;
}
// In-memory storage for texts (in production, use a database)
let texts: Text[] = [];
// Helper config object for the ATXP Image MCP Server
const imageService = {
mcpServer: 'https://image.mcp.atxp.ai',
createImageAsyncToolName: 'image_create_image_async',
getImageAsyncToolName: 'image_get_image_async',
description: 'ATXP Image MCP server',
getArguments: (prompt: string) => ({ prompt }),
getAsyncCreateResult: (result: any) => {
const jsonString = result.content[0].text;
const parsed = JSON.parse(jsonString);
return { taskId: parsed.taskId };
},
getAsyncStatusResult: (result: any) => {
const jsonString = result.content[0].text;
const parsed = JSON.parse(jsonString);
return { status: parsed.status, url: parsed.url };
}
};
// Helper config object for the ATXP Filestore MCP Server
const filestoreService = {
mcpServer: 'https://filestore.mcp.atxp.ai',
toolName: 'filestore_write',
description: 'ATXP Filestore MCP server',
getArguments: (sourceUrl: string) => ({ sourceUrl, makePublic: true }),
getResult: (result: any) => {
// Parse the JSON string from the result
const jsonString = result.content[0].text;
return JSON.parse(jsonString);
}
};
// Handle OPTIONS for SSE endpoint
app.options('/api/progress', (req: Request, res: Response) => {
res.writeHead(200, {
'Access-Control-Allow-Origin': `http://localhost:${FRONTEND_PORT}`,
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Headers': 'Cache-Control, Content-Type, x-atxp-connection-string',
'Access-Control-Allow-Methods': 'GET, OPTIONS'
});
res.end();
});
// SSE endpoint for progress updates
app.get('/api/progress', (req: Request, res: Response) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': `http://localhost:${FRONTEND_PORT}`,
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Headers': 'Cache-Control, Content-Type, x-atxp-connection-string',
'Access-Control-Allow-Methods': 'GET, OPTIONS'
});
console.log('SSE connection established');
// Send initial connection message
res.write(`data: ${JSON.stringify({ type: 'connected', message: 'SSE connection established' })}\n\n`);
// Add client to the set
addSSEClient(res);
// Remove client when connection closes
req.on('close', () => {
removeSSEClient(res);
});
});
// Background polling function for async image generation
async function pollForTaskCompletion(
imageClient: any,
taskId: string,
textId: number,
requestId: string,
account: any
) {
console.log(`Starting polling for task ${taskId}`);
let completed = false;
let attempts = 0;
const maxAttempts = 120; // Poll for up to 10 minutes (5 seconds * 120)
while (!completed && attempts < maxAttempts) {
attempts++;
await new Promise(resolve => setTimeout(resolve, 5000)); // Wait 5 seconds
try {
const statusResult = await imageClient.callTool({
name: imageService.getImageAsyncToolName,
arguments: { taskId },
});
const { status, url } = imageService.getAsyncStatusResult(statusResult);
console.log(`Task ${taskId} status (attempt ${attempts}):`, status);
// Find the text in our array and update it
const textIndex = texts.findIndex(text => text.id === textId);
if (textIndex === -1) {
console.error(`Text with ID ${textId} not found`);
completed = true;
continue;
}
if (status === 'completed' && url) {
console.log(`Task ${taskId} completed successfully. URL:`, url);
// Send stage update for completion
sendStageUpdate(requestId, 'image-completed', 'Image generation completed!', 'completed');
// Update the text with the completed image
texts[textIndex].status = 'completed';
texts[textIndex].imageUrl = url;
// Now try to store in filestore
try {
// Send stage update for file storage
sendStageUpdate(requestId, 'storing-file', 'Storing image in ATXP Filestore...', 'in-progress');
// Create filestore client with dynamic import
const { atxpClient: filestoreAtxpClient } = await import('@atxp/client');
const filestoreClient = await filestoreAtxpClient({
mcpServer: filestoreService.mcpServer,
account: account,
onPayment: async ({ payment }: { payment: any }) => {
console.log('Payment made to filestore:', payment);
sendPaymentUpdate({
accountId: payment.accountId,
resourceUrl: payment.resourceUrl,
resourceName: payment.resourceName,
network: payment.network,
currency: payment.currency,
amount: payment.amount.toString(),
iss: payment.iss
});
},
});
const filestoreResult = await filestoreClient.callTool({
name: filestoreService.toolName,
arguments: filestoreService.getArguments(url),
});
const fileResult = filestoreService.getResult(filestoreResult);
texts[textIndex].fileName = fileResult.filename;
texts[textIndex].imageUrl = fileResult.url; // Use filestore URL instead
texts[textIndex].fileId = fileResult.fileId || fileResult.filename;
console.log('Filestore result:', fileResult);
// Send final completion stage update
sendStageUpdate(requestId, 'completed', 'Image stored successfully! Process completed.', 'final');
} catch (filestoreError) {
console.error('Error with filestore, using direct image URL:', filestoreError);
// Send stage update for filestore error but continue
sendSSEUpdate({
id: requestId,
type: 'stage-update',
stage: 'filestore-warning',
message: 'Image ready! Filestore unavailable, using direct URL.',
timestamp: new Date().toISOString(),
status: 'completed'
});
// Send final completion stage update
sendStageUpdate(requestId, 'completed', 'Image generation completed!', 'final');
}
completed = true;
} else if (status === 'failed') {
console.error(`Task ${taskId} failed`);
// Send stage update for failure
sendStageUpdate(requestId, 'generation-failed', 'Image generation failed.', 'error');
// Update the text status
texts[textIndex].status = 'failed';
completed = true;
} else if (status === 'processing') {
// Send periodic progress updates
if (attempts % 2 === 0) { // Every 10 seconds
sendStageUpdate(requestId, 'processing', `Image generation in progress... (${Math.floor(attempts * 5 / 60)}m ${(attempts * 5) % 60}s)`, 'in-progress');
}
}
} catch (error) {
console.error(`Error checking status for task ${taskId}:`, error);
// On error, wait a bit longer before next attempt
await new Promise(resolve => setTimeout(resolve, 5000));
}
}
if (attempts >= maxAttempts) {
console.error(`Task ${taskId} timed out after ${maxAttempts} attempts`);
// Find and update the text status to failed
const textIndex = texts.findIndex(text => text.id === textId);
if (textIndex !== -1) {
texts[textIndex].status = 'failed';
}
// Send timeout error stage update
sendStageUpdate(requestId, 'timeout', 'Image generation timed out.', 'error');
}
}
// Routes
app.get('/api/texts', (req: Request, res: Response) => {
res.json({ texts });
});
app.post('/api/texts', async (req: Request, res: Response) => {
const { text } = req.body;
if (!text || text.trim() === '') {
return res.status(400).json({ error: 'Text is required' });
}
// Get ATXP connection string from header or environment variable
let connectionString: string;
let account: any;
try {
connectionString = getATXPConnectionString(req);
account = await findATXPAccount(connectionString);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Failed to get ATXP connection string';
return res.status(400).json({ error: errorMessage });
}
const requestId = Date.now().toString();
const textId = Date.now();
// Send initial stage update
sendStageUpdate(requestId, 'initializing', 'Starting async image generation process...', 'in-progress');
let newText: Text = {
id: textId,
text: text.trim(),
timestamp: new Date().toISOString(),
imageUrl: '',
fileName: '',
status: 'pending',
taskId: undefined
};
try {
// Send stage update for client creation
sendStageUpdate(requestId, 'creating-clients', 'Initializing ATXP clients...', 'in-progress');
// Dynamically import ATXP modules
const { atxpClient } = await import('@atxp/client');
const { ConsoleLogger, LogLevel } = await import('@atxp/common');
// Create a client using the `atxpClient` function for the ATXP Image MCP Server
const imageClient = await atxpClient({
mcpServer: imageService.mcpServer,
account: account,
allowedAuthorizationServers: [`http://localhost:${PORT}`, 'https://auth.atxp.ai', 'https://atxp-accounts-staging.onrender.com/'],
logger: new ConsoleLogger({level: LogLevel.DEBUG}),
onPayment: async ({ payment }: { payment: any }) => {
console.log('Payment made to image service:', payment);
sendPaymentUpdate({
accountId: payment.accountId,
resourceUrl: payment.resourceUrl,
resourceName: payment.resourceName,
network: payment.network,
currency: payment.currency,
amount: payment.amount.toString(),
iss: payment.iss
});
},
});
// Send stage update for starting async image generation
sendStageUpdate(requestId, 'starting-async-generation', 'Starting async image generation...', 'in-progress');
// Start async image generation
const asyncResult = await imageClient.callTool({
name: imageService.createImageAsyncToolName,
arguments: imageService.getArguments(text),
});
const { taskId } = imageService.getAsyncCreateResult(asyncResult);
console.log('Async image generation started with task ID:', taskId);
// Update the text with task information
newText.taskId = taskId;
newText.status = 'processing';
// Send stage update for task started
sendStageUpdate(requestId, 'task-started', `Async image generation started (Task ID: ${taskId})`, 'in-progress');
// Add to texts array immediately with pending status
texts.push(newText);
// Start background polling for this task
pollForTaskCompletion(imageClient, taskId, textId, requestId, account);
// Return immediately with pending status
res.status(201).json(newText);
} catch (error) {
console.error(`Error starting async image generation:`, error);
// Send stage update for error
sendSSEUpdate({
id: requestId,
type: 'stage-update',
stage: 'initialization-error',
message: 'Failed to start image generation.',
timestamp: new Date().toISOString(),
status: 'error'
});
// Return an error response
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
res.status(500).json({ error: 'Failed to start image generation', details: errorMessage });
}
});
// Health check endpoint
app.get('/api/health', (req: Request, res: Response) => {
res.json({ status: 'OK', message: 'Server is running' });
});
// Connection validation endpoint
app.get('/api/validate-connection', async (req: Request, res: Response) => {
const validationResult = await validateATXPConnectionString(req);
if (validationResult.isValid) {
res.json({
valid: true,
message: 'Valid ATXP account connection string found'
});
} else {
res.status(400).json({
valid: false,
error: validationResult.error
});
}
});
// Helper to resolve static path for frontend build
function getStaticPath() {
const candidates = [
// Development: running from project root
path.join(__dirname, './frontend/build'),
// Development: running from backend/ directory
path.join(__dirname, '../frontend/build'),
// Production: running from backend/dist/
path.join(__dirname, '../../frontend/build'),
// Vercel: frontend build copied to backend directory
path.join(__dirname, './build'),
// Vercel: alternative paths
'/var/task/backend/build',
// Development fallback
path.join(__dirname, '../build')
];
console.log('__dirname:', __dirname);
console.log('Looking for frontend build in candidates:', candidates);
for (const candidate of candidates) {
console.log(`Checking: ${candidate}, exists: ${fs.existsSync(candidate)}`);
if (fs.existsSync(candidate)) {
console.log(`Found frontend build at: ${candidate}`);
return candidate;
}
}
// List contents of current directory for debugging
try {
const currentDirContents = fs.readdirSync(__dirname);
console.log(`Contents of __dirname (${__dirname}):`, currentDirContents);
// Also check if build directory exists but is empty
const buildPath = path.join(__dirname, './build');
if (fs.existsSync(buildPath)) {
try {
const buildContents = fs.readdirSync(buildPath);
console.log(`Contents of build directory (${buildPath}):`, buildContents);
} catch (error) {
console.log('Could not read build directory contents:', error);
}
}
} catch (error) {
console.log('Could not read __dirname contents:', error);
}
// Fallback: throw error with more debugging info
throw new Error(`No frontend build directory found. __dirname: ${__dirname}. Checked paths: ${candidates.join(', ')}`);
}
// Serve static files in production
if (process.env.NODE_ENV === 'production') {
// Add static file serving middleware
app.use(express.static(getStaticPath()));
// Handle client-side routing by serving index.html for non-API routes
app.get('*', (req: Request, res: Response) => {
// Only serve index.html for non-API routes
if (!req.path.startsWith('/api/')) {
res.sendFile(path.join(getStaticPath(), 'index.html'));
} else {
res.status(404).json({ error: 'API endpoint not found' });
}
});
}
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});