-
Notifications
You must be signed in to change notification settings - Fork 59
/
table.ts
2065 lines (1921 loc) · 65.9 KB
/
table.ts
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016 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
//
// https://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.
import {promisifyAll} from '@google-cloud/promisify';
import arrify = require('arrify');
import {ServiceError} from 'google-gax';
import {BackoffSettings} from 'google-gax/build/src/gax';
import {PassThrough, Transform} from 'stream';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const concat = require('concat-stream');
import * as is from 'is';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const pumpify = require('pumpify');
import {
Family,
CreateFamilyOptions,
CreateFamilyCallback,
CreateFamilyResponse,
IColumnFamily,
} from './family';
import {Filter, BoundData, RawFilter} from './filter';
import {Mutation} from './mutation';
import {Row} from './row';
import {ChunkTransformer} from './chunktransformer';
import {CallOptions} from 'google-gax';
import {Bigtable, AbortableDuplex} from '.';
import {Instance} from './instance';
import {ModifiableBackupFields} from './backup';
import {CreateBackupCallback, CreateBackupResponse} from './cluster';
import {google} from '../protos/protos';
import {Duplex} from 'stream';
import {TableUtils} from './utils/table';
// See protos/google/rpc/code.proto
// (4=DEADLINE_EXCEEDED, 8=RESOURCE_EXHAUSTED, 10=ABORTED, 14=UNAVAILABLE)
const RETRYABLE_STATUS_CODES = new Set([4, 8, 10, 14]);
// (1=CANCELLED)
const IGNORED_STATUS_CODES = new Set([1]);
const DEFAULT_BACKOFF_SETTINGS: BackoffSettings = {
initialRetryDelayMillis: 10,
retryDelayMultiplier: 2,
maxRetryDelayMillis: 60000,
};
/**
* @typedef {object} Policy
* @property {number} [version] Specifies the format of the policy.
* Valid values are 0, 1, and 3. Requests specifying an invalid value will
* be rejected.
*
* Operations affecting conditional bindings must specify version 3. This
* can be either setting a conditional policy, modifying a conditional
* binding, or removing a binding (conditional or unconditional) from the
* stored conditional policy.
* Operations on non-conditional policies may specify any valid value or
* leave the field unset.
*
* If no etag is provided in the call to `setIamPolicy`, version compliance
* checks against the stored policy is skipped.
* @property {array} [policy.bindings] Bindings associate members with roles.
* @property {string} [policy.etag] `etag` is used for optimistic concurrency
* control as a way to help prevent simultaneous updates of a policy from
* overwriting each other. It is strongly suggested that systems make use
* of the `etag` in the read-modify-write cycle to perform policy updates
* in order to avoid raceconditions.
*/
export interface Policy {
version?: number;
bindings?: PolicyBinding[];
etag?: Buffer | string;
}
/**
* @typedef {object} PolicyBinding
* @property {array} [PolicyBinding.role] Role that is assigned to `members`.
* For example, `roles/viewer`, `roles/editor`, or `roles/owner`.
* @property {string} [PolicyBinding.members] Identities requesting access.
* The full list of accepted values is outlined here
* https://googleapis.dev/nodejs/bigtable/latest/google.iam.v1.html#.Binding
* @property {Expr} [PolicyBinding.condition] The condition that is associated
* with this binding.
* NOTE: An unsatisfied condition will not allow user access via current
* binding. Different bindings, including their conditions, are examined
* independently.
*/
export interface PolicyBinding {
role?: string;
members?: string[];
condition?: Expr | null;
}
/**
* @typedef {object} Expr
* @property {string} [Expr.expression] The application context of the containing
* message determines which well-known feature set of Common Expression Language
* is supported.
* @property {string} [Expr.title] An optional title for the expression, i.e. a
* short string describing its purpose. This can be used e.g. in UIs which
* allow to enter the expression.
* @property {string} [Expr.description] An optional description of the
* expression. This is a longer text which describes the expression,
* e.g. when hovered over it in a UI.
* @property {string} [Expr.location] An optional string indicating the location
* of the expression for error reporting, e.g. a file name and a position
* in the file.
*/
interface Expr {
expression?: string;
title?: string;
description?: string;
location?: string;
}
/**
* @callback GetIamPolicyCallback
* @param {?Error} err Request error, if any.
* @param {object} policy The policy.
*/
export interface GetIamPolicyCallback {
(err?: Error | null, policy?: Policy): void;
}
/**
* @typedef {array} GetIamPolicyResponse
* @property {object} 0 The policy.
*/
export type GetIamPolicyResponse = [Policy];
export interface GetIamPolicyOptions {
gaxOptions?: CallOptions;
requestedPolicyVersion?: 0 | 1 | 3;
}
export type SetIamPolicyCallback = GetIamPolicyCallback;
export type SetIamPolicyResponse = GetIamPolicyResponse;
/**
* @callback TestIamPermissionsCallback
* @param {?Error} err Request error, if any.
* @param {string[]} permissions A subset of permissions that the caller is
* allowed.
*/
export interface TestIamPermissionsCallback {
(err?: Error | null, permissions?: string[]): void;
}
/**
* @typedef {array} TestIamPermissionsResponse
* @property {string[]} 0 A subset of permissions that the caller is allowed.
*/
export type TestIamPermissionsResponse = [string[]];
export interface CreateTableOptions {
families?: {} | string[];
gaxOptions?: CallOptions;
splits?: string[];
}
export type CreateTableCallback = (
err: ServiceError | null,
table?: Table,
apiResponse?: google.bigtable.admin.v2.Table
) => void;
export type CreateTableResponse = [Table, google.bigtable.admin.v2.Table];
export type TableExistsCallback = (
err: ServiceError | null,
exists?: boolean
) => void;
export type TableExistsResponse = [boolean];
export interface GetTablesOptions {
gaxOptions?: CallOptions;
/**
* View over the table's fields. Possible options are 'name', 'schema' or
* 'full'. Default: 'name'.
*/
view?: 'name' | 'schema' | 'full';
pageSize?: number;
pageToken?: string;
}
export interface GetRowsOptions {
/**
* If set to `false` it will not decode Buffer values returned from Bigtable.
*/
decode?: boolean;
/**
* The encoding to use when converting Buffer values to a string.
*/
encoding?: string;
/**
* End value for key range.
*/
end?: string;
/**
* Row filters allow you to both make advanced queries and format how the data is returned.
*/
filter?: RawFilter;
/**
* Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/CallSettings.html.
*/
gaxOptions?: CallOptions;
/**
* A list of row keys.
*/
keys?: string[];
/**
* Maximum number of rows to be returned.
*/
limit?: number;
/**
* Prefix that the row key must match.
*/
prefix?: string;
/**
* List of prefixes that a row key must match.
*/
prefixes?: string[];
/**
* A list of key ranges.
*/
ranges?: PrefixRange[];
/**
* Start value for key range.
*/
start?: string;
}
export interface GetMetadataOptions {
/**
* Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/CallSettings.html.
*/
gaxOptions?: CallOptions;
/**
* The view to be applied to the table fields.
*/
view?: string;
}
export interface GetTableOptions {
/**
* Automatically create the instance if it does not already exist.
*/
autoCreate?: boolean;
/**
* Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/CallSettings.html.
*/
gaxOptions?: CallOptions;
}
export interface MutateOptions {
/**
* Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
*/
gaxOptions?: CallOptions;
/**
* If set to `true` will treat entriesmas a raw Mutation object. See {@link Mutation#parse}.
*/
rawMutation?: boolean;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type Entry = any;
export type DeleteTableCallback = (
err: ServiceError | null,
apiResponse?: google.protobuf.Empty
) => void;
export type DeleteTableResponse = [google.protobuf.Empty];
export type CheckConsistencyCallback = (
err: ServiceError | null,
consistent?: boolean
) => void;
export type CheckConsistencyResponse = [boolean];
export type GenerateConsistencyTokenCallback = (
err: ServiceError | null,
token?: string
) => void;
export type GenerateConsistencyTokenResponse = [string];
export type WaitForReplicationCallback = (
err: ServiceError | null,
wait?: boolean
) => void;
export type WaitForReplicationResponse = [boolean];
export type TruncateCallback = (
err: ServiceError | null,
apiResponse?: google.protobuf.Empty
) => void;
export type TruncateResponse = [google.protobuf.Empty];
export type SampleRowKeysCallback = (
err: ServiceError | null,
keys?: string[]
) => void;
export type SampleRowsKeysResponse = [string[]];
export type DeleteRowsCallback = (
err: ServiceError | null,
apiResponse?: google.protobuf.Empty
) => void;
export type DeleteRowsResponse = [google.protobuf.Empty];
export type GetMetadataCallback = (
err: ServiceError | null,
apiResponse: google.bigtable.admin.v2.ITable
) => void;
export type GetMetadataResponse = [google.bigtable.admin.v2.Table];
export type GetTableCallback = (
err: ServiceError | null,
table?: Table,
apiResponse?: google.bigtable.admin.v2.ITable
) => void;
export type GetTableResponse = [Table, google.bigtable.admin.v2.Table];
export type GetTablesCallback = (
err: ServiceError | null,
tables?: Table[],
apiResponse?: google.bigtable.admin.v2.ITable[]
) => void;
export type GetTablesResponse = [Table[], google.bigtable.admin.v2.Table[]];
export type GetFamiliesCallback = (
err: ServiceError | null,
families?: Family[],
apiResponse?: IColumnFamily
) => void;
export type GetFamiliesResponse = [Family[], IColumnFamily];
export type GetReplicationStatesCallback = (
err: ServiceError | null,
clusterStates?: Map<string, google.bigtable.admin.v2.Table.IClusterState>,
apiResponse?: {}
) => void;
export type GetReplicationStatesResponse = [
Map<string, google.bigtable.admin.v2.Table.IClusterState>,
google.bigtable.admin.v2.ITable
];
export type GetRowsCallback = (
err: ServiceError | null,
rows?: Row[],
apiResponse?: google.bigtable.v2.ReadRowsResponse
) => void;
export type GetRowsResponse = [Row[], google.bigtable.v2.ReadRowsResponse];
export type InsertRowsCallback = (
err: ServiceError | PartialFailureError | null,
apiResponse?: google.protobuf.Empty
) => void;
export type InsertRowsResponse = [google.protobuf.Empty];
export type MutateCallback = (
err: ServiceError | PartialFailureError | null,
apiResponse?: google.protobuf.Empty
) => void;
export type MutateResponse = [google.protobuf.Empty];
export interface PrefixRange {
start?: BoundData | string;
end?: BoundData | string;
}
export interface CreateBackupConfig extends ModifiableBackupFields {
gaxOptions?: CallOptions;
}
/**
* Create a Table object to interact with a Cloud Bigtable table.
*
* @class
* @param {Instance} instance Instance Object.
* @param {string} id Unique identifier of the table.
*
* @example
* ```
* const {Bigtable} = require('@google-cloud/bigtable');
* const bigtable = new Bigtable();
* const instance = bigtable.instance('my-instance');
* const table = instance.table('prezzy');
* ```
*/
export class Table {
bigtable: Bigtable;
instance: Instance;
name: string;
id: string;
metadata?: google.bigtable.admin.v2.ITable;
maxRetries?: number;
constructor(instance: Instance, id: string) {
this.bigtable = instance.bigtable;
this.instance = instance;
let name;
if (id.includes('/')) {
if (id.startsWith(`${instance.name}/tables/`)) {
name = id;
} else {
throw new Error(`Table id '${id}' is not formatted correctly.
Please use the format 'prezzy' or '${instance.name}/tables/prezzy'.`);
}
} else {
name = `${instance.name}/tables/${id}`;
}
this.name = name;
this.id = name.split('/').pop()!;
}
/**
* Formats the decodes policy etag value to string.
*
* @private
*
* @param {object} policy
*/
static decodePolicyEtag(policy: Policy): Policy {
policy.etag = policy.etag!.toString('ascii');
return policy;
}
/**
* Formats the table name to include the Bigtable cluster.
*
* @private
*
* @param {string} instanceName The formatted instance name.
* @param {string} name The table name.
*
* @example
* ```
* Table.formatName_(
* 'projects/my-project/zones/my-zone/instances/my-instance',
* 'my-table'
* );
* //
* 'projects/my-project/zones/my-zone/instances/my-instance/tables/my-table'
* ```
*/
static formatName_(instanceName: string, id: string) {
if (id.includes('/')) {
return id;
}
return `${instanceName}/tables/${id}`;
}
/**
* Creates a range based off of a key prefix.
*
* @private
*
* @param {string} start The key prefix/starting bound.
* @returns {object} range
*
* @example
* ```
* const {Bigtable} = require('@google-cloud/bigtable');
* const bigtable = new Bigtable();
* const instance = bigtable.instance('my-instance');
* const table = instance.table('prezzy');
* table.createPrefixRange('start');
* // => {
* // start: 'start',
* // end: {
* // value: 'staru',
* // inclusive: false
* // }
* // }
* ```
*/
static createPrefixRange(start: string): PrefixRange {
return TableUtils.createPrefixRange(start);
}
create(options?: CreateTableOptions): Promise<CreateTableResponse>;
create(options: CreateTableOptions, callback: CreateTableCallback): void;
create(callback: CreateTableCallback): void;
/**
* Create a table.
*
* @param {object} [options] See {@link Instance#createTable}.
* @param {object} [options.gaxOptions] Request configuration options, outlined
* here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
* @param {function} callback The callback function.
* @param {?error} callback.err An error returned while making this request.
* @param {Table} callback.table The newly created table.
* @param {object} callback.apiResponse The full API response.
*
* @example <caption>include:samples/api-reference-doc-snippets/table.js</caption>
* region_tag:bigtable_api_create_table
*/
create(
optionsOrCallback?: CreateTableOptions | CreateTableCallback,
cb?: CreateTableCallback
): void | Promise<CreateTableResponse> {
const callback =
typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!;
const options =
typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
this.instance.createTable(this.id, options, callback);
}
createBackup(
id: string,
config: CreateBackupConfig
): Promise<CreateBackupResponse>;
createBackup(
id: string,
config: CreateBackupConfig,
callback: CreateBackupCallback
): void;
createBackup(
id: string,
config: CreateBackupConfig,
callback: CreateBackupCallback
): void;
/**
* Backup a table with cluster auto selection.
*
* Backups of tables originate from a specific cluster. This is a helper
* around `Cluster.createBackup` that automatically selects the first ready
* cluster from which a backup can be performed.
*
* NOTE: This will make two API requests to first determine the most
* appropriate cluster, then create the backup. This could lead to a race
* condition if other requests are simultaneously sent or if the cluster
* availability state changes between each call.
*
* @param {string} id A unique ID for the backup.
* @param {CreateBackupConfig} config Metadata to set on the Backup.
* @param {BackupTimestamp} config.expireTime When the backup will be
* automatically deleted.
* @param {CallOptions} [config.gaxOptions] Request configuration options,
* outlined here:
* https://googleapis.github.io/gax-nodejs/CallSettings.html.
* @param {CreateBackupCallback} [callback] The callback function.
* @param {?error} callback.err An error returned while making this request.
* @param {Backup} callback.backup The newly created Backup.
* @param {Operation} callback.operation An operation object that can be used
* to check the status of the request.
* @param {object} callback.apiResponse The full API response.
* @return {void | Promise<CreateBackupResponse>}
*/
createBackup(
id: string,
config: CreateBackupConfig,
callback?: CreateBackupCallback
): void | Promise<CreateBackupResponse> {
if (!id) {
throw new TypeError('An id is required to create a backup.');
}
if (!config) {
throw new TypeError('A configuration object is required.');
}
this.getReplicationStates(config.gaxOptions!, (err, stateMap) => {
if (err) {
callback!(err);
return;
}
const [clusterId] =
[...stateMap!.entries()].find(([, clusterState]) => {
return (
clusterState.replicationState === 'READY' ||
clusterState.replicationState === 'READY_OPTIMIZING'
);
}) || [];
if (!clusterId) {
callback!(new Error('No ready clusters eligible for backup.'));
return;
}
this.instance.cluster(clusterId).createBackup(
id,
{
table: this.name,
...config,
},
callback!
);
});
}
createFamily(
id: string,
options?: CreateFamilyOptions
): Promise<CreateFamilyResponse>;
createFamily(
id: string,
options: CreateFamilyOptions,
callback: CreateFamilyCallback
): void;
createFamily(id: string, callback: CreateFamilyCallback): void;
/**
* Create a column family.
*
* Optionally you can send garbage collection rules and when creating a
* family. Garbage collection executes opportunistically in the background, so
* it's possible for reads to return a cell even if it matches the active
* expression for its family.
*
* @see [Garbage Collection Proto Docs]{@link https://github.com/googleapis/googleapis/blob/3b236df084cf9222c529a2890f90e3a4ff0f2dfd/google/bigtable/admin/v2/table.proto#L184}
*
* @throws {error} If a name is not provided.
*
* @param {string} id The unique identifier of column family.
* @param {object} [options] Configuration object.
* @param {object} [options.gaxOptions] Request configuration options, outlined
* here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
* @param {object} [options.rule] Garbage collection rule
* @param {object} [options.rule.age] Delete cells in a column older than the
* given age. Values must be at least 1 millisecond.
* @param {number} [options.rule.versions] Maximum number of versions to delete
* cells in a column, except for the most recent.
* @param {boolean} [options.rule.intersect] Cells to delete should match all
* rules.
* @param {boolean} [options.rule.union] Cells to delete should match any of the
* rules.
* @param {function} callback The callback function.
* @param {?error} callback.err An error returned while making this request.
* @param {Family} callback.family The newly created Family.
* @param {object} callback.apiResponse The full API response.
*
* @example <caption>include:samples/api-reference-doc-snippets/table.js</caption>
* region_tag:bigtable_api_create_family
*/
createFamily(
id: string,
optionsOrCallback?: CreateFamilyOptions | CreateFamilyCallback,
cb?: CreateFamilyCallback
): void | Promise<CreateFamilyResponse> {
const callback =
typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!;
const options =
typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
if (!id) {
throw new Error('An id is required to create a family.');
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const mod: any = {
id,
create: {},
};
if (options.rule) {
mod.create.gcRule = Family.formatRule_(options.rule);
}
const reqOpts = {
name: this.name,
modifications: [mod],
};
this.bigtable.request(
{
client: 'BigtableTableAdminClient',
method: 'modifyColumnFamilies',
reqOpts,
gaxOpts: options.gaxOptions,
},
(err, resp) => {
if (err) {
callback(err, null, resp);
return;
}
const family = this.family(id);
family.metadata = resp;
callback(null, family, resp);
}
);
}
/**
* Get {@link Row} objects for the rows currently in your table as a
* readable object stream.
*
* @param {object} [options] Configuration object.
* @param {boolean} [options.decode=true] If set to `false` it will not decode
* Buffer values returned from Bigtable.
* @param {boolean} [options.encoding] The encoding to use when converting
* Buffer values to a string.
* @param {string} [options.end] End value for key range.
* @param {Filter} [options.filter] Row filters allow you to
* both make advanced queries and format how the data is returned.
* @param {object} [options.gaxOptions] Request configuration options, outlined
* here: https://googleapis.github.io/gax-nodejs/CallSettings.html.
* @param {string[]} [options.keys] A list of row keys.
* @param {number} [options.limit] Maximum number of rows to be returned.
* @param {string} [options.prefix] Prefix that the row key must match.
* @param {string[]} [options.prefixes] List of prefixes that a row key must
* match.
* @param {object[]} [options.ranges] A list of key ranges.
* @param {string} [options.start] Start value for key range.
* @returns {stream}
*
* @example <caption>include:samples/api-reference-doc-snippets/table.js</caption>
* region_tag:bigtable_api_table_readstream
*/
createReadStream(opts?: GetRowsOptions) {
const options = opts || {};
const maxRetries = is.number(this.maxRetries) ? this.maxRetries! : 3;
let activeRequestStream: AbortableDuplex | null;
let rowKeys: string[];
let filter: {} | null;
const rowsLimit = options.limit || 0;
const hasLimit = rowsLimit !== 0;
let rowsRead = 0;
let numConsecutiveErrors = 0;
let numRequestsMade = 0;
let retryTimer: NodeJS.Timeout | null;
rowKeys = options.keys || [];
const ranges = TableUtils.getRanges(options);
// If rowKeys and ranges are both empty, the request is a full table scan.
// Add an empty range to simplify the resumption logic.
if (rowKeys.length === 0 && ranges.length === 0) {
ranges.push({});
}
if (options.filter) {
filter = Filter.parse(options.filter);
}
const userStream = new PassThrough({objectMode: true});
const end = userStream.end.bind(userStream);
userStream.end = () => {
rowStream?.unpipe(userStream);
if (activeRequestStream) {
activeRequestStream.abort();
}
if (retryTimer) {
clearTimeout(retryTimer);
}
return end();
};
let chunkTransformer: ChunkTransformer;
let rowStream: Duplex;
const makeNewRequest = () => {
// Avoid cancelling an expired timer if user
// cancelled the stream in the middle of a retry
retryTimer = null;
const lastRowKey = chunkTransformer ? chunkTransformer.lastRowKey : '';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
chunkTransformer = new ChunkTransformer({decode: options.decode} as any);
const reqOpts = {
tableName: this.name,
appProfileId: this.bigtable.appProfileId,
} as google.bigtable.v2.IReadRowsRequest;
const retryOpts = {
currentRetryAttempt: numConsecutiveErrors,
// Handling retries in this client. Specify the retry options to
// make sure nothing is retried in retry-request.
noResponseRetries: 0,
shouldRetryFn: (_: any) => {
return false;
},
};
if (lastRowKey) {
// Readjust and/or remove ranges based on previous valid row reads.
// Iterate backward since items may need to be removed.
for (let index = ranges.length - 1; index >= 0; index--) {
const range = ranges[index];
const startValue = is.object(range.start)
? (range.start as BoundData).value
: range.start;
const endValue = is.object(range.end)
? (range.end as BoundData).value
: range.end;
const startKeyIsRead =
!startValue ||
TableUtils.lessThanOrEqualTo(
startValue as string,
lastRowKey as string
);
const endKeyIsNotRead =
!endValue ||
(endValue as Buffer).length === 0 ||
TableUtils.lessThan(lastRowKey as string, endValue as string);
if (startKeyIsRead) {
if (endKeyIsNotRead) {
// EndKey is not read, reset the range to start from lastRowKey open
range.start = {
value: lastRowKey,
inclusive: false,
};
} else {
// EndKey is read, remove this range
ranges.splice(index, 1);
}
}
}
// Remove rowKeys already read.
rowKeys = rowKeys.filter(rowKey =>
TableUtils.greaterThan(rowKey, lastRowKey as string)
);
// If there was a row limit in the original request and
// we've already read all the rows, end the stream and
// do not retry.
if (hasLimit && rowsLimit === rowsRead) {
userStream.end();
return;
}
// If all the row keys and ranges are read, end the stream
// and do not retry.
if (rowKeys.length === 0 && ranges.length === 0) {
userStream.end();
return;
}
}
// Create the new reqOpts
reqOpts.rows = {};
// TODO: preprocess all the keys and ranges to Bytes
reqOpts.rows.rowKeys = rowKeys.map(
Mutation.convertToBytes
) as {} as Uint8Array[];
reqOpts.rows.rowRanges = ranges.map(range =>
Filter.createRange(
range.start as BoundData,
range.end as BoundData,
'Key'
)
);
if (filter) {
reqOpts.filter = filter;
}
if (hasLimit) {
reqOpts.rowsLimit = rowsLimit - rowsRead;
}
options.gaxOptions = populateAttemptHeader(
numRequestsMade,
options.gaxOptions
);
const requestStream = this.bigtable.request({
client: 'BigtableClient',
method: 'readRows',
reqOpts,
gaxOpts: options.gaxOptions,
retryOpts,
});
activeRequestStream = requestStream!;
const toRowStream = new Transform({
transform: (rowData, _, next) => {
if (
chunkTransformer._destroyed ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(userStream as any)._writableState.ended
) {
return next();
}
rowsRead++;
const row = this.row(rowData.key);
row.data = rowData.data;
next(null, row);
},
objectMode: true,
});
rowStream = pumpify.obj([requestStream, chunkTransformer, toRowStream]);
// Retry on "received rst stream" errors
const isRstStreamError = (error: ServiceError): boolean => {
if (error.code === 13 && error.message) {
const error_message = (error.message || '').toLowerCase();
return (
error.code === 13 &&
(error_message.includes('rst_stream') ||
error_message.includes('rst stream'))
);
}
return false;
};
rowStream
.on('error', (error: ServiceError) => {
rowStream.unpipe(userStream);
activeRequestStream = null;
if (IGNORED_STATUS_CODES.has(error.code)) {
// We ignore the `cancelled` "error", since we are the ones who cause
// it when the user calls `.abort()`.
userStream.end();
return;
}
numConsecutiveErrors++;
numRequestsMade++;
if (
numConsecutiveErrors <= maxRetries &&
(RETRYABLE_STATUS_CODES.has(error.code) || isRstStreamError(error))
) {
const backOffSettings =
options.gaxOptions?.retry?.backoffSettings ||
DEFAULT_BACKOFF_SETTINGS;
const nextRetryDelay = getNextDelay(
numConsecutiveErrors,
backOffSettings
);
retryTimer = setTimeout(makeNewRequest, nextRetryDelay);
} else {
userStream.emit('error', error);
}
})
.on('data', _ => {
// Reset error count after a successful read so the backoff
// time won't keep increasing when as stream had multiple errors
numConsecutiveErrors = 0;
})
.on('end', () => {
activeRequestStream = null;
});
rowStream.pipe(userStream);
};
makeNewRequest();
return userStream;
}
delete(gaxOptions?: CallOptions): Promise<DeleteTableResponse>;
delete(gaxOptions: CallOptions, callback: DeleteTableCallback): void;
delete(callback: DeleteTableCallback): void;
/**
* Delete the table.
*
* @param {object} [gaxOptions] Request configuration options, outlined
* here: https://googleapis.github.io/gax-nodejs/CallSettings.html.
* @param {function} [callback] The callback function.
* @param {?error} callback.err An error returned while making this
* request.
* @param {object} callback.apiResponse The full API response.
*
* @example <caption>include:samples/api-reference-doc-snippets/table.js</caption>
* region_tag:bigtable_api_del_table
*/
delete(
optionsOrCallback?: CallOptions | DeleteTableCallback,
cb?: DeleteTableCallback
): void | Promise<DeleteTableResponse> {
const gaxOptions =
typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
const callback =
typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!;
this.bigtable.request(
{
client: 'BigtableTableAdminClient',
method: 'deleteTable',
reqOpts: {
name: this.name,
},
gaxOpts: gaxOptions,
},
callback
);
}
deleteRows(
prefix: string,
gaxOptions?: CallOptions
): Promise<DeleteRowsResponse>;
deleteRows(
prefix: string,
gaxOptions: CallOptions,