-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_proxy.py
More file actions
236 lines (207 loc) · 9.54 KB
/
Copy pathsimple_proxy.py
File metadata and controls
236 lines (207 loc) · 9.54 KB
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
#!/usr/bin/env python3
"""
Simple proxy server that adds organization/team endpoints to the existing API
"""
import asyncio
import asyncpg
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
import urllib.parse
import requests
import uuid
from datetime import datetime
# Configuration
DATABASE_URL = "postgresql://postgres:J7hplO7vKnbUsKDAsxpe4t9C0@localhost:5434/ai_context"
ORIGINAL_API = "http://localhost:8000"
PORT = 8003
class ProxyHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path.startswith('/organizations'):
asyncio.run(self.handle_organizations_get())
elif self.path.startswith('/teams'):
asyncio.run(self.handle_teams_get())
else:
self.proxy_request()
def do_POST(self):
if self.path == '/organizations':
asyncio.run(self.handle_organizations_post())
elif self.path == '/teams':
asyncio.run(self.handle_teams_post())
else:
self.proxy_request()
def do_OPTIONS(self):
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
self.end_headers()
async def handle_organizations_get(self):
try:
conn = await asyncpg.connect(DATABASE_URL)
try:
rows = await conn.fetch("""
SELECT
id::text, name, description, settings,
created_at::text, updated_at::text
FROM organizations
ORDER BY created_at DESC
""")
organizations = []
for row in rows:
organizations.append({
'id': row['id'],
'name': row['name'],
'description': row['description'],
'settings': row['settings'] or {},
'created_at': row['created_at'],
'updated_at': row['updated_at']
})
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(json.dumps(organizations).encode())
finally:
await conn.close()
except Exception as e:
self.send_error(500, str(e))
async def handle_organizations_post(self):
try:
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
data = json.loads(post_data.decode('utf-8'))
conn = await asyncpg.connect(DATABASE_URL)
try:
org_id = str(uuid.uuid4())
row = await conn.fetchrow("""
INSERT INTO organizations (id, name, description, settings)
VALUES ($1, $2, $3, $4)
RETURNING
id::text, name, description, settings,
created_at::text, updated_at::text
""", org_id, data['name'], data.get('description'), json.dumps(data.get('settings', {})))
result = {
'id': row['id'],
'name': row['name'],
'description': row['description'],
'settings': row['settings'] or {},
'created_at': row['created_at'],
'updated_at': row['updated_at']
}
self.send_response(201)
self.send_header('Content-Type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(json.dumps(result).encode())
finally:
await conn.close()
except Exception as e:
self.send_error(500, str(e))
async def handle_teams_get(self):
try:
parsed_path = urllib.parse.urlparse(self.path)
query_params = urllib.parse.parse_qs(parsed_path.query)
organization_id = query_params.get('organization_id', [None])[0]
conn = await asyncpg.connect(DATABASE_URL)
try:
if organization_id:
rows = await conn.fetch("""
SELECT
id::text, organization_id::text, name, description,
team_type, settings, created_at::text, updated_at::text
FROM teams
WHERE organization_id = $1
ORDER BY created_at DESC
""", organization_id)
else:
rows = await conn.fetch("""
SELECT
id::text, organization_id::text, name, description,
team_type, settings, created_at::text, updated_at::text
FROM teams
ORDER BY created_at DESC
""")
teams = []
for row in rows:
teams.append({
'id': row['id'],
'organization_id': row['organization_id'],
'name': row['name'],
'description': row['description'],
'team_type': row['team_type'],
'settings': row['settings'] or {},
'created_at': row['created_at'],
'updated_at': row['updated_at']
})
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(json.dumps(teams).encode())
finally:
await conn.close()
except Exception as e:
self.send_error(500, str(e))
async def handle_teams_post(self):
try:
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
data = json.loads(post_data.decode('utf-8'))
conn = await asyncpg.connect(DATABASE_URL)
try:
team_id = str(uuid.uuid4())
row = await conn.fetchrow("""
INSERT INTO teams (id, organization_id, name, description, team_type, settings)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING
id::text, organization_id::text, name, description,
team_type, settings, created_at::text, updated_at::text
""", team_id, data['organization_id'], data['name'],
data.get('description'), data.get('team_type', 'general'), json.dumps(data.get('settings', {})))
result = {
'id': row['id'],
'organization_id': row['organization_id'],
'name': row['name'],
'description': row['description'],
'team_type': row['team_type'],
'settings': row['settings'] or {},
'created_at': row['created_at'],
'updated_at': row['updated_at']
}
self.send_response(201)
self.send_header('Content-Type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(json.dumps(result).encode())
finally:
await conn.close()
except Exception as e:
self.send_error(500, str(e))
def proxy_request(self):
try:
# Proxy to original API
url = f"{ORIGINAL_API}{self.path}"
if self.command == 'GET':
response = requests.get(url)
elif self.command == 'POST':
content_length = int(self.headers.get('Content-Length', 0))
post_data = self.rfile.read(content_length) if content_length > 0 else b''
response = requests.post(url, data=post_data,
headers={'Content-Type': self.headers.get('Content-Type', 'application/json')})
else:
self.send_error(405, "Method not allowed")
return
self.send_response(response.status_code)
self.send_header('Access-Control-Allow-Origin', '*')
for header, value in response.headers.items():
if header.lower() not in ['transfer-encoding', 'connection']:
self.send_header(header, value)
self.end_headers()
self.wfile.write(response.content)
except Exception as e:
self.send_error(500, str(e))
if __name__ == "__main__":
server = HTTPServer(('localhost', PORT), ProxyHandler)
print(f"Proxy server running on http://localhost:{PORT}")
print(f"Proxying to {ORIGINAL_API} with hierarchy endpoints")
server.serve_forever()