desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Gathers pre-mutation information: 1. Queries for all viewpoints/followers that contain photos to be unshared. 2. Queries for all episodes and posts that need to be unshared. 3. Checkpoints ids of episodes and photos that need to be unshared. 4. Checkpoints ids of posts that were already removed but not unshared. 5. Ch...
@gen.coroutine def _Check(self):
@gen.coroutine def _QueryPosts(episode_id, photo_ids): 'Queries the posts for the given episode id and photo ids.' post_keys = [DBKey(episode_id, photo_id) for photo_id in photo_ids] posts = (yield gen.Task(Post.BatchQuery, self._client, post_keys, None, mus...
'Updates the database: 1. Unshares all request photos, as well as shares of those photos. 2. Updates cover photo if it was unshared.'
@gen.coroutine def _Update(self):
'Apply updates to db based on previously collected information. Update the affected POSTs\n with UNSHARED labels set.\n ' @gen.coroutine def _UnsharePost(episode_id, photo_id): 'Add UNSHARED label to the given ...
'Makes accounting changes: 1. For unshared photos.'
@gen.coroutine def _Account(self):
acc_accum = AccountingAccumulator() tasks = [] for (viewpoint_id, ep_dicts) in self._unshares_dict.iteritems(): if (len(self._already_removed_ids) > 0): ep_dicts = deepcopy(ep_dicts) for (episode_id, photo_ids) in ep_dicts.iteritems(): ep_dicts[episode_id] = [...
'Creates notifications: 1. Notifies removed followers that viewpoints have new activity. 2. Notify followers of viewpoints that photos have been unshared.'
@gen.coroutine def _Notify(self):
(truncated_ts, device_id, (client_id, server_id)) = Activity.DeconstructActivityId(self._activity['activity_id']) @gen.coroutine def _NotifyOneViewpoint(notify_viewpoint_id): 'Notify all followers of a single viewpoint of the unshare.' if (notify_viewpoint_id != se...
'Recursively accumulates the set of viewpoints, episodes, and posts that are affected by an unshare operation rooted at the specified episodes and posts. Adds the unshare information to "unshares_dict" in the format described in the UnshareOperation._Unshare docstring. Also gets list of ids of posts that have already b...
@gen.coroutine def _GatherUnshares(self, episode, posts):
@gen.coroutine def _ProcessChildEpisode(child_episode, photo_ids_to_unshare): 'For each child episode, query for the set of posts to unshare from each (might be a\n subset of parent posts). Recurse into the child...
'Returns true if the given viewpoint\'s cover photo is in the set of photos which are to be unshared. "ep_dicts" is in the format described in the docstring for _Unshare.'
def _IsCoverPhotoUnshared(self, viewpoint, ep_dicts):
if (not viewpoint.IsDefault()): unshared_posts_set = set(((episode_id, photo_id) for (episode_id, photo_ids) in ep_dicts.iteritems() for photo_id in photo_ids)) assert ((len(unshared_posts_set) == 0) or viewpoint.IsCoverPhotoSet()), viewpoint post_id = (viewpoint.cover_photo['episode_id'], v...
'Entry point called by the operation framework.'
@classmethod @gen.coroutine def Execute(cls, client, activity, user_id, viewpoint):
(yield UpdateViewpointOperation(client, activity, user_id, viewpoint)._UpdateViewpoint())
'Orchestrates the update viewpoint operation by executing each of the phases in turn.'
@gen.coroutine def _UpdateViewpoint(self):
lock = (yield gen.Task(Viewpoint.AcquireLock, self._client, self._viewpoint_id)) try: (yield self._Check()) self._client.CheckDBNotModified() (yield self._Update()) (yield self._Account()) (yield Operation.TriggerFailpoint(self._client)) (yield self._Notify()) ...
'Gathers pre-mutation information: 1. Queries for existing followers and viewpoint. 2. Checkpoints list of followers that need to be revived. Validates the following: 1. Permission to update viewpoint metadata.'
@gen.coroutine def _Check(self):
(self._viewpoint, self._follower) = (yield gen.Task(Viewpoint.QueryWithFollower, self._client, self._user_id, self._viewpoint_id)) if (self._viewpoint is None): raise InvalidRequestError(('Viewpoint "%s" does not exist and so cannot be updated.' % self._viewpoint_id)) if (...
'Updates the database: 1. Revives any followers that have removed the viewpoint. 2. Updates the viewpoint metadata.'
@gen.coroutine def _Update(self):
(yield gen.Task(Follower.ReviveRemovedFollowers, self._client, self._followers)) assert ('update_seq' not in self._vp_dict), self._vp_dict self._viewpoint.UpdateFromKeywords(**self._vp_dict) (yield gen.Task(self._viewpoint.Update, self._client))
'Makes accounting changes: 1. For revived followers.'
@gen.coroutine def _Account(self):
acc_accum = AccountingAccumulator() (yield acc_accum.ReviveFollowers(self._client, self._viewpoint_id, self._revive_follower_ids)) (yield acc_accum.Apply(self._client))
'Creates notifications: 1. Notifies removed followers that conversation has new activity. 2. Notifies existing followers of the viewpoint that metadata has changed.'
@gen.coroutine def _Notify(self):
(yield NotificationManager.NotifyReviveFollowers(self._client, self._viewpoint_id, self._revive_follower_ids, self._op.timestamp)) (yield NotificationManager.NotifyUpdateViewpoint(self._client, self._vp_dict, self._followers, self._prev_values, self._act_dict))
'Entry point called by the operation framework.'
@classmethod @gen.coroutine def Execute(cls, client, target_user_id, source_identity_key):
(yield LinkIdentityOperation(client, target_user_id, source_identity_key)._Link())
'Orchestrates the link identity operation by executing each of the phases in turn.'
@gen.coroutine def _Link(self):
(yield self._Check()) self._client.CheckDBNotModified() (yield self._Update()) (yield Operation.TriggerFailpoint(self._client)) (yield self._Notify())
'Gathers pre-mutation information: 1. Queries for the identity. Validates the following: 1. Identity cannot be already linked to a different user.'
@gen.coroutine def _Check(self):
self._identity = (yield gen.Task(Identity.Query, self._client, self._source_identity_key, None, must_exist=False)) if (self._identity is None): self._identity = Identity.CreateFromKeywords(key=self._source_identity_key, authority='Viewfinder') if ((self._identity.user_id is not None) and (self._iden...
'Updates the database: 1. Binds the identity to the target user.'
@gen.coroutine def _Update(self):
self._identity.expires = 0 self._identity.user_id = self._target_user_id (yield gen.Task(self._identity.Update, self._client))
'Creates notifications: 1. Notifies other users with contacts that are bound to the identity. 2. Notifies target user that identities have changed.'
@gen.coroutine def _Notify(self):
(yield NotificationManager.NotifyLinkIdentity(self._client, self._target_user_id, self._source_identity_key, self._op.timestamp))
'Entry point called by the operation framework.'
@classmethod @gen.coroutine def Execute(cls, client, activity, user_id, viewpoint_id, episodes):
(yield ShareExistingOperation(client, activity, user_id, viewpoint_id, episodes)._ShareExisting())
'Orchestrates the share_existing operation by executing each of the phases in turn.'
@gen.coroutine def _ShareExisting(self):
lock = (yield gen.Task(Viewpoint.AcquireLock, self._client, self._viewpoint_id)) try: (yield self._Check()) self._client.CheckDBNotModified() (yield self._Update()) (yield self._Account()) (yield Operation.TriggerFailpoint(self._client)) (yield self._Notify()) ...
'Gathers pre-mutation information: 1. Existing viewpoint and owner follower. 2. Followers of the existing viewpoint. 3. List of requested episodes and photos to share. 4. Checkpoints list of episode and post ids that need to be (re)created. 5. Checkpoints list of followers that need to be revived. 6. Checkpoints boolea...
@gen.coroutine def _Check(self):
(self._viewpoint, self._follower) = (yield gen.Task(Viewpoint.QueryWithFollower, self._client, self._user_id, self._viewpoint_id)) if ((self._follower is None) or (not self._follower.CanContribute())): raise PermissionError(('User %d does not have permission to contribute to v...
'Updates the database: 1. Revives any followers that have removed the viewpoint. 2. Creates new episodes and posts. 3. Creates cover photo, if needed.'
@gen.coroutine def _Update(self):
(yield gen.Task(Follower.ReviveRemovedFollowers, self._client, self._followers)) (yield self._CreateNewEpisodesAndPosts(self._new_ep_dicts, self._new_ids)) if self._need_cover_photo: self._viewpoint.cover_photo = Viewpoint.SelectCoverPhotoFromEpDicts(self._new_ep_dicts) (yield gen.Task(self....
'Makes accounting changes: 1. For revived followers. 2. For new photos that were shared.'
@gen.coroutine def _Account(self):
photo_ids = [Post.DeconstructPostId(id)[1] for id in self._new_ids if id.startswith(IdPrefix.Post)] acc_accum = AccountingAccumulator() (yield acc_accum.ReviveFollowers(self._client, self._viewpoint_id, self._revive_follower_ids)) (yield acc_accum.SharePhotos(self._client, self._user_id, self._viewpoint...
'Creates notifications: 1. Notifies removed followers that conversation has new activity. 2. Notifies existing followers of the viewpoint that photos have been added.'
@gen.coroutine def _Notify(self):
(yield NotificationManager.NotifyReviveFollowers(self._client, self._viewpoint_id, self._revive_follower_ids, self._op.timestamp)) (yield NotificationManager.NotifyShareExisting(self._client, self._viewpoint_id, self._followers, self._act_dict, self._ep_dicts, self._need_cover_photo))
'For each follower that has enabled auto-save for this viewpoint, trigger save_photos operation that will save the shared photos to their default viewpoint.'
@gen.coroutine def _AutoSave(self):
source_ep_ids = [ep_dict['new_episode_id'] for ep_dict in self._ep_dicts] for follower in self._followers: if (not follower.ShouldAutoSave()): continue if follower.IsRemoved(): continue follower_user = (yield gen.Task(User.Query, self._client, follower.user_id, No...
'Entry point called by the operation framework.'
@classmethod @gen.coroutine def Execute(cls, client, activity, target_user_id, source_user_id):
(yield MergeAccountsOperation(client, activity, target_user_id, source_user_id)._Merge())
'Orchestrates the merge operation.'
@gen.coroutine def _Merge(self):
op_lock = (yield gen.Task(Lock.Acquire, self._client, LockResourceType.Operation, str(self._source_user_id), owner_id=self._op.operation_id)) try: state = (self._op.checkpoint['state'] if self._op.checkpoint else 'vp') if (state == 'vp'): (yield self._MergeViewpoints()) (...
'Loops over all viewpoints followed by the source user and merges any that have not been removed. Applies user accounting information accumulated in _MergeOneViewpoint.'
@gen.coroutine def _MergeViewpoints(self):
if (self._op.checkpoint is not None): start_key = self._op.checkpoint['id'] (yield self._MergeOneViewpoint(start_key)) else: start_key = None while True: follower_list = (yield gen.Task(Follower.RangeQuery, self._client, self._source_user_id, range_desc=None, limit=MergeAccou...
'Adds the target user as a follower of the given viewpoint owned by the source user. Accumulates the size of all viewpoints that are merged. Creates notifications for the merged viewpoint. Sets a checkpoint containing follower and accounting information to be used if a restart occurs.'
@gen.coroutine def _MergeOneViewpoint(self, viewpoint_id):
viewpoint = (yield gen.Task(Viewpoint.Query, self._client, viewpoint_id, None)) if (viewpoint.IsDefault() or viewpoint.IsSystem()): return vp_lock = (yield gen.Task(Viewpoint.AcquireLock, self._client, viewpoint_id)) try: if (self._op.checkpoint is None): (existing_follower_i...
'Re-binds all identities attached to the source user to the target user. Sends corresponding notifications for any merged identities. Sets a checkpoint so that the exact same set of identities will be merged if a restart occurs.'
@gen.coroutine def _MergeIdentities(self):
if (self._op.checkpoint is None): query_expr = ('identity.user_id={id}', {'id': self._source_user_id}) identity_keys = (yield gen.Task(Identity.IndexQueryKeys, self._client, query_expr, limit=MergeAccountsOperation._MAX_IDENTITIES)) checkpoint = {'state': 'id', 'ids': [key.hash_key for key i...
'Queries all notifications intended for \'user_id\' with max \'limit\' notifications since \'start_key\'. Creates a special "clear_badges" notification once all notifications have been queried. This resets the current badge counter and results in the push of an alert to all *other* devices so that their badge number ca...
@classmethod @gen.coroutine def QuerySince(cls, client, user_id, device_id, start_key, limit=None, scan_forward=True):
from viewfinder.backend.op.alert_manager import AlertManager limit = (NotificationManager._QUERY_LIMIT if (limit is None) else limit) notifications = (yield gen.Task(Notification.RangeQuery, client, hash_key=user_id, range_desc=None, limit=limit, col_names=None, excl_start_key=start_key, consistent_read=Tru...
'Notifies the specified followers that they have been added to the specified viewpoint. Invalidates the entire viewpoint so that the new follower will load it in its entirety. Also notifies all existing followers of the viewpoint that new followers have been added. Creates an add_followers activity in the viewpoint.'
@classmethod @gen.coroutine def NotifyAddFollowers(cls, client, viewpoint_id, existing_followers, new_followers, contact_user_ids, act_dict, timestamp):
activity_func = NotificationManager._CreateActivityFunc(act_dict, Activity.CreateAddFollowers, contact_user_ids) new_follower_ids = set((follower.user_id for follower in new_followers)) def _GetInvalidate(follower_id): if (follower_id in new_follower_ids): return {'viewpoints': [Notifica...
'Sends notifications that the given identities have been linked to new prospective user accounts. Sends notifications to all users that have a contact with a matching identity.'
@classmethod @gen.coroutine def NotifyCreateProspective(cls, client, prospective_identity_keys, timestamp):
(yield [NotificationManager._NotifyUsersWithContact(client, 'create prospective user', identity_key, timestamp) for identity_key in prospective_identity_keys])
'Adds a notification for the specified user that new contacts have been fetched and need to be pulled to the client. Invalidates all the newly fetched contacts, which all have sort_key greater than "timestamp".'
@classmethod @gen.coroutine def NotifyFetchContacts(cls, client, user_id, timestamp, reload_all):
invalidate = {'contacts': {'start_key': Contact.CreateSortKey(None, (0 if reload_all else timestamp))}} if reload_all: invalidate['contacts']['all'] = True (yield NotificationManager.CreateForUser(client, user_id, 'fetch_contacts', invalidate=invalidate))
'Adds a notification for the specified user that photos have been marked as hidden from his personal collection. Invalidates all episodes that contain the posts to be hidden. No activity is created, since other followers of the affected viewpoint(s) are not affected by this action.'
@classmethod @gen.coroutine def NotifyHidePhotos(cls, client, user_id, ep_dicts):
invalidate = {'episodes': [{'episode_id': ep_dict['episode_id'], 'get_photos': True} for ep_dict in ep_dicts]} (yield NotificationManager.CreateForUser(client, user_id, 'hide_photos', invalidate=invalidate))
'Notifies all users referencing any contact having the specified identity that the contact has been modified. Invalidates the contact metadata so that the user will re-load it. Notifies the new owner of the identity that he needs to refresh his identity list.'
@classmethod @gen.coroutine def NotifyLinkIdentity(cls, client, target_user_id, identity_key, timestamp):
(yield NotificationManager._NotifyUsersWithContact(client, 'link identity', identity_key, timestamp)) (yield NotificationManager._NotifyUserInvalidateSelf(client, 'link user', target_user_id))
'Notifies all users referencing any contact having the specified identity that the contact has been modified. Invalidates the contact metadata so that the user will re-load it. Notifies all owners of the identities and invalidates their user id. Causes an identity list refresh.'
@classmethod @gen.coroutine def NotifyMergeIdentities(cls, client, target_user_id, identity_keys, timestamp):
(yield [NotificationManager._NotifyUsersWithContact(client, 'merge identities', identity_key, timestamp) for identity_key in identity_keys]) (yield NotificationManager._NotifyUserInvalidateSelf(client, 'merge users', target_user_id))
'Notifies the target user that he has been added to the specified viewpoint. Invalidates the entire viewpoint so that the target user will load it in its entirety. Also notifies all specified existing followers of the viewpoint that a new follower has been added. Creates a merge activity in the viewpoint.'
@classmethod @gen.coroutine def NotifyMergeViewpoint(cls, client, viewpoint_id, existing_followers, target_follower, source_user_id, act_dict, timestamp):
activity_func = NotificationManager._CreateActivityFunc(act_dict, Activity.CreateMergeAccounts, target_follower.user_id, source_user_id) def _GetInvalidate(follower_id): if (follower_id == target_follower.user_id): return {'viewpoints': [NotificationManager._CreateViewpointInvalidation(viewp...
'Notifies specified followers that a new comment has been posted to the viewpoint. Invalidates this comment and all comments posted in the future by setting the start_key. Doing this enables the client to efficiently "stack" comment invalidations by fetching all comments beyond the lowest start_key in a single call to ...
@classmethod @gen.coroutine def NotifyPostComment(cls, client, followers, act_dict, cm_dict):
from viewfinder.backend.db.comment import Comment activity_func = NotificationManager._CreateActivityFunc(act_dict, Activity.CreatePostComment, cm_dict) if (len(cm_dict['message']) > NotificationManager.MAX_INLINE_COMMENT_LEN): start_key = Comment.ConstructCommentId(cm_dict['timestamp'], 0, 0) ...
'Notifies other devices of the user that a new subscriptrion has been recorded and needs to be fetched.'
@classmethod @gen.coroutine def NotifyRecordSubscription(cls, client, user_id):
invalidate = {'users': [user_id]} (yield NotificationManager.CreateForUser(client, user_id, 'record_subscription', invalidate=invalidate))
'Notifies friends and contact owners of the user when one (or several) of the following have occurred: 1. One or more friend-visible user attributes have been updated (such as name). 2. The user is registering for the first time (i.e. was a prospective user before). In this case, "is_first_register" is true. 3. A new i...
@classmethod @gen.coroutine def NotifyRegisterUser(cls, client, user_dict, ident_dict, timestamp, is_first_register, is_linking):
from viewfinder.backend.op.alert_manager import AlertManager if (is_first_register or is_linking): name = ('first register contact' if is_first_register else 'link contact') (yield NotificationManager._NotifyUsersWithContact(client, name, ident_dict['key'], timestamp)) if any(((attr...
'Adds a notification for the specified user that contacts have been removed and need to be removed from the client. Invalidates all the newly removed contacts, which all have sort_key greater than or equal to "timestamp".'
@classmethod @gen.coroutine def NotifyRemoveContacts(cls, client, user_id, timestamp, reload_all):
invalidate = {'contacts': {'start_key': Contact.CreateSortKey(None, (0 if reload_all else timestamp))}} if reload_all: invalidate['contacts']['all'] = True (yield NotificationManager.CreateForUser(client, user_id, 'remove_contacts', invalidate=invalidate))
'Notifies removed followers that they have been removed from the specified viewpoint. Invalidates the viewpoint attributes for those followers so that they will get the REMOVED label. Also notifies all existing followers of the viewpoint that they need to reload the list of viewpoint followers. Creates a remove_followe...
@classmethod @gen.coroutine def NotifyRemoveFollowers(cls, client, viewpoint_id, existing_followers, remove_ids, act_dict):
activity_func = NotificationManager._CreateActivityFunc(act_dict, Activity.CreateRemoveFollowers, remove_ids) remove_id_set = set(remove_ids) def _GetInvalidate(follower_id): if (follower_id in remove_id_set): return {'viewpoints': [{'viewpoint_id': viewpoint_id, 'get_attributes': True}]...
'Adds a notification for the specified user that photos have been marked as removed from his personal collection. Invalidates all episodes that contain the posts to be removed. No activity is created, since other followers of the affected viewpoint(s) are not affected by this action.'
@classmethod @gen.coroutine def NotifyRemovePhotos(cls, client, user_id, ep_dicts):
invalidate = {'episodes': [{'episode_id': ep_dict['episode_id'], 'get_photos': True} for ep_dict in ep_dicts]} (yield NotificationManager.CreateForUser(client, user_id, 'remove_photos', invalidate=invalidate))
'Adds a notification for the specified user that a viewpoint have been marked as removed from their inbox. Invalidates all viewpoints that were removed. No activity is created since other followers of the affected viewpoint(s) are not affected by this action.'
@classmethod @gen.coroutine def NotifyRemoveViewpoint(cls, client, user_id, viewpoint_id):
invalidate = {'viewpoints': [{'viewpoint_id': viewpoint_id, 'get_attributes': True}]} (yield NotificationManager.CreateForUser(client, user_id, 'remove_viewpoint', invalidate=invalidate, viewpoint_id=viewpoint_id))
'Adds a notification for each of the followers that have been revived. The notification invalidates the entire viewpoint in order to force the client to load it in its entirety.'
@classmethod @gen.coroutine def NotifyReviveFollowers(cls, client, viewpoint_id, revive_follower_ids, timestamp):
if (len(revive_follower_ids) > 0): invalidate = {'viewpoints': [NotificationManager._CreateViewpointInvalidation(viewpoint_id)]} (yield [NotificationManager.CreateForUser(client, follower_id, 'revive followers', invalidate=invalidate, viewpoint_id=viewpoint_id) for follower_id in revive_follower_...
'Creates notification and activity that new episode(s) have been created in a user\'s default viewpoint and filled with saved photos from other viewpoint(s). Since only the owning user follows the default viewpoint, the _NotifyFollowers call will just end up creating a notification for a single user. The new episode(s)...
@classmethod @gen.coroutine def NotifySavePhotos(cls, client, viewpoint_id, follower, act_dict, ep_dicts):
activity_func = NotificationManager._CreateActivityFunc(act_dict, Activity.CreateSavePhotos, ep_dicts) invalidate = {'episodes': [NotificationManager._CreateEpisodeInvalidation(ep_dict['new_episode_id']) for ep_dict in ep_dicts]} (yield NotificationManager._NotifyFollowers(client, viewpoint_id, [follower], ...
'Notifies the specified followers of an existing viewpoint that new photos have been shared with them. Invalidates all shared episodes. Creates a share activity in the viewpoint.'
@classmethod @gen.coroutine def NotifyShareExisting(cls, client, viewpoint_id, followers, act_dict, ep_dicts, viewpoint_updated):
activity_func = NotificationManager._CreateActivityFunc(act_dict, Activity.CreateShareExisting, ep_dicts) invalidate = {'episodes': [NotificationManager._CreateEpisodeInvalidation(ep_dict['new_episode_id']) for ep_dict in ep_dicts]} if viewpoint_updated: invalidate['viewpoints'] = [{'viewpoint_id': ...
'Notifies all followers of a new viewpoint that new photos have been shared with them. Invalidates the new viewpoint in its entirety. Notifies the owners of any contacts that have been newly registered. Creates a share activity in the viewpoint.'
@classmethod @gen.coroutine def NotifyShareNew(cls, client, vp_dict, followers, contact_user_ids, act_dict, ep_dicts, timestamp):
activity_func = NotificationManager._CreateActivityFunc(act_dict, Activity.CreateShareNew, ep_dicts, contact_user_ids) invalidate = {'viewpoints': [NotificationManager._CreateViewpointInvalidation(vp_dict['viewpoint_id'])]} (yield NotificationManager._NotifyFollowers(client, vp_dict['viewpoint_id'], followe...
'Notifies all friends of the specified user, and all users with the terminated user as a contact that the account has been terminated.'
@classmethod @gen.coroutine def NotifyTerminateAccount(cls, client, user_id):
invalidate = {'users': [user_id]} (yield NotificationManager._NotifyFriends(client, 'terminate_account', user_id, invalidate))
'Notifies all followers of a viewpoint that photos have been unshared from the viewpoint. Invalidates all episodes that contain any of the unshared photos. Creates an unshare activity in the viewpoint.'
@classmethod @gen.coroutine def NotifyUnshare(cls, client, viewpoint_id, followers, act_dict, ep_dicts, viewpoint_updated):
activity_func = NotificationManager._CreateActivityFunc(act_dict, Activity.CreateUnshare, ep_dicts) invalidate = {'episodes': [NotificationManager._CreateEpisodeInvalidation(ep_dict['episode_id']) for ep_dict in ep_dicts]} if viewpoint_updated: invalidate['viewpoints'] = [{'viewpoint_id': viewpoint_...
'Notifies all followers of the specified viewpoint that an episode within the viewpoint has been updated. Invalidates the metadata on the episode (but not the photos). Creates an update_episode activity in the viewpoint.'
@classmethod @gen.coroutine def NotifyUpdateEpisode(cls, client, viewpoint_id, followers, act_dict, ep_dict):
activity_func = NotificationManager._CreateActivityFunc(act_dict, Activity.CreateUpdateEpisode, ep_dict) invalidate = {'episodes': [{'episode_id': ep_dict['episode_id'], 'get_attributes': True}]} (yield NotificationManager._NotifyFollowers(client, viewpoint_id, followers, invalidate, activity_func))
'Adds a notification for the current user that friend metadata has changed. Since this only affects the current user, send invalidations to the current user\'s devices only.'
@classmethod @gen.coroutine def NotifyUpdateFriend(cls, client, friend_dict):
invalidate = {'users': [friend_dict['user_id']]} (yield NotificationManager.CreateForUser(client, NotificationManager._GetOperation().user_id, 'update_friend', invalidate=invalidate))
'Adds a notification for the current user that follower metadata has changed. Since this only affects that user, invalidates the viewpoint metadata only for that user. No activity is created, since other followers of the viewpoint are not affected by this action.'
@classmethod @gen.coroutine def NotifyUpdateFollower(cls, client, foll_dict):
viewpoint_id = foll_dict['viewpoint_id'] seq_num_pair = None invalidate = {'viewpoints': [{'viewpoint_id': viewpoint_id, 'get_attributes': True}]} if ('viewed_seq' in foll_dict): seq_num_pair = (None, foll_dict['viewed_seq']) if (len(foll_dict) == 2): invalidate = None (y...
'Notifies all friends of the specified user that one or more friend-visible attributes have been updated (such as name). If only private settings have been updated, only notify the user\'s other devices of the changes.'
@classmethod @gen.coroutine def NotifyUpdateUser(cls, client, user_dict, settings_dict, timestamp):
user_id = user_dict['user_id'] if any(((attr_name not in ('user_id', 'pwd_hash', 'salt')) for attr_name in user_dict.keys())): invalidate = {'users': [user_id]} (yield NotificationManager._NotifyFriends(client, 'update_user', user_dict['user_id'], invalidate)) else: invalidate = {'us...
'Notifies all followers of the specified viewpoint that the viewpoint\'s metadata has been updated. "prev_values" contains the old values of title and/or cover photo, if they were updated. Invalidates the metadata on the viewpoint.'
@classmethod @gen.coroutine def NotifyUpdateViewpoint(cls, client, vp_dict, followers, prev_values, act_dict):
activity_func = NotificationManager._CreateActivityFunc(act_dict, Activity.CreateUpdateViewpoint, prev_values) invalidate = {'viewpoints': [{'viewpoint_id': vp_dict['viewpoint_id'], 'get_attributes': True}]} (yield NotificationManager._NotifyFollowers(client, vp_dict['viewpoint_id'], followers, invalidate, ...
'Notifies all users referencing a contact having the specified identity that the contact has been modified. Invalidates the contact metadata so that the user will re-load it. Also invalidates the user itself, which causes a refresh of the identity list.'
@classmethod @gen.coroutine def NotifyUnlinkIdentity(cls, client, user_id, identity_key, timestamp):
(yield NotificationManager._NotifyUsersWithContact(client, 'unlink_identity', identity_key, timestamp)) (yield NotificationManager._NotifyUserInvalidateSelf(client, 'unlink_self', user_id))
'Adds a notification for the specified user that new contacts have been uploaded/updated and need to be pulled to the client. Invalidates all the newly uploaded/updated contacts, which all have sort_key greater than or equal to "timestamp".'
@classmethod @gen.coroutine def NotifyUploadContacts(cls, client, user_id, timestamp):
invalidate = {'contacts': {'start_key': Contact.CreateSortKey(None, timestamp)}} (yield NotificationManager.CreateForUser(client, user_id, 'upload_contacts', invalidate=invalidate))
'Creates notification and activity that a new episode in a user\'s default viewpoint has been created and filled with uploaded photos. Since only the owning user follows the default viewpoint, the _NotifyFollowers call will just end up creating a notification for a single user. The new episode is invalidated so that ot...
@classmethod @gen.coroutine def NotifyUploadEpisode(cls, client, viewpoint_id, follower, act_dict, ep_dict, ph_dicts):
activity_func = NotificationManager._CreateActivityFunc(act_dict, Activity.CreateUploadEpisode, ep_dict, ph_dicts) invalidate = {'episodes': [NotificationManager._CreateEpisodeInvalidation(ep_dict['episode_id'])]} (yield NotificationManager._NotifyFollowers(client, viewpoint_id, [follower], invalidate, acti...
'Gets the current operation, which must be in-scope.'
@classmethod def _GetOperation(cls):
operation = Operation.GetCurrent() assert (operation.operation_id is not None), 'there must be current operation in order to create notification' return operation
'Returns a coroutine with following signature: activity_func(client, user_id, viewpoint_id, update_seq) When this function is invoked, it executes "create_func", which is one of the constructor methods on the Activity class. It invokes the callback with the resulting activity.'
@classmethod def _CreateActivityFunc(cls, act_dict, create_func, *args):
@gen.coroutine def _CreateActivity(client, user_id, viewpoint_id, update_seq): activity = (yield create_func(client, user_id, viewpoint_id, act_dict['activity_id'], act_dict['timestamp'], update_seq, *args)) raise gen.Return(activity) return _CreateActivity
'Create invalidation for entire viewpoint, including all metadata and all collections. NOTE: Make sure to update this when new viewpoint collections are added.'
@classmethod def _CreateViewpointInvalidation(cls, viewpoint_id):
return {'viewpoint_id': viewpoint_id, 'get_attributes': True, 'get_followers': True, 'get_activities': True, 'get_episodes': True, 'get_comments': True}
'Create invalidation for entire episode, including all metadata and all collections. NOTE: Make sure to update this when new episode collections are added.'
@classmethod def _CreateEpisodeInvalidation(cls, episode_id):
return {'episode_id': episode_id, 'get_attributes': True, 'get_photos': True}
'Adds a notification to all users having contacts with the specified identity. Invalidates all contacts added after the specified timestamp.'
@classmethod @gen.coroutine def _NotifyUsersWithContact(cls, client, name, identity_key, timestamp):
@gen.coroutine def _VisitContactUserId(contact_user_id): (yield NotificationManager.CreateForUser(client, contact_user_id, name, invalidate=invalidate)) invalidate = {'contacts': {'start_key': Contact.CreateSortKey(None, timestamp)}} (yield gen.Task(Contact.VisitContactUserIds, client, identity_...
'Adds a notification for the user with \'user_id\'. Invalidates this user to trigger a refresh of user information (eg: list of identities).'
@classmethod @gen.coroutine def _NotifyUserInvalidateSelf(cls, client, name, user_id):
(yield NotificationManager.CreateForUser(client, user_id, name, invalidate={'users': [user_id]}))
'Adds a notification to all friends of the specified user that one or more friend-visible attributes have been updated. Always send the notification to every friend, even if that "friend" has blocked the user in question. Also send a notification to the user\'s other devices.'
@classmethod @gen.coroutine def _NotifyFriends(cls, client, name, user_id, invalidate):
from viewfinder.backend.db.friend import Friend @gen.coroutine def _VisitFriend(friend): (yield NotificationManager.CreateForUser(client, friend.friend_id, name, invalidate=invalidate)) (yield gen.Task(Friend.VisitRange, client, user_id, None, None, _VisitFriend))
'Adds a notification for each of the given followers that the specified viewpoint has structurally changed. If "invalidate" is a dict, then uses that directly. Otherwise, assumes it\'s a function that takes a follower id and returns the invalidate dict for that follower. If "always_notify" is true, then always send not...
@classmethod @gen.coroutine def _NotifyFollowers(cls, client, viewpoint_id, followers, invalidate, activity_func, inc_badge=False, always_notify=False):
from viewfinder.backend.db.viewpoint import Viewpoint from viewfinder.backend.op.alert_manager import AlertManager operation = NotificationManager._GetOperation() @gen.coroutine def _NotifyOneFollower(viewpoint, seq_num_pair, activity, follower, follower_settings): 'Creates a notificat...
'Calls Notification.CreateForUser with the current operation.'
@classmethod @gen.coroutine def CreateForUser(cls, client, user_id, name, invalidate=None, activity_id=None, viewpoint_id=None, seq_num_pair=None, inc_badge=False, consistent_read=False):
operation = NotificationManager._GetOperation() notification = (yield Notification.CreateForUser(client, operation, user_id, name, invalidate, activity_id, viewpoint_id, seq_num_pair, inc_badge, consistent_read)) raise gen.Return(notification)
'Entry point called by the operation framework.'
@classmethod @gen.coroutine def Execute(cls, client, user_id, contacts):
(yield UploadContactsOperation(client, user_id, contacts)._UploadContacts())
'Orchestrates the upload contacts operation by executing each of the phases in turn.'
@gen.coroutine def _UploadContacts(self):
(yield self._Check()) self._client.CheckDBNotModified() (yield self._Update()) (yield Operation.TriggerFailpoint(self._client)) (yield self._Notify())
'Check and prepare for update. Query for all of the existing contacts of the user so that any non-removed matches can be skipped and removed matches can be replaced. Complete construction of the contact dict. Check that the upload won\'t cause the max number of contacts to be exceeded.'
@gen.coroutine def _Check(self):
(existing_contacts_dict, self._contacts_to_delete) = (yield UploadContactsOperation._GetAllContactsWithDedup(self._client, self._user_id)) total_contact_count = 0 for existing_contact in existing_contacts_dict.itervalues(): if (not existing_contact.IsRemoved()): total_contact_count += 1 ...
'Perform insert/(replace) of uploaded contacts as well as deletion of duplicate contacts.'
@gen.coroutine def _Update(self):
@gen.coroutine def _ReplaceRemovedContact(contact_dict_to_insert, removed_contact_to_delete): contact_to_insert = Contact.CreateFromKeywords(**contact_dict_to_insert) (yield gen.Task(contact_to_insert.Update, self._client)) if (removed_contact_to_delete is not None): (yield O...
'Creates notifications: Notify of all contacts with timestamp greater than or equal to current.'
@gen.coroutine def _Notify(self):
(yield NotificationManager.NotifyUploadContacts(self._client, self._user_id, self._notify_timestamp))
'Entry point called by the operation framework.'
@classmethod @gen.coroutine def Execute(cls, client, activity, user_id, episode, photos):
user = (yield gen.Task(User.Query, client, user_id, None)) (yield UploadEpisodeOperation(client, activity, user, episode, photos)._UploadEpisode())
'Orchestrates the upload_episode operation by executing each of the phases in turn.'
@gen.coroutine def _UploadEpisode(self):
lock = (yield gen.Task(Viewpoint.AcquireLock, self._client, self._user.private_vp_id)) try: (yield self._Check()) self._client.CheckDBNotModified() (yield self._Update()) (yield self._Account()) (yield Operation.TriggerFailpoint(self._client)) (yield self._Notify(...
'Gathers pre-mutation information: 1. Episode and photos to upload. 2. Checkpoints list of episode and photo ids that need to be (re)created. 3. Checkpoints whether to attempt to set episode location and placemark from photos. Validates the following: 1. Permissions to upload to the given episode. 2. Each photo can be ...
@gen.coroutine def _Check(self):
self._episode = (yield gen.Task(Episode.Query, self._client, self._episode_id, None, must_exist=False)) if ((self._episode is not None) and (self._episode.parent_ep_id != None)): raise InvalidRequestError('Cannot upload photos into an episode that was saved.') photo_keys = [D...
'Updates the database: 1. Creates episode if it did not exist, or sets episode\'s location/placemark. 2. Creates posts that did not previously exist. 3. Creates photos that did not previously exist. 4. Updates photo MD5 values if they were given in a re-upload.'
@gen.coroutine def _Update(self):
if (self._set_location or self._set_placemark): for ph_dict in self._ph_dicts: if (('location' not in self._ep_dict) and ('location' in ph_dict)): self._ep_dict['location'] = ph_dict['location'] if (('placemark' not in self._ep_dict) and ('placemark' in ph_dict)): ...
'Makes accounting changes: 1. For new photos that were uploaded.'
@gen.coroutine def _Account(self):
new_ph_dicts = [ph_dict for ph_dict in self._ph_dicts if (ph_dict['photo_id'] in self._new_ids)] acc_accum = AccountingAccumulator() (yield acc_accum.UploadEpisode(self._client, self._user.user_id, self._user.private_vp_id, new_ph_dicts)) (yield acc_accum.Apply(self._client))
'Creates notifications: 1. Notifies all devices of the default viewpoint owner that new photos have been uploaded.'
@gen.coroutine def _Notify(self):
follower = (yield gen.Task(Follower.Query, self._client, self._user.user_id, self._user.private_vp_id, None)) (yield NotificationManager.NotifyUploadEpisode(self._client, self._user.private_vp_id, follower, self._act_dict, self._ep_dict, self._ph_dicts))
'Entry point called by the operation framework.'
@classmethod @gen.coroutine def Execute(cls, client, activity, user_id, viewpoint_id, contacts):
(yield AddFollowersOperation(client, activity, user_id, viewpoint_id, contacts)._AddFollowers())
'Orchestrates the add followers operation by executing each of the phases in turn.'
@gen.coroutine def _AddFollowers(self):
lock = (yield gen.Task(Viewpoint.AcquireLock, self._client, self._viewpoint_id)) try: (yield self._Check()) self._client.CheckDBNotModified() (yield self._Update()) (yield self._Account()) (yield Operation.TriggerFailpoint(self._client)) (yield self._Notify()) ...
'Gathers pre-mutation information: 1. Queries for existing followers and viewpoint. 2. Checkpoints list of followers that need to be revived. 3. Checkpoints list of contacts that need to be made prospective users. 4. Checkpoints list of contacts that are already following the viewpoint. Validates the following: 1. Max ...
@gen.coroutine def _Check(self):
(self._viewpoint, self._follower) = (yield gen.Task(Viewpoint.QueryWithFollower, self._client, self._user_id, self._viewpoint_id)) if ((self._follower is None) or (not self._follower.CanContribute())): raise PermissionError(('User %d does not have permission to add followers t...
'Updates the database: 1. Revives any followers that have removed the viewpoint. 2. Creates prospective users. 3. Adds the followers to the viewpoint.'
@gen.coroutine def _Update(self):
(yield self._ResolveContacts(self._contact_dicts, self._contact_ids, reason=('add_follower=%d' % self._user_id))) (yield gen.Task(Follower.ReviveRemovedFollowers, self._client, self._existing_followers)) existing_follower_ids = set((follower.user_id for follower in self._existing_followers if (not follower....
'Makes accounting changes: 1. For revived followers. 2. For new followers.'
@gen.coroutine def _Account(self):
acc_accum = AccountingAccumulator() (yield acc_accum.ReviveFollowers(self._client, self._viewpoint_id, self._revive_follower_ids)) (yield acc_accum.AddFollowers(self._client, self._viewpoint_id, self._new_follower_ids)) (yield acc_accum.Apply(self._client))
'Creates notifications: 1. Notifies removed followers that conversation has new activity. 2. Notifies users with contacts that have become prospective users. 3. Notifies existing followers of the viewpoint that new followers have been added. 4. Notifies new followers that they have been added to a viewpoint.'
@gen.coroutine def _Notify(self):
identity_keys = [contact_dict['identity'] for (contact_dict, (user_exists, user_id, webapp_dev_id)) in zip(self._contact_dicts, self._contact_ids) if (not user_exists)] (yield NotificationManager.NotifyCreateProspective(self._client, identity_keys, self._op.timestamp)) (yield NotificationManager.NotifyReviv...
'Entry point called by the operation framework.'
@classmethod @gen.coroutine def Execute(cls, client, user_id, contacts):
(yield RemoveContactsOperation(client, user_id, contacts)._RemoveContacts())
'Orchestrates the remove contacts operation by executing each of the phases in turn.'
@gen.coroutine def _RemoveContacts(self):
(yield self._Check()) self._client.CheckDBNotModified() (yield self._Update()) (yield Operation.TriggerFailpoint(self._client)) (yield self._Notify())
'Check and prepare for remove. Along with checks, builds two lists for the Update phase. 1) self._contacts_to_delete: list of contacts which have been superseded by more recent contacts with the same contact_id and because they no longer serve any purpose should be deleted. These may exist due to lack of transactional...
@gen.coroutine def _Check(self):
for request_contact_id in self._request_contact_ids: if (Contact.GetContactSourceFromContactId(request_contact_id) not in Contact.UPLOAD_SOURCES): raise InvalidRequestError(BAD_CONTACT_SOURCE, Contact.GetContactSourceFromContactId(request_contact_id)) (existing_contacts_dict, self._contacts_...
'Perform delete/insert of contacts as determined by check phase.'
@gen.coroutine def _Update(self):
@gen.coroutine def _RemoveContact(contact_to_remove): "Insert a 'removed' contact with the same contact_id as the one being removed and then\n delete the actual contact that's being removed." removed_contact = Con...
'Creates notifications: Notify of all contacts with timestamp greater than or equal to current. May also indicate that all \'removed\' contacts have been deleted and the client should reset by reloading all contacts.'
@gen.coroutine def _Notify(self):
(yield NotificationManager.NotifyRemoveContacts(self._client, self._user_id, self._notify_timestamp, self._removed_contacts_reset))
'Construct a new UserOpManager in order to execute operations for the specified user. Each time that no more operations can be executed for the user, "callback" is invoked. This can happen when the operation lock cannot be acquired or when all operations have been executed, blocked, or quarantined.'
def __init__(self, client, op_map, user_id, callback):
self._client = OpMgrDBClient(client) self._op_map = op_map self._user_id = user_id self._sync_cb_map = defaultdict(list) self._callback = stack_context.wrap(callback) self._is_executing = False
'Invokes "callback" when there is no current work do be done. To be used for cleanup in tests. Only needed after a previous run has failed.'
def Drain(self, callback):
self._callback = stack_context.wrap(callback) self.Execute()
'Starts execution of all operations for the managed user. Once all operations have been completed, or if another server is already executing the operations, then the callback passed to __init__ is invoked. If the "operation_id" argument is provided, it is used as a hint as to where to start execution. However, if an op...
@gen.engine def Execute(self, operation_id=None, wait_callback=None):
def _OnCompletedOp(type=None, value=None, tb=None): "Wraps the caller's callback so that it is called in the original context, and any\n exception is raised in the original context.\n " if ((typ...
'Tries to acquire the operation lock. If it is acquired, queries for each operation owned by the user and executes each in turn.'
@gen.coroutine def _ExecuteAll(self, operation_id=None):
self._requery = False results = (yield gen.Task(Lock.TryAcquire, self._client, LockResourceType.Operation, str(self._user_id), resource_data=operation_id, detect_abandonment=True)) (self._lock, status) = results.args if (status == Lock.FAILED_TO_ACQUIRE_LOCK): for operation_id in self._sync_cb_m...
'Executes the operation by marshalling the JSON-encoded op data as arguments to the operation method. The execution of the operation is wrapped in an execution scope, which will capture all logging during the execution of this operation.'
@gen.coroutine def _ExecuteOp(self, op):
if (op.backoff is not None): (yield gen.Task(IOLoop.current().add_timeout, op.backoff)) with OpContext.current().Enter(op): op_entry = self._op_map[op.method] op_args = json.loads(op.json) if (self._lock.resource_data != op.operation_id): self._lock.resource_data = op...
'The given operation has failed in such a way that we know it will never succeed so we will abort it. If it modified the DB before the failure, we log an error with callstack of db modification and call retry logic so that it sticks around in operation table for analysis.'
@gen.coroutine def _AbortOp(self, op, type, value, tb):
if self._client.HasDBBeenModified(): stackDumpLines = ''.join(traceback.format_list(self._client.GetModifiedDBStack())) logging.error(('Database modified before abortable exception was raised: %s' % stackDumpLines)) (yield self._FailOp(op, type, value, tb)) else: ...
'Writes the failure to the log and puts the operation to sleep in the database with a backoff. The operation will get re-run once the backoff expires. If the operation has failed less than 3 times, then the next operation will *not* be run until this operation has been retried at least 3 times. That many retries indica...
@gen.coroutine def _FailOp(self, op, type, value, tb, initial_backoff_secs=_INITIAL_BACKOFF_SECS):
elapsed_secs = (time.time() - op.timestamp) logging.error(('FAILURE: user: %d, device: %d, op: %s, method: %s in %.3fs, %s' % (op.user_id, op.device_id, op.operation_id, op.method, elapsed_secs, value)), exc_info=(type, value, tb)) exc = ''.join(traceback.format_exception(ty...
'Deletes the given operation and invokes the callback when that is complete.'
@gen.coroutine def _DeleteOp(self, op):
self._last_op_id = op.operation_id try: (yield gen.Task(op.Delete, self._client)) except Exception: logging.warning(('op %s (%s) was not deleted; assuming already deleted.' % (op.method, op.operation_id)), exc_info=True)
'Invoke all synchronous callbacks which are waiting for the specified operation to complete. If the operation completed with an error, then "type", "value", and/or "tb" will be defined.'
def _InvokeSyncCallbacks(self, operation_id, type=None, value=None, tb=None):
sync_cb_list = self._sync_cb_map.pop(operation_id, None) if (sync_cb_list is not None): for sync_cb in sync_cb_list: IOLoop.current().add_callback(partial(sync_cb, type, value, tb))
'Entry point called by the operation framework.'
@classmethod @gen.coroutine def Execute(cls, client, key, user_id):
(yield FetchContactsOperation(client, user_id, key)._FetchContactsOp())
'Orchestrates the fetch contacts operation by executing each of the phases in turn.'
@gen.coroutine def _FetchContactsOp(self):
(yield self._Check()) self._client.CheckDBNotModified() if self._do_fetch_and_update: (yield self._Update()) (yield Operation.TriggerFailpoint(self._client)) (yield self._Notify())