|
| 1 | +/* |
| 2 | + * Copyright 2020 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package com.google.cloud.bigquery.storage.v1alpha2; |
| 17 | + |
| 18 | +import com.google.common.annotations.VisibleForTesting; |
| 19 | +import com.google.common.base.Preconditions; |
| 20 | +import com.google.common.cache.Cache; |
| 21 | +import com.google.common.cache.CacheBuilder; |
| 22 | +import com.google.protobuf.Descriptors; |
| 23 | +import java.io.IOException; |
| 24 | +import java.util.concurrent.ConcurrentMap; |
| 25 | +import java.util.logging.Logger; |
| 26 | +import java.util.regex.Matcher; |
| 27 | +import java.util.regex.Pattern; |
| 28 | + |
| 29 | +/** |
| 30 | + * A cache of JsonStreamWriters that can be looked up by Table Name. The entries will expire after 5 |
| 31 | + * minutes if not used. Code sample: JsonWriterCache cache = JsonWriterCache.getInstance(); |
| 32 | + * JsonStreamWriter writer = cache.getWriter(); // Use... cache.returnWriter(writer); |
| 33 | + */ |
| 34 | +public class JsonWriterCache { |
| 35 | + private static final Logger LOG = Logger.getLogger(JsonWriterCache.class.getName()); |
| 36 | + |
| 37 | + private static String tablePatternString = "(projects/[^/]+/datasets/[^/]+/tables/[^/]+)"; |
| 38 | + private static Pattern tablePattern = Pattern.compile(tablePatternString); |
| 39 | + |
| 40 | + private static JsonWriterCache instance; |
| 41 | + private Cache<String, JsonStreamWriter> jsonWriterCache; |
| 42 | + |
| 43 | + // Maximum number of tables to hold in the cache, once the maxium exceeded, the cache will be |
| 44 | + // evicted based on least recent used. |
| 45 | + private static final int MAX_TABLE_ENTRY = 100; |
| 46 | + private static final int MAX_WRITERS_PER_TABLE = 1; |
| 47 | + |
| 48 | + private final BigQueryWriteClient stub; |
| 49 | + |
| 50 | + private JsonWriterCache(BigQueryWriteClient stub, int maxTableEntry) { |
| 51 | + this.stub = stub; |
| 52 | + jsonWriterCache = |
| 53 | + CacheBuilder.newBuilder().maximumSize(maxTableEntry).<String, JsonStreamWriter>build(); |
| 54 | + } |
| 55 | + |
| 56 | + public static JsonWriterCache getInstance() throws IOException { |
| 57 | + if (instance == null) { |
| 58 | + BigQueryWriteSettings stubSettings = BigQueryWriteSettings.newBuilder().build(); |
| 59 | + BigQueryWriteClient stub = BigQueryWriteClient.create(stubSettings); |
| 60 | + instance = new JsonWriterCache(stub, MAX_TABLE_ENTRY); |
| 61 | + } |
| 62 | + return instance; |
| 63 | + } |
| 64 | + |
| 65 | + /** Returns a cache with custom stub used by test. */ |
| 66 | + @VisibleForTesting |
| 67 | + public static JsonWriterCache getTestInstance(BigQueryWriteClient stub, int maxTableEntry) { |
| 68 | + Preconditions.checkNotNull(stub, "Stub is null."); |
| 69 | + return new JsonWriterCache(stub, maxTableEntry); |
| 70 | + } |
| 71 | + |
| 72 | + private Stream.WriteStream CreateNewWriteStream(String tableName) { |
| 73 | + Stream.WriteStream stream = |
| 74 | + Stream.WriteStream.newBuilder().setType(Stream.WriteStream.Type.COMMITTED).build(); |
| 75 | + stream = |
| 76 | + stub.createWriteStream( |
| 77 | + Storage.CreateWriteStreamRequest.newBuilder() |
| 78 | + .setParent(tableName) |
| 79 | + .setWriteStream(stream) |
| 80 | + .build()); |
| 81 | + LOG.info("Created write stream:" + stream.getName()); |
| 82 | + return stream; |
| 83 | + } |
| 84 | + |
| 85 | + JsonStreamWriter CreateNewWriter(Stream.WriteStream writeStream) |
| 86 | + throws IllegalArgumentException, IOException, InterruptedException, |
| 87 | + Descriptors.DescriptorValidationException { |
| 88 | + return JsonStreamWriter.newBuilder(writeStream.getName(), writeStream.getTableSchema()) |
| 89 | + .setChannelProvider(stub.getSettings().getTransportChannelProvider()) |
| 90 | + .setCredentialsProvider(stub.getSettings().getCredentialsProvider()) |
| 91 | + .setExecutorProvider(stub.getSettings().getExecutorProvider()) |
| 92 | + .build(); |
| 93 | + } |
| 94 | + /** |
| 95 | + * Gets a writer for a given table with the given tableName |
| 96 | + * |
| 97 | + * @param tableName |
| 98 | + * @return |
| 99 | + * @throws Exception |
| 100 | + */ |
| 101 | + public JsonStreamWriter getTableWriter(String tableName) |
| 102 | + throws IllegalArgumentException, IOException, InterruptedException, |
| 103 | + Descriptors.DescriptorValidationException { |
| 104 | + Preconditions.checkNotNull(tableName, "TableName is null."); |
| 105 | + Matcher matcher = tablePattern.matcher(tableName); |
| 106 | + if (!matcher.matches()) { |
| 107 | + throw new IllegalArgumentException("Invalid table name: " + tableName); |
| 108 | + } |
| 109 | + |
| 110 | + Stream.WriteStream writeStream = null; |
| 111 | + JsonStreamWriter writer = null; |
| 112 | + |
| 113 | + synchronized (this) { |
| 114 | + writer = jsonWriterCache.getIfPresent(tableName); |
| 115 | + if (writer != null) { |
| 116 | + if (!writer.expired()) { |
| 117 | + return writer; |
| 118 | + } else { |
| 119 | + writer.close(); |
| 120 | + } |
| 121 | + } |
| 122 | + writeStream = CreateNewWriteStream(tableName); |
| 123 | + writer = CreateNewWriter(writeStream); |
| 124 | + jsonWriterCache.put(tableName, writer); |
| 125 | + } |
| 126 | + return writer; |
| 127 | + } |
| 128 | + |
| 129 | + /** Clear the cache and close all the writers in the cache. */ |
| 130 | + public void clear() { |
| 131 | + synchronized (this) { |
| 132 | + ConcurrentMap<String, JsonStreamWriter> map = jsonWriterCache.asMap(); |
| 133 | + for (String key : map.keySet()) { |
| 134 | + JsonStreamWriter entry = jsonWriterCache.getIfPresent(key); |
| 135 | + entry.close(); |
| 136 | + } |
| 137 | + jsonWriterCache.cleanUp(); |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + @VisibleForTesting |
| 142 | + public long cachedTableCount() { |
| 143 | + synchronized (jsonWriterCache) { |
| 144 | + return jsonWriterCache.size(); |
| 145 | + } |
| 146 | + } |
| 147 | +} |
0 commit comments