refactor: read server config in backend-rs

This commit is contained in:
naskya 2024-01-27 07:38:30 +09:00
parent 9cc05e565b
commit 0db57bd423
Signed by: naskya
GPG key ID: 712D413B3A9FED5C
9 changed files with 27 additions and 53 deletions

View file

@ -1,9 +1,10 @@
use once_cell::sync::Lazy;
use serde::Deserialize;
use serde_yaml;
use std::env;
use std::fs;
#[derive(Debug, PartialEq, Deserialize)]
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
#[napi_derive::napi(object)]
pub struct ServerConfig {
@ -13,7 +14,7 @@ pub struct ServerConfig {
pub cache_server: Option<RedisConfig>,
}
#[derive(Debug, PartialEq, Deserialize)]
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[napi_derive::napi(object)]
pub struct DbConfig {
pub host: String,
@ -23,7 +24,7 @@ pub struct DbConfig {
pub pass: String,
}
#[derive(Debug, PartialEq, Deserialize)]
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[napi_derive::napi(object)]
pub struct RedisConfig {
pub host: String,
@ -37,7 +38,7 @@ pub struct RedisConfig {
pub prefix: String,
}
#[derive(Debug, PartialEq, Deserialize)]
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
#[napi_derive::napi(object)]
pub struct TlsConfig {
@ -52,3 +53,5 @@ pub fn read_server_config() -> ServerConfig {
.expect("Failed to open '.config/default.yml'");
serde_yaml::from_reader(yml).expect("Failed to parse yaml")
}
pub static SERVER_CONFIG: Lazy<ServerConfig> = Lazy::new(read_server_config);

View file

@ -1,7 +1,7 @@
pub mod error;
pub use error::NapiDbErrExt;
use crate::config::server::DbConfig;
use crate::config::server::SERVER_CONFIG;
use sea_orm::{Database, DbConn};
use urlencoding::encode;
@ -16,14 +16,14 @@ impl JsDbConn {
}
#[napi_derive::napi]
pub async fn connect_to_database(config: DbConfig) -> napi::Result<JsDbConn> {
pub async fn connect_to_database() -> napi::Result<JsDbConn> {
let conn_uri = format!(
"postgres://{}:{}@{}:{}/{}",
config.user,
encode(&config.pass),
config.host,
config.port,
config.db,
SERVER_CONFIG.db.user,
encode(&SERVER_CONFIG.db.pass),
SERVER_CONFIG.db.host,
SERVER_CONFIG.db.port,
SERVER_CONFIG.db.db,
);
let conn = Database::connect(conn_uri)
.await
@ -34,17 +34,9 @@ pub async fn connect_to_database(config: DbConfig) -> napi::Result<JsDbConn> {
#[cfg(test)]
mod unit_test {
use super::connect_to_database;
use crate::config::server::read_server_config;
#[tokio::test]
async fn connect_with_server_config() {
assert!(connect_to_database(read_server_config().db).await.is_ok());
}
#[tokio::test]
async fn connect_with_incorrect_password() {
let mut config = read_server_config().db;
config.pass.push('.'); // password should be incorrect now
assert!(connect_to_database(config).await.is_err());
async fn connect_test() {
assert!(connect_to_database().await.is_ok());
}
}

View file

@ -1,24 +1,20 @@
use crate::config::server::ServerConfig;
use crate::config::server::SERVER_CONFIG;
use idna;
use url::Url;
#[napi_derive::napi]
pub fn get_full_ap_account(
server_config: ServerConfig,
username: String,
host: Option<String>,
) -> String {
pub fn get_full_ap_account(username: String, host: Option<String>) -> String {
if host.is_none() {
format!("{}@{}", username, extract_host(server_config.url))
format!("{}@{}", username, extract_host(SERVER_CONFIG.url.clone()))
} else {
format!("{}@{}", username, to_puny(host.unwrap()))
}
}
#[napi_derive::napi]
pub fn is_self_host(server_config: ServerConfig, host: Option<String>) -> bool {
pub fn is_self_host(host: Option<String>) -> bool {
if let Some(x) = host {
extract_host(server_config.url) == to_puny(x)
extract_host(SERVER_CONFIG.url.clone()) == to_puny(x)
} else {
true
}

View file

@ -3,18 +3,16 @@ import {
readEnvironmentConfig,
connectToDatabase,
fetchMeta as fetchMetaImpl,
getFullApAccount as getFullApAccountImpl,
hasOtherRenoteOfThisNote as hasOtherRenoteOfThisNoteImpl,
isSelfHost as isSelfHostImpl,
JsDbConn,
} from "backend-rs";
export const serverConfig = readServerConfig();
export const envConfig = readEnvironmentConfig();
const dbPromise = connectToDatabase(serverConfig.db);
type Option<T> = T | null | undefined;
const dbPromise = connectToDatabase();
const curryDb =
<P extends any[], R>(f: (db: JsDbConn, ...args: P) => Promise<R>) =>
(...args: P) =>
@ -22,14 +20,3 @@ const curryDb =
export const fetchMeta = curryDb(fetchMetaImpl);
export const hasOtherRenoteOfThisNote = curryDb(hasOtherRenoteOfThisNoteImpl);
export function getFullApAccount(
username: string,
host: Option<string>,
): string {
return getFullApAccountImpl(serverConfig, username, host);
}
export function isSelfHost(host: Option<string>): boolean {
return isSelfHostImpl(serverConfig, host);
}

View file

@ -2,8 +2,7 @@ import type { Antenna } from "@/models/entities/antenna.js";
import type { Note } from "@/models/entities/note.js";
import type { User } from "@/models/entities/user.js";
import { Blockings, Followings, UserProfiles } from "@/models/index.js";
import { getFullApAccount } from "@/misc/backend-rs.js";
import { stringToAcct } from "backend-rs";
import { getFullApAccount, stringToAcct } from "backend-rs";
import type { Packed } from "@/misc/schema.js";
import { Cache } from "@/misc/cache.js";
import { getWordHardMute } from "@/misc/check-word-mute.js";

View file

@ -3,8 +3,7 @@ import { Emojis } from "@/models/index.js";
import type { Emoji } from "@/models/entities/emoji.js";
import type { Note } from "@/models/entities/note.js";
import { Cache } from "./cache.js";
import { toPunyOptional } from "backend-rs";
import { isSelfHost } from "@/misc/backend-rs.js";
import { isSelfHost, toPunyOptional } from "backend-rs";
import { decodeReaction } from "./reaction-lib.js";
import config from "@/config/index.js";
import { query } from "@/prelude/url.js";

View file

@ -1,8 +1,7 @@
import type { CacheableRemoteUser } from "@/models/entities/user.js";
import type { IRead } from "../type.js";
import { getApId } from "../type.js";
import { extractHost } from "backend-rs";
import { isSelfHost } from "@/misc/backend-rs.js";
import { extractHost, isSelfHost } from "backend-rs";
import { MessagingMessages } from "@/models/index.js";
import { readUserMessagingMessage } from "@/server/api/common/read-messaging-message.js";

View file

@ -3,8 +3,7 @@ import { getJson } from "@/misc/fetch.js";
import type { ILocalUser } from "@/models/entities/user.js";
import { getInstanceActor } from "@/services/instance-actor.js";
import { fetchMeta } from "@/misc/backend-rs.js";
import { extractHost } from "backend-rs";
import { isSelfHost } from "@/misc/backend-rs.js";
import { extractHost, isSelfHost } from "backend-rs";
import { signedGet } from "./request.js";
import type { IObject, ICollection, IOrderedCollection } from "./type.js";
import { isCollectionOrOrderedCollection, getApId } from "./type.js";

View file

@ -9,7 +9,7 @@ import renderKey from "@/remote/activitypub/renderer/key.js";
import { renderPerson } from "@/remote/activitypub/renderer/person.js";
import renderEmoji from "@/remote/activitypub/renderer/emoji.js";
import { inbox as processInbox } from "@/queue/index.js";
import { isSelfHost } from "@/misc/backend-rs.js";
import { isSelfHost } from "backend-rs";
import {
Notes,
Users,