forked from ker0olos/fable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
getInventory.ts
313 lines (253 loc) · 7.2 KB
/
getInventory.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
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
/// <reference lib="deno.unstable" />
import '#filter-boolean';
import { ulid } from 'ulid';
import {
charactersByInventoryPrefix,
guildsByDiscordId,
inventoriesByInstance,
inventoriesByUser,
usersByDiscordId,
} from './indices.ts';
import db, { kv } from './mod.ts';
import utils from '../src/utils.ts';
import { KvError } from '../src/errors.ts';
import type * as Schema from './schema.ts';
export const MAX_PULLS = 5;
export const MAX_NEW_PULLS = 10;
export const RECHARGE_MINS = 30;
export async function getUser(userId: string): Promise<Schema.User> {
const response = await db.getValue<Schema.User>(usersByDiscordId(userId));
if (response) {
return response;
}
const newUser: Schema.User = {
_id: ulid(),
id: userId,
inventories: [],
};
const insert = await kv.atomic()
.check({ key: usersByDiscordId(userId), versionstamp: null })
//
.set(['users', newUser._id], newUser)
.set(usersByDiscordId(userId), newUser)
//
.commit();
if (insert.ok) {
return newUser;
}
throw new KvError('failed to insert user');
}
export async function getGuild(guildId: string): Promise<Schema.Guild> {
const response = await db.getValue<Schema.Guild>(guildsByDiscordId(guildId));
if (response) {
return response;
}
const newGuild: Schema.Guild = {
_id: ulid(),
id: guildId,
instances: [],
};
const insert = await kv.atomic()
.check({ key: guildsByDiscordId(guildId), versionstamp: null })
//
.set(['guilds', newGuild._id], newGuild)
.set(guildsByDiscordId(guildId), newGuild)
//
.commit();
if (insert.ok) {
return newGuild;
}
throw new KvError('failed to insert guild');
}
export async function getInstance(
guild: Schema.Guild,
): Promise<Schema.Instance> {
if (guild.instances.length) {
const response = await db.getValue<Schema.Instance>([
'instances',
guild.instances[0],
]);
if (response) {
return response;
}
}
const newInstance: Schema.Instance = {
_id: ulid(),
main: true,
guild: guild._id,
inventories: [],
packs: [],
};
guild.instances = [newInstance._id];
const insert = await kv.atomic()
//
.set(['instances', newInstance._id], newInstance)
//
.set(['guilds', guild._id], guild)
.set(guildsByDiscordId(guild.id), guild)
//
.commit();
if (insert.ok) {
return newInstance;
}
throw new KvError('failed to insert instance');
}
export async function getInstancePacks(
instance: Schema.Instance,
): Promise<Schema.Pack[]> {
const ids = instance.packs.map(({ pack }) => ['packs', pack]);
const packs = (await db.getManyValues<Schema.Pack>(ids))
.filter(Boolean);
return packs;
}
export async function getInventory(
instance: Schema.Instance,
user: Schema.User,
): Promise<{
inventory: Schema.Inventory;
inventoryCheck: Deno.AtomicCheck;
}> {
const key = inventoriesByUser(instance._id, user._id);
const response = await db.getValueAndTimestamp<Schema.Inventory>(key);
if (response?.value) {
return {
inventory: response.value,
inventoryCheck: response,
};
}
const newInventory: Schema.Inventory = {
_id: ulid(),
availablePulls: MAX_NEW_PULLS,
instance: instance._id,
user: user._id,
};
instance.inventories.push(newInventory._id);
user.inventories.push(newInventory._id);
const insert = await kv.atomic()
.check({ key, versionstamp: null })
//
.set(['inventories', newInventory._id], newInventory)
.set(inventoriesByUser(instance._id, user._id), newInventory)
//
.set(['instances', instance._id], instance)
//
.set(['users', user._id], user)
.set(usersByDiscordId(user.id), user)
//
.commit();
if (insert.ok) {
return {
inventory: newInventory,
inventoryCheck: {
key,
versionstamp: (insert as Deno.KvCommitResult).versionstamp,
},
};
}
throw new KvError('failed to insert inventory');
}
export async function rechargePulls(
instance: Schema.Instance,
user: Schema.User,
commit = true,
): Promise<{
inventory: Schema.Inventory;
inventoryCheck: Deno.AtomicCheck;
}> {
let res = { ok: false }, retires = 0;
while (!res.ok && retires < 5) {
const { inventory, inventoryCheck } = await db.getInventory(
instance,
user,
);
const rechargeTimestamp = inventory.rechargeTimestamp
? new Date(inventory.rechargeTimestamp)
: new Date();
const currentPulls = inventory.availablePulls;
const newPulls = Math.max(
0,
Math.min(
MAX_PULLS - currentPulls,
Math.trunc(
utils.diffInMinutes(rechargeTimestamp, new Date()) / RECHARGE_MINS,
),
),
);
if (newPulls === currentPulls) {
return { inventory, inventoryCheck };
}
const rechargedPulls = currentPulls + newPulls;
inventory.availablePulls = Math.min(99, rechargedPulls);
if (rechargedPulls >= MAX_PULLS) {
inventory.rechargeTimestamp = undefined;
} else {
rechargeTimestamp.setMinutes(
rechargeTimestamp.getMinutes() + (newPulls * RECHARGE_MINS),
);
inventory.rechargeTimestamp = rechargeTimestamp.toISOString();
}
if (!commit) {
return { inventory, inventoryCheck };
}
res = await kv.atomic()
.check(inventoryCheck)
//
.set(['inventories', inventory._id], inventory)
.set(inventoriesByUser(inventory.instance, inventory._id), inventory)
//
.commit();
if (res.ok) {
return {
inventory,
inventoryCheck: {
key: inventoryCheck.key,
// TODO doesn't work
// as workaround we avoid committing new changes
// when we need to use the version stamp after recharging pulls
// addCharacter() & addPulls()
versionstamp: (res as Deno.KvCommitResult).versionstamp,
},
};
}
retires += 1;
}
throw new KvError('failed to update inventory');
}
export async function getInstanceInventories(
instance: Schema.Instance,
): Promise<[Schema.Inventory, Schema.User][]> {
const inventories = await db.getValues<Schema.Inventory>(
{ prefix: inventoriesByInstance(instance._id) },
);
const users = await db.getManyValues<Schema.User>(
inventories.map(({ user }) => ['users', user]),
);
// deno-lint-ignore no-non-null-assertion
return inventories.map((inventory, i) => [inventory, users[i]!]);
}
export async function getUserCharacters(
inventory: Schema.Inventory,
): Promise<Deno.KvEntry<Schema.Character>[]> {
const characters = await db.getValuesAndTimestamps<Schema.Character>(
{ prefix: charactersByInventoryPrefix(inventory._id) },
);
return characters;
}
export async function getUserParty(
inventory: Schema.Inventory,
): Promise<Schema.Party> {
const response = await db.getManyValues<Schema.Character>([
['characters', inventory.party?.member1 ?? ''],
['characters', inventory.party?.member2 ?? ''],
['characters', inventory.party?.member3 ?? ''],
['characters', inventory.party?.member4 ?? ''],
['characters', inventory.party?.member5 ?? ''],
]);
return {
member1: response[0],
member2: response[1],
member3: response[2],
member4: response[3],
member5: response[4],
};
}