From b41ed1ef0ed2bac1fa3d10c17a1ac4930f3569c8 Mon Sep 17 00:00:00 2001 From: Teo Gebhard Date: Mon, 11 Nov 2024 11:44:48 +0200 Subject: [PATCH 1/4] rename function --- developer-docs/testing-best-practices.md | 8 ++-- .../integration/StreamrChallenger.test.ts | 4 +- packages/cli-tools/test/storage-node.test.ts | 6 +-- packages/cli-tools/test/utils.ts | 4 +- packages/dht/src/dht/DhtNode.ts | 4 +- .../WebsocketConnectionRequest.test.ts | 4 +- .../dht/test/end-to-end/memory-leak.test.ts | 4 +- .../integration/ConnectionLocking.test.ts | 34 +++++++------- .../integration/ConnectionManager.test.ts | 6 +-- packages/dht/test/integration/DhtNode.test.ts | 4 +- .../dht/test/integration/Layer1-scale.test.ts | 2 +- .../dht/test/integration/RouteMessage.test.ts | 8 ++-- .../SimultaneousConnections.test.ts | 18 ++++---- .../StoreOnDhtWithTwoNodes.test.ts | 4 +- .../integration/WebrtcConnectorRpc.test.ts | 10 ++--- .../WebsocketConnectionManagement.test.ts | 6 +-- .../unit/ListeningRpcCommunicator.test.ts | 6 +-- packages/dht/test/unit/PeerManager.test.ts | 4 +- .../unit/RecursiveOperationSession.test.ts | 4 +- packages/dht/test/unit/StoreManager.test.ts | 4 +- .../unit/connectivityRequestHandler.test.ts | 6 +-- packages/dht/test/utils/utils.ts | 4 +- .../test/unit/GeoIpLocator-intervals.test.ts | 4 +- .../integration/broker-subscriptions.test.ts | 18 ++++---- .../multiple-publisher-plugins.test.ts | 8 ++-- .../operator/MaintainTopologyService.test.ts | 8 ++-- .../plugins/operator/OperatorPlugin.test.ts | 6 +-- .../operator/announceNodeToContract.test.ts | 4 +- .../operator/checkOperatorValueBreach.test.ts | 4 +- .../operator/maintainOperatorValue.test.ts | 4 +- .../plugins/storage/BatchManager.test.ts | 8 ++-- .../plugins/storage/BucketManager.test.ts | 24 +++++----- .../plugins/storage/StorageConfig.test.ts | 4 +- .../plugins/storage/cassanda-queries.test.ts | 4 +- .../subscriber/SubscriberPlugin.test.ts | 6 +-- packages/node/test/smoke/inspect.test.ts | 4 +- packages/node/test/smoke/profit.test.ts | 6 +-- .../operator/MaintainTopologyService.test.ts | 8 ++-- .../operator/OperatorFleetState.test.ts | 4 +- .../plugins/websocket/WebsocketServer.test.ts | 6 +-- .../test/unit/RpcCommunicator.test.ts | 12 ++--- packages/sdk/src/utils/promises.ts | 2 +- .../browser-smoke-test/nightwatch.conf.js | 2 +- packages/sdk/test/end-to-end/Metrics.test.ts | 4 +- packages/sdk/test/end-to-end/Operator.test.ts | 8 ++-- .../test/end-to-end/StreamRegistry.test.ts | 10 ++--- .../test/end-to-end/binary-publish.test.ts | 6 +-- .../erc1271-publish-subscribe.test.ts | 8 ++-- .../test/end-to-end/publish-subscribe.test.ts | 8 ++-- packages/sdk/test/end-to-end/resend.test.ts | 4 +- .../sdk/test/integration/Resends2.test.ts | 4 +- .../sdk/test/integration/Sequencing.test.ts | 10 ++--- .../sdk/test/integration/Subscriber2.test.ts | 4 +- .../integration/SubscriberKeyExchange.test.ts | 6 +-- .../integration/json-rpc-provider.test.ts | 4 +- .../test/integration/multiple-clients.test.ts | 6 +-- .../sequential-resend-subscribe.test.ts | 4 +- .../integration/update-encryption-key.test.ts | 4 +- .../sdk/test/test-utils/fake/FakeNetwork.ts | 4 +- packages/sdk/test/test-utils/utils.ts | 4 +- .../sdk/test/unit/ChainEventPoller.test.ts | 12 ++--- packages/sdk/test/unit/GapFiller.test.ts | 4 +- packages/sdk/test/unit/OrderMessages.test.ts | 4 +- packages/sdk/test/unit/OrderMessages2.test.ts | 4 +- .../sdk/test/unit/resendSubscription.test.ts | 4 +- packages/sdk/test/unit/utils.test.ts | 4 +- packages/test-utils/src/index.ts | 10 ++--- .../trackerless-network/src/NetworkStack.ts | 4 +- ...y-layer-node-with-real-connections.test.ts | 8 ++-- .../test/end-to-end/inspect.test.ts | 4 +- .../test/end-to-end/proxy-connections.test.ts | 16 +++---- .../webrtc-full-node-network.test.ts | 6 +-- .../websocket-full-node-network.test.ts | 6 +-- ...veryLayerNode-Layer1Node-Latencies.test.ts | 14 +++--- ...ontentDeliveryLayerNode-Layer1Node.test.ts | 12 ++--- .../ContentDeliveryManager.test.ts | 28 ++++++------ .../ContentDeliveryRpcRemote.test.ts | 6 +-- .../test/integration/NetworkNode.test.ts | 4 +- .../test/integration/NetworkRpc.test.ts | 4 +- .../test/integration/NetworkStack.test.ts | 4 +- .../test/integration/NodeInfoRpc.test.ts | 4 +- .../test/integration/Propagation.test.ts | 8 ++-- .../joining-streams-on-offline-peers.test.ts | 4 +- ...stream-without-default-entrypoints.test.ts | 10 ++--- .../streamEntryPointReplacing.test.ts | 6 +-- .../unit/ContentDeliveryLayerNode.test.ts | 8 ++-- .../test/unit/ContentDeliveryManager.test.ts | 4 +- .../test/unit/NeighborFinder.test.ts | 4 +- .../test/unit/StreamPartReconnect.test.ts | 4 +- packages/utils/src/exports.ts | 4 +- .../src/{waitForCondition.ts => until.ts} | 4 +- packages/utils/test/Metric.test.ts | 8 ++-- ...waitForCondition.test.ts => until.test.ts} | 44 +++++++++---------- 93 files changed, 334 insertions(+), 334 deletions(-) rename packages/utils/src/{waitForCondition.ts => until.ts} (94%) rename packages/utils/test/{waitForCondition.test.ts => until.test.ts} (63%) diff --git a/developer-docs/testing-best-practices.md b/developer-docs/testing-best-practices.md index de2cc99cd9..f6da1b74e2 100644 --- a/developer-docs/testing-best-practices.md +++ b/developer-docs/testing-best-practices.md @@ -6,7 +6,7 @@ It would seem like the best order in which to use the control flow utilities is 1. Simply await a Promise if possible and relevant 2. `waitForStreamToEnd` if dealing with ReadableStream 3. `waitForEvent` if dealing with events -4. `waitForCondition` when there is no direct handle to the async-behavior +4. `until` when there is no direct handle to the async-behavior 5. `wait` if nothing else works ### Try to avoid using `wait` when possible. @@ -15,10 +15,10 @@ It would seem like the best order in which to use the control flow utilities is - It increases test run time because we always wait for the pre-determined amount of time even if the required pre-condition has been met. - We often have to use quite large delays to err on the side of caution, increasing test run time further. -### When using `waitForCondition` favor simple conditions +### When using `until` favor simple conditions - The utility doesn't provide detailed info on what went wrong; when a condition fails, you will not have much visibility into the "why". -- Use a simple condition for `waitForCondition` and then later on in the test function perform proper assertions using the facilities provided by your test framework. -- E.g. use `waitForCondition` to wait for an array to have elements in it. Then afterwards assert the contents of those elements. +- Use a simple condition for `until` and then later on in the test function perform proper assertions using the facilities provided by your test framework. +- E.g. use `until` to wait for an array to have elements in it. Then afterwards assert the contents of those elements. ### Other - Usefulness of `waitForEvent` declines in the presence of multiple events from the same emitter with the same event type diff --git a/packages/autocertifier-server/test/integration/StreamrChallenger.test.ts b/packages/autocertifier-server/test/integration/StreamrChallenger.test.ts index 09b268af7a..68230d003f 100644 --- a/packages/autocertifier-server/test/integration/StreamrChallenger.test.ts +++ b/packages/autocertifier-server/test/integration/StreamrChallenger.test.ts @@ -12,7 +12,7 @@ import { toDhtAddressRaw } from '@streamr/dht' import path from 'path' -import { MetricsContext, waitForCondition } from '@streamr/utils' +import { MetricsContext, until } from '@streamr/utils' describe('StreamrChallenger', () => { @@ -68,7 +68,7 @@ describe('StreamrChallenger', () => { it('Happy path', async () => { await runStreamrChallenge('127.0.0.1', '12323', sessionId) - await waitForCondition(() => challengedClientTransport.getConnections().length === 0) + await until(() => challengedClientTransport.getConnections().length === 0) }) }) diff --git a/packages/cli-tools/test/storage-node.test.ts b/packages/cli-tools/test/storage-node.test.ts index 27ee4e2206..a306e0e024 100644 --- a/packages/cli-tools/test/storage-node.test.ts +++ b/packages/cli-tools/test/storage-node.test.ts @@ -2,7 +2,7 @@ import { fetchPrivateKeyWithGas } from '@streamr/test-utils' import 'jest-extended' import { StreamID } from '@streamr/sdk' import { DOCKER_DEV_STORAGE_NODE, createTestClient, runCommand } from './utils' -import { waitForCondition } from '@streamr/utils' +import { until } from '@streamr/utils' const isStored = async (streamId: StreamID): Promise => { const output = await runCommand(`storage-node list-streams ${DOCKER_DEV_STORAGE_NODE}`) @@ -19,11 +19,11 @@ describe('storage node', () => { await runCommand(`storage-node add-stream ${DOCKER_DEV_STORAGE_NODE} ${stream.id}`, { privateKey }) - await waitForCondition(async () => await isStored(stream.id) === true, 15 * 1000, 1000) + await until(async () => await isStored(stream.id) === true, 15 * 1000, 1000) await runCommand(`storage-node remove-stream ${DOCKER_DEV_STORAGE_NODE} ${stream.id}`, { privateKey }) - await waitForCondition(async () => await isStored(stream.id) === false, 15 * 1000, 1000) + await until(async () => await isStored(stream.id) === false, 15 * 1000, 1000) }, 80 * 1000) it('list nodes', async () => { diff --git a/packages/cli-tools/test/utils.ts b/packages/cli-tools/test/utils.ts index bf68aa6258..f3b8e0f8be 100644 --- a/packages/cli-tools/test/utils.ts +++ b/packages/cli-tools/test/utils.ts @@ -1,5 +1,5 @@ import { Stream, StreamrClient } from '@streamr/sdk' -import { collect, waitForCondition } from '@streamr/utils' +import { collect, until } from '@streamr/utils' import { spawn } from 'child_process' import merge2 from 'merge2' @@ -75,7 +75,7 @@ export const createTestClient = (privateKey?: string): StreamrClient => { } export const waitForTheGraphToHaveIndexed = async (stream: Stream, client: StreamrClient): Promise => { - await waitForCondition(async () => { + await until(async () => { // eslint-disable-next-line no-underscore-dangle for await (const _msg of client.searchStreams(stream.id, undefined)) { return true diff --git a/packages/dht/src/dht/DhtNode.ts b/packages/dht/src/dht/DhtNode.ts index 402b5cb431..658a3a658c 100644 --- a/packages/dht/src/dht/DhtNode.ts +++ b/packages/dht/src/dht/DhtNode.ts @@ -4,7 +4,7 @@ import { MetricsContext, merge, scheduleAtInterval, - waitForCondition + until } from '@streamr/utils' import { EventEmitter } from 'eventemitter3' import { sample } from 'lodash' @@ -621,7 +621,7 @@ export class DhtNode extends EventEmitter implements ITransport { } public async waitForNetworkConnectivity(): Promise { - await waitForCondition( + await until( () => this.connectionsView!.getConnectionCount() > 0, this.options.networkConnectivityTimeout, 100, diff --git a/packages/dht/test/end-to-end/WebsocketConnectionRequest.test.ts b/packages/dht/test/end-to-end/WebsocketConnectionRequest.test.ts index cf042af54e..d5501f261c 100644 --- a/packages/dht/test/end-to-end/WebsocketConnectionRequest.test.ts +++ b/packages/dht/test/end-to-end/WebsocketConnectionRequest.test.ts @@ -1,7 +1,7 @@ import { PeerDescriptor } from '../../generated/packages/dht/protos/PeerDescriptor' import { DhtNode } from '../../src/dht/DhtNode' import { ConnectionManager } from '../../src/connection/ConnectionManager' -import { waitForCondition } from '@streamr/utils' +import { until } from '@streamr/utils' import { createMockPeerDescriptor } from '../utils/utils' import { areEqualPeerDescriptors } from '../../src/identifiers' @@ -60,7 +60,7 @@ describe('Websocket IConnection Requests', () => { await node2.joinDht([epPeerDescriptor]) await node1.joinDht([epPeerDescriptor]) - await waitForCondition(() => { return (connected1 && connected2) }) + await until(() => { return (connected1 && connected2) }) expect((node1.getTransport() as ConnectionManager).hasConnection(node2.getNodeId())).toEqual(true) expect((node2.getTransport() as ConnectionManager).hasConnection(node1.getNodeId())).toEqual(true) diff --git a/packages/dht/test/end-to-end/memory-leak.test.ts b/packages/dht/test/end-to-end/memory-leak.test.ts index bf7381a59d..7572344e8a 100644 --- a/packages/dht/test/end-to-end/memory-leak.test.ts +++ b/packages/dht/test/end-to-end/memory-leak.test.ts @@ -1,5 +1,5 @@ import LeakDetector from 'jest-leak-detector' -import { waitForCondition } from '@streamr/utils' +import { until } from '@streamr/utils' import { DhtNode } from '../../src/dht/DhtNode' import { Message } from '../../generated/packages/dht/protos/DhtRpc' import { RpcMessage } from '../../generated/packages/proto-rpc/protos/ProtoRpc' @@ -55,7 +55,7 @@ describe('memory leak', () => { } } await sender.send(msg) - await waitForCondition(() => receivedMessage !== undefined) + await until(() => receivedMessage !== undefined) expect(receivedMessage!.messageId).toEqual(MESSAGE_ID) await Promise.all([ diff --git a/packages/dht/test/integration/ConnectionLocking.test.ts b/packages/dht/test/integration/ConnectionLocking.test.ts index dd5df2f2f0..18294ea882 100644 --- a/packages/dht/test/integration/ConnectionLocking.test.ts +++ b/packages/dht/test/integration/ConnectionLocking.test.ts @@ -1,4 +1,4 @@ -import { MetricsContext, waitForCondition } from '@streamr/utils' +import { MetricsContext, until } from '@streamr/utils' import { ConnectionManager } from '../../src/connection/ConnectionManager' import { DefaultConnectorFacade } from '../../src/connection/ConnectorFacade' import { LatencyType, Simulator } from '../../src/connection/simulator/Simulator' @@ -60,7 +60,7 @@ describe('Connection Locking', () => { const nodeId1 = toNodeId(mockPeerDescriptor1) const nodeId2 = toNodeId(mockPeerDescriptor2) await Promise.all([ - waitForCondition(() => connectionManager2.hasRemoteLockedConnection(nodeId1)), + until(() => connectionManager2.hasRemoteLockedConnection(nodeId1)), connectionManager1.lockConnection(mockPeerDescriptor2, 'testLock') ]) expect(connectionManager1.hasConnection(nodeId2)).toEqual(true) @@ -72,11 +72,11 @@ describe('Connection Locking', () => { const nodeId1 = toNodeId(mockPeerDescriptor1) const nodeId2 = toNodeId(mockPeerDescriptor2) await Promise.all([ - waitForCondition(() => connectionManager2.hasRemoteLockedConnection(nodeId1)), + until(() => connectionManager2.hasRemoteLockedConnection(nodeId1)), connectionManager1.lockConnection(mockPeerDescriptor2, 'testLock1') ]) await Promise.all([ - waitForCondition(() => connectionManager2.hasRemoteLockedConnection(nodeId1)), + until(() => connectionManager2.hasRemoteLockedConnection(nodeId1)), connectionManager1.lockConnection(mockPeerDescriptor2, 'testLock2') ]) expect(connectionManager1.hasConnection(nodeId2)).toEqual(true) @@ -88,7 +88,7 @@ describe('Connection Locking', () => { const nodeId1 = toNodeId(mockPeerDescriptor1) const nodeId2 = toNodeId(mockPeerDescriptor2) await Promise.all([ - waitForCondition(() => connectionManager2.hasRemoteLockedConnection(nodeId1)), + until(() => connectionManager2.hasRemoteLockedConnection(nodeId1)), connectionManager1.lockConnection(mockPeerDescriptor2, 'testLock') ]) expect(connectionManager1.hasConnection(nodeId2)) @@ -97,7 +97,7 @@ describe('Connection Locking', () => { connectionManager1.unlockConnection(mockPeerDescriptor2, 'testLock') expect(connectionManager1.hasLocalLockedConnection(nodeId2)).toEqual(false) - await waitForCondition(() => connectionManager2.hasRemoteLockedConnection(nodeId1) === false) + await until(() => connectionManager2.hasRemoteLockedConnection(nodeId1) === false) expect(connectionManager1.hasConnection(nodeId1)).toEqual(false) }) @@ -105,11 +105,11 @@ describe('Connection Locking', () => { const nodeId1 = toNodeId(mockPeerDescriptor1) const nodeId2 = toNodeId(mockPeerDescriptor2) await Promise.all([ - waitForCondition(() => connectionManager2.hasRemoteLockedConnection(nodeId1)), + until(() => connectionManager2.hasRemoteLockedConnection(nodeId1)), connectionManager1.lockConnection(mockPeerDescriptor2, 'testLock1') ]) await Promise.all([ - waitForCondition(() => connectionManager2.hasRemoteLockedConnection(nodeId1)), + until(() => connectionManager2.hasRemoteLockedConnection(nodeId1)), connectionManager1.lockConnection(mockPeerDescriptor2, 'testLock2') ]) @@ -128,8 +128,8 @@ describe('Connection Locking', () => { const nodeId1 = toNodeId(mockPeerDescriptor1) const nodeId2 = toNodeId(mockPeerDescriptor2) await Promise.all([ - waitForCondition(() => connectionManager2.hasRemoteLockedConnection(nodeId1)), - waitForCondition(() => connectionManager1.hasRemoteLockedConnection(nodeId2)), + until(() => connectionManager2.hasRemoteLockedConnection(nodeId1)), + until(() => connectionManager1.hasRemoteLockedConnection(nodeId2)), connectionManager1.lockConnection(mockPeerDescriptor2, 'testLock1'), connectionManager2.lockConnection(mockPeerDescriptor1, 'testLock1') ]) @@ -138,7 +138,7 @@ describe('Connection Locking', () => { expect(connectionManager2.hasLocalLockedConnection(nodeId1)) connectionManager1.unlockConnection(mockPeerDescriptor2, 'testLock1') - await waitForCondition(() => + await until(() => connectionManager1.hasRemoteLockedConnection(nodeId2) && !connectionManager1.hasLocalLockedConnection(nodeId2) && !connectionManager2.hasRemoteLockedConnection(nodeId1) @@ -153,8 +153,8 @@ describe('Connection Locking', () => { const nodeId1 = toNodeId(mockPeerDescriptor1) const nodeId2 = toNodeId(mockPeerDescriptor2) await Promise.all([ - waitForCondition(() => connectionManager2.hasRemoteLockedConnection(nodeId1)), - waitForCondition(() => connectionManager1.hasRemoteLockedConnection(nodeId2)), + until(() => connectionManager2.hasRemoteLockedConnection(nodeId1)), + until(() => connectionManager1.hasRemoteLockedConnection(nodeId2)), connectionManager1.lockConnection(mockPeerDescriptor2, 'testLock1'), connectionManager2.lockConnection(mockPeerDescriptor1, 'testLock1') ]) @@ -165,16 +165,16 @@ describe('Connection Locking', () => { //@ts-expect-error private field await connectionManager1.gracefullyDisconnectAsync(mockPeerDescriptor2) - await waitForCondition(() => + await until(() => !connectionManager1.hasRemoteLockedConnection(nodeId2) && !connectionManager1.hasLocalLockedConnection(nodeId2) ) - await waitForCondition(() => + await until(() => !connectionManager2.hasRemoteLockedConnection(nodeId1) && !connectionManager2.hasLocalLockedConnection(nodeId1) ) - await waitForCondition(() => !connectionManager2.hasConnection(nodeId1)) - await waitForCondition(() => !connectionManager1.hasConnection(nodeId2)) + await until(() => !connectionManager2.hasConnection(nodeId1)) + await until(() => !connectionManager1.hasConnection(nodeId2)) expect(connectionManager1.hasConnection(nodeId2)).toEqual(false) expect(connectionManager2.hasConnection(nodeId1)).toEqual(false) diff --git a/packages/dht/test/integration/ConnectionManager.test.ts b/packages/dht/test/integration/ConnectionManager.test.ts index c1c7fc12dc..a3fa28171d 100644 --- a/packages/dht/test/integration/ConnectionManager.test.ts +++ b/packages/dht/test/integration/ConnectionManager.test.ts @@ -1,4 +1,4 @@ -import { Logger, MetricsContext, waitForCondition, waitForEvent3 } from '@streamr/utils' +import { Logger, MetricsContext, until, waitForEvent3 } from '@streamr/utils' import { MarkOptional } from 'ts-essentials' import { ConnectionManager } from '../../src/connection/ConnectionManager' import { DefaultConnectorFacade, DefaultConnectorFacadeOptions } from '../../src/connection/ConnectorFacade' @@ -514,11 +514,11 @@ describe('ConnectionManager', () => { await Promise.all([connectedPromise1, connectedPromise2, connectionManager2.send(msg)]) await connectionManager1.enablePrivateClientMode() - await waitForCondition(() => connectionManager2.getConnections().length === 0) + await until(() => connectionManager2.getConnections().length === 0) expect(connectionManager1.getConnections().length).toEqual(1) await connectionManager1.disablePrivateClientMode() - await waitForCondition(() => connectionManager2.getConnections().length === 1) + await until(() => connectionManager2.getConnections().length === 1) expect(connectionManager1.getConnections().length).toEqual(1) await connectionManager1.stop() diff --git a/packages/dht/test/integration/DhtNode.test.ts b/packages/dht/test/integration/DhtNode.test.ts index 001246e1f8..87f6624600 100644 --- a/packages/dht/test/integration/DhtNode.test.ts +++ b/packages/dht/test/integration/DhtNode.test.ts @@ -1,4 +1,4 @@ -import { waitForCondition } from '@streamr/utils' +import { until } from '@streamr/utils' import { range, without } from 'lodash' import { DhtNodeRpcLocal } from '../../src/dht/DhtNodeRpcLocal' import { DhtNode, ListeningRpcCommunicator, toNodeId } from '../../src/exports' @@ -59,7 +59,7 @@ describe('DhtNode', () => { await localNode.joinDht([entryPointPeerDescriptor]) await localNode.waitForNetworkConnectivity() - await waitForCondition(() => localNode.getNeighborCount() === otherPeerDescriptors.length + 1) + await until(() => localNode.getNeighborCount() === otherPeerDescriptors.length + 1) const expectedNodeIds = without(getAllPeerDescriptors(), localPeerDescriptor).map((n) => toNodeId(n)) const actualNodeIds = localNode.getClosestContacts().map((n) => toNodeId(n)) expect(actualNodeIds).toIncludeSameMembers(expectedNodeIds) diff --git a/packages/dht/test/integration/Layer1-scale.test.ts b/packages/dht/test/integration/Layer1-scale.test.ts index 5000fcb7fc..09f608ce84 100644 --- a/packages/dht/test/integration/Layer1-scale.test.ts +++ b/packages/dht/test/integration/Layer1-scale.test.ts @@ -178,7 +178,7 @@ describe('Layer1', () => { // }) // }) // - // await waitForCondition(() => { + // await until(() => { // return [...receivedMessages.values()].every((set) => { // return set.size === receivedMessages.size - 1 // }) diff --git a/packages/dht/test/integration/RouteMessage.test.ts b/packages/dht/test/integration/RouteMessage.test.ts index 815eb2c2a2..235085d726 100644 --- a/packages/dht/test/integration/RouteMessage.test.ts +++ b/packages/dht/test/integration/RouteMessage.test.ts @@ -2,7 +2,7 @@ import { DhtNode, Events as DhtNodeEvents } from '../../src/dht/DhtNode' import { Message, RouteMessageWrapper } from '../../generated/packages/dht/protos/DhtRpc' import { PeerDescriptor, NodeType } from '../../generated/packages/dht/protos/PeerDescriptor' import { RpcMessage } from '../../generated/packages/proto-rpc/protos/ProtoRpc' -import { Logger, runAndWaitForEvents3, waitForCondition } from '@streamr/utils' +import { Logger, runAndWaitForEvents3, until } from '@streamr/utils' import { createMockConnectionDhtNode, createWrappedClosestPeersRequest } from '../utils/utils' import { Simulator } from '../../src/connection/simulator/Simulator' import { v4 } from 'uuid' @@ -117,7 +117,7 @@ describe('Route Message With Mock Connections', () => { parallelRootNodeIds: [] }) } - await waitForCondition(() => receivedMessages === messageCount) + await until(() => receivedMessages === messageCount) }) it('From all to all', async () => { @@ -158,10 +158,10 @@ describe('Route Message With Mock Connections', () => { })) ) ) - await waitForCondition(() => receivedMessageCounts[routerNodes[0].getNodeId()] >= routerNodes.length - 1, 30000) + await until(() => receivedMessageCounts[routerNodes[0].getNodeId()] >= routerNodes.length - 1, 30000) await Promise.all( Object.keys(receivedMessageCounts).map(async (key) => - waitForCondition(() => receivedMessageCounts[key as DhtAddress] >= routerNodes.length - 1, 30000) + until(() => receivedMessageCounts[key as DhtAddress] >= routerNodes.length - 1, 30000) ) ) diff --git a/packages/dht/test/integration/SimultaneousConnections.test.ts b/packages/dht/test/integration/SimultaneousConnections.test.ts index 1f197b3301..928f2263c0 100644 --- a/packages/dht/test/integration/SimultaneousConnections.test.ts +++ b/packages/dht/test/integration/SimultaneousConnections.test.ts @@ -1,4 +1,4 @@ -import { MetricsContext, waitForCondition } from '@streamr/utils' +import { MetricsContext, until } from '@streamr/utils' import { ConnectionManager } from '../../src/connection/ConnectionManager' import { DefaultConnectorFacade, DefaultConnectorFacadeOptions } from '../../src/connection/ConnectorFacade' import { LatencyType, Simulator } from '../../src/connection/simulator/Simulator' @@ -80,8 +80,8 @@ describe('SimultaneousConnections', () => { simTransport1.send(msg1), simTransport2.send(msg2) ]) - await waitForCondition(() => simTransport2.hasConnection(toNodeId(peerDescriptor1))) - await waitForCondition(() => simTransport1.hasConnection(toNodeId(peerDescriptor2))) + await until(() => simTransport2.hasConnection(toNodeId(peerDescriptor1))) + await until(() => simTransport1.hasConnection(toNodeId(peerDescriptor2))) }) describe('Websocket 2 servers', () => { @@ -161,8 +161,8 @@ describe('SimultaneousConnections', () => { connectionManager2.send(msg2) ]) - await waitForCondition(() => connectionManager1.hasConnection(toNodeId(wsPeerDescriptor2))) - await waitForCondition(() => connectionManager2.hasConnection(toNodeId(wsPeerDescriptor1))) + await until(() => connectionManager1.hasConnection(toNodeId(wsPeerDescriptor2))) + await until(() => connectionManager2.hasConnection(toNodeId(wsPeerDescriptor1))) }) }) @@ -241,8 +241,8 @@ describe('SimultaneousConnections', () => { connectionManager2.send(msg2) ]) - await waitForCondition(() => connectionManager1.hasConnection(toNodeId(wsPeerDescriptor2))) - await waitForCondition(() => connectionManager2.hasConnection(toNodeId(wsPeerDescriptor1))) + await until(() => connectionManager1.hasConnection(toNodeId(wsPeerDescriptor2))) + await until(() => connectionManager2.hasConnection(toNodeId(wsPeerDescriptor1))) }) }) @@ -309,8 +309,8 @@ describe('SimultaneousConnections', () => { connectionManager2.send(msg2) ]) - await waitForCondition(() => connectionManager1.hasConnection(toNodeId(wrtcPeerDescriptor2))) - await waitForCondition(() => connectionManager2.hasConnection(toNodeId(wrtcPeerDescriptor1))) + await until(() => connectionManager1.hasConnection(toNodeId(wrtcPeerDescriptor2))) + await until(() => connectionManager2.hasConnection(toNodeId(wrtcPeerDescriptor1))) }) }) diff --git a/packages/dht/test/integration/StoreOnDhtWithTwoNodes.test.ts b/packages/dht/test/integration/StoreOnDhtWithTwoNodes.test.ts index e1ab534f73..4ac05a17de 100644 --- a/packages/dht/test/integration/StoreOnDhtWithTwoNodes.test.ts +++ b/packages/dht/test/integration/StoreOnDhtWithTwoNodes.test.ts @@ -1,7 +1,7 @@ import { createMockConnectionDhtNode } from '../utils/utils' import { DhtNode } from '../../src/dht/DhtNode' import { Simulator } from '../../src/connection/simulator/Simulator' -import { waitForCondition } from '@streamr/utils' +import { until } from '@streamr/utils' import { createMockDataEntry, expectEqualData } from '../utils/mock/mockDataEntry' import { toDhtAddress } from '../../src/identifiers' @@ -42,7 +42,7 @@ describe('Storing data in DHT with two peers', () => { it('Can store on one peer DHT', async () => { await otherNode.stop() - await waitForCondition(() => entryPoint.getNeighborCount() === 0) + await until(() => entryPoint.getNeighborCount() === 0) const storedData = createMockDataEntry() await entryPoint.storeDataToDht(toDhtAddress(storedData.key), storedData.data!) const foundData = await entryPoint.fetchDataFromDht(toDhtAddress(storedData.key)) diff --git a/packages/dht/test/integration/WebrtcConnectorRpc.test.ts b/packages/dht/test/integration/WebrtcConnectorRpc.test.ts index be9599a019..620eec92f8 100644 --- a/packages/dht/test/integration/WebrtcConnectorRpc.test.ts +++ b/packages/dht/test/integration/WebrtcConnectorRpc.test.ts @@ -9,7 +9,7 @@ import { import { Empty } from '../../generated/google/protobuf/empty' import { createMockPeerDescriptor } from '../utils/utils' import { IWebrtcConnectorRpc } from '../../generated/packages/dht/protos/DhtRpc.server' -import { waitForCondition } from '@streamr/utils' +import { until } from '@streamr/utils' import { RpcMessage } from '../../generated/packages/proto-rpc/protos/ProtoRpc' import { DhtCallContext } from '../../src/rpc-protocol/DhtCallContext' @@ -86,7 +86,7 @@ describe('WebRTC rpc messages', () => { { targetDescriptor, notification: true } ) - await waitForCondition(() => requestConnectionCounter === 1) + await until(() => requestConnectionCounter === 1) }) it('send rtcOffer', async () => { @@ -97,7 +97,7 @@ describe('WebRTC rpc messages', () => { { targetDescriptor, notification: true } ) - await waitForCondition(() => rtcOfferCounter === 1) + await until(() => rtcOfferCounter === 1) }) it('send rtcAnswer', async () => { @@ -108,7 +108,7 @@ describe('WebRTC rpc messages', () => { { targetDescriptor, notification: true } ) - await waitForCondition(() => rtcAnswerCounter === 1) + await until(() => rtcAnswerCounter === 1) }) it('send iceCandidate', async () => { @@ -120,6 +120,6 @@ describe('WebRTC rpc messages', () => { { targetDescriptor, notification: true } ) - await waitForCondition(() => iceCandidateCounter === 1) + await until(() => iceCandidateCounter === 1) }) }) diff --git a/packages/dht/test/integration/WebsocketConnectionManagement.test.ts b/packages/dht/test/integration/WebsocketConnectionManagement.test.ts index a050ffc6be..7d20f0174c 100644 --- a/packages/dht/test/integration/WebsocketConnectionManagement.test.ts +++ b/packages/dht/test/integration/WebsocketConnectionManagement.test.ts @@ -1,4 +1,4 @@ -import { MetricsContext, waitForCondition, waitForEvent3 } from '@streamr/utils' +import { MetricsContext, until, waitForEvent3 } from '@streamr/utils' import { ConnectionManager } from '../../src/connection/ConnectionManager' import { DefaultConnectorFacade, DefaultConnectorFacadeOptions } from '../../src/connection/ConnectorFacade' import { Simulator } from '../../src/connection/simulator/Simulator' @@ -159,13 +159,13 @@ describe('Websocket Connection Management', () => { targetDescriptor: wsServerConnectorPeerDescriptor } await noWsServerManager.send(dummyMessage) - await waitForCondition( + await until( () => { const nodeId = toNodeId(noWsServerConnectorPeerDescriptor) return wsServerManager.hasConnection(nodeId) } ) - await waitForCondition( + await until( () => noWsServerManager.hasConnection(toNodeId(wsServerConnectorPeerDescriptor)) ) }) diff --git a/packages/dht/test/unit/ListeningRpcCommunicator.test.ts b/packages/dht/test/unit/ListeningRpcCommunicator.test.ts index 7b172b111f..b812f3d990 100644 --- a/packages/dht/test/unit/ListeningRpcCommunicator.test.ts +++ b/packages/dht/test/unit/ListeningRpcCommunicator.test.ts @@ -1,4 +1,4 @@ -import { waitForCondition } from '@streamr/utils' +import { until } from '@streamr/utils' import { ListeningRpcCommunicator } from '../../src/transport/ListeningRpcCommunicator' import { MockTransport } from '../utils/mock/MockTransport' import { createMockPeerDescriptor } from '../utils/utils' @@ -44,9 +44,9 @@ describe('ListeningRpcCommunicator', () => { RpcMessage.create(), { targetDescriptor: peerDescriptor }, createDeferredPromises() ) - await waitForCondition(() => rpcCommunicator.getRequestIds(() => true).length > 0) + await until(() => rpcCommunicator.getRequestIds(() => true).length > 0) transport.emit('disconnected', peerDescriptor, false) - await waitForCondition(() => rpcCommunicator.getRequestIds(() => true).length === 0) + await until(() => rpcCommunicator.getRequestIds(() => true).length === 0) }, 10000) }) diff --git a/packages/dht/test/unit/PeerManager.test.ts b/packages/dht/test/unit/PeerManager.test.ts index 41693f9b4b..2ada176807 100644 --- a/packages/dht/test/unit/PeerManager.test.ts +++ b/packages/dht/test/unit/PeerManager.test.ts @@ -1,4 +1,4 @@ -import { waitForCondition } from '@streamr/utils' +import { until } from '@streamr/utils' import { range, sample, sampleSize } from 'lodash' import { DhtNodeRpcRemote } from '../../src/dht/DhtNodeRpcRemote' import { PeerManager } from '../../src/dht/PeerManager' @@ -64,7 +64,7 @@ describe('PeerManager', () => { expect(manager.getNeighborCount()).toBe(0) manager.addContact(failureContact) const closesSuccessContact = getClosestNodes(toNodeId(localPeerDescriptor), successContacts)[0] - await waitForCondition(() => { + await until(() => { const neighborNodeIds = manager.getNeighbors().map((n) => n.getNodeId()) return neighborNodeIds.includes(toNodeId(closesSuccessContact)) }) diff --git a/packages/dht/test/unit/RecursiveOperationSession.test.ts b/packages/dht/test/unit/RecursiveOperationSession.test.ts index 368dd36ed3..358bb62f04 100644 --- a/packages/dht/test/unit/RecursiveOperationSession.test.ts +++ b/packages/dht/test/unit/RecursiveOperationSession.test.ts @@ -1,4 +1,4 @@ -import { waitForCondition } from '@streamr/utils' +import { until } from '@streamr/utils' import { range } from 'lodash' import { RecursiveOperationSession } from '../../src/dht/recursive-operation/RecursiveOperationSession' import { RecursiveOperationSessionRpcRemote } from '../../src/dht/recursive-operation/RecursiveOperationSessionRpcRemote' @@ -60,7 +60,7 @@ describe('RecursiveOperationSession', () => { // TODO now waits for the 4s timeout, could setup test so that it completes by receiving // all data it wants - await waitForCondition(() => onCompleted.mock.calls.length > 0) + await until(() => onCompleted.mock.calls.length > 0) const result = session.getResults() // TODO assert peer descriptors expect(result.closestNodes).toHaveLength(6) diff --git a/packages/dht/test/unit/StoreManager.test.ts b/packages/dht/test/unit/StoreManager.test.ts index a7fbc3d424..da758fc9ba 100644 --- a/packages/dht/test/unit/StoreManager.test.ts +++ b/packages/dht/test/unit/StoreManager.test.ts @@ -1,4 +1,4 @@ -import { wait, waitForCondition } from '@streamr/utils' +import { wait, until } from '@streamr/utils' import { range, without } from 'lodash' import { getClosestNodes } from '../../src/dht/contact/getClosestNodes' import { StoreManager } from '../../src/dht/store/StoreManager' @@ -68,7 +68,7 @@ describe('StoreManager', () => { setAllEntriesAsStale ) manager.onContactAdded(getNodeCloseToData(2)) - await waitForCondition(() => replicateData.mock.calls.length === 1) + await until(() => replicateData.mock.calls.length === 1) expect(replicateData).toHaveBeenCalledWith({ entry: DATA_ENTRY }, true) diff --git a/packages/dht/test/unit/connectivityRequestHandler.test.ts b/packages/dht/test/unit/connectivityRequestHandler.test.ts index 2258370b68..7c4a6d4fac 100644 --- a/packages/dht/test/unit/connectivityRequestHandler.test.ts +++ b/packages/dht/test/unit/connectivityRequestHandler.test.ts @@ -1,4 +1,4 @@ -import { ipv4ToNumber, waitForCondition } from '@streamr/utils' +import { ipv4ToNumber, until } from '@streamr/utils' import { EventEmitter } from 'eventemitter3' import { once } from 'events' import { Server as HttpServer, createServer as createHttpServer } from 'http' @@ -48,7 +48,7 @@ describe('connectivityRequestHandler', () => { } connection.emit('data', Message.toBinary(request)) - await waitForCondition(() => connection.send.mock.calls.length > 0) + await until(() => connection.send.mock.calls.length > 0) const receivedMessage = Message.fromBinary(connection.send.mock.calls[0][0]) expect(receivedMessage).toEqual({ @@ -83,7 +83,7 @@ describe('connectivityRequestHandler', () => { } connection.emit('data', Message.toBinary(request)) - await waitForCondition(() => connection.send.mock.calls.length > 0) + await until(() => connection.send.mock.calls.length > 0) const receivedMessage = Message.fromBinary(connection.send.mock.calls[0][0]) expect(receivedMessage).toEqual({ diff --git a/packages/dht/test/utils/utils.ts b/packages/dht/test/utils/utils.ts index 6d0cfaf0c5..1005ed7974 100644 --- a/packages/dht/test/utils/utils.ts +++ b/packages/dht/test/utils/utils.ts @@ -24,7 +24,7 @@ import { v4 } from 'uuid' import { getRandomRegion } from '../../src/connection/simulator/pings' import { Empty } from '../../generated/google/protobuf/empty' import { Any } from '../../generated/google/protobuf/any' -import { wait, waitForCondition } from '@streamr/utils' +import { wait, until } from '@streamr/utils' import { SimulatorTransport } from '../../src/connection/simulator/SimulatorTransport' import { DhtAddress, randomDhtAddress, toDhtAddressRaw } from '../../src/identifiers' @@ -257,7 +257,7 @@ export const waitForStableTopology = async (nodes: DhtNode[], maxConnectionCount await Promise.all(connectionManagers.map(async (connectionManager) => { connectionManager.garbageCollectConnections(maxConnectionCount, MAX_IDLE_TIME) try { - await waitForCondition(() => connectionManager.getConnections().length <= maxConnectionCount, waitTime) + await until(() => connectionManager.getConnections().length <= maxConnectionCount, waitTime) } catch { // the topology is very likely stable, but we can't be sure (maybe the node has more than maxConnectionCount // locked connections and therefore it is ok to that garbage collector was not able to remove any of those diff --git a/packages/geoip-location/test/unit/GeoIpLocator-intervals.test.ts b/packages/geoip-location/test/unit/GeoIpLocator-intervals.test.ts index 19af7e6740..b97cf8e54c 100644 --- a/packages/geoip-location/test/unit/GeoIpLocator-intervals.test.ts +++ b/packages/geoip-location/test/unit/GeoIpLocator-intervals.test.ts @@ -1,5 +1,5 @@ import { GeoIpLocator } from '../../src/GeoIpLocator' -import { wait, waitForCondition } from '@streamr/utils' +import { wait, until } from '@streamr/utils' import fs from 'fs' import { TestServer } from '../helpers/TestServer' @@ -94,7 +94,7 @@ describe('GeoIpLocator', () => { expect(fetchMock2).toHaveBeenCalledTimes(2) // expect the db to be there - await waitForCondition(() => fs.existsSync(dbDir + '/' + DB_FILENAME), 10000) + await until(() => fs.existsSync(dbDir + '/' + DB_FILENAME), 10000) // suomi.fi const location = locator.lookup('62.241.198.245') diff --git a/packages/node/test/integration/broker-subscriptions.test.ts b/packages/node/test/integration/broker-subscriptions.test.ts index 8bb677ae4f..002fab1881 100644 --- a/packages/node/test/integration/broker-subscriptions.test.ts +++ b/packages/node/test/integration/broker-subscriptions.test.ts @@ -2,7 +2,7 @@ import { Wallet } from 'ethers' import mqtt, { AsyncMqttClient } from 'async-mqtt' import { StreamrClient, Stream, StreamPartID, StreamPermission } from '@streamr/sdk' import { fastWallet, fetchPrivateKeyWithGas } from '@streamr/test-utils' -import { wait, waitForCondition } from '@streamr/utils' +import { wait, until } from '@streamr/utils' import { Broker } from '../../src/broker' import { startBroker, createClient, createTestStream } from '../utils' @@ -85,14 +85,14 @@ describe('broker subscriptions', () => { }) it('manage list of subscribed stream partitions when plugins subscribe/unsubscribe', async () => { - await waitForCondition(() => mqttClient1.connected) - await waitForCondition(() => mqttClient2.connected) + await until(() => mqttClient1.connected) + await until(() => mqttClient2.connected) await mqttClient1.subscribe(freshStream1.id) await mqttClient2.subscribe(freshStream2.id) - await waitForCondition(async () => (await getStreamParts(broker1)).length === 1) - await waitForCondition(async () => (await getStreamParts(broker2)).length === 1) + await until(async () => (await getStreamParts(broker1)).length === 1) + await until(async () => (await getStreamParts(broker2)).length === 1) expect((await getStreamParts(broker1))).toIncludeSameMembers([freshStream1.id + '#0']) expect((await getStreamParts(broker2))).toIncludeSameMembers([freshStream2.id + '#0']) @@ -100,8 +100,8 @@ describe('broker subscriptions', () => { await mqttClient1.subscribe(freshStream2.id) await mqttClient2.subscribe(freshStream1.id) - await waitForCondition(async () => (await getStreamParts(broker1)).length === 2) - await waitForCondition(async () => (await getStreamParts(broker2)).length === 2) + await until(async () => (await getStreamParts(broker1)).length === 2) + await until(async () => (await getStreamParts(broker2)).length === 2) expect((await getStreamParts(broker1))).toIncludeSameMembers([freshStream1.id + '#0', freshStream2.id + '#0']) expect((await getStreamParts(broker2))).toIncludeSameMembers([freshStream1.id + '#0', freshStream2.id + '#0']) @@ -118,14 +118,14 @@ describe('broker subscriptions', () => { await mqttClient1.unsubscribe(freshStream1.id) - await waitForCondition(async () => (await getStreamParts(broker2)).length === 2) + await until(async () => (await getStreamParts(broker2)).length === 2) expect((await getStreamParts(broker1))).toIncludeSameMembers([freshStream2.id + '#0']) expect((await getStreamParts(broker2))).toIncludeSameMembers([freshStream1.id + '#0', freshStream2.id + '#0']) await mqttClient1.unsubscribe(freshStream2.id) - await waitForCondition(async () => (await getStreamParts(broker2)).length === 2) + await until(async () => (await getStreamParts(broker2)).length === 2) expect((await getStreamParts(broker1))).toIncludeSameMembers([]) expect((await getStreamParts(broker2))).toIncludeSameMembers([freshStream1.id + '#0', freshStream2.id + '#0']) diff --git a/packages/node/test/integration/multiple-publisher-plugins.test.ts b/packages/node/test/integration/multiple-publisher-plugins.test.ts index 82eb610bb0..d1eed03854 100644 --- a/packages/node/test/integration/multiple-publisher-plugins.test.ts +++ b/packages/node/test/integration/multiple-publisher-plugins.test.ts @@ -5,7 +5,7 @@ import { StreamPermission } from '@streamr/sdk' import { fetchPrivateKeyWithGas, Queue, fastPrivateKey } from '@streamr/test-utils' import { Broker } from '../../src/broker' import { startBroker, createClient, createTestStream } from '../utils' -import { wait, waitForEvent, waitForCondition } from '@streamr/utils' +import { wait, waitForEvent, until } from '@streamr/utils' import sample from 'lodash/sample' import range from 'lodash/range' @@ -143,7 +143,7 @@ describe('multiple publisher plugins', () => { const messages = await publishMessages(streamId) - await waitForCondition(() => receivedMessages.size() >= messages.length) + await until(() => receivedMessages.size() >= messages.length) expect(receivedMessages.values()).toIncludeSameMembers(messages) await subscriber.destroy() @@ -160,7 +160,7 @@ describe('multiple publisher plugins', () => { const messages = await publishMessages(streamId) - await waitForCondition(() => receivedMessages.size() >= messages.length) + await until(() => receivedMessages.size() >= messages.length) expect(receivedMessages.values()).toIncludeSameMembers(messages) subscriber.close() @@ -179,7 +179,7 @@ describe('multiple publisher plugins', () => { const messages = await publishMessages(streamId) - await waitForCondition(() => receivedMessages.size() >= messages.length) + await until(() => receivedMessages.size() >= messages.length) expect(receivedMessages.values()).toIncludeSameMembers(messages) await subscriber.end(true) }) diff --git a/packages/node/test/integration/plugins/operator/MaintainTopologyService.test.ts b/packages/node/test/integration/plugins/operator/MaintainTopologyService.test.ts index fc1a704d62..320c84dd01 100644 --- a/packages/node/test/integration/plugins/operator/MaintainTopologyService.test.ts +++ b/packages/node/test/integration/plugins/operator/MaintainTopologyService.test.ts @@ -2,7 +2,7 @@ import { Stream, StreamrClient, _operatorContractUtils } from '@streamr/sdk' import { fastPrivateKey, fetchPrivateKeyWithGas } from '@streamr/test-utils' -import { StreamPartID, toEthereumAddress, waitForCondition } from '@streamr/utils' +import { StreamPartID, toEthereumAddress, until } from '@streamr/utils' import { MaintainTopologyHelper } from '../../../../src/plugins/operator/MaintainTopologyHelper' import { MaintainTopologyService } from '../../../../src/plugins/operator/MaintainTopologyService' import { OperatorFleetState } from '../../../../src/plugins/operator/OperatorFleetState' @@ -100,12 +100,12 @@ describe('MaintainTopologyService', () => { await operatorFleetState.start() await maintainTopologyHelper.start() - await waitForCondition(async () => { + await until(async () => { return containsAll(await getSubscribedStreamPartIds(client), stream1.getStreamParts()) }, 10000, 1000) await stake(operatorContract, await sponsorship2.getAddress(), 10000) - await waitForCondition(async () => { + await until(async () => { return containsAll(await getSubscribedStreamPartIds(client), [ ...stream1.getStreamParts(), ...stream2.getStreamParts() @@ -113,7 +113,7 @@ describe('MaintainTopologyService', () => { }, 10000, 1000) await (await operatorContract.unstake(await sponsorship1.getAddress())).wait() - await waitForCondition(async () => { + await until(async () => { const state = await getSubscribedStreamPartIds(client) return containsAll(state, stream2.getStreamParts()) && doesNotContainAny(state, stream1.getStreamParts()) }, 10000, 1000) diff --git a/packages/node/test/integration/plugins/operator/OperatorPlugin.test.ts b/packages/node/test/integration/plugins/operator/OperatorPlugin.test.ts index d54f44f4be..1da3b9cc74 100644 --- a/packages/node/test/integration/plugins/operator/OperatorPlugin.test.ts +++ b/packages/node/test/integration/plugins/operator/OperatorPlugin.test.ts @@ -5,7 +5,7 @@ import { _operatorContractUtils } from '@streamr/sdk' import { fastPrivateKey, fetchPrivateKeyWithGas } from '@streamr/test-utils' -import { EthereumAddress, StreamPartIDUtils, collect, toEthereumAddress, waitForCondition } from '@streamr/utils' +import { EthereumAddress, StreamPartIDUtils, collect, toEthereumAddress, until } from '@streamr/utils' import { Wallet } from 'ethers' import { cloneDeep, set } from 'lodash' import { Broker, createBroker } from '../../../../src/broker' @@ -76,7 +76,7 @@ describe('OperatorPlugin', () => { }) // wait for MaintainTopologyService to handle addStakedStreams // events emitted during Broker start - await waitForCondition(async () => (await broker.getStreamrClient().getSubscriptions(stream.id)).length > 0) + await until(async () => (await broker.getStreamrClient().getSubscriptions(stream.id)).length > 0) const brokerDescriptor = await broker.getStreamrClient().getPeerDescriptor() await subscriber.setProxies({ id: stream.id }, [brokerDescriptor], ProxyDirection.SUBSCRIBE) const subscription = await subscriber.subscribe(stream.id) @@ -125,7 +125,7 @@ describe('OperatorPlugin', () => { } } }) - await waitForCondition(async () => (await broker.getStreamrClient().getSubscriptions(stream.id)).length > 0) + await until(async () => (await broker.getStreamrClient().getSubscriptions(stream.id)).length > 0) // Ensure that heartbeat has been sent (setting heartbeatUpdateIntervalInMs lower did not help) await waitForHeartbeatMessage(toEthereumAddress(operatorContractAddress)) const brokerDescriptor = await broker.getStreamrClient().getPeerDescriptor() diff --git a/packages/node/test/integration/plugins/operator/announceNodeToContract.test.ts b/packages/node/test/integration/plugins/operator/announceNodeToContract.test.ts index b675325b73..977a7124b6 100644 --- a/packages/node/test/integration/plugins/operator/announceNodeToContract.test.ts +++ b/packages/node/test/integration/plugins/operator/announceNodeToContract.test.ts @@ -1,5 +1,5 @@ import { Operator, _operatorContractUtils } from '@streamr/sdk' -import { toEthereumAddress, waitForCondition } from '@streamr/utils' +import { toEthereumAddress, until } from '@streamr/utils' import { announceNodeToContract } from '../../../../src/plugins/operator/announceNodeToContract' import { createClient } from '../../../utils' @@ -24,7 +24,7 @@ describe('announceNodeToContract', () => { } await announceNodeToContract(0, operator, streamrClient as any) const approximateWriteTimestamp = Date.now() - await waitForCondition(async () => await operator.getTimestampOfLastHeartbeat() !== undefined, 10 * 1000, 1000) + await until(async () => await operator.getTimestampOfLastHeartbeat() !== undefined, 10 * 1000, 1000) // account for (1) the graph to pick up and (2) un-synced time between Docker box and this machine, // TODO: why is drift so large (ETH-577)? diff --git a/packages/node/test/integration/plugins/operator/checkOperatorValueBreach.test.ts b/packages/node/test/integration/plugins/operator/checkOperatorValueBreach.test.ts index 94e513c79b..c5e6289308 100644 --- a/packages/node/test/integration/plugins/operator/checkOperatorValueBreach.test.ts +++ b/packages/node/test/integration/plugins/operator/checkOperatorValueBreach.test.ts @@ -3,7 +3,7 @@ import { SetupOperatorContractOpts, _operatorContractUtils, } from '@streamr/sdk' -import { Logger, toEthereumAddress, waitForCondition } from '@streamr/utils' +import { Logger, toEthereumAddress, until } from '@streamr/utils' import { Contract } from 'ethers' import { checkOperatorValueBreach } from '../../../../src/plugins/operator/checkOperatorValueBreach' import { createClient, createTestStream } from '../../../utils' @@ -64,7 +64,7 @@ describe('checkOperatorValueBreach', () => { const operator = client.getOperator(toEthereumAddress(await watcherOperatorContract.getAddress())) logger.debug('Waiting until above', { allowedDifference }) - await waitForCondition(async () => await getEarnings(operatorContract) > allowedDifference, 10000, 1000) + await until(async () => await getEarnings(operatorContract) > allowedDifference, 10000, 1000) await checkOperatorValueBreach(operator, client, async () => { return [toEthereumAddress(await operatorContract.getAddress())] }, 1, 20) diff --git a/packages/node/test/integration/plugins/operator/maintainOperatorValue.test.ts b/packages/node/test/integration/plugins/operator/maintainOperatorValue.test.ts index fdb1b43ab7..0db255bf55 100644 --- a/packages/node/test/integration/plugins/operator/maintainOperatorValue.test.ts +++ b/packages/node/test/integration/plugins/operator/maintainOperatorValue.test.ts @@ -1,6 +1,6 @@ import { _operatorContractUtils } from '@streamr/sdk' import { fetchPrivateKeyWithGas } from '@streamr/test-utils' -import { Logger, toEthereumAddress, waitForCondition } from '@streamr/utils' +import { Logger, toEthereumAddress, until } from '@streamr/utils' import { multiply } from '../../../../src/helpers/multiply' import { maintainOperatorValue } from '../../../../src/plugins/operator/maintainOperatorValue' import { createClient, createTestStream } from '../../../utils' @@ -51,7 +51,7 @@ describe('maintainOperatorValue', () => { const operator = createClient(nodeWallets[0].privateKey).getOperator(toEthereumAddress(await operatorContract.getAddress())) const { maxAllowedEarningsDataWei } = await operator.getEarnings(1, 20) const triggerWithdrawLimitDataWei = multiply(maxAllowedEarningsDataWei, 1 - SAFETY_FRACTION) - await waitForCondition(async () => { + await until(async () => { const { sumDataWei } = await operator.getEarnings(1, 20) const earnings = sumDataWei return earnings > triggerWithdrawLimitDataWei diff --git a/packages/node/test/integration/plugins/storage/BatchManager.test.ts b/packages/node/test/integration/plugins/storage/BatchManager.test.ts index f24c6e38c6..26e485dc1b 100644 --- a/packages/node/test/integration/plugins/storage/BatchManager.test.ts +++ b/packages/node/test/integration/plugins/storage/BatchManager.test.ts @@ -1,4 +1,4 @@ -import { waitForCondition } from '@streamr/utils' +import { until } from '@streamr/utils' import { Client, types as cassandraTypes } from 'cassandra-driver' import { InsertRecord } from '../../../../src/plugins/storage/Batch' import { BatchManager } from '../../../../src/plugins/storage/BatchManager' @@ -134,7 +134,7 @@ describe('BatchManager', () => { }) batchManager.cassandraClient.batch = mockBatch - await waitForCondition(() => batch.retries === 1) + await until(() => batch.retries === 1) expect(mockBatch).toBeCalledTimes(1) expect(batch.retries).toEqual(1) @@ -158,12 +158,12 @@ describe('BatchManager', () => { expect(Object.values(batchManager.pendingBatches)).toHaveLength(0) expect(batch.reachedMaxRetries()).toBeFalsy() - await waitForCondition(() => batch.retries === 1) + await until(() => batch.retries === 1) expect(Object.values(batchManager.pendingBatches)).toHaveLength(1) expect(batch.reachedMaxRetries()).toBeFalsy() - await waitForCondition(() => batch.retries === 2) + await until(() => batch.retries === 2) expect(Object.values(batchManager.pendingBatches)).toHaveLength(0) expect(batch.reachedMaxRetries()).toBeTruthy() diff --git a/packages/node/test/integration/plugins/storage/BucketManager.test.ts b/packages/node/test/integration/plugins/storage/BucketManager.test.ts index 230712486d..e7422161ed 100644 --- a/packages/node/test/integration/plugins/storage/BucketManager.test.ts +++ b/packages/node/test/integration/plugins/storage/BucketManager.test.ts @@ -2,7 +2,7 @@ import { Client, types as cassandraTypes } from 'cassandra-driver' const { TimeUuid } = cassandraTypes import { BucketManager } from '../../../../src/plugins/storage/BucketManager' import { STREAMR_DOCKER_DEV_HOST } from '../../../utils' -import { waitForCondition } from '@streamr/utils' +import { until } from '@streamr/utils' const contactPoints = [STREAMR_DOCKER_DEV_HOST] const localDataCenter = 'datacenter1' @@ -68,7 +68,7 @@ describe('BucketManager', () => { expect(result.rows.length).toEqual(0) // first time we call in constructor, second after timeout - await waitForCondition(() => storeBucketsSpy.mock.calls.length === 2) + await until(() => storeBucketsSpy.mock.calls.length === 2) expect(storeBucketsSpy).toHaveBeenCalled() const foundBucketId = bucketManager.getBucketId(streamId, 0, timestamp)! @@ -76,7 +76,7 @@ describe('BucketManager', () => { expect(bucketManager.buckets[foundBucketId].size).toEqual(0) expect(bucketManager.buckets[foundBucketId].records).toEqual(0) - await waitForCondition(() => bucketManager.buckets[foundBucketId].isStored() === true) + await until(() => bucketManager.buckets[foundBucketId].isStored() === true) expect(bucketManager.buckets[foundBucketId].isStored()).toBeTruthy() bucketManager.incrementBucket(foundBucketId, 3) @@ -85,7 +85,7 @@ describe('BucketManager', () => { expect(bucketManager.buckets[foundBucketId].records).toEqual(2) expect(bucketManager.buckets[foundBucketId].isStored()).toBeFalsy() - await waitForCondition(() => bucketManager.buckets[foundBucketId].isStored()) + await until(() => bucketManager.buckets[foundBucketId].isStored()) result = await cassandraClient.execute('SELECT * FROM bucket WHERE stream_id = ? ALLOW FILTERING', [ streamId ]) @@ -104,7 +104,7 @@ describe('BucketManager', () => { expect(bucketManager.getBucketId(streamId, 0, timestamp)).toBeUndefined() expect(bucketManager.streamParts[`${streamId}-0`].minTimestamp).toEqual(timestamp) - await waitForCondition(() => bucketManager.getBucketId(streamId, 0, timestamp) !== undefined) + await until(() => bucketManager.getBucketId(streamId, 0, timestamp) !== undefined) expect(bucketManager.streamParts[`${streamId}-0`].minTimestamp).toBeUndefined() // future timestamp will give latest not full bucket @@ -118,12 +118,12 @@ describe('BucketManager', () => { // find or create bucketId for NOW timestamp expect(bucketManager.getBucketId(streamId, 0, timestamp)).toBeUndefined() - await waitForCondition(() => bucketManager.getBucketId(streamId, 0, timestamp) !== undefined) + await until(() => bucketManager.getBucketId(streamId, 0, timestamp) !== undefined) const lastBucketId = bucketManager.getBucketId(streamId, 0, timestamp)! // find or create bucketId for NOW - 5 minutes timestamp expect(bucketManager.getBucketId(streamId, 0, timestamp5ago)).toBeUndefined() - await waitForCondition(() => bucketManager.getBucketId(streamId, 0, timestamp5ago) !== undefined) + await until(() => bucketManager.getBucketId(streamId, 0, timestamp5ago) !== undefined) const bucketId5minAgo = bucketManager.getBucketId(streamId, 0, timestamp5ago)! // bucketId is not latest @@ -133,8 +133,8 @@ describe('BucketManager', () => { bucketManager.incrementBucket(lastBucketId, 1) bucketManager.incrementBucket(bucketId5minAgo, 1) - await waitForCondition(() => bucketManager.buckets[lastBucketId].isStored()) - await waitForCondition(() => bucketManager.buckets[bucketId5minAgo].isStored()) + await until(() => bucketManager.buckets[lastBucketId].isStored()) + await until(() => bucketManager.buckets[bucketId5minAgo].isStored()) // get latest sorted const lastBuckets = await bucketManager.getLastBuckets(streamId, 0, 5) @@ -205,12 +205,12 @@ describe('BucketManager', () => { // load latest bucket into memory const latestTimestamp = timestamp.getTime() + 100 * 60 * 1000 - await waitForCondition(() => bucketManager.getBucketId(streamId, 0, latestTimestamp) !== undefined) + await until(() => bucketManager.getBucketId(streamId, 0, latestTimestamp) !== undefined) const bucketId = bucketManager.getBucketId(streamId, 0, latestTimestamp)! const bucket = bucketManager.buckets[bucketId] // bucket got removed after 3 seconds - await waitForCondition(() => bucket.isAlive() === false) - await waitForCondition(() => Object.values(bucketManager.buckets).length === 0) + await until(() => bucket.isAlive() === false) + await until(() => Object.values(bucketManager.buckets).length === 0) }, 10000) }) diff --git a/packages/node/test/integration/plugins/storage/StorageConfig.test.ts b/packages/node/test/integration/plugins/storage/StorageConfig.test.ts index 35e9dcf8dd..58123e3f5c 100644 --- a/packages/node/test/integration/plugins/storage/StorageConfig.test.ts +++ b/packages/node/test/integration/plugins/storage/StorageConfig.test.ts @@ -9,7 +9,7 @@ import { startStorageNode } from '../../../utils' import { Broker } from '../../../../src/broker' -import { waitForCondition } from '@streamr/utils' +import { until } from '@streamr/utils' jest.setTimeout(30000) @@ -59,7 +59,7 @@ describe('StorageConfig', () => { const publishMessage = await client.publish(stream.id, { foo: 'bar' }) - await waitForCondition(async () => { + await until(async () => { const result = await cassandraClient.execute('SELECT COUNT(*) FROM stream_data WHERE stream_id = ? ALLOW FILTERING', [stream.id]) return (result.first().count > 0) }) diff --git a/packages/node/test/integration/plugins/storage/cassanda-queries.test.ts b/packages/node/test/integration/plugins/storage/cassanda-queries.test.ts index 22ebf03dd4..e0f013df58 100644 --- a/packages/node/test/integration/plugins/storage/cassanda-queries.test.ts +++ b/packages/node/test/integration/plugins/storage/cassanda-queries.test.ts @@ -1,6 +1,6 @@ import { ContentType, EncryptionType, MessageID, SignatureType, StreamMessage, convertBytesToStreamMessage } from '@streamr/sdk' import { randomUserId, waitForStreamToEnd } from '@streamr/test-utils' -import { UserID, hexToBinary, toStreamID, utf8ToBinary, waitForCondition, waitForEvent } from '@streamr/utils' +import { UserID, hexToBinary, toStreamID, utf8ToBinary, until, waitForEvent } from '@streamr/utils' import { Client } from 'cassandra-driver' import { PassThrough, Readable } from 'stream' import { Storage, startCassandraStorage } from '../../../../src/plugins/storage/Storage' @@ -95,7 +95,7 @@ describe('cassanda-queries', () => { let realClient: Client const waitForStoredMessageCount = async (expectedCount: number) => { - return waitForCondition(async () => { + return until(async () => { const result = await realClient.execute('SELECT COUNT(*) AS total FROM stream_data WHERE stream_id = ? ALLOW FILTERING', [ MOCK_STREAM_ID ]) diff --git a/packages/node/test/integration/plugins/subscriber/SubscriberPlugin.test.ts b/packages/node/test/integration/plugins/subscriber/SubscriberPlugin.test.ts index 9495323add..129cf83a06 100644 --- a/packages/node/test/integration/plugins/subscriber/SubscriberPlugin.test.ts +++ b/packages/node/test/integration/plugins/subscriber/SubscriberPlugin.test.ts @@ -2,7 +2,7 @@ import { createClient } from '../../../utils' import { SubscriberPlugin } from '../../../../src/plugins/subscriber/SubscriberPlugin' import { StreamrClient } from '@streamr/sdk' import { fastWallet } from '@streamr/test-utils' -import { waitForCondition } from '@streamr/utils' +import { until } from '@streamr/utils' const wallet = fastWallet() @@ -54,13 +54,13 @@ describe('Subscriber Plugin', () => { it('subscribes to the configured list of streams', async () => { const node = client.getNode() - await waitForCondition(async () => { + await until(async () => { const streams = (await node.getStreamParts()).map((stream) => stream.toString()) return streams.includes('stream-0#0') && streams.includes('stream-0#1') && streams.includes('stream-1#0') }) - // If waitForCondition succeeds we are okay + // If until succeeds we are okay expect(true).toEqual(true) }) }) diff --git a/packages/node/test/smoke/inspect.test.ts b/packages/node/test/smoke/inspect.test.ts index bea70d580a..2345fb5326 100644 --- a/packages/node/test/smoke/inspect.test.ts +++ b/packages/node/test/smoke/inspect.test.ts @@ -2,7 +2,7 @@ import { config as CHAIN_CONFIG } from '@streamr/config' import { StreamrConfig, streamrConfigABI } from '@streamr/network-contracts' import { _operatorContractUtils } from '@streamr/sdk' import { fetchPrivateKeyWithGas } from '@streamr/test-utils' -import { Logger, StreamID, TheGraphClient, wait, waitForCondition } from '@streamr/utils' +import { Logger, StreamID, TheGraphClient, wait, until } from '@streamr/utils' import { Contract, formatEther, JsonRpcProvider, parseEther, Wallet } from 'ethers' import fetch from 'node-fetch' import { Broker, createBroker } from '../../src/broker' @@ -281,7 +281,7 @@ describe('inspect', () => { it('freerider is kicked', async () => { logger.info('Wait for kick flag') - await waitForCondition(async () => { + await until(async () => { const flags = await getFlags(theGraphClient, startTimestamp) return flags.some((flag) => flag.result === 'kicked') }, MAX_TEST_RUN_TIME, 5000) diff --git a/packages/node/test/smoke/profit.test.ts b/packages/node/test/smoke/profit.test.ts index 891b2ecaaa..25022dd3a9 100644 --- a/packages/node/test/smoke/profit.test.ts +++ b/packages/node/test/smoke/profit.test.ts @@ -3,7 +3,7 @@ import type { Operator, Sponsorship } from '@streamr/network-contracts' import { StreamrConfig, streamrConfigABI } from '@streamr/network-contracts' import { _operatorContractUtils } from '@streamr/sdk' import { fetchPrivateKeyWithGas } from '@streamr/test-utils' -import { waitForCondition } from '@streamr/utils' +import { until } from '@streamr/utils' import { Contract, Wallet, formatEther, parseEther } from 'ethers' import { createClient, createTestStream, startBroker } from '../utils' @@ -145,8 +145,8 @@ describe('profit', () => { } } }) - await waitForCondition(async () => !(await sponsorshipContract.isFunded()), 60 * 1000) - await waitForCondition(async () => { + await until(async () => !(await sponsorshipContract.isFunded()), 60 * 1000) + await until(async () => { const operatorValue = (await getBalances()).operatorContract return (operatorValue === TOTAL_PROFIT) }) diff --git a/packages/node/test/unit/plugins/operator/MaintainTopologyService.test.ts b/packages/node/test/unit/plugins/operator/MaintainTopologyService.test.ts index bf15a995c2..441e4f871f 100644 --- a/packages/node/test/unit/plugins/operator/MaintainTopologyService.test.ts +++ b/packages/node/test/unit/plugins/operator/MaintainTopologyService.test.ts @@ -1,5 +1,5 @@ import { StreamrClient, Subscription } from '@streamr/sdk' -import { StreamPartID, StreamPartIDUtils, toStreamID, toStreamPartID, wait, waitForCondition } from '@streamr/utils' +import { StreamPartID, StreamPartIDUtils, toStreamID, toStreamPartID, wait, until } from '@streamr/utils' import EventEmitter3 from 'eventemitter3' import { MockProxy, mock } from 'jest-mock-extended' import { MaintainTopologyService } from '../../../../src/plugins/operator/MaintainTopologyService' @@ -60,7 +60,7 @@ describe('MaintainTopologyService', () => { assignments.emit('assigned', SP1) assignments.emit('assigned', SP2) - await waitForCondition(() => streamrClient.subscribe.mock.calls.length >= 2) + await until(() => streamrClient.subscribe.mock.calls.length >= 2) expect(streamrClient.subscribe).toHaveBeenCalledTimes(2) expect(streamrClient.subscribe.mock.calls[0][0]).toEqual(formRawSubscriptionParam(SP1)) expect(streamrClient.subscribe.mock.calls[1][0]).toEqual(formRawSubscriptionParam(SP2)) @@ -83,7 +83,7 @@ describe('MaintainTopologyService', () => { assignments.emit('unassigned', SP1) - await waitForCondition(() => totalUnsubscribes(SP1) === 1) + await until(() => totalUnsubscribes(SP1) === 1) expect(totalUnsubscribes(SP2)).toEqual(0) }) @@ -102,7 +102,7 @@ describe('MaintainTopologyService', () => { assignments.emit('assigned', SP3) } - await waitForCondition( + await until( () => totalUnsubscribes(SP3) >= 10, undefined, undefined, diff --git a/packages/node/test/unit/plugins/operator/OperatorFleetState.test.ts b/packages/node/test/unit/plugins/operator/OperatorFleetState.test.ts index fd1e06e64a..c78e335b7d 100644 --- a/packages/node/test/unit/plugins/operator/OperatorFleetState.test.ts +++ b/packages/node/test/unit/plugins/operator/OperatorFleetState.test.ts @@ -1,6 +1,6 @@ import { DhtAddress } from '@streamr/dht' import { eventsWithArgsToArray, randomEthereumAddress } from '@streamr/test-utils' -import { wait, waitForCondition, waitForEvent } from '@streamr/utils' +import { wait, until, waitForEvent } from '@streamr/utils' import { mock, MockProxy } from 'jest-mock-extended' import { MessageListener, StreamrClient, Subscription } from '@streamr/sdk' import { formCoordinationStreamId } from '../../../../src/plugins/operator/formCoordinationStreamId' @@ -112,7 +112,7 @@ describe(OperatorFleetState, () => { await setTimeAndPublishMessage(10, createHeartbeatMsg('c')) await setTimeAndPublishMessage(19, createHeartbeatMsg('e')) - await waitForCondition(() => state.getNodeIds().length <= 3) + await until(() => state.getNodeIds().length <= 3) expect(state.getNodeIds()).toEqual(['c', 'd', 'e']) expect(events).toEqual([ ['added', 'a'], diff --git a/packages/node/test/unit/plugins/websocket/WebsocketServer.test.ts b/packages/node/test/unit/plugins/websocket/WebsocketServer.test.ts index b67c6d65d3..e9dd847367 100644 --- a/packages/node/test/unit/plugins/websocket/WebsocketServer.test.ts +++ b/packages/node/test/unit/plugins/websocket/WebsocketServer.test.ts @@ -1,7 +1,7 @@ import WebSocket from 'ws' import qs from 'qs' import { StreamrClient, Subscription } from '@streamr/sdk' -import { waitForEvent, waitForCondition, merge } from '@streamr/utils' +import { waitForEvent, until, merge } from '@streamr/utils' import { WebsocketServer } from '../../../../src/plugins/websocket/WebsocketServer' import { PlainPayloadFormat } from '../../../../src/helpers/PayloadFormat' import { mock, MockProxy } from 'jest-mock-extended' @@ -69,7 +69,7 @@ describe('WebsocketServer', () => { wsClient = createTestClient(PATH_PUBLISH_MOCK_STREAM, queryParams) await waitForEvent(wsClient, 'open') wsClient.send(JSON.stringify(MOCK_MESSAGE)) - await waitForCondition(() => (streamrClient.publish.mock.calls.length === 1)) + await until(() => (streamrClient.publish.mock.calls.length === 1)) } it('without parameters', async () => { @@ -194,7 +194,7 @@ describe('WebsocketServer', () => { wsClient = createTestClient(PATH_SUBSCRIBE_MOCK_STREAM, { partitions: '0,2,5' }) await waitForEvent(wsClient, 'open') wsClient.close() - await waitForCondition(() => singletonSubscription.unsubscribe.mock.calls.length === 3) + await until(() => singletonSubscription.unsubscribe.mock.calls.length === 3) }) }) diff --git a/packages/proto-rpc/test/unit/RpcCommunicator.test.ts b/packages/proto-rpc/test/unit/RpcCommunicator.test.ts index 1876a909a5..cb56b96d86 100644 --- a/packages/proto-rpc/test/unit/RpcCommunicator.test.ts +++ b/packages/proto-rpc/test/unit/RpcCommunicator.test.ts @@ -9,7 +9,7 @@ import { Deferred, RpcMetadata, RpcStatus } from '@protobuf-ts/runtime-rpc' import * as Err from '../../src/errors' import { MockDhtRpc, clearMockTimeouts } from '../utils' import { ProtoCallContext } from '../../src/ProtoCallContext' -import { waitForCondition } from '@streamr/utils' +import { until } from '@streamr/utils' import { Any } from '../../generated/google/protobuf/any' describe('RpcCommunicator', () => { @@ -152,7 +152,7 @@ describe('RpcCommunicator', () => { }) rpcCommunicator.handleIncomingMessage(request, new ProtoCallContext()) - await waitForCondition(() => successCounter === 1) + await until(() => successCounter === 1) }) it('Success responses to new registration method', async () => { @@ -165,7 +165,7 @@ describe('RpcCommunicator', () => { }) rpcCommunicator.handleIncomingMessage(request, new ProtoCallContext()) - await waitForCondition(() => successCounter === 1) + await until(() => successCounter === 1) }) it('Error response on unknown method', async () => { @@ -178,7 +178,7 @@ describe('RpcCommunicator', () => { }) rpcCommunicator.handleIncomingMessage(request, new ProtoCallContext()) - await waitForCondition(() => errorCounter === 1) + await until(() => errorCounter === 1) }) it('Error response on server timeout', async () => { @@ -192,7 +192,7 @@ describe('RpcCommunicator', () => { }) rpcCommunicator.handleIncomingMessage(request, new ProtoCallContext()) - await waitForCondition(() => errorCounter === 1) + await until(() => errorCounter === 1) }) it('Error response on server timeout', async () => { @@ -205,7 +205,7 @@ describe('RpcCommunicator', () => { }) rpcCommunicator.handleIncomingMessage(request, new ProtoCallContext()) - await waitForCondition(() => errorCounter === 1) + await until(() => errorCounter === 1) }) it('getRequestIds', () => { diff --git a/packages/sdk/src/utils/promises.ts b/packages/sdk/src/utils/promises.ts index 1c44407823..b1a41a7eea 100644 --- a/packages/sdk/src/utils/promises.ts +++ b/packages/sdk/src/utils/promises.ts @@ -177,7 +177,7 @@ export async function pTimeout(promise: Promise, ...args: pTimeoutArgs): P }) } -// TODO use streamr-test-utils#waitForCondition instead (when streamr-test-utils is no longer a test-only dependency) +// TODO use streamr-test-utils#until instead (when streamr-test-utils is no longer a test-only dependency) /** * Wait until a condition is true * @param condition - wait until this callback function returns true diff --git a/packages/sdk/test/browser-smoke-test/nightwatch.conf.js b/packages/sdk/test/browser-smoke-test/nightwatch.conf.js index 977734ba9a..0fba357140 100644 --- a/packages/sdk/test/browser-smoke-test/nightwatch.conf.js +++ b/packages/sdk/test/browser-smoke-test/nightwatch.conf.js @@ -11,7 +11,7 @@ module.exports = { port: 9515 }, globals: { - waitForConditionTimeout: 15000 + untilTimeout: 15000 }, test_settings: { default: { diff --git a/packages/sdk/test/end-to-end/Metrics.test.ts b/packages/sdk/test/end-to-end/Metrics.test.ts index a3779d6b2b..995e15b37d 100644 --- a/packages/sdk/test/end-to-end/Metrics.test.ts +++ b/packages/sdk/test/end-to-end/Metrics.test.ts @@ -1,4 +1,4 @@ -import { waitForCondition, keyToArrayIndex, MetricsReport } from '@streamr/utils' +import { until, keyToArrayIndex, MetricsReport } from '@streamr/utils' import { fetchPrivateKeyWithGas } from '@streamr/test-utils' import { StreamPermission } from '../../src/permission' import { Stream } from '../../src/Stream' @@ -60,7 +60,7 @@ describe('NodeMetrics', () => { const dummyStream = await generatorClient.createStream(`/${Date.now()}`) await generatorClient.subscribe(dummyStream, () => {}) - await waitForCondition(() => report !== undefined, 10000) + await until(() => report !== undefined, 10000) expect(report!).toMatchObject({ node: { id: await generatorClient.getNodeId(), diff --git a/packages/sdk/test/end-to-end/Operator.test.ts b/packages/sdk/test/end-to-end/Operator.test.ts index ae19a2c25f..3a85a43bf4 100644 --- a/packages/sdk/test/end-to-end/Operator.test.ts +++ b/packages/sdk/test/end-to-end/Operator.test.ts @@ -1,6 +1,6 @@ import { config as CHAIN_CONFIG } from '@streamr/config' import { fetchPrivateKeyWithGas } from '@streamr/test-utils' -import { Logger, TheGraphClient, toEthereumAddress, waitForCondition } from '@streamr/utils' +import { Logger, TheGraphClient, toEthereumAddress, until } from '@streamr/utils' import { Contract, Wallet } from 'ethers' import fetch from 'node-fetch' import { StreamrClient } from '../../src/StreamrClient' @@ -111,7 +111,7 @@ describe('Operator', () => { const operator = await getOperator(undefined, deployedOperator) - await waitForCondition(async (): Promise => { + await until(async (): Promise => { const res = await operator.getSponsorships() return res.length === 2 }, 10000, 500) @@ -153,7 +153,7 @@ describe('Operator', () => { ) const graphClient = createTheGraphClient() - await waitForCondition(async (): Promise => { + await until(async (): Promise => { const result = await graphClient.queryEntity<{ operator: { flagsOpened: any[] } }>({ query: ` { operator(id: "${(await flagger.operatorContract.getAddress()).toLowerCase()}") { @@ -168,7 +168,7 @@ describe('Operator', () => { return result.operator.flagsOpened.length === 1 }, 10000, 1000) - await waitForCondition(async (): Promise => { + await until(async (): Promise => { const result = await graphClient.queryEntity<{ operator: { flagsTargeted: any[] } }>({ query: ` { operator(id: "${(await target.operatorContract.getAddress()).toLowerCase()}") { diff --git a/packages/sdk/test/end-to-end/StreamRegistry.test.ts b/packages/sdk/test/end-to-end/StreamRegistry.test.ts index 223407306c..2e9a6133f0 100644 --- a/packages/sdk/test/end-to-end/StreamRegistry.test.ts +++ b/packages/sdk/test/end-to-end/StreamRegistry.test.ts @@ -1,12 +1,12 @@ import 'reflect-metadata' import { fetchPrivateKeyWithGas, randomEthereumAddress, randomUserId } from '@streamr/test-utils' -import { EthereumAddress, collect, toEthereumAddress, toStreamID, waitForCondition } from '@streamr/utils' +import { EthereumAddress, collect, toEthereumAddress, toStreamID, until } from '@streamr/utils' import { Wallet } from 'ethers' import { CONFIG_TEST } from '../../src/ConfigTest' import { Stream } from '../../src/Stream' import { StreamrClient } from '../../src/StreamrClient' -import { until } from '../../src/utils/promises' +import { until as until_ } from '../../src/utils/promises' import { createRelativeTestStreamId, createTestStream } from '../test-utils/utils' const TIMEOUT = 20000 @@ -94,7 +94,7 @@ describe('StreamRegistry', () => { const streamIds = onStreamCreated.mock.calls.map((c) => c[0].streamId) return streamIds.includes(stream.id) } - await waitForCondition(() => hasBeenCalledFor(validStream)) + await until(() => hasBeenCalledFor(validStream)) client.off('streamCreated', onStreamCreated) expect(onStreamCreated).toHaveBeenCalledWith({ streamId: validStream.id, @@ -242,7 +242,7 @@ describe('StreamRegistry', () => { await createdStream.update({ description }) - await until(async () => { + await until_(async () => { try { return (await client.getStream(createdStream.id)).getMetadata().description === createdStream.getMetadata().description } catch { @@ -262,7 +262,7 @@ describe('StreamRegistry', () => { const props = { id: createRelativeTestStreamId(module) } const stream = await client.createStream(props) await stream.delete() - await until(async () => { + await until_(async () => { try { await client.getStream(stream.id) return false diff --git a/packages/sdk/test/end-to-end/binary-publish.test.ts b/packages/sdk/test/end-to-end/binary-publish.test.ts index 01f07b889e..fce9e504fe 100644 --- a/packages/sdk/test/end-to-end/binary-publish.test.ts +++ b/packages/sdk/test/end-to-end/binary-publish.test.ts @@ -1,6 +1,6 @@ import { Wallet } from 'ethers' import { fastWallet, fetchPrivateKeyWithGas } from '@streamr/test-utils' -import { waitForCondition, areEqualBinaries } from '@streamr/utils' +import { until, areEqualBinaries } from '@streamr/utils' import { StreamrClient } from '../../src/StreamrClient' import { Stream } from '../../src/Stream' import { createTestStream, createTestClient } from '../test-utils/utils' @@ -49,7 +49,7 @@ describe('binary publish', () => { messages.push(msg) }) await publisher.publish(stream.id, PAYLOAD) - await waitForCondition(() => messages.length > 0, TIMEOUT) + await until(() => messages.length > 0, TIMEOUT) expect(areEqualBinaries(messages[0] as Uint8Array, PAYLOAD)).toEqual(true) }, TIMEOUT) }) @@ -78,7 +78,7 @@ describe('binary publish', () => { messages.push(msg) }) await publisher.publish(stream.id, PAYLOAD) - await waitForCondition(() => messages.length > 0, TIMEOUT) + await until(() => messages.length > 0, TIMEOUT) expect(areEqualBinaries(messages[0] as Uint8Array, PAYLOAD)).toEqual(true) }, TIMEOUT) }) diff --git a/packages/sdk/test/end-to-end/erc1271-publish-subscribe.test.ts b/packages/sdk/test/end-to-end/erc1271-publish-subscribe.test.ts index 2da246a354..44e6275902 100644 --- a/packages/sdk/test/end-to-end/erc1271-publish-subscribe.test.ts +++ b/packages/sdk/test/end-to-end/erc1271-publish-subscribe.test.ts @@ -1,5 +1,5 @@ import { fastWallet, fetchPrivateKeyWithGas } from '@streamr/test-utils' -import { EthereumAddress, StreamID, areEqualBinaries, toEthereumAddress, waitForCondition } from '@streamr/utils' +import { EthereumAddress, StreamID, areEqualBinaries, toEthereumAddress, until } from '@streamr/utils' import { Wallet } from 'ethers' import { MessageMetadata } from '../../src' import { StreamrClient } from '../../src/StreamrClient' @@ -64,7 +64,7 @@ describe('ERC-1271: publish', () => { metadatas.push(metadata) }) await publisher.publish(streamId, PAYLOAD, { erc1271Contract: erc1271ContractAddress }) - await waitForCondition(() => messages.length > 0, TIMEOUT) + await until(() => messages.length > 0, TIMEOUT) expect(metadatas[0].signatureType).toEqual('ERC_1271') if (publicOrPrivate === 'public') { expect(metadatas[0].groupKeyId).toEqual(undefined) @@ -129,7 +129,7 @@ describe('ERC-1271: subscribe', () => { metadatas.push(metadata) }) await publisher.publish(streamId, PAYLOAD) - await waitForCondition(() => messages.length > 0, TIMEOUT) + await until(() => messages.length > 0, TIMEOUT) expect(metadatas[0].signatureType).toEqual('SECP256K1') expect(metadatas[0].groupKeyId).toBeString() expect(areEqualBinaries(messages[0] as Uint8Array, PAYLOAD)).toBe(true) @@ -190,7 +190,7 @@ describe('ERC-1271: publish and subscribe', () => { metadatas.push(metadata) }) await publisher.publish(streamId, PAYLOAD, { erc1271Contract: erc1271PublisherContractAddress }) - await waitForCondition(() => messages.length > 0, TIMEOUT) + await until(() => messages.length > 0, TIMEOUT) expect(metadatas[0].signatureType).toEqual('ERC_1271') expect(metadatas[0].groupKeyId).toBeString() expect(areEqualBinaries(messages[0] as Uint8Array, PAYLOAD)).toBe(true) diff --git a/packages/sdk/test/end-to-end/publish-subscribe.test.ts b/packages/sdk/test/end-to-end/publish-subscribe.test.ts index 96e7ee5f3e..34a7627d8e 100644 --- a/packages/sdk/test/end-to-end/publish-subscribe.test.ts +++ b/packages/sdk/test/end-to-end/publish-subscribe.test.ts @@ -2,7 +2,7 @@ import { config as CHAIN_CONFIG } from '@streamr/config' import { DhtAddress, NodeType, toDhtAddressRaw } from '@streamr/dht' import { fastWallet, fetchPrivateKeyWithGas } from '@streamr/test-utils' import { createNetworkNode } from '@streamr/trackerless-network' -import { StreamID, toStreamPartID, waitForCondition } from '@streamr/utils' +import { StreamID, toStreamPartID, until } from '@streamr/utils' import { Wallet } from 'ethers' import { Stream } from '../../src/Stream' import { StreamrClient } from '../../src/StreamrClient' @@ -32,7 +32,7 @@ async function startNetworkNodeAndListenForAtLeastOneMessage(streamId: StreamID) networkNode.addMessageListener((msg) => { messages.push(StreamMessageTranslator.toClientProtocol(msg).getParsedContent()) }) - await waitForCondition(() => messages.length > 0, TIMEOUT) + await until(() => messages.length > 0, TIMEOUT) return messages } finally { await networkNode.stop() @@ -104,7 +104,7 @@ describe('publish-subscribe', () => { await subscriberClient.subscribe(stream.id, (msg: any) => { messages.push(msg) }) - await waitForCondition(() => messages.length > 0, TIMEOUT) + await until(() => messages.length > 0, TIMEOUT) expect(messages).toEqual([PAYLOAD]) }, TIMEOUT) }) @@ -131,7 +131,7 @@ describe('publish-subscribe', () => { messages.push(msg) }) await publisherClient.publish(stream.id, PAYLOAD) - await waitForCondition(() => messages.length > 0, TIMEOUT) + await until(() => messages.length > 0, TIMEOUT) expect(messages).toEqual([PAYLOAD]) }, TIMEOUT) }) diff --git a/packages/sdk/test/end-to-end/resend.test.ts b/packages/sdk/test/end-to-end/resend.test.ts index da60b148dc..87595f7622 100644 --- a/packages/sdk/test/end-to-end/resend.test.ts +++ b/packages/sdk/test/end-to-end/resend.test.ts @@ -1,5 +1,5 @@ import { fastPrivateKey, fetchPrivateKeyWithGas } from '@streamr/test-utils' -import { wait, waitForCondition } from '@streamr/utils' +import { wait, until } from '@streamr/utils' import { randomBytes } from 'crypto' import random from 'lodash/random' import range from 'lodash/range' @@ -58,7 +58,7 @@ describe('resend', () => { }, { last: NUM_OF_MESSAGES }, (msg: any) => { messages.push(msg) }) - await waitForCondition( + await until( () => messages.length >= NUM_OF_MESSAGES, TIMEOUT - 1000, 250, diff --git a/packages/sdk/test/integration/Resends2.test.ts b/packages/sdk/test/integration/Resends2.test.ts index 70abb707f2..38a0a271aa 100644 --- a/packages/sdk/test/integration/Resends2.test.ts +++ b/packages/sdk/test/integration/Resends2.test.ts @@ -1,7 +1,7 @@ import 'reflect-metadata' import { fastWallet } from '@streamr/test-utils' -import { StreamID, collect, toStreamPartID, waitForCondition } from '@streamr/utils' +import { StreamID, collect, toStreamPartID, until } from '@streamr/utils' import { Wallet } from 'ethers' import { Message, MessageMetadata } from '../../src/Message' import { Stream } from '../../src/Stream' @@ -371,7 +371,7 @@ describe('Resends2', () => { const onResent = jest.fn() sub.once('resendCompleted', onResent) const receivedMsgsPromise = collect(sub, MAX_MESSAGES + REALTIME_MESSAGES) - await waitForCondition(() => onResent.mock.calls.length > 0) + await until(() => onResent.mock.calls.length > 0) published.push(...await publishTestMessages(REALTIME_MESSAGES)) diff --git a/packages/sdk/test/integration/Sequencing.test.ts b/packages/sdk/test/integration/Sequencing.test.ts index 7cc95f198e..f4af4bb47c 100644 --- a/packages/sdk/test/integration/Sequencing.test.ts +++ b/packages/sdk/test/integration/Sequencing.test.ts @@ -1,6 +1,6 @@ import 'reflect-metadata' -import { collect, merge, wait, waitForCondition } from '@streamr/utils' +import { collect, merge, wait, until } from '@streamr/utils' import { Message } from '../../src/Message' import { Stream } from '../../src/Stream' import { StreamrClient } from '../../src/StreamrClient' @@ -72,7 +72,7 @@ describe('Sequencing', () => { [[1, 1], [1, 0]], ]) - await waitForCondition(() => ( + await until(() => ( msgsReceieved.length === msgsPublished.length ), 8000).catch(() => {}) // ignore, tests will fail anyway @@ -121,7 +121,7 @@ describe('Sequencing', () => { [[1, 1], [1, 0]], ]) - await waitForCondition(() => ( + await until(() => ( msgsReceieved.length === msgsPublished.length ), 5000).catch(() => {}) // ignore, tests will fail anyway @@ -157,7 +157,7 @@ describe('Sequencing', () => { client.publish(stream, nextMsg(), { timestamp: ts + 3 }), ]) - await waitForCondition(() => ( + await until(() => ( msgsReceieved.length === msgsPublished.length ), 2000).catch(() => {}) // ignore, tests will fail anyway @@ -224,7 +224,7 @@ describe('Sequencing', () => { client.publish(stream, nextMsg(), { timestamp: ts + 2 }), ]) - await waitForCondition(() => ( + await until(() => ( msgsReceieved.length === msgsPublished.length ), 2000).catch(() => {}) // ignore, tests will fail anyway diff --git a/packages/sdk/test/integration/Subscriber2.test.ts b/packages/sdk/test/integration/Subscriber2.test.ts index 122ab307d6..5b9ec43b62 100644 --- a/packages/sdk/test/integration/Subscriber2.test.ts +++ b/packages/sdk/test/integration/Subscriber2.test.ts @@ -1,7 +1,7 @@ import 'reflect-metadata' import { fastWallet } from '@streamr/test-utils' -import { Defer, StreamID, collect, utf8ToBinary, waitForCondition, toUserId } from '@streamr/utils' +import { Defer, StreamID, collect, utf8ToBinary, until, toUserId } from '@streamr/utils' import sample from 'lodash/sample' import shuffle from 'lodash/shuffle' import { createPrivateKeyAuthentication } from '../../src/Authentication' @@ -293,7 +293,7 @@ describe('Subscriber', () => { const published = await publishTestMessages(NUM_MESSAGES, { timestamp: 111111, }) - await waitForCondition(() => onError1.mock.calls.length > 0) + await until(() => onError1.mock.calls.length > 0) expect(received1.map((m) => m.signature)).toEqual(published.slice(0, MAX_ITEMS).map((m) => m.signature)) expect(onError1).toHaveBeenCalledTimes(1) diff --git a/packages/sdk/test/integration/SubscriberKeyExchange.test.ts b/packages/sdk/test/integration/SubscriberKeyExchange.test.ts index d5bf183ebc..97521e9183 100644 --- a/packages/sdk/test/integration/SubscriberKeyExchange.test.ts +++ b/packages/sdk/test/integration/SubscriberKeyExchange.test.ts @@ -8,7 +8,7 @@ import { toStreamPartID, toUserId, UserID, - waitForCondition + until } from '@streamr/utils' import { Wallet } from 'ethers' import { StreamrClient } from '../../src/StreamrClient' @@ -127,7 +127,7 @@ describe('SubscriberKeyExchange', () => { SignatureType.SECP256K1 ) const keyStore = getLocalGroupKeyStore(toUserId(subscriberWallet.address)) - await waitForCondition(async () => (await keyStore.get(groupKey.id, toUserId(publisherWallet.address))) !== undefined) + await until(async () => (await keyStore.get(groupKey.id, toUserId(publisherWallet.address))) !== undefined) }) it('happy path: ERC-1271', async () => { @@ -157,7 +157,7 @@ describe('SubscriberKeyExchange', () => { }) await assertGroupKeyRequest(request, streamPartId, [groupKey.id], toUserId(erc1271Contract), SignatureType.ERC_1271) const keyStore = getLocalGroupKeyStore(toUserId(await subscriber.getUserId())) - await waitForCondition(async () => (await keyStore.get(groupKey.id, toUserId(publisherWallet.address))) !== undefined) + await until(async () => (await keyStore.get(groupKey.id, toUserId(publisherWallet.address))) !== undefined) }) }) }) diff --git a/packages/sdk/test/integration/json-rpc-provider.test.ts b/packages/sdk/test/integration/json-rpc-provider.test.ts index fe10228a3a..c288592755 100644 --- a/packages/sdk/test/integration/json-rpc-provider.test.ts +++ b/packages/sdk/test/integration/json-rpc-provider.test.ts @@ -1,6 +1,6 @@ import 'reflect-metadata' -import { wait, waitForCondition } from '@streamr/utils' +import { wait, until } from '@streamr/utils' import { range, sortBy } from 'lodash' import { StreamrClient } from '../../src/StreamrClient' import { StreamCreationEvent } from '../../src/contracts/StreamRegistry' @@ -112,7 +112,7 @@ describe('use JsonRpcProvider', () => { client.on('streamCreated', (event: StreamCreationEvent) => { receivedEvents.push(event) }) - await waitForCondition(() => getRequests().some((r) => r.method === 'eth_getLogs'), 5000 + extraWait) + await until(() => getRequests().some((r) => r.method === 'eth_getLogs'), 5000 + extraWait) servers.forEach((s) => s.setError('eth_getLogs', undefined)) await wait(1.5 * POLL_INTERVAL + extraWait) expect(receivedEvents).toEqual([{ diff --git a/packages/sdk/test/integration/multiple-clients.test.ts b/packages/sdk/test/integration/multiple-clients.test.ts index e8e77acc86..ce61313f9a 100644 --- a/packages/sdk/test/integration/multiple-clients.test.ts +++ b/packages/sdk/test/integration/multiple-clients.test.ts @@ -1,6 +1,6 @@ import 'reflect-metadata' -import { toUserId, UserID, waitForCondition } from '@streamr/utils' +import { toUserId, UserID, until } from '@streamr/utils' import { Message, MessageMetadata } from '../../src/Message' import { StreamPermission } from '../../src/permission' import { Stream } from '../../src/Stream' @@ -22,7 +22,7 @@ const waitMessagesReceived = async ( received: Record, published: Record ) => { - await waitForCondition(() => { + await until(() => { const receivedCount = Object.values(received).flat().length const publishedCount = Object.values(published).flat().length return receivedCount === publishedCount @@ -106,7 +106,7 @@ describe('PubSub with multiple clients', () => { } // publish message on main client await mainClient.publish(stream, message) - await waitForCondition(() => receivedMessagesMain.length === 1 && receivedMessagesOther.length === 1, 15 * 1000) + await until(() => receivedMessagesMain.length === 1 && receivedMessagesOther.length === 1, 15 * 1000) // messages should arrive on both clients? expect(receivedMessagesMain).toEqual([message]) expect(receivedMessagesOther).toEqual([message]) diff --git a/packages/sdk/test/integration/sequential-resend-subscribe.test.ts b/packages/sdk/test/integration/sequential-resend-subscribe.test.ts index a39781ee42..624b30699a 100644 --- a/packages/sdk/test/integration/sequential-resend-subscribe.test.ts +++ b/packages/sdk/test/integration/sequential-resend-subscribe.test.ts @@ -1,6 +1,6 @@ import 'reflect-metadata' -import { collect, waitForCondition } from '@streamr/utils' +import { collect, until } from '@streamr/utils' import { Message } from '../../src/Message' import { StreamPermission } from '../../src/permission' import { Stream } from '../../src/Stream' @@ -77,7 +77,7 @@ describe('sequential resend subscribe', () => { const expectedMessageCount = published.length + 1 // the realtime message which we publish next const receivedMsgsPromise = collect(sub, expectedMessageCount) - await waitForCondition(() => onResent.mock.calls.length > 0) + await until(() => onResent.mock.calls.length > 0) const streamMessage = await publisher.publish(stream.id, Msg(), { // should be realtime timestamp: id }) diff --git a/packages/sdk/test/integration/update-encryption-key.test.ts b/packages/sdk/test/integration/update-encryption-key.test.ts index 97ce36bba5..c7e3c89609 100644 --- a/packages/sdk/test/integration/update-encryption-key.test.ts +++ b/packages/sdk/test/integration/update-encryption-key.test.ts @@ -1,6 +1,6 @@ import 'reflect-metadata' -import { StreamPartID, StreamPartIDUtils, waitForCondition } from '@streamr/utils' +import { StreamPartID, StreamPartIDUtils, until } from '@streamr/utils' import { Message } from '../../src/Message' import { DecryptError } from '../../src/encryption/EncryptionUtil' import { GroupKey } from '../../src/encryption/GroupKey' @@ -160,7 +160,7 @@ describe('update encryption key', () => { await publisher.publish(streamPartId, { mockId: 2 }) - await waitForCondition(() => onError.mock.calls.length > 0, 10 * 1000) + await until(() => onError.mock.calls.length > 0, 10 * 1000) expect(onError.mock.calls[0][0]).toBeInstanceOf(DecryptError) }, 10 * 1000) }) diff --git a/packages/sdk/test/test-utils/fake/FakeNetwork.ts b/packages/sdk/test/test-utils/fake/FakeNetwork.ts index e62d96bf43..02fba76cb6 100644 --- a/packages/sdk/test/test-utils/fake/FakeNetwork.ts +++ b/packages/sdk/test/test-utils/fake/FakeNetwork.ts @@ -1,5 +1,5 @@ import { DhtAddress } from '@streamr/dht' -import { waitForCondition } from '@streamr/utils' +import { until } from '@streamr/utils' import { StreamMessage, StreamMessageType } from '../../../src/protocol/StreamMessage' import { StreamMessageTranslator } from '../../../src/protocol/StreamMessageTranslator' import { FakeNetworkNode } from './FakeNetworkNode' @@ -65,7 +65,7 @@ export class FakeNetwork { async waitForSentMessages(opts: SentMessagesFilter & { count: number }, timeout = 60 * 1000): Promise { let found: StreamMessage[] = [] const count = opts.count - await waitForCondition(() => { + await until(() => { found = this.getSentMessages(opts) return found.length >= count }, timeout, timeout / 100, undefined, () => { diff --git a/packages/sdk/test/test-utils/utils.ts b/packages/sdk/test/test-utils/utils.ts index 4ae2ff3e68..cae51b0c0f 100644 --- a/packages/sdk/test/test-utils/utils.ts +++ b/packages/sdk/test/test-utils/utils.ts @@ -11,7 +11,7 @@ import { merge, utf8ToBinary, wait, - waitForCondition + until } from '@streamr/utils' import crypto from 'crypto' import { Wallet } from 'ethers' @@ -244,7 +244,7 @@ export const createGroupKeyQueue = async (authentication: Authentication, curren } export const waitForCalls = async (mockFunction: jest.Mock, n: number): Promise => { - await waitForCondition(() => mockFunction.mock.calls.length >= n, 1000, 10, undefined, () => { + await until(() => mockFunction.mock.calls.length >= n, 1000, 10, undefined, () => { return `Timeout while waiting for calls: got ${mockFunction.mock.calls.length} out of ${n}` }) } diff --git a/packages/sdk/test/unit/ChainEventPoller.test.ts b/packages/sdk/test/unit/ChainEventPoller.test.ts index af6835c5a6..a9b85615f9 100644 --- a/packages/sdk/test/unit/ChainEventPoller.test.ts +++ b/packages/sdk/test/unit/ChainEventPoller.test.ts @@ -1,4 +1,4 @@ -import { wait, waitForCondition } from '@streamr/utils' +import { wait, until } from '@streamr/utils' import { Contract, EventLog, Provider } from 'ethers' import { ChainEventPoller, POLLS_SINCE_LAST_FROM_BLOCK_UPDATE_THRESHOLD } from './../../src/contracts/ChainEventPoller' import range from 'lodash/range' @@ -36,13 +36,13 @@ describe('ChainEventPoller', () => { poller.on(EVENT_NAME, listener1) // poller starts - await waitForCondition(() => listener1.mock.calls.length === 1) + await until(() => listener1.mock.calls.length === 1) expect(contract.runner!.provider!.getBlockNumber).toHaveBeenCalledTimes(1) expect(contract.queryFilter).toHaveBeenCalledTimes(1) expect(contract.queryFilter).toHaveBeenCalledWith([[EVENT_NAME]], INITIAL_BLOCK_NUMBER) expect(listener1).toHaveBeenCalledTimes(1) expect(listener1).toHaveBeenCalledWith(...EVENT_ARGS, INITIAL_BLOCK_NUMBER) - await waitForCondition(() => listener1.mock.calls.length === 2) + await until(() => listener1.mock.calls.length === 2) expect(contract.runner!.provider!.getBlockNumber).toHaveBeenCalledTimes(1) expect(contract.queryFilter).toHaveBeenCalledTimes(2) expect(contract.queryFilter).toHaveBeenNthCalledWith(2, [[EVENT_NAME]], INITIAL_BLOCK_NUMBER + 1) @@ -61,7 +61,7 @@ describe('ChainEventPoller', () => { poller.on(EVENT_NAME, listener2) // poller restarts - await waitForCondition(() => listener2.mock.calls.length === 1) + await until(() => listener2.mock.calls.length === 1) expect(contract.runner!.provider!.getBlockNumber).toHaveBeenCalledTimes(2) expect(contract.queryFilter).toHaveBeenCalledTimes(3) expect(listener2).toHaveBeenCalledTimes(1) @@ -117,7 +117,7 @@ describe('ChainEventPoller', () => { poller.on(EVENT_NAME_2, listener2) poller.on(EVENT_NAME_2, listener3) - await waitForCondition( + await until( () => { return (listener1.mock.calls.length > 0) && (listener2.mock.calls.length > 0) && (listener3.mock.calls.length > 0) } @@ -177,7 +177,7 @@ describe('ChainEventPoller', () => { const eventCb = () => {} poller.on('event', eventCb) const expectedLength = 3 * POLLS_SINCE_LAST_FROM_BLOCK_UPDATE_THRESHOLD + 6 - await waitForCondition(() => invocationHistory.length >= expectedLength) + await until(() => invocationHistory.length >= expectedLength) expect(invocationHistory.slice(0, expectedLength)).toEqual([ 'getBlockNumber', ...range(POLLS_SINCE_LAST_FROM_BLOCK_UPDATE_THRESHOLD).map(() => 'queryFilter(event, 10)'), diff --git a/packages/sdk/test/unit/GapFiller.test.ts b/packages/sdk/test/unit/GapFiller.test.ts index 3718b3b123..96c60e987f 100644 --- a/packages/sdk/test/unit/GapFiller.test.ts +++ b/packages/sdk/test/unit/GapFiller.test.ts @@ -6,7 +6,7 @@ import { toEthereumAddress, utf8ToBinary, wait, - waitForCondition + until } from '@streamr/utils' import { GapFillStrategy, GapFiller } from '../../src/subscribe/ordering/GapFiller' import { Gap, OrderedMessageChain } from '../../src/subscribe/ordering/OrderedMessageChain' @@ -97,7 +97,7 @@ describe('GapFiller', () => { } const expectOrderedMessages = async (expectedTimestamps: number[]) => { - await waitForCondition(() => onOrderedMessageAdded.mock.calls.length === expectedTimestamps.length) + await until(() => onOrderedMessageAdded.mock.calls.length === expectedTimestamps.length) const actualTimestamps = onOrderedMessageAdded.mock.calls.map((call) => call[0].getTimestamp()) expect(actualTimestamps).toEqual(expectedTimestamps) } diff --git a/packages/sdk/test/unit/OrderMessages.test.ts b/packages/sdk/test/unit/OrderMessages.test.ts index 0832147e42..c30ddaa3ae 100644 --- a/packages/sdk/test/unit/OrderMessages.test.ts +++ b/packages/sdk/test/unit/OrderMessages.test.ts @@ -6,7 +6,7 @@ import { StreamPartIDUtils, collect, hexToBinary, toStreamID, - waitForCondition + until } from '@streamr/utils' import last from 'lodash/last' import range from 'lodash/range' @@ -266,7 +266,7 @@ describe('OrderMessages', () => { const addMessages = async (orderMessages: OrderMessages) => { await orderMessages.addMessages(async function* () { yield* allMessages.filter((m) => CHUNK1.includes(m.getTimestamp())) - await waitForCondition(() => { + await until(() => { return outputMessages.some((m) => (m.getTimestamp() === last(CHUNK1))) }) yield* allMessages.filter((m) => CHUNK2.includes(m.getTimestamp())) diff --git a/packages/sdk/test/unit/OrderMessages2.test.ts b/packages/sdk/test/unit/OrderMessages2.test.ts index 6f0b6144fb..a9c554ad35 100644 --- a/packages/sdk/test/unit/OrderMessages2.test.ts +++ b/packages/sdk/test/unit/OrderMessages2.test.ts @@ -1,5 +1,5 @@ import { randomEthereumAddress, randomUserId } from '@streamr/test-utils' -import { ChangeFieldType, StreamPartID, StreamPartIDUtils, UserID, hexToBinary, toStreamID, wait, waitForCondition } from '@streamr/utils' +import { ChangeFieldType, StreamPartID, StreamPartIDUtils, UserID, hexToBinary, toStreamID, wait, until } from '@streamr/utils' import { range, shuffle } from 'lodash' import { ResendRangeOptions } from '../../src/subscribe/Resends' import { OrderMessages } from '../../src/subscribe/ordering/OrderMessages' @@ -196,7 +196,7 @@ describe.skip('OrderMessages2', () => { }() await orderMessages.addMessages(producer) - await waitForCondition(() => PUBLISHER_IDS.every((publisherId) => { + await until(() => PUBLISHER_IDS.every((publisherId) => { return expected[publisherId].length === actual[publisherId].length }), 60 * 1000) expect(onUnfillableGap).toHaveBeenCalledTimes(totalUnfillableGaps) diff --git a/packages/sdk/test/unit/resendSubscription.test.ts b/packages/sdk/test/unit/resendSubscription.test.ts index 740b2f9fc7..ea5669eff6 100644 --- a/packages/sdk/test/unit/resendSubscription.test.ts +++ b/packages/sdk/test/unit/resendSubscription.test.ts @@ -1,5 +1,5 @@ import { Queue, randomEthereumAddress } from '@streamr/test-utils' -import { StreamPartID, StreamPartIDUtils, waitForCondition } from '@streamr/utils' +import { StreamPartID, StreamPartIDUtils, until } from '@streamr/utils' import EventEmitter from 'eventemitter3' import { mock } from 'jest-mock-extended' import { isEqual } from 'lodash' @@ -34,7 +34,7 @@ const createResend = (historicalMessages: StreamMessage[], gapHandler: (opts: Re } const waitForMatchingItem = async (streamMessage: StreamMessage, queue: Queue) => { - await waitForCondition(() => { + await until(() => { return queue.values().some((msg) => isEqual(msg.content, streamMessage.getParsedContent())) }) } diff --git a/packages/sdk/test/unit/utils.test.ts b/packages/sdk/test/unit/utils.test.ts index 5217478b61..6545106a02 100644 --- a/packages/sdk/test/unit/utils.test.ts +++ b/packages/sdk/test/unit/utils.test.ts @@ -1,5 +1,5 @@ import { isRunningInElectron, startTestServer, testOnlyInNodeJs } from '@streamr/test-utils' -import { collect, toLengthPrefixedFrame, waitForCondition } from '@streamr/utils' +import { collect, toLengthPrefixedFrame, until } from '@streamr/utils' import { Request, Response } from 'express' import range from 'lodash/range' import { FetchHttpStreamResponseError, createQueryString, fetchLengthPrefixedFrameHttpBinaryStream, getEndpointUrl } from '../../src/utils/utils' @@ -54,7 +54,7 @@ describe('utils', () => { const line = await nextValue(iterator) expect(line?.toString()).toBe('foobar') abortController.abort() - await waitForCondition(() => serverResponseClosed === true) + await until(() => serverResponseClosed === true) await expect(() => nextValue(iterator)).rejects.toThrow(/aborted/) await server.stop() }) diff --git a/packages/test-utils/src/index.ts b/packages/test-utils/src/index.ts index 5eecd246d3..b190ed261e 100644 --- a/packages/test-utils/src/index.ts +++ b/packages/test-utils/src/index.ts @@ -1,4 +1,4 @@ -import { EthereumAddress, toEthereumAddress, toUserId, UserID, waitForCondition, waitForEvent } from '@streamr/utils' +import { EthereumAddress, toEthereumAddress, toUserId, UserID, until, waitForEvent } from '@streamr/utils' import cors from 'cors' import crypto, { randomBytes } from 'crypto' import { Wallet } from 'ethers' @@ -90,7 +90,7 @@ export const runAndRaceEvents = async ( /** * Run functions and wait conditions to become true by re-evaluating every `retryInterval` milliseconds. Returns a promise created with Promise.all() - * and waitForCondition() calls. Calls the functions after creating the promise. + * and until() calls. Calls the functions after creating the promise. * * @param operations function(s) to call * @param conditions condition(s) to be evaluated; condition functions should return boolean or Promise and have @@ -102,7 +102,7 @@ export const runAndRaceEvents = async ( * conditions evaluate to true on a retry attempt within timeout. If timeout * is reached with conditionFn never evaluating to true, rejects. */ -export const runAndWaitForConditions = async ( +export const runAnduntils = async ( operations: (() => void) | ((() => void)[]), conditions: (() => (boolean | Promise)) | (() => (boolean | Promise)) [], timeout = 5000, @@ -111,7 +111,7 @@ export const runAndWaitForConditions = async ( ): Promise => { const ops = Array.isArray(operations) ? operations : [operations] const conds = Array.isArray(conditions) ? conditions : [conditions] - const promise = Promise.all(conds.map((condition) => waitForCondition( + const promise = Promise.all(conds.map((condition) => until( condition, timeout, retryInterval, @@ -318,7 +318,7 @@ export class Queue { } async pop(timeout?: number): Promise { - await waitForCondition(() => this.items.length > 0, timeout) + await until(() => this.items.length > 0, timeout) return this.items.shift()! } diff --git a/packages/trackerless-network/src/NetworkStack.ts b/packages/trackerless-network/src/NetworkStack.ts index ebf4096741..c28182004b 100644 --- a/packages/trackerless-network/src/NetworkStack.ts +++ b/packages/trackerless-network/src/NetworkStack.ts @@ -7,7 +7,7 @@ import { areEqualPeerDescriptors, toNodeId } from '@streamr/dht' -import { Logger, MetricsContext, StreamID, StreamPartID, toStreamPartID, waitForCondition } from '@streamr/utils' +import { Logger, MetricsContext, StreamID, StreamPartID, toStreamPartID, until } from '@streamr/utils' import { pull } from 'lodash' import { version as applicationVersion } from '../package.json' import { ContentDeliveryManager, ContentDeliveryManagerOptions } from './logic/ContentDeliveryManager' @@ -82,7 +82,7 @@ export class NetworkStack { await this.ensureConnectedToControlLayer() this.getContentDeliveryManager().joinStreamPart(streamPartId) if (neighborRequirement !== undefined) { - await waitForCondition(() => { + await until(() => { return this.getContentDeliveryManager().getNeighbors(streamPartId).length >= neighborRequirement.minCount }, neighborRequirement.timeout) } diff --git a/packages/trackerless-network/test/end-to-end/content-delivery-layer-node-with-real-connections.test.ts b/packages/trackerless-network/test/end-to-end/content-delivery-layer-node-with-real-connections.test.ts index 2200f1b916..64c77b7958 100644 --- a/packages/trackerless-network/test/end-to-end/content-delivery-layer-node-with-real-connections.test.ts +++ b/packages/trackerless-network/test/end-to-end/content-delivery-layer-node-with-real-connections.test.ts @@ -1,5 +1,5 @@ import { ConnectionManager, DhtNode, PeerDescriptor } from '@streamr/dht' -import { StreamPartIDUtils, waitForCondition } from '@streamr/utils' +import { StreamPartIDUtils, until } from '@streamr/utils' import { ContentDeliveryLayerNode } from '../../src/logic/ContentDeliveryLayerNode' import { ControlLayerNode } from '../../src/logic/ControlLayerNode' import { DiscoveryLayerNode } from '../../src/logic/DiscoveryLayerNode' @@ -120,7 +120,7 @@ describe('content delivery layer node with real connections', () => { }) it('can fully connected topologies ', async () => { - await waitForCondition(() => { + await until(() => { return contentDeliveryLayerNode1.getNeighbors().length >= 3 && contentDeliveryLayerNode2.getNeighbors().length >= 3 && contentDeliveryLayerNode3.getNeighbors().length >= 3 @@ -141,7 +141,7 @@ describe('content delivery layer node with real connections', () => { contentDeliveryLayerNode4.on('message', () => receivedMessageCount += 1) contentDeliveryLayerNode5.on('message', () => receivedMessageCount += 1) - await waitForCondition(() => { + await until(() => { return contentDeliveryLayerNode1.getNeighbors().length >= 3 && contentDeliveryLayerNode2.getNeighbors().length >= 3 && contentDeliveryLayerNode3.getNeighbors().length >= 3 @@ -155,6 +155,6 @@ describe('content delivery layer node with real connections', () => { randomUserId() ) contentDeliveryLayerNode1.broadcast(msg) - await waitForCondition(() => receivedMessageCount >= 4) + await until(() => receivedMessageCount >= 4) }) }) diff --git a/packages/trackerless-network/test/end-to-end/inspect.test.ts b/packages/trackerless-network/test/end-to-end/inspect.test.ts index 41a591812f..6baf89fe65 100644 --- a/packages/trackerless-network/test/end-to-end/inspect.test.ts +++ b/packages/trackerless-network/test/end-to-end/inspect.test.ts @@ -1,5 +1,5 @@ import { randomUserId } from '@streamr/test-utils' -import { StreamPartIDUtils, hexToBinary, toUserIdRaw, utf8ToBinary, waitForCondition } from '@streamr/utils' +import { StreamPartIDUtils, hexToBinary, toUserIdRaw, utf8ToBinary, until } from '@streamr/utils' import { NetworkNode, createNetworkNode } from '../../src/NetworkNode' import { ContentType, EncryptionType, SignatureType, StreamMessage } from '../../generated/packages/trackerless-network/protos/NetworkRpc' import { createMockPeerDescriptor } from '../utils/utils' @@ -98,7 +98,7 @@ describe('inspect', () => { inspectedNode.stack.getContentDeliveryManager().joinStreamPart(STREAM_PART_ID) inspectorNode.stack.getContentDeliveryManager().joinStreamPart(STREAM_PART_ID) - await waitForCondition(() => + await until(() => publisherNode.stack.getContentDeliveryManager().getNeighbors(STREAM_PART_ID).length === 2 && inspectedNode.stack.getContentDeliveryManager().getNeighbors(STREAM_PART_ID).length === 2 && inspectorNode.stack.getContentDeliveryManager().getNeighbors(STREAM_PART_ID).length === 2 diff --git a/packages/trackerless-network/test/end-to-end/proxy-connections.test.ts b/packages/trackerless-network/test/end-to-end/proxy-connections.test.ts index 0fa8c052ef..8afbe1457f 100644 --- a/packages/trackerless-network/test/end-to-end/proxy-connections.test.ts +++ b/packages/trackerless-network/test/end-to-end/proxy-connections.test.ts @@ -1,6 +1,6 @@ import { DhtAddress } from '@streamr/dht' import { randomUserId } from '@streamr/test-utils' -import { StreamPartIDUtils, hexToBinary, toUserIdRaw, utf8ToBinary, wait, waitForCondition, waitForEvent3 } from '@streamr/utils' +import { StreamPartIDUtils, hexToBinary, toUserIdRaw, utf8ToBinary, wait, until, waitForEvent3 } from '@streamr/utils' import { NetworkNode, createNetworkNode } from '../../src/NetworkNode' import { ContentDeliveryLayerNode } from '../../src/logic/ContentDeliveryLayerNode' import { ProxyClient } from '../../src/logic/proxy/ProxyClient' @@ -129,7 +129,7 @@ describe('Proxy connections', () => { expect(hasConnectionFromProxy(proxyNode1)).toBe(true) await proxiedNode.setProxies(STREAM_PART_ID, [], ProxyDirection.PUBLISH, PROXIED_NODE_USER_ID, 0) expect(proxiedNode.hasStreamPart(STREAM_PART_ID)).toBe(false) - await waitForCondition(() => hasConnectionFromProxy(proxyNode1) === false) + await until(() => hasConnectionFromProxy(proxyNode1) === false) }) it('can leave proxy subscribe connection', async () => { @@ -138,7 +138,7 @@ describe('Proxy connections', () => { expect(hasConnectionFromProxy(proxyNode1)).toBe(true) await proxiedNode.setProxies(STREAM_PART_ID, [], ProxyDirection.SUBSCRIBE, PROXIED_NODE_USER_ID, 0) expect(proxiedNode.hasStreamPart(STREAM_PART_ID)).toBe(false) - await waitForCondition(() => hasConnectionFromProxy(proxyNode1) === false) + await until(() => hasConnectionFromProxy(proxyNode1) === false) }) it('can open multiple proxy connections', async () => { @@ -165,7 +165,7 @@ describe('Proxy connections', () => { expect(hasConnectionFromProxy(proxyNode2)).toBe(true) await proxiedNode.setProxies(STREAM_PART_ID, [proxyNode1.getPeerDescriptor()], ProxyDirection.SUBSCRIBE, PROXIED_NODE_USER_ID) expect(proxiedNode.hasStreamPart(STREAM_PART_ID)).toBe(true) - await waitForCondition(() => hasConnectionFromProxy(proxyNode2) === false) + await until(() => hasConnectionFromProxy(proxyNode2) === false) expect(hasConnectionFromProxy(proxyNode1)).toBe(true) }) @@ -182,8 +182,8 @@ describe('Proxy connections', () => { await proxiedNode.setProxies(STREAM_PART_ID, [], ProxyDirection.SUBSCRIBE, PROXIED_NODE_USER_ID) expect(proxiedNode.hasStreamPart(STREAM_PART_ID)).toBe(false) - await waitForCondition(() => hasConnectionFromProxy(proxyNode1) === false) - await waitForCondition(() => hasConnectionFromProxy(proxyNode2) === false) + await until(() => hasConnectionFromProxy(proxyNode1) === false) + await until(() => hasConnectionFromProxy(proxyNode2) === false) }) it('will reconnect if proxy node goes offline and comes back online', async () => { @@ -195,10 +195,10 @@ describe('Proxy connections', () => { ) expect(proxiedNode.hasStreamPart(STREAM_PART_ID)).toBe(true) await proxyNode1.leave(STREAM_PART_ID) - await waitForCondition(() => hasConnectionToProxy(proxyNode1.getNodeId(), ProxyDirection.SUBSCRIBE)) + await until(() => hasConnectionToProxy(proxyNode1.getNodeId(), ProxyDirection.SUBSCRIBE)) expect(hasConnectionFromProxy(proxyNode1)).toBe(false) proxyNode1.stack.getContentDeliveryManager().joinStreamPart(STREAM_PART_ID) - await waitForCondition(() => hasConnectionToProxy(proxyNode1.getNodeId(), ProxyDirection.SUBSCRIBE), 25000) + await until(() => hasConnectionToProxy(proxyNode1.getNodeId(), ProxyDirection.SUBSCRIBE), 25000) // TODO why wait is needed? await wait(100) expect(hasConnectionFromProxy(proxyNode1)).toBe(true) diff --git a/packages/trackerless-network/test/end-to-end/webrtc-full-node-network.test.ts b/packages/trackerless-network/test/end-to-end/webrtc-full-node-network.test.ts index f3a2e32474..096d3be4d7 100644 --- a/packages/trackerless-network/test/end-to-end/webrtc-full-node-network.test.ts +++ b/packages/trackerless-network/test/end-to-end/webrtc-full-node-network.test.ts @@ -1,5 +1,5 @@ import { toNodeId, getRandomRegion } from '@streamr/dht' -import { StreamPartIDUtils, waitForCondition } from '@streamr/utils' +import { StreamPartIDUtils, until } from '@streamr/utils' import { range } from 'lodash' import { NetworkStack } from '../../src/NetworkStack' import { createMockPeerDescriptor, createStreamMessage } from '../utils/utils' @@ -58,7 +58,7 @@ describe('Full node network with WebRTC connections', () => { it('happy path', async () => { await Promise.all(nodes.map((node) => - waitForCondition(() => { + until(() => { return node.getContentDeliveryManager().getNeighbors(streamPartId).length >= 3 } , 30000) @@ -77,7 +77,7 @@ describe('Full node network with WebRTC connections', () => { randomUserId() ) entryPoint.getContentDeliveryManager().broadcast(msg) - await waitForCondition(() => receivedMessageCount === NUM_OF_NODES) + await until(() => receivedMessageCount === NUM_OF_NODES) }, 120000) }) diff --git a/packages/trackerless-network/test/end-to-end/websocket-full-node-network.test.ts b/packages/trackerless-network/test/end-to-end/websocket-full-node-network.test.ts index 87a0d2936a..e84a78e621 100644 --- a/packages/trackerless-network/test/end-to-end/websocket-full-node-network.test.ts +++ b/packages/trackerless-network/test/end-to-end/websocket-full-node-network.test.ts @@ -1,5 +1,5 @@ import { toNodeId } from '@streamr/dht' -import { StreamPartIDUtils, waitForCondition } from '@streamr/utils' +import { StreamPartIDUtils, until } from '@streamr/utils' import { range } from 'lodash' import { NetworkStack } from '../../src/NetworkStack' import { createMockPeerDescriptor, createStreamMessage } from '../utils/utils' @@ -56,7 +56,7 @@ describe('Full node network with WebSocket connections only', () => { it('happy path', async () => { await Promise.all(nodes.map((node) => - waitForCondition(() => { + until(() => { return node.getContentDeliveryManager().getNeighbors(streamPartId).length >= 4 } , 30000) @@ -76,7 +76,7 @@ describe('Full node network with WebSocket connections only', () => { randomUserId() ) entryPoint.getContentDeliveryManager().broadcast(msg) - await waitForCondition(() => receivedMessageCount === NUM_OF_NODES) + await until(() => receivedMessageCount === NUM_OF_NODES) }, 220000) }) diff --git a/packages/trackerless-network/test/integration/ContentDeliveryLayerNode-Layer1Node-Latencies.test.ts b/packages/trackerless-network/test/integration/ContentDeliveryLayerNode-Layer1Node-Latencies.test.ts index 3c86d801ae..301ead87ce 100644 --- a/packages/trackerless-network/test/integration/ContentDeliveryLayerNode-Layer1Node-Latencies.test.ts +++ b/packages/trackerless-network/test/integration/ContentDeliveryLayerNode-Layer1Node-Latencies.test.ts @@ -1,5 +1,5 @@ import { DhtNode, LatencyType, PeerDescriptor, Simulator, SimulatorTransport, toNodeId } from '@streamr/dht' -import { StreamPartIDUtils, waitForCondition } from '@streamr/utils' +import { StreamPartIDUtils, until } from '@streamr/utils' import { range } from 'lodash' import { ContentDeliveryLayerNode } from '../../src/logic/ContentDeliveryLayerNode' import { DiscoveryLayerNode } from '../../src/logic/DiscoveryLayerNode' @@ -72,8 +72,8 @@ describe('ContentDeliveryLayerNode-DhtNode-Latencies', () => { await otherContentDeliveryLayerNodes[0].start() await otherDiscoveryLayerNodes[0].joinDht([entrypointDescriptor]) await Promise.all([ - waitForCondition(() => otherContentDeliveryLayerNodes[0].getNearbyNodeView().getIds().length === 1), - waitForCondition(() => otherContentDeliveryLayerNodes[0].getNeighbors().length === 1) + until(() => otherContentDeliveryLayerNodes[0].getNearbyNodeView().getIds().length === 1), + until(() => otherContentDeliveryLayerNodes[0].getNeighbors().length === 1) ]) expect(otherContentDeliveryLayerNodes[0].getNearbyNodeView().getIds().length).toEqual(1) expect(otherContentDeliveryLayerNodes[0].getNeighbors().length).toEqual(1) @@ -84,7 +84,7 @@ describe('ContentDeliveryLayerNode-DhtNode-Latencies', () => { await Promise.all(range(4).map(async (i) => { await otherDiscoveryLayerNodes[i].joinDht([entrypointDescriptor]) })) - await waitForCondition(() => range(4).every((i) => otherContentDeliveryLayerNodes[i].getNeighbors().length >= 4), 15000, 1000) + await until(() => range(4).every((i) => otherContentDeliveryLayerNodes[i].getNeighbors().length >= 4), 15000, 1000) range(4).forEach((i) => { expect(otherContentDeliveryLayerNodes[i].getNearbyNodeView().getIds().length).toBeGreaterThanOrEqual(4) expect(otherContentDeliveryLayerNodes[i].getNeighbors().length).toBeGreaterThanOrEqual(4) @@ -110,14 +110,14 @@ describe('ContentDeliveryLayerNode-DhtNode-Latencies', () => { otherDiscoveryLayerNodes[i].joinDht([entrypointDescriptor]) })) await Promise.all(otherContentDeliveryLayerNodes.map((node) => - waitForCondition(() => node.getNeighbors().length >= 4, 10000) + until(() => node.getNeighbors().length >= 4, 10000) )) await Promise.all(otherContentDeliveryLayerNodes.map((node) => - waitForCondition(() => node.getOutgoingHandshakeCount() === 0) + until(() => node.getOutgoingHandshakeCount() === 0) )) - await waitForCondition(() => { + await until(() => { let mismatchCounter = 0 otherContentDeliveryLayerNodes.forEach((node) => { const nodeId = node.getOwnNodeId() diff --git a/packages/trackerless-network/test/integration/ContentDeliveryLayerNode-Layer1Node.test.ts b/packages/trackerless-network/test/integration/ContentDeliveryLayerNode-Layer1Node.test.ts index 9e5ab5adce..d9a4820af4 100644 --- a/packages/trackerless-network/test/integration/ContentDeliveryLayerNode-Layer1Node.test.ts +++ b/packages/trackerless-network/test/integration/ContentDeliveryLayerNode-Layer1Node.test.ts @@ -1,5 +1,5 @@ import { ConnectionManager, DhtNode, PeerDescriptor, Simulator, SimulatorTransport, toNodeId, getRandomRegion } from '@streamr/dht' -import { Logger, StreamPartIDUtils, waitForCondition } from '@streamr/utils' +import { Logger, StreamPartIDUtils, until } from '@streamr/utils' import { range } from 'lodash' import { ContentDeliveryLayerNode } from '../../src/logic/ContentDeliveryLayerNode' import { DiscoveryLayerNode } from '../../src/logic/DiscoveryLayerNode' @@ -92,7 +92,7 @@ describe('ContentDeliveryLayerNode-DhtNode', () => { await otherContentDeliveryLayerNodes[0].start() await otherDiscoveryLayerNodes[0].joinDht([entrypointDescriptor]) - await waitForCondition(() => otherContentDeliveryLayerNodes[0].getNeighbors().length === 1) + await until(() => otherContentDeliveryLayerNodes[0].getNeighbors().length === 1) expect(otherContentDeliveryLayerNodes[0].getNearbyNodeView().getIds().length).toEqual(1) expect(otherContentDeliveryLayerNodes[0].getNeighbors().length).toEqual(1) }) @@ -103,7 +103,7 @@ describe('ContentDeliveryLayerNode-DhtNode', () => { await otherDiscoveryLayerNodes[i].joinDht([entrypointDescriptor]) })) - await waitForCondition(() => range(4).every((i) => otherContentDeliveryLayerNodes[i].getNeighbors().length === 4)) + await until(() => range(4).every((i) => otherContentDeliveryLayerNodes[i].getNeighbors().length === 4)) range(4).forEach((i) => { expect(otherContentDeliveryLayerNodes[i].getNearbyNodeView().getIds().length).toBeGreaterThanOrEqual(4) expect(otherContentDeliveryLayerNodes[i].getNeighbors().length).toBeGreaterThanOrEqual(4) @@ -129,7 +129,7 @@ describe('ContentDeliveryLayerNode-DhtNode', () => { otherDiscoveryLayerNodes[i].joinDht([entrypointDescriptor]) })) await Promise.all(otherContentDeliveryLayerNodes.map((node) => - waitForCondition(() => node.getNeighbors().length >= 4, 10000) + until(() => node.getNeighbors().length >= 4, 10000) )) const avg = otherContentDeliveryLayerNodes.reduce((acc, curr) => { @@ -138,9 +138,9 @@ describe('ContentDeliveryLayerNode-DhtNode', () => { logger.info(`AVG Number of neighbors: ${avg}`) await Promise.all(otherContentDeliveryLayerNodes.map((node) => - waitForCondition(() => node.getOutgoingHandshakeCount() === 0) + until(() => node.getOutgoingHandshakeCount() === 0) )) - await waitForCondition(() => { + await until(() => { let mismatchCounter = 0 otherContentDeliveryLayerNodes.forEach((node) => { const nodeId = node.getOwnNodeId() diff --git a/packages/trackerless-network/test/integration/ContentDeliveryManager.test.ts b/packages/trackerless-network/test/integration/ContentDeliveryManager.test.ts index 2f43530b37..5e7ccd90de 100644 --- a/packages/trackerless-network/test/integration/ContentDeliveryManager.test.ts +++ b/packages/trackerless-network/test/integration/ContentDeliveryManager.test.ts @@ -3,7 +3,7 @@ import { Simulator, SimulatorTransport } from '@streamr/dht' -import { StreamPartIDUtils, waitForCondition, waitForEvent3, wait } from '@streamr/utils' +import { StreamPartIDUtils, until, waitForEvent3, wait } from '@streamr/utils' import { ContentDeliveryManager, Events } from '../../src/logic/ContentDeliveryManager' import { ControlLayerNode } from '../../src/logic/ControlLayerNode' import { createMockPeerDescriptor, createStreamMessage } from '../utils/utils' @@ -84,8 +84,8 @@ describe('ContentDeliveryManager', () => { it('Joining stream', async () => { manager1.joinStreamPart(STREAM_PART_ID) manager2.joinStreamPart(STREAM_PART_ID) - await waitForCondition(() => manager1.getNeighbors(STREAM_PART_ID).length === 1) - await waitForCondition(() => manager2.getNeighbors(STREAM_PART_ID).length === 1) + await until(() => manager1.getNeighbors(STREAM_PART_ID).length === 1) + await until(() => manager2.getNeighbors(STREAM_PART_ID).length === 1) expect(manager1.getNeighbors(STREAM_PART_ID).length).toEqual(1) expect(manager2.getNeighbors(STREAM_PART_ID).length).toEqual(1) }) @@ -93,8 +93,8 @@ describe('ContentDeliveryManager', () => { it('Publishing after joining and waiting for neighbors', async () => { manager1.joinStreamPart(STREAM_PART_ID) manager2.joinStreamPart(STREAM_PART_ID) - await waitForCondition(() => manager1.getNeighbors(STREAM_PART_ID).length === 1) - await waitForCondition(() => manager2.getNeighbors(STREAM_PART_ID).length === 1) + await until(() => manager1.getNeighbors(STREAM_PART_ID).length === 1) + await until(() => manager2.getNeighbors(STREAM_PART_ID).length === 1) await Promise.all([ waitForEvent3(manager1, 'newMessage'), manager2.broadcast(msg) @@ -110,10 +110,10 @@ describe('ContentDeliveryManager', () => { manager2.joinStreamPart(STREAM_PART_ID) manager2.joinStreamPart(streamPartId2) await Promise.all([ - waitForCondition(() => manager1.getNeighbors(STREAM_PART_ID).length === 1), - waitForCondition(() => manager2.getNeighbors(STREAM_PART_ID).length === 1), - waitForCondition(() => manager1.getNeighbors(streamPartId2).length === 1), - waitForCondition(() => manager2.getNeighbors(streamPartId2).length === 1) + until(() => manager1.getNeighbors(STREAM_PART_ID).length === 1), + until(() => manager2.getNeighbors(STREAM_PART_ID).length === 1), + until(() => manager1.getNeighbors(streamPartId2).length === 1), + until(() => manager2.getNeighbors(streamPartId2).length === 1) ]) const msg2 = createStreamMessage( JSON.stringify({ hello: 'WORLD' }), @@ -132,19 +132,19 @@ describe('ContentDeliveryManager', () => { manager1.joinStreamPart(STREAM_PART_ID) manager2.joinStreamPart(STREAM_PART_ID) await Promise.all([ - waitForCondition(() => manager1.getNeighbors(STREAM_PART_ID).length === 1), - waitForCondition(() => manager2.getNeighbors(STREAM_PART_ID).length === 1) + until(() => manager1.getNeighbors(STREAM_PART_ID).length === 1), + until(() => manager2.getNeighbors(STREAM_PART_ID).length === 1) ]) await manager2.leaveStreamPart(STREAM_PART_ID) - await waitForCondition(() => manager1.getNeighbors(STREAM_PART_ID).length === 0) + await until(() => manager1.getNeighbors(STREAM_PART_ID).length === 0) }) it('RTTs are updated for node info', async () => { manager1.joinStreamPart(STREAM_PART_ID) manager2.joinStreamPart(STREAM_PART_ID) await Promise.all([ - waitForCondition(() => manager1.getNeighbors(STREAM_PART_ID).length === 1), - waitForCondition(() => manager2.getNeighbors(STREAM_PART_ID).length === 1) + until(() => manager1.getNeighbors(STREAM_PART_ID).length === 1), + until(() => manager2.getNeighbors(STREAM_PART_ID).length === 1) ]) // Wait for RTTs to be updated await wait(500) diff --git a/packages/trackerless-network/test/integration/ContentDeliveryRpcRemote.test.ts b/packages/trackerless-network/test/integration/ContentDeliveryRpcRemote.test.ts index 13cf170b07..42899773a8 100644 --- a/packages/trackerless-network/test/integration/ContentDeliveryRpcRemote.test.ts +++ b/packages/trackerless-network/test/integration/ContentDeliveryRpcRemote.test.ts @@ -5,7 +5,7 @@ import { Simulator, SimulatorTransport } from '@streamr/dht' -import { StreamPartIDUtils, waitForCondition } from '@streamr/utils' +import { StreamPartIDUtils, until } from '@streamr/utils' import { ContentDeliveryRpcRemote } from '../../src/logic/ContentDeliveryRpcRemote' import { Empty } from '../../generated/google/protobuf/empty' import { @@ -89,12 +89,12 @@ describe('ContentDeliveryRpcRemote', () => { ) await rpcRemote.sendStreamMessage(msg) - await waitForCondition(() => recvCounter === 1) + await until(() => recvCounter === 1) }) it('leaveNotice', async () => { rpcRemote.leaveStreamPartNotice(StreamPartIDUtils.parse('test#0'), false) - await waitForCondition(() => recvCounter === 1) + await until(() => recvCounter === 1) }) }) diff --git a/packages/trackerless-network/test/integration/NetworkNode.test.ts b/packages/trackerless-network/test/integration/NetworkNode.test.ts index 38087130ac..e571fca400 100644 --- a/packages/trackerless-network/test/integration/NetworkNode.test.ts +++ b/packages/trackerless-network/test/integration/NetworkNode.test.ts @@ -1,6 +1,6 @@ import { PeerDescriptor, Simulator, SimulatorTransport } from '@streamr/dht' import { randomUserId } from '@streamr/test-utils' -import { StreamPartIDUtils, hexToBinary, toUserIdRaw, utf8ToBinary, waitForCondition } from '@streamr/utils' +import { StreamPartIDUtils, hexToBinary, toUserIdRaw, utf8ToBinary, until } from '@streamr/utils' import { NetworkNode, createNetworkNode } from '../../src/NetworkNode' import { ContentType, EncryptionType, SignatureType, StreamMessage } from '../../generated/packages/trackerless-network/protos/NetworkRpc' import { createMockPeerDescriptor } from '../utils/utils' @@ -92,7 +92,7 @@ describe('NetworkNode', () => { msgCount += 1 }) await node2.broadcast(streamMessage) - await waitForCondition(() => msgCount === 1) + await until(() => msgCount === 1) }) it('fetchNodeInfo', async () => { diff --git a/packages/trackerless-network/test/integration/NetworkRpc.test.ts b/packages/trackerless-network/test/integration/NetworkRpc.test.ts index a1220a4617..1922de748d 100644 --- a/packages/trackerless-network/test/integration/NetworkRpc.test.ts +++ b/packages/trackerless-network/test/integration/NetworkRpc.test.ts @@ -4,7 +4,7 @@ import { RpcCommunicator, toProtoRpcClient } from '@streamr/proto-rpc' -import { StreamPartIDUtils, waitForCondition } from '@streamr/utils' +import { StreamPartIDUtils, until } from '@streamr/utils' import { Empty } from '../../generated/google/protobuf/empty' import { RpcMessage } from '../../generated/packages/proto-rpc/protos/ProtoRpc' import { StreamMessage } from '../../generated/packages/trackerless-network/protos/NetworkRpc' @@ -47,6 +47,6 @@ describe('Network RPC', () => { randomUserId() ) await client.sendStreamMessage(msg) - await waitForCondition(() => recvCounter === 1) + await until(() => recvCounter === 1) }) }) diff --git a/packages/trackerless-network/test/integration/NetworkStack.test.ts b/packages/trackerless-network/test/integration/NetworkStack.test.ts index c72bbdcf8b..0f9a6eb7a6 100644 --- a/packages/trackerless-network/test/integration/NetworkStack.test.ts +++ b/packages/trackerless-network/test/integration/NetworkStack.test.ts @@ -1,6 +1,6 @@ import { StreamPartIDUtils, - waitForCondition + until } from '@streamr/utils' import { NetworkStack } from '../../src/NetworkStack' import { createMockPeerDescriptor, createStreamMessage } from '../utils/utils' @@ -58,7 +58,7 @@ describe('NetworkStack', () => { randomUserId() ) stack2.getContentDeliveryManager().broadcast(msg) - await waitForCondition(() => receivedMessages === 1) + await until(() => receivedMessages === 1) }) it('join and wait for neighbors', async () => { diff --git a/packages/trackerless-network/test/integration/NodeInfoRpc.test.ts b/packages/trackerless-network/test/integration/NodeInfoRpc.test.ts index 638512d5f1..d8e09e2c66 100644 --- a/packages/trackerless-network/test/integration/NodeInfoRpc.test.ts +++ b/packages/trackerless-network/test/integration/NodeInfoRpc.test.ts @@ -1,5 +1,5 @@ import { ListeningRpcCommunicator, PeerDescriptor, Simulator, SimulatorTransport } from '@streamr/dht' -import { StreamPartIDUtils, waitForCondition } from '@streamr/utils' +import { StreamPartIDUtils, until } from '@streamr/utils' import { NetworkStack } from '../../src/NetworkStack' import { NodeInfoClient } from '../../src/logic/node-info/NodeInfoClient' import { NODE_INFO_RPC_SERVICE_ID } from '../../src/logic/node-info/NodeInfoRpcLocal' @@ -72,7 +72,7 @@ describe('NetworkStack NodeInfoRpc', () => { otherStack.getContentDeliveryManager().joinStreamPart(streamPartId1) requesteStack.getContentDeliveryManager().joinStreamPart(streamPartId2) otherStack.getContentDeliveryManager().joinStreamPart(streamPartId2) - await waitForCondition(() => + await until(() => requesteStack.getContentDeliveryManager().getNeighbors(streamPartId1).length === 1 && otherStack.getContentDeliveryManager().getNeighbors(streamPartId1).length === 1 && requesteStack.getContentDeliveryManager().getNeighbors(streamPartId2).length === 1 diff --git a/packages/trackerless-network/test/integration/Propagation.test.ts b/packages/trackerless-network/test/integration/Propagation.test.ts index 79e6adba33..aea3ad4a05 100644 --- a/packages/trackerless-network/test/integration/Propagation.test.ts +++ b/packages/trackerless-network/test/integration/Propagation.test.ts @@ -1,5 +1,5 @@ import { Simulator } from '@streamr/dht' -import { StreamPartIDUtils, waitForCondition } from '@streamr/utils' +import { StreamPartIDUtils, until } from '@streamr/utils' import { range } from 'lodash' import { ContentDeliveryLayerNode } from '../../src/logic/ContentDeliveryLayerNode' import { DiscoveryLayerNode } from '../../src/logic/DiscoveryLayerNode' @@ -56,10 +56,10 @@ describe('Propagation', () => { }) it('All nodes receive messages', async () => { - await waitForCondition( + await until( () => contentDeliveryLayerNodes.every((node) => node.getNeighbors().length >= 3), 30000 ) - await waitForCondition(() => { + await until(() => { const avg = contentDeliveryLayerNodes.reduce((acc, curr) => { return acc + curr.getNeighbors().length }, 0) / contentDeliveryLayerNodes.length @@ -71,6 +71,6 @@ describe('Propagation', () => { randomUserId() ) contentDeliveryLayerNodes[0].broadcast(msg) - await waitForCondition(() => totalReceived >= NUM_OF_NODES, 10000) + await until(() => totalReceived >= NUM_OF_NODES, 10000) }, 45000) }) diff --git a/packages/trackerless-network/test/integration/joining-streams-on-offline-peers.test.ts b/packages/trackerless-network/test/integration/joining-streams-on-offline-peers.test.ts index 70d421e873..7e0fd0e31f 100644 --- a/packages/trackerless-network/test/integration/joining-streams-on-offline-peers.test.ts +++ b/packages/trackerless-network/test/integration/joining-streams-on-offline-peers.test.ts @@ -1,5 +1,5 @@ import { LatencyType, PeerDescriptor, Simulator, SimulatorTransport } from '@streamr/dht' -import { StreamPartIDUtils, waitForCondition } from '@streamr/utils' +import { StreamPartIDUtils, until } from '@streamr/utils' import { NetworkStack } from '../../src/NetworkStack' import { streamPartIdToDataKey } from '../../src/logic/ContentDeliveryManager' import { Any } from '../../generated/google/protobuf/any' @@ -76,7 +76,7 @@ describe('Joining stream parts on offline nodes', () => { node1.getContentDeliveryManager().on('newMessage', () => { messageReceived = true }) const msg = createStreamMessage(JSON.stringify({ hello: 'WORLD' }), STREAM_PART_ID, randomUserId()) node2.getContentDeliveryManager().broadcast(msg) - await waitForCondition(() => messageReceived, 40000) + await until(() => messageReceived, 40000) }, 60000) }) diff --git a/packages/trackerless-network/test/integration/stream-without-default-entrypoints.test.ts b/packages/trackerless-network/test/integration/stream-without-default-entrypoints.test.ts index 87f5f72fdf..eabbf94e7e 100644 --- a/packages/trackerless-network/test/integration/stream-without-default-entrypoints.test.ts +++ b/packages/trackerless-network/test/integration/stream-without-default-entrypoints.test.ts @@ -1,6 +1,6 @@ import { LatencyType, PeerDescriptor, Simulator, SimulatorTransport } from '@streamr/dht' import { randomUserId } from '@streamr/test-utils' -import { StreamPartIDUtils, hexToBinary, toUserIdRaw, utf8ToBinary, waitForCondition } from '@streamr/utils' +import { StreamPartIDUtils, hexToBinary, toUserIdRaw, utf8ToBinary, until } from '@streamr/utils' import { range } from 'lodash' import { NetworkNode, createNetworkNode } from '../../src/NetworkNode' import { streamPartIdToDataKey } from '../../src/logic/ContentDeliveryManager' @@ -86,7 +86,7 @@ describe('stream without default entrypoints', () => { receivedMessageCount += 1 }) await Promise.all([ - waitForCondition(() => receivedMessageCount === 1, 10000), + until(() => receivedMessageCount === 1, 10000), nodes[1].broadcast(streamMessage) ]) }) @@ -96,7 +96,7 @@ describe('stream without default entrypoints', () => { receivedMessageCount += 1 }) await Promise.all([ - waitForCondition(() => receivedMessageCount === 1, 15000), + until(() => receivedMessageCount === 1, 15000), nodes[0].join(STREAM_PART_ID), nodes[1].broadcast(streamMessage), ]) @@ -112,14 +112,14 @@ describe('stream without default entrypoints', () => { })) const nonjoinedNode = nodes[subscriberCount] await nonjoinedNode.broadcast(streamMessage) - await waitForCondition(() => receivedMessageCount === subscriberCount, 15000) + await until(() => receivedMessageCount === subscriberCount, 15000) }, 45000) it('nodes store themselves as entrypoints on streamPart if number of entrypoints is low', async () => { for (let i = 0; i < 10; i++) { await nodes[i].join(STREAM_PART_ID, { minCount: (i > 0) ? 1 : 0, timeout: 15000 }) } - await waitForCondition(async () => { + await until(async () => { const entryPointData = await nodes[15].stack.getControlLayerNode().fetchDataFromDht(streamPartIdToDataKey(STREAM_PART_ID)) return entryPointData.length >= 7 }, 15000) diff --git a/packages/trackerless-network/test/integration/streamEntryPointReplacing.test.ts b/packages/trackerless-network/test/integration/streamEntryPointReplacing.test.ts index 85b5846569..05f37606a6 100644 --- a/packages/trackerless-network/test/integration/streamEntryPointReplacing.test.ts +++ b/packages/trackerless-network/test/integration/streamEntryPointReplacing.test.ts @@ -1,5 +1,5 @@ import { LatencyType, Simulator, SimulatorTransport } from '@streamr/dht' -import { StreamPartIDUtils, waitForCondition } from '@streamr/utils' +import { StreamPartIDUtils, until } from '@streamr/utils' import { range } from 'lodash' import { NetworkStack } from '../../src/NetworkStack' import { MAX_NODE_COUNT } from '../../src/logic/PeerDescriptorStoreManager' @@ -82,7 +82,7 @@ describe('Stream Entry Points are replaced when known entry points leave streams } await Promise.all(initialNodesOnStream.map((node) => node.getContentDeliveryManager().leaveStreamPart(STREAM_PART_ID))) - await waitForCondition(() => + await until(() => laterNodesOnStream.every((node) => node.getContentDeliveryManager().getNeighbors(STREAM_PART_ID).length >= 4), 60000, 1000 ) @@ -92,6 +92,6 @@ describe('Stream Entry Points are replaced when known entry points leave streams randomUserId() ) newNodeInStream.getContentDeliveryManager().broadcast(msg) - await waitForCondition(() => receivedMessages === NUM_OF_LATER_NODES, 30000) + await until(() => receivedMessages === NUM_OF_LATER_NODES, 30000) }, 200000) }) diff --git a/packages/trackerless-network/test/unit/ContentDeliveryLayerNode.test.ts b/packages/trackerless-network/test/unit/ContentDeliveryLayerNode.test.ts index a1ea635f1c..636ced86ac 100644 --- a/packages/trackerless-network/test/unit/ContentDeliveryLayerNode.test.ts +++ b/packages/trackerless-network/test/unit/ContentDeliveryLayerNode.test.ts @@ -1,5 +1,5 @@ import { toNodeId } from '@streamr/dht' -import { StreamPartIDUtils, waitForCondition } from '@streamr/utils' +import { StreamPartIDUtils, until } from '@streamr/utils' import { ContentDeliveryLayerNode } from '../../src/logic/ContentDeliveryLayerNode' import { NodeList } from '../../src/logic/NodeList' import { createContentDeliveryLayerNode } from '../../src/logic/createContentDeliveryLayerNode' @@ -69,7 +69,7 @@ describe('ContentDeliveryLayerNode', () => { const peerDescriptor2 = createMockPeerDescriptor() discoveryLayerNode.setClosestContacts([peerDescriptor1, peerDescriptor2]) discoveryLayerNode.emit('nearbyContactAdded', peerDescriptor1) - await waitForCondition(() => nearbyNodeView.size() === 2) + await until(() => nearbyNodeView.size() === 2) expect(nearbyNodeView.get(toNodeId(peerDescriptor1))).toBeTruthy() expect(nearbyNodeView.get(toNodeId(peerDescriptor2))).toBeTruthy() }) @@ -79,7 +79,7 @@ describe('ContentDeliveryLayerNode', () => { const peerDescriptor2 = createMockPeerDescriptor() discoveryLayerNode.setRandomContacts([peerDescriptor1, peerDescriptor2]) discoveryLayerNode.emit('randomContactAdded', peerDescriptor1) - await waitForCondition(() => randomNodeView.size() === 2) + await until(() => randomNodeView.size() === 2) expect(randomNodeView.get(toNodeId(peerDescriptor1))).toBeTruthy() expect(randomNodeView.get(toNodeId(peerDescriptor2))).toBeTruthy() }) @@ -90,7 +90,7 @@ describe('ContentDeliveryLayerNode', () => { discoveryLayerNode.addNewRandomPeerToKBucket() discoveryLayerNode.setClosestContacts([peerDescriptor1, peerDescriptor2]) discoveryLayerNode.emit('nearbyContactAdded', peerDescriptor1) - await waitForCondition(() => { + await until(() => { return nearbyNodeView.size() === 3 }, 20000) expect(nearbyNodeView.get(toNodeId(peerDescriptor1))).toBeTruthy() diff --git a/packages/trackerless-network/test/unit/ContentDeliveryManager.test.ts b/packages/trackerless-network/test/unit/ContentDeliveryManager.test.ts index 9754f93b38..c82a3853bd 100644 --- a/packages/trackerless-network/test/unit/ContentDeliveryManager.test.ts +++ b/packages/trackerless-network/test/unit/ContentDeliveryManager.test.ts @@ -1,5 +1,5 @@ import { areEqualPeerDescriptors } from '@streamr/dht' -import { StreamPartIDUtils, waitForCondition } from '@streamr/utils' +import { StreamPartIDUtils, until } from '@streamr/utils' import { ContentDeliveryManager } from '../../src/logic/ContentDeliveryManager' import { ProxyDirection } from '../../generated/packages/trackerless-network/protos/NetworkRpc' import { MockControlLayerNode } from '../utils/mock/MockControlLayerNode' @@ -53,7 +53,7 @@ describe('ContentDeliveryManager', () => { it('broadcast joins stream', async () => { manager.broadcast(message) - await waitForCondition(() => manager.hasStreamPart(streamPartId)) + await until(() => manager.hasStreamPart(streamPartId)) }) }) diff --git a/packages/trackerless-network/test/unit/NeighborFinder.test.ts b/packages/trackerless-network/test/unit/NeighborFinder.test.ts index 54146f4913..423c19ac33 100644 --- a/packages/trackerless-network/test/unit/NeighborFinder.test.ts +++ b/packages/trackerless-network/test/unit/NeighborFinder.test.ts @@ -1,6 +1,6 @@ import { NeighborFinder } from '../../src/logic/neighbor-discovery/NeighborFinder' import { NodeList } from '../../src/logic/NodeList' -import { waitForCondition } from '@streamr/utils' +import { until } from '@streamr/utils' import { range } from 'lodash' import { expect } from 'expect' import { createMockContentDeliveryRpcRemote } from '../utils/utils' @@ -45,7 +45,7 @@ describe('NeighborFinder', () => { it('Finds target number of nodes', async () => { neighborFinder.start() - await waitForCondition(() => neighbors.size() >= minCount, 10000) + await until(() => neighbors.size() >= minCount, 10000) expect(neighborFinder.isRunning()).toEqual(false) }) }) diff --git a/packages/trackerless-network/test/unit/StreamPartReconnect.test.ts b/packages/trackerless-network/test/unit/StreamPartReconnect.test.ts index 28382bdd7e..c7be6f9578 100644 --- a/packages/trackerless-network/test/unit/StreamPartReconnect.test.ts +++ b/packages/trackerless-network/test/unit/StreamPartReconnect.test.ts @@ -2,7 +2,7 @@ import { PeerDescriptorStoreManager } from '../../src/logic/PeerDescriptorStoreM import { StreamPartReconnect } from '../../src/logic/StreamPartReconnect' import { MockDiscoveryLayerNode } from '../utils/mock/MockDiscoveryLayerNode' import { createFakePeerDescriptorStoreManager } from '../utils/fake/FakePeerDescriptorStoreManager' -import { waitForCondition } from '@streamr/utils' +import { until } from '@streamr/utils' describe('StreamPartReconnect', () => { @@ -24,7 +24,7 @@ describe('StreamPartReconnect', () => { await streamPartReconnect.reconnect(1000) expect(streamPartReconnect.isRunning()).toEqual(true) discoveryLayerNode.addNewRandomPeerToKBucket() - await waitForCondition(() => streamPartReconnect.isRunning() === false) + await until(() => streamPartReconnect.isRunning() === false) }) }) diff --git a/packages/utils/src/exports.ts b/packages/utils/src/exports.ts index 9d71679ebc..b59cc6a531 100644 --- a/packages/utils/src/exports.ts +++ b/packages/utils/src/exports.ts @@ -27,7 +27,7 @@ import { wait } from './wait' import { waitForEvent } from './waitForEvent' import { TimeoutError, withTimeout } from './withTimeout' import { composeAbortSignals, ComposedAbortSignal } from './composeAbortSignals' -import { waitForCondition } from './waitForCondition' +import { until } from './until' import { waitForEvent3, runAndWaitForEvents3, raceEvents3, runAndRaceEvents3, RunAndRaceEventsReturnType } from './waitForEvent3' import { withRateLimit } from './withRateLimit' import { ObservableEventEmitter } from './ObservableEventEmitter' @@ -72,7 +72,7 @@ export { toEthereumAddress, toEthereumAddressOrENSName, wait, - waitForCondition, + until, waitForEvent, withRateLimit, withTimeout, diff --git a/packages/utils/src/waitForCondition.ts b/packages/utils/src/until.ts similarity index 94% rename from packages/utils/src/waitForCondition.ts rename to packages/utils/src/until.ts index 4fc7f9da6c..ae7b69f427 100644 --- a/packages/utils/src/waitForCondition.ts +++ b/packages/utils/src/until.ts @@ -5,7 +5,7 @@ import { composeAbortSignals } from './composeAbortSignals' function throwError(userAborted: boolean, conditionFn: () => any, onTimeoutContext?: () => string): never { const action = userAborted ? 'aborted' : 'timed out' - let msg = `waitForCondition: ${action} before "${conditionFn.toString()}" became true` + let msg = `until: ${action} before "${conditionFn.toString()}" became true` if (onTimeoutContext) { msg += `\n${onTimeoutContext()}` } @@ -25,7 +25,7 @@ function throwError(userAborted: boolean, conditionFn: () => any, onTimeoutConte * conditionFn evaluates to true on a retry attempt within timeout. If timeout * is reached with conditionFn never evaluating to true, rejects. */ -export const waitForCondition = async ( +export const until = async ( conditionFn: () => (boolean | Promise), timeout = 5000, retryInterval = 100, diff --git a/packages/utils/test/Metric.test.ts b/packages/utils/test/Metric.test.ts index 0255c880f9..1314923754 100644 --- a/packages/utils/test/Metric.test.ts +++ b/packages/utils/test/Metric.test.ts @@ -1,6 +1,6 @@ import { wait } from '../src/wait' import { AverageMetric, CountMetric, LevelMetric, MetricsContext, MetricsReport, RateMetric } from '../src/Metric' -import { waitForCondition } from '../src/waitForCondition' +import { until } from '../src/until' const REPORT_INTERVAL = 100 const ONE_SECOND = 1000 @@ -59,7 +59,7 @@ describe('metrics', () => { metricThree.rate.record(2000) metricThree.rate.record(4000) - await waitForCondition(() => getReport(inputTime1) !== undefined) + await until(() => getReport(inputTime1) !== undefined) expect(getReport(inputTime1)).toMatchObject({ metricOne: { count: 7 + 2 @@ -80,7 +80,7 @@ describe('metrics', () => { metricThree.level.record(39) metricThree.rate.record(1000) - await waitForCondition(() => getReport(inputTime2) !== undefined) + await until(() => getReport(inputTime2) !== undefined) expect(getReport(inputTime2)).toMatchObject({ metricOne: { count: 3 @@ -100,7 +100,7 @@ describe('metrics', () => { context.addMetrics('foo', { bar: new CountMetric() }) - await waitForCondition(() => reports.length > 0) + await until(() => reports.length > 0) expect(reports[0]).toMatchObject({ foo: { bar: 0 diff --git a/packages/utils/test/waitForCondition.test.ts b/packages/utils/test/until.test.ts similarity index 63% rename from packages/utils/test/waitForCondition.test.ts rename to packages/utils/test/until.test.ts index c8d8f6fedd..1f0df2d576 100644 --- a/packages/utils/test/waitForCondition.test.ts +++ b/packages/utils/test/until.test.ts @@ -1,9 +1,9 @@ -import { waitForCondition } from '../src/waitForCondition' +import { until } from '../src/until' -describe('waitForCondition', () => { +describe('until', () => { describe('given conditionFn that returns boolean primitives', () => { it('resolves immediately if conditionFn returns true from the get-go', (done) => { - waitForCondition(() => true) + until(() => true) .then(done) .catch(() => done(new Error('timed out'))) }) @@ -11,15 +11,15 @@ describe('waitForCondition', () => { it('resolves eventually when conditionFn returns true', (done) => { let cbReturnValue = false setTimeout(() => cbReturnValue = true, 50) - waitForCondition(() => cbReturnValue, 5000, 10) + until(() => cbReturnValue, 5000, 10) .then(done) .catch(() => done(new Error('timed out'))) }) it('rejects if conditionFn does not return true within timeout', (done) => { const pollCb = () => false - waitForCondition(pollCb, 50, 5).catch((err) => { - expect(err.message).toEqual('waitForCondition: timed out before "() => false" became true') + until(pollCb, 50, 5).catch((err) => { + expect(err.message).toEqual('until: timed out before "() => false" became true') done() }) }) @@ -29,8 +29,8 @@ describe('waitForCondition', () => { setTimeout(() => { abortController.abort() }, 100) - waitForCondition(() => false, 5000, 10, abortController.signal).catch((err) => { - expect(err.message).toEqual('waitForCondition: aborted before "() => false" became true') + until(() => false, 5000, 10, abortController.signal).catch((err) => { + expect(err.message).toEqual('until: aborted before "() => false" became true') done() }) }) @@ -39,7 +39,7 @@ describe('waitForCondition', () => { describe('given conditionFn that returns promisified booleans (i.e. Promise)', () => { it('resolves immediately if conditionFn returns (promisified) true from the get-go', async () => { const fn = jest.fn().mockResolvedValue(true) - await waitForCondition(fn) + await until(fn) expect(fn).toBeCalledTimes(1) }) @@ -47,19 +47,19 @@ describe('waitForCondition', () => { const fn = jest.fn() .mockResolvedValueOnce(false) .mockResolvedValueOnce(true) - await waitForCondition(fn) + await until(fn) expect(fn).toBeCalledTimes(2) }) it('rejects if conditionFn keeps returning (promisified) false within timeout', async () => { const fn = () => Promise.resolve(false) - await expect(waitForCondition(fn, 50, 10)).rejects - .toThrow('waitForCondition: timed out before "() => Promise.resolve(false)" became true') + await expect(until(fn, 50, 10)).rejects + .toThrow('until: timed out before "() => Promise.resolve(false)" became true') }) it('rejects immediately if conditionFn returns rejected promise from the get-go', async () => { const error = new Error('mock') - await expect(waitForCondition(() => Promise.reject(error))).rejects.toThrow(error) + await expect(until(() => Promise.reject(error))).rejects.toThrow(error) }) it('rejects eventually if conditionFn returns rejected promise and no (promisifed) true was encountered', async () => { @@ -67,15 +67,15 @@ describe('waitForCondition', () => { const fn = jest.fn() .mockResolvedValueOnce(false) .mockRejectedValueOnce(error) - await expect(waitForCondition(fn)) + await expect(until(fn)) .rejects .toThrow(error) }) it('rejects if conditionFn returns promise that does not settle within timeout', async () => { - await expect(waitForCondition(() => new Promise(() => {}), 100, 10)) + await expect(until(() => new Promise(() => {}), 100, 10)) .rejects - .toThrow('waitForCondition: timed out before "() => new Promise(() => { })" became true') + .toThrow('until: timed out before "() => new Promise(() => { })" became true') }) it('rejects if conditionFn does not return true before abort signalled', (done) => { @@ -83,8 +83,8 @@ describe('waitForCondition', () => { setTimeout(() => { abortController.abort() }, 100) - waitForCondition(() => Promise.resolve(false), 5000, 10, abortController.signal).catch((err) => { - expect(err.message).toEqual('waitForCondition: aborted before "() => Promise.resolve(false)" became true') + until(() => Promise.resolve(false), 5000, 10, abortController.signal).catch((err) => { + expect(err.message).toEqual('until: aborted before "() => Promise.resolve(false)" became true') done() }) }) @@ -93,16 +93,16 @@ describe('waitForCondition', () => { it('rejects immediately if given pre-aborted signal', (done) => { const abortController = new AbortController() abortController.abort() - waitForCondition(() => true, 5000, 1, abortController.signal).catch((err) => { - expect(err.message).toEqual('waitForCondition: aborted before "() => true" became true') + until(() => true, 5000, 1, abortController.signal).catch((err) => { + expect(err.message).toEqual('until: aborted before "() => true" became true') done() }) }) it('can provide contextual information on rejection', (done) => { const pollCb = () => false - waitForCondition(pollCb, 50, 5, undefined, () => 'a was 5, expected 10').catch((err) => { - expect(err.message).toEqual('waitForCondition: timed out before "() => false" became true' + + until(pollCb, 50, 5, undefined, () => 'a was 5, expected 10').catch((err) => { + expect(err.message).toEqual('until: timed out before "() => false" became true' + '\na was 5, expected 10') done() }) From 85aee1493e054f2cf64b16f7ad7eb60a24a9324c Mon Sep 17 00:00:00 2001 From: Teo Gebhard Date: Mon, 11 Nov 2024 11:56:34 +0200 Subject: [PATCH 2/4] rm function --- packages/sdk/src/contracts/StreamRegistry.ts | 4 +- packages/sdk/src/utils/promises.ts | 51 +----------------- .../end-to-end/StorageNodeRegistry.test.ts | 3 +- .../test/end-to-end/StreamRegistry.test.ts | 5 +- .../integration/GroupKeyPersistence.test.ts | 3 +- packages/sdk/test/unit/promises.test.ts | 54 +------------------ 6 files changed, 9 insertions(+), 111 deletions(-) diff --git a/packages/sdk/src/contracts/StreamRegistry.ts b/packages/sdk/src/contracts/StreamRegistry.ts index 990304fefe..b056e4be95 100644 --- a/packages/sdk/src/contracts/StreamRegistry.ts +++ b/packages/sdk/src/contracts/StreamRegistry.ts @@ -11,7 +11,8 @@ import { isEthereumAddressUserId, toEthereumAddress, toStreamID, - toUserId + toUserId, + until } from '@streamr/utils' import { ContractTransactionResponse } from 'ethers' import { intersection } from 'lodash' @@ -43,7 +44,6 @@ import { import { filter, map } from '../utils/GeneratorUtils' import { LoggerFactory } from '../utils/LoggerFactory' import { CacheAsyncFn, CacheAsyncFnType } from '../utils/caches' -import { until } from '../utils/promises' import { ChainEventPoller } from './ChainEventPoller' import { ContractFactory } from './ContractFactory' import { ObservableContract, initContractEventGateway, waitForTx } from './contract' diff --git a/packages/sdk/src/utils/promises.ts b/packages/sdk/src/utils/promises.ts index b1a41a7eea..37b06a355c 100644 --- a/packages/sdk/src/utils/promises.ts +++ b/packages/sdk/src/utils/promises.ts @@ -1,7 +1,6 @@ +import { Defer } from '@streamr/utils' import pLimit from 'p-limit' import pThrottle from 'p-throttle' -import { Defer, wait } from '@streamr/utils' -import { MaybeAsync } from '../types' /** * Returns a function that executes with limited concurrency. @@ -177,54 +176,6 @@ export async function pTimeout(promise: Promise, ...args: pTimeoutArgs): P }) } -// TODO use streamr-test-utils#until instead (when streamr-test-utils is no longer a test-only dependency) -/** - * Wait until a condition is true - * @param condition - wait until this callback function returns true - * @param timeOutMs - stop waiting after that many milliseconds, -1 for disable - * @param pollingIntervalMs - check condition between so many milliseconds - * @param failedMsgFn - append the string return value of this getter function to the error message, if given - * @return the (last) truthy value returned by the condition function - */ -export async function until( - condition: MaybeAsync<() => boolean>, - timeOutMs = 10000, - pollingIntervalMs = 100, - failedMsgFn?: () => string -): Promise { - // condition could as well return any instead of boolean, could be convenient - // sometimes if waiting until a value is returned. Maybe change if such use - // case emerges. - const err = new Error(`Timeout after ${timeOutMs} milliseconds`) - let isTimedOut = false - let t!: ReturnType - if (timeOutMs > 0) { - t = setTimeout(() => { isTimedOut = true }, timeOutMs) - } - - try { - // Promise wrapped condition function works for normal functions just the same as Promises - let wasDone = false - while (!wasDone && !isTimedOut) { - wasDone = await Promise.resolve().then(condition) - if (!wasDone && !isTimedOut) { - await wait(pollingIntervalMs) - } - } - - if (isTimedOut) { - if (failedMsgFn) { - err.message += ` ${failedMsgFn()}` - } - throw err - } - - return wasDone - } finally { - clearTimeout(t) - } -} - // TODO better type annotations export const withThrottling = (fn: (...args: any[]) => Promise, maxInvocationsPerSecond: number): ((...args: any[]) => Promise) => { const throttler = pThrottle({ diff --git a/packages/sdk/test/end-to-end/StorageNodeRegistry.test.ts b/packages/sdk/test/end-to-end/StorageNodeRegistry.test.ts index 4b070a4327..b0d9f08fd9 100644 --- a/packages/sdk/test/end-to-end/StorageNodeRegistry.test.ts +++ b/packages/sdk/test/end-to-end/StorageNodeRegistry.test.ts @@ -1,11 +1,12 @@ import 'reflect-metadata' + import { Wallet } from 'ethers' import { fetchPrivateKeyWithGas, randomEthereumAddress } from '@streamr/test-utils' import { DOCKER_DEV_STORAGE_NODE } from '../../src/ConfigTest' import { Stream } from '../../src/Stream' import { StreamrClient } from '../../src/StreamrClient' -import { until } from '../../src/utils/promises' import { createTestStream, createTestClient } from '../test-utils/utils' +import { until } from '@streamr/utils' const TEST_TIMEOUT = 30 * 1000 diff --git a/packages/sdk/test/end-to-end/StreamRegistry.test.ts b/packages/sdk/test/end-to-end/StreamRegistry.test.ts index 1671867fd1..1a1142edde 100644 --- a/packages/sdk/test/end-to-end/StreamRegistry.test.ts +++ b/packages/sdk/test/end-to-end/StreamRegistry.test.ts @@ -6,7 +6,6 @@ import { Wallet } from 'ethers' import { CONFIG_TEST } from '../../src/ConfigTest' import { Stream } from '../../src/Stream' import { StreamrClient } from '../../src/StreamrClient' -import { until as until_ } from '../../src/utils/promises' import { createRelativeTestStreamId, createTestStream } from '../test-utils/utils' const TIMEOUT = 20000 @@ -242,7 +241,7 @@ describe('StreamRegistry', () => { await createdStream.setMetadata({ description }) - await until_(async () => { + await until(async () => { try { return (await client.getStream(createdStream.id)).getMetadata().description === createdStream.getMetadata().description } catch { @@ -262,7 +261,7 @@ describe('StreamRegistry', () => { const props = { id: createRelativeTestStreamId(module) } const stream = await client.createStream(props) await client.deleteStream(stream.id) - await until_(async () => { + await until(async () => { try { await client.getStream(stream.id) return false diff --git a/packages/sdk/test/integration/GroupKeyPersistence.test.ts b/packages/sdk/test/integration/GroupKeyPersistence.test.ts index 80b3c07627..18adcddad6 100644 --- a/packages/sdk/test/integration/GroupKeyPersistence.test.ts +++ b/packages/sdk/test/integration/GroupKeyPersistence.test.ts @@ -1,14 +1,13 @@ import 'reflect-metadata' import { fastPrivateKey } from '@streamr/test-utils' -import { collect, toStreamPartID } from '@streamr/utils' +import { collect, toStreamPartID, until } from '@streamr/utils' import { Message } from '../../src/Message' import { Stream } from '../../src/Stream' import { StreamrClient } from '../../src/StreamrClient' import { GroupKey } from '../../src/encryption/GroupKey' import { StreamPermission } from '../../src/permission' import { StreamMessageType } from '../../src/protocol/StreamMessage' -import { until } from '../../src/utils/promises' import { FakeEnvironment } from '../test-utils/fake/FakeEnvironment' import { FakeStorageNode } from '../test-utils/fake/FakeStorageNode' import { getPublishTestStreamMessages } from '../test-utils/publish' diff --git a/packages/sdk/test/unit/promises.test.ts b/packages/sdk/test/unit/promises.test.ts index f061516e46..f1277dc236 100644 --- a/packages/sdk/test/unit/promises.test.ts +++ b/packages/sdk/test/unit/promises.test.ts @@ -1,61 +1,9 @@ import { wait } from '@streamr/utils' -import { pOnce, pLimitFn, pOne, until } from '../../src/utils/promises' +import { pOnce, pLimitFn, pOne } from '../../src/utils/promises' import { CacheAsyncFn } from '../../src/utils/caches' const WAIT_TIME = 25 -describe('until', () => { - it('works with sync true', async () => { - const condition = jest.fn(() => true) - await until(condition) - expect(condition).toHaveBeenCalledTimes(1) - }) - - it('works with async true', async () => { - const condition = jest.fn(async () => true) - await until(condition) - expect(condition).toHaveBeenCalledTimes(1) - }) - - it('works with sync false -> true', async () => { - let calls = 0 - const condition = jest.fn(() => { - calls += 1 - return calls > 1 - }) - await until(condition) - expect(condition).toHaveBeenCalledTimes(2) - }) - - it('works with sync false -> true', async () => { - let calls = 0 - const condition = jest.fn(async () => { - calls += 1 - return calls > 1 - }) - await until(condition) - expect(condition).toHaveBeenCalledTimes(2) - }) - - it('can time out', async () => { - const condition = jest.fn(() => false) - await expect(async () => { - await until(condition, 100) - }).rejects.toThrow('Timeout') - expect(condition).toHaveBeenCalled() - }) - - it('can set interval', async () => { - const condition = jest.fn(() => false) - await expect(async () => { - await until(condition, 100, 20) - }).rejects.toThrow('Timeout') - expect(condition.mock.calls.length).toBeLessThan(7) - // ideally it should be 5. - expect(condition.mock.calls.length).toBeGreaterThan(4) - }) -}) - describe('pLimitFn', () => { it('adopts type of wrapped function', async () => { // actually checking via ts-expect-error From 291dfb6c744784dccc9fcfcf05f9a13208728991 Mon Sep 17 00:00:00 2001 From: Teo Gebhard Date: Mon, 11 Nov 2024 15:58:34 +0200 Subject: [PATCH 3/4] rm function --- packages/test-utils/src/index.ts | 34 -------------------------------- 1 file changed, 34 deletions(-) diff --git a/packages/test-utils/src/index.ts b/packages/test-utils/src/index.ts index b190ed261e..6586d01313 100644 --- a/packages/test-utils/src/index.ts +++ b/packages/test-utils/src/index.ts @@ -88,40 +88,6 @@ export const runAndRaceEvents = async ( return runAndWait(operations, waitedEvents, timeout, Promise.race.bind(Promise)) } -/** - * Run functions and wait conditions to become true by re-evaluating every `retryInterval` milliseconds. Returns a promise created with Promise.all() - * and until() calls. Calls the functions after creating the promise. - * - * @param operations function(s) to call - * @param conditions condition(s) to be evaluated; condition functions should return boolean or Promise and have - * no side-effects. - * @param timeout amount of time in milliseconds to wait for - * @param retryInterval how often, in milliseconds, to re-evaluate condition - * @param onTimeoutContext evaluated only on timeout. Used to associate human-friendly textual context to error. - * @returns {Promise} resolves immediately if - * conditions evaluate to true on a retry attempt within timeout. If timeout - * is reached with conditionFn never evaluating to true, rejects. - */ -export const runAnduntils = async ( - operations: (() => void) | ((() => void)[]), - conditions: (() => (boolean | Promise)) | (() => (boolean | Promise)) [], - timeout = 5000, - retryInterval = 100, - onTimeoutContext?: () => string -): Promise => { - const ops = Array.isArray(operations) ? operations : [operations] - const conds = Array.isArray(conditions) ? conditions : [conditions] - const promise = Promise.all(conds.map((condition) => until( - condition, - timeout, - retryInterval, - undefined, - onTimeoutContext - ))) - ops.forEach((op) => { op() }) - return promise -} - /** * Collect events emitted by an emitter into an array. * From bc8f8b3448d157d35ef1b2dd569a340636985ef5 Mon Sep 17 00:00:00 2001 From: Teo Gebhard Date: Mon, 11 Nov 2024 17:29:43 +0200 Subject: [PATCH 4/4] fix merge e7560db --- packages/sdk/src/contracts/StreamRegistry.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/packages/sdk/src/contracts/StreamRegistry.ts b/packages/sdk/src/contracts/StreamRegistry.ts index 1774957571..f4c40cfd10 100644 --- a/packages/sdk/src/contracts/StreamRegistry.ts +++ b/packages/sdk/src/contracts/StreamRegistry.ts @@ -23,6 +23,7 @@ import { RpcProviderSource } from '../RpcProviderSource' import { Stream } from '../Stream' import { StreamIDBuilder } from '../StreamIDBuilder' import { StreamMetadata, parseMetadata } from '../StreamMetadata' +import { StreamrClient } from '../StreamrClient' import { StreamrClientError } from '../StreamrClientError' import type { StreamRegistryV5 as StreamRegistryContract } from '../ethereumArtifacts/StreamRegistryV5' import StreamRegistryArtifact from '../ethereumArtifacts/StreamRegistryV5Abi.json' @@ -41,16 +42,13 @@ import { isPublicPermissionQuery, streamPermissionToSolidityType } from '../permission' +import { CachingMap } from '../utils/CachingMap' import { filter, map } from '../utils/GeneratorUtils' import { LoggerFactory } from '../utils/LoggerFactory' -import { CacheAsyncFn, CacheAsyncFnType } from '../utils/caches' -import { CachingMap } from '../utils/CachingMap' -import { until } from '../utils/promises' import { ChainEventPoller } from './ChainEventPoller' import { ContractFactory } from './ContractFactory' import { ObservableContract, initContractEventGateway, waitForTx } from './contract' import { InternalSearchStreamsPermissionFilter, SearchStreamsOrderBy, searchStreams as _searchStreams } from './searchStreams' -import { StreamrClient } from '../StreamrClient' /* * On-chain registry of stream metadata and permissions.