-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
178 lines (152 loc) · 5.24 KB
/
app.js
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
// see https://github.com/mu-semtech/mu-javascript-template for more info
import { app, errorHandler, uuid } from 'mu';
import bodyParser from 'body-parser';
// TODO: Ensure messages are cleared when clients don't connect.
// TODO: On connecting, check that the session-id has not changed for the given tab identifier
const clientMessageMap = {};
const clientAliveTimestamps = {};
const idSessionMap = {};
const clientConnectionTimeout = 5 * 60 * 1000;
const cleanupInterval = 30 * 1000;
const LOG_CLEANUP = true;
const LOG_CONNECTIONS = false;
// Internal endpoint for internal testing
app.post('/push', function (req, res) {
const id = req.query["id"];
const message = req.body;
if( clientMessageMap[id] ) {
clientMessageMap[id].push(message);
res
.status(204)
.send();
} else {
res
.status(404)
.send({"message": `client ${id} is unknown`});
}
});
// Clients receive an id when they connect
app.post('/connect', function (req, res) {
const id = `http://services.semantic.works/push-messages/client-id/${uuid()}`;
if( LOG_CONNECTIONS ) {
console.log({ idSessionMap, clientMessageMap, clientAliveTimestamps });
console.log(req.get("mu-session-id"));
}
clientAliveTimestamps[id] = new Date();
clientMessageMap[id] = [];
idSessionMap[id] = req.get("mu-session-id");
res
.status(200)
.send({ type: 'push-update-connections', id, attributes: { id } });
});
// Well behaving clients may disconnect
app.post('/disconnect', function (req, res) {
const id = req.query["id"];
if (idSessionMap[id] && idSessionMap[id] !== req.get("mu-session-id")) {
res
.status(403)
.send({ error: "Forbidden" });
} else {
delete idSessionMap[id];
delete clientMessageMap[id];
delete clientAliveTimestamps[id];
res
.status(204)
.send();
}
});
app.post('/delta', bodyParser.json({ limit: '50mb' }), function(req, res) {
try {
// we only care about inserts
if( LOG_CONNECTIONS )
console.log(`Got body ${JSON.stringify(req.body)}`);
for (const changeSet of req.body) {
const inserts = changeSet.inserts;
const predicateMapping = {
"http://mu.semte.ch/vocabularies/push/messageJSON": "message",
"http://mu.semte.ch/vocabularies/push/target": "target",
"http://mu.semte.ch/vocabularies/push/kind": "kind"
};
// find inserts with the desired type
const resourcesWithType = inserts.filter(
({ predicate, object }) => predicate.value == "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"
&& object.type == "uri"
&& object.value == "http://mu.semte.ch/vocabularies/push/JSONPushMessage"
);
// capture message content
const infoObjects = {};
resourcesWithType.forEach(({ subject: { value } }) => infoObjects[value] = {});
for (const { subject, predicate, object } of inserts) {
if (infoObjects[subject.value]) {
const key = predicateMapping[predicate.value];
if (key) infoObjects[subject.value][key] = object.value;
}
}
// add messages
for (const messageUri in infoObjects) {
const { message, target, kind } = infoObjects[messageUri];
if( LOG_CONNECTIONS )
console.log(`Handling ${JSON.stringify({ message, target, kind })}`);
if (clientMessageMap[target]) {
if( LOG_CONNECTIONS )
console.log(`Setting ${JSON.stringify({ message, target, kind })}`);
clientMessageMap[target].push({ body: JSON.parse(message), kind });
} else {
if( LOG_CONNECTIONS )
console.log(`Target ${target} not found`);
}
}
console.log({
inserts: JSON.stringify(inserts),
predicateMapping: JSON.stringify(predicateMapping),
resourcesWithType: JSON.stringify(resourcesWithType),
infoObjects: JSON.stringify(infoObjects)
});
}
res
.status(200)
.send({ message: "Processed" });
} catch (e) {
console.error(`Something went wrong!`);
console.error(e);
}
});
app.get('/pull', function (req, res) {
const id = req.query["id"];
if( LOG_CONNECTIONS ) {
console.log(JSON.stringify({ idSessionMap, clientMessageMap, clientAliveTimestamps }));
console.log(req.get("mu-session-id"));
}
if (idSessionMap[id] && idSessionMap[id] == req.get("mu-session-id")) {
const messages = clientMessageMap[id];
clientAliveTimestamps[id] = new Date();
clientMessageMap[id] = [];
res
.status(200)
.send({ messages });
} else if (!idSessionMap[id]) {
if( LOG_CLEANUP )
console.log('no session for id ${id}');
res
.status(410)
.send({ error: "Session expired" });
} else {
res
.status(403)
.send({ error: "Forbidden" });
}
});
setInterval(() => {
let ids = Object.keys(clientAliveTimestamps);
let minLastSeenDate = new Date((new Date()).getTime() - clientConnectionTimeout);
for (const id of ids) {
if (clientAliveTimestamps[id] < minLastSeenDate) {
if( LOG_CLEANUP )
console.log(`Cleaning up id: ${id} mu-session-id: ${idSessionMap[id]} due to inactivity.`);
delete clientAliveTimestamps[id];
delete idSessionMap[id];
delete clientMessageMap[id];
}
}
}, cleanupInterval);
app.use(errorHandler);