summaryrefslogtreecommitdiffstats
path: root/gerrit-httpd/src/test/java/com/google/gerrit/httpd/raw/ResourceServletTest.java
blob: 3eb308872b0e6aa768f8c09ee1a349f43f2f04e4 (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
// Copyright (C) 2015 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.httpd.raw;

import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import static javax.servlet.http.HttpServletResponse.SC_OK;

import com.google.common.base.CharMatcher;
import com.google.common.base.Strings;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Lists;
import com.google.common.io.ByteStreams;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import com.google.gerrit.httpd.raw.ResourceServlet.Resource;
import com.google.gerrit.util.http.testutil.FakeHttpServletRequest;
import com.google.gerrit.util.http.testutil.FakeHttpServletResponse;

import org.joda.time.format.ISODateTimeFormat;
import org.junit.Before;
import org.junit.Test;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.util.concurrent.atomic.AtomicLong;
import java.util.zip.GZIPInputStream;

public class ResourceServletTest {
  private static Cache<Path, Resource> newCache(int size) {
    return CacheBuilder.newBuilder()
      .maximumSize(size)
      .recordStats()
      .build();
  }

  private static class Servlet extends ResourceServlet {
    private static final long serialVersionUID = 1L;

    private final FileSystem fs;

    private Servlet(FileSystem fs, Cache<Path, Resource> cache,
        boolean refresh) {
      super(cache, refresh);
      this.fs = fs;
    }

    private Servlet(FileSystem fs, Cache<Path, Resource> cache,
        boolean refresh, int cacheFileSizeLimitBytes) {
      super(cache, refresh, cacheFileSizeLimitBytes);
      this.fs = fs;
    }

    @Override
    protected Path getResourcePath(String pathInfo) {
      return fs.getPath("/" + CharMatcher.is('/').trimLeadingFrom(pathInfo));
    }
  }

  private FileSystem fs;
  private AtomicLong ts;

  @Before
  public void setUp() {
    fs = Jimfs.newFileSystem(Configuration.unix());
    ts = new AtomicLong(ISODateTimeFormat.dateTime().parseMillis(
        "2010-01-30T12:00:00.000-08:00"));
  }

  @Test
  public void notFoundWithoutRefresh() throws Exception {
    Cache<Path, Resource> cache = newCache(1);
    Servlet servlet = new Servlet(fs, cache, false);

    FakeHttpServletResponse res = new FakeHttpServletResponse();
    servlet.doGet(request("/notfound"), res);
    assertThat(res.getStatus()).isEqualTo(SC_NOT_FOUND);
    assertNotCacheable(res);
    assertCacheHits(cache, 0, 1);

    res = new FakeHttpServletResponse();
    servlet.doGet(request("/notfound"), res);
    assertThat(res.getStatus()).isEqualTo(SC_NOT_FOUND);
    assertNotCacheable(res);
    assertCacheHits(cache, 1, 1);
  }

  @Test
  public void notFoundWithRefresh() throws Exception {
    Cache<Path, Resource> cache = newCache(1);
    Servlet servlet = new Servlet(fs, cache, true);

    FakeHttpServletResponse res = new FakeHttpServletResponse();
    servlet.doGet(request("/notfound"), res);
    assertThat(res.getStatus()).isEqualTo(SC_NOT_FOUND);
    assertNotCacheable(res);
    assertCacheHits(cache, 0, 1);

    res = new FakeHttpServletResponse();
    servlet.doGet(request("/notfound"), res);
    assertThat(res.getStatus()).isEqualTo(SC_NOT_FOUND);
    assertNotCacheable(res);
    assertCacheHits(cache, 1, 1);
  }

  @Test
  public void smallFileWithRefresh() throws Exception {
    Cache<Path, Resource> cache = newCache(1);
    Servlet servlet = new Servlet(fs, cache, true);

    writeFile("/foo", "foo1");
    FakeHttpServletResponse res = new FakeHttpServletResponse();
    servlet.doGet(request("/foo"), res);
    assertThat(res.getStatus()).isEqualTo(SC_OK);
    assertThat(res.getActualBodyString()).isEqualTo("foo1");
    assertCacheable(res, true);
    assertHasETag(res);
    // Miss on getIfPresent, miss on get.
    assertCacheHits(cache, 0, 2);

    res = new FakeHttpServletResponse();
    servlet.doGet(request("/foo"), res);
    assertThat(res.getStatus()).isEqualTo(SC_OK);
    assertThat(res.getActualBodyString()).isEqualTo("foo1");
    assertCacheable(res, true);
    assertHasETag(res);
    assertCacheHits(cache, 1, 2);

    writeFile("/foo", "foo2");
    res = new FakeHttpServletResponse();
    servlet.doGet(request("/foo"), res);
    assertThat(res.getStatus()).isEqualTo(SC_OK);
    assertThat(res.getActualBodyString()).isEqualTo("foo2");
    assertCacheable(res, true);
    assertHasETag(res);
    // Hit, invalidate, miss.
    assertCacheHits(cache, 2, 3);
  }

  @Test
  public void smallFileWithoutRefresh() throws Exception {
    Cache<Path, Resource> cache = newCache(1);
    Servlet servlet = new Servlet(fs, cache, false);

    writeFile("/foo", "foo1");
    FakeHttpServletResponse res = new FakeHttpServletResponse();
    servlet.doGet(request("/foo"), res);
    assertThat(res.getStatus()).isEqualTo(SC_OK);
    assertThat(res.getActualBodyString()).isEqualTo("foo1");
    assertCacheable(res, false);
    assertHasETag(res);
    // Miss on getIfPresent, miss on get.
    assertCacheHits(cache, 0, 2);

    res = new FakeHttpServletResponse();
    servlet.doGet(request("/foo"), res);
    assertThat(res.getStatus()).isEqualTo(SC_OK);
    assertThat(res.getActualBodyString()).isEqualTo("foo1");
    assertCacheable(res, false);
    assertHasETag(res);
    assertCacheHits(cache, 1, 2);

    writeFile("/foo", "foo2");
    res = new FakeHttpServletResponse();
    servlet.doGet(request("/foo"), res);
    assertThat(res.getStatus()).isEqualTo(SC_OK);
    assertThat(res.getActualBodyString()).isEqualTo("foo1");
    assertCacheable(res, false);
    assertHasETag(res);
    assertCacheHits(cache, 2, 2);
  }

  @Test
  public void verySmallFileDoesntBotherWithGzip() throws Exception {
    Cache<Path, Resource> cache = newCache(1);
    Servlet servlet = new Servlet(fs, cache, true);
    writeFile("/foo", "foo1");

    FakeHttpServletRequest req = request("/foo")
        .addHeader("Accept-Encoding", "gzip");
    FakeHttpServletResponse res = new FakeHttpServletResponse();
    servlet.doGet(req, res);
    assertThat(res.getStatus()).isEqualTo(SC_OK);
    assertThat(res.getHeader("Content-Encoding")).isNull();
    assertThat(res.getActualBodyString()).isEqualTo("foo1");
    assertHasETag(res);
    assertCacheable(res, true);
  }

  @Test
  public void smallFileWithGzip() throws Exception {
    Cache<Path, Resource> cache = newCache(1);
    Servlet servlet = new Servlet(fs, cache, true);
    String content = Strings.repeat("a", 100);
    writeFile("/foo", content);

    FakeHttpServletRequest req = request("/foo")
        .addHeader("Accept-Encoding", "gzip");
    FakeHttpServletResponse res = new FakeHttpServletResponse();
    servlet.doGet(req, res);
    assertThat(res.getStatus()).isEqualTo(SC_OK);
    assertThat(res.getHeader("Content-Encoding")).isEqualTo("gzip");
    assertThat(gunzip(res.getActualBody())).isEqualTo(content);
    assertHasETag(res);
    assertCacheable(res, true);
  }

  @Test
  public void largeFileBypassesCacheRegardlessOfRefreshParamter()
      throws Exception {
    for (boolean refresh : Lists.newArrayList(true, false)) {
      Cache<Path, Resource> cache = newCache(1);
      Servlet servlet = new Servlet(fs, cache, refresh, 3);

      writeFile("/foo", "foo1");
      FakeHttpServletResponse res = new FakeHttpServletResponse();
      servlet.doGet(request("/foo"), res);
      assertThat(res.getStatus()).isEqualTo(SC_OK);
      assertThat(res.getActualBodyString()).isEqualTo("foo1");
      assertThat(res.getHeader("Last-Modified")).isNotNull();
      assertCacheable(res, refresh);
      assertHasLastModified(res);
      assertCacheHits(cache, 0, 1);

      writeFile("/foo", "foo1");
      res = new FakeHttpServletResponse();
      servlet.doGet(request("/foo"), res);
      assertThat(res.getStatus()).isEqualTo(SC_OK);
      assertThat(res.getActualBodyString()).isEqualTo("foo1");
      assertThat(res.getHeader("Last-Modified")).isNotNull();
      assertCacheable(res, refresh);
      assertHasLastModified(res);
      assertCacheHits(cache, 0, 2);

      writeFile("/foo", "foo2");
      res = new FakeHttpServletResponse();
      servlet.doGet(request("/foo"), res);
      assertThat(res.getStatus()).isEqualTo(SC_OK);
      assertThat(res.getActualBodyString()).isEqualTo("foo2");
      assertThat(res.getHeader("Last-Modified")).isNotNull();
      assertCacheable(res, refresh);
      assertHasLastModified(res);
      assertCacheHits(cache, 0, 3);
    }
  }

  @Test
  public void largeFileWithGzip() throws Exception {
    Cache<Path, Resource> cache = newCache(1);
    Servlet servlet = new Servlet(fs, cache, true, 3);
    String content = Strings.repeat("a", 100);
    writeFile("/foo", content);

    FakeHttpServletRequest req = request("/foo")
        .addHeader("Accept-Encoding", "gzip");
    FakeHttpServletResponse res = new FakeHttpServletResponse();
    servlet.doGet(req, res);
    assertThat(res.getStatus()).isEqualTo(SC_OK);
    assertThat(res.getHeader("Content-Encoding")).isEqualTo("gzip");
    assertThat(gunzip(res.getActualBody())).isEqualTo(content);
    assertHasLastModified(res);
    assertCacheable(res, true);
  }

  // TODO(dborowitz): Check MIME type.
  // TODO(dborowitz): Test that JS is not gzipped.
  // TODO(dborowitz): Test ?e parameter.
  // TODO(dborowitz): Test If-None-Match behavior.
  // TODO(dborowitz): Test If-Modified-Since behavior.

  private void writeFile(String path, String content) throws Exception {
    Files.write(fs.getPath(path), content.getBytes(UTF_8));
    Files.setLastModifiedTime(
        fs.getPath(path), FileTime.fromMillis(ts.getAndIncrement()));
  }

  private static void assertCacheHits(Cache<?, ?> cache, int hits, int misses) {
    assertThat(cache.stats().hitCount()).named("hits").isEqualTo(hits);
    assertThat(cache.stats().missCount()).named("misses").isEqualTo(misses);
  }

  private static void assertCacheable(FakeHttpServletResponse res,
      boolean revalidate) {
    String header = res.getHeader("Cache-Control").toLowerCase();
    assertThat(header).contains("public");
    if (revalidate) {
      assertThat(header).contains("must-revalidate");
    } else {
      assertThat(header).doesNotContain("must-revalidate");
    }
  }

  private static void assertHasLastModified(FakeHttpServletResponse res) {
    assertThat(res.getHeader("Last-Modified")).isNotNull();
    assertThat(res.getHeader("ETag")).isNull();
  }

  private static void assertHasETag(FakeHttpServletResponse res) {
    assertThat(res.getHeader("ETag")).isNotNull();
    assertThat(res.getHeader("Last-Modified")).isNull();
  }

  private static void assertNotCacheable(FakeHttpServletResponse res) {
    assertThat(res.getHeader("Cache-Control")).contains("no-cache");
    assertThat(res.getHeader("ETag")).isNull();
    assertThat(res.getHeader("Last-Modified")).isNull();
  }

  private static FakeHttpServletRequest request(String path) {
    return new FakeHttpServletRequest().setPathInfo(path);
  }

  private static String gunzip(byte[] data) throws Exception {
    try (InputStream in = new GZIPInputStream(new ByteArrayInputStream(data))) {
      return new String(ByteStreams.toByteArray(in), UTF_8);
    }
  }
}