testground / sdk-js

Other
1 stars 3 forks source link

feat: use new sync service #17

Closed hacdias closed 3 years ago

hacdias commented 3 years ago

This PR changes the sync package implementation to use the new sync service. Read more at testground/sync-service#4.

hacdias commented 3 years ago

@alanshaw long time no see 😄 Since you're the master of JS iterators and I'm a bit blocked, I have a question for you.

I want to have a connection to a websocket and a function doRequest that sends a certain request to the websocket. There may be one or more responses and I can simply check for the response ID to see if it matches the request ID.

In Go, I'm simply using channels: I have a map id => channel and every time there is a new message on the websocket, I redirect the message to the right channel.

On JavaScript (must be both Node and browser compatible), I tried using event emitters and generators with no success. It is also important that there is a way to simply "cancel" the request and do not accept more incoming messages for such request.

  ws.onmessage = function incoming (event) {
    const res = /** @type Response */(JSON.parse(event.data.toString()))

    const ee = emitters[res.id]
    if (!ee) {
      logger.warn(`no event emitter available for response: ${res.id}`)
    } else {
      ee.emit('response', res)
    }
  }

  /**
   * @param {Request} req
   * @returns {ResponseIterator}
   */
  const doRequest = function (req) {
    const id = next++
    req.id = id.toString()

    let run = true

    const cancel = () => {
      run = false
    }

    const wait = (async function * () {
      const ee = new EventEmitter()
      emitters[id] = ee
      ws.send(JSON.stringify(req))

      while (run) { // eslint-disable-line
        yield /** @type {Response} */({})

        ee.on('response', res => {
          // Does not work bc yield cannot be in anon func
          yield res
        })
      }
    })()

    return {
      cancel,
      wait
    }
  }

I saw you have a it-ws package, but I didn't figure out if it could be easily applied here. Do you have any recommended strategy for this?

hacdias commented 3 years ago

To note: Ping Pong example test is failing.