Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
119 lines (100 loc) · 2.71 KB
/
Copy pathindex.js
File metadata and controls
119 lines (100 loc) · 2.71 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
var r = require('rethinkdb')
var Promise = require('bluebird')
var setup = require('./setup')
var logger = require('../util/logger')
var lifecycle = require('../util/lifecycle')
var srv = require('../util/srv')
var db = module.exports = Object.create(null)
var log = logger.createLogger('db')
function connect() {
var options = {
// These environment variables are exposed when we --link to a
// RethinkDB container.
url: process.env.RETHINKDB_PORT_28015_TCP || 'tcp://127.0.0.1:28015'
, db: process.env.RETHINKDB_ENV_DATABASE || 'stf'
, authKey: process.env.RETHINKDB_ENV_AUTHKEY
}
return srv.resolve(options.url)
.then(function(records) {
function next() {
var record = records.shift()
if (!record) {
throw new Error('No hosts left to try')
}
log.info('Connecting to %s:%d', record.name, record.port)
return r.connect({
host: record.name
, port: record.port
, db: options.db
, authKey: options.authKey
})
.catch(r.Error.RqlDriverError, function() {
log.info('Unable to connect to %s:%d', record.name, record.port)
return next()
})
}
return next()
})
}
// Export connection as a Promise
db.connect = (function() {
var connection
, queue = []
lifecycle.observe(function() {
if (connection) {
return connection.close()
}
})
function createConnection() {
return connect()
.then(function(conn) {
connection = conn
conn.on('close', function closeListener() {
log.warn('Connection closed')
connection = null
conn.removeListener('close', closeListener)
createConnection()
})
queue.splice(0).forEach(function(resolver) {
resolver.resolve(conn)
})
return conn
})
.catch(function(err) {
log.fatal(err.message)
lifecycle.fatal()
})
}
createConnection()
return function() {
return new Promise(function(resolve, reject) {
if (connection) {
resolve(connection)
}
else {
queue.push({
resolve: resolve
, reject: reject
})
}
})
}
})()
// Close connection, we don't really care if it hasn't been created yet or not
db.close = function() {
return db.connect().then(function(conn) {
return conn.close()
})
}
// Small utility for running queries without having to acquire a connection
db.run = function(q, options) {
return db.connect().then(function(conn) {
return q.run(conn, options)
})
}
// Sets up the database
db.setup = function() {
return db.connect().then(function(conn) {
return setup(conn)
})
}