-
Notifications
You must be signed in to change notification settings - Fork 0
/
store-account-event.ts
177 lines (170 loc) · 5.97 KB
/
store-account-event.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
import { AccountEvent } from "@bouzuya/tsukota-account-events";
import { App } from "firebase-admin/app";
import { FieldValue, Firestore, getFirestore } from "firebase-admin/firestore";
import * as functions from "firebase-functions";
import {
accountDocumentForQueryConverter,
accountEventDocumentConverter,
accountEventDocumentForQueryConverter,
accountEventStreamDocumentConverter,
userDocumentConverter,
} from "../schema";
export function buildStoreAccountEvent(
app: App,
region: string
): functions.HttpsFunction {
const db = getFirestore(app);
return functions
.region(region)
.https.onCall(async (data: unknown, context) => {
if (
typeof data !== "object" ||
data === null ||
!("event" in data) ||
!("last_event_id" in data)
)
throw new functions.https.HttpsError(
"invalid-argument",
// TODO: fix message
"invalid-argument"
);
const uid = context.auth?.uid;
if (uid === undefined)
throw new functions.https.HttpsError(
"unauthenticated",
// TODO: fix message
"unauthenticated"
);
const { event, last_event_id: lastEventId } = data;
if (lastEventId !== null && typeof lastEventId !== "string")
throw new functions.https.HttpsError(
"invalid-argument",
// TODO: fix message
"invalid-argument"
);
// TODO: check event format
if (typeof event !== "object" || event === null)
throw new functions.https.HttpsError(
"invalid-argument",
// TODO: fix message
"invalid-argument"
);
await storeAccountEvent(db, uid, lastEventId, event as AccountEvent);
return {};
});
}
function err(message: string): Promise<never> {
return Promise.reject(
// TODO: fix error code
new functions.https.HttpsError("invalid-argument", message)
);
}
function storeAccountEvent(
db: Firestore,
uid: string,
lastEventId: string | null,
event: AccountEvent
): Promise<void> {
return db.runTransaction(
async (transaction: FirebaseFirestore.Transaction): Promise<void> => {
const eventStreamDocRef = db
.collection("aggregates")
.doc("account")
.collection("event_streams")
.doc(event.accountId)
.withConverter(accountEventStreamDocumentConverter);
const eventDocRef = eventStreamDocRef
.collection("events")
.doc(event.id)
.withConverter(accountEventDocumentConverter);
const accountForQueryDocRef = db
.collection("accounts")
.doc(event.accountId)
.withConverter(accountDocumentForQueryConverter);
const accountEventForQueryDocRef = accountForQueryDocRef
.collection("events")
.doc(event.id)
.withConverter(accountEventDocumentForQueryConverter);
// create or update account
const esDocSnapshot = await transaction.get(eventStreamDocRef);
if (lastEventId === null) {
if (esDocSnapshot.exists)
return err(`account already exist (accountId: ${event.accountId})`);
if (event.type !== "accountCreated")
return err(
`event type is not accountCreated (accountId: ${event.accountId})`
);
transaction.create(eventStreamDocRef, {
id: event.accountId,
lastEventId: event.id,
owners: event.owners,
protocolVersion: event.protocolVersion,
updatedAt: event.at,
});
transaction.create(accountForQueryDocRef, {
deletedAt: null,
id: event.accountId,
name: event.name,
owners: event.owners,
});
} else {
const data = esDocSnapshot.data();
// not found
if (data === undefined)
return err(`account does not exist (accountId: ${event.accountId})`);
// forbidden
if (data.owners.indexOf(uid) === -1)
return err(
`account is not owned by the user (accountId: ${event.accountId}, uid: ${uid})`
);
// conflict
if (data.lastEventId !== lastEventId)
return err(
`account already updated (accountId: ${event.accountId}, expected: ${lastEventId}, actual: ${data.lastEventId})`
);
// bad request (invalid protocol version)
if (event.protocolVersion < data.protocolVersion)
return err(
`invalid protocol version (accountId: ${event.accountId}, expected: ${data.protocolVersion}, actual: ${event.protocolVersion})`
);
// bad request (invalid event timestamp)
if (event.at <= data.updatedAt)
return err(
`invalid event timestamp (accountId: ${event.accountId}, expected: ${data.updatedAt}, actual: ${event.at})`
);
transaction.update(
eventStreamDocRef,
{
lastEventId: event.id,
...(event.type === "accountUpdated" ? { name: event.name } : {}),
protocolVersion: event.protocolVersion,
updatedAt: event.at,
},
{ lastUpdateTime: esDocSnapshot.updateTime }
);
transaction.update(accountForQueryDocRef, {
id: event.accountId,
...(event.type === "accountDeleted" ? { deletedAt: event.at } : {}),
...(event.type === "accountUpdated" ? { name: event.name } : {}),
...(event.type === "accountCreated" ? { owners: event.owners } : {}),
});
}
// create event
transaction.create(eventDocRef, event);
transaction.create(accountEventForQueryDocRef, event);
// update the `accounts` field of the `users/{uid}`
if (event.type === "accountCreated") {
const userRef = db
.collection("users")
.doc(uid)
.withConverter(userDocumentConverter);
transaction.update(userRef, {
id: uid,
account_ids: FieldValue.arrayUnion(event.accountId),
});
}
return Promise.resolve();
},
{ maxAttempts: 1 }
);
}