desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Returns true if this is a fully registered user that has been authenticated by a trusted authority.'
def IsRegistered(self):
return (User.REGISTERED in self.labels)
'Returns true if this user should always be redirected to the staging cluster.'
def IsStaging(self):
return (User.STAGING in self.labels)
'Returns true if this user\'s account has been terminated.'
def IsTerminated(self):
return (User.TERMINATED in self.labels)
'Returns true if this user is a system user.'
def IsSystem(self):
return (User.SYSTEM in self.labels)
'Adds the SYSTEM label to this user.'
@gen.coroutine def MakeSystemUser(self, client):
self.labels.add(User.SYSTEM) (yield gen.Task(self.Update, client))
'Queries the identities (if any) attached to this user and returns the list to the provided callback.'
def QueryIdentities(self, client, callback):
query_str = ('identity.user_id=%d' % self.user_id) Identity.IndexQuery(client, query_str, col_names=None, callback=callback)
'Method to return the primary identity associated with an account. This currently only works for prospective users, which are guaranteed to have a single identity. The method is being created with a more general signature so that it will be useful once the anticipated concept of a primary identity is introduced.'
@gen.coroutine def QueryPrimaryIdentity(self, client):
assert (not self.IsRegistered()), 'QueryPrimaryIdentity is currently only permitted for Prospective users.' identities = (yield gen.Task(self.QueryIdentities, client)) assert (len(identities) == 1), ('Encountered prospective user %d with multiple identities.' % self.us...
'Returns list of column names that should not be printed in logs.'
@classmethod def ShouldScrubColumn(cls, name):
return (name in ['signing_key', 'pwd_hash', 'salt'])
'Returns a list suitable for the \'labels\' field of USER_PROFILE_METADATA. If \'is_friend\' is True, returns labels accessible to friends; if it is false, returns only labels accessible to strangers.'
def MakeLabelList(self, is_friend):
if is_friend: labels = [label for label in self.labels if (label in User._USER_FRIEND_LABELS)] labels.append('friend') return labels else: return [label for label in self.labels if (label in User._USER_NON_FRIEND_LABELS)]
'Projects a subset of the user attributes that can be provided to the viewing user (using the same schema as the query_users service method). The \'forward_friend\' is viewer_user_id => friend_user_id, and the \'reverse_friend\' is the reverse. This user\'s profile information will only be provided to the viewer if the...
@gen.engine def MakeUserMetadataDict(self, client, viewer_user_id, forward_friend, reverse_friend, callback):
user_dict = {'user_id': self.user_id} if (reverse_friend is not None): for attr_name in User._USER_FRIEND_ATTRIBUTES: util.SetIfNotNone(user_dict, attr_name, getattr(self, attr_name, None)) user_dict['labels'] = self.MakeLabelList(True) else: user_dict['labels'] = self.Ma...
'Allocates \'num_ids\' new ids from the \'asset_id_seq\' column in a block for the specified user id and returns the first id in the sequence (first_id, ..., first_id + num_ids] with the callback'
@classmethod def AllocateAssetIds(cls, client, user_id, num_ids, callback):
id_seq_key = cls._table.GetColumn('asset_id_seq').key def _OnUpdateIdSeq(result): last_id = result.return_values[id_seq_key] first_id = (last_id - num_ids) callback(first_id) client.UpdateItem(table=cls._table.name, key=db_client.DBKey(hash_key=user_id, range_key=None), attributes={i...
'Allocates a new user id and a new web device id and returns them in a tuple.'
@classmethod @gen.coroutine def AllocateUserAndWebDeviceIds(cls, client):
user_id = (yield gen.Task(User._allocator.NextId, client)) webapp_dev_id = (yield gen.Task(Device._allocator.NextId, client)) raise gen.Return((user_id, webapp_dev_id))
'Queries User objects for each id in the \'user_ids\' list. Invokes \'callback\' with a list of (user, forward_friend, reverse_friend) tuples. Non-existent users are omitted.'
@classmethod @gen.engine def QueryUsers(cls, client, viewer_user_id, user_ids, callback):
user_keys = [db_client.DBKey(user_id, None) for user_id in user_ids] forward_friend_keys = [db_client.DBKey(viewer_user_id, user_id) for user_id in user_ids] reverse_friend_keys = [db_client.DBKey(user_id, viewer_user_id) for user_id in user_ids] (users, forward_friends, reverse_friends) = (yield [gen.T...
'Creates a prospective user with the specified user id. web device id, and identity key. A prospective user is typically created when photos are shared with a contact that is not yet a Viewfinder user. Returns a tuple containing the user and identity.'
@classmethod @gen.coroutine def CreateProspective(cls, client, user_id, webapp_dev_id, identity_key, timestamp):
from viewfinder.backend.db.viewpoint import Viewpoint (identity_type, identity_value) = Identity.SplitKey(identity_key) identity = (yield gen.Task(Identity.CreateProspective, client, identity_key, user_id, timestamp)) viewpoint = (yield Viewpoint.CreateDefault(client, user_id, webapp_dev_id, timestamp))...
'Registers a user or updates its attributes using the contents of "user_dict". Updates an identity using the contents of "ident_dict" and ensures its linked to the user. "user_dict" contains oauth-supplied user information which is either used to initially populate the fields for a new user account, or is used to updat...
@classmethod @gen.coroutine def Register(cls, client, user_dict, ident_dict, timestamp, rewrite_contacts):
assert ('user_id' in user_dict), user_dict assert ('authority' in ident_dict), ident_dict user = (yield gen.Task(User.Query, client, user_dict['user_id'], None)) identity = (yield gen.Task(Identity.Query, client, ident_dict['key'], None)) for (k, v) in user_dict.items(): assert (k in User._R...
'Update the user\'s public profile, as well as any account settings specified in "settings_dict".'
@classmethod @gen.engine def UpdateWithSettings(cls, client, user_dict, settings_dict, callback):
assert all((((attr_name == 'user_id') or (attr_name in User._UPDATE_USER_ATTRIBUTES)) for attr_name in user_dict)), user_dict for attr_name in ['name', 'given_name', 'family_name']: if (attr_name in user_dict): user_dict.setdefault('name', None) user_dict.setdefault('given_name',...
'Terminate the user\'s account by adding the "TERMINATED" flag to the labels set. If "merged_with" is not None, then the terminate is due to a merge, so set the "merged_with" field on the terminated user.'
@classmethod @gen.coroutine def TerminateAccount(cls, client, user_id, merged_with):
user = (yield gen.Task(User.Query, client, user_id, None)) user.merged_with = merged_with user.labels.add(User.TERMINATED) (yield gen.Task(user.Update, client))
'Create a user unsubscribe cookie that is passed as an argument to the unsubscribe handler, and which proves control of the given user id.'
@classmethod def CreateUnsubscribeCookie(cls, user_id, email_type):
unsubscribe_dict = {'user_id': user_id, 'email_type': email_type} return web.create_signed_value(secrets.GetSecret('invite_signing'), 'unsubscribe', json.dumps(unsubscribe_dict))
'Decode a user unsubscribe cookie that is passed as an argument to the unsubscribe handler. Returns the unsubscribe dict containing the user_id and email_type originally passed to CreateUnsubscribeCookie.'
@classmethod def DecodeUnsubscribeCookie(cls, unsubscribe_cookie):
value = web.decode_signed_value(secrets.GetSecret('invite_signing'), 'unsubscribe', unsubscribe_cookie) return (None if (value is None) else json.loads(value))
'Invokes User.TerminateAccount via operation execution.'
@classmethod @gen.coroutine def TerminateAccountOperation(cls, client, user_id, merged_with=None):
@gen.coroutine def _VisitIdentity(identity_key): 'Unlink this identity from the user.' (yield Identity.UnlinkIdentityOperation(client, user_id, identity_key.hash_key)) (yield gen.Task(Device.MuteAlerts, client, user_id)) query_expr = ('identity.user_id={id}', {'id': user_i...
'Invokes User.Update via operation execution.'
@classmethod @gen.engine def UpdateOperation(cls, client, callback, user_dict, settings_dict):
(yield gen.Task(User.UpdateWithSettings, client, user_dict, settings_dict)) timestamp = Operation.GetCurrent().timestamp (yield NotificationManager.NotifyUpdateUser(client, user_dict, settings_dict, timestamp)) callback()
'Create a new Device object from \'device_dict\'. Clears out \'device_uuid\' and \'test_udid\' if present.'
@classmethod def Create(cls, **device_dict):
create_dict = device_dict if (('device_uuid' in device_dict) or ('test_udid' in device_dict)): create_dict = deepcopy(device_dict) create_dict.pop('device_uuid', None) create_dict.pop('test_udid', None) return cls.CreateFromKeywords(**create_dict)
'Update a Device object from \'device_dict\'. Clears out \'device_uuid\' and \'test_udid\' if present.'
def UpdateFields(self, **device_dict):
create_dict = device_dict if (('device_uuid' in device_dict) or ('test_udid' in device_dict)): create_dict = deepcopy(device_dict) create_dict.pop('device_uuid', None) create_dict.pop('test_udid', None) self.UpdateFromKeywords(**create_dict)
'Registers a new device or update an existing device, using the fields in "device_dict". If "is_first" is true, then this is the first mobile device to be registered for this user.'
@classmethod @gen.coroutine def Register(cls, client, user_id, device_dict, is_first=True):
assert ('device_id' in device_dict), device_dict device = (yield gen.Task(Device.Query, client, user_id, device_dict['device_id'], None, must_exist=False)) if (device is None): device = Device.Create(user_id=user_id, timestamp=util.GetCurrentTimestamp(), **device_dict) else: device.Updat...
'Call the base class "Update" method in order to persist modified columns to the db. But also ensure that this device has a unique push token; two Viewfinder devices might share the same push token if a phone has been given or sold to another person without re-installing the OS. Also, ensure that the device is added to...
def Update(self, client, callback):
def _DoUpdate(): super(Device, self).Update(client, callback) def _OnQueryByPushToken(devices): 'Disable alerts for all other devices.' with util.Barrier(_DoUpdate) as b: for device in devices: if (device.device_id != self.device_id): ...
'Queries all devices for \'user\'. Devices with \'push_token\' set are pushed notifications via the push_notification API. NOTE: currently, code path is synchronous, but the callback is provided in case that changes. If specified, \'exclude_device_id\' will exclude a particular device from the set to which notification...
@classmethod def PushNotification(cls, client, user_id, alert, badge, callback, exclude_device_id=None, extra=None, sound=None):
def _OnQuery(devices): with util.Barrier(callback) as b: now = util.GetCurrentTimestamp() for device in devices: if (device.device_id != exclude_device_id): token = device.push_token assert token, device try:...
'Returns all devices owned by the given user that can be alerted.'
@classmethod def QueryAlertable(cls, client, user_id, callback, limit=_MAX_ALERT_DEVICES):
query_expr = ('device.alert_user_id={u}', {'u': user_id}) Device.IndexQuery(client, query_expr, None, callback, limit=limit)
'Turn off alerts to all devices owned by "user_id".'
@classmethod @gen.coroutine def MuteAlerts(cls, client, user_id):
@gen.coroutine def _VisitDevice(device): device.alert_user_id = None (yield gen.Task(device.Update, client)) (yield gen.Task(Device.VisitRange, client, user_id, None, None, _VisitDevice))
'Returns a callback which deals appropriately with device push tokens which have failed delivery.'
@classmethod def FeedbackHandler(cls, client):
return partial(Device._HandleBadPushToken, client)
'Generate a unique id to be used for identifying system-generated objects. Return the new id.'
@classmethod def AllocateSystemObjectId(cls, client, callback):
Device._sys_obj_allocator.NextId(client, callback)
'Callback in the event of failed delivery of push notification. \'push_token\' is queried via the secondary index on Device. Timestamp is the time at which the delivery failed. If the device attached to the failed push_token has \'last_access\' > timestamp, ignore failure; otherwise, clear the push token and update.'
@classmethod def _HandleBadPushToken(cls, client, push_token, timestamp=None, callback=None):
def _OnQueryByPushToken(devices): if (not devices): logging.warning(('unable to locate device for push token: %s' % push_token)) return for device in devices: if ((device.last_access is None) or (device.last_access < timestamp)): ...
'Updates device metadata.'
@classmethod def UpdateOperation(cls, client, callback, user_id, device_id, device_dict):
def _OnQuery(device): device.UpdateFields(**device_dict) device.Update(client, callback) Device.Query(client, user_id, device_id, None, _OnQuery)
'Returns true if marketing communication is allowed to be sent.'
def AllowMarketing(self):
return (self.marketing != AccountSettings.MARKETING_NONE)
'Project a subset of account settings attributes that can be provided to the user.'
def MakeMetadataDict(self):
settings_dict = {} for attr_name in AccountSettings._JSON_ATTRIBUTES: value = getattr(self, attr_name, None) if isinstance(value, frozenset): util.SetIfNotEmpty(settings_dict, attr_name, list(value)) else: util.SetIfNotNone(settings_dict, attr_name, value) ret...
'Constructs the settings id used for user settings: us:<user_id>.'
@classmethod def ConstructSettingsId(cls, user_id):
return ('us:%d' % user_id)
'Constructs a DBKey that refers to the account settings for the given user: (us:<user_id>, \'account\').'
@classmethod def ConstructKey(cls, user_id):
return DBKey(AccountSettings.ConstructSettingsId(user_id), AccountSettings.GROUP_NAME)
'Creates a new AccountSettings object for the given user and populates it with the given attributes.'
@classmethod def CreateForUser(cls, user_id, **obj_dict):
return AccountSettings.CreateFromKeywords(settings_id=AccountSettings.ConstructSettingsId(user_id), group_name=AccountSettings.GROUP_NAME, user_id=user_id, **obj_dict)
'For the convenience of the caller, automatically creates the settings_id and group_name parameters for the call to the base Query method.'
@classmethod def QueryByUser(cls, client, user_id, col_names, callback, must_exist=True, consistent_read=False):
super(AccountSettings, cls).KeyQuery(client, AccountSettings.ConstructKey(user_id), col_names, callback, must_exist=must_exist, consistent_read=consistent_read)
'Takes the left child as a parameter. The right child is merged into this operation via a call to Merge. The two are followed recursively during evaluation, with the left and right evaluated asynchronously. When both have completed, the result of the set operation (union, difference, intersection & positional intersect...
def __init__(self, schema, left):
self._left = left self._right = None
'Depth-first printout of tree structure for debugging.'
def PrintTree(self, level, param_dict):
return ((((((self._OpName() + ' __ ') + self._left.PrintTree((level + 1), param_dict)) + '\n') + (level * ' ')) + ' \\_ ') + self._right.PrintTree((level + 1), param_dict))
'Rearranges the parent-child relationship to conform to operator precedence. If the precedence of the current node is >= the node to its right, then the right-hand node becomes the new parent, with the current node made its new left-hand node (meaning this node will be evaluated first, as the evaluation is a depth-firs...
def Merge(self, right):
if (self._precedence >= right._precedence): self._right = right._left right._left = self return right else: self._right = right return self
'Recursively evaluates the query tree via a depth- first traversal. Returns the result set, defined by the data delivered via the IndexTermNodes and then operated on by the OpNodes.'
def Evaluate(self, client, callback, start_key, consistent_read, param_dict):
with util.ArrayBarrier(partial(self._SetOperation, callback)) as b: self._left.Evaluate(client, b.Callback(), start_key, consistent_read, param_dict) self._right.Evaluate(client, b.Callback(), start_key, consistent_read, param_dict)
'For union, the sets are additively combined. Both the first and last keys are defined as the minimum of first and last keys for the two results. This jibes well with the intuitive notion that we were able to successfully evaluate the union between these two sets for all values starting at the very minimum up to and in...
def _SetOperation(self, callback, results):
assert (len(results) == 2) matches = (results[0].matches + results[1].matches) matches.sort() if (results[0].last_key is None): last_key = results[1].last_key elif (results[1].last_key is None): last_key = results[0].last_key else: last_key = min(results[0].last_key, resu...
'For set difference, the ordering matters. The second set can be thought of as a mask over the first set. The overlap starting at the first key and extending to the min(last_key1, last_key2) defines the successfully-evaluated range. To see this, consider that any portion of the subtracted range which lies before the fi...
def _SetOperation(self, callback, results):
assert (len(results) == 2) m1 = results[0].matches m2 = results[1].matches matches = [] while m1: m2_idx = bisect_left(m2, m1[0]) if (m2_idx == len(m2)): break elif (m1[0] == m2[m2_idx]): m1 = m1[1:] elif (m2_idx == 0): m1_idx = bis...
'Efficiently skip through the two lists using list bisection.'
def _SetOperation(self, callback, results):
assert (len(results) == 2) m1 = results[0].matches m2 = results[1].matches matches = [] while (m1 and m2): if (m1[0] < m2[0]): m1 = m1[bisect_left(m1, m2[0]):] elif (m2[0] < m1[0]): m2 = m2[bisect_left(m2, m1[0]):] else: matches.append(m1[0...
'For set intersection, the successfully-evaluated portion starts at the maximum of the first keys and extends as far as the minimum of the last keys. This is the portion for which we have enough information to definitively determine intersection.'
def _ComputeLastKey(self, results):
if (results[0].last_key is None): last_key = results[1].last_key elif (results[1].last_key is None): last_key = results[0].last_key else: last_key = min(results[0].last_key, results[1].last_key) return last_key
'Merging for positional intersections works a little differently than for normal operations. Here, we are on the lookout to merge place-holder (None) nodes out of the tree. If the right-hand node we\'re trying to merge is a place-holder, then return the left-hand node as the result of the merge (this removes trailing p...
def Merge(self, right):
if (right is None): return self._left elif (isinstance(right, PositionalIntersection) and (right._left is None)): self._delta += right._delta self._right = right._right else: self._right = right return self
'Perform a standard intersection operation, but on a match, return only the left node\'s position data, and then only those positions with a difference of self._delta from the right node\'s positions.'
def _SetOperation(self, callback, results):
assert (len(results) == 2) m1 = results[0].matches m2 = results[1].matches matches = [] while (m1 and m2): if (m1[0] < m2[0]): m1 = m1[bisect_left(m1, m2[0]):] elif (m2[0] < m1[0]): m2 = m2[bisect_left(m2, m1[0]):] else: new_data = [pos for...
'Convert the phrase into a query string using the appropriate indexer object (found via table:column in schema). This query string is passed to the phrase parser, and the new query subtree is set as the child of this PhraseNode.'
def __init__(self, schema, table_name, column_name, phrase):
self._precedence = 1000 try: self.schema = schema self.table = self.schema.GetTable(table_name) assert isinstance(self.table, IndexedTable), table_name column = self.table.GetColumn(column_name) assert column.indexer, column_name self.column = column self....
'Queries the database for keys beginning with start_key, with a limit defined in the table schema. Consistent reads are disabled as they\'re unlikely to make a difference in search results (and are half as expensive in the DynamoDB cost model).'
def Evaluate(self, client, callback, start_key, consistent_read, param_dict):
def _OnQuery(result): self._start_key = start_key self._last_key = (result.last_key.range_key if (result.last_key is not None) else None) self._matches = [_MatchResult(key=item['k'], data=self._Unpack(item.get('d', None))) for item in result.items] callback(_EvalResult(matches=self._...
'Runs the parser on the provided query expression and returns the resulting query tree.'
def Run(self, query_str):
(query_tree, _) = run_text_parser(self._expr_parser, escape.to_unicode(query_str)) return query_tree
'Consumes one operation, defined by left term and right expression, which may be either another term or another ParseOp().'
@tri def _ParseOp(self):
left = self._term_parser() op = self._operator() commit() right = self._expr_parser() whitespace() node = self._op_classes[op](self._schema, left) return node.Merge(right)
'Consumes parenthetical expression.'
@tri def _ParseParenthetical(self):
whitespace() one_of('(') commit() whitespace() node = self._expr_parser() whitespace() one_of(')') whitespace() return Parenthetical(self._schema, node)
'Consumes parameter keys for lookup in a parameter dictionary passed in with the query. Parameter keys may consist of letters, digits and underscores (_). Returns the value that the parameter key maps to.'
@tri def _ParseParam(self):
one_of('{') param_name = ''.join(many_until1(p(one_of, ((letters + digits) + '_')), p(one_of, '}'))[0]) return Parameter(param_name)
'Consumes a key range specification of the form <table>.<column>=<maybe quoted value>.'
@tri def _ParsePhrase(self):
whitespace() table = self._token().lower() one_of('.') commit() column = self._token().lower() whitespace() one_of('=') whitespace() phrase = self._param_parser() node = PhraseNode(self._schema, table, column, phrase) whitespace() return node
'Consumes an index term. If \'_\', creates a place-holder node (None); otherwise, creates an IndexTermNode.'
def _ParseIndexTerm(self):
whitespace() index_term = self._phrase() if (index_term == '_'): node = None else: node = IndexTermNode(self._schema, self._table, self._column, index_term) whitespace() return node
'Parses query_str into a query node tree.'
def __init__(self, schema, query_str):
self._query_str = query_str self._query_tree = _QueryParser(schema).Run(query_str)
'Evaluates the query tree according to the provided db client. \'callback\' is invoked with the query results. Returns keys matching the query expression, up to the limit.'
def Evaluate(self, client, callback, limit=50, start_key=None, end_key=None, consistent_read=False, param_dict=None):
def _OnEvaluate(results, read_units, eval_result): results += [mr.key for mr in eval_result.matches if ((not end_key) or (mr.key < end_key))] read_units += eval_result.read_units reached_end_key = ((end_key is not None) and (eval_result.last_key >= end_key)) reached_limit = ((limit i...
'Queries a object by primary hash key.'
@classmethod @return_future def Query(cls, client, hash_key, col_names, callback, must_exist=True, consistent_read=False):
cls.KeyQuery(client, key=db_client.DBKey(hash_key=hash_key, range_key=None), col_names=col_names, callback=callback, must_exist=must_exist, consistent_read=consistent_read)
'Allocates a new primary key via the id_allocator table. Invokes the provided callback with new object.'
@classmethod def Allocate(cls, client, callback):
assert cls._allocator, 'class has no id allocator declared' def _OnAllocate(obj_id): o = cls(obj_id) o._columns[schema.Table.VERSION_COLUMN.name].Set(Version.GetCurrentVersion()) callback(o) cls._allocator.NextId(client, _OnAllocate)
'Returns the object\'s primary hash key.'
def GetKey(self):
return db_client.DBKey(hash_key=self._columns[self._table.hash_key_col.name].Get(), range_key=None)
'Creates an indexing key from the provided object key. This is symmetric with _ParseIndexKey. All index keys are stored as strings, so we get a string representation here in case the hash key column is a number.'
@classmethod def _MakeIndexKey(cls, db_key):
val = db_key.hash_key if (cls._table.hash_key_col.value_type == 'N'): assert isinstance(val, (int, long)), 'primary hash key not of type int or long' val = str(val) return val
'Returns the object\'s key by parsing the index key. This is symmetric with _MakeIndexKey, and is used to extract the actual object key from results of index queries. By default, returns the unadulterated index_key. Because all keys are stored in the index table as strings, if the hash key column type is a number, conv...
@classmethod def _ParseIndexKey(cls, index_key):
if (cls._table.hash_key_col.value_type == 'N'): index_key = int(index_key) return db_client.DBKey(hash_key=index_key, range_key=None)
'Returns true if the photo has been unshared by the posting user, making it inaccessible to followers of the viewpoint.'
def IsUnshared(self):
return (Post.UNSHARED in self.labels)
'Returns true if the photo has been removed by the posting user, making it inaccessible to followers of the viewpoint. This label will always be set if the unshared label is set.'
def IsRemoved(self):
return ((Post.UNSHARED in self.labels) or (Post.REMOVED in self.labels))
'Returns a post id constructed by concatenating the id of the episode that contains the post with the id of the posted photo. The two parts are separated by a \'+\' character, which is not produced by the base64hex encoding, and so can be used to later deconstruct the post id if necessary. While the key for a post is c...
@classmethod def ConstructPostId(cls, episode_id, photo_id):
return (((IdPrefix.Post + episode_id[1:]) + '+') + photo_id[1:])
'Returns the components of a post id: (episode_id, photo_id).'
@classmethod def DeconstructPostId(cls, post_id):
assert (post_id[0] == IdPrefix.Post), post_id index = post_id.index('+') assert (index > 0), post_id return ((IdPrefix.Episode + post_id[1:index]), (IdPrefix.Photo + post_id[(index + 1):]))
'Creates a new post from post_dict. The caller is responsible for checking permission to do this, as well as ensuring that the post does not yet exist (or is just being identically rewritten). Posts are sorted using the photo id. Since the photo id is prefixed by the photo timestamp, this amounts to sorting by photo ti...
@classmethod @gen.coroutine def CreateNew(cls, client, **post_dict):
post = Post.CreateFromKeywords(**post_dict) (yield gen.Task(post.Update, client)) raise gen.Return(post)
'Adds a viewpoint id to the set on the current operation.'
@classmethod def AddViewpointId(cls, viewpoint_lock_id):
lock_tracker = ViewpointLockTracker._GetInstance() assert (viewpoint_lock_id not in lock_tracker.viewpoint_lock_ids) lock_tracker.viewpoint_lock_ids.add(viewpoint_lock_id)
'Removes a viewpoint id from the set on the current operation.'
@classmethod def RemoveViewpointId(cls, viewpoint_lock_id):
lock_tracker = ViewpointLockTracker._GetInstance() assert (viewpoint_lock_id in lock_tracker.viewpoint_lock_ids) lock_tracker.viewpoint_lock_ids.remove(viewpoint_lock_id)
'Returns true if the the viewpoint id is in the set on the current operation.'
@classmethod def HasViewpointId(cls, viewpoint_lock_id):
lock_tracker = ViewpointLockTracker._GetInstance() return (viewpoint_lock_id in lock_tracker.viewpoint_lock_ids)
'Ensures that a viewpoint lock tracker has been created and attached to the current operation.'
@classmethod def _GetInstance(cls):
op = Operation.GetCurrent() lock_tracker = op.context.get('viewpoint_lock_tracker') if (lock_tracker is None): lock_tracker = ViewpointLockTracker() op.context['viewpoint_lock_tracker'] = lock_tracker return lock_tracker
'Gets an ISO date string for the specified UTC "timestamp".'
@classmethod def _IsoDate(cls, timestamp):
return datetime.datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d')
'Creates a key prefix for user log files based on "user_id" and the "iso_date_str".'
@classmethod def _LogKeyPrefix(cls, user_id, iso_date_str):
return ('%d/%s' % (user_id, iso_date_str))
'Returns a URL for the client to write device logs to S3. URLs expire by default in a day and expect content-type CLIENT_LOG_CONTENT_TYPE.'
@classmethod def GetPutUrl(cls, user_id, device_id, timestamp, client_log_id, content_type=CLIENT_LOG_CONTENT_TYPE, content_md5=None, max_bytes=(10 << 20)):
iso_date_str = ClientLog._IsoDate(timestamp) key = ('%s/dev-%d-%s' % (ClientLog._LogKeyPrefix(user_id, iso_date_str), device_id, client_log_id)) obj_store = ObjectStore.GetInstance(ObjectStore.USER_LOG) return obj_store.GenerateUploadUrl(key, content_type=content_type, content_md5=content_md5, expires_i...
'Queries S3 based on specified "user_id", and the specified array of ISO date strings. The results are filtered according to the regular expression "filter". Returns an array of {filename, URL} objects for each date in "iso_dates".'
@classmethod def ListClientLogs(cls, user_id, start_timestamp, end_timestamp, filter, callback):
obj_store = ObjectStore.GetInstance(ObjectStore.USER_LOG) def _OnListDates(date_listings): 'Assemble {filename, url} objects for each date listing.' filter_re = re.compile((filter or '.*')) callback([{'filename': key, 'url': obj_store.GenerateUrl(key)} for logs in da...
'Lists all keys for the given prefix, making multiple calls as necessary.'
@classmethod def _ListAllKeys(cls, obj_store, prefix, callback):
def _AppendResults(results, keys): results += keys if (len(keys) < MAX_CLIENT_LOGS): callback(results) else: obj_store.ListKeys(partial(_AppendResults, results), prefix=prefix, marker=keys[(-1)], maxkeys=MAX_CLIENT_LOGS) obj_store.ListKeys(partial(_AppendResults, ...
'Queries a object by composite hash/range key.'
@classmethod def Query(cls, client, hash_key, range_key, col_names, callback, must_exist=True, consistent_read=False):
cls.KeyQuery(client, key=db_client.DBKey(hash_key=hash_key, range_key=range_key), col_names=col_names, callback=callback, must_exist=must_exist, consistent_read=consistent_read)
'Allocates a new range key via the id_allocator table. Instantiates a new object using provided \'hash_key\' and the allocated \'range_key\' and Invokes the provided callback with new ojb.'
@classmethod def Allocate(cls, client, hash_key, callback):
assert cls._allocator, 'class has no id allocator declared' def _OnAllocate(range_key): o = cls(hash_key, range_key) o._columns[schema.Table.VERSION_COLUMN.name].Set(Version.GetCurrentVersion()) callback(o) cls._allocator.NextId(client, _OnAllocate)
'Executes a range query using the predicate contained in \'range_desc\' to select a set of items. If \'limit\' is not None, then the database will be queried until \'limit\' items have been fetched, or until there are no more items to fetch. If \'limit\' is None, then the first page of results is returned (i.e. whateve...
@classmethod @gen.engine def RangeQuery(cls, client, hash_key, range_desc, limit, col_names, callback, excl_start_key=None, consistent_read=False, count=False, scan_forward=True):
if (limit == 0): assert (not count) callback([]) return if (not count): col_set = cls._CreateColumnSet(col_names) attrs = [cls._table.GetColumn(name).key for name in col_set] else: attrs = None if ((excl_start_key is not None) and (not isinstance(excl_star...
'Query for all items in the specified key range. For each key, invoke the "visitor" function: visitor(object, visit_callback) When the visitor function has completed the visit, it should invoke "visit_callback" with no parameters. Once all object keys have been visited, then "callback" is invoked.'
@classmethod def VisitRange(cls, client, hash_key, range_desc, col_names, visitor, callback, consistent_read=False, scan_forward=True):
def _OnQuery(items): if (len(items) < DBObject._VISIT_LIMIT): barrier_callback = callback else: barrier_callback = partial(_DoQuery, excl_start_key=items[(-1)].GetKey()) with util.Barrier(barrier_callback) as b: for item in items: visitor(i...
'Returns the object\'s composite (hash, range) key.'
def GetKey(self):
return db_client.DBKey(hash_key=self._columns[self._table.hash_key_col.name].Get(), range_key=self._columns[self._table.range_key_col.name].Get())
'Creates an indexing key from the provided object key. This is an amalgamation of the composite key. Separates the hash and range keys by a colon \':\'. This method is symmetric with _ParseIndexKey. Override for more efficient formulation (e.g. Breadcrumb).'
@classmethod def _MakeIndexKey(cls, db_key):
hash_key = util.ConvertToString(db_key.hash_key) range_key = util.ConvertToString(db_key.range_key) index_key = ((('%d:' % len(hash_key)) + hash_key) + range_key) return index_key
'Returns a tuple representing the object\'s composite key by parsing the provided index key. This is symmetric with _MakeIndexKey, and is used to extract the actual object key from results of index queries.'
@classmethod def _ParseIndexKey(cls, index_key):
colon_loc = index_key.find(':') assert (colon_loc != (-1)), index_key hash_key_len = int(index_key[:colon_loc]) index_key = index_key[(colon_loc + 1):] hash_key = index_key[:hash_key_len] range_key = index_key[hash_key_len:] if (cls._table.hash_key_col.value_type == 'N'): hash_key = ...
'Can be overridden by derived range-type classes to specify what class of object can be created from a parsed index key, if not the DBRangeObject-derived class itself. For example, Breadcrumb index keys yield User instances, but Post index keys yield Post instances.'
@classmethod def _GetIndexedObjectClass(cls):
return cls
'Returns true if the "friend" identified by self.friend_id is blocked.'
def IsBlocked(self):
return (self.status == Friend.BLOCKED)
'Decays \'total_shares\' and \'colocated_shares\' based on \'timestamp\'. Updates \'last_share\' and \'last_colocated\' to \'timestamp\'.'
def DecayShares(self, timestamp):
def _ComputeDecay(shares, last_time): if (last_time is None): assert (shares is None), shares return 0 decay = math.exp((((- math.log(2)) * (timestamp - last_time)) / Friend._SHARE_HALF_LIFE)) return (shares * decay) self.total_shares = _ComputeDecay(self.total_sh...
'Decays and updates \'total_shares\' and \'last_share\' based on whether sharing occurred (\'shared\'==True). If \'colocated\', the \'colocated_shares\' and \'last_colocated\' are updated similarly.'
def IncrementShares(self, timestamp, shared, colocated):
self.DecayShares(timestamp) self.total_shares += (1.0 if shared else (-1.0)) if colocated: self.colocated_shares += (1.0 if shared else (-1.0))
'Creates a bi-directional friendship between user_id and friend_id if it does not already exist. Invokes the callback with the pair of friendship objects: [(user_id=>friend_id), (friend_id=>user_id)]'
@classmethod @gen.engine def MakeFriends(cls, client, user_id, friend_id, callback):
from viewfinder.backend.db.user import User (forward_friend, reverse_friend) = (yield [gen.Task(Friend.Query, client, user_id, friend_id, None, must_exist=False), gen.Task(Friend.Query, client, friend_id, user_id, None, must_exist=False)]) if (forward_friend is None): forward_friend = Friend.CreateF...
'Creates bi-directional friendships between all the specified users. Each user will be friends with every other user.'
@classmethod @gen.engine def MakeFriendsWithGroup(cls, client, user_ids, callback):
(yield [gen.Task(Friend.MakeFriends, client, user_id, friend_id) for (index, user_id) in enumerate(user_ids) for friend_id in user_ids[(index + 1):] if (user_id != friend_id)]) callback()
'Ensures that the given user has at least a one-way friend relationship with the given friend. Updates the friend relationship attributes with those given in "friend_dict".'
@classmethod @gen.engine def MakeFriendAndUpdate(cls, client, user_id, friend_dict, callback):
from viewfinder.backend.db.user import User friend = (yield gen.Task(Friend.Query, client, user_id, friend_dict['user_id'], None, must_exist=False)) if (friend is None): friend_user = (yield gen.Task(User.Query, client, friend_dict['user_id'], None, must_exist=False)) if (friend_user is None...
'Updates friend metadata for the relationship between the given user and friend.'
@classmethod @gen.engine def UpdateOperation(cls, client, callback, user_id, friend):
(yield gen.Task(Friend.MakeFriendAndUpdate, client, user_id, friend)) (yield NotificationManager.NotifyUpdateFriend(client, friend)) callback()
'Verify that inserting duplicate operations is a no-op.'
@async_test def testDuplicateOperations(self):
op_id = Operation.ConstructOperationId(self._mobile_dev.device_id, 100) with util.Barrier(self.stop) as b: for i in xrange(10): Operation.CreateAndExecute(self._client, self._user.user_id, self._mobile_dev.device_id, 'HidePhotosOperation.Execute', {'headers': {'op_id': op_id, 'op_timestamp':...
'Verify an operation is retried on failure.'
def testOperationRetries(self):
self._RunAsync(Lock.Acquire, self._client, LockResourceType.Viewpoint, self._user.private_vp_id, Operation.ConstructOperationId(self._mobile_dev.device_id, 123)) op = self._RunAsync(self._UploadPhotoOperation, self._user.user_id, self._mobile_dev.device_id, 1) start = time.time() while True: sel...
'Verify that a failing retriable operation doesn\'t stop other ops from continuing.'
@async_test def testFailedRetriableOp(self):
def _OnQueryOrigOp(orig_op): retry_count = (orig_op.attempts - 1) self._CheckCounters(((3 + 1) + retry_count), retry_count) self.stop() def _OnSecondUploadOp(orig_op, op): 'Wait for the second operation and on completion, query the\n ...
'Verify that a failing aborted operation doesn\'t stop other ops from continuing.'
@async_test def testFailedAbortableOp(self):
def _OnQueryOrigOp(orig_op): self._CheckCounters(3, 0) self.stop() def _OnSecondUploadOp(orig_op, op): 'Wait for the second operation and on completion, query the\n original operation which is still failing. It should...
'ERROR: Try to create an op_id that does not match the client\'s device.'
def testMismatchedDeviceId(self):
op_id = Operation.ConstructOperationId(100, 100) self.assertRaises(PermissionError, self._RunAsync, Operation.CreateAndExecute, self._client, self._user.user_id, self._mobile_dev.device_id, 'ShareNewOperation.Execute', {'headers': {'op_id': op_id, 'op_timestamp': time.time(), 'original_version': message.Message...
'Creates an upload photos operation using seed to create unique ids.'
def _UploadPhotoOperation(self, user_id, device_id, seed, callback, photo_id=None):
request = {'user_id': user_id, 'activity': {'activity_id': Activity.ConstructActivityId(time.time(), device_id, seed), 'timestamp': time.time()}, 'episode': {'user_id': user_id, 'episode_id': Episode.ConstructEpisodeId(time.time(), device_id, seed), 'timestamp': time.time()}, 'photos': [{'photo_id': (Photo.Construc...
'Creates a photo share for a photo which doesn\'t exist.'
def _CreateBadOperation(self, user_id, device_id, callback):
request = {'user_id': user_id, 'activity': {'activity_id': 'a123', 'timestamp': time.time()}, 'viewpoint': {'viewpoint_id': Viewpoint.ConstructViewpointId(100, 100), 'type': Viewpoint.EVENT}, 'episodes': [{'existing_episode_id': 'eg8QVrk3S', 'new_episode_id': 'eg8QVrk3T', 'timestamp': time.time(), 'photo_ids': ['pg...
'Creates a photo share after locking the viewpoint so that the operation will fail and get retried.'
def _CreateBlockedOperation(self, user_id, device_id, callback):
photo_id = Photo.ConstructPhotoId(time.time(), device_id, 123) self._RunAsync(self._UploadPhotoOperation, user_id, device_id, 1, photo_id=photo_id) self._RunAsync(Lock.Acquire, self._client, LockResourceType.Viewpoint, 'vp123', Operation.ConstructOperationId(device_id, 123)) request = {'user_id': user_i...