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

implement request timeout annotation #4499

Merged
merged 19 commits into from
Dec 9, 2022
Merged
Show file tree
Hide file tree
Changes from 8 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
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import com.linecorp.armeria.server.annotation.ServerSentEventResponseConverterFunction;
import com.linecorp.armeria.server.annotation.decorator.LoggingDecoratorFactoryFunction;
import com.linecorp.armeria.server.annotation.decorator.RateLimitingDecoratorFactoryFunction;
import com.linecorp.armeria.server.annotation.decorator.RequestTimeoutDecoratorFunction;

public enum BuiltInDependencyInjector implements DependencyInjector {

Expand All @@ -36,7 +37,8 @@ public enum BuiltInDependencyInjector implements DependencyInjector {
private static final Set<Class<?>> builtInClasses =
ImmutableSet.of(LoggingDecoratorFactoryFunction.class,
RateLimitingDecoratorFactoryFunction.class,
ServerSentEventResponseConverterFunction.class);
ServerSentEventResponseConverterFunction.class,
RequestTimeoutDecoratorFunction.class);

private static final Map<Class<?>, Object> instances = new ConcurrentHashMap<>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ private void setTimeoutNanosFromStart(long timeoutNanos) {
eventLoop.execute(() -> setTimeoutNanosFromStart0(timeoutNanos));
}
} else {
addPendingTimeoutNanos(timeoutNanos);
setPendingTimeoutNanos(timeoutNanos);
mscheong01 marked this conversation as resolved.
Show resolved Hide resolved
addPendingTask(() -> setTimeoutNanosFromStart0(timeoutNanos));
}
}
Expand Down Expand Up @@ -260,18 +260,18 @@ private void setTimeoutNanosFromNow(long timeoutNanos) {
if (eventLoop.inEventLoop()) {
setTimeoutNanosFromNow0(timeoutNanos);
} else {
final long startTimeNanos = System.nanoTime();
final long eventLoopStartTimeNanos = System.nanoTime();
eventLoop.execute(() -> {
final long passedTimeNanos0 = System.nanoTime() - startTimeNanos;
final long passedTimeNanos0 = System.nanoTime() - eventLoopStartTimeNanos;
final long timeoutNanos0 = Math.max(1, timeoutNanos - passedTimeNanos0);
setTimeoutNanosFromNow0(timeoutNanos0);
});
}
} else {
final long startTimeNanos = System.nanoTime();
final long pendingTaskRegisterTimeNanos = System.nanoTime();
setPendingTimeoutNanos(timeoutNanos);
addPendingTask(() -> {
final long passedTimeNanos0 = System.nanoTime() - startTimeNanos;
final long passedTimeNanos0 = System.nanoTime() - pendingTaskRegisterTimeNanos;
final long timeoutNanos0 = Math.max(1, timeoutNanos - passedTimeNanos0);
setTimeoutNanosFromNow0(timeoutNanos0);
});
Expand Down Expand Up @@ -411,7 +411,8 @@ public CompletableFuture<Void> whenTimedOut() {
}
}

private boolean isInitialized() {
@VisibleForTesting
public boolean isInitialized() {
return pendingTask == noopPendingTask && eventLoop != null;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* Copyright 2022 LINE Corporation
*
* LINE Corporation licenses this file to you 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:
*
* https://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 com.linecorp.armeria.server.annotation.decorator;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.concurrent.TimeUnit;

import com.linecorp.armeria.server.annotation.DecoratorFactory;

/**
* Annotation for request timeout.
*/
@DecoratorFactory(RequestTimeoutDecoratorFunction.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface RequestTimeout {
mscheong01 marked this conversation as resolved.
Show resolved Hide resolved

/**
* Value of request timeout to set.
*/
long value();

/**
* Time unit of request timeout to set.
*/
TimeUnit unit() default TimeUnit.MILLISECONDS;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* Copyright 2022 LINE Corporation
*
* LINE Corporation licenses this file to you 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:
*
* https://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 com.linecorp.armeria.server.annotation.decorator;

import java.util.function.Function;

import com.linecorp.armeria.common.HttpRequest;
import com.linecorp.armeria.common.HttpResponse;
import com.linecorp.armeria.common.util.TimeoutMode;
import com.linecorp.armeria.server.HttpService;
import com.linecorp.armeria.server.ServiceRequestContext;
import com.linecorp.armeria.server.SimpleDecoratingHttpService;
import com.linecorp.armeria.server.annotation.DecoratorFactoryFunction;

/**
* A factory which creates a decorator that sets request timeout to current {@link ServiceRequestContext}.
*/
public final class RequestTimeoutDecoratorFunction implements DecoratorFactoryFunction<RequestTimeout> {

/**
* Creates a new decorator with the specified {@code parameter}.
mscheong01 marked this conversation as resolved.
Show resolved Hide resolved
*/
@Override
public Function<? super HttpService, ? extends HttpService> newDecorator(RequestTimeout parameter) {
final long timeoutMillis = parameter.unit().toMillis(parameter.value());
return delegate -> new SimpleDecoratingHttpService(delegate) {
@Override
public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) throws Exception {
ServiceRequestContext.current()
.setRequestTimeoutMillis(TimeoutMode.SET_FROM_START, timeoutMillis);
mscheong01 marked this conversation as resolved.
Show resolved Hide resolved
return delegate.serve(ctx, req);
}
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
* Copyright 2022 LINE Corporation
*
* LINE Corporation licenses this file to you 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:
*
* https://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 com.linecorp.armeria.internal.server.annotation;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.concurrent.TimeUnit;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import com.linecorp.armeria.client.BlockingWebClient;
import com.linecorp.armeria.common.AggregatedHttpResponse;
import com.linecorp.armeria.common.HttpMethod;
import com.linecorp.armeria.common.HttpRequest;
import com.linecorp.armeria.common.HttpStatus;
import com.linecorp.armeria.common.RequestHeaders;
import com.linecorp.armeria.internal.server.DefaultServiceRequestContext;
import com.linecorp.armeria.server.ServerBuilder;
import com.linecorp.armeria.server.ServiceRequestContext;
import com.linecorp.armeria.server.annotation.Get;
import com.linecorp.armeria.server.annotation.decorator.RequestTimeout;
import com.linecorp.armeria.testing.junit5.server.ServerExtension;

public class RequestTimeoutAnnotationTest {
mscheong01 marked this conversation as resolved.
Show resolved Hide resolved

@RegisterExtension
static ServerExtension server = new ServerExtension() {
@Override
protected void configure(ServerBuilder sb) throws Exception {
sb.annotatedService("/myService", new MyAnnotationService());
}
};

static final long timeoutMillis = 1230;
static final long timeoutSeconds = 4560;

public static class MyAnnotationService {
@Get("/timeoutMillis")
@RequestTimeout(timeoutMillis)
public String timeoutMillis(ServiceRequestContext ctx, HttpRequest req) {
AnnotatedServiceTest.validateContextAndRequest(ctx, req);
return Long.toString(ctx.requestTimeoutMillis());
}

@Get("/timeoutSeconds")
@RequestTimeout(value = timeoutSeconds, unit = TimeUnit.SECONDS)
public String timeoutSeconds(ServiceRequestContext ctx, HttpRequest req) {
AnnotatedServiceTest.validateContextAndRequest(ctx, req);
return Long.toString(ctx.requestTimeoutMillis());
}

@Get("/subscriberIsInitialized")
public boolean subscriberIsInitialized(ServiceRequestContext ctx, HttpRequest req) {
AnnotatedServiceTest.validateContextAndRequest(ctx, req);
return ((DefaultServiceRequestContext) ctx).requestCancellationScheduler().isInitialized();
}
}

@Test
public void testRequestTimeoutSet() {
mscheong01 marked this conversation as resolved.
Show resolved Hide resolved
final BlockingWebClient client = BlockingWebClient.of(server.httpUri());
mscheong01 marked this conversation as resolved.
Show resolved Hide resolved

AggregatedHttpResponse response;

response = client.execute(RequestHeaders.of(HttpMethod.GET, "/myService/timeoutMillis"));
assertThat(response.status()).isEqualTo(HttpStatus.OK);
assertThat(Long.parseLong(response.contentUtf8())).isEqualTo(timeoutMillis);

response = client.execute(RequestHeaders.of(HttpMethod.GET, "/myService/timeoutSeconds"));
assertThat(response.status()).isEqualTo(HttpStatus.OK);
assertThat(Long.parseLong(response.contentUtf8()))
.isEqualTo(TimeUnit.SECONDS.toMillis(timeoutSeconds));
}

@Test
public void testCancellationSchedulerInit() {
final BlockingWebClient client = BlockingWebClient.of(server.httpUri());

final AggregatedHttpResponse response = client.execute(
RequestHeaders.of(HttpMethod.GET, "/myService/timeoutMillis"));
assertThat(response.status()).isEqualTo(HttpStatus.OK);
assertThat(Boolean.parseBoolean(response.contentUtf8())).isEqualTo(true);
}
}