kubemq-js
Version:
kubemq js/ts library for KubeMQ Message Broker
258 lines • 11.5 kB
JavaScript
"use strict";
// commandsClient.ts
Object.defineProperty(exports, "__esModule", { value: true });
exports.CQClient = void 0;
const KubeMQClient_1 = require("../client/KubeMQClient");
const pb = require("../protos");
const utils_1 = require("../common/utils");
const grpc = require("@grpc/grpc-js");
const common_1 = require("../common/common");
const queryTypes_1 = require("./queryTypes");
const commandTypes_1 = require("./commandTypes");
class CQClient extends KubeMQClient_1.KubeMQClient {
constructor(Options) {
super(Options);
}
sendCommandRequest(msg) {
const pbMessage = new pb.kubemq.Request();
pbMessage.RequestID = (msg.id ? msg.id : utils_1.Utils.uuid());
pbMessage.ClientID = (msg.clientId ? msg.clientId : this.clientId);
if (!msg.channel || msg.channel.trim().length === 0) {
throw new Error('Command message must have a channel.');
}
pbMessage.Channel = (msg.channel);
pbMessage.ReplyChannel = (msg.channel);
if ((!msg.metadata || msg.metadata.trim().length === 0) &&
(!msg.body || msg.body.length === 0) &&
(!msg.tags || msg.tags.size === 0)) {
throw new Error('Command message must have at least one of the following: metadata, body, or tags.');
}
//pbMessage.setBody(msg.body);
pbMessage.Body = typeof msg.body === 'string' ? new TextEncoder().encode(msg.body) : msg.body;
pbMessage.Metadata = (msg.metadata);
if (msg.tags != null) {
pbMessage.Tags = (msg.tags);
}
if (msg.timeout <= 0) {
throw new Error('Command message timeout must be a positive integer.');
}
pbMessage.Timeout = (msg.timeout);
pbMessage.RequestTypeData = pb.kubemq.Request.RequestType.Command;
return new Promise((resolve, reject) => {
this.grpcClient.SendRequest(pbMessage, this.getMetadata(), (e, response) => {
if (e) {
reject(e);
return;
}
resolve({
id: response.RequestID,
clientId: response.ClientID,
error: response.Error,
executed: response.Executed,
timestamp: response.Timestamp,
});
});
});
}
sendQueryRequest(msg) {
const pbMessage = new pb.kubemq.Request();
pbMessage.RequestID = (msg.id ? msg.id : utils_1.Utils.uuid());
pbMessage.ClientID = (msg.clientId ? msg.clientId : this.clientId);
pbMessage.Channel = (msg.channel);
pbMessage.ReplyChannel = (msg.channel);
//pbMessage.setBody(msg.body);
pbMessage.Body = typeof msg.body === 'string' ? new TextEncoder().encode(msg.body) : msg.body;
pbMessage.Metadata = (msg.metadata);
if (msg.tags != null) {
pbMessage.Tags = (msg.tags);
}
pbMessage.Timeout = (msg.timeout);
pbMessage.RequestTypeData = (2);
pbMessage.CacheKey = (msg.cacheKey ? msg.cacheKey : '');
pbMessage.CacheTTL = (msg.cacheTTL ? msg.cacheTTL : 0);
return new Promise((resolve, reject) => {
this.grpcClient.SendRequest(pbMessage, this.getMetadata(), (e, response) => {
if (e) {
reject(e);
return;
}
resolve({
id: response.RequestID,
clientId: response.ClientID,
error: response.Error,
executed: response.Executed,
timestamp: response.Timestamp,
body: response.Body,
metadata: response.Metadata,
tags: response.Tags,
});
});
});
}
sendCommandResponseMessage(msg) {
const pbMessage = new pb.kubemq.Response();
pbMessage.RequestID = (msg.id);
pbMessage.ClientID = (msg.clientId ? msg.clientId : this.clientId);
pbMessage.ReplyChannel = (msg.replyChannel);
pbMessage.Error = (msg.error);
pbMessage.Executed = (msg.executed);
return new Promise((resolve, reject) => {
this.grpcClient.SendResponse(pbMessage, this.getMetadata(), (e) => {
if (e) {
reject(e);
return;
}
resolve();
});
});
}
sendQueryResponseMessage(msg) {
const pbMessage = new pb.kubemq.Response();
pbMessage.RequestID = (msg.id);
pbMessage.ClientID = (msg.clientId ? msg.clientId : this.clientId);
pbMessage.ReplyChannel = (msg.replyChannel);
pbMessage.Error = (msg.error);
pbMessage.Executed = (msg.executed);
pbMessage.Body = typeof msg.body === 'string' ? new TextEncoder().encode(msg.body) : msg.body;
//pbMessage.setBody(msg.body);
pbMessage.Metadata = (msg.metadata);
if (msg.tags != null) {
pbMessage.Tags = (msg.tags);
}
return new Promise((resolve, reject) => {
this.grpcClient.SendResponse(pbMessage, this.getMetadata(), (e) => {
if (e) {
reject(e);
return;
}
resolve();
});
});
}
createCommandsChannel(channelName) {
return (0, common_1.createChannel)(this.grpcClient, this.getMetadata(), this.clientId, channelName, 'commands');
}
createQueriesChannel(channelName) {
return (0, common_1.createChannel)(this.grpcClient, this.getMetadata(), this.clientId, channelName, 'queries');
}
deleteCommandsChannel(channelName) {
return (0, common_1.deleteChannel)(this.grpcClient, this.getMetadata(), this.clientId, channelName, 'commands');
}
deleteQueriesChannel(channelName) {
return (0, common_1.deleteChannel)(this.grpcClient, this.getMetadata(), this.clientId, channelName, 'queries');
}
listCommandsChannels(search) {
return (0, common_1.listCQChannels)(this.grpcClient, this.getMetadata(), this.clientId, search, 'commands');
}
listQueriesChannels(search) {
return (0, common_1.listCQChannels)(this.grpcClient, this.getMetadata(), this.clientId, search, 'queries');
}
async subscribeToCommands(request) {
try {
console.debug('Subscribing to Command');
request.validate(); // Validate the request
const subscribe = request.encode(this);
const stream = this.grpcClient.SubscribeToRequests(subscribe, this.getMetadata());
// Assign observer to the request
request.observer = stream;
// Command Message received
stream.on('data', (data) => {
console.debug(`Command Message received: ID='${data.RequestID}', Channel='${data.Channel}'`);
const event = commandTypes_1.CommandMessageReceived.decode(data);
request.raiseOnReceiveMessage(event); // Process received event
});
// Handle errors (like server being unavailable)
stream.on('error', (err) => {
console.error('Command Subscription error:', err.message);
console.error('Command Subscription error code:', err.code);
request.raiseOnError(err.message);
if (err.code === grpc.status.UNAVAILABLE) {
console.debug('Server is unavailable, attempting to reconnect...');
request.reconnect(this, this.reconnectIntervalSeconds); // Trigger reconnection
}
});
// Handle stream close
stream.on('close', () => {
console.debug('Stream closed by the server, attempting to reconnect...');
request.reconnect(this, this.reconnectIntervalSeconds); // Attempt to reconnect when the stream is closed
});
}
catch (error) {
console.error('Failed to subscribe to events', error);
throw new Error('Subscription failed');
}
}
async subscribeToQueries(request) {
try {
console.debug('Subscribing to queries');
request.validate(); // Validate the request
const subscribe = request.encode(this);
const stream = this.grpcClient.SubscribeToRequests(subscribe, this.getMetadata());
// Assign observer to the request
request.observer = stream;
// Command Message received
stream.on('data', (data) => {
console.debug(`Queries Message received: ID='${data.RequestID}', Channel='${data.Channel}'`);
const event = queryTypes_1.QueryMessageReceived.decode(data);
request.raiseOnReceiveMessage(event); // Process received event
});
// Handle errors (like server being unavailable)
stream.on('error', (err) => {
console.error('Queries Subscription error:', err.message);
console.error('Queries Subscription error code:', err.code);
request.raiseOnError(err.message);
if (err.code === grpc.status.UNAVAILABLE) {
console.debug('Server is unavailable, attempting to reconnect...');
request.reconnect(this, this.reconnectIntervalSeconds); // Trigger reconnection
}
});
// Handle stream close
stream.on('close', () => {
console.debug('Stream closed by the server, attempting to reconnect...');
request.reconnect(this, this.reconnectIntervalSeconds); // Attempt to reconnect when the stream is closed
});
}
catch (error) {
console.error('Failed to subscribe to events', error);
throw new Error('Subscription failed');
}
}
}
exports.CQClient = CQClient;
// private subscribeFnQueries(request: QueriesSubscriptionRequest, cb: QueriesReceiveMessageCallback): Promise<internalQueriesSubscriptionResponse> {
// return new Promise<internalQueriesSubscriptionResponse>((resolve, reject) => {
// if (!cb) {
// reject(new Error('queries subscription requires a callback'));
// return;
// }
// const pbSubRequest = new pb.kubemq.Subscribe();
// pbSubRequest.ClientID=(request.clientId ? request.clientId : this.clientId);
// pbSubRequest.Group=(request.group ? request.group : '');
// pbSubRequest.Channel=(request.channel);
// pbSubRequest.SubscribeTypeData= pb.kubemq.Subscribe.SubscribeType.Queries;
// const stream = this.grpcClient.SubscribeToRequests(pbSubRequest, this.getMetadata());
// stream.on('data', function (data: pb.kubemq.Request) {
// cb(null, {
// id: data.RequestID,
// channel: data.Channel,
// metadata: data.Metadata,
// body: data.Body,
// tags: data.Tags,
// replyChannel: data.ReplyChannel,
// });
// });
// stream.on('error', (e: Error) => {
// cb(e, null);
// });
// let onClose = new TypedEvent<void>();
// stream.on('close', () => {
// onClose.emit();
// });
// resolve({
// onClose: onClose,
// stream: stream,
// });
// });
// }
// }
//# sourceMappingURL=CQClient.js.map