Skip to content
This repository has been archived by the owner on Jul 13, 2023. It is now read-only.

Commit

Permalink
refactor: various cleanup
Browse files Browse the repository at this point in the history
- params -> router_data, kill unused vapid_info/body
- kill bogus/unused timing vars
- app_id isn't optional

issue #695
  • Loading branch information
pjenvey committed Apr 4, 2017
1 parent 76f772e commit f6add5e
Show file tree
Hide file tree
Showing 6 changed files with 29 additions and 36 deletions.
7 changes: 4 additions & 3 deletions autopush/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@

# Typing
T = TypeVar('T') # noqa
ItemLike = Union[Item, Dict[str, Any]]

key_hash = ""
TRACK_DB_CALLS = False
Expand Down Expand Up @@ -105,7 +106,7 @@ def hasher(uaid):


def dump_uaid(uaid_data):
# type: (Union[Dict[str, Any], Item]) -> str
# type: (ItemLike) -> str
"""Return a dict for a uaid.
This is utilized instead of repr since some db methods return a
Expand Down Expand Up @@ -303,7 +304,7 @@ def wrapper(self, *args, **kwargs):


def has_connected_this_month(item):
# type: (Dict[str, Any]) -> bool
# type: (ItemLike) -> bool
"""Whether or not a router item has connected this month"""
last_connect = item.get("last_connect")
if not last_connect:
Expand Down Expand Up @@ -678,7 +679,7 @@ def get_uaid(self, uaid):

@track_provisioned
def register_user(self, data):
# type: (Dict[str, Any]) -> Tuple[bool, Dict[str, Any], Dict[str, Any]]
# type: (ItemLike) -> Tuple[bool, Dict[str, Any], Dict[str, Any]]
"""Register this user
If a record exists with a newer ``connected_at``, then the user will
Expand Down
2 changes: 1 addition & 1 deletion autopush/router/fcm.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def amend_msg(self, msg, data=None):
msg["senderid"] = data.get('creds', {}).get('senderID')
return msg

def register(self, uaid, router_data, app_id=None, *args, **kwargs):
def register(self, uaid, router_data, app_id, *args, **kwargs):
"""Validate that the FCM Instance Token is in the ``router_data``"""
senderid = app_id
# "token" is the GCM registration id token generated by the client.
Expand Down
18 changes: 8 additions & 10 deletions autopush/router/interface.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Router interface"""
from typing import Any, Optional # noqa


class RouterResponse(object):
Expand Down Expand Up @@ -26,27 +27,24 @@ def __init__(self, settings, router_conf):
the given settings and router conf."""
raise NotImplementedError("__init__ must be implemented")

def register(self, uaid, routing_data, app_id, *args, **kwargs):
"""Register the uaid with the connect dict however is preferred and
return a dict that will be stored as routing_data for this user in the
future.
def register(self, uaid, router_data, app_id, *args, **kwargs):
# type: (str, dict, str, *Any, **Any) -> dict
"""Register the uaid with the router_data dict however is preferred
and return a dict that will be stored as router_data for this
user in the future.
:param uaid: User Agent Identifier
:type uaid: str
:param routing_data: Route specific configuration info
:type routing_data: dict
:param router_data: Route specific configuration info
:param app_id: Application identifier from URI
:type app_id: str
:returns: A response object
:rtype: :class:`RouterResponse`
:raises:
:exc:`RouterException` if data supplied is invalid.
"""
raise NotImplementedError("register must be implemented")

def amend_msg(self, msg, router_data=None):
# type: (dict, Optional[dict]) -> dict
"""Modify an outbound response message to include router info
:param msg: A dict of the response data to be sent to the client
Expand Down
6 changes: 2 additions & 4 deletions autopush/tests/test_web_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,19 +98,17 @@ def test_validate_invalid_schema(self):
eq_(d, {})

def test_call_func_no_error(self):
start_time = time.time()
mock_func = Mock()
tv, rh = self._make_full()
result = tv._validate_request(rh)
tv._call_func(result, mock_func, rh, start_time)
tv._call_func(result, mock_func, rh)
mock_func.assert_called()

def test_call_func_error(self):
start_time = time.time()
mock_func = Mock()
tv, rh = self._make_full(schema=InvalidSchema)
result = tv._validate_request(rh)
tv._call_func(result, mock_func, rh, start_time)
tv._call_func(result, mock_func, rh)
self._mock_errors.assert_called()
eq_(len(mock_func.mock_calls), 0)

Expand Down
30 changes: 13 additions & 17 deletions autopush/web/registration.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import json
import re
import time
import uuid

from boto.dynamodb2.exceptions import ItemNotFound
Expand Down Expand Up @@ -28,27 +27,25 @@
class RegistrationSchema(Schema):
uaid = fields.UUID(allow_none=True)
chid = fields.Str(allow_none=True)
body = fields.Dict(allow_none=True)
router_type = fields.Str()
router_token = fields.Str()
params = fields.Dict()
router_data = fields.Dict()
auth = fields.Str(allow_none=True)
vapid_info = fields.Dict(allow_none=True)

@pre_load
def extract_data(self, req):
params = {}
router_data = {}
if req['body']:
try:
params = json.loads(req['body'])
router_data = json.loads(req['body'])
except ValueError:
raise InvalidRequest("Invalid Request body",
status_code=401,
errno=108)
# UAID and CHID may be empty. This can trigger different behaviors
# in the handlers, so we can't set default values here.
uaid = req['path_kwargs'].get('uaid')
chid = req['path_kwargs'].get('chid', params.get("channelID"))
chid = req['path_kwargs'].get('chid', router_data.get("channelID"))
if uaid:
try:
u_uuid = uuid.UUID(uaid)
Expand All @@ -74,7 +71,7 @@ def extract_data(self, req):

return dict(
auth=req.get('headers', {}).get("Authorization"),
params=params,
router_data=router_data,
router_type=req['path_kwargs'].get('router_type'),
router_token=req['path_kwargs'].get('router_token'),
uaid=uaid,
Expand Down Expand Up @@ -145,15 +142,14 @@ def post(self, *args, **kwargs):
"""
self.start_time = time.time()
self.add_header("Content-Type", "application/json")
params = self.valid_input['params']
router_data = self.valid_input['router_data']
# If the client didn't provide a CHID, make one up.
# Note, valid_input may explicitly set "chid" to None
# THIS VALUE MUST MATCH WHAT'S SPECIFIED IN THE BRIDGE CONNECTIONS.
# currently hex formatted.
self.chid = params["channelID"] = (self.valid_input["chid"] or
uuid.uuid4().hex)
self.chid = router_data["channelID"] = (self.valid_input["chid"] or
uuid.uuid4().hex)
self.ap_settings.metrics.increment("updates.client.register",
tags=self.base_tags())
# If there's a UAID, ensure its valid, otherwise we ensure the hash
Expand All @@ -167,10 +163,11 @@ def post(self, *args, **kwargs):
self.valid_input['uaid'] = uuid.uuid4()
new_uaid = True
self.uaid = self.valid_input['uaid']
self.app_server_key = params.get("key")
self.app_server_key = router_data.get("key")
if new_uaid:
d = Deferred()
d.addCallback(router.register, router_data=params,
d.addCallback(router.register,
router_data=router_data,
app_id=self.valid_input.get("router_token"),
uri=self.request.uri)
d.addCallback(self._save_router_data,
Expand All @@ -192,13 +189,12 @@ def put(self, *args, **kwargs):
Update router type/data for a UAID.
"""
self.start_time = time.time()

self.uaid = self.valid_input['uaid']
router = self.valid_input['router']
self.add_header("Content-Type", "application/json")
d = Deferred()
d.addCallback(router.register, router_data=self.valid_input['params'],
d.addCallback(router.register,
router_data=self.valid_input['router_data'],
app_id=self.valid_input['router_token'],
uri=self.request.uri)
d.addCallback(self._save_router_data, self.valid_input['router_type'])
Expand Down
2 changes: 1 addition & 1 deletion autopush/websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -584,7 +584,7 @@ def _lookup_node(self, results):
extra="Failed to get UAID for redeliver")

def _trap_uaid_not_found(self, fail):
# type: (Failure) -> None
# type: (failure.Failure) -> None
"""Traps UAID not found error"""
fail.trap(ItemNotFound)
self.ps.metrics.increment("client.lookup_uaid_failure",
Expand Down

0 comments on commit f6add5e

Please sign in to comment.