summaryrefslogtreecommitdiffstats
path: root/javatests/com/google/gerrit/acceptance/rest/CancellationIT.java
blob: ed5e5595512e97734dcfdedd7a70b023770c9b4c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
// Copyright (C) 2021 The Android Open Source Project
//
// 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 com.google.gerrit.acceptance.rest;

import static com.google.common.truth.Truth.assertThat;
import static com.google.gerrit.httpd.restapi.RestApiServlet.SC_CLIENT_CLOSED_REQUEST;
import static org.apache.http.HttpStatus.SC_REQUEST_TIMEOUT;

import com.google.gerrit.acceptance.AbstractDaemonTest;
import com.google.gerrit.acceptance.ExtensionRegistry;
import com.google.gerrit.acceptance.ExtensionRegistry.Registration;
import com.google.gerrit.acceptance.PushOneCommit;
import com.google.gerrit.acceptance.RestResponse;
import com.google.gerrit.acceptance.config.GerritConfig;
import com.google.gerrit.httpd.restapi.RestApiServlet;
import com.google.gerrit.server.cancellation.RequestCancelledException;
import com.google.gerrit.server.cancellation.RequestStateProvider;
import com.google.gerrit.server.events.CommitReceivedEvent;
import com.google.gerrit.server.git.validators.CommitValidationException;
import com.google.gerrit.server.git.validators.CommitValidationListener;
import com.google.gerrit.server.git.validators.CommitValidationMessage;
import com.google.gerrit.server.project.CreateProjectArgs;
import com.google.gerrit.server.validators.ProjectCreationValidationListener;
import com.google.gerrit.server.validators.ValidationException;
import com.google.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.message.BasicHeader;
import org.junit.Test;

public class CancellationIT extends AbstractDaemonTest {
  @Inject private ExtensionRegistry extensionRegistry;

  @Test
  public void handleClientDisconnected() throws Exception {
    ProjectCreationValidationListener projectCreationListener =
        new ProjectCreationValidationListener() {
          @Override
          public void validateNewProject(CreateProjectArgs args) throws ValidationException {
            // Simulate a request cancellation by throwing RequestCancelledException. In contrast to
            // an actual request cancellation this allows us to verify the HTTP status code that is
            // set when a request is cancelled.
            throw new RequestCancelledException(
                RequestStateProvider.Reason.CLIENT_CLOSED_REQUEST, /* cancellationMessage= */ null);
          }
        };
    try (Registration registration =
        extensionRegistry.newRegistration().add(projectCreationListener)) {
      RestResponse response = adminRestSession.put("/projects/" + name("new"));
      assertThat(response.getStatusCode()).isEqualTo(SC_CLIENT_CLOSED_REQUEST);
      assertThat(response.getEntityContent()).isEqualTo("Client Closed Request");
    }
  }

  @Test
  public void handleClientDeadlineExceeded() throws Exception {
    ProjectCreationValidationListener projectCreationListener =
        new ProjectCreationValidationListener() {
          @Override
          public void validateNewProject(CreateProjectArgs args) throws ValidationException {
            // Simulate an exceeded deadline by throwing RequestCancelledException.
            throw new RequestCancelledException(
                RequestStateProvider.Reason.CLIENT_PROVIDED_DEADLINE_EXCEEDED,
                /* cancellationMessage= */ null);
          }
        };
    try (Registration registration =
        extensionRegistry.newRegistration().add(projectCreationListener)) {
      RestResponse response = adminRestSession.put("/projects/" + name("new"));
      assertThat(response.getStatusCode()).isEqualTo(SC_REQUEST_TIMEOUT);
      assertThat(response.getEntityContent()).isEqualTo("Client Provided Deadline Exceeded");
    }
  }

  @Test
  public void handleServerDeadlineExceeded() throws Exception {
    ProjectCreationValidationListener projectCreationListener =
        new ProjectCreationValidationListener() {
          @Override
          public void validateNewProject(CreateProjectArgs args) throws ValidationException {
            // Simulate an exceeded deadline by throwing RequestCancelledException.
            throw new RequestCancelledException(
                RequestStateProvider.Reason.SERVER_DEADLINE_EXCEEDED,
                /* cancellationMessage= */ null);
          }
        };
    try (Registration registration =
        extensionRegistry.newRegistration().add(projectCreationListener)) {
      RestResponse response = adminRestSession.put("/projects/" + name("new"));
      assertThat(response.getStatusCode()).isEqualTo(SC_REQUEST_TIMEOUT);
      assertThat(response.getEntityContent()).isEqualTo("Server Deadline Exceeded");
    }
  }

  @Test
  public void handleRequestCancellationWithMessage() throws Exception {
    ProjectCreationValidationListener projectCreationListener =
        new ProjectCreationValidationListener() {
          @Override
          public void validateNewProject(CreateProjectArgs args) throws ValidationException {
            // Simulate an exceeded deadline by throwing RequestCancelledException.
            throw new RequestCancelledException(
                RequestStateProvider.Reason.SERVER_DEADLINE_EXCEEDED, "deadline = 10m");
          }
        };
    try (Registration registration =
        extensionRegistry.newRegistration().add(projectCreationListener)) {
      RestResponse response = adminRestSession.put("/projects/" + name("new"));
      assertThat(response.getStatusCode()).isEqualTo(SC_REQUEST_TIMEOUT);
      assertThat(response.getEntityContent())
          .isEqualTo("Server Deadline Exceeded\n\ndeadline = 10m");
    }
  }

  @Test
  public void handleWrappedRequestCancelledException() throws Exception {
    ProjectCreationValidationListener projectCreationListener =
        new ProjectCreationValidationListener() {
          @Override
          public void validateNewProject(CreateProjectArgs args) throws ValidationException {
            // Simulate an exceeded deadline by throwing RequestCancelledException.
            throw new RuntimeException(
                new RequestCancelledException(
                    RequestStateProvider.Reason.SERVER_DEADLINE_EXCEEDED, "deadline = 10m"));
          }
        };
    try (Registration registration =
        extensionRegistry.newRegistration().add(projectCreationListener)) {
      RestResponse response = adminRestSession.put("/projects/" + name("new"));
      assertThat(response.getStatusCode()).isEqualTo(SC_REQUEST_TIMEOUT);
      assertThat(response.getEntityContent())
          .isEqualTo("Server Deadline Exceeded\n\ndeadline = 10m");
    }
  }

  @Test
  public void abortIfClientProvidedDeadlineExceeded() throws Exception {
    RestResponse response =
        adminRestSession.putWithHeaders(
            "/projects/" + name("new"), new BasicHeader(RestApiServlet.X_GERRIT_DEADLINE, "1ms"));
    assertThat(response.getStatusCode()).isEqualTo(SC_REQUEST_TIMEOUT);
    assertThat(response.getEntityContent())
        .isEqualTo("Client Provided Deadline Exceeded\n\nclient.timeout=1ms");
  }

  @Test
  public void requestRejectedIfInvalidDeadlineIsProvided_missingTimeUnit() throws Exception {
    RestResponse response =
        adminRestSession.putWithHeaders(
            "/projects/" + name("new"), new BasicHeader(RestApiServlet.X_GERRIT_DEADLINE, "1"));
    response.assertBadRequest();
    assertThat(response.getEntityContent()).isEqualTo("Invalid deadline. Missing time unit: 1");
  }

  @Test
  public void requestRejectedIfInvalidDeadlineIsProvided_invalidTimeUnit() throws Exception {
    RestResponse response =
        adminRestSession.putWithHeaders(
            "/projects/" + name("new"), new BasicHeader(RestApiServlet.X_GERRIT_DEADLINE, "1x"));
    response.assertBadRequest();
    assertThat(response.getEntityContent())
        .isEqualTo("Invalid deadline. Invalid time unit value: 1x");
  }

  @Test
  public void requestRejectedIfInvalidDeadlineIsProvided_invalidValue() throws Exception {
    RestResponse response =
        adminRestSession.putWithHeaders(
            "/projects/" + name("new"),
            new BasicHeader(RestApiServlet.X_GERRIT_DEADLINE, "invalid"));
    response.assertBadRequest();
    assertThat(response.getEntityContent()).isEqualTo("Invalid deadline. Invalid value: invalid");
  }

  @Test
  public void requestSucceedsWithinDeadline() throws Exception {
    RestResponse response =
        adminRestSession.putWithHeaders(
            "/projects/" + name("new"), new BasicHeader(RestApiServlet.X_GERRIT_DEADLINE, "10m"));
    response.assertCreated();
  }

  @GerritConfig(name = "deadline.default.timeout", value = "1ms")
  public void abortIfServerDeadlineExceeded() throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    assertThat(response.getStatusCode()).isEqualTo(SC_REQUEST_TIMEOUT);
    assertThat(response.getEntityContent()).isEqualTo("Server Deadline Exceeded\n\ntimeout=1ms");
  }

  @Test
  @GerritConfig(name = "deadline.foo.timeout", value = "1ms")
  @GerritConfig(name = "deadline.bar.timeout", value = "100ms")
  public void stricterDeadlineTakesPrecedence() throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    assertThat(response.getStatusCode()).isEqualTo(SC_REQUEST_TIMEOUT);
    assertThat(response.getEntityContent())
        .isEqualTo("Server Deadline Exceeded\n\nfoo.timeout=1ms");
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "1ms")
  @GerritConfig(name = "deadline.default.requestType", value = "REST")
  public void abortIfServerDeadlineExceeded_requestType() throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    assertThat(response.getStatusCode()).isEqualTo(SC_REQUEST_TIMEOUT);
    assertThat(response.getEntityContent())
        .isEqualTo("Server Deadline Exceeded\n\ndefault.timeout=1ms");
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "1ms")
  @GerritConfig(name = "deadline.default.requestUriPattern", value = "/projects/.*")
  public void abortIfServerDeadlineExceeded_requestUriPattern() throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    assertThat(response.getStatusCode()).isEqualTo(SC_REQUEST_TIMEOUT);
    assertThat(response.getEntityContent())
        .isEqualTo("Server Deadline Exceeded\n\ndefault.timeout=1ms");
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "1ms")
  @GerritConfig(
      name = "deadline.default.excludedRequestUriPattern",
      value = "/projects/non-matching")
  public void abortIfServerDeadlineExceeded_excludedRequestUriPattern() throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    assertThat(response.getStatusCode()).isEqualTo(SC_REQUEST_TIMEOUT);
    assertThat(response.getEntityContent())
        .isEqualTo("Server Deadline Exceeded\n\ndefault.timeout=1ms");
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "1ms")
  @GerritConfig(name = "deadline.default.requestUriPattern", value = "/projects/.*")
  @GerritConfig(
      name = "deadline.default.excludedRequestUriPattern",
      value = "/projects/non-matching")
  public void abortIfServerDeadlineExceeded_requestUriPatternAndExcludedRequestUriPattern()
      throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    assertThat(response.getStatusCode()).isEqualTo(SC_REQUEST_TIMEOUT);
    assertThat(response.getEntityContent())
        .isEqualTo("Server Deadline Exceeded\n\ndefault.timeout=1ms");
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "1ms")
  @GerritConfig(name = "deadline.default.projectPattern", value = ".*new.*")
  public void abortIfServerDeadlineExceeded_projectPattern() throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    assertThat(response.getStatusCode()).isEqualTo(SC_REQUEST_TIMEOUT);
    assertThat(response.getEntityContent())
        .isEqualTo("Server Deadline Exceeded\n\ndefault.timeout=1ms");
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "1ms")
  @GerritConfig(name = "deadline.default.account", value = "1000000")
  public void abortIfServerDeadlineExceeded_account() throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    assertThat(response.getStatusCode()).isEqualTo(SC_REQUEST_TIMEOUT);
    assertThat(response.getEntityContent())
        .isEqualTo("Server Deadline Exceeded\n\ndefault.timeout=1ms");
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "1ms")
  @GerritConfig(name = "deadline.default.requestType", value = "SSH")
  public void nonMatchingServerDeadlineIsIgnored_requestType() throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    response.assertCreated();
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "1ms")
  @GerritConfig(name = "deadline.default.requestUriPattern", value = "/changes/.*")
  public void nonMatchingServerDeadlineIsIgnored_requestUriPattern() throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    response.assertCreated();
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "1ms")
  @GerritConfig(name = "deadline.default.excludedRequestUriPattern", value = "/projects/.*")
  public void nonMatchingServerDeadlineIsIgnored_excludedRequestUriPattern() throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    response.assertCreated();
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "1ms")
  @GerritConfig(name = "deadline.default.requestUriPattern", value = "/projects/.*")
  @GerritConfig(name = "deadline.default.excludedRequestUriPattern", value = "/projects/.*new")
  public void nonMatchingServerDeadlineIsIgnored_requestUriPatternAndExcludedRequestUriPattern()
      throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    response.assertCreated();
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "1ms")
  @GerritConfig(name = "deadline.default.projectPattern", value = ".*foo.*")
  public void nonMatchingServerDeadlineIsIgnored_projectPattern() throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    response.assertCreated();
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "1ms")
  @GerritConfig(name = "deadline.default.account", value = "999")
  public void nonMatchingServerDeadlineIsIgnored_account() throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    response.assertCreated();
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "1ms")
  @GerritConfig(name = "deadline.default.isAdvisory", value = "true")
  public void advisoryServerDeadlineIsIgnored() throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    response.assertCreated();
  }

  @Test
  @GerritConfig(name = "deadline.test.timeout", value = "1ms")
  @GerritConfig(name = "deadline.test.isAdvisory", value = "true")
  @GerritConfig(name = "deadline.default.timeout", value = "2ms")
  public void nonAdvisoryDeadlineIsAppliedIfStricterAdvisoryDeadlineExists() throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    assertThat(response.getStatusCode()).isEqualTo(SC_REQUEST_TIMEOUT);
    assertThat(response.getEntityContent())
        .isEqualTo("Server Deadline Exceeded\n\ndefault.timeout=2ms");
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "1")
  public void invalidServerDeadlineIsIgnored_missingTimeUnit() throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    response.assertCreated();
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "1x")
  public void invalidServerDeadlineIsIgnored_invalidTimeUnit() throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    response.assertCreated();
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "invalid")
  public void invalidServerDeadlineIsIgnored_invalidValue() throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    response.assertCreated();
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "1ms")
  @GerritConfig(name = "deadline.default.requestType", value = "INVALID")
  public void invalidServerDeadlineIsIgnored_invalidRequestType() throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    response.assertCreated();
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "1ms")
  @GerritConfig(name = "deadline.default.requestUriPattern", value = "][")
  public void invalidServerDeadlineIsIgnored_invalidRequestUriPattern() throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    response.assertCreated();
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "1ms")
  @GerritConfig(name = "deadline.default.excludedRequestUriPattern", value = "][")
  public void invalidServerDeadlineIsIgnored_invalidExcludedRequestUriPattern() throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    response.assertCreated();
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "1ms")
  @GerritConfig(name = "deadline.default.projectPattern", value = "][")
  public void invalidServerDeadlineIsIgnored_invalidProjectPattern() throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    response.assertCreated();
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "1ms")
  @GerritConfig(name = "deadline.default.account", value = "invalid")
  public void invalidServerDeadlineIsIgnored_invalidAccount() throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    response.assertCreated();
  }

  @Test
  @GerritConfig(name = "deadline.default.requestType", value = "REST")
  public void deadlineConfigWithoutTimeoutIsIgnored() throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    response.assertCreated();
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "0ms")
  @GerritConfig(name = "deadline.default.requestType", value = "REST")
  public void deadlineConfigWithZeroTimeoutIsIgnored() throws Exception {
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
    response.assertCreated();
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "500ms")
  public void exceededDeadlineForOneRequestDoesntAbortFollowUpRequest() throws Exception {
    ProjectCreationValidationListener projectCreationValidationListener =
        new ProjectCreationValidationListener() {
          @Override
          public void validateNewProject(CreateProjectArgs args) throws ValidationException {
            try {
              Thread.sleep(1000);
            } catch (InterruptedException e) {
              throw new RuntimeException("interrupted during sleep", e);
            }
          }
        };
    try (Registration registration =
        extensionRegistry.newRegistration().add(projectCreationValidationListener)) {
      RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new"));
      assertThat(response.getStatusCode()).isEqualTo(SC_REQUEST_TIMEOUT);
      assertThat(response.getEntityContent())
          .isEqualTo("Server Deadline Exceeded\n\ndefault.timeout=500ms");
    }
    // verify that the exceeded deadline for the previous request, isn't applied to a new request
    RestResponse response = adminRestSession.putWithHeaders("/projects/" + name("new2"));
    response.assertCreated();
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "1ms")
  public void clientProvidedDeadlineOverridesServerDeadline() throws Exception {
    RestResponse response =
        adminRestSession.putWithHeaders(
            "/projects/" + name("new"), new BasicHeader(RestApiServlet.X_GERRIT_DEADLINE, "2ms"));
    assertThat(response.getStatusCode()).isEqualTo(SC_REQUEST_TIMEOUT);
    assertThat(response.getEntityContent())
        .isEqualTo("Client Provided Deadline Exceeded\n\nclient.timeout=2ms");
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "1ms")
  public void clientCanDisableDeadlineBySettingZeroAsDeadline() throws Exception {
    RestResponse response =
        adminRestSession.putWithHeaders(
            "/projects/" + name("new"), new BasicHeader(RestApiServlet.X_GERRIT_DEADLINE, "0"));
    response.assertCreated();
  }

  @Test
  public void handleClientDisconnectedForPush() throws Exception {
    CommitValidationListener commitValidationListener =
        new CommitValidationListener() {
          @Override
          public List<CommitValidationMessage> onCommitReceived(CommitReceivedEvent receiveEvent)
              throws CommitValidationException {
            // Simulate a request cancellation by throwing RequestCancelledException. In contrast to
            // an actual request cancellation this allows us verify the error message that is sent
            // to the client.
            throw new RequestCancelledException(
                RequestStateProvider.Reason.CLIENT_CLOSED_REQUEST, /* cancellationMessage= */ null);
          }
        };
    try (Registration registration =
        extensionRegistry.newRegistration().add(commitValidationListener)) {
      PushOneCommit push = pushFactory.create(admin.newIdent(), testRepo);
      PushOneCommit.Result r = push.to("refs/heads/master");
      r.assertErrorStatus("Client Closed Request");
    }
  }

  @Test
  public void handleClientDeadlineExceededForPush() throws Exception {
    CommitValidationListener commitValidationListener =
        new CommitValidationListener() {
          @Override
          public List<CommitValidationMessage> onCommitReceived(CommitReceivedEvent receiveEvent)
              throws CommitValidationException {
            // Simulate an exceeded deadline by throwing RequestCancelledException.
            throw new RequestCancelledException(
                RequestStateProvider.Reason.CLIENT_PROVIDED_DEADLINE_EXCEEDED,
                /* cancellationMessage= */ null);
          }
        };
    try (Registration registration =
        extensionRegistry.newRegistration().add(commitValidationListener)) {
      PushOneCommit push = pushFactory.create(admin.newIdent(), testRepo);
      PushOneCommit.Result r = push.to("refs/heads/master");
      r.assertErrorStatus("Client Provided Deadline Exceeded");
    }
  }

  @Test
  public void handleServerDeadlineExceededForPush() throws Exception {
    CommitValidationListener commitValidationListener =
        new CommitValidationListener() {
          @Override
          public List<CommitValidationMessage> onCommitReceived(CommitReceivedEvent receiveEvent)
              throws CommitValidationException {
            // Simulate an exceeded deadline by throwing RequestCancelledException.
            throw new RequestCancelledException(
                RequestStateProvider.Reason.SERVER_DEADLINE_EXCEEDED,
                /* cancellationMessage= */ null);
          }
        };
    try (Registration registration =
        extensionRegistry.newRegistration().add(commitValidationListener)) {
      PushOneCommit push = pushFactory.create(admin.newIdent(), testRepo);
      PushOneCommit.Result r = push.to("refs/heads/master");
      r.assertErrorStatus("Server Deadline Exceeded");
    }
  }

  @Test
  public void handleWrappedRequestCancelledExceptionForPush() throws Exception {
    CommitValidationListener commitValidationListener =
        new CommitValidationListener() {
          @Override
          public List<CommitValidationMessage> onCommitReceived(CommitReceivedEvent receiveEvent)
              throws CommitValidationException {
            // Simulate an exceeded deadline by throwing RequestCancelledException.
            throw new RuntimeException(
                new RequestCancelledException(
                    RequestStateProvider.Reason.SERVER_DEADLINE_EXCEEDED, "deadline = 10m"));
          }
        };
    try (Registration registration =
        extensionRegistry.newRegistration().add(commitValidationListener)) {
      PushOneCommit push = pushFactory.create(admin.newIdent(), testRepo);
      PushOneCommit.Result r = push.to("refs/heads/master");
      r.assertErrorStatus("Server Deadline Exceeded (deadline = 10m)");
    }
  }

  @Test
  public void handleRequestCancellationWithMessageForPush() throws Exception {
    CommitValidationListener commitValidationListener =
        new CommitValidationListener() {
          @Override
          public List<CommitValidationMessage> onCommitReceived(CommitReceivedEvent receiveEvent)
              throws CommitValidationException {
            // Simulate an exceeded deadline by throwing RequestCancelledException.
            throw new RequestCancelledException(
                RequestStateProvider.Reason.SERVER_DEADLINE_EXCEEDED, "deadline = 10m");
          }
        };
    try (Registration registration =
        extensionRegistry.newRegistration().add(commitValidationListener)) {
      PushOneCommit push = pushFactory.create(admin.newIdent(), testRepo);
      PushOneCommit.Result r = push.to("refs/heads/master");
      r.assertErrorStatus("Server Deadline Exceeded (deadline = 10m)");
    }
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "1ms")
  public void abortPushIfServerDeadlineExceeded() throws Exception {
    PushOneCommit push = pushFactory.create(admin.newIdent(), testRepo);
    PushOneCommit.Result r = push.to("refs/for/master");
    r.assertErrorStatus("Server Deadline Exceeded (default.timeout=1ms)");
  }

  @Test
  @GerritConfig(name = "receive.timeout", value = "1ms")
  public void abortPushIfTimeoutExceeded() throws Exception {
    PushOneCommit push = pushFactory.create(admin.newIdent(), testRepo);
    PushOneCommit.Result r = push.to("refs/for/master");
    r.assertErrorStatus("Server Deadline Exceeded (receive.timeout=1ms)");
  }

  @Test
  @GerritConfig(name = "receive.timeout", value = "1ms")
  @GerritConfig(name = "deadline.default.timeout", value = "10s")
  public void receiveTimeoutTakesPrecedence() throws Exception {
    PushOneCommit push = pushFactory.create(admin.newIdent(), testRepo);
    PushOneCommit.Result r = push.to("refs/for/master");
    r.assertErrorStatus("Server Deadline Exceeded (receive.timeout=1ms)");
  }

  @Test
  public void abortPushIfClientProvidedDeadlineExceeded() throws Exception {
    List<String> pushOptions = new ArrayList<>();
    pushOptions.add("deadline=1ms");
    PushOneCommit push = pushFactory.create(admin.newIdent(), testRepo);
    push.setPushOptions(pushOptions);
    PushOneCommit.Result r = push.to("refs/for/master");
    r.assertErrorStatus("Client Provided Deadline Exceeded (client.timeout=1ms)");
  }

  @Test
  public void pushRejectedIfInvalidDeadlineIsProvided_missingTimeUnit() throws Exception {
    List<String> pushOptions = new ArrayList<>();
    pushOptions.add("deadline=1");
    PushOneCommit push = pushFactory.create(admin.newIdent(), testRepo);
    push.setPushOptions(pushOptions);
    PushOneCommit.Result r = push.to("refs/for/master");
    r.assertErrorStatus("Invalid deadline. Missing time unit: 1");
  }

  @Test
  public void pushRejectedIfInvalidDeadlineIsProvided_invalidTimeUnit() throws Exception {
    List<String> pushOptions = new ArrayList<>();
    pushOptions.add("deadline=1x");
    PushOneCommit push = pushFactory.create(admin.newIdent(), testRepo);
    push.setPushOptions(pushOptions);
    PushOneCommit.Result r = push.to("refs/for/master");
    r.assertErrorStatus("Invalid deadline. Invalid time unit value: 1x");
  }

  @Test
  public void pushRejectedIfInvalidDeadlineIsProvided_invalidValue() throws Exception {
    List<String> pushOptions = new ArrayList<>();
    pushOptions.add("deadline=invalid");
    PushOneCommit push = pushFactory.create(admin.newIdent(), testRepo);
    push.setPushOptions(pushOptions);
    PushOneCommit.Result r = push.to("refs/for/master");
    r.assertErrorStatus("Invalid deadline. Invalid value: invalid");
  }

  @Test
  public void pushSucceedsWithinDeadline() throws Exception {
    List<String> pushOptions = new ArrayList<>();
    pushOptions.add("deadline=10m");
    PushOneCommit push = pushFactory.create(admin.newIdent(), testRepo);
    push.setPushOptions(pushOptions);
    PushOneCommit.Result r = push.to("refs/for/master");
    r.assertOkStatus();
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "1ms")
  public void clientProvidedDeadlineOnPushOverridesServerDeadline() throws Exception {
    List<String> pushOptions = new ArrayList<>();
    pushOptions.add("deadline=2ms");
    PushOneCommit push = pushFactory.create(admin.newIdent(), testRepo);
    push.setPushOptions(pushOptions);
    PushOneCommit.Result r = push.to("refs/for/master");
    r.assertErrorStatus("Client Provided Deadline Exceeded (client.timeout=2ms)");
  }

  @Test
  @GerritConfig(name = "receive.timeout", value = "1ms")
  public void clientProvidedDeadlineOnPushDoesntOverrideServerTimeout() throws Exception {
    List<String> pushOptions = new ArrayList<>();
    pushOptions.add("deadline=10m");
    PushOneCommit push = pushFactory.create(admin.newIdent(), testRepo);
    push.setPushOptions(pushOptions);
    PushOneCommit.Result r = push.to("refs/for/master");
    r.assertErrorStatus("Server Deadline Exceeded (receive.timeout=1ms)");
  }

  @Test
  @GerritConfig(name = "deadline.default.timeout", value = "1ms")
  public void clientCanDisableDeadlineOnPushBySettingZeroAsDeadline() throws Exception {
    List<String> pushOptions = new ArrayList<>();
    pushOptions.add("deadline=0");
    PushOneCommit push = pushFactory.create(admin.newIdent(), testRepo);
    push.setPushOptions(pushOptions);
    PushOneCommit.Result r = push.to("refs/for/master");
    r.assertOkStatus();
  }
}