-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwebsocket.ts
164 lines (144 loc) · 4.61 KB
/
websocket.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
// Copyright 2020 Privacy Research, LLC
import { ApiGatewayManagementApi } from 'aws-sdk'
import {
Handler,
APIGatewayProxyEvent,
APIGatewayEventRequestContext,
DynamoDBStreamEvent,
AttributeValue,
} from 'aws-lambda'
import { addSubscription, listConnectionIDsForSub, removeSubscriptionsForConnections } from './subscription-table'
import { storeMessage, getMessagesAfter } from './message-table'
interface RealtimeAPIGatewayEventRequestContext extends APIGatewayEventRequestContext {
connectionId: string
connectedAt: number
}
export interface WebsocketAPIGatewayEvent extends APIGatewayProxyEvent {
requestContext: RealtimeAPIGatewayEventRequestContext
}
export const connect: Handler = async (event: WebsocketAPIGatewayEvent) => {
console.log(event)
const { connectionId } = event.requestContext
return {
statusCode: 200,
body: connectionId,
}
}
export const subscribe: Handler = async (event: WebsocketAPIGatewayEvent) => {
console.log('subscribe', event)
const message = JSON.parse(event.body)
const { connectionId } = event.requestContext
for (const sub of message.channels) {
await addSubscription(sub, connectionId)
}
return {
statusCode: 200,
body: connectionId,
}
}
export const handleDefault: Handler = async (event: WebsocketAPIGatewayEvent) => {
console.log('$default route, unexpected data', { event })
return {
statusCode: 400,
body: 'Unrecognized websocket action',
}
}
export const acceptMessage: Handler = async (event: WebsocketAPIGatewayEvent) => {
// POST to all address connectionIDs
let body
try {
body = JSON.parse(event.body)
} catch (err) {
console.log('Invalid message format', event.body)
return {
statusCode: 200,
body: '',
}
}
// store the message in the database
const { address } = body
const item = await storeMessage(address, event.body)
return {
statusCode: 200,
body: JSON.stringify(item),
}
}
export const onMessageInsert: Handler = async (event: DynamoDBStreamEvent) => {
for (const record of event.Records) {
// POST to all address connectionIDs
if (record.eventName === 'REMOVE') {
continue
}
let message: { [x: string]: AttributeValue }
try {
message = record.dynamodb.NewImage
} catch (err) {
console.log('Invalid message format', record)
return {
statusCode: 200,
body: '',
}
}
const address = message.address.S
const msg = message.message.S
await sendMessage(address, msg)
}
return {
statusCode: 200,
body: '',
}
}
const sendMessage = async (address: string, msg: string) => {
const connectionIDs = await listConnectionIDsForSub(address)
for (const connectionID of connectionIDs) {
try {
await send(connectionID, msg)
} catch (e) {
console.error(`Error sending to connection id. Removing connection.`, { connectionID, e })
await removeSubscriptionsForConnections(connectionID)
}
}
}
export const getRecentMessages: Handler = async (event: WebsocketAPIGatewayEvent) => {
const { connectionId } = event.requestContext
let body: { address: string }
try {
body = JSON.parse(event.body)
} catch (err) {
console.log('Invalid message format', event.body)
return {
statusCode: 200,
body: '',
}
}
const { address } = body
const items = await getMessagesAfter(address, Date.now() - 24 * 60 * 60 * 1000)
console.log({ items })
for (const item of items) {
await send(connectionId, item)
}
return {
statusCode: 200,
body: '',
}
}
export const disconnect: Handler = async (event: WebsocketAPIGatewayEvent) => {
const { connectionId } = event.requestContext
await removeSubscriptionsForConnections(connectionId)
return {
statusCode: 200,
}
}
function apiGatewayEndpoint() {
const apiID = process.env[`WEBSOCKETS_API`]
const region = process.env[`REGION`]
const stage = process.env[`STAGE`]
return `https://${apiID}.execute-api.${region}.amazonaws.com/${stage}`
}
const send = async (connectionID: string, message: string) => {
const apigwManagementApi = new ApiGatewayManagementApi({
apiVersion: '2018-11-29',
endpoint: apiGatewayEndpoint(),
})
await apigwManagementApi.postToConnection({ ConnectionId: connectionID, Data: message }).promise()
}