-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
399 lines (374 loc) · 9.9 KB
/
index.js
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
"use strict";
const Couchbase = require("couchbase");
const { ViewQuery, N1qlQuery } = Couchbase;
const debug = require("debug")("cb-utils:index");
const noop = function () {};
const delay = (ms) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, ms);
});
};
function connectCluster(host, username, password) {
const cluster = new Couchbase.Cluster(host);
cluster.authenticate(username, password);
return cluster;
}
/**
* open bucket
* @param {Couchbase.Cluster} cluster
* @param {string} bucket
* @returns {Promise<Couchbase.Bucket>}
*/
function openBucket(cluster, bucket) {
return new Promise((resolve, reject) => {
const result = cluster.openBucket(bucket, (err) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
}
function getDoc(bucket, key) {
return new Promise((resolve, reject) => {
bucket.get(key, (err, res) => {
if (err) {
reject(err);
} else {
resolve(res);
}
});
});
}
function getDocs(bucket, keys) {
return new Promise((resolve, reject) => {
bucket.getMulti(keys, (err, res) => {
if (err) {
reject(err);
} else {
resolve(res);
}
});
});
}
function removeDoc(bucket, key) {
return new Promise((resolve, reject) => {
bucket.remove(key, (err, res) => {
if (err) {
reject(err);
} else {
resolve(res);
}
});
});
}
function upsert(bucket, key, value, options = {}) {
return new Promise((resolve, reject) => {
bucket.upsert(key, value, options, (err, res) => {
if (err) {
reject(err);
} else {
resolve(res);
}
});
});
}
async function upsertViews(bucket, designDocs) {
debug("bucket.name %s", bucket.name);
const ddocs = designDocs.filter((ddoc) => {
return ddoc.bucket === bucket.name;
});
if (ddocs.length === 0) return;
debug("ddocs %o", ddocs);
await Promise.all(
ddocs.map((ddoc) => {
return new Promise((resolve, reject) => {
console.log("[info] upsertDesignDocument:", ddoc.docName);
bucket.manager().upsertDesignDocument(ddoc.docName, ddoc.doc, (err) => {
if (err) {
return reject(err);
}
return resolve();
});
});
})
);
return;
}
function newViewQuery(designDoc, viewName, options) {
const ViewQuery = Couchbase.ViewQuery;
// With some defaults.
// See https://docs.couchbase.com/sdk-api/couchbase-node-client-2.1.4/ViewQuery.html#.ErrorMode
let query = ViewQuery.from(designDoc, viewName)
.on_error(ViewQuery.ErrorMode.STOP)
.order(ViewQuery.Order.ASCENDING)
.stale(ViewQuery.Update.BEFORE);
if (options == null) {
return query;
}
// The SDK made it easier for some options formats.
// Call.
let opts = Object.assign({}, options);
[
"stale",
"order",
"group",
"group_level",
"key",
"keys",
"include_docs",
"full_set",
"on_error",
"limit",
].forEach((key) => {
if (opts[key] != null) {
query = query[key].call(query, opts[key]);
delete opts[key];
}
});
// Apply.
["range", "id_range"].forEach((key) => {
if (opts[key] != null) {
query = query[key].apply(query, opts[key]);
delete opts[key];
}
});
query = query.custom(opts);
return query;
}
/**
* query bucket
* @param {Couchbase.Bucket} bucket
* @param {any} query
* @returns {Promise<{rows: any[], meta: Couchbase.Bucket.N1qlQueryResponse.Meta}>}
*/
async function query(bucket, q, params = {}) {
return new Promise((resolve, reject) => {
bucket.query(q, params, (err, rows, meta) => {
if (err) {
reject(err);
} else {
resolve({ rows, meta });
}
});
});
}
// alias of query
async function queryView(bucket, q) {
return (await query(bucket, q)).rows;
}
async function queryN1ql(bucket, q, params = {}) {
return query(bucket, N1qlQuery.fromString(q), params);
}
const paginate = async (
bucket,
designDoc,
view,
viewOpts,
exec = noop,
startkey_docid
) => {
if (startkey_docid) {
viewOpts.stale = ViewQuery.Update.NONE;
viewOpts.id_range = [startkey_docid];
viewOpts.skip = 1;
}
const q = newViewQuery(designDoc, view, viewOpts);
const queryResult = await queryView(bucket, q);
const startKey = viewOpts.range[0];
const rows = queryResult.filter((r) => r.key === startKey);
const stopRecur = rows.length < viewOpts.limit;
debug("selected doc length: %d \n", rows.length);
try {
await Promise.all(
rows.map(async (row) => {
return exec(bucket, row);
})
);
} catch (err) {
// append the start doc id to the error so the caller knows where the iteration stopped.
err.startDocId = startkey_docid;
throw err;
}
debug("finished callback");
if (!stopRecur) {
const lag = viewOpts.lagForNextIteration || 200;
debug(`rest for ${lag} millseconds`);
await delay(lag);
await paginate(
bucket,
designDoc,
view,
viewOpts,
exec,
rows[rows.length - 1].id
);
} else {
console.log("pagination done");
return;
}
};
const groupBy = function (col, key) {
return col.reduce(function (acc, cur) {
(acc[cur[key]] = acc[cur[key]] || []).push(cur);
return acc;
}, {});
};
async function defineIndexes(buckets, indexes) {
const indexDefinitions = indexes.map(async (idx) => {
const text = idx.template
.replace(new RegExp(`\\$bucket`, "g"), idx.bucket)
.replace(new RegExp(`\\$name`, "g"), idx.name)
.replace(
new RegExp(`\\$defered`, "g"),
idx.defer_build ? "true" : "false"
);
console.log("[info]", text);
try {
await query(buckets[idx.bucket], N1qlQuery.fromString(text));
} catch (err) {
if (err.code === 4300) {
console.warn("[warn]", err.message + " Trying to drop it.");
const dropIndex = `DROP INDEX \`${idx.bucket}\`.${idx.name} using GSI`;
await query(buckets[idx.bucket], N1qlQuery.fromString(dropIndex));
await query(buckets[idx.bucket], N1qlQuery.fromString(text));
console.log("[info]", `GSI index ${idx.name} created`);
} else {
throw err;
}
}
});
await Promise.all(indexDefinitions);
}
async function triggerDeferedIndexes(buckets, indexes) {
const indexesOnBucket = groupBy(indexes, "bucket");
debug("indexesOnBucket %o", indexesOnBucket);
return Promise.all(
Object.values(indexesOnBucket).map(async (idxArr) => {
const bucketName = idxArr[0].bucket;
const indexNames = idxArr.map((i) => "`" + i.name + "`").join(",");
const text = `build index on \`${bucketName}\`(${indexNames}) using gsi`;
console.log("[info]", text);
try {
await query(buckets[bucketName], N1qlQuery.fromString(text));
} catch (err) {
if (err.message.includes("is already built")) {
console.log("[warn]", err.message);
} else {
throw err;
}
}
})
);
}
async function buildIndexes(buckets, indexes) {
await defineIndexes(buckets, indexes);
const defered = indexes.filter((idx) => idx.defer_build);
if (defered.length <= 0) {
console.log(`[info] no deferred indexes`);
return;
}
await triggerDeferedIndexes(buckets, defered);
}
async function counter(bucket, key, delta, options) {
return new Promise((resolve, reject) => {
bucket.counter(key, delta, options, (err, res) => {
if (err) {
reject(err);
} else {
resolve(res);
}
});
});
}
// Operations on the sub docs
async function createSubItem(bucket, docId, subId, item) {
return new Promise((resolve, reject) => {
bucket
.mutateIn(docId)
.insert(subId, item)
.execute((err, res) => {
// 1. When error happens on the doc level, the error is stored in err.
// 2. When error happens on the sub doc level, the err is a number to indicate
// how many error occurs when performing sub doc operation commands. The actual
// error instances are stored in the res.contents.
if (err) {
if (typeof err === "object") {
reject(err);
} else {
reject(res.contents);
}
} else {
resolve(res);
}
});
});
}
async function upsertSubItem(bucket, docId, subId, item) {
return new Promise((resolve, reject) => {
bucket
.mutateIn(docId)
.upsert(subId, item)
.execute((err, res) => {
// 1. When error happens on the doc level, the error is stored in err.
// 2. When error happens on the sub doc level, the err is a number to indicate
// how many error occurs when performing sub doc operation commands. The actual
// error instances are stored in the res.contents.
if (err) {
if (typeof err === "object") {
reject(err);
} else {
reject(res.contents);
}
} else {
resolve(res);
}
});
});
}
async function removeSubItem(bucket, docId, subId) {
return new Promise((resolve, reject) => {
bucket
.mutateIn(docId)
.remove(subId)
.execute((err, res) => {
// 1. When error happens on the doc level, the error is stored in err.
// 2. When error happens on the sub doc level, the err is a number to indicate
// how many error occurs when performing sub doc operation commands. The actual
// error instances are stored in the res.contents.
if (err) {
if (typeof err === "object") {
reject(err);
} else {
reject(res.contents);
}
} else {
resolve(res);
}
});
});
}
module.exports = {
connectCluster,
openBucket,
newViewQuery,
queryView,
queryN1ql,
query,
ViewQuery,
getDoc,
getDocs,
removeDoc,
delay,
paginate,
upsert,
upsertViews,
buildIndexes,
counter,
createSubItem,
upsertSubItem,
removeSubItem,
};