-
Notifications
You must be signed in to change notification settings - Fork 81
/
WriterCache.java
189 lines (173 loc) · 7.03 KB
/
WriterCache.java
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
/*
* Copyright 2020 Google LLC
*
* 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.cloud.bigquery.storage.v1alpha2;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import com.google.protobuf.Descriptors.Descriptor;
import java.io.IOException;
import java.util.concurrent.ConcurrentMap;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A cache of StreamWriters that can be looked up by Table Name. The entries will expire after 5
* minutes if not used. Code sample: WriterCache cache = WriterCache.getInstance(); StreamWriter
* writer = cache.getWriter(); // Use... cache.returnWriter(writer);
*/
public class WriterCache {
private static final Logger LOG = Logger.getLogger(WriterCache.class.getName());
private static String tablePatternString = "(projects/[^/]+/datasets/[^/]+/tables/[^/]+)";
private static Pattern tablePattern = Pattern.compile(tablePatternString);
private static WriterCache instance;
private Cache<String, Cache<Descriptor, StreamWriter>> writerCache;
// Maximum number of tables to hold in the cache, once the maxium exceeded, the cache will be
// evicted based on least recent used.
private static final int MAX_TABLE_ENTRY = 100;
private static final int MAX_WRITERS_PER_TABLE = 2;
private final BigQueryWriteClient stub;
private final SchemaCompatibility compact;
private WriterCache(BigQueryWriteClient stub, int maxTableEntry, SchemaCompatibility compact) {
this.stub = stub;
this.compact = compact;
writerCache =
CacheBuilder.newBuilder()
.maximumSize(maxTableEntry)
.removalListener(
new RemovalListener<String, Cache<Descriptor, StreamWriter>>() {
@Override
public void onRemoval(
RemovalNotification<String, Cache<Descriptor, StreamWriter>>
removalNotification) {
removalNotification.getValue().invalidateAll();
}
})
.<String, Cache<Descriptor, StreamWriter>>build();
}
public static WriterCache getInstance() throws IOException {
if (instance == null) {
BigQueryWriteSettings stubSettings = BigQueryWriteSettings.newBuilder().build();
BigQueryWriteClient stub = BigQueryWriteClient.create(stubSettings);
instance = new WriterCache(stub, MAX_TABLE_ENTRY, SchemaCompatibility.getInstance());
}
return instance;
}
/** Returns a cache with custom stub used by test. */
@VisibleForTesting
public static WriterCache getTestInstance(
BigQueryWriteClient stub, int maxTableEntry, SchemaCompatibility compact) {
return new WriterCache(stub, maxTableEntry, compact);
}
/** Returns an entry with {@code StreamWriter} and expiration time in millis. */
private String CreateNewStream(String tableName) {
Stream.WriteStream stream =
Stream.WriteStream.newBuilder().setType(Stream.WriteStream.Type.COMMITTED).build();
stream =
stub.createWriteStream(
Storage.CreateWriteStreamRequest.newBuilder()
.setParent(tableName)
.setWriteStream(stream)
.build());
LOG.info("Created write stream:" + stream.getName());
return stream.getName();
}
StreamWriter CreateNewWriter(String streamName)
throws IllegalArgumentException, IOException, InterruptedException {
return StreamWriter.newBuilder(streamName)
.setChannelProvider(stub.getSettings().getTransportChannelProvider())
.setCredentialsProvider(stub.getSettings().getCredentialsProvider())
.setExecutorProvider(stub.getSettings().getExecutorProvider())
.build();
}
/**
* Gets a writer for a given table with a given user schema from global cache.
*
* @param tableName
* @param userSchema
* @return
* @throws Exception
*/
public StreamWriter getTableWriter(String tableName, Descriptor userSchema)
throws IllegalArgumentException, IOException, InterruptedException {
Matcher matcher = tablePattern.matcher(tableName);
if (!matcher.matches()) {
throw new IllegalArgumentException("Invalid table name: " + tableName);
}
String streamName = null;
Boolean streamExpired = false;
StreamWriter writer = null;
Cache<Descriptor, StreamWriter> tableEntry = null;
synchronized (this) {
tableEntry = writerCache.getIfPresent(tableName);
if (tableEntry != null) {
writer = tableEntry.getIfPresent(userSchema);
if (writer != null) {
if (!writer.expired()) {
return writer;
} else {
writer.close();
}
}
compact.check(tableName, userSchema);
streamName = CreateNewStream(tableName);
writer = CreateNewWriter(streamName);
tableEntry.put(userSchema, writer);
} else {
compact.check(tableName, userSchema);
streamName = CreateNewStream(tableName);
tableEntry =
CacheBuilder.newBuilder()
.maximumSize(MAX_WRITERS_PER_TABLE)
.removalListener(
new RemovalListener<Descriptor, StreamWriter>() {
@Override
public void onRemoval(
RemovalNotification<Descriptor, StreamWriter> removalNotification) {
removalNotification.getValue().close();
}
})
.<Descriptor, StreamWriter>build();
writer = CreateNewWriter(streamName);
tableEntry.put(userSchema, writer);
writerCache.put(tableName, tableEntry);
}
}
return writer;
}
/** Clear the cache and close all the writers in the cache. */
public void clear() {
synchronized (this) {
ConcurrentMap<String, Cache<Descriptor, StreamWriter>> map = writerCache.asMap();
for (String key : map.keySet()) {
Cache<Descriptor, StreamWriter> entry = writerCache.getIfPresent(key);
ConcurrentMap<Descriptor, StreamWriter> entryMap = entry.asMap();
for (Descriptor descriptor : entryMap.keySet()) {
StreamWriter writer = entry.getIfPresent(descriptor);
writer.close();
}
}
writerCache.cleanUp();
}
}
@VisibleForTesting
public long cachedTableCount() {
synchronized (writerCache) {
return writerCache.size();
}
}
}