|
@@ -9,6 +9,7 @@ import { EventMessage, FisMessage } from '../interface/transport.interface';
|
|
import { WrappedMessage } from './message.ordering';
|
|
import { WrappedMessage } from './message.ordering';
|
|
import axios, { AxiosError, AxiosResponse } from 'axios';
|
|
import axios, { AxiosError, AxiosResponse } from 'axios';
|
|
import ConsoleLogger from './log.utils';
|
|
import ConsoleLogger from './log.utils';
|
|
|
|
+import path from 'path';
|
|
const console: ConsoleLogger = new ConsoleLogger(`HttpUtils`, ['transport'])
|
|
const console: ConsoleLogger = new ConsoleLogger(`HttpUtils`, ['transport'])
|
|
|
|
|
|
export function startHttpServer(port: number): Observable<ConnectedHttpClient> {
|
|
export function startHttpServer(port: number): Observable<ConnectedHttpClient> {
|
|
@@ -41,7 +42,7 @@ export async function initiateClientToServer(url: string, event: Subject<Transpo
|
|
checkOwnClientInfo(receiverProfileInfo.id).then((profile: ConnectedHttpServer) => {
|
|
checkOwnClientInfo(receiverProfileInfo.id).then((profile: ConnectedHttpServer) => {
|
|
receiverProfileInfo!.id = profile.id
|
|
receiverProfileInfo!.id = profile.id
|
|
// console.log({ message: 'jsonfile', details: profile })
|
|
// console.log({ message: 'jsonfile', details: profile })
|
|
- postAxiosRequest(url + '/profile', { name: 'Old Client', message: profile }).then((profileInfo: { name: string, message: { id: string } }) => {
|
|
|
|
|
|
+ postAxiosRequest(url + 'profile', { name: 'Old Client', message: profile }).then((profileInfo: { name: string, message: { id: string } }) => {
|
|
console.log({ message: `Acknowledged as previous client. Id: ${profileInfo.message.id}` })
|
|
console.log({ message: `Acknowledged as previous client. Id: ${profileInfo.message.id}` })
|
|
event.next({
|
|
event.next({
|
|
id: uuidv4(),
|
|
id: uuidv4(),
|
|
@@ -66,7 +67,7 @@ export async function initiateClientToServer(url: string, event: Subject<Transpo
|
|
})
|
|
})
|
|
}).catch((error) => {
|
|
}).catch((error) => {
|
|
console.error(error)
|
|
console.error(error)
|
|
- postAxiosRequest(url + '/profile', { name: 'New Client', data: null }).then((profileInfo: { name: string, message: any }) => {
|
|
|
|
|
|
+ postAxiosRequest(url + 'profile', { name: 'New Client', data: null }).then((profileInfo: { name: string, message: any }) => {
|
|
updateProfileAndPublishEvent((receiverProfileInfo as ConnectedHttpServer), profileInfo, event, connectedHttpServers).then((receiverProfileInfo) => {
|
|
updateProfileAndPublishEvent((receiverProfileInfo as ConnectedHttpServer), profileInfo, event, connectedHttpServers).then((receiverProfileInfo) => {
|
|
resolve(receiverProfileInfo)
|
|
resolve(receiverProfileInfo)
|
|
})
|
|
})
|
|
@@ -76,7 +77,8 @@ export async function initiateClientToServer(url: string, event: Subject<Transpo
|
|
reject({ error: error, objRef: receiverProfileInfo })
|
|
reject({ error: error, objRef: receiverProfileInfo })
|
|
})
|
|
})
|
|
} else {
|
|
} else {
|
|
- postAxiosRequest(url + '/profile', { name: 'New Client', data: null }).then((profileInfo: { name: string, message: any }) => {
|
|
|
|
|
|
+ console.log({ message: `Is New profile, Connecting with server` })
|
|
|
|
+ postAxiosRequest(url + 'profile', { name: 'New Client', data: null }).then((profileInfo: { name: string, message: any }) => {
|
|
updateProfileAndPublishEvent(receiverProfileInfo, profileInfo, event, connectedHttpServers).then((receiverProfileInfo) => {
|
|
updateProfileAndPublishEvent(receiverProfileInfo, profileInfo, event, connectedHttpServers).then((receiverProfileInfo) => {
|
|
resolve(receiverProfileInfo)
|
|
resolve(receiverProfileInfo)
|
|
})
|
|
})
|
|
@@ -91,6 +93,7 @@ export async function initiateClientToServer(url: string, event: Subject<Transpo
|
|
// For client usage
|
|
// For client usage
|
|
export function handleClientHttpConnection(url: string, server: ConnectedHttpServer): Observable<TransportEvent> {
|
|
export function handleClientHttpConnection(url: string, server: ConnectedHttpServer): Observable<TransportEvent> {
|
|
return new Observable((eventNotification: Observer<TransportEvent>) => {
|
|
return new Observable((eventNotification: Observer<TransportEvent>) => {
|
|
|
|
+ console.log({ message: `Long Poll Attempt for ${server.id}` })
|
|
server.connectionState.next('ONLINE');
|
|
server.connectionState.next('ONLINE');
|
|
let active: boolean = true; // Flag to control polling lifecycle
|
|
let active: boolean = true; // Flag to control polling lifecycle
|
|
|
|
|
|
@@ -98,10 +101,10 @@ export function handleClientHttpConnection(url: string, server: ConnectedHttpSer
|
|
while (active) {
|
|
while (active) {
|
|
try {
|
|
try {
|
|
// Axios request with timeout
|
|
// Axios request with timeout
|
|
- // const response = await axios.get(`${url}/poll`); // removing the timeout temporarily.
|
|
|
|
- const response = await axios.get(`${url}/poll`, {
|
|
|
|
- timeout: 3000, // 10s timeout this one will trigger error. That's why it keeps on throwing error
|
|
|
|
- });
|
|
|
|
|
|
+ const response = await axios.get(`${url}poll`); // removing the timeout temporarily.
|
|
|
|
+ // const response = await axios.get(`${url}response`, {
|
|
|
|
+ // timeout: 3000, // 10s timeout this one will trigger error. That's why it keeps on throwing error
|
|
|
|
+ // });
|
|
|
|
|
|
if (response.status === 200) {
|
|
if (response.status === 200) {
|
|
const data = response.data;
|
|
const data = response.data;
|
|
@@ -114,7 +117,7 @@ export function handleClientHttpConnection(url: string, server: ConnectedHttpSer
|
|
dateCreated: new Date(),
|
|
dateCreated: new Date(),
|
|
transport: Transport.Http,
|
|
transport: Transport.Http,
|
|
target: server.id,
|
|
target: server.id,
|
|
- payload: data.message,
|
|
|
|
|
|
+ payload: data,
|
|
} as TransportMessage,
|
|
} as TransportMessage,
|
|
});
|
|
});
|
|
} else if (response.status === 204) {
|
|
} else if (response.status === 204) {
|
|
@@ -184,7 +187,7 @@ async function updateProfileAndPublishEvent(receiverProfileInfo: ConnectedHttpSe
|
|
return new Promise((resolve, reject) => {
|
|
return new Promise((resolve, reject) => {
|
|
console.log({ message: `Assigned client Name: ${(profile.message as ConnectedHttpServer).id}` })
|
|
console.log({ message: `Assigned client Name: ${(profile.message as ConnectedHttpServer).id}` })
|
|
receiverProfileInfo = profile.message as ConnectedHttpServer
|
|
receiverProfileInfo = profile.message as ConnectedHttpServer
|
|
- writeFile(profile.message).then(() => {
|
|
|
|
|
|
+ writeFile(profile.message as ConnectedHttpServer, (profile.message as ConnectedHttpServer).id).then(() => {
|
|
event.next({
|
|
event.next({
|
|
id: uuidv4(),
|
|
id: uuidv4(),
|
|
event: `New Server`,
|
|
event: `New Server`,
|
|
@@ -217,7 +220,7 @@ async function updateProfileAndPublishEvent(receiverProfileInfo: ConnectedHttpSe
|
|
})
|
|
})
|
|
}
|
|
}
|
|
|
|
|
|
-async function postAxiosRequest(url: string, data: any): Promise<any> {
|
|
|
|
|
|
+export async function postAxiosRequest(url: string, data: any): Promise<any> {
|
|
return new Promise(async (resolve, reject) => {
|
|
return new Promise(async (resolve, reject) => {
|
|
try {
|
|
try {
|
|
const response: AxiosResponse<any> = await axios.post(url, data);
|
|
const response: AxiosResponse<any> = await axios.post(url, data);
|
|
@@ -314,16 +317,15 @@ function handleProfile(app: Express, data: { name: `Old Client` | `New Client`,
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
-
|
|
|
|
-
|
|
|
|
}
|
|
}
|
|
|
|
|
|
-export async function checkIfClientExists(id: string, filePath: string = 'clients.json'): Promise<ConnectedHttpClient> {
|
|
|
|
|
|
+export async function checkIfClientExists(id: string): Promise<ConnectedHttpClient> {
|
|
return new Promise((resolve, reject) => {
|
|
return new Promise((resolve, reject) => {
|
|
try {
|
|
try {
|
|
// Check if the file exists
|
|
// Check if the file exists
|
|
|
|
+ let filePath = process.env.FolderPath as string + 'clients.json'
|
|
if (!fs.existsSync(filePath)) {
|
|
if (!fs.existsSync(filePath)) {
|
|
- console.log({ message: "File does not exist." });
|
|
|
|
|
|
+ console.log({ message: `File does not exist.` })
|
|
reject('File does not exist');
|
|
reject('File does not exist');
|
|
}
|
|
}
|
|
|
|
|
|
@@ -331,28 +333,26 @@ export async function checkIfClientExists(id: string, filePath: string = 'client
|
|
const fileContent = fs.readFileSync(filePath, 'utf-8');
|
|
const fileContent = fs.readFileSync(filePath, 'utf-8');
|
|
const data: any[] = JSON.parse(fileContent);
|
|
const data: any[] = JSON.parse(fileContent);
|
|
|
|
|
|
- // Check if an object with the given id exists
|
|
|
|
|
|
+ // Check if an details with the given id exists
|
|
let obj = data.find(entry => entry.id === id);
|
|
let obj = data.find(entry => entry.id === id);
|
|
|
|
|
|
if (obj) {
|
|
if (obj) {
|
|
- console.log({ message: `Client with ID ${id} exists.` });
|
|
|
|
|
|
+ console.log({ message: `Client with ID ${id} exists.` })
|
|
} else {
|
|
} else {
|
|
- console.log({ message: `Client with ID ${id} does not exist.` });
|
|
|
|
|
|
+ console.log({ message: `Client with ID ${id} does not exist.` })
|
|
}
|
|
}
|
|
-
|
|
|
|
resolve(obj);
|
|
resolve(obj);
|
|
} catch (error) {
|
|
} catch (error) {
|
|
- console.error({ message: 'Error reading the file:', details: error });
|
|
|
|
reject(`Error reading the file`)
|
|
reject(`Error reading the file`)
|
|
}
|
|
}
|
|
})
|
|
})
|
|
}
|
|
}
|
|
|
|
|
|
/* For Internal Usage only. Temporary serve as a way for server to keep track of clients. To be replaced in the future with better alternatives. */
|
|
/* For Internal Usage only. Temporary serve as a way for server to keep track of clients. To be replaced in the future with better alternatives. */
|
|
-export function addClientToDB(entry: ConnectedHttpClient, filePath: string = 'clients.json'): void {
|
|
|
|
|
|
+export function addClientToDB(entry: ConnectedHttpClient): void {
|
|
try {
|
|
try {
|
|
let data: ConnectedHttpClient[] = [];
|
|
let data: ConnectedHttpClient[] = [];
|
|
-
|
|
|
|
|
|
+ let filePath = process.env.FolderPath as string + 'clients.json'
|
|
// Check if the file exists and load existing data
|
|
// Check if the file exists and load existing data
|
|
if (fs.existsSync(filePath)) {
|
|
if (fs.existsSync(filePath)) {
|
|
const fileContent = fs.readFileSync(filePath, 'utf-8');
|
|
const fileContent = fs.readFileSync(filePath, 'utf-8');
|
|
@@ -415,8 +415,8 @@ export function startListeningAndStreaming(app: Express, client: ConnectedHttpCl
|
|
const subscription = client.responseStream.asObservable().subscribe({
|
|
const subscription = client.responseStream.asObservable().subscribe({
|
|
next: (message: WrappedMessage) => {
|
|
next: (message: WrappedMessage) => {
|
|
if (!responseSent) {
|
|
if (!responseSent) {
|
|
- console.log({ message: `Sending data to client: ${JSON.stringify(message)}` });
|
|
|
|
- res.json({ message }); // Send the data to the client
|
|
|
|
|
|
+ console.log({ message: `Sending data ${message.thisMessageID} to client ${client.id}}` });
|
|
|
|
+ res.json(message); // Send the data to the client
|
|
responseSent = true; // Mark response as sent
|
|
responseSent = true; // Mark response as sent
|
|
subscription.unsubscribe(); // Unsubscribe to close this request
|
|
subscription.unsubscribe(); // Unsubscribe to close this request
|
|
}
|
|
}
|
|
@@ -477,7 +477,8 @@ export function startListeningAndStreaming(app: Express, client: ConnectedHttpCl
|
|
export async function checkOwnClientInfo(filename?: string): Promise<ConnectedHttpServer> {
|
|
export async function checkOwnClientInfo(filename?: string): Promise<ConnectedHttpServer> {
|
|
return new Promise((resolve, reject) => {
|
|
return new Promise((resolve, reject) => {
|
|
// Check if the file exists
|
|
// Check if the file exists
|
|
- if (fs.existsSync(`${filename}.json`)) {
|
|
|
|
|
|
+ let filePath = process.env.FolderPath as string
|
|
|
|
+ if (fs.existsSync(filePath + `${filename}.json`)) {
|
|
try {
|
|
try {
|
|
// Read the file contents
|
|
// Read the file contents
|
|
const fileData = fs.readFileSync(`${filename}.json`, 'utf8');
|
|
const fileData = fs.readFileSync(`${filename}.json`, 'utf8');
|
|
@@ -503,18 +504,31 @@ export async function checkOwnClientInfo(filename?: string): Promise<ConnectedHt
|
|
}
|
|
}
|
|
|
|
|
|
// Specifically to write receiver profile information
|
|
// Specifically to write receiver profile information
|
|
-export async function writeFile(data: { id: string }): Promise<boolean> {
|
|
|
|
|
|
+async function writeFile(data: ConnectedHttpServer, filename: string): Promise<boolean> {
|
|
return new Promise((resolve, reject) => {
|
|
return new Promise((resolve, reject) => {
|
|
|
|
+ // Ensure the folder exists
|
|
|
|
+ const folderPath = process.env.FolderPath as string
|
|
|
|
+ console.log({ message: folderPath })
|
|
|
|
+ // const folderPath = path.join(__dirname, folder);
|
|
|
|
+ if (!fs.existsSync(folderPath)) {
|
|
|
|
+ fs.mkdirSync(folderPath, { recursive: true }); // Create folder if it doesn't exist
|
|
|
|
+ } else {
|
|
|
|
+ console.log({ message: 'Folder already exist' })
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ // Construct the full file path (include the folder)
|
|
|
|
+ const filePath = path.join(folderPath, `${filename}.json`);
|
|
|
|
+
|
|
// Write JSON data to a file
|
|
// Write JSON data to a file
|
|
- fs.writeFile(`${data.id}.json`, JSON.stringify(data, null, 2), (err) => {
|
|
|
|
|
|
+ fs.writeFile(filePath, JSON.stringify(data, null, 2), (err) => {
|
|
if (err) {
|
|
if (err) {
|
|
- console.error({ message: 'Error writing file', details: err });
|
|
|
|
- reject(false)
|
|
|
|
|
|
+ console.log({ message: 'Error writing file', details: err });
|
|
|
|
+ reject(false);
|
|
} else {
|
|
} else {
|
|
- console.log({ message: 'File has been written' });
|
|
|
|
- resolve(true)
|
|
|
|
|
|
+ console.log({ message: 'File has been written', details: filePath });
|
|
|
|
+ resolve(true);
|
|
}
|
|
}
|
|
});
|
|
});
|
|
- })
|
|
|
|
|
|
+ });
|
|
}
|
|
}
|
|
|
|
|