Search in sources :

Example 26 with Protocol

use of okhttp3.Protocol in project buck by facebook.

the class ThriftArtifactCache method fetchImpl.

@Override
public CacheResult fetchImpl(RuleKey ruleKey, LazyPath output, HttpArtifactCacheEvent.Finished.Builder eventBuilder) throws IOException {
    BuckCacheFetchRequest fetchRequest = new BuckCacheFetchRequest();
    com.facebook.buck.artifact_cache.thrift.RuleKey thriftRuleKey = new com.facebook.buck.artifact_cache.thrift.RuleKey();
    thriftRuleKey.setHashString(ruleKey.getHashCode().toString());
    fetchRequest.setRuleKey(thriftRuleKey);
    fetchRequest.setRepository(repository);
    fetchRequest.setScheduleType(scheduleType);
    fetchRequest.setDistributedBuildModeEnabled(distributedBuildModeEnabled);
    BuckCacheRequest cacheRequest = new BuckCacheRequest();
    cacheRequest.setType(BuckCacheRequestType.FETCH);
    cacheRequest.setFetchRequest(fetchRequest);
    LOG.verbose("Will fetch key %s", thriftRuleKey);
    final ThriftArtifactCacheProtocol.Request request = ThriftArtifactCacheProtocol.createRequest(PROTOCOL, cacheRequest);
    Request.Builder builder = toOkHttpRequest(request);
    try (HttpResponse httpResponse = fetchClient.makeRequest(hybridThriftEndpoint, builder)) {
        if (httpResponse.statusCode() != 200) {
            String message = String.format("Failed to fetch cache artifact with HTTP status code [%d:%s] " + " to url [%s] for rule key [%s].", httpResponse.statusCode(), httpResponse.statusMessage(), httpResponse.requestUrl(), ruleKey.toString());
            LOG.error(message);
            return CacheResult.error(name, message);
        }
        try (ThriftArtifactCacheProtocol.Response response = ThriftArtifactCacheProtocol.parseResponse(PROTOCOL, httpResponse.getBody())) {
            eventBuilder.getFetchBuilder().setResponseSizeBytes(httpResponse.contentLength());
            BuckCacheResponse cacheResponse = response.getThriftData();
            if (!cacheResponse.isWasSuccessful()) {
                LOG.warn("Request was unsuccessful: %s", cacheResponse.getErrorMessage());
                return CacheResult.error(name, cacheResponse.getErrorMessage());
            }
            BuckCacheFetchResponse fetchResponse = cacheResponse.getFetchResponse();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Debug info for cache fetch request: request=[%s] response=[%s]", ThriftUtil.thriftToDebugJson(cacheRequest), ThriftUtil.thriftToDebugJson(cacheResponse));
            }
            if (!fetchResponse.isArtifactExists()) {
                LOG.verbose("Artifact did not exist.");
                return CacheResult.miss();
            }
            LOG.verbose("Got artifact.  Attempting to read payload.");
            Path tmp = createTempFileForDownload();
            ThriftArtifactCacheProtocol.Response.ReadPayloadInfo readResult;
            try (OutputStream tmpFile = projectFilesystem.newFileOutputStream(tmp)) {
                readResult = response.readPayload(tmpFile);
                LOG.verbose("Successfully read payload: %d bytes.", readResult.getBytesRead());
            }
            ArtifactMetadata metadata = fetchResponse.getMetadata();
            if (LOG.isVerboseEnabled()) {
                LOG.verbose(String.format("Fetched artifact with rule key [%s] contains the following metadata: [%s]", ruleKey, ThriftUtil.thriftToDebugJson(metadata)));
            }
            eventBuilder.setTarget(Optional.ofNullable(metadata.getBuildTarget())).getFetchBuilder().setAssociatedRuleKeys(toImmutableSet(metadata.getRuleKeys())).setArtifactSizeBytes(readResult.getBytesRead());
            if (!metadata.isSetArtifactPayloadMd5()) {
                String msg = "Fetched artifact is missing the MD5 hash.";
                LOG.warn(msg);
            } else {
                eventBuilder.getFetchBuilder().setArtifactContentHash(metadata.getArtifactPayloadMd5());
                if (!readResult.getMd5Hash().equals(fetchResponse.getMetadata().getArtifactPayloadMd5())) {
                    String msg = String.format("The artifact fetched from cache is corrupted. ExpectedMD5=[%s] ActualMD5=[%s]", fetchResponse.getMetadata().getArtifactPayloadMd5(), readResult.getMd5Hash());
                    LOG.error(msg);
                    return CacheResult.error(name, msg);
                }
            }
            // This makes sure we don't have 'half downloaded files' in the dir cache.
            projectFilesystem.move(tmp, output.get(), StandardCopyOption.REPLACE_EXISTING);
            return CacheResult.hit(name, ImmutableMap.copyOf(fetchResponse.getMetadata().getMetadata()), readResult.getBytesRead());
        }
    }
}
Also used : Path(java.nio.file.Path) LazyPath(com.facebook.buck.io.LazyPath) BuckCacheFetchResponse(com.facebook.buck.artifact_cache.thrift.BuckCacheFetchResponse) RuleKey(com.facebook.buck.rules.RuleKey) OutputStream(java.io.OutputStream) BuckCacheStoreRequest(com.facebook.buck.artifact_cache.thrift.BuckCacheStoreRequest) Request(okhttp3.Request) BuckCacheRequest(com.facebook.buck.artifact_cache.thrift.BuckCacheRequest) BuckCacheFetchRequest(com.facebook.buck.artifact_cache.thrift.BuckCacheFetchRequest) HttpResponse(com.facebook.buck.slb.HttpResponse) BuckCacheRequest(com.facebook.buck.artifact_cache.thrift.BuckCacheRequest) BuckCacheFetchRequest(com.facebook.buck.artifact_cache.thrift.BuckCacheFetchRequest) BuckCacheResponse(com.facebook.buck.artifact_cache.thrift.BuckCacheResponse) HttpResponse(com.facebook.buck.slb.HttpResponse) BuckCacheFetchResponse(com.facebook.buck.artifact_cache.thrift.BuckCacheFetchResponse) BuckCacheResponse(com.facebook.buck.artifact_cache.thrift.BuckCacheResponse) ArtifactMetadata(com.facebook.buck.artifact_cache.thrift.ArtifactMetadata)

Example 27 with Protocol

use of okhttp3.Protocol in project stetho by facebook.

the class StethoInterceptorTest method testHappyPath.

@Test
public void testHappyPath() throws IOException {
    InOrder inOrder = Mockito.inOrder(mMockEventReporter);
    hookAlmostRealRequestWillBeSent(mMockEventReporter);
    ByteArrayOutputStream capturedOutput = hookAlmostRealInterpretResponseStream(mMockEventReporter);
    Uri requestUri = Uri.parse("http://www.facebook.com/nowhere");
    String requestText = "Test input";
    Request request = new Request.Builder().url(requestUri.toString()).method("POST", RequestBody.create(MediaType.parse("text/plain"), requestText)).build();
    String originalBodyData = "Success!";
    Response reply = new Response.Builder().request(request).protocol(Protocol.HTTP_1_1).code(200).body(ResponseBody.create(MediaType.parse("text/plain"), originalBodyData)).build();
    Response filteredResponse = mInterceptor.intercept(new SimpleTestChain(request, reply, null));
    inOrder.verify(mMockEventReporter).isEnabled();
    inOrder.verify(mMockEventReporter).requestWillBeSent(any(NetworkEventReporter.InspectorRequest.class));
    inOrder.verify(mMockEventReporter).dataSent(anyString(), eq(requestText.length()), eq(requestText.length()));
    inOrder.verify(mMockEventReporter).responseHeadersReceived(any(NetworkEventReporter.InspectorResponse.class));
    String filteredResponseString = filteredResponse.body().string();
    String interceptedOutput = capturedOutput.toString();
    inOrder.verify(mMockEventReporter).dataReceived(anyString(), anyInt(), anyInt());
    inOrder.verify(mMockEventReporter).responseReadFinished(anyString());
    assertEquals(originalBodyData, filteredResponseString);
    assertEquals(originalBodyData, interceptedOutput);
    inOrder.verifyNoMoreInteractions();
}
Also used : Response(okhttp3.Response) MockResponse(okhttp3.mockwebserver.MockResponse) InOrder(org.mockito.InOrder) Request(okhttp3.Request) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Uri(android.net.Uri) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 28 with Protocol

use of okhttp3.Protocol in project buck by facebook.

the class HttpArtifactCacheTest method testFetchBadChecksum.

@Test
public void testFetchBadChecksum() throws Exception {
    FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
    final RuleKey ruleKey = new RuleKey("00000000000000000000000000000000");
    final List<Response> responseList = Lists.newArrayList();
    argsBuilder.setFetchClient(withMakeRequest((path, requestBuilder) -> {
        Request request = requestBuilder.url(SERVER + path).build();
        Response response = new Response.Builder().request(request).protocol(Protocol.HTTP_1_1).code(HttpURLConnection.HTTP_OK).body(createResponseBody(ImmutableSet.of(ruleKey), ImmutableMap.of(), ByteSource.wrap(new byte[0]), "data")).build();
        responseList.add(response);
        return new OkHttpResponseWrapper(response);
    }));
    HttpArtifactCache cache = new HttpArtifactCache(argsBuilder.build());
    Path output = Paths.get("output/file");
    CacheResult result = cache.fetch(ruleKey, LazyPath.ofInstance(output));
    assertEquals(CacheResultType.ERROR, result.getType());
    assertEquals(Optional.empty(), filesystem.readFileIfItExists(output));
    assertTrue("response wasn't fully read!", responseList.get(0).body().source().exhausted());
    cache.close();
}
Also used : Response(okhttp3.Response) HttpResponse(com.facebook.buck.slb.HttpResponse) BuckEventBus(com.facebook.buck.event.BuckEventBus) HttpURLConnection(java.net.HttpURLConnection) DataInputStream(java.io.DataInputStream) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BuckEvent(com.facebook.buck.event.BuckEvent) FakeProjectFilesystem(com.facebook.buck.testutil.FakeProjectFilesystem) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ConsoleEvent(com.facebook.buck.event.ConsoleEvent) Assert.assertThat(org.junit.Assert.assertThat) Lists(com.google.common.collect.Lists) ByteArrayInputStream(java.io.ByteArrayInputStream) DataOutputStream(java.io.DataOutputStream) BuildId(com.facebook.buck.model.BuildId) RuleKey(com.facebook.buck.rules.RuleKey) Assert.assertArrayEquals(org.junit.Assert.assertArrayEquals) Response(okhttp3.Response) ByteSource(com.google.common.io.ByteSource) HttpResponse(com.facebook.buck.slb.HttpResponse) Path(java.nio.file.Path) MediaType(okhttp3.MediaType) ResponseBody(okhttp3.ResponseBody) HttpService(com.facebook.buck.slb.HttpService) Before(org.junit.Before) Charsets(com.google.common.base.Charsets) Request(okhttp3.Request) Buffer(okio.Buffer) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) Assert.assertTrue(org.junit.Assert.assertTrue) OkHttpResponseWrapper(com.facebook.buck.slb.OkHttpResponseWrapper) Matchers(org.hamcrest.Matchers) Set(java.util.Set) Test(org.junit.Test) IOException(java.io.IOException) Sets(com.google.common.collect.Sets) List(java.util.List) Paths(java.nio.file.Paths) LazyPath(com.facebook.buck.io.LazyPath) IncrementingFakeClock(com.facebook.buck.timing.IncrementingFakeClock) Optional(java.util.Optional) Protocol(okhttp3.Protocol) Assert.assertEquals(org.junit.Assert.assertEquals) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) Path(java.nio.file.Path) LazyPath(com.facebook.buck.io.LazyPath) RuleKey(com.facebook.buck.rules.RuleKey) FakeProjectFilesystem(com.facebook.buck.testutil.FakeProjectFilesystem) Request(okhttp3.Request) OkHttpResponseWrapper(com.facebook.buck.slb.OkHttpResponseWrapper) Test(org.junit.Test)

Example 29 with Protocol

use of okhttp3.Protocol in project buck by facebook.

the class HttpArtifactCacheTest method testFetchOK.

@Test
public void testFetchOK() throws Exception {
    Path output = Paths.get("output/file");
    final String data = "test";
    final RuleKey ruleKey = new RuleKey("00000000000000000000000000000000");
    FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
    final List<Response> responseList = Lists.newArrayList();
    argsBuilder.setProjectFilesystem(filesystem);
    argsBuilder.setFetchClient(withMakeRequest((path, requestBuilder) -> {
        Request request = requestBuilder.url(SERVER + path).build();
        Response response = new Response.Builder().request(request).protocol(Protocol.HTTP_1_1).code(HttpURLConnection.HTTP_OK).body(createResponseBody(ImmutableSet.of(ruleKey), ImmutableMap.of(), ByteSource.wrap(data.getBytes(Charsets.UTF_8)), data)).build();
        responseList.add(response);
        return new OkHttpResponseWrapper(response);
    }));
    HttpArtifactCache cache = new HttpArtifactCache(argsBuilder.build());
    CacheResult result = cache.fetch(ruleKey, LazyPath.ofInstance(output));
    assertEquals(result.cacheError().orElse(""), CacheResultType.HIT, result.getType());
    assertEquals(Optional.of(data), filesystem.readFileIfItExists(output));
    assertEquals(result.artifactSizeBytes(), Optional.of(filesystem.getFileSize(output)));
    assertTrue("response wasn't fully read!", responseList.get(0).body().source().exhausted());
    cache.close();
}
Also used : Path(java.nio.file.Path) LazyPath(com.facebook.buck.io.LazyPath) Response(okhttp3.Response) HttpResponse(com.facebook.buck.slb.HttpResponse) BuckEventBus(com.facebook.buck.event.BuckEventBus) HttpURLConnection(java.net.HttpURLConnection) DataInputStream(java.io.DataInputStream) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BuckEvent(com.facebook.buck.event.BuckEvent) FakeProjectFilesystem(com.facebook.buck.testutil.FakeProjectFilesystem) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ConsoleEvent(com.facebook.buck.event.ConsoleEvent) Assert.assertThat(org.junit.Assert.assertThat) Lists(com.google.common.collect.Lists) ByteArrayInputStream(java.io.ByteArrayInputStream) DataOutputStream(java.io.DataOutputStream) BuildId(com.facebook.buck.model.BuildId) RuleKey(com.facebook.buck.rules.RuleKey) Assert.assertArrayEquals(org.junit.Assert.assertArrayEquals) Response(okhttp3.Response) ByteSource(com.google.common.io.ByteSource) HttpResponse(com.facebook.buck.slb.HttpResponse) Path(java.nio.file.Path) MediaType(okhttp3.MediaType) ResponseBody(okhttp3.ResponseBody) HttpService(com.facebook.buck.slb.HttpService) Before(org.junit.Before) Charsets(com.google.common.base.Charsets) Request(okhttp3.Request) Buffer(okio.Buffer) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) Assert.assertTrue(org.junit.Assert.assertTrue) OkHttpResponseWrapper(com.facebook.buck.slb.OkHttpResponseWrapper) Matchers(org.hamcrest.Matchers) Set(java.util.Set) Test(org.junit.Test) IOException(java.io.IOException) Sets(com.google.common.collect.Sets) List(java.util.List) Paths(java.nio.file.Paths) LazyPath(com.facebook.buck.io.LazyPath) IncrementingFakeClock(com.facebook.buck.timing.IncrementingFakeClock) Optional(java.util.Optional) Protocol(okhttp3.Protocol) Assert.assertEquals(org.junit.Assert.assertEquals) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) RuleKey(com.facebook.buck.rules.RuleKey) FakeProjectFilesystem(com.facebook.buck.testutil.FakeProjectFilesystem) Request(okhttp3.Request) OkHttpResponseWrapper(com.facebook.buck.slb.OkHttpResponseWrapper) Test(org.junit.Test)

Example 30 with Protocol

use of okhttp3.Protocol in project buck by facebook.

the class HttpArtifactCacheTest method testFetchNotFound.

@Test
public void testFetchNotFound() throws Exception {
    final List<Response> responseList = Lists.newArrayList();
    argsBuilder.setFetchClient(withMakeRequest((path, requestBuilder) -> {
        Response response = new Response.Builder().code(HttpURLConnection.HTTP_NOT_FOUND).body(ResponseBody.create(MediaType.parse("application/octet-stream"), "extraneous")).protocol(Protocol.HTTP_1_1).request(requestBuilder.url(SERVER + path).build()).build();
        responseList.add(response);
        return new OkHttpResponseWrapper(response);
    }));
    HttpArtifactCache cache = new HttpArtifactCache(argsBuilder.build());
    CacheResult result = cache.fetch(new RuleKey("00000000000000000000000000000000"), LazyPath.ofInstance(Paths.get("output/file")));
    assertEquals(result.getType(), CacheResultType.MISS);
    assertTrue("response wasn't fully read!", responseList.get(0).body().source().exhausted());
    cache.close();
}
Also used : Response(okhttp3.Response) HttpResponse(com.facebook.buck.slb.HttpResponse) BuckEventBus(com.facebook.buck.event.BuckEventBus) HttpURLConnection(java.net.HttpURLConnection) DataInputStream(java.io.DataInputStream) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BuckEvent(com.facebook.buck.event.BuckEvent) FakeProjectFilesystem(com.facebook.buck.testutil.FakeProjectFilesystem) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ConsoleEvent(com.facebook.buck.event.ConsoleEvent) Assert.assertThat(org.junit.Assert.assertThat) Lists(com.google.common.collect.Lists) ByteArrayInputStream(java.io.ByteArrayInputStream) DataOutputStream(java.io.DataOutputStream) BuildId(com.facebook.buck.model.BuildId) RuleKey(com.facebook.buck.rules.RuleKey) Assert.assertArrayEquals(org.junit.Assert.assertArrayEquals) Response(okhttp3.Response) ByteSource(com.google.common.io.ByteSource) HttpResponse(com.facebook.buck.slb.HttpResponse) Path(java.nio.file.Path) MediaType(okhttp3.MediaType) ResponseBody(okhttp3.ResponseBody) HttpService(com.facebook.buck.slb.HttpService) Before(org.junit.Before) Charsets(com.google.common.base.Charsets) Request(okhttp3.Request) Buffer(okio.Buffer) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) Assert.assertTrue(org.junit.Assert.assertTrue) OkHttpResponseWrapper(com.facebook.buck.slb.OkHttpResponseWrapper) Matchers(org.hamcrest.Matchers) Set(java.util.Set) Test(org.junit.Test) IOException(java.io.IOException) Sets(com.google.common.collect.Sets) List(java.util.List) Paths(java.nio.file.Paths) LazyPath(com.facebook.buck.io.LazyPath) IncrementingFakeClock(com.facebook.buck.timing.IncrementingFakeClock) Optional(java.util.Optional) Protocol(okhttp3.Protocol) Assert.assertEquals(org.junit.Assert.assertEquals) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) RuleKey(com.facebook.buck.rules.RuleKey) OkHttpResponseWrapper(com.facebook.buck.slb.OkHttpResponseWrapper) Test(org.junit.Test)

Aggregations

Request (okhttp3.Request)26 Response (okhttp3.Response)26 Test (org.junit.Test)25 ResponseBody (okhttp3.ResponseBody)20 IOException (java.io.IOException)18 Protocol (okhttp3.Protocol)14 Buffer (okio.Buffer)13 HttpResponse (com.facebook.buck.slb.HttpResponse)12 LazyPath (com.facebook.buck.io.LazyPath)11 RuleKey (com.facebook.buck.rules.RuleKey)11 Path (java.nio.file.Path)11 OkHttpResponseWrapper (com.facebook.buck.slb.OkHttpResponseWrapper)10 List (java.util.List)10 MediaType (okhttp3.MediaType)10 FakeProjectFilesystem (com.facebook.buck.testutil.FakeProjectFilesystem)9 HttpURLConnection (java.net.HttpURLConnection)9 MockResponse (okhttp3.mockwebserver.MockResponse)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 DataOutputStream (java.io.DataOutputStream)7 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)7