Skip to content

Commit

Permalink
fix quotes.
Browse files Browse the repository at this point in the history
  • Loading branch information
sasagar committed Nov 11, 2023
1 parent 790e235 commit d3ef809
Show file tree
Hide file tree
Showing 3 changed files with 280 additions and 280 deletions.
38 changes: 19 additions & 19 deletions packages/backend/src/boot/entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,40 +7,40 @@
* Misskey Entry Point!
*/

import cluster from "node:cluster";
import { EventEmitter } from "node:events";
import chalk from "chalk";
import Xev from "xev";
import Logger from "@/logger.js";
import { envOption } from "../env.js";
import { masterMain } from "./master.js";
import { workerMain } from "./worker.js";
import cluster from 'node:cluster';
import { EventEmitter } from 'node:events';
import chalk from 'chalk';
import Xev from 'xev';
import Logger from '@/logger.js';
import { envOption } from '../env.js';
import { masterMain } from './master.js';
import { workerMain } from './worker.js';

import "reflect-metadata";
import 'reflect-metadata';

process.title = `Misskey (${cluster.isPrimary ? "master" : "worker"})`;
process.title = `Misskey (${cluster.isPrimary ? 'master' : 'worker'})`;

Error.stackTraceLimit = Infinity;
EventEmitter.defaultMaxListeners = 128;

const logger = new Logger("core", "cyan");
const clusterLogger = logger.createSubLogger("cluster", "orange", false);
const logger = new Logger('core', 'cyan');
const clusterLogger = logger.createSubLogger('cluster', 'orange', false);
const ev = new Xev();

//#region Events

// Listen new workers
cluster.on("fork", (worker) => {
cluster.on('fork', (worker) => {
clusterLogger.debug(`Process forked: [${worker.id}]`);
});

// Listen online workers
cluster.on("online", (worker) => {
cluster.on('online', (worker) => {
clusterLogger.debug(`Process is now online: [${worker.id}]`);
});

// Listen for dying workers
cluster.on("exit", (worker) => {
cluster.on('exit', (worker) => {
// Replace the dead worker,
// we're not sentimental
clusterLogger.error(chalk.red(`[${worker.id}] died :(`));
Expand All @@ -49,19 +49,19 @@ cluster.on("exit", (worker) => {

// Display detail of unhandled promise rejection
if (!envOption.quiet) {
process.on("unhandledRejection", console.dir);
process.on('unhandledRejection', console.dir);
}

// Display detail of uncaught exception
process.on("uncaughtException", (err) => {
process.on('uncaughtException', (err) => {
try {
logger.error(err);
console.trace(err);
} catch {}
});

// Dying away...
process.on("exit", (code) => {
process.on('exit', (code) => {
logger.info(`The process is going to exit with code ${code}`);
});

Expand All @@ -82,5 +82,5 @@ if (cluster.isWorker || envOption.disableClustering) {
// ユニットテスト時にMisskeyが子プロセスで起動された時のため
// それ以外のときは process.send は使えないので弾く
if (process.send) {
process.send("ok");
process.send('ok');
}
130 changes: 65 additions & 65 deletions packages/backend/src/server/ServerService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,36 @@
* SPDX-FileCopyrightText: syuilo and other misskey contributors
* SPDX-License-Identifier: AGPL-3.0-only
*/
import cluster from "node:cluster";
import * as fs from "node:fs";
import { fileURLToPath } from "node:url";
import { Inject, Injectable, OnApplicationShutdown } from "@nestjs/common";
import Fastify, { FastifyInstance } from "fastify";
import fastifyStatic from "@fastify/static";
import { IsNull } from "typeorm";
import { GlobalEventService } from "@/core/GlobalEventService.js";
import type { Config } from "@/config.js";
import type { EmojisRepository, UserProfilesRepository, UsersRepository } from "@/models/_.js";
import { DI } from "@/di-symbols.js";
import type Logger from "@/logger.js";
import * as Acct from "@/misc/acct.js";
import { genIdenticon } from "@/misc/gen-identicon.js";
import { createTemp } from "@/misc/create-temp.js";
import { UserEntityService } from "@/core/entities/UserEntityService.js";
import { LoggerService } from "@/core/LoggerService.js";
import { bindThis } from "@/decorators.js";
import { MetaService } from "@/core/MetaService.js";
import { ActivityPubServerService } from "./ActivityPubServerService.js";
import { NodeinfoServerService } from "./NodeinfoServerService.js";
import { ApiServerService } from "./api/ApiServerService.js";
import { StreamingApiServerService } from "./api/StreamingApiServerService.js";
import { WellKnownServerService } from "./WellKnownServerService.js";
import { FileServerService } from "./FileServerService.js";
import { ClientServerService } from "./web/ClientServerService.js";
import { OpenApiServerService } from "./api/openapi/OpenApiServerService.js";
import { OAuth2ProviderService } from "./oauth/OAuth2ProviderService.js";

const _dirname = fileURLToPath(new URL(".", import.meta.url));
import cluster from 'node:cluster';
import * as fs from 'node:fs';
import { fileURLToPath } from 'node:url';
import { Inject, Injectable, OnApplicationShutdown } from '@nestjs/common';
import Fastify, { FastifyInstance } from 'fastify';
import fastifyStatic from '@fastify/static';
import { IsNull } from 'typeorm';
import { GlobalEventService } from '@/core/GlobalEventService.js';
import type { Config } from '@/config.js';
import type { EmojisRepository, UserProfilesRepository, UsersRepository } from '@/models/_.js';
import { DI } from '@/di-symbols.js';
import type Logger from '@/logger.js';
import * as Acct from '@/misc/acct.js';
import { genIdenticon } from '@/misc/gen-identicon.js';
import { createTemp } from '@/misc/create-temp.js';
import { UserEntityService } from '@/core/entities/UserEntityService.js';
import { LoggerService } from '@/core/LoggerService.js';
import { bindThis } from '@/decorators.js';
import { MetaService } from '@/core/MetaService.js';
import { ActivityPubServerService } from './ActivityPubServerService.js';
import { NodeinfoServerService } from './NodeinfoServerService.js';
import { ApiServerService } from './api/ApiServerService.js';
import { StreamingApiServerService } from './api/StreamingApiServerService.js';
import { WellKnownServerService } from './WellKnownServerService.js';
import { FileServerService } from './FileServerService.js';
import { ClientServerService } from './web/ClientServerService.js';
import { OpenApiServerService } from './api/openapi/OpenApiServerService.js';
import { OAuth2ProviderService } from './oauth/OAuth2ProviderService.js';

const _dirname = fileURLToPath(new URL('.', import.meta.url));

@Injectable()
export class ServerService implements OnApplicationShutdown {
Expand Down Expand Up @@ -65,7 +65,7 @@ export class ServerService implements OnApplicationShutdown {
private loggerService: LoggerService,
private oauth2ProviderService: OAuth2ProviderService
) {
this.logger = this.loggerService.getLogger("server", "gray", false);
this.logger = this.loggerService.getLogger('server', 'gray', false);
}

@bindThis
Expand All @@ -78,9 +78,9 @@ export class ServerService implements OnApplicationShutdown {

// HSTS
// 6months (15552000sec)
if (this.config.url.startsWith("https") && !this.config.disableHsts) {
fastify.addHook("onRequest", (request, reply, done) => {
reply.header("strict-transport-security", "max-age=15552000; preload");
if (this.config.url.startsWith('https') && !this.config.disableHsts) {
fastify.addHook('onRequest', (request, reply, done) => {
reply.header('strict-transport-security', 'max-age=15552000; preload');
done();
});
}
Expand All @@ -92,7 +92,7 @@ export class ServerService implements OnApplicationShutdown {
serve: false,
});

fastify.register(this.apiServerService.createServer, { prefix: "/api" });
fastify.register(this.apiServerService.createServer, { prefix: '/api' });
fastify.register(this.openApiServerService.createServer);
fastify.register(this.fileServerService.createServer);
fastify.register(this.activityPubServerService.createServer);
Expand All @@ -103,58 +103,58 @@ export class ServerService implements OnApplicationShutdown {
fastify.get<{
Params: { path: string };
Querystring: { static?: any; badge?: any };
}>("/emoji/:path(.*)", async (request, reply) => {
}>('/emoji/:path(.*)', async (request, reply) => {
const path = request.params.path;

reply.header("Cache-Control", "public, max-age=86400");
reply.header('Cache-Control', 'public, max-age=86400');

if (!path.match(/^[a-zA-Z0-9\-_@\.]+?\.webp$/)) {
reply.code(404);
return;
}

const name = path.split("@")[0].replace(".webp", "");
const host = path.split("@")[1]?.replace(".webp", "");
const name = path.split('@')[0].replace('.webp', '');
const host = path.split('@')[1]?.replace('.webp', '');

const emoji = await this.emojisRepository.findOneBy({
// `@.` is the spec of ReactionService.decodeReaction
host: host == null || host === "." ? IsNull() : host,
host: host == null || host === '.' ? IsNull() : host,
name: name,
});

reply.header(
"Content-Security-Policy",
"default-src 'none'; style-src 'unsafe-inline'"
'Content-Security-Policy',
'default-src 'none'; style-src 'unsafe-inline''
);

if (emoji == null) {
if ("fallback" in request.query) {
return await reply.redirect("/static-assets/emoji-unknown.png");
if ('fallback' in request.query) {
return await reply.redirect('/static-assets/emoji-unknown.png');
} else {
reply.code(404);
return;
}
}

let url: URL;
if ("badge" in request.query) {
if ('badge' in request.query) {
url = new URL(`${this.config.mediaProxy}/emoji.png`);
// || emoji.originalUrl してるのは後方互換性のため(publicUrlはstringなので??はだめ)
url.searchParams.set("url", emoji.publicUrl || emoji.originalUrl);
url.searchParams.set("badge", "1");
url.searchParams.set('url', emoji.publicUrl || emoji.originalUrl);
url.searchParams.set('badge', '1');
} else {
url = new URL(`${this.config.mediaProxy}/emoji.webp`);
// || emoji.originalUrl してるのは後方互換性のため(publicUrlはstringなので??はだめ)
url.searchParams.set("url", emoji.publicUrl || emoji.originalUrl);
url.searchParams.set("emoji", "1");
if ("static" in request.query) url.searchParams.set("static", "1");
url.searchParams.set('url', emoji.publicUrl || emoji.originalUrl);
url.searchParams.set('emoji', '1');
if ('static' in request.query) url.searchParams.set('static', '1');
}

return await reply.redirect(301, url.toString());
});

fastify.get<{ Params: { acct: string } }>(
"/avatar/@:acct",
'/avatar/@:acct',
async (request, reply) => {
const { username, host } = Acct.parse(request.params.acct);
const user = await this.usersRepository.findOne({
Expand All @@ -165,36 +165,36 @@ export class ServerService implements OnApplicationShutdown {
},
});

reply.header("Cache-Control", "public, max-age=86400");
reply.header('Cache-Control', 'public, max-age=86400');

if (user) {
reply.redirect(
user.avatarUrl ?? this.userEntityService.getIdenticonUrl(user)
);
} else {
reply.redirect("/static-assets/user-unknown.png");
reply.redirect('/static-assets/user-unknown.png');
}
}
);

fastify.get<{ Params: { x: string } }>(
"/identicon/:x",
'/identicon/:x',
async (request, reply) => {
reply.header("Content-Type", "image/png");
reply.header("Cache-Control", "public, max-age=86400");
reply.header('Content-Type', 'image/png');
reply.header('Cache-Control', 'public, max-age=86400');

if ((await this.metaService.fetch()).enableIdenticonGeneration) {
const [temp, cleanup] = await createTemp();
await genIdenticon(request.params.x, fs.createWriteStream(temp));
return fs.createReadStream(temp).on("close", () => cleanup());
return fs.createReadStream(temp).on('close', () => cleanup());
} else {
return reply.redirect("/static-assets/avatar.png");
return reply.redirect('/static-assets/avatar.png');
}
}
);

fastify.get<{ Params: { code: string } }>(
"/verify-email/:code",
'/verify-email/:code',
async (request, reply) => {
const profile = await this.userProfilesRepository.findOneBy({
emailVerifyCode: request.params.code,
Expand All @@ -211,7 +211,7 @@ export class ServerService implements OnApplicationShutdown {

this.globalEventService.publishMainStream(
profile.userId,
"meUpdated",
'meUpdated',
await this.userEntityService.pack(
profile.userId,
{ id: profile.userId },
Expand All @@ -234,14 +234,14 @@ export class ServerService implements OnApplicationShutdown {

this.streamingApiServerService.attach(fastify.server);

fastify.server.on("error", (err) => {
fastify.server.on('error', (err) => {
switch ((err as any).code) {
case "EACCES":
case 'EACCES':
this.logger.error(
`You do not have permission to listen on port ${this.config.port}.`
);
break;
case "EADDRINUSE":
case 'EADDRINUSE':
this.logger.error(
`Port ${this.config.port} is already in use by another process.`
);
Expand All @@ -252,7 +252,7 @@ export class ServerService implements OnApplicationShutdown {
}

if (cluster.isWorker) {
process.send!("listenFailed");
process.send!('listenFailed');
} else {
// disableClustering
process.exit(1);
Expand All @@ -269,7 +269,7 @@ export class ServerService implements OnApplicationShutdown {
}
});
} else {
fastify.listen({ port: this.config.port, host: "0.0.0.0" });
fastify.listen({ port: this.config.port, host: '0.0.0.0' });
}

await fastify.ready();
Expand Down
Loading

0 comments on commit d3ef809

Please sign in to comment.