Implement send default and R/W to file

This commit is contained in:
David Majdandžić
2023-03-28 03:51:52 +02:00
parent 1dd5b9ed7c
commit bb363deb2a
7 changed files with 250 additions and 1651 deletions

View File

@@ -247,6 +247,7 @@ class ClientSession {
this.eventEmitter.emit(ClientSession.ANY_PDU_EVENT, payload); this.eventEmitter.emit(ClientSession.ANY_PDU_EVENT, payload);
} }
}); });
this.session.send();
this.session.on('pdu', this.sessionPdu.bind(this)); this.session.on('pdu', this.sessionPdu.bind(this));
this.connectingPromise.resolve(); this.connectingPromise.resolve();
} }

View File

@@ -22,7 +22,7 @@ export class Client implements SmppSession {
defaultMultipleJob: Job = Job.createEmptyMultiple(); defaultMultipleJob: Job = Job.createEmptyMultiple();
private readonly eventEmitter: EventEmitter; private readonly eventEmitter: EventEmitter;
private readonly logger: Logger; private readonly logger: Logger;
private readonly id: number; private readonly _id: number;
private session?: any; private session?: any;
private connectPromise: PersistentPromise | null = null; private connectPromise: PersistentPromise | null = null;
private bindPromise: PersistentPromise | null = null; private bindPromise: PersistentPromise | null = null;
@@ -30,7 +30,7 @@ export class Client implements SmppSession {
private counterUpdateTimer: any | null = null; private counterUpdateTimer: any | null = null;
constructor(id: number, url: string, username: string, password: string) { constructor(id: number, url: string, username: string, password: string) {
this.id = id; this._id = id;
this._url = url; this._url = url;
this._username = username; this._username = username;
this._password = password; this._password = password;
@@ -56,6 +56,10 @@ export class Client implements SmppSession {
private _url: string; private _url: string;
getUrl(): string {
return this._url;
}
set url(value: string) { set url(value: string) {
this._url = value; this._url = value;
} }
@@ -68,6 +72,24 @@ export class Client implements SmppSession {
this.eventEmitter.emit(Client.ClientEvents.STATE_CHANGED, this.serialize()); this.eventEmitter.emit(Client.ClientEvents.STATE_CHANGED, this.serialize());
} }
setDefaultSingleJob(job: Job): void {
this.defaultSingleJob = job;
this.eventEmitter.emit(Client.ClientEvents.STATE_CHANGED, this.serialize());
}
setDefaultMultipleJob(job: Job): void {
this.defaultMultipleJob = job;
this.eventEmitter.emit(Client.ClientEvents.STATE_CHANGED, this.serialize());
}
getDefaultSingleJob(): Job {
return this.defaultSingleJob;
}
getDefaultMultipleJob(): Job {
return this.defaultMultipleJob;
}
setStatus(status: ClientStatus): void { setStatus(status: ClientStatus): void {
this._status = status; this._status = status;
this.eventEmitter.emit("status", status); this.eventEmitter.emit("status", status);
@@ -119,15 +141,15 @@ export class Client implements SmppSession {
connectAndBind(): Promise<void> { connectAndBind(): Promise<void> {
return this.connect().then(this.bind.bind(this), (error) => { return this.connect().then(this.bind.bind(this), (error) => {
this.logger.log1(`Client-${this.id} connectAndBind failed: ${error}`); this.logger.log1(`Client-${this._id} connectAndBind failed: ${error}`);
}); });
} }
serialize(): string { serialize(): object {
return JSON.stringify({ return {
id: this.id, url: this._url, username: this._username, password: this._password, status: this._status, id: this._id, url: this._url, username: this._username, password: this._password, status: this._status,
defaultSingleJob: this.defaultSingleJob, defaultMultipleJob: this.defaultMultipleJob, defaultSingleJob: this.defaultSingleJob, defaultMultipleJob: this.defaultMultipleJob,
}); };
} }
close(): Promise<void> { close(): Promise<void> {
@@ -143,7 +165,7 @@ export class Client implements SmppSession {
this.validateSession(reject); this.validateSession(reject);
this.validateBound(reject); this.validateBound(reject);
} }
this.logger.log5(`Client-${this.id} sending PDU: ${JSON.stringify(pdu)}`); this.logger.log5(`Client-${this._id} sending PDU: ${JSON.stringify(pdu)}`);
this.session.send(pdu); this.session.send(pdu);
resolve(pdu); resolve(pdu);
}); });
@@ -154,9 +176,9 @@ export class Client implements SmppSession {
this.validateSession(reject); this.validateSession(reject);
this.validateBound(reject); this.validateBound(reject);
if (!job.count || !job.perSecond) { if (!job.count || !job.perSecond) {
reject(`Client-${this.id} sendMultiple failed: invalid job, missing fields`); reject(`Client-${this._id} sendMultiple failed: invalid job, missing fields`);
} }
this.logger.log1(`Client-${this.id} sending multiple messages: ${JSON.stringify(job)}`); this.logger.log1(`Client-${this._id} sending multiple messages: ${JSON.stringify(job)}`);
this.setStatus(ClientStatus.BUSY); this.setStatus(ClientStatus.BUSY);
@@ -205,11 +227,23 @@ export class Client implements SmppSession {
this.eventEmitter.on(event, callback); this.eventEmitter.on(event, callback);
} }
getId(): number {
return this._id;
}
sendMultipleDefault(): Promise<void> {
return this.sendMultiple(this.getDefaultMultipleJob());
}
sendSingleDefault(): Promise<object> {
return this.sendSingle(this.getDefaultSingleJob());
}
private connectSession(): void { private connectSession(): void {
if (!this.fieldsAreOk()) { if (!this.fieldsAreOk()) {
return; return;
} }
this.logger.log1(`Client-${this.id} connecting to ${this._url}`); this.logger.log1(`Client-${this._id} connecting to ${this._url}`);
this.session = smpp.connect({ this.session = smpp.connect({
url: this._url, auto_enquire_link_period: AUTO_ENQUIRE_LINK_PERIOD, url: this._url, auto_enquire_link_period: AUTO_ENQUIRE_LINK_PERIOD,
@@ -220,7 +254,7 @@ export class Client implements SmppSession {
} }
private eventSessionConnected(): void { private eventSessionConnected(): void {
this.logger.log1(`Client-${this.id} connected to ${this._url}`); this.logger.log1(`Client-${this._id} connected to ${this._url}`);
this.setStatus(ClientStatus.CONNECTED); this.setStatus(ClientStatus.CONNECTED);
if (this.connectPromise) { if (this.connectPromise) {
this.connectPromise.resolve(); this.connectPromise.resolve();
@@ -228,31 +262,31 @@ export class Client implements SmppSession {
} }
private eventAnyPdu(pdu: any): void { private eventAnyPdu(pdu: any): void {
this.logger.log6(`Client-${this.id} received PDU: ${JSON.stringify(pdu)}`); this.logger.log6(`Client-${this._id} received PDU: ${JSON.stringify(pdu)}`);
this.eventEmitter.emit(Client.ClientEvents.ANY_PDU, pdu); this.eventEmitter.emit(Client.ClientEvents.ANY_PDU, pdu);
} }
private eventSessionError(pdu: any): void { private eventSessionError(pdu: any): void {
this.logger.log1(`Client-${this.id} error on ${this._url}`); this.logger.log1(`Client-${this._id} error on ${this._url}`);
this.setStatus(ClientStatus.NOT_CONNECTED); this.setStatus(ClientStatus.NOT_CONNECTED);
this.rejectPromises(pdu); this.rejectPromises(pdu);
} }
private eventSessionClose(): void { private eventSessionClose(): void {
this.logger.log1(`Client-${this.id} closed on ${this._url}`); this.logger.log1(`Client-${this._id} closed on ${this._url}`);
this.setStatus(ClientStatus.NOT_CONNECTED); this.setStatus(ClientStatus.NOT_CONNECTED);
this.rejectPromises(); this.rejectPromises();
} }
private eventBindReply(pdu: any): void { private eventBindReply(pdu: any): void {
if (pdu.command_status === 0) { if (pdu.command_status === 0) {
this.logger.log1(`Client-${this.id} bound to ${this._url}`); this.logger.log1(`Client-${this._id} bound to ${this._url}`);
this.setStatus(ClientStatus.BOUND); this.setStatus(ClientStatus.BOUND);
if (this.bindPromise) { if (this.bindPromise) {
this.bindPromise.resolve(); this.bindPromise.resolve();
} }
} else { } else {
this.logger.log1(`Client-${this.id} bind failed to ${this.url}`); this.logger.log1(`Client-${this._id} bind failed to ${this.url}`);
this.setStatus(ClientStatus.CONNECTED); this.setStatus(ClientStatus.CONNECTED);
if (this.bindPromise) { if (this.bindPromise) {
this.bindPromise.reject(pdu); this.bindPromise.reject(pdu);
@@ -271,15 +305,15 @@ export class Client implements SmppSession {
private fieldsAreOk() { private fieldsAreOk() {
if (!this._url) { if (!this._url) {
this.logger.log1(`Client-${this.id} has no url set`); this.logger.log1(`Client-${this._id} has no url set`);
return false; return false;
} }
if (!this._username) { if (!this._username) {
this.logger.log1(`Client-${this.id} has no username set`); this.logger.log1(`Client-${this._id} has no username set`);
return false; return false;
} }
if (!this._password) { if (!this._password) {
this.logger.log1(`Client-${this.id} has no password set`); this.logger.log1(`Client-${this._id} has no password set`);
return false; return false;
} }
return true; return true;
@@ -287,7 +321,7 @@ export class Client implements SmppSession {
private validateSession(reject: (reason?: any) => void) { private validateSession(reject: (reason?: any) => void) {
if (!this.session) { if (!this.session) {
let errorMessage = `Client-${this.id} session is not defined`; let errorMessage = `Client-${this._id} session is not defined`;
this.logger.log1(errorMessage); this.logger.log1(errorMessage);
reject(errorMessage); reject(errorMessage);
} }
@@ -295,7 +329,7 @@ export class Client implements SmppSession {
private validateBound(reject: (reason?: any) => void) { private validateBound(reject: (reason?: any) => void) {
if (this._status !== ClientStatus.BOUND) { if (this._status !== ClientStatus.BOUND) {
let errorMessage = `Client-${this.id} is not bound`; let errorMessage = `Client-${this._id} is not bound`;
this.logger.log1(errorMessage); this.logger.log1(errorMessage);
reject(errorMessage); reject(errorMessage);
} }

121
src/ClientSessionManager.ts Normal file
View File

@@ -0,0 +1,121 @@
import fs from "fs";
import {Client} from "./Client";
import {Job} from "./Job";
import Logger from "./Logger";
import SessionManager from "./SessionManager";
import {SmppSession} from "./SmppSession";
const CLIENT_SESSIONS_FILE: string = process.env.CLIENT_SESSIONS_FILE || "client_sessions.json";
export default class ClientSessionManager implements SessionManager {
sessionId: number;
sessions: Client[];
private readonly logger: any;
constructor() {
this.sessionId = 0;
this.sessions = [];
this.logger = new Logger("ClientSessionManager");
}
addSession(session: SmppSession): Promise<void> {
return new Promise<void>((resolve, reject) => {
this.sessions.push(session as Client);
resolve();
});
}
removeSession(session: SmppSession): Promise<void> {
return new Promise<void>((resolve, reject) => {
this.sessions = this.sessions.filter(s => s.getId() !== session.getId());
resolve();
});
}
// TODO: Make sure no url duplicates exist
createSession(url: string, username: string, password: string): Promise<SmppSession> {
return new Promise<SmppSession>((resolve, reject) => {
this.verifyUrl(url, reject);
this.verifyUsername(username, reject);
this.verifyPassword(password, reject);
let client = new Client(this.sessionId++, url, username, password);
this.addSession(client).then(() => {
resolve(client);
});
});
}
getSession(id: number): Promise<SmppSession> {
return new Promise<SmppSession>((resolve, reject) => {
let session: SmppSession | undefined = this.sessions.find(s => s.getId() === id);
if (session) {
resolve(session);
} else {
reject(`Session with id ${id} not found`);
}
});
}
getSessionByUrl(url: string): Promise<SmppSession> {
return new Promise<SmppSession>((resolve, reject) => {
let session: SmppSession | undefined = this.sessions.find(s => s.getUrl() === url);
if (session) {
resolve(session);
} else {
reject(`Session with url ${url} not found`);
}
});
}
serialize(): object {
return this.sessions.map((session: SmppSession) => {
return session.serialize();
});
}
setup(): void {
try {
let sessions: Buffer = fs.readFileSync(CLIENT_SESSIONS_FILE);
let loadedSessions: any[] = JSON.parse(String(sessions));
this.logger.log1(`Loaded ${sessions.length} clients from ${CLIENT_SESSIONS_FILE}...`);
loadedSessions.forEach(session => {
this.createSession(session.url, session.username, session.password).then((sessionObj: SmppSession) => {
sessionObj.setDefaultSingleJob(Job.deserialize(session.defaultSingleJob));
sessionObj.setDefaultMultipleJob(Job.deserialize(session.defaultMultipleJob));
});
});
} catch (e) {
this.logger.log1(`Error loading clients from ${CLIENT_SESSIONS_FILE}: ${e}`);
}
}
cleanup(): void {
this.logger.log1(`Saving clients to ${CLIENT_SESSIONS_FILE}...`);
fs.writeFileSync(CLIENT_SESSIONS_FILE, JSON.stringify(this.serialize(), null, 4));
}
private verifyUrl(url: string, reject: (reason?: any) => void) {
if (!url) {
let error = `Request to make a new client failed because of missing url.`;
this.logger.log1(error);
reject(error);
}
}
private verifyUsername(username: string, reject: (reason?: any) => void) {
if (!username) {
let error = `Request to make a new client failed because of missing username.`;
this.logger.log1(error);
reject(error);
}
}
private verifyPassword(password: string, reject: (reason?: any) => void) {
if (!password) {
let error = `Request to make a new client failed because of missing password.`;
this.logger.log1(error);
reject(error);
}
}
}

View File

@@ -1,5 +1,6 @@
const smpp = require("smpp"); const smpp = require("smpp");
// TODO: Implement on change event and propagate it to sessions
export class Job { export class Job {
pdu: any; pdu: any;
perSecond?: number; perSecond?: number;
@@ -15,6 +16,14 @@ export class Job {
return JSON.stringify(this); return JSON.stringify(this);
} }
static deserialize(serialized: any): Job {
if (!serialized.pdu.command) {
throw new Error("Invalid serialized job");
}
let pdu: any = new smpp.PDU(serialized.pdu.command, serialized.pdu);
return new Job(pdu, serialized.perSecond, serialized.count);
}
static createEmptySingle(): Job { static createEmptySingle(): Job {
return new Job({}); return new Job({});
} }

20
src/SessionManager.ts Normal file
View File

@@ -0,0 +1,20 @@
import {SmppSession} from "./SmppSession";
export default interface SessionManager {
sessions: SmppSession[];
sessionId: number;
addSession(session: SmppSession): Promise<void>;
removeSession(session: SmppSession): Promise<void>;
createSession(...args: any[]): Promise<SmppSession>;
getSession(id: number): Promise<SmppSession>;
serialize(): object;
cleanup(): void;
setup(): void;
}

View File

@@ -1,14 +1,28 @@
import {Job} from "./Job"; import {Job} from "./Job";
// TODO: Implement on change event and propagate it to sessions
// Do something like "onJobChange" here...
// Maybe even make it default
export interface SmppSession { export interface SmppSession {
username: string, username: string,
password: string, password: string,
defaultSingleJob: Job;
defaultMultipleJob: Job;
getDefaultSingleJob(): Job;
setDefaultSingleJob(job: Job): void;
getDefaultMultipleJob(): Job;
setDefaultMultipleJob(job: Job): void;
getId(): number;
sendPdu(pdu: object, force?: boolean): Promise<object>; sendPdu(pdu: object, force?: boolean): Promise<object>;
sendSingle(job: Job): Promise<object>; sendSingle(job: Job): Promise<object>;
sendSingleDefault(): Promise<object>;
sendMultiple(job: Job): Promise<void>; sendMultiple(job: Job): Promise<void>;
sendMultipleDefault(): Promise<void>;
cancelSendInterval(): void; cancelSendInterval(): void;
@@ -16,5 +30,5 @@ export interface SmppSession {
initialize(): void; initialize(): void;
serialize(): string; serialize(): object;
} }

File diff suppressed because it is too large Load Diff