Skip to content

Commit

Permalink
feat: do not recreate multiaddr if not necessary
Browse files Browse the repository at this point in the history
  • Loading branch information
indietyp committed Dec 11, 2024
1 parent 969d4e6 commit 87b1170
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
20 changes: 16 additions & 4 deletions libs/@local/harpc/client/typescript/src/net/internal/multiaddr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,27 @@ import {
type MultiaddrInput,
type ResolveOptions,
} from "@multiformats/multiaddr";
import { Equal, Hash, pipe } from "effect";
import { Equal, Hash, pipe, Predicate } from "effect";

import { createProto, hashUint8Array } from "../../utils.js";

const MultiaddrSymbol = Symbol.for("@multiformats/js-multiaddr/multiaddr");
type MultiaddrSymbol = typeof MultiaddrSymbol;

const TypeId: unique symbol = Symbol(
"@local/harpc-client/net/internal/HashableMultiaddr",
);
type TypeId = typeof TypeId;

/** @internal */
export interface HashableMultiaddr extends Multiaddr, Equal.Equal {
readonly [TypeId]: TypeId;
readonly [MultiaddrSymbol]: true;
readonly inner: Multiaddr;
}

const HashableMultiaddrProto: Omit<HashableMultiaddr, "inner"> = {
[TypeId]: TypeId,
[MultiaddrSymbol]: true,

get bytes() {
Expand Down Expand Up @@ -105,8 +112,13 @@ const HashableMultiaddrProto: Omit<HashableMultiaddr, "inner"> = {
},
};

const isHashableMultiaddr = (value: unknown): value is HashableMultiaddr =>
Predicate.hasProperty(value, TypeId);

/** @internal */
export const make = (inner: Multiaddr): HashableMultiaddr =>
createProto(HashableMultiaddrProto, {
inner,
}) satisfies HashableMultiaddr;
isHashableMultiaddr(inner)
? inner
: (createProto(HashableMultiaddrProto, {
inner,
}) satisfies HashableMultiaddr);
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,7 @@ export const make = (config?: TransportConfig) =>
capacity: config?.dns?.cacheCapacity ?? 32,
timeToLive: config?.dns?.cacheTimeToLive ?? 5 * 60 * 1000,
// eslint-disable-next-line @typescript-eslint/no-use-before-define -- this is fine, because we're using it only after it's defined, as the cache accesses the transport
lookup: (address) => lookupPeer(transport, makeMultiaddr(address)),
lookup: (address) => lookupPeer(transport, address),
});

const acquire = Effect.tryPromise({
Expand Down

0 comments on commit 87b1170

Please sign in to comment.