Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/rate limiter publisher #672

Merged
merged 3 commits into from
Aug 5, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 11 additions & 10 deletions rsocket-core/src/main/java/io/rsocket/RSocketRequester.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
import io.rsocket.exceptions.Exceptions;
import io.rsocket.frame.*;
import io.rsocket.frame.decoder.PayloadDecoder;
import io.rsocket.internal.LimitableRequestPublisher;
import io.rsocket.internal.RateLimitableRequestPublisher;
import io.rsocket.internal.SynchronizedIntObjectHashMap;
import io.rsocket.internal.UnboundedProcessor;
import io.rsocket.internal.UnicastMonoProcessor;
Expand All @@ -47,6 +47,7 @@
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import reactor.core.publisher.*;
import reactor.util.concurrent.Queues;

/**
* Requester Side of a RSocket socket. Sends {@link ByteBuf}s to a {@link RSocketResponder} of peer
Expand All @@ -60,7 +61,7 @@ class RSocketRequester implements RSocket {
private final PayloadDecoder payloadDecoder;
private final Consumer<Throwable> errorConsumer;
private final StreamIdSupplier streamIdSupplier;
private final IntObjectMap<LimitableRequestPublisher> senders;
private final IntObjectMap<RateLimitableRequestPublisher> senders;
private final IntObjectMap<Processor<Payload, Payload>> receivers;
private final UnboundedProcessor<ByteBuf> sendProcessor;
private final RequesterLeaseHandler leaseHandler;
Expand Down Expand Up @@ -131,7 +132,7 @@ private void handleSendProcessorError(Throwable t) {
}
});

senders.values().forEach(LimitableRequestPublisher::cancel);
senders.values().forEach(RateLimitableRequestPublisher::cancel);
}

private void handleSendProcessorCancel(SignalType t) {
Expand All @@ -150,7 +151,7 @@ private void handleSendProcessorCancel(SignalType t) {
}
});

senders.values().forEach(LimitableRequestPublisher::cancel);
senders.values().forEach(RateLimitableRequestPublisher::cancel);
}

@Override
Expand Down Expand Up @@ -343,8 +344,8 @@ public void accept(long n) {
request
.transform(
f -> {
LimitableRequestPublisher<Payload> wrapped =
LimitableRequestPublisher.wrap(f);
RateLimitableRequestPublisher<Payload> wrapped =
RateLimitableRequestPublisher.wrap(f, Queues.SMALL_BUFFER_SIZE);
// Need to set this to one for first the frame
wrapped.request(1);
senders.put(streamId, wrapped);
Expand Down Expand Up @@ -421,7 +422,7 @@ protected void hookOnError(Throwable t) {
.doFinally(
s -> {
receivers.remove(streamId);
LimitableRequestPublisher sender = senders.remove(streamId);
RateLimitableRequestPublisher sender = senders.remove(streamId);
if (sender != null) {
sender.cancel();
}
Expand Down Expand Up @@ -489,7 +490,7 @@ private void setTerminationError(Throwable error) {
}

private synchronized void cleanUpLimitableRequestPublisher(
LimitableRequestPublisher<?> limitableRequestPublisher) {
RateLimitableRequestPublisher<?> limitableRequestPublisher) {
try {
limitableRequestPublisher.cancel();
} catch (Throwable t) {
Expand Down Expand Up @@ -561,7 +562,7 @@ private void handleFrame(int streamId, FrameType type, ByteBuf frame) {
break;
case CANCEL:
{
LimitableRequestPublisher sender = senders.remove(streamId);
RateLimitableRequestPublisher sender = senders.remove(streamId);
if (sender != null) {
sender.cancel();
}
Expand All @@ -572,7 +573,7 @@ private void handleFrame(int streamId, FrameType type, ByteBuf frame) {
break;
case REQUEST_N:
{
LimitableRequestPublisher sender = senders.get(streamId);
RateLimitableRequestPublisher sender = senders.get(streamId);
if (sender != null) {
int n = RequestNFrameFlyweight.requestN(frame);
sender.request(n >= Integer.MAX_VALUE ? Long.MAX_VALUE : n);
Expand Down
9 changes: 5 additions & 4 deletions rsocket-core/src/main/java/io/rsocket/RSocketResponder.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
import io.rsocket.exceptions.ApplicationErrorException;
import io.rsocket.frame.*;
import io.rsocket.frame.decoder.PayloadDecoder;
import io.rsocket.internal.LimitableRequestPublisher;
import io.rsocket.internal.RateLimitableRequestPublisher;
import io.rsocket.internal.SynchronizedIntObjectHashMap;
import io.rsocket.internal.UnboundedProcessor;
import io.rsocket.lease.ResponderLeaseHandler;
Expand All @@ -35,6 +35,7 @@
import reactor.core.Disposable;
import reactor.core.Exceptions;
import reactor.core.publisher.*;
import reactor.util.concurrent.Queues;

/** Responder side of RSocket. Receives {@link ByteBuf}s from a peer's {@link RSocketRequester} */
class RSocketResponder implements ResponderRSocket {
Expand All @@ -46,7 +47,7 @@ class RSocketResponder implements ResponderRSocket {
private final Consumer<Throwable> errorConsumer;
private final ResponderLeaseHandler leaseHandler;

private final IntObjectMap<LimitableRequestPublisher> sendingLimitableSubscriptions;
private final IntObjectMap<RateLimitableRequestPublisher> sendingLimitableSubscriptions;
private final IntObjectMap<Subscription> sendingSubscriptions;
private final IntObjectMap<Processor<Payload, Payload>> channelProcessors;

Expand Down Expand Up @@ -435,8 +436,8 @@ private void handleStream(int streamId, Flux<Payload> response, int initialReque
response
.transform(
frameFlux -> {
LimitableRequestPublisher<Payload> payloads =
LimitableRequestPublisher.wrap(frameFlux);
RateLimitableRequestPublisher<Payload> payloads =
RateLimitableRequestPublisher.wrap(frameFlux, Queues.SMALL_BUFFER_SIZE);
sendingLimitableSubscriptions.put(streamId, payloads);
payloads.request(
initialRequestN >= Integer.MAX_VALUE ? Long.MAX_VALUE : initialRequestN);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,242 @@
/*
* Copyright 2015-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.rsocket.internal;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import javax.annotation.Nullable;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import reactor.core.CoreSubscriber;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Operators;

/** */
public class RateLimitableRequestPublisher<T> extends Flux<T> implements Subscription {

private static final int NOT_CANCELED_STATE = 0;
private static final int CANCELED_STATE = 1;

private final Publisher<T> source;

private volatile int canceled;
private static final AtomicIntegerFieldUpdater<RateLimitableRequestPublisher> CANCELED =
AtomicIntegerFieldUpdater.newUpdater(RateLimitableRequestPublisher.class, "canceled");

private final long prefetch;
private final long limit;

private long externalRequested; // need sync
private int pendingToFulfil; // need sync since should be checked/zerroed in onNext
// and increased in request
private int deliveredElements; // no need to sync since increased zerroed only in
// the request method

private boolean subscribed;

private @Nullable Subscription internalSubscription;

private RateLimitableRequestPublisher(Publisher<T> source, long prefetch) {
this.source = source;
this.prefetch = prefetch;
this.limit = prefetch == Integer.MAX_VALUE ? Integer.MAX_VALUE : (prefetch - (prefetch >> 2));
}

public static <T> RateLimitableRequestPublisher<T> wrap(Publisher<T> source, long prefetch) {
return new RateLimitableRequestPublisher<>(source, prefetch);
}

@Override
public void subscribe(CoreSubscriber<? super T> destination) {
synchronized (this) {
if (subscribed) {
throw new IllegalStateException("only one subscriber at a time");
}

subscribed = true;
}
final InnerOperator s = new InnerOperator(destination);

source.subscribe(s);
destination.onSubscribe(s);
}

@Override
public void request(long n) {
synchronized (this) {
long requested = externalRequested;
if (requested == Long.MAX_VALUE) {
Copy link
Member

@yschimke yschimke Jul 29, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't appear to match the logic on line 56. Integer vs Long MAX_VALUE. It's hard to intuit whether that's intentional because there are multiple fields. Maybe some comments to clarify what max values are used.

return;
}
externalRequested = Operators.addCap(n, requested);
}

requestN();
}

private void requestN() {
final long r;
final Subscription s;

synchronized (this) {
s = internalSubscription;
if (s == null) {
return;
}

final long er = externalRequested;
final long p = prefetch;
final int pendingFulfil = pendingToFulfil;

if (er != Long.MAX_VALUE || p != Integer.MAX_VALUE) {
// shortcut
if (pendingFulfil == p) {
return;
}

r = Math.min(p - pendingFulfil, er);
if (er != Long.MAX_VALUE) {
externalRequested -= r;
}
if (p != Integer.MAX_VALUE) {
pendingToFulfil += r;
}
} else {
r = Long.MAX_VALUE;
}
}

if (r > 0) {
s.request(r);
}
}

public void cancel() {
if (!isCanceled() && CANCELED.compareAndSet(this, NOT_CANCELED_STATE, CANCELED_STATE)) {
Subscription s;

synchronized (this) {
s = internalSubscription;
internalSubscription = null;
subscribed = false;
}

if (s != null) {
s.cancel();
}
}
}

private boolean isCanceled() {
return canceled == CANCELED_STATE;
}

private class InnerOperator implements CoreSubscriber<T>, Subscription {
final Subscriber<? super T> destination;

private InnerOperator(Subscriber<? super T> destination) {
this.destination = destination;
}

@Override
public void onSubscribe(Subscription s) {
synchronized (RateLimitableRequestPublisher.this) {
RateLimitableRequestPublisher.this.internalSubscription = s;

if (isCanceled()) {
s.cancel();
subscribed = false;
RateLimitableRequestPublisher.this.internalSubscription = null;
}
}

requestN();
}

@Override
public void onNext(T t) {
try {
destination.onNext(t);

if (prefetch == Integer.MAX_VALUE) {
return;
}

final long l = limit;
int d = deliveredElements + 1;

if (d == l) {
d = 0;
final long r;
final Subscription s;

synchronized (RateLimitableRequestPublisher.this) {
long er = externalRequested;
s = internalSubscription;

if (s == null) {
return;
}

if (er >= l) {
er -= l;
// keep pendingToFulfil as is since it is eq to prefetch
r = l;
} else {
pendingToFulfil -= l;
if (er > 0) {
r = er;
er = 0;
pendingToFulfil += r;
} else {
r = 0;
}
}

externalRequested = er;
}

if (r > 0) {
s.request(r);
}
}

deliveredElements = d;
} catch (Throwable e) {
onError(e);
}
}

@Override
public void onError(Throwable t) {
destination.onError(t);
}

@Override
public void onComplete() {
destination.onComplete();
}

@Override
public void request(long n) {}

@Override
public void cancel() {
RateLimitableRequestPublisher.this.cancel();
}
}
}
Loading