-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathclient.js
More file actions
1379 lines (1371 loc) · 45.2 KB
/
client.js
File metadata and controls
1379 lines (1371 loc) · 45.2 KB
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
// src/client.js
import crypto2 from "crypto";
import fs from "fs";
import { fileURLToPath } from "url";
import avro3 from "avro-js";
import grpc from "@grpc/grpc-js";
import protoLoader from "@grpc/proto-loader";
import { connectivityState } from "@grpc/grpc-js";
// src/utils/types.js
var SubscribeCallbackType = {
EVENT: "event",
LAST_EVENT: "lastEvent",
ERROR: "error",
END: "end",
GRPC_STATUS: "grpcStatus",
GRPC_KEEP_ALIVE: "grpcKeepAlive"
};
var PublishCallbackType = {
PUBLISH_RESPONSE: "publishResponse",
ERROR: "error",
GRPC_STATUS: "grpcStatus",
GRPC_KEEP_ALIVE: "grpcKeepAlive"
};
var AuthType = {
USER_SUPPLIED: "user-supplied",
USERNAME_PASSWORD: "username-password",
OAUTH_CLIENT_CREDENTIALS: "oauth-client-credentials",
OAUTH_JWT_BEARER: "oauth-jwt-bearer"
};
var EventSubscriptionAdminState = {
RUN: "RUN",
STOP: "STOP"
};
// src/utils/eventParseError.js
var EventParseError = class extends Error {
/**
* The cause of the error.
* @type {Error}
* @public
*/
cause;
/**
* The replay ID of the event at the origin of the error.
* Could be undefined if we're not able to extract it from the event data.
* @type {number}
* @public
*/
replayId;
/**
* The un-parsed event data at the origin of the error.
* @type {Object}
* @public
*/
event;
/**
* The latest replay ID that was received before the error.
* There could be more than one event between the replay ID and the event causing the error if the events were processed in batch.
* @type {number}
* @public
*/
latestReplayId;
/**
* Builds a new ParseError error.
* @param {string} message The error message.
* @param {Error} cause The cause of the error.
* @param {number} replayId The replay ID of the event at the origin of the error.
* Could be undefined if we're not able to extract it from the event data.
* @param {Object} event The un-parsed event data at the origin of the error.
* @param {number} latestReplayId The latest replay ID that was received before the error.
* @protected
*/
constructor(message, cause, replayId, event, latestReplayId) {
super(message);
this.cause = cause;
this.replayId = replayId;
this.event = event;
this.latestReplayId = latestReplayId;
}
};
// src/utils/avroHelper.js
import avro from "avro-js";
var CustomLongAvroType = avro.types.LongType.using({
fromBuffer: (buf) => {
const big = buf.readBigInt64LE();
if (big < Number.MIN_SAFE_INTEGER || big > Number.MAX_SAFE_INTEGER) {
return big;
}
return Number(BigInt.asIntN(64, big));
},
toBuffer: (n) => {
const buf = Buffer.allocUnsafe(8);
if (n instanceof BigInt) {
buf.writeBigInt64LE(n);
} else {
buf.writeBigInt64LE(BigInt(n));
}
return buf;
},
fromJSON: BigInt,
toJSON: Number,
isValid: (n) => {
const type = typeof n;
return type === "number" && n % 1 === 0 || type === "bigint";
},
compare: (n1, n2) => {
return n1 === n2 ? 0 : n1 < n2 ? -1 : 1;
}
});
// src/utils/configurationLoader.js
var DEFAULT_PUB_SUB_ENDPOINT = "api.pubsub.salesforce.com:7443";
var DEFAULT_REJECT_UNAUTHORIZED_SSL = true;
var ConfigurationLoader = class _ConfigurationLoader {
/**
* @param {Configuration} config the client configuration
* @returns {Configuration} the sanitized client configuration
*/
static load(config) {
config.pubSubEndpoint = config.pubSubEndpoint ?? DEFAULT_PUB_SUB_ENDPOINT;
_ConfigurationLoader.#checkMandatoryVariables(config, ["authType"]);
switch (config.authType) {
case AuthType.USER_SUPPLIED:
config = _ConfigurationLoader.#loadUserSuppliedAuth(config);
break;
case AuthType.USERNAME_PASSWORD:
_ConfigurationLoader.#checkMandatoryVariables(config, [
"loginUrl",
"username",
"password"
]);
config.userToken = config.userToken ?? "";
break;
case AuthType.OAUTH_CLIENT_CREDENTIALS:
_ConfigurationLoader.#checkMandatoryVariables(config, [
"loginUrl",
"clientId",
"clientSecret"
]);
break;
case AuthType.OAUTH_JWT_BEARER:
_ConfigurationLoader.#checkMandatoryVariables(config, [
"loginUrl",
"clientId",
"username",
"privateKey"
]);
break;
default:
throw new Error(
`Unsupported authType value: ${config.authType}`
);
}
_ConfigurationLoader.#loadBooleanValue(
config,
"rejectUnauthorizedSsl",
DEFAULT_REJECT_UNAUTHORIZED_SSL
);
return config;
}
/**
* Loads a boolean value from a config key.
* Falls back to the provided default value if no value is specified.
* Errors out if the config value can't be converted to a boolean value.
* @param {Configuration} config
* @param {string} key
* @param {boolean} defaultValue
*/
static #loadBooleanValue(config, key, defaultValue) {
if (!Object.hasOwn(config, key) || config[key] === void 0 || config[key] === null) {
config[key] = defaultValue;
return;
}
const value = config[key];
const type = typeof value;
switch (type) {
case "boolean":
break;
case "string":
{
switch (value.toUppercase()) {
case "TRUE":
config[key] = true;
break;
case "FALSE":
config[key] = false;
break;
default:
throw new Error(
`Expected boolean value for ${key}, found ${type} with value ${value}`
);
}
}
break;
default:
throw new Error(
`Expected boolean value for ${key}, found ${type} with value ${value}`
);
}
}
/**
* @param {Configuration} config the client configuration
* @returns {Configuration} sanitized configuration
*/
static #loadUserSuppliedAuth(config) {
_ConfigurationLoader.#checkMandatoryVariables(config, [
"accessToken",
"instanceUrl"
]);
if (!config.instanceUrl.startsWith("https://")) {
throw new Error(
`Invalid Salesforce Instance URL format supplied: ${config.instanceUrl}`
);
}
if (!config.organizationId) {
try {
config.organizationId = config.accessToken.split("!").at(0);
} catch (error) {
throw new Error(
"Unable to parse organizationId from access token",
{
cause: error
}
);
}
}
if (config.organizationId.length !== 15 && config.organizationId.length !== 18) {
throw new Error(
`Invalid Salesforce Org ID format supplied: ${config.organizationId}`
);
}
return config;
}
static #checkMandatoryVariables(config, varNames) {
varNames.forEach((varName) => {
if (!config[varName]) {
throw new Error(
`Missing value for ${varName} mandatory configuration key`
);
}
});
}
};
// src/utils/eventParser.js
import avro2 from "avro-js";
function parseEvent(schema, event) {
const allFields = schema.type.getFields();
const replayId = decodeReplayId(event.replayId);
const payload = schema.type.fromBuffer(event.event.payload);
if (payload.ChangeEventHeader) {
try {
payload.ChangeEventHeader.nulledFields = parseFieldBitmaps(
allFields,
payload.ChangeEventHeader.nulledFields
);
} catch (error) {
throw new Error("Failed to parse nulledFields", { cause: error });
}
try {
payload.ChangeEventHeader.diffFields = parseFieldBitmaps(
allFields,
payload.ChangeEventHeader.diffFields
);
} catch (error) {
throw new Error("Failed to parse diffFields", { cause: error });
}
try {
payload.ChangeEventHeader.changedFields = parseFieldBitmaps(
allFields,
payload.ChangeEventHeader.changedFields
);
} catch (error) {
throw new Error("Failed to parse changedFields", { cause: error });
}
}
flattenSinglePropertyObjects(payload);
return {
id: event.event.id,
schemaId: event.event.schemaId,
replayId,
payload
};
}
function flattenSinglePropertyObjects(theObject) {
Object.entries(theObject).forEach(([key, value]) => {
if (key !== "ChangeEventHeader" && value && typeof value === "object") {
const subKeys = Object.keys(value);
if (subKeys.length === 1) {
const subValue = value[subKeys[0]];
theObject[key] = subValue;
if (subValue && typeof subValue === "object") {
flattenSinglePropertyObjects(theObject[key]);
}
}
}
});
}
function parseFieldBitmaps(allFields, fieldBitmapsAsHex) {
if (fieldBitmapsAsHex.length === 0) {
return [];
}
let fieldNames = [];
if (fieldBitmapsAsHex[0].startsWith("0x")) {
fieldNames = getFieldNamesFromBitmap(allFields, fieldBitmapsAsHex[0]);
}
if (fieldBitmapsAsHex.length > 1 && fieldBitmapsAsHex[fieldBitmapsAsHex.length - 1].indexOf("-") !== -1) {
fieldBitmapsAsHex.forEach((fieldBitmapAsHex) => {
const bitmapMapStrings = fieldBitmapAsHex.split("-");
if (bitmapMapStrings.length >= 2) {
const parentField = allFields[parseInt(bitmapMapStrings[0], 10)];
const childFields = getChildFields(parentField);
const childFieldNames = getFieldNamesFromBitmap(
childFields,
bitmapMapStrings[1]
);
fieldNames = fieldNames.concat(
childFieldNames.map(
(fieldName) => `${parentField._name}.${fieldName}`
)
);
}
});
}
return fieldNames;
}
function getChildFields(parentField) {
const types = parentField._type.getTypes();
let fields = [];
types.forEach((type) => {
if (type instanceof avro2.types.RecordType) {
fields = fields.concat(type.getFields());
}
});
return fields;
}
function getFieldNamesFromBitmap(fields, fieldBitmapAsHex) {
let binValue = hexToBin(fieldBitmapAsHex);
binValue = binValue.split("").reverse().join("");
const fieldNames = [];
for (let i = 0; i < binValue.length && i < fields.length; i++) {
if (binValue[i] === "1") {
fieldNames.push(fields[i].getName());
}
}
return fieldNames;
}
function decodeReplayId(encodedReplayId) {
return Number(encodedReplayId.readBigUInt64BE());
}
function encodeReplayId(replayId) {
const buf = Buffer.allocUnsafe(8);
buf.writeBigUInt64BE(BigInt(replayId), 0);
return buf;
}
function toJsonString(event) {
return JSON.stringify(
event,
(key, value) => (
/* Convert BigInt values into strings and keep other types unchanged */
typeof value === "bigint" ? value.toString() : value
)
);
}
function hexToBin(hex) {
let bin = hex.substring(2);
bin = bin.replaceAll("0", "0000");
bin = bin.replaceAll("1", "0001");
bin = bin.replaceAll("2", "0010");
bin = bin.replaceAll("3", "0011");
bin = bin.replaceAll("4", "0100");
bin = bin.replaceAll("5", "0101");
bin = bin.replaceAll("6", "0110");
bin = bin.replaceAll("7", "0111");
bin = bin.replaceAll("8", "1000");
bin = bin.replaceAll("9", "1001");
bin = bin.replaceAll("A", "1010");
bin = bin.replaceAll("B", "1011");
bin = bin.replaceAll("C", "1100");
bin = bin.replaceAll("D", "1101");
bin = bin.replaceAll("E", "1110");
bin = bin.replaceAll("F", "1111");
return bin;
}
// src/utils/toolingApiHelper.js
import jsforce from "jsforce";
var API_VERSION = "62.0";
var MANAGED_SUBSCRIPTION_KEY_PREFIX = "18x";
async function getManagedSubscription(instanceUrl, accessToken, subscriptionIdOrName) {
const conn = new jsforce.Connection({ instanceUrl, accessToken });
if (subscriptionIdOrName.indexOf("'") !== -1) {
throw new Error(
`Suspected SOQL injection in subscription ID or name string value: ${subscriptionIdOrName}`
);
}
let filter;
if ((subscriptionIdOrName.length === 15 || subscriptionIdOrName.length === 18) && subscriptionIdOrName.toLowerCase().startsWith(MANAGED_SUBSCRIPTION_KEY_PREFIX)) {
filter = `Id='${subscriptionIdOrName}'`;
} else {
filter = `DeveloperName='${subscriptionIdOrName}'`;
}
const query = `SELECT Id, DeveloperName, Metadata FROM ManagedEventSubscription WHERE ${filter} LIMIT 1`;
const res = await conn.request(
`/services/data/v${API_VERSION}/tooling/query/?q=${encodeURIComponent(query)}`
);
if (res.size === 0) {
throw new Error(
`Failed to retrieve managed event subscription with ${filter}`
);
}
return res.records[0];
}
// src/utils/auth.js
import crypto from "crypto";
import jsforce2 from "jsforce";
import { fetch } from "undici";
var SalesforceAuth = class {
/**
* Client configuration
* @type {Configuration}
*/
#config;
/**
* Logger
* @type {Logger}
*/
#logger;
/**
* Builds a new Pub/Sub API client
* @param {Configuration} config the client configuration
* @param {Logger} logger a logger
*/
constructor(config, logger) {
this.#config = config;
this.#logger = logger;
}
/**
* Authenticates with the auth mode specified in configuration
* @returns {ConnectionMetadata}
*/
async authenticate() {
this.#logger.debug(`Authenticating with ${this.#config.authType} mode`);
switch (this.#config.authType) {
case AuthType.USER_SUPPLIED:
throw new Error(
"Authenticate method should not be called in user-supplied mode."
);
case AuthType.USERNAME_PASSWORD:
return this.#authWithUsernamePassword();
case AuthType.OAUTH_CLIENT_CREDENTIALS:
return this.#authWithOAuthClientCredentials();
case AuthType.OAUTH_JWT_BEARER:
return this.#authWithJwtBearer();
default:
throw new Error(
`Unsupported authType value: ${this.#config.authType}`
);
}
}
/**
* Authenticates with the username/password flow
* @returns {ConnectionMetadata}
*/
async #authWithUsernamePassword() {
const { loginUrl, username, password, userToken } = this.#config;
const sfConnection = new jsforce2.Connection({
loginUrl
});
await sfConnection.login(username, `${password}${userToken}`);
return {
accessToken: sfConnection.accessToken,
instanceUrl: sfConnection.instanceUrl,
organizationId: sfConnection.userInfo.organizationId,
username
};
}
/**
* Authenticates with the OAuth 2.0 client credentials flow
* @returns {ConnectionMetadata}
*/
async #authWithOAuthClientCredentials() {
const { clientId, clientSecret } = this.#config;
const params = new URLSearchParams();
params.append("grant_type", "client_credentials");
params.append("client_id", clientId);
params.append("client_secret", clientSecret);
return this.#authWithOAuth(params.toString());
}
/**
* Authenticates with the OAuth 2.0 JWT bearer flow
* @returns {ConnectionMetadata}
*/
async #authWithJwtBearer() {
const { clientId, username, loginUrl, privateKey } = this.#config;
const header = JSON.stringify({ alg: "RS256" });
const claims = JSON.stringify({
iss: clientId,
sub: username,
aud: loginUrl,
exp: Math.floor(Date.now() / 1e3) + 60 * 5
});
let token = `${base64url(header)}.${base64url(claims)}`;
const sign = crypto.createSign("RSA-SHA256");
sign.update(token);
sign.end();
token += `.${base64url(sign.sign(privateKey))}`;
const body = `grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=${token}`;
return this.#authWithOAuth(body);
}
/**
* Generic OAuth 2.0 connect method
* @param {string} body URL encoded body
* @returns {ConnectionMetadata} connection metadata
*/
async #authWithOAuth(body) {
const { loginUrl } = this.#config;
const loginResponse = await fetch(`${loginUrl}/services/oauth2/token`, {
method: "post",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body
});
if (loginResponse.status !== 200) {
throw new Error(
`Authentication error: HTTP ${loginResponse.status} - ${await loginResponse.text()}`
);
}
const { access_token, instance_url } = await loginResponse.json();
const userInfoResponse = await fetch(
`${loginUrl}/services/oauth2/userinfo`,
{
headers: { authorization: `Bearer ${access_token}` }
}
);
if (userInfoResponse.status !== 200) {
throw new Error(
`Failed to retrieve user info: HTTP ${userInfoResponse.status} - ${await userInfoResponse.text()}`
);
}
const { organization_id, preferred_username } = await userInfoResponse.json();
return {
accessToken: access_token,
instanceUrl: instance_url,
organizationId: organization_id,
username: preferred_username
};
}
};
function base64url(input) {
const buf = Buffer.from(input, "utf8");
return buf.toString("base64url");
}
// src/client.js
var MAX_EVENT_BATCH_SIZE = 100;
var PubSubApiClient = class {
/**
* Client configuration
* @type {Configuration}
*/
#config;
/**
* gRPC client
* @type {Object}
*/
#client;
/**
* Map of schemas indexed by ID
* @type {Map<string,Schema>}
*/
#schemas;
/**
* Map of subscriptions indexed by topic name
* @type {Map<string,Subscription>}
*/
#subscriptions;
/**
* Map of managed subscriptions indexed by subscription ID
* @type {Map<string,Subscription>}
*/
#managedSubscriptions;
/**
* Map of publish streams indexed by topic name
* @type {Map<string,PublishStream>}
*/
#publishStreams;
/**
* Logger
* @type {Logger}
*/
#logger;
/**
* Builds a new Pub/Sub API client
* @param {Configuration} config the client configuration
* @param {Logger} [logger] an optional custom logger. The client uses the console if no value is supplied.
*/
constructor(config, logger = console) {
this.#logger = logger;
this.#schemas = /* @__PURE__ */ new Map();
this.#subscriptions = /* @__PURE__ */ new Map();
this.#managedSubscriptions = /* @__PURE__ */ new Map();
this.#publishStreams = /* @__PURE__ */ new Map();
try {
this.#config = ConfigurationLoader.load(config);
} catch (error) {
this.#logger.error(error);
throw new Error("Failed to initialize Pub/Sub API client", {
cause: error
});
}
}
/**
* Authenticates with Salesforce (if not using user-supplied authentication mode) then,
* connects to the Pub/Sub API.
* @returns {Promise<void>} Promise that resolves once the connection is established
*/
async connect() {
if (this.#config.authType !== AuthType.USER_SUPPLIED) {
try {
const auth = new SalesforceAuth(this.#config, this.#logger);
const conMetadata = await auth.authenticate();
this.#config.accessToken = conMetadata.accessToken;
this.#config.username = conMetadata.username;
this.#config.instanceUrl = conMetadata.instanceUrl;
this.#config.organizationId = conMetadata.organizationId;
this.#logger.info(
`Connected to Salesforce org ${conMetadata.instanceUrl} (${this.#config.organizationId}) as ${conMetadata.username}`
);
} catch (error) {
throw new Error("Failed to authenticate with Salesforce", {
cause: error
});
}
}
try {
this.#logger.debug(`Connecting to Pub/Sub API`);
const rootCert = fs.readFileSync(
fileURLToPath(new URL("./cacert-2ebcb9e8.pem?hash=2ebcb9e8", import.meta.url))
);
const protoFilePath = fileURLToPath(
new URL("./pubsub_api-07e1f84a.proto?hash=07e1f84a", import.meta.url)
);
const packageDef = protoLoader.loadSync(protoFilePath, {});
const grpcObj = grpc.loadPackageDefinition(packageDef);
const sfdcPackage = grpcObj.eventbus.v1;
const metaCallback = (_params, callback) => {
const meta = new grpc.Metadata();
meta.add("accesstoken", this.#config.accessToken);
meta.add("instanceurl", this.#config.instanceUrl);
meta.add("tenantid", this.#config.organizationId);
callback(null, meta);
};
const callCreds = grpc.credentials.createFromMetadataGenerator(metaCallback);
const combCreds = grpc.credentials.combineChannelCredentials(
grpc.credentials.createSsl(rootCert, null, null, {
rejectUnauthorized: this.#config.rejectUnauthorizedSsl
}),
callCreds
);
this.#client = new sfdcPackage.PubSub(
this.#config.pubSubEndpoint,
combCreds
);
this.#logger.info(
`Connected to Pub/Sub API endpoint ${this.#config.pubSubEndpoint}`
);
} catch (error) {
throw new Error("Failed to connect to Pub/Sub API", {
cause: error
});
}
}
/**
* Gets the gRPC connectivity state from the current channel.
* @returns {Promise<connectivityState>} Promise that holds channel's connectivity information {@link connectivityState}
*/
async getConnectivityState() {
return this.#client?.getChannel()?.getConnectivityState(false);
}
/**
* Subscribes to a topic and retrieves all past events in retention window.
* @param {string} topicName name of the topic that we're subscribing to
* @param {SubscribeCallback} subscribeCallback callback function for handling subscription events
* @param {number | null} [numRequested] optional number of events requested. If not supplied or null, the client keeps the subscription alive forever.
*/
subscribeFromEarliestEvent(topicName, subscribeCallback, numRequested = null) {
this.#subscribe(
{
topicName,
numRequested,
replayPreset: 1
},
subscribeCallback
);
}
/**
* Subscribes to a topic and retrieves past events starting from a replay ID.
* @param {string} topicName name of the topic that we're subscribing to
* @param {SubscribeCallback} subscribeCallback callback function for handling subscription events
* @param {number | null} numRequested number of events requested. If null, the client keeps the subscription alive forever.
* @param {number} replayId replay ID
*/
subscribeFromReplayId(topicName, subscribeCallback, numRequested, replayId) {
this.#subscribe(
{
topicName,
numRequested,
replayPreset: 2,
replayId: encodeReplayId(replayId)
},
subscribeCallback
);
}
/**
* Subscribes to a topic.
* @param {string} topicName name of the topic that we're subscribing to
* @param {SubscribeCallback} subscribeCallback callback function for handling subscription events
* @param {number | null} [numRequested] optional number of events requested. If not supplied or null, the client keeps the subscription alive forever.
*/
subscribe(topicName, subscribeCallback, numRequested = null) {
this.#subscribe(
{
topicName,
numRequested
},
subscribeCallback
);
}
/**
* Subscribes to a topic using the gRPC client and an event schema
* @param {SubscribeRequest} subscribeRequest subscription request
* @param {SubscribeCallback} subscribeCallback callback function for handling subscription events
*/
#subscribe(subscribeRequest, subscribeCallback) {
this.#logger.debug(
`Preparing subscribe request: ${toJsonString(subscribeRequest)}`
);
if (!this.#client) {
throw new Error("Pub/Sub API client is not connected.");
}
let { topicName, numRequested } = subscribeRequest;
try {
let isInfiniteEventRequest = false;
if (numRequested === null || numRequested === void 0) {
isInfiniteEventRequest = true;
subscribeRequest.numRequested = numRequested = MAX_EVENT_BATCH_SIZE;
} else {
subscribeRequest.numRequested = this.#validateRequestedEventCount(topicName, numRequested);
}
if (!this.#client) {
throw new Error("Pub/Sub API client is not connected.");
}
let subscription = this.#subscriptions.get(topicName);
let grpcSubscription;
if (subscription) {
this.#logger.debug(
`${topicName} - Reusing cached gRPC subscription`
);
grpcSubscription = subscription.grpcSubscription;
subscription.info.receivedEventCount = 0;
subscription.info.requestedEventCount = subscribeRequest.numRequested;
subscription.info.isInfiniteEventRequest = isInfiniteEventRequest;
} else {
this.#logger.debug(
`${topicName} - Establishing new gRPC subscription`
);
grpcSubscription = this.#client.Subscribe();
subscription = {
info: {
isManaged: false,
topicName,
requestedEventCount: subscribeRequest.numRequested,
receivedEventCount: 0,
lastReplayId: null,
isInfiniteEventRequest
},
grpcSubscription,
subscribeCallback
};
this.#subscriptions.set(topicName, subscription);
}
this.#injectEventHandlingLogic(subscription);
grpcSubscription.write(subscribeRequest);
this.#logger.info(
`${topicName} - Subscribe request sent for ${numRequested} events`
);
} catch (error) {
throw new Error(
`Failed to subscribe to events for topic ${topicName}`,
{ cause: error }
);
}
}
/**
* Subscribes to a topic thanks to a managed subscription.
* @param {string} subscriptionIdOrName managed subscription ID or developer name
* @param {SubscribeCallback} subscribeCallback callback function for handling subscription events
* @param {number | null} [numRequested] optional number of events requested. If not supplied or null, the client keeps the subscription alive forever.
* @throws Throws an error if the managed subscription does not exist or is not in the `RUN` state.
*/
async subscribeWithManagedSubscription(subscriptionIdOrName, subscribeCallback, numRequested = null) {
this.#logger.debug(
`Preparing managed subscribe request: ${toJsonString({ subscriptionIdOrName, numRequested })}`
);
if (!this.#client) {
throw new Error("Pub/Sub API client is not connected.");
}
const managedSubscription = await getManagedSubscription(
this.#config.instanceUrl,
this.#config.accessToken,
subscriptionIdOrName
);
const subscriptionId = managedSubscription.Id;
const subscriptionName = managedSubscription.DeveloperName;
const subscriptionLabel = `${subscriptionName} (${subscriptionId})`;
const { topicName, state } = managedSubscription.Metadata;
this.#logger.info(
`Retrieved managed subscription ${subscriptionLabel}: ${toJsonString(managedSubscription.Metadata)}`
);
if (state !== EventSubscriptionAdminState.RUN) {
throw new Error(
`Can't subscribe to managed subscription ${subscriptionLabel}: subscription is in ${state} state`
);
}
try {
let isInfiniteEventRequest = false;
if (numRequested === null || numRequested === void 0) {
isInfiniteEventRequest = true;
numRequested = MAX_EVENT_BATCH_SIZE;
} else {
numRequested = this.#validateRequestedEventCount(
topicName,
numRequested
);
}
if (!this.#client) {
throw new Error("Pub/Sub API client is not connected.");
}
let subscription = this.#managedSubscriptions.get(subscriptionId);
let grpcSubscription;
if (subscription) {
this.#logger.debug(
`${topicName} - Reusing cached gRPC subscription`
);
grpcSubscription = subscription.grpcSubscription;
subscription.info.receivedEventCount = 0;
subscription.info.requestedEventCount = numRequested;
subscription.info.isInfiniteEventRequest = isInfiniteEventRequest;
} else {
this.#logger.debug(
`${topicName} - Establishing new gRPC subscription`
);
grpcSubscription = this.#client.ManagedSubscribe();
subscription = {
info: {
isManaged: true,
topicName,
subscriptionId,
subscriptionName,
requestedEventCount: numRequested,
receivedEventCount: 0,
lastReplayId: null
},
grpcSubscription,
subscribeCallback
};
this.#managedSubscriptions.set(subscriptionId, subscription);
}
this.#injectEventHandlingLogic(subscription);
grpcSubscription.write({
subscriptionId,
numRequested
});
this.#logger.info(
`${topicName} - Managed subscribe request sent to ${subscriptionLabel} for ${numRequested} events`
);
} catch (error) {
throw new Error(
`Failed to subscribe to managed subscription ${subscriptionLabel}`,
{ cause: error }
);
}
}
/**
* Request additional events on an existing subscription.
* @param {string} topicName topic name
* @param {number} numRequested number of events requested
*/
requestAdditionalEvents(topicName, numRequested) {
if (!this.#client) {
throw new Error("Pub/Sub API client is not connected.");
}
const subscription = this.#subscriptions.get(topicName);
if (!subscription) {
throw new Error(
`Failed to request additional events for topic ${topicName}: no active subscription found.`
);
}
subscription.info.receivedEventCount = 0;
subscription.info.requestedEventCount = numRequested;
subscription.grpcSubscription.write({
topicName,
numRequested
});
this.#logger.debug(
`${topicName} - Resubscribing to a batch of ${numRequested} events`
);
}
/**
* Request additional events on an existing managed subscription.
* @param {string} subscriptionId managed subscription ID
* @param {number} numRequested number of events requested
*/
requestAdditionalManagedEvents(subscriptionId, numRequested) {
if (!this.#client) {
throw new Error("Pub/Sub API client is not connected.");
}
const subscription = this.#managedSubscriptions.get(subscriptionId);
if (!subscription) {
throw new Error(
`Failed to request additional events for managed subscription with ID ${subscriptionId}: no active subscription found.`
);
}
subscription.info.receivedEventCount = 0;
subscription.info.requestedEventCount = numRequested;
subscription.grpcSubscription.write({
subscriptionId,
numRequested
});
const { subscriptionName } = subscription.info;
this.#logger.debug(
`${subscriptionName} (${subscriptionId}) - Resubscribing to a batch of ${numRequested} events`
);
}
/**
* Commits a replay ID on a managed subscription.
* @param {string} subscriptionId managed subscription ID
* @param {number} replayId event replay ID
* @returns {string} commit request UUID
*/
commitReplayId(subscriptionId, replayId) {
if (!this.#client) {
throw new Error("Pub/Sub API client is not connected.");
}
const subscription = this.#managedSubscriptions.get(subscriptionId);
if (!subscription) {
throw new Error(
`Failed to commit a replay ID on managed subscription with ID ${subscriptionId}: no active subscription found.`
);
}
const commitRequestId = crypto2.randomUUID();
subscription.grpcSubscription.write({
subscriptionId,
commitReplayIdRequest: {
commitRequestId,
replayId: encodeReplayId(replayId)
}
});
const { subscriptionName } = subscription.info;
this.#logger.debug(
`${subscriptionName} (${subscriptionId}) - Sent replay ID commit request (request ID: ${commitRequestId}, replay ID: ${replayId})`
);
return commitRequestId;
}
/**
* Publishes a payload to a topic using the gRPC client. This is a synchronous operation, use `publishBatch` when publishing event batches.
* @param {string} topicName name of the topic that we're publishing on
* @param {Object} payload payload of the event that is being published
* @param {string} [correlationKey] optional correlation key. If you don't provide one, we'll generate a random UUID for you.
* @returns {Promise<PublishResult>} Promise holding a PublishResult object with replayId and correlationKey
*/
async publish(topicName, payload, correlationKey) {
try {
this.#logger.debug(
`${topicName} - Preparing to publish event: ${toJsonString(payload)}`
);
if (!this.#client) {
throw new Error("Pub/Sub API client is not connected.");
}
const schema = await this.#fetchEventSchemaFromTopicNameWithClient(topicName);
const id = correlationKey ? correlationKey : crypto2.randomUUID();
const response = await new Promise((resolve, reject) => {
this.#client.Publish(
{
topicName,
events: [
{
id,
// Correlation key
schemaId: schema.id,
payload: schema.type.toBuffer(payload)
}
]
},
(err, response2) => {