forked from parse-community/parse-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStatusHandler.js
More file actions
283 lines (253 loc) · 7.5 KB
/
Copy pathStatusHandler.js
File metadata and controls
283 lines (253 loc) · 7.5 KB
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
import { md5Hash, newObjectId } from './cryptoUtils';
import { logger } from './logger';
import _ from 'lodash';
const PUSH_STATUS_COLLECTION = '_PushStatus';
const JOB_STATUS_COLLECTION = '_JobStatus';
const PUSH_COLLECTION = '_Push';
export function flatten(array) {
return array.reduce((memo, element) => {
if (Array.isArray(element)) {
memo = memo.concat(flatten(element));
} else {
memo = memo.concat(element);
}
return memo;
}, []);
}
function statusHandler(className, database) {
let lastPromise = Promise.resolve();
function create(object) {
lastPromise = lastPromise.then(() => {
return database.create(className, object).then(() => {
return Promise.resolve(object);
});
});
return lastPromise;
}
function update(where, object) {
lastPromise = lastPromise.then(() => {
return database.update(className, where, object);
});
return lastPromise;
}
function createPush(object) {
return database.create(PUSH_COLLECTION, object).then(() => {
return Promise.resolve(object);
});
}
function updatePush(query, updateFields) {
return database.update(PUSH_COLLECTION, query, updateFields);
}
function insertPushes(pushStatusObjectId, installations) {
// Insert a Push object for each installation we're pushing to
let now = new Date();
let promises = _.map(installations, installation => {
let pushObjectId = newObjectId();
let push = {
objectId: pushObjectId,
createdAt: now,
updatedAt: now,
deviceToken: installation.deviceToken,
installation: {
__type: 'Pointer',
className: "_Installation",
objectId: installation.objectId,
},
pushStatus: pushStatusObjectId
};
return createPush(push);
});
return Promise.all(promises);
}
function updatePushes(pushStatusObjectId, installations, results) {
let now = new Date();
let resultsByDeviceToken = _.keyBy(results, r => r.device.deviceToken);
// Update the push record for each installation
let promises = _.map(installations, installation => {
let deviceToken = installation.deviceToken;
let result = null;
// Handle different failure scenarios
if (!deviceToken) {
result = { transmitted: false, error: 'No deviceToken found on installation' }
} else if (deviceToken in resultsByDeviceToken) {
result = resultsByDeviceToken[deviceToken];
} else {
result = { transmitted: false, error: 'No result from adapter' }
}
// Find the record to update
let query = {
pushStatus: pushStatusObjectId,
installation: {
__type: 'Pointer',
className: "_Installation",
objectId: installation.objectId,
}
};
let updateFields = {
result: result,
updatedAt: now
};
return updatePush(query, updateFields);
});
return Promise.all(promises);
}
return Object.freeze({
create,
update,
createPush,
updatePush,
insertPushes,
updatePushes
})
}
export function jobStatusHandler(config) {
let jobStatus;
let objectId = newObjectId();
let database = config.database;
let lastPromise = Promise.resolve();
let handler = statusHandler(JOB_STATUS_COLLECTION, database);
let setRunning = function(jobName, params) {
let now = new Date();
jobStatus = {
objectId,
jobName,
params,
status: 'running',
source: 'api',
createdAt: now,
// lockdown!
ACL: {}
}
return handler.create(jobStatus);
}
let setMessage = function(message) {
if (!message || typeof message !== 'string') {
return Promise.resolve();
}
return handler.update({ objectId }, { message });
}
let setSucceeded = function(message) {
return setFinalStatus('succeeded', message);
}
let setFailed = function(message) {
return setFinalStatus('failed', message);
}
let setFinalStatus = function(status, message = undefined) {
let finishedAt = new Date();
let update = { status, finishedAt };
if (message && typeof message === 'string') {
update.message = message;
}
return handler.update({ objectId }, update);
}
return Object.freeze({
setRunning,
setSucceeded,
setMessage,
setFailed
});
}
export function pushStatusHandler(config) {
let pushStatus;
let objectId = newObjectId();
let database = config.database;
let handler = statusHandler(PUSH_STATUS_COLLECTION, database);
let setInitial = function(body = {}, where, options = {source: 'rest'}) {
let now = new Date();
let data = body.data || {};
let payloadString = JSON.stringify(data);
let pushHash;
if (typeof data.alert === 'string') {
pushHash = md5Hash(data.alert);
} else if (typeof data.alert === 'object') {
pushHash = md5Hash(JSON.stringify(data.alert));
} else {
pushHash = 'd41d8cd98f00b204e9800998ecf8427e';
}
let object = {
objectId,
createdAt: now,
pushTime: now.toISOString(),
query: JSON.stringify(where),
payload: payloadString,
source: options.source,
title: options.title,
expiry: body.expiration_time,
status: "pending",
numSent: 0,
pushHash,
// lockdown!
ACL: {}
}
return handler.create(object).then(() => {
pushStatus = {
objectId
};
return Promise.resolve(pushStatus);
});
}
let setRunning = function(installations) {
logger.verbose('sending push to %d installations', installations.length);
return handler.update({status:"pending", objectId: objectId},
{status: "running", updatedAt: new Date() }).then((result) => {
return handler.insertPushes(objectId, installations).then(() => {
return result;
});
});
}
let complete = function(data) {
let results = data.results;
let installations = data.installations;
let update = {
status: 'succeeded',
updatedAt: new Date(),
numSent: 0,
numFailed: 0,
};
if (Array.isArray(results)) {
results = flatten(results);
results.reduce((memo, result) => {
// Cannot handle that
if (!result || !result.device || !result.device.deviceType) {
return memo;
}
let deviceType = result.device.deviceType;
if (result.transmitted)
{
memo.numSent++;
memo.sentPerType = memo.sentPerType || {};
memo.sentPerType[deviceType] = memo.sentPerType[deviceType] || 0;
memo.sentPerType[deviceType]++;
} else {
memo.numFailed++;
memo.failedPerType = memo.failedPerType || {};
memo.failedPerType[deviceType] = memo.failedPerType[deviceType] || 0;
memo.failedPerType[deviceType]++;
}
return memo;
}, update);
}
logger.verbose('sent push! %d success, %d failures', update.numSent, update.numFailed);
return handler.update({status:"running", objectId }, update).then((result) => {
return handler.updatePushes(objectId, installations, results).then(() => {
return result;
});
});
}
let fail = function(err) {
let update = {
errorMessage: JSON.stringify(err),
status: 'failed',
updatedAt: new Date()
}
logger.info('warning: error while sending push', err);
return handler.update({ objectId }, update);
}
return Object.freeze({
objectId,
setInitial,
setRunning,
complete,
fail
})
}