-
Notifications
You must be signed in to change notification settings - Fork 0
opts string #17
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
aricart
wants to merge
3
commits into
main
Choose a base branch
from
optsstring
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
opts string #17
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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]}`); | ||
| } | ||
| // 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); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"); | ||
| }); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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://orws://? It looks like if I providenats://then this will turn it intonats://nats://whatever, andtls://xintonats://tls://xThere was a problem hiding this comment.
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/sor 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.There was a problem hiding this comment.
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/tlstype schemes if they are included as they are meaningless. For secure options,tlsneeds to be set, this prevents inconsistencies where a client connects via TLS on one server, but not in another because of some prefix.There was a problem hiding this comment.
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 thatencode()should also check fornatss:and avoid prependingnats:to that? Or are we relying upon the parse inserting only the hostname into the server list, so encode will never see that?There was a problem hiding this comment.
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.