-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrata.py
More file actions
202 lines (155 loc) · 5.75 KB
/
Copy pathstrata.py
File metadata and controls
202 lines (155 loc) · 5.75 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
import time
import os
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
from starlette.exceptions import HTTPException
from sqlalchemy import create_engine, Column, Integer, String, Float, ForeignKey, select
from sqlalchemy.orm import Session, declarative_base
DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite:///strata.db")
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
Base = declarative_base()
class Period(Base):
__tablename__ = "periods"
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
path = Column(String, unique=True, nullable=False)
start = Column(Float, nullable=False)
end = Column(Float, nullable=True)
parent_id = Column(Integer, ForeignKey("periods.id"), nullable=True)
Base.metadata.create_all(engine)
def get_db():
return Session(engine)
def _end_active_descendants(db, period, now):
children = db.execute(
select(Period).where(Period.parent_id == period.id, Period.end.is_(None))
).scalars().all()
for child in children:
_end_active_descendants(db, child, now)
child.end = now
async def handle_get(request):
path = request.path_params.get("path", "").rstrip("/")
with get_db() as db:
if not path:
roots = db.execute(
select(Period).where(Period.parent_id.is_(None))
).scalars().all()
return JSONResponse([r.name for r in roots])
period = db.execute(
select(Period).where(Period.path == path)
).scalar_one_or_none()
if period is None:
raise HTTPException(404, "Period not found")
children = db.execute(
select(Period).where(Period.parent_id == period.id)
).scalars().all()
return JSONResponse({
"start": int(period.start),
"end": int(period.end) if period.end is not None else None,
"children": [c.name for c in children],
})
def ensure_parent(db, parent_path, now):
parent = db.execute(
select(Period).where(Period.path == parent_path)
).scalar_one_or_none()
if parent is not None:
if parent.end is not None:
raise HTTPException(400, f"Ancestor {parent_path} has already ended")
return parent
parts = parent_path.split("/")
name = parts[-1]
ancestor_path = "/".join(parts[:-1]) if len(parts) > 1 else None
grandparent = None
if ancestor_path:
grandparent = ensure_parent(db, ancestor_path, now)
if grandparent:
active_sibling = _find_active_sibling(db, grandparent)
if active_sibling is not None:
_end_active_descendants(db, active_sibling, now)
active_sibling.end = now
parent = Period(
name=name,
path=parent_path,
start=now,
parent_id=grandparent.id if grandparent else None,
)
db.add(parent)
return parent
def _find_active_sibling(db, parent_period):
db.flush()
return db.execute(
select(Period).where(
Period.parent_id == parent_period.id,
Period.end.is_(None),
)
).scalar_one_or_none()
async def handle_put(request):
path = request.path_params.get("path", "").rstrip("/")
if not path:
raise HTTPException(400, "Path must not be empty")
parts = path.split("/")
name = parts[-1]
parent_path = "/".join(parts[:-1]) if len(parts) > 1 else None
now = time.time()
with get_db() as db:
existing = db.execute(
select(Period).where(Period.path == path)
).scalar_one_or_none()
if existing is not None:
if existing.end is not None:
raise HTTPException(400, "Period has already ended")
children = db.execute(
select(Period).where(Period.parent_id == existing.id)
).scalars().all()
return JSONResponse({
"start": int(existing.start),
"end": None,
"children": [c.name for c in children],
})
parent = None
if parent_path:
parent = ensure_parent(db, parent_path, now)
if parent:
active_sibling = _find_active_sibling(db, parent)
if active_sibling is not None and active_sibling.path != path:
_end_active_descendants(db, active_sibling, now)
active_sibling.end = now
period = Period(
name=name,
path=path,
start=now,
parent_id=parent.id if parent else None,
)
db.add(period)
db.commit()
return JSONResponse({
"start": int(period.start),
"end": None,
"children": [],
}, status_code=201)
async def handle_delete(request):
path = request.path_params.get("path", "").rstrip("/")
if not path:
raise HTTPException(400, "Path must not be empty")
now = time.time()
with get_db() as db:
period = db.execute(
select(Period).where(Period.path == path)
).scalar_one_or_none()
if period is None:
raise HTTPException(404, "Period not found")
if period.end is not None:
raise HTTPException(400, "Period already ended")
_end_active_descendants(db, period, now)
period.end = now
db.commit()
return JSONResponse({"status": "ok"})
routes = [
Route("/{path:path}", endpoint=handle_get, methods=["GET"]),
Route("/{path:path}", endpoint=handle_put, methods=["PUT"]),
Route("/{path:path}", endpoint=handle_delete, methods=["DELETE"]),
]
app = Starlette(routes=routes)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)