initial commit
This commit is contained in:
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2010 - 2021 Brian Carlson
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
# pg-cloudflare
|
||||
|
||||
`pg-cloudflare` makes it easier to take an existing package that relies on `tls` and `net`, and make it work in environments where only `connect()` is supported, such as Cloudflare Workers.
|
||||
|
||||
`pg-cloudflare` wraps `connect()`, the [TCP Socket API](https://github.com/wintercg/proposal-sockets-api) proposed within WinterCG, and implemented in [Cloudflare Workers](https://developers.cloudflare.com/workers/runtime-apis/tcp-sockets/), and exposes an interface with methods similar to what the `net` and `tls` modules in Node.js expose. (ex: `net.connect(path[, options][, callback])`). This minimizes the number of changes needed in order to make an existing package work across JavaScript runtimes.
|
||||
|
||||
## Installation
|
||||
|
||||
```
|
||||
npm i --save-dev pg-cloudflare
|
||||
```
|
||||
|
||||
The package uses conditional exports to support bundlers that don't know about
|
||||
`cloudflare:sockets`, so the consumer code by default imports an empty file. To
|
||||
enable the package, resolve to the `cloudflare` condition in your bundler's
|
||||
config. For example:
|
||||
|
||||
- `webpack.config.js`
|
||||
```js
|
||||
export default {
|
||||
...,
|
||||
resolve: { conditionNames: [..., "workerd"] },
|
||||
plugins: [
|
||||
// ignore cloudflare:sockets imports
|
||||
new webpack.IgnorePlugin({
|
||||
resourceRegExp: /^cloudflare:sockets$/,
|
||||
}),
|
||||
],
|
||||
}
|
||||
```
|
||||
- `vite.config.js`
|
||||
|
||||
> [!NOTE]
|
||||
> If you are using the [Cloudflare Vite plugin](https://www.npmjs.com/package/@cloudflare/vite-plugin) then the following configuration is not necessary.
|
||||
|
||||
```js
|
||||
export default defineConfig({
|
||||
...,
|
||||
resolve: {
|
||||
conditions: [..., "workerd"],
|
||||
},
|
||||
build: {
|
||||
...,
|
||||
// don't try to bundle cloudflare:sockets
|
||||
rollupOptions: {
|
||||
external: [..., 'cloudflare:sockets'],
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
- `rollup.config.js`
|
||||
```js
|
||||
export default defineConfig({
|
||||
...,
|
||||
plugins: [..., nodeResolve({ exportConditions: [..., 'workerd'] })],
|
||||
// don't try to bundle cloudflare:sockets
|
||||
external: [..., 'cloudflare:sockets'],
|
||||
})
|
||||
```
|
||||
- `esbuild.config.js`
|
||||
```js
|
||||
await esbuild.build({
|
||||
...,
|
||||
conditions: [..., 'workerd'],
|
||||
})
|
||||
```
|
||||
|
||||
The concrete examples can be found in `packages/pg-bundler-test`.
|
||||
|
||||
## How to use conditionally, in non-Node.js environments
|
||||
|
||||
As implemented in `pg` [here](https://github.com/brianc/node-postgres/commit/07553428e9c0eacf761a5d4541a3300ff7859578#diff-34588ad868ebcb232660aba7ee6a99d1e02f4bc93f73497d2688c3f074e60533R5-R13), a typical use case might look as follows, where in a Node.js environment the `net` module is used, while in a non-Node.js environment, where `net` is unavailable, `pg-cloudflare` is used instead, providing an equivalent interface:
|
||||
|
||||
```js
|
||||
module.exports.getStream = function getStream(ssl = false) {
|
||||
const net = require('net')
|
||||
if (typeof net.Socket === 'function') {
|
||||
return net.Socket()
|
||||
}
|
||||
const { CloudflareSocket } = require('pg-cloudflare')
|
||||
return new CloudflareSocket(ssl)
|
||||
}
|
||||
```
|
||||
|
||||
## Node.js implementation of the Socket API proposal
|
||||
|
||||
If you're looking for a way to rely on `connect()` as the interface you use to interact with raw sockets, but need this interface to be available in a Node.js environment, [`@arrowood.dev/socket`](https://github.com/Ethan-Arrowood/socket) provides a Node.js implementation of the Socket API.
|
||||
|
||||
### license
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2023 Brian M. Carlson
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import cf from '../dist/index.js'
|
||||
|
||||
export const CloudflareSocket = cf.CloudflareSocket
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"name": "pg-cloudflare",
|
||||
"version": "1.3.0",
|
||||
"description": "A socket implementation that can run on Cloudflare Workers using native TCP connections.",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"ts-node": "^8.5.4",
|
||||
"typescript": "^4.0.3"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"workerd": {
|
||||
"import": "./esm/index.mjs",
|
||||
"require": "./dist/index.js"
|
||||
},
|
||||
"default": "./dist/empty.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"build:watch": "tsc --watch",
|
||||
"prepublish": "yarn build",
|
||||
"test": "echo e2e test in pg package"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/brianc/node-postgres.git",
|
||||
"directory": "packages/pg-cloudflare"
|
||||
},
|
||||
"files": [
|
||||
"/dist/*{js,ts,map}",
|
||||
"/src",
|
||||
"/esm"
|
||||
],
|
||||
"gitHead": "d10e09c888f94abf77382aba6f353ca665a1cf09"
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
// This is an empty module that is served up when outside of a workerd environment
|
||||
// See the `exports` field in package.json
|
||||
export default {}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
import { SocketOptions, Socket, TlsOptions } from 'cloudflare:sockets'
|
||||
import { EventEmitter } from 'events'
|
||||
|
||||
/**
|
||||
* Wrapper around the Cloudflare built-in socket that can be used by the `Connection`.
|
||||
*/
|
||||
export class CloudflareSocket extends EventEmitter {
|
||||
writable = false
|
||||
destroyed = false
|
||||
|
||||
private _upgrading = false
|
||||
private _upgraded = false
|
||||
private _cfSocket: Socket | null = null
|
||||
private _cfWriter: WritableStreamDefaultWriter | null = null
|
||||
private _cfReader: ReadableStreamDefaultReader | null = null
|
||||
|
||||
constructor(readonly ssl: boolean) {
|
||||
super()
|
||||
}
|
||||
|
||||
setNoDelay() {
|
||||
return this
|
||||
}
|
||||
setKeepAlive() {
|
||||
return this
|
||||
}
|
||||
ref() {
|
||||
return this
|
||||
}
|
||||
unref() {
|
||||
return this
|
||||
}
|
||||
|
||||
async connect(port: number, host: string, connectListener?: (...args: unknown[]) => void) {
|
||||
try {
|
||||
log('connecting')
|
||||
if (connectListener) this.once('connect', connectListener)
|
||||
|
||||
const options: SocketOptions = this.ssl ? { secureTransport: 'starttls' } : {}
|
||||
const mod = await import('cloudflare:sockets')
|
||||
const connect = mod.connect
|
||||
this._cfSocket = connect(`${host}:${port}`, options)
|
||||
this._cfWriter = this._cfSocket.writable.getWriter()
|
||||
this._addClosedHandler()
|
||||
|
||||
this._cfReader = this._cfSocket.readable.getReader()
|
||||
if (this.ssl) {
|
||||
this._listenOnce().catch((e) => this.emit('error', e))
|
||||
} else {
|
||||
this._listen().catch((e) => this.emit('error', e))
|
||||
}
|
||||
|
||||
await this._cfWriter!.ready
|
||||
log('socket ready')
|
||||
this.writable = true
|
||||
this.emit('connect')
|
||||
|
||||
return this
|
||||
} catch (e) {
|
||||
this.emit('error', e)
|
||||
}
|
||||
}
|
||||
|
||||
async _listen() {
|
||||
// eslint-disable-next-line no-constant-condition
|
||||
while (true) {
|
||||
log('awaiting receive from CF socket')
|
||||
const { done, value } = await this._cfReader!.read()
|
||||
log('CF socket received:', done, value)
|
||||
if (done) {
|
||||
log('done')
|
||||
break
|
||||
}
|
||||
this.emit('data', Buffer.from(value))
|
||||
}
|
||||
}
|
||||
|
||||
async _listenOnce() {
|
||||
log('awaiting first receive from CF socket')
|
||||
const { done, value } = await this._cfReader!.read()
|
||||
log('First CF socket received:', done, value)
|
||||
this.emit('data', Buffer.from(value))
|
||||
}
|
||||
|
||||
write(
|
||||
data: Uint8Array | string,
|
||||
encoding: BufferEncoding = 'utf8',
|
||||
callback: (...args: unknown[]) => void = () => {}
|
||||
) {
|
||||
if (data.length === 0) return callback()
|
||||
if (typeof data === 'string') data = Buffer.from(data, encoding)
|
||||
|
||||
log('sending data direct:', data)
|
||||
this._cfWriter!.write(data).then(
|
||||
() => {
|
||||
log('data sent')
|
||||
callback()
|
||||
},
|
||||
(err) => {
|
||||
log('send error', err)
|
||||
callback(err)
|
||||
}
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
end(data = Buffer.alloc(0), encoding: BufferEncoding = 'utf8', callback: (...args: unknown[]) => void = () => {}) {
|
||||
log('ending CF socket')
|
||||
this.write(data, encoding, (err) => {
|
||||
this._cfSocket!.close()
|
||||
if (callback) callback(err)
|
||||
})
|
||||
return this
|
||||
}
|
||||
|
||||
destroy(reason: string) {
|
||||
log('destroying CF socket', reason)
|
||||
this.destroyed = true
|
||||
return this.end()
|
||||
}
|
||||
|
||||
startTls(options: TlsOptions) {
|
||||
if (this._upgraded) {
|
||||
// Don't try to upgrade again.
|
||||
this.emit('error', 'Cannot call `startTls()` more than once on a socket')
|
||||
return
|
||||
}
|
||||
this._cfWriter!.releaseLock()
|
||||
this._cfReader!.releaseLock()
|
||||
this._upgrading = true
|
||||
this._cfSocket = this._cfSocket!.startTls(options)
|
||||
this._cfWriter = this._cfSocket.writable.getWriter()
|
||||
this._cfReader = this._cfSocket.readable.getReader()
|
||||
this._addClosedHandler()
|
||||
this._listen().catch((e) => this.emit('error', e))
|
||||
}
|
||||
|
||||
_addClosedHandler() {
|
||||
this._cfSocket!.closed.then(() => {
|
||||
if (!this._upgrading) {
|
||||
log('CF socket closed')
|
||||
this._cfSocket = null
|
||||
this.emit('close')
|
||||
} else {
|
||||
this._upgrading = false
|
||||
this._upgraded = true
|
||||
}
|
||||
}).catch((e) => this.emit('error', e))
|
||||
}
|
||||
}
|
||||
|
||||
const debug = false
|
||||
|
||||
function dump(data: unknown) {
|
||||
if (data instanceof Uint8Array || data instanceof ArrayBuffer) {
|
||||
const hex = Buffer.from(data).toString('hex')
|
||||
const str = new TextDecoder().decode(data)
|
||||
return `\n>>> STR: "${str.replace(/\n/g, '\\n')}"\n>>> HEX: ${hex}\n`
|
||||
} else {
|
||||
return data
|
||||
}
|
||||
}
|
||||
|
||||
function log(...args: unknown[]) {
|
||||
debug && console.log(...args.map(dump))
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
declare module 'cloudflare:sockets' {
|
||||
export class Socket {
|
||||
public readonly readable: any
|
||||
public readonly writable: any
|
||||
public readonly closed: Promise<void>
|
||||
public close(): Promise<void>
|
||||
public startTls(options: TlsOptions): Socket
|
||||
}
|
||||
|
||||
export type TlsOptions = {
|
||||
expectedServerHostname?: string
|
||||
}
|
||||
|
||||
export type SocketAddress = {
|
||||
hostname: string
|
||||
port: number
|
||||
}
|
||||
|
||||
export type SocketOptions = {
|
||||
secureTransport?: 'off' | 'on' | 'starttls'
|
||||
allowHalfOpen?: boolean
|
||||
}
|
||||
|
||||
export function connect(address: string | SocketAddress, options?: SocketOptions): Socket
|
||||
}
|
||||
Reference in New Issue
Block a user