Commit 997b53ef authored by nanahira's avatar nanahira

first

parents
Pipeline #16881 passed with stages
in 2 minutes and 22 seconds
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
/data
/output
/config.yaml
.git*
Dockerfile
.dockerignore
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
tsconfigRootDir : __dirname,
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
/data
/output
/config.yaml
\ No newline at end of file
stages:
- build
- deploy
variables:
GIT_DEPTH: "1"
before_script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
.build-image:
stage: build
script:
- docker build --pull -t $TARGET_IMAGE .
- docker push $TARGET_IMAGE
build-x86:
extends: .build-image
tags:
- docker
variables:
TARGET_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG-x86
build-arm:
extends: .build-image
tags:
- docker-arm
variables:
TARGET_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG-arm
.deploy:
stage: deploy
tags:
- docker
script:
- docker pull $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG-x86
- docker pull $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG-arm
- docker manifest create $TARGET_IMAGE --amend $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG-x86 --amend
$CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG-arm
- docker manifest push $TARGET_IMAGE
deploy_latest:
extends: .deploy
variables:
TARGET_IMAGE: $CI_REGISTRY_IMAGE:latest
only:
- master
deploy_branch:
extends: .deploy
variables:
TARGET_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG
/install-npm.sh
.git*
/data
/output
/config.yaml
.idea
.dockerignore
Dockerfile
/src
{
"singleQuote": true,
"trailingComma": "all"
}
\ No newline at end of file
FROM node:lts-bullseye-slim as base
LABEL Author="Nanahira <nanahira@momobako.com>"
RUN apt update && apt -y install python3 build-essential && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /var/log/*
WORKDIR /usr/src/app
COPY ./package*.json ./
FROM base as builder
RUN npm ci && npm cache clean --force
COPY . ./
RUN npm run build
FROM base
ENV NODE_ENV production
RUN npm ci && npm cache clean --force
COPY --from=builder /usr/src/app/dist ./dist
COPY ./config.example.yaml ./config.yaml
EXPOSE 3000
CMD [ "npm", "run", "start:prod" ]
This diff is collapsed.
# App name
App description.
## Installation
```bash
$ npm install
```
## Config
- `REDIS_URI` - Redis connection URI. eg. `redis://:password@localhost:6379/4`
- `ACCOUNTS_URL` - Accounts service URL. eg. `https://sapi.moecube.com:444/accounts`
- `MAX_SERVER_COUNT` Max server count for non-admin users. default `10`.
## Running the app
```bash
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
```
## License
AGPLv3
host: '::'
port: 3000
#!/bin/bash
npm install --save \
class-validator \
class-transformer \
@nestjs/swagger \
@nestjs/config \
yaml
npm install --save-dev \
@types/express
{
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"plugins": ["@nestjs/swagger"]
}
}
This diff is collapsed.
{
"name": "gameserver-registry",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs/common": "^9.0.0",
"@nestjs/config": "^2.2.0",
"@nestjs/core": "^9.0.0",
"@nestjs/platform-express": "^9.0.0",
"@nestjs/swagger": "^6.1.2",
"aragami": "^1.1.2",
"class-transformer": "^0.5.1",
"class-validator": "^0.13.2",
"nestjs-aragami": "^1.0.0",
"nestjs-mycard": "^3.0.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.2.0",
"yaml": "^2.1.1"
},
"devDependencies": {
"@nestjs/cli": "^9.0.0",
"@nestjs/schematics": "^9.0.0",
"@nestjs/testing": "^9.0.0",
"@types/express": "^4.17.14",
"@types/jest": "28.1.8",
"@types/node": "^16.0.0",
"@types/supertest": "^2.0.11",
"@typescript-eslint/eslint-plugin": "^5.0.0",
"@typescript-eslint/parser": "^5.0.0",
"eslint": "8.22.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"jest": "28.1.3",
"prettier": "^2.3.2",
"source-map-support": "^0.5.20",
"supertest": "^6.1.3",
"ts-jest": "28.0.8",
"ts-loader": "^9.2.3",
"ts-node": "^10.0.0",
"tsconfig-paths": "4.1.0",
"typescript": "^4.7.4"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should be defined', () => {
expect(appController).toBeDefined();
});
});
});
import {
Body,
Controller,
Delete,
Get,
Param,
Put,
Query,
ValidationPipe,
} from '@nestjs/common';
import { AppService } from './app.service';
import {
ApiBody,
ApiCreatedResponse,
ApiHeader,
ApiNoContentResponse,
ApiOkResponse,
ApiOperation,
ApiParam,
ApiQuery,
} from '@nestjs/swagger';
import { GameServer, GameServerInput } from './dto/GameServer.dto';
import {
BlankReturnMessageDto,
ReturnMessageDto,
} from './dto/ReturnMessage.dto';
import { MycardUser, PutMycardUser } from 'nestjs-mycard';
const ServerReturnMessageDto = ReturnMessageDto(GameServer);
@Controller('api/server-list/:ns')
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
@ApiOperation({ summary: 'Get server list' })
@ApiParam({ name: 'ns', description: 'Namespace' })
@ApiOkResponse({ type: [GameServer] })
serverList(@Param('ns') ns: string) {
return this.appService.serverList(ns);
}
@Put()
@ApiOperation({ summary: 'Register server. Must refresh once every minute.' })
@ApiParam({ name: 'ns', description: 'Namespace' })
@ApiHeader({
name: 'Authorization',
description: 'Bearer token from MyCard account.',
})
@ApiBody({ type: GameServerInput })
@ApiCreatedResponse({ type: ServerReturnMessageDto })
async registerServer(
@Param('ns') ns: string,
@PutMycardUser() user: MycardUser,
@Body(
new ValidationPipe({
transform: true,
transformOptions: { enableImplicitConversion: true },
}),
)
input: GameServerInput,
) {
const server = await this.appService.registerServer(ns, user, input);
return new ServerReturnMessageDto(201, 'success', server);
}
@Delete()
@ApiOperation({ summary: 'Delete server.' })
@ApiParam({ name: 'ns', description: 'Namespace' })
@ApiHeader({
name: 'Authorization',
description: 'Bearer token from MyCard account.',
})
@ApiQuery({ name: 'name', description: 'Server name' })
@ApiNoContentResponse({ type: BlankReturnMessageDto })
async deleteServer(
@Param('ns') ns: string,
@PutMycardUser() user: MycardUser,
@Query('name') name: string,
) {
await this.appService.deleteServer(ns, user, name);
return new BlankReturnMessageDto(204, 'success');
}
}
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { loadConfig } from './utility/config';
import { AragamiModule } from 'nestjs-aragami';
import { MycardAuthModule } from 'nestjs-mycard';
@Module({
imports: [
ConfigModule.forRoot({
load: [loadConfig],
isGlobal: true,
ignoreEnvVars: true,
ignoreEnvFile: true,
}),
AragamiModule.registerAsync({
inject: [ConfigService],
useFactory: (configService: ConfigService) => {
const uri = configService.get<string>('REDIS_URI');
return {
redis: uri ? { uri } : undefined,
};
},
}),
MycardAuthModule.registerAsync({
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
accountUrl: configService.get<string>('ACCOUNT_URL'),
}),
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
import { Injectable, ConsoleLogger } from '@nestjs/common';
import { Aragami } from 'aragami';
import { InjectAragami } from 'nestjs-aragami';
import { GameServer, GameServerInput } from './dto/GameServer.dto';
import { MycardUser } from 'nestjs-mycard';
import { ConfigService } from '@nestjs/config';
import { BlankReturnMessageDto } from './dto/ReturnMessage.dto';
@Injectable()
export class AppService extends ConsoleLogger {
private maxServerCount = parseInt(this.config.get('MAX_SERVER_COUNT'));
constructor(
@InjectAragami() private readonly aragami: Aragami,
private config: ConfigService,
) {
super('app');
}
async serverList(ns: string) {
return this.aragami.values(GameServer, `${ns}:`);
}
async registerServer(ns: string, user: MycardUser, input: GameServerInput) {
const server = new GameServer().withNs(ns).fromInput(input).fromOwner(user);
if (!user.admin) {
const existingServers = await this.aragami.keys(
GameServer,
`${ns}:${user.username}:`,
);
if (existingServers.length > this.maxServerCount) {
throw new BlankReturnMessageDto(
403,
'You have too many servers.',
).toException();
} else if (existingServers.length === this.maxServerCount) {
const existingServer = await this.aragami.get(
GameServer,
server.cacheKey(),
);
if (!existingServer) {
throw new BlankReturnMessageDto(
403,
'You have too many servers.',
).toException();
}
}
}
const errorReason = await server.testConnection();
if (errorReason) {
throw new BlankReturnMessageDto(
404,
`Server broken: ${errorReason}`,
).toException();
}
await this.aragami.set(server);
return server;
}
async deleteServer(ns: string, user: MycardUser, name: string) {
const server = await this.aragami.get(
GameServer,
`${ns}:${user.username}:${name}`,
);
if (!server) {
throw new BlankReturnMessageDto(404, 'Server not found.').toException();
}
await this.aragami.del(server);
}
}
import { CacheKey, CachePrefix, CacheTTL } from 'aragami';
import {
IsInt,
IsNotEmpty,
IsPositive,
IsString,
Max,
MaxLength,
Min,
} from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
import { MycardUser } from 'nestjs-mycard';
import * as net from 'net';
export class GameServerInput {
@IsString()
@ApiProperty({ description: 'The name of the game server' })
@IsNotEmpty()
@MaxLength(32)
name: string;
@IsString()
@ApiProperty({ description: 'The description of the game server' })
@MaxLength(256)
description: string;
@IsString()
@MaxLength(100)
@ApiProperty({ description: 'The address of the game server' })
host: string;
@IsPositive()
@IsInt()
@Min(1)
@Max(65535)
@ApiProperty({ description: 'The port of the game server' })
port: number;
async testConnection() {
return new Promise<string>((resolve) => {
const socket = new net.Socket();
socket.connect(this.port, this.host);
socket.setTimeout(5000);
socket.on('connect', () => {
socket.destroy();
resolve(undefined);
});
socket.on('error', (error) => {
socket.destroy();
resolve(error.message);
});
socket.on('timeout', () => {
socket.destroy();
resolve('Connection timed out.');
});
});
}
}
@CacheTTL(600000)
@CachePrefix('server')
export class GameServer extends GameServerInput {
@ApiProperty({ description: 'The ID of the game.' })
ns: string;
@ApiProperty({ description: 'The username of the game server owner.' })
ownerUsername: string;
@ApiProperty({ description: 'The name of the game server owner.' })
owner: string;
fromInput(input: GameServerInput) {
this.name = input.name;
this.description = input.description;
this.host = input.host;
this.port = input.port;
return this;
}
fromOwner(user: MycardUser) {
this.ownerUsername = user.username;
this.owner = user.name;
return this;
}
withNs(ns: string) {
this.ns = ns;
return this;
}
@CacheKey()
cacheKey() {
return `${this.ns}:${this.ownerUsername}:${this.name}`;
}
}
import { ApiProperty } from '@nestjs/swagger';
import { HttpException } from '@nestjs/common';
export interface BlankReturnMessage {
statusCode: number;
message: string;
success: boolean;
}
export interface ReturnMessage<T> extends BlankReturnMessage {
data?: T;
}
export class BlankReturnMessageDto implements BlankReturnMessage {
@ApiProperty({ description: 'Return code' })
statusCode: number;
@ApiProperty({ description: 'Return message' })
message: string;
@ApiProperty({ description: 'Whether success.' })
success: boolean;
constructor(statusCode: number, message?: string) {
this.statusCode = statusCode;
this.message = message || 'success';
this.success = statusCode < 400;
}
toException() {
return new HttpException(this, this.statusCode);
}
}
type AnyClass = new (...args: any[]) => any;
type ClassOrArray = AnyClass | [AnyClass];
type TypeFromClass<T> = T extends new (...args: any[]) => infer U ? U : never;
export type ParseType<T extends ClassOrArray> = T extends [infer U]
? TypeFromClass<U>[]
: TypeFromClass<T>;
function getClass(o: ClassOrArray) {
return o instanceof Array ? o[0] : o;
}
export function ReturnMessageDto<T extends ClassOrArray>(type: T) {
const cl = class SpecificReturnMessage extends BlankReturnMessageDto {
data?: ParseType<T>;
constructor(statusCode: number, message?: string, data?: ParseType<T>) {
super(statusCode, message);
this.data = data;
}
};
ApiProperty({ description: 'Return data.', type, required: false })(
cl.prototype,
'data',
);
Object.defineProperty(cl, 'name', {
value: `${getClass(type).name}ReturnMessageDto`,
});
return cl;
}
export class StringReturnMessageDto
extends BlankReturnMessageDto
implements ReturnMessage<string>
{
@ApiProperty({ description: 'Return data.' })
data?: string;
constructor(statusCode: number, message?: string, data?: string) {
super(statusCode, message);
this.data = data;
}
}
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { NestExpressApplication } from '@nestjs/platform-express';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
app.enableCors();
app.set('trust proxy', ['172.16.0.0/12', 'loopback']);
const documentConfig = new DocumentBuilder()
.setTitle('app')
.setDescription('The app')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, documentConfig);
SwaggerModule.setup('docs', app, document);
const config = app.get(ConfigService);
await app.listen(
config.get<number>('port') || 3000,
config.get<string>('host') || '::',
);
}
bootstrap();
import yaml from 'yaml';
import * as fs from 'fs';
const defaultConfig = {
host: '::',
port: 3000,
REDIS_URI: '',
ACCOUNT_URL: 'https://sapi.moecube.com:444/accounts',
MAX_SERVER_COUNT: 5,
};
export type Config = typeof defaultConfig;
export async function loadConfig(): Promise<Config> {
let readConfig: Partial<Config> = {};
try {
const configText = await fs.promises.readFile('./config.yaml', 'utf-8');
readConfig = yaml.parse(configText);
} catch (e) {
console.error(`Failed to read config: ${e.toString()}`);
}
return {
...defaultConfig,
...readConfig,
...process.env,
};
}
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
/* it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
}); */
});
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2021",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"esModuleInterop": true
},
"compileOnSave": true,
"allowJs": true
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment