Java Code Examples for io.rsocket.Payload#release()

The following examples show how to use io.rsocket.Payload#release() . 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: RoutingServerRSocket.java    From rsocket-rpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> fireAndForget(Payload payload) {
  try {
    final MetadataDecoder.Metadata decodedMetadata = decoder.decode(payload.sliceMetadata());

    final String route = decodedMetadata.route();
    final IPCFunction<Mono<Void>> monoIPCFunction = this.router.routeFireAndForget(route);

    if (monoIPCFunction == null) {
      return Mono.error(new RouteNotFound("Nothing found for route " + route));
    }

    final Mono<Void> response = monoIPCFunction.apply(payload, decodedMetadata);

    payload.release();

    return response;
  } catch (Throwable t) {
    payload.release();
    return Mono.error(t);
  }
}
 
Example 2
Source File: RoutingServerRSocket.java    From rsocket-rpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Payload> requestResponse(Payload payload) {
  try {
    final MetadataDecoder.Metadata decodedMetadata = decoder.decode(payload.sliceMetadata());

    final String route = decodedMetadata.route();
    final IPCFunction<Mono<Payload>> monoIPCFunction = this.router.routeRequestResponse(route);

    if (monoIPCFunction == null) {
      return Mono.error(new NullPointerException("nothing found for route " + route));
    }

    final Mono<Payload> response = monoIPCFunction.apply(payload, decodedMetadata);

    payload.release();

    return response;
  } catch (Throwable t) {
    payload.release();
    return Mono.error(t);
  }
}
 
Example 3
Source File: RoutingServerRSocket.java    From rsocket-rpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public Flux<Payload> requestStream(Payload payload) {
  try {
    final MetadataDecoder.Metadata decodedMetadata = decoder.decode(payload.sliceMetadata());

    final String route = decodedMetadata.route();
    final IPCFunction<Flux<Payload>> ffContext = this.router.routeRequestStream(route);

    if (ffContext == null) {
      return Flux.error(new NullPointerException("nothing found for route " + route));
    }

    final Flux<Payload> response = ffContext.apply(payload, decodedMetadata);

    payload.release();

    return response;
  } catch (Throwable t) {
    payload.release();
    return Flux.error(t);
  }
}
 
Example 4
Source File: RoutingServerRSocket.java    From rsocket-rpc-java with Apache License 2.0 6 votes vote down vote up
private Flux<Payload> doRequestChannel(Payload payload, Flux<Payload> payloadFlux) {
  try {
    final MetadataDecoder.Metadata decodedMetadata = decoder.decode(payload.sliceMetadata());

    final String route = decodedMetadata.route();
    final IPCChannelFunction ffContext = this.router.routeRequestChannel(route);

    if (ffContext == null) {
      payload.release();
      return Flux.error(new NullPointerException("nothing found for route " + route));
    }

    return ffContext.apply(payloadFlux, payload, decodedMetadata);
  } catch (Throwable t) {
    payload.release();
    return Flux.error(t);
  }
}
 
Example 5
Source File: MetadataPushFrameCodec.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
public static ByteBuf encodeReleasingPayload(ByteBufAllocator allocator, Payload payload) {
  if (!payload.hasMetadata()) {
    throw new IllegalStateException(
        "Metadata  push requires to have metadata present" + " in the given Payload");
  }
  final ByteBuf metadata = payload.metadata().retain();
  // releasing payload safely since it can be already released wheres we have to release retained
  // data and metadata as well
  try {
    payload.release();
  } catch (IllegalReferenceCountException e) {
    metadata.release();
    throw e;
  }
  return encode(allocator, metadata);
}
 
Example 6
Source File: DefaultRSocketClient.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
public void cancel() {
  long state = REQUESTED.getAndSet(this, STATE_CANCELLED);
  if (state == STATE_CANCELLED) {
    return;
  }

  this.main.cancel();

  if (state == STATE_SUBSCRIBED) {
    this.s.cancel();
  } else {
    this.parent.remove(this);
    Payload payload = PAYLOAD.getAndSet(this, null);
    if (payload != null) {
      payload.release();
    }
  }
}
 
Example 7
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));
}
 
Example 8
Source File: PayloadUtils.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Use this method to slice, retain and wrap the data portion of the
 * {@code Payload}, and also to release the {@code Payload}. This assumes
 * the Payload metadata has been read by now and ensures downstream code
 * need only be aware of {@code DataBuffer}s.
 * @param payload the payload to process
 * @param bufferFactory the DataBufferFactory to wrap with
 * @return the created {@code DataBuffer} instance
 */
public static DataBuffer retainDataAndReleasePayload(Payload payload, DataBufferFactory bufferFactory) {
	try {
		if (bufferFactory instanceof NettyDataBufferFactory) {
			ByteBuf byteBuf = payload.sliceData().retain();
			return ((NettyDataBufferFactory) bufferFactory).wrap(byteBuf);
		}
		else {
			return bufferFactory.wrap(payload.getData());
		}
	}
	finally {
		if (payload.refCnt() > 0) {
			payload.release();
		}
	}
}
 
Example 9
Source File: RSocketRequester.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
private Mono<Void> handleMetadataPush(Payload payload) {
  if (payload.refCnt() <= 0) {
    return Mono.error(new IllegalReferenceCountException());
  }

  if (isDisposed()) {
    Throwable err = this.terminationError;
    payload.release();
    return Mono.error(err);
  }

  if (!PayloadValidationUtils.isValid(this.mtu, payload)) {
    payload.release();
    return Mono.error(new IllegalArgumentException(INVALID_PAYLOAD_ERROR_MESSAGE));
  }

  final AtomicBoolean once = new AtomicBoolean();

  return Mono.defer(
      () -> {
        if (once.getAndSet(true)) {
          return Mono.error(
              new IllegalStateException("MetadataPushMono allows only a single subscriber"));
        }

        if (isDisposed()) {
          payload.release();
          final Throwable t = terminationError;
          return Mono.error(t);
        }

        ByteBuf metadataPushFrame =
            MetadataPushFrameCodec.encodeReleasingPayload(allocator, payload);

        sendProcessor.onNextPrioritized(metadataPushFrame);

        return Mono.empty();
      });
}
 
Example 10
Source File: RSocketResponder.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
private Flux<Payload> requestChannel(Payload payload, Publisher<Payload> payloads) {
  try {
    if (leaseHandler.useLease()) {
      return responderRSocket.requestChannel(payload, payloads);
    } else {
      payload.release();
      return Flux.error(leaseHandler.leaseError());
    }
  } catch (Throwable t) {
    return Flux.error(t);
  }
}
 
Example 11
Source File: RSocketResponder.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Override
public Flux<Payload> requestStream(Payload payload) {
  try {
    if (leaseHandler.useLease()) {
      return requestHandler.requestStream(payload);
    } else {
      payload.release();
      return Flux.error(leaseHandler.leaseError());
    }
  } catch (Throwable t) {
    return Flux.error(t);
  }
}
 
Example 12
Source File: RSocketResponder.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Payload> requestResponse(Payload payload) {
  try {
    if (leaseHandler.useLease()) {
      return requestHandler.requestResponse(payload);
    } else {
      payload.release();
      return Mono.error(leaseHandler.leaseError());
    }
  } catch (Throwable t) {
    return Mono.error(t);
  }
}
 
Example 13
Source File: RSocketResponder.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> fireAndForget(Payload payload) {
  try {
    if (leaseHandler.useLease()) {
      return requestHandler.fireAndForget(payload);
    } else {
      payload.release();
      return Mono.error(leaseHandler.leaseError());
    }
  } catch (Throwable t) {
    return Mono.error(t);
  }
}
 
Example 14
Source File: TaskProcessingWithServerSideNotificationsExample.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> fireAndForget(Payload payload) {
  logger.info("Received a Task[{}] from Client.ID[{}]", payload.getDataUtf8(), id);
  tasksToProcess.onNext(new Task(id, payload.getDataUtf8()));
  payload.release();
  return Mono.empty();
}
 
Example 15
Source File: RSocketResponder.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
private void handleRequestResponse(int streamId, Mono<Payload> response) {
  final BaseSubscriber<Payload> subscriber =
      new BaseSubscriber<Payload>() {
        private boolean isEmpty = true;

        @Override
        protected void hookOnNext(Payload payload) {
          if (isEmpty) {
            isEmpty = false;
          }

          if (!PayloadValidationUtils.isValid(mtu, payload)) {
            payload.release();
            cancel();
            final IllegalArgumentException t =
                new IllegalArgumentException(INVALID_PAYLOAD_ERROR_MESSAGE);
            handleError(streamId, t);
            return;
          }

          ByteBuf byteBuf =
              PayloadFrameCodec.encodeNextCompleteReleasingPayload(allocator, streamId, payload);
          sendProcessor.onNext(byteBuf);
        }

        @Override
        protected void hookOnError(Throwable throwable) {
          if (sendingSubscriptions.remove(streamId, this)) {
            handleError(streamId, throwable);
          }
        }

        @Override
        protected void hookOnComplete() {
          if (isEmpty) {
            if (sendingSubscriptions.remove(streamId, this)) {
              sendProcessor.onNext(PayloadFrameCodec.encodeComplete(allocator, streamId));
            }
          }
        }
      };

  sendingSubscriptions.put(streamId, subscriber);
  response.doOnDiscard(ReferenceCounted.class, DROPPED_ELEMENTS_CONSUMER).subscribe(subscriber);
}
 
Example 16
Source File: DefaultRSocketClient.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
public void accept(RSocket rSocket, Throwable t) {
  if (this.isCancelled()) {
    return;
  }

  Payload payload = PAYLOAD.getAndSet(this, null);

  // means cancelled
  if (payload == null) {
    return;
  }

  if (t != null) {
    if (payload.refCnt() > 0) {
      try {
        payload.release();
      } catch (IllegalReferenceCountException e) {
        // ignored
      }
    }
    onError(t);
    return;
  }

  CorePublisher<?> source;
  switch (this.interactionType) {
    case REQUEST_FNF:
      source = rSocket.fireAndForget(payload);
      break;
    case REQUEST_RESPONSE:
      source = rSocket.requestResponse(payload);
      break;
    case REQUEST_STREAM:
      source = rSocket.requestStream(payload);
      break;
    case METADATA_PUSH:
      source = rSocket.metadataPush(payload);
      break;
    default:
      this.onError(new IllegalStateException("Should never happen"));
      return;
  }

  source.subscribe((CoreSubscriber) this);
}
 
Example 17
Source File: RSocketConnector.java    From rsocket-java with Apache License 2.0 3 votes vote down vote up
/**
 * Provide a {@code Payload} with data and/or metadata for the initial {@code SETUP} frame. Data
 * and metadata should be formatted according to the MIME types specified via {@link
 * #dataMimeType(String)} and {@link #metadataMimeType(String)}.
 *
 * @param payload the payload containing data and/or metadata for the {@code SETUP} frame. Note,
 *     if the instance of the given payload is not a {@link DefaultPayload}, its content will be
 *     copied
 * @return the same instance for method chaining
 * @see <a href="https://github.com/rsocket/rsocket/blob/master/Protocol.md#frame-setup">SETUP
 *     Frame</a>
 */
public RSocketConnector setupPayload(Payload payload) {
  if (payload instanceof DefaultPayload) {
    this.setupPayload = payload;
  } else {
    this.setupPayload = DefaultPayload.create(Objects.requireNonNull(payload));
    payload.release();
  }
  return this;
}