-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
245 lines (231 loc) · 7.31 KB
/
index.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
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
import fetch from "node-fetch"
import { config } from "dotenv"
import knex from 'knex'
import { Logtail } from "@logtail/node";
// Set up dotenv for environment variables
config({ path: '.env' });
// Set up logging
const LOGTAIL_TOKEN = process.env.LOGTAIL_TOKEN
const logtail = new Logtail(LOGTAIL_TOKEN);
// All other env vars
const STARRY_BACKEND = process.env.STARRY_BACKEND
const DB_HOSTIP = process.env.DB_HOSTIP
const PORT = process.env.PORT
const DB_HOSTPORT = process.env.DB_HOSTPORT
const DB_NAME = process.env.DB_NAME
const DB_USER = process.env.DB_USER
const DB_PASS = process.env.DB_PASS
const DB_TABLENAME_MEMBERS = process.env.DB_TABLENAME_MEMBERS
const DB_TABLENAME_SYNC = process.env.DB_TABLENAME_SYNC
const DB_TABLENAME_SYNC_LOGS = process.env.DB_TABLENAME_SYNC_LOGS
const TIMEOUT = process.env.TIMEOUT
// Set up guild(s) to update
const GUILDS_TO_UPDATE = process.env.GUILDS_TO_UPDATE
// This one needs to be mutable
let guildsToUpdate = JSON.parse(GUILDS_TO_UPDATE)
// This will keep track of how many members were updated
let membersPerGuild = {}
const enableSSL = !['localhost', '127.0.0.1'].includes(DB_HOSTIP);
const db = knex({
client: 'pg',
connection: {
user: DB_USER,
password: DB_PASS,
database: DB_NAME,
host: DB_HOSTIP,
port: DB_HOSTPORT,
ssl: enableSSL
},
pool: {
max: 5,
min: 5,
acquireTimeoutMillis: 60000,
createTimeoutMillis: 30000,
idleTimeoutMillis: 600000,
createRetryIntervalMillis: 200,
}
});
// Makes POST request to backend to sync a Discord member from a guild
const updateGuildUser = async (guildId, discordUserId) => {
// Log intention
try {
await logtail.info('calling token rule info', {
event: 'track-user-flow',
time_relative: 'before',
predicate: 'calling /token-rule-info',
data: {
guildId,
discordUserId
}
})
} catch (e) {
console.warn('Logtail is messing up again.', e)
}
// Make request to update this member from this guild
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ discordUserId, guildId })
}
const res = await fetch(`${STARRY_BACKEND}:${PORT}/token-rule-info`, requestOptions)
switch (res.status) {
case 200:
// Expected behavior
try {
await logtail.info('calling token rule info', {
event: 'track-user-flow',
time_relative: 'after',
predicate: 'calling /token-rule-info',
data: {
guildId,
discordUserId,
res: {
status: res.status,
statusText: res.statusText,
json: await res.json()
}
}
})
} catch (e) {
console.warn('Logtail is messing up again.', e)
}
break
case 400:
try {
await logtail.error('400 status', {
event: 'received 400 status',
res: {
status: res.status,
statusText: res.statusText,
discordUserId,
guildId
}
})
} catch (e) {
console.warn('Logtail is messing up again.', e)
}
break;
default:
// Alert of oddness
try {
await logtail.error('unexpected status', {
event: 'received unexpected status',
res: {
status: res.status,
statusText: res.statusText,
}
})
} catch (e) {
console.warn('Logtail is messing up again.', e)
}
}
}
// Update or insert database row for this guild,
// indicating it is beginning a sync
const setBeginUpdate = async (guildId) => {
const rowExists = await db(DB_TABLENAME_SYNC)
.where('discord_guild_id', guildId)
.count('discord_guild_id')
// Should be 0 or 1, depending on whether it's been added
const numRows = parseInt(rowExists[0]['count'])
if (numRows === 0) {
// Insert
await db(DB_TABLENAME_SYNC)
.insert({
discord_guild_id: guildId,
began_update: 'now()',
finished_update: null
})
} else {
await db(DB_TABLENAME_SYNC)
.update({
began_update: 'now()',
finished_update: null
})
.where('discord_guild_id', guildId)
}
}
// Add more permanent row outside of logging
const AddSyncLog = async (guildId, memberCount) => {
await db(DB_TABLENAME_SYNC_LOGS)
.insert({
discord_guild_id: guildId,
members_updated: memberCount
})
}
// Entrypoint
// This is a recursive function based on a recommendation here:
// https://developer.mozilla.org/en-US/docs/Web/API/setInterval#ensure_that_execution_duration_is_shorter_than_interval_frequency
const cronMe = async (guildId, members = null) => {
setTimeout(async () => {
if (members === null) {
// Load members directly from database
// (this happens the first time a guild begins an update)
members = await db(DB_TABLENAME_MEMBERS)
.where('discord_guild_id', guildId)
.whereNotNull('cosmos_address')
.select(['discord_account_id', 'cosmos_address']).distinct('discord_account_id')
// Keep track of how many members we'll have synced
membersPerGuild[guildId] = members.length
await setBeginUpdate(guildId)
}
// If there are no members to update for this guild
if (members.length === 0) {
// Update
await db(DB_TABLENAME_SYNC)
.update({finished_update: 'now()'})
.where('discord_guild_id', guildId)
// Increase the times_updated by 1
.increment('times_updated', 1)
// Recurse if there are more guilds to update
const guildMemberCount = membersPerGuild[guildId]
if (guildsToUpdate.length) {
try {
await logtail.info(`Finished updating guild ${guildId} with ${guildMemberCount} members.`)
} catch (e) {
console.warn('Logtail is messing up again.', e)
}
await AddSyncLog(guildId, guildMemberCount)
cronMe(guildsToUpdate.pop())
} else {
try {
await logtail.info(`Finished updating the final guild: ${guildId} with ${guildMemberCount} members.`)
} catch (e) {
console.warn('Logtail is messing up again.', e)
}
await AddSyncLog(guildId, guildMemberCount)
process.exit()
}
} else {
const member = members.pop()
try {
// Call endpoint that will update user's roles
const discordAccountId = member['discord_account_id']
try {
await logtail.info(`doing something with member ${discordAccountId} for guild ${guildId}`)
} catch (e) {
console.warn('Logtail is messing up again.', e)
}
await updateGuildUser(guildId, discordAccountId)
} catch (e) {
try {
await logtail.error('Failure updating guild user', {
event: 'calling updateGuildUser',
res: {
error: JSON.stringify(e),
}
})
} catch (e) {
console.warn('Logtail is messing up again.', e)
}
}
cronMe(guildId, members)
}
}, TIMEOUT);
}
if (guildsToUpdate && guildsToUpdate.length) {
cronMe(guildsToUpdate.pop()).then(() => logtail.info('Beginning…'))
} else {
console.log('No guilds to update, please add the proper environment variable to ' +
'look like this:\nGUILDS_TO_UPDATE=["123821047347744788","808885156490133514"]')
}