Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/client-configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

| Property | Default | Description |
|------------------------------|------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| url | | `redis[s]://[[username][:password]@][host][:port][/db-number]` (see [`redis`](https://www.iana.org/assignments/uri-schemes/prov/redis) and [`rediss`](https://www.iana.org/assignments/uri-schemes/prov/rediss) IANA registration for more details) |
| url | | `redis[s]://[[username][:password]@][host][:port][/db-number]` (see [`redis`](https://www.iana.org/assignments/uri-schemes/prov/redis) and [`rediss`](https://www.iana.org/assignments/uri-schemes/prov/rediss) IANA registration for more details), or `unix://[[username][:password]@]/path/to/socket[?db=N]` for a UNIX domain socket |
| socket | | Socket connection properties. Unlisted [`net.connect`](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) properties (and [`tls.connect`](https://nodejs.org/api/tls.html#tlsconnectoptions-callback)) are also supported |
| socket.port | `6379` | Redis server port |
| socket.host | `'localhost'` | Redis server hostname |
Expand Down
94 changes: 94 additions & 0 deletions packages/client/lib/client/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,100 @@ describe('Client', () => {
}
});
});

describe('unix socket URLs', () => {
it('unix:///tmp/redis.sock', () => {
assert.deepEqual(
RedisClient.parseURL('unix:///tmp/redis.sock'),
{
socket: {
path: '/tmp/redis.sock',
tls: false
}
}
);
});

it('unix:///tmp/redis.sock?db=2', () => {
assert.deepEqual(
RedisClient.parseURL('unix:///tmp/redis.sock?db=2'),
{
socket: {
path: '/tmp/redis.sock',
tls: false
},
database: 2
}
);
});

it('unix://user:secret@/tmp/redis.sock?db=2', async () => {
const result = RedisClient.parseURL('unix://user:secret@/tmp/redis.sock?db=2');
const expected: RedisClientOptions = {
socket: {
path: '/tmp/redis.sock',
tls: false
},
username: 'user',
password: 'secret',
database: 2,
credentialsProvider: {
type: 'async-credentials-provider',
credentials: async () => ({
username: 'user',
password: 'secret'
})
}
};

const { credentialsProvider: _r, ...resultRest } = result;
const { credentialsProvider: _e, ...expectedRest } = expected;
assert.deepEqual(resultRest, expectedRest);

if (result.credentialsProvider?.type === 'async-credentials-provider'
&& expected.credentialsProvider?.type === 'async-credentials-provider') {
assert.deepEqual(
await result.credentialsProvider.credentials(),
await expected.credentialsProvider.credentials()
);
} else {
assert.fail('Credentials provider type mismatch');
}
});

it('percent-encoded path is decoded', () => {
assert.deepEqual(
RedisClient.parseURL('unix:///var/run/redis%20test.sock'),
{
socket: {
path: '/var/run/redis test.sock',
tls: false
}
}
);
});

it('missing path is rejected', () => {
assert.throws(
() => RedisClient.parseURL('unix://'),
TypeError
);
});

it('empty path is rejected', () => {
assert.throws(
() => RedisClient.parseURL('unix:///'),
TypeError
);
});

it('invalid db query parameter is rejected', () => {
assert.throws(
() => RedisClient.parseURL('unix:///tmp/redis.sock?db=NaN'),
TypeError
);
});
});
});

describe('parseOptions', () => {
Expand Down
71 changes: 68 additions & 3 deletions packages/client/lib/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ export type RedisClientType<
RedisClientExtensions<M, F, S, RESP, TYPE_MAPPING>
);

type ProxyClient = RedisClient<any, any, any, any, any>;
type ProxyClient = RedisClient<RedisModules, RedisFunctions, RedisScripts, RespVersions, TypeMapping>;

type NamespaceProxyClient = { _self: ProxyClient };

Expand Down Expand Up @@ -320,6 +320,7 @@ export default class RedisClient<
}
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
static #SingleEntryCache = new SingleEntryCache<any, any>()

static factory<
Expand Down Expand Up @@ -385,6 +386,12 @@ export default class RedisClient<
tls: boolean
}
} {
// unix:// URIs use a non-special scheme; WHATWG URL refuses to parse an
// authority (e.g. `user:pass@`) without a host, so handle it separately.
if (url.startsWith('unix:')) {
return RedisClient.#parseUnixURL(url);
}

// https://www.iana.org/assignments/uri-schemes/prov/redis
const { hostname, port, protocol, username, password, pathname } = new URL(url),
parsed: RedisClientOptions & {
Expand Down Expand Up @@ -440,6 +447,62 @@ export default class RedisClient<
return parsed;
}

static #parseUnixURL(url: string): RedisClientOptions & {
socket: Exclude<RedisClientOptions['socket'], undefined> & {
tls: boolean
}
} {
// unix://[user[:password]@]/path/to/sock[?db=N]
const match = /^unix:\/\/(?:([^:@/]*)(?::([^@/]*))?@)?(\/[^?#]*)(?:\?([^#]*))?(?:#.*)?$/.exec(url);
if (!match || match[3] === '/') {
throw new TypeError('Invalid unix URL');
}

const [, username, password, rawPath, rawQuery] = match,
parsed: RedisClientOptions & {
socket: Exclude<RedisClientOptions['socket'], undefined> & {
tls: boolean
}
} = {
socket: {
path: decodeURIComponent(rawPath),
tls: false
}
};

if (username) {
parsed.username = decodeURIComponent(username);
}

if (password) {
parsed.password = decodeURIComponent(password);
}

if (username || password) {
parsed.credentialsProvider = {
type: 'async-credentials-provider',
credentials: async () => (
{
username: username ? decodeURIComponent(username) : undefined,
password: password ? decodeURIComponent(password) : undefined
})
};
}

if (rawQuery) {
const db = new URLSearchParams(rawQuery).get('db');
if (db !== null) {
const database = Number(db);
if (isNaN(database)) {
throw new TypeError('Invalid db query parameter');
}
parsed.database = database;
}
}

return parsed;
}

readonly #options: RedisClientOptions<M, F, S, RESP, TYPE_MAPPING>;
#socket: RedisSocket;
readonly #queue: RedisCommandsQueue;
Expand Down Expand Up @@ -598,6 +661,7 @@ export default class RedisClient<
const cscConfig = this.#options.clientSideCache;
this.#clientSideCache = new BasicClientSideCache(cscConfig);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this.#queue.addPushHandler((push: Array<any>): boolean => {
if (push[0].toString() !== 'invalidate') return false;

Expand All @@ -612,6 +676,7 @@ export default class RedisClient<
return true
});
} else if (options?.emitInvalidate) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this.#queue.addPushHandler((push: Array<any>): boolean => {
if (push[0].toString() !== 'invalidate') return false;

Expand Down Expand Up @@ -1057,7 +1122,7 @@ export default class RedisClient<
*/
_ejectSocket(): RedisSocket {
const socket = this._self.#socket;
// @ts-ignore
// @ts-expect-error null assignment is intentional during eject
this._self.#socket = null;
socket.removeAllListeners();
return socket;
Expand Down Expand Up @@ -1524,7 +1589,7 @@ export default class RedisClient<

MULTI<isTyped extends MultiMode = MULTI_MODE['TYPED']>() {
type Multi = new (...args: ConstructorParameters<typeof RedisClientMultiCommand>) => RedisClientMultiCommandType<isTyped, [], M, F, S, RESP, TYPE_MAPPING>;
return new ((this as any).Multi as Multi)(
return new ((this as unknown as { Multi: Multi }).Multi)(
this._executeMulti.bind(this),
this._executePipeline.bind(this),
this._commandOptions?.typeMapping
Expand Down
Loading