Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding backend changes for alerts view #1011

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion server/.chalice/config.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"version": "2.0",
"app_name": "data-dashboard-v4",
"app_name": "data-dashboard",
"api_gateway_endpoint_type": "REGIONAL",
"minimum_compression_size": 1000,
"lambda_timeout": 30,
Expand Down
31 changes: 9 additions & 22 deletions server/.chalice/policy.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,22 @@
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Action": ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"],
"Effect": "Allow",
"Resource": "arn:*:logs:*:*:*"
},
{
"Action": [
"s3:ListBucket"
],
"Action": ["s3:ListBucket"],
"Effect": "Allow",
"Resource": [
"arn:aws:s3:::tm-mbta-performance"
]
"Resource": ["arn:aws:s3:::tm-mbta-performance"]
},
{
"Action": [
"s3:GetObject"
],
"Action": ["s3:GetObject"],
"Effect": "Allow",
"Resource": [
"arn:aws:s3:::tm-mbta-performance/*"
]
"Resource": ["arn:aws:s3:::tm-mbta-performance/*"]
},
{
"Action": [
"dynamodb:Query"
],
"Action": ["dynamodb:Query"],
"Effect": "Allow",
"Resource": [
"arn:aws:dynamodb:*:*:table/DeliveredTripMetrics",
Expand All @@ -41,8 +27,9 @@
"arn:aws:dynamodb:*:*:table/ScheduledServiceDaily",
"arn:aws:dynamodb:*:*:table/Ridership",
"arn:aws:dynamodb:*:*:table/SpeedRestrictions",
"arn:aws:dynamodb:*:*:table/TimePredictions"
"arn:aws:dynamodb:*:*:table/TimePredictions",
"arn:aws:dynamodb:*:*:table/AlertDelaysWeekly"
]
}
]
}
}
7 changes: 7 additions & 0 deletions server/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
aggregation,
data_funcs,
secrets,
delays,
mbta_v3,
speed,
speed_restrictions,
Expand Down Expand Up @@ -164,6 +165,12 @@ def get_alerts():
return json.dumps(response, indent=4, sort_keys=True, default=str)


@app.route("/api/linedelays", cors=cors_config)
def get_delays_by_line():
response = delays.delay_time_by_line(app.current_request.query_params)
return json.dumps(response, indent=4, sort_keys=True)


@app.route("/api/tripmetrics", cors=cors_config)
def get_trips_by_line():
response = speed.trip_metrics_by_line(app.current_request.query_params)
Expand Down
2 changes: 2 additions & 0 deletions server/chalicelib/constants.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
EVENT_ARRIVAL = ["ARR", "PRA"]
EVENT_DEPARTURE = ["DEP", "PRD"]

DATE_FORMAT_BACKEND = "%Y-%m-%d"

LINE_TO_ROUTE_MAP = {
"line-red": ["line-red-a", "line-red-b"],
"line-green": ["line-green-b", "line-green-c", "line-green-d", "line-green-e"],
Expand Down
46 changes: 46 additions & 0 deletions server/chalicelib/delays.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from typing import TypedDict
from chalice import BadRequestError, ForbiddenError
from chalicelib import dynamo
from datetime import date, datetime, timedelta
from chalicelib.constants import DATE_FORMAT_BACKEND


TABLE_NAME = "AlertDelaysWeekly"
MAX_DELTA = 5000


class AlertDelaysByLineParams(TypedDict):
start_date: str | date
end_date: str | date
line: str


def is_invalid_range(start_date, end_date, max_delta):
"""Check if number of requested entries is more than maximum for the table"""
start_datetime = datetime.strptime(start_date, DATE_FORMAT_BACKEND)
end_datetime = datetime.strptime(end_date, DATE_FORMAT_BACKEND)
return start_datetime + timedelta(days=max_delta) < end_datetime


def delay_time_by_line(params: AlertDelaysByLineParams):
try:
start_date = params["start_date"]
end_date = params["end_date"]
line = params["line"]
if line not in [
"Red",
"Blue",
"Orange",
"Green-B",
"Green-C",
"Green-D",
"Green-E",
]:
raise BadRequestError("Invalid Line key.")
except KeyError:
raise BadRequestError("Missing or invalid parameters.")
# Prevent queries of more than 5000 items.
if is_invalid_range(start_date, end_date, MAX_DELTA):
raise ForbiddenError("Date range too long. The maximum number of requested values is 150.")
# If querying for weekly/monthly data, can just return the query.
return dynamo.query_agg_trip_metrics(start_date, end_date, TABLE_NAME, line)
3 changes: 1 addition & 2 deletions server/chalicelib/speed.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from datetime import date, datetime, timedelta
import pandas as pd
import numpy as np
from chalicelib.constants import DATE_FORMAT_BACKEND


class TripMetricsByLineParams(TypedDict):
Expand All @@ -20,8 +21,6 @@ class TripMetricsByLineParams(TypedDict):
"monthly": {"table_name": "DeliveredTripMetricsMonthly", "delta": 30 * 150},
}

DATE_FORMAT_BACKEND = "%Y-%m-%d"


def aggregate_actual_trips(actual_trips, agg, start_date):
flat_data = [entry for sublist in actual_trips for entry in sublist]
Expand Down
Loading
Loading