Ruy Adorno f82f39c20c
Add support to stream factory (#2898)
This changeset enables declaring the `stream` config value as a factory
method. Providing a much more flexible control of the socket connection.

Defining a custom `stream` config value allows the postgres driver to
support a larger variety of environments/setups such as proxy servers
and secure socket connections that are used by cloud providers such as
GCP.

Currently, usage of the `stream` config value is only viable for single
connections given that it's only possible to define a single socket
stream instance per new Client/Pool instance. By adding support to a
factory function, it becomes possible to enable usage of custom socket
streams for connection pools.

For reference, see the `mysql2` driver for MySQL (linked below) for
prior art example of this pattern.

Refs: ba15fe2570/lib/connection.js (L63-L65)
Refs: https://cloud.google.com/sql/docs/postgres/connect-overview
Signed-off-by: Ruy Adorno <ruyadorno@google.com>

Signed-off-by: Ruy Adorno <ruyadorno@google.com>
2023-01-23 10:02:39 -08:00

79 lines
1.8 KiB
JavaScript

'use strict'
require('./test-helper')
var Connection = require('../../../lib/connection')
test('connection can take existing stream', function () {
var stream = new MemoryStream()
var con = new Connection({ stream: stream })
assert.equal(con.stream, stream)
})
test('connection can take stream factory method', function () {
var stream = new MemoryStream()
var connectionOpts = {}
var makeStream = function (opts) {
assert.equal(connectionOpts, opts)
return stream
}
connectionOpts.stream = makeStream
var con = new Connection(connectionOpts)
assert.equal(con.stream, stream)
})
test('using any stream', function () {
var makeStream = function () {
var stream = new MemoryStream()
stream.connect = function (port, host) {
this.connectCalled = true
this.port = port
this.host = host
}
return stream
}
var stream = makeStream()
var con = new Connection({ stream: stream })
con.connect(1234, 'bang')
test('makes stream connect', function () {
assert.equal(stream.connectCalled, true)
})
test('uses configured port', function () {
assert.equal(stream.port, 1234)
})
test('uses configured host', function () {
assert.equal(stream.host, 'bang')
})
test('after stream connects client emits connected event', function () {
var hit = false
con.once('connect', function () {
hit = true
})
assert.ok(stream.emit('connect'))
assert.ok(hit)
})
test('after stream emits connected event init TCP-keepalive', function () {
var stream = makeStream()
var con = new Connection({ stream: stream, keepAlive: true })
con.connect(123, 'test')
var res = false
stream.setKeepAlive = function (bit) {
res = bit
}
assert.ok(stream.emit('connect'))
setTimeout(function () {
assert.equal(res, true)
})
})
})