Skip to content

Improve Future cancellation story in JsonRpcProvider constructor. #111

Description

@emizzle

JsonRpcProvider is constructed with two futures:

type
  JsonRpcProvider* = ref object of Provider
    client: Future[RpcClient]
    subscriptions: Future[JsonRpcSubscriptions]

And in the constructor, another Future[void] is created for initialized:

proc new*(
  _: type JsonRpcProvider,
  url=defaultUrl,
  pollingInterval=defaultPollingInterval): JsonRpcProvider {.raises: [JsonRpcProviderError].} =

  var initialized: Future[void]
  var client: RpcClient
  var subscriptions: JsonRpcSubscriptions

  proc initialize() {.async: (raises: [JsonRpcProviderError, CancelledError]).} =
    convertError:
      case parseUri(url).scheme
      of "ws", "wss":
        let websocket = newRpcWebSocketClient(getHeaders = jsonHeaders)
        await websocket.connect(url)
        client = websocket
        subscriptions = JsonRpcSubscriptions.new(websocket)
      else:
        let http = newRpcHttpClient(getHeaders = jsonHeaders)
        await http.connect(url)
        client = http
        subscriptions = JsonRpcSubscriptions.new(http,
                                                pollingInterval = pollingInterval)
      subscriptions.start()

  proc awaitClient(): Future[RpcClient] {.
      async: (raises: [JsonRpcProviderError, CancelledError])
  .} =
    convertError:
      await initialized
      return client

  proc awaitSubscriptions(): Future[JsonRpcSubscriptions] {.
      async: (raises: [JsonRpcProviderError, CancelledError])
  .} =
    convertError:
      await initialized
      return subscriptions

  initialized = initialize()
  return JsonRpcProvider(client: awaitClient(), subscriptions: awaitSubscriptions())

If these futures are never completed/awaited, they could leak. This could happen anytime an exception is raised in the constructor, or if an exception is raised in awaitSubscriptions/awaitClient, or if JsonRpcProvider is successfully constructed but then the futures are not completed/awaited.

If exceptions are raised, the futures would need to be cancelled.

If the construction is successful, the futures would need to be cancelled on destruction.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions