Skip to content
Draft
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
23 changes: 23 additions & 0 deletions opts/deno.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "@synadiaorbit/opts",
"version": "1.0.0-1",
"exports": {
".": "./mod.ts"
},
"publish": {
"exclude": ["./examples"]
},
"tasks": {
"clean": "rm -Rf ./coverage",

"test": {
"command": "deno test --allow-all --parallel --reload --quiet --coverage=coverage",
"dependencies": ["clean"]
},
"cover": "deno coverage ./coverage --lcov > ./coverage/out.lcov && genhtml -o ./coverage/html ./coverage/out.lcov && open ./coverage/html/index.html"
},
"imports": {
"@nats-io/nats-core": "jsr:@nats-io/nats-core@^3.0.0-50",
"@std/assert": "jsr:@std/assert@^1.0.13"
}
}
263 changes: 263 additions & 0 deletions opts/mod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,263 @@
/*
* Copyright 2025 Synadia Communications, Inc
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import type { ConnectionOptions } from "@nats-io/nats-core";

type ConnectionProperty = Omit<
keyof ConnectionOptions & { creds: string },
"authenticator" | "reconnectDelayHandler"
>;

const booleanProps = [
"debug",
"ignoreAuthErrorAbort",
"ignoreClusterUpdates",
"noAsyncTraces",
"noEcho",
"noRandomize",
"pedantic",
"reconnect",
"resolve",
"verbose",
"waitOnFirstConnect",
"handshakeFirst",
] as const;

const numberProps = [
"maxPingOut",
"maxReconnectAttempts",
"pingInterval",
"reconnectJitter",
"reconnectJitterTLS",
"reconnectTimeWait",
"timeout",
] as const;

const stringProps = [
"name",
"inboxPrefix",
] as const;
const arrayProps = ["servers"] as const;

const tlsBooleanProps = [
"handshakeFirst",
];

const tlsStringProps = [
"cert",
"certFile",
"ca",
"caFile",
"key",
"keyFile",
];

function encodeStringPropsFn(src: Record<string, unknown>, target: URL) {
return (n: string) => {
const v = src[n] as string | undefined;
if (v) {
target.searchParams.append(n, encodeURIComponent(v));
}
};
}

function encodeBooleanPropsFn(src: Record<string, unknown>, target: URL) {
return (n: string) => {
const v = src[n] as boolean | undefined;
if (typeof v === "boolean") {
target.searchParams.append(n, v ? "true" : "false");
}
};
}

function encodeNumberPropsFn(src: Record<string, unknown>, target: URL) {
return (n: string) => {
const v = src[n] as number | undefined;
if (typeof v === "number") {
target.searchParams.append(n, v.toString());
}
};
}

export function encode(opts: Partial<ConnectionOptions>): string {
opts = opts || {};
opts = Object.assign({}, opts);

if (typeof opts?.servers === "string") {
opts.servers = [opts.servers];
}
let u: URL;
if (opts?.servers?.length) {
if (
opts.servers[0].startsWith("nats://") ||
opts.servers[0].startsWith("wss://") ||
opts.servers[0].startsWith("ws://")
) {
u = new URL(opts.servers[0]);
} else {
u = new URL(`nats://${opts.servers[0]}`);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this do something to start with the opts.servers starting with something other than wss:// or ws://? It looks like if I provide nats:// then this will turn it into nats://nats://whatever, and tls://x into nats://tls://x

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for the javascript client you don't provide the scheme - it is host port, the only one that needs to have a scheme is ws/s or I cannot tell what they are. - But possibly the thing to do is whip through all the servers and rip out the scheme if it isn't ws/s.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have added a check for this - the javascript clients strops nats/tls type schemes if they are included as they are meaningless. For secure options, tls needs to be set, this prevents inconsistencies where a client connects via TLS on one server, but not in another because of some prefix.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So you've now introduced in parse() handling for natss: to do the TLS-handshake-on-connect behavior, which is great. But doesn't this mean that encode() should also check for natss: and avoid prepending nats: to that? Or are we relying upon the parse inserting only the hostname into the server list, so encode will never see that?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Encode is using the connection options, there's no such prefix that is understood - the serialized version does do that, but when decoded recreates the connect options.

}
// remove this server from the list as it is part of the URL
opts.servers = opts.servers.slice(1);
} else {
u = new URL("nats://127.0.0.1:4222");
}
if (opts.port) {
u.port = `${opts.port}`;
}

if (opts.user) {
u.username = opts.user;
}
if (opts.pass) {
u.password = opts.pass;
}
if (opts.token) {
u.username = opts.token;
}

arrayProps.forEach((n) => {
let v = opts[n] as string[] | string;
if (!Array.isArray(v)) {
v = [v];
}
if (v) {
v.forEach((s) => {
u.searchParams.append(n, encodeURIComponent(s));
});
}
});

stringProps.forEach(encodeStringPropsFn(opts, u));
numberProps.forEach(encodeNumberPropsFn(opts, u));
booleanProps.forEach(encodeBooleanPropsFn(opts, u));

if (opts.tls) {
if (u.protocol !== "nats:") {
throw new Error("tls options can only be used with nats:// urls");
}
u.protocol = opts.tls.handshakeFirst ? "natss:" : "tls:";
tlsStringProps.forEach(
encodeStringPropsFn(opts.tls as Record<string, unknown>, u),
);
}

return u.toString();
}

type Values = boolean | number | string | string[];
type Obj = Record<string, Values>;
type Config = Record<string, Values | Obj>;

function configBooleanFn(u: URL, target: Config) {
return (n: string) => {
const v = u?.searchParams.get(n) || null;
if (v !== null) {
target[n] = v === "true";
}
};
}

function configNumberFn(u: URL, target: Config) {
return (
n: string,
) => {
const v = u?.searchParams.get(n) || null;
if (v !== null) {
target[n] = parseInt(v);
}
};
}

function configStringFn(u: URL, target: Config) {
return (n: string) => {
const v = u?.searchParams.get(n);
if (v) {
target[n] = decodeURIComponent(v);
}
};
}

function configStringArrayFn(u: URL, target: Config) {
return (n: string) => {
let a = u?.searchParams.getAll(n);
a = a?.map((s) => decodeURIComponent(s));
if (!target[n]) {
target[n] = a;
} else {
const aa = target[n] as string[];
aa.push(...a);
target[n] = aa;
}
};
}

export function parse(
str = "",
): Promise<Partial<ConnectionOptions>> {
if (str === "") {
return Promise.resolve({ servers: "127.0.0.1:4222" });
}

const u = URL.parse(str);
if (u === null) {
return Promise.reject(new Error(`failed to parse '${str}'`));
}

const opts: ConnectionOptions = {};
const r = opts as Record<string, Values>;
if (u.protocol === "natss:") {
opts.tls = { handshakeFirst: true };
r.servers = [u.host];
} else if (u.protocol !== "nats:") {
const protocol = u.protocol;
const host = u.host;
let s = `${protocol}//${host}`;
if (u.pathname && u.pathname !== "/") {
s += u.pathname;
}
r.servers = [s];
} else {
r.servers = [u.host];
}

if (u.username) {
if (u.password === undefined || u.password === "") {
opts.token = u.username;
} else {
opts.user = u.username;
}
}
if (u.password) {
opts.pass = u.password;
}
if (u.protocol === "natss") {
opts.tls = { handshakeFirst: true };
}

booleanProps.forEach(configBooleanFn(u, r));
stringProps.forEach(configStringFn(u, r));
numberProps.forEach(configNumberFn(u, r));
arrayProps.forEach(configStringArrayFn(u, r));

const tls: Obj = opts.tls as Obj || {};
tlsBooleanProps.forEach(configBooleanFn(u, tls));
tlsStringProps.forEach(configStringFn(u, tls));
if (Object.keys(tls).length > 0) {
opts.tls = tls;
}

return Promise.resolve(opts);
}
88 changes: 88 additions & 0 deletions opts/mod_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
* Copyright 2025 Synadia Communications, Inc
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type { ConnectionOptions } from "@nats-io/nats-core";
import { wsconnect } from "@nats-io/nats-core";
import { encode, parse } from "./mod.ts";
import {
assert,
assertEquals,
assertExists,
} from "https://deno.land/[email protected]/assert/mod.ts";

Deno.test("basics", async () => {
const opts: Partial<ConnectionOptions> = {};
opts.debug = true;
opts.servers = ["wss://demo.nats.io:8443"];
opts.name = "me";
opts.noEcho = true;
opts.reconnect = false;
opts.timeout = 10_000;

const u = encode(opts);
console.log(u);

const opts2 = await parse(u);
console.log(opts2);

assertEquals(opts, opts2);

const nc = await wsconnect(opts2);
console.log(nc.getServer());
await nc.flush();
await nc.close();
});

Deno.test("tls", async () => {
const opts: Partial<ConnectionOptions> = {};
opts.debug = true;
opts.servers = ["demo.nats.io:2224"];
opts.name = "me";
opts.noEcho = true;
opts.reconnect = false;
opts.timeout = 10_000;
opts.tls = {
handshakeFirst: true,
};

const u = encode(opts);
const opts2 = await parse(u);

assertEquals(opts, opts2);
});

Deno.test("schemes", async () => {
const opts: Partial<ConnectionOptions> = {};
opts.servers = [
"nats://localhost:1234",
"localhost:4222",
"wss://localhost",
];

const s = encode(opts);
const opts2 = await parse(s) as ConnectionOptions;

assertExists(opts2.servers);
assert(Array.isArray(opts2.servers));
const n =
(opts2.servers as string[]).find((s: string) => s.startsWith("nats://")) ||
"";
assertEquals(n, "");
const n2 =
(opts2.servers as string[]).find((s: string) =>
s.startsWith("localhost:1234")
) ||
"";
assertEquals(n2, "localhost:1234");
});