io.rsocket.util.ByteBufPayload Java Examples

The following examples show how to use io.rsocket.util.ByteBufPayload. 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: RSocketLeaseTest.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@MethodSource("interactions")
void expiredLeaseRequestsAreRejected(BiFunction<RSocket, Payload, Publisher<?>> interaction) {
  leaseSender.onNext(Lease.create(50, 1));

  ByteBuf buffer = byteBufAllocator.buffer();
  buffer.writeCharSequence("test", CharsetUtil.UTF_8);
  Payload payload1 = ByteBufPayload.create(buffer);

  Flux.from(interaction.apply(rSocketRequester, payload1))
      .delaySubscription(Duration.ofMillis(100))
      .as(StepVerifier::create)
      .expectError(MissingLeaseException.class)
      .verify(Duration.ofSeconds(5));

  Assertions.assertThat(connection.getSent())
      .hasSize(1)
      .first()
      .matches(bb -> FrameHeaderCodec.frameType(bb) == LEASE)
      .matches(ReferenceCounted::release);

  byteBufAllocator.assertHasNoLeaks();
}
 
Example #2
Source File: IPCTracingAndMetricsAwareFireAndForgetFunction.java    From rsocket-rpc-java with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Mono<Void> apply(Payload payload, MetadataDecoder.Metadata metadata) {
  Object input = unmarshaller.apply(payload.sliceData());
  return fnf.apply(input, metadata.metadata())
      .map(o -> ByteBufPayload.create(marshaller.apply(o)))
      .transform(
          Tracing.traceAsChild(
                  tracer,
                  route,
                  Tag.of("rsocket.route", route),
                  Tag.of("rsocket.ipc.role", "server"),
                  Tag.of("rsocket.ipc.version", "ipc"))
              .apply(metadata.spanContext()))
      .transform(Metrics.timed(meterRegistry, "rsocket.server", "route", route));
}
 
Example #3
Source File: IPCTracingAndMetricsAwareRequestResponseFunction.java    From rsocket-rpc-java with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Mono<Payload> apply(Payload payload, MetadataDecoder.Metadata metadata) {
  Object input = unmarshaller.apply(payload.sliceData());
  return rr.apply(input, metadata.metadata())
      .map(o -> ByteBufPayload.create(marshaller.apply(o)))
      .transform(
          Tracing.traceAsChild(
                  tracer,
                  route,
                  Tag.of("rsocket.route", route),
                  Tag.of("rsocket.ipc.role", "server"),
                  Tag.of("rsocket.ipc.version", "ipc"))
              .apply(metadata.spanContext()))
      .transform(Metrics.timed(meterRegistry, "rsocket.server", "route", route));
}
 
Example #4
Source File: IPCMetricsAwareRequestChannelFunction.java    From rsocket-rpc-java with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Flux<Payload> apply(
    Flux<Payload> source, Payload payload, MetadataDecoder.Metadata decodedMetadata) {
  return rc.apply(
          unmarshaller.apply(payload.sliceData()),
          source.map(
              p -> {
                try {
                  ByteBuf dd = p.sliceData();
                  Object result = unmarshaller.apply(dd);
                  p.release();
                  return result;
                } catch (Throwable t) {
                  p.release();
                  throw Exceptions.propagate(t);
                }
              }),
          decodedMetadata.metadata())
      .map(o -> ByteBufPayload.create(marshaller.apply(o)))
      .transform(Metrics.timed(meterRegistry, "rsocket.server", "route", route));
}
 
Example #5
Source File: IPCTracingAndMetricsAwareRequestStreamFunction.java    From rsocket-rpc-java with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Flux<Payload> apply(Payload payload, MetadataDecoder.Metadata metadata) {
  Object input = unmarshaller.apply(payload.sliceData());
  return rs.apply(input, metadata.metadata())
      .map(o -> ByteBufPayload.create(marshaller.apply(o)))
      .transform(
          Tracing.traceAsChild(
                  tracer,
                  route,
                  Tag.of("rsocket.route", route),
                  Tag.of("rsocket.ipc.role", "server"),
                  Tag.of("rsocket.ipc.version", "ipc"))
              .apply(metadata.spanContext()))
      .transform(Metrics.timed(meterRegistry, "rsocket.server", "route", route));
}
 
Example #6
Source File: IPCRequestChannelFunction.java    From rsocket-rpc-java with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Flux<Payload> apply(
    Flux<Payload> source, Payload payload, MetadataDecoder.Metadata metadata) {
  return rc.apply(
          unmarshaller.apply(payload.sliceData()),
          source.map(
              p -> {
                try {
                  ByteBuf dd = p.sliceData();
                  Object result = unmarshaller.apply(dd);
                  p.release();
                  return result;
                } catch (Throwable t) {
                  p.release();
                  throw Exceptions.propagate(t);
                }
              }),
          metadata.metadata())
      .map(o -> ByteBufPayload.create(marshaller.apply(o)));
}
 
Example #7
Source File: RSocketLeaseTest.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@MethodSource("interactions")
void requesterExpiredLeaseRequestsAreRejected(
    BiFunction<RSocket, Payload, Publisher<?>> interaction) {
  ByteBuf frame = leaseFrame(50, 1, Unpooled.EMPTY_BUFFER);
  requesterLeaseHandler.receive(frame);

  ByteBuf buffer = byteBufAllocator.buffer();
  buffer.writeCharSequence("test", CharsetUtil.UTF_8);
  Payload payload1 = ByteBufPayload.create(buffer);

  Flux.defer(() -> interaction.apply(rSocketRequester, payload1))
      .delaySubscription(Duration.ofMillis(200))
      .as(StepVerifier::create)
      .expectError(MissingLeaseException.class)
      .verify(Duration.ofSeconds(5));

  Assertions.assertThat(frame.release()).isTrue();

  byteBufAllocator.assertHasNoLeaks();
}
 
Example #8
Source File: ServiceQueryController.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
@GetMapping(value = "/definition/{serviceName}")
public Mono<String> queryDefinition(@PathVariable(name = "serviceName") String serviceName) {
    Integer handler = routingSelector.findHandler(new ServiceLocator("", serviceName, "").getId());
    if (handler != null) {
        RSocketBrokerResponderHandler brokerResponderHandler = brokerHandlerRegistry.findById(handler);
        if (brokerResponderHandler != null) {
            GSVRoutingMetadata routingMetadata = new GSVRoutingMetadata("", ReactiveServiceDiscovery.class.getCanonicalName() + ".findServiceByFullName", "");
            RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(routingMetadata, jsonMetaEncoding);
            ByteBuf bodyBuf = Unpooled.wrappedBuffer(("[\"" + serviceName + "\"]").getBytes());
            return brokerResponderHandler.getPeerRsocket()
                    .requestResponse(ByteBufPayload.create(bodyBuf, compositeMetadata.getContent()))
                    .map(Payload::getDataUtf8);
        }
    }
    return Mono.error(new Exception(RsocketErrorCode.message("RST-900404", serviceName)));
}
 
Example #9
Source File: RSocketRequesterTest.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Test
public void simpleOnDiscardRequestChannelTest() {
  AssertSubscriber<Payload> assertSubscriber = AssertSubscriber.create(1);
  TestPublisher<Payload> testPublisher = TestPublisher.create();

  Flux<Payload> payloadFlux = rule.socket.requestChannel(testPublisher);

  payloadFlux.subscribe(assertSubscriber);

  testPublisher.next(
      ByteBufPayload.create("d", "m"),
      ByteBufPayload.create("d1", "m1"),
      ByteBufPayload.create("d2", "m2"));

  assertSubscriber.cancel();

  Assertions.assertThat(rule.connection.getSent()).allMatch(ByteBuf::release);

  rule.assertHasNoLeaks();
}
 
Example #10
Source File: RSocketRequesterTest.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Test
public void simpleOnDiscardRequestChannelTest2() {
  ByteBufAllocator allocator = rule.alloc();
  AssertSubscriber<Payload> assertSubscriber = AssertSubscriber.create(1);
  TestPublisher<Payload> testPublisher = TestPublisher.create();

  Flux<Payload> payloadFlux = rule.socket.requestChannel(testPublisher);

  payloadFlux.subscribe(assertSubscriber);

  testPublisher.next(ByteBufPayload.create("d", "m"));

  int streamId = rule.getStreamIdForRequestType(REQUEST_CHANNEL);
  testPublisher.next(ByteBufPayload.create("d1", "m1"), ByteBufPayload.create("d2", "m2"));

  rule.connection.addToReceivedBuffer(
      ErrorFrameCodec.encode(
          allocator, streamId, new CustomRSocketException(0x00000404, "test")));

  Assertions.assertThat(rule.connection.getSent()).allMatch(ByteBuf::release);

  rule.assertHasNoLeaks();
}
 
Example #11
Source File: RSocketRequesterTest.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Test
// see https://github.com/rsocket/rsocket-java/issues/858
public void testWorkaround858() {
  ByteBuf buffer = rule.alloc().buffer();
  buffer.writeCharSequence("test", CharsetUtil.UTF_8);

  rule.socket.requestResponse(ByteBufPayload.create(buffer)).subscribe();

  rule.connection.addToReceivedBuffer(
      ErrorFrameCodec.encode(rule.alloc(), 1, new RuntimeException("test")));

  Assertions.assertThat(rule.connection.getSent())
      .hasSize(1)
      .first()
      .matches(bb -> FrameHeaderCodec.frameType(bb) == REQUEST_RESPONSE)
      .matches(ByteBuf::release);

  Assertions.assertThat(rule.socket.isDisposed()).isFalse();

  rule.assertHasNoLeaks();
}
 
Example #12
Source File: RSocketRequesterSupportImpl.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
@Override
public Supplier<Payload> setupPayload() {
    return () -> {
        //composite metadata with app metadata
        RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(getAppMetadata());
        //add published in setup payload
        Set<ServiceLocator> serviceLocators = exposedServices().get();
        if (!compositeMetadata.contains(RSocketMimeType.ServiceRegistry) && !serviceLocators.isEmpty()) {
            ServiceRegistryMetadata serviceRegistryMetadata = new ServiceRegistryMetadata();
            serviceRegistryMetadata.setPublished(serviceLocators);
            compositeMetadata.addMetadata(serviceRegistryMetadata);
        }
        // authentication
        if (this.jwtToken != null && this.jwtToken.length > 0) {
            compositeMetadata.addMetadata(new BearerTokenMetadata(this.jwtToken));
        }
        return ByteBufPayload.create(Unpooled.EMPTY_BUFFER, compositeMetadata.getContent());
    };
}
 
Example #13
Source File: PayloadUtils.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Create a Payload from the given metadata and data.
 * @param metadata the metadata part for the payload
 * @param data the data part for the payload
 * @return the created Payload
 */
public static Payload createPayload(DataBuffer metadata, DataBuffer data) {
	if (metadata instanceof NettyDataBuffer && data instanceof NettyDataBuffer) {
		return ByteBufPayload.create(
				((NettyDataBuffer) data).getNativeBuffer(),
				((NettyDataBuffer) metadata).getNativeBuffer());
	}
	else if (metadata instanceof DefaultDataBuffer && data instanceof DefaultDataBuffer) {
		return DefaultPayload.create(
				((DefaultDataBuffer) data).getNativeBuffer(),
				((DefaultDataBuffer) metadata).getNativeBuffer());
	}
	else {
		return DefaultPayload.create(data.asByteBuffer(), metadata.asByteBuffer());
	}
}
 
Example #14
Source File: MetricsScrapeController.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
@GetMapping(value = "/{uuid}", produces = MimeTypeUtils.TEXT_PLAIN_VALUE)
public Mono<String> scrape(@PathVariable(name = "uuid") String uuid) {
    RSocketBrokerResponderHandler rsocket = handlerRegistry.findByUUID(uuid);
    if (rsocket == null) {
        return Mono.error(new Exception(RsocketErrorCode.message("RST-300205", uuid)));
    }
    return rsocket.getPeerRsocket().requestResponse(ByteBufPayload.create(Unpooled.EMPTY_BUFFER, metricsScrapeCompositeByteBuf.retainedDuplicate()))
            .map(Payload::getDataUtf8);
}
 
Example #15
Source File: CloudEventRSocket.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
default Payload cloudEventToMetadataPushPayload(CloudEventImpl<?> cloudEvent) {
    ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.buffer();
    try {
        ByteBufOutputStream bos = new ByteBufOutputStream(byteBuf);
        JsonUtils.objectMapper.writeValue((OutputStream) bos, cloudEvent);
        return ByteBufPayload.create(Unpooled.EMPTY_BUFFER, byteBuf);
    } catch (Exception e) {
        ReferenceCountUtil.safeRelease(byteBuf);
        throw new EncodingException(RsocketErrorCode.message("RST-700500", "CloudEventImpl", "ByteBuf"), e);
    }
}
 
Example #16
Source File: ServiceTestingView.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
public void callRSocketService(String service, String method, @Nullable String jsonData, Pre response) {
    Integer handlerId = this.routingSelector.findHandler(ServiceLocator.serviceHashCode(service));
    if (handlerId != null) {
        RSocketBrokerResponderHandler handler = handlerRegistry.findById(handlerId);
        if (handler != null) {
            //composite metadata for health check
            RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(
                    new GSVRoutingMetadata(null, service, method, null),
                    new MessageMimeTypeMetadata(RSocketMimeType.Json));
            ByteBuf payLoadData;
            if (jsonData == null || jsonData.isEmpty()) {
                payLoadData = Unpooled.EMPTY_BUFFER;
            } else {
                payLoadData = Unpooled.wrappedBuffer(jsonData.getBytes(StandardCharsets.UTF_8));
            }
            Payload requestPayload = ByteBufPayload.create(payLoadData, compositeMetadata.getContent());
            handler.getPeerRsocket().requestResponse(requestPayload)
                    .doOnError(throwable -> getUI().ifPresent(ui -> ui.access(() -> {
                        response.setText(throwable.getMessage());
                    })))
                    .subscribe(payload -> getUI().ifPresent(ui -> ui.access(() -> {
                        response.setText(payload.getDataUtf8());
                    })));
        } else {
            this.serviceNameFiled.setInvalid(true);
            this.serviceNameFiled.setErrorMessage("No Service Provider!");
        }
    } else {
        this.serviceNameFiled.setInvalid(true);
        this.serviceNameFiled.setErrorMessage("Service not found!");
    }

}
 
Example #17
Source File: IPCTracingAndMetricsAwareRequestChannelFunction.java    From rsocket-rpc-java with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Flux<Payload> apply(
    Flux<Payload> source, Payload payload, MetadataDecoder.Metadata metadata) {
  return rc.apply(
          unmarshaller.apply(payload.sliceData()),
          source.map(
              p -> {
                try {
                  ByteBuf dd = p.sliceData();
                  Object result = unmarshaller.apply(dd);
                  p.release();
                  return result;
                } catch (Throwable t) {
                  p.release();
                  throw Exceptions.propagate(t);
                }
              }),
          metadata.metadata())
      .map(o -> ByteBufPayload.create(marshaller.apply(o)))
      .transform(
          Tracing.traceAsChild(
                  tracer,
                  route,
                  Tag.of("rsocket.route", route),
                  Tag.of("rsocket.ipc.role", "server"),
                  Tag.of("rsocket.ipc.version", "ipc"))
              .apply(metadata.spanContext()))
      .transform(Metrics.timed(meterRegistry, "rsocket.server", "route", route));
}
 
Example #18
Source File: IPCRequestResponseFunction.java    From rsocket-rpc-java with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Mono<Payload> apply(Payload payload, MetadataDecoder.Metadata metadata) {
  Object input = unmarshaller.apply(payload.sliceData());
  return rr.apply(input, metadata.metadata())
      .map(o -> ByteBufPayload.create(marshaller.apply(o)));
}
 
Example #19
Source File: PayloadUtils.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Create a Payload from the given data.
 * @param data the data part for the payload
 * @return the created Payload
 */
public static Payload createPayload(DataBuffer data) {
	if (data instanceof NettyDataBuffer) {
		return ByteBufPayload.create(((NettyDataBuffer) data).getNativeBuffer());
	}
	else if (data instanceof DefaultDataBuffer) {
		return DefaultPayload.create(((DefaultDataBuffer) data).getNativeBuffer());
	}
	else {
		return DefaultPayload.create(data.asByteBuffer());
	}
}
 
Example #20
Source File: IPCTracingAwareRequestResponseFunction.java    From rsocket-rpc-java with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Mono<Payload> apply(Payload payload, MetadataDecoder.Metadata metadata) {
  Object input = unmarshaller.apply(payload.sliceData());
  return rr.apply(input, metadata.metadata())
      .map(o -> ByteBufPayload.create(marshaller.apply(o)))
      .transform(
          Tracing.traceAsChild(
                  tracer,
                  route,
                  Tag.of("rsocket.route", route),
                  Tag.of("rsocket.ipc.role", "server"),
                  Tag.of("rsocket.ipc.version", "ipc"))
              .apply(metadata.spanContext()));
}
 
Example #21
Source File: IPCTracingAwareRequestStreamFunction.java    From rsocket-rpc-java with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Flux<Payload> apply(Payload payload, MetadataDecoder.Metadata metadata) {
  Object input = unmarshaller.apply(payload.sliceData());
  return rs.apply(input, metadata.metadata())
      .map(o -> ByteBufPayload.create(marshaller.apply(o)))
      .transform(
          Tracing.traceAsChild(
                  tracer,
                  route,
                  Tag.of("rsocket.route", route),
                  Tag.of("rsocket.ipc.role", "server"),
                  Tag.of("rsocket.ipc.version", "ipc"))
              .apply(metadata.spanContext()));
}
 
Example #22
Source File: ZeroCopyPayloadDecoder.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Override
public Payload apply(ByteBuf byteBuf) {
  ByteBuf m;
  ByteBuf d;
  FrameType type = FrameHeaderCodec.frameType(byteBuf);
  switch (type) {
    case REQUEST_FNF:
      d = RequestFireAndForgetFrameCodec.data(byteBuf);
      m = RequestFireAndForgetFrameCodec.metadata(byteBuf);
      break;
    case REQUEST_RESPONSE:
      d = RequestResponseFrameCodec.data(byteBuf);
      m = RequestResponseFrameCodec.metadata(byteBuf);
      break;
    case REQUEST_STREAM:
      d = RequestStreamFrameCodec.data(byteBuf);
      m = RequestStreamFrameCodec.metadata(byteBuf);
      break;
    case REQUEST_CHANNEL:
      d = RequestChannelFrameCodec.data(byteBuf);
      m = RequestChannelFrameCodec.metadata(byteBuf);
      break;
    case NEXT:
    case NEXT_COMPLETE:
      d = PayloadFrameCodec.data(byteBuf);
      m = PayloadFrameCodec.metadata(byteBuf);
      break;
    case METADATA_PUSH:
      d = Unpooled.EMPTY_BUFFER;
      m = MetadataPushFrameCodec.metadata(byteBuf);
      break;
    default:
      throw new IllegalArgumentException("unsupported frame type: " + type);
  }

  return ByteBufPayload.create(d.retain(), m != null ? m.retain() : null);
}
 
Example #23
Source File: UnboundedProcessorTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testPrioritizedSending() {
  UnboundedProcessor<Payload> processor = new UnboundedProcessor<>();

  for (int i = 0; i < 1000; i++) {
    processor.onNext(EmptyPayload.INSTANCE);
  }

  processor.onNextPrioritized(ByteBufPayload.create("test"));

  Payload closestPayload = processor.next().block();

  Assert.assertEquals(closestPayload.getDataUtf8(), "test");
}
 
Example #24
Source File: UnboundedProcessorTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testPrioritizedFused() {
  UnboundedProcessor<Payload> processor = new UnboundedProcessor<>();

  for (int i = 0; i < 1000; i++) {
    processor.onNext(EmptyPayload.INSTANCE);
  }

  processor.onNextPrioritized(ByteBufPayload.create("test"));

  Payload closestPayload = processor.poll();

  Assert.assertEquals(closestPayload.getDataUtf8(), "test");
}
 
Example #25
Source File: RSocketConnectorTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Test
public void ensuresThatMonoFromRSocketConnectorCanBeUsedForMultipleSubscriptions() {
  Payload setupPayload = ByteBufPayload.create("TestData", "TestMetadata");

  Assertions.assertThat(setupPayload.refCnt()).isOne();

  TestClientTransport testClientTransport = new TestClientTransport();
  Mono<RSocket> connectionMono =
      RSocketConnector.create().setupPayload(setupPayload).connect(testClientTransport);

  connectionMono
      .as(StepVerifier::create)
      .expectNextCount(1)
      .expectComplete()
      .verify(Duration.ofMillis(100));

  connectionMono
      .as(StepVerifier::create)
      .expectNextCount(1)
      .expectComplete()
      .verify(Duration.ofMillis(100));

  Assertions.assertThat(testClientTransport.testConnection().getSent())
      .hasSize(2)
      .allMatch(
          bb -> {
            DefaultConnectionSetupPayload payload = new DefaultConnectionSetupPayload(bb);
            return payload.getDataUtf8().equals("TestData")
                && payload.getMetadataUtf8().equals("TestMetadata");
          })
      .allMatch(ReferenceCounted::release);
  Assertions.assertThat(setupPayload.refCnt()).isZero();
}
 
Example #26
Source File: RSocketLeaseTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@MethodSource("interactions")
void requesterMissingLeaseRequestsAreRejected(
    BiFunction<RSocket, Payload, Publisher<?>> interaction) {
  Assertions.assertThat(rSocketRequester.availability()).isCloseTo(0.0, offset(1e-2));
  ByteBuf buffer = byteBufAllocator.buffer();
  buffer.writeCharSequence("test", CharsetUtil.UTF_8);
  Payload payload1 = ByteBufPayload.create(buffer);
  StepVerifier.create(interaction.apply(rSocketRequester, payload1))
      .expectError(MissingLeaseException.class)
      .verify(Duration.ofSeconds(5));

  byteBufAllocator.assertHasNoLeaks();
}
 
Example #27
Source File: RSocketLeaseTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@MethodSource("interactions")
void responderMissingLeaseRequestsAreRejected(
    BiFunction<RSocket, Payload, Publisher<?>> interaction) {
  ByteBuf buffer = byteBufAllocator.buffer();
  buffer.writeCharSequence("test", CharsetUtil.UTF_8);
  Payload payload1 = ByteBufPayload.create(buffer);

  StepVerifier.create(interaction.apply(rSocketResponder, payload1))
      .expectError(MissingLeaseException.class)
      .verify(Duration.ofSeconds(5));
}
 
Example #28
Source File: RSocketResponderTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Test
public void checkNoLeaksOnRacingBetweenDownstreamCancelAndOnNextFromRequestResponseTest1() {
  Scheduler parallel = Schedulers.parallel();
  Hooks.onErrorDropped((e) -> {});
  ByteBufAllocator allocator = rule.alloc();
  for (int i = 0; i < 10000; i++) {
    Operators.MonoSubscriber<Payload, Payload>[] sources = new Operators.MonoSubscriber[1];

    rule.setAcceptingSocket(
        new RSocket() {
          @Override
          public Mono<Payload> requestResponse(Payload payload) {
            payload.release();
            return new Mono<Payload>() {
              @Override
              public void subscribe(CoreSubscriber<? super Payload> actual) {
                sources[0] = new Operators.MonoSubscriber<>(actual);
                actual.onSubscribe(sources[0]);
              }
            };
          }
        },
        Integer.MAX_VALUE);

    rule.sendRequest(1, REQUEST_RESPONSE);

    ByteBuf cancelFrame = CancelFrameCodec.encode(allocator, 1);
    RaceTestUtils.race(
        () -> rule.connection.addToReceivedBuffer(cancelFrame),
        () -> {
          sources[0].complete(ByteBufPayload.create("d1", "m1"));
        },
        parallel);

    Assertions.assertThat(rule.connection.getSent()).allMatch(ReferenceCounted::release);

    rule.assertHasNoLeaks();
  }
}
 
Example #29
Source File: RSocketResponderTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Test
// see https://github.com/rsocket/rsocket-java/issues/858
public void testWorkaround858() {
  ByteBuf buffer = rule.alloc().buffer();
  buffer.writeCharSequence("test", CharsetUtil.UTF_8);

  TestPublisher<Payload> testPublisher = TestPublisher.create();

  rule.setAcceptingSocket(
      new RSocket() {
        @Override
        public Flux<Payload> requestChannel(Publisher<Payload> payloads) {
          Flux.from(payloads).doOnNext(ReferenceCounted::release).subscribe();

          return testPublisher.flux();
        }
      });

  rule.connection.addToReceivedBuffer(
      RequestChannelFrameCodec.encodeReleasingPayload(
          rule.alloc(), 1, false, 1, ByteBufPayload.create(buffer)));
  rule.connection.addToReceivedBuffer(
      ErrorFrameCodec.encode(rule.alloc(), 1, new RuntimeException("test")));

  Assertions.assertThat(rule.connection.getSent())
      .hasSize(1)
      .first()
      .matches(bb -> FrameHeaderCodec.frameType(bb) == REQUEST_N)
      .matches(ReferenceCounted::release);

  Assertions.assertThat(rule.socket.isDisposed()).isFalse();
  testPublisher.assertWasCancelled();

  rule.assertHasNoLeaks();
}
 
Example #30
Source File: RSocketRequesterTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@MethodSource("refCntCases")
public void ensureSendsErrorOnIllegalRefCntPayload(
    BiFunction<Payload, RSocket, Publisher<?>> sourceProducer) {
  Payload invalidPayload = ByteBufPayload.create("test", "test");
  invalidPayload.release();

  Publisher<?> source = sourceProducer.apply(invalidPayload, rule.socket);

  StepVerifier.create(source, 0)
      .expectError(IllegalReferenceCountException.class)
      .verify(Duration.ofMillis(100));
}