/
FirestoreOptions.java
421 lines (361 loc) · 13.9 KB
/
FirestoreOptions.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
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
/*
* Copyright 2017 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.firestore;
import com.google.api.core.ApiFunction;
import com.google.api.core.InternalApi;
import com.google.api.gax.core.CredentialsProvider;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.auth.Credentials;
import com.google.cloud.ServiceDefaults;
import com.google.cloud.ServiceOptions;
import com.google.cloud.TransportOptions;
import com.google.cloud.firestore.spi.v1.FirestoreRpc;
import com.google.cloud.firestore.spi.v1.GrpcFirestoreRpc;
import com.google.cloud.firestore.v1.FirestoreSettings;
import com.google.cloud.grpc.GrpcTransportOptions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import io.grpc.ManagedChannelBuilder;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/** A Factory class to create new Firestore instances. */
public final class FirestoreOptions extends ServiceOptions<Firestore, FirestoreOptions> {
private static final String API_SHORT_NAME = "Firestore";
private static final Set<String> SCOPES =
ImmutableSet.<String>builder()
.add("https://www.googleapis.com/auth/cloud-platform")
.add("https://www.googleapis.com/auth/datastore")
.build();
private static final boolean DEFAULT_TIMESTAMPS_IN_SNAPSHOTS_ENABLED = true;
private static final long serialVersionUID = -5853552236134770090L;
private static final String FIRESTORE_EMULATOR_SYSTEM_VARIABLE = "FIRESTORE_EMULATOR_HOST";
private final String databaseId;
private final boolean timestampsInSnapshotsEnabled;
private final TransportChannelProvider channelProvider;
private final CredentialsProvider credentialsProvider;
public static class DefaultFirestoreFactory implements FirestoreFactory {
private static final FirestoreFactory INSTANCE = new DefaultFirestoreFactory();
@Nonnull
@Override
public Firestore create(@Nonnull FirestoreOptions options) {
return new FirestoreImpl(options);
}
}
/** Returns a default {@code FirestoreOptions} instance. */
public static FirestoreOptions getDefaultInstance() {
return newBuilder().build();
}
public static class DefaultFirestoreRpcFactory implements FirestoreRpcFactory {
private static final FirestoreRpcFactory INSTANCE = new DefaultFirestoreRpcFactory();
@Nonnull
@Override
public FirestoreRpc create(@Nonnull FirestoreOptions options) {
try {
return new GrpcFirestoreRpc(options);
} catch (IOException e) {
throw FirestoreException.networkException(e, false);
}
}
}
@Override
protected boolean projectIdRequired() {
return false;
}
@Override
protected String getDefaultHost() {
return FirestoreDefaults.INSTANCE.getHost();
}
public String getDatabaseId() {
return databaseId;
}
public CredentialsProvider getCredentialsProvider() {
return credentialsProvider;
}
public TransportChannelProvider getTransportChannelProvider() {
return channelProvider;
}
public static class Builder extends ServiceOptions.Builder<Firestore, FirestoreOptions, Builder> {
@Nullable private String databaseId = null;
@Nullable private Boolean timestampsInSnapshotsEnabled = null;
@Nullable private TransportChannelProvider channelProvider = null;
@Nullable private CredentialsProvider credentialsProvider = null;
private Builder() {}
private Builder(FirestoreOptions options) {
super(options);
this.databaseId = options.databaseId;
this.timestampsInSnapshotsEnabled = options.timestampsInSnapshotsEnabled;
this.channelProvider = options.channelProvider;
this.credentialsProvider = options.credentialsProvider;
}
/**
* Sets the {@link TransportOptions} to use with this Firestore client.
*
* @param transportOptions A GrpcTransportOptions object that defines the transport options for
* this client.
*/
@Nonnull
@Override
public Builder setTransportOptions(@Nonnull TransportOptions transportOptions) {
if (!(transportOptions instanceof GrpcTransportOptions)) {
throw new IllegalArgumentException(
"Only GRPC transport is allowed for " + API_SHORT_NAME + ".");
}
super.setTransportOptions(transportOptions);
return this;
}
/**
* Sets the {@link TransportChannelProvider} to use with this Firestore client.
*
* @param channelProvider A InstantiatingGrpcChannelProvider object that defines the transport
* provider for this client.
*/
@Nonnull
public Builder setChannelProvider(@Nonnull TransportChannelProvider channelProvider) {
if (!(channelProvider instanceof InstantiatingGrpcChannelProvider)) {
throw new IllegalArgumentException(
"Only GRPC channels are allowed for " + API_SHORT_NAME + ".");
}
this.channelProvider = channelProvider;
return this;
}
/**
* Sets the {@link CredentialsProvider} to use with this Firestore client.
*
* @param credentialsProvider A CredentialsProvider object that defines the credential provider
* for this client.
*/
@Nonnull
public Builder setCredentialsProvider(@Nonnull CredentialsProvider credentialsProvider) {
this.credentialsProvider = credentialsProvider;
return this;
}
/**
* Sets the database ID to use with this Firestore client.
*
* @param databaseId The Firestore database ID to use with this client.
*/
public Builder setDatabaseId(@Nonnull String databaseId) {
this.databaseId = databaseId;
return this;
}
/**
* Specifies whether to use {@link com.google.cloud.Timestamp Timestamps} for timestamp fields
* in {@link DocumentSnapshot DocumentSnapshots}. This is now enabled by default and should not
* be disabled.
*
* <p>Previously, Firestore returned timestamp fields as {@link java.util.Date} but {@link
* java.util.Date} only supports millisecond precision, which leads to truncation and causes
* unexpected behavior when using a timestamp from a snapshot as a part of a subsequent query.
*
* <p>So now Firestore returns {@link com.google.cloud.Timestamp Timestamp} values instead of
* {@link java.util.Date}, avoiding this kind of problem.
*
* <p>To opt into the old behavior of returning {@link java.util.Date Dates}, you can
* temporarily set {@link FirestoreOptions#areTimestampsInSnapshotsEnabled} to false.
*
* @deprecated This setting now defaults to true and will be removed in a future release. If you
* are already setting it to true, just remove the setting. If you are setting it to false,
* you should update your code to expect {@link com.google.cloud.Timestamp Timestamps}
* instead of {@link java.util.Date Dates} and then remove the setting.
*/
@Deprecated
@Nonnull
public Builder setTimestampsInSnapshotsEnabled(boolean value) {
this.timestampsInSnapshotsEnabled = value;
return this;
}
@Override
@Nonnull
public FirestoreOptions build() {
if (this.credentials == null && this.credentialsProvider != null) {
try {
this.setCredentials(credentialsProvider.getCredentials());
} catch (IOException e) {
throw new RuntimeException("Failed to obtain credentials", e);
}
}
// Override credentials and channel provider if we are using the emulator.
String emulatorHost = System.getenv(FIRESTORE_EMULATOR_SYSTEM_VARIABLE);
if (emulatorHost != null) {
// Try creating a host in order to validate that the host name is valid.
try {
String hostUrlString = "http://" + emulatorHost;
URI.create(hostUrlString);
} catch (Exception e) {
throw new IllegalArgumentException(
"Value: '"
+ emulatorHost
+ "' for property "
+ FIRESTORE_EMULATOR_SYSTEM_VARIABLE
+ " is not a valid host",
e);
}
// Setting the channel provider to use plaintext turns off SSL.
this.setChannelProvider(
InstantiatingGrpcChannelProvider.newBuilder()
.setEndpoint(emulatorHost)
.setChannelConfigurator(
new ApiFunction<ManagedChannelBuilder, ManagedChannelBuilder>() {
@Override
public ManagedChannelBuilder apply(ManagedChannelBuilder input) {
return input.usePlaintext();
}
})
.build());
// Use a `CredentialProvider` to match the Firebase Admin SDK, which prevents the Admin SDK
// from overwriting the Emulator credentials.
this.setCredentialsProvider(FixedCredentialsProvider.create(new FakeCredentials()));
}
return new FirestoreOptions(this);
}
public class FakeCredentials extends Credentials {
private final Map<String, List<String>> HEADERS =
ImmutableMap.of("Authorization", Arrays.asList("Bearer owner"));
@Override
public String getAuthenticationType() {
throw new IllegalArgumentException("Not supported");
}
@Override
public Map<String, List<String>> getRequestMetadata(URI uri) {
return HEADERS;
}
@Override
public boolean hasRequestMetadata() {
return true;
}
@Override
public boolean hasRequestMetadataOnly() {
return true;
}
@Override
public void refresh() {}
}
}
@InternalApi("This class should only be extended within google-cloud-java")
protected FirestoreOptions(Builder builder) {
super(FirestoreFactory.class, FirestoreRpcFactory.class, builder, new FirestoreDefaults());
this.databaseId =
builder.databaseId != null
? builder.databaseId
: FirestoreDefaults.INSTANCE.getDatabaseId();
this.timestampsInSnapshotsEnabled =
builder.timestampsInSnapshotsEnabled != null
? builder.timestampsInSnapshotsEnabled
: DEFAULT_TIMESTAMPS_IN_SNAPSHOTS_ENABLED;
this.channelProvider =
builder.channelProvider != null
? builder.channelProvider
: GrpcTransportOptions.setUpChannelProvider(
FirestoreSettings.defaultGrpcTransportProviderBuilder(), this);
this.credentialsProvider =
builder.credentialsProvider != null
? builder.credentialsProvider
: GrpcTransportOptions.setUpCredentialsProvider(this);
}
private static class FirestoreDefaults implements ServiceDefaults<Firestore, FirestoreOptions> {
private static final FirestoreDefaults INSTANCE = new FirestoreDefaults();
private final String HOST = FirestoreSettings.getDefaultEndpoint();
private final String DATABASE_ID = "(default)";
private final TransportOptions TRANSPORT_OPTIONS = getDefaultTransportOptionsBuilder().build();
@Nonnull
String getHost() {
return HOST;
}
@Nonnull
String getDatabaseId() {
return DATABASE_ID;
}
@Nonnull
@Override
public FirestoreFactory getDefaultServiceFactory() {
return DefaultFirestoreFactory.INSTANCE;
}
@Nonnull
@Override
public FirestoreRpcFactory getDefaultRpcFactory() {
return DefaultFirestoreRpcFactory.INSTANCE;
}
@Nonnull
@Override
public TransportOptions getDefaultTransportOptions() {
return TRANSPORT_OPTIONS;
}
}
@Nonnull
public static GrpcTransportOptions.Builder getDefaultTransportOptionsBuilder() {
return GrpcTransportOptions.newBuilder();
}
@Nonnull
public static InstantiatingGrpcChannelProvider.Builder
getDefaultTransportChannelProviderBuilder() {
return FirestoreSettings.defaultGrpcTransportProviderBuilder();
}
@Nonnull
public static GoogleCredentialsProvider.Builder getDefaultCredentialsProviderBuilder() {
return FirestoreSettings.defaultCredentialsProviderBuilder();
}
/**
* Returns whether or not {@link DocumentSnapshot DocumentSnapshots} return timestamp fields as
* {@link com.google.cloud.Timestamp Timestamps}.
*/
public boolean areTimestampsInSnapshotsEnabled() {
return timestampsInSnapshotsEnabled;
}
@Override
protected Set<String> getScopes() {
return SCOPES;
}
FirestoreRpc getFirestoreRpc() {
return (FirestoreRpc) getRpc();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FirestoreOptions that = (FirestoreOptions) o;
return Objects.equals(databaseId, that.databaseId)
&& Objects.equals(channelProvider, that.channelProvider)
&& baseEquals(that);
}
@Override
public int hashCode() {
return Objects.hash(databaseId, channelProvider, baseHashCode());
}
@Nonnull
@SuppressWarnings("unchecked")
@Override
public Builder toBuilder() {
return new Builder(this);
}
@Nonnull
public static Builder newBuilder() {
return new Builder();
}
}