-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathGooglePubSub.agent.lib.nut
1891 lines (1752 loc) · 87.6 KB
/
GooglePubSub.agent.lib.nut
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
// MIT License
//
// Copyright 2017-2020 Electric Imp
//
// SPDX-License-Identifier: MIT
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
// EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
// OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// GooglePubSub library provides an integration with Google Cloud Pub/Sub service using
// Google Cloud Pub/Sub REST API.
//
// Google Cloud Pub/Sub is a publish/subscribe (Pub/Sub) service:
// a messaging service where the senders of messages are decoupled from the receivers
// of messages. There are several key concepts in a Pub/Sub service:
// - Message: the data that moves through the service.
// - Topic: a named resource that represents a feed of messages.
// - Subscription: a named resource that represents an interest in receiving messages
// on a particular topic.
// - Publisher: creates messages and sends (publishes) them to the messaging service
// on a specified topic.
// - Subscriber: receives messages on a specified subscription.
// Communication between publishers and subscribers can be one-to-many, many-to-one,
// and many-to-many.
//
// Pub/Sub Message flow steps:
// 1. A publisher application creates a topic in the Google Cloud Pub/Sub service and
// sends messages to the topic. A message contains a payload and optional attributes
// that describe the payload content.
// 2. Messages are persisted in a Google Pub/Sub message store until they are delivered
// and acknowledged by subscribers.
// 3. The Pub/Sub service forwards messages from a topic to all of its subscriptions,
// individually.
// Each subscription receives messages either by Pub/Sub pushing them to the subscriber's
// chosen endpoint, or by the subscriber pulling them from the service.
// 4. The subscriber receives pending messages from its subscription and acknowledges each
// one to the Pub/Sub service.
// 5. When a message is acknowledged by the subscriber, it is removed from the subscription's
// queue of messages.
//
// For more information see Google Cloud Pub/Sub Documentation
// https://cloud.google.com/pubsub/docs/overview
//
// Before using this library you need to:
// - register Google Cloud Platform account
// - create and configure Google Cloud Project
//
// Google Cloud Project is a basic entity of Google Cloud Platform which allows to create,
// configure and use all Cloud Platform resources and services, including Pub/Sub.
// All Pub/Sub Topics and Subscriptions are owned by a specific Project.
// To manage Pub/Sub resources associated with different Projects, you may use
// different instances of the classes from this library.
//
// For more information about Google Cloud Project see
// https://cloud.google.com/resource-manager/docs/creating-managing-projects
//
// The library consists of five independent parts (classes):
//
// - GooglePubSub.Topics - provides access to Pub/Sub Topics manipulation methods.
// One instance of this class is enough to manage all topics of one Project.
//
// - GooglePubSub.Subscriptions - provides access to Pub/Sub Subscriptions manipulation methods.
// One instance of this class is enough to manage all subscriptions of one Project.
//
// - GooglePubSub.Publisher - allows to publish messages to a topic.
// One instance of this class allows to publish messages to one topic.
//
// - GooglePubSub.PullSubscriber - allows to receive messages from a pull subscription.
// One instance of this class allows to receive messages from one pull subscription.
//
// - GooglePubSub.PushSubscriber - allows to receive messages from a push subscription
// configured with imp Agent related URL as push endpoint.
// One instance of this class allows to receive messages from one push subscription.
//
// You can instantiate and use any parts of the library in your imp agent code depending on your
// application requirements.
//
// To instantiate every part (class) of this library you need to have:
//
// - Google Cloud Platform Project ID
//
// - Provider of access tokens suitable for Google Pub/Sub service requests authentication.
// For more information about Google Pub/Sub service authentication see
// https://cloud.google.com/docs/authentication
//
// The library requires acquireAccessToken(tokenReadyCallback) method of the provider, where
// tokenReadyCallback is a handler to be called when access token is acquired or an error occurs.
// It has the following signature:
// tokenReadyCallback(token, error), where
// token : string String representation of access token.
// error : string String with error details, null in case of success.
//
// Token provider can be an instance of OAuth2.JWTProfile.Client OAuth2 library
// (see https://github.com/electricimp/OAuth-2.0)
// or any other access token provider with a similar interface.
//
// Also, the library includes several additional auxiliary classes.
//
// All requests to Google Cloud Pub/Sub service are made asynchronously.
// Any method that sends a request has an optional callback parameter.
// If the callback is provided, it is executed when the operation is completed
// (e.g. a response is received), successfully or not.
// Details of every callback are described in the corresponding methods.
// GooglePubSub library operation error types
enum PUB_SUB_ERROR {
// the library detects an error, e.g. the library is wrongly initialized or
// a method is called with invalid argument(s). The error details can be
// found in the error.details value
LIBRARY_ERROR,
// HTTP request to Google Pub/Sub service failed. The error details can be found in
// the error.httpStatus and error.httpResponse properties
PUB_SUB_REQUEST_FAILED,
// Unexpected response from Google Pub/Sub service. The error details can be found in
// the error.details and error.httpResponse properties
PUB_SUB_UNEXPECTED_RESPONSE
};
// Error details produced by the library
const GOOGLE_PUB_SUB_TOKEN_ACQUISITION_ERROR = "Access token acquisition error";
const GOOGLE_PUB_SUB_REQUEST_FAILED = "Google Pub/Sub request failed with status code";
const GOOGLE_PUB_SUB_NON_EMPTY_ARG = "Non empty argument required";
const GOOGLE_PUB_SUB_POSITIVE_ARG = "Positive argument required";
const GOOGLE_PUB_SUB_WRONG_ARG_TYPE = "Invalid type of argument, required";
const GOOGLE_PUB_SUB_PULL_IN_PROGRESS = "Different pull is active";
const GOOGLE_PUB_SUB_PUSH_SUBSCR_REQUIRED = "Push subscription required";
const GOOGLE_PUB_SUB_INTERNAL_PUSH_REQUIRED = "Push endpoint based on imp Agent URL required";
const GOOGLE_PUB_SUB_OPTION_REQUIRED = "option must be specified";
const GOOGLE_PUB_SUB_INVALID_FORMAT = "Invalid format of";
class GooglePubSub {
static VERSION = "1.1.1";
// Enables/disables the library debug output (including errors logging).
// Disabled by default.
//
// Parameters:
// value : boolean true to enable, false to disable
function setDebug(value) {
_utils._debug = value;
}
// Internal utility methods used by different parts of the library
static _utils = {
_debug = false,
// Logs an error occurred during the library methods execution
function _logError(errMessage) {
if (_debug) {
server.error("[GooglePubSub] " + errMessage);
}
}
// Logs an debug messages occurred during the library methods execution
function _logDebug(message) {
if (_debug) {
server.log("[GooglePubSub] " + message);
}
}
// Converts a value to an array
function _arrify(value) {
if (typeof value == "array") {
return value;
}
else if (value == null) {
return [];
}
else {
return array(1, value);
}
}
// Returns value of specified table key, if exists or defaultValue
function _getTableValue(table, key, defaultValue) {
return (table && key in table) ? table[key] : defaultValue;
}
// Checks if value is empty (null, empty string, empty table or empty array)
function _isEmpty(value) {
if (value == null || typeof value == "string" && value.len() == 0 ||
typeof value == "table" && value.len() == 0 ||
typeof value == "array" && value.len() == 0) {
return true;
}
return false;
}
// Validates the argument is not empty. Returns PUB_SUB_ERROR.LIBRARY_ERROR if the check failed.
function _validateNonEmptyArg(param, paramName, logError = true) {
if (_isEmpty(param)) {
return GooglePubSub.Error(
PUB_SUB_ERROR.LIBRARY_ERROR,
format("%s: %s", GOOGLE_PUB_SUB_NON_EMPTY_ARG, paramName),
null, null, logError);
}
return null;
}
// Validates the argument is positive and belongs to the specified type.
// Returns PUB_SUB_ERROR.LIBRARY_ERROR if the check failed.
function _validatePositiveArg(param, paramName, type = "integer") {
if (type && typeof param != type) {
return GooglePubSub.Error(
PUB_SUB_ERROR.LIBRARY_ERROR,
format("%s %s: %s", GOOGLE_PUB_SUB_WRONG_ARG_TYPE, type, paramName));
}
if (param <= 0) {
return GooglePubSub.Error(
PUB_SUB_ERROR.LIBRARY_ERROR,
format("%s: %s", GOOGLE_PUB_SUB_POSITIVE_ARG, paramName));
}
return null;
}
// Invokes default callback with single error parameter.
function _invokeDefaultCallback(error, callback) {
if (callback) {
imp.wakeup(0, function () {
callback(error);
});
}
}
};
}
// Auxiliary class, represents error returned by the library.
class GooglePubSub.Error {
// error type, one of the PUB_SUB_ERROR enum values
type = null;
// error details (string)
details = null;
// HTTP status code (integer),
// null if type is PUB_SUB_ERROR.LIBRARY_ERROR
httpStatus = null;
// Response body of failed request (table),
// null if type is PUB_SUB_ERROR.LIBRARY_ERROR
httpResponse = null;
constructor(type, details, httpResponse = null, httpStatus = null, logError = true) {
this.type = type;
this.details = details;
this.httpStatus = httpStatus;
this.httpResponse = httpResponse;
if (logError) {
GooglePubSub._utils._logError(details);
}
}
}
// Internal GooglePubSub library constants
const _GOOGLE_PUB_SUB_BASE_URL = "https://pubsub.googleapis.com/v1";
const _GOOGLE_PUB_SUB_TOPICS_TYPE = "topics";
const _GOOGLE_PUB_SUB_SUBSCRIPTIONS_TYPE = "subscriptions";
const _GOOGLE_PUB_SUB_LIST_PAGE_SIZE_DEFAULT = 20;
const _GOOGLE_PUB_SUB_PULL_MAX_MESSAGES_DEFAULT = 20;
const _GOOGLE_PUB_SUB_ACK_DEADLINE_SECONDS_DEFAULT = 10;
// This class provides access to Pub/Sub Topics manipulation methods.
// It can be used to check existence, create, delete topics of the specified Project
// and obtain a list of the topics registered to the Project.
class GooglePubSub.Topics {
_projectId = null;
_oAuthTokenProvider = null;
_topic = null;
_iam = null;
// GooglePubSub.Topics constructor.
//
// Parameters:
// projectId : string Google Cloud Project ID.
// oAuthTokenProvider Provider of access tokens suitable for Google Pub/Sub service requests
// authentication.
//
// Returns: GooglePubSub.Topics instance created
constructor(projectId, oAuthTokenProvider) {
_projectId = projectId;
_oAuthTokenProvider = oAuthTokenProvider;
_topic = GooglePubSub._Resource(projectId, oAuthTokenProvider, _GOOGLE_PUB_SUB_TOPICS_TYPE);
_iam = GooglePubSub.IAM(_topic);
}
// Checks if the specified topic exists and optionally creates it if not.
// If the topic does not exist and autoCreate option is true, the topic is created.
// If the topic does not exist and autoCreate option is false, the method fails with
// PUB_SUB_ERROR.PUB_SUB_REQUEST_FAILED error (with httpStatus 404).
//
// Parameters:
// topicName : string Name of the topic.
// options : table Optional Key/Value settings.
// (optional) The valid keys are:
// autoCreate : boolean Create the topic if it
// does not exist.
// Default: false
// callback : function Optional callback function to be executed once the topic is
// (optional) checked or created.
// The callback signature:
// callback(error), where
// error : Error details,
// GooglePubSub.Error null if the operation succeeds.
//
// Returns: Nothing
function obtain(topicName, options = null, callback = null) {
_topic.setName(topicName);
_topic.obtain(
options,
null,
function (error, httpResponse) {
GooglePubSub._utils._invokeDefaultCallback(error, callback);
}.bindenv(this));
}
// Deletes the specified topic, if it exists.
// Otherwise - fails with PUB_SUB_ERROR.PUB_SUB_REQUEST_FAILED error (with httpStatus 404).
//
// Existing subscriptions to the deleted topic are not destroyed.
//
// After the topic is deleted, a new topic may be created with the same name;
// this is an entirely new topic with none of the old configuration or subscriptions.
//
// Parameters:
// topicName : string Name of the topic.
// callback : function Optional callback function to be executed once the topic is deleted.
// (optional) The callback signature:
// callback(error), where
// error : Error details,
// GooglePubSub.Error null if the operation succeeds.
//
// Returns: Nothing
function remove(topicName, callback = null) {
_topic.setName(topicName);
_topic.remove(function (error, httpResponse) {
GooglePubSub._utils._invokeDefaultCallback(error, callback);
}.bindenv(this));
}
// Gets a list of the topics (names of all topics) registered to the project.
//
// Parameters:
// options : table Optional Key/Value settings.
// (optional) The valid keys are:
// paginate : boolean If true, the method returns limited
// number of topics (up to pageSize)
// and pageToken which allows to obtain next
// page of data.
// If false, the method returns the entire
// list of topics.
// Default: false
// pageSize : integer Maximum number of topics to return.
// If paginate option value is false,
// the value is ignored.
// Default: 20
// pageToken : string Page token returned by the previous
// paginated GooglePubSub.Topics.list() call;
// indicates that the system should return
// the next page of data.
// If paginate option value is false,
// the value is ignored.
// callback : function Optional callback function to be executed once the topics are obtained.
// (optional) The callback signature:
// callback(error, topicNames, nextOptions = null), where
// error : Error details,
// GooglePubSub.Error null if the operation succeeds.
// topicNames : Names of topics obtained.
// array of string
// nextOptions : table Options table that can be used for subsequent
// paginated GooglePubSub.Topics.list() call.
// Contains pageToken returned by the current
// GooglePubSub.Topics.list() call.
// Has null value if:
// - no more results are available,
// - paginate option value is false,
// - the current list() operation failed.
//
// Returns: Nothing
function list(options = null, callback = null) {
_topic.list(options, callback);
}
// Provides Identity and Access Management (IAM) functionality for topics.
// (see GooglePubSub.IAM class description for details)
//
// Returns: An instance of IAM class that can be used for execution of
// IAM methods for a specific topic.
function iam() {
return _iam;
}
}
// This class provides access to Pub/Sub Subscriptions manipulation methods.
// It can be used to check existence, create, configure, delete subscriptions of the specified Project
// and obtain a list of the subscriptions registered to the Project or related to a topic.
//
// Information about Google Pub/Sub subscriptions see here:
// https://cloud.google.com/pubsub/docs/subscriber
//
// A subscription configuration is encapsulated in GooglePubSub.SubscriptionConfig class.
// The library allows to manipulate with the both - pull and push - types of subscription.
// Additional configuration parameters for a push subscription are encapsulated in
// GooglePubSub.PushConfig class.
//
// The library provides GooglePubSub.PullSubscriber class to receive messages from a pull subscription.
//
// A push subscription configuration has a pushEndpoint parameter -
// URL to a custom endpoint that messages should be pushed to.
// In a general case it may be any URL and receiving of the push subscription messages
// is out of the library's scope.
// But it is possible to specify a push endpoint URL which is based on imp Agent URL.
// Auxiliary GooglePubSub.Subscriptions.getImpAgentEndpoint() method may be used to generate such an URL.
// In this case GooglePubSub.PushSubscriber class can be utilized to receive messages from the push subscription.
//
class GooglePubSub.Subscriptions {
_projectId = null;
_oAuthTokenProvider = null;
_subscr = null;
_iam = null;
// GooglePubSub.Subscriptions constructor.
//
// Parameters:
// projectId : string Google Cloud Project ID.
// oAuthTokenProvider Provider of access tokens suitable for Google Pub/Sub service requests
// authentication.
//
// Returns: GooglePubSub.Subscriptions instance created
constructor(projectId, oAuthTokenProvider) {
_projectId = projectId;
_oAuthTokenProvider = oAuthTokenProvider;
_subscr = GooglePubSub._Resource(projectId, oAuthTokenProvider, _GOOGLE_PUB_SUB_SUBSCRIPTIONS_TYPE);
_iam = GooglePubSub.IAM(_subscr);
}
// Obtains (get or create) the specified subscription.
// If subscription with the specified name exists, the method retrieves it's configuration.
// If it does not exist and optional autoCreate option is true, the subscription is created.
// In this case subscrConfig option must be specified.
// If the subscription does not exist and autoCreate option is false, the method fails with
// PUB_SUB_ERROR.PUB_SUB_REQUEST_FAILED error (with httpStatus 404).
//
// Parameters:
// subscrName : string Name of the subscription.
// options : table Optional Key/Value settings.
// (optional) The valid keys are:
// autoCreate : boolean Create the subscription
// if it does not exist.
// Default: false
// subscrConfig : Configuration of subscription
// GooglePubSub.SubscriptionConfig to be created.
// (optional) subscrConfig must be specified
// if autoCreate option is true,
// otherwise it is ignored.
// callback : function Optional callback function to be executed once the subscription is obtained.
// (optional) The callback signature:
// callback(error, subscrConfig), where
// error : Error details,
// GooglePubSub.Error null if the operation succeeds.
// subscrConfig : Configuration of the subscription
// GooglePubSub.SubscriptionConfig obtained.
//
// Returns: Nothing
function obtain(subscrName, options = null, callback = null) {
local autoCreate = GooglePubSub._utils._getTableValue(options, "autoCreate", false);
local subscrConfig = GooglePubSub._utils._getTableValue(options, "subscrConfig", null);
if (autoCreate && !subscrConfig) {
_invokeObtainCallback(
GooglePubSub.Error(PUB_SUB_ERROR.LIBRARY_ERROR, format("%s %s", "subscrConfig", GOOGLE_PUB_SUB_OPTION_REQUIRED)),
null, callback);
return;
}
if (subscrConfig) {
local configError = subscrConfig._getError();
if (configError) {
_invokeObtainCallback(configError, null, callback);
return;
}
}
_subscr.setName(subscrName);
_subscr.obtain(
options,
subscrConfig ? subscrConfig._toJson(_projectId) : null,
function (error, httpResponse) {
local subscrCfg = null;
if (!error) {
subscrCfg = GooglePubSub.SubscriptionConfig(null);
subscrCfg._fromJson(httpResponse, _projectId);
}
_invokeObtainCallback(error, subscrCfg, callback);
}.bindenv(this));
}
// Modifies push delivery endpoint configuration for the specified subscription.
// The method may be used to change a push subscription to a pull one or vice versa,
// or change the endpoint URL and other attributes of a push subscription.
//
// To modify a push subscription to a pull one, pass null or empty table as a pushConfig parameter
// value.
//
// Parameters:
// subscrName : string Name of the subscription.
// pushConfig : The push configuration for future deliveries.
// GooglePubSub.PushConfig An empty pushConfig indicates that the Pub/Sub service should stop
// pushing messages from the given subscription and allow messages
// to be pulled and acknowledged.
// callback : function Optional callback function to be executed once the Push Config is modified.
// (optional) The callback signature:
// callback(error), where
// error : Error details,
// GooglePubSub.Error null if the operation succeeds.
//
// Returns: Nothing
function modifyPushConfig(subscrName, pushConfig, callback = null) {
_subscr.setName(subscrName);
if (pushConfig) {
local configError = pushConfig._getError();
if (configError) {
GooglePubSub._utils._invokeDefaultCallback(configError, callback);
return;
}
}
_subscr.request(
"POST",
":modifyPushConfig",
pushConfig ? { "pushConfig" : pushConfig._toJson() } : {},
function (error, httpResponse) {
GooglePubSub._utils._invokeDefaultCallback(error, callback);
}.bindenv(this));
}
// Deletes the specified subscription, if it exists.
// Otherwise - fails with PUB_SUB_ERROR.PUB_SUB_REQUEST_FAILED error (with httpStatus 404).
//
// All messages retained in the subscription are immediately dropped
// and cannot be delivered neither by pull, nor by push ways.
//
// After the subscription is deleted, a new one may be created with the same name, but the new one has no
// association with the old subscription or its topic unless the same topic is specified.
//
// Parameters:
// subscrName : string Name of the subscription.
// callback : function Optional callback function to be executed once the subscription is deleted.
// (optional) The callback signature:
// callback(error), where
// error : Error details,
// GooglePubSub.Error null if the operation succeeds.
//
// Returns: Nothing
function remove(subscrName, callback = null) {
_subscr.setName(subscrName);
_subscr.remove(function (error, httpResponse) {
GooglePubSub._utils._invokeDefaultCallback(error, callback);
}.bindenv(this));
}
// Gets a list of the subscriptions (names of all subscriptions) registered to the project
// or related to the specified topic.
//
// Parameters:
// options : table Optional Key/Value settings.
// (optional) The valid keys are:
// topicName : string Name of the topic to list subscriptions from.
// paginate : boolean If true, the method returns limited
// number of subscriptions (up to pageSize)
// and pageToken which allows to obtain next
// page of data.
// If false, the method returns the entire
// list of subscriptions.
// Default: false
// pageSize : integer Maximum number of subscriptions to return.
// If paginate option value is false,
// the value is ignored.
// Default: 20
// pageToken : string Page token returned by the previous paginated
// GooglePubSub.Subscriptions.list() call;
// indicates that the system should return
// the next page of data.
// If paginate option value is false,
// the value is ignored.
// callback : function Optional callback function to be executed once the subscriptions are obtained.
// (optional) The callback signature:
// callback(error, subscrNames, nextOptions = null), where
// error : Error details,
// GooglePubSub.Error null if the operation succeeds.
// subscrNames : Names of subscriptions obtained.
// array of string
// nextOptions : table Options table that can be used for subsequent
// paginated GooglePubSub.Subscriptions.list() call.
// Contains pageToken returned by the current
// GooglePubSub.Subscriptions.list() call.
// Has null value if:
// - no more results are available,
// - paginate option value is false,
// - the current list() operation failed.
//
// Returns: Nothing
function list(options = null, callback = null) {
local topicName = GooglePubSub._utils._getTableValue(options, "topicName", null);
if (topicName) {
local topic = GooglePubSub._Resource(_projectId, _oAuthTokenProvider, _GOOGLE_PUB_SUB_TOPICS_TYPE);
topic.setName(topicName);
_subscr._list(topic.getResourceUrl(), options, true, callback);
}
else {
_subscr.list(options, callback);
}
}
// Provides Identity and Access Management (IAM) functionality for subscriptions.
// (see GooglePubSub.IAM class description for details)
//
// Returns: An instance of IAM class that can be used for execution of
// IAM methods for a specific subscription.
function iam() {
return _iam;
}
// Auxiliary method to compose a endpoint URL based on imp Agent URL.
// The result URL can be used to create a push subscription and receive
// messages from this subscription using GooglePubSub.PushSubscriber class.
//
// Parameters:
// relativePath : Optional relative path from imp Agent URL.
// string If specified, <imp Agent URL>/<relativePath>
// (optional) is returned.
// If not specified or empty, <imp Agent URL> is
// returned.
// secretToken : Optional secret token specified by a user.
// string It allows to verify that the messages
// (optional) pushed to the push endpoint are originated
// from Google Cloud Pub/Sub.
// For more information see
// https://cloud.google.com/pubsub/docs/faq#security
//
// Returns: URL based on imp Agent URL
function getImpAgentEndpoint(relativePath = null, secretToken = null) {
local endpoint = http.agenturl();
if (relativePath) {
endpoint = format("%s/%s", endpoint, relativePath);
}
if (endpoint.slice(endpoint.len() - 1) != "/") {
endpoint = endpoint + "/";
}
if (secretToken) {
endpoint = format("%s?token=%s", endpoint, secretToken);
}
return endpoint;
}
// -------------------- PRIVATE METHODS -------------------- //
function _invokeObtainCallback(error, subscrConfig, callback) {
if (callback) {
imp.wakeup(0, function () {
callback(error, subscrConfig);
});
}
}
}
// Auxiliary class, represents configuration of a subscription.
class GooglePubSub.SubscriptionConfig {
// Name of the topic from which this subscription receives messages.
topicName = null;
// The maximum time (in seconds) after receiving a message when the message must be acknowledged
// before it is redelivered by Pub/Sub service.
ackDeadlineSeconds = null;
// Push subscription configuration (GooglePubSub.PushConfig). Null for pull subscriptions.
pushConfig = null;
// SubscriptionConfig constructor that can be used for creating subscription using
// GooglePubSub.Subscriptions.obtain() method.
//
// Parameters:
// topicName : string Name of the topic associated with the subscription.
// ackDeadlineSeconds : The maximum time (in seconds) after receiving
// integer a message when the message must be acknowledged
// (optional) before it is redelivered by Pub/Sub service.
// Default : 10
// pushConfig : Configuration for a push delivery endpoint.
// GooglePubSub.PushConfig Null for pull subscriptions.
// (optional)
//
// Returns: GooglePubSub.SubscriptionConfig instance created.
constructor(topicName, ackDeadlineSeconds = _GOOGLE_PUB_SUB_ACK_DEADLINE_SECONDS_DEFAULT, pushConfig = null) {
this.topicName = topicName;
this.ackDeadlineSeconds = ackDeadlineSeconds;
this.pushConfig = pushConfig;
}
// -------------------- PRIVATE METHODS -------------------- //
function _toJson(projectId) {
local topic = GooglePubSub._Resource(projectId, null, _GOOGLE_PUB_SUB_TOPICS_TYPE);
topic.setName(topicName);
local result = {
"topic" : topic.getResourceName(),
"ackDeadlineSeconds" : ackDeadlineSeconds
};
if (pushConfig) {
result["pushConfig"] <- pushConfig._toJson();
}
return result;
}
function _fromJson(jsonSubscrConfig, projectId) {
topicName = null;
ackDeadlineSeconds = null;
pushConfig = null;
local topic = GooglePubSub._utils._getTableValue(jsonSubscrConfig, "topic", null);
if (topic) {
topicName = GooglePubSub._Resource(projectId, null, _GOOGLE_PUB_SUB_TOPICS_TYPE).getName(topic);
}
ackDeadlineSeconds = GooglePubSub._utils._getTableValue(
jsonSubscrConfig, "ackDeadlineSeconds", _GOOGLE_PUB_SUB_ACK_DEADLINE_SECONDS_DEFAULT);
local pushCfg = GooglePubSub._utils._getTableValue(jsonSubscrConfig, "pushConfig", null);
if (!GooglePubSub._utils._isEmpty(pushCfg)) {
pushConfig = GooglePubSub.PushConfig(null);
pushConfig._fromJson(pushCfg);
}
}
function _getError() {
return GooglePubSub._utils._validateNonEmptyArg(topicName, "topicName") ||
GooglePubSub._utils._validatePositiveArg(ackDeadlineSeconds, "ackDeadlineSeconds") ||
(pushConfig ? pushConfig._getError() : null);
}
}
// Auxiliary class, represents additional configuration of a push subscription.
class GooglePubSub.PushConfig {
// A URL to a custom endpoint that messages should be pushed to.
pushEndpoint = null;
// Push endpoint attributes: key-value table of string attributes.
// For more information about Push Config valid attributes, see
// https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.subscriptions#PushConfig
attributes = null;
// PushConfig constructor that can be used for creating push subscription.
//
// Parameters:
// pushEndpoint : string Push endpoint URL.
// attributes : table Optional push endpoint attributes.
// (optional)
//
// Returns: GooglePubSub.PushConfig instance created.
constructor(pushEndpoint, attributes = null) {
this.pushEndpoint = pushEndpoint;
this.attributes = attributes;
}
// -------------------- PRIVATE METHODS -------------------- //
function _toJson() {
local result = {
"pushEndpoint" : pushEndpoint
};
if (attributes) {
result["attributes"] <- attributes;
}
return result;
}
function _fromJson(jsonPushConfig) {
pushEndpoint = GooglePubSub._utils._getTableValue(jsonPushConfig, "pushEndpoint", null);
attributes = GooglePubSub._utils._getTableValue(jsonPushConfig, "attributes", null);
}
function _getError() {
return GooglePubSub._utils._validateNonEmptyArg(pushEndpoint, "pushEndpoint");
}
}
// Auxiliary class, provides Identity and Access Management (IAM) functionality for individual Pub/Sub
// resources (topics and subscriptions).
// IAM allows you to manage access control by defining who (members) has what access (role) for which
// resource.
// For example:
// - Grant access to any operation with particular topic or subscription to a specific user or group of users.
// - Grant access with limited capabilities, such as to only publish messages to a topic, or to only
// consume messages from a subscription, but not to delete the topic or subscription.
//
// It is assumed that this class is not instantiated by a user directly,
// but GooglePubSub.Topics.iam() and GooglePubSub.Subscriptions.iam() functions are used to get the instances
// and execute IAM methods for topics and subscriptions respectively.
//
// IAM policy representation is encapsulated in GooglePubSub.IAM.Policy class.
//
// For a detailed description of IAM and its features, see the Google Cloud Identity and Access
// Management Documentation: https://cloud.google.com/iam/docs/overview
//
class GooglePubSub.IAM {
_resource = null;
constructor(resource) {
_resource = resource;
}
// Gets the access control policy for a resource.
// Returns an empty policy if the resource exists and does not have a policy set.
//
// Parameters:
// resourceName : string Name of the topic or subscription.
// callback : function Optional callback function to be executed once the policy is obtained.
// (optional) The callback signature:
// callback(error, policy), where
// error : Error details,
// GooglePubSub.Error null if the operation succeeds.
// policy : IAM policy obtained for the resource.
// GooglePubSub.IAM.Policy
//
// Returns: Nothing
function getPolicy(resourceName, callback = null) {
_resource.setName(resourceName);
_resource.getIamPolicy(function (error, httpResponse) {
_invokePolicyCallback(error, httpResponse, callback);
}.bindenv(this));
}
// Sets the access control policy on the specified resource. Replaces any existing policy.
//
// Parameters:
// resourceName : string Name of the topic or subscription.
// policy : The policy to be set.
// GooglePubSub.IAM.Policy
// callback : function Optional callback function to be executed once the policy is set.
// (optional) The callback signature:
// callback(error, policy), where
// error : Error details,
// GooglePubSub.Error null if the operation succeeds.
// policy : IAM policy was set.
// GooglePubSub.IAM.Policy
//
// Returns: Nothing
function setPolicy(resourceName, policy, callback = null) {
local policyError = GooglePubSub._utils._validateNonEmptyArg(policy, "policy");
if (policyError) {
_invokePolicyCallback(policyError, null, callback);
return;
}
_resource.setName(resourceName);
_resource.setIamPolicy(policy, function (error, httpResponse) {
_invokePolicyCallback(error, httpResponse, callback);
}.bindenv(this));
}
// Tests a set of permissions for a resource.
// If the resource does not exist, this method will return an empty set of permissions,
// not a PUB_SUB_ERROR.PUB_SUB_REQUEST_FAILED error.
//
// Permissions with wildcards such as * or pubsub.topics.* are not allowed.
//
// For a list of the permissions available, see Google Cloud Pub/Sub Access Control documentation:
// https://cloud.google.com/pubsub/docs/access_control
//
// Parameters:
// resourceName : string Name of the topic or subscription.
// permissions : string or The permission(s) to test for a resource.
// array of strings
// callback : function Optional callback function to be executed once the permissions are tested.
// (optional) The callback signature:
// callback(error, permissions), where
// error : Error details,
// GooglePubSub.Error null if the operation succeeds.
// permissions : A subset of permissions that is allowed
// array of strings for the resource.
//
// Returns: Nothing
function testPermissions(resourceName, permissions, callback = null) {
local error = GooglePubSub._utils._validateNonEmptyArg(permissions, "permissions");
if (error) {
imp.wakeup(0, function () {
callback(error, null);
});
return;
}
_resource.setName(resourceName);
_resource.testIamPermissions(permissions, function (error, httpResponse) {
if (callback) {
local permissions = null;
if (!error) {
permissions = GooglePubSub._utils._getTableValue(httpResponse, "permissions", []);
}
imp.wakeup(0, function () {
callback(error, permissions);
});
}
}.bindenv(this));
}
// -------------------- PRIVATE METHODS -------------------- //
function _invokePolicyCallback(error, httpResponse, callback) {
if (callback) {
local policy = null;
if (!error) {
policy = GooglePubSub.IAM.Policy(null);
policy._fromJson(httpResponse);
}
imp.wakeup(0, function () {
callback(error, policy);
});
}
}
}
// Auxiliary class, represents Identity and Access Management (IAM) policy.
// For more information about IAM Policy see https://cloud.google.com/iam/docs/overview
// and https://cloud.google.com/pubsub/docs/reference/rest/v1/Policy
class GooglePubSub.IAM.Policy {
// Version of the Policy (integer)
version = null;
// Array of bindings (tables { "role" : string, "members" : array of strings })
// Every binding binds a list of members to a role, where the members can be
// user accounts, Google groups, Google domains, service accounts.
// A role is a named set of permissions defined by IAM.
// For a list of roles Google Cloud Pub/Sub IAM supports, see Google Cloud Pub/Sub
// Access Control documentation: https://cloud.google.com/pubsub/docs/access_control
bindings = null;
// Entity tag
// For more information see https://cloud.google.com/pubsub/docs/reference/rest/v1/Policy
etag = null;
// GooglePubSub.IAM.Policy constructor that can be used to set resource policy
// using GooglePubSub.IAM.setPolicy() method.
//
// Parameters:
// version : integer Version of the Policy.
// (optional) Default : 0
// bindings : array Array of bindings: associations between a role and
// of tables a list of members.
// { "role" : string, For more information see https://cloud.google.com/pubsub/docs/reference/rest/v1/Policy
// "members" : array and https://cloud.google.com/pubsub/docs/access_control
// of strings }
// etag : string Entity tag
// (optional) For more information see https://cloud.google.com/pubsub/docs/reference/rest/v1/Policy
// Returns: GooglePubSub.IAM.Policy instance created.
constructor(version = 0, bindings = null, etag = null) {
this.version = version;
this.bindings = bindings;
this.etag = etag;
}
// -------------------- PRIVATE METHODS -------------------- //
function _toJson() {
local result = {};
if (version) {
result["version"] <- version;
}
if (bindings) {
result["bindings"] <- bindings;
}
if (etag) {
result["etag"] <- etag;
}
return result;
}
function _fromJson(jsonPolicy) {
version = GooglePubSub._utils._getTableValue(jsonPolicy, "version", 0);
bindings = GooglePubSub._utils._getTableValue(jsonPolicy, "bindings", []);
etag = GooglePubSub._utils._getTableValue(jsonPolicy, "etag", null);
}
}
// This class represents Pub/Sub Publisher.
// It allows to publish messages to a specific topic of Google Cloud Pub/Sub service.
class GooglePubSub.Publisher {
_projectId = null;
_oAuthTokenProvider = null;
_topic = null;
// GooglePubSub.Publisher constructor.
//
// Parameters:
// projectId : string Google Cloud Project ID.
// oAuthTokenProvider Provider of access tokens suitable for Google Pub/Sub service requests