All files / util getServiceInterface.ts

20.87% Statements 19/91
0% Branches 0/32
2.5% Functions 1/40
19.27% Lines 16/83

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284  1x                               1x 1x 8x 8x 8x 8x 8x                                                                                         1x       1x     1x 1x                                                                   1x                                                                                                                                     1x                                                                                     1x                                                                                                                 1x            
import { ServiceInterfaceType } from "../StartSdk"
import { knownProtocols } from "../interfaces/Host"
import {
  AddressInfo,
  Effects,
  Host,
  HostAddress,
  Hostname,
  HostnameInfo,
  HostnameInfoIp,
  HostnameInfoOnion,
  IpInfo,
} from "../types"
 
export type UrlString = string
export type HostId = string
 
const getHostnameRegex = /^(\w+:\/\/)?([^\/\:]+)(:\d{1,3})?(\/)?/
export const getHostname = (url: string): Hostname | null => {
  const founds = url.match(getHostnameRegex)?.[2]
  Iif (!founds) return null
  const parts = founds.split("@")
  const last = parts[parts.length - 1] as Hostname | null
  return last
}
 
export type Filled = {
  hostnames: HostnameInfo[]
  onionHostnames: HostnameInfo[]
  localHostnames: HostnameInfo[]
  ipHostnames: HostnameInfo[]
  ipv4Hostnames: HostnameInfo[]
  ipv6Hostnames: HostnameInfo[]
  nonIpHostnames: HostnameInfo[]
 
  urls: UrlString[]
  onionUrls: UrlString[]
  localUrls: UrlString[]
  ipUrls: UrlString[]
  ipv4Urls: UrlString[]
  ipv6Urls: UrlString[]
  nonIpUrls: UrlString[]
}
export type FilledAddressInfo = AddressInfo & Filled
export type ServiceInterfaceFilled = {
  id: string
  /** The title of this field to be displayed */
  name: string
  /** Human readable description, used as tooltip usually */
  description: string
  /** Whether or not the interface has a primary URL */
  hasPrimary: boolean
  /** Whether or not the interface disabled */
  disabled: boolean
  /** Whether or not to mask the URIs for this interface. Useful if the URIs contain sensitive information, such as a password, macaroon, or API key */
  masked: boolean
  /** Information about the host for this binding */
  host: Host
  /** URI information */
  addressInfo: FilledAddressInfo
  /** Indicates if we are a ui/p2p/api for the kind of interface that this is representing */
  type: ServiceInterfaceType
  /** The primary hostname for the service, as chosen by the user */
  primaryHostname: Hostname | null
  /** The primary URL for the service, as chosen by the user */
  primaryUrl: UrlString | null
}
const either =
  <A>(...args: ((a: A) => boolean)[]) =>
  (a: A) =>
    args.some((x) => x(a))
const negate =
  <A>(fn: (a: A) => boolean) =>
  (a: A) =>
    !fn(a)
const unique = <A>(values: A[]) => Array.from(new Set(values))
export const addressHostToUrl = (
  { scheme, sslScheme, username, suffix }: AddressInfo,
  host: HostnameInfo,
): UrlString[] => {
  const res = []
  const fmt = (scheme: string | null, host: HostnameInfo, port: number) => {
    const excludePort =
      scheme &&
      scheme in knownProtocols &&
      port === knownProtocols[scheme as keyof typeof knownProtocols].defaultPort
    let hostname
    if (host.kind === "onion") {
      hostname = host.hostname.value
    } else Iif (host.kind === "ip") {
      if (host.hostname.kind === "domain") {
        hostname = `${host.hostname.subdomain ? `${host.hostname.subdomain}.` : ""}${host.hostname.domain}`
      } else {
        hostname = host.hostname.value
      }
    }
    return `${scheme ? `${scheme}://` : ""}${
      username ? `${username}@` : ""
    }${hostname}${excludePort ? "" : `:${port}`}${suffix}`
  }
  Iif (host.hostname.sslPort !== null) {
    res.push(fmt(sslScheme, host, host.hostname.sslPort))
  }
  Iif (host.hostname.port !== null) {
    res.push(fmt(scheme, host, host.hostname.port))
  }
 
  return res
}
 
export const filledAddress = (
  host: Host,
  addressInfo: AddressInfo,
): FilledAddressInfo => {
  const toUrl = addressHostToUrl.bind(null, addressInfo)
  const hostnames = host.hostnameInfo[addressInfo.internalPort]
 
  return {
    ...addressInfo,
    hostnames,
    get onionHostnames() {
      return hostnames.filter((h) => h.kind === "onion")
    },
    get localHostnames() {
      return hostnames.filter(
        (h) => h.kind === "ip" && h.hostname.kind === "local",
      )
    },
    get ipHostnames() {
      return hostnames.filter(
        (h) =>
          h.kind === "ip" &&
          (h.hostname.kind === "ipv4" || h.hostname.kind === "ipv6"),
      )
    },
    get ipv4Hostnames() {
      return hostnames.filter(
        (h) => h.kind === "ip" && h.hostname.kind === "ipv4",
      )
    },
    get ipv6Hostnames() {
      return hostnames.filter(
        (h) => h.kind === "ip" && h.hostname.kind === "ipv6",
      )
    },
    get nonIpHostnames() {
      return hostnames.filter(
        (h) =>
          h.kind === "ip" &&
          h.hostname.kind !== "ipv4" &&
          h.hostname.kind !== "ipv6",
      )
    },
    get urls() {
      return this.hostnames.flatMap(toUrl)
    },
    get onionUrls() {
      return this.onionHostnames.flatMap(toUrl)
    },
    get localUrls() {
      return this.localHostnames.flatMap(toUrl)
    },
    get ipUrls() {
      return this.ipHostnames.flatMap(toUrl)
    },
    get ipv4Urls() {
      return this.ipv4Hostnames.flatMap(toUrl)
    },
    get ipv6Urls() {
      return this.ipv6Hostnames.flatMap(toUrl)
    },
    get nonIpUrls() {
      return this.nonIpHostnames.flatMap(toUrl)
    },
  }
}
 
const makeInterfaceFilled = async ({
  effects,
  id,
  packageId,
  callback,
}: {
  effects: Effects
  id: string
  packageId: string | null
  callback: () => void
}) => {
  const serviceInterfaceValue = await effects.getServiceInterface({
    serviceInterfaceId: id,
    packageId,
    callback,
  })
  const hostId = serviceInterfaceValue.addressInfo.hostId
  const host = await effects.getHostInfo({
    packageId,
    hostId,
    callback,
  })
  const primaryUrl = await effects
    .getPrimaryUrl({
      serviceInterfaceId: id,
      packageId,
      callback,
    })
    .catch((e) => null)
 
  const interfaceFilled: ServiceInterfaceFilled = {
    ...serviceInterfaceValue,
    primaryUrl: primaryUrl,
    host,
    addressInfo: filledAddress(host, serviceInterfaceValue.addressInfo),
    get primaryHostname() {
      Iif (primaryUrl == null) return null
      return getHostname(primaryUrl)
    },
  }
  return interfaceFilled
}
 
export class GetServiceInterface {
  constructor(
    readonly effects: Effects,
    readonly opts: { id: string; packageId: string | null },
  ) {}
 
  /**
   * Returns the value of Store at the provided path. Restart the service if the value changes
   */
  async const() {
    const { id, packageId } = this.opts
    const callback = this.effects.restart
    const interfaceFilled: ServiceInterfaceFilled = await makeInterfaceFilled({
      effects: this.effects,
      id,
      packageId,
      callback,
    })
 
    return interfaceFilled
  }
  /**
   * Returns the value of ServiceInterfacesFilled at the provided path. Does nothing if the value changes
   */
  async once() {
    const { id, packageId } = this.opts
    const callback = () => {}
    const interfaceFilled: ServiceInterfaceFilled = await makeInterfaceFilled({
      effects: this.effects,
      id,
      packageId,
      callback,
    })
 
    return interfaceFilled
  }
 
  /**
   * Watches the value of ServiceInterfacesFilled at the provided path. Takes a custom callback function to run whenever the value changes
   */
  async *watch() {
    const { id, packageId } = this.opts
    while (true) {
      let callback: () => void = () => {}
      const waitForNext = new Promise<void>((resolve) => {
        callback = resolve
      })
      yield await makeInterfaceFilled({
        effects: this.effects,
        id,
        packageId,
        callback,
      })
      await waitForNext
    }
  }
}
export function getServiceInterface(
  effects: Effects,
  opts: { id: string; packageId: string | null },
) {
  return new GetServiceInterface(effects, opts)
}