1
+ package io .grpc .examples .deadline ;
2
+
3
+ import java .util .concurrent .ScheduledExecutorService ;
4
+ import java .util .concurrent .TimeUnit ;
5
+
6
+ import io .grpc .Context ;
7
+ import io .grpc .Contexts ;
8
+ import io .grpc .Metadata ;
9
+ import io .grpc .ServerCall ;
10
+ import io .grpc .ServerCallHandler ;
11
+ import io .grpc .ServerInterceptor ;
12
+ import io .grpc .Status ;
13
+
14
+ import static com .google .common .util .concurrent .MoreExecutors .directExecutor ;
15
+ import static io .grpc .Contexts .statusFromCancelled ;
16
+ import static io .grpc .Status .DEADLINE_EXCEEDED ;
17
+
18
+ class DeadlineServerInterceptor implements ServerInterceptor {
19
+ public static final Metadata .Key <String > GRPC_DEADLINE = Metadata .Key .of ("grpc-deadline" ,
20
+ Metadata .ASCII_STRING_MARSHALLER );
21
+
22
+ private final ScheduledExecutorService scheduler ;
23
+
24
+ public DeadlineServerInterceptor (ScheduledExecutorService scheduler ) {
25
+ this .scheduler = scheduler ;
26
+ }
27
+
28
+ @ Override
29
+ public <ReqT , RespT > ServerCall .Listener <ReqT > interceptCall (ServerCall <ReqT , RespT > call , Metadata headers ,
30
+ ServerCallHandler <ReqT , RespT > next ) {
31
+
32
+ Context .CancellableContext context = Context .current ()
33
+ .fork ()
34
+ .withDeadlineAfter (100 , TimeUnit .MILLISECONDS , scheduler );
35
+
36
+ context .addListener (ctx -> {
37
+ Status status = statusFromCancelled (ctx );
38
+ if (DEADLINE_EXCEEDED .getCode ().equals (status .getCode ())) {
39
+ call .close (status , new Metadata ());
40
+ }
41
+ }, directExecutor ());
42
+
43
+ return Contexts .interceptCall (context , call , headers , next );
44
+ }
45
+ }
0 commit comments