• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

suculent / thinx-device-api / #252646374

28 Mar 2022 03:28PM UTC coverage: 1.897% (+0.1%) from 1.785%
#252646374

push

web-flow
Merge pull request #340 from suculent/thinx-swarm

non-functional improvements

2 of 527 branches covered (0.38%)

Branch coverage included in aggregate %.

0 of 6 new or added lines in 2 files covered. (0.0%)

434 existing lines in 7 files now uncovered.

33 of 1318 relevant lines covered (2.5%)

0.06 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.72
/lib/thinx/database.js
1
// Database Manager
2

3
const Globals = require("./globals.js");
1✔
4
const app_config = Globals.app_config();
×
5
const fs = require("fs-extra");
×
6
module.exports = class Database {
×
7

8
        constructor() {
9

10
                let db_uri;
11
                let user = process.env.COUCHDB_USER;
×
12
                let pass = process.env.COUCHDB_PASS;
×
13

14
                if ((typeof (user) !== "undefined") && (typeof (pass) !== "undefined")) {
×
15
                        db_uri = `http://${user}:${pass}@couchdb:5984`;
×
16
                } else {
17
                        db_uri = app_config.database_uri; // fallback to old config.json; deprecated
×
18
                        console.log("⛔️ [deprecated] Using database credentials from configuration...");
×
19
                }
20

21
                this.db_uri = db_uri;
×
22
                this.nano = require("nano")(db_uri);
×
23
                console.log("✅ [info] Loaded module: Database");
×
24
        }
25

26
        nano() {
27
                return this.nano;
×
28
        }
29

30
        uri() {
31

32
                /* duplicate code, happens in constructor and that's enough
33
                let db_uri;
34
                let user = process.env.COUCHDB_USER;
35
                let pass = process.env.COUCHDB_PASS;
36

37
                if ((typeof (user) !== "undefined") && (typeof (pass) !== "undefined")) {
38
                        db_uri = `http://${user}:${pass}@couchdb:5984`;
39
                } else {
40
                        db_uri = app_config.database_uri; // fallback to old config.json; deprecated
41
                        console.log("⛔️ [deprecated] Using database credentials from configuration...");
42
                }
43

44
                this.db_uri = db_uri;
45
                */
46

47
                return this.db_uri;
×
48
        }
49
        
50

51
        null_cb(err, body, header) {
52
                // only unexpected errors should be logged
53
                if (process.env.ENVIRONMENT === "test") {
×
54
                        // The database may already exist.
55
                        if (err.ststusCode !== 412) {
×
56
                                console.log(err, body, header);
×
57
                        }
58
                }
59
        }
60

61
        // Designated initalizer
62
        init(callback) {
63

64
                console.log("ℹ️ [info] Initializing databases...");
×
65

66
                let db_names = [
×
67
                        "devices", "builds", "users", "logs"
68
                ];
69

70
                this.nano.db.list((err, existing_dbs) => {
×
71

72
                        if ((typeof(existing_dbs) === "undefined") || (existing_dbs === null)) existing_dbs = [];
×
73

74
                        db_names.forEach((name) => {
×
75

76
                                if (existing_dbs.includes(name)) {
×
77
                                        console.log(`ℹ️ [info] DB ${name} already exists.`);
×
78
                                        return;
×
79
                                }
80

81
                                console.log("ℹ️ [info] Creating database", name);
×
82

83
                                const dbprefix = Globals.prefix();
×
84

NEW
85
                                this.nano.db.create(dbprefix + "managed_" + name).then((/* cerr, data */) => {
×
86
                                        var couch_db = this.nano.db.use(dbprefix + "managed_" + name);
×
87
                                        this.injectDesign(couch_db, name, "/opt/thinx/thinx-device-api/design/design_" + name + ".json");
×
88
                                        this.injectReplFilter(couch_db, "/opt/thinx/thinx-device-api/design/filters_" + name + ".json");
×
89
                                        console.log(`ℹ️ [info] Database managed_${name} initialized.`);
×
90
                                }).catch((err2) => {
91
                                        // returns error normally if DB already exists
92
                                        this.handleDatabaseErrors(err2, "managed_" + name, dbprefix);
×
93
                                });
94
                        });
95

UNCOV
96
                        this.nano.db.list((err2, new_dbs) => {
×
97
                                if (typeof (callback) !== "undefined") {
×
98
                                        callback(err2, new_dbs);
×
99
                                } else {
UNCOV
100
                                        return new_dbs;
×
101
                                }
102
                        });
103

UNCOV
104
                        setTimeout(() => {
×
105
                                setInterval(this.compactDatabases, 3600 * 1000); // Compact databases once an hour        
×
106
                        }, 30000);
107
                        
108
                });
109
        }
110

111
        compactDatabases(opt_callback) {
UNCOV
112
                const prefix = Globals.prefix();
×
113
                let db_uri = new Database().uri();
×
114
                this.nano = require("nano")(db_uri);
×
115
                this.nano.db.compact(prefix + "managed_logs", () => {
×
116
                        this.nano.db.compact(prefix + "managed_builds", () => {
×
117
                                this.nano.db.compact(prefix + "managed_devices", () => {
×
118
                                        this.nano.db.compact(prefix + "managed_users", "owners_by_username", (err) => {
×
119
                                                if (err) {
×
120
                                                        if (typeof (opt_callback) !== "undefined") opt_callback(err);
×
121
                                                } else {
UNCOV
122
                                                        console.log("» Database compact jobs completed.");
×
123
                                                        if (typeof (opt_callback) !== "undefined") opt_callback(true);
×
124
                                                }
125
                                        });
126
                                });
127
                        });
128
                });
129
        }
130

131
        // Database preparation on first run
132
        getDocument(file) {
UNCOV
133
                if (!fs.existsSync(file)) {
×
134
                        console.log("☣️ [error] Initializing replication filter failed, file does not exist", file);
×
135
                        return false;
×
136
                }
UNCOV
137
                const data = fs.readFileSync(file);
×
138
                if (typeof (data) === "undefined") {
×
139
                        console.log("☣️ [error] [getDocument] no data read.");
×
140
                        return false;
×
141
                }
142
                // Parser may fail
UNCOV
143
                try {
×
144
                        return JSON.parse(data);
×
145
                } catch (e) {
UNCOV
146
                        console.log("☣️ [error] Document File may not exist: " + e);
×
147
                        return false;
×
148
                }
149
        }
150

151
        logCouchError(err, body, header, tag) {
UNCOV
152
                if (err !== null) {
×
153
                        if (err.toString().indexOf("conflict") === -1) {
×
154
                                console.log("☣️ [error] Couch Init error: ", err, body, header, tag);
×
155
                        }
UNCOV
156
                        if (err.toString().indexOf("ENOTFOUND") !== -1) {
×
157
                                console.log("Critical DB integration error, exiting.");
×
158
                                process.exit(1);
×
159
                        }
160
                } else {
UNCOV
161
                        return;
×
162
                }
UNCOV
163
                if (typeof (body) !== "undefined") {
×
164
                        console.log("☣️ [error] Log Couch Insert body: " + body + " " + tag);
×
165
                }
UNCOV
166
                if (typeof (header) !== "undefined") {
×
167
                        console.log("☣️ [error] Log Couchd Insert header: " + header + " " + tag);
×
168
                }
169
        }
170

171
        injectDesign(db, design, file) {
UNCOV
172
                if (typeof (design) === "undefined") return;
×
173
                let design_doc = this.getDocument(file);
×
174
                if (design_doc != null) {
×
175
                        db.insert(design_doc, "_design/" + design, (err, body, header) => {
×
176
                                this.logCouchError(err, body, header, "init:design:" + design); // returns if no err
×
177
                        });
178
                } else {
UNCOV
179
                        console.log("☣️ [error] Design doc injection issue at " + file);
×
180
                }
181
        }
182

183
        injectReplFilter(db, file) {
UNCOV
184
                let filter_doc = this.getDocument(file);
×
185
                if (filter_doc !== false) {
×
186
                        db.insert(filter_doc, "_design/repl_filters", (err, body, header) => {
×
187
                                this.logCouchError(err, body, header, "init:repl:" + JSON.stringify(filter_doc)); // returns if no err
×
188
                        });
189
                } else {
UNCOV
190
                        console.log("☣️ [error] Filter doc injection issue (no doc) at " + file);
×
191
                }
192
        }
193

194
        handleDatabaseErrors(err, name, info) {
UNCOV
195
                if (err.toString().indexOf("the file already exists") !== -1) {
×
196
                        // silently fail, this is ok
UNCOV
197
                } else if (err.toString().indexOf("error happened") !== -1) {
×
198
                        console.log("🚫 [critical] Database connectivity issue. " + err.toString());
×
199
                        // give some time for DB to wake up until next try, also prevents too fast restarts...
UNCOV
200
                        setTimeout(() => {
×
201
                                process.exit(1);
×
202
                        }, 1000);
203
                } else {
UNCOV
204
                        console.log("🚫 [critical] Database " + name + " creation failed. " + err, " info:", info);
×
205
                        setTimeout(() => {
×
206
                                process.exit(2);
×
207
                        }, 1000);
208
                }
209
        }
210
};
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc