forked from oknosoft/windowbuilder-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstream.js
More file actions
195 lines (175 loc) · 5.3 KB
/
stream.js
File metadata and controls
195 lines (175 loc) · 5.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
/**
* ### Модуль создания начальных образов баз Заказа дилера для быстрой стратовой синхронизации
*
* Created 24.02.2018
*/
/**
* ### Переменные окружения
* DEBUG "wb:*,-not_this"
* ZONE 21
* DBPWD admin
* DBUSER admin
* COUCHPATH http://cou221:5984/wb_
* TO_FILE 1
*/
'use strict';
require('http').globalAgent.maxSockets = 35;
const debug = require('debug')('wb:stream');
const JSZip = require('jszip');
const PouchDB = require('./pouchdb');
const MemoryStream = require('memorystream');
const repStream = require('pouchdb-replication-stream');
const fs = require('fs');
// register pouch-replication-stream as a plugin
PouchDB.plugin(repStream.plugin);
PouchDB.adapter('writableStream', repStream.adapters.writableStream);
debug('required');
// инициализируем параметры сеанса и метаданные
const {DBUSER, DBPWD, COUCHPATH, ZONE, TO_FILE} = process.env;
const prefix = 'wb_';
let index = -1;
// получаем массив всех баз
// new PouchDB(COUCHPATH.replace(prefix, '_all_dbs'), {
// auth: {
// username: DBUSER,
// password: DBPWD
// },
// skip_setup: true,
// ajax: {timeout: 100000}
// }).info()
// .then(next);
next(['wb_21_ram', 'wb_21_templates']);
// перебирает базы в асинхронном цикле
function next(dbs) {
index++;
let name = dbs[index];
if(name && name.indexOf(`${prefix}${ZONE}_`) !== -1 && name.match(/(_ram|_templates)$/)) {
name = name.replace(`${prefix}${ZONE}_`, '');
return ddump(name)
.then(() => next(dbs));
}
else if(name) {
return remove(name)
.then(() => next(dbs));
}
}
function remove(name) {
// получаем базы
const db = new PouchDB(`${COUCHPATH.replace(prefix, '')}${name}`, {
auth: {
username: DBUSER,
password: DBPWD
},
skip_setup: true,
ajax: {timeout: 100000}
});
return db.info()
.then((info) => {
return db.get('_local/dump')
.then((doc) => db.remove('_local/dump', doc._rev));
})
.catch((err) => {
debug(err);
});
}
// выполняет дамп конкретной базы
function ddump(name) {
// получаем базы
const db = new PouchDB(`${COUCHPATH}${ZONE}_${name}`, {
auth: {
username: DBUSER,
password: DBPWD
},
skip_setup: true,
ajax: {timeout: 100000}
});
return db.info()
.then((info) => {
if(info.doc_count > 100) {
debug(`connected to ${info.host}, doc count: ${info.doc_count}`);
return db;
}
throw `empty db ${name}`;
})
.then((src) => {
// в dumpedString будем накапливать строку потоковой репликации
let dumpedString = '';
let ind = 0;
let doc_count = 0;
const stream = new MemoryStream();
stream.on('data', (chunk) => {
const data = chunk.toString();
dumpedString += data;
if(TO_FILE && data.length < 3000) {
ind++;
let suffix = ind.toString();
while (suffix.length < 5) {
suffix = '0' + suffix;
}
if(ind === 1) {
const info = JSON.parse(data);
doc_count = info.db_info.doc_count;
}
fs.writeFile(`${name}/${suffix}.json`, dumpedString, 'utf8', (err) => {
if (err) {
debug(err);
process.exit(1);
} else {
debug(`Записан ${suffix}.json`);
}
});
dumpedString = '';
}
});
// базы doc архивируем с фильтром 'auth/push_only'
const opt = {batch_size: 300};
return src.dump(stream, opt)
.then(() => {
if(TO_FILE) {
fs.writeFile(`${name}/00000.json`, JSON.stringify({files: ind, stamp: Date.now(), doc_count}), 'utf8', (err) => {
if (err) {
debug(err);
process.exit(1);
} else {
debug(`Записан 0000.json`);
}
});
return '';
}
else {
debug(`dumped size: ${(dumpedString.length/1000000).toFixed(3)}Mb`);
// создаём виртуальный файл в JSZip
const zip = new JSZip();
zip.file('dump', dumpedString);
dumpedString = '';
// сжимаем
return zip.generateAsync({
type: 'base64',
compression: 'DEFLATE',
compressionOptions: {level: 9}
});
}
})
})
.then((dump) => {
// записываем дамп в '_local/dump' или удаляем dump
debug(`gzipped string: ${(dump.length/1000000).toFixed(3)}Mb`);
return db.get('_local/dump')
.catch(() => ({_id: '_local/dump'}))
.then((doc) => {
if(dump.length) {
doc.dump = dump;
debug(`saving _local/dump`);
return db.put(doc);
}
else if(doc._rev) {
debug(`deleting _local/dump`);
return db.remove('_local/dump', doc._rev);
}
});
})
.then(() => debug(`${name}: ok ==========`))
.catch((err) => {
debug(err);
});
}