Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix cors gateway and updates #41

Closed
wants to merge 11 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 42 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ The frontend user interface for Mr.market on Mixin.

### Prerequisites

Install dependencies with npm
Install dependencies with yarn

```
npm install
Expand All @@ -37,7 +37,7 @@ npm install
### Run development server

```
npm run dev
npm dev
```

If you're using bun:
Expand Down Expand Up @@ -73,6 +73,45 @@ npm run test:e2e
* [Svelte](https://svelte.dev/) - Web framework
* [Daisy UI](https://daisyui.com/) - UI framework

---

The backend server for Mr.market.

## Getting Started

### Prerequisites

Install dependencies with yarn

```
yarn
```

### Run development server

```
yarn start
```

## Tests

```
yarn test
```

## Built With

* [Nest.js](https://nestjs.com/) - Backend API framework

## Contributing

Please read [CONTRIBUTING.md]() for details on our code of conduct, and the process for submitting pull requests to us.

## License

This project is licensed under the GNU Affero General Public License - see the [LICENSE.md](../LICENSE) file for details


# License

This project is licensed under the GNU Affero General Public License - see the [LICENSE.md](LICENSE) file for details
This project is licensed under the GNU Affero General Public License - see the [LICENSE.md](LICENSE) file for details
13 changes: 13 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"name": "hufi",
"version": "1.0.0",
"description": "This is highly alpha code. Do not use it or you will lose all your money",
"main": "index.js",
"scripts": {
"start": "concurrently \"npm run start --prefix server\" \"npm run start --prefix interface\"",
"install:frontend": "npm install --prefix interface",
"install:server": "npm install --prefix server"
},
"keywords": [],
"author": ""
}
1 change: 1 addition & 0 deletions server/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ dotenv.config();
database: process.env.POSTGRES_DATABASE,
entities: [Trade, Performance, Transaction, UserBalance],
synchronize: true,
ssl: true,
}),
TradeModule,
StrategyModule,
Expand Down
68 changes: 16 additions & 52 deletions server/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,64 +1,28 @@
import * as fs from 'fs';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { CustomLogger } from './modules/logger/logger.service';

async function bootstrap() {
const logger = new CustomLogger(AppModule.name);
const dev = true;
if (dev) {
const app = await NestFactory.create(AppModule);
app.enableCors({
origin: true,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
credentials: true,
});
const app = await NestFactory.create(AppModule);
app.enableCors();

// Global request logging
app.use((req, res, next) => {
logger.log(`Incoming request: ${req.method} ${req.url}`);
next();
});
// Global request logging
app.use((req, _, next) => {
logger.log(`Incoming request: ${req.method} ${req.url}`);
next();
});

const config = new DocumentBuilder()
.setTitle('Mixin Doc backend API')
.setDescription('Mixin Doc backend to execute trades and strategies')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('docs', app, document);
const config = new DocumentBuilder()
.setTitle('Mixin Doc backend API')
.setDescription('Mixin Doc backend to execute trades and strategies')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('docs', app, document);

const port = process.env.PORT || 3000;
await app.listen(port);
} else {
const httpsOptions = {
key: fs.readFileSync(
'/etc/letsencrypt/live/bc6e1fa0-3c5a-4235-809c-c4fcc4a5d859.mvg.fi/privkey.pem',
),
cert: fs.readFileSync(
'/etc/letsencrypt/live/bc6e1fa0-3c5a-4235-809c-c4fcc4a5d859.mvg.fi/fullchain.pem',
),
};
const app = await NestFactory.create(AppModule, { httpsOptions });
app.enableCors();

// Global request logging
app.use((req, res, next) => {
console.log(`Incoming request: ${req.method} ${req.url}`);
next();
});

const config = new DocumentBuilder()
.setTitle('Mixin Doc backend API')
.setDescription('Mixin Doc backend to execute trades and strategies')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('docs', app, document);

const port = process.env.PORT || 3000;
await app.listen(port);
}
const port = process.env.PORT || 3000;
await app.listen(port);
}
bootstrap();
74 changes: 29 additions & 45 deletions server/src/modules/logger/logger.service.ts
Original file line number Diff line number Diff line change
@@ -1,65 +1,49 @@
import { Injectable, Logger, Scope } from '@nestjs/common';
import * as winston from 'winston';
import * as path from 'path';
import * as fs from 'fs';

@Injectable({ scope: Scope.DEFAULT })
export class CustomLogger extends Logger {
private readonly logsDir = path.join(__dirname, '..', '..', 'logs');
private logFilePath: string;
private errorFilePath: string;
private logger: winston.Logger;

constructor(context?: string) {
super(context);
if (!fs.existsSync(this.logsDir)) {
fs.mkdirSync(this.logsDir, { recursive: true });
}
const date = new Date().toISOString().slice(0, 10); // Format: YYYY-MM-DD
this.logFilePath = this.generateFilePath('log', date);
this.errorFilePath = this.generateFilePath('error', date);
}

private generateFilePath(baseName: string, date: string): string {
let filePath;
let fileNumber = 1;
do {
filePath = path.join(
this.logsDir,
`${baseName}_${fileNumber}_${date}.log`,
);
fileNumber++;
} while (fs.existsSync(filePath));
return filePath;
}

private writeToFile(filePath: string, message: string): void {
fs.appendFile(filePath, message, (err) => {
if (err) {
console.error('Failed to write log:', err);
}
const logsDir = process.env.IS_DEV
? path.join(__dirname, '..', '..', 'logs')
: path.join(__dirname, '..', 'logs'); // Adjust as necessary for production

this.logger = winston.createLogger({
level: 'info', // Default logging level
format: winston.format.combine(
winston.format.timestamp(),
winston.format.printf(
(info) =>
`[${info.timestamp}] [${info.level.toUpperCase()}] [${
context || this.context
}] ${info.message}`,
),
),
transports: [
new winston.transports.Console(), // Log to console
new winston.transports.File({
filename: path.join(logsDir, 'error.log'),
level: 'error',
}),
new winston.transports.File({
filename: path.join(logsDir, 'combined.log'),
}),
],
});
}

private formatMessage(level: string, message: any, context?: string): string {
const timestamp = new Date().toISOString();
return `[${timestamp}] [${level.toUpperCase()}] [${
context || this.context
}] ${message}\n`;
}

log(message: any, context?: string) {
super.log(message, context); // NestJS's internal logging
const formattedMessage = this.formatMessage('info', message, context);
this.writeToFile(this.logFilePath, formattedMessage);
this.logger.info(message, { context });
}

error(message: any, trace?: string, context?: string) {
super.error(message, trace, context); // NestJS's internal error logging
const formattedMessage = this.formatMessage(
'error',
`${message}, Trace: ${trace}`,
context,
);
this.writeToFile(this.errorFilePath, formattedMessage);
this.logger.error(`${message}, Trace: ${trace}`, { context });
}

// Implement warn, debug, verbose similarly...
Expand Down
6 changes: 4 additions & 2 deletions server/src/modules/marketdata/marketdata.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ import {
import { CustomLogger } from '../logger/logger.service';

const webSocketPort = process.env.WS_PORT || '3012';
@WebSocketGateway(parseInt(webSocketPort), {
@WebSocketGateway(parseInt(webSocketPort, 10), {
namespace: '/marketdata',
cors: true,
cors: {
origin: "*", // Allow all origins, Temporary to be changed and restricted.
},
})
export class MarketDataGateway
implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
Expand Down
Loading
Loading