/
on-update-contract.ts
182 lines (167 loc) · 5.43 KB
/
on-update-contract.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
import * as functions from 'firebase-functions'
import {
getContractSupabase,
getUser,
log,
processPaginated,
revalidateContractStaticProps,
} from 'shared/utils'
import { createCommentOrUpdatedContractNotification } from 'shared/create-notification'
import { Contract, CPMMMultiContract, MultiContract } from 'common/contract'
import * as admin from 'firebase-admin'
import { difference, isEqual, pick } from 'lodash'
import { secrets } from 'common/secrets'
import {
createSupabaseClient,
createSupabaseDirectClient,
} from 'shared/supabase/init'
import { upsertGroupEmbedding } from 'shared/helpers/embeddings'
import { addContractToFeed } from 'shared/create-feed'
import { DAY_MS } from 'common/util/time'
type AnyContract = Contract & CPMMMultiContract & MultiContract
const propsThatTriggerRevalidation: (keyof AnyContract)[] = [
// 'volume', // This DOES trigger revalidation, but is run in place-bet.ts
'question',
'closeTime',
'description',
'groupLinks',
'lastCommentTime',
'visibility',
'addAnswersMode',
'sort',
'coverImageUrl',
'isPolitics',
] as const
const propsThatTriggerUpdatedTime: (keyof AnyContract)[] = [
'question',
'description',
'closeTime',
'groupLinks',
'isResolved',
'isRanked',
'isSubsidized',
'visibility',
] as const
export const onUpdateContract = functions
.runWith({ secrets })
.firestore.document('contracts/{contractId}')
.onUpdate(async (change, context) => {
const contract = change.after.data() as Contract
const previousContract = change.before.data() as Contract
const { eventId } = context
const { closeTime, question, groupLinks } = contract
const db = createSupabaseClient()
const pg = createSupabaseDirectClient()
// Update group embeddings if group links changed
const previousGroupIds = (previousContract.groupLinks ?? []).map(
(gl) => gl.groupId
)
const currentGroupIds = (groupLinks ?? []).map((gl) => gl.groupId)
const onlyNewGroupIds = difference(currentGroupIds, previousGroupIds)
const differentGroupIds = onlyNewGroupIds.concat(
difference(previousGroupIds, currentGroupIds)
)
await Promise.all(
differentGroupIds.map(async (groupId) =>
upsertGroupEmbedding(pg, groupId)
)
)
// Adding a contract to a group is ~similar~ to creating a new contract in that group
if (
onlyNewGroupIds.length > 0 &&
contract.createdTime > Date.now() - 2 * DAY_MS &&
contract.visibility === 'public'
) {
const contractWithScore = await getContractSupabase(contract.id)
if (!contractWithScore) return
await addContractToFeed(
contractWithScore,
['contract_in_group_you_are_in'],
'new_contract',
[contractWithScore.creatorId],
{
idempotencyKey: contractWithScore.id + '_new_contract',
}
)
}
if (
(previousContract.closeTime !== closeTime ||
previousContract.question !== question) &&
!contract.isResolved
) {
await handleUpdatedCloseTime(previousContract, contract, eventId)
}
if (
!isEqual(
pick(previousContract, propsThatTriggerRevalidation),
pick(contract, propsThatTriggerRevalidation)
)
) {
// Check if replicated to supabase before revalidating contract.
const result = await db
.from('contracts')
.select('id')
.eq('id', contract.id)
.limit(1)
if (result.data && result.data.length > 0) {
log(`Revalidating contract ${contract.id}.`)
await revalidateContractStaticProps(contract)
}
}
if (previousContract.visibility !== contract.visibility) {
const newVisibility = contract.visibility as 'public' | 'unlisted'
await updateContractSubcollectionsVisibility(contract.id, newVisibility)
}
if (
!isEqual(
pick(previousContract, propsThatTriggerUpdatedTime),
pick(contract, propsThatTriggerUpdatedTime)
)
) {
log(`Updating lastUpdatedTime for contract ${contract.id}.`)
// mqp: ugly to do this update in the trigger but i was too lazy
// to fix all the random call sites
await firestore.collection('contracts').doc(contract.id).update({
lastUpdatedTime: Date.now(),
})
}
})
async function handleUpdatedCloseTime(
previousContract: Contract,
contract: Contract,
eventId: string
) {
const contractUpdater = await getUser(contract.creatorId)
if (!contractUpdater) throw new Error('Could not find contract updater')
let sourceText = ''
if (previousContract.closeTime !== contract.closeTime && contract.closeTime) {
sourceText = contract.closeTime.toString()
} else if (previousContract.question !== contract.question) {
sourceText = contract.question
}
await createCommentOrUpdatedContractNotification(
contract.id,
'contract',
'updated',
contractUpdater,
eventId,
sourceText,
contract
)
}
async function updateContractSubcollectionsVisibility(
contractId: string,
newVisibility: 'public' | 'unlisted'
) {
const contractRef = firestore.collection('contracts').doc(contractId)
const batchSize = 500
// Update bets' visibility
const betsRef = contractRef.collection('bets')
await processPaginated(betsRef, batchSize, (ts) => {
const updatePromises = ts.docs.map((doc) => {
return doc.ref.update({ visibility: newVisibility })
})
return Promise.all(updatePromises)
})
}
const firestore = admin.firestore()