forked from googleapis/nodejs-pubsub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpubsub.ts
1587 lines (1484 loc) · 49.6 KB
/
pubsub.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 2014 Google Inc. All Rights Reserved.
*
* 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.
*/
import {paginator} from '@google-cloud/paginator';
import {replaceProjectIdToken} from '@google-cloud/projectify';
import * as extend from 'extend';
import {GoogleAuth} from 'google-auth-library';
import * as gax from 'google-gax';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const PKG = require('../../package.json');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const v1 = require('./v1');
import {promisifySome} from './util';
import {
Schema,
SchemaType,
ICreateSchemaRequest,
SchemaViews,
ISchema,
SchemaView,
} from './schema';
import {Snapshot} from './snapshot';
import {
Subscription,
SubscriptionMetadata,
SubscriptionOptions,
CreateSubscriptionOptions,
CreateSubscriptionCallback,
CreateSubscriptionResponse,
DetachSubscriptionCallback,
DetachSubscriptionResponse,
} from './subscription';
import {
Topic,
GetTopicSubscriptionsCallback,
GetTopicSubscriptionsResponse,
CreateTopicCallback,
CreateTopicResponse,
TopicMetadata,
} from './topic';
import {PublishOptions} from './publisher';
import {CallOptions} from 'google-gax';
import {Transform} from 'stream';
import {google} from '../protos/protos';
import {SchemaServiceClient} from './v1';
/**
* Project ID placeholder.
* @type {string}
* @private
*/
const PROJECT_ID_PLACEHOLDER = '{{projectId}}';
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export interface ClientConfig extends gax.GrpcClientOptions {
apiEndpoint?: string;
servicePath?: string;
port?: string | number;
sslCreds?: gax.grpc.ChannelCredentials;
}
export interface PageOptions {
gaxOpts?: CallOptions;
pageSize?: number;
pageToken?: string;
autoPaginate?: boolean;
}
export type GetSnapshotsCallback = RequestCallback<
Snapshot,
google.pubsub.v1.IListSnapshotsResponse
>;
export type GetSnapshotsResponse = PagedResponse<
Snapshot,
google.pubsub.v1.IListSnapshotsResponse
>;
export type GetSubscriptionsOptions = PageOptions & {topic?: string | Topic};
type GetAllSubscriptionsCallback = RequestCallback<
Subscription,
google.pubsub.v1.IListSubscriptionsResponse
>;
type GetAllSubscriptionsResponse = PagedResponse<
Subscription,
google.pubsub.v1.IListSubscriptionsResponse
>;
export type GetSubscriptionsCallback =
| GetAllSubscriptionsCallback
| GetTopicSubscriptionsCallback;
export type GetSubscriptionsResponse =
| GetAllSubscriptionsResponse
| GetTopicSubscriptionsResponse;
export type GetTopicsCallback = RequestCallback<
Topic,
google.pubsub.v1.IListTopicsResponse
>;
export type GetTopicsResponse = PagedResponse<
Topic,
google.pubsub.v1.IListTopicsResponse
>;
export type EmptyCallback = RequestCallback<google.protobuf.IEmpty>;
export type EmptyResponse = [google.protobuf.IEmpty];
export type ExistsCallback = RequestCallback<boolean>;
export type ExistsResponse = [boolean];
export type DetachedCallback = RequestCallback<boolean>;
export type DetachedResponse = [boolean];
export interface GetClientConfig {
client: 'PublisherClient' | 'SubscriberClient';
}
export interface RequestConfig extends GetClientConfig {
method: string;
reqOpts?: object;
gaxOpts?: CallOptions;
}
export interface ResourceCallback<Resource, Response> {
(
err: gax.grpc.ServiceError | null,
resource?: Resource | null,
response?: Response | null
): void;
}
export type RequestCallback<T, R = void> = R extends void
? NormalCallback<T>
: PagedCallback<T, R>;
export interface NormalCallback<TResponse> {
(err: gax.grpc.ServiceError | null, res?: TResponse | null): void;
}
export interface PagedCallback<Item, Response> {
(
err: gax.grpc.ServiceError | null,
results?: Item[] | null,
nextQuery?: {} | null,
response?: Response | null
): void;
}
export type PagedResponse<Item, Response> =
| [Item[]]
| [Item[], {} | null, Response];
export type ObjectStream<O> = {
addListener(event: 'data', listener: (data: O) => void): ObjectStream<O>;
emit(event: 'data', data: O): boolean;
on(event: 'data', listener: (data: O) => void): ObjectStream<O>;
once(event: 'data', listener: (data: O) => void): ObjectStream<O>;
prependListener(event: 'data', listener: (data: O) => void): ObjectStream<O>;
prependOnceListener(
event: 'data',
listener: (data: O) => void
): ObjectStream<O>;
} & Transform;
interface GetClientCallback {
(err: Error | null, gaxClient?: gax.ClientStub): void;
}
/**
* @typedef {object} ClientConfig
* @property {string} [projectId] The project ID from the Google Developer's
* Console, e.g. 'grape-spaceship-123'. We will also check the environment
* variable `GCLOUD_PROJECT` for your project ID. If your app is running in
* an environment which supports {@link
* https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application
* Application Default Credentials}, your project ID will be detected
* automatically.
* @property {string} [keyFilename] Full path to the a .json, .pem, or .p12 key
* downloaded from the Google Developers Console. If you provide a path to a
* JSON file, the `projectId` option above is not necessary. NOTE: .pem and
* .p12 require you to specify the `email` option as well.
* @property {string} [apiEndpoint] The `apiEndpoint` from options will set the
* host. If not set, the `PUBSUB_EMULATOR_HOST` environment variable from the
* gcloud SDK is honored. We also check the `CLOUD_API_ENDPOINT_OVERRIDES_PUBSUB`
* environment variable used by `gcloud alpha pubsub`. Otherwise the actual API
* endpoint will be used. Note that if the URL doesn't end in '.googleapis.com',
* we will assume that it's an emulator and disable strict SSL checks.
* @property {string} [email] Account email address. Required when using a .pem
* or .p12 keyFilename.
* @property {object} [credentials] Credentials object.
* @property {string} [credentials.client_email]
* @property {string} [credentials.private_key]
* @property {boolean} [autoRetry=true] Automatically retry requests if the
* response is related to rate limits or certain intermittent server errors.
* We will exponentially backoff subsequent requests by default.
* @property {Constructor} [promise] Custom promise module to use instead of
* native Promises.
*/
/**
* [Cloud Pub/Sub](https://developers.google.com/pubsub/overview) is a
* reliable, many-to-many, asynchronous messaging service from Cloud
* Platform.
*
* @class
*
* @see [Cloud Pub/Sub overview]{@link https://developers.google.com/pubsub/overview}
*
* @param {ClientConfig} [options] Configuration options.
*
* @example Import the client library
* ```
* const {PubSub} = require('@google-cloud/pubsub');
*
* ```
* @example Create a client that uses <a href="https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application">Application Default Credentials (ADC)</a>:
* ```
* const pubsub = new PubSub();
*
* ```
* @example Create a client with <a href="https://cloud.google.com/docs/authentication/production#obtaining_and_providing_service_account_credentials_manually">explicit credentials</a>:
* ```
* const pubsub = new PubSub({
* projectId: 'your-project-id',
* keyFilename: '/path/to/keyfile.json'
* });
*
* ```
* @example <caption>include:samples/quickstart.js</caption>
* region_tag:pubsub_quickstart_create_topic
* Full quickstart example:
*/
export class PubSub {
options: ClientConfig;
isEmulator: boolean;
api: {[key: string]: gax.ClientStub};
auth: GoogleAuth;
projectId: string;
name?: string;
// tslint:disable-next-line variable-name
Promise?: PromiseConstructor;
getSubscriptionsStream = paginator.streamify(
'getSubscriptions'
) as () => ObjectStream<Subscription>;
getSnapshotsStream = paginator.streamify(
'getSnapshots'
) as () => ObjectStream<Snapshot>;
getTopicsStream = paginator.streamify(
'getTopics'
) as () => ObjectStream<Topic>;
isOpen = true;
private schemaClient?: SchemaServiceClient;
constructor(options?: ClientConfig) {
options = Object.assign({}, options || {});
// Needed for potentially large responses that may come from using exactly-once delivery.
// This will get passed down to grpc client objects.
const maxMetadataSize = 'grpc.max_metadata_size';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const optionsAny = options as any;
if (optionsAny[maxMetadataSize] === undefined) {
optionsAny[maxMetadataSize] = 4 * 1024 * 1024; // 4 MiB
}
// Determine what scopes are needed.
// It is the union of the scopes on both clients.
const clientClasses = [v1.SubscriberClient, v1.PublisherClient];
const allScopes: {[key: string]: boolean} = {};
for (const clientClass of clientClasses) {
for (const scope of clientClass.scopes) {
allScopes[scope] = true;
}
}
this.options = Object.assign(
{
libName: 'gccl',
libVersion: PKG.version,
scopes: Object.keys(allScopes),
},
options
);
/**
* @name PubSub#isEmulator
* @type {boolean}
*/
this.isEmulator = false;
this.determineBaseUrl_();
this.api = {};
this.auth = new GoogleAuth(this.options);
this.projectId = this.options.projectId || PROJECT_ID_PLACEHOLDER;
if (this.projectId !== PROJECT_ID_PLACEHOLDER) {
this.name = PubSub.formatName_(this.projectId);
}
}
/**
* Returns true if we have actually resolved the full project name.
*
* @returns {boolean} true if the name is resolved.
*/
get isIdResolved(): boolean {
return this.projectId.indexOf(PROJECT_ID_PLACEHOLDER) < 0;
}
/**
* Closes out this object, releasing any server connections. Note that once
* you close a PubSub object, it may not be used again. Any pending operations
* (e.g. queued publish messages) will fail. If you have topic or subscription
* objects that may have pending operations, you should call close() on those
* first if you want any pending messages to be delivered correctly. The
* PubSub class doesn't track those.
*
* @callback EmptyCallback
* @returns {Promise<void>}
*/
close(): Promise<void>;
close(callback: EmptyCallback): void;
close(callback?: EmptyCallback): Promise<void> | void {
const definedCallback = callback || (() => {});
if (this.isOpen) {
this.isOpen = false;
this.closeAllClients_()
.then(() => this.schemaClient?.close())
.then(() => {
definedCallback(null);
})
.catch(definedCallback);
} else {
definedCallback(null);
}
}
/**
* Create a schema in the project.
*
* @see [Schemas: create API Documentation]{@link https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.schemas/create}
* @see {@link Schema#create}
*
* @throws {Error} If a schema ID or name is not provided.
* @throws {Error} If an invalid SchemaType is provided.
* @throws {Error} If an invalid schema definition is provided.
*
* @param {string} schemaId The name or ID of the subscription.
* @param {SchemaType} type The type of the schema (Protobuf, Avro, etc).
* @param {string} definition The text describing the schema in terms of the type.
* @param {object} [options] Request configuration options, outlined
* here: https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html.
* @returns {Promise<Schema>}
*
* @example Create a schema.
* ```
* const {PubSub} = require('@google-cloud/pubsub');
* const pubsub = new PubSub();
*
* await pubsub.createSchema(
* 'messageType',
* SchemaTypes.Avro,
* '{...avro definition...}'
* );
* ```
*/
async createSchema(
schemaId: string,
type: SchemaType,
definition: string,
gaxOpts?: CallOptions
): Promise<Schema> {
// This populates projectId for us.
await this.getClientConfig();
const schemaName = Schema.formatName_(this.projectId, schemaId);
const request: ICreateSchemaRequest = {
parent: this.name,
schemaId,
schema: {
name: schemaName,
type,
definition,
},
};
const client = await this.getSchemaClient_();
await client.createSchema(request, gaxOpts);
return new Schema(this, schemaName);
}
/**
* @typedef {array} CreateSubscriptionResponse
* @property {Subscription} 0 The new {@link Subscription}.
* @property {object} 1 The full API response.
*/
/**
* @callback CreateSubscriptionCallback
* @param {?Error} err Request error, if any.
* @param {Subscription} Subscription
* @param {object} apiResponse The full API response.
*/
/**
* Options for creating a subscription.
*
* See a [Subscription
* resource](https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.subscriptions).
*
* @typedef {object} CreateSubscriptionRequest
* @property {DeadLetterPolicy} [deadLetterPolicy] A policy that specifies the
* conditions for dead lettering messages in this subscription.
* @property {object} [flowControl] Flow control configurations for
* receiving messages. Note that these options do not persist across
* subscription instances.
* @property {number} [flowControl.maxBytes] The maximum number of bytes
* in un-acked messages to allow before the subscription pauses incoming
* messages. Defaults to 20% of free memory.
* @property {number} [flowControl.maxMessages=Infinity] The maximum number
* of un-acked messages to allow before the subscription pauses incoming
* messages.
* @property {object} [gaxOpts] Request configuration options, outlined
* here: https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html.
* @property {number|google.protobuf.Duration} [messageRetentionDuration] Set
* this to override the default duration of 7 days. This value is expected
* in seconds. Acceptable values are in the range of 10 minutes and 7
* days.
* @property {string} [pushEndpoint] A URL to a custom endpoint that
* messages should be pushed to.
* @property {object} [oidcToken] If specified, Pub/Sub will generate and
* attach an OIDC JWT token as an `Authorization` header in the HTTP
* request for every pushed message. This object should have the same
* structure as [OidcToken]{@link google.pubsub.v1.OidcToken}
* @property {boolean} [retainAckedMessages=false] If set, acked messages
* are retained in the subscription's backlog for the length of time
* specified by `options.messageRetentionDuration`.
* @property {ExpirationPolicy} [expirationPolicy] A policy that specifies
* the conditions for this subscription's expiration.
*/
/**
* Create a subscription to a topic.
*
* @see [Subscriptions: create API Documentation]{@link https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.subscriptions/create}
* @see {@link Topic#createSubscription}
*
* @throws {Error} If a Topic instance or topic name is not provided.
* @throws {Error} If a subscription name is not provided.
*
* @param {Topic|string} topic The Topic to create a subscription to.
* @param {string} name The name of the subscription.
* @param {CreateSubscriptionRequest} [options] See a [Subscription resource](https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.subscriptions).
* @param {CreateSubscriptionCallback} [callback] Callback function.
* @returns {Promise<CreateSubscriptionResponse>}
*
* @example Subscribe to a topic.
* ```
* const {PubSub} = require('@google-cloud/pubsub');
* const pubsub = new PubSub();
*
* const topic = 'messageCenter';
* const name = 'newMessages';
*
* const callback = function(err, subscription, apiResponse) {};
*
* pubsub.createSubscription(topic, name, callback);
*
* ```
* @example If the callback is omitted, we'll return a Promise.
* ```
* pubsub.createSubscription(topic, name)
* .then(function(data) {
* const subscription = data[0];
* const apiResponse = data[1];
* });
* ```
*/
createSubscription(
topic: Topic | string,
name: string,
options?: CreateSubscriptionOptions
): Promise<CreateSubscriptionResponse>;
createSubscription(
topic: Topic | string,
name: string,
callback: CreateSubscriptionCallback
): void;
createSubscription(
topic: Topic | string,
name: string,
options: CreateSubscriptionOptions,
callback: CreateSubscriptionCallback
): void;
createSubscription(
topic: Topic | string,
name: string,
optionsOrCallback?: CreateSubscriptionOptions | CreateSubscriptionCallback,
callback?: CreateSubscriptionCallback
): Promise<CreateSubscriptionResponse> | void {
if (typeof topic !== 'string' && !(topic instanceof Topic)) {
throw new Error('A Topic is required for a new subscription.');
}
if (typeof name !== 'string') {
throw new Error('A subscription name is required.');
}
if (typeof topic === 'string') {
topic = this.topic(topic);
}
let options =
typeof optionsOrCallback === 'object'
? optionsOrCallback
: ({} as CreateSubscriptionOptions);
callback =
typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
// Make a deep copy of options to not pollute caller object.
options = extend(true, {}, options);
const gaxOpts = options.gaxOpts;
const flowControl = options.flowControl;
delete options.gaxOpts;
delete options.flowControl;
const metadata = Subscription.formatMetadata_(
options as SubscriptionMetadata
);
let subscriptionCtorOptions = flowControl ? {flowControl} : {};
subscriptionCtorOptions = Object.assign(subscriptionCtorOptions, metadata);
const subscription = this.subscription(name, subscriptionCtorOptions);
const reqOpts = Object.assign(metadata, {
topic: topic.name,
name: subscription.name,
});
this.request<google.pubsub.v1.ISubscription>(
{
client: 'SubscriberClient',
method: 'createSubscription',
reqOpts,
gaxOpts,
},
(err, resp) => {
if (err) {
callback!(err, null, resp);
return;
}
subscription.metadata = resp!;
callback!(null, subscription, resp!);
}
);
}
/**
* @typedef {array} CreateTopicResponse
* @property {Topic} 0 The new {@link Topic}.
* @property {object} 1 The full API response.
*/
/**
* @callback CreateTopicCallback
* @param {?Error} err Request error, if any.
* @param {Topic} topic The new {@link Topic}.
* @param {object} apiResponse The full API response.
*/
/**
* Create a topic with the given name.
*
* @see [Topics: create API Documentation]{@link https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.topics/create}
*
* @param {string} name Name of the topic.
* @param {object} [gaxOpts] Request configuration options, outlined
* here: https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html.
* @param {CreateTopicCallback} [callback] Callback function.
* @returns {Promise<CreateTopicResponse>}
*
* @example
* ```
* const {PubSub} = require('@google-cloud/pubsub');
* const pubsub = new PubSub();
*
* pubsub.createTopic('my-new-topic', function(err, topic, apiResponse) {
* if (!err) {
* // The topic was created successfully.
* }
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* pubsub.createTopic('my-new-topic').then(function(data) {
* const topic = data[0];
* const apiResponse = data[1];
* });
* ```
*/
createTopic(
name: string | TopicMetadata,
gaxOpts?: CallOptions
): Promise<CreateTopicResponse>;
createTopic(
name: string | TopicMetadata,
callback: CreateTopicCallback
): void;
createTopic(
name: string | TopicMetadata,
gaxOpts: CallOptions,
callback: CreateTopicCallback
): void;
createTopic(
name: string | TopicMetadata,
optsOrCallback?: CallOptions | CreateTopicCallback,
callback?: CreateTopicCallback
): Promise<CreateTopicResponse> | void {
const reqOpts: TopicMetadata =
typeof name === 'string'
? {
name,
}
: name;
// We don't allow a blank name, but this will let topic() handle that case.
const topic = this.topic(reqOpts.name || '');
// Topic#constructor might have canonicalized the name.
reqOpts.name = topic.name;
const gaxOpts = typeof optsOrCallback === 'object' ? optsOrCallback : {};
callback = typeof optsOrCallback === 'function' ? optsOrCallback : callback;
this.request<google.pubsub.v1.ITopic>(
{
client: 'PublisherClient',
method: 'createTopic',
reqOpts,
gaxOpts,
},
(err, resp) => {
if (err) {
callback!(err, null, resp);
return;
}
topic.metadata = resp!;
callback!(null, topic, resp!);
}
);
}
/**
* Detach a subscription with the given name.
*
* @see [Admin: Pub/Sub administration API Documentation]{@link https://cloud.google.com/pubsub/docs/admin}
*
* @param {string} name Name of the subscription.
* @param {object} [gaxOpts] Request configuration options, outlined
* here: https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html.
* @param {DetachSubscriptionCallback} [callback] Callback function.
* @returns {Promise<DetachSubscriptionResponse>}
*
* @example
* ```
* const {PubSub} = require('@google-cloud/pubsub');
* const pubsub = new PubSub();
*
* pubsub.detachSubscription('my-sub', (err, topic, apiResponse) => {
* if (!err) {
* // The topic was created successfully.
* }
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* pubsub.detachSubscription('my-sub').then(data => {
* const apiResponse = data[0];
* });
* ```
*/
detachSubscription(
name: string,
gaxOpts?: CallOptions
): Promise<DetachSubscriptionResponse>;
detachSubscription(name: string, callback: DetachSubscriptionCallback): void;
detachSubscription(
name: string,
gaxOpts: CallOptions,
callback: DetachSubscriptionCallback
): void;
detachSubscription(
name: string,
optsOrCallback?: CallOptions | DetachSubscriptionCallback,
callback?: DetachSubscriptionCallback
): Promise<DetachSubscriptionResponse> | void {
if (typeof name !== 'string') {
throw new Error('A subscription name is required.');
}
const sub = this.subscription(name);
const reqOpts = {
subscription: sub.name,
};
const gaxOpts = typeof optsOrCallback === 'object' ? optsOrCallback : {};
callback = typeof optsOrCallback === 'function' ? optsOrCallback : callback;
this.request<google.pubsub.v1.IDetachSubscriptionRequest>(
{
client: 'PublisherClient',
method: 'detachSubscription',
reqOpts,
gaxOpts: gaxOpts as CallOptions,
},
callback!
);
}
/**
* Determine the appropriate endpoint to use for API requests, first trying
* the `apiEndpoint` parameter. If that isn't set, we try the Pub/Sub emulator
* environment variable (PUBSUB_EMULATOR_HOST). If that is also null, we try
* the standard `gcloud alpha pubsub` environment variable
* (CLOUDSDK_API_ENDPOINT_OVERRIDES_PUBSUB). Otherwise the default production
* API is used.
*
* Note that if the URL doesn't end in '.googleapis.com', we will assume that
* it's an emulator and disable strict SSL checks.
*
* @private
*/
determineBaseUrl_() {
// We allow an override from the client object options, or from
// one of these variables. The CLOUDSDK variable is provided for
// compatibility with the `gcloud alpha` utility.
const gcloudVarName = 'CLOUDSDK_API_ENDPOINT_OVERRIDES_PUBSUB';
const emulatorVarName = 'PUBSUB_EMULATOR_HOST';
const apiEndpoint =
this.options.apiEndpoint ||
process.env[emulatorVarName] ||
process.env[gcloudVarName];
if (!apiEndpoint) {
return;
}
// Parse the URL into a hostname and port, if possible.
const leadingProtocol = new RegExp('^https?://');
const trailingSlashes = new RegExp('/*$');
const baseUrlParts = apiEndpoint!
.replace(leadingProtocol, '')
.replace(trailingSlashes, '')
.split(':');
this.options.servicePath = baseUrlParts[0];
if (!baseUrlParts[1]) {
// No port was given -- figure it out from the protocol.
if (apiEndpoint!.startsWith('https')) {
this.options.port = 443;
} else if (apiEndpoint!.startsWith('http')) {
this.options.port = 80;
} else {
this.options.port = undefined;
}
} else {
this.options.port = parseInt(baseUrlParts[1], 10);
}
// If this looks like a GCP URL of some kind, don't go into emulator
// mode. Otherwise, supply a fake SSL provider so a real cert isn't
// required for running the emulator.
const officialUrlMatch =
this.options.servicePath!.endsWith('.googleapis.com');
if (!officialUrlMatch) {
const grpcInstance = this.options.grpc || gax.grpc;
this.options.sslCreds = grpcInstance.credentials.createInsecure();
this.isEmulator = true;
}
if (!this.options.projectId && process.env.PUBSUB_PROJECT_ID) {
this.options.projectId = process.env.PUBSUB_PROJECT_ID;
}
}
/**
* Get a list of schemas associated with your project.
*
* The returned AsyncIterable will resolve to {@link google.pubsub.v1.ISchema} objects.
*
* This method returns an async iterable. These objects can be adapted
* to work in a Promise/then framework, as well as with callbacks, but
* this discussion is considered out of scope for these docs.
*
* @see [Schemas: list API Documentation]{@link https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.schemas/list}
* @see [More about async iterators]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of}
*
* @param {google.pubsub.v1.SchemaView} [view] The type of schema objects
* requested, which should be an enum value from {@link SchemaViews}. Defaults
* to Full.
* @param {object} [options] Request configuration options, outlined
* here: https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html.
* @returns {AsyncIterable<ISchema>}
*
* @example
* ```
* for await (const s of pubsub.listSchemas()) {
* const moreInfo = await s.get();
* }
* ```
*/
async *listSchemas(
view: SchemaView = SchemaViews.Basic,
options?: CallOptions
): AsyncIterable<google.pubsub.v1.ISchema> {
const client = await this.getSchemaClient_();
const query = {
parent: this.name,
view,
};
for await (const s of client.listSchemasAsync(query, options)) {
yield s;
}
}
/**
* Query object for listing snapshots.
*
* @typedef {object} GetSnapshotsRequest
* @property {boolean} [autoPaginate=true] Have pagination handled
* automatically.
* @property {object} [options.gaxOpts] Request configuration options, outlined
* here: https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html.
* @property {number} [options.pageSize] Maximum number of results to return.
* @property {string} [options.pageToken] Page token.
*/
/**
* @typedef {array} GetSnapshotsResponse
* @property {Snapshot[]} 0 Array of {@link Snapshot} instances.
* @property {object} 1 The full API response.
*/
/**
* @callback GetSnapshotsCallback
* @param {?Error} err Request error, if any.
* @param {Snapshot[]} snapshots Array of {@link Snapshot} instances.
* @param {object} apiResponse The full API response.
*/
/**
* Get a list of snapshots.
*
* @param {GetSnapshotsRequest} [query] Query object for listing snapshots.
* @param {GetSnapshotsCallback} [callback] Callback function.
* @returns {Promise<GetSnapshotsResponse>}
*
* @example
* ```
* const {PubSub} = require('@google-cloud/pubsub');
* const pubsub = new PubSub();
*
* pubsub.getSnapshots(function(err, snapshots) {
* if (!err) {
* // snapshots is an array of Snapshot objects.
* }
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* pubsub.getSnapshots().then(function(data) {
* const snapshots = data[0];
* });
* ```
*/
getSnapshots(options?: PageOptions): Promise<GetSnapshotsResponse>;
getSnapshots(callback: GetSnapshotsCallback): void;
getSnapshots(options: PageOptions, callback: GetSnapshotsCallback): void;
getSnapshots(
optsOrCallback?: PageOptions | GetSnapshotsCallback,
callback?: GetSnapshotsCallback
): void | Promise<GetSnapshotsResponse> {
const options = typeof optsOrCallback === 'object' ? optsOrCallback : {};
callback = typeof optsOrCallback === 'function' ? optsOrCallback : callback;
const reqOpts = Object.assign(
{
project: PubSub.formatName_(this.projectId),
},
options
);
delete reqOpts.gaxOpts;
delete reqOpts.autoPaginate;
const gaxOpts = Object.assign(
{
autoPaginate: options.autoPaginate,
},
options.gaxOpts
);
this.request<
google.pubsub.v1.ISnapshot,
google.pubsub.v1.IListSnapshotsResponse
>(
{
client: 'SubscriberClient',
method: 'listSnapshots',
reqOpts,
gaxOpts,
},
(err, rawSnapshots, ...args) => {
let snapshots: Snapshot[];
if (rawSnapshots) {
snapshots = rawSnapshots.map(
(snapshot: google.pubsub.v1.ISnapshot) => {
const snapshotInstance = this.snapshot(snapshot.name!);
snapshotInstance.metadata = snapshot;
return snapshotInstance;
}
);
}
callback!(err, snapshots!, ...args);
}
);
}
/**
* Query object for listing subscriptions.
*
* @typedef {object} GetSubscriptionsRequest
* @property {boolean} [autoPaginate=true] Have pagination handled
* automatically.
* @property {object} [options.gaxOpts] Request configuration options, outlined
* here: https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html.
* @property {number} [options.pageSize] Maximum number of results to return.
* @property {string} [options.pageToken] Page token.
* @param {string|Topic} options.topic - The name of the topic to
* list subscriptions from.
*/
/**
* @typedef {array} GetSubscriptionsResponse
* @property {Subscription[]} 0 Array of {@link Subscription} instances.
* @property {object} 1 The full API response.
*/
/**
* @callback GetSubscriptionsCallback
* @param {?Error} err Request error, if any.
* @param {Subscription[]} subscriptions Array of {@link Subscription} instances.
* @param {object} apiResponse The full API response.
*/
/**
* Get a list of the subscriptions registered to all of your project's topics.
* You may optionally provide a query object as the first argument to
* customize the response.
*
* Your provided callback will be invoked with an error object if an API error
* occurred or an array of {@link Subscription} objects.
*
* To get subscriptions for a topic, see {@link Topic}.
*
* @see [Subscriptions: list API Documentation]{@link https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.subscriptions/list}
*
* @param {GetSubscriptionsRequest} [query] Query object for listing subscriptions.
* @param {GetSubscriptionsCallback} [callback] Callback function.
* @returns {Promise<GetSubscriptionsResponse>}
*
* @example
* ```
* const {PubSub} = require('@google-cloud/pubsub');
* const pubsub = new PubSub();
*
* pubsub.getSubscriptions(function(err, subscriptions) {
* if (!err) {
* // subscriptions is an array of Subscription objects.
* }
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* pubsub.getSubscriptions().then(function(data) {
* const subscriptions = data[0];
* });
* ```
*/
getSubscriptions(
options?: GetSubscriptionsOptions
): Promise<GetSubscriptionsResponse>;