-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
237 lines (223 loc) · 5.51 KB
/
index.ts
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
import { Elysia, t } from 'elysia';
import {
blockUser,
createUser,
userExists,
getUser,
userList,
getBlockedUsers,
} from './users';
import { getCurrentEpoch, createEpochRecord } from './epochs';
import {
claimPoints,
AssignResult,
epochTick,
getPoints,
processIntents,
registerIntent,
tallyAssignedPoints,
} from './points';
import { html } from '@elysiajs/html';
import { promises as fs } from 'fs';
import path from 'path';
/**
* Basic, trivial prototype to play with the points concept.
*
*/
const EPOCH_SECONDS = 4 * 60 * 60;
let currentEpoch = (await getCurrentEpoch()) ?? -1n;
if (currentEpoch < 0n) {
await createEpochRecord(0n);
currentEpoch = 0n;
}
const StringID = t.Object({
encodedId: t.String(),
});
const UserBody = t.Object({
optsIn: t.Optional(t.Boolean()),
});
const ClaimBody = t.Object({
index: t.Number(),
});
const app = new Elysia()
.use(html())
.get('/', async () => {
let htmlContent = '';
try {
const filePath = path.join(__dirname, '../html/index.html');
htmlContent = await fs.readFile(filePath, 'utf-8');
} catch (error) {
console.error('Error reading template file:', error);
}
return htmlContent;
})
.get('/user', ({ query }) => {
const { all } = query;
return userList(all === 'true');
})
.get(
'/user/:encodedId',
({ params: { encodedId }, error }) => {
const id = decodeURIComponent(encodedId);
const user = getUser(id);
if (!user) {
return error(404, 'User not found');
} else {
return user;
}
},
{
params: StringID,
}
)
.post(
'/user/:encodedId',
async ({ body, params: { encodedId }, error }) => {
try {
const id = decodeURIComponent(encodedId);
const { optsIn } = body ?? {};
return (await userExists(id))
? error(409, 'User already exists')
: await createUser(id, currentEpoch, optsIn ?? true);
} catch (e) {
return error(500, `Unknown exception`);
}
},
{
params: StringID,
body: t.Optional(UserBody),
}
)
.get('/block/:encodedId', async ({ params: { encodedId }, error }) => {
const blocker = decodeURIComponent(encodedId);
return !userExists(blocker)
? error(404, 'User not found')
: Array.from(await getBlockedUsers(blocker));
})
.put(
'/block/:encodedBlocker/:encodedBlockee',
({ params: { encodedBlocker, encodedBlockee }, error }) => {
const blocker = decodeURIComponent(encodedBlocker);
const blockee = decodeURIComponent(encodedBlockee);
return !userExists(blocker)
? error(404, 'Blocker not found')
: !userExists(blockee)
? error(404, 'Blockee not found')
: blockUser(blocker, blockee);
}
)
.get(
'/points/:encodedId/detail',
({ params: { encodedId }, error }) => {
const id = decodeURIComponent(encodedId);
const userPoints = getPoints(id);
if (!userPoints) {
return error(404, 'User not found or they have no points');
} else {
return userPoints;
}
},
{
params: StringID,
}
)
.get(
'/points/:encodedId/tally',
async ({ params: { encodedId }, error }) => {
const id = decodeURIComponent(encodedId);
const user = await getUser(id);
if (!user) {
return error(404, 'User not found');
}
const tally = await tallyAssignedPoints(id);
return {
own: user.ownPoints,
assigned: tally,
total: tally + user.ownPoints,
};
},
{
params: StringID,
}
)
.put(
'/points/transfer/:encodedFrom/:encodedTo/:points',
async ({ params: { encodedFrom, encodedTo, points }, error }) => {
try {
const from = decodeURIComponent(encodedFrom);
const to = decodeURIComponent(encodedTo);
const success = await registerIntent(
from,
to,
BigInt(points),
currentEpoch
);
if (!success) {
return error(400, `Could not register point assignment`);
}
return { success: true };
} catch (e) {
console.error(`Exception with points transfer: ${e}`);
return error(500, `Unknown exception`);
}
},
{
params: t.Object({
encodedFrom: t.String(),
encodedTo: t.String(),
points: t.Number(),
}),
}
)
.put(
'/points/claim/:encodedId',
async ({ params: { encodedId }, body, error }) => {
const id = decodeURIComponent(encodedId);
const { index } = body;
const result = await claimPoints(id, index, currentEpoch);
return result == AssignResult.Ok
? { success: true }
: error(400, `Invalid points claim: ${result}`);
},
{
params: StringID,
body: ClaimBody,
}
)
.get('/epoch', () => currentEpoch)
.post('/epoch/tick', async () => {
currentEpoch = ((await getCurrentEpoch()) ?? 0n) + 1n;
await epochTick(currentEpoch);
return currentEpoch;
})
.post('/echo', ({ body }) => body)
.listen(3000);
console.log(`Creating sample data...`);
const serverPath = `http://${app.server?.hostname}:${app.server?.port}`;
app.handle(new Request(`${serverPath}/user/morat`, { method: 'POST' }));
console.log(`🦊 Elysia is running at ${serverPath}`);
setInterval(() => {
console.log(`Ticking epoch...`);
app.handle(new Request(`${serverPath}/epoch/tick`, { method: 'POST' }));
}, EPOCH_SECONDS * 1000);
let itemCount = 0;
let loopTime = 0;
const pointAssignLoop = async () => {
try {
const start = Date.now();
const result = await processIntents(currentEpoch, 40);
const took = Date.now() - start;
if (result.length > 0) {
loopTime += took;
itemCount += result.length;
console.log(
`Took ${took}ms avg ${(loopTime / itemCount).toFixed(2)}ms per item`,
result
);
}
} catch (e) {
console.error(`Update loop error`, e);
}
setTimeout(pointAssignLoop, 5);
};
setTimeout(pointAssignLoop, 150);