All files / src/emulator emulator.js

70.77% Statements 46/65
51.61% Branches 16/31
58.82% Functions 10/17
72.58% Lines 45/62

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                                            11x   11x 11x   11x                           11x 11x 11x 11x               3x                                                   91x 91x     91x 91x 91x     91x                   91x     91x   91x 91x                     91x     91x                     91x   91x 91x 181x 181x 181x 181x 90x       91x 835x 835x     91x 91x     91x   91x       91x   91x 90x     90x                                                                             91x 91x 91x 90x 90x                
/*
 * Flow JS Testing
 *
 * Copyright 2020-2021 Dapper Labs, 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 {send, build, getBlock, decode, config} from "@onflow/fcl"
import {Logger, LOGGER_LEVELS} from "./logger"
import {getAvailablePorts} from "../utils"
 
const {spawn} = require("child_process")
 
const DEFAULT_HTTP_PORT = 8080
const DEFAULT_GRPC_PORT = 3569
 
const print = {
  log: console.log,
  service: console.log,
  info: console.log,
  error: console.error,
  warn: console.warn,
}
 
/** Class representing emulator */
export class Emulator {
  /**
   * Create an emulator.
   */
  constructor() {
    this.initialized = false
    this.logging = false
    this.filters = []
    this.logger = new Logger()
  }
 
  /**
   * Set logging flag.
   * @param {boolean} logging - whether logs shall be printed
   */
  setLogging(logging) {
    this.logging = logging
  }
 
  /**
   * Log message with a specific type.
   * @param {*} message - message to put into log output
   * @param {"log"|"error"} type - type of the message to output
   */
  log(message, type = "log") {
    if (this.logging !== false) {
      print[type](message)
    }
  }
 
  /**
   * Start emulator.
   * @param {Object} options - Optional parameters to start emulator with
   * @param {string} [options.flags] - Extra flags to supply to emulator
   * @param {boolean} [options.logging] - Switch to enable/disable logging by default
   * @param {number} [options.grpcPort] - Hardcoded GRPC port
   * @param {number} [options.restPort] - Hardcoded REST/HTTP port
   * @param {number} [options.adminPort] - Hardcoded admin port
   * @returns Promise<*>
   */
  async start(options = {}) {
    // populate emulator ports with available ports
    const ports = await getAvailablePorts(3)
    const [grpcPort, restPort, adminPort] = ports
 
    // override ports if specified in options
    this.grpcPort = options.grpcPort || grpcPort
    this.restPort = options.restPort || restPort
    this.adminPort = options.adminPort || adminPort
 
    // Support deprecated start call using static port
    Iif (arguments.length > 1 || typeof arguments[0] === "number") {
      console.warn(`Calling emulator.start with the port argument is now deprecated in favour of dynamically selected ports and will be removed in future versions of flow-js-testing.
Please refrain from supplying this argument, as using it may cause unintended consequences.
More info: https://github.com/onflow/flow-js-testing/blob/master/TRANSITIONS.md#0001-deprecate-emulatorstart-port-argument`)
      ;[this.adminPort, options = {}] = arguments
 
      const offset = this.adminPort - DEFAULT_HTTP_PORT
      this.grpcPort = DEFAULT_GRPC_PORT + offset
    }
 
    const {flags, logging = false, signatureCheck = false} = options
 
    // config access node
    config().put("accessNode.api", `http://localhost:${this.restPort}`)
 
    this.logging = logging
    this.process = spawn("flow", [
      "emulator",
      "--verbose",
      `--log-format=JSON`,
      `--rest-port=${this.restPort}`,
      `--admin-port=${this.adminPort}`,
      `--port=${this.grpcPort}`,
      `--skip-version-check`,
      signatureCheck ? "" : "--skip-tx-validation",
      flags,
    ])
    this.logger.setProcess(this.process)
 
    // Listen to logger to display logs if enabled
    this.logger.on("*", (level, msg) => {
      if (!this.filters.includes(level)) return
 
      this.log(`${level.toUpperCase()}: ${msg}`)
 
      if (msg.includes("Starting") && msg.includes(this.adminPort)) {
        this.log("EMULATOR IS UP! Listening for events!")
      }
    })
 
    // Suppress logger warning while waiting for emulator
    await config().put("logger.level", 0)
 
    return new Promise((resolve, reject) => {
      const cleanup = success => {
        this.initialized = success
        this.logger.removeListener(LOGGER_LEVELS.ERROR, listener)
        clearInterval(internalId)
        if (success) resolve(true)
        else reject()
      }
 
      let internalId
      const checkLiveness = async function () {
        try {
          await send(build([getBlock(false)])).then(decode)
 
          // Enable logger after emulator has come online
          await config().put("logger.level", 2)
          cleanup(true)
        } catch (err) {} // eslint-disable-line no-unused-vars, no-empty
      }
      internalId = setInterval(checkLiveness, 100)
 
      const listener = msg => {
        this.log(`EMULATOR ERROR: ${msg}`, "error")
        cleanup(false)
      }
      this.logger.on(LOGGER_LEVELS.ERROR, listener)
 
      this.process.on("close", code => {
        Iif (this.filters.includes("service")) {
          this.log(`EMULATOR: process exited with code ${code}`)
        }
        cleanup(false)
      })
    })
  }
 
  /**
   * Clear all log filters.
   * @returns void
   **/
  clearFilters() {
    this.filters = []
  }
 
  /**
   * Remove specific type of log filter.
   * @param {(debug|info|warning)} type - type of message
   * @returns void
   **/
  removeFilter(type) {
    this.filters = this.filters.filter(item => item !== type)
  }
 
  /**
   * Add log filter.
   * @param {(debug|info|warning)} type type - type of message
   * @returns void
   **/
  addFilter(type) {
    if (!this.filters.includes(type)) {
      this.filters.push(type)
    }
  }
 
  /**
   * Stop emulator.
   * @returns Promise<*>
   */
  async stop() {
    // eslint-disable-next-line no-undef
    return new Promise(resolve => {
      this.process.kill()
      setTimeout(() => {
        this.initialized = false
        resolve(false)
      }, 50)
    })
  }
}
 
/** Singleton instance */
export default new Emulator()