Skip to content

Commit

Permalink
API: fix naming and meaning of entity vs. entity type
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidB137 committed Aug 10, 2023
1 parent 1ff0682 commit 14b1e9f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 39 deletions.
58 changes: 28 additions & 30 deletions dp3/api/routers/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,27 +20,27 @@
from dp3.common.task import DataPointTask


async def check_entity(entity: str):
"""Middleware to check entity existence"""
if entity not in MODEL_SPEC.entities:
raise RequestValidationError(["path", "entity"], f"Entity '{entity}' doesn't exist")
return entity
async def check_etype(etype: str):
"""Middleware to check entity type existence"""
if etype not in MODEL_SPEC.entities:
raise RequestValidationError(["path", "etype"], f"Entity type '{etype}' doesn't exist")
return etype


router = APIRouter(dependencies=[Depends(check_entity)])
router = APIRouter(dependencies=[Depends(check_etype)])


@router.get("/{entity}")
async def list_entity_eids(
entity: str, skip: NonNegativeInt = 0, limit: PositiveInt = 20
@router.get("/{etype}")
async def list_entity_type_eids(
etype: str, skip: NonNegativeInt = 0, limit: PositiveInt = 20
) -> EntityEidList:
"""List latest snapshots of all `id`s present in database under `entity`.
"""List latest snapshots of all `id`s present in database under `etype`.
Contains only latest snapshot.
Uses pagination.
"""
cursor = DB.get_latest_snapshots(entity).skip(skip).limit(limit)
cursor = DB.get_latest_snapshots(etype).skip(skip).limit(limit)

time_created = None

Expand All @@ -54,11 +54,11 @@ async def list_entity_eids(
return EntityEidList(time_created=time_created, data=result)


@router.get("/{entity}/{eid}")
@router.get("/{etype}/{eid}")
async def get_eid_data(
entity: str, eid: str, date_from: Optional[datetime] = None, date_to: Optional[datetime] = None
etype: str, eid: str, date_from: Optional[datetime] = None, date_to: Optional[datetime] = None
) -> EntityEidData:
"""Get data of `entity`'s `eid`.
"""Get data of `etype`'s `eid`.
Contains all snapshots and master record.
Snapshots are ordered by ascending creation time.
Expand All @@ -67,24 +67,24 @@ async def get_eid_data(
# TODO: This is probably not the most efficient way. Maybe gather only
# plain data from master record and then call `get_timeseries_history`
# for timeseries.
master_record = DB.get_master_record(entity, eid)
master_record = DB.get_master_record(etype, eid)
if "_id" in master_record:
del master_record["_id"]
if "#hash" in master_record:
del master_record["#hash"]

entity_attribs = MODEL_SPEC.attribs(entity)
entity_attribs = MODEL_SPEC.attribs(etype)

# Get filtered timeseries data
for attr in master_record:
# Check for no longer existing attributes
if attr in entity_attribs and entity_attribs[attr].t == AttrType.TIMESERIES:
master_record[attr] = DB.get_timeseries_history(
entity, attr, eid, t1=date_from, t2=date_to
etype, attr, eid, t1=date_from, t2=date_to
)

# Get snapshots
snapshots = list(DB.get_snapshots(entity, eid, t1=date_from, t2=date_to))
snapshots = list(DB.get_snapshots(etype, eid, t1=date_from, t2=date_to))
for s in snapshots:
del s["_id"]

Expand All @@ -94,9 +94,9 @@ async def get_eid_data(
return EntityEidData(empty=empty, master_record=master_record, snapshots=snapshots)


@router.get("/{entity}/{eid}/get/{attr}")
@router.get("/{etype}/{eid}/get/{attr}")
async def get_eid_attr_value(
entity: str,
etype: str,
eid: str,
attr: str,
date_from: Optional[datetime] = None,
Expand All @@ -110,19 +110,17 @@ async def get_eid_attr_value(
- history: in case of timeseries attribute
"""
# Check if attribute exists
if attr not in MODEL_SPEC.attribs(entity):
if attr not in MODEL_SPEC.attribs(etype):
raise RequestValidationError(["path", "attr"], f"Attribute '{attr}' doesn't exist")

value_or_history = DB.get_value_or_history(entity, attr, eid, t1=date_from, t2=date_to)
value_or_history = DB.get_value_or_history(etype, attr, eid, t1=date_from, t2=date_to)

return EntityEidAttrValueOrHistory(
attr_type=MODEL_SPEC.attr(entity, attr).t, **value_or_history
)
return EntityEidAttrValueOrHistory(attr_type=MODEL_SPEC.attr(etype, attr).t, **value_or_history)


@router.post("/{entity}/{eid}/set/{attr}")
@router.post("/{etype}/{eid}/set/{attr}")
async def set_eid_attr_value(
entity: str, eid: str, attr: str, body: EntityEidAttrValue, request: Request
etype: str, eid: str, attr: str, body: EntityEidAttrValue, request: Request
) -> SuccessResponse:
"""Set current value of attribute
Expand All @@ -131,13 +129,13 @@ async def set_eid_attr_value(
This endpoint is meant for `editable` plain attributes -- for direct user edit on DP3 web UI.
"""
# Check if attribute exists
if attr not in MODEL_SPEC.attribs(entity):
if attr not in MODEL_SPEC.attribs(etype):
raise RequestValidationError(["path", "attr"], f"Attribute '{attr}' doesn't exist")

# Construct datapoint
try:
dp = DataPoint(
type=entity,
type=etype,
id=eid,
attr=attr,
v=body.value,
Expand All @@ -149,7 +147,7 @@ async def set_eid_attr_value(
raise RequestValidationError(["body", "value"], e.errors()[0]["msg"]) from e

# This shouldn't fail
task = DataPointTask(model_spec=MODEL_SPEC, etype=entity, eid=eid, data_points=[dp3_dp])
task = DataPointTask(model_spec=MODEL_SPEC, etype=etype, eid=eid, data_points=[dp3_dp])

# Push tasks to task queue
TASK_WRITER.put_task(task, False)
Expand Down
18 changes: 9 additions & 9 deletions dp3/api/routers/root.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,21 +64,21 @@ async def insert_datapoints(dps: list[DataPoint], request: Request) -> SuccessRe


@router.get("/entities", tags=["Entity"])
async def list_entities() -> dict[str, EntityState]:
"""List entities
async def list_entity_types() -> dict[str, EntityState]:
"""List entity types
Returns dictionary containing all entities configured -- their simplified configuration
Returns dictionary containing all entity types configured -- their simplified configuration
and current state information.
"""
entities = {}

for e_id in MODEL_SPEC.entities:
entity_spec = MODEL_SPEC.entity(e_id)
entities[e_id] = {
"id": e_id,
for etype in MODEL_SPEC.entities:
entity_spec = MODEL_SPEC.entity(etype)
entities[etype] = {
"id": etype,
"name": entity_spec.name,
"attribs": MODEL_SPEC.attribs(e_id),
"eid_estimate_count": DB.estimate_count_eids(e_id),
"attribs": MODEL_SPEC.attribs(etype),
"eid_estimate_count": DB.estimate_count_eids(etype),
}

return entities

0 comments on commit 14b1e9f

Please sign in to comment.