-
-
Notifications
You must be signed in to change notification settings - Fork 189
/
manager.ts
274 lines (239 loc) · 7.6 KB
/
manager.ts
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
/*
* @adonisjs/lucid
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import type { Emitter } from '@adonisjs/core/events'
import type { Logger } from '@adonisjs/core/logger'
import {
ReportNode,
ConnectionNode,
ConnectionConfig,
ConnectionContract,
ConnectionManagerContract,
} from '../types/database.js'
import { Connection } from './index.js'
import * as errors from '../errors.js'
/**
* Connection manager job is to manage multiple named connections. You can add any number
* or connections by registering their config only once and then make use of `connect`
* and `close` methods to create and destroy db connections.
*/
export class ConnectionManager implements ConnectionManagerContract {
/**
* List of managed connections
*/
connections: ConnectionManagerContract['connections'] = new Map()
/**
* Connections for which the config was patched. They must get removed
* overtime, unless application is behaving unstable.
*/
private orphanConnections: Set<ConnectionContract> = new Set()
constructor(
private logger: Logger,
private emitter: Emitter<any>
) {}
/**
* Handles disconnection of a connection
*/
private handleDisconnect(connection: ConnectionContract) {
/**
* We received the close event on the orphan connection and not the connection
* that is in use
*/
if (this.orphanConnections.has(connection)) {
this.orphanConnections.delete(connection)
this.emitter.emit('db:connection:disconnect', connection)
this.logger.trace({ connection: connection.name }, 'disconnecting connection inside manager')
return
}
const internalConnection = this.get(connection.name)
/**
* This will be false, when connection was released at the
* time of closing
*/
if (!internalConnection) {
return
}
this.emitter.emit('db:connection:disconnect', connection)
this.logger.trace({ connection: connection.name }, 'disconnecting connection inside manager')
delete internalConnection.connection
internalConnection.state = 'closed'
}
/**
* Handles event when a new connection is added
*/
private handleConnect(connection: ConnectionContract) {
const internalConnection = this.get(connection.name)
if (!internalConnection) {
return
}
this.emitter.emit('db:connection:connect', connection)
internalConnection.state = 'open'
}
/**
* Monitors a given connection by listening for lifecycle events
*/
private monitorConnection(connection: ConnectionContract): void {
connection.on('disconnect', ($connection) => this.handleDisconnect($connection))
connection.on('connect', ($connection) => this.handleConnect($connection))
connection.on('error', (error, $connection) => {
this.emitter.emit('db:connection:error', [error, $connection])
})
}
/**
* Add a named connection with it's configuration. Make sure to call `connect`
* before using the connection to make database queries.
*/
add(connectionName: string, config: ConnectionConfig): void {
/**
* Noop when connection already exists. If one wants to change the config, they
* must release the old connection and add a new one
*/
if (this.has(connectionName)) {
return
}
this.logger.trace({ connection: connectionName }, 'adding new connection to the manager')
this.connections.set(connectionName, {
name: connectionName,
config: config,
state: 'registered',
})
}
/**
* Connect to the database using config for a given named connection
*/
connect(connectionName: string): void {
const connection = this.connections.get(connectionName)
if (!connection) {
throw new errors.E_UNMANAGED_DB_CONNECTION([connectionName])
}
/**
* Ignore when the there is already a connection.
*/
if (this.isConnected(connection.name)) {
return
}
/**
* Create a new connection and monitor it's state
*/
connection.connection = new Connection(connection.name, connection.config, this.logger)
this.monitorConnection(connection.connection)
connection.connection.connect()
}
/**
* Patching the config
*/
patch(connectionName: string, config: ConnectionConfig): void {
const connection = this.get(connectionName)
/**
* If connection is missing, then simply add it
*/
if (!connection) {
return this.add(connectionName, config)
}
/**
* Move the current connection to the orphan connections. We need
* to keep a separate track of old connections to make sure
* they cleanup after some time
*/
if (connection.connection) {
this.orphanConnections.add(connection.connection)
connection.connection.disconnect()
}
/**
* Updating config and state. Next call to connect will use the
* new config
*/
connection.state = 'migrating'
connection.config = config
/**
* Removing the connection right away, so that the next call to `connect`
* creates a new one with new config
*/
delete connection.connection
}
/**
* Returns the connection node for a given named connection
*/
get(connectionName: string): ConnectionNode | undefined {
return this.connections.get(connectionName)
}
/**
* Returns a boolean telling if we have connection details for
* a given named connection. This method doesn't tell if
* connection is connected or not.
*/
has(connectionName: string): boolean {
return this.connections.has(connectionName)
}
/**
* Returns a boolean telling if connection has been established
* with the database or not
*/
isConnected(connectionName: string): boolean {
if (!this.has(connectionName)) {
return false
}
const connection = this.get(connectionName)!
return !!connection.connection && connection.state === 'open'
}
/**
* Closes a given connection and can optionally release it from the
* tracking list
*/
async close(connectionName: string, release: boolean = false): Promise<void> {
if (this.isConnected(connectionName)) {
const connection = this.get(connectionName)!
await connection.connection!.disconnect()
connection.state = 'closing'
}
if (release) {
await this.release(connectionName)
}
}
/**
* Close all tracked connections
*/
async closeAll(release: boolean = false): Promise<void> {
await Promise.all(Array.from(this.connections.keys()).map((name) => this.close(name, release)))
}
/**
* Release a connection. This will disconnect the connection
* and will delete it from internal list
*/
async release(connectionName: string): Promise<void> {
if (this.isConnected(connectionName)) {
await this.close(connectionName, true)
} else {
this.connections.delete(connectionName)
}
}
/**
* Returns the report for all the connections marked for healthChecks.
*/
async report(): Promise<any & { meta: ReportNode[] }> {
const reports = await Promise.all(
Array.from(this.connections.keys())
.filter((one) => this.get(one)!.config.healthCheck)
.map((one) => {
this.connect(one)
return this.get(one)!.connection!.getReport()
})
)
const healthy = !reports.find((report) => !!report.error)
return {
displayName: 'Database',
health: {
healthy,
message: healthy
? 'All connections are healthy'
: 'One or more connections are not healthy',
},
meta: reports,
}
}
}