Skip to content

Commit

Permalink
Add support to stream factory (#2898)
Browse files Browse the repository at this point in the history
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: https://github.com/sidorares/node-mysql2/blob/ba15fe25703665e516ab0a23af8d828d1473b8c3/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>
  • Loading branch information
ruyadorno committed Jan 23, 2023
1 parent 3e34816 commit f82f39c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
5 changes: 5 additions & 0 deletions packages/pg/lib/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@ class Connection extends EventEmitter {
constructor(config) {
super()
config = config || {}

this.stream = config.stream || new net.Socket()
if (typeof this.stream === 'function') {
this.stream = this.stream(config)
}

this._keepAlive = config.keepAlive
this._keepAliveInitialDelayMillis = config.keepAliveInitialDelayMillis
this.lastBuffer = false
Expand Down
12 changes: 12 additions & 0 deletions packages/pg/test/unit/connection/startup-tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,18 @@ test('connection can take existing stream', function () {
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()
Expand Down

0 comments on commit f82f39c

Please sign in to comment.