-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.py
235 lines (183 loc) · 6.69 KB
/
handler.py
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
import base64
import datetime
import json
import logging
from urllib import parse
import boto3
import flask
from dateutil import parser
from neo4j import GraphDatabase
from retrying import retry
ssmc = boto3.client('ssm')
app = flask.Flask('feedback form')
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def get_ssm_param(key):
resp = ssmc.get_parameter(
Name=key,
WithDecryption=True
)
return resp['Parameter']['Value']
def str2bool(v):
return v.lower() in ("yes", "true", "t", "1")
host_port = get_ssm_param('com.neo4j.labs.feedback.dbhostport')
user = get_ssm_param('com.neo4j.labs.feedback.dbuser')
password = get_ssm_param('com.neo4j.labs.feedback.dbpassword')
db_driver = GraphDatabase.driver(f"bolt+routing://{host_port}", auth=(user, password), max_retry_time=15)
post_feedback_query = """
MATCH (project:Project {name: $project})
MERGE (page:Page {uri: $page})
MERGE (page)-[:PROJECT]->(project)
CREATE (feedback:Feedback)
SET feedback += $params, feedback.timestamp = datetime()
CREATE (page)-[:HAS_FEEDBACK]->(feedback)
"""
@retry(stop_max_attempt_number=5, wait_random_max=1000)
def post_feedback(params):
with db_driver.session() as session:
result = session.run(post_feedback_query, params)
print(result.summary().counters)
return True
def determine_project(page):
if "/docs/labs/neo4j-streams" in page:
return "neo4j-streams"
if "grandstack.io" in page:
return "GRANDstack"
return "apoc"
def feedback(request, context):
print("request:", request, "context:", context)
form_data = parse.parse_qsl(request["body"])
params = {key: value for key, value in form_data}
page = params["url"]
params["helpful"] = str2bool(params["helpful"])
headers = request["headers"]
params["userAgent"] = headers.get("User-Agent")
params["referer"] = headers.get("Referer")
if "project" in params:
project = params["project"]
else:
project = determine_project(page)
print(page, params)
post_feedback({"params": params, "page": page, "project": project})
return {
"statusCode": 200,
"body": json.dumps({"message": "Foo"}),
"headers": {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': True,
}
}
def feedback_api(event, context):
path_parameters = event.get("pathParameters")
if not path_parameters:
return {
"statusCode": 404
}
project = path_parameters.get("project").replace("@graphapps-", "@graphapps/")
qs = event.get("multiValueQueryStringParameters")
if qs and qs.get("date"):
now = parser.parse(qs["date"][0])
else:
now = datetime.datetime.now().replace(day=1)
logger.info(f"Retrieving feedback for {now}")
with db_driver.session() as session:
params = {"year": now.year, "month": now.month, "project": project}
result = session.run("""
MATCH (feedback:Feedback)<-[:HAS_FEEDBACK]-(page)-[:PROJECT]->(:Project {name: $project})
WHERE datetime({year:$year, month:$month+1}) > feedback.timestamp >= datetime({year:$year, month:$month })
RETURN feedback, page
ORDER BY feedback.timestamp DESC
""", params)
rows = [{"helpful": row["feedback"]["helpful"],
"information": row["feedback"]["moreInformation"],
"reason": row["feedback"]["reason"],
"uri": row["page"]["uri"],
"date": row["feedback"]["timestamp"].to_native().strftime("%d %b %Y")
}
for row in result]
response = {
"statusCode": 200,
"body": json.dumps(rows),
"headers": {
"Content-Type": "application/json",
'Access-Control-Allow-Origin': '*'
}
}
return response
def page_api(event, context):
logger.info(f"event: {event}, context: {context}")
path_parameters = event.get("pathParameters")
if not path_parameters:
return {
"statusCode": 404
}
encoded_page = path_parameters.get("id")
page = base64.b64decode(encoded_page).decode("utf-8")
logger.info(f"page: {page}")
with db_driver.session() as session:
params = {"page": page}
result = session.run("""
MATCH (page {uri: $page})
RETURN page, [(page)-[:HAS_FEEDBACK]->(feedback) | feedback] AS feedback
""", params)
rows = [{"uri": row["page"]["uri"],
"feedback": [{
"helpful": entry["helpful"],
"information": entry["moreInformation"],
"reason": entry["reason"],
"date": entry["timestamp"].to_native().strftime("%d %b %Y")
}
for entry in row["feedback"]
]}
for row in result]
response = {
"statusCode": 200,
"body": json.dumps(rows),
"headers": {
"Content-Type": "application/json",
'Access-Control-Allow-Origin': '*'
}
}
return response
def fire_api(event, context):
path_parameters = event.get("pathParameters")
if not path_parameters:
return {
"statusCode": 404
}
project = path_parameters.get("project").replace("@graphapps-", "@graphapps/")
with db_driver.session() as session:
result = session.run("""
MATCH (project:Project {name: $project})<-[:PROJECT]-(page:Page)-[:HAS_FEEDBACK]->(feedback)
WITH page, collect(feedback) AS allFeedback
WITH page,
size([f in allFeedback WHERE f.helpful]) AS helpful,
size([f in allFeedback WHERE not(f.helpful)]) AS notHelpful
WHERE notHelpful > 0
WITH page, helpful, notHelpful,
helpful + notHelpful * 1.0 AS n
WITH page, helpful, notHelpful, n,
1.281551565545 AS z,
(notHelpful * 1.0) / n AS p
WITH page, helpful, notHelpful, n, z, p,
p + (1.0/(2*n))*(z*z) AS left,
z*(sqrt((p*(1-p)/n) + (z*z)/(4*n*n))) AS right,
1+(1/n*z*z) AS under
RETURN page, notHelpful, helpful, (left-right) / under AS unhelpfulness
ORDER BY unhelpfulness desc
""", {"project": project})
rows = [{"uri": row["page"]["uri"],
"helpful": row["helpful"],
"notHelpful": row["notHelpful"],
"unhelpfulness": row["unhelpfulness"]
}
for row in result]
response = {
"statusCode": 200,
"body": json.dumps(rows),
"headers": {
"Content-Type": "application/json",
'Access-Control-Allow-Origin': '*'
}
}
return response