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

suculent / thinx-device-api / #252646445

25 Mar 2022 08:10PM UTC coverage: 1.791% (+0.006%) from 1.785%
#252646445

push

suculent
subomdule sync

2 of 576 branches covered (0.35%)

Branch coverage included in aggregate %.

33 of 1378 relevant lines covered (2.39%)

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

85
                                this.nano.db.create(dbprefix + "managed_" + name).then((/* body */) => {
×
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
                                        this.handleDatabaseErrors(err2, "managed_" + name, dbprefix);
×
92
                                });
93
                        });
94

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

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

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

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

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

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

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

193
        handleDatabaseErrors(err, name, info) {
194
                if (err.toString().indexOf("the file already exists") !== -1) {
×
195
                        // silently fail, this is ok
196
                } else if (err.toString().indexOf("error happened") !== -1) {
×
197
                        console.log("🚫 [critical] Database connectivity issue. " + err.toString());
×
198
                        // give some time for DB to wake up until next try, also prevents too fast restarts...
199
                        setTimeout(() => {
×
200
                                process.exit(1);
×
201
                        }, 1000);
202
                } else {
203
                        console.log("🚫 [critical] Database " + name + " creation failed. " + err, " info:", info);
×
204
                        setTimeout(() => {
×
205
                                process.exit(2);
×
206
                        }, 1000);
207
                }
208
        }
209
};
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