reactor.core.scheduler.Schedulers Java Examples

The following examples show how to use reactor.core.scheduler.Schedulers. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MonoSubscriberTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void issue1719() {
	for (int i = 0; i < 10000; i++) {
		Map<String, Mono<Integer>> input = new HashMap<>();
		input.put("one", Mono.just(1));
		input.put("two", Mono.create(
				(sink) -> Schedulers.boundedElastic().schedule(() -> sink.success(2))));
		input.put("three", Mono.just(3));
		int sum = Flux.fromIterable(input.entrySet())
		              .flatMap((entry) -> Mono.zip(Mono.just(entry.getKey()), entry.getValue()))
		              .collectMap(Tuple2::getT1, Tuple2::getT2).map((items) -> {
					AtomicInteger result = new AtomicInteger();
					items.values().forEach(result::addAndGet);
					return result.get();
				}).block();
		assertThat(sum).as("Iteration %s", i).isEqualTo(6);
	}
}
 
Example #2
Source File: RabbitMQTerminationSubscriber.java    From james-project with Apache License 2.0 6 votes vote down vote up
public void start() {
    sender.declareExchange(ExchangeSpecification.exchange(EXCHANGE_NAME)).block();
    sender.declare(QueueSpecification.queue(queueName).durable(false).autoDelete(true)).block();
    sender.bind(BindingSpecification.binding(EXCHANGE_NAME, ROUTING_KEY, queueName)).block();
    sendQueue = UnicastProcessor.create();
    sendQueueHandle = sender
        .send(sendQueue)
        .subscribeOn(Schedulers.elastic())
        .subscribe();

    listenerReceiver = receiverProvider.createReceiver();
    listener = DirectProcessor.create();
    listenQueueHandle = listenerReceiver
        .consumeAutoAck(queueName)
        .subscribeOn(Schedulers.elastic())
        .map(this::toEvent)
        .handle(publishIfPresent())
        .subscribe(listener::onNext);
}
 
Example #3
Source File: ReconnectMonoTests.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldTimeoutRetryWithVirtualTime() {
  // given
  final int minBackoff = 1;
  final int maxBackoff = 5;
  final int timeout = 10;

  // then
  StepVerifier.withVirtualTime(
          () ->
              Mono.<String>error(new RuntimeException("Something went wrong"))
                  .retryWhen(
                      Retry.backoff(Long.MAX_VALUE, Duration.ofSeconds(minBackoff))
                          .doAfterRetry(onRetry())
                          .maxBackoff(Duration.ofSeconds(maxBackoff)))
                  .timeout(Duration.ofSeconds(timeout))
                  .as(m -> new ReconnectMono<>(m, onExpire(), onValue()))
                  .subscribeOn(Schedulers.elastic()))
      .expectSubscription()
      .thenAwait(Duration.ofSeconds(timeout))
      .expectError(TimeoutException.class)
      .verify(Duration.ofSeconds(timeout));

  Assertions.assertThat(received).isEmpty();
  Assertions.assertThat(expired).isEmpty();
}
 
Example #4
Source File: SimpleFifoPoolTest.java    From reactor-pool with Apache License 2.0 6 votes vote down vote up
@Test
void defaultThreadDeliveringWhenNoElementsButNotFull() throws InterruptedException {
    AtomicReference<String> threadName = new AtomicReference<>();
    Scheduler acquireScheduler = Schedulers.newSingle("acquire");
    PoolConfig<PoolableTest> testConfig = poolableTestConfig(0, 1,
            Mono.fromCallable(PoolableTest::new)
                .subscribeOn(Schedulers.newParallel("poolable test allocator")));
    SimpleFifoPool<PoolableTest> pool = new SimpleFifoPool<>(testConfig);

    //the pool is started with no elements, and has capacity for 1
    //we prepare to acquire, which would allocate the element
    Mono<PooledRef<PoolableTest>> borrower = pool.acquire();
    CountDownLatch latch = new CountDownLatch(1);

    //we actually request the acquire from a separate thread, but the allocation also happens in a dedicated thread
    //we look at which thread the element was delivered from
    acquireScheduler.schedule(() -> borrower.subscribe(v -> threadName.set(Thread.currentThread().getName()), e -> latch.countDown(), latch::countDown));
    latch.await(1, TimeUnit.SECONDS);

    assertThat(threadName.get())
            .startsWith("poolable test allocator-");
}
 
Example #5
Source File: FluxSubscribeOnTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void forceScheduledRequests() {
	Flux<Integer> test = Flux.<Integer>create(sink -> {
		for (int i = 1; i < 1001; i++) {
			sink.next(i);
			try {
				Thread.sleep(1);
			}
			catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		sink.complete();
	}, DROP)
			.map(Function.identity())
			.subscribeOn(Schedulers.single(), true)
			.publishOn(Schedulers.boundedElastic());

	AtomicInteger count = new AtomicInteger();
	StepVerifier.create(test)
	            .thenConsumeWhile(t -> count.incrementAndGet() != -1)
	            .expectComplete()
	            .verify(Duration.ofSeconds(5));

	assertThat(count.get()).isEqualTo(Queues.SMALL_BUFFER_SIZE);
}
 
Example #6
Source File: FluxOnBackpressureBufferTimeoutTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void scanSubscriber() {
	CoreSubscriber<String> actual = new LambdaSubscriber<>(null, null, null, null);
	BackpressureBufferTimeoutSubscriber<String> test = new BackpressureBufferTimeoutSubscriber<>(actual, Duration.ofSeconds(1), Schedulers.immediate(), 123, v -> {});
	Subscription s = Operators.emptySubscription();
	test.onSubscribe(s);

	assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(s);
	assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual);

	assertThat(test.scan(Scannable.Attr.REQUESTED_FROM_DOWNSTREAM)).isEqualTo(Long.MAX_VALUE);
	assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse();
	assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse();

	test.offer("foo");
	test.offer("bar");
	assertThat(test.scan(Scannable.Attr.BUFFERED)).isEqualTo(2);

	test.error = new RuntimeException("boom");
	assertThat(test.scan(Scannable.Attr.ERROR)).isSameAs(test.error);

	assertThat(test.scan(Scannable.Attr.PREFETCH)).isEqualTo(Integer.MAX_VALUE);
	assertThat(test.scan(Scannable.Attr.DELAY_ERROR)).isFalse();
	assertThat(test.scan(Scannable.Attr.RUN_ON)).isSameAs(Schedulers.immediate());
}
 
Example #7
Source File: DefaultBackingServicesProvisionService.java    From spring-cloud-app-broker with Apache License 2.0 6 votes vote down vote up
@Override
public Flux<String> deleteServiceInstance(List<BackingService> backingServices) {
	return Flux.fromIterable(backingServices)
		.parallel()
		.runOn(Schedulers.parallel())
		.flatMap(deployerClient::deleteServiceInstance)
		.sequential()
		.doOnRequest(l -> {
			LOG.info("Deleting backing services");
			LOG.debug(BACKINGSERVICES_LOG_TEMPLATE, backingServices);
		})
		.doOnComplete(() -> {
			LOG.info("Finish deleting backing services");
			LOG.debug(BACKINGSERVICES_LOG_TEMPLATE, backingServices);
		})
		.doOnError(e -> LOG.error(String.format("Error deleting backing services. error=%s", e.getMessage()), e));
}
 
Example #8
Source File: MonoExpandTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void depthEmitCancelRace() {
	for (int i = 0; i < 1000; i++) {

		final TestPublisher<Integer> pp = TestPublisher.create();

		final AssertSubscriber<Integer> ts = AssertSubscriber.create(1);

		Mono.just(0)
		    .expandDeep(it -> pp)
		    .subscribe(ts);

		Runnable r1 = () -> pp.next(1);
		Runnable r2 = ts::cancel;

		RaceTestUtils.race(r1, r2, Schedulers.single());
	}
}
 
Example #9
Source File: FluxSubscribeOnValueTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void scanMainSubscriber() {
    CoreSubscriber<Integer> actual = new LambdaSubscriber<>(null, e -> {}, null, null);
    FluxSubscribeOnValue.ScheduledScalar<Integer> test =
    		new FluxSubscribeOnValue.ScheduledScalar<Integer>(actual, 1, Schedulers.single());

    assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual);
    assertThat(test.scan(Scannable.Attr.BUFFERED)).isEqualTo(1);

    assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse();
    test.future = FluxSubscribeOnValue.ScheduledScalar.FINISHED;
    assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue();

    assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse();
    test.future = OperatorDisposables.DISPOSED;
    assertThat(test.scan(Scannable.Attr.CANCELLED)).isTrue();

    assertThat(test.scan(Scannable.Attr.RUN_ON)).isSameAs(Schedulers.single());
}
 
Example #10
Source File: FluxExpandTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void breadthFirstAsync() {
	Node root = createTest();

	StepVerifier.create(Flux.just(root)
	                        .expand(v -> Flux.fromIterable(v.children).subscribeOn(Schedulers.boundedElastic()))
	                        .map(v -> v.name))
	            .expectNext(
			            "root",
			            "1", "2", "3", "4",
			            "11", "21", "22", "31", "32", "33", "41", "42", "43", "44",
			            "221", "321", "331", "332", "421", "431", "432", "441", "442", "443",
			            "3321", "4321", "4421", "4431", "4432"
	            )
	            .expectComplete()
	            .verify(Duration.ofSeconds(5));
}
 
Example #11
Source File: FluxTests.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void consistentMultithreadingWithPartition() throws InterruptedException {
	Scheduler supplier1 = Schedulers.newParallel("groupByPool", 2);
	Scheduler supplier2 = Schedulers.newParallel("partitionPool", 5);

	CountDownLatch latch = new CountDownLatch(10);

	/*Disposable c = */Flux.range(1, 10)
	                     .groupBy(n -> n % 2 == 0)
	                     .flatMap(stream -> stream.publishOn(supplier1)
	                                            .log("groupBy-" + stream.key()))
	                     .parallel(5)
	                     .runOn(supplier2)
	                     .sequential()
	                     .publishOn(asyncGroup)
	                     .log("join")
	                     .subscribe(t -> {
		                   latch.countDown();
	                   });


	latch.await(30, TimeUnit.SECONDS);
	assertThat("Not totally dispatched: " + latch.getCount(), latch.getCount() == 0);
	supplier1.dispose();
	supplier2.dispose();
}
 
Example #12
Source File: DefaultLocalSchedulerTest.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
@Test
public void testTimeout() throws Exception {
    ScheduleReference reference = localScheduler.scheduleMono(
            scheduleDescriptor.toBuilder().withName("testTimeout").build(),
            tick -> Mono.never(),
            Schedulers.parallel()
    );

    expectScheduleAdded(reference);
    expectScheduleUpdateEvent(SchedulingState.Running);
    expectScheduleUpdateEvent(SchedulingState.Failed);

    // Replacement
    expectScheduleUpdateEvent(SchedulingState.Waiting);

    assertThat(reference.getSchedule().getCompletedActions()).hasSize(1);
    ScheduledAction failedAction = reference.getSchedule().getCompletedActions().get(0);
    assertThat(failedAction.getStatus().getState()).isEqualTo(SchedulingState.Failed);
    assertThat(failedAction.getStatus().getError().get()).isInstanceOf(TimeoutException.class);
}
 
Example #13
Source File: SimpleFifoPoolTest.java    From reactor-pool with Apache License 2.0 6 votes vote down vote up
@Test
void defaultThreadDeliveringWhenHasElements() throws InterruptedException {
    AtomicReference<String> threadName = new AtomicReference<>();
    Scheduler acquireScheduler = Schedulers.newSingle("acquire");
    PoolConfig<PoolableTest> testConfig = poolableTestConfig(1, 1,
            Mono.fromCallable(PoolableTest::new)
                .subscribeOn(Schedulers.newParallel("poolable test allocator")));
    SimpleFifoPool<PoolableTest> pool = new SimpleFifoPool<>(testConfig);
    pool.warmup().block();

    //the pool is started and warmed up with one available element
    //we prepare to acquire it
    Mono<PooledRef<PoolableTest>> borrower = pool.acquire();
    CountDownLatch latch = new CountDownLatch(1);

    //we actually request the acquire from a separate thread and see from which thread the element was delivered
    acquireScheduler.schedule(() -> borrower.subscribe(v -> threadName.set(Thread.currentThread().getName()), e -> latch.countDown(), latch::countDown));
    latch.await(1, TimeUnit.SECONDS);

    assertThat(threadName.get())
            .startsWith("acquire-");
}
 
Example #14
Source File: FluxSubscribeOnCallableTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void normalBackpressuredFused() {
	StepVerifier.withVirtualTime(() -> Mono.fromCallable(() -> 1)
	                                       .flux()
	                                       .subscribeOn(
			Schedulers.single()), 0)
	            .expectFusion(Fuseable.ASYNC)
	            .thenAwait()
	            .consumeSubscriptionWith(s -> {
	            	assertThat(FluxSubscribeOnCallable
				            .CallableSubscribeOnSubscription.class.cast(s)
		            .size()).isEqualTo(1);
	            })
	            .thenRequest(1)
	            .thenAwait()
	            .expectNext(1)
	            .expectComplete()
	            .verify();
}
 
Example #15
Source File: MailQueueContract.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
default void dequeueShouldBeFifo() throws Exception {
    String firstExpectedName = "name1";
    enQueue(defaultMail()
        .name(firstExpectedName)
        .build());
    String secondExpectedName = "name2";
    enQueue(defaultMail()
        .name(secondExpectedName)
        .build());

    Iterator<MailQueue.MailQueueItem> items = Flux.from(getMailQueue().deQueue()).subscribeOn(Schedulers.elastic()).toIterable().iterator();
    MailQueue.MailQueueItem mailQueueItem1 = items.next();
    mailQueueItem1.done(true);
    MailQueue.MailQueueItem mailQueueItem2 = items.next();
    mailQueueItem2.done(true);
    assertThat(mailQueueItem1.getMail().getName()).isEqualTo(firstExpectedName);
    assertThat(mailQueueItem2.getMail().getName()).isEqualTo(secondExpectedName);
}
 
Example #16
Source File: ElasticsearchRepository.java    From staccato with Apache License 2.0 6 votes vote down vote up
public Mono<ItemCollection> searchItemCollection(Collection<String> indices, QueryBuilder queryBuilder,
                                                 final com.planet.staccato.dto.api.SearchRequest searchRequest) {
    String searchString = buildEsSearchString(indices, queryBuilder, searchRequest);
    final Context context = new Context();
    final StringBuilder nextTokenBuilder = new StringBuilder();
    return client.search(searchString, indices)
            // build the meta object and return the search hits
            .flatMapIterable(response -> {
                List<SearchHit> searchHits = itemCollectionBuilder.buildMeta(context, response, searchRequest);
                nextTokenBuilder.append(itemCollectionBuilder.buildNextToken(context, response));
                return searchHits;
            })
            // process all the hits in parallel -- will use all CPU cores by default
            .parallel().runOn(Schedulers.parallel())
            // map each hit to it's source bytes
            .map(hit -> SerializationUtils.deserializeItem(hit.getSourceRef().toBytesRef().bytes, mapper))
            // revert to sequential processing
            .sequential()
            .collectList()
            // take the api list build an item collection from it
            .map(itemList -> itemCollectionBuilder
                    .buildItemCollection(context, itemList, searchRequest, nextTokenBuilder.toString()));
}
 
Example #17
Source File: ReactiveAccessDecisionManagerAdapter.java    From spring-security-reactive with Apache License 2.0 6 votes vote down vote up
public Mono<Boolean> decide(Authentication authentication, Object object, Flux<ConfigAttribute> configAttributes) {
	return Mono
		.just(Tuples.of(authentication, object, configAttributes))
		.publishOn(Schedulers.elastic())
		.filter((Tuple3<Authentication, Object, Flux<ConfigAttribute>> t) -> {
			Authentication auth = t.getT1();
			return auth != null && auth.isAuthenticated();
		})
		.flatMap((Function<Tuple3<Authentication, Object, Flux<ConfigAttribute>>, Mono<Boolean>>) t -> {
			List<ConfigAttribute> attrs = new ArrayList<>();
			t.getT3().toIterable().forEach(attrs::add);

			try {
				accessDecisionManager.decide(t.getT1(), t.getT2(), attrs);
				return Mono.just(true);
			} catch(AccessDeniedException fail) {
				return Mono.just(false);
			}
		});
}
 
Example #18
Source File: FluxTransformingTests.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void flatMap() {
  Flux<Player> playerFlux = Flux
    .just("Michael Jordan", "Scottie Pippen", "Steve Kerr")
    .flatMap(n -> Mono.just(n)
        .map(p -> {
            String[] split = p.split("\\s");
            return new Player(split[0], split[1]);
          })
        .subscribeOn(Schedulers.parallel())
      );
  
  List<Player> playerList = Arrays.asList(
      new Player("Michael", "Jordan"), 
      new Player("Scottie", "Pippen"), 
      new Player("Steve", "Kerr"));

  StepVerifier.create(playerFlux)
      .expectNextMatches(p -> playerList.contains(p))
      .expectNextMatches(p -> playerList.contains(p))
      .expectNextMatches(p -> playerList.contains(p))
      .verifyComplete();
}
 
Example #19
Source File: ModifyResponseBodyGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
private <T> Mono<T> extractBody(ServerWebExchange exchange,
		ClientResponse clientResponse, Class<T> inClass) {
	// if inClass is byte[] then just return body, otherwise check if
	// decoding required
	if (byte[].class.isAssignableFrom(inClass)) {
		return clientResponse.bodyToMono(inClass);
	}

	List<String> encodingHeaders = exchange.getResponse().getHeaders()
			.getOrEmpty(HttpHeaders.CONTENT_ENCODING);
	for (String encoding : encodingHeaders) {
		MessageBodyDecoder decoder = messageBodyDecoders.get(encoding);
		if (decoder != null) {
			return clientResponse.bodyToMono(byte[].class)
					.publishOn(Schedulers.parallel()).map(decoder::decode)
					.map(bytes -> exchange.getResponse().bufferFactory()
							.wrap(bytes))
					.map(buffer -> prepareClientResponse(Mono.just(buffer),
							exchange.getResponse().getHeaders()))
					.flatMap(response -> response.bodyToMono(inClass));
		}
	}

	return clientResponse.bodyToMono(inClass);
}
 
Example #20
Source File: ReactiveInvocationHandlerTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void invokeFailureReactor() throws Throwable {
  given(this.methodHandler.invoke(any())).willThrow(new IOException("Could Not Decode"));
  ReactorInvocationHandler handler = new ReactorInvocationHandler(this.target,
      Collections.singletonMap(this.method, this.methodHandler), Schedulers.elastic());

  Object result = handler.invoke(this.method, this.methodHandler, new Object[] {});
  assertThat(result).isInstanceOf(Mono.class);
  verifyZeroInteractions(this.methodHandler);

  /* subscribe and execute the method, should result in an error */
  StepVerifier.create((Mono) result)
      .expectError(IOException.class)
      .verify();
  verify(this.methodHandler, times(1)).invoke(any());
}
 
Example #21
Source File: MonoSubscribeOnTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void classicWithTimeout() {
	AssertSubscriber<Integer> ts = AssertSubscriber.create(0);
	Mono.fromCallable(() -> {
		try {
			TimeUnit.SECONDS.sleep(2L);
		}
		catch (InterruptedException ignore) {
		}
		return 0;
	})
	    .timeout(Duration.ofMillis(100L))
	    .onErrorResume(t -> Mono.fromCallable(() -> 1))
	    .subscribeOn(afterTest.autoDispose(Schedulers.newBoundedElastic(4, 100, "timeout")))
	    .subscribe(ts);

	ts.request(1);

	ts.await(Duration.ofMillis(400))
	  .assertValues(1)
	  .assertNoError()
	  .assertComplete();
}
 
Example #22
Source File: CustomBlockingMethodTest.java    From BlockHound with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReportCustomBlockingMethods() {
    Throwable e = Assertions.catchThrowable(() -> {
        Mono.fromRunnable(Blocking::block).hide().subscribeOn(Schedulers.parallel()).block(Duration.ofMillis(100));
    });
    assertThat(e)
            .as("exception")
            .hasCauseInstanceOf(BlockingOperationError.class);

    assertThat(e.getCause()).isInstanceOfSatisfying(BlockingOperationError.class, cause -> {
        assertThat(cause.getMethod())
                .isNotNull()
                .returns(Blocking.class.getName(), BlockingMethod::getClassName)
                .returns("block", BlockingMethod::getName);
    });
}
 
Example #23
Source File: BackingAppManagementService.java    From spring-cloud-app-broker with Apache License 2.0 6 votes vote down vote up
/**
 * Stops the backing applications for the service instance with the given id
 * @param serviceInstanceId target service instance id
 * @param serviceName service name
 * @param planName plan name
 * @return completes when the operation is completed
 */
public Mono<Void> stop(String serviceInstanceId, String serviceName, String planName) {
	return getBackingApplicationsForService(serviceInstanceId, serviceName, planName)
		.flatMapMany(backingApps -> Flux.fromIterable(backingApps)
			.parallel()
			.runOn(Schedulers.parallel())
			.flatMap(managementClient::stop)
			.doOnRequest(l -> {
				LOG.info("Stopping applications");
				LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps);
			})
			.doOnComplete(() -> {
				LOG.info("Finish stopping applications");
				LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps);
			})
			.doOnError(e -> {
				LOG.error(String.format("Error stopping applications. error=%s", e.getMessage()), e);
				LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps);
			}))
		.then();
}
 
Example #24
Source File: SchedulerTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 6 votes vote down vote up
@Test
public void testParallelScheduler() throws Exception{
    Flux<Long> fibonacciGenerator = Flux.generate(() -> Tuples.<Long,
            Long>of(0L, 1L), (state, sink) -> {
        if (state.getT1() < 0)
            sink.complete();
        else
            sink.next(state.getT1());
        print("Generating next of "+ state.getT2());

        return Tuples.of(state.getT2(), state.getT1() + state.getT2());
    });
    fibonacciGenerator
            .filter(x -> {
                print("Executing Filter");
                return x < 100;
            }).delayElements(Duration.ZERO,Schedulers.parallel())
             .doOnNext(x -> print("Next value is  "+ x))
            .doFinally(x -> print("Closing "+x))
            .subscribe(x -> print("Sub received : "));
    Thread.sleep(500);
}
 
Example #25
Source File: DefaultDirectKubeApiServerIntegrator.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Inject
public DefaultDirectKubeApiServerIntegrator(DirectKubeConfiguration configuration,
                                            KubeApiFacade kubeApiFacade,
                                            TaskToPodConverter taskToPodConverter,
                                            TitusRuntime titusRuntime) {
    this.configuration = configuration;
    this.kubeApiFacade = kubeApiFacade;
    this.taskToPodConverter = taskToPodConverter;
    this.podCreateErrorToReasonCodeResolver = new PodCreateErrorToResultCodeResolver(configuration);
    this.titusRuntime = titusRuntime;

    this.metrics = new DefaultDirectKubeApiServerIntegratorMetrics(titusRuntime);
    metrics.observePodsCollection(pods);

    this.apiClientExecutor = ExecutorsExt.instrumentedFixedSizeThreadPool(titusRuntime.getRegistry(), "kube-apiclient", configuration.getApiClientThreadPoolSize());
    this.apiClientScheduler = Schedulers.fromExecutorService(apiClientExecutor);

    FitFramework fit = titusRuntime.getFitFramework();
    if (fit.isActive()) {
        FitInjection fitKubeInjection = fit.newFitInjectionBuilder("directKubeIntegration")
                .withDescription("DefaultDirectKubeApiServerIntegrator injection")
                .build();
        fit.getRootComponent().getChild(DirectKubeApiServerIntegrator.COMPONENT).addInjection(fitKubeInjection);
        this.fitKubeInjection = Optional.of(fitKubeInjection);
    } else {
        this.fitKubeInjection = Optional.empty();
    }
}
 
Example #26
Source File: AwsS3ObjectStorage.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Mono<Void> putWithRetry(ObjectStorageBucketName bucketName, ThrowingRunnable puttingAttempt) {
    return Mono.<Void>fromRunnable(puttingAttempt)
        .publishOn(Schedulers.elastic())
        .retryWhen(Retry
            .backoff(MAX_RETRY_ON_EXCEPTION, FIRST_BACK_OFF)
            .filter(throwable -> needToCreateBucket(throwable))
            .doBeforeRetry(retryContext -> s3Client.createBucket(bucketName.asString()))
            .scheduler(Schedulers.elastic()));
}
 
Example #27
Source File: TrackEventListener.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onTrackStart(AudioPlayer player, AudioTrack track) {
    Mono.justOrEmpty(MusicManager.getInstance().getGuildMusic(this.guildId))
            .flatMap(guildMusic -> {
                final String message = String.format(Emoji.MUSICAL_NOTE + " Currently playing: **%s**",
                        FormatUtils.trackName(track.getInfo()));
                return guildMusic.getMessageChannel()
                        .flatMap(channel -> DiscordUtils.sendMessage(message, channel));
            })
            .subscribeOn(Schedulers.boundedElastic())
            .subscribe(null, ExceptionHandler::handleUnknownError);
}
 
Example #28
Source File: ReconnectMonoTests.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Test
public void ensuresThatMainSubscriberAllowsOnlyTerminationWithValue() {
  final int timeout = 10;
  final ReconnectMono<String> reconnectMono =
      new ReconnectMono<>(Mono.empty(), onExpire(), onValue());

  StepVerifier.create(reconnectMono.subscribeOn(Schedulers.elastic()))
      .expectSubscription()
      .expectErrorSatisfies(
          t ->
              Assertions.assertThat(t)
                  .hasMessage("Source completed empty")
                  .isInstanceOf(IllegalStateException.class))
      .verify(Duration.ofSeconds(timeout));
}
 
Example #29
Source File: StepVerifierTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void thenCancel_cancelsAfterFirst2() {
	TestPublisher<Long> publisher = TestPublisher.create();
	AtomicBoolean downStreamCancelled = new AtomicBoolean();
	AtomicBoolean asserted = new AtomicBoolean();
	Flux<Long> source = publisher
			.flux()
			.doOnCancel(() -> downStreamCancelled.set(true));

	Duration took = StepVerifier.create(source)
	                            .then(() -> Schedulers.boundedElastic().schedule(() -> publisher.next(0L)))
	                            .assertNext(next -> {
		                            asserted.set(true);
		                            assertThat(next).isEqualTo(0L);
	                            })
	                            .then(() -> Schedulers.boundedElastic().schedule(() ->
			                            publisher.next(1L)))
	                            .thenCancel()
	                            .verify(Duration.ofSeconds(5));

	publisher.assertCancelled();

	assertThat(asserted.get())
			.as("expectation processed")
			.isTrue();
	assertThat(downStreamCancelled.get())
			.as("is cancelled by awaitThenCancel")
			.isTrue();
}
 
Example #30
Source File: FluxPublishOnTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void errorHide() {
	StepVerifier.create(Flux.error(new RuntimeException("forced failure"))
	                        .hide()
	                        .publishOn(Schedulers.fromExecutorService(exec)))
	            .verifyErrorMessage("forced failure");
}