Compare commits

...

24 Commits

Author SHA1 Message Date
Book Pauk
f7e1e09928 Merge branch 'release/0.11.8-7' 2022-07-19 00:52:36 +07:00
Book Pauk
f0832b07cb Исправление привнесенного бага 2022-07-19 00:50:44 +07:00
Book Pauk
7c253df291 Merge tag '0.11.8-6' into develop
0.11.8-6
2022-07-19 00:36:00 +07:00
Book Pauk
bb7cd9cbde Merge branch 'release/0.11.8-6' 2022-07-19 00:35:55 +07:00
Book Pauk
56c4182985 Небольшой тюнинг 2022-07-19 00:35:12 +07:00
Book Pauk
cb6c7536bf Небольшой тюнинг 2022-07-19 00:32:52 +07:00
Book Pauk
fbfe8cbda0 Решение проблемы невалидного tls-сертификата 2022-07-19 00:27:54 +07:00
Book Pauk
6129d2d7eb Небольшие поправки 2022-07-19 00:14:18 +07:00
Book Pauk
16b30c922a Улучшение работы с удаленным хранилищем 2022-07-18 23:54:25 +07:00
Book Pauk
c42ad66be6 Merge tag '0.11.8-5' into develop
0.11.8-5
2022-07-17 21:15:37 +07:00
Book Pauk
f36c13fea1 Merge branch 'release/0.11.8-5' 2022-07-17 21:15:31 +07:00
Book Pauk
4fd9d579e0 Небольшие доработки remoteSent, оптимизация отправки файлов 2022-07-17 21:10:52 +07:00
Book Pauk
e65a8a13ea Рефакторинг 2022-07-17 20:04:23 +07:00
Book Pauk
6ddb97d43e Тюнинг таймаутов 2022-07-17 17:11:34 +07:00
Book Pauk
89082603de Merge tag '0.11.8-4' into develop
0.11.8-4
2022-07-17 16:54:15 +07:00
Book Pauk
a9a3227433 Merge branch 'release/0.11.8-4' 2022-07-17 16:53:59 +07:00
Book Pauk
60cb3514b2 Тюнинг таймаутов 2022-07-17 16:53:12 +07:00
Book Pauk
4aeaa05f0b Merge tag '0.11.8-3' into develop
0.11.8-3
2022-07-17 15:58:34 +07:00
Book Pauk
9c06552278 Merge branch 'release/0.11.8-3' 2022-07-17 15:58:28 +07:00
Book Pauk
000f8dde82 Переход на RemoteStorage 2022-07-17 15:43:12 +07:00
Book Pauk
9ffc218002 Поправка 2022-07-16 21:36:50 +07:00
Book Pauk
68a188f099 Конфиг nginx 2022-07-16 21:10:33 +07:00
Book Pauk
8829bb3810 Конфиг nginx 2022-07-16 21:07:16 +07:00
Book Pauk
5164d2f536 Merge tag '0.11.8-2' into develop
0.11.8-2
2022-07-16 21:02:05 +07:00
12 changed files with 342 additions and 52 deletions

View File

@@ -6,6 +6,7 @@ server {
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
server_name beta.liberama.top;
set $liberama http://127.0.0.1:34082;
client_max_body_size 50m;
proxy_read_timeout 1h;
@@ -15,15 +16,20 @@ server {
gzip_proxied expired no-cache no-store private auth;
gzip_types *;
location @liberama {
proxy_pass $liberama;
}
location /api {
proxy_pass http://127.0.0.1:34082;
proxy_pass $liberama;
}
location /ws {
proxy_pass http://127.0.0.1:34082;
proxy_pass $liberama;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 600s;
}
location / {
@@ -32,6 +38,11 @@ server {
location /tmp {
types { } default_type "application/xml; charset=utf-8";
add_header Content-Encoding gzip;
try_files $uri @liberama;
}
location /upload {
try_files $uri @liberama;
}
location ~* \.(?:manifest|appcache|html)$ {
@@ -50,6 +61,7 @@ server {
server {
listen 80;
server_name b.beta.liberama.top;
set $liberama http://127.0.0.1:34082;
client_max_body_size 50m;
proxy_read_timeout 1h;
@@ -59,15 +71,20 @@ server {
gzip_proxied expired no-cache no-store private auth;
gzip_types *;
location @liberama {
proxy_pass $liberama;
}
location /api {
proxy_pass http://127.0.0.1:34082;
proxy_pass $liberama;
}
location /ws {
proxy_pass http://127.0.0.1:34082;
proxy_pass $liberama;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 600s;
}
location / {
@@ -76,6 +93,11 @@ server {
location /tmp {
types { } default_type "application/xml; charset=utf-8";
add_header Content-Encoding gzip;
try_files $uri @liberama;
}
location /upload {
try_files $uri @liberama;
}
location ~* \.(?:manifest|appcache|html)$ {

View File

@@ -6,6 +6,7 @@ server {
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
server_name beta.omnireader.ru;
set $liberama http://127.0.0.1:34081;
client_max_body_size 50m;
proxy_read_timeout 1h;
@@ -15,15 +16,20 @@ server {
gzip_proxied expired no-cache no-store private auth;
gzip_types *;
location @liberama {
proxy_pass $liberama;
}
location /api {
proxy_pass http://127.0.0.1:34081;
proxy_pass $liberama;
}
location /ws {
proxy_pass http://127.0.0.1:34081;
proxy_pass $liberama;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 600s;
}
location / {
@@ -32,6 +38,11 @@ server {
location /tmp {
types { } default_type "application/xml; charset=utf-8";
add_header Content-Encoding gzip;
try_files $uri @liberama;
}
location /upload {
try_files $uri @liberama;
}
location ~* \.(?:manifest|appcache|html)$ {

View File

@@ -1,6 +1,7 @@
server {
listen 80;
server_name beta.omnireader.ru;
set $liberama http://127.0.0.1:34081;
client_max_body_size 50m;
proxy_read_timeout 1h;
@@ -10,15 +11,20 @@ server {
gzip_proxied expired no-cache no-store private auth;
gzip_types *;
location @liberama {
proxy_pass $liberama;
}
location /api {
proxy_pass http://127.0.0.1:34081;
proxy_pass $liberama;
}
location /ws {
proxy_pass http://127.0.0.1:34081;
proxy_pass $liberama;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 600s;
}
location / {
@@ -27,6 +33,11 @@ server {
location /tmp {
types { } default_type "application/xml; charset=utf-8";
add_header Content-Encoding gzip;
try_files $uri @liberama;
}
location /upload {
try_files $uri @liberama;
}
location ~* \.(?:manifest|appcache|html)$ {

View File

@@ -39,6 +39,11 @@ module.exports = {
],
jembaDb: [
{
dbName: 'app',
thread: true,
openAll: true,
},
{
dbName: 'reader-storage',
thread: true,
@@ -55,8 +60,8 @@ module.exports = {
},
],
remoteWebDavStorage: false,
/*
remoteWebDavStorage: false,
remoteWebDavStorage: {
url: '127.0.0.1:1900',
username: '',
@@ -64,5 +69,12 @@ module.exports = {
},
*/
remoteStorage: false,
/*
remoteStorage: {
url: 'https://127.0.0.1:11900',
accessToken: '',
},
*/
};

View File

@@ -6,12 +6,16 @@ const WorkerState = require('../WorkerState');//singleton
const FileDownloader = require('../FileDownloader');
const FileDecompressor = require('../FileDecompressor');
const BookConverter = require('./BookConverter');
const RemoteWebDavStorage = require('../RemoteWebDavStorage');
const RemoteStorage = require('../RemoteStorage');
const JembaConnManager = require('../../db/JembaConnManager');//singleton
const ayncExit = new (require('../AsyncExit'))();
const utils = require('../utils');
const log = new (require('../AppLogger'))().log;//singleton
const cleanDirPeriod = 30*60*1000;//раз в полчаса
const cleanDirPeriod = 60*60*1000;//каждый час
const remoteSendPeriod = 119*1000;//примерно раз 2 минуты
const queue = new LimitedQueue(5, 100, 2*60*1000 + 15000);//2 минуты ожидание подвижек
let instance = null;
@@ -33,27 +37,37 @@ class ReaderWorker {
this.decomp = new FileDecompressor(3*config.maxUploadFileSize);
this.bookConverter = new BookConverter(this.config);
this.remoteWebDavStorage = false;
if (config.remoteWebDavStorage) {
this.remoteWebDavStorage = new RemoteWebDavStorage(
Object.assign({maxContentLength: 3*config.maxUploadFileSize}, config.remoteWebDavStorage)
this.connManager = new JembaConnManager();
this.appDb = this.connManager.db['app'];
this.remoteStorage = false;
if (config.remoteStorage) {
this.remoteStorage = new RemoteStorage(
Object.assign({maxContentLength: 3*config.maxUploadFileSize}, config.remoteStorage)
);
}
this.remoteConfig = {
'/tmp': {
this.dirConfigArr = [
{
dir: this.config.tempPublicDir,
remoteDir: '/tmp',
maxSize: this.config.maxTempPublicDirSize,
moveToRemote: true,
},
'/upload': {
{
dir: this.config.uploadDir,
remoteDir: '/upload',
maxSize: this.config.maxUploadPublicDirSize,
moveToRemote: true,
}
};
];
//преобразуем в объект для большего удобства
this.dirConfig = {};
for (const configRec of this.dirConfigArr)
this.dirConfig[configRec.remoteDir] = configRec;
this.periodicCleanDir(this.remoteConfig);//no await
this.remoteFilesToSend = [];
this.periodicCleanDir();//no await
instance = this;
}
@@ -154,6 +168,13 @@ class ReaderWorker {
const finishFilename = path.basename(compFilename);
wState.finish({path: `/tmp/${finishFilename}`, size: stat.size});
//асинхронно через 30 сек добавим в очередь на отправку
//т.к. gzipFileIfNotExists может переупаковать файл
(async() => {
await utils.sleep(30*1000);
this.pushRemoteSend(compFilename, '/tmp');
})();
} catch (e) {
log(LM_ERR, e.stack);
let mes = e.message.split('|FORLOG|');
@@ -194,6 +215,7 @@ class ReaderWorker {
if (!await fs.pathExists(outFilename)) {
await fs.move(file.path, outFilename);
this.pushRemoteSend(outFilename, '/upload');
} else {
await utils.touchFile(outFilename);
await fs.remove(file.path);
@@ -208,6 +230,7 @@ class ReaderWorker {
if (!await fs.pathExists(outFilename)) {
await fs.writeFile(outFilename, buf);
this.pushRemoteSend(outFilename, '/upload');
} else {
await utils.touchFile(outFilename);
}
@@ -225,8 +248,8 @@ class ReaderWorker {
async restoreRemoteFile(filename, remoteDir) {
let targetDir = '';
if (this.remoteConfig[remoteDir])
targetDir = this.remoteConfig[remoteDir].dir;
if (this.dirConfig[remoteDir])
targetDir = this.dirConfig[remoteDir].dir;
else
throw new Error(`restoreRemoteFile: unknown remoteDir value (${remoteDir})`);
@@ -235,8 +258,8 @@ class ReaderWorker {
if (!await fs.pathExists(targetName)) {
let found = false;
if (this.remoteWebDavStorage) {
found = await this.remoteWebDavStorage.getFileSuccess(targetName, remoteDir);
if (this.remoteStorage) {
found = await this.remoteStorage.getFileSuccess(targetName, remoteDir);
}
if (!found) {
@@ -247,13 +270,57 @@ class ReaderWorker {
return targetName;
}
async cleanDir(dir, remoteDir, maxSize, moveToRemote) {
if (!this.remoteSent)
this.remoteSent = {};
if (!this.remoteSent[remoteDir])
this.remoteSent[remoteDir] = {};
pushRemoteSend(fileName, remoteDir) {
if (this.remoteStorage
&& this.dirConfig[remoteDir]
&& this.dirConfig[remoteDir].moveToRemote) {
this.remoteFilesToSend.push({fileName, remoteDir});
}
}
const sent = this.remoteSent[remoteDir];
async remoteSendFile(sendFileRec) {
const {fileName, remoteDir} = sendFileRec;
const sent = this.remoteSent;
if (!fileName || sent[fileName])
return;
log(`remoteSendFile ${remoteDir}/${path.basename(fileName)}`);
//отправляем в remoteStorage
await this.remoteStorage.putFile(fileName, remoteDir);
sent[fileName] = true;
await this.appDb.insert({table: 'remote_sent', ignore: true, rows: [{id: fileName, remoteDir}]});
}
async remoteSendAll() {
if (!this.remoteStorage)
return;
const newSendQueue = [];
while (this.remoteFilesToSend.length) {
const sendFileRec = this.remoteFilesToSend.shift();
if (sendFileRec.remoteDir
&& this.dirConfig[sendFileRec.remoteDir]
&& this.dirConfig[sendFileRec.remoteDir].moveToRemote) {
try {
await this.remoteSendFile(sendFileRec);
} catch (e) {
newSendQueue.push(sendFileRec)
log(LM_ERR, e.stack);
}
}
}
this.remoteFilesToSend = newSendQueue;
}
async cleanDir(config) {
const {dir, remoteDir, maxSize, moveToRemote} = config;
const sent = this.remoteSent;
const list = await fs.readdir(dir);
@@ -267,24 +334,35 @@ class ReaderWorker {
files.push({name: filePath, stat});
}
}
log(`clean dir ${dir}, maxSize=${maxSize}, found ${files.length} files, total size=${size}`);
log(LM_WARN, `clean dir ${dir}, maxSize=${maxSize}, found ${files.length} files, total size=${size}`);
files.sort((a, b) => a.stat.mtimeMs - b.stat.mtimeMs);
if (moveToRemote && this.remoteWebDavStorage) {
//удаленное хранилище
if (moveToRemote && this.remoteStorage) {
const foundFiles = new Set();
for (const file of files) {
if (sent[file.name])
continue;
foundFiles.add(file.name);
//отправляем в remoteWebDavStorage
//отсылаем на всякий случай перед удалением, если вдруг remoteSendAll не справился
try {
log(`remoteWebDavStorage.putFile ${remoteDir}/${path.basename(file.name)}`);
await this.remoteWebDavStorage.putFile(file.name, remoteDir);
sent[file.name] = true;
await this.remoteSendFile({fileName: file.name, remoteDir});
} catch (e) {
log(LM_ERR, e.stack);
}
}
//почистим remoteSent и БД
//несколько неоптимально, таскает все записи из таблицы
const rows = await this.appDb.select({table: 'remote_sent'});
for (const row of rows) {
if ((row.remoteDir === remoteDir && !foundFiles.has(row.id))
|| !this.dirConfig[row.remoteDir]) {
delete sent[row.id];
await this.appDb.delete({table: 'remote_sent', where: `@@id(${this.appDb.esc(row.id)})`});
}
}
}
let i = 0;
@@ -294,7 +372,9 @@ class ReaderWorker {
const oldFile = file.name;
//реально удаляем только если сохранили в хранилище или размер dir увеличен в 1.5 раза
if ((moveToRemote && this.remoteWebDavStorage && sent[oldFile]) || size > maxSize*1.5) {
if (!(moveToRemote && this.remoteStorage)
|| (moveToRemote && this.remoteStorage && sent[oldFile])
|| size > maxSize*1.5) {
await fs.remove(oldFile);
j++;
}
@@ -302,20 +382,55 @@ class ReaderWorker {
size -= file.stat.size;
i++;
}
log(`removed ${j} files`);
log(LM_WARN, `removed ${j} files`);
}
async periodicCleanDir(cleanConfig) {
while (1) {// eslint-disable-line no-constant-condition
for (const [remoteDir, config] of Object.entries(cleanConfig)) {
try {
await this.cleanDir(config.dir, remoteDir, config.maxSize, config.moveToRemote);
} catch(e) {
log(LM_ERR, e.stack);
async periodicCleanDir() {
try {
if (!this.remoteSent)
this.remoteSent = {};
//инициализация this.remoteSent
if (this.remoteStorage) {
const rows = await this.appDb.select({table: 'remote_sent'});
for (const row of rows) {
this.remoteSent[row.id] = true;
}
}
await utils.sleep(cleanDirPeriod);
let lastCleanDirTime = 0;
let lastRemoteSendTime = 0;
while (1) {// eslint-disable-line no-constant-condition
//отсылка в удаленное хранилище
if (Date.now() - lastRemoteSendTime >= remoteSendPeriod) {
try {
await this.remoteSendAll();
} catch(e) {
log(LM_ERR, e.stack);
}
lastRemoteSendTime = Date.now();
}
//чистка папок
if (Date.now() - lastCleanDirTime >= cleanDirPeriod) {
for (const config of Object.values(this.dirConfig)) {
try {
await this.cleanDir(config);
} catch(e) {
log(LM_ERR, e.stack);
}
}
lastCleanDirTime = Date.now();
}
await utils.sleep(60*1000);//интервал проверки 1 минута
}
} catch (e) {
log(LM_FATAL, e.message);
ayncExit.exit(1);
}
}

View File

@@ -0,0 +1,98 @@
const fs = require('fs-extra');
const path = require('path');
const WebSocketConnection = require('./WebSocketConnection');
class RemoteStorage {
constructor(config) {
this.config = Object.assign({}, config);
this.config.maxContentLength = this.config.maxContentLength || 10*1024*1024;
this.accessToken = this.config.accessToken;
this.wsc = new WebSocketConnection(config.url, 10, 30, {rejectUnauthorized: false});
}
async wsRequest(query) {
const response = await this.wsc.message(
await this.wsc.send(Object.assign({accessToken: this.accessToken}, query), 600),
600
);
if (response.error)
throw new Error(response.error);
return response;
}
async wsStat(fileName) {
return await this.wsRequest({action: 'get-stat', fileName});
}
async wsGetFile(fileName) {
return this.wsRequest({action: 'get-file', fileName});
}
async wsPutFile(fileName, data) {//data base64 encoded string
return this.wsRequest({action: 'put-file', fileName, data});
}
async wsDelFile(fileName) {
return this.wsRequest({action: 'del-file', fileName});
}
makeRemoteFileName(fileName, dir = '') {
const base = path.basename(fileName);
if (base.length > 3) {
return `${dir}/${base.substr(0, 3)}/${base}`;
} else {
return `${dir}/${base}`;
}
}
async putFile(fileName, dir = '') {
if (!await fs.pathExists(fileName)) {
throw new Error(`File not found: ${fileName}`);
}
const remoteFilename = this.makeRemoteFileName(fileName, dir);
try {
const localStat = await fs.stat(fileName);
let remoteStat = await this.wsStat(remoteFilename);
remoteStat = remoteStat.stat;
if (remoteStat.isFile && localStat.size == remoteStat.size) {
return;
}
await this.wsDelFile(remoteFilename);
} catch (e) {
//
}
const data = await fs.readFile(fileName, 'base64');
await this.wsPutFile(remoteFilename, data);
}
async getFile(fileName, dir = '') {
if (await fs.pathExists(fileName)) {
return;
}
const remoteFilename = this.makeRemoteFileName(fileName, dir);
const response = await this.wsGetFile(remoteFilename);
await fs.writeFile(fileName, response.data, 'base64');
}
async getFileSuccess(filename, dir = '') {
try {
await this.getFile(filename, dir);
return true;
} catch (e) {
//
}
return false;
}
}
module.exports = RemoteStorage;

View File

@@ -8,10 +8,13 @@ const cleanPeriod = 5*1000;//5 секунд
class WebSocketConnection {
//messageLifeTime в секундах (проверка каждый cleanPeriod интервал)
constructor(url, openTimeoutSecs = 10, messageLifeTimeSecs = 30) {
constructor(url, openTimeoutSecs = 10, messageLifeTimeSecs = 30, webSocketOptions = {}) {
this.WebSocket = (isBrowser ? WebSocket : require('ws'));
this.url = url;
this.webSocketOptions = webSocketOptions;
this.ws = null;
this.listeners = [];
this.messageQueue = [];
this.messageLifeTime = messageLifeTimeSecs*1000;
@@ -91,7 +94,7 @@ class WebSocketConnection {
const url = this.url || `${protocol}//${window.location.host}/ws`;
this.ws = new this.WebSocket(url);
} else {
this.ws = new this.WebSocket(this.url);
this.ws = new this.WebSocket(this.url, this.webSocketOptions);
}
const onopen = () => {

View File

@@ -0,0 +1,12 @@
module.exports = {
up: [
['create', {
table: 'remote_sent'
}],
],
down: [
['drop', {
table: 'remote_sent'
}],
]
};

View File

@@ -0,0 +1,6 @@
module.exports = {
table: 'migration1',
data: [
{id: 1, name: 'create', data: require('./001-create')}
]
}

View File

@@ -1,4 +1,5 @@
module.exports = {
'app': require('./app'),
'reader-storage': require('./reader-storage'),
'book-update-server': require('./book-update-server'),
};

View File

@@ -1,5 +1,4 @@
require('tls').DEFAULT_MIN_VERSION = 'TLSv1';
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0;
const fs = require('fs-extra');
const argv = require('minimist')(process.argv.slice(2));

View File

@@ -115,7 +115,7 @@ function initStatic(app, config) {
}
}
} catch(e) {
log(LM_ERR, `Static.restoreRemoteFile: ${e.message}`);
log(LM_ERR, `static::restoreRemoteFile ${req.path} > ${e.message}`);
}
return next();