This repository has been archived by the owner on Jun 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sample.html
348 lines (284 loc) · 10.4 KB
/
sample.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Pub-Sub demo</title>
<link
href="https://fonts.googleapis.com/css2?family=Overpass+Mono&display=swap"
rel="stylesheet"
/>
<link
rel="stylesheet"
href="//cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.css"
/>
<link
rel="stylesheet"
href="//cdnjs.cloudflare.com/ajax/libs/milligram/1.3.0/milligram.css"
/>
<style rel="stylesheet">
#console {
font-family: "Roboto Mono", monospace !important;
}
</style>
</head>
<body class="container" style="max-width: none">
<div class="row">
<div class="column column-40" style="padding: 20px; height: 100vh">
<h1>Pub Sub Demo</h1>
<textarea
rows="10"
style="resize: vertical; height: 200px"
placeholder="Enter your message here..."
id="messageBox"
></textarea>
<div style="display: flex">
<div style="flex-grow: 1">
<button onclick="init()" class="button-outline" id="startButton">
Start
</button>
<button
onclick="closeConnection()"
class="button-clear"
disabled
id="closeButton"
>
Close
</button>
</div>
<button onclick="publish()" id="publishButton" disabled>
Publish
</button>
</div>
</div>
<div
id="console"
class="column column-60"
style="padding: 20px; height: 100vh; background: black; overflow: auto"
></div>
</div>
</body>
<script type="text/javascript">
/* ------------------- API MIDDLEWARE TO MANAGE API CALLS ------------------- */
class APIRequest {
_headers = {
Accept: "application/json",
"Content-Type": "application/json",
};
constructor(url) {
this._url = url;
}
login(email, password) {
const endpoint = "/_open/auth";
const self = this;
return new Promise(function (resolve, reject) {
self
.req(endpoint, {
body: { email, password },
method: "POST",
})
.then(({ jwt, ...data }) => {
self._headers.authorization = `bearer ${jwt}`;
resolve(data);
})
.catch(reject);
});
}
_handleResponse(response, resolve, reject) {
if (response.ok) {
resolve(response.json());
} else {
reject(response);
}
}
req(endpoint, { body, ...options } = {}) {
const self = this;
return new Promise(function (resolve, reject) {
fetch(self._url + endpoint, {
headers: self._headers,
body: body ? JSON.stringify(body) : undefined,
...options,
}).then((response) =>
self._handleResponse(response, resolve, reject)
);
});
}
}
/* ---------------------------- PUB-SUB TUTORIAL ---------------------------- */
const EMAIL = "xxxx@macrometa.io";
const PASSWORD = "xxxx";
const FEDERATION_NAME = "xxxx.eng.macrometa.io";
const FEDERATION_URL = `https://${FEDERATION_NAME}`;
const STREAM_NAME = "api_tutorial_streams1";
const CONSUMER_NAME = "api_tutorial_streams_consumer1";
const IS_GLOBAL = true;
/* ------------------------------ UI References ----------------------------- */
const consoleElement = document.getElementById("console");
const input = document.getElementById("messageBox");
const startButton = document.getElementById("startButton");
const closeButton = document.getElementById("closeButton");
const publishButton = document.getElementById("publishButton");
/* ---------------------------- Global Variables ---------------------------- */
var consumer;
var producer;
/* ---------------------------- Helpers Functions --------------------------- */
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function getTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
return h + ":" + m + ":" + s;
}
function print(msg) {
var node = document.createElement("small");
node.style =
"display:block; font-weight:400;color:white;word-break:break-all;position:relative;padding-left:100px";
var span = document.createElement("span");
span.style = "position:absolute;left:0";
var time = document.createTextNode(`> ${getTime()} : `);
span.appendChild(time);
var textnode = document.createTextNode(`${msg}`);
node.appendChild(span);
node.appendChild(textnode);
consoleElement.appendChild(node);
consoleElement.scrollTop = consoleElement.scrollHeight;
}
function toggleUIButtons(
skip = { start: false, publish: false, close: false }
) {
if (!skip.start) startButton.disabled = !startButton.disabled;
if (!skip.publish) publishButton.disabled = !publishButton.disabled;
if (!skip.close) closeButton.disabled = !closeButton.disabled;
if (!skip.publish) input.disabled = !input.disabled;
}
/* -------------------------------------------------------------------------- */
const connection = new APIRequest(FEDERATION_URL);
const init = async function () {
try {
toggleUIButtons({ publish: true, close: true });
/* -------------------- Login (nemo@nautilus.com/xxxxxx) -------------------- */
const { tenant } = await connection.login(EMAIL, PASSWORD);
print("Login Successfully using");
/* ------------------------------ Create Stream ----------------------------- */
const stream = await connection.req(
`/_fabric/_system/streams/${STREAM_NAME}?global=${IS_GLOBAL}`,
{
body: { name: STREAM_NAME },
method: "POST",
}
);
print("STREAM CREATED SUCCESSFULLY");
/* ----------------- Publish and Subscribe message to stream ---------------- */
const region = IS_GLOBAL ? "c8global" : "c8local";
const streamName = `${region}s.${STREAM_NAME}`;
// FOR gdn use the below snippet
// const url = IS_GLOBAL
// ? FEDERATION_NAME;
// : `api-${streamApp.streamApps[0].regions[0]}.prod.macrometa.io`
// #URL_REVIEW : If you have changed your FEDERATION_NAME please review the below code and make required changes to the URL
const url = IS_GLOBAL
? FEDERATION_NAME
: `api-${streamApp.streamApps[0].regions[0]}.macrometa.io`;
const consumerUrl = `wss://${url}/_ws/ws/v2/consumer/persistent/${tenant}/${region}._system/${streamName}/${CONSUMER_NAME}`;
const producerUrl = `wss://${url}/_ws/ws/v2/producer/persistent/${tenant}/${region}._system/${streamName}`;
/* -------------------------- Initalizing Consumer -------------------------- */
const initConsumer = () => {
return new Promise((resolve) => {
consumer = new WebSocket(consumerUrl);
consumer.onopen = function () {
print("Consumer is open now for " + streamName);
resolve();
};
consumer.onerror = function () {
print(
"Failed to establish Consumer connection for " + streamName
);
};
consumer.onclose = function () {
print("Closed Consumer connection for " + streamName);
};
consumer.onmessage = function (message) {
var receivedMsg = message.data && JSON.parse(message.data);
print(
"------------------ Consumer Message Received -----------------"
);
print(atob(receivedMsg.payload));
print(
"--------------------------------------------------------------"
);
const ackMsg = { messageId: receivedMsg.messageId };
consumer.send(JSON.stringify(ackMsg));
};
});
};
/* -------------------------- Initalizing Producer -------------------------- */
const initProducer = () => {
producer = new WebSocket(producerUrl);
producer.onopen = function () {
print("Producer is open now for " + streamName);
};
producer.onclose = function (e) {
print("Closed Producer connection for " + streamName);
};
producer.onerror = function (e) {
print("Failed to establish Producer connection for " + streamName);
};
};
initConsumer().then(() => {
initProducer();
toggleUIButtons({ start: true });
print(
"--------------------------------------------------------------"
);
print(
"----------YOU CAN NOW START PUBLISHING YOUR MESSAGES----------"
);
print(
"--------------------------------------------------------------"
);
});
} catch (e) {
console.error(e);
}
};
function publish() {
try {
const value = input.value.trim().replace(/(\r\n|\n|\r)/gm, "");
let msgToSend = value;
if (value[0] === "{" && value.slice(-1) === "}") {
msgToSend = JSON.stringify(JSON.parse(input.value));
}
producer.send(JSON.stringify({ payload: btoa(msgToSend) }));
print(`Sending message.... : ${msgToSend}`);
print(`Producer message sent`);
} catch (e) {
print(e);
}
}
async function closeConnection() {
toggleUIButtons();
consumer.close();
print("CONSUMER CLOSING...");
producer.close();
print("PRODUCER CLOSING...");
await new Promise((resolve) => setTimeout(resolve, 5000));
/* ------------------------ Unsubscribe from stream. ------------------------ */
await connection.req(
`/_fabric/_system/_api/streams/unsubscribe/${CONSUMER_NAME}`,
{
method: "POST",
}
);
print(`${CONSUMER_NAME} UNSUBSCRIBED SUCCESSFULLY`);
}
</script>
</html>