author
int64
658
755k
date
stringlengths
19
19
timezone
int64
-46,800
43.2k
hash
stringlengths
40
40
message
stringlengths
5
490
mods
list
language
stringclasses
20 values
license
stringclasses
3 values
repo
stringlengths
5
68
original_message
stringlengths
12
491
129,187
11.10.2018 11:25:55
14,400
5fb267826342c80c351104cfe4f331440ccdbad8
[native] Update ComposeThread to use navigation.getParam Did this in preparation for and to test it
[ { "change_type": "MODIFY", "old_path": "native/chat/compose-thread.react.js", "new_path": "native/chat/compose-thread.react.js", "diff": "// @flow\n-import type { NavigationScreenProp, NavigationRoute } from 'react-navigation';\n+import type {\n+ NavigationScreenProp,\n+ NavigationLeafRoute,\n+} from 'react-navigation';\nimport type { AppState } from '../redux-setup';\nimport type { LoadingStatus } from 'lib/types/loading-types';\nimport { loadingStatusPropType } from 'lib/types/loading-types';\n@@ -67,18 +70,14 @@ const tagInputProps = {\nreturnKeyType: \"go\",\n};\n-type NavProp =\n- & {\n- state: {\n+type NavProp = NavigationScreenProp<{|\n+ ...NavigationLeafRoute,\nparams: {\nthreadType?: ThreadType,\nparentThreadID?: string,\ncreateButtonDisabled?: bool,\n},\n- key: string,\n- },\n- }\n- & NavigationScreenProp<NavigationRoute>;\n+|}>;\nlet queuedPress = false;\nfunction setQueuedPress() {\n@@ -150,7 +149,7 @@ class InnerComposeThread extends React.PureComponent<Props, State> {\n<LinkButton\ntext=\"Create\"\nonPress={pressCreateThread}\n- disabled={!!navigation.state.params.createButtonDisabled}\n+ disabled={!!navigation.getParam('createButtonDisabled')}\n/>\n),\nheaderBackTitle: \"Back\",\n@@ -289,14 +288,14 @@ class InnerComposeThread extends React.PureComponent<Props, State> {\n);\n}\nlet parentThreadRow = null;\n- const parentThreadID = this.props.navigation.state.params.parentThreadID;\n+ const parentThreadID = this.props.navigation.getParam('parentThreadID');\nif (parentThreadID) {\nconst parentThreadInfo = this.props.parentThreadInfo;\ninvariant(\nparentThreadInfo,\n`can't find ThreadInfo for parent ${parentThreadID}`,\n);\n- const threadType = this.props.navigation.state.params.threadType;\n+ const threadType = this.props.navigation.getParam('threadType');\ninvariant(\nthreadType !== undefined && threadType !== null,\n`no threadType provided for ${parentThreadID}`,\n@@ -438,9 +437,8 @@ class InnerComposeThread extends React.PureComponent<Props, State> {\nasync newChatThreadAction() {\nthis.props.navigation.setParams({ createButtonDisabled: true });\ntry {\n- const threadType = this.props.navigation.state.params.threadType\n- ? this.props.navigation.state.params.threadType\n- : threadTypes.CHAT_SECRET;\n+ const threadTypeParam = this.props.navigation.getParam('threadType');\n+ const threadType = threadTypeParam ? threadTypeParam : threadTypes.CHAT_SECRET;\nconst initialMemberIDs = this.state.userInfoInputArray.map(\n(userInfo: AccountUserInfo) => userInfo.id,\n);\n@@ -571,7 +569,7 @@ registerFetchKey(searchUsersActionTypes);\nconst ComposeThread = connect(\n(state: AppState, ownProps: { navigation: NavProp }) => {\nlet parentThreadInfo = null;\n- const parentThreadID = ownProps.navigation.state.params.parentThreadID;\n+ const parentThreadID = ownProps.navigation.getParam('parentThreadID');\nif (parentThreadID) {\nparentThreadInfo = threadInfoSelector(state)[parentThreadID];\ninvariant(parentThreadInfo, \"parent thread should exist\");\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Update ComposeThread to use navigation.getParam Did this in preparation for https://github.com/react-navigation/react-navigation/pull/5074, and to test it
129,187
11.10.2018 12:18:15
14,400
b5be095983d050364eb47d07cfb1531209500eae
[native] Move AddUsersModal to use new React Navigation-based Modal
[ { "change_type": "MODIFY", "old_path": "native/calendar/thread-picker-modal.react.js", "new_path": "native/calendar/thread-picker-modal.react.js", "diff": "@@ -29,10 +29,16 @@ import { createModal } from '../components/modal.react';\nimport ThreadList from '../components/thread-list.react';\nimport { ThreadPickerModalRouteName } from '../navigation/route-names';\n+const Modal = createModal(ThreadPickerModalRouteName);\n+type NavProp = NavigationScreenProp<{|\n+ ...NavigationLeafRoute,\n+ params: {|\n+ dateString: string,\n+ |},\n+|}>;\n+\ntype Props = {\n- navigation:\n- & { state: { params: { dateString: string } } }\n- & NavigationScreenProp<NavigationLeafRoute>,\n+ navigation: NavProp,\n// Redux state\nonScreenThreadInfos: $ReadOnlyArray<ThreadInfo>,\nviewerID: ?string,\n@@ -40,7 +46,6 @@ type Props = {\n// Redux dispatch functions\ndispatchActionPayload: DispatchActionPayload,\n};\n-const Modal = createModal(ThreadPickerModalRouteName);\nclass ThreadPickerModal extends React.PureComponent<Props> {\nstatic propTypes = {\n" }, { "change_type": "MODIFY", "old_path": "native/chat/compose-thread.react.js", "new_path": "native/chat/compose-thread.react.js", "diff": "@@ -72,11 +72,11 @@ const tagInputProps = {\ntype NavProp = NavigationScreenProp<{|\n...NavigationLeafRoute,\n- params: {\n+ params: {|\nthreadType?: ThreadType,\nparentThreadID?: string,\ncreateButtonDisabled?: bool,\n- },\n+ |},\n|}>;\nlet queuedPress = false;\n" }, { "change_type": "MODIFY", "old_path": "native/chat/settings/add-users-modal.react.js", "new_path": "native/chat/settings/add-users-modal.react.js", "diff": "@@ -16,6 +16,10 @@ import type { DispatchActionPromise } from 'lib/utils/action-utils';\nimport type { UserSearchResult } from 'lib/types/search-types';\nimport type { LoadingStatus } from 'lib/types/loading-types';\nimport { loadingStatusPropType } from 'lib/types/loading-types';\n+import type {\n+ NavigationScreenProp,\n+ NavigationLeafRoute,\n+} from 'react-navigation';\nimport React from 'react';\nimport {\n@@ -51,18 +55,24 @@ import { threadInfoSelector } from 'lib/selectors/thread-selectors';\nimport UserList from '../../components/user-list.react';\nimport TagInput from '../../components/tag-input.react';\nimport Button from '../../components/button.react';\n-import KeyboardAvoidingModal\n- from '../../components/keyboard-avoiding-modal.react';\n+import { createModal } from '../../components/modal.react';\n+import { AddUsersModalRouteName } from '../../navigation/route-names';\nconst tagInputProps = {\nplaceholder: \"Select users to add\",\nautoFocus: true,\n};\n-type Props = {\n- isVisible: bool,\n+const Modal = createModal(AddUsersModalRouteName);\n+type NavProp = NavigationScreenProp<{|\n+ ...NavigationLeafRoute,\n+ params: {|\nthreadInfo: ThreadInfo,\n- close: () => void,\n+ |},\n+|}>;\n+\n+type Props = {\n+ navigation: NavProp,\n// Redux state\nparentThreadInfo: ?ThreadInfo,\notherUserInfos: {[id: string]: AccountUserInfo},\n@@ -84,9 +94,13 @@ type State = {|\nclass AddUsersModal extends React.PureComponent<Props, State> {\nstatic propTypes = {\n- isVisible: PropTypes.bool.isRequired,\n+ navigation: PropTypes.shape({\n+ state: PropTypes.shape({\n+ params: PropTypes.shape({\nthreadInfo: threadInfoPropType.isRequired,\n- close: PropTypes.func.isRequired,\n+ }).isRequired,\n+ }).isRequired,\n+ }).isRequired,\nparentThreadInfo: threadInfoPropType,\notherUserInfos: PropTypes.objectOf(accountUserInfoPropType).isRequired,\nuserSearchIndex: PropTypes.instanceOf(SearchIndex).isRequired,\n@@ -105,7 +119,7 @@ class AddUsersModal extends React.PureComponent<Props, State> {\nprops.otherUserInfos,\nprops.userSearchIndex,\n[],\n- props.threadInfo,\n+ props.navigation.state.params.threadInfo,\nprops.parentThreadInfo,\n);\nthis.state = {\n@@ -158,14 +172,15 @@ class AddUsersModal extends React.PureComponent<Props, State> {\nif (\nthis.props.otherUserInfos !== nextProps.otherUserInfos ||\nthis.props.userSearchIndex !== nextProps.userSearchIndex ||\n- this.props.threadInfo !== nextProps.threadInfo\n+ this.props.navigation.state.params.threadInfo\n+ !== nextProps.navigation.state.params.threadInfo\n) {\nconst userSearchResults = AddUsersModal.getSearchResults(\nthis.state.usernameInputText,\nnextProps.otherUserInfos,\nnextProps.userSearchIndex,\nthis.state.userInfoInputArray,\n- nextProps.threadInfo,\n+ nextProps.navigation.state.params.threadInfo,\nnextProps.parentThreadInfo,\n);\nthis.setState({ userSearchResults });\n@@ -200,7 +215,10 @@ class AddUsersModal extends React.PureComponent<Props, State> {\nlet cancelButton;\nif (this.props.changeThreadSettingsLoadingStatus !== \"loading\") {\ncancelButton = (\n- <Button onPress={this.props.close} style={styles.cancelButton}>\n+ <Button\n+ onPress={this.close}\n+ style={styles.cancelButton}\n+ >\n<Text style={styles.cancelText}>Cancel</Text>\n</Button>\n);\n@@ -211,12 +229,7 @@ class AddUsersModal extends React.PureComponent<Props, State> {\n}\nreturn (\n- <KeyboardAvoidingModal\n- isVisible={this.props.isVisible}\n- onClose={this.props.close}\n- containerStyle={styles.container}\n- style={styles.modal}\n- >\n+ <Modal navigation={this.props.navigation}>\n<TagInput\nvalue={this.state.userInfoInputArray}\nonChange={this.onChangeTagInput}\n@@ -236,10 +249,14 @@ class AddUsersModal extends React.PureComponent<Props, State> {\n{cancelButton}\n{addButton}\n</View>\n- </KeyboardAvoidingModal>\n+ </Modal>\n);\n}\n+ close = () => {\n+ this.props.navigation.goBack();\n+ }\n+\ntagInputRef = (tagInput: ?TagInput<AccountUserInfo>) => {\nthis.tagInput = tagInput;\n}\n@@ -253,7 +270,7 @@ class AddUsersModal extends React.PureComponent<Props, State> {\nthis.props.otherUserInfos,\nthis.props.userSearchIndex,\nuserInfoInputArray,\n- this.props.threadInfo,\n+ this.props.navigation.state.params.threadInfo,\nthis.props.parentThreadInfo,\n);\nthis.setState({ userInfoInputArray, userSearchResults });\n@@ -270,7 +287,7 @@ class AddUsersModal extends React.PureComponent<Props, State> {\nthis.props.otherUserInfos,\nthis.props.userSearchIndex,\nthis.state.userInfoInputArray,\n- this.props.threadInfo,\n+ this.props.navigation.state.params.threadInfo,\nthis.props.parentThreadInfo,\n);\nthis.searchUsers(text);\n@@ -295,7 +312,7 @@ class AddUsersModal extends React.PureComponent<Props, State> {\nthis.props.otherUserInfos,\nthis.props.userSearchIndex,\nuserInfoInputArray,\n- this.props.threadInfo,\n+ this.props.navigation.state.params.threadInfo,\nthis.props.parentThreadInfo,\n);\nthis.setState({\n@@ -317,10 +334,10 @@ class AddUsersModal extends React.PureComponent<Props, State> {\nconst newMemberIDs =\nthis.state.userInfoInputArray.map((userInfo) => userInfo.id);\nconst result = await this.props.changeThreadSettings({\n- threadID: this.props.threadInfo.id,\n+ threadID: this.props.navigation.state.params.threadInfo.id,\nchanges: { newMemberIDs },\n});\n- this.props.close();\n+ this.close();\nreturn result;\n} catch (e) {\nAlert.alert(\n@@ -348,7 +365,7 @@ class AddUsersModal extends React.PureComponent<Props, State> {\nthis.props.otherUserInfos,\nthis.props.userSearchIndex,\nuserInfoInputArray,\n- this.props.threadInfo,\n+ this.props.navigation.state.params.threadInfo,\nthis.props.parentThreadInfo,\n);\nthis.setState(\n@@ -364,12 +381,6 @@ class AddUsersModal extends React.PureComponent<Props, State> {\n}\nconst styles = StyleSheet.create({\n- container: {\n- flex: 1,\n- },\n- modal: {\n- flex: 1,\n- },\nbuttons: {\nflexDirection: 'row',\njustifyContent: 'space-between',\n@@ -406,9 +417,9 @@ const changeThreadSettingsLoadingStatusSelector\nregisterFetchKey(searchUsersActionTypes);\nexport default connect(\n- (state: AppState, ownProps: { threadInfo: ThreadInfo }) => {\n+ (state: AppState, ownProps: { navigation: NavProp }) => {\nlet parentThreadInfo = null;\n- const parentThreadID = ownProps.threadInfo.parentThreadID;\n+ const { parentThreadID } = ownProps.navigation.state.params.threadInfo;\nif (parentThreadID) {\nparentThreadInfo = threadInfoSelector(state)[parentThreadID];\n}\n" }, { "change_type": "MODIFY", "old_path": "native/chat/settings/thread-settings.react.js", "new_path": "native/chat/settings/thread-settings.react.js", "diff": "import type {\nNavigationScreenProp,\n- NavigationRoute,\n+ NavigationLeafRoute,\nNavigationParams,\nNavigationNavigateAction,\n} from 'react-navigation';\n@@ -55,7 +55,6 @@ import {\nThreadSettingsAddMember,\nThreadSettingsAddChildThread,\n} from './thread-settings-list-action.react';\n-import AddUsersModal from './add-users-modal.react';\nimport ComposeSubthreadModal from './compose-subthread-modal.react';\nimport ThreadSettingsChildThread from './thread-settings-child-thread.react';\nimport { registerChatScreen } from '../chat-screen-registry';\n@@ -67,17 +66,21 @@ import ThreadSettingsVisibility from './thread-settings-visibility.react';\nimport ThreadSettingsPushNotifs from './thread-settings-push-notifs.react';\nimport ThreadSettingsLeaveThread from './thread-settings-leave-thread.react';\nimport ThreadSettingsDeleteThread from './thread-settings-delete-thread.react';\n+import {\n+ AddUsersModalRouteName,\n+ ChatRouteName,\n+} from '../../navigation/route-names';\n+import { createActiveTabSelector } from '../../selectors/nav-selectors';\nconst itemPageLength = 5;\n-type NavProp =\n- & {\n- state: {\n- params: { threadInfo: ThreadInfo },\n- key: string,\n- },\n- }\n- & NavigationScreenProp<NavigationRoute>;\n+type NavProp = NavigationScreenProp<{|\n+ ...NavigationLeafRoute,\n+ params: {|\n+ threadInfo: ThreadInfo,\n+ |},\n+|}>;\n+\ntype ChatSettingsItem =\n| {|\nitemType: \"header\",\n@@ -187,19 +190,16 @@ type ChatSettingsItem =\ncanLeaveThread: bool,\n|};\n-type StateProps = {|\n+type Props = {|\n+ navigation: NavProp,\n+ // Redux state\nthreadInfo: ?ThreadInfo,\nthreadMembers: RelativeMemberInfo[],\nchildThreadInfos: ?ThreadInfo[],\nsomethingIsSaving: bool,\n-|};\n-type Props = {|\n- navigation: NavProp,\n- // Redux state\n- ...StateProps,\n+ tabActive: bool,\n|};\ntype State = {|\n- showAddUsersModal: bool,\nshowComposeSubthreadModal: bool,\nshowMaxMembers: number,\nshowMaxChildThreads: number,\n@@ -227,6 +227,7 @@ class InnerThreadSettings extends React.PureComponent<Props, State> {\nthreadMembers: PropTypes.arrayOf(relativeMemberInfoPropType).isRequired,\nchildThreadInfos: PropTypes.arrayOf(threadInfoPropType),\nsomethingIsSaving: PropTypes.bool.isRequired,\n+ tabActive: PropTypes.bool.isRequired,\n};\nstatic navigationOptions = ({ navigation }) => ({\ntitle: navigation.state.params.threadInfo.uiName,\n@@ -241,7 +242,6 @@ class InnerThreadSettings extends React.PureComponent<Props, State> {\n\"ThreadInfo should exist when ThreadSettings opened\",\n);\nthis.state = {\n- showAddUsersModal: false,\nshowComposeSubthreadModal: false,\nshowMaxMembers: itemPageLength,\nshowMaxChildThreads: itemPageLength,\n@@ -306,7 +306,7 @@ class InnerThreadSettings extends React.PureComponent<Props, State> {\n}\ncanReset = () => {\n- return !this.state.showAddUsersModal &&\n+ return this.props.tabActive &&\n!this.state.showComposeSubthreadModal &&\n(this.state.nameEditValue === null ||\nthis.state.nameEditValue === undefined) &&\n@@ -581,11 +581,6 @@ class InnerThreadSettings extends React.PureComponent<Props, State> {\ncontentContainerStyle={styles.flatList}\nrenderItem={this.renderItem}\n/>\n- <AddUsersModal\n- isVisible={this.state.showAddUsersModal}\n- threadInfo={threadInfo}\n- close={this.closeAddUsersModal}\n- />\n<Modal\nisVisible={this.state.showComposeSubthreadModal}\nonBackButtonPress={this.closeComposeSubthreadModal}\n@@ -732,11 +727,11 @@ class InnerThreadSettings extends React.PureComponent<Props, State> {\n}\nonPressAddMember = () => {\n- this.setState({ showAddUsersModal: true });\n- }\n-\n- closeAddUsersModal = () => {\n- this.setState({ showAddUsersModal: false });\n+ const threadInfo = InnerThreadSettings.getThreadInfo(this.props);\n+ this.props.navigation.navigate(\n+ AddUsersModalRouteName,\n+ { threadInfo },\n+ );\n}\nonPressSeeMoreMembers = () => {\n@@ -805,6 +800,7 @@ const somethingIsSaving = (\nreturn false;\n};\n+const activeTabSelector = createActiveTabSelector(ChatRouteName);\nconst ThreadSettings = connect(\n(state: AppState, ownProps: { navigation: NavProp }) => {\nconst threadID = ownProps.navigation.state.params.threadInfo.id;\n@@ -815,6 +811,7 @@ const ThreadSettings = connect(\nthreadMembers,\nchildThreadInfos: childThreadInfos(state)[threadID],\nsomethingIsSaving: somethingIsSaving(state, threadMembers),\n+ tabActive: activeTabSelector(state),\n};\n},\n)(InnerThreadSettings);\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/navigation-setup.js", "new_path": "native/navigation/navigation-setup.js", "diff": "@@ -81,12 +81,14 @@ import {\nChatThreadListRouteName,\nCalendarRouteName,\nThreadPickerModalRouteName,\n+ AddUsersModalRouteName,\n} from './route-names';\nimport {\nhandleURLActionType,\nnavigateToAppActionType,\n} from './action-types';\nimport ThreadPickerModal from '../calendar/thread-picker-modal.react';\n+import AddUsersModal from '../chat/settings/add-users-modal.react';\nexport type NavInfo = {|\n...$Exact<BaseNavInfo>,\n@@ -212,6 +214,7 @@ const RootNavigator = createStackNavigator(\n[VerificationModalRouteName]: { screen: VerificationModal },\n[AppRouteName]: { screen: ReduxWrappedAppNavigator },\n[ThreadPickerModalRouteName]: { screen: ThreadPickerModal },\n+ [AddUsersModalRouteName]: { screen: AddUsersModal },\n},\n{\nheaderMode: 'none',\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/route-names.js", "new_path": "native/navigation/route-names.js", "diff": "@@ -18,3 +18,4 @@ export const DevToolsRouteName = 'DevTools';\nexport const EditEmailRouteName = 'EditEmail';\nexport const EditPasswordRouteName = 'EditPassword';\nexport const ThreadPickerModalRouteName = 'ThreadPickerModal';\n+export const AddUsersModalRouteName = 'AddUsersModal';\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Move AddUsersModal to use new React Navigation-based Modal
129,187
11.10.2018 14:57:32
14,400
bca96cc8394b60ad3589a8a6bd981d9a0032a97b
[native] Move CustomServerModal to use new React Navigation-based Modal
[ { "change_type": "MODIFY", "old_path": "native/chat/settings/add-users-modal.react.js", "new_path": "native/chat/settings/add-users-modal.react.js", "diff": "@@ -100,6 +100,7 @@ class AddUsersModal extends React.PureComponent<Props, State> {\nthreadInfo: threadInfoPropType.isRequired,\n}).isRequired,\n}).isRequired,\n+ goBack: PropTypes.func.isRequired,\n}).isRequired,\nparentThreadInfo: threadInfoPropType,\notherUserInfos: PropTypes.objectOf(accountUserInfoPropType).isRequired,\n" }, { "change_type": "DELETE", "old_path": "native/components/keyboard-avoiding-modal.react.js", "new_path": null, "diff": "-// @flow\n-\n-import type { ViewStyle } from '../types/styles';\n-\n-import * as React from 'react';\n-import { StyleSheet, View, ViewPropTypes } from 'react-native';\n-import PropTypes from 'prop-types';\n-import Modal from 'react-native-modal';\n-\n-type Props = {|\n- isVisible: bool,\n- onClose: () => void,\n- children?: React.Node,\n- style?: ViewStyle,\n- containerStyle?: ViewStyle,\n-|};\n-class KeyboardAvoidingModal extends React.PureComponent<Props> {\n-\n- static propTypes = {\n- isVisible: PropTypes.bool.isRequired,\n- onClose: PropTypes.func.isRequired,\n- children: PropTypes.node,\n- style: ViewPropTypes.style,\n- containerStyle: ViewPropTypes.style,\n- };\n-\n- render() {\n- return (\n- <Modal\n- isVisible={this.props.isVisible}\n- onBackButtonPress={this.props.onClose}\n- onBackdropPress={this.props.onClose}\n- avoidKeyboard={true}\n- style={[styles.container, this.props.containerStyle]}\n- >\n- <View style={[styles.modal, this.props.style]}>\n- {this.props.children}\n- </View>\n- </Modal>\n- );\n- }\n-\n-}\n-\n-const styles = StyleSheet.create({\n- container: {\n- marginHorizontal: 15,\n- marginTop: 50,\n- marginBottom: 30,\n- },\n- modal: {\n- padding: 12,\n- borderRadius: 5,\n- backgroundColor: '#EEEEEE',\n- },\n-});\n-\n-export default KeyboardAvoidingModal;\n" }, { "change_type": "MODIFY", "old_path": "native/components/modal.react.js", "new_path": "native/components/modal.react.js", "diff": "@@ -5,6 +5,7 @@ import type {\nNavigationLeafRoute,\n} from 'react-navigation';\nimport type { AppState } from '../redux-setup';\n+import type { ViewStyle } from '../types/styles';\nimport * as React from 'react';\nimport {\n@@ -12,6 +13,7 @@ import {\nView,\nTouchableWithoutFeedback,\nBackHandler,\n+ ViewPropTypes,\n} from 'react-native';\nimport PropTypes from 'prop-types';\nimport { connect } from 'lib/utils/redux-utils';\n@@ -22,6 +24,8 @@ import { createIsForegroundSelector } from '../selectors/nav-selectors';\ntype Props = $ReadOnly<{|\nnavigation: NavigationScreenProp<NavigationLeafRoute>,\nchildren: React.Node,\n+ containerStyle?: ViewStyle,\n+ modalStyle?: ViewStyle,\n// Redux state\nisForeground: bool,\n|}>;\n@@ -33,6 +37,8 @@ class Modal extends React.PureComponent<Props> {\ngoBack: PropTypes.func.isRequired,\n}).isRequired,\nisForeground: PropTypes.bool.isRequired,\n+ containerStyle: ViewPropTypes.style,\n+ modalStyle: ViewPropTypes.style,\n};\ncomponentDidMount() {\n@@ -73,13 +79,14 @@ class Modal extends React.PureComponent<Props> {\n}\nrender() {\n+ const { containerStyle, modalStyle, children } = this.props;\nreturn (\n- <KeyboardAvoidingView style={styles.container}>\n+ <KeyboardAvoidingView style={[styles.container, containerStyle]}>\n<TouchableWithoutFeedback onPress={this.close}>\n<View style={styles.backdrop} />\n</TouchableWithoutFeedback>\n- <View style={styles.modal}>\n- {this.props.children}\n+ <View style={[styles.modal, modalStyle]}>\n+ {children}\n</View>\n</KeyboardAvoidingView>\n);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "native/more/custom-server-modal.react.js", "diff": "+// @flow\n+\n+import type { AppState } from '../redux-setup';\n+import type { DispatchActionPayload } from 'lib/utils/action-utils';\n+import type {\n+ NavigationScreenProp,\n+ NavigationLeafRoute,\n+} from 'react-navigation';\n+\n+import * as React from 'react';\n+import {\n+ StyleSheet,\n+ Text,\n+ TextInput,\n+} from 'react-native';\n+import PropTypes from 'prop-types';\n+\n+import { connect } from 'lib/utils/redux-utils';\n+import { setURLPrefix } from 'lib/utils/url-utils';\n+\n+import Button from '../components/button.react';\n+import { createModal } from '../components/modal.react';\n+import { CustomServerModalRouteName } from '../navigation/route-names';\n+import { setCustomServer } from '../utils/url-utils';\n+\n+const Modal = createModal(CustomServerModalRouteName);\n+\n+type Props = {|\n+ navigation: NavigationScreenProp<NavigationLeafRoute>,\n+ // Redux state\n+ urlPrefix: string,\n+ customServer: ?string,\n+ // Redux dispatch functions\n+ dispatchActionPayload: DispatchActionPayload,\n+|};\n+type State = {|\n+ customServer: string,\n+|};\n+class CustomServerModal extends React.PureComponent<Props, State> {\n+\n+ static propTypes = {\n+ navigation: PropTypes.shape({\n+ goBack: PropTypes.func.isRequired,\n+ }).isRequired,\n+ urlPrefix: PropTypes.string.isRequired,\n+ customServer: PropTypes.string,\n+ dispatchActionPayload: PropTypes.func.isRequired,\n+ };\n+\n+ constructor(props: Props) {\n+ super(props);\n+ const { customServer } = props;\n+ this.state = {\n+ customServer: customServer ? customServer : \"\",\n+ };\n+ }\n+\n+ render() {\n+ return (\n+ <Modal\n+ navigation={this.props.navigation}\n+ containerStyle={styles.container}\n+ modalStyle={styles.modal}\n+ >\n+ <TextInput\n+ style={styles.textInput}\n+ underlineColorAndroid=\"transparent\"\n+ value={this.state.customServer}\n+ onChangeText={this.onChangeCustomServer}\n+ autoFocus={true}\n+ />\n+ <Button\n+ onPress={this.onPressGo}\n+ style={styles.button}\n+ >\n+ <Text style={styles.buttonText}>Go</Text>\n+ </Button>\n+ </Modal>\n+ );\n+ }\n+\n+ onChangeCustomServer = (newCustomServer: string) => {\n+ this.setState({ customServer: newCustomServer });\n+ }\n+\n+ onPressGo = () => {\n+ const { customServer } = this.state;\n+ if (customServer !== this.props.urlPrefix) {\n+ this.props.dispatchActionPayload(setURLPrefix, customServer);\n+ }\n+ if (customServer && customServer !== this.props.customServer) {\n+ this.props.dispatchActionPayload(setCustomServer, customServer);\n+ }\n+ this.props.navigation.goBack();\n+ }\n+\n+}\n+\n+const styles = StyleSheet.create({\n+ container: {\n+ justifyContent: 'flex-end',\n+ },\n+ modal: {\n+ flex: 0,\n+ flexDirection: 'row',\n+ },\n+ textInput: {\n+ padding: 0,\n+ margin: 0,\n+ fontSize: 16,\n+ color: '#333333',\n+ flex: 1,\n+ },\n+ button: {\n+ backgroundColor: \"#88BB88\",\n+ marginVertical: 2,\n+ marginHorizontal: 2,\n+ borderRadius: 5,\n+ paddingVertical: 4,\n+ paddingHorizontal: 12,\n+ },\n+ buttonText: {\n+ fontSize: 18,\n+ textAlign: 'center',\n+ color: \"white\",\n+ },\n+});\n+\n+export default connect(\n+ (state: AppState) => ({\n+ urlPrefix: state.urlPrefix,\n+ customServer: state.customServer,\n+ }),\n+ null,\n+ true,\n+)(CustomServerModal);\n" }, { "change_type": "DELETE", "old_path": "native/more/custom-server-selector.react.js", "new_path": null, "diff": "-// @flow\n-\n-import * as React from 'react';\n-import {\n- StyleSheet,\n- View,\n- Text,\n- TextInput,\n-} from 'react-native';\n-import PropTypes from 'prop-types';\n-\n-import Button from '../components/button.react';\n-import KeyboardAvoidingModal from '../components/keyboard-avoiding-modal.react';\n-\n-type Props = {|\n- isVisible: bool,\n- currentCustomServer: ?string,\n- onClose: () => void,\n- onCompleteInput: (customServer: string) => void,\n-|};\n-type State = {|\n- customServer: string,\n-|};\n-class CustomServerSelector extends React.PureComponent<Props, State> {\n-\n- static propTypes = {\n- isVisible: PropTypes.bool.isRequired,\n- currentCustomServer: PropTypes.string,\n- onClose: PropTypes.func.isRequired,\n- onCompleteInput: PropTypes.func.isRequired,\n- };\n-\n- constructor(props: Props) {\n- super(props);\n- this.state = {\n- customServer: this.props.currentCustomServer\n- ? this.props.currentCustomServer\n- : \"\",\n- };\n- }\n-\n- render() {\n- return (\n- <KeyboardAvoidingModal\n- isVisible={this.props.isVisible}\n- onClose={this.props.onClose}\n- containerStyle={styles.container}\n- style={styles.modal}\n- >\n- <TextInput\n- style={styles.textInput}\n- underlineColorAndroid=\"transparent\"\n- value={this.state.customServer}\n- onChangeText={this.onChangeCustomServer}\n- autoFocus={true}\n- />\n- <Button\n- onPress={this.onPressGo}\n- style={styles.button}\n- >\n- <Text style={styles.buttonText}>Go</Text>\n- </Button>\n- </KeyboardAvoidingModal>\n- );\n- }\n-\n- onChangeCustomServer = (newCustomServer: string) => {\n- this.setState({ customServer: newCustomServer });\n- }\n-\n- onPressGo = () => {\n- this.props.onCompleteInput(this.state.customServer);\n- this.props.onClose();\n- }\n-\n-}\n-\n-const styles = StyleSheet.create({\n- container: {\n- justifyContent: 'flex-end',\n- },\n- modal: {\n- marginBottom: 20,\n- flexDirection: 'row',\n- },\n- textInput: {\n- padding: 0,\n- margin: 0,\n- fontSize: 16,\n- color: '#333333',\n- flex: 1,\n- },\n- button: {\n- backgroundColor: \"#88BB88\",\n- marginVertical: 2,\n- marginHorizontal: 2,\n- borderRadius: 5,\n- paddingVertical: 4,\n- paddingHorizontal: 12,\n- },\n- buttonText: {\n- fontSize: 18,\n- textAlign: 'center',\n- color: \"white\",\n- },\n-});\n-\n-export default CustomServerSelector;\n" }, { "change_type": "MODIFY", "old_path": "native/more/dev-tools.react.js", "new_path": "native/more/dev-tools.react.js", "diff": "import type { AppState } from '../redux-setup';\nimport type { DispatchActionPayload } from 'lib/utils/action-utils';\n+import type {\n+ NavigationScreenProp,\n+ NavigationLeafRoute,\n+} from 'react-navigation';\nimport * as React from 'react';\nimport { StyleSheet, View, Text, ScrollView, Platform } from 'react-native';\n@@ -15,8 +19,8 @@ import sleep from 'lib/utils/sleep';\nimport Button from '../components/button.react';\nimport { getPersistor } from '../persist';\n-import { serverOptions, setCustomServer } from '../utils/url-utils';\n-import CustomServerSelector from './custom-server-selector.react';\n+import { serverOptions } from '../utils/url-utils';\n+import { CustomServerModalRouteName } from '../navigation/route-names';\nconst ServerIcon = (props: {||}) => (\n<Icon\n@@ -28,18 +32,19 @@ const ServerIcon = (props: {||}) => (\n);\ntype Props = {|\n+ navigation: NavigationScreenProp<NavigationLeafRoute>,\n// Redux state\nurlPrefix: string,\ncustomServer: ?string,\n// Redux dispatch functions\ndispatchActionPayload: DispatchActionPayload,\n|};\n-type State = {|\n- customServerModalOpen: bool,\n-|};\n-class InnerDevTools extends React.PureComponent<Props, State> {\n+class InnerDevTools extends React.PureComponent<Props> {\nstatic propTypes = {\n+ navigation: PropTypes.shape({\n+ navigate: PropTypes.func.isRequired,\n+ }).isRequired,\nurlPrefix: PropTypes.string.isRequired,\ncustomServer: PropTypes.string,\ndispatchActionPayload: PropTypes.func.isRequired,\n@@ -47,9 +52,6 @@ class InnerDevTools extends React.PureComponent<Props, State> {\nstatic navigationOptions = {\nheaderTitle: \"Developer tools\",\n};\n- state = {\n- customServerModalOpen: false,\n- };\nrender() {\nconst serverButtons = [];\n@@ -136,12 +138,6 @@ class InnerDevTools extends React.PureComponent<Props, State> {\n{serverButtons}\n</View>\n</ScrollView>\n- <CustomServerSelector\n- isVisible={this.state.customServerModalOpen}\n- currentCustomServer={this.props.customServer}\n- onClose={this.closeCustomServerModal}\n- onCompleteInput={this.onCompleteCustomServerInput}\n- />\n</View>\n);\n}\n@@ -167,20 +163,7 @@ class InnerDevTools extends React.PureComponent<Props, State> {\n}\nonSelectCustomServer = () => {\n- this.setState({ customServerModalOpen: true });\n- }\n-\n- closeCustomServerModal = () => {\n- this.setState({ customServerModalOpen: false });\n- }\n-\n- onCompleteCustomServerInput = (customServer: string) => {\n- if (customServer !== this.props.urlPrefix) {\n- this.props.dispatchActionPayload(setURLPrefix, customServer);\n- }\n- if (customServer && customServer != this.props.customServer) {\n- this.props.dispatchActionPayload(setCustomServer, customServer);\n- }\n+ this.props.navigation.navigate(CustomServerModalRouteName);\n}\n}\n@@ -239,7 +222,7 @@ const styles = StyleSheet.create({\n},\n});\n-const DevTools = connect(\n+export default connect(\n(state: AppState) => ({\nurlPrefix: state.urlPrefix,\ncustomServer: state.customServer,\n@@ -247,5 +230,3 @@ const DevTools = connect(\nnull,\ntrue,\n)(InnerDevTools);\n-\n-export default DevTools;\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/navigation-setup.js", "new_path": "native/navigation/navigation-setup.js", "diff": "@@ -82,6 +82,7 @@ import {\nCalendarRouteName,\nThreadPickerModalRouteName,\nAddUsersModalRouteName,\n+ CustomServerModalRouteName,\n} from './route-names';\nimport {\nhandleURLActionType,\n@@ -89,6 +90,7 @@ import {\n} from './action-types';\nimport ThreadPickerModal from '../calendar/thread-picker-modal.react';\nimport AddUsersModal from '../chat/settings/add-users-modal.react';\n+import CustomServerModal from '../more/custom-server-modal.react';\nexport type NavInfo = {|\n...$Exact<BaseNavInfo>,\n@@ -215,6 +217,7 @@ const RootNavigator = createStackNavigator(\n[AppRouteName]: { screen: ReduxWrappedAppNavigator },\n[ThreadPickerModalRouteName]: { screen: ThreadPickerModal },\n[AddUsersModalRouteName]: { screen: AddUsersModal },\n+ [CustomServerModalRouteName]: { screen: CustomServerModal },\n},\n{\nheaderMode: 'none',\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/route-names.js", "new_path": "native/navigation/route-names.js", "diff": "@@ -19,3 +19,4 @@ export const EditEmailRouteName = 'EditEmail';\nexport const EditPasswordRouteName = 'EditPassword';\nexport const ThreadPickerModalRouteName = 'ThreadPickerModal';\nexport const AddUsersModalRouteName = 'AddUsersModal';\n+export const CustomServerModalRouteName = 'CustomServerModal';\n" }, { "change_type": "MODIFY", "old_path": "native/types/styles.js", "new_path": "native/types/styles.js", "diff": "// @flow\n-import type {\n- ____ViewStyleProp_Internal as ViewStyle,\n- ____TextStyleProp_Internal as TextStyle,\n- ____ImageStyleProp_Internal as ImageStyle,\n-} from 'react-native/Libraries/StyleSheet/StyleSheetTypes';\n+import * as React from 'react';\n+import { View, Text, Image } from 'react-native';\n+\n+type ViewProps = React.ElementProps<typeof View>;\n+type ViewStyle = $PropertyType<ViewProps, 'style'>;\n+\n+type TextProps = React.ElementProps<typeof Text>;\n+type TextStyle = $PropertyType<TextProps, 'style'>;\n+\n+type ImageProps = React.ElementProps<typeof Image>;\n+type ImageStyle = $PropertyType<ImageProps, 'style'>;\nexport type {\nViewStyle,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Move CustomServerModal to use new React Navigation-based Modal
129,187
11.10.2018 15:46:47
14,400
49aba34d24ebed94b66693c3db4830a98aeaec4e
[native] Move ColorPickerModal to use new React Navigation-based Modal
[ { "change_type": "DELETE", "old_path": "native/chat/color-picker-modal.react.js", "new_path": null, "diff": "-// @flow\n-\n-import React from 'react';\n-import PropTypes from 'prop-types';\n-import { View, TouchableHighlight, StyleSheet } from 'react-native';\n-import Modal from 'react-native-modal';\n-import Icon from 'react-native-vector-icons/FontAwesome';\n-\n-import ColorPicker from '../components/color-picker.react';\n-\n-type Props = {|\n- isVisible: bool,\n- closeModal: () => void,\n- color: string,\n- oldColor?: ?string,\n- onColorSelected: (color: string) => void,\n-|};\n-class ColorPickerModal extends React.PureComponent<Props> {\n-\n- static propTypes = {\n- isVisible: PropTypes.bool.isRequired,\n- closeModal: PropTypes.func.isRequired,\n- color: PropTypes.string.isRequired,\n- oldColor: PropTypes.string,\n- onColorSelected: PropTypes.func.isRequired,\n- };\n-\n- render() {\n- return (\n- <Modal\n- isVisible={this.props.isVisible}\n- onBackButtonPress={this.props.closeModal}\n- onBackdropPress={this.props.closeModal}\n- >\n- <View style={styles.colorPickerContainer}>\n- <ColorPicker\n- defaultColor={this.props.color}\n- oldColor={this.props.oldColor}\n- onColorSelected={this.props.onColorSelected}\n- style={styles.colorPicker}\n- />\n- <TouchableHighlight\n- onPress={this.props.closeModal}\n- style={styles.closeButton}\n- underlayColor=\"#CCCCCCDD\"\n- >\n- <Icon\n- name=\"close\"\n- size={16}\n- color=\"#AAAAAA\"\n- style={styles.closeButtonIcon}\n- />\n- </TouchableHighlight>\n- </View>\n- </Modal>\n- );\n- }\n-\n-}\n-\n-const styles = StyleSheet.create({\n- colorPickerContainer: {\n- height: 350,\n- backgroundColor: '#EEEEEE',\n- marginVertical: 20,\n- marginHorizontal: 15,\n- borderRadius: 5,\n- },\n- colorPicker: {\n- top: 10,\n- bottom: 10,\n- left: 10,\n- right: 10,\n- position: 'absolute',\n- },\n- closeButton: {\n- position: 'absolute',\n- top: 5,\n- right: 5,\n- width: 18,\n- height: 18,\n- borderRadius: 3,\n- },\n- closeButtonIcon: {\n- position: 'absolute',\n- left: 3,\n- },\n-});\n-\n-export default ColorPickerModal;\n" }, { "change_type": "ADD", "old_path": null, "new_path": "native/chat/settings/color-picker-modal.react.js", "diff": "+// @flow\n+\n+import type { AppState } from '../../redux-setup';\n+import type { DispatchActionPromise } from 'lib/utils/action-utils';\n+import type {\n+ NavigationScreenProp,\n+ NavigationLeafRoute,\n+} from 'react-navigation';\n+import {\n+ type ThreadInfo,\n+ threadInfoPropType,\n+ type ChangeThreadSettingsResult,\n+ type UpdateThreadRequest,\n+} from 'lib/types/thread-types';\n+\n+import * as React from 'react';\n+import PropTypes from 'prop-types';\n+import { TouchableHighlight, StyleSheet, Alert } from 'react-native';\n+import Icon from 'react-native-vector-icons/FontAwesome';\n+\n+import { connect } from 'lib/utils/redux-utils';\n+import {\n+ changeThreadSettingsActionTypes,\n+ changeThreadSettings,\n+} from 'lib/actions/thread-actions';\n+\n+import { createModal } from '../../components/modal.react';\n+import { AddUsersModalRouteName } from '../../navigation/route-names';\n+import ColorPicker from '../../components/color-picker.react';\n+\n+const Modal = createModal(AddUsersModalRouteName);\n+type NavProp = NavigationScreenProp<{|\n+ ...NavigationLeafRoute,\n+ params: {|\n+ color: string,\n+ threadInfo: ThreadInfo,\n+ setColor: (color: string) => void,\n+ |},\n+|}>;\n+\n+type Props = {|\n+ navigation: NavProp,\n+ // Redux dispatch functions\n+ dispatchActionPromise: DispatchActionPromise,\n+ // async functions that hit server APIs\n+ changeThreadSettings: (\n+ request: UpdateThreadRequest,\n+ ) => Promise<ChangeThreadSettingsResult>,\n+|};\n+class ColorPickerModal extends React.PureComponent<Props> {\n+\n+ static propTypes = {\n+ navigation: PropTypes.shape({\n+ state: PropTypes.shape({\n+ params: PropTypes.shape({\n+ color: PropTypes.string.isRequired,\n+ threadInfo: threadInfoPropType.isRequired,\n+ setColor: PropTypes.func.isRequired,\n+ }).isRequired,\n+ }).isRequired,\n+ goBack: PropTypes.func.isRequired,\n+ }).isRequired,\n+ dispatchActionPromise: PropTypes.func.isRequired,\n+ changeThreadSettings: PropTypes.func.isRequired,\n+ };\n+\n+ render() {\n+ const { color, threadInfo } = this.props.navigation.state.params;\n+ return (\n+ <Modal\n+ navigation={this.props.navigation}\n+ modalStyle={styles.colorPickerContainer}\n+ >\n+ <ColorPicker\n+ defaultColor={color}\n+ oldColor={threadInfo.color}\n+ onColorSelected={this.onColorSelected}\n+ style={styles.colorPicker}\n+ />\n+ <TouchableHighlight\n+ onPress={this.close}\n+ style={styles.closeButton}\n+ underlayColor=\"#CCCCCCDD\"\n+ >\n+ <Icon\n+ name=\"close\"\n+ size={16}\n+ color=\"#AAAAAA\"\n+ style={styles.closeButtonIcon}\n+ />\n+ </TouchableHighlight>\n+ </Modal>\n+ );\n+ }\n+\n+ close = () => {\n+ this.props.navigation.goBack();\n+ }\n+\n+ onColorSelected = (color: string) => {\n+ const colorEditValue = color.substr(1);\n+ this.props.navigation.state.params.setColor(colorEditValue);\n+ this.close();\n+ this.props.dispatchActionPromise(\n+ changeThreadSettingsActionTypes,\n+ this.editColor(colorEditValue),\n+ { customKeyName: `${changeThreadSettingsActionTypes.started}:color` },\n+ );\n+ }\n+\n+ async editColor(newColor: string) {\n+ const threadID = this.props.navigation.state.params.threadInfo.id;\n+ try {\n+ return await this.props.changeThreadSettings({\n+ threadID,\n+ changes: { color: newColor },\n+ });\n+ } catch (e) {\n+ Alert.alert(\n+ \"Unknown error\",\n+ \"Uhh... try again?\",\n+ [\n+ { text: 'OK', onPress: this.onErrorAcknowledged },\n+ ],\n+ { cancelable: false },\n+ );\n+ throw e;\n+ }\n+ }\n+\n+ onErrorAcknowledged = () => {\n+ const { threadInfo, setColor } = this.props.navigation.state.params;\n+ setColor(threadInfo.color);\n+ }\n+\n+}\n+\n+const styles = StyleSheet.create({\n+ colorPickerContainer: {\n+ flex: 0,\n+ height: 350,\n+ backgroundColor: '#EEEEEE',\n+ marginVertical: 20,\n+ marginHorizontal: 15,\n+ borderRadius: 5,\n+ },\n+ colorPicker: {\n+ top: 10,\n+ bottom: 10,\n+ left: 10,\n+ right: 10,\n+ position: 'absolute',\n+ },\n+ closeButton: {\n+ position: 'absolute',\n+ top: 5,\n+ right: 5,\n+ width: 18,\n+ height: 18,\n+ borderRadius: 3,\n+ },\n+ closeButtonIcon: {\n+ position: 'absolute',\n+ left: 3,\n+ },\n+});\n+\n+export default connect(\n+ null,\n+ { changeThreadSettings },\n+)(ColorPickerModal);\n" }, { "change_type": "MODIFY", "old_path": "native/chat/settings/thread-settings-color.react.js", "new_path": "native/chat/settings/thread-settings-color.react.js", "diff": "import {\ntype ThreadInfo,\nthreadInfoPropType,\n- type ChangeThreadSettingsResult,\n- type UpdateThreadRequest,\n} from 'lib/types/thread-types';\n-import type { DispatchActionPromise } from 'lib/utils/action-utils';\nimport type { LoadingStatus } from 'lib/types/loading-types';\nimport { loadingStatusPropType } from 'lib/types/loading-types';\nimport type { AppState } from '../../redux-setup';\n+import type { NavigationParams } from 'react-navigation';\nimport React from 'react';\nimport {\nText,\nStyleSheet,\n- Alert,\nActivityIndicator,\nView,\nPlatform,\n@@ -23,31 +20,25 @@ import {\nimport PropTypes from 'prop-types';\nimport { connect } from 'lib/utils/redux-utils';\n-import {\n- changeThreadSettingsActionTypes,\n- changeThreadSettings,\n-} from 'lib/actions/thread-actions';\n+import { changeThreadSettingsActionTypes } from 'lib/actions/thread-actions';\nimport { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\nimport EditSettingButton from '../../components/edit-setting-button.react';\nimport ColorSplotch from '../../components/color-splotch.react';\n-import ColorPickerModal from '../color-picker-modal.react';\n+import { ColorPickerModalRouteName } from '../../navigation/route-names';\ntype Props = {|\nthreadInfo: ThreadInfo,\ncolorEditValue: string,\nsetColorEditValue: (color: string) => void,\n- showEditColorModal: bool,\n- setEditColorModalVisibility: (visible: bool) => void,\ncanChangeSettings: bool,\n+ navigate: ({\n+ routeName: string,\n+ params?: NavigationParams,\n+ key?: string,\n+ }) => bool,\n// Redux state\nloadingStatus: LoadingStatus,\n- // Redux dispatch functions\n- dispatchActionPromise: DispatchActionPromise,\n- // async functions that hit server APIs\n- changeThreadSettings: (\n- request: UpdateThreadRequest,\n- ) => Promise<ChangeThreadSettingsResult>,\n|};\nclass ThreadSettingsColor extends React.PureComponent<Props> {\n@@ -55,12 +46,9 @@ class ThreadSettingsColor extends React.PureComponent<Props> {\nthreadInfo: threadInfoPropType.isRequired,\ncolorEditValue: PropTypes.string.isRequired,\nsetColorEditValue: PropTypes.func.isRequired,\n- showEditColorModal: PropTypes.bool.isRequired,\n- setEditColorModalVisibility: PropTypes.func.isRequired,\ncanChangeSettings: PropTypes.bool.isRequired,\n+ navigate: PropTypes.func.isRequired,\nloadingStatus: loadingStatusPropType.isRequired,\n- dispatchActionPromise: PropTypes.func.isRequired,\n- changeThreadSettings: PropTypes.func.isRequired,\n};\nrender() {\n@@ -84,56 +72,19 @@ class ThreadSettingsColor extends React.PureComponent<Props> {\n<ColorSplotch color={this.props.threadInfo.color} />\n</View>\n{colorButton}\n- <ColorPickerModal\n- isVisible={this.props.showEditColorModal}\n- closeModal={this.closeColorPicker}\n- color={this.props.colorEditValue}\n- oldColor={this.props.threadInfo.color}\n- onColorSelected={this.onColorSelected}\n- />\n</View>\n);\n}\nonPressEditColor = () => {\n- this.props.setEditColorModalVisibility(true);\n- }\n-\n- closeColorPicker = () => {\n- this.props.setEditColorModalVisibility(false);\n- }\n-\n- onColorSelected = (color: string) => {\n- const colorEditValue = color.substr(1);\n- this.props.setColorEditValue(colorEditValue);\n- this.props.dispatchActionPromise(\n- changeThreadSettingsActionTypes,\n- this.editColor(colorEditValue),\n- { customKeyName: `${changeThreadSettingsActionTypes.started}:color` },\n- );\n- }\n-\n- async editColor(newColor: string) {\n- try {\n- return await this.props.changeThreadSettings({\n- threadID: this.props.threadInfo.id,\n- changes: { color: newColor },\n+ this.props.navigate({\n+ routeName: ColorPickerModalRouteName,\n+ params: {\n+ color: this.props.colorEditValue,\n+ threadInfo: this.props.threadInfo,\n+ setColor: this.props.setColorEditValue,\n+ },\n});\n- } catch (e) {\n- Alert.alert(\n- \"Unknown error\",\n- \"Uhh... try again?\",\n- [\n- { text: 'OK', onPress: this.onErrorAcknowledged },\n- ],\n- { cancelable: false },\n- );\n- throw e;\n- }\n- }\n-\n- onErrorAcknowledged = () => {\n- this.props.setColorEditValue(this.props.threadInfo.color);\n}\n}\n@@ -165,9 +116,6 @@ const loadingStatusSelector = createLoadingStatusSelector(\n`${changeThreadSettingsActionTypes.started}:color`,\n);\n-export default connect(\n- (state: AppState) => ({\n+export default connect((state: AppState) => ({\nloadingStatus: loadingStatusSelector(state),\n- }),\n- { changeThreadSettings },\n-)(ThreadSettingsColor);\n+}))(ThreadSettingsColor);\n" }, { "change_type": "MODIFY", "old_path": "native/chat/settings/thread-settings.react.js", "new_path": "native/chat/settings/thread-settings.react.js", "diff": "@@ -81,6 +81,13 @@ type NavProp = NavigationScreenProp<{|\n|},\n|}>;\n+type Navigate = ({\n+ routeName: string,\n+ params?: NavigationParams,\n+ action?: NavigationNavigateAction,\n+ key?: string,\n+}) => bool;\n+\ntype ChatSettingsItem =\n| {|\nitemType: \"header\",\n@@ -106,8 +113,8 @@ type ChatSettingsItem =\nkey: string,\nthreadInfo: ThreadInfo,\ncolorEditValue: string,\n- showEditColorModal: bool,\ncanChangeSettings: bool,\n+ navigate: Navigate,\n|}\n| {|\nitemType: \"description\",\n@@ -121,12 +128,7 @@ type ChatSettingsItem =\nitemType: \"parent\",\nkey: string,\nthreadInfo: ThreadInfo,\n- navigate: ({\n- routeName: string,\n- params?: NavigationParams,\n- action?: NavigationNavigateAction,\n- key?: string,\n- }) => bool,\n+ navigate: Navigate,\n|}\n| {|\nitemType: \"visibility\",\n@@ -147,12 +149,7 @@ type ChatSettingsItem =\nitemType: \"childThread\",\nkey: string,\nthreadInfo: ThreadInfo,\n- navigate: ({\n- routeName: string,\n- params?: NavigationParams,\n- action?: NavigationNavigateAction,\n- key?: string,\n- }) => bool,\n+ navigate: Navigate,\nlastListItem: bool,\n|}\n| {|\n@@ -181,12 +178,7 @@ type ChatSettingsItem =\nitemType: \"deleteThread\",\nkey: string,\nthreadInfo: ThreadInfo,\n- navigate: ({\n- routeName: string,\n- params?: NavigationParams,\n- action?: NavigationNavigateAction,\n- key?: string,\n- }) => bool,\n+ navigate: Navigate,\ncanLeaveThread: bool,\n|};\n@@ -207,7 +199,6 @@ type State = {|\ndescriptionEditValue: ?string,\nnameTextHeight: ?number,\ndescriptionTextHeight: ?number,\n- showEditColorModal: bool,\ncolorEditValue: string,\n|};\nclass InnerThreadSettings extends React.PureComponent<Props, State> {\n@@ -249,7 +240,6 @@ class InnerThreadSettings extends React.PureComponent<Props, State> {\ndescriptionEditValue: null,\nnameTextHeight: null,\ndescriptionTextHeight: null,\n- showEditColorModal: false,\ncolorEditValue: threadInfo.color,\n};\n}\n@@ -310,7 +300,6 @@ class InnerThreadSettings extends React.PureComponent<Props, State> {\n!this.state.showComposeSubthreadModal &&\n(this.state.nameEditValue === null ||\nthis.state.nameEditValue === undefined) &&\n- !this.state.showEditColorModal &&\n!this.props.somethingIsSaving;\n}\n@@ -344,8 +333,8 @@ class InnerThreadSettings extends React.PureComponent<Props, State> {\nkey: \"color\",\nthreadInfo,\ncolorEditValue: this.state.colorEditValue,\n- showEditColorModal: this.state.showEditColorModal,\ncanChangeSettings,\n+ navigate: this.props.navigation.navigate,\n});\nlistData.push({\nitemType: \"footer\",\n@@ -624,9 +613,8 @@ class InnerThreadSettings extends React.PureComponent<Props, State> {\nthreadInfo={item.threadInfo}\ncolorEditValue={item.colorEditValue}\nsetColorEditValue={this.setColorEditValue}\n- showEditColorModal={item.showEditColorModal}\n- setEditColorModalVisibility={this.setEditColorModalVisibility}\ncanChangeSettings={item.canChangeSettings}\n+ navigate={item.navigate}\n/>\n);\n} else if (item.itemType === \"description\") {\n@@ -702,12 +690,8 @@ class InnerThreadSettings extends React.PureComponent<Props, State> {\nthis.setState({ nameTextHeight: height });\n}\n- setEditColorModalVisibility = (visible: bool) => {\n- this.setState({ showEditColorModal: visible });\n- }\n-\nsetColorEditValue = (color: string) => {\n- this.setState({ showEditColorModal: false, colorEditValue: color });\n+ this.setState({ colorEditValue: color });\n}\nsetDescriptionEditValue = (value: ?string, callback?: () => void) => {\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/navigation-setup.js", "new_path": "native/navigation/navigation-setup.js", "diff": "@@ -83,6 +83,7 @@ import {\nThreadPickerModalRouteName,\nAddUsersModalRouteName,\nCustomServerModalRouteName,\n+ ColorPickerModalRouteName,\n} from './route-names';\nimport {\nhandleURLActionType,\n@@ -91,6 +92,7 @@ import {\nimport ThreadPickerModal from '../calendar/thread-picker-modal.react';\nimport AddUsersModal from '../chat/settings/add-users-modal.react';\nimport CustomServerModal from '../more/custom-server-modal.react';\n+import ColorPickerModal from '../chat/settings/color-picker-modal.react';\nexport type NavInfo = {|\n...$Exact<BaseNavInfo>,\n@@ -218,6 +220,7 @@ const RootNavigator = createStackNavigator(\n[ThreadPickerModalRouteName]: { screen: ThreadPickerModal },\n[AddUsersModalRouteName]: { screen: AddUsersModal },\n[CustomServerModalRouteName]: { screen: CustomServerModal },\n+ [ColorPickerModalRouteName]: { screen: ColorPickerModal },\n},\n{\nheaderMode: 'none',\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/route-names.js", "new_path": "native/navigation/route-names.js", "diff": "@@ -20,3 +20,4 @@ export const EditPasswordRouteName = 'EditPassword';\nexport const ThreadPickerModalRouteName = 'ThreadPickerModal';\nexport const AddUsersModalRouteName = 'AddUsersModal';\nexport const CustomServerModalRouteName = 'CustomServerModal';\n+export const ColorPickerModalRouteName = 'ColorPickerModal';\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Move ColorPickerModal to use new React Navigation-based Modal
129,187
11.10.2018 16:05:21
14,400
4320e2667fc4ed8ed75f85e7d54b59bc3034e861
[native] Move ComposeSubthreadModal to use new React Navigation-based Modal
[ { "change_type": "MODIFY", "old_path": "native/chat/settings/compose-subthread-modal.react.js", "new_path": "native/chat/settings/compose-subthread-modal.react.js", "diff": "@@ -6,45 +6,55 @@ import {\nthreadTypes,\n} from 'lib/types/thread-types';\nimport type {\n- NavigationParams,\n- NavigationNavigateAction,\n+ NavigationScreenProp,\n+ NavigationLeafRoute,\n} from 'react-navigation';\n-import React from 'react';\n+import * as React from 'react';\nimport PropTypes from 'prop-types';\n-import { View, StyleSheet, Text, InteractionManager } from 'react-native';\n+import { StyleSheet, Text } from 'react-native';\nimport Icon from 'react-native-vector-icons/MaterialIcons';\nimport IonIcon from 'react-native-vector-icons/Ionicons';\nimport { threadTypeDescriptions } from 'lib/shared/thread-utils';\nimport Button from '../../components/button.react';\n-import { ComposeThreadRouteName } from '../../navigation/route-names';\n-import KeyboardAvoidingView\n- from '../../components/keyboard-avoiding-view.react';\n+import {\n+ ComposeSubthreadModalRouteName,\n+ ComposeThreadRouteName,\n+} from '../../navigation/route-names';\n+import { createModal } from '../../components/modal.react';\n-type Props = {|\n+const Modal = createModal(ComposeSubthreadModalRouteName);\n+type NavProp = NavigationScreenProp<{|\n+ ...NavigationLeafRoute,\n+ params: {|\nthreadInfo: ThreadInfo,\n- navigate: ({\n- routeName: string,\n- params?: NavigationParams,\n- action?: NavigationNavigateAction,\n- key?: string,\n- }) => bool,\n- closeModal: () => void,\n+ |},\n+|}>;\n+\n+type Props = {|\n+ navigation: NavProp,\n|};\nclass ComposeSubthreadModal extends React.PureComponent<Props> {\nstatic propTypes = {\n+ navigation: PropTypes.shape({\n+ state: PropTypes.shape({\n+ params: PropTypes.shape({\nthreadInfo: threadInfoPropType.isRequired,\n+ }).isRequired,\n+ }).isRequired,\nnavigate: PropTypes.func.isRequired,\n- closeModal: PropTypes.func.isRequired,\n+ }).isRequired,\n};\n- waitingToNavigate = false;\nrender() {\n- const content = (\n- <View style={styles.modal}>\n+ return (\n+ <Modal\n+ navigation={this.props.navigation}\n+ modalStyle={styles.modal}\n+ >\n<Text style={styles.visibility}>Thread type</Text>\n<Button style={styles.option} onPress={this.onPressOpen}>\n<Icon name=\"public\" size={32} color=\"black\" />\n@@ -72,65 +82,40 @@ class ComposeSubthreadModal extends React.PureComponent<Props> {\nstyle={styles.forwardIcon}\n/>\n</Button>\n- </View>\n- );\n- return (\n- <KeyboardAvoidingView style={styles.container}>\n- {content}\n- </KeyboardAvoidingView>\n+ </Modal>\n);\n}\nonPressOpen = () => {\n- if (this.waitingToNavigate) {\n- return;\n- }\n- this.waitingToNavigate = true;\n- InteractionManager.runAfterInteractions(() => {\n- this.props.navigate({\n+ const threadID = this.props.navigation.state.params.threadInfo.id;\n+ this.props.navigation.navigate({\nrouteName: ComposeThreadRouteName,\nparams: {\nthreadType: threadTypes.CHAT_NESTED_OPEN,\n- parentThreadID: this.props.threadInfo.id,\n+ parentThreadID: threadID,\n},\n- key: ComposeThreadRouteName +\n- `${this.props.threadInfo.id}|${threadTypes.CHAT_NESTED_OPEN}`,\n- });\n- this.waitingToNavigate = false;\n+ key:\n+ `${ComposeThreadRouteName}|${threadID}|${threadTypes.CHAT_NESTED_OPEN}`,\n});\n- this.props.closeModal();\n}\nonPressSecret = () => {\n- if (this.waitingToNavigate) {\n- return;\n- }\n- this.waitingToNavigate = true;\n- InteractionManager.runAfterInteractions(() => {\n- this.props.navigate({\n+ const threadID = this.props.navigation.state.params.threadInfo.id;\n+ this.props.navigation.navigate({\nrouteName: ComposeThreadRouteName,\nparams: {\nthreadType: threadTypes.CHAT_SECRET,\n- parentThreadID: this.props.threadInfo.id,\n+ parentThreadID: threadID,\n},\n- key: ComposeThreadRouteName +\n- `${this.props.threadInfo.id}|${threadTypes.CHAT_NESTED_OPEN}`,\n- });\n- this.waitingToNavigate = false;\n+ key: `${ComposeThreadRouteName}|${threadID}|${threadTypes.CHAT_SECRET}`,\n});\n- this.props.closeModal();\n}\n}\nconst styles = StyleSheet.create({\n- container: {\n- marginHorizontal: 10,\n- },\nmodal: {\n- padding: 12,\n- borderRadius: 5,\n- backgroundColor: '#EEEEEE',\n+ flex: 0,\n},\nvisibility: {\nfontSize: 24,\n" }, { "change_type": "MODIFY", "old_path": "native/chat/settings/thread-settings.react.js", "new_path": "native/chat/settings/thread-settings.react.js", "diff": "@@ -18,8 +18,7 @@ import type { CategoryType } from './thread-settings-category.react';\nimport React from 'react';\nimport PropTypes from 'prop-types';\n-import { FlatList, StyleSheet, View } from 'react-native';\n-import Modal from 'react-native-modal';\n+import { FlatList, StyleSheet } from 'react-native';\nimport _isEqual from 'lodash/fp/isEqual';\nimport invariant from 'invariant';\n@@ -55,7 +54,6 @@ import {\nThreadSettingsAddMember,\nThreadSettingsAddChildThread,\n} from './thread-settings-list-action.react';\n-import ComposeSubthreadModal from './compose-subthread-modal.react';\nimport ThreadSettingsChildThread from './thread-settings-child-thread.react';\nimport { registerChatScreen } from '../chat-screen-registry';\nimport ThreadSettingsName from './thread-settings-name.react';\n@@ -68,6 +66,7 @@ import ThreadSettingsLeaveThread from './thread-settings-leave-thread.react';\nimport ThreadSettingsDeleteThread from './thread-settings-delete-thread.react';\nimport {\nAddUsersModalRouteName,\n+ ComposeSubthreadModalRouteName,\nChatRouteName,\n} from '../../navigation/route-names';\nimport { createActiveTabSelector } from '../../selectors/nav-selectors';\n@@ -192,7 +191,6 @@ type Props = {|\ntabActive: bool,\n|};\ntype State = {|\n- showComposeSubthreadModal: bool,\nshowMaxMembers: number,\nshowMaxChildThreads: number,\nnameEditValue: ?string,\n@@ -233,7 +231,6 @@ class InnerThreadSettings extends React.PureComponent<Props, State> {\n\"ThreadInfo should exist when ThreadSettings opened\",\n);\nthis.state = {\n- showComposeSubthreadModal: false,\nshowMaxMembers: itemPageLength,\nshowMaxChildThreads: itemPageLength,\nnameEditValue: null,\n@@ -297,7 +294,6 @@ class InnerThreadSettings extends React.PureComponent<Props, State> {\ncanReset = () => {\nreturn this.props.tabActive &&\n- !this.state.showComposeSubthreadModal &&\n(this.state.nameEditValue === null ||\nthis.state.nameEditValue === undefined) &&\n!this.props.somethingIsSaving;\n@@ -564,24 +560,11 @@ class InnerThreadSettings extends React.PureComponent<Props, State> {\n}\nreturn (\n- <View>\n<FlatList\ndata={listData}\ncontentContainerStyle={styles.flatList}\nrenderItem={this.renderItem}\n/>\n- <Modal\n- isVisible={this.state.showComposeSubthreadModal}\n- onBackButtonPress={this.closeComposeSubthreadModal}\n- onBackdropPress={this.closeComposeSubthreadModal}\n- >\n- <ComposeSubthreadModal\n- threadInfo={threadInfo}\n- navigate={this.props.navigation.navigate}\n- closeModal={this.closeComposeSubthreadModal}\n- />\n- </Modal>\n- </View>\n);\n}\n@@ -703,11 +686,11 @@ class InnerThreadSettings extends React.PureComponent<Props, State> {\n}\nonPressComposeSubthread = () => {\n- this.setState({ showComposeSubthreadModal: true });\n- }\n-\n- closeComposeSubthreadModal = () => {\n- this.setState({ showComposeSubthreadModal: false });\n+ const threadInfo = InnerThreadSettings.getThreadInfo(this.props);\n+ this.props.navigation.navigate(\n+ ComposeSubthreadModalRouteName,\n+ { threadInfo },\n+ );\n}\nonPressAddMember = () => {\n" }, { "change_type": "DELETE", "old_path": "native/flow-typed/npm/react-native-modal_vx.x.x.js", "new_path": null, "diff": "-// flow-typed signature: 6414d9b7cc36a3888b70d45e791faafc\n-// flow-typed version: <<STUB>>/react-native-modal_v^6.2.0/flow_v0.78.0\n-\n-/**\n- * This is an autogenerated libdef stub for:\n- *\n- * 'react-native-modal'\n- *\n- * Fill this stub out by replacing all the `any` types.\n- *\n- * Once filled out, we encourage you to share your work with the\n- * community by sending a pull request to:\n- * https://github.com/flowtype/flow-typed\n- */\n-\n-declare module 'react-native-modal' {\n- declare module.exports: any;\n-}\n-\n-/**\n- * We include stubs for each file inside this npm package in case you need to\n- * require those files directly. Feel free to delete any files that aren't\n- * needed.\n- */\n-declare module 'react-native-modal/src/animations' {\n- declare module.exports: any;\n-}\n-\n-declare module 'react-native-modal/src/index' {\n- declare module.exports: any;\n-}\n-\n-declare module 'react-native-modal/src/index.style' {\n- declare module.exports: any;\n-}\n-\n-// Filename aliases\n-declare module 'react-native-modal/src/animations.js' {\n- declare module.exports: $Exports<'react-native-modal/src/animations'>;\n-}\n-declare module 'react-native-modal/src/index.js' {\n- declare module.exports: $Exports<'react-native-modal/src/index'>;\n-}\n-declare module 'react-native-modal/src/index.style.js' {\n- declare module.exports: $Exports<'react-native-modal/src/index.style'>;\n-}\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/navigation-setup.js", "new_path": "native/navigation/navigation-setup.js", "diff": "@@ -84,6 +84,7 @@ import {\nAddUsersModalRouteName,\nCustomServerModalRouteName,\nColorPickerModalRouteName,\n+ ComposeSubthreadModalRouteName,\n} from './route-names';\nimport {\nhandleURLActionType,\n@@ -93,6 +94,7 @@ import ThreadPickerModal from '../calendar/thread-picker-modal.react';\nimport AddUsersModal from '../chat/settings/add-users-modal.react';\nimport CustomServerModal from '../more/custom-server-modal.react';\nimport ColorPickerModal from '../chat/settings/color-picker-modal.react';\n+import ComposeSubthreadModal from '../chat/settings/compose-subthread-modal.react';\nexport type NavInfo = {|\n...$Exact<BaseNavInfo>,\n@@ -221,6 +223,7 @@ const RootNavigator = createStackNavigator(\n[AddUsersModalRouteName]: { screen: AddUsersModal },\n[CustomServerModalRouteName]: { screen: CustomServerModal },\n[ColorPickerModalRouteName]: { screen: ColorPickerModal },\n+ [ComposeSubthreadModalRouteName]: { screen: ComposeSubthreadModal },\n},\n{\nheaderMode: 'none',\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/route-names.js", "new_path": "native/navigation/route-names.js", "diff": "@@ -21,3 +21,4 @@ export const ThreadPickerModalRouteName = 'ThreadPickerModal';\nexport const AddUsersModalRouteName = 'AddUsersModal';\nexport const CustomServerModalRouteName = 'CustomServerModal';\nexport const ColorPickerModalRouteName = 'ColorPickerModal';\n+export const ComposeSubthreadModalRouteName = 'ComposeSubthreadModal';\n" }, { "change_type": "MODIFY", "old_path": "native/package.json", "new_path": "native/package.json", "diff": "\"react-native-hyperlink\": \"git+https://git@github.com/ashoat/react-native-hyperlink.git#both\",\n\"react-native-in-app-notification\": \"^2.1.0\",\n\"react-native-keychain\": \"^3.0.0\",\n- \"react-native-modal\": \"^6.2.0\",\n\"react-native-notifications\": \"git+https://git@github.com/ashoat/react-native-notifications.git\",\n\"react-native-onepassword\": \"^1.0.6\",\n\"react-native-segmented-control-tab\": \"^3.2.1\",\n" }, { "change_type": "MODIFY", "old_path": "yarn.lock", "new_path": "yarn.lock", "diff": "@@ -9062,13 +9062,6 @@ react-linkify@^0.2.2:\nprop-types \"^15.5.8\"\ntlds \"^1.57.0\"\n-react-native-animatable@^1.2.4:\n- version \"1.3.0\"\n- resolved \"https://registry.yarnpkg.com/react-native-animatable/-/react-native-animatable-1.3.0.tgz#b5c3940fc758cfd9b2fe54613a457c4b6962b46e\"\n- integrity sha512-GGYEYvderfzPZcPnw7xov4nlRmi9d6oqcIzx0fGkUUsMshOQEtq5IEzFp3np0uTB9n8/gZIZcdbUPggVlVydMg==\n- dependencies:\n- prop-types \"^15.5.10\"\n-\nreact-native-dismiss-keyboard@1.0.0:\nversion \"1.0.0\"\nresolved \"https://registry.yarnpkg.com/react-native-dismiss-keyboard/-/react-native-dismiss-keyboard-1.0.0.tgz#32886242b3f2317e121f3aeb9b0a585e2b879b49\"\n@@ -9121,14 +9114,6 @@ react-native-keychain@^3.0.0:\nresolved \"https://registry.yarnpkg.com/react-native-keychain/-/react-native-keychain-3.0.0.tgz#29da1dfa43c2581f76bf9420914fd38a1558cf18\"\nintegrity sha512-0incABt1+aXsZvG34mDV57KKanSB+iMHmxvWv+N6lgpNLaSoqrCxazjbZdeqD4qJ7Z+Etp5CLf/4v1aI+sNLBw==\n-react-native-modal@^6.2.0:\n- version \"6.5.0\"\n- resolved \"https://registry.yarnpkg.com/react-native-modal/-/react-native-modal-6.5.0.tgz#46220b2289a41597d344c1db17454611b426a758\"\n- integrity sha512-ewchdETAGd32xLGLK93NETEGkRcePtN7ZwjmLSQnNW1Zd0SRUYE8NqftjamPyfKvK0i2DZjX4YAghGZTqaRUbA==\n- dependencies:\n- prop-types \"^15.6.1\"\n- react-native-animatable \"^1.2.4\"\n-\n\"react-native-notifications@git+https://git@github.com/ashoat/react-native-notifications.git\":\nversion \"1.1.19\"\nresolved \"git+https://git@github.com/ashoat/react-native-notifications.git#6f741c582bcf19fd4151f2b18d48d55d3da157e9\"\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Move ComposeSubthreadModal to use new React Navigation-based Modal
129,187
11.10.2018 16:53:02
14,400
f9914a2cb26d87bf9a5297188e2094bff747a313
[native] Fix ColorPicker crash on unmount
[ { "change_type": "MODIFY", "old_path": "native/components/color-picker.react.js", "new_path": "native/components/color-picker.react.js", "diff": "@@ -177,7 +177,9 @@ class ColorPicker extends React.PureComponent<Props, State> {\n// is double broken (#12591, #15290). Unfortunately, the only way to get\n// absolute positioning for a View is via measure() after onLayout (#10556).\nInteractionManager.runAfterInteractions(() => {\n- invariant(this._pickerContainer, \"should be set\");\n+ if (!this._pickerContainer) {\n+ return;\n+ }\nthis._pickerContainer.measure((x, y, width, height, pageX, pageY) => {\nthis._pageX = pageX;\nthis._pageY = pageY;\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Fix ColorPicker crash on unmount
129,187
12.10.2018 11:53:06
14,400
8bdec98d47657611c34899c3868a8fef114d4fde
[native] Use defaultInterpolation for all non-modal screens
[ { "change_type": "MODIFY", "old_path": "native/navigation/navigation-setup.js", "new_path": "native/navigation/navigation-setup.js", "diff": "@@ -247,7 +247,10 @@ const RootNavigator = createStackNavigator(\ndefaultConfig.screenInterpolator(sceneProps);\nconst { position, scene } = sceneProps;\nconst { index, route } = scene;\n- if (route.routeName !== ThreadPickerModalRouteName) {\n+ if (\n+ accountModals.includes(route.routeName) ||\n+ route.routeName === AppRouteName\n+ ) {\nreturn defaultInterpolation;\n}\nconst opacity = position.interpolate({\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Use defaultInterpolation for all non-modal screens
129,187
12.10.2018 12:13:09
14,400
cb87d65d32dbc0753113b34a70742b1b19f4f0ce
[native] Dismiss the Keyboard on most top-level transitions
[ { "change_type": "MODIFY", "old_path": "native/navigation/navigation-setup.js", "new_path": "native/navigation/navigation-setup.js", "diff": "@@ -29,7 +29,7 @@ import {\nimport invariant from 'invariant';\nimport _findIndex from 'lodash/fp/findIndex';\nimport _includes from 'lodash/fp/includes';\n-import { Alert, BackHandler, Platform } from 'react-native';\n+import { Alert, BackHandler, Platform, Keyboard } from 'react-native';\nimport React from 'react';\nimport PropTypes from 'prop-types';\nimport { StackViewTransitionConfigs } from 'react-navigation-stack';\n@@ -230,6 +230,16 @@ const RootNavigator = createStackNavigator(\nmode: 'modal',\ntransparentCard: true,\ndisableKeyboardHandling: true,\n+ onTransitionStart: (\n+ transitionProps: NavigationTransitionProps,\n+ prevTransitionProps: ?NavigationTransitionProps,\n+ ) => {\n+ const { scene } = transitionProps;\n+ const { route } = scene;\n+ if (route.routeName !== ThreadPickerModalRouteName) {\n+ Keyboard.dismiss();\n+ }\n+ },\ntransitionConfig: (\ntransitionProps: NavigationTransitionProps,\nprevTransitionProps: ?NavigationTransitionProps,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Dismiss the Keyboard on most top-level transitions
129,187
12.10.2018 14:00:07
14,400
b6a6905d457e570db8b1ea91afda00de30bba9c3
[server] Fix notifications Ugh... such a dumb mistake. Why didn't Flow catch this?
[ { "change_type": "MODIFY", "old_path": "server/src/push/send.js", "new_path": "server/src/push/send.js", "diff": "@@ -138,7 +138,7 @@ async function sendPushNotifs(pushInfo: PushInfo) {\nconst iosVersionsToTokens = byDeviceType.get(\"ios\");\nif (iosVersionsToTokens) {\n- for (let [ codeVer, deviceTokens ] in iosVersionsToTokens) {\n+ for (let [ codeVer, deviceTokens ] of iosVersionsToTokens) {\nconst codeVersion = parseInt(codeVer); // only for Flow\nconst shimmedNewRawMessageInfos = shimUnsupportedRawMessageInfos(\nnewRawMessageInfos,\n@@ -161,7 +161,7 @@ async function sendPushNotifs(pushInfo: PushInfo) {\n}\nconst androidVersionsToTokens = byDeviceType.get(\"android\");\nif (androidVersionsToTokens) {\n- for (let [ codeVer, deviceTokens ] in androidVersionsToTokens) {\n+ for (let [ codeVer, deviceTokens ] of androidVersionsToTokens) {\nconst codeVersion = parseInt(codeVer); // only for Flow\nconst shimmedNewRawMessageInfos = shimUnsupportedRawMessageInfos(\nnewRawMessageInfos,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Fix notifications Ugh... such a dumb mistake. Why didn't Flow catch this?
129,187
12.10.2018 14:01:22
14,400
09354cd2f0751b28a54902dbdb033b54ca1e524c
[server] session table has last_validated column, not last_verified
[ { "change_type": "MODIFY", "old_path": "server/src/deleters/session-deleters.js", "new_path": "server/src/deleters/session-deleters.js", "diff": "@@ -28,7 +28,7 @@ async function deleteOldWebSessions(): Promise<void> {\nLEFT JOIN ids iup ON iup.id = up.id\nWHERE s.id != s.cookie\nAND s.last_update < ${oldestWebSessionToKeep}\n- AND s.last_verified < ${oldestWebSessionToKeep}\n+ AND s.last_validated < ${oldestWebSessionToKeep}\n`);\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] session table has last_validated column, not last_verified
129,187
12.10.2018 14:10:02
14,400
8c544e7a3f5d46ef8d46ca2c68b2f191d2fe0a6c
[native] Make sure to only disable CalendarInputBar when threadPickerOpen changes
[ { "change_type": "MODIFY", "old_path": "native/calendar/calendar.react.js", "new_path": "native/calendar/calendar.react.js", "diff": "@@ -418,7 +418,11 @@ class InnerCalendar extends React.PureComponent<Props, State> {\nthis.lastEntryKeyActive = null;\n}\n- if (this.props.threadPickerOpen && !this.state.disableInputBar) {\n+ if (\n+ this.props.threadPickerOpen &&\n+ !prevProps.threadPickerOpen &&\n+ !this.state.disableInputBar\n+ ) {\nthis.setState({ disableInputBar: true });\n}\nif (\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Make sure to only disable CalendarInputBar when threadPickerOpen changes
129,187
12.10.2018 17:02:12
14,400
214e937fdca3ffc47ec1e7df44dd4d65501a06b8
[native] Fix Entry text height calculation issues
[ { "change_type": "MODIFY", "old_path": "native/calendar/calendar.react.js", "new_path": "native/calendar/calendar.react.js", "diff": "@@ -753,7 +753,7 @@ class InnerCalendar extends React.PureComponent<Props, State> {\n<TextHeightMeasurer\ntextToMeasure={this.state.textToMeasure}\nallHeightsMeasuredCallback={this.allHeightsMeasured}\n- style={entryStyles.text}\n+ style={[entryStyles.entry, entryStyles.text]}\n/>\n<KeyboardAvoidingView\nstyle={styles.keyboardAvoidingView}\n" }, { "change_type": "MODIFY", "old_path": "native/calendar/entry.react.js", "new_path": "native/calendar/entry.react.js", "diff": "@@ -164,9 +164,9 @@ class InternalEntry extends React.Component<Props, State> {\nconst willBeActive = InternalEntry.isActive(nextProps);\nif (\n!willBeActive &&\n- (nextProps.entryInfo.text !== this.props.entryInfo.text &&\n- nextProps.entryInfo.text !== this.state.text) ||\n- (nextProps.entryInfo.textHeight !== this.props.entryInfo.textHeight &&\n+ (nextProps.entryInfo.text !== this.props.entryInfo.text ||\n+ nextProps.entryInfo.textHeight !== this.props.entryInfo.textHeight) &&\n+ (nextProps.entryInfo.text !== this.state.text ||\nnextProps.entryInfo.textHeight !== this.state.height)\n) {\nthis.guardedSetState({\n" }, { "change_type": "MODIFY", "old_path": "native/text-height-measurer.react.js", "new_path": "native/text-height-measurer.react.js", "diff": "@@ -4,7 +4,7 @@ import type { TextStyle } from './types/styles';\nimport React from 'react';\nimport PropTypes from 'prop-types';\n-import { Text, View, StyleSheet, Platform } from 'react-native';\n+import { Text, View, StyleSheet } from 'react-native';\nimport invariant from 'invariant';\nimport _isEmpty from 'lodash/fp/isEmpty';\nimport _intersectionWith from 'lodash/fp/intersectionWith';\n@@ -152,10 +152,7 @@ class TextHeightMeasurer extends React.PureComponent<Props, State> {\nconst style = textToMeasure.style ? textToMeasure.style : this.props.style;\ninvariant(style, \"style should exist for every text being measured!\");\nlet text = textToMeasure.text;\n- if (\n- Platform.OS === \"android\" &&\n- (text === \"\" || text.slice(-1) === \"\\n\")\n- ) {\n+ if (text === \"\" || text.slice(-1) === \"\\n\") {\ntext += \" \";\n}\nreturn (\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Fix Entry text height calculation issues
129,187
12.10.2018 17:55:33
14,400
79e5104929703820d4fe2db1ab0fa7526ccfa750
[native] codeVersion -> 20
[ { "change_type": "MODIFY", "old_path": "lib/facts/version.json", "new_path": "lib/facts/version.json", "diff": "{\n- \"currentCodeVersion\": 19\n+ \"currentCodeVersion\": 20\n}\n" }, { "change_type": "MODIFY", "old_path": "native/android/app/build.gradle", "new_path": "native/android/app/build.gradle", "diff": "@@ -109,8 +109,8 @@ android {\napplicationId \"org.squadcal\"\nminSdkVersion rootProject.ext.minSdkVersion\ntargetSdkVersion rootProject.ext.targetSdkVersion\n- versionCode 19\n- versionName \"0.0.19\"\n+ versionCode 20\n+ versionName \"0.0.20\"\nndk {\nabiFilters \"armeabi-v7a\", \"x86\"\n}\n" }, { "change_type": "MODIFY", "old_path": "native/ios/SquadCal/Info.plist", "new_path": "native/ios/SquadCal/Info.plist", "diff": "<key>CFBundlePackageType</key>\n<string>APPL</string>\n<key>CFBundleShortVersionString</key>\n- <string>0.0.19</string>\n+ <string>0.0.20</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>19</string>\n+ <string>20</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] codeVersion -> 20
129,187
15.10.2018 17:14:14
14,400
cf6c90ed0146a3709a2f248fd81ec651be60fe7d
[server] Include stacktrace in error report Probably won't be helpful since it'll be all symbolified, but might as well...
[ { "change_type": "MODIFY", "old_path": "lib/types/report-types.js", "new_path": "lib/types/report-types.js", "diff": "@@ -28,6 +28,7 @@ export type ErrorInfo = { componentStack: string };\nexport type ErrorData = {| error: Error, info?: ErrorInfo |};\nexport type FlatErrorData = {|\nerrorMessage: string,\n+ stack?: string,\ncomponentStack?: ?string,\n|};\n" }, { "change_type": "MODIFY", "old_path": "native/crash.react.js", "new_path": "native/crash.react.js", "diff": "@@ -151,6 +151,7 @@ class Crash extends React.PureComponent<Props, State> {\n},\nerrors: this.props.errorData.map(data => ({\nerrorMessage: data.error.message,\n+ stack: data.error.stack,\ncomponentStack: data.info && data.info.componentStack,\n})),\npreloadedState: reduxLogger.preloadedState,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Include stacktrace in error report Probably won't be helpful since it'll be all symbolified, but might as well...
129,187
15.10.2018 17:15:10
14,400
ef79917933df8d3366e19e8d7906f27effc0e3cf
[server] Only avoid dismissing Keyboard in ThreadPickerModal -> App transition
[ { "change_type": "MODIFY", "old_path": "native/navigation/navigation-setup.js", "new_path": "native/navigation/navigation-setup.js", "diff": "@@ -236,7 +236,12 @@ const RootNavigator = createStackNavigator(\n) => {\nconst { scene } = transitionProps;\nconst { route } = scene;\n- if (route.routeName !== ThreadPickerModalRouteName) {\n+ const { scene: prevScene } = prevTransitionProps;\n+ const { route: prevRoute } = prevScene;\n+ if (\n+ route.routeName !== AppRouteName ||\n+ prevRoute.routeName !== ThreadPickerModalRouteName\n+ ) {\nKeyboard.dismiss();\n}\n},\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Only avoid dismissing Keyboard in ThreadPickerModal -> App transition
129,187
15.10.2018 17:16:18
14,400
f02307e6f3e7b1564af41eec2cacd36db6e67132
[native] codeVersion -> 21
[ { "change_type": "MODIFY", "old_path": "lib/facts/version.json", "new_path": "lib/facts/version.json", "diff": "{\n- \"currentCodeVersion\": 20\n+ \"currentCodeVersion\": 21\n}\n" }, { "change_type": "MODIFY", "old_path": "native/android/app/build.gradle", "new_path": "native/android/app/build.gradle", "diff": "@@ -109,8 +109,8 @@ android {\napplicationId \"org.squadcal\"\nminSdkVersion rootProject.ext.minSdkVersion\ntargetSdkVersion rootProject.ext.targetSdkVersion\n- versionCode 20\n- versionName \"0.0.20\"\n+ versionCode 21\n+ versionName \"0.0.21\"\nndk {\nabiFilters \"armeabi-v7a\", \"x86\"\n}\n" }, { "change_type": "MODIFY", "old_path": "native/ios/SquadCal/Info.plist", "new_path": "native/ios/SquadCal/Info.plist", "diff": "<key>CFBundlePackageType</key>\n<string>APPL</string>\n<key>CFBundleShortVersionString</key>\n- <string>0.0.20</string>\n+ <string>0.0.21</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>20</string>\n+ <string>21</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] codeVersion -> 21
129,187
16.10.2018 13:46:33
14,400
48539ff48b92278c4e73b840a0bb2d4aab0853d0
[native] Type fix for onTransitionStart
[ { "change_type": "MODIFY", "old_path": "native/navigation/navigation-setup.js", "new_path": "native/navigation/navigation-setup.js", "diff": "@@ -234,6 +234,9 @@ const RootNavigator = createStackNavigator(\ntransitionProps: NavigationTransitionProps,\nprevTransitionProps: ?NavigationTransitionProps,\n) => {\n+ if (!prevTransitionProps) {\n+ return;\n+ }\nconst { scene } = transitionProps;\nconst { route } = scene;\nconst { scene: prevScene } = prevTransitionProps;\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Type fix for onTransitionStart
129,187
17.10.2018 11:04:21
14,400
4ce900481bbfd1681d568edc669b66b1ae9555f0
[native] Fix appLoggedIn for new modal paradigm
[ { "change_type": "MODIFY", "old_path": "native/app.react.js", "new_path": "native/app.react.js", "diff": "@@ -93,7 +93,7 @@ import {\nimport ConnectedStatusBar from './connected-status-bar.react';\nimport {\nactiveThreadSelector,\n- createIsForegroundSelector,\n+ appLoggedInSelector,\n} from './selectors/nav-selectors';\nimport {\nrequestIOSPushPermissions,\n@@ -881,11 +881,10 @@ const styles = StyleSheet.create({\n},\n});\n-const isForegroundSelector = createIsForegroundSelector(AppRouteName);\nconst ConnectedAppWithNavigationState = connect(\n(state: AppState) => {\nconst activeThread = activeThreadSelector(state);\n- const appLoggedIn = isForegroundSelector(state);\n+ const appLoggedIn = appLoggedInSelector(state);\nreturn {\nnavigationState: state.navInfo.navigationState,\npingStartingPayload: pingNativeStartingPayload(state),\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/navigation-setup.js", "new_path": "native/navigation/navigation-setup.js", "diff": "@@ -60,7 +60,7 @@ import More from '../more/more.react';\nimport LoggedOutModal from '../account/logged-out-modal.react';\nimport VerificationModal from '../account/verification-modal.react';\nimport {\n- createIsForegroundSelector,\n+ appLoggedInSelector,\nappCanRespondToBackButtonSelector,\n} from '../selectors/nav-selectors';\nimport {\n@@ -85,6 +85,7 @@ import {\nCustomServerModalRouteName,\nColorPickerModalRouteName,\nComposeSubthreadModalRouteName,\n+ accountModals,\n} from './route-names';\nimport {\nhandleURLActionType,\n@@ -207,10 +208,9 @@ class WrappedAppNavigator\n}\n-const isForegroundSelector = createIsForegroundSelector(AppRouteName);\nconst ReduxWrappedAppNavigator = connect((state: AppState) => ({\nappCanRespondToBackButton: appCanRespondToBackButtonSelector(state),\n- isForeground: isForegroundSelector(state),\n+ isForeground: appLoggedInSelector(state),\n}))(WrappedAppNavigator);\n(ReduxWrappedAppNavigator: Object).router = AppNavigator.router;\n@@ -319,7 +319,6 @@ const defaultNavInfo: NavInfo = {\nnavigationState: defaultNavigationState,\n};\n-const accountModals = [ LoggedOutModalRouteName, VerificationModalRouteName ];\nfunction reduceNavInfo(\nstate: AppState,\naction: *,\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/route-names.js", "new_path": "native/navigation/route-names.js", "diff": "@@ -22,3 +22,8 @@ export const AddUsersModalRouteName = 'AddUsersModal';\nexport const CustomServerModalRouteName = 'CustomServerModal';\nexport const ColorPickerModalRouteName = 'ColorPickerModal';\nexport const ComposeSubthreadModalRouteName = 'ComposeSubthreadModal';\n+\n+export const accountModals = [\n+ LoggedOutModalRouteName,\n+ VerificationModalRouteName,\n+];\n" }, { "change_type": "MODIFY", "old_path": "native/selectors/nav-selectors.js", "new_path": "native/selectors/nav-selectors.js", "diff": "@@ -12,6 +12,7 @@ import {\nThreadSettingsRouteName,\nMessageListRouteName,\nChatRouteName,\n+ accountModals,\n} from '../navigation/route-names';\nimport {\nassertNavigationRouteNotLeafNode,\n@@ -25,6 +26,13 @@ const baseCreateIsForegroundSelector = (routeName: string) => createSelector(\n);\nconst createIsForegroundSelector = _memoize(baseCreateIsForegroundSelector);\n+const appLoggedInSelector = createSelector(\n+ (state: AppState) => state.navInfo.navigationState,\n+ (navigationState: NavigationState) => !accountModals.includes(\n+ navigationState.routes[navigationState.index].routeName,\n+ ),\n+);\n+\nconst foregroundKeySelector = createSelector(\n(state: AppState) => state.navInfo.navigationState,\n(navigationState: NavigationState) =>\n@@ -85,6 +93,7 @@ const appCanRespondToBackButtonSelector = createSelector(\nexport {\ncreateIsForegroundSelector,\n+ appLoggedInSelector,\nforegroundKeySelector,\ncreateActiveTabSelector,\nactiveThreadSelector,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Fix appLoggedIn for new modal paradigm
129,187
17.10.2018 11:06:50
14,400
95fb6dc2d152428d4fcbf3b7adea965fe38e4bc4
[native] codeVersion -> 22
[ { "change_type": "MODIFY", "old_path": "lib/facts/version.json", "new_path": "lib/facts/version.json", "diff": "{\n- \"currentCodeVersion\": 21\n+ \"currentCodeVersion\": 22\n}\n" }, { "change_type": "MODIFY", "old_path": "native/android/app/build.gradle", "new_path": "native/android/app/build.gradle", "diff": "@@ -109,8 +109,8 @@ android {\napplicationId \"org.squadcal\"\nminSdkVersion rootProject.ext.minSdkVersion\ntargetSdkVersion rootProject.ext.targetSdkVersion\n- versionCode 21\n- versionName \"0.0.21\"\n+ versionCode 22\n+ versionName \"0.0.22\"\nndk {\nabiFilters \"armeabi-v7a\", \"x86\"\n}\n" }, { "change_type": "MODIFY", "old_path": "native/ios/SquadCal/Info.plist", "new_path": "native/ios/SquadCal/Info.plist", "diff": "<key>CFBundlePackageType</key>\n<string>APPL</string>\n<key>CFBundleShortVersionString</key>\n- <string>0.0.21</string>\n+ <string>0.0.22</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>21</string>\n+ <string>22</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] codeVersion -> 22
129,187
17.10.2018 19:30:42
14,400
bd49f17d7c6eaf579d4db2a4adab300cf3c5e076
Hash only the in-query entryInfos for state check
[ { "change_type": "MODIFY", "old_path": "lib/selectors/ping-selectors.js", "new_path": "lib/selectors/ping-selectors.js", "diff": "@@ -19,6 +19,7 @@ import { getConfig } from '../utils/config';\nimport {\nserverEntryInfo,\nserverEntryInfosObject,\n+ filterRawEntryInfosByCalendarQuery,\n} from '../shared/entry-utils';\nimport { values, hash } from '../utils/objects';\n@@ -49,6 +50,7 @@ const pingActionInput = createSelector(\n(state: AppState) => state.threadStore.inconsistencyResponses,\n(state: AppState) => state.entryStore.inconsistencyResponses,\n(state: AppState) => state.pingTimestamps.lastSuccess,\n+ currentCalendarQuery,\n(\nthreadInfos: {[id: string]: RawThreadInfo},\nentryInfos: {[id: string]: RawEntryInfo},\n@@ -62,6 +64,7 @@ const pingActionInput = createSelector(\nentryInconsistencyResponses:\n$ReadOnlyArray<EntryInconsistencyClientResponse>,\nlastSuccess: number,\n+ calendarQuery: () => CalendarQuery,\n): (startingPayload: PingStartingPayload) => PingActionInput => {\nconst clientResponses = [\n...threadInconsistencyResponses,\n@@ -100,7 +103,11 @@ const pingActionInput = createSelector(\nif (key === \"threadInfos\") {\nhashValue = hash(threadInfos);\n} else if (key === \"entryInfos\") {\n- hashValue = hash(serverEntryInfosObject(values(entryInfos)));\n+ const filteredEntryInfos = filterRawEntryInfosByCalendarQuery(\n+ serverEntryInfosObject(values(entryInfos)),\n+ calendarQuery(),\n+ );\n+ hashValue = hash(filteredEntryInfos);\n} else if (key === \"currentUserInfo\") {\nhashValue = hash(currentUserInfo);\n} else if (key.startsWith(\"threadInfo|\")) {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Hash only the in-query entryInfos for state check
129,187
17.10.2018 20:12:20
14,400
b2371d5e764ebc1434c1e07e7057756766b36994
[server] Don't re-fetch cookie deviceToken
[ { "change_type": "MODIFY", "old_path": "server/src/deleters/cookie-deleters.js", "new_path": "server/src/deleters/cookie-deleters.js", "diff": "import { cookieLifetime } from 'lib/types/session-types';\nimport { dbQuery, SQL, mergeOrConditions } from '../database';\n-import { fetchDeviceTokensForCookie } from '../fetchers/device-token-fetchers';\nasync function deleteCookie(cookieID: string): Promise<void> {\nawait dbQuery(SQL`\n@@ -22,9 +21,8 @@ async function deleteCookie(cookieID: string): Promise<void> {\nasync function deleteCookiesOnLogOut(\nuserID: string,\ncookieID: string,\n+ deviceToken: ?string,\n): Promise<void> {\n- const deviceToken = await fetchDeviceTokensForCookie(cookieID);\n-\nconst conditions = [ SQL`c.id = ${cookieID}` ];\nif (deviceToken) {\nconditions.push(SQL`c.device_token = ${deviceToken}`);\n" }, { "change_type": "DELETE", "old_path": "server/src/fetchers/device-token-fetchers.js", "new_path": null, "diff": "-// @flow\n-\n-import { ServerError } from 'lib/utils/errors';\n-\n-import { dbQuery, SQL } from '../database';\n-\n-async function fetchDeviceTokensForCookie(\n- cookieID: string,\n-): Promise<?string> {\n- const query = SQL`\n- SELECT device_token\n- FROM cookies\n- WHERE id = ${cookieID}\n- `;\n- const [ result ] = await dbQuery(query);\n- if (result.length === 0) {\n- throw new ServerError('invalid_cookie');\n- }\n- const row = result[0];\n- return row.device_token;\n-}\n-\n-export {\n- fetchDeviceTokensForCookie,\n-};\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/user-responders.js", "new_path": "server/src/responders/user-responders.js", "diff": "@@ -131,7 +131,7 @@ async function logOutResponder(\nif (viewer.loggedIn) {\nconst [ anonymousViewerData ] = await Promise.all([\ncreateNewAnonymousCookie(viewer.platformDetails),\n- deleteCookiesOnLogOut(viewer.userID, viewer.cookieID),\n+ deleteCookiesOnLogOut(viewer.userID, viewer.cookieID, viewer.deviceToken),\n]);\nviewer.setNewCookie(anonymousViewerData);\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Don't re-fetch cookie deviceToken
129,187
17.10.2018 22:47:28
14,400
0b1fd48f928edfb00f37b5617e23ad9d45fc195d
Simplify and improve device token lifecycle
[ { "change_type": "MODIFY", "old_path": "lib/selectors/account-selectors.js", "new_path": "lib/selectors/account-selectors.js", "diff": "@@ -20,8 +20,7 @@ const logInExtraInfoSelector = createSelector(\nlet deviceTokenUpdateRequest = null;\nconst platform = getConfig().platformDetails.platform;\nif (deviceToken && isDeviceType(platform)) {\n- const deviceType = assertDeviceType(platform);\n- deviceTokenUpdateRequest = { deviceType, deviceToken };\n+ deviceTokenUpdateRequest = { deviceToken };\n}\n// Return a function since we depend on the time of evaluation\nreturn (): LogInExtraInfo => ({\n" }, { "change_type": "MODIFY", "old_path": "lib/types/account-types.js", "new_path": "lib/types/account-types.js", "diff": "@@ -17,7 +17,6 @@ import type {\nGenericMessagesResult,\n} from './message-types';\nimport type {\n- DeviceTokenUpdateRequest,\nPlatformDetails,\nDeviceType,\n} from './device-types';\n@@ -43,6 +42,10 @@ export type RegisterInfo = {|\npassword: string,\n|};\n+type DeviceTokenUpdateRequest = {|\n+ deviceToken: string,\n+|};\n+\nexport type RegisterRequest = {|\nusername: string,\nemail: string,\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/account-creator.js", "new_path": "server/src/creators/account-creator.js", "diff": "@@ -75,6 +75,9 @@ async function createAccount(\nconst hash = bcrypt.hashSync(request.password);\nconst time = Date.now();\n+ const deviceToken = request.deviceTokenUpdateRequest\n+ ? request.deviceTokenUpdateRequest.deviceToken\n+ : viewer.deviceToken;\nconst [ id ] = await createIDs(\"users\", 1);\nconst newUserRow = [id, request.username, hash, request.email, time];\nconst newUserQuery = SQL`\n@@ -82,7 +85,13 @@ async function createAccount(\nVALUES ${[newUserRow]}\n`;\nconst [ userViewerData ] = await Promise.all([\n- createNewUserCookie(id, request.platformDetails),\n+ createNewUserCookie(\n+ id,\n+ {\n+ platformDetails: request.platformDetails,\n+ deviceToken,\n+ },\n+ ),\ndeleteCookie(viewer.cookieID),\ndbQuery(newUserQuery),\nsendEmailAddressVerificationEmail(\n" }, { "change_type": "MODIFY", "old_path": "server/src/deleters/account-deleters.js", "new_path": "server/src/deleters/account-deleters.js", "diff": "@@ -56,7 +56,10 @@ async function deleteAccount(\nWHERE u.id = ${deletedUserID}\n`;\nconst [ anonymousViewerData ] = await Promise.all([\n- createNewAnonymousCookie(viewer.platformDetails),\n+ createNewAnonymousCookie({\n+ platformDetails: viewer.platformDetails,\n+ deviceToken: viewer.deviceToken,\n+ }),\ndbQuery(deletionQuery),\n]);\nviewer.setNewCookie(anonymousViewerData);\n" }, { "change_type": "MODIFY", "old_path": "server/src/deleters/cookie-deleters.js", "new_path": "server/src/deleters/cookie-deleters.js", "diff": "import { cookieLifetime } from 'lib/types/session-types';\n-import { dbQuery, SQL, mergeOrConditions } from '../database';\n+import invariant from 'invariant';\n-async function deleteCookie(cookieID: string): Promise<void> {\n- await dbQuery(SQL`\n- DELETE c, i, s, si, u, iu, fo\n- FROM cookies c\n- LEFT JOIN ids i ON i.id = c.id\n- LEFT JOIN sessions s ON s.cookie = c.id\n- LEFT JOIN ids si ON si.id = s.id\n- LEFT JOIN updates u ON u.target = c.id OR u.target = s.id\n- LEFT JOIN ids iu ON iu.id = u.id\n- LEFT JOIN focused fo ON fo.session = c.id OR fo.session = s.id\n- WHERE c.id = ${cookieID}\n- `);\n-}\n-\n-async function deleteCookiesOnLogOut(\n- userID: string,\n- cookieID: string,\n- deviceToken: ?string,\n-): Promise<void> {\n- const conditions = [ SQL`c.id = ${cookieID}` ];\n- if (deviceToken) {\n- conditions.push(SQL`c.device_token = ${deviceToken}`);\n- }\n+import { dbQuery, SQL, SQLStatement, mergeOrConditions } from '../database';\n+async function deleteCookiesByConditions(\n+ conditions: $ReadOnlyArray<SQLStatement>,\n+) {\n+ invariant(conditions.length > 0, \"no conditions specified\");\n+ const conditionClause = mergeOrConditions(conditions);\nconst query = SQL`\nDELETE c, i, s, si, u, iu, fo\nFROM cookies c\n@@ -37,31 +20,24 @@ async function deleteCookiesOnLogOut(\nLEFT JOIN updates u ON u.target = c.id OR u.target = s.id\nLEFT JOIN ids iu ON iu.id = u.id\nLEFT JOIN focused fo ON fo.session = c.id OR fo.session = s.id\n- WHERE c.user = ${userID} AND\n+ WHERE\n`;\n- query.append(mergeOrConditions(conditions));\n-\n+ query.append(conditionClause);\nawait dbQuery(query);\n}\n+async function deleteCookie(cookieID: string): Promise<void> {\n+ const condition = SQL`c.id = ${cookieID}`;\n+ await deleteCookiesByConditions([ condition ]);\n+}\n+\nasync function deleteExpiredCookies(): Promise<void> {\nconst earliestInvalidLastUpdate = Date.now() - cookieLifetime;\n- const query = SQL`\n- DELETE c, i, u, iu, s, si, fo\n- FROM cookies c\n- LEFT JOIN ids i ON i.id = c.id\n- LEFT JOIN updates u ON u.target = c.id\n- LEFT JOIN ids iu ON iu.id = u.id\n- LEFT JOIN sessions s ON s.cookie = c.id\n- LEFT JOIN ids si ON si.id = s.id\n- LEFT JOIN focused fo ON fo.session = s.id\n- WHERE c.last_used <= ${earliestInvalidLastUpdate}\n- `;\n- await dbQuery(query);\n+ const condition = SQL`c.last_used <= ${earliestInvalidLastUpdate}`;\n+ await deleteCookiesByConditions([ condition ]);\n}\nexport {\ndeleteCookie,\n- deleteCookiesOnLogOut,\ndeleteExpiredCookies,\n};\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/user-responders.js", "new_path": "server/src/responders/user-responders.js", "diff": "@@ -47,10 +47,7 @@ import {\ncreateNewAnonymousCookie,\ncreateNewUserCookie,\n} from '../session/cookies';\n-import {\n- deleteCookie,\n- deleteCookiesOnLogOut,\n-} from '../deleters/cookie-deleters';\n+import { deleteCookie } from '../deleters/cookie-deleters';\nimport { deleteAccount } from '../deleters/account-deleters';\nimport createAccount from '../creators/account-creator';\nimport {\n@@ -62,8 +59,6 @@ import {\nimport { dbQuery, SQL } from '../database';\nimport { fetchMessageInfos } from '../fetchers/message-fetchers';\nimport { fetchEntryInfos } from '../fetchers/entry-fetchers';\n-import { deviceTokenUpdater } from '../updaters/device-token-updaters';\n-import { deviceTokenUpdateRequestInputValidator } from './device-responders';\nimport { sendAccessRequestEmailToAshoat } from '../emails/access-request';\nimport { setNewSession } from '../session/cookies';\n@@ -130,8 +125,11 @@ async function logOutResponder(\nawait validateInput(viewer, null, null);\nif (viewer.loggedIn) {\nconst [ anonymousViewerData ] = await Promise.all([\n- createNewAnonymousCookie(viewer.platformDetails),\n- deleteCookiesOnLogOut(viewer.userID, viewer.cookieID, viewer.deviceToken),\n+ createNewAnonymousCookie({\n+ platformDetails: viewer.platformDetails,\n+ deviceToken: viewer.deviceToken,\n+ }),\n+ deleteCookie(viewer.cookieID),\n]);\nviewer.setNewCookie(anonymousViewerData);\n}\n@@ -156,6 +154,11 @@ async function accountDeletionResponder(\nreturn await deleteAccount(viewer, request);\n}\n+const deviceTokenUpdateRequestInputValidator = tShape({\n+ deviceType: t.maybe(t.enums.of(['ios', 'android'])),\n+ deviceToken: t.String,\n+});\n+\nconst registerRequestInputValidator = tShape({\nusername: t.String,\nemail: t.String,\n@@ -171,7 +174,10 @@ async function accountCreationResponder(\ninput: any,\n): Promise<RegisterResponse> {\nif (!input.platformDetails && input.platform) {\n- input.platformDetails = { platform: input.platform };\n+ input.platformDetails = {\n+ ...viewer.platformDetails,\n+ platform: input.platform,\n+ };\ndelete input.platform;\n}\nconst request: RegisterRequest = input;\n@@ -195,7 +201,10 @@ async function logInResponder(\n): Promise<LogInResponse> {\nawait validateInput(viewer, logInRequestInputValidator, input);\nif (!input.platformDetails && input.platform) {\n- input.platformDetails = { platform: input.platform };\n+ input.platformDetails = {\n+ ...viewer.platformDetails,\n+ platform: input.platform,\n+ };\ndelete input.platform;\n}\nconst request: LogInRequest = input;\n@@ -227,8 +236,14 @@ async function logInResponder(\nconst id = userRow.id.toString();\nconst newPingTime = Date.now();\n+ const deviceToken = request.deviceTokenUpdateRequest\n+ ? request.deviceTokenUpdateRequest.deviceToken\n+ : viewer.deviceToken;\nconst [ userViewerData ] = await Promise.all([\n- createNewUserCookie(id, request.platformDetails),\n+ createNewUserCookie(\n+ id,\n+ { platformDetails: request.platformDetails, deviceToken },\n+ ),\ndeleteCookie(viewer.cookieID),\n]);\nviewer.setNewCookie(userViewerData);\n@@ -249,9 +264,6 @@ async function logInResponder(\ndefaultNumberPerThread,\n),\ncalendarQuery ? fetchEntryInfos(viewer, [ calendarQuery ]) : undefined,\n- request.deviceTokenUpdateRequest\n- ? deviceTokenUpdater(viewer, request.deviceTokenUpdateRequest)\n- : undefined,\n]);\nconst rawEntryInfos = entriesResult ? entriesResult.rawEntryInfos : null;\n@@ -292,20 +304,17 @@ async function passwordUpdateResponder(\n): Promise<LogInResponse> {\nawait validateInput(viewer, updatePasswordRequestInputValidator, input);\nif (!input.platformDetails && input.platform) {\n- input.platformDetails = { platform: input.platform };\n+ input.platformDetails = {\n+ ...viewer.platformDetails,\n+ platform: input.platform,\n+ };\ndelete input.platform;\n}\nconst request: UpdatePasswordRequest = input;\nif (request.calendarQuery) {\nrequest.calendarQuery = normalizeCalendarQuery(request.calendarQuery);\n}\n- const response = await updatePassword(viewer, request);\n-\n- if (request.deviceTokenUpdateRequest) {\n- await deviceTokenUpdater(viewer, request.deviceTokenUpdateRequest);\n- }\n-\n- return response;\n+ return await updatePassword(viewer, request);\n}\nconst accessRequestInputValidator = tShape({\n" }, { "change_type": "MODIFY", "old_path": "server/src/session/cookies.js", "new_path": "server/src/session/cookies.js", "diff": "@@ -35,6 +35,7 @@ import { assertSecureRequest } from '../utils/security-utils';\nimport { deleteCookie } from '../deleters/cookie-deleters';\nimport { handleAsyncPromise } from '../responders/handlers';\nimport { createSession } from '../creators/session-creator';\n+import { clearDeviceToken } from '../updaters/device-token-updaters';\nconst { baseDomain, basePath, https } = urlFacts;\n@@ -57,6 +58,7 @@ type FetchViewerResult =\ncookieSource: CookieSource,\nsessionIdentifierType: SessionIdentifierType,\nplatformDetails: ?PlatformDetails,\n+ deviceToken: ?string,\n|};\nasync function fetchUserViewer(\n@@ -109,6 +111,7 @@ async function fetchUserViewer(\n} else if (cookieRow.platform) {\nplatformDetails = { platform: cookieRow.platform };\n}\n+ const deviceToken = cookieRow.device_token;\nif (\n!bcrypt.compareSync(cookiePassword, cookieRow.hash) ||\n@@ -121,6 +124,7 @@ async function fetchUserViewer(\ncookieSource,\nsessionIdentifierType,\nplatformDetails,\n+ deviceToken,\n};\n}\nconst userID = cookieRow.user.toString();\n@@ -128,7 +132,7 @@ async function fetchUserViewer(\nloggedIn: true,\nid: userID,\nplatformDetails,\n- deviceToken: cookieRow.device_token,\n+ deviceToken,\nuserID,\ncookieSource,\ncookieID,\n@@ -191,6 +195,7 @@ async function fetchAnonymousViewer(\n} else if (cookieRow.platform) {\nplatformDetails = { platform: cookieRow.platform };\n}\n+ const deviceToken = cookieRow.device_token;\nif (\n!bcrypt.compareSync(cookiePassword, cookieRow.hash) ||\n@@ -203,13 +208,14 @@ async function fetchAnonymousViewer(\ncookieSource,\nsessionIdentifierType,\nplatformDetails,\n+ deviceToken,\n};\n}\nconst viewer = new Viewer({\nloggedIn: false,\nid: cookieID,\nplatformDetails,\n- deviceToken: cookieRow.device_token,\n+ deviceToken,\ncookieSource,\ncookieID,\ncookiePassword,\n@@ -361,9 +367,10 @@ async function handleFetchViewerResult(\nif (!platformDetails && result.type === \"invalidated\") {\nplatformDetails = result.platformDetails;\n}\n+ const deviceToken = result.type === \"invalidated\" ? result.deviceToken : null;\nconst [ anonymousViewerData ] = await Promise.all([\n- createNewAnonymousCookie(platformDetails),\n+ createNewAnonymousCookie({ platformDetails, deviceToken }),\nresult.type === \"invalidated\"\n? deleteCookie(result.cookieID)\n: null,\n@@ -430,6 +437,12 @@ async function addSessionChangeInfoToResult(\nresult.cookieChange = sessionChange;\n}\n+type CookieCreationParams = $Shape<{|\n+ platformDetails: ?PlatformDetails,\n+ deviceToken: ?string,\n+|}>;\n+const defaultPlatformDetails = {};\n+\n// The AnonymousViewerData returned by this function...\n// (1) Does not specify a sessionIdentifierType. This will cause an exception\n// if passed directly to the Viewer constructor, so the caller should set it\n@@ -437,18 +450,23 @@ async function addSessionChangeInfoToResult(\n// (2) Does not specify a cookieSource. This will cause an exception if passed\n// directly to the Viewer constructor, so the caller should set it before\n// doing so.\n-const defaultPlatformDetails = {};\nasync function createNewAnonymousCookie(\n- platformDetails: ?PlatformDetails,\n+ params: CookieCreationParams,\n): Promise<AnonymousViewerData> {\n- const time = Date.now();\n- const cookiePassword = crypto.randomBytes(32).toString('hex');\n- const cookieHash = bcrypt.hashSync(cookiePassword);\n- const [ id ] = await createIDs(\"cookies\", 1);\n+ const { platformDetails, deviceToken } = params;\nconst { platform, ...versions } = (platformDetails || defaultPlatformDetails);\nconst versionsString = Object.keys(versions).length > 0\n? JSON.stringify(versions)\n: null;\n+\n+ const time = Date.now();\n+ const cookiePassword = crypto.randomBytes(32).toString('hex');\n+ const cookieHash = bcrypt.hashSync(cookiePassword);\n+ const [ [ id ] ] = await Promise.all([\n+ createIDs(\"cookies\", 1),\n+ deviceToken ? clearDeviceToken(deviceToken) : undefined,\n+ ]);\n+\nconst cookieRow = [\nid,\ncookieHash,\n@@ -456,11 +474,12 @@ async function createNewAnonymousCookie(\nplatform,\ntime,\ntime,\n+ deviceToken,\nversionsString,\n];\nconst query = SQL`\nINSERT INTO cookies(id, hash, user, platform, creation_time, last_used,\n- versions)\n+ device_token, versions)\nVALUES ${[cookieRow]}\n`;\nawait dbQuery(query);\n@@ -468,7 +487,7 @@ async function createNewAnonymousCookie(\nloggedIn: false,\nid,\nplatformDetails,\n- deviceToken: null,\n+ deviceToken,\ncookieID: id,\ncookiePassword,\nsessionID: undefined,\n@@ -490,16 +509,22 @@ async function createNewAnonymousCookie(\n// result is never passed directly to the Viewer constructor.\nasync function createNewUserCookie(\nuserID: string,\n- platformDetails: ?PlatformDetails,\n+ params: CookieCreationParams,\n): Promise<UserViewerData> {\n- const time = Date.now();\n- const cookiePassword = crypto.randomBytes(32).toString('hex');\n- const cookieHash = bcrypt.hashSync(cookiePassword);\n- const [ cookieID ] = await createIDs(\"cookies\", 1);\n+ const { platformDetails, deviceToken } = params;\nconst { platform, ...versions } = (platformDetails || defaultPlatformDetails);\nconst versionsString = Object.keys(versions).length > 0\n? JSON.stringify(versions)\n: null;\n+\n+ const time = Date.now();\n+ const cookiePassword = crypto.randomBytes(32).toString('hex');\n+ const cookieHash = bcrypt.hashSync(cookiePassword);\n+ const [ [ cookieID ] ] = await Promise.all([\n+ createIDs(\"cookies\", 1),\n+ deviceToken ? clearDeviceToken(deviceToken) : undefined,\n+ ]);\n+\nconst cookieRow = [\ncookieID,\ncookieHash,\n@@ -507,11 +532,12 @@ async function createNewUserCookie(\nplatform,\ntime,\ntime,\n+ deviceToken,\nversionsString,\n];\nconst query = SQL`\nINSERT INTO cookies(id, hash, user, platform, creation_time, last_used,\n- versions)\n+ device_token, versions)\nVALUES ${[cookieRow]}\n`;\nawait dbQuery(query);\n@@ -519,7 +545,7 @@ async function createNewUserCookie(\nloggedIn: true,\nid: userID,\nplatformDetails,\n- deviceToken: null,\n+ deviceToken,\nuserID,\ncookieID,\nsessionID: undefined,\n" }, { "change_type": "MODIFY", "old_path": "server/src/session/version.js", "new_path": "server/src/session/version.js", "diff": "@@ -6,7 +6,7 @@ import type { Viewer } from '../session/viewer';\nimport { ServerError } from 'lib/utils/errors';\nimport { createNewAnonymousCookie } from './cookies';\n-import { deleteCookiesOnLogOut } from '../deleters/cookie-deleters';\n+import { deleteCookie } from '../deleters/cookie-deleters';\nasync function verifyClientSupported(\nviewer: Viewer,\n@@ -17,8 +17,11 @@ async function verifyClientSupported(\n}\nif (viewer.loggedIn) {\nconst [ data ] = await Promise.all([\n- createNewAnonymousCookie(platformDetails),\n- deleteCookiesOnLogOut(viewer.userID, viewer.cookieID),\n+ createNewAnonymousCookie({\n+ platformDetails,\n+ deviceToken: viewer.deviceToken,\n+ }),\n+ deleteCookie(viewer.cookieID),\n]);\nviewer.setNewCookie(data);\nviewer.cookieInvalidated = true;\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/account-updaters.js", "new_path": "server/src/updaters/account-updaters.js", "diff": "@@ -203,8 +203,14 @@ async function updatePassword(\nconst userRow = userResult[0];\nconst newPingTime = Date.now();\n+ const deviceToken = request.deviceTokenUpdateRequest\n+ ? request.deviceTokenUpdateRequest.deviceToken\n+ : viewer.deviceToken;\nconst [ userViewerData ] = await Promise.all([\n- createNewUserCookie(userID, request.platformDetails),\n+ createNewUserCookie(\n+ userID,\n+ { platformDetails: request.platformDetails, deviceToken },\n+ ),\nclearVerifyCodes(verificationResult),\n]);\nviewer.setNewCookie(userViewerData);\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/device-token-updaters.js", "new_path": "server/src/updaters/device-token-updaters.js", "diff": "@@ -9,6 +9,7 @@ async function deviceTokenUpdater(\nviewer: Viewer,\nupdate: DeviceTokenUpdateRequest,\n): Promise<void> {\n+ await clearDeviceToken(update.deviceToken);\nconst query = SQL`\nUPDATE cookies\nSET device_token = ${update.deviceToken}, platform = ${update.deviceType}\n@@ -17,6 +18,18 @@ async function deviceTokenUpdater(\nawait dbQuery(query);\n}\n+async function clearDeviceToken(\n+ deviceToken: string,\n+): Promise<void> {\n+ const query = SQL`\n+ UPDATE cookies\n+ SET device_token = NULL\n+ WHERE device_token = ${deviceToken}\n+ `;\n+ await dbQuery(query);\n+}\n+\nexport {\ndeviceTokenUpdater,\n+ clearDeviceToken,\n};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Simplify and improve device token lifecycle
129,187
17.10.2018 23:20:20
14,400
b1eabb18eb4afbba7d26fe62af56e33213e36865
[native] Avoid sending notifs to logged out clients
[ { "change_type": "MODIFY", "old_path": "native/app.react.js", "new_path": "native/app.react.js", "diff": "@@ -189,7 +189,6 @@ class AppWithNavigationState extends React.PureComponent<Props> {\ninitialAndroidNotifHandled = false;\nopenThreadOnceReceived: Set<string> = new Set();\nupdateBadgeCountAfterNextPing = true;\n- queuedDeviceToken: ?string = null;\nappStarted = 0;\ncomponentDidMount() {\n@@ -238,8 +237,16 @@ class AppWithNavigationState extends React.PureComponent<Props> {\nthis.registerPushPermissionsAndHandleInitialNotif,\n);\n}\n+ this.onForeground();\n+ }\n+\n+ onForeground() {\nif (this.props.appLoggedIn) {\nthis.ensurePushNotifsEnabled();\n+ } else if (this.props.deviceToken) {\n+ // We do this in case there was a crash, so we can clear deviceToken from\n+ // any other cookies it might be set for\n+ this.setDeviceToken(this.props.deviceToken);\n}\n}\n@@ -398,9 +405,7 @@ class AppWithNavigationState extends React.PureComponent<Props> {\n) {\nthis.props.dispatchActionPayload(foregroundActionType, null);\nthis.startTimeouts();\n- if (this.props.appLoggedIn) {\n- this.ensurePushNotifsEnabled();\n- }\n+ this.onForeground();\nif (this.props.activeThread) {\nAppWithNavigationState.clearNotifsOfThread(this.props);\n}\n@@ -488,16 +493,6 @@ class AppWithNavigationState extends React.PureComponent<Props> {\n) {\nthis.ensurePushNotifsEnabled();\n}\n-\n- if (\n- this.props.appLoggedIn &&\n- !prevProps.appLoggedIn &&\n- this.queuedDeviceToken !== null &&\n- this.queuedDeviceToken !== undefined\n- ) {\n- this.setDeviceToken(this.queuedDeviceToken);\n- this.queuedDeviceToken = null;\n- }\n}\nstatic serverRequestsHasDeviceTokenRequest(\n@@ -509,6 +504,9 @@ class AppWithNavigationState extends React.PureComponent<Props> {\n}\nasync ensurePushNotifsEnabled() {\n+ if (!this.props.appLoggedIn) {\n+ return;\n+ }\nif (Platform.OS === \"ios\") {\nconst missingDeviceToken = this.props.deviceToken === null\n|| this.props.deviceToken === undefined;\n@@ -576,11 +574,7 @@ class AppWithNavigationState extends React.PureComponent<Props> {\niosPushPermissionResponseReceived();\n}\nif (deviceToken !== this.props.deviceToken) {\n- if (this.props.appLoggedIn) {\nthis.setDeviceToken(deviceToken);\n- } else {\n- this.queuedDeviceToken = deviceToken;\n- }\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "native/crash.react.js", "new_path": "native/crash.react.js", "diff": "@@ -8,6 +8,7 @@ import {\nimport type { DispatchActionPromise } from 'lib/utils/action-utils';\nimport type { AppState } from './redux-setup';\nimport type { ErrorData } from 'lib/types/report-types';\n+import type { LogOutResult } from 'lib/types/account-types';\nimport * as React from 'react';\nimport {\n@@ -29,6 +30,7 @@ import { connect } from 'lib/utils/redux-utils';\nimport { sendReportActionTypes, sendReport } from 'lib/actions/report-actions';\nimport sleep from 'lib/utils/sleep';\nimport { reduxLogger } from 'lib/utils/redux-logger';\n+import { logOutActionTypes, logOut } from 'lib/actions/user-actions';\nimport Button from './components/button.react';\nimport { store } from './redux-setup';\n@@ -47,6 +49,7 @@ type Props = {\nsendReport: (\nrequest: ReportCreationRequest,\n) => Promise<ReportCreationResponse>,\n+ logOut: () => Promise<LogOutResult>,\n};\ntype State = {|\nerrorReportID: ?string,\n@@ -63,6 +66,7 @@ class Crash extends React.PureComponent<Props, State> {\n})).isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nsendReport: PropTypes.func.isRequired,\n+ logOut: PropTypes.func.isRequired,\n};\nerrorTitle = _shuffle(errorTitles)[0];\nstate = {\n@@ -171,10 +175,20 @@ class Crash extends React.PureComponent<Props, State> {\nExitApp.exitApp();\n}\n- onPressWipe = () => {\n+ onPressWipe = async () => {\nif (!this.state.doneWaiting) {\nreturn;\n}\n+ this.props.dispatchActionPromise(\n+ logOutActionTypes,\n+ this.logOutAndExit(),\n+ );\n+ }\n+\n+ async logOutAndExit() {\n+ try {\n+ await this.props.logOut();\n+ } catch (e) { }\ngetPersistor().purge();\nExitApp.exitApp();\n}\n@@ -254,5 +268,5 @@ const styles = StyleSheet.create({\nexport default connect(\nundefined,\n- { sendReport },\n+ { sendReport, logOut },\n)(Crash);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Avoid sending notifs to logged out clients
129,187
15.10.2018 14:15:34
14,400
ddaea70e3a66d725545e6ab848ea9012c9151860
[lib] Get rid of friends.json
[ { "change_type": "DELETE", "old_path": "lib/facts/friends.json", "new_path": null, "diff": "-{\n- \"larry\": \"15972\"\n-}\n" }, { "change_type": "MODIFY", "old_path": "lib/shared/user-utils.js", "new_path": "lib/shared/user-utils.js", "diff": "@@ -4,7 +4,6 @@ import type { RelativeUserInfo } from '../types/user-types';\nimport type { RelativeMemberInfo } from '../types/thread-types';\nimport ashoat from '../facts/ashoat';\n-import friends from '../facts/friends';\nimport bots from '../facts/bots';\nfunction stringForUser(user: RelativeUserInfo | RelativeMemberInfo): string {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Get rid of friends.json
129,187
19.10.2018 15:07:29
14,400
2509497e2ed3e090f4a7ebc2f76eecc406806d78
[server] Accept stack in reportResponder
[ { "change_type": "MODIFY", "old_path": "server/src/responders/report-responders.js", "new_path": "server/src/responders/report-responders.js", "diff": "@@ -39,6 +39,7 @@ const reportCreationRequestInputValidator = t.union([\nstateVersion: t.maybe(t.Number),\nerrors: t.list(tShape({\nerrorMessage: t.String,\n+ stack: t.maybe(t.String),\ncomponentStack: t.maybe(t.String),\n})),\npreloadedState: t.Object,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Accept stack in reportResponder
129,187
19.10.2018 15:41:03
14,400
bb9c4da7e6e75cb408718721c8939dfd8956a0b8
[native] Some fixes for inconsistencies 1. Allow `saveMessagesActionType` set an "active" thread to unread while the app is backgrounded. 2. Always call `saveMessageInfos` before `pingNow` in `native/app.react.js`.
[ { "change_type": "MODIFY", "old_path": "native/app.react.js", "new_path": "native/app.react.js", "diff": "@@ -770,8 +770,8 @@ class AppWithNavigationState extends React.PureComponent<Props> {\n// We are here because notif was received, but hasn't been pressed yet. We\n// will preemptively dispatch a ping to fetch any missing info, and\n// integrate whatever MessageInfos were delivered into our Redux state.\n- this.pingNow();\nthis.saveMessageInfos(customNotification.messageInfos);\n+ this.pingNow();\nif (this.currentState === \"active\") {\n// In the case where the app is in the foreground, we will show an\n" }, { "change_type": "MODIFY", "old_path": "native/redux-setup.js", "new_path": "native/redux-setup.js", "diff": "@@ -40,7 +40,10 @@ import { AppState as NativeAppState } from 'react-native';\nimport baseReducer from 'lib/reducers/master-reducer';\nimport { notificationPressActionType } from 'lib/shared/notif-utils';\n-import { sendMessageActionTypes } from 'lib/actions/message-actions';\n+import {\n+ sendMessageActionTypes,\n+ saveMessagesActionType,\n+} from 'lib/actions/message-actions';\nimport { pingActionTypes } from 'lib/actions/ping-actions';\nimport { reduxLoggerMiddleware } from 'lib/utils/redux-logger';\nimport { defaultCalendarQuery } from 'lib/selectors/nav-selectors';\n@@ -283,15 +286,20 @@ function reducer(state: AppState = defaultState, action: *) {\nstate = { ...state, navInfo };\n}\n- return validateState(oldState, state);\n+ return validateState(oldState, state, action);\n}\n-function validateState(oldState: AppState, state: AppState): AppState {\n+function validateState(\n+ oldState: AppState,\n+ state: AppState,\n+ action: *,\n+): AppState {\nconst activeThread = activeThreadSelector(state);\nif (\nactiveThread &&\n(NativeAppState.currentState === \"active\" ||\n- appLastBecameInactive + 10000 < Date.now()) &&\n+ (appLastBecameInactive + 10000 < Date.now() &&\n+ action.type !== saveMessagesActionType)) &&\nstate.threadStore.threadInfos[activeThread].currentUser.unread\n) {\n// Makes sure a currently focused thread is never unread. Note that we\n@@ -299,7 +307,8 @@ function validateState(oldState: AppState, state: AppState): AppState {\n// changed to inactive more than 10 seconds ago. This is because there is a\n// delay when NativeAppState is updating in response to a foreground, and\n// actions don't get processed more than 10 seconds after a backgrounding\n- // anyways.\n+ // anyways. However we don't consider this for saveMessagesActionType, since\n+ // that action can be expected to happen while the app is backgrounded.\nstate = {\n...state,\nthreadStore: {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Some fixes for inconsistencies 1. Allow `saveMessagesActionType` set an "active" thread to unread while the app is backgrounded. 2. Always call `saveMessageInfos` before `pingNow` in `native/app.react.js`.
129,187
19.10.2018 16:17:09
14,400
df021bf18d5f7dbff1fd1a0b0cc40eed685d52b3
[native] Sanitize cookie password from reports
[ { "change_type": "MODIFY", "old_path": "lib/reducers/entry-reducer.js", "new_path": "lib/reducers/entry-reducer.js", "diff": "@@ -68,6 +68,7 @@ import { threadInFilterList } from '../shared/thread-utils';\nimport { getConfig } from '../utils/config';\nimport { reduxLogger } from '../utils/redux-logger';\nimport { values } from '../utils/objects';\n+import { sanitizeAction } from '../utils/sanitization';\nfunction daysToEntriesFromEntryInfos(entryInfos: $ReadOnlyArray<RawEntryInfo>) {\nreturn _flow(\n@@ -802,7 +803,7 @@ function findInconsistencies(\ntype: serverRequestTypes.ENTRY_INCONSISTENCY,\nplatformDetails: getConfig().platformDetails,\nbeforeAction,\n- action,\n+ action: sanitizeAction(action),\ncalendarQuery,\npollResult: oldResult,\npushResult: newResult,\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/thread-reducer.js", "new_path": "lib/reducers/thread-reducer.js", "diff": "@@ -37,6 +37,7 @@ import {\nimport { saveMessagesActionType } from '../actions/message-actions';\nimport { getConfig } from '../utils/config';\nimport { reduxLogger } from '../utils/redux-logger';\n+import { sanitizeAction } from '../utils/sanitization';\n// If the user goes away for a while and the server stops keeping track of their\n// session, the server will send down the full current set of threadInfos\n@@ -220,7 +221,7 @@ function findInconsistencies(\ntype: serverRequestTypes.THREAD_INCONSISTENCY,\nplatformDetails: getConfig().platformDetails,\nbeforeAction,\n- action,\n+ action: sanitizeAction(action),\npollResult: oldResult,\npushResult: newResult,\nlastActionTypes: reduxLogger.actions.map(action => action.type),\n" }, { "change_type": "MODIFY", "old_path": "lib/types/redux-types.js", "new_path": "lib/types/redux-types.js", "diff": "@@ -75,10 +75,13 @@ export type BaseAppState<NavInfo: BaseNavInfo> = {\n// Web JS runtime doesn't have access to the cookie for security reasons.\n// Native JS doesn't have a sessionID because the cookieID is used instead.\n// Web JS doesn't have a device token because it's not a device...\n-export type AppState = BaseAppState<*> & (\n- | { sessionID?: void, deviceToken: ?string, cookie: ?string }\n- | { sessionID: ?string, deviceToken?: void, cookie?: void }\n-);\n+export type NativeAppState =\n+ & BaseAppState<*>\n+ & { sessionID?: void, deviceToken: ?string, cookie: ?string };\n+export type WebAppState =\n+ & BaseAppState<*>\n+ & { sessionID: ?string, deviceToken?: void, cookie?: void };\n+export type AppState = NativeAppState | WebAppState;\nexport type BaseAction =\n{| type: \"@@redux/INIT\" |} | {|\n" }, { "change_type": "MODIFY", "old_path": "lib/types/report-types.js", "new_path": "lib/types/report-types.js", "diff": "// @flow\n-import type { BaseAppState, BaseAction } from './redux-types';\n+import type { AppState, BaseAction } from './redux-types';\nimport type { UserInfo } from './user-types';\nimport type { PlatformDetails } from './device-types';\nimport type { RawThreadInfo } from './thread-types';\n@@ -36,8 +36,8 @@ type ErrorReportCreationRequest = {|\ntype: 0,\nplatformDetails: PlatformDetails,\nerrors: $ReadOnlyArray<FlatErrorData>,\n- preloadedState: BaseAppState<*>,\n- currentState: BaseAppState<*>,\n+ preloadedState: AppState,\n+ currentState: AppState,\nactions: $ReadOnlyArray<BaseAction>,\n|};\nexport type ThreadInconsistencyReportCreationRequest = {|\n@@ -87,6 +87,6 @@ export type FetchErrorReportInfosResponse = {|\n|};\nexport type ReduxToolsImport = {|\n- preloadedState: BaseAppState<*>,\n+ preloadedState: AppState,\npayload: $ReadOnlyArray<BaseAction>,\n|};\n" }, { "change_type": "MODIFY", "old_path": "lib/utils/redux-logger.js", "new_path": "lib/utils/redux-logger.js", "diff": "// @flow\n-import type { BaseAppState } from '../types/redux-types';\n+import type { AppState } from '../types/redux-types';\n// This is lifted from redux-persist/lib/constants.js\n// I don't want to add redux-persist to the web/server bundles...\n@@ -13,7 +13,7 @@ class ReduxLogger {\nlastNActions = [];\nlastNStates = [];\n- get preloadedState(): BaseAppState<*> {\n+ get preloadedState(): AppState {\nreturn this.lastNStates[0];\n}\n@@ -21,7 +21,7 @@ class ReduxLogger {\nreturn [...this.lastNActions];\n}\n- addAction(action: *, state: BaseAppState<*>) {\n+ addAction(action: *, state: AppState) {\nif (\nthis.lastNActions.length > 0 &&\nthis.lastNActions[this.lastNActions.length - 1].type === REHYDRATE\n" }, { "change_type": "ADD", "old_path": null, "new_path": "lib/utils/sanitization.js", "diff": "+// @flow\n+\n+import type {\n+ BaseAction,\n+ NativeAppState,\n+ AppState,\n+} from '../types/redux-types';\n+import { setNewSessionActionType } from './action-utils';\n+\n+function sanitizeAction(action: BaseAction): BaseAction {\n+ if (action.type === setNewSessionActionType) {\n+ const { sessionChange } = action.payload;\n+ if (sessionChange.cookieInvalidated) {\n+ const { cookie, ...rest } = sessionChange;\n+ return {\n+ type: \"SET_NEW_SESSION\",\n+ payload: {\n+ ...action.payload,\n+ sessionChange: { ...rest },\n+ },\n+ };\n+ } else {\n+ const { cookie, ...rest } = sessionChange;\n+ return {\n+ type: \"SET_NEW_SESSION\",\n+ payload: {\n+ ...action.payload,\n+ sessionChange: { ...rest },\n+ },\n+ };\n+ }\n+ }\n+ return action;\n+}\n+\n+function sanitizeState<T>(state: AppState): AppState {\n+ if (state.cookie !== undefined && state.cookie !== null) {\n+ return ({ ...state, cookie: null }: NativeAppState);\n+ }\n+ return state;\n+}\n+\n+export {\n+ sanitizeAction,\n+ sanitizeState,\n+};\n" }, { "change_type": "MODIFY", "old_path": "native/crash.react.js", "new_path": "native/crash.react.js", "diff": "@@ -31,6 +31,7 @@ import { sendReportActionTypes, sendReport } from 'lib/actions/report-actions';\nimport sleep from 'lib/utils/sleep';\nimport { reduxLogger } from 'lib/utils/redux-logger';\nimport { logOutActionTypes, logOut } from 'lib/actions/user-actions';\n+import { sanitizeAction, sanitizeState } from 'lib/utils/sanitization';\nimport Button from './components/button.react';\nimport { store } from './redux-setup';\n@@ -158,9 +159,9 @@ class Crash extends React.PureComponent<Props, State> {\nstack: data.error.stack,\ncomponentStack: data.info && data.info.componentStack,\n})),\n- preloadedState: reduxLogger.preloadedState,\n- currentState: store.getState(),\n- actions: reduxLogger.actions,\n+ preloadedState: sanitizeState(reduxLogger.preloadedState),\n+ currentState: sanitizeState(store.getState()),\n+ actions: reduxLogger.actions.map(sanitizeAction),\n});\nthis.setState({\nerrorReportID: result.id,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Sanitize cookie password from reports
129,187
20.10.2018 18:12:37
14,400
7212f5bde88ef251c8c7cdce5815fb75946da7ea
[server] Enable activityUpdater to handle focus and unfocus in the same request If updates get queued by the client that have the user visiting and leaving a thread, we should still set the thread as read.
[ { "change_type": "MODIFY", "old_path": "server/src/updaters/activity-updaters.js", "new_path": "server/src/updaters/activity-updaters.js", "diff": "@@ -37,27 +37,34 @@ async function activityUpdater(\n}\nconst threadID = activityUpdate.threadID;\nunverifiedThreadIDs.add(threadID);\n- focusUpdatesByThreadID.set(threadID, activityUpdate);\n+ let updatesForThreadID = focusUpdatesByThreadID.get(threadID);\n+ if (!updatesForThreadID) {\n+ updatesForThreadID = [];\n+ focusUpdatesByThreadID.set(updatesForThreadID);\n+ }\n+ updatesForThreadID.push(activityUpdate);\n}\nconst verifiedThreadIDs = await verifyThreadIDs([...unverifiedThreadIDs]);\n- const focusedThreadIDs = [];\n- const unfocusedThreadIDs = [];\n+ const focusedThreadIDs = new Set();\n+ const unfocusedThreadIDs = new Set();\nconst unfocusedThreadLatestMessages = new Map();\nfor (let threadID of verifiedThreadIDs) {\n- const focusUpdate = focusUpdatesByThreadID.get(threadID);\n- invariant(focusUpdate, `no focusUpdate for thread ID ${threadID}`);\n+ const focusUpdates = focusUpdatesByThreadID.get(threadID);\n+ invariant(focusUpdates, `n focusUpdate for thread ID ${threadID}`);\n+ for (let focusUpdate of focusUpdates) {\nif (focusUpdate.focus) {\n- focusedThreadIDs.push(threadID);\n+ focusedThreadIDs.add(threadID);\n} else if (focusUpdate.focus === false) {\n- unfocusedThreadIDs.push(threadID);\n+ unfocusedThreadIDs.add(threadID);\nunfocusedThreadLatestMessages.set(\nthreadID,\nfocusUpdate.latestMessage ? focusUpdate.latestMessage : \"0\",\n);\n}\n}\n+ }\nconst membershipQuery = SQL`\nSELECT thread\n@@ -74,12 +81,12 @@ async function activityUpdater(\nviewerMemberThreads.add(threadID);\n}\nconst filterFunc = threadID => viewerMemberThreads.has(threadID);\n- const memberFocusedThreadIDs = focusedThreadIDs.filter(filterFunc);\n- const memberUnfocusedThreadIDs = unfocusedThreadIDs.filter(filterFunc);\n+ const memberFocusedThreadIDs = [...focusedThreadIDs].filter(filterFunc);\n+ const memberUnfocusedThreadIDs = [...unfocusedThreadIDs].filter(filterFunc);\nconst promises = [];\n- promises.push(updateFocusedRows(viewer, focusedThreadIDs));\n- if (focusedThreadIDs.length > 0) {\n+ promises.push(updateFocusedRows(viewer, memberFocusedThreadIDs));\n+ if (memberFocusedThreadIDs.length > 0) {\npromises.push(dbQuery(SQL`\nUPDATE memberships\nSET unread = 0\n@@ -98,7 +105,7 @@ async function activityUpdater(\n{ viewer },\n));\nconst rescindCondition = SQL`\n- n.user = ${viewer.userID} AND n.thread IN (${focusedThreadIDs})\n+ n.user = ${viewer.userID} AND n.thread IN (${memberFocusedThreadIDs})\n`;\npromises.push(rescindPushNotifs(rescindCondition));\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Enable activityUpdater to handle focus and unfocus in the same request If updates get queued by the client that have the user visiting and leaving a thread, we should still set the thread as read.
129,187
22.10.2018 01:10:51
14,400
ca64d7ecc3d51eb709a84fbb1e360dd453159026
[server] Fix typo in activityUpdater
[ { "change_type": "MODIFY", "old_path": "server/src/updaters/activity-updaters.js", "new_path": "server/src/updaters/activity-updaters.js", "diff": "@@ -40,7 +40,7 @@ async function activityUpdater(\nlet updatesForThreadID = focusUpdatesByThreadID.get(threadID);\nif (!updatesForThreadID) {\nupdatesForThreadID = [];\n- focusUpdatesByThreadID.set(updatesForThreadID);\n+ focusUpdatesByThreadID.set(threadID, updatesForThreadID);\n}\nupdatesForThreadID.push(activityUpdate);\n}\n@@ -52,7 +52,7 @@ async function activityUpdater(\nconst unfocusedThreadLatestMessages = new Map();\nfor (let threadID of verifiedThreadIDs) {\nconst focusUpdates = focusUpdatesByThreadID.get(threadID);\n- invariant(focusUpdates, `n focusUpdate for thread ID ${threadID}`);\n+ invariant(focusUpdates, `no focusUpdate for thread ID ${threadID}`);\nfor (let focusUpdate of focusUpdates) {\nif (focusUpdate.focus) {\nfocusedThreadIDs.add(threadID);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Fix typo in activityUpdater
129,187
23.10.2018 10:44:10
14,400
7e1aa86948e06857d7d2d875b72ee4e6517a5d8d
Exclude SAVE_DRAFT from lastActionTypes in inconsistency reports
[ { "change_type": "MODIFY", "old_path": "lib/reducers/entry-reducer.js", "new_path": "lib/reducers/entry-reducer.js", "diff": "@@ -807,7 +807,7 @@ function findInconsistencies(\ncalendarQuery,\npollResult: oldResult,\npushResult: newResult,\n- lastActionTypes: reduxLogger.actions.map(action => action.type),\n+ lastActionTypes: reduxLogger.interestingActionTypes,\ntime: Date.now(),\n}];\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/thread-reducer.js", "new_path": "lib/reducers/thread-reducer.js", "diff": "@@ -224,7 +224,7 @@ function findInconsistencies(\naction: sanitizeAction(action),\npollResult: oldResult,\npushResult: newResult,\n- lastActionTypes: reduxLogger.actions.map(action => action.type),\n+ lastActionTypes: reduxLogger.interestingActionTypes,\ntime: Date.now(),\n}];\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/utils/redux-logger.js", "new_path": "lib/utils/redux-logger.js", "diff": "// @flow\n-import type { AppState } from '../types/redux-types';\n+import type { AppState, BaseAction } from '../types/redux-types';\n+\n+import { saveDraftActionType } from '../reducers/draft-reducer';\n// This is lifted from redux-persist/lib/constants.js\n// I don't want to add redux-persist to the web/server bundles...\n// import { REHYDRATE } from 'redux-persist';\nconst REHYDRATE = 'persist/REHYDRATE';\n+const uninterestingActionTypes = new Set([ saveDraftActionType ]);\nclass ReduxLogger {\n@@ -17,11 +20,17 @@ class ReduxLogger {\nreturn this.lastNStates[0];\n}\n- get actions(): Array<*> {\n+ get actions(): BaseAction[] {\nreturn [...this.lastNActions];\n}\n- addAction(action: *, state: AppState) {\n+ get interestingActionTypes(): Array<$PropertyType<BaseAction, 'type'>> {\n+ return this.actions\n+ .map(action => action.type)\n+ .filter(type => !uninterestingActionTypes.has(type));\n+ }\n+\n+ addAction(action: BaseAction, state: AppState) {\nif (\nthis.lastNActions.length > 0 &&\nthis.lastNActions[this.lastNActions.length - 1].type === REHYDRATE\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Exclude SAVE_DRAFT from lastActionTypes in inconsistency reports
129,187
15.10.2018 14:20:36
14,400
8a15b2bcaffb7f8d9e21c6dfb08e957e09e99bda
[server] Move outdated client invalidation logic to handler This allows us to customize the behavior depending on the handler, which matters because we can't change cookies from a socket context.
[ { "change_type": "MODIFY", "old_path": "lib/utils/errors.js", "new_path": "lib/utils/errors.js", "diff": "// @flow\n+import type { PlatformDetails } from '../types/device-types';\n+\nclass ExtendableError extends Error {\nconstructor(message: string) {\n@@ -18,6 +20,8 @@ class ExtendableError extends Error {\nclass ServerError extends ExtendableError {\npayload: ?Object;\n+ // Used for client_version_unsupported on server-side only\n+ platformDetails: ?PlatformDetails;\nconstructor(error: string, payload?: Object) {\nsuper(error);\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/handlers.js", "new_path": "server/src/responders/handlers.js", "diff": "@@ -11,6 +11,8 @@ import {\nfetchViewerForHomeRequest,\naddCookieToHomeResponse,\n} from '../session/cookies';\n+import { createNewAnonymousCookie } from '../session/cookies';\n+import { deleteCookie } from '../deleters/cookie-deleters';\nexport type JSONResponder = (viewer: Viewer, input: any) => Promise<*>;\nexport type DownloadResponder\n@@ -73,6 +75,19 @@ async function handleException(\n? { error: error.message, payload: error.payload }\n: { error: error.message };\nif (viewer) {\n+ if (error.message === \"client_version_unsupported\" && viewer.loggedIn) {\n+ // If the client version is unsupported, log the user out\n+ const { platformDetails } = error;\n+ const [ data ] = await Promise.all([\n+ createNewAnonymousCookie({\n+ platformDetails,\n+ deviceToken: viewer.deviceToken,\n+ }),\n+ deleteCookie(viewer.cookieID),\n+ ]);\n+ viewer.setNewCookie(data);\n+ viewer.cookieInvalidated = true;\n+ }\n// This can mutate the result object\nawait addCookieToJSONResponse(viewer, res, result);\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/session/version.js", "new_path": "server/src/session/version.js", "diff": "@@ -5,9 +5,6 @@ import type { Viewer } from '../session/viewer';\nimport { ServerError } from 'lib/utils/errors';\n-import { createNewAnonymousCookie } from './cookies';\n-import { deleteCookie } from '../deleters/cookie-deleters';\n-\nasync function verifyClientSupported(\nviewer: Viewer,\nplatformDetails: ?PlatformDetails,\n@@ -15,18 +12,9 @@ async function verifyClientSupported(\nif (clientSupported(platformDetails)) {\nreturn;\n}\n- if (viewer.loggedIn) {\n- const [ data ] = await Promise.all([\n- createNewAnonymousCookie({\n- platformDetails,\n- deviceToken: viewer.deviceToken,\n- }),\n- deleteCookie(viewer.cookieID),\n- ]);\n- viewer.setNewCookie(data);\n- viewer.cookieInvalidated = true;\n- }\n- throw new ServerError(\"client_version_unsupported\");\n+ const error = new ServerError(\"client_version_unsupported\");\n+ error.platformDetails = platformDetails;\n+ throw error;\n}\nfunction clientSupported(platformDetails: ?PlatformDetails): bool {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Move outdated client invalidation logic to handler This allows us to customize the behavior depending on the handler, which matters because we can't change cookies from a socket context.
129,187
15.10.2018 14:30:30
14,400
317abb4ffec6d5d1aa6430be2757ab2788cf1996
[server] Avoid specifying sanitizedInput as ServerError payload `ServerError`'s `payload` gets passed down to the client, which we don't need to do for `sanitizedInput`. We just want it to go into the server log.
[ { "change_type": "MODIFY", "old_path": "lib/utils/errors.js", "new_path": "lib/utils/errors.js", "diff": "@@ -19,9 +19,13 @@ class ExtendableError extends Error {\nclass ServerError extends ExtendableError {\n+ // When specified on server side, will get passed down to client\n+ // Only used in updateEntry and deleteEntry currently\npayload: ?Object;\n// Used for client_version_unsupported on server-side only\nplatformDetails: ?PlatformDetails;\n+ // Used for input validators on server-side only\n+ sanitizedInput: mixed;\nconstructor(error: string, payload?: Object) {\nsuper(error);\n" }, { "change_type": "MODIFY", "old_path": "server/src/utils/validation-utils.js", "new_path": "server/src/utils/validation-utils.js", "diff": "@@ -36,8 +36,9 @@ async function validateInput(viewer: Viewer, inputValidator: *, input: *) {\nreturn;\n}\n- const sanitizedInput = input ? sanitizeInput(inputValidator, input) : null;\n- throw new ServerError('invalid_parameters', { input: sanitizedInput });\n+ const error = new ServerError('invalid_parameters');\n+ error.sanitizedInput = input ? sanitizeInput(inputValidator, input) : null;\n+ throw error;\n}\nconst fakePassword = \"********\";\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Avoid specifying sanitizedInput as ServerError payload `ServerError`'s `payload` gets passed down to the client, which we don't need to do for `sanitizedInput`. We just want it to go into the server log.
129,187
16.10.2018 13:48:44
14,400
3decda32b00c4750167e9d11a98ddd6fa7dab233
Server WebSocket initialization logic Another overlarge commit. Hopefully I'll have better discipline going forward, but not like anyone's watching...
[ { "change_type": "MODIFY", "old_path": "lib/components/socket.react.js", "new_path": "lib/components/socket.react.js", "diff": "@@ -49,9 +49,12 @@ class Socket extends React.PureComponent<Props> {\nif (this.socket) {\nthis.socket.close();\n}\n- this.socket = this.props.openSocket();\n- this.socket.addEventListener('open', this.sendInitialMessage);\n- registerActiveWebSocket(this.socket);\n+ const socket = this.props.openSocket();\n+ socket.onopen = this.sendInitialMessage;\n+ socket.onmessage = this.receiveMessage;\n+ socket.onclose = this.onClose;\n+ this.socket = socket;\n+ registerActiveWebSocket(socket);\n}\ncloseSocket() {\n@@ -100,6 +103,17 @@ class Socket extends React.PureComponent<Props> {\nsocket.send(JSON.stringify(message));\n}\n+ receiveMessage = (event: MessageEvent) => {\n+ if (typeof event.data !== \"string\") {\n+ return;\n+ }\n+ console.log('message', JSON.parse(event.data));\n+ }\n+\n+ onClose = (event: CloseEvent) => {\n+ console.log('close', event);\n+ }\n+\nsendInitialMessage = () => {\nconst clientResponses = [ ...this.props.clientResponses ];\nif (this.props.activeThread) {\n" }, { "change_type": "MODIFY", "old_path": "lib/shared/socket-utils.js", "new_path": "lib/shared/socket-utils.js", "diff": "function createOpenSocketFunction(baseURL: string) {\nconst [ protocol, address ] = baseURL.split(\"://\");\n- const endpoint = `ws://${address}/ws`;\n- return () => {\n- const socket = new WebSocket(endpoint);\n- socket.addEventListener('message', event => {\n- console.log(event);\n- });\n- return socket;\n- };\n-\n+ const prefix = protocol === \"https\" ? \"wss\" : \"ws\";\n+ const endpoint = `${prefix}://${address}/ws`;\n+ return () => new WebSocket(endpoint);\n}\nexport {\n" }, { "change_type": "MODIFY", "old_path": "lib/types/ping-types.js", "new_path": "lib/types/ping-types.js", "diff": "@@ -23,7 +23,7 @@ export type PingRequest = {|\ntype?: PingResponseType,\ncalendarQuery: CalendarQuery,\nwatchedIDs: $ReadOnlyArray<string>,\n- lastPing: ?number,\n+ lastPing?: ?number,\nmessagesCurrentAsOf: ?number,\nupdatesCurrentAsOf: ?number,\nclientResponses?: $ReadOnlyArray<ClientResponse>,\n" }, { "change_type": "MODIFY", "old_path": "lib/types/socket-types.js", "new_path": "lib/types/socket-types.js", "diff": "// @flow\nimport type { SessionState, SessionIdentification } from './session-types';\n-import type { ClientResponse } from './request-types';\n+import type { ServerRequest, ClientResponse } from './request-types';\n+import type { RawThreadInfo } from './thread-types';\n+import type { MessagesPingResponse } from './message-types';\n+import type { UpdatesResult } from './update-types';\n+import type {\n+ UserInfo,\n+ CurrentUserInfo,\n+ LoggedOutUserInfo,\n+} from './user-types';\n+import type { RawEntryInfo } from './entry-types';\nimport invariant from 'invariant';\n+import { pingResponseTypes } from './ping-types';\n+\n// The types of messages that the client sends across the socket\nexport const clientSocketMessageTypes = Object.freeze({\nINITIAL: 0,\n@@ -22,14 +33,20 @@ export function assertClientSocketMessageType(\n// The types of messages that the server sends across the socket\nexport const serverSocketMessageTypes = Object.freeze({\n- INITIAL_RESPONSE: 0,\n+ STATE_SYNC: 0,\n+ REQUESTS: 1,\n+ ERROR: 2,\n+ AUTH_ERROR: 3,\n});\nexport type ServerSocketMessageType = $Values<typeof serverSocketMessageTypes>;\nexport function assertServerSocketMessageType(\nourServerSocketMessageType: number,\n): ServerSocketMessageType {\ninvariant(\n- ourServerSocketMessageType === 0,\n+ ourServerSocketMessageType === 0 ||\n+ ourServerSocketMessageType === 1 ||\n+ ourServerSocketMessageType === 2 ||\n+ ourServerSocketMessageType === 3,\n\"number is not ServerSocketMessageType enum\",\n);\nreturn ourServerSocketMessageType;\n@@ -47,6 +64,59 @@ export type InitialClientSocketMessage = {|\nexport type ClientSocketMessage =\n| InitialClientSocketMessage;\n+export const stateSyncPayloadTypes = pingResponseTypes;\n+export type StateSyncFullPayload = {|\n+ type: 0,\n+ messagesResult: MessagesPingResponse,\n+ threadInfos: {[id: string]: RawThreadInfo},\n+ currentUserInfo: CurrentUserInfo,\n+ rawEntryInfos: $ReadOnlyArray<RawEntryInfo>,\n+ userInfos: $ReadOnlyArray<UserInfo>,\n+ // Included iff client is using sessionIdentifierTypes.BODY_SESSION_ID\n+ sessionID?: string,\n+|};\n+type StateSyncIncrementalPayload = {|\n+ type: 1,\n+ messagesResult: MessagesPingResponse,\n+ updatesResult: UpdatesResult,\n+ deltaEntryInfos: $ReadOnlyArray<RawEntryInfo>,\n+ userInfos: $ReadOnlyArray<UserInfo>,\n+|};\n+export type StateSyncPayload =\n+ | StateSyncFullPayload\n+ | StateSyncIncrementalPayload;\n+\n+export type StateSyncServerSocketMessage = {|\n+ type: 0,\n+ responseTo: number,\n+ payload: StateSyncPayload,\n+|};\n+export type RequestsServerSocketMessage = {|\n+ type: 1,\n+ payload: {|\n+ serverRequests: $ReadOnlyArray<ServerRequest>,\n+ |},\n+|};\n+export type ErrorServerSocketMessage = {|\n+ type: 2,\n+ responseTo?: number,\n+ message: string,\n+ payload?: Object,\n+|};\n+export type AuthErrorServerSocketMessage = {|\n+ type: 3,\n+ responseTo: number,\n+ message: string,\n+ // If unspecified, it is because the client is using cookieSources.HEADER,\n+ // which means the server can't update the cookie from a socket message.\n+ currentUserInfo?: LoggedOutUserInfo,\n+|};\n+export type ServerSocketMessage =\n+ | StateSyncServerSocketMessage\n+ | RequestsServerSocketMessage\n+ | ErrorServerSocketMessage\n+ | AuthErrorServerSocketMessage;\n+\nexport type ConnectionStatus =\n| \"connecting\"\n| \"connected\"\n" }, { "change_type": "MODIFY", "old_path": "server/flow-typed/npm/ws_vx.x.x.js", "new_path": "server/flow-typed/npm/ws_vx.x.x.js", "diff": "@@ -19,6 +19,7 @@ declare module 'ws' {\ndeclare type WebSocket = {\non: (name: string, func: Function) => void,\nsend: (value: string) => void,\n+ close: (code?: number, reason?: string) => void,\n};\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/ping-responders.js", "new_path": "server/src/responders/ping-responders.js", "diff": "@@ -92,14 +92,7 @@ import {\nimport { activityUpdatesInputValidator } from './activity-responders';\nimport { SQL } from '../database';\n-const pingRequestInputValidator = tShape({\n- type: t.maybe(t.Number),\n- calendarQuery: entryQueryInputValidator,\n- lastPing: t.maybe(t.Number), // deprecated\n- messagesCurrentAsOf: t.maybe(t.Number),\n- updatesCurrentAsOf: t.maybe(t.Number),\n- watchedIDs: t.list(t.String),\n- clientResponses: t.maybe(t.list(t.union([\n+const clientResponseInputValidator = t.union([\ntShape({\ntype: t.irreducible(\n'serverRequestTypes.PLATFORM',\n@@ -169,7 +162,16 @@ const pingRequestInputValidator = tShape({\n),\nactivityUpdates: activityUpdatesInputValidator,\n}),\n- ]))),\n+]);\n+\n+const pingRequestInputValidator = tShape({\n+ type: t.maybe(t.Number),\n+ calendarQuery: entryQueryInputValidator,\n+ lastPing: t.maybe(t.Number), // deprecated\n+ messagesCurrentAsOf: t.maybe(t.Number),\n+ updatesCurrentAsOf: t.maybe(t.Number),\n+ watchedIDs: t.list(t.String),\n+ clientResponses: t.maybe(t.list(clientResponseInputValidator)),\n});\nasync function pingResponder(\n@@ -731,5 +733,9 @@ async function checkState(\n}\nexport {\n+ clientResponseInputValidator,\npingResponder,\n+ processClientResponses,\n+ initializeSession,\n+ checkState,\n};\n" }, { "change_type": "MODIFY", "old_path": "server/src/session/cookies.js", "new_path": "server/src/session/cookies.js", "diff": "@@ -18,6 +18,7 @@ import {\n} from 'lib/types/device-types';\nimport type { CalendarQuery } from 'lib/types/entry-types';\nimport type { UserInfo } from 'lib/types/user-types';\n+import type { InitialClientSocketMessage } from 'lib/types/socket-types';\nimport bcrypt from 'twin-bcrypt';\nimport url from 'url';\n@@ -25,6 +26,7 @@ import crypto from 'crypto';\nimport { ServerError } from 'lib/utils/errors';\nimport { values } from 'lib/utils/objects';\n+import { promiseAll } from 'lib/utils/promises';\nimport { dbQuery, SQL } from '../database';\nimport { Viewer } from './viewer';\n@@ -45,6 +47,9 @@ function cookieIsExpired(lastUsed: number) {\ntype FetchViewerResult =\n| {| type: \"valid\", viewer: Viewer |}\n+ | InvalidFetchViewerResult;\n+\n+type InvalidFetchViewerResult =\n| {|\ntype: \"nonexistant\",\ncookieName: ?string,\n@@ -64,9 +69,9 @@ type FetchViewerResult =\nasync function fetchUserViewer(\ncookie: string,\ncookieSource: CookieSource,\n- req: $Request,\n+ sessionParameterInfo: SessionParameterInfo,\n): Promise<FetchViewerResult> {\n- const sessionIdentifierType = getSessionIdentifierTypeFromRequestBody(req);\n+ const { sessionIdentifierType } = sessionParameterInfo;\nconst [ cookieID, cookiePassword ] = cookie.split(':');\nif (!cookieID || !cookiePassword) {\nreturn {\n@@ -84,7 +89,7 @@ async function fetchUserViewer(\n`;\nconst [ [ result ], allSessionInfo ] = await Promise.all([\ndbQuery(query),\n- fetchSessionInfo(req, cookieID),\n+ fetchSessionInfo(sessionParameterInfo, cookieID),\n]);\nif (result.length === 0) {\nreturn {\n@@ -148,9 +153,9 @@ async function fetchUserViewer(\nasync function fetchAnonymousViewer(\ncookie: string,\ncookieSource: CookieSource,\n- req: $Request,\n+ sessionParameterInfo: SessionParameterInfo,\n): Promise<FetchViewerResult> {\n- const sessionIdentifierType = getSessionIdentifierTypeFromRequestBody(req);\n+ const { sessionIdentifierType } = sessionParameterInfo;\nconst [ cookieID, cookiePassword ] = cookie.split(':');\nif (!cookieID || !cookiePassword) {\nreturn {\n@@ -168,7 +173,7 @@ async function fetchAnonymousViewer(\n`;\nconst [ [ result ], allSessionInfo ] = await Promise.all([\ndbQuery(query),\n- fetchSessionInfo(req, cookieID),\n+ fetchSessionInfo(sessionParameterInfo, cookieID),\n]);\nif (result.length === 0) {\nreturn {\n@@ -227,29 +232,10 @@ async function fetchAnonymousViewer(\nreturn { type: \"valid\", viewer };\n}\n-function getSessionIDFromRequestBody(req: $Request): ?string {\n- const body = (req.body: any);\n- if (req.method === \"GET\" && body.sessionID === undefined) {\n- // GET requests are only done from web, and web requests should always\n- // specify a sessionID since the cookieID can't be guaranteed unique\n- return null;\n- }\n- return body.sessionID;\n-}\n-\n-function getSessionIdentifierTypeFromRequestBody(\n- req: $Request,\n-): SessionIdentifierType {\n- if (req.method === \"GET\") {\n- // GET requests are only done from web, and web requests should always\n- // specify a sessionID since the cookieID can't be guaranteed unique\n- return sessionIdentifierTypes.BODY_SESSION_ID;\n- }\n- const sessionID = getSessionIDFromRequestBody(req);\n- return sessionID === undefined\n- ? sessionIdentifierTypes.COOKIE_ID\n- : sessionIdentifierTypes.BODY_SESSION_ID;\n-}\n+type SessionParameterInfo = {|\n+ sessionID: ?string,\n+ sessionIdentifierType: SessionIdentifierType,\n+|};\ntype SessionInfo = {|\nsessionID: ?string,\n@@ -257,10 +243,10 @@ type SessionInfo = {|\ncalendarQuery: CalendarQuery,\n|};\nasync function fetchSessionInfo(\n- req: $Request,\n+ sessionParameterInfo: SessionParameterInfo,\ncookieID: string,\n): Promise<?SessionInfo> {\n- const sessionID = getSessionIDFromRequestBody(req);\n+ const { sessionID } = sessionParameterInfo;\nconst session = sessionID !== undefined ? sessionID : cookieID;\nif (!session) {\nreturn null;\n@@ -286,32 +272,49 @@ async function fetchSessionInfo(\n// doesn't update the cookie's last_used timestamp.\nasync function fetchViewerFromCookieData(\nreq: $Request,\n+ sessionParameterInfo: SessionParameterInfo,\n): Promise<FetchViewerResult> {\nconst { user, anonymous } = req.cookies;\nif (user) {\n- return await fetchUserViewer(user, cookieSources.HEADER, req);\n+ return await fetchUserViewer(\n+ user,\n+ cookieSources.HEADER,\n+ sessionParameterInfo,\n+ );\n} else if (anonymous) {\n- return await fetchAnonymousViewer(anonymous, cookieSources.HEADER, req);\n+ return await fetchAnonymousViewer(\n+ anonymous,\n+ cookieSources.HEADER,\n+ sessionParameterInfo,\n+ );\n}\nreturn {\ntype: \"nonexistant\",\ncookieName: null,\ncookieSource: null,\n- sessionIdentifierType: getSessionIdentifierTypeFromRequestBody(req),\n+ sessionIdentifierType: sessionParameterInfo.sessionIdentifierType,\n};\n}\nasync function fetchViewerFromRequestBody(\n- req: $Request,\n+ body: mixed,\n+ sessionParameterInfo: SessionParameterInfo,\n): Promise<FetchViewerResult> {\n- const body = (req.body: any);\n+ if (!body || typeof body !== \"object\") {\n+ return {\n+ type: \"nonexistant\",\n+ cookieName: null,\n+ cookieSource: null,\n+ sessionIdentifierType: sessionParameterInfo.sessionIdentifierType,\n+ };\n+ }\nconst cookiePair = body.cookie;\nif (cookiePair === null) {\nreturn {\ntype: \"nonexistant\",\ncookieName: null,\ncookieSource: cookieSources.BODY,\n- sessionIdentifierType: getSessionIdentifierTypeFromRequestBody(req),\n+ sessionIdentifierType: sessionParameterInfo.sessionIdentifierType,\n};\n}\nif (!cookiePair || !(typeof cookiePair === \"string\")) {\n@@ -319,31 +322,53 @@ async function fetchViewerFromRequestBody(\ntype: \"nonexistant\",\ncookieName: null,\ncookieSource: null,\n- sessionIdentifierType: getSessionIdentifierTypeFromRequestBody(req),\n+ sessionIdentifierType: sessionParameterInfo.sessionIdentifierType,\n};\n}\nconst [ type, cookie ] = cookiePair.split(\"=\");\nif (type === cookieTypes.USER && cookie) {\n- return await fetchUserViewer(cookie, cookieSources.BODY, req);\n+ return await fetchUserViewer(\n+ cookie,\n+ cookieSources.BODY,\n+ sessionParameterInfo,\n+ );\n} else if (type === cookieTypes.ANONYMOUS && cookie) {\n- return await fetchAnonymousViewer(cookie, cookieSources.BODY, req);\n+ return await fetchAnonymousViewer(\n+ cookie,\n+ cookieSources.BODY,\n+ sessionParameterInfo,\n+ );\n}\nreturn {\ntype: \"nonexistant\",\ncookieName: null,\ncookieSource: null,\n- sessionIdentifierType: getSessionIdentifierTypeFromRequestBody(req),\n+ sessionIdentifierType: sessionParameterInfo.sessionIdentifierType,\n};\n}\n+function getSessionParameterInfoFromRequestBody(\n+ req: $Request,\n+): SessionParameterInfo {\n+ const body = (req.body: any);\n+ const sessionID = body.sessionID !== undefined || req.method !== \"GET\"\n+ ? body.sessionID\n+ : null;\n+ const sessionIdentifierType = req.method === \"GET\" || sessionID !== undefined\n+ ? sessionIdentifierTypes.BODY_SESSION_ID\n+ : sessionIdentifierTypes.COOKIE_ID;\n+ return { sessionID, sessionIdentifierType };\n+}\n+\nasync function fetchViewerForJSONRequest(req: $Request): Promise<Viewer> {\nassertSecureRequest(req);\n- let result = await fetchViewerFromRequestBody(req);\n+ const sessionParameterInfo = getSessionParameterInfoFromRequestBody(req);\n+ let result = await fetchViewerFromRequestBody(req.body, sessionParameterInfo);\nif (\nresult.type === \"nonexistant\" &&\n(result.cookieSource === null || result.cookieSource === undefined)\n) {\n- result = await fetchViewerFromCookieData(req);\n+ result = await fetchViewerFromCookieData(req, sessionParameterInfo);\n}\nreturn await handleFetchViewerResult(result);\n}\n@@ -351,10 +376,69 @@ async function fetchViewerForJSONRequest(req: $Request): Promise<Viewer> {\nconst webPlatformDetails = { platform: \"web\" };\nasync function fetchViewerForHomeRequest(req: $Request): Promise<Viewer> {\nassertSecureRequest(req);\n- const result = await fetchViewerFromCookieData(req);\n+ const sessionParameterInfo = getSessionParameterInfoFromRequestBody(req);\n+ const result = await fetchViewerFromCookieData(req, sessionParameterInfo);\nreturn await handleFetchViewerResult(result, webPlatformDetails);\n}\n+async function fetchViewerForSocket(\n+ req: $Request,\n+ clientMessage: InitialClientSocketMessage,\n+): Promise<?Viewer> {\n+ assertSecureRequest(req);\n+ const { sessionIdentification } = clientMessage.payload;\n+ const { sessionID } = sessionIdentification;\n+ const sessionParameterInfo = {\n+ sessionID,\n+ sessionIdentifierType: sessionID !== undefined\n+ ? sessionIdentifierTypes.BODY_SESSION_ID\n+ : sessionIdentifierTypes.COOKIE_ID,\n+ };\n+\n+ let result = await fetchViewerFromRequestBody(\n+ clientMessage.payload.sessionIdentification,\n+ sessionParameterInfo,\n+ );\n+ if (\n+ result.type === \"nonexistant\" &&\n+ (result.cookieSource === null || result.cookieSource === undefined)\n+ ) {\n+ result = await fetchViewerFromCookieData(req, sessionParameterInfo);\n+ }\n+ if (result.type === \"valid\") {\n+ return result.viewer;\n+ }\n+\n+ const promises = {};\n+ if (result.cookieSource === cookieSources.BODY) {\n+ // We initialize a socket's Viewer after the WebSocket handshake, since to\n+ // properly initialize the Viewer we need a bunch of data, but that data\n+ // can't be sent until after the handshake. Consequently, by the time we\n+ // know that a cookie may be invalid, we are no longer communicating via\n+ // HTTP, and have no way to set a new cookie for HEADER (web) clients.\n+ const platformDetails = result.type === \"invalidated\"\n+ ? result.platformDetails\n+ : null;\n+ const deviceToken = result.type === \"invalidated\"\n+ ? result.deviceToken\n+ : null;\n+ promises.anonymousViewerData = createNewAnonymousCookie({\n+ platformDetails,\n+ deviceToken,\n+ });\n+ }\n+ if (result.type === \"invalidated\") {\n+ promises.deleteCookie = deleteCookie(result.cookieID);\n+ }\n+ const { anonymousViewerData } = await promiseAll(promises);\n+\n+ if (!anonymousViewerData) {\n+ return null;\n+ }\n+\n+ return createViewerForInvalidFetchViewerResult(result, anonymousViewerData);\n+}\n+\nasync function handleFetchViewerResult(\nresult: FetchViewerResult,\ninputPlatformDetails?: PlatformDetails,\n@@ -376,6 +460,13 @@ async function handleFetchViewerResult(\n: null,\n]);\n+ return createViewerForInvalidFetchViewerResult(result, anonymousViewerData);\n+}\n+\n+function createViewerForInvalidFetchViewerResult(\n+ result: InvalidFetchViewerResult,\n+ anonymousViewerData: AnonymousViewerData,\n+): Viewer {\n// If a null cookie was specified in the request body, result.cookieSource\n// will still be BODY here. The only way it would be null or undefined here\n// is if there was no cookie specified in either the body or the header, in\n@@ -650,9 +741,11 @@ async function setCookiePlatformDetails(\nexport {\nfetchViewerForJSONRequest,\nfetchViewerForHomeRequest,\n+ fetchViewerForSocket,\ncreateNewAnonymousCookie,\ncreateNewUserCookie,\nsetNewSession,\n+ extendCookieLifespan,\naddCookieToJSONResponse,\naddCookieToHomeResponse,\nsetCookiePlatform,\n" }, { "change_type": "MODIFY", "old_path": "server/src/session/viewer.js", "new_path": "server/src/session/viewer.js", "diff": "@@ -35,7 +35,7 @@ export type AnonymousViewerData = {|\n+platformDetails: ?PlatformDetails,\n+deviceToken: ?string,\n+cookieSource?: CookieSource,\n- +cookieID: ?string,\n+ +cookieID: string,\n+cookiePassword: ?string,\n+cookieInsertedThisRequest?: bool,\n+sessionIdentifierType?: SessionIdentifierType,\n" }, { "change_type": "MODIFY", "old_path": "server/src/socket.js", "new_path": "server/src/socket.js", "diff": "import type { WebSocket } from 'ws';\nimport type { $Request } from 'express';\n+import {\n+ type ClientSocketMessage,\n+ type InitialClientSocketMessage,\n+ type StateSyncFullPayload,\n+ type ServerSocketMessage,\n+ type ErrorServerSocketMessage,\n+ type AuthErrorServerSocketMessage,\n+ clientSocketMessageTypes,\n+ stateSyncPayloadTypes,\n+ serverSocketMessageTypes,\n+} from 'lib/types/socket-types';\n+import { cookieSources } from 'lib/types/session-types';\n+import type { Viewer } from './session/viewer';\n+import { defaultNumberPerThread } from 'lib/types/message-types';\n+\n+import t from 'tcomb';\n+import invariant from 'invariant';\n+\n+import { ServerError } from 'lib/utils/errors';\n+import { mostRecentMessageTimestamp } from 'lib/shared/message-utils';\n+import { mostRecentUpdateTimestamp } from 'lib/shared/update-utils';\n+import { promiseAll } from 'lib/utils/promises';\n+import { values } from 'lib/utils/objects';\n+\n+import {\n+ checkInputValidator,\n+ checkClientSupported,\n+ tShape,\n+} from './utils/validation-utils';\n+import {\n+ newEntryQueryInputValidator,\n+ verifyCalendarQueryThreadIDs,\n+} from './responders/entry-responders';\n+import {\n+ clientResponseInputValidator,\n+ processClientResponses,\n+ initializeSession,\n+ checkState,\n+} from './responders/ping-responders';\n+import { assertSecureRequest } from './utils/security-utils';\n+import { fetchViewerForSocket, extendCookieLifespan } from './session/cookies';\n+import { fetchMessageInfosSince } from './fetchers/message-fetchers';\n+import { fetchThreadInfos } from './fetchers/thread-fetchers';\n+import { fetchEntryInfos } from './fetchers/entry-fetchers';\n+import { fetchCurrentUserInfo } from './fetchers/user-fetchers';\n+import { updateActivityTime } from './updaters/activity-updaters';\n+import {\n+ deleteUpdatesBeforeTimeTargettingSession,\n+} from './deleters/update-deleters';\n+import { fetchUpdateInfos } from './fetchers/update-fetchers';\n+import { commitSessionUpdate } from './updaters/session-updaters';\n+import { handleAsyncPromise } from './responders/handlers';\n+import { deleteCookie } from './deleters/cookie-deleters';\n+import { createNewAnonymousCookie } from './session/cookies';\n+\n+const clientSocketMessageInputValidator = tShape({\n+ type: t.irreducible(\n+ 'clientSocketMessageTypes.INITIAL',\n+ x => x === clientSocketMessageTypes.INITIAL,\n+ ),\n+ id: t.Number,\n+ payload: tShape({\n+ sessionIdentification: tShape({\n+ cookie: t.maybe(t.String),\n+ sessionID: t.maybe(t.String),\n+ }),\n+ sessionState: tShape({\n+ calendarQuery: newEntryQueryInputValidator,\n+ messagesCurrentAsOf: t.Number,\n+ updatesCurrentAsOf: t.Number,\n+ watchedIDs: t.list(t.String),\n+ }),\n+ clientResponses: t.list(clientResponseInputValidator),\n+ }),\n+});\n+\n+type SendMessageFunc = (message: ServerSocketMessage) => void;\nfunction onConnection(ws: WebSocket, req: $Request) {\n- console.log(req.cookies);\n- ws.on('message', function incoming(message) {\n- console.log(message);\n+ assertSecureRequest(req);\n+ let viewer;\n+ const sendMessage = (message: ServerSocketMessage) => {\n+ ws.send(JSON.stringify(message));\n+ };\n+ ws.on('message', async messageString => {\n+ let clientSocketMessage: ?ClientSocketMessage;\n+ try {\n+ const message = JSON.parse(messageString);\n+ checkInputValidator(clientSocketMessageInputValidator, message);\n+ clientSocketMessage = message;\n+ if (clientSocketMessage.type === clientSocketMessageTypes.INITIAL) {\n+ if (viewer) {\n+ // This indicates that the user sent multiple INITIAL messages.\n+ throw new ServerError('socket_already_initialized');\n+ }\n+ viewer = await fetchViewerForSocket(req, clientSocketMessage);\n+ if (!viewer) {\n+ // This indicates that the cookie was invalid, but the client is using\n+ // cookieSources.HEADER and thus can't accept a new cookie over\n+ // WebSockets. See comment under catch block for socket_deauthorized.\n+ throw new ServerError('socket_deauthorized');\n+ }\n+ }\n+ if (!viewer) {\n+ // This indicates a non-INITIAL message was sent by the client before\n+ // the INITIAL message.\n+ throw new ServerError('socket_uninitialized');\n+ }\n+ if (viewer.sessionChanged) {\n+ // This indicates that the cookie was invalid, and we've assigned a new\n+ // anonymous one.\n+ throw new ServerError('socket_deauthorized');\n+ }\n+ if (!viewer.loggedIn) {\n+ // This indicates that the specified cookie was an anonymous one.\n+ throw new ServerError('not_logged_in');\n+ }\n+ await checkClientSupported(\n+ viewer,\n+ clientSocketMessageInputValidator,\n+ clientSocketMessage,\n+ );\n+ const serverResponses = await handleClientSocketMessage(\n+ viewer,\n+ clientSocketMessage,\n+ );\n+ if (viewer.sessionChanged) {\n+ // This indicates that something has caused the session to change, which\n+ // shouldn't happen from inside a WebSocket since we can't handle cookie\n+ // invalidation.\n+ throw new ServerError('session_mutated_from_socket');\n+ }\n+ handleAsyncPromise(extendCookieLifespan(viewer.cookieID));\n+ for (let response of serverResponses) {\n+ sendMessage(response);\n+ }\n+ } catch (error) {\n+ console.warn(error);\n+ if (!(error instanceof ServerError)) {\n+ const errorMessage: ErrorServerSocketMessage = {\n+ type: serverSocketMessageTypes.ERROR,\n+ message: error.message,\n+ };\n+ const responseTo = clientSocketMessage ? clientSocketMessage.id : null;\n+ if (responseTo !== null) {\n+ errorMessage.responseTo = responseTo;\n+ }\n+ sendMessage(errorMessage);\n+ return;\n+ }\n+ invariant(clientSocketMessage, \"should be set\");\n+ const responseTo = clientSocketMessage.id;\n+ if (error.message === \"socket_deauthorized\") {\n+ const authErrorMessage: AuthErrorServerSocketMessage = {\n+ type: serverSocketMessageTypes.AUTH_ERROR,\n+ responseTo,\n+ message: error.message,\n+ }\n+ if (viewer) {\n+ // viewer should only be falsey for cookieSources.HEADER (web)\n+ // clients. Usually if the cookie is invalid we construct a new\n+ // anonymous Viewer with a new cookie, and then pass the cookie down\n+ // in the error. But we can't pass HTTP cookies in WebSocket messages.\n+ authErrorMessage.currentUserInfo = {\n+ id: viewer.cookieID,\n+ anonymous: true,\n+ };\n+ }\n+ sendMessage(authErrorMessage);\n+ ws.close(4100, error.message);\n+ return;\n+ } else if (error.message === \"client_version_unsupported\") {\n+ invariant(viewer, \"should be set\");\n+ const promises = {};\n+ promises.deleteCookie = deleteCookie(viewer.cookieID);\n+ if (viewer.cookieSource !== cookieSources.BODY) {\n+ promises.anonymousViewerData = createNewAnonymousCookie({\n+ platformDetails: error.platformDetails,\n+ deviceToken: viewer.deviceToken,\n+ });\n+ }\n+ const { anonymousViewerData } = await promiseAll(promises);\n+ const authErrorMessage: AuthErrorServerSocketMessage = {\n+ type: serverSocketMessageTypes.AUTH_ERROR,\n+ responseTo,\n+ message: error.message,\n+ }\n+ if (anonymousViewerData) {\n+ authErrorMessage.currentUserInfo = {\n+ id: anonymousViewerData.cookieID,\n+ anonymous: true,\n+ };\n+ }\n+ sendMessage(authErrorMessage);\n+ ws.close(4101, error.message);\n+ return;\n+ }\n+ sendMessage({\n+ type: serverSocketMessageTypes.ERROR,\n+ responseTo,\n+ message: error.message,\n+ });\n+ if (error.message === \"not_logged_in\") {\n+ ws.close(4101, error.message);\n+ } else if (error.message === \"session_mutated_from_socket\") {\n+ ws.close(4102, error.message);\n+ }\n+ }\n+ });\n+ ws.on('close', () => {\n+ console.log('connection closed');\n});\n- console.log('onConnection???');\n+}\n+\n+async function handleClientSocketMessage(\n+ viewer: Viewer,\n+ message: ClientSocketMessage,\n+): Promise<ServerSocketMessage[]> {\n+ if (message.type === clientSocketMessageTypes.INITIAL) {\n+ return await handleInitialClientSocketMessage(viewer, message);\n+ }\n+ return [];\n+}\n+\n+async function handleInitialClientSocketMessage(\n+ viewer: Viewer,\n+ message: InitialClientSocketMessage,\n+): Promise<ServerSocketMessage[]> {\n+ const responses = [];\n+\n+ const { sessionState, clientResponses } = message.payload;\n+ const {\n+ calendarQuery,\n+ updatesCurrentAsOf: oldUpdatesCurrentAsOf,\n+ messagesCurrentAsOf: oldMessagesCurrentAsOf,\n+ watchedIDs,\n+ } = sessionState;\n+ await verifyCalendarQueryThreadIDs(calendarQuery);\n+\n+ const sessionInitializationResult = await initializeSession(\n+ viewer,\n+ calendarQuery,\n+ oldUpdatesCurrentAsOf,\n+ );\n+\n+ const threadCursors = {};\n+ for (let watchedThreadID of watchedIDs) {\n+ threadCursors[watchedThreadID] = null;\n+ }\n+ const threadSelectionCriteria = { threadCursors, joinedThreads: true };\n+ const [\n+ fetchMessagesResult,\n+ { serverRequests, stateCheckStatus },\n+ ] = await Promise.all([\n+ fetchMessageInfosSince(\n+ viewer,\n+ threadSelectionCriteria,\n+ oldMessagesCurrentAsOf,\n+ defaultNumberPerThread,\n+ ),\n+ processClientResponses(\n+ viewer,\n+ clientResponses,\n+ ),\n+ ]);\n+ const messagesResult = {\n+ rawMessageInfos: fetchMessagesResult.rawMessageInfos,\n+ truncationStatuses: fetchMessagesResult.truncationStatuses,\n+ currentAsOf: mostRecentMessageTimestamp(\n+ fetchMessagesResult.rawMessageInfos,\n+ oldMessagesCurrentAsOf,\n+ ),\n+ };\n+\n+ if (!sessionInitializationResult.sessionContinued) {\n+ const [\n+ threadsResult,\n+ entriesResult,\n+ currentUserInfo,\n+ ] = await Promise.all([\n+ fetchThreadInfos(viewer),\n+ fetchEntryInfos(viewer, [ calendarQuery ]),\n+ fetchCurrentUserInfo(viewer),\n+ ]);\n+ const payload: StateSyncFullPayload = {\n+ type: stateSyncPayloadTypes.FULL,\n+ messagesResult,\n+ threadInfos: threadsResult.threadInfos,\n+ currentUserInfo,\n+ rawEntryInfos: entriesResult.rawEntryInfos,\n+ userInfos: values({\n+ ...fetchMessagesResult.userInfos,\n+ ...entriesResult.userInfos,\n+ ...threadsResult.userInfos,\n+ }),\n+ };\n+ if (viewer.sessionChanged) {\n+ // If initializeSession encounters sessionIdentifierTypes.BODY_SESSION_ID,\n+ // but the session is unspecified or expired, it will set a new sessionID\n+ // and specify viewer.sessionChanged\n+ const { sessionID } = viewer;\n+ invariant(sessionID !== null && sessionID !== undefined, \"should be set\");\n+ payload.sessionID = sessionID;\n+ viewer.sessionChanged = false;\n+ }\n+ responses.push({\n+ type: serverSocketMessageTypes.STATE_SYNC,\n+ responseTo: message.id,\n+ payload,\n+ });\n+ } else {\n+ const promises = {};\n+ promises.activityUpdate = updateActivityTime(viewer);\n+ promises.deleteExpiredUpdates = deleteUpdatesBeforeTimeTargettingSession(\n+ viewer,\n+ oldUpdatesCurrentAsOf,\n+ );\n+ promises.fetchUpdateResult = fetchUpdateInfos(\n+ viewer,\n+ oldUpdatesCurrentAsOf,\n+ calendarQuery,\n+ );\n+ if (stateCheckStatus) {\n+ promises.stateCheck = checkState(viewer, stateCheckStatus, calendarQuery);\n+ }\n+ const { fetchUpdateResult, stateCheck } = await promiseAll(promises);\n+\n+ const updateUserInfos = fetchUpdateResult.userInfos;\n+ const { updateInfos } = fetchUpdateResult;\n+ const newUpdatesCurrentAsOf = mostRecentUpdateTimestamp(\n+ [...updateInfos],\n+ oldUpdatesCurrentAsOf,\n+ );\n+ const updatesResult = {\n+ newUpdates: updateInfos,\n+ currentAsOf: newUpdatesCurrentAsOf,\n+ };\n+\n+ let sessionUpdate = sessionInitializationResult.sessionUpdate;\n+ if (stateCheck && stateCheck.sessionUpdate) {\n+ sessionUpdate = { ...sessionUpdate, ...stateCheck.sessionUpdate };\n+ }\n+ await commitSessionUpdate(viewer, sessionUpdate);\n+\n+ if (stateCheck && stateCheck.checkStateRequest) {\n+ serverRequests.push(stateCheck.checkStateRequest);\n+ }\n+\n+ responses.push({\n+ type: serverSocketMessageTypes.STATE_SYNC,\n+ responseTo: message.id,\n+ payload: {\n+ type: stateSyncPayloadTypes.INCREMENTAL,\n+ messagesResult,\n+ updatesResult,\n+ deltaEntryInfos:\n+ sessionInitializationResult.deltaEntryInfoResult.rawEntryInfos,\n+ userInfos: values({\n+ ...fetchMessagesResult.userInfos,\n+ ...updateUserInfos,\n+ ...sessionInitializationResult.deltaEntryInfoResult.userInfos,\n+ }),\n+ },\n+ });\n+ }\n+\n+ if (serverRequests.length > 0) {\n+ responses.push({\n+ type: serverSocketMessageTypes.REQUESTS,\n+ payload: {\n+ serverRequests,\n+ },\n+ });\n+ }\n- ws.send('something');\n+ return responses;\n}\nexport {\n" }, { "change_type": "MODIFY", "old_path": "server/src/utils/validation-utils.js", "new_path": "server/src/utils/validation-utils.js", "diff": "@@ -9,6 +9,20 @@ import { ServerError } from 'lib/utils/errors';\nimport { verifyClientSupported } from '../session/version';\nasync function validateInput(viewer: Viewer, inputValidator: *, input: *) {\n+ await checkClientSupported(viewer, inputValidator, input);\n+ checkInputValidator(inputValidator, input);\n+}\n+\n+async function checkInputValidator(inputValidator: *, input: *) {\n+ if (!inputValidator || inputValidator.is(input)) {\n+ return;\n+ }\n+ const error = new ServerError('invalid_parameters');\n+ error.sanitizedInput = input ? sanitizeInput(inputValidator, input) : null;\n+ throw error;\n+}\n+\n+async function checkClientSupported(viewer: Viewer, inputValidator: *, input: *) {\nlet platformDetails;\nif (inputValidator) {\nplatformDetails = findFirstInputMatchingValidator(\n@@ -31,14 +45,6 @@ async function validateInput(viewer: Viewer, inputValidator: *, input: *) {\n({ platformDetails } = viewer);\n}\nawait verifyClientSupported(viewer, platformDetails);\n-\n- if (!inputValidator || inputValidator.is(input)) {\n- return;\n- }\n-\n- const error = new ServerError('invalid_parameters');\n- error.sanitizedInput = input ? sanitizeInput(inputValidator, input) : null;\n- throw error;\n}\nconst fakePassword = \"********\";\n@@ -183,6 +189,8 @@ const tPassword = t.refinement(t.String, (password: string) => password);\nexport {\nvalidateInput,\n+ checkInputValidator,\n+ checkClientSupported,\ntBool,\ntString,\ntShape,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Server WebSocket initialization logic Another overlarge commit. Hopefully I'll have better discipline going forward, but not like anyone's watching...
129,187
16.10.2018 23:08:05
14,400
13122ed6e4be78527b25ba7d3d3e1535eb0620c1
Get rid of threadInfos/userInfos from SessionChange
[ { "change_type": "MODIFY", "old_path": "lib/actions/user-actions.js", "new_path": "lib/actions/user-actions.js", "diff": "@@ -35,8 +35,6 @@ async function logOut(\n): Promise<LogOutResult> {\nconst response = await fetchJSON('log_out', {});\nreturn {\n- threadInfos: response.cookieChange.threadInfos,\n- userInfos: response.cookieChange.userInfos,\ncurrentUserInfo: response.currentUserInfo,\n};\n}\n@@ -52,8 +50,6 @@ async function deleteAccount(\n): Promise<LogOutResult> {\nconst response = await fetchJSON('delete_account', { password });\nreturn {\n- threadInfos: response.cookieChange.threadInfos,\n- userInfos: response.cookieChange.userInfos,\ncurrentUserInfo: response.currentUserInfo,\n};\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/thread-reducer.js", "new_path": "lib/reducers/thread-reducer.js", "diff": "@@ -234,8 +234,6 @@ export default function reduceThreadInfos(\naction: BaseAction,\n): ThreadStore {\nif (\n- action.type === logOutActionTypes.success ||\n- action.type === deleteAccountActionTypes.success ||\naction.type === logInActionTypes.success ||\naction.type === registerActionTypes.success ||\naction.type === resetPasswordActionTypes.success\n@@ -247,13 +245,17 @@ export default function reduceThreadInfos(\nthreadInfos: action.payload.threadInfos,\ninconsistencyResponses: state.inconsistencyResponses,\n};\n- } else if (action.type === setNewSessionActionType) {\n- const { threadInfos } = action.payload.sessionChange;\n- if (_isEqual(state.threadInfos)(threadInfos)) {\n+ } else if (\n+ action.type === logOutActionTypes.success ||\n+ action.type === deleteAccountActionTypes.success ||\n+ (action.type === setNewSessionActionType &&\n+ action.payload.sessionChange.cookieInvalidated)\n+ ) {\n+ if (Object.keys(state.threadInfos).length === 0) {\nreturn state;\n}\nreturn {\n- threadInfos,\n+ threadInfos: {},\ninconsistencyResponses: state.inconsistencyResponses,\n};\n} else if (\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/user-reducer.js", "new_path": "lib/reducers/user-reducer.js", "diff": "@@ -128,25 +128,20 @@ function reduceUserInfos(\nif (!_isEqual(state)(updated)) {\nreturn updated;\n}\n- } else if (action.type === setNewSessionActionType) {\n- const { sessionChange } = action.payload;\n- const newUserInfos = _keyBy('id')(sessionChange.userInfos);\n- if (sessionChange.cookieInvalidated) {\n- if (!_isEqual(state)(newUserInfos)) {\n- return newUserInfos;\n- }\n- } else {\n- const updated = { ...state, ...newUserInfos };\n- if (!_isEqual(state)(updated)) {\n- return updated;\n- }\n+ } else if (\n+ action.type === logOutActionTypes.success ||\n+ action.type === deleteAccountActionTypes.success ||\n+ (action.type === setNewSessionActionType &&\n+ action.payload.sessionChange.cookieInvalidated)\n+ ) {\n+ if (Object.keys(state).length === 0) {\n+ return state;\n}\n+ return {};\n} else if (\naction.type === logInActionTypes.success ||\naction.type === registerActionTypes.success ||\n- action.type === resetPasswordActionTypes.success ||\n- action.type === logOutActionTypes.success ||\n- action.type === deleteAccountActionTypes.success\n+ action.type === resetPasswordActionTypes.success\n) {\nconst newUserInfos = _keyBy('id')(action.payload.userInfos);\nif (!_isEqual(state)(newUserInfos)) {\n" }, { "change_type": "MODIFY", "old_path": "lib/types/account-types.js", "new_path": "lib/types/account-types.js", "diff": "@@ -26,8 +26,6 @@ export type ResetPasswordRequest = {|\n|};\nexport type LogOutResult = {|\n- threadInfos: {[id: string]: RawThreadInfo},\n- userInfos: $ReadOnlyArray<UserInfo>,\ncurrentUserInfo: LoggedOutUserInfo,\n|};\n@@ -58,6 +56,10 @@ export type RegisterRequest = {|\nexport type RegisterResponse = {|\nid: string,\nrawMessageInfos: $ReadOnlyArray<RawMessageInfo>,\n+ cookieChange: {\n+ threadInfos: {[id: string]: RawThreadInfo},\n+ userInfos: $ReadOnlyArray<UserInfo>,\n+ },\n|};\nexport type RegisterResult = {|\n@@ -111,6 +113,10 @@ export type LogInResponse = {|\nuserInfos: $ReadOnlyArray<UserInfo>,\nrawEntryInfos?: ?$ReadOnlyArray<RawEntryInfo>,\nserverTime: number,\n+ cookieChange: {\n+ threadInfos: {[id: string]: RawThreadInfo},\n+ userInfos: $ReadOnlyArray<UserInfo>,\n+ },\n|};\nexport type LogInResult = {|\n" }, { "change_type": "MODIFY", "old_path": "lib/types/session-types.js", "new_path": "lib/types/session-types.js", "diff": "@@ -45,7 +45,7 @@ export const cookieTypes = Object.freeze({\n});\nexport type CookieType = $Values<typeof cookieTypes>;\n-export type SessionChange = {|\n+export type ServerSessionChange = {|\ncookieInvalidated: false,\nthreadInfos: {[id: string]: RawThreadInfo},\nuserInfos: UserInfo[],\n@@ -60,8 +60,19 @@ export type SessionChange = {|\ncookie?: string,\n|};\n+export type ClientSessionChange = {|\n+ cookieInvalidated: false,\n+ sessionID?: null | string,\n+ cookie?: string,\n+|} | {|\n+ cookieInvalidated: true,\n+ currentUserInfo: LoggedOutUserInfo,\n+ sessionID?: null | string,\n+ cookie?: string,\n+|};\n+\nexport type SetSessionPayload = {|\n- sessionChange: SessionChange,\n+ sessionChange: ClientSessionChange,\nerror: ?string,\n|};\n" }, { "change_type": "MODIFY", "old_path": "lib/utils/action-utils.js", "new_path": "lib/utils/action-utils.js", "diff": "@@ -17,7 +17,7 @@ import type {\nLogInExtraInfo,\n} from '../types/account-types';\nimport type { Endpoint } from '../types/endpoints';\n-import type { SessionChange } from '../types/session-types';\n+import type { ClientSessionChange } from '../types/session-types';\nimport invariant from 'invariant';\nimport _mapValues from 'lodash/fp/mapValues';\n@@ -171,7 +171,7 @@ export type DispatchRecoveryAttempt = (\nconst setNewSessionActionType = \"SET_NEW_SESSION\";\nfunction setNewSession(\ndispatch: Dispatch,\n- sessionChange: SessionChange,\n+ sessionChange: ClientSessionChange,\nerror: ?string,\n) {\ndispatch({\n@@ -191,7 +191,7 @@ async function fetchNewCookieFromNativeCredentials(\nurlPrefix: string,\nsource: LogInActionSource,\nlogInExtraInfo: () => LogInExtraInfo,\n-): Promise<?SessionChange> {\n+): Promise<?ClientSessionChange> {\nlet newSessionChange = null;\nlet fetchJSONCallback = null;\nconst boundFetchJSON = async (\n@@ -200,7 +200,7 @@ async function fetchNewCookieFromNativeCredentials(\noptions?: ?FetchJSONOptions,\n) => {\nconst innerBoundSetNewSession = (\n- sessionChange: SessionChange,\n+ sessionChange: ClientSessionChange,\nerror: ?string,\n) => {\nnewSessionChange = sessionChange;\n@@ -211,7 +211,7 @@ async function fetchNewCookieFromNativeCredentials(\ncookie,\ninnerBoundSetNewSession,\n() => new Promise(r => r(null)),\n- (sessionChange: SessionChange) => new Promise(r => r(null)),\n+ (sessionChange: ClientSessionChange) => new Promise(r => r(null)),\nurlPrefix,\nnull,\nendpoint,\n@@ -282,7 +282,8 @@ function bindCookieAndUtilsIntoFetchJSON(\nreturn new Promise(r => fetchJSONCallsWaitingForNewCookie.push(r));\n};\n// This function is a helper for the next function defined below\n- const attemptToResolveInvalidation = async (sessionChange: SessionChange) => {\n+ const attemptToResolveInvalidation =\n+ async (sessionChange: ClientSessionChange) => {\nconst newAnonymousCookie = sessionChange.cookie;\nconst newSessionChange = await fetchNewCookieFromNativeCredentials(\ndispatch,\n@@ -314,7 +315,7 @@ function bindCookieAndUtilsIntoFetchJSON(\n// If this function is called, fetchJSON got a response invalidating its\n// cookie, and is wondering if it should just like... give up? Or if there's\n// a chance at redemption\n- const cookieInvalidationRecovery = (sessionChange: SessionChange) => {\n+ const cookieInvalidationRecovery = (sessionChange: ClientSessionChange) => {\nif (!getConfig().resolveInvalidatedCookie) {\n// If there is no resolveInvalidatedCookie function, just let the caller\n// fetchJSON instance continue\n" }, { "change_type": "MODIFY", "old_path": "lib/utils/fetch-json.js", "new_path": "lib/utils/fetch-json.js", "diff": "// @flow\nimport type { Endpoint } from '../types/endpoints';\n-import type { SessionChange } from '../types/session-types';\n+import type {\n+ ServerSessionChange,\n+ ClientSessionChange,\n+} from '../types/session-types';\nimport invariant from 'invariant';\nimport _map from 'lodash/fp/map';\n@@ -42,10 +45,10 @@ type RequestData = {|\n// (indicating we don't have one), and we will then set an empty Cookie header.\nasync function fetchJSON(\ncookie: ?string,\n- setNewSession: (sessionChange: SessionChange, error: ?string) => void,\n+ setNewSession: (sessionChange: ClientSessionChange, error: ?string) => void,\nwaitIfCookieInvalidated: () => Promise<?FetchJSON>,\ncookieInvalidationRecovery:\n- (sessionChange: SessionChange) => Promise<?FetchJSON>,\n+ (sessionChange: ClientSessionChange) => Promise<?FetchJSON>,\nurlPrefix: string,\nsessionID: ?string,\nendpoint: Endpoint,\n@@ -104,15 +107,19 @@ async function fetchJSON(\nthrow e;\n}\n- const { cookieChange: sessionChange, error, payload } = json;\n+ const { cookieChange, error, payload } = json;\n+ const sessionChange: ServerSessionChange = cookieChange;\nif (sessionChange) {\n- if (sessionChange.cookieInvalidated) {\n- const maybeReplacement = await cookieInvalidationRecovery(sessionChange);\n+ const { threadInfos, userInfos, ...rest } = sessionChange;\n+ if (rest.cookieInvalidated) {\n+ const maybeReplacement = await cookieInvalidationRecovery(rest);\nif (maybeReplacement) {\nreturn await maybeReplacement(endpoint, input, options);\n}\n+ setNewSession(rest, error);\n+ } else {\n+ setNewSession(rest, error);\n}\n- setNewSession(sessionChange, error);\n}\nif (error) {\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/account-creator.js", "new_path": "server/src/creators/account-creator.js", "diff": "@@ -15,6 +15,7 @@ import {\nvalidEmailRegex,\n} from 'lib/shared/account-regexes';\nimport { ServerError } from 'lib/utils/errors';\n+import { values } from 'lib/utils/objects';\nimport ashoat from 'lib/facts/ashoat';\nimport { dbQuery, SQL } from '../database';\n@@ -26,6 +27,7 @@ import createMessages from './message-creator';\nimport createThread from './thread-creator';\nimport { verifyCalendarQueryThreadIDs } from '../responders/entry-responders';\nimport { setNewSession } from '../session/cookies';\n+import { fetchThreadInfos } from '../fetchers/thread-fetchers';\nconst ashoatMessages = [\n\"welcome to SquadCal! thanks for helping to test the alpha.\",\n@@ -141,7 +143,14 @@ async function createAccount(\n...ashoatMessageInfos,\n];\n- return { id, rawMessageInfos };\n+ const threadsResult = await fetchThreadInfos(viewer);\n+ const userInfos = values({ ...threadsResult.userInfos });\n+\n+ return {\n+ id,\n+ rawMessageInfos,\n+ cookieChange: { threadInfos: threadsResult.threadInfos, userInfos },\n+ };\n}\nexport default createAccount;\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/handlers.js", "new_path": "server/src/responders/handlers.js", "diff": "@@ -33,7 +33,7 @@ function jsonHandler(responder: JSONResponder) {\nreturn;\n}\nconst result = { ...responderResult };\n- await addCookieToJSONResponse(viewer, res, result);\n+ addCookieToJSONResponse(viewer, res, result);\nres.json({ success: true, ...result });\n} catch (e) {\nawait handleException(e, res, viewer);\n@@ -89,7 +89,7 @@ async function handleException(\nviewer.cookieInvalidated = true;\n}\n// This can mutate the result object\n- await addCookieToJSONResponse(viewer, res, result);\n+ addCookieToJSONResponse(viewer, res, result);\n}\nres.json(result);\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/user-responders.js", "new_path": "server/src/responders/user-responders.js", "diff": "@@ -61,6 +61,7 @@ import { fetchMessageInfos } from '../fetchers/message-fetchers';\nimport { fetchEntryInfos } from '../fetchers/entry-fetchers';\nimport { sendAccessRequestEmailToAshoat } from '../emails/access-request';\nimport { setNewSession } from '../session/cookies';\n+import { fetchThreadInfos } from '../fetchers/thread-fetchers';\nconst subscriptionUpdateRequestInputValidator = tShape({\nthreadID: t.String,\n@@ -257,7 +258,8 @@ async function logInResponder(\n}\nconst threadSelectionCriteria = { threadCursors, joinedThreads: true };\n- const [ messagesResult, entriesResult ] = await Promise.all([\n+ const [ threadsResult, messagesResult, entriesResult ] = await Promise.all([\n+ fetchThreadInfos(viewer),\nfetchMessageInfos(\nviewer,\nthreadSelectionCriteria,\n@@ -267,9 +269,12 @@ async function logInResponder(\n]);\nconst rawEntryInfos = entriesResult ? entriesResult.rawEntryInfos : null;\n- const userInfos = entriesResult\n- ? { ...messagesResult.userInfos, ...entriesResult.userInfos }\n- : messagesResult.userInfos;\n+ const entryUserInfos = entriesResult ? entriesResult.userInfos : {};\n+ const userInfos = values({\n+ ...threadsResult.userInfos,\n+ ...messagesResult.userInfos,\n+ ...entryUserInfos,\n+ });\nconst response: LogInResponse = {\ncurrentUserInfo: {\nid,\n@@ -280,7 +285,11 @@ async function logInResponder(\nrawMessageInfos: messagesResult.rawMessageInfos,\ntruncationStatuses: messagesResult.truncationStatuses,\nserverTime: newPingTime,\n- userInfos: values(userInfos),\n+ userInfos,\n+ cookieChange: {\n+ threadInfos: threadsResult.threadInfos,\n+ userInfos: [],\n+ },\n};\nif (rawEntryInfos) {\nresponse.rawEntryInfos = rawEntryInfos;\n" }, { "change_type": "MODIFY", "old_path": "server/src/session/cookies.js", "new_path": "server/src/session/cookies.js", "diff": "import type { $Response, $Request } from 'express';\nimport type { ViewerData, AnonymousViewerData, UserViewerData } from './viewer';\nimport {\n- type SessionChange,\n+ type ServerSessionChange,\ncookieLifetime,\ncookieSources,\ntype CookieSource,\n@@ -30,7 +30,6 @@ import { promiseAll } from 'lib/utils/promises';\nimport { dbQuery, SQL } from '../database';\nimport { Viewer } from './viewer';\n-import { fetchThreadInfos } from '../fetchers/thread-fetchers';\nimport urlFacts from '../../facts/url';\nimport createIDs from '../creators/id-creator';\nimport { assertSecureRequest } from '../utils/security-utils';\n@@ -493,12 +492,15 @@ function createViewerForInvalidFetchViewerResult(\n}\nconst domainAsURL = new url.URL(baseDomain);\n-async function addSessionChangeInfoToResult(\n+function addSessionChangeInfoToResult(\nviewer: Viewer,\nres: $Response,\nresult: Object,\n) {\n- const { threadInfos, userInfos } = await fetchThreadInfos(viewer);\n+ let threadInfos = {}, userInfos = {};\n+ if (result.cookieChange) {\n+ ({ threadInfos, userInfos } = result.cookieChange);\n+ }\nlet sessionChange;\nif (viewer.cookieInvalidated) {\nsessionChange = ({\n@@ -509,13 +511,13 @@ async function addSessionChangeInfoToResult(\nid: viewer.cookieID,\nanonymous: true,\n},\n- }: SessionChange);\n+ }: ServerSessionChange);\n} else {\nsessionChange = ({\ncookieInvalidated: false,\nthreadInfos,\nuserInfos: (values(userInfos).map(a => a): UserInfo[]),\n- }: SessionChange);\n+ }: ServerSessionChange);\n}\nif (viewer.cookieSource === cookieSources.BODY) {\nsessionChange.cookie = viewer.cookiePairString;\n@@ -670,7 +672,7 @@ async function extendCookieLifespan(cookieID: string) {\nawait dbQuery(query);\n}\n-async function addCookieToJSONResponse(\n+function addCookieToJSONResponse(\nviewer: Viewer,\nres: $Response,\nresult: Object,\n@@ -679,7 +681,7 @@ async function addCookieToJSONResponse(\nhandleAsyncPromise(extendCookieLifespan(viewer.cookieID));\n}\nif (viewer.sessionChanged) {\n- await addSessionChangeInfoToResult(viewer, res, result);\n+ addSessionChangeInfoToResult(viewer, res, result);\n} else if (viewer.cookieSource !== cookieSources.BODY) {\naddActualHTTPCookie(viewer, res);\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/account-updaters.js", "new_path": "server/src/updaters/account-updaters.js", "diff": "@@ -29,6 +29,7 @@ import { fetchLoggedInUserInfos } from '../fetchers/user-fetchers';\nimport { verifyCalendarQueryThreadIDs } from '../responders/entry-responders';\nimport { setNewSession } from '../session/cookies';\nimport { createUpdates } from '../creators/update-creator';\n+import { fetchThreadInfos } from '../fetchers/thread-fetchers';\nasync function accountUpdater(\nviewer: Viewer,\n@@ -224,7 +225,8 @@ async function updatePassword(\n}\nconst threadSelectionCriteria = { threadCursors, joinedThreads: true };\n- const [ messagesResult, entriesResult ] = await Promise.all([\n+ const [ threadsResult, messagesResult, entriesResult ] = await Promise.all([\n+ fetchThreadInfos(viewer),\nfetchMessageInfos(\nviewer,\nthreadSelectionCriteria,\n@@ -234,9 +236,12 @@ async function updatePassword(\n]);\nconst rawEntryInfos = entriesResult ? entriesResult.rawEntryInfos : null;\n- const userInfos = entriesResult\n- ? { ...messagesResult.userInfos, ...entriesResult.userInfos }\n- : messagesResult.userInfos;\n+ const entryUserInfos = entriesResult ? entriesResult.userInfos : {};\n+ const userInfos = values({\n+ ...threadsResult.userInfos,\n+ ...messagesResult.userInfos,\n+ ...entryUserInfos,\n+ });\nconst response: LogInResponse = {\ncurrentUserInfo: {\nid: userID,\n@@ -247,7 +252,11 @@ async function updatePassword(\nrawMessageInfos: messagesResult.rawMessageInfos,\ntruncationStatuses: messagesResult.truncationStatuses,\nserverTime: newPingTime,\n- userInfos: values(userInfos),\n+ userInfos,\n+ cookieChange: {\n+ threadInfos: threadsResult.threadInfos,\n+ userInfos: [],\n+ },\n};\nif (rawEntryInfos) {\nresponse.rawEntryInfos = rawEntryInfos;\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Get rid of threadInfos/userInfos from SessionChange
129,187
17.10.2018 13:28:24
14,400
e993ac2b21b438a7d9eebfb0e467e5d65ab83d26
Client WebSocket initialization logic
[ { "change_type": "MODIFY", "old_path": "lib/actions/user-actions.js", "new_path": "lib/actions/user-actions.js", "diff": "@@ -100,6 +100,8 @@ const appStartNativeCredentialsAutoLogIn =\n\"APP_START_NATIVE_CREDENTIALS_AUTO_LOG_IN\";\nconst appStartReduxLoggedInButInvalidCookie =\n\"APP_START_REDUX_LOGGED_IN_BUT_INVALID_COOKIE\";\n+const socketAuthErrorResolutionAttempt =\n+ \"SOCKET_AUTH_ERROR_RESOLUTION_ATTEMPT\";\nconst logInActionTypes = Object.freeze({\nstarted: \"LOG_IN_STARTED\",\n@@ -290,6 +292,7 @@ export {\ncookieInvalidationResolutionAttempt,\nappStartNativeCredentialsAutoLogIn,\nappStartReduxLoggedInButInvalidCookie,\n+ socketAuthErrorResolutionAttempt,\nlogInActionTypes,\nlogIn,\nresetPasswordActionTypes,\n" }, { "change_type": "MODIFY", "old_path": "lib/components/socket.react.js", "new_path": "lib/components/socket.react.js", "diff": "@@ -13,14 +13,28 @@ import {\nimport {\nclientSocketMessageTypes,\ntype ClientSocketMessage,\n+ serverSocketMessageTypes,\n+ type ServerSocketMessage,\n+ stateSyncPayloadTypes,\n} from '../types/socket-types';\n+import type { Dispatch } from '../types/redux-types';\n+import type { DispatchActionPayload } from '../utils/action-utils';\n+import type { LogInExtraInfo } from '../types/account-types';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport invariant from 'invariant';\nimport { getConfig } from '../utils/config';\n-import { registerActiveWebSocket } from '../utils/action-utils';\n+import {\n+ registerActiveWebSocket,\n+ setNewSessionActionType,\n+ fetchNewCookieFromNativeCredentials,\n+} from '../utils/action-utils';\n+import { socketAuthErrorResolutionAttempt } from '../actions/user-actions';\n+\n+const fullStateSyncActionPayload = \"FULL_STATE_SYNC\";\n+const incrementalStateSyncActionPayload = \"INCREMENTAL_STATE_SYNC\";\ntype Props = {|\nactive: bool,\n@@ -30,6 +44,12 @@ type Props = {|\nactiveThread: ?string,\nsessionStateFunc: () => SessionState,\nsessionIdentification: SessionIdentification,\n+ cookie: ?string,\n+ urlPrefix: string,\n+ logInExtraInfo: () => LogInExtraInfo,\n+ // Redux dispatch functions\n+ dispatch: Dispatch,\n+ dispatchActionPayload: DispatchActionPayload,\n|};\nclass Socket extends React.PureComponent<Props> {\n@@ -40,6 +60,11 @@ class Socket extends React.PureComponent<Props> {\nactiveThread: PropTypes.string,\nsessionStateFunc: PropTypes.func.isRequired,\nsessionIdentification: sessionIdentificationPropType.isRequired,\n+ cookie: PropTypes.string,\n+ urlPrefix: PropTypes.string.isRequired,\n+ logInExtraInfo: PropTypes.func.isRequired,\n+ dispatch: PropTypes.func.isRequired,\n+ dispatchActionPayload: PropTypes.func.isRequired,\n};\nsocket: ?WebSocket;\ninitialPlatformDetailsSent = false;\n@@ -54,15 +79,17 @@ class Socket extends React.PureComponent<Props> {\nsocket.onmessage = this.receiveMessage;\nsocket.onclose = this.onClose;\nthis.socket = socket;\n- registerActiveWebSocket(socket);\n}\ncloseSocket() {\n+ registerActiveWebSocket(null);\nif (this.socket) {\n+ if (this.socket.readyState < 2) {\n+ // If it's not closing already, close it\nthis.socket.close();\n+ }\nthis.socket = null;\n}\n- registerActiveWebSocket(null);\n}\ncomponentDidMount() {\n@@ -103,15 +130,86 @@ class Socket extends React.PureComponent<Props> {\nsocket.send(JSON.stringify(message));\n}\n- receiveMessage = (event: MessageEvent) => {\n+ messageFromEvent(event: MessageEvent): ?ServerSocketMessage {\nif (typeof event.data !== \"string\") {\n+ console.warn('socket received a non-string message');\n+ return null;\n+ }\n+ try {\n+ return JSON.parse(event.data);\n+ } catch (e) {\n+ console.warn(e);\n+ return null;\n+ }\n+ }\n+\n+ receiveMessage = async (event: MessageEvent) => {\n+ const message = this.messageFromEvent(event);\n+ if (!message) {\nreturn;\n}\n- console.log('message', JSON.parse(event.data));\n+ if (message.type === serverSocketMessageTypes.STATE_SYNC) {\n+ if (message.payload.type === stateSyncPayloadTypes.FULL) {\n+ const { sessionID, type, ...actionPayload } = message.payload;\n+ this.props.dispatchActionPayload(\n+ fullStateSyncActionPayload,\n+ actionPayload,\n+ );\n+ if (sessionID !== null && sessionID !== undefined) {\n+ this.props.dispatchActionPayload(\n+ setNewSessionActionType,\n+ {\n+ sessionChange: { cookieInvalidated: false, sessionID },\n+ error: null,\n+ },\n+ );\n+ }\n+ } else {\n+ const { type, ...actionPayload } = message.payload;\n+ this.props.dispatchActionPayload(\n+ incrementalStateSyncActionPayload,\n+ actionPayload,\n+ );\n+ }\n+ // Once we receive the STATE_SYNC, the socket is ready for use\n+ registerActiveWebSocket(this.socket);\n+ } else if (message.type === serverSocketMessageTypes.REQUESTS) {\n+ } else if (message.type === serverSocketMessageTypes.ERROR) {\n+ const { message: errorMessage, payload } = message;\n+ if (payload) {\n+ console.warn(`socket sent error ${errorMessage} with payload`, payload);\n+ } else {\n+ console.warn(`socket sent error ${errorMessage}`);\n+ }\n+ } else if (message.type === serverSocketMessageTypes.AUTH_ERROR) {\n+ const { sessionChange } = message;\n+ const cookie = sessionChange ? sessionChange.cookie : this.props.cookie;\n+\n+ const recoverySessionChange = await fetchNewCookieFromNativeCredentials(\n+ this.props.dispatch,\n+ cookie,\n+ this.props.urlPrefix,\n+ socketAuthErrorResolutionAttempt,\n+ this.props.logInExtraInfo,\n+ );\n+\n+ if (!recoverySessionChange && sessionChange) {\n+ // This should only happen in the cookieSources.BODY (native) case when\n+ // the resolution attempt failed\n+ const { cookie, currentUserInfo } = sessionChange;\n+ this.props.dispatchActionPayload(\n+ setNewSessionActionType,\n+ {\n+ sessionChange: { cookieInvalidated: true, currentUserInfo, cookie },\n+ error: null,\n+ },\n+ );\n+ }\n+ }\n}\nonClose = (event: CloseEvent) => {\n- console.log('close', event);\n+ this.closeSocket();\n}\nsendInitialMessage = () => {\n" }, { "change_type": "MODIFY", "old_path": "lib/types/account-types.js", "new_path": "lib/types/account-types.js", "diff": "@@ -80,7 +80,8 @@ export type ChangeUserSettingsResult = {|\nexport type LogInActionSource =\n| \"COOKIE_INVALIDATION_RESOLUTION_ATTEMPT\"\n| \"APP_START_NATIVE_CREDENTIALS_AUTO_LOG_IN\"\n- | \"APP_START_REDUX_LOGGED_IN_BUT_INVALID_COOKIE\";\n+ | \"APP_START_REDUX_LOGGED_IN_BUT_INVALID_COOKIE\"\n+ | \"SOCKET_AUTH_ERROR_RESOLUTION_ATTEMPT\";\nexport type LogInStartingPayload = {|\ncalendarQuery: CalendarQuery,\nsource?: LogInActionSource,\n" }, { "change_type": "MODIFY", "old_path": "lib/types/redux-types.js", "new_path": "lib/types/redux-types.js", "diff": "@@ -54,7 +54,11 @@ import type {\nSetCalendarDeletedFilterPayload,\n} from './filter-types';\nimport type { SubscriptionUpdateResult } from '../types/subscription-types';\n-import type { ConnectionInfo } from '../types/socket-types';\n+import type {\n+ ConnectionInfo,\n+ StateSyncFullActionPayload,\n+ StateSyncIncrementalActionPayload,\n+} from '../types/socket-types';\nexport type BaseAppState<NavInfo: BaseNavInfo> = {\nnavInfo: NavInfo,\n@@ -533,6 +537,12 @@ export type BaseAction =\ntype: \"UPDATE_CALENDAR_QUERY_SUCCESS\",\npayload: CalendarQueryUpdateResult,\nloadingInfo: LoadingInfo,\n+ |} | {|\n+ type: \"FULL_STATE_SYNC\",\n+ payload: StateSyncFullActionPayload,\n+ |} | {|\n+ type: \"INCREMENTAL_STATE_SYNC\",\n+ payload: StateSyncIncrementalActionPayload,\n|};\nexport type ActionPayload\n" }, { "change_type": "MODIFY", "old_path": "lib/types/socket-types.js", "new_path": "lib/types/socket-types.js", "diff": "@@ -65,31 +65,37 @@ export type ClientSocketMessage =\n| InitialClientSocketMessage;\nexport const stateSyncPayloadTypes = pingResponseTypes;\n-export type StateSyncFullPayload = {|\n- type: 0,\n+export type StateSyncFullActionPayload = {|\nmessagesResult: MessagesPingResponse,\nthreadInfos: {[id: string]: RawThreadInfo},\ncurrentUserInfo: CurrentUserInfo,\nrawEntryInfos: $ReadOnlyArray<RawEntryInfo>,\nuserInfos: $ReadOnlyArray<UserInfo>,\n+|};\n+export type StateSyncFullSocketPayload = {|\n+ ...StateSyncFullActionPayload,\n+ type: 0,\n// Included iff client is using sessionIdentifierTypes.BODY_SESSION_ID\nsessionID?: string,\n|};\n-type StateSyncIncrementalPayload = {|\n- type: 1,\n+export type StateSyncIncrementalActionPayload = {|\nmessagesResult: MessagesPingResponse,\nupdatesResult: UpdatesResult,\ndeltaEntryInfos: $ReadOnlyArray<RawEntryInfo>,\nuserInfos: $ReadOnlyArray<UserInfo>,\n|};\n-export type StateSyncPayload =\n- | StateSyncFullPayload\n- | StateSyncIncrementalPayload;\n+type StateSyncIncrementalSocketPayload = {|\n+ type: 1,\n+ ...StateSyncIncrementalActionPayload,\n+|};\n+export type StateSyncSocketPayload =\n+ | StateSyncFullSocketPayload\n+ | StateSyncIncrementalSocketPayload;\nexport type StateSyncServerSocketMessage = {|\ntype: 0,\nresponseTo: number,\n- payload: StateSyncPayload,\n+ payload: StateSyncSocketPayload,\n|};\nexport type RequestsServerSocketMessage = {|\ntype: 1,\n@@ -109,7 +115,10 @@ export type AuthErrorServerSocketMessage = {|\nmessage: string,\n// If unspecified, it is because the client is using cookieSources.HEADER,\n// which means the server can't update the cookie from a socket message.\n- currentUserInfo?: LoggedOutUserInfo,\n+ sessionChange?: {\n+ cookie: string,\n+ currentUserInfo: LoggedOutUserInfo,\n+ },\n|};\nexport type ServerSocketMessage =\n| StateSyncServerSocketMessage\n" }, { "change_type": "MODIFY", "old_path": "lib/utils/fetch-json.js", "new_path": "lib/utils/fetch-json.js", "diff": "@@ -108,7 +108,7 @@ async function fetchJSON(\n}\nconst { cookieChange, error, payload } = json;\n- const sessionChange: ServerSessionChange = cookieChange;\n+ const sessionChange: ?ServerSessionChange = cookieChange;\nif (sessionChange) {\nconst { threadInfos, userInfos, ...rest } = sessionChange;\nif (rest.cookieInvalidated) {\n@@ -116,10 +116,8 @@ async function fetchJSON(\nif (maybeReplacement) {\nreturn await maybeReplacement(endpoint, input, options);\n}\n- setNewSession(rest, error);\n- } else {\n- setNewSession(rest, error);\n}\n+ setNewSession(rest, error);\n}\nif (error) {\n" }, { "change_type": "MODIFY", "old_path": "native/selectors/socket-selectors.js", "new_path": "native/selectors/socket-selectors.js", "diff": "@@ -9,6 +9,12 @@ import { createOpenSocketFunction } from 'lib/shared/socket-utils';\nconst openSocketSelector = createSelector(\n(state: AppState) => state.urlPrefix,\n+ // We don't actually use the cookie in the socket open function, but we do use\n+ // it in the initial message, and when the cookie changes the socket needs to\n+ // be reopened. By including the cookie here, whenever the cookie changes this\n+ // function will change, which tells the Socket component to restart the\n+ // connection.\n+ (state: AppState) => state.cookie,\ncreateOpenSocketFunction,\n);\n" }, { "change_type": "MODIFY", "old_path": "native/socket.react.js", "new_path": "native/socket.react.js", "diff": "@@ -7,6 +7,7 @@ import {\nclientResponsesSelector,\nsessionStateFuncSelector,\n} from 'lib/selectors/socket-selectors';\n+import { logInExtraInfoSelector } from 'lib/selectors/account-selectors';\nimport Socket from 'lib/components/socket.react';\nimport {\n@@ -15,10 +16,17 @@ import {\n} from './selectors/socket-selectors';\nimport { activeThreadSelector } from './selectors/nav-selectors';\n-export default connect((state: AppState) => ({\n+export default connect(\n+ (state: AppState) => ({\nopenSocket: openSocketSelector(state),\nclientResponses: clientResponsesSelector(state),\nactiveThread: activeThreadSelector(state),\nsessionStateFunc: sessionStateFuncSelector(state),\nsessionIdentification: sessionIdentificationSelector(state),\n-}))(Socket);\n+ cookie: state.cookie,\n+ urlPrefix: state.urlPrefix,\n+ logInExtraInfo: logInExtraInfoSelector(state),\n+ }),\n+ null,\n+ true,\n+)(Socket);\n" }, { "change_type": "MODIFY", "old_path": "server/src/socket.js", "new_path": "server/src/socket.js", "diff": "@@ -5,7 +5,7 @@ import type { $Request } from 'express';\nimport {\ntype ClientSocketMessage,\ntype InitialClientSocketMessage,\n- type StateSyncFullPayload,\n+ type StateSyncFullSocketPayload,\ntype ServerSocketMessage,\ntype ErrorServerSocketMessage,\ntype AuthErrorServerSocketMessage,\n@@ -14,7 +14,6 @@ import {\nserverSocketMessageTypes,\n} from 'lib/types/socket-types';\nimport { cookieSources } from 'lib/types/session-types';\n-import type { Viewer } from './session/viewer';\nimport { defaultNumberPerThread } from 'lib/types/message-types';\nimport t from 'tcomb';\n@@ -26,6 +25,7 @@ import { mostRecentUpdateTimestamp } from 'lib/shared/update-utils';\nimport { promiseAll } from 'lib/utils/promises';\nimport { values } from 'lib/utils/objects';\n+import { Viewer } from './session/viewer';\nimport {\ncheckInputValidator,\ncheckClientSupported,\n@@ -165,9 +165,12 @@ function onConnection(ws: WebSocket, req: $Request) {\n// clients. Usually if the cookie is invalid we construct a new\n// anonymous Viewer with a new cookie, and then pass the cookie down\n// in the error. But we can't pass HTTP cookies in WebSocket messages.\n- authErrorMessage.currentUserInfo = {\n+ authErrorMessage.sessionChange = {\n+ cookie: viewer.cookiePairString,\n+ currentUserInfo: {\nid: viewer.cookieID,\nanonymous: true,\n+ },\n};\n}\nsendMessage(authErrorMessage);\n@@ -190,9 +193,13 @@ function onConnection(ws: WebSocket, req: $Request) {\nmessage: error.message,\n}\nif (anonymousViewerData) {\n- authErrorMessage.currentUserInfo = {\n- id: anonymousViewerData.cookieID,\n+ const anonViewer = new Viewer(anonymousViewerData);\n+ authErrorMessage.sessionChange = {\n+ cookie: anonViewer.cookiePairString,\n+ currentUserInfo: {\n+ id: anonViewer.cookieID,\nanonymous: true,\n+ },\n};\n}\nsendMessage(authErrorMessage);\n@@ -286,7 +293,7 @@ async function handleInitialClientSocketMessage(\nfetchEntryInfos(viewer, [ calendarQuery ]),\nfetchCurrentUserInfo(viewer),\n]);\n- const payload: StateSyncFullPayload = {\n+ const payload: StateSyncFullSocketPayload = {\ntype: stateSyncPayloadTypes.FULL,\nmessagesResult,\nthreadInfos: threadsResult.threadInfos,\n" }, { "change_type": "MODIFY", "old_path": "web/socket.react.js", "new_path": "web/socket.react.js", "diff": "@@ -7,6 +7,7 @@ import {\nclientResponsesSelector,\nsessionStateFuncSelector,\n} from 'lib/selectors/socket-selectors';\n+import { logInExtraInfoSelector } from 'lib/selectors/account-selectors';\nimport Socket from 'lib/components/socket.react';\nimport {\n@@ -15,10 +16,17 @@ import {\n} from './selectors/socket-selectors';\nimport { activeThreadSelector } from './selectors/nav-selectors';\n-export default connect((state: AppState) => ({\n+export default connect(\n+ (state: AppState) => ({\nopenSocket: openSocketSelector(state),\nclientResponses: clientResponsesSelector(state),\nactiveThread: activeThreadSelector(state),\nsessionStateFunc: sessionStateFuncSelector(state),\nsessionIdentification: sessionIdentificationSelector(state),\n-}))(Socket);\n+ cookie: state.cookie,\n+ urlPrefix: state.urlPrefix,\n+ logInExtraInfo: logInExtraInfoSelector(state),\n+ }),\n+ null,\n+ true,\n+)(Socket);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Client WebSocket initialization logic
129,187
17.10.2018 23:43:42
14,400
b258f145183d3993c026078ebdee66533315df75
[server] Mutate Viewer to incorporate updated session/cookie data `sessionInfo`, `deviceToken`, and `platformDetails`
[ { "change_type": "MODIFY", "old_path": "server/src/responders/ping-responders.js", "new_path": "server/src/responders/ping-responders.js", "diff": "@@ -391,7 +391,7 @@ async function processClientResponses(\n!clientSentPlatformDetails\n) {\npromises.push(setCookiePlatform(\n- viewer.cookieID,\n+ viewer,\nclientResponse.platform,\n));\nviewerMissingPlatform = false;\n@@ -423,7 +423,7 @@ async function processClientResponses(\n));\n} else if (clientResponse.type === serverRequestTypes.PLATFORM_DETAILS) {\npromises.push(setCookiePlatformDetails(\n- viewer.cookieID,\n+ viewer,\nclientResponse.platformDetails,\n));\nviewerMissingPlatform = false;\n" }, { "change_type": "MODIFY", "old_path": "server/src/session/cookies.js", "new_path": "server/src/session/cookies.js", "diff": "@@ -713,21 +713,24 @@ function addActualHTTPCookie(viewer: Viewer, res: $Response) {\n}\nasync function setCookiePlatform(\n- cookieID: string,\n+ viewer: Viewer,\nplatform: Platform,\n): Promise<void> {\n+ const newPlatformDetails = { ...viewer.platformDetails, platform };\n+ viewer.setPlatformDetails(newPlatformDetails);\nconst query = SQL`\nUPDATE cookies\nSET platform = ${platform}\n- WHERE id = ${cookieID}\n+ WHERE id = ${viewer.cookieID}\n`;\nawait dbQuery(query);\n}\nasync function setCookiePlatformDetails(\n- cookieID: string,\n+ viewer: Viewer,\nplatformDetails: PlatformDetails,\n): Promise<void> {\n+ viewer.setPlatformDetails(platformDetails);\nconst { platform, ...versions } = platformDetails;\nconst versionsString = Object.keys(versions).length > 0\n? JSON.stringify(versions)\n@@ -735,7 +738,7 @@ async function setCookiePlatformDetails(\nconst query = SQL`\nUPDATE cookies\nSET platform = ${platform}, versions = ${versionsString}\n- WHERE id = ${cookieID}\n+ WHERE id = ${viewer.cookieID}\n`;\nawait dbQuery(query);\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/session/viewer.js", "new_path": "server/src/session/viewer.js", "diff": "@@ -124,6 +124,24 @@ class Viewer {\n}\n}\n+ setDeviceToken(deviceToken: string) {\n+ if (this.data.loggedIn) {\n+ this.data = { ...this.data, deviceToken };\n+ } else {\n+ // This is a separate condition because of Flow\n+ this.data = { ...this.data, deviceToken };\n+ }\n+ }\n+\n+ setPlatformDetails(platformDetails: PlatformDetails) {\n+ if (this.data.loggedIn) {\n+ this.data = { ...this.data, platformDetails };\n+ } else {\n+ // This is a separate condition because of Flow\n+ this.data = { ...this.data, platformDetails };\n+ }\n+ }\n+\nget id(): string {\nreturn this.data.id;\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/device-token-updaters.js", "new_path": "server/src/updaters/device-token-updaters.js", "diff": "@@ -9,6 +9,7 @@ async function deviceTokenUpdater(\nviewer: Viewer,\nupdate: DeviceTokenUpdateRequest,\n): Promise<void> {\n+ viewer.setDeviceToken(update.deviceToken);\nawait clearDeviceToken(update.deviceToken);\nconst query = SQL`\nUPDATE cookies\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/session-updaters.js", "new_path": "server/src/updaters/session-updaters.js", "diff": "@@ -29,6 +29,15 @@ async function commitSessionUpdate(\nreturn;\n}\n+ viewer.setSessionInfo({\n+ lastValidated: sessionUpdate.lastValidated\n+ ? sessionUpdate.lastValidated\n+ : viewer.sessionLastValidated,\n+ calendarQuery: sessionUpdate.query\n+ ? sessionUpdate.query\n+ : viewer.calendarQuery,\n+ });\n+\nconst query = SQL`\nUPDATE sessions\nSET ${sqlUpdate}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Mutate Viewer to incorporate updated session/cookie data `sessionInfo`, `deviceToken`, and `platformDetails`
129,187
18.10.2018 01:34:58
14,400
c5d5fb9ac9985518fc5c799fddc120cbc07f9288
[lib] Reducer support for processServerRequestsActionType
[ { "change_type": "MODIFY", "old_path": "lib/reducers/entry-reducer.js", "new_path": "lib/reducers/entry-reducer.js", "diff": "@@ -11,8 +11,10 @@ import { type RawThreadInfo } from '../types/thread-types';\nimport { updateTypes, type UpdateInfo } from '../types/update-types';\nimport {\ntype EntryInconsistencyClientResponse,\n+ type ServerRequest,\nserverRequestTypes,\nclearDeliveredClientResponsesActionType,\n+ processServerRequestsActionType,\n} from '../types/request-types';\nimport { pingResponseTypes } from '../types/ping-types';\n@@ -633,35 +635,18 @@ function reduceEntryInfos(\ndeltaEntryInfos,\nupdatesResult.newUpdates,\n);\n- const updateResult = mergeNewEntryInfos(\n+ ({\n+ updatedEntryInfos,\n+ updatedDaysToEntries,\n+ newInconsistencies,\n+ } = handleCheckStateServerRequests(\nentryInfos,\n+ action,\nupdateEntryInfos,\nnewThreadInfos,\n- );\n- const checkStateRequest = payload.requests.serverRequests.find(\n- candidate => candidate.type === serverRequestTypes.CHECK_STATE,\n- );\n- if (\n- !checkStateRequest ||\n- !checkStateRequest.stateChanges ||\n- !checkStateRequest.stateChanges.rawEntryInfos\n- ) {\n- [ updatedEntryInfos, updatedDaysToEntries ] = updateResult;\n- } else {\n- const { rawEntryInfos } = checkStateRequest.stateChanges;\n- [ updatedEntryInfos, updatedDaysToEntries ] = mergeNewEntryInfos(\n- entryInfos,\n- [ ...updateEntryInfos, ...rawEntryInfos ],\n- newThreadInfos,\n- );\n- newInconsistencies = findInconsistencies(\n- entryInfos,\n- action,\n- updateResult[0],\n- updatedEntryInfos,\n+ payload.requests.serverRequests,\ncalendarQuery,\n- );\n- }\n+ ));\n}\nreturn {\n@@ -735,6 +720,29 @@ function reduceEntryInfos(\nlastUserInteractionCalendar,\ninconsistencyResponses: updatedResponses,\n};\n+ } else if (action.type === processServerRequestsActionType) {\n+ const {\n+ updatedEntryInfos,\n+ updatedDaysToEntries,\n+ newInconsistencies,\n+ } = handleCheckStateServerRequests(\n+ entryInfos,\n+ action,\n+ [],\n+ newThreadInfos,\n+ action.payload.serverRequests,\n+ actualizedCalendarQuery,\n+ );\n+ return {\n+ entryInfos: updatedEntryInfos,\n+ daysToEntries: updatedDaysToEntries,\n+ actualizedCalendarQuery,\n+ lastUserInteractionCalendar,\n+ inconsistencyResponses: [\n+ ...inconsistencyResponses,\n+ ...newInconsistencies,\n+ ],\n+ };\n}\nreturn entryStore;\n}\n@@ -766,6 +774,56 @@ function mergeUpdateEntryInfos(\nreturn mergedEntryInfos;\n}\n+type HandleCheckStateServerRequestsResult = {|\n+ updatedEntryInfos: {[id: string]: RawEntryInfo},\n+ updatedDaysToEntries: {[day: string]: string[]},\n+ newInconsistencies: EntryInconsistencyClientResponse[],\n+|};\n+function handleCheckStateServerRequests(\n+ beforeAction: {[id: string]: RawEntryInfo},\n+ action: BaseAction,\n+ baseEntryInfos: $ReadOnlyArray<RawEntryInfo>,\n+ newThreadInfos: {[id: string]: RawThreadInfo},\n+ serverRequests: $ReadOnlyArray<ServerRequest>,\n+ calendarQuery: CalendarQuery,\n+): HandleCheckStateServerRequestsResult {\n+ const updateResult = mergeNewEntryInfos(\n+ beforeAction,\n+ baseEntryInfos,\n+ newThreadInfos,\n+ );\n+\n+ const checkStateRequest = serverRequests.find(\n+ candidate => candidate.type === serverRequestTypes.CHECK_STATE,\n+ );\n+ if (\n+ !checkStateRequest ||\n+ !checkStateRequest.stateChanges ||\n+ !checkStateRequest.stateChanges.rawEntryInfos\n+ ) {\n+ return {\n+ updatedEntryInfos: updateResult[0],\n+ updatedDaysToEntries: updateResult[1],\n+ newInconsistencies: [],\n+ };\n+ }\n+\n+ const { rawEntryInfos } = checkStateRequest.stateChanges;\n+ const [ updatedEntryInfos, updatedDaysToEntries ] = mergeNewEntryInfos(\n+ beforeAction,\n+ [ ...baseEntryInfos, ...rawEntryInfos ],\n+ newThreadInfos,\n+ );\n+ const newInconsistencies = findInconsistencies(\n+ beforeAction,\n+ action,\n+ updateResult[0],\n+ updatedEntryInfos,\n+ calendarQuery,\n+ );\n+ return { updatedEntryInfos, updatedDaysToEntries, newInconsistencies };\n+}\n+\nconst emptyArray = [];\nfunction findInconsistencies(\nbeforeAction: {[id: string]: RawEntryInfo},\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/thread-reducer.js", "new_path": "lib/reducers/thread-reducer.js", "diff": "@@ -6,8 +6,10 @@ import { type PingResult, pingResponseTypes } from '../types/ping-types';\nimport { updateTypes, type UpdateInfo } from '../types/update-types';\nimport {\ntype ThreadInconsistencyClientResponse,\n+ type ServerRequest,\nserverRequestTypes,\nclearDeliveredClientResponsesActionType,\n+ processServerRequestsActionType,\n} from '../types/request-types';\nimport invariant from 'invariant';\n@@ -178,6 +180,41 @@ function reduceThreadUpdates(\nreturn newState;\n}\n+type HandleCheckStateServerRequestsResult = {|\n+ newThreadInfos: {[id: string]: RawThreadInfo},\n+ newInconsistencies: ThreadInconsistencyClientResponse[],\n+|};\n+function handleCheckStateServerRequests(\n+ beforeAction: {[id: string]: RawThreadInfo},\n+ action: BaseAction,\n+ baseThreadInfos: {[id: string]: RawThreadInfo},\n+ serverRequests: $ReadOnlyArray<ServerRequest>,\n+): HandleCheckStateServerRequestsResult {\n+ const checkStateRequest = serverRequests.find(\n+ candidate => candidate.type === serverRequestTypes.CHECK_STATE,\n+ );\n+ if (\n+ !checkStateRequest ||\n+ !checkStateRequest.stateChanges ||\n+ !checkStateRequest.stateChanges.rawThreadInfos\n+ ) {\n+ return { newThreadInfos: baseThreadInfos, newInconsistencies: [] };\n+ }\n+\n+ const { rawThreadInfos } = checkStateRequest.stateChanges;\n+ const newThreadInfos = { ...baseThreadInfos };\n+ for (let rawThreadInfo of rawThreadInfos) {\n+ newThreadInfos[rawThreadInfo.id] = rawThreadInfo;\n+ }\n+ const newInconsistencies = findInconsistencies(\n+ beforeAction,\n+ action,\n+ baseThreadInfos,\n+ newThreadInfos,\n+ );\n+ return { newThreadInfos, newInconsistencies };\n+}\n+\nconst emptyArray = [];\nfunction findInconsistencies(\nbeforeAction: {[id: string]: RawThreadInfo},\n@@ -295,28 +332,12 @@ export default function reduceThreadInfos(\nnewThreadInfos = reduceFullState(state.threadInfos, payload);\n} else {\nconst updateResult = reduceThreadUpdates(state.threadInfos, payload);\n- const checkStateRequest = payload.requests.serverRequests.find(\n- candidate => candidate.type === serverRequestTypes.CHECK_STATE,\n- );\n- if (\n- !checkStateRequest ||\n- !checkStateRequest.stateChanges ||\n- !checkStateRequest.stateChanges.rawThreadInfos\n- ) {\n- newThreadInfos = updateResult;\n- } else {\n- const { rawThreadInfos } = checkStateRequest.stateChanges;\n- newThreadInfos = { ...updateResult };\n- for (let rawThreadInfo of rawThreadInfos) {\n- newThreadInfos[rawThreadInfo.id] = rawThreadInfo;\n- }\n- newInconsistencies = findInconsistencies(\n+ ({ newThreadInfos, newInconsistencies } = handleCheckStateServerRequests(\nstate.threadInfos,\naction,\nupdateResult,\n- newThreadInfos,\n- );\n- }\n+ payload.requests.serverRequests,\n+ ));\n}\nreturn {\n@@ -428,6 +449,23 @@ export default function reduceThreadInfos(\nthreadInfos: state.threadInfos,\ninconsistencyResponses: updatedResponses,\n};\n+ } else if (action.type === processServerRequestsActionType) {\n+ const {\n+ newThreadInfos,\n+ newInconsistencies,\n+ } = handleCheckStateServerRequests(\n+ state.threadInfos,\n+ action,\n+ state.threadInfos,\n+ action.payload.serverRequests,\n+ );\n+ return {\n+ threadInfos: newThreadInfos,\n+ inconsistencyResponses: [\n+ ...state.inconsistencyResponses,\n+ ...newInconsistencies,\n+ ],\n+ };\n}\nreturn state;\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/user-reducer.js", "new_path": "lib/reducers/user-reducer.js", "diff": "@@ -4,7 +4,11 @@ import type { BaseAction } from '../types/redux-types';\nimport type { CurrentUserInfo, UserInfo } from '../types/user-types';\nimport { updateTypes } from '../types/update-types';\nimport { pingResponseTypes } from '../types/ping-types';\n-import { serverRequestTypes } from '../types/request-types';\n+import {\n+ serverRequestTypes,\n+ type ServerRequest,\n+ processServerRequestsActionType,\n+} from '../types/request-types';\nimport invariant from 'invariant';\nimport _keyBy from 'lodash/fp/keyBy';\n@@ -35,6 +39,26 @@ import {\nfetchMostRecentMessagesActionTypes,\n} from '../actions/message-actions';\n+function getCurrentUserInfoFromServerRequests(\n+ serverRequests: $ReadOnlyArray<ServerRequest>,\n+ prevCurrentUserInfo: ?CurrentUserInfo,\n+): ?CurrentUserInfo {\n+ const checkStateRequest = serverRequests.find(\n+ candidate => candidate.type === serverRequestTypes.CHECK_STATE,\n+ );\n+ if (\n+ checkStateRequest &&\n+ checkStateRequest.stateChanges &&\n+ checkStateRequest.stateChanges.currentUserInfo &&\n+ !_isEqual(\n+ checkStateRequest.stateChanges.currentUserInfo,\n+ )(prevCurrentUserInfo)\n+ ) {\n+ return checkStateRequest.stateChanges.currentUserInfo;\n+ }\n+ return null;\n+}\n+\nfunction reduceCurrentUserInfo(\nstate: ?CurrentUserInfo,\naction: BaseAction,\n@@ -46,19 +70,17 @@ function reduceCurrentUserInfo(\naction.type === logOutActionTypes.success ||\naction.type === deleteAccountActionTypes.success\n) {\n- if (_isEqual(action.payload.currentUserInfo)(state)) {\n- return state;\n- }\n+ if (!_isEqual(action.payload.currentUserInfo)(state)) {\nreturn action.payload.currentUserInfo;\n+ }\n} else if (\naction.type === setNewSessionActionType &&\naction.payload.sessionChange.cookieInvalidated\n) {\nconst { sessionChange } = action.payload;\n- if (_isEqual(sessionChange.currentUserInfo)(state)) {\n- return state;\n- }\n+ if (!_isEqual(sessionChange.currentUserInfo)(state)) {\nreturn sessionChange.currentUserInfo;\n+ }\n} else if (action.type === pingActionTypes.success) {\nconst { payload } = action;\nfor (let update of payload.updatesResult.newUpdates) {\n@@ -78,20 +100,13 @@ function reduceCurrentUserInfo(\nreturn payload.currentUserInfo;\n}\n}\n- const checkStateRequest = payload.requests.serverRequests.find(\n- candidate => candidate.type === serverRequestTypes.CHECK_STATE,\n+ const fromServerRequests = getCurrentUserInfoFromServerRequests(\n+ payload.requests.serverRequests,\n+ prevCurrentUserInfo,\n);\n- if (\n- checkStateRequest &&\n- checkStateRequest.stateChanges &&\n- checkStateRequest.stateChanges.currentUserInfo &&\n- !_isEqual(\n- checkStateRequest.stateChanges.currentUserInfo,\n- )(prevCurrentUserInfo)\n- ) {\n- return checkStateRequest.stateChanges.currentUserInfo;\n+ if (fromServerRequests) {\n+ return fromServerRequests;\n}\n- return state;\n} else if (action.type === changeUserSettingsActionTypes.success) {\ninvariant(\nstate && !state.anonymous,\n@@ -107,10 +122,39 @@ function reduceCurrentUserInfo(\nemail: email,\nemailVerified: false,\n};\n+ } else if (action.type === processServerRequestsActionType) {\n+ const fromServerRequests = getCurrentUserInfoFromServerRequests(\n+ action.payload.serverRequests,\n+ state,\n+ );\n+ if (fromServerRequests) {\n+ return fromServerRequests;\n+ }\n}\nreturn state;\n}\n+function handleCheckStateServerRequests(\n+ baseUserInfos: $ReadOnlyArray<UserInfo>,\n+ serverRequests: $ReadOnlyArray<ServerRequest>,\n+): $ReadOnlyArray<UserInfo> {\n+ const checkStateRequest = serverRequests.find(\n+ candidate => candidate.type === serverRequestTypes.CHECK_STATE,\n+ );\n+ if (\n+ checkStateRequest &&\n+ checkStateRequest.stateChanges &&\n+ checkStateRequest.stateChanges.userInfos\n+ ) {\n+ return [\n+ ...baseUserInfos,\n+ ...checkStateRequest.stateChanges.userInfos,\n+ ];\n+ } else {\n+ return baseUserInfos;\n+ }\n+}\n+\nfunction reduceUserInfos(\nstate: {[id: string]: UserInfo},\naction: BaseAction,\n@@ -148,22 +192,10 @@ function reduceUserInfos(\nreturn newUserInfos;\n}\n} else if (action.type === pingActionTypes.success) {\n- let newUserInfos = action.payload.userInfos;\n-\n- const checkStateRequest = action.payload.requests.serverRequests.find(\n- candidate => candidate.type === serverRequestTypes.CHECK_STATE,\n+ const newUserInfos = handleCheckStateServerRequests(\n+ action.payload.userInfos,\n+ action.payload.requests.serverRequests,\n);\n- if (\n- checkStateRequest &&\n- checkStateRequest.stateChanges &&\n- checkStateRequest.stateChanges.userInfos\n- ) {\n- newUserInfos = [\n- ...newUserInfos,\n- ...checkStateRequest.stateChanges.userInfos,\n- ];\n- }\n-\nconst newUserInfoObject = _keyBy('id')(newUserInfos);\nconst updated = { ...state, ...newUserInfoObject };\nfor (let update of action.payload.updatesResult.newUpdates) {\n@@ -190,6 +222,16 @@ function reduceUserInfos(\nif (!_isEqual(state)(updated)) {\nreturn updated;\n}\n+ } else if (action.type === processServerRequestsActionType) {\n+ const newUserInfos = handleCheckStateServerRequests(\n+ [],\n+ action.payload.serverRequests,\n+ );\n+ const newUserInfoObject = _keyBy('id')(newUserInfos);\n+ const updated = { ...state, ...newUserInfoObject };\n+ if (!_isEqual(state)(updated)) {\n+ return updated;\n+ }\n}\nreturn state;\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Reducer support for processServerRequestsActionType
129,187
18.10.2018 14:58:34
14,400
8f0c25ff8c066959b9d59381e7f4511bf125a258
Replace ping reducers with socket reducers
[ { "change_type": "MODIFY", "old_path": "lib/components/socket.react.js", "new_path": "lib/components/socket.react.js", "diff": "@@ -18,6 +18,8 @@ import {\nserverSocketMessageTypes,\ntype ServerSocketMessage,\nstateSyncPayloadTypes,\n+ fullStateSyncActionPayload,\n+ incrementalStateSyncActionPayload,\n} from '../types/socket-types';\nimport type { Dispatch } from '../types/redux-types';\nimport type { DispatchActionPayload } from '../utils/action-utils';\n@@ -35,8 +37,6 @@ import {\n} from '../utils/action-utils';\nimport { socketAuthErrorResolutionAttempt } from '../actions/user-actions';\n-const fullStateSyncActionPayload = \"FULL_STATE_SYNC\";\n-const incrementalStateSyncActionPayload = \"INCREMENTAL_STATE_SYNC\";\ntype SentClientResponse = { clientResponse: ClientResponse, messageID: number };\ntype Props = {|\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/calendar-filters-reducer.js", "new_path": "lib/reducers/calendar-filters-reducer.js", "diff": "@@ -10,7 +10,11 @@ import {\n} from '../types/filter-types';\nimport type { BaseAction } from '../types/redux-types';\nimport type { RawThreadInfo } from '../types/thread-types';\n-import { updateTypes } from '../types/update-types';\n+import { updateTypes, type UpdateInfo } from '../types/update-types';\n+import {\n+ fullStateSyncActionPayload,\n+ incrementalStateSyncActionPayload,\n+} from '../types/socket-types';\nimport {\nlogOutActionTypes,\n@@ -32,7 +36,6 @@ import {\nleaveThreadActionTypes,\ndeleteThreadActionTypes,\n} from '../actions/thread-actions';\n-import { pingActionTypes } from '../actions/ping-actions';\nexport default function reduceCalendarFilters(\nstate: $ReadOnlyArray<CalendarFilter>,\n@@ -78,15 +81,36 @@ export default function reduceCalendarFilters(\naction.type === newThreadActionTypes.success ||\naction.type === joinThreadActionTypes.success ||\naction.type === leaveThreadActionTypes.success ||\n- action.type === deleteThreadActionTypes.success ||\n- action.type === pingActionTypes.success\n+ action.type === deleteThreadActionTypes.success\n) {\n+ return updateFilterListFromUpdateInfos(\n+ state,\n+ action.payload.updatesResult.newUpdates,\n+ );\n+ } else if (action.type === incrementalStateSyncActionPayload) {\n+ return updateFilterListFromUpdateInfos(\n+ state,\n+ action.payload.updatesResult.newUpdates,\n+ );\n+ } else if (action.type === fullStateSyncActionPayload) {\n+ return removeDeletedThreadIDsFromFilterList(\n+ state,\n+ action.payload.threadInfos,\n+ );\n+ }\n+ return state;\n+}\n+\n+function updateFilterListFromUpdateInfos(\n+ state: $ReadOnlyArray<CalendarFilter>,\n+ updateInfos: $ReadOnlyArray<UpdateInfo>,\n+): $ReadOnlyArray<CalendarFilter> {\nconst currentlyFilteredIDs = filteredThreadIDs(state);\n- let changeOccurred = false;\nif (!currentlyFilteredIDs) {\nreturn state;\n}\n- for (let update of action.payload.updatesResult.newUpdates) {\n+ let changeOccurred = false;\n+ for (let update of updateInfos) {\nif (update.type === updateTypes.DELETE_THREAD) {\nconst result = currentlyFilteredIDs.delete(update.threadID);\nif (result) {\n@@ -117,6 +141,25 @@ export default function reduceCalendarFilters(\n{ type: \"threads\", threadIDs: [...currentlyFilteredIDs] },\n];\n}\n+ return state;\n+}\n+\n+function removeDeletedThreadIDsFromFilterList(\n+ state: $ReadOnlyArray<CalendarFilter>,\n+ threadInfos: {[id: string]: RawThreadInfo}\n+): $ReadOnlyArray<CalendarFilter> {\n+ const currentlyFilteredIDs = filteredThreadIDs(state);\n+ if (!currentlyFilteredIDs) {\n+ return state;\n+ }\n+ const filtered = [...currentlyFilteredIDs].filter(\n+ threadID => threadInFilterList(threadInfos[threadID]),\n+ );\n+ if (filtered.length < currentlyFilteredIDs.size) {\n+ return [\n+ ...nonThreadCalendarFilters(state),\n+ { type: \"threads\", threadIDs: filtered },\n+ ];\n}\nreturn state;\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/entry-reducer.js", "new_path": "lib/reducers/entry-reducer.js", "diff": "@@ -16,7 +16,10 @@ import {\nclearDeliveredClientResponsesActionType,\nprocessServerRequestsActionType,\n} from '../types/request-types';\n-import { pingResponseTypes } from '../types/ping-types';\n+import {\n+ fullStateSyncActionPayload,\n+ incrementalStateSyncActionPayload,\n+} from '../types/socket-types';\nimport _flow from 'lodash/fp/flow';\nimport _map from 'lodash/fp/map';\n@@ -60,7 +63,6 @@ import {\nremoveUsersFromThreadActionTypes,\nchangeThreadMemberRolesActionTypes,\n} from '../actions/thread-actions';\n-import { pingActionTypes } from '../actions/ping-actions';\nimport { rehydrateActionType } from '../types/redux-types';\nimport {\nentryID,\n@@ -307,8 +309,7 @@ function reduceEntryInfos(\n} else if (\naction.type === logInActionTypes.started ||\naction.type === resetPasswordActionTypes.started ||\n- action.type === registerActionTypes.started ||\n- action.type === pingActionTypes.started\n+ action.type === registerActionTypes.started\n) {\nreturn {\nentryInfos,\n@@ -615,52 +616,35 @@ function reduceEntryInfos(\ninconsistencyResponses,\n};\n}\n- } else if (action.type === pingActionTypes.success) {\n- const { payload } = action;\n-\n- let newInconsistencies = [], updatedEntryInfos, updatedDaysToEntries;\n- if (payload.type === pingResponseTypes.FULL) {\n- [ updatedEntryInfos, updatedDaysToEntries ] = mergeNewEntryInfos(\n- entryInfos,\n- payload.calendarResult.rawEntryInfos,\n- newThreadInfos,\n- {\n- prevEntryInfos: payload.prevState.entryInfos,\n- calendarQuery: payload.calendarResult.calendarQuery,\n- },\n- );\n- } else {\n- const { calendarQuery, updatesResult, deltaEntryInfos } = payload;\n+ } else if (action.type === incrementalStateSyncActionPayload) {\nconst updateEntryInfos = mergeUpdateEntryInfos(\n- deltaEntryInfos,\n- updatesResult.newUpdates,\n+ action.payload.deltaEntryInfos,\n+ action.payload.updatesResult.newUpdates,\n);\n- ({\n- updatedEntryInfos,\n- updatedDaysToEntries,\n- newInconsistencies,\n- } = handleCheckStateServerRequests(\n+ const [ updatedEntryInfos, updatedDaysToEntries ] = mergeNewEntryInfos(\nentryInfos,\n- action,\nupdateEntryInfos,\nnewThreadInfos,\n- payload.requests.serverRequests,\n- calendarQuery,\n- ));\n- }\n-\n+ );\nreturn {\nentryInfos: updatedEntryInfos,\ndaysToEntries: updatedDaysToEntries,\nactualizedCalendarQuery,\nlastUserInteractionCalendar,\n- inconsistencyResponses: [\n- ...inconsistencyResponses.filter(\n- response =>\n- !payload.requests.deliveredClientResponses.includes(response),\n- ),\n- ...newInconsistencies,\n- ],\n+ inconsistencyResponses,\n+ };\n+ } else if (action.type === fullStateSyncActionPayload) {\n+ const [ updatedEntryInfos, updatedDaysToEntries ] = mergeNewEntryInfos(\n+ entryInfos,\n+ action.payload.rawEntryInfos,\n+ newThreadInfos,\n+ );\n+ return {\n+ entryInfos: updatedEntryInfos,\n+ daysToEntries: updatedDaysToEntries,\n+ actualizedCalendarQuery,\n+ lastUserInteractionCalendar,\n+ inconsistencyResponses,\n};\n} else if (\naction.type === changeThreadSettingsActionTypes.success ||\n@@ -721,16 +705,27 @@ function reduceEntryInfos(\ninconsistencyResponses: updatedResponses,\n};\n} else if (action.type === processServerRequestsActionType) {\n- const {\n- updatedEntryInfos,\n- updatedDaysToEntries,\n- newInconsistencies,\n- } = handleCheckStateServerRequests(\n+ const checkStateRequest = action.payload.serverRequests.find(\n+ candidate => candidate.type === serverRequestTypes.CHECK_STATE,\n+ );\n+ if (\n+ !checkStateRequest ||\n+ !checkStateRequest.stateChanges ||\n+ !checkStateRequest.stateChanges.rawEntryInfos\n+ ) {\n+ return entryStore;\n+ }\n+ const { rawEntryInfos } = checkStateRequest.stateChanges;\n+ const [ updatedEntryInfos, updatedDaysToEntries ] = mergeNewEntryInfos(\nentryInfos,\n- action,\n- [],\n+ rawEntryInfos,\nnewThreadInfos,\n- action.payload.serverRequests,\n+ );\n+ const newInconsistencies = findInconsistencies(\n+ entryInfos,\n+ action,\n+ entryInfos,\n+ updatedEntryInfos,\nactualizedCalendarQuery,\n);\nreturn {\n@@ -774,56 +769,6 @@ function mergeUpdateEntryInfos(\nreturn mergedEntryInfos;\n}\n-type HandleCheckStateServerRequestsResult = {|\n- updatedEntryInfos: {[id: string]: RawEntryInfo},\n- updatedDaysToEntries: {[day: string]: string[]},\n- newInconsistencies: EntryInconsistencyClientResponse[],\n-|};\n-function handleCheckStateServerRequests(\n- beforeAction: {[id: string]: RawEntryInfo},\n- action: BaseAction,\n- baseEntryInfos: $ReadOnlyArray<RawEntryInfo>,\n- newThreadInfos: {[id: string]: RawThreadInfo},\n- serverRequests: $ReadOnlyArray<ServerRequest>,\n- calendarQuery: CalendarQuery,\n-): HandleCheckStateServerRequestsResult {\n- const updateResult = mergeNewEntryInfos(\n- beforeAction,\n- baseEntryInfos,\n- newThreadInfos,\n- );\n-\n- const checkStateRequest = serverRequests.find(\n- candidate => candidate.type === serverRequestTypes.CHECK_STATE,\n- );\n- if (\n- !checkStateRequest ||\n- !checkStateRequest.stateChanges ||\n- !checkStateRequest.stateChanges.rawEntryInfos\n- ) {\n- return {\n- updatedEntryInfos: updateResult[0],\n- updatedDaysToEntries: updateResult[1],\n- newInconsistencies: [],\n- };\n- }\n-\n- const { rawEntryInfos } = checkStateRequest.stateChanges;\n- const [ updatedEntryInfos, updatedDaysToEntries ] = mergeNewEntryInfos(\n- beforeAction,\n- [ ...baseEntryInfos, ...rawEntryInfos ],\n- newThreadInfos,\n- );\n- const newInconsistencies = findInconsistencies(\n- beforeAction,\n- action,\n- updateResult[0],\n- updatedEntryInfos,\n- calendarQuery,\n- );\n- return { updatedEntryInfos, updatedDaysToEntries, newInconsistencies };\n-}\n-\nconst emptyArray = [];\nfunction findInconsistencies(\nbeforeAction: {[id: string]: RawEntryInfo},\n@@ -843,35 +788,16 @@ function findInconsistencies(\nif (_isEqual(filteredPollResult)(filteredPushResult)) {\nreturn emptyArray;\n}\n- if (action.type === pingActionTypes.success) {\n- if (action.payload.type === pingResponseTypes.FULL) {\n+ if (action.type === clearDeliveredClientResponsesActionType) {\n// We can get a memory leak if we include a previous\n// EntryInconsistencyClientResponse in this one\naction = {\n- type: \"PING_SUCCESS\",\n- loadingInfo: action.loadingInfo,\n+ type: \"CLEAR_DELIVERED_CLIENT_RESPONSES\",\npayload: {\n...action.payload,\n- requests: {\n- ...action.payload.requests,\n- deliveredClientResponses: [],\n- },\n+ clientResponses: [],\n},\n};\n- } else {\n- // This is a separate condition because of Flow\n- action = {\n- type: \"PING_SUCCESS\",\n- loadingInfo: action.loadingInfo,\n- payload: {\n- ...action.payload,\n- requests: {\n- ...action.payload.requests,\n- deliveredClientResponses: [],\n- },\n- },\n- };\n- }\n}\nreturn [{\ntype: serverRequestTypes.ENTRY_INCONSISTENCY,\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/message-reducer.js", "new_path": "lib/reducers/message-reducer.js", "diff": "@@ -5,7 +5,7 @@ import {\ntype ThreadMessageInfo,\ntype MessageStore,\ntype MessageTruncationStatus,\n- type GenericMessagesResult,\n+ type MessagesPingResponse,\nmessageTruncationStatus,\nmessageTypes,\ndefaultNumberPerThread,\n@@ -13,6 +13,10 @@ import {\nimport type { BaseAction } from '../types/redux-types';\nimport { type RawThreadInfo, threadPermissions } from '../types/thread-types';\nimport { type UpdateInfo, updateTypes } from '../types/update-types';\n+import {\n+ fullStateSyncActionPayload,\n+ incrementalStateSyncActionPayload,\n+} from '../types/socket-types';\nimport invariant from 'invariant';\nimport _flow from 'lodash/fp/flow';\n@@ -57,7 +61,6 @@ import {\nchangeThreadMemberRolesActionTypes,\njoinThreadActionTypes,\n} from '../actions/thread-actions';\n-import { pingActionTypes } from '../actions/ping-actions';\nimport { rehydrateActionType } from '../types/redux-types';\nimport {\nfetchMessagesBeforeCursorActionTypes,\n@@ -353,9 +356,9 @@ function reduceMessageStore(\nmessagesResult.currentAsOf,\nnewThreadInfos,\n);\n- } else if (action.type === pingActionTypes.success) {\n+ } else if (action.type === incrementalStateSyncActionPayload) {\nif (\n- action.payload.messagesResult.messageInfos.length === 0 &&\n+ action.payload.messagesResult.rawMessageInfos.length === 0 &&\naction.payload.updatesResult.newUpdates.length === 0\n) {\nreturn messageStore;\n@@ -366,21 +369,25 @@ function reduceMessageStore(\n);\nconst newMessageStore = mergeNewMessages(\nmessageStore,\n- messagesResult.messageInfos,\n- messagesResult.truncationStatus,\n+ messagesResult.rawMessageInfos,\n+ messagesResult.truncationStatuses,\n+ newThreadInfos,\n+ action.type,\n+ );\n+ return {\n+ messages: newMessageStore.messages,\n+ threads: newMessageStore.threads,\n+ currentAsOf: messagesResult.currentAsOf,\n+ };\n+ } else if (action.type === fullStateSyncActionPayload) {\n+ const { messagesResult } = action.payload;\n+ const newMessageStore = mergeNewMessages(\n+ messageStore,\n+ messagesResult.rawMessageInfos,\n+ messagesResult.truncationStatuses,\nnewThreadInfos,\naction.type,\n);\n- const oldWatchedIDs = messagesResult.watchedIDsAtRequestTime;\n- const currentWatchedIDs = threadWatcher.getWatchedIDs();\n- if (_difference(currentWatchedIDs)(oldWatchedIDs).length !== 0) {\n- // This indicates that we have had a new watched ID since this query was\n- // issued. As a result this query does not update the new watched ID to be\n- // \"current as of\" the new time here, and thus we cannot advance the value\n- // in Redux. The next ping might consequently include duplicates, but\n- // reduceMessageStore should be able to handle that.\n- return newMessageStore;\n- }\nreturn {\nmessages: newMessageStore.messages,\nthreads: newMessageStore.threads,\n@@ -593,33 +600,6 @@ function reduceMessageStore(\n}\n}\nsetHighestLocalID(highestLocalIDFound + 1);\n- } else if (\n- action.type === pingActionTypes.started &&\n- action.payload.messageStorePruneRequest\n- ) {\n- const messageStorePruneRequest = action.payload.messageStorePruneRequest;\n- const now = Date.now();\n- const messageIDsToPrune = [];\n- let newThreads = { ...messageStore.threads };\n- for (let threadID of messageStorePruneRequest.threadIDs) {\n- const thread = newThreads[threadID];\n- if (!thread) {\n- continue;\n- }\n- const removed = thread.messageIDs.splice(defaultNumberPerThread);\n- for (let messageID of removed) {\n- messageIDsToPrune.push(messageID);\n- }\n- thread.lastPruned = now;\n- if (removed.length > 0) {\n- thread.startReached = false;\n- }\n- }\n- return {\n- messages: _omit(messageIDsToPrune)(messageStore.messages),\n- threads: newThreads,\n- currentAsOf: messageStore.currentAsOf,\n- };\n} else if (action.type === saveMessagesActionType) {\nconst truncationStatuses = {};\nfor (let messageInfo of action.payload.rawMessageInfos) {\n@@ -638,14 +618,14 @@ function reduceMessageStore(\n}\nfunction mergeUpdatesIntoMessagesResult(\n- messagesResult: GenericMessagesResult,\n+ messagesResult: MessagesPingResponse,\nnewUpdates: $ReadOnlyArray<UpdateInfo>,\n-): GenericMessagesResult {\n- const messageIDs = new Set(messagesResult.messageInfos.map(\n+): MessagesPingResponse {\n+ const messageIDs = new Set(messagesResult.rawMessageInfos.map(\nmessageInfo => messageInfo.id,\n));\n- const mergedMessageInfos = [...messagesResult.messageInfos];\n- const mergedTruncationStatuses = {...messagesResult.truncationStatus};\n+ const mergedMessageInfos = [...messagesResult.rawMessageInfos];\n+ const mergedTruncationStatuses = {...messagesResult.truncationStatuses};\nfor (let updateInfo of newUpdates) {\nif (updateInfo.type !== updateTypes.JOIN_THREAD) {\ncontinue;\n@@ -664,9 +644,8 @@ function mergeUpdatesIntoMessagesResult(\n);\n}\nreturn {\n- messageInfos: mergedMessageInfos,\n- truncationStatus: mergedTruncationStatuses,\n- watchedIDsAtRequestTime: messagesResult.watchedIDsAtRequestTime,\n+ rawMessageInfos: mergedMessageInfos,\n+ truncationStatuses: mergedTruncationStatuses,\ncurrentAsOf: messagesResult.currentAsOf,\n};\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/nav-reducer.js", "new_path": "lib/reducers/nav-reducer.js", "diff": "@@ -10,7 +10,6 @@ import {\nresetPasswordActionTypes,\nregisterActionTypes,\n} from '../actions/user-actions';\n-import { pingActionTypes } from '../actions/ping-actions';\nexport default function reduceBaseNavInfo<T: BaseNavInfo>(\nstate: T,\n@@ -19,8 +18,7 @@ export default function reduceBaseNavInfo<T: BaseNavInfo>(\nif (\naction.type === logInActionTypes.started ||\naction.type === resetPasswordActionTypes.started ||\n- action.type === registerActionTypes.started ||\n- action.type === pingActionTypes.started\n+ action.type === registerActionTypes.started\n) {\nconst { startDate, endDate } = action.payload.calendarQuery;\nreturn { ...state, startDate, endDate };\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/thread-reducer.js", "new_path": "lib/reducers/thread-reducer.js", "diff": "import type { BaseAction } from '../types/redux-types';\nimport type { RawThreadInfo, ThreadStore } from '../types/thread-types';\n-import { type PingResult, pingResponseTypes } from '../types/ping-types';\nimport { updateTypes, type UpdateInfo } from '../types/update-types';\nimport {\ntype ThreadInconsistencyClientResponse,\n- type ServerRequest,\nserverRequestTypes,\nclearDeliveredClientResponsesActionType,\nprocessServerRequestsActionType,\n} from '../types/request-types';\n+import {\n+ fullStateSyncActionPayload,\n+ incrementalStateSyncActionPayload,\n+} from '../types/socket-types';\nimport invariant from 'invariant';\nimport _isEqual from 'lodash/fp/isEqual';\n@@ -33,98 +35,12 @@ import {\njoinThreadActionTypes,\nleaveThreadActionTypes,\n} from '../actions/thread-actions';\n-import {\n- pingActionTypes,\n- updateActivityActionTypes,\n-} from '../actions/ping-actions';\n+import { updateActivityActionTypes } from '../actions/ping-actions';\nimport { saveMessagesActionType } from '../actions/message-actions';\nimport { getConfig } from '../utils/config';\nimport { reduxLogger } from '../utils/redux-logger';\nimport { sanitizeAction } from '../utils/sanitization';\n-// If the user goes away for a while and the server stops keeping track of their\n-// session, the server will send down the full current set of threadInfos\n-function reduceFullState(\n- threadInfos: {[id: string]: RawThreadInfo},\n- payload: PingResult,\n-): {[id: string]: RawThreadInfo} {\n- if (\n- payload.type !== pingResponseTypes.FULL ||\n- _isEqual(threadInfos)(payload.threadInfos)\n- ) {\n- return threadInfos;\n- }\n- const newThreadInfos = {};\n- let threadIDsWithNewMessages: ?Set<string> = null;\n- const getThreadIDsWithNewMessages = () => {\n- if (threadIDsWithNewMessages) {\n- return threadIDsWithNewMessages;\n- }\n- threadIDsWithNewMessages = new Set();\n- for (let rawMessageInfo of payload.messagesResult.messageInfos) {\n- threadIDsWithNewMessages.add(rawMessageInfo.threadID);\n- }\n- return threadIDsWithNewMessages;\n- };\n- for (let threadID in payload.threadInfos) {\n- const newThreadInfo = payload.threadInfos[threadID];\n- const currentThreadInfo = threadInfos[threadID];\n- const prevThreadInfo = payload.prevState.threadInfos[threadID];\n- if (_isEqual(currentThreadInfo)(newThreadInfo)) {\n- newThreadInfos[threadID] = currentThreadInfo;\n- } else if (_isEqual(prevThreadInfo)(newThreadInfo)) {\n- // If the thread at the time of the start of the ping is the same as\n- // what was returned, but the current state is different, then it's\n- // likely that an action mutated the state after the ping result was\n- // fetched on the server. We should keep the mutated (current) state.\n- if (currentThreadInfo) {\n- newThreadInfos[threadID] = currentThreadInfo;\n- }\n- } else if (\n- newThreadInfo.currentUser.unread &&\n- currentThreadInfo &&\n- !currentThreadInfo.currentUser.unread &&\n- !getThreadIDsWithNewMessages().has(threadID)\n- ) {\n- // To make sure the unread status doesn't update from a stale ping\n- // result, we check if there actually are any new messages for this\n- // threadInfo.\n- const potentiallyNewThreadInfo = {\n- ...newThreadInfo,\n- currentUser: {\n- ...newThreadInfo.currentUser,\n- unread: false,\n- },\n- };\n- if (_isEqual(currentThreadInfo)(potentiallyNewThreadInfo)) {\n- newThreadInfos[threadID] = currentThreadInfo;\n- } else {\n- newThreadInfos[threadID] = potentiallyNewThreadInfo;\n- }\n- } else {\n- newThreadInfos[threadID] = newThreadInfo;\n- }\n- }\n- for (let threadID in threadInfos) {\n- const newThreadInfo = payload.threadInfos[threadID];\n- if (newThreadInfo) {\n- continue;\n- }\n- const prevThreadInfo = payload.prevState.threadInfos[threadID];\n- if (prevThreadInfo) {\n- continue;\n- }\n- // If a thread was not present at the start of the ping, it's possible\n- // that an action added it in between the start and the end of the ping.\n- const currentThreadInfo = threadInfos[threadID];\n- newThreadInfos[threadID] = currentThreadInfo;\n- }\n- if (_isEqual(threadInfos)(newThreadInfos)) {\n- return threadInfos;\n- }\n- return newThreadInfos;\n-}\n-\nfunction reduceThreadUpdates(\nthreadInfos: {[id: string]: RawThreadInfo},\npayload: { +updatesResult: { newUpdates: $ReadOnlyArray<UpdateInfo> } },\n@@ -180,41 +96,6 @@ function reduceThreadUpdates(\nreturn newState;\n}\n-type HandleCheckStateServerRequestsResult = {|\n- newThreadInfos: {[id: string]: RawThreadInfo},\n- newInconsistencies: ThreadInconsistencyClientResponse[],\n-|};\n-function handleCheckStateServerRequests(\n- beforeAction: {[id: string]: RawThreadInfo},\n- action: BaseAction,\n- baseThreadInfos: {[id: string]: RawThreadInfo},\n- serverRequests: $ReadOnlyArray<ServerRequest>,\n-): HandleCheckStateServerRequestsResult {\n- const checkStateRequest = serverRequests.find(\n- candidate => candidate.type === serverRequestTypes.CHECK_STATE,\n- );\n- if (\n- !checkStateRequest ||\n- !checkStateRequest.stateChanges ||\n- !checkStateRequest.stateChanges.rawThreadInfos\n- ) {\n- return { newThreadInfos: baseThreadInfos, newInconsistencies: [] };\n- }\n-\n- const { rawThreadInfos } = checkStateRequest.stateChanges;\n- const newThreadInfos = { ...baseThreadInfos };\n- for (let rawThreadInfo of rawThreadInfos) {\n- newThreadInfos[rawThreadInfo.id] = rawThreadInfo;\n- }\n- const newInconsistencies = findInconsistencies(\n- beforeAction,\n- action,\n- baseThreadInfos,\n- newThreadInfos,\n- );\n- return { newThreadInfos, newInconsistencies };\n-}\n-\nconst emptyArray = [];\nfunction findInconsistencies(\nbeforeAction: {[id: string]: RawThreadInfo},\n@@ -225,36 +106,17 @@ function findInconsistencies(\nif (_isEqual(oldResult)(newResult)) {\nreturn emptyArray;\n}\n- if (action.type === pingActionTypes.success) {\n- if (action.payload.type === pingResponseTypes.FULL) {\n+ if (action.type === clearDeliveredClientResponsesActionType) {\n// We can get a memory leak if we include a previous\n- // EntryInconsistencyClientResponse in this one\n- action = {\n- type: \"PING_SUCCESS\",\n- loadingInfo: action.loadingInfo,\n- payload: {\n- ...action.payload,\n- requests: {\n- ...action.payload.requests,\n- deliveredClientResponses: [],\n- },\n- },\n- };\n- } else {\n- // This is a separate condition because of Flow\n+ // ThreadInconsistencyClientResponse in this one\naction = {\n- type: \"PING_SUCCESS\",\n- loadingInfo: action.loadingInfo,\n+ type: \"CLEAR_DELIVERED_CLIENT_RESPONSES\",\npayload: {\n...action.payload,\n- requests: {\n- ...action.payload.requests,\n- deliveredClientResponses: [],\n- },\n+ clientResponses: [],\n},\n};\n}\n- }\nreturn [{\ntype: serverRequestTypes.THREAD_INCONSISTENCY,\nplatformDetails: getConfig().platformDetails,\n@@ -274,7 +136,8 @@ export default function reduceThreadInfos(\nif (\naction.type === logInActionTypes.success ||\naction.type === registerActionTypes.success ||\n- action.type === resetPasswordActionTypes.success\n+ action.type === resetPasswordActionTypes.success ||\n+ action.type === fullStateSyncActionPayload\n) {\nif (_isEqual(state.threadInfos)(action.payload.threadInfos)) {\nreturn state;\n@@ -324,31 +187,11 @@ export default function reduceThreadInfos(\n),\n],\n};\n- } else if (action.type === pingActionTypes.success) {\n- const payload = action.payload;\n-\n- let newInconsistencies = [], newThreadInfos;\n- if (payload.type === pingResponseTypes.FULL) {\n- newThreadInfos = reduceFullState(state.threadInfos, payload);\n- } else {\n- const updateResult = reduceThreadUpdates(state.threadInfos, payload);\n- ({ newThreadInfos, newInconsistencies } = handleCheckStateServerRequests(\n- state.threadInfos,\n- action,\n- updateResult,\n- payload.requests.serverRequests,\n- ));\n- }\n-\n+ } else if (action.type === incrementalStateSyncActionPayload) {\n+ const updateResult = reduceThreadUpdates(state.threadInfos, action.payload);\nreturn {\n- threadInfos: newThreadInfos,\n- inconsistencyResponses: [\n- ...state.inconsistencyResponses.filter(\n- response =>\n- !payload.requests.deliveredClientResponses.includes(response),\n- ),\n- ...newInconsistencies,\n- ],\n+ threadInfos: updateResult,\n+ inconsistencyResponses: state.inconsistencyResponses,\n};\n} else if (action.type === newThreadActionTypes.success) {\nconst newThreadInfo = action.payload.newThreadInfo;\n@@ -450,14 +293,26 @@ export default function reduceThreadInfos(\ninconsistencyResponses: updatedResponses,\n};\n} else if (action.type === processServerRequestsActionType) {\n- const {\n- newThreadInfos,\n- newInconsistencies,\n- } = handleCheckStateServerRequests(\n+ const checkStateRequest = action.payload.serverRequests.find(\n+ candidate => candidate.type === serverRequestTypes.CHECK_STATE,\n+ );\n+ if (\n+ !checkStateRequest ||\n+ !checkStateRequest.stateChanges ||\n+ !checkStateRequest.stateChanges.rawThreadInfos\n+ ) {\n+ return state;\n+ }\n+ const { rawThreadInfos } = checkStateRequest.stateChanges;\n+ const newThreadInfos = { ...state.threadInfos };\n+ for (let rawThreadInfo of rawThreadInfos) {\n+ newThreadInfos[rawThreadInfo.id] = rawThreadInfo;\n+ }\n+ const newInconsistencies = findInconsistencies(\nstate.threadInfos,\naction,\nstate.threadInfos,\n- action.payload.serverRequests,\n+ newThreadInfos,\n);\nreturn {\nthreadInfos: newThreadInfos,\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/updates-reducer.js", "new_path": "lib/reducers/updates-reducer.js", "diff": "@@ -8,8 +8,11 @@ import {\nlogInActionTypes,\nresetPasswordActionTypes,\n} from '../actions/user-actions';\n-import { pingActionTypes } from '../actions/ping-actions';\nimport threadWatcher from '../shared/thread-watcher';\n+import {\n+ fullStateSyncActionPayload,\n+ incrementalStateSyncActionPayload,\n+} from '../types/socket-types';\nfunction reduceUpdatesCurrentAsOf(\ncurrentAsOf: number,\n@@ -20,7 +23,9 @@ function reduceUpdatesCurrentAsOf(\naction.type === resetPasswordActionTypes.success\n) {\nreturn action.payload.updatesCurrentAsOf;\n- } else if (action.type === pingActionTypes.success) {\n+ } else if (action.type === fullStateSyncActionPayload) {\n+ return action.payload.updatesCurrentAsOf;\n+ } else if (action.type === incrementalStateSyncActionPayload) {\nreturn action.payload.updatesResult.currentAsOf;\n}\nreturn currentAsOf;\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/user-reducer.js", "new_path": "lib/reducers/user-reducer.js", "diff": "@@ -6,9 +6,12 @@ import { updateTypes } from '../types/update-types';\nimport { pingResponseTypes } from '../types/ping-types';\nimport {\nserverRequestTypes,\n- type ServerRequest,\nprocessServerRequestsActionType,\n} from '../types/request-types';\n+import {\n+ fullStateSyncActionPayload,\n+ incrementalStateSyncActionPayload,\n+} from '../types/socket-types';\nimport invariant from 'invariant';\nimport _keyBy from 'lodash/fp/keyBy';\n@@ -33,32 +36,11 @@ import {\nsearchUsersActionTypes,\n} from '../actions/user-actions';\nimport { joinThreadActionTypes } from '../actions/thread-actions';\n-import { pingActionTypes } from '../actions/ping-actions';\nimport {\nfetchMessagesBeforeCursorActionTypes,\nfetchMostRecentMessagesActionTypes,\n} from '../actions/message-actions';\n-function getCurrentUserInfoFromServerRequests(\n- serverRequests: $ReadOnlyArray<ServerRequest>,\n- prevCurrentUserInfo: ?CurrentUserInfo,\n-): ?CurrentUserInfo {\n- const checkStateRequest = serverRequests.find(\n- candidate => candidate.type === serverRequestTypes.CHECK_STATE,\n- );\n- if (\n- checkStateRequest &&\n- checkStateRequest.stateChanges &&\n- checkStateRequest.stateChanges.currentUserInfo &&\n- !_isEqual(\n- checkStateRequest.stateChanges.currentUserInfo,\n- )(prevCurrentUserInfo)\n- ) {\n- return checkStateRequest.stateChanges.currentUserInfo;\n- }\n- return null;\n-}\n-\nfunction reduceCurrentUserInfo(\nstate: ?CurrentUserInfo,\naction: BaseAction,\n@@ -81,9 +63,13 @@ function reduceCurrentUserInfo(\nif (!_isEqual(sessionChange.currentUserInfo)(state)) {\nreturn sessionChange.currentUserInfo;\n}\n- } else if (action.type === pingActionTypes.success) {\n- const { payload } = action;\n- for (let update of payload.updatesResult.newUpdates) {\n+ } else if (action.type === fullStateSyncActionPayload) {\n+ const { currentUserInfo } = action.payload;\n+ if (!_isEqual(currentUserInfo)(state)) {\n+ return currentUserInfo;\n+ }\n+ } else if (action.type === incrementalStateSyncActionPayload) {\n+ for (let update of action.payload.updatesResult.newUpdates) {\nif (\nupdate.type === updateTypes.UPDATE_CURRENT_USER &&\n!_isEqual(update.currentUserInfo)(state)\n@@ -91,22 +77,6 @@ function reduceCurrentUserInfo(\nreturn update.currentUserInfo;\n}\n}\n- const prevCurrentUserInfo = payload.prevState.currentUserInfo;\n- if (payload.type === pingResponseTypes.FULL) {\n- if (\n- !_isEqual(payload.currentUserInfo)(state) &&\n- !_isEqual(payload.currentUserInfo)(prevCurrentUserInfo)\n- ) {\n- return payload.currentUserInfo;\n- }\n- }\n- const fromServerRequests = getCurrentUserInfoFromServerRequests(\n- payload.requests.serverRequests,\n- prevCurrentUserInfo,\n- );\n- if (fromServerRequests) {\n- return fromServerRequests;\n- }\n} else if (action.type === changeUserSettingsActionTypes.success) {\ninvariant(\nstate && !state.anonymous,\n@@ -123,36 +93,19 @@ function reduceCurrentUserInfo(\nemailVerified: false,\n};\n} else if (action.type === processServerRequestsActionType) {\n- const fromServerRequests = getCurrentUserInfoFromServerRequests(\n- action.payload.serverRequests,\n- state,\n- );\n- if (fromServerRequests) {\n- return fromServerRequests;\n- }\n- }\n- return state;\n-}\n-\n-function handleCheckStateServerRequests(\n- baseUserInfos: $ReadOnlyArray<UserInfo>,\n- serverRequests: $ReadOnlyArray<ServerRequest>,\n-): $ReadOnlyArray<UserInfo> {\n- const checkStateRequest = serverRequests.find(\n+ const checkStateRequest = action.payload.serverRequests.find(\ncandidate => candidate.type === serverRequestTypes.CHECK_STATE,\n);\nif (\ncheckStateRequest &&\ncheckStateRequest.stateChanges &&\n- checkStateRequest.stateChanges.userInfos\n+ checkStateRequest.stateChanges.currentUserInfo &&\n+ !_isEqual(checkStateRequest.stateChanges.currentUserInfo)(state)\n) {\n- return [\n- ...baseUserInfos,\n- ...checkStateRequest.stateChanges.userInfos,\n- ];\n- } else {\n- return baseUserInfos;\n+ return checkStateRequest.stateChanges.currentUserInfo;\n+ }\n}\n+ return state;\n}\nfunction reduceUserInfos(\n@@ -185,19 +138,16 @@ function reduceUserInfos(\n} else if (\naction.type === logInActionTypes.success ||\naction.type === registerActionTypes.success ||\n- action.type === resetPasswordActionTypes.success\n+ action.type === resetPasswordActionTypes.success ||\n+ action.type === fullStateSyncActionPayload\n) {\nconst newUserInfos = _keyBy('id')(action.payload.userInfos);\nif (!_isEqual(state)(newUserInfos)) {\nreturn newUserInfos;\n}\n- } else if (action.type === pingActionTypes.success) {\n- const newUserInfos = handleCheckStateServerRequests(\n- action.payload.userInfos,\n- action.payload.requests.serverRequests,\n- );\n- const newUserInfoObject = _keyBy('id')(newUserInfos);\n- const updated = { ...state, ...newUserInfoObject };\n+ } else if (action.type === incrementalStateSyncActionPayload) {\n+ const newUserInfos = _keyBy('id')(action.payload.userInfos);\n+ const updated = { ...state, ...newUserInfos };\nfor (let update of action.payload.updatesResult.newUpdates) {\nif (update.type === updateTypes.DELETE_ACCOUNT) {\ndelete updated[update.deletedUserID];\n@@ -223,16 +173,22 @@ function reduceUserInfos(\nreturn updated;\n}\n} else if (action.type === processServerRequestsActionType) {\n- const newUserInfos = handleCheckStateServerRequests(\n- [],\n- action.payload.serverRequests,\n+ const checkStateRequest = action.payload.serverRequests.find(\n+ candidate => candidate.type === serverRequestTypes.CHECK_STATE,\n);\n+ if (\n+ checkStateRequest &&\n+ checkStateRequest.stateChanges &&\n+ checkStateRequest.stateChanges.userInfos\n+ ) {\n+ const newUserInfos = checkStateRequest.stateChanges.userInfos;\nconst newUserInfoObject = _keyBy('id')(newUserInfos);\nconst updated = { ...state, ...newUserInfoObject };\nif (!_isEqual(state)(updated)) {\nreturn updated;\n}\n}\n+ }\nreturn state;\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/types/message-types.js", "new_path": "lib/types/message-types.js", "diff": "@@ -595,7 +595,7 @@ export type SendTextMessagePayload = {|\n// Used for the message info included in log-in type actions and pings\nexport type GenericMessagesResult = {|\nmessageInfos: RawMessageInfo[],\n- truncationStatus: {[threadID: string]: MessageTruncationStatus},\n+ truncationStatus: MessageTruncationStatuses,\nwatchedIDsAtRequestTime: $ReadOnlyArray<string>,\ncurrentAsOf: number,\n|};\n" }, { "change_type": "MODIFY", "old_path": "lib/types/socket-types.js", "new_path": "lib/types/socket-types.js", "diff": "@@ -81,7 +81,9 @@ export type StateSyncFullActionPayload = {|\ncurrentUserInfo: CurrentUserInfo,\nrawEntryInfos: $ReadOnlyArray<RawEntryInfo>,\nuserInfos: $ReadOnlyArray<UserInfo>,\n+ updatesCurrentAsOf: number,\n|};\n+export const fullStateSyncActionPayload = \"FULL_STATE_SYNC\";\nexport type StateSyncFullSocketPayload = {|\n...StateSyncFullActionPayload,\ntype: 0,\n@@ -94,6 +96,7 @@ export type StateSyncIncrementalActionPayload = {|\ndeltaEntryInfos: $ReadOnlyArray<RawEntryInfo>,\nuserInfos: $ReadOnlyArray<UserInfo>,\n|};\n+export const incrementalStateSyncActionPayload = \"INCREMENTAL_STATE_SYNC\";\ntype StateSyncIncrementalSocketPayload = {|\ntype: 1,\n...StateSyncIncrementalActionPayload,\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/navigation-setup.js", "new_path": "native/navigation/navigation-setup.js", "diff": "@@ -44,7 +44,6 @@ import {\nregisterActionTypes,\nresetPasswordActionTypes,\n} from 'lib/actions/user-actions';\n-import { pingActionTypes } from 'lib/actions/ping-actions';\nimport {\nleaveThreadActionTypes,\ndeleteThreadActionTypes,\n" }, { "change_type": "MODIFY", "old_path": "native/redux-setup.js", "new_path": "native/redux-setup.js", "diff": "@@ -22,6 +22,7 @@ import { setDeviceTokenActionTypes } from 'lib/actions/device-actions';\nimport {\ntype ConnectionInfo,\ndefaultConnectionInfo,\n+ incrementalStateSyncActionPayload,\n} from 'lib/types/socket-types';\nimport React from 'react';\n@@ -43,7 +44,6 @@ import {\nsendMessageActionTypes,\nsaveMessagesActionType,\n} from 'lib/actions/message-actions';\n-import { pingActionTypes } from 'lib/actions/ping-actions';\nimport { reduxLoggerMiddleware } from 'lib/utils/redux-logger';\nimport { defaultCalendarQuery } from 'lib/selectors/nav-selectors';\n@@ -216,7 +216,7 @@ function reducer(state: AppState = defaultState, action: *) {\n...state,\ndeviceToken: action.payload,\n};\n- } else if (action.type === pingActionTypes.success) {\n+ } else if (action.type === incrementalStateSyncActionPayload) {\nlet wipeDeviceToken = false;\nfor (let update of action.payload.updatesResult.newUpdates) {\nif (\n" }, { "change_type": "MODIFY", "old_path": "server/src/socket.js", "new_path": "server/src/socket.js", "diff": "@@ -320,6 +320,7 @@ async function handleInitialClientSocketMessage(\n...entriesResult.userInfos,\n...threadsResult.userInfos,\n}),\n+ updatesCurrentAsOf: oldUpdatesCurrentAsOf,\n};\nif (viewer.sessionChanged) {\n// If initializeSession encounters sessionIdentifierTypes.BODY_SESSION_ID,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Replace ping reducers with socket reducers
129,187
18.10.2018 15:04:13
14,400
4711a9be6f840dc7fe1b4e7ba47d1dd58073e38a
Clear out some old ping stuff
[ { "change_type": "ADD", "old_path": null, "new_path": "lib/actions/activity-actions.js", "diff": "+// @flow\n+\n+import type { FetchJSON } from '../utils/fetch-json';\n+import type {\n+ ActivityUpdate,\n+ UpdateActivityResult,\n+} from '../types/activity-types';\n+\n+const updateActivityActionTypes = Object.freeze({\n+ started: \"UPDATE_ACTIVITY_STARTED\",\n+ success: \"UPDATE_ACTIVITY_SUCCESS\",\n+ failed: \"UPDATE_ACTIVITY_FAILED\",\n+});\n+async function updateActivity(\n+ fetchJSON: FetchJSON,\n+ activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n+): Promise<UpdateActivityResult> {\n+ const response = await fetchJSON(\n+ 'update_activity',\n+ { updates: activityUpdates },\n+ );\n+ return {\n+ unfocusedToUnread: response.unfocusedToUnread,\n+ };\n+}\n+\n+export {\n+ updateActivityActionTypes,\n+ updateActivity,\n+}\n" }, { "change_type": "DELETE", "old_path": "lib/actions/ping-actions.js", "new_path": null, "diff": "-// @flow\n-\n-import type { FetchJSON } from '../utils/fetch-json';\n-import {\n- type PingActionInput,\n- type PingResult,\n- pingResponseTypes,\n-} from '../types/ping-types';\n-import type {\n- ActivityUpdate,\n- UpdateActivityResult,\n-} from '../types/activity-types';\n-\n-import threadWatcher from '../shared/thread-watcher';\n-\n-const pingActionTypes = Object.freeze({\n- started: \"PING_STARTED\",\n- success: \"PING_SUCCESS\",\n- failed: \"PING_FAILED\",\n-});\n-async function ping(\n- fetchJSON: FetchJSON,\n- actionInput: PingActionInput,\n-): Promise<PingResult> {\n- const watchedIDs = threadWatcher.getWatchedIDs();\n- const response = await fetchJSON('ping', {\n- type: pingResponseTypes.INCREMENTAL,\n- calendarQuery: actionInput.calendarQuery,\n- messagesCurrentAsOf: actionInput.messagesCurrentAsOf,\n- updatesCurrentAsOf: actionInput.updatesCurrentAsOf,\n- clientResponses: actionInput.clientResponses,\n- watchedIDs,\n- });\n- if (!response.updatesResult) {\n- throw new Error(\"we have an anonymous cookie but think we're logged in\");\n- }\n- const requests = {\n- serverRequests: response.serverRequests ? response.serverRequests : [],\n- deliveredClientResponses: actionInput.clientResponses,\n- };\n- if (response.type === pingResponseTypes.INCREMENTAL) {\n- return {\n- type: pingResponseTypes.INCREMENTAL,\n- prevState: actionInput.prevState,\n- messagesResult: {\n- messageInfos: response.messagesResult.rawMessageInfos,\n- truncationStatus: response.messagesResult.truncationStatuses,\n- watchedIDsAtRequestTime: watchedIDs,\n- currentAsOf: response.messagesResult.currentAsOf,\n- },\n- updatesResult: response.updatesResult,\n- deltaEntryInfos: response.deltaEntryInfos,\n- calendarQuery: actionInput.calendarQuery,\n- userInfos: response.userInfos,\n- requests,\n- };\n- }\n- return {\n- type: pingResponseTypes.FULL,\n- threadInfos: response.threadInfos,\n- currentUserInfo: response.currentUserInfo,\n- calendarResult: {\n- calendarQuery: actionInput.calendarQuery,\n- rawEntryInfos: response.rawEntryInfos,\n- userInfos: response.userInfos,\n- },\n- messagesResult: {\n- messageInfos: response.rawMessageInfos,\n- truncationStatus: response.truncationStatuses,\n- watchedIDsAtRequestTime: watchedIDs,\n- currentAsOf: response.messagesCurrentAsOf,\n- },\n- userInfos: response.userInfos,\n- prevState: actionInput.prevState,\n- updatesResult: response.updatesResult,\n- requests,\n- };\n-}\n-\n-const updateActivityActionTypes = Object.freeze({\n- started: \"UPDATE_ACTIVITY_STARTED\",\n- success: \"UPDATE_ACTIVITY_SUCCESS\",\n- failed: \"UPDATE_ACTIVITY_FAILED\",\n-});\n-async function updateActivity(\n- fetchJSON: FetchJSON,\n- activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n-): Promise<UpdateActivityResult> {\n- const response = await fetchJSON(\n- 'update_activity',\n- { updates: activityUpdates },\n- );\n- return {\n- unfocusedToUnread: response.unfocusedToUnread,\n- };\n-}\n-\n-export {\n- pingActionTypes,\n- ping,\n- updateActivityActionTypes,\n- updateActivity,\n-}\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/thread-reducer.js", "new_path": "lib/reducers/thread-reducer.js", "diff": "@@ -35,7 +35,7 @@ import {\njoinThreadActionTypes,\nleaveThreadActionTypes,\n} from '../actions/thread-actions';\n-import { updateActivityActionTypes } from '../actions/ping-actions';\n+import { updateActivityActionTypes } from '../actions/activity-actions';\nimport { saveMessagesActionType } from '../actions/message-actions';\nimport { getConfig } from '../utils/config';\nimport { reduxLogger } from '../utils/redux-logger';\n" }, { "change_type": "ADD", "old_path": null, "new_path": "lib/shared/activity-utils.js", "diff": "+// @flow\n+\n+// We can't push yet, so we rely on pings to keep Redux state updated with the\n+// server. As a result, we do them fairly frequently (once every 3s) while the\n+// app is active and the user is logged in.\n+const pingFrequency = 3000; // in milliseconds\n+\n+// If the time column for a given entry in the focused table has a time later\n+// than this, then that entry is considered current, and consequently the thread\n+// in question is considered in focus.\n+function earliestTimeConsideredCurrent() {\n+ return Date.now() - pingFrequency - 1500;\n+}\n+\n+// If the time column for a given entry in the focused table has a time earlier\n+// than this, then that entry is considered expired, and consequently we will\n+// remove it from the table in the nightly cronjob.\n+function earliestTimeConsideredExpired() {\n+ return Date.now() - pingFrequency * 2 - 1500;\n+}\n+\n+export {\n+ pingFrequency,\n+ earliestTimeConsideredCurrent,\n+ earliestTimeConsideredExpired,\n+};\n" }, { "change_type": "DELETE", "old_path": "lib/shared/ping-utils.js", "new_path": null, "diff": "-// @flow\n-\n-import type {\n- PingStartingPayload,\n- PingActionInput,\n- PingResult,\n-} from '../types/ping-types';\n-import type { DispatchActionPromise } from '../utils/action-utils';\n-import { serverRequestTypes } from '../types/request-types';\n-\n-import { pingActionTypes } from '../actions/ping-actions';\n-\n-// We can't push yet, so we rely on pings to keep Redux state updated with the\n-// server. As a result, we do them fairly frequently (once every 3s) while the\n-// app is active and the user is logged in.\n-const pingFrequency = 3000; // in milliseconds\n-\n-// If the time column for a given entry in the focused table has a time later\n-// than this, then that entry is considered current, and consequently the thread\n-// in question is considered in focus.\n-function earliestTimeConsideredCurrent() {\n- return Date.now() - pingFrequency - 1500;\n-}\n-\n-// If the time column for a given entry in the focused table has a time earlier\n-// than this, then that entry is considered expired, and consequently we will\n-// remove it from the table in the nightly cronjob.\n-function earliestTimeConsideredExpired() {\n- return Date.now() - pingFrequency * 2 - 1500;\n-}\n-\n-type Props = {\n- pingStartingPayload: () => PingStartingPayload,\n- pingActionInput: (\n- startingPayload: PingStartingPayload,\n- justForegrounded: bool,\n- ) => PingActionInput,\n- loggedIn: bool,\n- // Redux dispatch functions\n- dispatchActionPromise: DispatchActionPromise,\n- // async functions that hit server APIs\n- ping: (actionInput: PingActionInput) => Promise<PingResult>,\n-};\n-function dispatchPing(props: Props, justForegrounded: bool) {\n- if (!props.loggedIn) {\n- return;\n- }\n- const startingPayload = props.pingStartingPayload();\n- const actionInput = props.pingActionInput(startingPayload, justForegrounded);\n- props.dispatchActionPromise(\n- pingActionTypes,\n- props.ping(actionInput),\n- undefined,\n- startingPayload,\n- );\n-}\n-\n-const pingActionInputSelector = (\n- activeThread: ?string,\n- actionInput: (startingPayload: PingStartingPayload) => PingActionInput,\n-) => (\n- startingPayload: PingStartingPayload,\n- justForegrounded: bool,\n-) => {\n- const genericActionInput = actionInput(startingPayload);\n- if (!justForegrounded || !activeThread) {\n- return genericActionInput;\n- }\n- return {\n- ...genericActionInput,\n- clientResponses: [\n- ...genericActionInput.clientResponses,\n- {\n- type: serverRequestTypes.INITIAL_ACTIVITY_UPDATES,\n- activityUpdates: [{\n- focus: true,\n- threadID: activeThread,\n- }],\n- },\n- ],\n- };\n-};\n-\n-export {\n- pingFrequency,\n- earliestTimeConsideredCurrent,\n- earliestTimeConsideredExpired,\n- dispatchPing,\n- pingActionInputSelector,\n-};\n" }, { "change_type": "MODIFY", "old_path": "lib/types/ping-types.js", "new_path": "lib/types/ping-types.js", "diff": "@@ -58,52 +58,3 @@ export type PingResponse =\nuserInfos: $ReadOnlyArray<UserInfo>,\nserverRequests: $ReadOnlyArray<ServerRequest>,\n|};\n-\n-export type PingPrevState = {|\n- threadInfos: {[id: string]: RawThreadInfo},\n- entryInfos: {[id: string]: RawEntryInfo},\n- currentUserInfo: ?CurrentUserInfo,\n-|};\n-\n-type ServerRequestPingResult = {|\n- serverRequests: $ReadOnlyArray<ServerRequest>,\n- deliveredClientResponses: $ReadOnlyArray<ClientResponse>,\n-|};\n-export type PingResult =\n- | {|\n- type: 0,\n- threadInfos: {[id: string]: RawThreadInfo},\n- currentUserInfo: CurrentUserInfo,\n- messagesResult: GenericMessagesResult,\n- calendarResult: CalendarResult,\n- userInfos: $ReadOnlyArray<UserInfo>,\n- prevState: PingPrevState,\n- updatesResult: UpdatesResult,\n- requests: ServerRequestPingResult,\n- |}\n- | {|\n- type: 1,\n- prevState: PingPrevState,\n- messagesResult: GenericMessagesResult,\n- updatesResult: UpdatesResult,\n- deltaEntryInfos: $ReadOnlyArray<RawEntryInfo>,\n- calendarQuery: CalendarQuery,\n- userInfos: $ReadOnlyArray<UserInfo>,\n- requests: ServerRequestPingResult,\n- |};\n-\n-export type PingStartingPayload = {|\n- calendarQuery: CalendarQuery,\n- time: number,\n- messageStorePruneRequest?: {\n- threadIDs: $ReadOnlyArray<string>,\n- },\n-|};\n-\n-export type PingActionInput = {|\n- calendarQuery: CalendarQuery,\n- messagesCurrentAsOf: number,\n- updatesCurrentAsOf: number,\n- prevState: PingPrevState,\n- clientResponses: $ReadOnlyArray<ClientResponse>,\n-|};\n" }, { "change_type": "MODIFY", "old_path": "lib/types/redux-types.js", "new_path": "lib/types/redux-types.js", "diff": "@@ -32,10 +32,6 @@ import type {\nRegisterResult,\n} from './account-types';\nimport type { UserSearchResult } from '../types/search-types';\n-import type {\n- PingStartingPayload,\n- PingResult,\n-} from './ping-types';\nimport type {\nMessageStore,\nRawTextMessageInfo,\n@@ -366,19 +362,6 @@ export type BaseAction =\n|} | {|\ntype: \"SET_NEW_SESSION\",\npayload: SetSessionPayload,\n- |} | {|\n- type: \"PING_STARTED\",\n- payload: PingStartingPayload,\n- loadingInfo: LoadingInfo,\n- |} | {|\n- type: \"PING_FAILED\",\n- error: true,\n- payload: Error,\n- loadingInfo: LoadingInfo,\n- |} | {|\n- type: \"PING_SUCCESS\",\n- payload: PingResult,\n- loadingInfo: LoadingInfo,\n|} | {|\ntype: \"FETCH_ENTRIES_AND_APPEND_RANGE_STARTED\",\nloadingInfo: LoadingInfo,\n" }, { "change_type": "MODIFY", "old_path": "native/app.react.js", "new_path": "native/app.react.js", "diff": "@@ -50,7 +50,7 @@ import { connect } from 'lib/utils/redux-utils';\nimport {\nupdateActivityActionTypes,\nupdateActivity,\n-} from 'lib/actions/ping-actions';\n+} from 'lib/actions/activity-actions';\nimport {\nsetDeviceTokenActionTypes,\nsetDeviceToken,\n" }, { "change_type": "DELETE", "old_path": "native/flow-typed/npm/lib_vx.x.x.js", "new_path": null, "diff": "-// flow-typed signature: 955b997194be0a642942a3fbe859dd03\n-// flow-typed version: <<STUB>>/lib_v0.0.1/flow_v0.78.0\n-\n-/**\n- * This is an autogenerated libdef stub for:\n- *\n- * 'lib'\n- *\n- * Fill this stub out by replacing all the `any` types.\n- *\n- * Once filled out, we encourage you to share your work with the\n- * community by sending a pull request to:\n- * https://github.com/flowtype/flow-typed\n- */\n-\n-declare module 'lib' {\n- declare module.exports: any;\n-}\n-\n-/**\n- * We include stubs for each file inside this npm package in case you need to\n- * require those files directly. Feel free to delete any files that aren't\n- * needed.\n- */\n-declare module 'lib/actions/device-actions' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/actions/entry-actions' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/actions/message-actions' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/actions/ping-actions' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/actions/report-actions' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/actions/thread-actions' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/actions/user-actions' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/flow-typed/npm/color_vx.x.x' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/flow-typed/npm/dateformat_v2.x.x' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/flow-typed/npm/fast-json-stable-stringify_vx.x.x' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/flow-typed/npm/flow_vx.x.x' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/flow-typed/npm/flow-bin_v0.x.x' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/flow-typed/npm/invariant_v2.x.x' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/flow-typed/npm/isomorphic-fetch_v2.x.x' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/flow-typed/npm/lodash_v4.x.x' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/flow-typed/npm/prop-types_v15.x.x' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/flow-typed/npm/react-redux_v5.x.x' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/flow-typed/npm/redux_v3.x.x' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/flow-typed/npm/reselect_v3.x.x' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/flow-typed/npm/string-hash_vx.x.x' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/flow-typed/npm/tokenize-text_vx.x.x' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/flow-typed/npm/whatwg-fetch_vx.x.x' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/permissions/thread-permissions' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/reducers/calendar-filters-reducer' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/reducers/draft-reducer' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/reducers/entry-reducer' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/reducers/loading-reducer' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/reducers/master-reducer' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/reducers/message-reducer' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/reducers/nav-reducer' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/reducers/ping-timestamps-reducer' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/reducers/server-requests-reducer' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/reducers/thread-reducer' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/reducers/updates-reducer' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/reducers/url-prefix-reducer' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/reducers/user-reducer' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/selectors/account-selectors' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/selectors/calendar-filter-selectors' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/selectors/calendar-selectors' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/selectors/chat-selectors' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/selectors/loading-selectors' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/selectors/nav-selectors' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/selectors/ping-selectors' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/selectors/thread-selectors' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/selectors/user-selectors' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/shared/account-regexes' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/shared/core' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/shared/emojis' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/shared/entry-utils' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/shared/message-utils' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/shared/notif-utils' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/shared/ping-utils' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/shared/search-index' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/shared/search-utils' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/shared/thread-utils' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/shared/thread-watcher' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/shared/update-utils' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/shared/user-utils' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/types/account-types' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/types/activity-types' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/types/device-types' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/types/endpoints' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/types/entry-types' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/types/filter-types' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/types/history-types' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/types/loading-types' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/types/message-types' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/types/nav-types' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/types/ping-types' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/types/redux-types' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/types/report-types' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/types/request-types' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/types/search-types' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/types/session-types' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/types/subscription-types' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/types/thread-types' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/types/update-types' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/types/user-types' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/types/verify-types' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/utils/action-utils' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/utils/config' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/utils/date-utils' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/utils/errors' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/utils/fetch-json' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/utils/local-ids' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/utils/objects' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/utils/promises' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/utils/redux-logger' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/utils/redux-utils' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/utils/sleep' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/utils/text-utils' {\n- declare module.exports: any;\n-}\n-\n-declare module 'lib/utils/url-utils' {\n- declare module.exports: any;\n-}\n-\n-// Filename aliases\n-declare module 'lib/actions/device-actions.js' {\n- declare module.exports: $Exports<'lib/actions/device-actions'>;\n-}\n-declare module 'lib/actions/entry-actions.js' {\n- declare module.exports: $Exports<'lib/actions/entry-actions'>;\n-}\n-declare module 'lib/actions/message-actions.js' {\n- declare module.exports: $Exports<'lib/actions/message-actions'>;\n-}\n-declare module 'lib/actions/ping-actions.js' {\n- declare module.exports: $Exports<'lib/actions/ping-actions'>;\n-}\n-declare module 'lib/actions/report-actions.js' {\n- declare module.exports: $Exports<'lib/actions/report-actions'>;\n-}\n-declare module 'lib/actions/thread-actions.js' {\n- declare module.exports: $Exports<'lib/actions/thread-actions'>;\n-}\n-declare module 'lib/actions/user-actions.js' {\n- declare module.exports: $Exports<'lib/actions/user-actions'>;\n-}\n-declare module 'lib/flow-typed/npm/color_vx.x.x.js' {\n- declare module.exports: $Exports<'lib/flow-typed/npm/color_vx.x.x'>;\n-}\n-declare module 'lib/flow-typed/npm/dateformat_v2.x.x.js' {\n- declare module.exports: $Exports<'lib/flow-typed/npm/dateformat_v2.x.x'>;\n-}\n-declare module 'lib/flow-typed/npm/fast-json-stable-stringify_vx.x.x.js' {\n- declare module.exports: $Exports<'lib/flow-typed/npm/fast-json-stable-stringify_vx.x.x'>;\n-}\n-declare module 'lib/flow-typed/npm/flow_vx.x.x.js' {\n- declare module.exports: $Exports<'lib/flow-typed/npm/flow_vx.x.x'>;\n-}\n-declare module 'lib/flow-typed/npm/flow-bin_v0.x.x.js' {\n- declare module.exports: $Exports<'lib/flow-typed/npm/flow-bin_v0.x.x'>;\n-}\n-declare module 'lib/flow-typed/npm/invariant_v2.x.x.js' {\n- declare module.exports: $Exports<'lib/flow-typed/npm/invariant_v2.x.x'>;\n-}\n-declare module 'lib/flow-typed/npm/isomorphic-fetch_v2.x.x.js' {\n- declare module.exports: $Exports<'lib/flow-typed/npm/isomorphic-fetch_v2.x.x'>;\n-}\n-declare module 'lib/flow-typed/npm/lodash_v4.x.x.js' {\n- declare module.exports: $Exports<'lib/flow-typed/npm/lodash_v4.x.x'>;\n-}\n-declare module 'lib/flow-typed/npm/prop-types_v15.x.x.js' {\n- declare module.exports: $Exports<'lib/flow-typed/npm/prop-types_v15.x.x'>;\n-}\n-declare module 'lib/flow-typed/npm/react-redux_v5.x.x.js' {\n- declare module.exports: $Exports<'lib/flow-typed/npm/react-redux_v5.x.x'>;\n-}\n-declare module 'lib/flow-typed/npm/redux_v3.x.x.js' {\n- declare module.exports: $Exports<'lib/flow-typed/npm/redux_v3.x.x'>;\n-}\n-declare module 'lib/flow-typed/npm/reselect_v3.x.x.js' {\n- declare module.exports: $Exports<'lib/flow-typed/npm/reselect_v3.x.x'>;\n-}\n-declare module 'lib/flow-typed/npm/string-hash_vx.x.x.js' {\n- declare module.exports: $Exports<'lib/flow-typed/npm/string-hash_vx.x.x'>;\n-}\n-declare module 'lib/flow-typed/npm/tokenize-text_vx.x.x.js' {\n- declare module.exports: $Exports<'lib/flow-typed/npm/tokenize-text_vx.x.x'>;\n-}\n-declare module 'lib/flow-typed/npm/whatwg-fetch_vx.x.x.js' {\n- declare module.exports: $Exports<'lib/flow-typed/npm/whatwg-fetch_vx.x.x'>;\n-}\n-declare module 'lib/permissions/thread-permissions.js' {\n- declare module.exports: $Exports<'lib/permissions/thread-permissions'>;\n-}\n-declare module 'lib/reducers/calendar-filters-reducer.js' {\n- declare module.exports: $Exports<'lib/reducers/calendar-filters-reducer'>;\n-}\n-declare module 'lib/reducers/draft-reducer.js' {\n- declare module.exports: $Exports<'lib/reducers/draft-reducer'>;\n-}\n-declare module 'lib/reducers/entry-reducer.js' {\n- declare module.exports: $Exports<'lib/reducers/entry-reducer'>;\n-}\n-declare module 'lib/reducers/loading-reducer.js' {\n- declare module.exports: $Exports<'lib/reducers/loading-reducer'>;\n-}\n-declare module 'lib/reducers/master-reducer.js' {\n- declare module.exports: $Exports<'lib/reducers/master-reducer'>;\n-}\n-declare module 'lib/reducers/message-reducer.js' {\n- declare module.exports: $Exports<'lib/reducers/message-reducer'>;\n-}\n-declare module 'lib/reducers/nav-reducer.js' {\n- declare module.exports: $Exports<'lib/reducers/nav-reducer'>;\n-}\n-declare module 'lib/reducers/ping-timestamps-reducer.js' {\n- declare module.exports: $Exports<'lib/reducers/ping-timestamps-reducer'>;\n-}\n-declare module 'lib/reducers/server-requests-reducer.js' {\n- declare module.exports: $Exports<'lib/reducers/server-requests-reducer'>;\n-}\n-declare module 'lib/reducers/thread-reducer.js' {\n- declare module.exports: $Exports<'lib/reducers/thread-reducer'>;\n-}\n-declare module 'lib/reducers/updates-reducer.js' {\n- declare module.exports: $Exports<'lib/reducers/updates-reducer'>;\n-}\n-declare module 'lib/reducers/url-prefix-reducer.js' {\n- declare module.exports: $Exports<'lib/reducers/url-prefix-reducer'>;\n-}\n-declare module 'lib/reducers/user-reducer.js' {\n- declare module.exports: $Exports<'lib/reducers/user-reducer'>;\n-}\n-declare module 'lib/selectors/account-selectors.js' {\n- declare module.exports: $Exports<'lib/selectors/account-selectors'>;\n-}\n-declare module 'lib/selectors/calendar-filter-selectors.js' {\n- declare module.exports: $Exports<'lib/selectors/calendar-filter-selectors'>;\n-}\n-declare module 'lib/selectors/calendar-selectors.js' {\n- declare module.exports: $Exports<'lib/selectors/calendar-selectors'>;\n-}\n-declare module 'lib/selectors/chat-selectors.js' {\n- declare module.exports: $Exports<'lib/selectors/chat-selectors'>;\n-}\n-declare module 'lib/selectors/loading-selectors.js' {\n- declare module.exports: $Exports<'lib/selectors/loading-selectors'>;\n-}\n-declare module 'lib/selectors/nav-selectors.js' {\n- declare module.exports: $Exports<'lib/selectors/nav-selectors'>;\n-}\n-declare module 'lib/selectors/ping-selectors.js' {\n- declare module.exports: $Exports<'lib/selectors/ping-selectors'>;\n-}\n-declare module 'lib/selectors/thread-selectors.js' {\n- declare module.exports: $Exports<'lib/selectors/thread-selectors'>;\n-}\n-declare module 'lib/selectors/user-selectors.js' {\n- declare module.exports: $Exports<'lib/selectors/user-selectors'>;\n-}\n-declare module 'lib/shared/account-regexes.js' {\n- declare module.exports: $Exports<'lib/shared/account-regexes'>;\n-}\n-declare module 'lib/shared/core.js' {\n- declare module.exports: $Exports<'lib/shared/core'>;\n-}\n-declare module 'lib/shared/emojis.js' {\n- declare module.exports: $Exports<'lib/shared/emojis'>;\n-}\n-declare module 'lib/shared/entry-utils.js' {\n- declare module.exports: $Exports<'lib/shared/entry-utils'>;\n-}\n-declare module 'lib/shared/message-utils.js' {\n- declare module.exports: $Exports<'lib/shared/message-utils'>;\n-}\n-declare module 'lib/shared/notif-utils.js' {\n- declare module.exports: $Exports<'lib/shared/notif-utils'>;\n-}\n-declare module 'lib/shared/ping-utils.js' {\n- declare module.exports: $Exports<'lib/shared/ping-utils'>;\n-}\n-declare module 'lib/shared/search-index.js' {\n- declare module.exports: $Exports<'lib/shared/search-index'>;\n-}\n-declare module 'lib/shared/search-utils.js' {\n- declare module.exports: $Exports<'lib/shared/search-utils'>;\n-}\n-declare module 'lib/shared/thread-utils.js' {\n- declare module.exports: $Exports<'lib/shared/thread-utils'>;\n-}\n-declare module 'lib/shared/thread-watcher.js' {\n- declare module.exports: $Exports<'lib/shared/thread-watcher'>;\n-}\n-declare module 'lib/shared/update-utils.js' {\n- declare module.exports: $Exports<'lib/shared/update-utils'>;\n-}\n-declare module 'lib/shared/user-utils.js' {\n- declare module.exports: $Exports<'lib/shared/user-utils'>;\n-}\n-declare module 'lib/types/account-types.js' {\n- declare module.exports: $Exports<'lib/types/account-types'>;\n-}\n-declare module 'lib/types/activity-types.js' {\n- declare module.exports: $Exports<'lib/types/activity-types'>;\n-}\n-declare module 'lib/types/device-types.js' {\n- declare module.exports: $Exports<'lib/types/device-types'>;\n-}\n-declare module 'lib/types/endpoints.js' {\n- declare module.exports: $Exports<'lib/types/endpoints'>;\n-}\n-declare module 'lib/types/entry-types.js' {\n- declare module.exports: $Exports<'lib/types/entry-types'>;\n-}\n-declare module 'lib/types/filter-types.js' {\n- declare module.exports: $Exports<'lib/types/filter-types'>;\n-}\n-declare module 'lib/types/history-types.js' {\n- declare module.exports: $Exports<'lib/types/history-types'>;\n-}\n-declare module 'lib/types/loading-types.js' {\n- declare module.exports: $Exports<'lib/types/loading-types'>;\n-}\n-declare module 'lib/types/message-types.js' {\n- declare module.exports: $Exports<'lib/types/message-types'>;\n-}\n-declare module 'lib/types/nav-types.js' {\n- declare module.exports: $Exports<'lib/types/nav-types'>;\n-}\n-declare module 'lib/types/ping-types.js' {\n- declare module.exports: $Exports<'lib/types/ping-types'>;\n-}\n-declare module 'lib/types/redux-types.js' {\n- declare module.exports: $Exports<'lib/types/redux-types'>;\n-}\n-declare module 'lib/types/report-types.js' {\n- declare module.exports: $Exports<'lib/types/report-types'>;\n-}\n-declare module 'lib/types/request-types.js' {\n- declare module.exports: $Exports<'lib/types/request-types'>;\n-}\n-declare module 'lib/types/search-types.js' {\n- declare module.exports: $Exports<'lib/types/search-types'>;\n-}\n-declare module 'lib/types/session-types.js' {\n- declare module.exports: $Exports<'lib/types/session-types'>;\n-}\n-declare module 'lib/types/subscription-types.js' {\n- declare module.exports: $Exports<'lib/types/subscription-types'>;\n-}\n-declare module 'lib/types/thread-types.js' {\n- declare module.exports: $Exports<'lib/types/thread-types'>;\n-}\n-declare module 'lib/types/update-types.js' {\n- declare module.exports: $Exports<'lib/types/update-types'>;\n-}\n-declare module 'lib/types/user-types.js' {\n- declare module.exports: $Exports<'lib/types/user-types'>;\n-}\n-declare module 'lib/types/verify-types.js' {\n- declare module.exports: $Exports<'lib/types/verify-types'>;\n-}\n-declare module 'lib/utils/action-utils.js' {\n- declare module.exports: $Exports<'lib/utils/action-utils'>;\n-}\n-declare module 'lib/utils/config.js' {\n- declare module.exports: $Exports<'lib/utils/config'>;\n-}\n-declare module 'lib/utils/date-utils.js' {\n- declare module.exports: $Exports<'lib/utils/date-utils'>;\n-}\n-declare module 'lib/utils/errors.js' {\n- declare module.exports: $Exports<'lib/utils/errors'>;\n-}\n-declare module 'lib/utils/fetch-json.js' {\n- declare module.exports: $Exports<'lib/utils/fetch-json'>;\n-}\n-declare module 'lib/utils/local-ids.js' {\n- declare module.exports: $Exports<'lib/utils/local-ids'>;\n-}\n-declare module 'lib/utils/objects.js' {\n- declare module.exports: $Exports<'lib/utils/objects'>;\n-}\n-declare module 'lib/utils/promises.js' {\n- declare module.exports: $Exports<'lib/utils/promises'>;\n-}\n-declare module 'lib/utils/redux-logger.js' {\n- declare module.exports: $Exports<'lib/utils/redux-logger'>;\n-}\n-declare module 'lib/utils/redux-utils.js' {\n- declare module.exports: $Exports<'lib/utils/redux-utils'>;\n-}\n-declare module 'lib/utils/sleep.js' {\n- declare module.exports: $Exports<'lib/utils/sleep'>;\n-}\n-declare module 'lib/utils/text-utils.js' {\n- declare module.exports: $Exports<'lib/utils/text-utils'>;\n-}\n-declare module 'lib/utils/url-utils.js' {\n- declare module.exports: $Exports<'lib/utils/url-utils'>;\n-}\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/message-creator.js", "new_path": "server/src/creators/message-creator.js", "diff": "@@ -16,7 +16,7 @@ import {\nmessageTypeGeneratesNotifs,\nshimUnsupportedRawMessageInfos,\n} from 'lib/shared/message-utils';\n-import { earliestTimeConsideredCurrent } from 'lib/shared/ping-utils';\n+import { earliestTimeConsideredCurrent } from 'lib/shared/activity-utils';\nimport { permissionLookup } from 'lib/permissions/thread-permissions';\nimport {\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/report-creator.js", "new_path": "server/src/creators/report-creator.js", "diff": "@@ -9,12 +9,10 @@ import {\nreportTypes,\n} from 'lib/types/report-types';\nimport { messageTypes } from 'lib/types/message-types';\n-import { pingResponseTypes } from 'lib/types/ping-types';\nimport bots from 'lib/facts/bots';\nimport _isEqual from 'lodash/fp/isEqual';\n-import { pingActionTypes } from 'lib/actions/ping-actions';\nimport { filterRawEntryInfosByCalendarQuery } from 'lib/shared/entry-utils';\nimport { dbQuery, SQL } from '../database';\n@@ -94,9 +92,6 @@ async function ignoreReport(\nviewer: Viewer,\nrequest: ReportCreationRequest,\n): Promise<bool> {\n- if (ignoreKnownInconsistencyReport(request)) {\n- return true;\n- }\n// The below logic is to avoid duplicate inconsistency reports\nif (\nrequest.type !== reportTypes.THREAD_INCONSISTENCY &&\n@@ -119,42 +114,6 @@ async function ignoreReport(\nreturn result.length !== 0;\n}\n-// Currently this only ignores cases that are the result of the thread-reducer\n-// conditional with the comment above that starts with \"If the thread at the\"\n-function ignoreKnownInconsistencyReport(request: ReportCreationRequest): bool {\n- if (request.type !== reportTypes.THREAD_INCONSISTENCY) {\n- return false;\n- }\n- if (request.action.type !== pingActionTypes.success) {\n- return false;\n- }\n- const { payload } = request.action;\n- if (payload.type !== pingResponseTypes.FULL) {\n- return false;\n- }\n- const { beforeAction, pollResult, pushResult } = request;\n- const payloadThreadInfos = payload.threadInfos;\n- const prevStateThreadInfos = payload.prevState.threadInfos;\n- const nonMatchingThreadIDs = getInconsistentThreadIDsFromReport(request);\n- for (let threadID of nonMatchingThreadIDs) {\n- const newThreadInfo = payloadThreadInfos[threadID];\n- const prevThreadInfo = prevStateThreadInfos[threadID];\n- if (!_isEqual(prevThreadInfo)(newThreadInfo)) {\n- return false;\n- }\n- const currentThreadInfo = beforeAction[threadID];\n- const pollThreadInfo = pollResult[threadID];\n- if (!_isEqual(currentThreadInfo)(pollThreadInfo)) {\n- return false;\n- }\n- const pushThreadInfo = pushResult[threadID];\n- if (!_isEqual(pushThreadInfo)(newThreadInfo)) {\n- return false;\n- }\n- }\n- return true;\n-}\n-\nfunction getSquadbotMessage(\nrequest: ReportCreationRequest,\nreportID: string,\n" }, { "change_type": "MODIFY", "old_path": "server/src/deleters/activity-deleters.js", "new_path": "server/src/deleters/activity-deleters.js", "diff": "// @flow\n-import { earliestTimeConsideredExpired } from 'lib/shared/ping-utils';\n+import { earliestTimeConsideredExpired } from 'lib/shared/activity-utils';\nimport { dbQuery, SQL } from '../database';\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/activity-updaters.js", "new_path": "server/src/updaters/activity-updaters.js", "diff": "@@ -12,7 +12,7 @@ import { updateTypes } from 'lib/types/update-types';\nimport invariant from 'invariant';\nimport _difference from 'lodash/fp/difference';\n-import { earliestTimeConsideredCurrent } from 'lib/shared/ping-utils';\n+import { earliestTimeConsideredCurrent } from 'lib/shared/activity-utils';\nimport { ServerError } from 'lib/utils/errors';\nimport { dbQuery, SQL, mergeOrConditions } from '../database';\n" }, { "change_type": "MODIFY", "old_path": "web/app.react.js", "new_path": "web/app.react.js", "diff": "@@ -51,7 +51,7 @@ import {\nimport {\nupdateActivityActionTypes,\nupdateActivity,\n-} from 'lib/actions/ping-actions';\n+} from 'lib/actions/activity-actions';\nimport { activeThreadSelector } from './selectors/nav-selectors';\nimport { canonicalURLFromReduxState, navInfoFromURL } from './url-utils';\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Clear out some old ping stuff
129,187
19.10.2018 16:53:42
14,400
e84b4ddb522a770d8079a0c5e4c1d03cf5fb60ed
[server] Sanitize cookie from input validation error logs Using the same mechanism we used for sanitizing passwords
[ { "change_type": "MODIFY", "old_path": "server/src/session/cookies.js", "new_path": "server/src/session/cookies.js", "diff": "@@ -316,7 +316,7 @@ async function fetchViewerFromRequestBody(\nsessionIdentifierType: sessionParameterInfo.sessionIdentifierType,\n};\n}\n- if (!cookiePair || !(typeof cookiePair === \"string\")) {\n+ if (!cookiePair || typeof cookiePair !== \"string\") {\nreturn {\ntype: \"nonexistant\",\ncookieName: null,\n" }, { "change_type": "MODIFY", "old_path": "server/src/socket.js", "new_path": "server/src/socket.js", "diff": "@@ -32,6 +32,7 @@ import {\ncheckInputValidator,\ncheckClientSupported,\ntShape,\n+ tCookie,\n} from './utils/validation-utils';\nimport {\nnewEntryQueryInputValidator,\n@@ -68,7 +69,7 @@ const clientSocketMessageInputValidator = t.union([\nid: t.Number,\npayload: tShape({\nsessionIdentification: tShape({\n- cookie: t.maybe(t.String),\n+ cookie: t.maybe(tCookie),\nsessionID: t.maybe(t.String),\n}),\nsessionState: tShape({\n" }, { "change_type": "MODIFY", "old_path": "server/src/utils/validation-utils.js", "new_path": "server/src/utils/validation-utils.js", "diff": "@@ -8,6 +8,48 @@ import { ServerError } from 'lib/utils/errors';\nimport { verifyClientSupported } from '../session/version';\n+function tBool(value: bool) {\n+ return t.irreducible('literal bool', x => x === value);\n+}\n+\n+function tString(value: string) {\n+ return t.irreducible('literal string', x => x === value);\n+}\n+\n+function tShape(spec: {[key: string]: *}) {\n+ return t.interface(spec, { strict: true });\n+}\n+\n+function tRegex(regex: RegExp) {\n+ return t.refinement(t.String, val => regex.test(val));\n+}\n+\n+function tNumEnum(assertFunc: (input: number) => *) {\n+ return t.refinement(\n+ t.Number,\n+ (input: number) => {\n+ try {\n+ assertFunc(input);\n+ return true;\n+ } catch (e) {\n+ return false;\n+ }\n+ },\n+ );\n+}\n+\n+const tDate = tRegex(/^[0-9]{4}-[0-1][0-9]-[0-3][0-9]$/);\n+const tColor = tRegex(/^[a-fA-F0-9]{6}$/); // we don't include # char\n+const tPlatform = t.enums.of(['ios', 'android', 'web']);\n+const tDeviceType = t.enums.of(['ios', 'android']);\n+const tPlatformDetails = tShape({\n+ platform: tPlatform,\n+ codeVersion: t.maybe(t.Number),\n+ stateVersion: t.maybe(t.Number),\n+});\n+const tPassword = t.refinement(t.String, (password: string) => password);\n+const tCookie = tRegex(/^(user|anonymous)=[0-9]+:[0-9a-f]+$/);\n+\nasync function validateInput(viewer: Viewer, inputValidator: *, input: *) {\nawait checkClientSupported(viewer, inputValidator, input);\ncheckInputValidator(inputValidator, input);\n@@ -47,20 +89,21 @@ async function checkClientSupported(viewer: Viewer, inputValidator: *, input: *)\nawait verifyClientSupported(viewer, platformDetails);\n}\n-const fakePassword = \"********\";\n+const redactedString = \"********\";\n+const redactedTypes = [ tPassword, tCookie ];\nfunction sanitizeInput(inputValidator: *, input: *) {\nif (!inputValidator) {\nreturn input;\n}\n- if (inputValidator === tPassword && typeof input === \"string\") {\n- return fakePassword;\n+ if (redactedTypes.includes(inputValidator) && typeof input === \"string\") {\n+ return redactedString;\n}\nif (\ninputValidator.meta.kind === \"maybe\" &&\n- inputValidator.meta.type === tPassword &&\n+ redactedTypes.includes(inputValidator.meta.type) &&\ntypeof input === \"string\"\n) {\n- return fakePassword;\n+ return redactedString;\n}\nif (\ninputValidator.meta.kind !== \"interface\" ||\n@@ -146,51 +189,7 @@ function findFirstInputMatchingValidator(\nreturn null;\n}\n-function tBool(value: bool) {\n- return t.irreducible('literal bool', x => x === value);\n-}\n-\n-function tString(value: string) {\n- return t.irreducible('literal string', x => x === value);\n-}\n-\n-function tShape(spec: {[key: string]: *}) {\n- return t.interface(spec, { strict: true });\n-}\n-\n-function tRegex(regex: RegExp) {\n- return t.refinement(t.String, val => regex.test(val));\n-}\n-\n-function tNumEnum(assertFunc: (input: number) => *) {\n- return t.refinement(\n- t.Number,\n- (input: number) => {\n- try {\n- assertFunc(input);\n- return true;\n- } catch (e) {\n- return false;\n- }\n- },\n- );\n-}\n-\n-const tDate = tRegex(/^[0-9]{4}-[0-1][0-9]-[0-3][0-9]$/);\n-const tColor = tRegex(/^[a-fA-F0-9]{6}$/); // we don't include # char\n-const tPlatform = t.enums.of(['ios', 'android', 'web']);\n-const tDeviceType = t.enums.of(['ios', 'android']);\n-const tPlatformDetails = tShape({\n- platform: tPlatform,\n- codeVersion: t.maybe(t.Number),\n- stateVersion: t.maybe(t.Number),\n-});\n-const tPassword = t.refinement(t.String, (password: string) => password);\n-\nexport {\n- validateInput,\n- checkInputValidator,\n- checkClientSupported,\ntBool,\ntString,\ntShape,\n@@ -202,4 +201,8 @@ export {\ntDeviceType,\ntPlatformDetails,\ntPassword,\n+ tCookie,\n+ validateInput,\n+ checkInputValidator,\n+ checkClientSupported,\n};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Sanitize cookie from input validation error logs Using the same mechanism we used for sanitizing passwords
129,187
19.10.2018 17:21:35
14,400
96a81e51124af7d19f90ea8f36d09d1c1b13d30a
[server] Delete all entries in focused table for session when closing socket
[ { "change_type": "MODIFY", "old_path": "lib/components/socket.react.js", "new_path": "lib/components/socket.react.js", "diff": "@@ -78,7 +78,7 @@ class Socket extends React.PureComponent<Props> {\nclientResponsesInTransit: SentClientResponse[] = [];\nopenSocket() {\n- if (this.socket) {\n+ if (this.socket && this.socket.readyState < 2) {\nthis.socket.close();\n}\nconst socket = this.props.openSocket();\n" }, { "change_type": "MODIFY", "old_path": "server/src/deleters/activity-deleters.js", "new_path": "server/src/deleters/activity-deleters.js", "diff": "// @flow\n+import type { Viewer } from '../session/viewer';\n+\nimport { earliestTimeConsideredExpired } from 'lib/shared/activity-utils';\nimport { dbQuery, SQL } from '../database';\n+async function deleteForViewerSession(\n+ viewer: Viewer,\n+ beforeTime?: number,\n+): Promise<void> {\n+ const query = SQL`\n+ DELETE FROM focused\n+ WHERE user = ${viewer.userID} AND session = ${viewer.session}\n+ `;\n+ if (beforeTime !== undefined) {\n+ query.append(SQL`AND time < ${beforeTime}`);\n+ }\n+ await dbQuery(query);\n+}\n+\nasync function deleteOrphanedFocused(): Promise<void> {\nconst time = earliestTimeConsideredExpired();\nawait dbQuery(SQL`\n@@ -17,5 +33,6 @@ async function deleteOrphanedFocused(): Promise<void> {\n}\nexport {\n+ deleteForViewerSession,\ndeleteOrphanedFocused,\n};\n" }, { "change_type": "MODIFY", "old_path": "server/src/socket.js", "new_path": "server/src/socket.js", "diff": "@@ -59,6 +59,7 @@ import { commitSessionUpdate } from './updaters/session-updaters';\nimport { handleAsyncPromise } from './responders/handlers';\nimport { deleteCookie } from './deleters/cookie-deleters';\nimport { createNewAnonymousCookie } from './session/cookies';\n+import { deleteForViewerSession } from './deleters/activity-deleters';\nconst clientSocketMessageInputValidator = t.union([\ntShape({\n@@ -233,8 +234,10 @@ function onConnection(ws: WebSocket, req: $Request) {\n}\n}\n});\n- ws.on('close', () => {\n- console.log('connection closed');\n+ ws.on('close', async () => {\n+ if (viewer && viewer.hasSessionInfo) {\n+ await deleteForViewerSession(viewer);\n+ }\n});\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/activity-updaters.js", "new_path": "server/src/updaters/activity-updaters.js", "diff": "@@ -19,6 +19,7 @@ import { dbQuery, SQL, mergeOrConditions } from '../database';\nimport { verifyThreadIDs } from '../fetchers/thread-fetchers';\nimport { rescindPushNotifs } from '../push/rescind';\nimport { createUpdates } from '../creators/update-creator';\n+import { deleteForViewerSession } from '../deleters/activity-deleters';\nasync function activityUpdater(\nviewer: Viewer,\n@@ -138,11 +139,7 @@ async function updateFocusedRows(\nON DUPLICATE KEY UPDATE time = VALUES(time)\n`);\n}\n- await dbQuery(SQL`\n- DELETE FROM focused\n- WHERE user = ${viewer.userID} AND session = ${viewer.session}\n- AND time < ${time}\n- `);\n+ await deleteForViewerSession(viewer, time);\n}\n// To protect against a possible race condition, we reset the thread to unread\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Delete all entries in focused table for session when closing socket
129,187
20.10.2018 20:42:33
14,400
63cf65d2a6fe2d3f635428637f7a77fcd854bab9
*StateSyncActionPayload -> *StateSyncActionType (typo fix)
[ { "change_type": "MODIFY", "old_path": "lib/components/socket.react.js", "new_path": "lib/components/socket.react.js", "diff": "@@ -18,8 +18,8 @@ import {\nserverSocketMessageTypes,\ntype ServerSocketMessage,\nstateSyncPayloadTypes,\n- fullStateSyncActionPayload,\n- incrementalStateSyncActionPayload,\n+ fullStateSyncActionType,\n+ incrementalStateSyncActionType,\n} from '../types/socket-types';\nimport type { Dispatch } from '../types/redux-types';\nimport type { DispatchActionPayload } from '../utils/action-utils';\n@@ -177,7 +177,7 @@ class Socket extends React.PureComponent<Props> {\nif (message.payload.type === stateSyncPayloadTypes.FULL) {\nconst { sessionID, type, ...actionPayload } = message.payload;\nthis.props.dispatchActionPayload(\n- fullStateSyncActionPayload,\n+ fullStateSyncActionType,\nactionPayload,\n);\nif (sessionID !== null && sessionID !== undefined) {\n@@ -192,7 +192,7 @@ class Socket extends React.PureComponent<Props> {\n} else {\nconst { type, ...actionPayload } = message.payload;\nthis.props.dispatchActionPayload(\n- incrementalStateSyncActionPayload,\n+ incrementalStateSyncActionType,\nactionPayload,\n);\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/calendar-filters-reducer.js", "new_path": "lib/reducers/calendar-filters-reducer.js", "diff": "@@ -12,8 +12,8 @@ import type { BaseAction } from '../types/redux-types';\nimport type { RawThreadInfo } from '../types/thread-types';\nimport { updateTypes, type UpdateInfo } from '../types/update-types';\nimport {\n- fullStateSyncActionPayload,\n- incrementalStateSyncActionPayload,\n+ fullStateSyncActionType,\n+ incrementalStateSyncActionType,\n} from '../types/socket-types';\nimport {\n@@ -87,12 +87,12 @@ export default function reduceCalendarFilters(\nstate,\naction.payload.updatesResult.newUpdates,\n);\n- } else if (action.type === incrementalStateSyncActionPayload) {\n+ } else if (action.type === incrementalStateSyncActionType) {\nreturn updateFilterListFromUpdateInfos(\nstate,\naction.payload.updatesResult.newUpdates,\n);\n- } else if (action.type === fullStateSyncActionPayload) {\n+ } else if (action.type === fullStateSyncActionType) {\nreturn removeDeletedThreadIDsFromFilterList(\nstate,\naction.payload.threadInfos,\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/entry-reducer.js", "new_path": "lib/reducers/entry-reducer.js", "diff": "@@ -17,8 +17,8 @@ import {\nprocessServerRequestsActionType,\n} from '../types/request-types';\nimport {\n- fullStateSyncActionPayload,\n- incrementalStateSyncActionPayload,\n+ fullStateSyncActionType,\n+ incrementalStateSyncActionType,\n} from '../types/socket-types';\nimport _flow from 'lodash/fp/flow';\n@@ -616,7 +616,7 @@ function reduceEntryInfos(\ninconsistencyResponses,\n};\n}\n- } else if (action.type === incrementalStateSyncActionPayload) {\n+ } else if (action.type === incrementalStateSyncActionType) {\nconst updateEntryInfos = mergeUpdateEntryInfos(\naction.payload.deltaEntryInfos,\naction.payload.updatesResult.newUpdates,\n@@ -633,7 +633,7 @@ function reduceEntryInfos(\nlastUserInteractionCalendar,\ninconsistencyResponses,\n};\n- } else if (action.type === fullStateSyncActionPayload) {\n+ } else if (action.type === fullStateSyncActionType) {\nconst [ updatedEntryInfos, updatedDaysToEntries ] = mergeNewEntryInfos(\nentryInfos,\naction.payload.rawEntryInfos,\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/message-reducer.js", "new_path": "lib/reducers/message-reducer.js", "diff": "@@ -14,8 +14,8 @@ import type { BaseAction } from '../types/redux-types';\nimport { type RawThreadInfo, threadPermissions } from '../types/thread-types';\nimport { type UpdateInfo, updateTypes } from '../types/update-types';\nimport {\n- fullStateSyncActionPayload,\n- incrementalStateSyncActionPayload,\n+ fullStateSyncActionType,\n+ incrementalStateSyncActionType,\n} from '../types/socket-types';\nimport invariant from 'invariant';\n@@ -356,7 +356,7 @@ function reduceMessageStore(\nmessagesResult.currentAsOf,\nnewThreadInfos,\n);\n- } else if (action.type === incrementalStateSyncActionPayload) {\n+ } else if (action.type === incrementalStateSyncActionType) {\nif (\naction.payload.messagesResult.rawMessageInfos.length === 0 &&\naction.payload.updatesResult.newUpdates.length === 0\n@@ -379,7 +379,7 @@ function reduceMessageStore(\nthreads: newMessageStore.threads,\ncurrentAsOf: messagesResult.currentAsOf,\n};\n- } else if (action.type === fullStateSyncActionPayload) {\n+ } else if (action.type === fullStateSyncActionType) {\nconst { messagesResult } = action.payload;\nconst newMessageStore = mergeNewMessages(\nmessageStore,\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/thread-reducer.js", "new_path": "lib/reducers/thread-reducer.js", "diff": "@@ -10,8 +10,8 @@ import {\nprocessServerRequestsActionType,\n} from '../types/request-types';\nimport {\n- fullStateSyncActionPayload,\n- incrementalStateSyncActionPayload,\n+ fullStateSyncActionType,\n+ incrementalStateSyncActionType,\n} from '../types/socket-types';\nimport invariant from 'invariant';\n@@ -137,7 +137,7 @@ export default function reduceThreadInfos(\naction.type === logInActionTypes.success ||\naction.type === registerActionTypes.success ||\naction.type === resetPasswordActionTypes.success ||\n- action.type === fullStateSyncActionPayload\n+ action.type === fullStateSyncActionType\n) {\nif (_isEqual(state.threadInfos)(action.payload.threadInfos)) {\nreturn state;\n@@ -187,7 +187,7 @@ export default function reduceThreadInfos(\n),\n],\n};\n- } else if (action.type === incrementalStateSyncActionPayload) {\n+ } else if (action.type === incrementalStateSyncActionType) {\nconst updateResult = reduceThreadUpdates(state.threadInfos, action.payload);\nreturn {\nthreadInfos: updateResult,\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/updates-reducer.js", "new_path": "lib/reducers/updates-reducer.js", "diff": "@@ -10,8 +10,8 @@ import {\n} from '../actions/user-actions';\nimport threadWatcher from '../shared/thread-watcher';\nimport {\n- fullStateSyncActionPayload,\n- incrementalStateSyncActionPayload,\n+ fullStateSyncActionType,\n+ incrementalStateSyncActionType,\n} from '../types/socket-types';\nfunction reduceUpdatesCurrentAsOf(\n@@ -23,9 +23,9 @@ function reduceUpdatesCurrentAsOf(\naction.type === resetPasswordActionTypes.success\n) {\nreturn action.payload.updatesCurrentAsOf;\n- } else if (action.type === fullStateSyncActionPayload) {\n+ } else if (action.type === fullStateSyncActionType) {\nreturn action.payload.updatesCurrentAsOf;\n- } else if (action.type === incrementalStateSyncActionPayload) {\n+ } else if (action.type === incrementalStateSyncActionType) {\nreturn action.payload.updatesResult.currentAsOf;\n}\nreturn currentAsOf;\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/user-reducer.js", "new_path": "lib/reducers/user-reducer.js", "diff": "@@ -9,8 +9,8 @@ import {\nprocessServerRequestsActionType,\n} from '../types/request-types';\nimport {\n- fullStateSyncActionPayload,\n- incrementalStateSyncActionPayload,\n+ fullStateSyncActionType,\n+ incrementalStateSyncActionType,\n} from '../types/socket-types';\nimport invariant from 'invariant';\n@@ -63,12 +63,12 @@ function reduceCurrentUserInfo(\nif (!_isEqual(sessionChange.currentUserInfo)(state)) {\nreturn sessionChange.currentUserInfo;\n}\n- } else if (action.type === fullStateSyncActionPayload) {\n+ } else if (action.type === fullStateSyncActionType) {\nconst { currentUserInfo } = action.payload;\nif (!_isEqual(currentUserInfo)(state)) {\nreturn currentUserInfo;\n}\n- } else if (action.type === incrementalStateSyncActionPayload) {\n+ } else if (action.type === incrementalStateSyncActionType) {\nfor (let update of action.payload.updatesResult.newUpdates) {\nif (\nupdate.type === updateTypes.UPDATE_CURRENT_USER &&\n@@ -139,13 +139,13 @@ function reduceUserInfos(\naction.type === logInActionTypes.success ||\naction.type === registerActionTypes.success ||\naction.type === resetPasswordActionTypes.success ||\n- action.type === fullStateSyncActionPayload\n+ action.type === fullStateSyncActionType\n) {\nconst newUserInfos = _keyBy('id')(action.payload.userInfos);\nif (!_isEqual(state)(newUserInfos)) {\nreturn newUserInfos;\n}\n- } else if (action.type === incrementalStateSyncActionPayload) {\n+ } else if (action.type === incrementalStateSyncActionType) {\nconst newUserInfos = _keyBy('id')(action.payload.userInfos);\nconst updated = { ...state, ...newUserInfos };\nfor (let update of action.payload.updatesResult.newUpdates) {\n" }, { "change_type": "MODIFY", "old_path": "lib/types/socket-types.js", "new_path": "lib/types/socket-types.js", "diff": "@@ -83,7 +83,7 @@ export type StateSyncFullActionPayload = {|\nuserInfos: $ReadOnlyArray<UserInfo>,\nupdatesCurrentAsOf: number,\n|};\n-export const fullStateSyncActionPayload = \"FULL_STATE_SYNC\";\n+export const fullStateSyncActionType = \"FULL_STATE_SYNC\";\nexport type StateSyncFullSocketPayload = {|\n...StateSyncFullActionPayload,\ntype: 0,\n@@ -96,7 +96,7 @@ export type StateSyncIncrementalActionPayload = {|\ndeltaEntryInfos: $ReadOnlyArray<RawEntryInfo>,\nuserInfos: $ReadOnlyArray<UserInfo>,\n|};\n-export const incrementalStateSyncActionPayload = \"INCREMENTAL_STATE_SYNC\";\n+export const incrementalStateSyncActionType = \"INCREMENTAL_STATE_SYNC\";\ntype StateSyncIncrementalSocketPayload = {|\ntype: 1,\n...StateSyncIncrementalActionPayload,\n" }, { "change_type": "MODIFY", "old_path": "native/redux-setup.js", "new_path": "native/redux-setup.js", "diff": "@@ -22,7 +22,7 @@ import { setDeviceTokenActionTypes } from 'lib/actions/device-actions';\nimport {\ntype ConnectionInfo,\ndefaultConnectionInfo,\n- incrementalStateSyncActionPayload,\n+ incrementalStateSyncActionType,\n} from 'lib/types/socket-types';\nimport React from 'react';\n@@ -216,7 +216,7 @@ function reducer(state: AppState = defaultState, action: *) {\n...state,\ndeviceToken: action.payload,\n};\n- } else if (action.type === incrementalStateSyncActionPayload) {\n+ } else if (action.type === incrementalStateSyncActionType) {\nlet wipeDeviceToken = false;\nfor (let update of action.payload.updatesResult.newUpdates) {\nif (\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
*StateSyncActionPayload -> *StateSyncActionType (typo fix)
129,187
20.10.2018 20:49:53
14,400
34cedc0b27c585891b893c7b8c8be71b2f59e3b0
[lib] Redux actions and reducer for connection status
[ { "change_type": "MODIFY", "old_path": "lib/components/socket.react.js", "new_path": "lib/components/socket.react.js", "diff": "@@ -20,6 +20,7 @@ import {\nstateSyncPayloadTypes,\nfullStateSyncActionType,\nincrementalStateSyncActionType,\n+ updateConnectionStatusActionType,\n} from '../types/socket-types';\nimport type { Dispatch } from '../types/redux-types';\nimport type { DispatchActionPayload } from '../utils/action-utils';\n@@ -81,6 +82,10 @@ class Socket extends React.PureComponent<Props> {\nif (this.socket && this.socket.readyState < 2) {\nthis.socket.close();\n}\n+ this.props.dispatchActionPayload(\n+ updateConnectionStatusActionType,\n+ { status: \"connecting\" },\n+ );\nconst socket = this.props.openSocket();\nsocket.onopen = this.sendInitialMessage;\nsocket.onmessage = this.receiveMessage;\n@@ -92,6 +97,10 @@ class Socket extends React.PureComponent<Props> {\ncloseSocket() {\nthis.socketInitializedAndActive = false;\nregisterActiveWebSocket(null);\n+ this.props.dispatchActionPayload(\n+ updateConnectionStatusActionType,\n+ { status: \"disconnecting\" },\n+ );\nif (this.socket) {\nif (this.socket.readyState < 2) {\n// If it's not closing already, close it\n@@ -104,6 +113,10 @@ class Socket extends React.PureComponent<Props> {\nmarkSocketInitialized() {\nthis.socketInitializedAndActive = true;\nregisterActiveWebSocket(this.socket);\n+ this.props.dispatchActionPayload(\n+ updateConnectionStatusActionType,\n+ { status: \"connected\" },\n+ );\n// In case any ClientResponses have accumulated in Redux while we were\n// initializing\nthis.possiblySendReduxClientResponses();\n" }, { "change_type": "ADD", "old_path": null, "new_path": "lib/reducers/connection-reducer.js", "diff": "+// @flow\n+\n+import type { BaseAction } from '../types/redux-types';\n+import {\n+ type ConnectionInfo,\n+ updateConnectionStatusActionType,\n+} from '../types/socket-types';\n+\n+export default function reduceConnectionInfo(\n+ state: ConnectionInfo,\n+ action: BaseAction,\n+): ConnectionInfo {\n+ if (action.type === updateConnectionStatusActionType) {\n+ return { ...state, status: action.payload.status };\n+ }\n+ return state;\n+}\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/master-reducer.js", "new_path": "lib/reducers/master-reducer.js", "diff": "@@ -15,6 +15,7 @@ import reduceUpdatesCurrentAsOf from './updates-reducer';\nimport { reduceDrafts } from './draft-reducer';\nimport reduceURLPrefix from './url-prefix-reducer';\nimport reduceCalendarFilters from './calendar-filters-reducer';\n+import reduceConnectionInfo from './connection-reducer';\nexport default function baseReducer<N: BaseNavInfo, T: BaseAppState<N>>(\nstate: T,\n@@ -53,5 +54,6 @@ export default function baseReducer<N: BaseNavInfo, T: BaseAppState<N>>(\nstate.calendarFilters,\naction,\n),\n+ connection: reduceConnectionInfo(state.connection, action),\n};\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/types/redux-types.js", "new_path": "lib/types/redux-types.js", "diff": "@@ -57,6 +57,7 @@ import type {\nConnectionInfo,\nStateSyncFullActionPayload,\nStateSyncIncrementalActionPayload,\n+ UpdateConnectionStatusPayload,\n} from '../types/socket-types';\nexport type BaseAppState<NavInfo: BaseNavInfo> = {\n@@ -534,6 +535,9 @@ export type BaseAction =\n|} | {|\ntype: \"PROCESS_SERVER_REQUESTS\",\npayload: ProcessServerRequestsPayload,\n+ |} | {|\n+ type: \"UPDATE_CONNECTION_STATUS\",\n+ payload: UpdateConnectionStatusPayload,\n|};\nexport type ActionPayload\n" }, { "change_type": "MODIFY", "old_path": "lib/types/socket-types.js", "new_path": "lib/types/socket-types.js", "diff": "@@ -144,6 +144,8 @@ export type ConnectionStatus =\n| \"connecting\"\n| \"connected\"\n| \"reconnecting\"\n+ | \"disconnecting\"\n+ | \"forcedDisconnecting\"\n| \"disconnected\";\nexport type ConnectionInfo = {|\nstatus: ConnectionStatus,\n@@ -151,3 +153,7 @@ export type ConnectionInfo = {|\nexport const defaultConnectionInfo = {\nstatus: \"connecting\",\n};\n+export const updateConnectionStatusActionType = \"UPDATE_CONNECTION_STATUS\";\n+export type UpdateConnectionStatusPayload = {|\n+ status: ConnectionStatus,\n+|};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Redux actions and reducer for connection status
129,187
21.10.2018 15:56:35
14,400
fd0f8ec680c908631d7ac8e25e87fb215adb9276
Redux state for queuing activity updates
[ { "change_type": "MODIFY", "old_path": "lib/reducers/connection-reducer.js", "new_path": "lib/reducers/connection-reducer.js", "diff": "@@ -4,6 +4,8 @@ import type { BaseAction } from '../types/redux-types';\nimport {\ntype ConnectionInfo,\nupdateConnectionStatusActionType,\n+ queueActivityUpdateActionType,\n+ clearQueuedActivityUpdatesActionType,\n} from '../types/socket-types';\nexport default function reduceConnectionInfo(\n@@ -12,6 +14,16 @@ export default function reduceConnectionInfo(\n): ConnectionInfo {\nif (action.type === updateConnectionStatusActionType) {\nreturn { ...state, status: action.payload.status };\n+ } else if (action.type === queueActivityUpdateActionType) {\n+ return {\n+ ...state,\n+ queuedActivityUpdates: [\n+ ...state.queuedActivityUpdates,\n+ action.payload.activityUpdate,\n+ ],\n+ };\n+ } else if (action.type === clearQueuedActivityUpdatesActionType) {\n+ return { ...state, queuedActivityUpdates: [] };\n}\nreturn state;\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/types/redux-types.js", "new_path": "lib/types/redux-types.js", "diff": "@@ -58,6 +58,8 @@ import type {\nStateSyncFullActionPayload,\nStateSyncIncrementalActionPayload,\nUpdateConnectionStatusPayload,\n+ QueueActivityUpdatePayload,\n+ ClearActivityUpdatesPayload,\n} from '../types/socket-types';\nexport type BaseAppState<NavInfo: BaseNavInfo> = {\n@@ -538,6 +540,12 @@ export type BaseAction =\n|} | {|\ntype: \"UPDATE_CONNECTION_STATUS\",\npayload: UpdateConnectionStatusPayload,\n+ |} | {|\n+ type: \"QUEUE_ACTIVITY_UPDATE\",\n+ payload: QueueActivityUpdatePayload,\n+ |} | {|\n+ type: \"CLEAR_QUEUED_ACTIVITY_UPDATES\",\n+ payload: ClearActivityUpdatesPayload,\n|};\nexport type ActionPayload\n" }, { "change_type": "MODIFY", "old_path": "lib/types/socket-types.js", "new_path": "lib/types/socket-types.js", "diff": "@@ -11,6 +11,7 @@ import type {\nLoggedOutUserInfo,\n} from './user-types';\nimport type { RawEntryInfo } from './entry-types';\n+import type { ActivityUpdate } from './activity-types';\nimport invariant from 'invariant';\n@@ -149,11 +150,22 @@ export type ConnectionStatus =\n| \"disconnected\";\nexport type ConnectionInfo = {|\nstatus: ConnectionStatus,\n+ queuedActivityUpdates: $ReadOnlyArray<ActivityUpdate>,\n|};\nexport const defaultConnectionInfo = {\nstatus: \"connecting\",\n+ queuedActivityUpdates: [],\n};\nexport const updateConnectionStatusActionType = \"UPDATE_CONNECTION_STATUS\";\nexport type UpdateConnectionStatusPayload = {|\nstatus: ConnectionStatus,\n|};\n+export const queueActivityUpdateActionType = \"QUEUE_ACTIVITY_UPDATE\";\n+export type QueueActivityUpdatePayload = {|\n+ activityUpdate: ActivityUpdate,\n+|};\n+export const clearQueuedActivityUpdatesActionType =\n+ \"CLEAR_QUEUED_ACTIVITY_UPDATES\";\n+export type ClearActivityUpdatesPayload = {|\n+ activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n+|};\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/action-types.js", "new_path": "native/navigation/action-types.js", "diff": "@@ -5,6 +5,8 @@ export const navigateToAppActionType = \"NAVIGATE_TO_APP\";\nexport const backgroundActionType = \"BACKGROUND\";\nexport const foregroundActionType = \"FOREGROUND\";\nexport const resetUserStateActionType = \"RESET_USER_STATE\";\n-export const recordNotifPermissionAlertActionType = \"RECORD_NOTIF_PERMISSION_ALERT\";\n-export const recordAndroidNotificationActionType = \"RECORD_ANDROID_NOTIFICATION\";\n+export const recordNotifPermissionAlertActionType =\n+ \"RECORD_NOTIF_PERMISSION_ALERT\";\n+export const recordAndroidNotificationActionType =\n+ \"RECORD_ANDROID_NOTIFICATION\";\nexport const clearAndroidNotificationActionType = \"CLEAR_ANDROID_NOTIFICATION\";\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Redux state for queuing activity updates
129,187
21.10.2018 21:16:46
14,400
af3b7658886c1f787eff20c957f64fa52f42949b
Retry delivering client responses if it triggers an error
[ { "change_type": "MODIFY", "old_path": "lib/components/socket.react.js", "new_path": "lib/components/socket.react.js", "diff": "@@ -186,7 +186,7 @@ class Socket extends React.PureComponent<Props> {\nreturn;\n}\nif (message.type === serverSocketMessageTypes.STATE_SYNC) {\n- this.clearDeliveredClientResponses(message.responseTo);\n+ this.handleResponseToClientResponses(true, message.responseTo);\nif (message.payload.type === stateSyncPayloadTypes.FULL) {\nconst { sessionID, type, ...actionPayload } = message.payload;\nthis.props.dispatchActionPayload(\n@@ -211,7 +211,7 @@ class Socket extends React.PureComponent<Props> {\n}\nthis.markSocketInitialized();\n} else if (message.type === serverSocketMessageTypes.REQUESTS) {\n- this.clearDeliveredClientResponses(message.responseTo);\n+ this.handleResponseToClientResponses(true, message.responseTo);\nconst { serverRequests } = message.payload;\nthis.processServerRequests(serverRequests);\nconst clientResponses = this.props.getClientResponses(serverRequests);\n@@ -219,7 +219,7 @@ class Socket extends React.PureComponent<Props> {\n} else if (message.type === serverSocketMessageTypes.ERROR) {\nconst { message: errorMessage, payload, responseTo } = message;\nif (responseTo !== null && responseTo !== undefined) {\n- this.clearDeliveredClientResponses(responseTo);\n+ this.handleResponseToClientResponses(false, message.responseTo);\n}\nif (payload) {\nconsole.warn(`socket sent error ${errorMessage} with payload`, payload);\n@@ -353,7 +353,7 @@ class Socket extends React.PureComponent<Props> {\nreturn filtered;\n}\n- clearDeliveredClientResponses(messageID: number) {\n+ handleResponseToClientResponses(success: bool, messageID: number) {\nconst deliveredClientResponses = [], clientResponsesStillInTransit = [];\nfor (let sentClientResponse of this.clientResponsesInTransit) {\nif (sentClientResponse.messageID === messageID) {\n@@ -365,9 +365,10 @@ class Socket extends React.PureComponent<Props> {\nif (deliveredClientResponses.length === 0) {\nreturn;\n}\n+ if (success) {\n// Note: it's hypothetically possible for something to call\n// possiblySendReduxClientResponses after we update\n- // this.clientResponsesInTransit below but before the Redux action below\n+ // this.clientResponsesInTransit below but before this Redux action\n// propagates to this component. In that case, we could double-send some\n// Redux-cached ClientResponses. Since right now only inconsistency\n// responses are Redux-cached, and the server knows how to dedup those so\n@@ -377,6 +378,10 @@ class Socket extends React.PureComponent<Props> {\n{ clientResponses: deliveredClientResponses },\n);\nthis.clientResponsesInTransit = clientResponsesStillInTransit;\n+ } else {\n+ this.clientResponsesInTransit = clientResponsesStillInTransit;\n+ this.possiblySendReduxClientResponses();\n+ }\n}\nprocessServerRequests(serverRequests: $ReadOnlyArray<ServerRequest>) {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Retry delivering client responses if it triggers an error
129,187
21.10.2018 21:47:35
14,400
6efcf9769b69aa14d90cd0722be5e493e8579125
Only retry delivery for each ClientResponse once Otherwise we'll get an infinite loop.
[ { "change_type": "MODIFY", "old_path": "lib/components/socket.react.js", "new_path": "lib/components/socket.react.js", "diff": "@@ -38,7 +38,9 @@ import {\n} from '../utils/action-utils';\nimport { socketAuthErrorResolutionAttempt } from '../actions/user-actions';\n-type SentClientResponse = { clientResponse: ClientResponse, messageID: number };\n+type ClientResponseTransitStatus =\n+ | {| status: \"inflight\", clientResponse: ClientResponse, messageID: number |}\n+ | {| status: \"errored\", clientResponse: ClientResponse, messageID?: number |};\ntype Props = {|\nactive: bool,\n@@ -76,7 +78,7 @@ class Socket extends React.PureComponent<Props> {\ninitialPlatformDetailsSent = false;\nnextClientMessageID = 0;\nsocketInitializedAndActive = false;\n- clientResponsesInTransit: SentClientResponse[] = [];\n+ clientResponseTransitStatuses: ClientResponseTransitStatus[] = [];\nopenSocket() {\nif (this.socket && this.socket.readyState < 2) {\n@@ -91,7 +93,7 @@ class Socket extends React.PureComponent<Props> {\nsocket.onmessage = this.receiveMessage;\nsocket.onclose = this.onClose;\nthis.socket = socket;\n- this.clientResponsesInTransit = [];\n+ this.clientResponseTransitStatuses = [];\n}\ncloseSocket() {\n@@ -219,7 +221,7 @@ class Socket extends React.PureComponent<Props> {\n} else if (message.type === serverSocketMessageTypes.ERROR) {\nconst { message: errorMessage, payload, responseTo } = message;\nif (responseTo !== null && responseTo !== undefined) {\n- this.handleResponseToClientResponses(false, message.responseTo);\n+ this.handleResponseToClientResponses(false, responseTo);\n}\nif (payload) {\nconsole.warn(`socket sent error ${errorMessage} with payload`, payload);\n@@ -328,10 +330,45 @@ class Socket extends React.PureComponent<Props> {\n// We want to avoid double-sending the ClientResponses we cache in Redux\n// (namely, the inconsistency responses), so we mark them as in-transit once\n// they're sent\n+ if (clientResponses.length === 0) {\n+ return;\n+ }\n+ const errored = [];\n+ const newTransitStatuses = this.clientResponseTransitStatuses.filter(\n+ transitStatus => {\n+ let matches = false;\n+ for (let clientResponse of clientResponses) {\n+ if (clientResponse === transitStatus.clientResponse) {\n+ matches = true;\n+ break;\n+ }\n+ }\n+ if (!matches) {\n+ return true;\n+ }\n+ if (transitStatus.status === \"errored\") {\n+ errored.push(transitStatus.clientResponse);\n+ }\n+ return false;\n+ },\n+ );\nfor (let clientResponse of clientResponses) {\n- this.clientResponsesInTransit.push({ clientResponse, messageID });\n+ if (errored.includes(clientResponse)) {\n+ newTransitStatuses.push({\n+ status: \"errored\",\n+ clientResponse,\n+ messageID,\n+ });\n+ } else {\n+ newTransitStatuses.push({\n+ status: \"inflight\",\n+ clientResponse,\n+ messageID,\n+ });\n}\n}\n+ this.clientResponseTransitStatuses = newTransitStatuses;\n+ }\nfilterInTransitClientResponses(\nclientResponses: $ReadOnlyArray<ClientResponse>,\n@@ -339,9 +376,17 @@ class Socket extends React.PureComponent<Props> {\nconst filtered = [];\nfor (let clientResponse of clientResponses) {\nlet inTransit = false;\n- for (let sentClientResponse of this.clientResponsesInTransit) {\n- const { clientResponse: inTransitClientResponse } = sentClientResponse;\n- if (inTransitClientResponse === clientResponse) {\n+ for (\n+ let clientResponseTransitStatus of this.clientResponseTransitStatuses\n+ ) {\n+ const {\n+ clientResponse: inTransitClientResponse,\n+ messageID,\n+ } = clientResponseTransitStatus;\n+ if (\n+ inTransitClientResponse === clientResponse &&\n+ messageID !== null && messageID !== undefined\n+ ) {\ninTransit = true;\nbreak;\n}\n@@ -354,33 +399,51 @@ class Socket extends React.PureComponent<Props> {\n}\nhandleResponseToClientResponses(success: bool, messageID: number) {\n- const deliveredClientResponses = [], clientResponsesStillInTransit = [];\n- for (let sentClientResponse of this.clientResponsesInTransit) {\n- if (sentClientResponse.messageID === messageID) {\n- deliveredClientResponses.push(sentClientResponse.clientResponse);\n+ const deliveredResponses = [], erroredStatuses = [], stillInTransit = [];\n+ for (\n+ let clientResponseTransitStatus of this.clientResponseTransitStatuses\n+ ) {\n+ if (clientResponseTransitStatus.messageID === messageID) {\n+ if (success || clientResponseTransitStatus.status === \"errored\") {\n+ deliveredResponses.push(clientResponseTransitStatus.clientResponse);\n} else {\n- clientResponsesStillInTransit.push(sentClientResponse);\n+ erroredStatuses.push(clientResponseTransitStatus);\n}\n+ } else {\n+ stillInTransit.push(clientResponseTransitStatus);\n}\n- if (deliveredClientResponses.length === 0) {\n- return;\n}\n- if (success) {\n+\n+ if (deliveredResponses.length > 0) {\n// Note: it's hypothetically possible for something to call\n// possiblySendReduxClientResponses after we update\n- // this.clientResponsesInTransit below but before this Redux action\n+ // this.clientResponseTransitStatuses below but before this Redux action\n// propagates to this component. In that case, we could double-send some\n// Redux-cached ClientResponses. Since right now only inconsistency\n// responses are Redux-cached, and the server knows how to dedup those so\n// that the transaction is idempotent, we're not going to worry about it.\nthis.props.dispatchActionPayload(\nclearDeliveredClientResponsesActionType,\n- { clientResponses: deliveredClientResponses },\n+ { clientResponses: deliveredResponses },\n);\n- this.clientResponsesInTransit = clientResponsesStillInTransit;\n- } else {\n- this.clientResponsesInTransit = clientResponsesStillInTransit;\n- this.possiblySendReduxClientResponses();\n+ }\n+\n+ if (erroredStatuses.length > 0) {\n+ const newTransitStatuses = erroredStatuses.map(transitStatus => ({\n+ // Mark our second attempt as already \"errored\" so they get\n+ // filtered out on the next cycle\n+ status: \"errored\",\n+ clientResponse: transitStatus.clientResponse,\n+ }));\n+ this.clientResponseTransitStatuses = [\n+ ...stillInTransit,\n+ ...newTransitStatuses,\n+ ],\n+ this.sendClientResponses(\n+ newTransitStatuses.map(transitStatus => transitStatus.clientResponse),\n+ );\n+ } else if (deliveredResponses.length > 0) {\n+ this.clientResponseTransitStatuses = stillInTransit;\n}\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Only retry delivery for each ClientResponse once Otherwise we'll get an infinite loop.
129,187
22.10.2018 01:13:02
14,400
43cd1f67980816e85715e23a03bc8ff88c8cfe21
[server] Store queuedActivityUpdates in Redux Also introduces shared `TransitStatus` type to track inflight requests.
[ { "change_type": "MODIFY", "old_path": "lib/components/socket.react.js", "new_path": "lib/components/socket.react.js", "diff": "@@ -21,7 +21,12 @@ import {\nfullStateSyncActionType,\nincrementalStateSyncActionType,\nupdateConnectionStatusActionType,\n+ connectionInfoPropType,\n+ type ConnectionInfo,\n+ queueActivityUpdateActionType,\n+ clearQueuedActivityUpdatesActionType,\n} from '../types/socket-types';\n+import type { ActivityUpdate } from '../types/activity-types';\nimport type { Dispatch } from '../types/redux-types';\nimport type { DispatchActionPayload } from '../utils/action-utils';\nimport type { LogInExtraInfo } from '../types/account-types';\n@@ -38,9 +43,32 @@ import {\n} from '../utils/action-utils';\nimport { socketAuthErrorResolutionAttempt } from '../actions/user-actions';\n-type ClientResponseTransitStatus =\n- | {| status: \"inflight\", clientResponse: ClientResponse, messageID: number |}\n- | {| status: \"errored\", clientResponse: ClientResponse, messageID?: number |};\n+type TransitStatus =\n+ | {|\n+ type: \"ClientResponse\",\n+ status: \"inflight\",\n+ clientResponse: ClientResponse,\n+ // Socket message ID, not chat message\n+ messageID: number,\n+ |}\n+ | {|\n+ type: \"ClientResponse\",\n+ status: \"errored\",\n+ clientResponse: ClientResponse,\n+ messageID?: number,\n+ |}\n+ | {|\n+ type: \"ActivityUpdate\",\n+ status: \"inflight\",\n+ activityUpdate: ActivityUpdate,\n+ messageID: number,\n+ |}\n+ | {|\n+ type: \"ActivityUpdate\",\n+ status: \"errored\",\n+ activityUpdate: ActivityUpdate,\n+ messageID?: number,\n+ |};\ntype Props = {|\nactive: bool,\n@@ -55,6 +83,7 @@ type Props = {|\ncookie: ?string,\nurlPrefix: string,\nlogInExtraInfo: () => LogInExtraInfo,\n+ connection: ConnectionInfo,\n// Redux dispatch functions\ndispatch: Dispatch,\ndispatchActionPayload: DispatchActionPayload,\n@@ -71,6 +100,7 @@ class Socket extends React.PureComponent<Props> {\ncookie: PropTypes.string,\nurlPrefix: PropTypes.string.isRequired,\nlogInExtraInfo: PropTypes.func.isRequired,\n+ connection: connectionInfoPropType.isRequired,\ndispatch: PropTypes.func.isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\n};\n@@ -78,12 +108,23 @@ class Socket extends React.PureComponent<Props> {\ninitialPlatformDetailsSent = false;\nnextClientMessageID = 0;\nsocketInitializedAndActive = false;\n- clientResponseTransitStatuses: ClientResponseTransitStatus[] = [];\n+ transitStatuses: TransitStatus[] = [];\nopenSocket() {\nif (this.socket && this.socket.readyState < 2) {\nthis.socket.close();\n}\n+ if (this.props.activeThread) {\n+ this.props.dispatchActionPayload(\n+ queueActivityUpdateActionType,\n+ {\n+ activityUpdate: {\n+ focus: true,\n+ threadID: this.props.activeThread,\n+ },\n+ },\n+ );\n+ }\nthis.props.dispatchActionPayload(\nupdateConnectionStatusActionType,\n{ status: \"connecting\" },\n@@ -93,7 +134,7 @@ class Socket extends React.PureComponent<Props> {\nsocket.onmessage = this.receiveMessage;\nsocket.onclose = this.onClose;\nthis.socket = socket;\n- this.clientResponseTransitStatuses = [];\n+ this.transitStatuses = [];\n}\ncloseSocket() {\n@@ -188,7 +229,7 @@ class Socket extends React.PureComponent<Props> {\nreturn;\n}\nif (message.type === serverSocketMessageTypes.STATE_SYNC) {\n- this.handleResponseToClientResponses(true, message.responseTo);\n+ this.updateTransitStatusesWithServerResponse(true, message.responseTo);\nif (message.payload.type === stateSyncPayloadTypes.FULL) {\nconst { sessionID, type, ...actionPayload } = message.payload;\nthis.props.dispatchActionPayload(\n@@ -213,7 +254,7 @@ class Socket extends React.PureComponent<Props> {\n}\nthis.markSocketInitialized();\n} else if (message.type === serverSocketMessageTypes.REQUESTS) {\n- this.handleResponseToClientResponses(true, message.responseTo);\n+ this.updateTransitStatusesWithServerResponse(true, message.responseTo);\nconst { serverRequests } = message.payload;\nthis.processServerRequests(serverRequests);\nconst clientResponses = this.props.getClientResponses(serverRequests);\n@@ -221,7 +262,7 @@ class Socket extends React.PureComponent<Props> {\n} else if (message.type === serverSocketMessageTypes.ERROR) {\nconst { message: errorMessage, payload, responseTo } = message;\nif (responseTo !== null && responseTo !== undefined) {\n- this.handleResponseToClientResponses(false, responseTo);\n+ this.updateTransitStatusesWithServerResponse(false, responseTo);\n}\nif (payload) {\nconsole.warn(`socket sent error ${errorMessage} with payload`, payload);\n@@ -260,32 +301,33 @@ class Socket extends React.PureComponent<Props> {\n}\nsendInitialMessage = () => {\n+ const messageID = this.nextClientMessageID++;\n+\nconst baseClientResponses = this.props.getClientResponses();\n- const clientResponses = [ ...baseClientResponses ];\n- if (this.props.activeThread) {\n- clientResponses.push({\n- type: serverRequestTypes.INITIAL_ACTIVITY_UPDATES,\n- activityUpdates: [{\n- focus: true,\n- threadID: this.props.activeThread,\n- }],\n- });\n- }\n- const responsesIncludePlatformDetails = clientResponses.some(\n+ const nonActivityClientResponses = [ ...baseClientResponses ];\n+ const responsesIncludePlatformDetails = nonActivityClientResponses.some(\nresponse => response.type === serverRequestTypes.PLATFORM_DETAILS,\n);\nif (!this.initialPlatformDetailsSent) {\nthis.initialPlatformDetailsSent = true;\nif (!responsesIncludePlatformDetails) {\n- clientResponses.push({\n+ nonActivityClientResponses.push({\ntype: serverRequestTypes.PLATFORM_DETAILS,\nplatformDetails: getConfig().platformDetails,\n});\n}\n}\n+ this.markClientResponsesAsInTransit(nonActivityClientResponses, messageID);\n- const messageID = this.nextClientMessageID++;\n- this.markClientResponsesAsInTransit(clientResponses, messageID);\n+ const clientResponses = [...nonActivityClientResponses];\n+ const { queuedActivityUpdates } = this.props.connection;\n+ if (queuedActivityUpdates.length > 0) {\n+ clientResponses.push({\n+ type: serverRequestTypes.INITIAL_ACTIVITY_UPDATES,\n+ activityUpdates: queuedActivityUpdates,\n+ });\n+ this.markActivityUpdatesAsInTransit(queuedActivityUpdates, messageID);\n+ }\nconst sessionState = this.props.sessionStateFunc();\nconst { sessionIdentification } = this.props;\n@@ -334,8 +376,11 @@ class Socket extends React.PureComponent<Props> {\nreturn;\n}\nconst errored = [];\n- const newTransitStatuses = this.clientResponseTransitStatuses.filter(\n+ const newTransitStatuses = this.transitStatuses.filter(\ntransitStatus => {\n+ if (transitStatus.type !== \"ClientResponse\") {\n+ return true;\n+ }\nlet matches = false;\nfor (let clientResponse of clientResponses) {\nif (clientResponse === transitStatus.clientResponse) {\n@@ -355,19 +400,21 @@ class Socket extends React.PureComponent<Props> {\nfor (let clientResponse of clientResponses) {\nif (errored.includes(clientResponse)) {\nnewTransitStatuses.push({\n+ type: \"ClientResponse\",\nstatus: \"errored\",\nclientResponse,\nmessageID,\n});\n} else {\nnewTransitStatuses.push({\n+ type: \"ClientResponse\",\nstatus: \"inflight\",\nclientResponse,\nmessageID,\n});\n}\n}\n- this.clientResponseTransitStatuses = newTransitStatuses;\n+ this.transitStatuses = newTransitStatuses;\n}\nfilterInTransitClientResponses(\n@@ -376,13 +423,14 @@ class Socket extends React.PureComponent<Props> {\nconst filtered = [];\nfor (let clientResponse of clientResponses) {\nlet inTransit = false;\n- for (\n- let clientResponseTransitStatus of this.clientResponseTransitStatuses\n- ) {\n+ for (let transitStatus of this.transitStatuses) {\n+ if (transitStatus.type !== \"ClientResponse\") {\n+ continue;\n+ }\nconst {\nclientResponse: inTransitClientResponse,\nmessageID,\n- } = clientResponseTransitStatus;\n+ } = transitStatus;\nif (\ninTransitClientResponse === clientResponse &&\nmessageID !== null && messageID !== undefined\n@@ -398,52 +446,90 @@ class Socket extends React.PureComponent<Props> {\nreturn filtered;\n}\n- handleResponseToClientResponses(success: bool, messageID: number) {\n- const deliveredResponses = [], erroredStatuses = [], stillInTransit = [];\n- for (\n- let clientResponseTransitStatus of this.clientResponseTransitStatuses\n+ updateTransitStatusesWithServerResponse(success: bool, messageID: number) {\n+ const deliveredResponses = [], erroredResponseStatuses = [];\n+ const deliveredActivityUpdates = [], erroredActivityUpdateStatuses = [];\n+ const stillInTransit = [];\n+ for (let transitStatus of this.transitStatuses) {\n+ if (\n+ transitStatus.type === \"ClientResponse\" &&\n+ transitStatus.messageID === messageID\n+ ) {\n+ if (success || transitStatus.status === \"errored\") {\n+ deliveredResponses.push(transitStatus.clientResponse);\n+ } else {\n+ erroredResponseStatuses.push(transitStatus);\n+ }\n+ } else if (\n+ transitStatus.type === \"ActivityUpdate\" &&\n+ transitStatus.messageID === messageID\n) {\n- if (clientResponseTransitStatus.messageID === messageID) {\n- if (success || clientResponseTransitStatus.status === \"errored\") {\n- deliveredResponses.push(clientResponseTransitStatus.clientResponse);\n+ if (success || transitStatus.status === \"errored\") {\n+ deliveredActivityUpdates.push(transitStatus.activityUpdate);\n} else {\n- erroredStatuses.push(clientResponseTransitStatus);\n+ erroredActivityUpdateStatuses.push(transitStatus);\n}\n} else {\n- stillInTransit.push(clientResponseTransitStatus);\n+ stillInTransit.push(transitStatus);\n}\n}\n+ this.transitStatuses = stillInTransit;\nif (deliveredResponses.length > 0) {\n// Note: it's hypothetically possible for something to call\n- // possiblySendReduxClientResponses after we update\n- // this.clientResponseTransitStatuses below but before this Redux action\n- // propagates to this component. In that case, we could double-send some\n- // Redux-cached ClientResponses. Since right now only inconsistency\n- // responses are Redux-cached, and the server knows how to dedup those so\n- // that the transaction is idempotent, we're not going to worry about it.\n+ // possiblySendReduxClientResponses after we update this.transitStatuses\n+ // but before this Redux action propagates to this component. In that\n+ // case, we could double-send some Redux-cached ClientResponses. Since\n+ // right now only inconsistency responses are Redux-cached, and the server\n+ // knows how to dedup those so that the transaction is idempotent, we're\n+ // not going to worry about it.\nthis.props.dispatchActionPayload(\nclearDeliveredClientResponsesActionType,\n{ clientResponses: deliveredResponses },\n);\n}\n- if (erroredStatuses.length > 0) {\n- const newTransitStatuses = erroredStatuses.map(transitStatus => ({\n+ if (deliveredActivityUpdates.length > 0) {\n+ // Same possibility as above. Our transactions this time aren't\n+ // idempotent, but we don't expect this race condition to happen often.\n+ // TODO: see if there is an issue here\n+ this.props.dispatchActionPayload(\n+ clearQueuedActivityUpdatesActionType,\n+ { activityUpdates: deliveredActivityUpdates },\n+ );\n+ }\n+\n+ if (erroredResponseStatuses.length > 0) {\n+ const newTransitStatuses = erroredResponseStatuses.map(transitStatus => ({\n// Mark our second attempt as already \"errored\" so they get\n// filtered out on the next cycle\n+ type: \"ClientResponse\",\nstatus: \"errored\",\nclientResponse: transitStatus.clientResponse,\n}));\n- this.clientResponseTransitStatuses = [\n- ...stillInTransit,\n+ this.transitStatuses = [\n+ ...this.transitStatuses,\n...newTransitStatuses,\n- ],\n+ ];\nthis.sendClientResponses(\nnewTransitStatuses.map(transitStatus => transitStatus.clientResponse),\n);\n- } else if (deliveredResponses.length > 0) {\n- this.clientResponseTransitStatuses = stillInTransit;\n+ }\n+\n+ if (erroredResponseStatuses.length > 0) {\n+ const newTransitStatuses =\n+ erroredActivityUpdateStatuses.map(transitStatus => ({\n+ // Mark our second attempt as already \"errored\" so they get\n+ // filtered out on the next cycle\n+ type: \"ActivityUpdate\",\n+ status: \"errored\",\n+ activityUpdate: transitStatus.activityUpdate,\n+ }));\n+ this.transitStatuses = [\n+ ...this.transitStatuses,\n+ ...newTransitStatuses,\n+ ];\n+ // TODO: send update to client\n}\n}\n@@ -457,6 +543,57 @@ class Socket extends React.PureComponent<Props> {\n);\n}\n+ markActivityUpdatesAsInTransit(\n+ activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n+ messageID: number,\n+ ) {\n+ // We want to avoid double-sending ActivityUpdates, so we mark them as\n+ // in-transit once they're sent\n+ if (activityUpdates.length === 0) {\n+ return;\n+ }\n+ const errored = [];\n+ const newTransitStatuses = this.transitStatuses.filter(\n+ transitStatus => {\n+ if (transitStatus.type !== \"ActivityUpdate\") {\n+ return true;\n+ }\n+ let matches = false;\n+ for (let activityUpdate of activityUpdates) {\n+ if (activityUpdate === transitStatus.activityUpdate) {\n+ matches = true;\n+ break;\n+ }\n+ }\n+ if (!matches) {\n+ return true;\n+ }\n+ if (transitStatus.status === \"errored\") {\n+ errored.push(transitStatus.activityUpdate);\n+ }\n+ return false;\n+ },\n+ );\n+ for (let activityUpdate of activityUpdates) {\n+ if (errored.includes(activityUpdate)) {\n+ newTransitStatuses.push({\n+ type: \"ActivityUpdate\",\n+ status: \"errored\",\n+ activityUpdate,\n+ messageID,\n+ });\n+ } else {\n+ newTransitStatuses.push({\n+ type: \"ActivityUpdate\",\n+ status: \"inflight\",\n+ activityUpdate,\n+ messageID,\n+ });\n+ }\n+ }\n+ this.transitStatuses = newTransitStatuses;\n+ }\n+\n}\nexport default Socket;\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/connection-reducer.js", "new_path": "lib/reducers/connection-reducer.js", "diff": "@@ -8,6 +8,12 @@ import {\nclearQueuedActivityUpdatesActionType,\n} from '../types/socket-types';\n+import { setNewSessionActionType } from '../utils/action-utils';\n+import {\n+ logOutActionTypes,\n+ deleteAccountActionTypes,\n+} from '../actions/user-actions';\n+\nexport default function reduceConnectionInfo(\nstate: ConnectionInfo,\naction: BaseAction,\n@@ -15,14 +21,38 @@ export default function reduceConnectionInfo(\nif (action.type === updateConnectionStatusActionType) {\nreturn { ...state, status: action.payload.status };\n} else if (action.type === queueActivityUpdateActionType) {\n+ const { activityUpdate } = action.payload;\nreturn {\n...state,\nqueuedActivityUpdates: [\n- ...state.queuedActivityUpdates,\n- action.payload.activityUpdate,\n+ ...state.queuedActivityUpdates.filter(existingUpdate => {\n+ if (\n+ (existingUpdate.focus && activityUpdate.focus) ||\n+ existingUpdate.focus === false &&\n+ activityUpdate.focus !== undefined\n+ ) {\n+ return existingUpdate.threadID !== activityUpdate.threadID;\n+ }\n+ return true;\n+ },\n+ ),\n+ activityUpdate,\n],\n};\n} else if (action.type === clearQueuedActivityUpdatesActionType) {\n+ const { payload } = action;\n+ return {\n+ ...state,\n+ queuedActivityUpdates: state.queuedActivityUpdates.filter(\n+ activityUpdate => !payload.activityUpdates.includes(activityUpdate),\n+ ),\n+ };\n+ } else if (\n+ action.type === logOutActionTypes.success ||\n+ action.type === deleteAccountActionTypes.success ||\n+ (action.type === setNewSessionActionType &&\n+ action.payload.sessionChange.cookieInvalidated)\n+ ) {\nreturn { ...state, queuedActivityUpdates: [] };\n}\nreturn state;\n" }, { "change_type": "MODIFY", "old_path": "lib/types/activity-types.js", "new_path": "lib/types/activity-types.js", "diff": "// @flow\n+import PropTypes from 'prop-types';\n+\nexport type ActivityUpdate =\n| {| focus: true, threadID: string |}\n| {| focus: false, threadID: string, latestMessage: ?string |}\n- | {| closing: true |};\n+ | {| focus?: void, closing: true |};\n+export const activityUpdatePropType = PropTypes.oneOfType([\n+ PropTypes.shape({\n+ focus: PropTypes.oneOf([ true ]).isRequired,\n+ threadID: PropTypes.string.isRequired,\n+ }),\n+ PropTypes.shape({\n+ focus: PropTypes.oneOf([ false ]).isRequired,\n+ threadID: PropTypes.string.isRequired,\n+ latestMessage: PropTypes.string,\n+ }),\n+]);\nexport type UpdateActivityRequest = {|\nupdates: $ReadOnlyArray<ActivityUpdate>,\n" }, { "change_type": "MODIFY", "old_path": "lib/types/request-types.js", "new_path": "lib/types/request-types.js", "diff": "@@ -127,76 +127,6 @@ type InitialActivityUpdatesClientResponse = {|\nactivityUpdates: $ReadOnlyArray<ActivityUpdate>,\n|};\n-export const serverRequestPropType = PropTypes.oneOfType([\n- PropTypes.shape({\n- type: PropTypes.oneOf([ serverRequestTypes.PLATFORM ]).isRequired,\n- }),\n- PropTypes.shape({\n- type: PropTypes.oneOf([ serverRequestTypes.DEVICE_TOKEN ]).isRequired,\n- }),\n- PropTypes.shape({\n- type: PropTypes.oneOf([ serverRequestTypes.PLATFORM_DETAILS ]).isRequired,\n- }),\n- PropTypes.shape({\n- type: PropTypes.oneOf([ serverRequestTypes.CHECK_STATE ]).isRequired,\n- hashesToCheck: PropTypes.objectOf(PropTypes.number).isRequired,\n- stateChanges: PropTypes.shape({\n- rawThreadInfos: PropTypes.arrayOf(rawThreadInfoPropType),\n- rawEntryInfos: PropTypes.arrayOf(rawEntryInfoPropType),\n- currentUserInfo: currentUserPropType,\n- userInfos: PropTypes.arrayOf(accountUserInfoPropType),\n- }),\n- }),\n-]);\n-\n-export const clientResponsePropType = PropTypes.oneOfType([\n- PropTypes.shape({\n- type: PropTypes.oneOf([ serverRequestTypes.PLATFORM ]).isRequired,\n- platform: platformPropType.isRequired,\n- }),\n- PropTypes.shape({\n- type: PropTypes.oneOf([ serverRequestTypes.DEVICE_TOKEN ]).isRequired,\n- deviceToken: PropTypes.string.isRequired,\n- }),\n- PropTypes.shape({\n- type: PropTypes.oneOf([\n- serverRequestTypes.THREAD_INCONSISTENCY,\n- ]).isRequired,\n- platformDetails: platformDetailsPropType.isRequired,\n- beforeAction: PropTypes.objectOf(rawThreadInfoPropType).isRequired,\n- action: PropTypes.object.isRequired,\n- pollResult: PropTypes.objectOf(rawThreadInfoPropType).isRequired,\n- pushResult: PropTypes.objectOf(rawThreadInfoPropType).isRequired,\n- lastActionTypes: PropTypes.arrayOf(PropTypes.string),\n- time: PropTypes.number,\n- }),\n- PropTypes.shape({\n- type: PropTypes.oneOf([ serverRequestTypes.PLATFORM_DETAILS ]).isRequired,\n- platformDetails: platformDetailsPropType.isRequired,\n- }),\n- PropTypes.shape({\n- type: PropTypes.oneOf([ serverRequestTypes.INITIAL_ACTIVITY_UPDATE ]).isRequired,\n- threadID: PropTypes.string.isRequired,\n- }),\n- PropTypes.shape({\n- type: PropTypes.oneOf([\n- serverRequestTypes.ENTRY_INCONSISTENCY,\n- ]).isRequired,\n- platformDetails: platformDetailsPropType.isRequired,\n- beforeAction: PropTypes.objectOf(rawEntryInfoPropType).isRequired,\n- action: PropTypes.object.isRequired,\n- calendarQuery: calendarQueryPropType.isRequired,\n- pollResult: PropTypes.objectOf(rawEntryInfoPropType).isRequired,\n- pushResult: PropTypes.objectOf(rawEntryInfoPropType).isRequired,\n- lastActionTypes: PropTypes.arrayOf(PropTypes.string).isRequired,\n- time: PropTypes.number.isRequired,\n- }),\n- PropTypes.shape({\n- type: PropTypes.oneOf([ serverRequestTypes.CHECK_STATE ]).isRequired,\n- hashResults: PropTypes.objectOf(PropTypes.bool).isRequired,\n- }),\n-]);\n-\nexport type ServerRequest =\n| PlatformServerRequest\n| DeviceTokenServerRequest\n" }, { "change_type": "MODIFY", "old_path": "lib/types/socket-types.js", "new_path": "lib/types/socket-types.js", "diff": "@@ -11,9 +11,10 @@ import type {\nLoggedOutUserInfo,\n} from './user-types';\nimport type { RawEntryInfo } from './entry-types';\n-import type { ActivityUpdate } from './activity-types';\n+import { type ActivityUpdate, activityUpdatePropType } from './activity-types';\nimport invariant from 'invariant';\n+import PropTypes from 'prop-types';\nimport { pingResponseTypes } from './ping-types';\n@@ -152,6 +153,17 @@ export type ConnectionInfo = {|\nstatus: ConnectionStatus,\nqueuedActivityUpdates: $ReadOnlyArray<ActivityUpdate>,\n|};\n+export const connectionInfoPropType = PropTypes.shape({\n+ status: PropTypes.oneOf([\n+ \"connecting\",\n+ \"connected\",\n+ \"reconnecting\",\n+ \"disconnecting\",\n+ \"forcedDisconnecting\",\n+ \"disconnected\",\n+ ]).isRequired,\n+ queuedActivityUpdates: PropTypes.arrayOf(activityUpdatePropType).isRequired,\n+});\nexport const defaultConnectionInfo = {\nstatus: \"connecting\",\nqueuedActivityUpdates: [],\n" }, { "change_type": "MODIFY", "old_path": "native/socket.react.js", "new_path": "native/socket.react.js", "diff": "@@ -26,6 +26,7 @@ export default connect(\ncookie: state.cookie,\nurlPrefix: state.urlPrefix,\nlogInExtraInfo: logInExtraInfoSelector(state),\n+ connection: state.connection,\n}),\nnull,\ntrue,\n" }, { "change_type": "MODIFY", "old_path": "web/socket.react.js", "new_path": "web/socket.react.js", "diff": "@@ -26,6 +26,7 @@ export default connect(\ncookie: state.cookie,\nurlPrefix: state.urlPrefix,\nlogInExtraInfo: logInExtraInfoSelector(state),\n+ connection: state.connection,\n}),\nnull,\ntrue,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Store queuedActivityUpdates in Redux Also introduces shared `TransitStatus` type to track inflight requests.
129,187
22.10.2018 13:43:46
14,400
b62de8b74164a792dc80d6f0b2d94b1f53660c58
Replace socketInitializedAndActive with Redux connection state
[ { "change_type": "MODIFY", "old_path": "lib/components/socket.react.js", "new_path": "lib/components/socket.react.js", "diff": "@@ -107,7 +107,6 @@ class Socket extends React.PureComponent<Props> {\nsocket: ?WebSocket;\ninitialPlatformDetailsSent = false;\nnextClientMessageID = 0;\n- socketInitializedAndActive = false;\ntransitStatuses: TransitStatus[] = [];\nopenSocket() {\n@@ -138,7 +137,6 @@ class Socket extends React.PureComponent<Props> {\n}\ncloseSocket() {\n- this.socketInitializedAndActive = false;\nregisterActiveWebSocket(null);\nthis.props.dispatchActionPayload(\nupdateConnectionStatusActionType,\n@@ -154,15 +152,11 @@ class Socket extends React.PureComponent<Props> {\n}\nmarkSocketInitialized() {\n- this.socketInitializedAndActive = true;\nregisterActiveWebSocket(this.socket);\nthis.props.dispatchActionPayload(\nupdateConnectionStatusActionType,\n{ status: \"connected\" },\n);\n- // In case any ClientResponses have accumulated in Redux while we were\n- // initializing\n- this.possiblySendReduxClientResponses();\n}\ncomponentDidMount() {\n@@ -193,8 +187,9 @@ class Socket extends React.PureComponent<Props> {\n}\nif (\n- this.socketInitializedAndActive &&\n- this.props.getClientResponses !== prevProps.getClientResponses\n+ this.props.connection.status === \"connected\" &&\n+ (prevProps.connection.status !== \"connected\" ||\n+ this.props.getClientResponses !== prevProps.getClientResponses)\n) {\nthis.possiblySendReduxClientResponses();\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Replace socketInitializedAndActive with Redux connection state
129,187
22.10.2018 14:09:36
14,400
31beed58dd051e321720f1c15de8c6495d97974f
Type DispatchActionPromise correctly
[ { "change_type": "MODIFY", "old_path": "lib/types/entry-types.js", "new_path": "lib/types/entry-types.js", "diff": "@@ -194,6 +194,9 @@ export type CalendarResult = {|\nuserInfos: $ReadOnlyArray<UserInfo>,\n|};\n+export type CalendarQueryUpdateStartingPayload = {|\n+ calendarQuery?: CalendarQuery,\n+|};\nexport type CalendarQueryUpdateResult = {|\nrawEntryInfos: $ReadOnlyArray<RawEntryInfo>,\nuserInfos: $ReadOnlyArray<AccountUserInfo>,\n" }, { "change_type": "MODIFY", "old_path": "lib/types/redux-types.js", "new_path": "lib/types/redux-types.js", "diff": "@@ -18,6 +18,7 @@ import type {\nFetchEntryInfosResult,\nCalendarResult,\nCalendarQueryUpdateResult,\n+ CalendarQueryUpdateStartingPayload,\n} from './entry-types';\nimport type { LoadingStatus, LoadingInfo } from './loading-types';\nimport type { BaseNavInfo } from './nav-types';\n@@ -90,8 +91,12 @@ export type WebAppState =\nexport type AppState = NativeAppState | WebAppState;\nexport type BaseAction =\n- {| type: \"@@redux/INIT\" |} | {|\n+ {|\n+ type: \"@@redux/INIT\",\n+ payload?: void,\n+ |} | {|\ntype: \"FETCH_ENTRIES_STARTED\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"FETCH_ENTRIES_FAILED\",\n@@ -104,6 +109,7 @@ export type BaseAction =\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"LOG_OUT_STARTED\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"LOG_OUT_FAILED\",\n@@ -116,6 +122,7 @@ export type BaseAction =\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"DELETE_ACCOUNT_STARTED\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"DELETE_ACCOUNT_FAILED\",\n@@ -131,6 +138,7 @@ export type BaseAction =\npayload: RawEntryInfo,\n|} | {|\ntype: \"CREATE_ENTRY_STARTED\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"CREATE_ENTRY_FAILED\",\n@@ -143,6 +151,7 @@ export type BaseAction =\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"SAVE_ENTRY_STARTED\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"SAVE_ENTRY_FAILED\",\n@@ -216,6 +225,7 @@ export type BaseAction =\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"FORGOT_PASSWORD_STARTED\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"FORGOT_PASSWORD_FAILED\",\n@@ -224,9 +234,11 @@ export type BaseAction =\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"FORGOT_PASSWORD_SUCCESS\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"CHANGE_USER_SETTINGS_STARTED\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"CHANGE_USER_SETTINGS_FAILED\",\n@@ -241,6 +253,7 @@ export type BaseAction =\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"RESEND_VERIFICATION_EMAIL_STARTED\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"RESEND_VERIFICATION_EMAIL_FAILED\",\n@@ -249,9 +262,11 @@ export type BaseAction =\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"RESEND_VERIFICATION_EMAIL_SUCCESS\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"CHANGE_THREAD_SETTINGS_STARTED\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"CHANGE_THREAD_SETTINGS_FAILED\",\n@@ -264,6 +279,7 @@ export type BaseAction =\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"DELETE_THREAD_STARTED\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"DELETE_THREAD_FAILED\",\n@@ -276,6 +292,7 @@ export type BaseAction =\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"NEW_THREAD_STARTED\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"NEW_THREAD_FAILED\",\n@@ -288,6 +305,7 @@ export type BaseAction =\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"REMOVE_USERS_FROM_THREAD_STARTED\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"REMOVE_USERS_FROM_THREAD_FAILED\",\n@@ -300,6 +318,7 @@ export type BaseAction =\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"CHANGE_THREAD_MEMBER_ROLES_STARTED\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"CHANGE_THREAD_MEMBER_ROLES_FAILED\",\n@@ -312,6 +331,7 @@ export type BaseAction =\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"FETCH_REVISIONS_FOR_ENTRY_STARTED\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"FETCH_REVISIONS_FOR_ENTRY_FAILED\",\n@@ -328,6 +348,7 @@ export type BaseAction =\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"RESTORE_ENTRY_STARTED\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"RESTORE_ENTRY_FAILED\",\n@@ -340,6 +361,7 @@ export type BaseAction =\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"JOIN_THREAD_STARTED\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"JOIN_THREAD_FAILED\",\n@@ -352,6 +374,7 @@ export type BaseAction =\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"LEAVE_THREAD_STARTED\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"LEAVE_THREAD_FAILED\",\n@@ -367,6 +390,7 @@ export type BaseAction =\npayload: SetSessionPayload,\n|} | {|\ntype: \"FETCH_ENTRIES_AND_APPEND_RANGE_STARTED\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"FETCH_ENTRIES_AND_APPEND_RANGE_FAILED\",\n@@ -382,6 +406,7 @@ export type BaseAction =\npayload: BaseAppState<*>,\n|} | {|\ntype: \"FETCH_MESSAGES_BEFORE_CURSOR_STARTED\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"FETCH_MESSAGES_BEFORE_CURSOR_FAILED\",\n@@ -394,6 +419,7 @@ export type BaseAction =\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"FETCH_MOST_RECENT_MESSAGES_STARTED\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"FETCH_MOST_RECENT_MESSAGES_FAILED\",\n@@ -422,6 +448,7 @@ export type BaseAction =\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"SEARCH_USERS_STARTED\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"SEARCH_USERS_FAILED\",\n@@ -440,6 +467,7 @@ export type BaseAction =\n},\n|} | {|\ntype: \"UPDATE_ACTIVITY_STARTED\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"UPDATE_ACTIVITY_FAILED\",\n@@ -465,6 +493,7 @@ export type BaseAction =\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"HANDLE_VERIFICATION_CODE_STARTED\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"HANDLE_VERIFICATION_CODE_FAILED\",\n@@ -473,9 +502,11 @@ export type BaseAction =\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"HANDLE_VERIFICATION_CODE_SUCCESS\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"SEND_REPORT_STARTED\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"SEND_REPORT_FAILED\",\n@@ -497,11 +528,13 @@ export type BaseAction =\npayload: CalendarThreadFilter,\n|} | {|\ntype: \"CLEAR_CALENDAR_THREAD_FILTER\",\n+ payload?: void,\n|} | {|\ntype: \"SET_CALENDAR_DELETED_FILTER\",\npayload: SetCalendarDeletedFilterPayload,\n|} | {|\ntype: \"UPDATE_SUBSCRIPTION_STARTED\",\n+ payload?: void,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"UPDATE_SUBSCRIPTION_FAILED\",\n@@ -515,7 +548,7 @@ export type BaseAction =\n|} | {|\ntype: \"UPDATE_CALENDAR_QUERY_STARTED\",\nloadingInfo: LoadingInfo,\n- payload?: {| calendarQuery?: CalendarQuery |},\n+ payload?: CalendarQueryUpdateStartingPayload,\n|} | {|\ntype: \"UPDATE_CALENDAR_QUERY_FAILED\",\nerror: true,\n" }, { "change_type": "MODIFY", "old_path": "lib/utils/action-utils.js", "new_path": "lib/utils/action-utils.js", "diff": "@@ -4,7 +4,7 @@ import type {\nActionPayload,\nDispatch,\nPromisedAction,\n- SuperAction,\n+ BaseAction,\n} from '../types/redux-types';\nimport type { LoadingOptions, LoadingInfo } from '../types/loading-types';\nimport type { FetchJSON, FetchJSONOptions } from './fetch-json';\n@@ -40,18 +40,6 @@ export type ActionTypes<\nfailed: CT,\n};\n-type ActionSupportingPromise<\n- AT: $Subtype<string>,\n- AP: ActionPayload,\n- BT: $Subtype<string>,\n- BP: ActionPayload,\n- CT: $Subtype<string>,\n-> =\n- { type: AT, loadingInfo: LoadingInfo, payload?: AP } |\n- { type: BT, loadingInfo: LoadingInfo, payload?: BP } |\n- { type: CT, loadingInfo: LoadingInfo, payload: Error } |\n- { type: AT, payload?: AP };\n-\nfunction wrapActionPromise<\nAT: $Subtype<string>, // *_STARTED action type (string literal)\nAP: ActionPayload, // *_STARTED payload\n@@ -106,9 +94,9 @@ function wrapActionPromise<\nexport type DispatchActionPayload =\n<T: $Subtype<string>, P: ActionPayload>(actionType: T, payload: P) => void;\nexport type DispatchActionPromise = <\n- A: SuperAction,\n- B: SuperAction,\n- C: SuperAction,\n+ A: BaseAction,\n+ B: BaseAction,\n+ C: BaseAction,\n>(\nactionTypes: ActionTypes<\n$PropertyType<A, 'type'>,\n@@ -127,7 +115,7 @@ type BoundActions = {\n};\nfunction includeDispatchActionProps(dispatch: Dispatch): BoundActions {\nconst dispatchActionPromise =\n- function<A: SuperAction, B: SuperAction, C: SuperAction>(\n+ function<A: BaseAction, B: BaseAction, C: BaseAction>(\nactionTypes: ActionTypes<\n$PropertyType<A, 'type'>,\n$PropertyType<B, 'type'>,\n" }, { "change_type": "MODIFY", "old_path": "native/account/log-in-panel.react.js", "new_path": "native/account/log-in-panel.react.js", "diff": "@@ -7,6 +7,7 @@ import type {\nLogInInfo,\nLogInExtraInfo,\nLogInResult,\n+ LogInStartingPayload,\n} from 'lib/types/account-types';\nimport {\ntype StateContainer,\n@@ -216,7 +217,7 @@ class LogInPanel extends React.PureComponent<Props> {\nlogInActionTypes,\nthis.logInAction(extraInfo),\nundefined,\n- { calendarQuery: extraInfo.calendarQuery },\n+ ({ calendarQuery: extraInfo.calendarQuery }: LogInStartingPayload),\n);\n}\n" }, { "change_type": "MODIFY", "old_path": "native/account/register-panel.react.js", "new_path": "native/account/register-panel.react.js", "diff": "@@ -7,6 +7,7 @@ import type {\nRegisterInfo,\nLogInExtraInfo,\nRegisterResult,\n+ LogInStartingPayload,\n} from 'lib/types/account-types';\nimport {\ntype StateContainer,\n@@ -269,7 +270,7 @@ class RegisterPanel extends React.PureComponent<Props> {\nregisterActionTypes,\nthis.registerAction(extraInfo),\nundefined,\n- { calendarQuery: extraInfo.calendarQuery },\n+ ({ calendarQuery: extraInfo.calendarQuery }: LogInStartingPayload),\n);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "native/account/reset-password-panel.react.js", "new_path": "native/account/reset-password-panel.react.js", "diff": "@@ -7,6 +7,7 @@ import type {\nUpdatePasswordInfo,\nLogInExtraInfo,\nLogInResult,\n+ LogInStartingPayload,\n} from 'lib/types/account-types';\nimport React from 'react';\n@@ -188,7 +189,7 @@ class ResetPasswordPanel extends React.PureComponent<Props, State> {\nresetPasswordActionTypes,\nthis.resetPasswordAction(extraInfo),\nundefined,\n- { calendarQuery: extraInfo.calendarQuery },\n+ ({ calendarQuery: extraInfo.calendarQuery }: LogInStartingPayload),\n);\n}\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-input-bar.react.js", "new_path": "native/chat/chat-input-bar.react.js", "diff": "@@ -277,8 +277,13 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nmessageInfo.threadID,\nmessageInfo.text,\n);\n+ const { localID } = messageInfo;\n+ invariant(\n+ localID !== null && localID !== undefined,\n+ \"localID should be set\",\n+ );\nreturn {\n- localID: messageInfo.localID,\n+ localID,\nserverID: result.id,\nthreadID: messageInfo.threadID,\ntime: result.time,\n" }, { "change_type": "MODIFY", "old_path": "native/chat/settings/thread-settings-push-notifs.react.js", "new_path": "native/chat/settings/thread-settings-push-notifs.react.js", "diff": "@@ -5,7 +5,7 @@ import type { AppState } from '../../redux-setup';\nimport type { DispatchActionPromise } from 'lib/utils/action-utils';\nimport type {\nSubscriptionUpdateRequest,\n- ThreadSubscription,\n+ SubscriptionUpdateResult,\n} from 'lib/types/subscription-types';\nimport React from 'react';\n@@ -25,7 +25,7 @@ type Props = {|\n// async functions that hit server APIs\nupdateSubscription: (\nsubscriptionUpdate: SubscriptionUpdateRequest,\n- ) => Promise<ThreadSubscription>,\n+ ) => Promise<SubscriptionUpdateResult>,\n|};\ntype State = {|\ncurrentValue: bool,\n" }, { "change_type": "MODIFY", "old_path": "web/app.react.js", "new_path": "web/app.react.js", "diff": "@@ -11,6 +11,7 @@ import {\ntype CalendarQuery,\ntype CalendarQueryUpdateResult,\ncalendarQueryPropType,\n+ type CalendarQueryUpdateStartingPayload,\n} from 'lib/types/entry-types';\nimport type {\nActivityUpdate,\n@@ -303,7 +304,7 @@ class App extends React.PureComponent<Props, State> {\nupdateCalendarQueryActionTypes,\nnextProps.updateCalendarQuery(calendarQuery, true),\nundefined,\n- { calendarQuery },\n+ ({ calendarQuery }: CalendarQueryUpdateStartingPayload),\n);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "web/calendar/calendar.react.js", "new_path": "web/calendar/calendar.react.js", "diff": "@@ -5,6 +5,7 @@ import {\ntype EntryInfo,\ntype CalendarQuery,\ntype CalendarQueryUpdateResult,\n+ type CalendarQueryUpdateStartingPayload,\n} from 'lib/types/entry-types';\nimport { type AppState, type NavInfo, navInfoPropType } from '../redux-setup';\nimport type { DispatchActionPromise } from 'lib/utils/action-utils';\n@@ -248,7 +249,7 @@ class Calendar extends React.PureComponent<Props, State> {\nupdateCalendarQueryActionTypes,\nthis.props.updateCalendarQuery(newCalendarQuery, true),\nundefined,\n- { calendarQuery: newCalendarQuery },\n+ ({ calendarQuery: newCalendarQuery }: CalendarQueryUpdateStartingPayload),\n);\n}\n@@ -263,7 +264,7 @@ class Calendar extends React.PureComponent<Props, State> {\nupdateCalendarQueryActionTypes,\nthis.props.updateCalendarQuery(newCalendarQuery, true),\nundefined,\n- { calendarQuery: newCalendarQuery },\n+ ({ calendarQuery: newCalendarQuery }: CalendarQueryUpdateStartingPayload),\n);\n}\n" }, { "change_type": "MODIFY", "old_path": "web/chat/chat-input-bar.react.js", "new_path": "web/chat/chat-input-bar.react.js", "diff": "@@ -236,8 +236,13 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nmessageInfo.threadID,\nmessageInfo.text,\n);\n+ const { localID } = messageInfo;\n+ invariant(\n+ localID !== null && localID !== undefined,\n+ \"localID should be set\",\n+ );\nreturn {\n- localID: messageInfo.localID,\n+ localID,\nserverID: result.id,\nthreadID: messageInfo.threadID,\ntime: result.time,\n" }, { "change_type": "MODIFY", "old_path": "web/modals/account/log-in-modal.react.js", "new_path": "web/modals/account/log-in-modal.react.js", "diff": "@@ -6,6 +6,7 @@ import type {\nLogInInfo,\nLogInExtraInfo,\nLogInResult,\n+ LogInStartingPayload,\n} from 'lib/types/account-types';\nimport * as React from 'react';\n@@ -168,7 +169,7 @@ class LogInModal extends React.PureComponent<Props, State> {\nlogInActionTypes,\nthis.logInAction(extraInfo),\nundefined,\n- { calendarQuery: extraInfo.calendarQuery },\n+ ({ calendarQuery: extraInfo.calendarQuery }: LogInStartingPayload),\n);\n}\n" }, { "change_type": "MODIFY", "old_path": "web/modals/account/register-modal.react.js", "new_path": "web/modals/account/register-modal.react.js", "diff": "@@ -6,6 +6,7 @@ import type {\nRegisterInfo,\nLogInExtraInfo,\nRegisterResult,\n+ LogInStartingPayload,\n} from 'lib/types/account-types';\nimport * as React from 'react';\n@@ -230,7 +231,7 @@ class RegisterModal extends React.PureComponent<Props, State> {\nregisterActionTypes,\nthis.registerAction(extraInfo),\nundefined,\n- { calendarQuery: extraInfo.calendarQuery },\n+ ({ calendarQuery: extraInfo.calendarQuery }: LogInStartingPayload),\n);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "web/modals/account/reset-password-modal.react.js", "new_path": "web/modals/account/reset-password-modal.react.js", "diff": "@@ -6,6 +6,7 @@ import type {\nUpdatePasswordInfo,\nLogInExtraInfo,\nLogInResult,\n+ LogInStartingPayload,\n} from 'lib/types/account-types';\nimport * as React from 'react';\n@@ -167,7 +168,7 @@ class ResetPasswordModal extends React.PureComponent<Props, State> {\nresetPasswordActionTypes,\nthis.resetPasswordAction(extraInfo),\nundefined,\n- { calendarQuery: extraInfo.calendarQuery },\n+ ({ calendarQuery: extraInfo.calendarQuery }: LogInStartingPayload),\n);\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Type DispatchActionPromise correctly
129,187
22.10.2018 15:02:06
14,400
9a87282347775c16329e28ba4b6873114cc56523
Queue ActivityUpdates when activeThread changes from within Socket component
[ { "change_type": "MODIFY", "old_path": "lib/components/socket.react.js", "new_path": "lib/components/socket.react.js", "diff": "@@ -78,6 +78,7 @@ type Props = {|\nactiveServerRequests?: $ReadOnlyArray<ServerRequest>,\n) => $ReadOnlyArray<ClientResponse>,\nactiveThread: ?string,\n+ activeThreadLatestMessage: ?string,\nsessionStateFunc: () => SessionState,\nsessionIdentification: SessionIdentification,\ncookie: ?string,\n@@ -95,6 +96,7 @@ class Socket extends React.PureComponent<Props> {\nactive: PropTypes.bool.isRequired,\ngetClientResponses: PropTypes.func.isRequired,\nactiveThread: PropTypes.string,\n+ activeThreadLatestMessage: PropTypes.string,\nsessionStateFunc: PropTypes.func.isRequired,\nsessionIdentification: sessionIdentificationPropType.isRequired,\ncookie: PropTypes.string,\n@@ -193,6 +195,32 @@ class Socket extends React.PureComponent<Props> {\n) {\nthis.possiblySendReduxClientResponses();\n}\n+\n+ if (this.props.activeThread !== prevProps.activeThread) {\n+ if (prevProps.activeThread) {\n+ this.props.dispatchActionPayload(\n+ queueActivityUpdateActionType,\n+ {\n+ activityUpdate: {\n+ focus: false,\n+ threadID: prevProps.activeThread,\n+ latestMessage: prevProps.activeThreadLatestMessage,\n+ },\n+ },\n+ );\n+ }\n+ if (this.props.activeThread) {\n+ this.props.dispatchActionPayload(\n+ queueActivityUpdateActionType,\n+ {\n+ activityUpdate: {\n+ focus: true,\n+ threadID: this.props.activeThread,\n+ },\n+ },\n+ );\n+ }\n+ }\n}\nrender() {\n" }, { "change_type": "MODIFY", "old_path": "native/socket.react.js", "new_path": "native/socket.react.js", "diff": "@@ -17,17 +17,24 @@ import {\nimport { activeThreadSelector } from './selectors/nav-selectors';\nexport default connect(\n- (state: AppState) => ({\n+ (state: AppState) => {\n+ const activeThread = activeThreadSelector(state);\n+ return {\nopenSocket: openSocketSelector(state),\ngetClientResponses: clientResponsesSelector(state),\n- activeThread: activeThreadSelector(state),\n+ activeThread,\n+ activeThreadLatestMessage:\n+ activeThread && state.messageStore.threads[activeThread]\n+ ? state.messageStore.threads[activeThread].messageIDs[0]\n+ : null,\nsessionStateFunc: sessionStateFuncSelector(state),\nsessionIdentification: sessionIdentificationSelector(state),\ncookie: state.cookie,\nurlPrefix: state.urlPrefix,\nlogInExtraInfo: logInExtraInfoSelector(state),\nconnection: state.connection,\n- }),\n+ };\n+ },\nnull,\ntrue,\n)(Socket);\n" }, { "change_type": "MODIFY", "old_path": "web/socket.react.js", "new_path": "web/socket.react.js", "diff": "@@ -17,17 +17,24 @@ import {\nimport { activeThreadSelector } from './selectors/nav-selectors';\nexport default connect(\n- (state: AppState) => ({\n+ (state: AppState) => {\n+ const activeThread = activeThreadSelector(state);\n+ return {\nopenSocket: openSocketSelector(state),\ngetClientResponses: clientResponsesSelector(state),\n- activeThread: activeThreadSelector(state),\n+ activeThread,\n+ activeThreadLatestMessage:\n+ activeThread && state.messageStore.threads[activeThread]\n+ ? state.messageStore.threads[activeThread].messageIDs[0]\n+ : null,\nsessionStateFunc: sessionStateFuncSelector(state),\nsessionIdentification: sessionIdentificationSelector(state),\ncookie: state.cookie,\nurlPrefix: state.urlPrefix,\nlogInExtraInfo: logInExtraInfoSelector(state),\nconnection: state.connection,\n- }),\n+ };\n+ },\nnull,\ntrue,\n)(Socket);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Queue ActivityUpdates when activeThread changes from within Socket component
129,187
22.10.2018 15:09:16
14,400
262f43221d33ff110bf69f8a2d9ba1524e2a2282
[lib] Allowing queueing multiple ActivityUpdates at once
[ { "change_type": "MODIFY", "old_path": "lib/components/socket.react.js", "new_path": "lib/components/socket.react.js", "diff": "@@ -23,7 +23,7 @@ import {\nupdateConnectionStatusActionType,\nconnectionInfoPropType,\ntype ConnectionInfo,\n- queueActivityUpdateActionType,\n+ queueActivityUpdatesActionType,\nclearQueuedActivityUpdatesActionType,\n} from '../types/socket-types';\nimport type { ActivityUpdate } from '../types/activity-types';\n@@ -117,12 +117,12 @@ class Socket extends React.PureComponent<Props> {\n}\nif (this.props.activeThread) {\nthis.props.dispatchActionPayload(\n- queueActivityUpdateActionType,\n+ queueActivityUpdatesActionType,\n{\n- activityUpdate: {\n+ activityUpdates: [{\nfocus: true,\nthreadID: this.props.activeThread,\n- },\n+ }],\n},\n);\n}\n@@ -197,27 +197,24 @@ class Socket extends React.PureComponent<Props> {\n}\nif (this.props.activeThread !== prevProps.activeThread) {\n+ const activityUpdates = [];\nif (prevProps.activeThread) {\n- this.props.dispatchActionPayload(\n- queueActivityUpdateActionType,\n- {\n- activityUpdate: {\n+ activityUpdates.push({\nfocus: false,\nthreadID: prevProps.activeThread,\nlatestMessage: prevProps.activeThreadLatestMessage,\n- },\n- },\n- );\n+ });\n}\nif (this.props.activeThread) {\n- this.props.dispatchActionPayload(\n- queueActivityUpdateActionType,\n- {\n- activityUpdate: {\n+ activityUpdates.push({\nfocus: true,\nthreadID: this.props.activeThread,\n- },\n- },\n+ });\n+ }\n+ if (activityUpdates.length > 0) {\n+ this.props.dispatchActionPayload(\n+ queueActivityUpdatesActionType,\n+ { activityUpdates },\n);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/connection-reducer.js", "new_path": "lib/reducers/connection-reducer.js", "diff": "@@ -4,7 +4,7 @@ import type { BaseAction } from '../types/redux-types';\nimport {\ntype ConnectionInfo,\nupdateConnectionStatusActionType,\n- queueActivityUpdateActionType,\n+ queueActivityUpdatesActionType,\nclearQueuedActivityUpdatesActionType,\n} from '../types/socket-types';\n@@ -20,23 +20,27 @@ export default function reduceConnectionInfo(\n): ConnectionInfo {\nif (action.type === updateConnectionStatusActionType) {\nreturn { ...state, status: action.payload.status };\n- } else if (action.type === queueActivityUpdateActionType) {\n- const { activityUpdate } = action.payload;\n+ } else if (action.type === queueActivityUpdatesActionType) {\n+ const { activityUpdates } = action.payload;\nreturn {\n...state,\nqueuedActivityUpdates: [\n...state.queuedActivityUpdates.filter(existingUpdate => {\n+ for (let activityUpdate of activityUpdates) {\nif (\n+ (\n(existingUpdate.focus && activityUpdate.focus) ||\n- existingUpdate.focus === false &&\n- activityUpdate.focus !== undefined\n+ (existingUpdate.focus === false &&\n+ activityUpdate.focus !== undefined)\n+ ) &&\n+ existingUpdate.threadID === activityUpdate.threadID\n) {\n- return existingUpdate.threadID !== activityUpdate.threadID;\n+ return false;\n+ }\n}\nreturn true;\n- },\n- ),\n- activityUpdate,\n+ }),\n+ ...activityUpdates,\n],\n};\n} else if (action.type === clearQueuedActivityUpdatesActionType) {\n" }, { "change_type": "MODIFY", "old_path": "lib/types/redux-types.js", "new_path": "lib/types/redux-types.js", "diff": "@@ -59,7 +59,7 @@ import type {\nStateSyncFullActionPayload,\nStateSyncIncrementalActionPayload,\nUpdateConnectionStatusPayload,\n- QueueActivityUpdatePayload,\n+ QueueActivityUpdatesPayload,\nClearActivityUpdatesPayload,\n} from '../types/socket-types';\n@@ -574,8 +574,8 @@ export type BaseAction =\ntype: \"UPDATE_CONNECTION_STATUS\",\npayload: UpdateConnectionStatusPayload,\n|} | {|\n- type: \"QUEUE_ACTIVITY_UPDATE\",\n- payload: QueueActivityUpdatePayload,\n+ type: \"QUEUE_ACTIVITY_UPDATES\",\n+ payload: QueueActivityUpdatesPayload,\n|} | {|\ntype: \"CLEAR_QUEUED_ACTIVITY_UPDATES\",\npayload: ClearActivityUpdatesPayload,\n" }, { "change_type": "MODIFY", "old_path": "lib/types/socket-types.js", "new_path": "lib/types/socket-types.js", "diff": "@@ -172,9 +172,9 @@ export const updateConnectionStatusActionType = \"UPDATE_CONNECTION_STATUS\";\nexport type UpdateConnectionStatusPayload = {|\nstatus: ConnectionStatus,\n|};\n-export const queueActivityUpdateActionType = \"QUEUE_ACTIVITY_UPDATE\";\n-export type QueueActivityUpdatePayload = {|\n- activityUpdate: ActivityUpdate,\n+export const queueActivityUpdatesActionType = \"QUEUE_ACTIVITY_UPDATES\";\n+export type QueueActivityUpdatesPayload = {|\n+ activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n|};\nexport const clearQueuedActivityUpdatesActionType =\n\"CLEAR_QUEUED_ACTIVITY_UPDATES\";\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Allowing queueing multiple ActivityUpdates at once
129,187
22.10.2018 15:22:01
14,400
2bdcea094f63e0dea783bbd3baba568579c8143c
[lib] Send activity updates once they are queued
[ { "change_type": "MODIFY", "old_path": "lib/components/socket.react.js", "new_path": "lib/components/socket.react.js", "diff": "@@ -188,14 +188,6 @@ class Socket extends React.PureComponent<Props> {\nthis.openSocket();\n}\n- if (\n- this.props.connection.status === \"connected\" &&\n- (prevProps.connection.status !== \"connected\" ||\n- this.props.getClientResponses !== prevProps.getClientResponses)\n- ) {\n- this.possiblySendReduxClientResponses();\n- }\n-\nif (this.props.activeThread !== prevProps.activeThread) {\nconst activityUpdates = [];\nif (prevProps.activeThread) {\n@@ -218,6 +210,24 @@ class Socket extends React.PureComponent<Props> {\n);\n}\n}\n+\n+ if (\n+ this.props.connection.status === \"connected\" &&\n+ (prevProps.connection.status !== \"connected\" ||\n+ this.props.getClientResponses !== prevProps.getClientResponses)\n+ ) {\n+ const clientResponses = this.props.getClientResponses();\n+ this.sendClientResponses(clientResponses);\n+ }\n+\n+ if (\n+ this.props.connection.status === \"connected\" &&\n+ (prevProps.connection.status !== \"connected\" ||\n+ this.props.connection.queuedActivityUpdates !==\n+ prevProps.connection.queuedActivityUpdates)\n+ ) {\n+ this.sendActivityUpdates(this.props.connection.queuedActivityUpdates);\n+ }\n}\nrender() {\n@@ -363,11 +373,6 @@ class Socket extends React.PureComponent<Props> {\nthis.sendMessage(initialMessage);\n}\n- possiblySendReduxClientResponses() {\n- const clientResponses = this.props.getClientResponses();\n- this.sendClientResponses(clientResponses);\n- }\n-\nsendClientResponses(clientResponses: $ReadOnlyArray<ClientResponse>) {\nif (clientResponses.length === 0) {\nreturn;\n@@ -437,22 +442,22 @@ class Socket extends React.PureComponent<Props> {\nthis.transitStatuses = newTransitStatuses;\n}\n- filterInTransitClientResponses(\n- clientResponses: $ReadOnlyArray<ClientResponse>,\n- ): ClientResponse[] {\n+ filterInTransitActivityUpdates(\n+ activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n+ ): ActivityUpdate[] {\nconst filtered = [];\n- for (let clientResponse of clientResponses) {\n+ for (let activityUpdate of activityUpdates) {\nlet inTransit = false;\nfor (let transitStatus of this.transitStatuses) {\n- if (transitStatus.type !== \"ClientResponse\") {\n+ if (transitStatus.type !== \"ActivityUpdate\") {\ncontinue;\n}\nconst {\n- clientResponse: inTransitClientResponse,\n+ activityUpdate: inTransitActivityUpdate,\nmessageID,\n} = transitStatus;\nif (\n- inTransitClientResponse === clientResponse &&\n+ inTransitActivityUpdate === activityUpdate &&\nmessageID !== null && messageID !== undefined\n) {\ninTransit = true;\n@@ -460,7 +465,7 @@ class Socket extends React.PureComponent<Props> {\n}\n}\nif (!inTransit) {\n- filtered.push(clientResponse);\n+ filtered.push(activityUpdate);\n}\n}\nreturn filtered;\n@@ -497,12 +502,12 @@ class Socket extends React.PureComponent<Props> {\nif (deliveredResponses.length > 0) {\n// Note: it's hypothetically possible for something to call\n- // possiblySendReduxClientResponses after we update this.transitStatuses\n- // but before this Redux action propagates to this component. In that\n- // case, we could double-send some Redux-cached ClientResponses. Since\n- // right now only inconsistency responses are Redux-cached, and the server\n- // knows how to dedup those so that the transaction is idempotent, we're\n- // not going to worry about it.\n+ // sendClientResponses after we update this.transitStatuses but before\n+ // this Redux action propagates to this component. In that case, we could\n+ // double-send some Redux-cached ClientResponses. Since right now only\n+ // inconsistency responses are Redux-cached, and the server knows how to\n+ // dedup those so that the transaction is idempotent, we're not going to\n+ // worry about it.\nthis.props.dispatchActionPayload(\nclearDeliveredClientResponsesActionType,\n{ clientResponses: deliveredResponses },\n@@ -549,7 +554,9 @@ class Socket extends React.PureComponent<Props> {\n...this.transitStatuses,\n...newTransitStatuses,\n];\n- // TODO: send update to client\n+ this.sendActivityUpdates(\n+ newTransitStatuses.map(transitStatus => transitStatus.activityUpdate),\n+ );\n}\n}\n@@ -563,6 +570,23 @@ class Socket extends React.PureComponent<Props> {\n);\n}\n+ sendActivityUpdates(activityUpdates: $ReadOnlyArray<ActivityUpdate>) {\n+ if (activityUpdates.length === 0) {\n+ return;\n+ }\n+ const filtered = this.filterInTransitActivityUpdates(activityUpdates);\n+ if (filtered.length === 0) {\n+ return;\n+ }\n+ const messageID = this.nextClientMessageID++;\n+ this.markActivityUpdatesAsInTransit(filtered, messageID);\n+ this.sendMessage({\n+ type: clientSocketMessageTypes.ACTIVITY_UPDATES,\n+ id: messageID,\n+ payload: { activityUpdates: filtered },\n+ });\n+ }\n+\nmarkActivityUpdatesAsInTransit(\nactivityUpdates: $ReadOnlyArray<ActivityUpdate>,\nmessageID: number,\n@@ -614,6 +638,35 @@ class Socket extends React.PureComponent<Props> {\nthis.transitStatuses = newTransitStatuses;\n}\n+ filterInTransitClientResponses(\n+ clientResponses: $ReadOnlyArray<ClientResponse>,\n+ ): ClientResponse[] {\n+ const filtered = [];\n+ for (let clientResponse of clientResponses) {\n+ let inTransit = false;\n+ for (let transitStatus of this.transitStatuses) {\n+ if (transitStatus.type !== \"ClientResponse\") {\n+ continue;\n+ }\n+ const {\n+ clientResponse: inTransitClientResponse,\n+ messageID,\n+ } = transitStatus;\n+ if (\n+ inTransitClientResponse === clientResponse &&\n+ messageID !== null && messageID !== undefined\n+ ) {\n+ inTransit = true;\n+ break;\n+ }\n+ }\n+ if (!inTransit) {\n+ filtered.push(clientResponse);\n+ }\n+ }\n+ return filtered;\n+ }\n+\n}\nexport default Socket;\n" }, { "change_type": "MODIFY", "old_path": "lib/types/socket-types.js", "new_path": "lib/types/socket-types.js", "diff": "@@ -22,6 +22,7 @@ import { pingResponseTypes } from './ping-types';\nexport const clientSocketMessageTypes = Object.freeze({\nINITIAL: 0,\nRESPONSES: 1,\n+ ACTIVITY_UPDATES: 2,\n});\nexport type ClientSocketMessageType = $Values<typeof clientSocketMessageTypes>;\nexport function assertClientSocketMessageType(\n@@ -29,7 +30,8 @@ export function assertClientSocketMessageType(\n): ClientSocketMessageType {\ninvariant(\nourClientSocketMessageType === 0 ||\n- ourClientSocketMessageType === 1,\n+ ourClientSocketMessageType === 1 ||\n+ ourClientSocketMessageType === 2,\n\"number is not ClientSocketMessageType enum\",\n);\nreturn ourClientSocketMessageType;\n@@ -51,9 +53,17 @@ export type ResponsesClientSocketMessage = {|\nclientResponses: $ReadOnlyArray<ClientResponse>,\n|},\n|};\n+export type ActivityUpdatesClientSocketMessage = {|\n+ type: 2,\n+ id: number,\n+ payload: {|\n+ activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n+ |},\n+|};\nexport type ClientSocketMessage =\n| InitialClientSocketMessage\n- | ResponsesClientSocketMessage;\n+ | ResponsesClientSocketMessage\n+ | ActivityUpdatesClientSocketMessage;\n// The types of messages that the server sends across the socket\nexport const serverSocketMessageTypes = Object.freeze({\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Send activity updates once they are queued
129,187
22.10.2018 15:43:55
14,400
32cf8cac1372e9b79e5f4f73d7d00e26fd2ae84a
Server support for client ActivityUpdate socket message
[ { "change_type": "MODIFY", "old_path": "lib/components/socket.react.js", "new_path": "lib/components/socket.react.js", "diff": "@@ -24,7 +24,8 @@ import {\nconnectionInfoPropType,\ntype ConnectionInfo,\nqueueActivityUpdatesActionType,\n- clearQueuedActivityUpdatesActionType,\n+ activityUpdateSuccessActionType,\n+ activityUpdateFailedActionType,\n} from '../types/socket-types';\nimport type { ActivityUpdate } from '../types/activity-types';\nimport type { Dispatch } from '../types/redux-types';\n@@ -220,13 +221,19 @@ class Socket extends React.PureComponent<Props> {\nthis.sendClientResponses(clientResponses);\n}\n+ const { queuedActivityUpdates } = this.props.connection;\n+ if (queuedActivityUpdates !== prevProps.connection.queuedActivityUpdates) {\n+ this.transitStatuses = this.transitStatuses.filter(\n+ transitStatus => transitStatus.type !== \"ActivityUpdate\" ||\n+ queuedActivityUpdates.includes(transitStatus.activityUpdate),\n+ );\n+ }\nif (\nthis.props.connection.status === \"connected\" &&\n(prevProps.connection.status !== \"connected\" ||\n- this.props.connection.queuedActivityUpdates !==\n- prevProps.connection.queuedActivityUpdates)\n+ queuedActivityUpdates !== prevProps.connection.queuedActivityUpdates)\n) {\n- this.sendActivityUpdates(this.props.connection.queuedActivityUpdates);\n+ this.sendActivityUpdates(queuedActivityUpdates);\n}\n}\n@@ -323,6 +330,25 @@ class Socket extends React.PureComponent<Props> {\n},\n);\n}\n+ } else if (\n+ message.type === serverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE\n+ ) {\n+ const deliveredActivityUpdates = [];\n+ for (let transitStatus of this.transitStatuses) {\n+ if (\n+ transitStatus.type === \"ActivityUpdate\" &&\n+ transitStatus.messageID === message.responseTo\n+ ) {\n+ deliveredActivityUpdates.push(transitStatus.activityUpdate);\n+ }\n+ }\n+ this.props.dispatchActionPayload(\n+ activityUpdateSuccessActionType,\n+ {\n+ activityUpdates: deliveredActivityUpdates,\n+ result: message.payload,\n+ },\n+ );\n}\n}\n@@ -473,7 +499,7 @@ class Socket extends React.PureComponent<Props> {\nupdateTransitStatusesWithServerResponse(success: bool, messageID: number) {\nconst deliveredResponses = [], erroredResponseStatuses = [];\n- const deliveredActivityUpdates = [], erroredActivityUpdateStatuses = [];\n+ const failedActivityUpdates = [], erroredActivityUpdateStatuses = [];\nconst stillInTransit = [];\nfor (let transitStatus of this.transitStatuses) {\nif (\n@@ -487,10 +513,12 @@ class Socket extends React.PureComponent<Props> {\n}\n} else if (\ntransitStatus.type === \"ActivityUpdate\" &&\n- transitStatus.messageID === messageID\n+ transitStatus.messageID === messageID &&\n+ !success\n) {\n- if (success || transitStatus.status === \"errored\") {\n- deliveredActivityUpdates.push(transitStatus.activityUpdate);\n+ if (transitStatus.status === \"errored\") {\n+ failedActivityUpdates.push(transitStatus.activityUpdate);\n+ stillInTransit.push(transitStatus);\n} else {\nerroredActivityUpdateStatuses.push(transitStatus);\n}\n@@ -514,13 +542,10 @@ class Socket extends React.PureComponent<Props> {\n);\n}\n- if (deliveredActivityUpdates.length > 0) {\n- // Same possibility as above. Our transactions this time aren't\n- // idempotent, but we don't expect this race condition to happen often.\n- // TODO: see if there is an issue here\n+ if (failedActivityUpdates.length > 0) {\nthis.props.dispatchActionPayload(\n- clearQueuedActivityUpdatesActionType,\n- { activityUpdates: deliveredActivityUpdates },\n+ activityUpdateFailedActionType,\n+ { activityUpdates: failedActivityUpdates },\n);\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/connection-reducer.js", "new_path": "lib/reducers/connection-reducer.js", "diff": "@@ -5,7 +5,8 @@ import {\ntype ConnectionInfo,\nupdateConnectionStatusActionType,\nqueueActivityUpdatesActionType,\n- clearQueuedActivityUpdatesActionType,\n+ activityUpdateSuccessActionType,\n+ activityUpdateFailedActionType,\n} from '../types/socket-types';\nimport { setNewSessionActionType } from '../utils/action-utils';\n@@ -43,7 +44,10 @@ export default function reduceConnectionInfo(\n...activityUpdates,\n],\n};\n- } else if (action.type === clearQueuedActivityUpdatesActionType) {\n+ } else if (\n+ action.type === activityUpdateSuccessActionType ||\n+ action.type === activityUpdateFailedActionType\n+ ) {\nconst { payload } = action;\nreturn {\n...state,\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/thread-reducer.js", "new_path": "lib/reducers/thread-reducer.js", "diff": "@@ -12,6 +12,7 @@ import {\nimport {\nfullStateSyncActionType,\nincrementalStateSyncActionType,\n+ activityUpdateSuccessActionType,\n} from '../types/socket-types';\nimport invariant from 'invariant';\n@@ -321,6 +322,18 @@ export default function reduceThreadInfos(\n...newInconsistencies,\n],\n};\n+ } else if (action.type === activityUpdateSuccessActionType) {\n+ const newThreadInfos = { ...state.threadInfos };\n+ for (let setToUnread of action.payload.result.unfocusedToUnread) {\n+ const threadInfo = newThreadInfos[setToUnread];\n+ if (threadInfo) {\n+ threadInfo.currentUser.unread = true;\n+ }\n+ }\n+ return {\n+ threadInfos: newThreadInfos,\n+ inconsistencyResponses: state.inconsistencyResponses,\n+ };\n}\nreturn state;\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/types/redux-types.js", "new_path": "lib/types/redux-types.js", "diff": "@@ -60,7 +60,8 @@ import type {\nStateSyncIncrementalActionPayload,\nUpdateConnectionStatusPayload,\nQueueActivityUpdatesPayload,\n- ClearActivityUpdatesPayload,\n+ ActivityUpdateSuccessPayload,\n+ ActivityUpdateFailedPayload,\n} from '../types/socket-types';\nexport type BaseAppState<NavInfo: BaseNavInfo> = {\n@@ -577,8 +578,11 @@ export type BaseAction =\ntype: \"QUEUE_ACTIVITY_UPDATES\",\npayload: QueueActivityUpdatesPayload,\n|} | {|\n- type: \"CLEAR_QUEUED_ACTIVITY_UPDATES\",\n- payload: ClearActivityUpdatesPayload,\n+ type: \"ACTIVITY_UPDATE_SUCCESS\",\n+ payload: ActivityUpdateSuccessPayload,\n+ |} | {|\n+ type: \"ACTIVITY_UPDATE_FAILED\",\n+ payload: ActivityUpdateFailedPayload,\n|};\nexport type ActionPayload\n" }, { "change_type": "MODIFY", "old_path": "lib/types/socket-types.js", "new_path": "lib/types/socket-types.js", "diff": "@@ -11,7 +11,11 @@ import type {\nLoggedOutUserInfo,\n} from './user-types';\nimport type { RawEntryInfo } from './entry-types';\n-import { type ActivityUpdate, activityUpdatePropType } from './activity-types';\n+import {\n+ type ActivityUpdate,\n+ type UpdateActivityResult,\n+ activityUpdatePropType,\n+} from './activity-types';\nimport invariant from 'invariant';\nimport PropTypes from 'prop-types';\n@@ -71,6 +75,7 @@ export const serverSocketMessageTypes = Object.freeze({\nREQUESTS: 1,\nERROR: 2,\nAUTH_ERROR: 3,\n+ ACTIVITY_UPDATE_RESPONSE: 4,\n});\nexport type ServerSocketMessageType = $Values<typeof serverSocketMessageTypes>;\nexport function assertServerSocketMessageType(\n@@ -80,7 +85,8 @@ export function assertServerSocketMessageType(\nourServerSocketMessageType === 0 ||\nourServerSocketMessageType === 1 ||\nourServerSocketMessageType === 2 ||\n- ourServerSocketMessageType === 3,\n+ ourServerSocketMessageType === 3 ||\n+ ourServerSocketMessageType === 4,\n\"number is not ServerSocketMessageType enum\",\n);\nreturn ourServerSocketMessageType;\n@@ -146,11 +152,17 @@ export type AuthErrorServerSocketMessage = {|\ncurrentUserInfo: LoggedOutUserInfo,\n},\n|};\n+export type ActivityUpdateResponseServerSocketMessage = {|\n+ type: 4,\n+ responseTo: number,\n+ payload: UpdateActivityResult,\n+|};\nexport type ServerSocketMessage =\n| StateSyncServerSocketMessage\n| RequestsServerSocketMessage\n| ErrorServerSocketMessage\n- | AuthErrorServerSocketMessage;\n+ | AuthErrorServerSocketMessage\n+ | ActivityUpdateResponseServerSocketMessage;\nexport type ConnectionStatus =\n| \"connecting\"\n@@ -186,8 +198,12 @@ export const queueActivityUpdatesActionType = \"QUEUE_ACTIVITY_UPDATES\";\nexport type QueueActivityUpdatesPayload = {|\nactivityUpdates: $ReadOnlyArray<ActivityUpdate>,\n|};\n-export const clearQueuedActivityUpdatesActionType =\n- \"CLEAR_QUEUED_ACTIVITY_UPDATES\";\n-export type ClearActivityUpdatesPayload = {|\n+export const activityUpdateSuccessActionType = \"ACTIVITY_UPDATE_SUCCESS\";\n+export type ActivityUpdateSuccessPayload = {|\n+ activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n+ result: UpdateActivityResult,\n+|};\n+export const activityUpdateFailedActionType = \"ACTIVITY_UPDATE_FAILED\";\n+export type ActivityUpdateFailedPayload = {|\nactivityUpdates: $ReadOnlyArray<ActivityUpdate>,\n|};\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/ping-responders.js", "new_path": "server/src/responders/ping-responders.js", "diff": "@@ -28,6 +28,7 @@ import type {\n} from 'lib/types/entry-types';\nimport { sessionCheckFrequency } from 'lib/types/session-types';\nimport type { CurrentUserInfo } from 'lib/types/user-types';\n+import type { UpdateActivityResult } from 'lib/types/activity-types';\nimport type { SessionUpdate } from '../updaters/session-updaters';\nimport t from 'tcomb';\n@@ -363,6 +364,7 @@ type StateCheckStatus =\ntype ProcessClientResponsesResult = {|\nserverRequests: ServerRequest[],\nstateCheckStatus: ?StateCheckStatus,\n+ activityUpdateResult: ?UpdateActivityResult,\n|};\nasync function processClientResponses(\nviewer: Viewer,\n@@ -380,6 +382,7 @@ async function processClientResponses(\nisDeviceType(viewer.platform) && viewer.loggedIn && !viewer.deviceToken;\nconst promises = [];\n+ let activityUpdates = [];\nlet stateCheckStatus = null;\nif (clientResponses) {\nconst clientSentPlatformDetails = clientResponses.some(\n@@ -438,10 +441,7 @@ async function processClientResponses(\n} else if (\nclientResponse.type === serverRequestTypes.INITIAL_ACTIVITY_UPDATES\n) {\n- promises.push(activityUpdater(\n- viewer,\n- { updates: clientResponse.activityUpdates },\n- ));\n+ activityUpdates = [...activityUpdates, ...clientResponse.activityUpdates];\n} else if (clientResponse.type === serverRequestTypes.CHECK_STATE) {\nconst invalidKeys = [];\nfor (let key in clientResponse.hashResults) {\n@@ -457,8 +457,21 @@ async function processClientResponses(\n}\n}\n- if (promises.length > 0) {\n- await Promise.all(promises);\n+ if (activityUpdates.length > 0) {\n+ promises.push(activityUpdater(\n+ viewer,\n+ { updates: activityUpdates },\n+ ));\n+ }\n+\n+ let activityUpdateResult;\n+ if (activityUpdates.length > 0 || promises.length > 0) {\n+ [ activityUpdateResult ] = await Promise.all([\n+ activityUpdates.length > 0\n+ ? activityUpdater(viewer, { updates: activityUpdates })\n+ : undefined,\n+ promises.length > 0 ? Promise.all(promises) : undefined,\n+ ]);\n}\nif (\n@@ -479,7 +492,7 @@ async function processClientResponses(\nif (viewerMissingDeviceToken) {\nserverRequests.push({ type: serverRequestTypes.DEVICE_TOKEN });\n}\n- return { serverRequests, stateCheckStatus };\n+ return { serverRequests, stateCheckStatus, activityUpdateResult };\n}\nasync function recordThreadInconsistency(\n" }, { "change_type": "MODIFY", "old_path": "server/src/socket.js", "new_path": "server/src/socket.js", "diff": "@@ -6,6 +6,7 @@ import {\ntype ClientSocketMessage,\ntype InitialClientSocketMessage,\ntype ResponsesClientSocketMessage,\n+ type ActivityUpdatesClientSocketMessage,\ntype StateSyncFullSocketPayload,\ntype ServerSocketMessage,\ntype ErrorServerSocketMessage,\n@@ -50,7 +51,10 @@ import { fetchMessageInfosSince } from './fetchers/message-fetchers';\nimport { fetchThreadInfos } from './fetchers/thread-fetchers';\nimport { fetchEntryInfos } from './fetchers/entry-fetchers';\nimport { fetchCurrentUserInfo } from './fetchers/user-fetchers';\n-import { updateActivityTime } from './updaters/activity-updaters';\n+import {\n+ updateActivityTime,\n+ activityUpdater,\n+} from './updaters/activity-updaters';\nimport {\ndeleteUpdatesBeforeTimeTargettingSession,\n} from './deleters/update-deleters';\n@@ -60,6 +64,9 @@ import { handleAsyncPromise } from './responders/handlers';\nimport { deleteCookie } from './deleters/cookie-deleters';\nimport { createNewAnonymousCookie } from './session/cookies';\nimport { deleteForViewerSession } from './deleters/activity-deleters';\n+import {\n+ activityUpdatesInputValidator,\n+} from './responders/activity-responders';\nconst clientSocketMessageInputValidator = t.union([\ntShape({\n@@ -92,6 +99,16 @@ const clientSocketMessageInputValidator = t.union([\nclientResponses: t.list(clientResponseInputValidator),\n}),\n}),\n+ tShape({\n+ type: t.irreducible(\n+ 'clientSocketMessageTypes.ACTIVITY_UPDATES',\n+ x => x === clientSocketMessageTypes.ACTIVITY_UPDATES,\n+ ),\n+ id: t.Number,\n+ payload: tShape({\n+ activityUpdates: activityUpdatesInputValidator,\n+ }),\n+ }),\n]);\ntype SendMessageFunc = (message: ServerSocketMessage) => void;\n@@ -249,6 +266,8 @@ async function handleClientSocketMessage(\nreturn await handleInitialClientSocketMessage(viewer, message);\n} else if (message.type === clientSocketMessageTypes.RESPONSES) {\nreturn await handleResponsesClientSocketMessage(viewer, message);\n+ } else if (message.type === clientSocketMessageTypes.ACTIVITY_UPDATES) {\n+ return await handleActivityUpdatesClientSocketMessage(viewer, message);\n}\nreturn [];\n}\n@@ -281,7 +300,7 @@ async function handleInitialClientSocketMessage(\nconst threadSelectionCriteria = { threadCursors, joinedThreads: true };\nconst [\nfetchMessagesResult,\n- { serverRequests, stateCheckStatus },\n+ { serverRequests, stateCheckStatus, activityUpdateResult },\n] = await Promise.all([\nfetchMessageInfosSince(\nviewer,\n@@ -409,6 +428,14 @@ async function handleInitialClientSocketMessage(\n});\n}\n+ if (activityUpdateResult) {\n+ responses.push({\n+ type: serverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE,\n+ responseTo: message.id,\n+ payload: activityUpdateResult,\n+ });\n+ }\n+\nreturn responses;\n}\n@@ -446,6 +473,21 @@ async function handleResponsesClientSocketMessage(\n}];\n}\n+async function handleActivityUpdatesClientSocketMessage(\n+ viewer: Viewer,\n+ message: ActivityUpdatesClientSocketMessage,\n+): Promise<ServerSocketMessage[]> {\n+ const result = await activityUpdater(\n+ viewer,\n+ { updates: message.payload.activityUpdates },\n+ );\n+ return [{\n+ type: serverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE,\n+ responseTo: message.id,\n+ payload: result,\n+ }];\n+}\n+\nexport {\nonConnection,\n};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Server support for client ActivityUpdate socket message
129,187
22.10.2018 15:49:12
14,400
d8b7bdc93c8340f09d836ee47f099c8230e58a6e
Get rid of activity update code from App component Socket component handles it now.
[ { "change_type": "DELETE", "old_path": "lib/actions/activity-actions.js", "new_path": null, "diff": "-// @flow\n-\n-import type { FetchJSON } from '../utils/fetch-json';\n-import type {\n- ActivityUpdate,\n- UpdateActivityResult,\n-} from '../types/activity-types';\n-\n-const updateActivityActionTypes = Object.freeze({\n- started: \"UPDATE_ACTIVITY_STARTED\",\n- success: \"UPDATE_ACTIVITY_SUCCESS\",\n- failed: \"UPDATE_ACTIVITY_FAILED\",\n-});\n-async function updateActivity(\n- fetchJSON: FetchJSON,\n- activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n-): Promise<UpdateActivityResult> {\n- const response = await fetchJSON(\n- 'update_activity',\n- { updates: activityUpdates },\n- );\n- return {\n- unfocusedToUnread: response.unfocusedToUnread,\n- };\n-}\n-\n-export {\n- updateActivityActionTypes,\n- updateActivity,\n-}\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/thread-reducer.js", "new_path": "lib/reducers/thread-reducer.js", "diff": "@@ -36,7 +36,6 @@ import {\njoinThreadActionTypes,\nleaveThreadActionTypes,\n} from '../actions/thread-actions';\n-import { updateActivityActionTypes } from '../actions/activity-actions';\nimport { saveMessagesActionType } from '../actions/message-actions';\nimport { getConfig } from '../utils/config';\nimport { reduxLogger } from '../utils/redux-logger';\n@@ -219,18 +218,6 @@ export default function reduceThreadInfos(\n),\n],\n};\n- } else if (action.type === updateActivityActionTypes.success) {\n- const newThreadInfos = { ...state.threadInfos };\n- for (let setToUnread of action.payload.unfocusedToUnread) {\n- const threadInfo = newThreadInfos[setToUnread];\n- if (threadInfo) {\n- threadInfo.currentUser.unread = true;\n- }\n- }\n- return {\n- threadInfos: newThreadInfos,\n- inconsistencyResponses: state.inconsistencyResponses,\n- };\n} else if (action.type === updateSubscriptionActionTypes.success) {\nconst newThreadInfos = {\n...state.threadInfos,\n" }, { "change_type": "MODIFY", "old_path": "lib/types/redux-types.js", "new_path": "lib/types/redux-types.js", "diff": "@@ -42,7 +42,6 @@ import type {\nSaveMessagesPayload,\n} from './message-types';\nimport type { SetSessionPayload } from './session-types';\n-import type { UpdateActivityResult } from './activity-types';\nimport type { ReportCreationResponse } from './report-types';\nimport type {\nClearDeliveredClientResponsesPayload,\n@@ -466,19 +465,6 @@ export type BaseAction =\nkey: string,\ndraft: string,\n},\n- |} | {|\n- type: \"UPDATE_ACTIVITY_STARTED\",\n- payload?: void,\n- loadingInfo: LoadingInfo,\n- |} | {|\n- type: \"UPDATE_ACTIVITY_FAILED\",\n- error: true,\n- payload: Error,\n- loadingInfo: LoadingInfo,\n- |} | {|\n- type: \"UPDATE_ACTIVITY_SUCCESS\",\n- payload: UpdateActivityResult,\n- loadingInfo: LoadingInfo,\n|} | {|\ntype: \"SET_DEVICE_TOKEN_STARTED\",\npayload: string,\n" }, { "change_type": "MODIFY", "old_path": "native/app.react.js", "new_path": "native/app.react.js", "diff": "@@ -11,10 +11,6 @@ import type {\nDispatchActionPayload,\nDispatchActionPromise,\n} from 'lib/utils/action-utils';\n-import type {\n- ActivityUpdate,\n- UpdateActivityResult,\n-} from 'lib/types/activity-types';\nimport type { RawThreadInfo } from 'lib/types/thread-types';\nimport { rawThreadInfoPropType } from 'lib/types/thread-types';\nimport type { DeviceType } from 'lib/types/device-types';\n@@ -47,10 +43,6 @@ import SplashScreen from 'react-native-splash-screen';\nimport { registerConfig } from 'lib/utils/config';\nimport { connect } from 'lib/utils/redux-utils';\n-import {\n- updateActivityActionTypes,\n- updateActivity,\n-} from 'lib/actions/activity-actions';\nimport {\nsetDeviceTokenActionTypes,\nsetDeviceToken,\n@@ -113,7 +105,6 @@ type Props = {\nactiveThread: ?string,\nappLoggedIn: bool,\nloggedIn: bool,\n- activeThreadLatestMessage: ?string,\ndeviceToken: ?string,\nunreadCount: number,\nrawThreadInfos: {[id: string]: RawThreadInfo},\n@@ -124,9 +115,6 @@ type Props = {\ndispatchActionPayload: DispatchActionPayload,\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n- updateActivity: (\n- activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n- ) => Promise<UpdateActivityResult>,\nsetDeviceToken: (\ndeviceToken: string,\ndeviceType: DeviceType,\n@@ -142,7 +130,6 @@ class AppWithNavigationState extends React.PureComponent<Props, State> {\nactiveThread: PropTypes.string,\nappLoggedIn: PropTypes.bool.isRequired,\nloggedIn: PropTypes.bool.isRequired,\n- activeThreadLatestMessage: PropTypes.string,\ndeviceToken: PropTypes.string,\nunreadCount: PropTypes.number.isRequired,\nrawThreadInfos: PropTypes.objectOf(rawThreadInfoPropType).isRequired,\n@@ -151,7 +138,6 @@ class AppWithNavigationState extends React.PureComponent<Props, State> {\ndispatch: PropTypes.func.isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\n- updateActivity: PropTypes.func.isRequired,\nsetDeviceToken: PropTypes.func.isRequired,\n};\nstate = {\n@@ -333,23 +319,11 @@ class AppWithNavigationState extends React.PureComponent<Props, State> {\nthis.currentState.match(/inactive|background/)\n) {\nthis.props.dispatchActionPayload(backgroundActionType, null);\n- this.closingApp();\n+ appBecameInactive();\n}\n}\ncomponentWillReceiveProps(nextProps: Props) {\n- const justLoggedIn = nextProps.loggedIn && !this.props.loggedIn;\n- if (\n- !justLoggedIn &&\n- nextProps.activeThread !== this.props.activeThread\n- ) {\n- this.updateFocusedThreads(\n- nextProps,\n- this.props.activeThread,\n- this.props.activeThreadLatestMessage,\n- );\n- }\n-\nconst nextActiveThread = nextProps.activeThread;\nif (nextActiveThread && nextActiveThread !== this.props.activeThread) {\nAppWithNavigationState.clearNotifsOfThread(nextProps);\n@@ -664,58 +638,6 @@ class AppWithNavigationState extends React.PureComponent<Props, State> {\n}\n}\n- updateFocusedThreads(\n- props: Props,\n- oldActiveThread: ?string,\n- oldActiveThreadLatestMessage: ?string,\n- ) {\n- if (!props.appLoggedIn || this.currentState !== \"active\") {\n- // If the app isn't logged in, the server isn't tracking our activity\n- // anyways. If the currentState isn't active, we can expect that when it\n- // becomes active, the socket initialization will include any activity\n- // update that it needs to update the server. We want to avoid any races\n- // between update_activity and socket initialization, so we return here.\n- return;\n- }\n- const updates = [];\n- if (props.activeThread) {\n- updates.push({\n- focus: true,\n- threadID: props.activeThread,\n- });\n- }\n- if (oldActiveThread && oldActiveThread !== props.activeThread) {\n- updates.push({\n- focus: false,\n- threadID: oldActiveThread,\n- latestMessage: oldActiveThreadLatestMessage,\n- });\n- }\n- if (updates.length === 0) {\n- return;\n- }\n- props.dispatchActionPromise(\n- updateActivityActionTypes,\n- props.updateActivity(updates),\n- );\n- }\n-\n- closingApp() {\n- appBecameInactive();\n- if (!this.props.appLoggedIn || !this.props.activeThread) {\n- return;\n- }\n- const updates = [{\n- focus: false,\n- threadID: this.props.activeThread,\n- latestMessage: this.props.activeThreadLatestMessage,\n- }];\n- this.props.dispatchActionPromise(\n- updateActivityActionTypes,\n- this.props.updateActivity(updates),\n- );\n- }\n-\nrender() {\nconst inAppNotificationHeight = DeviceInfo.isIPhoneX_deprecated ? 104 : 80;\nreturn (\n@@ -749,18 +671,13 @@ const styles = StyleSheet.create({\nconst ConnectedAppWithNavigationState = connect(\n(state: AppState) => {\n- const activeThread = activeThreadSelector(state);\nconst appLoggedIn = appLoggedInSelector(state);\nreturn {\nnavigationState: state.navInfo.navigationState,\n- activeThread,\n+ activeThread: activeThreadSelector(state),\nappLoggedIn,\nloggedIn: appLoggedIn &&\n!!(state.currentUserInfo && !state.currentUserInfo.anonymous && true),\n- activeThreadLatestMessage:\n- activeThread && state.messageStore.threads[activeThread]\n- ? state.messageStore.threads[activeThread].messageIDs[0]\n- : null,\ndeviceToken: state.deviceToken,\nunreadCount: unreadCount(state),\nrawThreadInfos: state.threadStore.threadInfos,\n@@ -768,7 +685,7 @@ const ConnectedAppWithNavigationState = connect(\nupdatesCurrentAsOf: state.updatesCurrentAsOf,\n};\n},\n- { updateActivity, setDeviceToken },\n+ { setDeviceToken },\n)(AppWithNavigationState);\nconst App = (props: {}) =>\n" }, { "change_type": "MODIFY", "old_path": "web/app.react.js", "new_path": "web/app.react.js", "diff": "@@ -13,10 +13,6 @@ import {\ncalendarQueryPropType,\ntype CalendarQueryUpdateStartingPayload,\n} from 'lib/types/entry-types';\n-import type {\n- ActivityUpdate,\n- UpdateActivityResult,\n-} from 'lib/types/activity-types';\nimport * as React from 'react';\nimport invariant from 'invariant';\n@@ -49,10 +45,6 @@ import {\nmostRecentReadThreadSelector,\nunreadCount,\n} from 'lib/selectors/thread-selectors';\n-import {\n- updateActivityActionTypes,\n- updateActivity,\n-} from 'lib/actions/activity-actions';\nimport { activeThreadSelector } from './selectors/nav-selectors';\nimport { canonicalURLFromReduxState, navInfoFromURL } from './url-utils';\n@@ -99,9 +91,7 @@ type Props = {\nloggedIn: bool,\nincludeDeleted: bool,\nmostRecentReadThread: ?string,\n- activeThread: ?string,\nactiveThreadCurrentlyUnread: bool,\n- activeThreadLatestMessage: ?string,\nviewerID: ?string,\nunreadCount: number,\nactualizedCalendarQuery: CalendarQuery,\n@@ -113,9 +103,6 @@ type Props = {\ncalendarQuery: CalendarQuery,\nreduxAlreadyUpdated?: bool,\n) => Promise<CalendarQueryUpdateResult>,\n- updateActivity: (\n- activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n- ) => Promise<UpdateActivityResult>,\n};\ntype State = {|\ncurrentModal: ?React.Node,\n@@ -134,16 +121,13 @@ class App extends React.PureComponent<Props, State> {\nloggedIn: PropTypes.bool.isRequired,\nincludeDeleted: PropTypes.bool.isRequired,\nmostRecentReadThread: PropTypes.string,\n- activeThread: PropTypes.string,\nactiveThreadCurrentlyUnread: PropTypes.bool.isRequired,\n- activeThreadLatestMessage: PropTypes.string,\nviewerID: PropTypes.string,\nunreadCount: PropTypes.number.isRequired,\nactualizedCalendarQuery: calendarQueryPropType.isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nupdateCalendarQuery: PropTypes.func.isRequired,\n- updateActivity: PropTypes.func.isRequired,\n};\nstate = {\ncurrentModal: null,\n@@ -192,55 +176,6 @@ class App extends React.PureComponent<Props, State> {\nonVisibilityChange = (e, state: string) => {\nthis.setState({ visible: state === \"visible\" });\n- if (state !== \"visible\") {\n- this.closingApp();\n- }\n- }\n-\n- static updateFocusedThreads(\n- props: Props,\n- oldActiveThread: ?string,\n- oldActiveThreadLatestMessage: ?string,\n- ) {\n- if (!props.loggedIn) {\n- return;\n- }\n- const updates = [];\n- if (props.activeThread) {\n- updates.push({\n- focus: true,\n- threadID: props.activeThread,\n- });\n- }\n- if (oldActiveThread && oldActiveThread !== props.activeThread) {\n- updates.push({\n- focus: false,\n- threadID: oldActiveThread,\n- latestMessage: oldActiveThreadLatestMessage,\n- });\n- }\n- if (updates.length === 0) {\n- return;\n- }\n- props.dispatchActionPromise(\n- updateActivityActionTypes,\n- props.updateActivity(updates),\n- );\n- }\n-\n- closingApp() {\n- if (!this.props.loggedIn || !this.props.activeThread) {\n- return;\n- }\n- const updates = [{\n- focus: false,\n- threadID: this.props.activeThread,\n- latestMessage: this.props.activeThreadLatestMessage,\n- }];\n- this.props.dispatchActionPromise(\n- updateActivityActionTypes,\n- this.props.updateActivity(updates),\n- );\n}\ncomponentDidUpdate(prevProps: Props) {\n@@ -318,12 +253,6 @@ class App extends React.PureComponent<Props, State> {\nif (nextProps.location.pathname !== newURL) {\nhistory.replace(newURL);\n}\n- } else if (nextProps.activeThread !== this.props.activeThread) {\n- App.updateFocusedThreads(\n- nextProps,\n- this.props.activeThread,\n- this.props.activeThreadLatestMessage,\n- );\n}\nconst justLoggedOut = !nextProps.loggedIn && this.props.loggedIn;\n@@ -487,17 +416,12 @@ export default connect(\n!state.currentUserInfo.anonymous && true),\nincludeDeleted: includeDeletedSelector(state),\nmostRecentReadThread: mostRecentReadThreadSelector(state),\n- activeThread: activeThreadSelector(state),\nactiveThreadCurrentlyUnread: !activeChatThreadID ||\nstate.threadStore.threadInfos[activeChatThreadID].currentUser.unread,\n- activeThreadLatestMessage:\n- activeChatThreadID && state.messageStore.threads[activeChatThreadID]\n- ? state.messageStore.threads[activeChatThreadID].messageIDs[0]\n- : null,\nviewerID: state.currentUserInfo && state.currentUserInfo.id,\nunreadCount: unreadCount(state),\nactualizedCalendarQuery: state.entryStore.actualizedCalendarQuery,\n};\n},\n- { updateCalendarQuery, updateActivity },\n+ { updateCalendarQuery },\n)(App);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Get rid of activity update code from App component Socket component handles it now.
129,187
23.10.2018 10:14:28
14,400
5862d4de310d33c2f086dd7cea226f3090944a08
Wait for inflight requests to resolve before closing socket
[ { "change_type": "MODIFY", "old_path": "lib/components/socket.react.js", "new_path": "lib/components/socket.react.js", "diff": "@@ -113,8 +113,18 @@ class Socket extends React.PureComponent<Props> {\ntransitStatuses: TransitStatus[] = [];\nopenSocket() {\n+ const { status } = this.props.connection;\n+ if (\n+ status === \"disconnecting\" &&\n+ this.socket &&\n+ this.socket.readyState === 1\n+ ) {\n+ this.markSocketInitialized();\n+ return;\n+ }\nif (this.socket && this.socket.readyState < 2) {\nthis.socket.close();\n+ console.warn(`this.socket seems open, but Redux thinks it's ${status}`);\n}\nif (this.props.activeThread) {\nthis.props.dispatchActionPayload(\n@@ -139,27 +149,50 @@ class Socket extends React.PureComponent<Props> {\nthis.transitStatuses = [];\n}\n+ markSocketInitialized() {\n+ registerActiveWebSocket(this.socket);\n+ this.props.dispatchActionPayload(\n+ updateConnectionStatusActionType,\n+ { status: \"connected\" },\n+ );\n+ }\n+\ncloseSocket() {\nregisterActiveWebSocket(null);\nthis.props.dispatchActionPayload(\nupdateConnectionStatusActionType,\n{ status: \"disconnecting\" },\n);\n- if (this.socket) {\n- if (this.socket.readyState < 2) {\n- // If it's not closing already, close it\n- this.socket.close();\n- }\n- this.socket = null;\n+\n+ if (this.props.activeThread) {\n+ const activityUpdates = [{\n+ focus: false,\n+ threadID: this.props.activeThread,\n+ latestMessage: this.props.activeThreadLatestMessage,\n+ }];\n+ this.props.dispatchActionPayload(\n+ queueActivityUpdatesActionType,\n+ { activityUpdates },\n+ );\n+ this.sendActivityUpdates(activityUpdates);\n}\n+\n+ this.finishClosingSocket();\n}\n- markSocketInitialized() {\n- registerActiveWebSocket(this.socket);\n+ finishClosingSocket() {\n+ if (this.transitStatuses.length > 0) {\n+ return;\n+ }\nthis.props.dispatchActionPayload(\nupdateConnectionStatusActionType,\n- { status: \"connected\" },\n+ { status: \"disconnected\" },\n);\n+ if (this.socket && this.socket.readyState < 2) {\n+ // If it's not closing already, close it\n+ this.socket.close();\n+ }\n+ this.socket = null;\n}\ncomponentDidMount() {\n@@ -227,6 +260,9 @@ class Socket extends React.PureComponent<Props> {\ntransitStatus => transitStatus.type !== \"ActivityUpdate\" ||\nqueuedActivityUpdates.includes(transitStatus.activityUpdate),\n);\n+ if (this.props.connection.status === \"disconnecting\") {\n+ this.finishClosingSocket();\n+ }\n}\nif (\nthis.props.connection.status === \"connected\" &&\n@@ -353,7 +389,21 @@ class Socket extends React.PureComponent<Props> {\n}\nonClose = (event: CloseEvent) => {\n- this.closeSocket();\n+ const { status } = this.props.connection;\n+ if (\n+ status !== \"disconnecting\" &&\n+ status !== \"forcedDisconnecting\" &&\n+ status !== \"disconnected\"\n+ ) {\n+ registerActiveWebSocket(null);\n+ }\n+ if (status !== \"disconnected\") {\n+ this.props.dispatchActionPayload(\n+ updateConnectionStatusActionType,\n+ { status: \"disconnected\" },\n+ );\n+ }\n+ this.socket = null;\n}\nsendInitialMessage = () => {\n@@ -583,6 +633,10 @@ class Socket extends React.PureComponent<Props> {\nnewTransitStatuses.map(transitStatus => transitStatus.activityUpdate),\n);\n}\n+\n+ if (this.props.connection.status === \"disconnecting\") {\n+ this.finishClosingSocket();\n+ }\n}\nprocessServerRequests(serverRequests: $ReadOnlyArray<ServerRequest>) {\n" }, { "change_type": "MODIFY", "old_path": "native/app.react.js", "new_path": "native/app.react.js", "diff": "@@ -302,7 +302,6 @@ class AppWithNavigationState extends React.PureComponent<Props, State> {\nhandleAppStateChange = (nextAppState: ?string) => {\nconst lastState = this.currentState;\nthis.currentState = nextAppState;\n- this.setState({ foreground: this.currentState === \"active\" });\nif (\nlastState &&\nlastState.match(/inactive|background/) &&\n@@ -321,6 +320,7 @@ class AppWithNavigationState extends React.PureComponent<Props, State> {\nthis.props.dispatchActionPayload(backgroundActionType, null);\nappBecameInactive();\n}\n+ this.setState({ foreground: this.currentState === \"active\" });\n}\ncomponentWillReceiveProps(nextProps: Props) {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Wait for inflight requests to resolve before closing socket
129,187
23.10.2018 10:30:04
14,400
f480e0c63a58c93d251e4d2892320a2266a98341
Introduce forceCloseSocket
[ { "change_type": "MODIFY", "old_path": "lib/components/socket.react.js", "new_path": "lib/components/socket.react.js", "diff": "@@ -111,9 +111,14 @@ class Socket extends React.PureComponent<Props> {\ninitialPlatformDetailsSent = false;\nnextClientMessageID = 0;\ntransitStatuses: TransitStatus[] = [];\n+ reopenConnectionAfterClosing = false;\nopenSocket() {\nconst { status } = this.props.connection;\n+ if (status === \"forcedDisconnecting\") {\n+ this.reopenConnectionAfterClosing = true;\n+ return;\n+ }\nif (\nstatus === \"disconnecting\" &&\nthis.socket &&\n@@ -126,6 +131,13 @@ class Socket extends React.PureComponent<Props> {\nthis.socket.close();\nconsole.warn(`this.socket seems open, but Redux thinks it's ${status}`);\n}\n+ if (status === \"connecting\" && this.socket) {\n+ return;\n+ }\n+ this.props.dispatchActionPayload(\n+ updateConnectionStatusActionType,\n+ { status: \"connecting\" },\n+ );\nif (this.props.activeThread) {\nthis.props.dispatchActionPayload(\nqueueActivityUpdatesActionType,\n@@ -137,10 +149,6 @@ class Socket extends React.PureComponent<Props> {\n},\n);\n}\n- this.props.dispatchActionPayload(\n- updateConnectionStatusActionType,\n- { status: \"connecting\" },\n- );\nconst socket = this.props.openSocket();\nsocket.onopen = this.sendInitialMessage;\nsocket.onmessage = this.receiveMessage;\n@@ -159,12 +167,33 @@ class Socket extends React.PureComponent<Props> {\ncloseSocket() {\nregisterActiveWebSocket(null);\n+ const { status } = this.props.connection;\n+ if (status === \"disconnecting\" || status === \"forcedDisconnecting\") {\n+ this.reopenConnectionAfterClosing = false;\n+ return;\n+ }\nthis.props.dispatchActionPayload(\nupdateConnectionStatusActionType,\n{ status: \"disconnecting\" },\n);\n+ this.sendFinalActivityUpdate();\n+ this.finishClosingSocket();\n+ }\n- if (this.props.activeThread) {\n+ forceCloseSocket() {\n+ registerActiveWebSocket(null);\n+ this.props.dispatchActionPayload(\n+ updateConnectionStatusActionType,\n+ { status: \"forcedDisconnecting\" },\n+ );\n+ this.sendFinalActivityUpdate();\n+ this.finishClosingSocket();\n+ }\n+\n+ sendFinalActivityUpdate() {\n+ if (!this.props.activeThread) {\n+ return;\n+ }\nconst activityUpdates = [{\nfocus: false,\nthreadID: this.props.activeThread,\n@@ -177,9 +206,6 @@ class Socket extends React.PureComponent<Props> {\nthis.sendActivityUpdates(activityUpdates);\n}\n- this.finishClosingSocket();\n- }\n-\nfinishClosingSocket() {\nif (this.transitStatuses.length > 0) {\nreturn;\n@@ -193,6 +219,12 @@ class Socket extends React.PureComponent<Props> {\nthis.socket.close();\n}\nthis.socket = null;\n+ if (this.reopenConnectionAfterClosing) {\n+ this.reopenConnectionAfterClosing = false;\n+ if (this.props.active) {\n+ this.openSocket();\n+ }\n+ }\n}\ncomponentDidMount() {\n@@ -214,12 +246,9 @@ class Socket extends React.PureComponent<Props> {\nthis.props.active &&\nprevProps.openSocket !== this.props.openSocket\n) {\n- // This case happens when the baseURL/urlPrefix is changed. Not sure if\n- // the closeSocket() call is entirely necessary. Long-term we will update\n- // this logic to retry in-flight requests anyways, so we can figure out\n- // then.\n- this.closeSocket();\n- this.openSocket();\n+ // This case happens when the baseURL/urlPrefix is changed\n+ this.reopenConnectionAfterClosing = true;\n+ this.forceCloseSocket();\n}\nif (this.props.activeThread !== prevProps.activeThread) {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Introduce forceCloseSocket
129,187
23.10.2018 10:57:37
14,400
86bb4f2231215036c1166415473bc863a3ec1dff
Clean up some more old ping stuff
[ { "change_type": "MODIFY", "old_path": "lib/reducers/entry-reducer.js", "new_path": "lib/reducers/entry-reducer.js", "diff": "@@ -102,10 +102,6 @@ function mergeNewEntryInfos(\ncurrentEntryInfos: {[id: string]: RawEntryInfo},\nnewEntryInfos: $ReadOnlyArray<RawEntryInfo>,\nthreadInfos: {[id: string]: RawThreadInfo},\n- pingInfo?: {|\n- prevEntryInfos: {[id: string]: RawEntryInfo},\n- calendarQuery: CalendarQuery,\n- |},\n) {\nconst mergedEntryInfos = {};\n@@ -148,50 +144,14 @@ function mergeNewEntryInfos(\ncontinue;\n}\n- if (pingInfo) {\n- const prevEntryInfo = pingInfo.prevEntryInfos[serverID];\n- // If the entry at the time of the start of the ping is the same as what\n- // was returned, but the current state is different, then it's likely that\n- // an action mutated the state after the ping result was fetched on the\n- // server. We should keep the mutated (current) state.\n- if (_isEqual(prevEntryInfo)(newEntryInfo)) {\n- if (currentEntryInfo) {\n- mergedEntryInfos[serverID] = currentEntryInfo;\n- }\n- continue;\n- }\n- }\n-\nmergedEntryInfos[serverID] = newEntryInfo;\n}\nfor (let id in currentEntryInfos) {\nconst newEntryInfo = mergedEntryInfos[id];\n- if (newEntryInfo) {\n- continue;\n- }\n- const currentEntryInfo = currentEntryInfos[id];\n- if (pingInfo) {\n- const prevEntryInfo = pingInfo.prevEntryInfos[id];\n- // If an EntryInfo was present at the start of the ping, and is currently\n- // present, but did not appear in the ping result, then there are three\n- // possibilities:\n- // - It is outside the scope of the CalendarQuery.\n- // - It is a local entry that has not been committed to the server yet, in\n- // which case we should keep it.\n- // - It has been deleted on the server side.\n- // We should delete it only in the third case.\n- if (prevEntryInfo && prevEntryInfo.id) {\n- const withinCalendarQueryRange = rawEntryInfoWithinCalendarQuery(\n- currentEntryInfo,\n- pingInfo.calendarQuery,\n- );\n- if (withinCalendarQueryRange) {\n- continue;\n- }\n- }\n+ if (!newEntryInfo) {\n+ mergedEntryInfos[id] = currentEntryInfos[id];\n}\n- mergedEntryInfos[id] = currentEntryInfo;\n}\nfor (let entryID in mergedEntryInfos) {\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/message-reducer.js", "new_path": "lib/reducers/message-reducer.js", "diff": "@@ -5,7 +5,7 @@ import {\ntype ThreadMessageInfo,\ntype MessageStore,\ntype MessageTruncationStatus,\n- type MessagesPingResponse,\n+ type MessagesResponse,\nmessageTruncationStatus,\nmessageTypes,\ndefaultNumberPerThread,\n@@ -618,9 +618,9 @@ function reduceMessageStore(\n}\nfunction mergeUpdatesIntoMessagesResult(\n- messagesResult: MessagesPingResponse,\n+ messagesResult: MessagesResponse,\nnewUpdates: $ReadOnlyArray<UpdateInfo>,\n-): MessagesPingResponse {\n+): MessagesResponse {\nconst messageIDs = new Set(messagesResult.rawMessageInfos.map(\nmessageInfo => messageInfo.id,\n));\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/user-reducer.js", "new_path": "lib/reducers/user-reducer.js", "diff": "import type { BaseAction } from '../types/redux-types';\nimport type { CurrentUserInfo, UserInfo } from '../types/user-types';\nimport { updateTypes } from '../types/update-types';\n-import { pingResponseTypes } from '../types/ping-types';\nimport {\nserverRequestTypes,\nprocessServerRequestsActionType,\n" }, { "change_type": "MODIFY", "old_path": "lib/shared/message-utils.js", "new_path": "lib/shared/message-utils.js", "diff": "@@ -558,10 +558,10 @@ function rawMessageInfoFromMessageData(\nfunction mostRecentMessageTimestamp(\nmessageInfos: RawMessageInfo[],\n- lastPing: number,\n+ previousTimestamp: number,\n): number {\nif (messageInfos.length === 0) {\n- return lastPing;\n+ return previousTimestamp;\n}\nreturn _maxBy('time')(messageInfos).time;\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/shared/update-utils.js", "new_path": "lib/shared/update-utils.js", "diff": "@@ -11,10 +11,10 @@ import invariant from 'invariant';\nfunction mostRecentUpdateTimestamp(\nupdateInfos: UpdateInfo[],\n- lastPing: number,\n+ previousTimestamp: number,\n): number {\nif (updateInfos.length === 0) {\n- return lastPing;\n+ return previousTimestamp;\n}\nreturn _maxBy('time')(updateInfos).time;\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/types/message-types.js", "new_path": "lib/types/message-types.js", "diff": "@@ -567,7 +567,7 @@ export type FetchMessageInfosPayload = {|\ntruncationStatus: MessageTruncationStatus,\nuserInfos: UserInfo[],\n|};\n-export type MessagesPingResponse = {|\n+export type MessagesResponse = {|\nrawMessageInfos: RawMessageInfo[],\ntruncationStatuses: MessageTruncationStatuses,\ncurrentAsOf: number,\n@@ -592,7 +592,7 @@ export type SendTextMessagePayload = {|\ntime: number,\n|};\n-// Used for the message info included in log-in type actions and pings\n+// Used for the message info included in log-in type actions\nexport type GenericMessagesResult = {|\nmessageInfos: RawMessageInfo[],\ntruncationStatus: MessageTruncationStatuses,\n" }, { "change_type": "MODIFY", "old_path": "lib/types/ping-types.js", "new_path": "lib/types/ping-types.js", "diff": "@@ -10,12 +10,13 @@ import type {\nimport type {\nRawMessageInfo,\nMessageTruncationStatuses,\n- MessagesPingResponse,\n+ MessagesResponse,\nGenericMessagesResult,\n} from './message-types';\nimport type { UpdatesResult } from './update-types';\nimport type { Platform } from './device-types';\nimport type { ServerRequest, ClientResponse } from './request-types';\n+import { stateSyncPayloadTypes } from './socket-types';\nimport PropTypes from 'prop-types';\n@@ -29,10 +30,7 @@ export type PingRequest = {|\nclientResponses?: $ReadOnlyArray<ClientResponse>,\n|};\n-export const pingResponseTypes = Object.freeze({\n- FULL: 0,\n- INCREMENTAL: 1,\n-});\n+export const pingResponseTypes = stateSyncPayloadTypes;\ntype PingResponseType = $Values<typeof pingResponseTypes>;\nexport type PingResponse =\n@@ -52,7 +50,7 @@ export type PingResponse =\n|}\n| {|\ntype: 1,\n- messagesResult: MessagesPingResponse,\n+ messagesResult: MessagesResponse,\nupdatesResult?: UpdatesResult,\ndeltaEntryInfos: $ReadOnlyArray<RawEntryInfo>,\nuserInfos: $ReadOnlyArray<UserInfo>,\n" }, { "change_type": "MODIFY", "old_path": "lib/types/socket-types.js", "new_path": "lib/types/socket-types.js", "diff": "import type { SessionState, SessionIdentification } from './session-types';\nimport type { ServerRequest, ClientResponse } from './request-types';\nimport type { RawThreadInfo } from './thread-types';\n-import type { MessagesPingResponse } from './message-types';\n+import type { MessagesResponse } from './message-types';\nimport type { UpdatesResult } from './update-types';\nimport type {\nUserInfo,\n@@ -20,8 +20,6 @@ import {\nimport invariant from 'invariant';\nimport PropTypes from 'prop-types';\n-import { pingResponseTypes } from './ping-types';\n-\n// The types of messages that the client sends across the socket\nexport const clientSocketMessageTypes = Object.freeze({\nINITIAL: 0,\n@@ -92,9 +90,12 @@ export function assertServerSocketMessageType(\nreturn ourServerSocketMessageType;\n}\n-export const stateSyncPayloadTypes = pingResponseTypes;\n+export const stateSyncPayloadTypes = Object.freeze({\n+ FULL: 0,\n+ INCREMENTAL: 1,\n+});\nexport type StateSyncFullActionPayload = {|\n- messagesResult: MessagesPingResponse,\n+ messagesResult: MessagesResponse,\nthreadInfos: {[id: string]: RawThreadInfo},\ncurrentUserInfo: CurrentUserInfo,\nrawEntryInfos: $ReadOnlyArray<RawEntryInfo>,\n@@ -109,7 +110,7 @@ export type StateSyncFullSocketPayload = {|\nsessionID?: string,\n|};\nexport type StateSyncIncrementalActionPayload = {|\n- messagesResult: MessagesPingResponse,\n+ messagesResult: MessagesResponse,\nupdatesResult: UpdatesResult,\ndeltaEntryInfos: $ReadOnlyArray<RawEntryInfo>,\nuserInfos: $ReadOnlyArray<UserInfo>,\n" }, { "change_type": "MODIFY", "old_path": "native/account/logged-out-modal.react.js", "new_path": "native/account/logged-out-modal.react.js", "diff": "@@ -329,7 +329,7 @@ class InnerLoggedOutModal extends React.PureComponent<Props, State> {\nreturn;\n}\n// Looks like we failed to recover. We'll handle resetting Redux state to\n- // match our cookie in the ping call below\n+ // match our cookie in the reset call below\nif (newCookie) {\ncookie = newCookie;\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/user-responders.js", "new_path": "server/src/responders/user-responders.js", "diff": "@@ -236,7 +236,7 @@ async function logInResponder(\n}\nconst id = userRow.id.toString();\n- const newPingTime = Date.now();\n+ const newServerTime = Date.now();\nconst deviceToken = request.deviceTokenUpdateRequest\n? request.deviceTokenUpdateRequest.deviceToken\n: viewer.deviceToken;\n@@ -249,7 +249,7 @@ async function logInResponder(\n]);\nviewer.setNewCookie(userViewerData);\nif (calendarQuery) {\n- await setNewSession(viewer, calendarQuery, newPingTime);\n+ await setNewSession(viewer, calendarQuery, newServerTime);\n}\nconst threadCursors = {};\n@@ -284,7 +284,7 @@ async function logInResponder(\n},\nrawMessageInfos: messagesResult.rawMessageInfos,\ntruncationStatuses: messagesResult.truncationStatuses,\n- serverTime: newPingTime,\n+ serverTime: newServerTime,\nuserInfos,\ncookieChange: {\nthreadInfos: threadsResult.threadInfos,\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/account-updaters.js", "new_path": "server/src/updaters/account-updaters.js", "diff": "@@ -203,7 +203,7 @@ async function updatePassword(\n}\nconst userRow = userResult[0];\n- const newPingTime = Date.now();\n+ const newServerTime = Date.now();\nconst deviceToken = request.deviceTokenUpdateRequest\n? request.deviceTokenUpdateRequest.deviceToken\n: viewer.deviceToken;\n@@ -216,7 +216,7 @@ async function updatePassword(\n]);\nviewer.setNewCookie(userViewerData);\nif (calendarQuery) {\n- await setNewSession(viewer, calendarQuery, newPingTime);\n+ await setNewSession(viewer, calendarQuery, newServerTime);\n}\nconst threadCursors = {};\n@@ -251,7 +251,7 @@ async function updatePassword(\n},\nrawMessageInfos: messagesResult.rawMessageInfos,\ntruncationStatuses: messagesResult.truncationStatuses,\n- serverTime: newPingTime,\n+ serverTime: newServerTime,\nuserInfos,\ncookieChange: {\nthreadInfos: threadsResult.threadInfos,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Clean up some more old ping stuff
129,187
23.10.2018 17:13:24
14,400
411c45bd0ccdc6d15ee7f174051ad18792b1d1af
A whole bunch of fixes to buggy client socket code
[ { "change_type": "MODIFY", "old_path": "lib/components/socket.react.js", "new_path": "lib/components/socket.react.js", "diff": "@@ -114,25 +114,25 @@ class Socket extends React.PureComponent<Props> {\nreopenConnectionAfterClosing = false;\nopenSocket() {\n+ if (this.socket) {\nconst { status } = this.props.connection;\nif (status === \"forcedDisconnecting\") {\nthis.reopenConnectionAfterClosing = true;\nreturn;\n- }\n- if (\n- status === \"disconnecting\" &&\n- this.socket &&\n- this.socket.readyState === 1\n- ) {\n+ } else if (status === \"disconnecting\" && this.socket.readyState === 1) {\nthis.markSocketInitialized();\nreturn;\n+ } else if (\n+ status === \"connected\" ||\n+ status === \"connecting\" ||\n+ status === \"reconnecting\"\n+ ) {\n+ return;\n}\n- if (this.socket && this.socket.readyState < 2) {\n+ if (this.socket.readyState < 2) {\nthis.socket.close();\nconsole.warn(`this.socket seems open, but Redux thinks it's ${status}`);\n}\n- if (status === \"connecting\" && this.socket) {\n- return;\n}\nthis.props.dispatchActionPayload(\nupdateConnectionStatusActionType,\n@@ -150,9 +150,17 @@ class Socket extends React.PureComponent<Props> {\n);\n}\nconst socket = this.props.openSocket();\n- socket.onopen = this.sendInitialMessage;\n+ socket.onopen = () => {\n+ if (this.socket === socket) {\n+ this.sendInitialMessage();\n+ }\n+ };\nsocket.onmessage = this.receiveMessage;\n- socket.onclose = this.onClose;\n+ socket.onclose = (event: CloseEvent) => {\n+ if (this.socket === socket) {\n+ this.onClose(event);\n+ }\n+ };\nthis.socket = socket;\nthis.transitStatuses = [];\n}\n@@ -166,12 +174,14 @@ class Socket extends React.PureComponent<Props> {\n}\ncloseSocket() {\n- registerActiveWebSocket(null);\nconst { status } = this.props.connection;\n- if (status === \"disconnecting\" || status === \"forcedDisconnecting\") {\n+ if (status === \"disconnected\") {\n+ return;\n+ } else if (status === \"disconnecting\" || status === \"forcedDisconnecting\") {\nthis.reopenConnectionAfterClosing = false;\nreturn;\n}\n+ registerActiveWebSocket(null);\nthis.props.dispatchActionPayload(\nupdateConnectionStatusActionType,\n{ status: \"disconnecting\" },\n@@ -182,16 +192,20 @@ class Socket extends React.PureComponent<Props> {\nforceCloseSocket() {\nregisterActiveWebSocket(null);\n+ const { status } = this.props.connection;\n+ if (status !== \"forcedDisconnecting\" && status !== \"disconnected\") {\nthis.props.dispatchActionPayload(\nupdateConnectionStatusActionType,\n{ status: \"forcedDisconnecting\" },\n);\n+ }\nthis.sendFinalActivityUpdate();\nthis.finishClosingSocket();\n}\nsendFinalActivityUpdate() {\n- if (!this.props.activeThread) {\n+ const { status } = this.props.connection;\n+ if (status !== \"connected\" || !this.props.activeThread) {\nreturn;\n}\nconst activityUpdates = [{\n@@ -218,7 +232,6 @@ class Socket extends React.PureComponent<Props> {\n// If it's not closing already, close it\nthis.socket.close();\n}\n- this.socket = null;\nif (this.reopenConnectionAfterClosing) {\nthis.reopenConnectionAfterClosing = false;\nif (this.props.active) {\n@@ -274,9 +287,11 @@ class Socket extends React.PureComponent<Props> {\n}\n}\n+ const { status } = this.props.connection;\n+ const { status: prevStatus } = prevProps.connection;\nif (\n- this.props.connection.status === \"connected\" &&\n- (prevProps.connection.status !== \"connected\" ||\n+ status === \"connected\" &&\n+ (prevStatus !== \"connected\" ||\nthis.props.getClientResponses !== prevProps.getClientResponses)\n) {\nconst clientResponses = this.props.getClientResponses();\n@@ -289,13 +304,13 @@ class Socket extends React.PureComponent<Props> {\ntransitStatus => transitStatus.type !== \"ActivityUpdate\" ||\nqueuedActivityUpdates.includes(transitStatus.activityUpdate),\n);\n- if (this.props.connection.status === \"disconnecting\") {\n+ if (status === \"disconnecting\" || status === \"forcedDisconnecting\") {\nthis.finishClosingSocket();\n}\n}\nif (\n- this.props.connection.status === \"connected\" &&\n- (prevProps.connection.status !== \"connected\" ||\n+ status === \"connected\" &&\n+ (prevStatus !== \"connected\" ||\nqueuedActivityUpdates !== prevProps.connection.queuedActivityUpdates)\n) {\nthis.sendActivityUpdates(queuedActivityUpdates);\n@@ -663,7 +678,8 @@ class Socket extends React.PureComponent<Props> {\n);\n}\n- if (this.props.connection.status === \"disconnecting\") {\n+ const { status } = this.props.connection;\n+ if (status === \"disconnecting\" || status === \"forcedDisconnecting\") {\nthis.finishClosingSocket();\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "native/utils/url-utils.js", "new_path": "native/utils/url-utils.js", "diff": "@@ -6,7 +6,7 @@ import { Platform } from 'react-native';\nconst productionServer = \"https://squadcal.org\";\nconst localhostServer = \"http://localhost/squadcal\";\nconst localhostServerFromAndroidEmulator = \"http://10.0.2.2/squadcal\";\n-const natServer = \"http://192.168.1.5/squadcal\";\n+const natServer = \"http://192.168.1.4/squadcal\";\nfunction defaultURLPrefix() {\nif (!__DEV__) {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
A whole bunch of fixes to buggy client socket code
129,187
23.10.2018 19:06:34
14,400
37c807d1560975a9298caafd32bef553006d5258
Extract foreground state and fix broken app state change logic
[ { "change_type": "MODIFY", "old_path": "lib/components/socket.react.js", "new_path": "lib/components/socket.react.js", "diff": "@@ -72,8 +72,8 @@ type TransitStatus =\n|};\ntype Props = {|\n- active: bool,\n// Redux state\n+ active: bool,\nopenSocket: () => WebSocket,\ngetClientResponses: (\nactiveServerRequests?: $ReadOnlyArray<ServerRequest>,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "lib/reducers/foreground-reducer.js", "diff": "+// @flow\n+\n+import type { BaseAction } from '../types/redux-types';\n+\n+export const backgroundActionType = \"BACKGROUND\";\n+export const foregroundActionType = \"FOREGROUND\";\n+\n+export default function reduceForeground(\n+ state: bool,\n+ action: BaseAction,\n+): bool {\n+ if (action.type === backgroundActionType) {\n+ return false;\n+ } else if (action.type === foregroundActionType) {\n+ return true;\n+ }\n+ return state;\n+}\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/master-reducer.js", "new_path": "lib/reducers/master-reducer.js", "diff": "@@ -16,6 +16,7 @@ import { reduceDrafts } from './draft-reducer';\nimport reduceURLPrefix from './url-prefix-reducer';\nimport reduceCalendarFilters from './calendar-filters-reducer';\nimport reduceConnectionInfo from './connection-reducer';\n+import reduceForeground from './foreground-reducer';\nexport default function baseReducer<N: BaseNavInfo, T: BaseAppState<N>>(\nstate: T,\n@@ -55,5 +56,6 @@ export default function baseReducer<N: BaseNavInfo, T: BaseAppState<N>>(\naction,\n),\nconnection: reduceConnectionInfo(state.connection, action),\n+ foreground: reduceForeground(state.foreground, action),\n};\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/types/redux-types.js", "new_path": "lib/types/redux-types.js", "diff": "@@ -77,6 +77,7 @@ export type BaseAppState<NavInfo: BaseNavInfo> = {\nurlPrefix: string,\nconnection: ConnectionInfo,\nwatchedThreadIDs: $ReadOnlyArray<string>,\n+ foreground: bool,\n};\n// Web JS runtime doesn't have access to the cookie for security reasons.\n@@ -569,6 +570,12 @@ export type BaseAction =\n|} | {|\ntype: \"ACTIVITY_UPDATE_FAILED\",\npayload: ActivityUpdateFailedPayload,\n+ |} | {|\n+ type: \"FOREGROUND\",\n+ payload?: void,\n+ |} | {|\n+ type: \"BACKGROUND\",\n+ payload?: void,\n|};\nexport type ActionPayload\n" }, { "change_type": "MODIFY", "old_path": "native/app.react.js", "new_path": "native/app.react.js", "diff": "@@ -50,14 +50,16 @@ import {\nimport { unreadCount } from 'lib/selectors/thread-selectors';\nimport { notificationPressActionType } from 'lib/shared/notif-utils';\nimport { saveMessagesActionType } from 'lib/actions/message-actions';\n+import {\n+ backgroundActionType,\n+ foregroundActionType,\n+} from 'lib/reducers/foreground-reducer';\nimport {\nRootNavigator,\n} from './navigation/navigation-setup';\nimport {\nhandleURLActionType,\n- backgroundActionType,\n- foregroundActionType,\nrecordNotifPermissionAlertActionType,\nrecordAndroidNotificationActionType,\nclearAndroidNotificationActionType,\n@@ -120,10 +122,7 @@ type Props = {\ndeviceType: DeviceType,\n) => Promise<string>,\n};\n-type State = {|\n- foreground: bool,\n-|};\n-class AppWithNavigationState extends React.PureComponent<Props, State> {\n+class AppWithNavigationState extends React.PureComponent<Props> {\nstatic propTypes = {\nnavigationState: PropTypes.object.isRequired,\n@@ -140,9 +139,6 @@ class AppWithNavigationState extends React.PureComponent<Props, State> {\ndispatchActionPromise: PropTypes.func.isRequired,\nsetDeviceToken: PropTypes.func.isRequired,\n};\n- state = {\n- foreground: true,\n- };\ncurrentState: ?string = NativeAppState.currentState;\ninAppNotification: ?InAppNotification = null;\nandroidNotifListener: ?Object = null;\n@@ -299,28 +295,22 @@ class AppWithNavigationState extends React.PureComponent<Props, State> {\nthis.props.dispatchActionPayload(handleURLActionType, url);\n}\n- handleAppStateChange = (nextAppState: ?string) => {\n+ handleAppStateChange = (nextState: ?string) => {\n+ if (!nextState || nextState === \"unknown\") {\n+ return;\n+ }\nconst lastState = this.currentState;\n- this.currentState = nextAppState;\n- if (\n- lastState &&\n- lastState.match(/inactive|background/) &&\n- this.currentState === \"active\"\n- ) {\n+ this.currentState = nextState;\n+ if (lastState === \"background\" && nextState === \"active\") {\nthis.props.dispatchActionPayload(foregroundActionType, null);\nthis.onForeground();\nif (this.props.activeThread) {\nAppWithNavigationState.clearNotifsOfThread(this.props);\n}\n- } else if (\n- lastState === \"active\" &&\n- this.currentState &&\n- this.currentState.match(/inactive|background/)\n- ) {\n+ } else if (lastState !== \"background\" && nextState === \"background\") {\nthis.props.dispatchActionPayload(backgroundActionType, null);\nappBecameInactive();\n}\n- this.setState({ foreground: this.currentState === \"active\" });\n}\ncomponentWillReceiveProps(nextProps: Props) {\n@@ -642,7 +632,6 @@ class AppWithNavigationState extends React.PureComponent<Props, State> {\nconst inAppNotificationHeight = DeviceInfo.isIPhoneX_deprecated ? 104 : 80;\nreturn (\n<View style={styles.app}>\n- <Socket active={this.props.appLoggedIn && this.state.foreground} />\n<ReduxifiedRootNavigator\nstate={this.props.navigationState}\ndispatch={this.props.dispatch}\n@@ -692,6 +681,7 @@ const App = (props: {}) =>\n<Provider store={store}>\n<ErrorBoundary>\n<ConnectedAppWithNavigationState />\n+ <Socket />\n</ErrorBoundary>\n</Provider>;\nAppRegistry.registerComponent('SquadCal', () => App);\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/action-types.js", "new_path": "native/navigation/action-types.js", "diff": "export const handleURLActionType = \"HANDLE_URL\";\nexport const navigateToAppActionType = \"NAVIGATE_TO_APP\";\n-export const backgroundActionType = \"BACKGROUND\";\n-export const foregroundActionType = \"FOREGROUND\";\nexport const resetUserStateActionType = \"RESET_USER_STATE\";\nexport const recordNotifPermissionAlertActionType =\n\"RECORD_NOTIF_PERMISSION_ALERT\";\n" }, { "change_type": "MODIFY", "old_path": "native/persist.js", "new_path": "native/persist.js", "diff": "@@ -79,6 +79,7 @@ const migrations = {\nactiveServerRequests: undefined,\nconnection: defaultConnectionInfo,\nwatchedThreadIDs: [],\n+ foreground: true,\n}),\n};\n" }, { "change_type": "MODIFY", "old_path": "native/redux-setup.js", "new_path": "native/redux-setup.js", "diff": "@@ -105,6 +105,7 @@ export type AppState = {|\nmessageSentFromRoute: $ReadOnlyArray<string>,\nconnection: ConnectionInfo,\nwatchedThreadIDs: $ReadOnlyArray<string>,\n+ foreground: bool,\n_persist: ?PersistState,\nsessionID?: void,\n|};\n@@ -142,6 +143,7 @@ const defaultState = ({\nmessageSentFromRoute: [],\nconnection: defaultConnectionInfo,\nwatchedThreadIDs: [],\n+ foreground: true,\n_persist: null,\n}: AppState);\n" }, { "change_type": "MODIFY", "old_path": "native/socket.react.js", "new_path": "native/socket.react.js", "diff": "@@ -14,12 +14,19 @@ import {\nopenSocketSelector,\nsessionIdentificationSelector,\n} from './selectors/socket-selectors';\n-import { activeThreadSelector } from './selectors/nav-selectors';\n+import {\n+ activeThreadSelector,\n+ appLoggedInSelector,\n+} from './selectors/nav-selectors';\nexport default connect(\n(state: AppState) => {\nconst activeThread = activeThreadSelector(state);\nreturn {\n+ active: appLoggedInSelector(state) &&\n+ state.currentUserInfo &&\n+ !state.currentUserInfo.anonymous &&\n+ state.foreground,\nopenSocket: openSocketSelector(state),\ngetClientResponses: clientResponsesSelector(state),\nactiveThread,\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/website-responders.js", "new_path": "server/src/responders/website-responders.js", "diff": "@@ -156,6 +156,7 @@ async function websiteResponder(viewer: Viewer, url: string): Promise<string> {\nbaseHref: baseDomain + baseURL,\nconnection: defaultConnectionInfo,\nwatchedThreadIDs: [],\n+ foreground: true,\n}: AppState),\n);\nconst routerContext = {};\n" }, { "change_type": "MODIFY", "old_path": "web/app.react.js", "new_path": "web/app.react.js", "diff": "@@ -45,6 +45,10 @@ import {\nmostRecentReadThreadSelector,\nunreadCount,\n} from 'lib/selectors/thread-selectors';\n+import {\n+ backgroundActionType,\n+ foregroundActionType,\n+} from 'lib/reducers/foreground-reducer';\nimport { activeThreadSelector } from './selectors/nav-selectors';\nimport { canonicalURLFromReduxState, navInfoFromURL } from './url-utils';\n@@ -59,7 +63,6 @@ import history from './router-history';\nimport { updateNavInfoActionType } from './redux-setup';\nimport Splash from './splash/splash.react';\nimport Chat from './chat/chat.react';\n-import Socket from './socket.react';\n// We want Webpack's css-loader and style-loader to handle the Fontawesome CSS,\n// so we disable the autoAddCss logic and import the CSS file.\n@@ -106,7 +109,6 @@ type Props = {\n};\ntype State = {|\ncurrentModal: ?React.Node,\n- visible: bool,\n|};\nclass App extends React.PureComponent<Props, State> {\n@@ -131,7 +133,6 @@ class App extends React.PureComponent<Props, State> {\n};\nstate = {\ncurrentModal: null,\n- visible: true,\n};\nactualizedCalendarQuery: CalendarQuery;\n@@ -175,7 +176,11 @@ class App extends React.PureComponent<Props, State> {\n}\nonVisibilityChange = (e, state: string) => {\n- this.setState({ visible: state === \"visible\" });\n+ if (state === \"visible\") {\n+ this.props.dispatchActionPayload(foregroundActionType, null);\n+ } else {\n+ this.props.dispatchActionPayload(backgroundActionType, null);\n+ }\n}\ncomponentDidUpdate(prevProps: Props) {\n@@ -275,7 +280,6 @@ class App extends React.PureComponent<Props, State> {\n}\nreturn (\n<React.Fragment>\n- <Socket active={this.props.loggedIn && this.state.visible} />\n{content}\n{this.state.currentModal}\n</React.Fragment>\n" }, { "change_type": "MODIFY", "old_path": "web/redux-setup.js", "new_path": "web/redux-setup.js", "diff": "@@ -62,6 +62,7 @@ export type AppState = {|\nbaseHref: string,\nconnection: ConnectionInfo,\nwatchedThreadIDs: $ReadOnlyArray<string>,\n+ foreground: bool,\n|};\nexport const updateNavInfoActionType = \"UPDATE_NAV_INFO\";\n" }, { "change_type": "MODIFY", "old_path": "web/root.js", "new_path": "web/root.js", "diff": "@@ -16,6 +16,7 @@ import {\nimport { reduxLoggerMiddleware } from 'lib/utils/redux-logger';\nimport App from './app.react';\n+import Socket from './socket.react';\nimport history from './router-history';\nimport { reducer } from './redux-setup';\n@@ -29,9 +30,12 @@ const store: Store<AppState, Action> = createStore(\n);\nconst RootRouter = () => (\n+ <React.Fragment>\n<Router history={history.getHistoryObject()}>\n<Route path=\"*\" component={App} />\n</Router>\n+ <Socket />\n+ </React.Fragment>\n);\nconst RootHMR = hot(module)(RootRouter);\n" }, { "change_type": "MODIFY", "old_path": "web/socket.react.js", "new_path": "web/socket.react.js", "diff": "@@ -20,6 +20,9 @@ export default connect(\n(state: AppState) => {\nconst activeThread = activeThreadSelector(state);\nreturn {\n+ active: state.currentUserInfo &&\n+ !state.currentUserInfo.anonymous &&\n+ state.foreground,\nopenSocket: openSocketSelector(state),\ngetClientResponses: clientResponsesSelector(state),\nactiveThread,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Extract foreground state and fix broken app state change logic
129,187
24.10.2018 15:34:04
14,400
181c8979b9d821424f241871be8899efe6ea0a27
Promise-based mechanism for ActivityUpdates in Socket component
[ { "change_type": "MODIFY", "old_path": "lib/components/socket.react.js", "new_path": "lib/components/socket.react.js", "diff": "@@ -26,6 +26,9 @@ import {\nqueueActivityUpdatesActionType,\nactivityUpdateSuccessActionType,\nactivityUpdateFailedActionType,\n+ type ActivityUpdateResponseServerSocketMessage,\n+ type InflightRequest,\n+ resolveRequests,\n} from '../types/socket-types';\nimport type { ActivityUpdate } from '../types/activity-types';\nimport type { Dispatch } from '../types/redux-types';\n@@ -43,6 +46,7 @@ import {\nfetchNewCookieFromNativeCredentials,\n} from '../utils/action-utils';\nimport { socketAuthErrorResolutionAttempt } from '../actions/user-actions';\n+import { ServerError } from '../utils/errors';\ntype TransitStatus =\n| {|\n@@ -57,18 +61,6 @@ type TransitStatus =\nstatus: \"errored\",\nclientResponse: ClientResponse,\nmessageID?: number,\n- |}\n- | {|\n- type: \"ActivityUpdate\",\n- status: \"inflight\",\n- activityUpdate: ActivityUpdate,\n- messageID: number,\n- |}\n- | {|\n- type: \"ActivityUpdate\",\n- status: \"errored\",\n- activityUpdate: ActivityUpdate,\n- messageID?: number,\n|};\ntype Props = {|\n@@ -112,6 +104,7 @@ class Socket extends React.PureComponent<Props> {\nnextClientMessageID = 0;\ntransitStatuses: TransitStatus[] = [];\nreopenConnectionAfterClosing = false;\n+ inflightRequests: InflightRequest[] = [];\nopenSocket() {\nif (this.socket) {\n@@ -138,17 +131,6 @@ class Socket extends React.PureComponent<Props> {\nupdateConnectionStatusActionType,\n{ status: \"connecting\" },\n);\n- if (this.props.activeThread) {\n- this.props.dispatchActionPayload(\n- queueActivityUpdatesActionType,\n- {\n- activityUpdates: [{\n- focus: true,\n- threadID: this.props.activeThread,\n- }],\n- },\n- );\n- }\nconst socket = this.props.openSocket();\nsocket.onopen = () => {\nif (this.socket === socket) {\n@@ -163,6 +145,7 @@ class Socket extends React.PureComponent<Props> {\n};\nthis.socket = socket;\nthis.transitStatuses = [];\n+ this.inflightRequests = [];\n}\nmarkSocketInitialized() {\n@@ -173,7 +156,7 @@ class Socket extends React.PureComponent<Props> {\n);\n}\n- closeSocket() {\n+ closeSocket(activityUpdates: $ReadOnlyArray<ActivityUpdate>) {\nconst { status } = this.props.connection;\nif (status === \"disconnected\") {\nreturn;\n@@ -186,11 +169,11 @@ class Socket extends React.PureComponent<Props> {\nupdateConnectionStatusActionType,\n{ status: \"disconnecting\" },\n);\n- this.sendFinalActivityUpdate();\n+ this.sendFinalActivityUpdates(activityUpdates);\nthis.finishClosingSocket();\n}\n- forceCloseSocket() {\n+ forceCloseSocket(activityUpdates: $ReadOnlyArray<ActivityUpdate>) {\nregisterActiveWebSocket(null);\nconst { status } = this.props.connection;\nif (status !== \"forcedDisconnecting\" && status !== \"disconnected\") {\n@@ -199,29 +182,19 @@ class Socket extends React.PureComponent<Props> {\n{ status: \"forcedDisconnecting\" },\n);\n}\n- this.sendFinalActivityUpdate();\n+ this.sendFinalActivityUpdates(activityUpdates);\nthis.finishClosingSocket();\n}\n- sendFinalActivityUpdate() {\n+ sendFinalActivityUpdates(activityUpdates: $ReadOnlyArray<ActivityUpdate>) {\nconst { status } = this.props.connection;\n- if (status !== \"connected\" || !this.props.activeThread) {\n- return;\n+ if (status === \"connected\") {\n+ this.sendAndHandleActivityUpdates(activityUpdates);\n}\n- const activityUpdates = [{\n- focus: false,\n- threadID: this.props.activeThread,\n- latestMessage: this.props.activeThreadLatestMessage,\n- }];\n- this.props.dispatchActionPayload(\n- queueActivityUpdatesActionType,\n- { activityUpdates },\n- );\n- this.sendActivityUpdates(activityUpdates);\n}\nfinishClosingSocket() {\n- if (this.transitStatuses.length > 0) {\n+ if (this.transitStatuses.length > 0 || this.inflightRequests.length > 0) {\nreturn;\n}\nthis.props.dispatchActionPayload(\n@@ -247,25 +220,12 @@ class Socket extends React.PureComponent<Props> {\n}\ncomponentWillUnmount() {\n- this.closeSocket();\n+ this.closeSocket([]);\n}\ncomponentDidUpdate(prevProps: Props) {\n- if (this.props.active && !prevProps.active) {\n- this.openSocket();\n- } else if (!this.props.active && prevProps.active) {\n- this.closeSocket();\n- } else if (\n- this.props.active &&\n- prevProps.openSocket !== this.props.openSocket\n- ) {\n- // This case happens when the baseURL/urlPrefix is changed\n- this.reopenConnectionAfterClosing = true;\n- this.forceCloseSocket();\n- }\n-\n- if (this.props.activeThread !== prevProps.activeThread) {\nconst activityUpdates = [];\n+ if (this.props.activeThread !== prevProps.activeThread) {\nif (prevProps.activeThread) {\nactivityUpdates.push({\nfocus: false,\n@@ -279,13 +239,27 @@ class Socket extends React.PureComponent<Props> {\nthreadID: this.props.activeThread,\n});\n}\n+ }\n+\n+ if (this.props.active && !prevProps.active) {\n+ this.openSocket();\n+ } else if (!this.props.active && prevProps.active) {\n+ this.closeSocket(activityUpdates);\n+ } else if (\n+ this.props.active &&\n+ prevProps.openSocket !== this.props.openSocket\n+ ) {\n+ // This case happens when the baseURL/urlPrefix is changed\n+ this.reopenConnectionAfterClosing = true;\n+ this.forceCloseSocket(activityUpdates);\n+ }\n+\nif (activityUpdates.length > 0) {\nthis.props.dispatchActionPayload(\nqueueActivityUpdatesActionType,\n{ activityUpdates },\n);\n}\n- }\nconst { status } = this.props.connection;\nconst { status: prevStatus } = prevProps.connection;\n@@ -299,21 +273,18 @@ class Socket extends React.PureComponent<Props> {\n}\nconst { queuedActivityUpdates } = this.props.connection;\n- if (queuedActivityUpdates !== prevProps.connection.queuedActivityUpdates) {\n- this.transitStatuses = this.transitStatuses.filter(\n- transitStatus => transitStatus.type !== \"ActivityUpdate\" ||\n- queuedActivityUpdates.includes(transitStatus.activityUpdate),\n- );\n- if (status === \"disconnecting\" || status === \"forcedDisconnecting\") {\n- this.finishClosingSocket();\n- }\n- }\n- if (\n+ const { queuedActivityUpdates: prevActivityUpdates } = prevProps.connection;\n+ if (status === \"connected\" && prevStatus !== \"connected\") {\n+ this.sendAndHandleActivityUpdates(queuedActivityUpdates);\n+ } else if (\nstatus === \"connected\" &&\n- (prevStatus !== \"connected\" ||\n- queuedActivityUpdates !== prevProps.connection.queuedActivityUpdates)\n+ queuedActivityUpdates !== prevActivityUpdates\n) {\n- this.sendActivityUpdates(queuedActivityUpdates);\n+ const previousUpdates = new Set(prevActivityUpdates);\n+ const newUpdates = queuedActivityUpdates.filter(\n+ update => !previousUpdates.has(update),\n+ );\n+ this.sendAndHandleActivityUpdates(newUpdates);\n}\n}\n@@ -345,6 +316,16 @@ class Socket extends React.PureComponent<Props> {\nif (!message) {\nreturn;\n}\n+\n+ this.inflightRequests = resolveRequests(\n+ message,\n+ this.inflightRequests,\n+ );\n+ const { status } = this.props.connection;\n+ if (status === \"disconnecting\" || status === \"forcedDisconnecting\") {\n+ this.finishClosingSocket();\n+ }\n+\nif (message.type === serverSocketMessageTypes.STATE_SYNC) {\nthis.updateTransitStatusesWithServerResponse(true, message.responseTo);\nif (message.payload.type === stateSyncPayloadTypes.FULL) {\n@@ -422,13 +403,6 @@ class Socket extends React.PureComponent<Props> {\ndeliveredActivityUpdates.push(transitStatus.activityUpdate);\n}\n}\n- this.props.dispatchActionPayload(\n- activityUpdateSuccessActionType,\n- {\n- activityUpdates: deliveredActivityUpdates,\n- result: message.payload,\n- },\n- );\n}\n}\n@@ -476,7 +450,16 @@ class Socket extends React.PureComponent<Props> {\ntype: serverRequestTypes.INITIAL_ACTIVITY_UPDATES,\nactivityUpdates: queuedActivityUpdates,\n});\n- this.markActivityUpdatesAsInTransit(queuedActivityUpdates, messageID);\n+ const activityUpdatePromise = new Promise(\n+ (resolve, reject) => this.inflightRequests.push({\n+ expectedResponseType:\n+ serverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE,\n+ resolve,\n+ reject,\n+ messageID,\n+ }),\n+ );\n+ this.handleActivityUpdates(activityUpdatePromise, queuedActivityUpdates);\n}\nconst sessionState = this.props.sessionStateFunc();\n@@ -562,38 +545,8 @@ class Socket extends React.PureComponent<Props> {\nthis.transitStatuses = newTransitStatuses;\n}\n- filterInTransitActivityUpdates(\n- activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n- ): ActivityUpdate[] {\n- const filtered = [];\n- for (let activityUpdate of activityUpdates) {\n- let inTransit = false;\n- for (let transitStatus of this.transitStatuses) {\n- if (transitStatus.type !== \"ActivityUpdate\") {\n- continue;\n- }\n- const {\n- activityUpdate: inTransitActivityUpdate,\n- messageID,\n- } = transitStatus;\n- if (\n- inTransitActivityUpdate === activityUpdate &&\n- messageID !== null && messageID !== undefined\n- ) {\n- inTransit = true;\n- break;\n- }\n- }\n- if (!inTransit) {\n- filtered.push(activityUpdate);\n- }\n- }\n- return filtered;\n- }\n-\nupdateTransitStatusesWithServerResponse(success: bool, messageID: number) {\nconst deliveredResponses = [], erroredResponseStatuses = [];\n- const failedActivityUpdates = [], erroredActivityUpdateStatuses = [];\nconst stillInTransit = [];\nfor (let transitStatus of this.transitStatuses) {\nif (\n@@ -605,17 +558,6 @@ class Socket extends React.PureComponent<Props> {\n} else {\nerroredResponseStatuses.push(transitStatus);\n}\n- } else if (\n- transitStatus.type === \"ActivityUpdate\" &&\n- transitStatus.messageID === messageID &&\n- !success\n- ) {\n- if (transitStatus.status === \"errored\") {\n- failedActivityUpdates.push(transitStatus.activityUpdate);\n- stillInTransit.push(transitStatus);\n- } else {\n- erroredActivityUpdateStatuses.push(transitStatus);\n- }\n} else {\nstillInTransit.push(transitStatus);\n}\n@@ -636,13 +578,6 @@ class Socket extends React.PureComponent<Props> {\n);\n}\n- if (failedActivityUpdates.length > 0) {\n- this.props.dispatchActionPayload(\n- activityUpdateFailedActionType,\n- { activityUpdates: failedActivityUpdates },\n- );\n- }\n-\nif (erroredResponseStatuses.length > 0) {\nconst newTransitStatuses = erroredResponseStatuses.map(transitStatus => ({\n// Mark our second attempt as already \"errored\" so they get\n@@ -660,24 +595,6 @@ class Socket extends React.PureComponent<Props> {\n);\n}\n- if (erroredResponseStatuses.length > 0) {\n- const newTransitStatuses =\n- erroredActivityUpdateStatuses.map(transitStatus => ({\n- // Mark our second attempt as already \"errored\" so they get\n- // filtered out on the next cycle\n- type: \"ActivityUpdate\",\n- status: \"errored\",\n- activityUpdate: transitStatus.activityUpdate,\n- }));\n- this.transitStatuses = [\n- ...this.transitStatuses,\n- ...newTransitStatuses,\n- ];\n- this.sendActivityUpdates(\n- newTransitStatuses.map(transitStatus => transitStatus.activityUpdate),\n- );\n- }\n-\nconst { status } = this.props.connection;\nif (status === \"disconnecting\" || status === \"forcedDisconnecting\") {\nthis.finishClosingSocket();\n@@ -694,72 +611,70 @@ class Socket extends React.PureComponent<Props> {\n);\n}\n- sendActivityUpdates(activityUpdates: $ReadOnlyArray<ActivityUpdate>) {\n+ sendAndHandleActivityUpdates(\n+ activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n+ ) {\nif (activityUpdates.length === 0) {\nreturn;\n}\n- const filtered = this.filterInTransitActivityUpdates(activityUpdates);\n- if (filtered.length === 0) {\n- return;\n+ const promise = this.sendActivityUpdates(activityUpdates);\n+ this.handleActivityUpdates(promise, activityUpdates);\n}\n+\n+ sendActivityUpdates(\n+ activityUpdates: $ReadOnlyArray<ActivityUpdate>\n+ ): Promise<ActivityUpdateResponseServerSocketMessage> {\nconst messageID = this.nextClientMessageID++;\n- this.markActivityUpdatesAsInTransit(filtered, messageID);\n+ const activityUpdatePromise = new Promise(\n+ (resolve, reject) => this.inflightRequests.push({\n+ expectedResponseType:\n+ serverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE,\n+ resolve,\n+ reject,\n+ messageID,\n+ }),\n+ );\nthis.sendMessage({\ntype: clientSocketMessageTypes.ACTIVITY_UPDATES,\nid: messageID,\n- payload: { activityUpdates: filtered },\n+ payload: { activityUpdates },\n});\n+ return activityUpdatePromise;\n}\n- markActivityUpdatesAsInTransit(\n+ async handleActivityUpdates(\n+ promise: Promise<ActivityUpdateResponseServerSocketMessage>,\nactivityUpdates: $ReadOnlyArray<ActivityUpdate>,\n- messageID: number,\n- ) {\n- // We want to avoid double-sending ActivityUpdates, so we mark them as\n- // in-transit once they're sent\n- if (activityUpdates.length === 0) {\n- return;\n- }\n- const errored = [];\n- const newTransitStatuses = this.transitStatuses.filter(\n- transitStatus => {\n- if (transitStatus.type !== \"ActivityUpdate\") {\n- return true;\n- }\n- let matches = false;\n- for (let activityUpdate of activityUpdates) {\n- if (activityUpdate === transitStatus.activityUpdate) {\n- matches = true;\n- break;\n- }\n- }\n- if (!matches) {\n- return true;\n- }\n- if (transitStatus.status === \"errored\") {\n- errored.push(transitStatus.activityUpdate);\n+ retriesLeft: number = 1,\n+ ): Promise<void> {\n+ try {\n+ const response = await promise;\n+ this.props.dispatchActionPayload(\n+ activityUpdateSuccessActionType,\n+ { activityUpdates, result: response.payload },\n+ );\n+ } catch (e) {\n+ if (!(e instanceof ServerError)) {\n+ console.warn(e);\n}\n- return false;\n- },\n+ if (\n+ !(e instanceof ServerError) ||\n+ retriesLeft === 0 ||\n+ this.props.connection.status !== \"connected\"\n+ ) {\n+ this.props.dispatchActionPayload(\n+ activityUpdateFailedActionType,\n+ { activityUpdates },\n);\n- for (let activityUpdate of activityUpdates) {\n- if (errored.includes(activityUpdate)) {\n- newTransitStatuses.push({\n- type: \"ActivityUpdate\",\n- status: \"errored\",\n- activityUpdate,\n- messageID,\n- });\n} else {\n- newTransitStatuses.push({\n- type: \"ActivityUpdate\",\n- status: \"inflight\",\n- activityUpdate,\n- messageID,\n- });\n+ const newPromise = this.sendActivityUpdates(activityUpdates);\n+ await this.handleActivityUpdates(\n+ newPromise,\n+ activityUpdates,\n+ retriesLeft - 1,\n+ );\n}\n}\n- this.transitStatuses = newTransitStatuses;\n}\nfilterInTransitClientResponses(\n" }, { "change_type": "MODIFY", "old_path": "lib/types/socket-types.js", "new_path": "lib/types/socket-types.js", "diff": "@@ -16,6 +16,7 @@ import {\ntype UpdateActivityResult,\nactivityUpdatePropType,\n} from './activity-types';\n+import { ServerError } from '../utils/errors';\nimport invariant from 'invariant';\nimport PropTypes from 'prop-types';\n@@ -165,6 +166,55 @@ export type ServerSocketMessage =\n| AuthErrorServerSocketMessage\n| ActivityUpdateResponseServerSocketMessage;\n+type BaseInflightRequest<Response: ServerSocketMessage> = {|\n+ expectedResponseType: $PropertyType<Response, 'type'>,\n+ resolve: (response: Response) => void,\n+ reject: (error: Error) => void,\n+ messageID: number,\n+|};\n+export type InflightRequest =\n+ | BaseInflightRequest<StateSyncServerSocketMessage>\n+ | BaseInflightRequest<RequestsServerSocketMessage>\n+ | BaseInflightRequest<ActivityUpdateResponseServerSocketMessage>;\n+export function resolveRequests(\n+ message: ServerSocketMessage,\n+ inflightRequests: $ReadOnlyArray<InflightRequest>,\n+): InflightRequest[] {\n+ const remainingInflightRequests = [];\n+ for (let inflightRequest of inflightRequests) {\n+ if (inflightRequest.messageID !== message.responseTo) {\n+ remainingInflightRequests.push(inflightRequest);\n+ continue;\n+ }\n+ if (message.type === serverSocketMessageTypes.ERROR) {\n+ const error = message.payload\n+ ? new ServerError(message.message, message.payload)\n+ : new ServerError(message.message);\n+ inflightRequest.reject(error);\n+ } else if (\n+ message.type === serverSocketMessageTypes.STATE_SYNC &&\n+ inflightRequest.expectedResponseType ===\n+ serverSocketMessageTypes.STATE_SYNC\n+ ) {\n+ inflightRequest.resolve(message);\n+ } else if (\n+ message.type === serverSocketMessageTypes.REQUESTS &&\n+ inflightRequest.expectedResponseType === serverSocketMessageTypes.REQUESTS\n+ ) {\n+ inflightRequest.resolve(message);\n+ } else if (\n+ message.type === serverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE &&\n+ inflightRequest.expectedResponseType ===\n+ serverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE\n+ ) {\n+ inflightRequest.resolve(message);\n+ } else {\n+ remainingInflightRequests.push(inflightRequest);\n+ }\n+ }\n+ return remainingInflightRequests;\n+}\n+\nexport type ConnectionStatus =\n| \"connecting\"\n| \"connected\"\n" }, { "change_type": "MODIFY", "old_path": "native/socket.react.js", "new_path": "native/socket.react.js", "diff": "@@ -21,12 +21,13 @@ import {\nexport default connect(\n(state: AppState) => {\n- const activeThread = activeThreadSelector(state);\n- return {\n- active: appLoggedInSelector(state) &&\n+ const active = appLoggedInSelector(state) &&\nstate.currentUserInfo &&\n!state.currentUserInfo.anonymous &&\n- state.foreground,\n+ state.foreground;\n+ const activeThread = active ? activeThreadSelector(state) : null;\n+ return {\n+ active,\nopenSocket: openSocketSelector(state),\ngetClientResponses: clientResponsesSelector(state),\nactiveThread,\n" }, { "change_type": "MODIFY", "old_path": "server/flow-typed/npm/ws_vx.x.x.js", "new_path": "server/flow-typed/npm/ws_vx.x.x.js", "diff": "@@ -20,6 +20,7 @@ declare module 'ws' {\non: (name: string, func: Function) => void,\nsend: (value: string) => void,\nclose: (code?: number, reason?: string) => void,\n+ ping: () => void,\n};\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/socket.js", "new_path": "server/src/socket.js", "diff": "@@ -429,7 +429,10 @@ async function handleInitialClientSocketMessage(\n}\nif (activityUpdateResult) {\n- responses.push({\n+ // We send this message first since the STATE_SYNC triggers the client's\n+ // connection status to shift to \"connected\", and we want to make sure the\n+ // queued activity updates are cleared from Redux before that happens\n+ responses.unshift({\ntype: serverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE,\nresponseTo: message.id,\npayload: activityUpdateResult,\n" }, { "change_type": "MODIFY", "old_path": "web/socket.react.js", "new_path": "web/socket.react.js", "diff": "@@ -18,11 +18,12 @@ import { activeThreadSelector } from './selectors/nav-selectors';\nexport default connect(\n(state: AppState) => {\n- const activeThread = activeThreadSelector(state);\n- return {\n- active: state.currentUserInfo &&\n+ const active = state.currentUserInfo &&\n!state.currentUserInfo.anonymous &&\n- state.foreground,\n+ state.foreground;\n+ const activeThread = active ? activeThreadSelector(state) : null;\n+ return {\n+ active,\nopenSocket: openSocketSelector(state),\ngetClientResponses: clientResponsesSelector(state),\nactiveThread,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Promise-based mechanism for ActivityUpdates in Socket component
129,187
25.10.2018 12:17:54
14,400
7e5b45c9d5547203d08bc00984496aa0df77fd24
Promise-based mechanism for ClientResponses in Socket component
[ { "change_type": "MODIFY", "old_path": "lib/components/socket.react.js", "new_path": "lib/components/socket.react.js", "diff": "@@ -6,6 +6,7 @@ import {\ntype ClientResponse,\nclearDeliveredClientResponsesActionType,\nprocessServerRequestsActionType,\n+ clientResponsePropType,\n} from '../types/request-types';\nimport {\ntype SessionState,\n@@ -27,6 +28,7 @@ import {\nactivityUpdateSuccessActionType,\nactivityUpdateFailedActionType,\ntype ActivityUpdateResponseServerSocketMessage,\n+ type RequestsServerSocketMessage,\ntype InflightRequest,\nresolveRequests,\n} from '../types/socket-types';\n@@ -48,27 +50,13 @@ import {\nimport { socketAuthErrorResolutionAttempt } from '../actions/user-actions';\nimport { ServerError } from '../utils/errors';\n-type TransitStatus =\n- | {|\n- type: \"ClientResponse\",\n- status: \"inflight\",\n- clientResponse: ClientResponse,\n- // Socket message ID, not chat message\n- messageID: number,\n- |}\n- | {|\n- type: \"ClientResponse\",\n- status: \"errored\",\n- clientResponse: ClientResponse,\n- messageID?: number,\n- |};\n-\ntype Props = {|\n// Redux state\nactive: bool,\nopenSocket: () => WebSocket,\n+ queuedClientResponses: $ReadOnlyArray<ClientResponse>,\ngetClientResponses: (\n- activeServerRequests?: $ReadOnlyArray<ServerRequest>,\n+ activeServerRequests: $ReadOnlyArray<ServerRequest>,\n) => $ReadOnlyArray<ClientResponse>,\nactiveThread: ?string,\nactiveThreadLatestMessage: ?string,\n@@ -87,6 +75,7 @@ class Socket extends React.PureComponent<Props> {\nstatic propTypes = {\nopenSocket: PropTypes.func.isRequired,\nactive: PropTypes.bool.isRequired,\n+ queuedClientResponses: PropTypes.arrayOf(clientResponsePropType).isRequired,\ngetClientResponses: PropTypes.func.isRequired,\nactiveThread: PropTypes.string,\nactiveThreadLatestMessage: PropTypes.string,\n@@ -100,11 +89,10 @@ class Socket extends React.PureComponent<Props> {\ndispatchActionPayload: PropTypes.func.isRequired,\n};\nsocket: ?WebSocket;\n- initialPlatformDetailsSent = false;\nnextClientMessageID = 0;\n- transitStatuses: TransitStatus[] = [];\n- reopenConnectionAfterClosing = false;\ninflightRequests: InflightRequest[] = [];\n+ initialPlatformDetailsSent = false;\n+ reopenConnectionAfterClosing = false;\nopenSocket() {\nif (this.socket) {\n@@ -144,7 +132,6 @@ class Socket extends React.PureComponent<Props> {\n}\n};\nthis.socket = socket;\n- this.transitStatuses = [];\nthis.inflightRequests = [];\n}\n@@ -194,7 +181,7 @@ class Socket extends React.PureComponent<Props> {\n}\nfinishClosingSocket() {\n- if (this.transitStatuses.length > 0 || this.inflightRequests.length > 0) {\n+ if (this.inflightRequests.length > 0) {\nreturn;\n}\nthis.props.dispatchActionPayload(\n@@ -261,28 +248,39 @@ class Socket extends React.PureComponent<Props> {\n);\n}\n- const { status } = this.props.connection;\n- const { status: prevStatus } = prevProps.connection;\n- if (\n+ const { queuedClientResponses, connection } = this.props;\n+ const { status, queuedActivityUpdates } = connection;\n+ const {\n+ queuedClientResponses: prevClientResponses,\n+ connection: prevConnection,\n+ } = this.props;\n+ const {\n+ status: prevStatus,\n+ queuedActivityUpdates: prevActivityUpdates,\n+ } = prevConnection;\n+\n+ if (status === \"connected\" && prevStatus !== \"connected\") {\n+ this.sendAndHandleQueuedClientResponses(queuedClientResponses);\n+ } else if (\nstatus === \"connected\" &&\n- (prevStatus !== \"connected\" ||\n- this.props.getClientResponses !== prevProps.getClientResponses)\n+ queuedClientResponses !== prevClientResponses\n) {\n- const clientResponses = this.props.getClientResponses();\n- this.sendClientResponses(clientResponses);\n+ const prevResponses = new Set(prevClientResponses);\n+ const newResponses = queuedClientResponses.filter(\n+ response => !prevResponses.has(response),\n+ );\n+ this.sendAndHandleQueuedClientResponses(newResponses);\n}\n- const { queuedActivityUpdates } = this.props.connection;\n- const { queuedActivityUpdates: prevActivityUpdates } = prevProps.connection;\nif (status === \"connected\" && prevStatus !== \"connected\") {\nthis.sendAndHandleActivityUpdates(queuedActivityUpdates);\n} else if (\nstatus === \"connected\" &&\nqueuedActivityUpdates !== prevActivityUpdates\n) {\n- const previousUpdates = new Set(prevActivityUpdates);\n+ const prevUpdates = new Set(prevActivityUpdates);\nconst newUpdates = queuedActivityUpdates.filter(\n- update => !previousUpdates.has(update),\n+ update => !prevUpdates.has(update),\n);\nthis.sendAndHandleActivityUpdates(newUpdates);\n}\n@@ -327,7 +325,6 @@ class Socket extends React.PureComponent<Props> {\n}\nif (message.type === serverSocketMessageTypes.STATE_SYNC) {\n- this.updateTransitStatusesWithServerResponse(true, message.responseTo);\nif (message.payload.type === stateSyncPayloadTypes.FULL) {\nconst { sessionID, type, ...actionPayload } = message.payload;\nthis.props.dispatchActionPayload(\n@@ -352,16 +349,14 @@ class Socket extends React.PureComponent<Props> {\n}\nthis.markSocketInitialized();\n} else if (message.type === serverSocketMessageTypes.REQUESTS) {\n- this.updateTransitStatusesWithServerResponse(true, message.responseTo);\nconst { serverRequests } = message.payload;\nthis.processServerRequests(serverRequests);\nconst clientResponses = this.props.getClientResponses(serverRequests);\n- this.sendClientResponses(clientResponses);\n- } else if (message.type === serverSocketMessageTypes.ERROR) {\n- const { message: errorMessage, payload, responseTo } = message;\n- if (responseTo !== null && responseTo !== undefined) {\n- this.updateTransitStatusesWithServerResponse(false, responseTo);\n+ if (this.props.connection.status === \"connected\") {\n+ this.sendAndHandleClientResponsesToServerRequests(clientResponses);\n}\n+ } else if (message.type === serverSocketMessageTypes.ERROR) {\n+ const { message: errorMessage, payload } = message;\nif (payload) {\nconsole.warn(`socket sent error ${errorMessage} with payload`, payload);\n} else {\n@@ -391,18 +386,6 @@ class Socket extends React.PureComponent<Props> {\n},\n);\n}\n- } else if (\n- message.type === serverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE\n- ) {\n- const deliveredActivityUpdates = [];\n- for (let transitStatus of this.transitStatuses) {\n- if (\n- transitStatus.type === \"ActivityUpdate\" &&\n- transitStatus.messageID === message.responseTo\n- ) {\n- deliveredActivityUpdates.push(transitStatus.activityUpdate);\n- }\n- }\n}\n}\n@@ -427,21 +410,29 @@ class Socket extends React.PureComponent<Props> {\nsendInitialMessage = () => {\nconst messageID = this.nextClientMessageID++;\n- const baseClientResponses = this.props.getClientResponses();\n- const nonActivityClientResponses = [ ...baseClientResponses ];\n- const responsesIncludePlatformDetails = nonActivityClientResponses.some(\n- response => response.type === serverRequestTypes.PLATFORM_DETAILS,\n- );\n+ const nonActivityClientResponses = [ ...this.props.queuedClientResponses ];\nif (!this.initialPlatformDetailsSent) {\nthis.initialPlatformDetailsSent = true;\n- if (!responsesIncludePlatformDetails) {\nnonActivityClientResponses.push({\ntype: serverRequestTypes.PLATFORM_DETAILS,\nplatformDetails: getConfig().platformDetails,\n});\n}\n+\n+ if (nonActivityClientResponses.length > 0) {\n+ const clientResponsesPromise = new Promise(\n+ (resolve, reject) => this.inflightRequests.push({\n+ expectedResponseType: serverSocketMessageTypes.REQUESTS,\n+ resolve,\n+ reject,\n+ messageID,\n+ }),\n+ );\n+ this.handleQueuedClientResponses(\n+ clientResponsesPromise,\n+ nonActivityClientResponses,\n+ );\n}\n- this.markClientResponsesAsInTransit(nonActivityClientResponses, messageID);\nconst clientResponses = [ ...nonActivityClientResponses];\nconst { queuedActivityUpdates } = this.props.connection;\n@@ -476,128 +467,104 @@ class Socket extends React.PureComponent<Props> {\nthis.sendMessage(initialMessage);\n}\n- sendClientResponses(clientResponses: $ReadOnlyArray<ClientResponse>) {\n+ sendAndHandleQueuedClientResponses(\n+ clientResponses: $ReadOnlyArray<ClientResponse>,\n+ ) {\nif (clientResponses.length === 0) {\nreturn;\n}\n- const filtered = this.filterInTransitClientResponses(clientResponses);\n- if (filtered.length === 0) {\n- return;\n+ const promise = this.sendClientResponses(clientResponses);\n+ this.handleQueuedClientResponses(promise, clientResponses);\n}\n+\n+ sendClientResponses(\n+ clientResponses: $ReadOnlyArray<ClientResponse>,\n+ ): Promise<RequestsServerSocketMessage> {\nconst messageID = this.nextClientMessageID++;\n- this.markClientResponsesAsInTransit(filtered, messageID);\n+ const promise = new Promise(\n+ (resolve, reject) => this.inflightRequests.push({\n+ expectedResponseType: serverSocketMessageTypes.REQUESTS,\n+ resolve,\n+ reject,\n+ messageID,\n+ }),\n+ );\nthis.sendMessage({\ntype: clientSocketMessageTypes.RESPONSES,\nid: messageID,\n- payload: { clientResponses: filtered },\n+ payload: { clientResponses },\n});\n+ return promise;\n}\n- markClientResponsesAsInTransit(\n+ async handleQueuedClientResponses(\n+ promise: Promise<RequestsServerSocketMessage>,\nclientResponses: $ReadOnlyArray<ClientResponse>,\n- messageID: number,\n- ) {\n- // We want to avoid double-sending the ClientResponses we cache in Redux\n- // (namely, the inconsistency responses), so we mark them as in-transit once\n- // they're sent\n- if (clientResponses.length === 0) {\n- return;\n- }\n- const errored = [];\n- const newTransitStatuses = this.transitStatuses.filter(\n- transitStatus => {\n- if (transitStatus.type !== \"ClientResponse\") {\n- return true;\n- }\n- let matches = false;\n- for (let clientResponse of clientResponses) {\n- if (clientResponse === transitStatus.clientResponse) {\n- matches = true;\n- break;\n- }\n- }\n- if (!matches) {\n- return true;\n- }\n- if (transitStatus.status === \"errored\") {\n- errored.push(transitStatus.clientResponse);\n+ retriesLeft: number = 1,\n+ ): Promise<void> {\n+ try {\n+ const response = await promise;\n+ this.props.dispatchActionPayload(\n+ clearDeliveredClientResponsesActionType,\n+ { clientResponses },\n+ );\n+ } catch (e) {\n+ if (!(e instanceof ServerError)) {\n+ console.warn(e);\n}\n- return false;\n- },\n+ if (\n+ !(e instanceof ServerError) ||\n+ retriesLeft === 0 ||\n+ this.props.connection.status !== \"connected\"\n+ ) {\n+ this.props.dispatchActionPayload(\n+ clearDeliveredClientResponsesActionType,\n+ { clientResponses },\n);\n- for (let clientResponse of clientResponses) {\n- if (errored.includes(clientResponse)) {\n- newTransitStatuses.push({\n- type: \"ClientResponse\",\n- status: \"errored\",\n- clientResponse,\n- messageID,\n- });\n} else {\n- newTransitStatuses.push({\n- type: \"ClientResponse\",\n- status: \"inflight\",\n- clientResponse,\n- messageID,\n- });\n+ const newPromise = this.sendClientResponses(clientResponses);\n+ await this.handleQueuedClientResponses(\n+ newPromise,\n+ clientResponses,\n+ retriesLeft - 1,\n+ );\n}\n}\n- this.transitStatuses = newTransitStatuses;\n}\n- updateTransitStatusesWithServerResponse(success: bool, messageID: number) {\n- const deliveredResponses = [], erroredResponseStatuses = [];\n- const stillInTransit = [];\n- for (let transitStatus of this.transitStatuses) {\n- if (\n- transitStatus.type === \"ClientResponse\" &&\n- transitStatus.messageID === messageID\n+ sendAndHandleClientResponsesToServerRequests(\n+ clientResponses: $ReadOnlyArray<ClientResponse>,\n) {\n- if (success || transitStatus.status === \"errored\") {\n- deliveredResponses.push(transitStatus.clientResponse);\n- } else {\n- erroredResponseStatuses.push(transitStatus);\n- }\n- } else {\n- stillInTransit.push(transitStatus);\n+ if (clientResponses.length === 0) {\n+ return;\n}\n+ const promise = this.sendClientResponses(clientResponses);\n+ this.handleClientResponsesToServerRequests(promise, clientResponses);\n}\n- this.transitStatuses = stillInTransit;\n- if (deliveredResponses.length > 0) {\n- // Note: it's hypothetically possible for something to call\n- // sendClientResponses after we update this.transitStatuses but before\n- // this Redux action propagates to this component. In that case, we could\n- // double-send some Redux-cached ClientResponses. Since right now only\n- // inconsistency responses are Redux-cached, and the server knows how to\n- // dedup those so that the transaction is idempotent, we're not going to\n- // worry about it.\n- this.props.dispatchActionPayload(\n- clearDeliveredClientResponsesActionType,\n- { clientResponses: deliveredResponses },\n- );\n+ async handleClientResponsesToServerRequests(\n+ promise: Promise<RequestsServerSocketMessage>,\n+ clientResponses: $ReadOnlyArray<ClientResponse>,\n+ retriesLeft: number = 1,\n+ ): Promise<void> {\n+ try {\n+ const response = await promise;\n+ } catch (e) {\n+ if (!(e instanceof ServerError)) {\n+ console.warn(e);\n}\n-\n- if (erroredResponseStatuses.length > 0) {\n- const newTransitStatuses = erroredResponseStatuses.map(transitStatus => ({\n- // Mark our second attempt as already \"errored\" so they get\n- // filtered out on the next cycle\n- type: \"ClientResponse\",\n- status: \"errored\",\n- clientResponse: transitStatus.clientResponse,\n- }));\n- this.transitStatuses = [\n- ...this.transitStatuses,\n- ...newTransitStatuses,\n- ];\n- this.sendClientResponses(\n- newTransitStatuses.map(transitStatus => transitStatus.clientResponse),\n+ if (\n+ e instanceof ServerError &&\n+ retriesLeft > 0 &&\n+ this.props.connection.status === \"connected\"\n+ ) {\n+ const newPromise = this.sendClientResponses(clientResponses);\n+ await this.handleClientResponsesToServerRequests(\n+ newPromise,\n+ clientResponses,\n+ retriesLeft - 1,\n);\n}\n-\n- const { status } = this.props.connection;\n- if (status === \"disconnecting\" || status === \"forcedDisconnecting\") {\n- this.finishClosingSocket();\n}\n}\n@@ -625,7 +592,7 @@ class Socket extends React.PureComponent<Props> {\nactivityUpdates: $ReadOnlyArray<ActivityUpdate>\n): Promise<ActivityUpdateResponseServerSocketMessage> {\nconst messageID = this.nextClientMessageID++;\n- const activityUpdatePromise = new Promise(\n+ const promise = new Promise(\n(resolve, reject) => this.inflightRequests.push({\nexpectedResponseType:\nserverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE,\n@@ -639,7 +606,7 @@ class Socket extends React.PureComponent<Props> {\nid: messageID,\npayload: { activityUpdates },\n});\n- return activityUpdatePromise;\n+ return promise;\n}\nasync handleActivityUpdates(\n@@ -677,35 +644,6 @@ class Socket extends React.PureComponent<Props> {\n}\n}\n- filterInTransitClientResponses(\n- clientResponses: $ReadOnlyArray<ClientResponse>,\n- ): ClientResponse[] {\n- const filtered = [];\n- for (let clientResponse of clientResponses) {\n- let inTransit = false;\n- for (let transitStatus of this.transitStatuses) {\n- if (transitStatus.type !== \"ClientResponse\") {\n- continue;\n- }\n- const {\n- clientResponse: inTransitClientResponse,\n- messageID,\n- } = transitStatus;\n- if (\n- inTransitClientResponse === clientResponse &&\n- messageID !== null && messageID !== undefined\n- ) {\n- inTransit = true;\n- break;\n- }\n- }\n- if (!inTransit) {\n- filtered.push(clientResponse);\n- }\n- }\n- return filtered;\n- }\n-\n}\nexport default Socket;\n" }, { "change_type": "MODIFY", "old_path": "lib/selectors/socket-selectors.js", "new_path": "lib/selectors/socket-selectors.js", "diff": "@@ -25,32 +25,34 @@ import { values, hash } from '../utils/objects';\nimport { currentCalendarQuery } from './nav-selectors';\nimport threadWatcher from '../shared/thread-watcher';\n-const clientResponsesSelector = createSelector(\n+const queuedClientResponsesSelector = createSelector(\n(state: AppState) => state.threadStore.inconsistencyResponses,\n(state: AppState) => state.entryStore.inconsistencyResponses,\n- (state: AppState) => state.threadStore.threadInfos,\n- (state: AppState) => state.entryStore.entryInfos,\n- (state: AppState) => state.currentUserInfo,\n- currentCalendarQuery,\n(\nthreadInconsistencyResponses:\n$ReadOnlyArray<ThreadInconsistencyClientResponse>,\nentryInconsistencyResponses:\n$ReadOnlyArray<EntryInconsistencyClientResponse>,\n+ ): $ReadOnlyArray<ClientResponse> => [\n+ ...threadInconsistencyResponses,\n+ ...entryInconsistencyResponses,\n+ ],\n+);\n+\n+const getClientResponsesSelector = createSelector(\n+ (state: AppState) => state.threadStore.threadInfos,\n+ (state: AppState) => state.entryStore.entryInfos,\n+ (state: AppState) => state.currentUserInfo,\n+ currentCalendarQuery,\n+ (\nthreadInfos: {[id: string]: RawThreadInfo},\nentryInfos: {[id: string]: RawEntryInfo},\ncurrentUserInfo: ?CurrentUserInfo,\ncalendarQuery: () => CalendarQuery,\n) => (\n- serverRequests?: $ReadOnlyArray<ServerRequest>,\n+ serverRequests: $ReadOnlyArray<ServerRequest>,\n): $ReadOnlyArray<ClientResponse> => {\n- const clientResponses = [\n- ...threadInconsistencyResponses,\n- ...entryInconsistencyResponses,\n- ];\n- if (!serverRequests) {\n- return clientResponses;\n- }\n+ const clientResponses = [];\nconst serverRequestedPlatformDetails = serverRequests.some(\nrequest => request.type === serverRequestTypes.PLATFORM_DETAILS,\n);\n@@ -123,6 +125,7 @@ const sessionStateFuncSelector = createSelector(\n);\nexport {\n- clientResponsesSelector,\n+ queuedClientResponsesSelector,\n+ getClientResponsesSelector,\nsessionStateFuncSelector,\n};\n" }, { "change_type": "MODIFY", "old_path": "lib/types/request-types.js", "new_path": "lib/types/request-types.js", "diff": "@@ -14,7 +14,7 @@ import {\ncalendarQueryPropType,\n} from './entry-types';\nimport type { BaseAction } from './redux-types';\n-import type { ActivityUpdate } from './activity-types';\n+import { type ActivityUpdate, activityUpdatePropType } from './activity-types';\nimport {\ntype CurrentUserInfo,\ntype AccountUserInfo,\n@@ -142,6 +142,60 @@ export type ClientResponse =\n| CheckStateClientResponse\n| InitialActivityUpdatesClientResponse;\n+export const clientResponsePropType = PropTypes.oneOfType([\n+ PropTypes.shape({\n+ type: PropTypes.oneOf([ serverRequestTypes.PLATFORM ]).isRequired,\n+ platform: platformPropType.isRequired,\n+ }),\n+ PropTypes.shape({\n+ type: PropTypes.oneOf([ serverRequestTypes.DEVICE_TOKEN ]).isRequired,\n+ deviceToken: PropTypes.string.isRequired,\n+ }),\n+ PropTypes.shape({\n+ type: PropTypes.oneOf([\n+ serverRequestTypes.THREAD_INCONSISTENCY,\n+ ]).isRequired,\n+ platformDetails: platformDetailsPropType.isRequired,\n+ beforeAction: PropTypes.objectOf(rawThreadInfoPropType).isRequired,\n+ action: PropTypes.object.isRequired,\n+ pollResult: PropTypes.objectOf(rawThreadInfoPropType).isRequired,\n+ pushResult: PropTypes.objectOf(rawThreadInfoPropType).isRequired,\n+ lastActionTypes: PropTypes.arrayOf(PropTypes.string),\n+ time: PropTypes.number,\n+ }),\n+ PropTypes.shape({\n+ type: PropTypes.oneOf([ serverRequestTypes.PLATFORM_DETAILS ]).isRequired,\n+ platformDetails: platformDetailsPropType.isRequired,\n+ }),\n+ PropTypes.shape({\n+ type: PropTypes.oneOf([ serverRequestTypes.INITIAL_ACTIVITY_UPDATE ]).isRequired,\n+ threadID: PropTypes.string.isRequired,\n+ }),\n+ PropTypes.shape({\n+ type: PropTypes.oneOf([\n+ serverRequestTypes.ENTRY_INCONSISTENCY,\n+ ]).isRequired,\n+ platformDetails: platformDetailsPropType.isRequired,\n+ beforeAction: PropTypes.objectOf(rawEntryInfoPropType).isRequired,\n+ action: PropTypes.object.isRequired,\n+ calendarQuery: calendarQueryPropType.isRequired,\n+ pollResult: PropTypes.objectOf(rawEntryInfoPropType).isRequired,\n+ pushResult: PropTypes.objectOf(rawEntryInfoPropType).isRequired,\n+ lastActionTypes: PropTypes.arrayOf(PropTypes.string).isRequired,\n+ time: PropTypes.number.isRequired,\n+ }),\n+ PropTypes.shape({\n+ type: PropTypes.oneOf([ serverRequestTypes.CHECK_STATE ]).isRequired,\n+ hashResults: PropTypes.objectOf(PropTypes.bool).isRequired,\n+ }),\n+ PropTypes.shape({\n+ type: PropTypes.oneOf([\n+ serverRequestTypes.INITIAL_ACTIVITY_UPDATES,\n+ ]).isRequired,\n+ activityUpdates: PropTypes.arrayOf(activityUpdatePropType).isRequired,\n+ }),\n+]);\n+\nexport const clearDeliveredClientResponsesActionType =\n\"CLEAR_DELIVERED_CLIENT_RESPONSES\";\nexport type ClearDeliveredClientResponsesPayload = {|\n" }, { "change_type": "MODIFY", "old_path": "lib/types/socket-types.js", "new_path": "lib/types/socket-types.js", "diff": "@@ -173,7 +173,6 @@ type BaseInflightRequest<Response: ServerSocketMessage> = {|\nmessageID: number,\n|};\nexport type InflightRequest =\n- | BaseInflightRequest<StateSyncServerSocketMessage>\n| BaseInflightRequest<RequestsServerSocketMessage>\n| BaseInflightRequest<ActivityUpdateResponseServerSocketMessage>;\nexport function resolveRequests(\n@@ -191,12 +190,6 @@ export function resolveRequests(\n? new ServerError(message.message, message.payload)\n: new ServerError(message.message);\ninflightRequest.reject(error);\n- } else if (\n- message.type === serverSocketMessageTypes.STATE_SYNC &&\n- inflightRequest.expectedResponseType ===\n- serverSocketMessageTypes.STATE_SYNC\n- ) {\n- inflightRequest.resolve(message);\n} else if (\nmessage.type === serverSocketMessageTypes.REQUESTS &&\ninflightRequest.expectedResponseType === serverSocketMessageTypes.REQUESTS\n" }, { "change_type": "MODIFY", "old_path": "native/socket.react.js", "new_path": "native/socket.react.js", "diff": "@@ -4,7 +4,8 @@ import type { AppState } from './redux-setup';\nimport { connect } from 'lib/utils/redux-utils';\nimport {\n- clientResponsesSelector,\n+ queuedClientResponsesSelector,\n+ getClientResponsesSelector,\nsessionStateFuncSelector,\n} from 'lib/selectors/socket-selectors';\nimport { logInExtraInfoSelector } from 'lib/selectors/account-selectors';\n@@ -29,7 +30,8 @@ export default connect(\nreturn {\nactive,\nopenSocket: openSocketSelector(state),\n- getClientResponses: clientResponsesSelector(state),\n+ queuedClientResponses: queuedClientResponsesSelector(state),\n+ getClientResponses: getClientResponsesSelector(state),\nactiveThread,\nactiveThreadLatestMessage:\nactiveThread && state.messageStore.threads[activeThread]\n" }, { "change_type": "MODIFY", "old_path": "server/src/socket.js", "new_path": "server/src/socket.js", "diff": "@@ -420,8 +420,11 @@ async function handleInitialClientSocketMessage(\nconst filteredServerRequests = serverRequests.filter(\nrequest => request.type !== serverRequestTypes.DEVICE_TOKEN,\n);\n- if (filteredServerRequests.length > 0) {\n- responses.push({\n+ if (filteredServerRequests.length > 0 || clientResponses.length > 0) {\n+ // We send this message first since the STATE_SYNC triggers the client's\n+ // connection status to shift to \"connected\", and we want to make sure the\n+ // client responses are cleared from Redux before that happens\n+ responses.unshift({\ntype: serverSocketMessageTypes.REQUESTS,\nresponseTo: message.id,\npayload: { serverRequests: filteredServerRequests },\n@@ -429,9 +432,7 @@ async function handleInitialClientSocketMessage(\n}\nif (activityUpdateResult) {\n- // We send this message first since the STATE_SYNC triggers the client's\n- // connection status to shift to \"connected\", and we want to make sure the\n- // queued activity updates are cleared from Redux before that happens\n+ // Same reason for unshifting as above\nresponses.unshift({\ntype: serverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE,\nresponseTo: message.id,\n" }, { "change_type": "MODIFY", "old_path": "web/socket.react.js", "new_path": "web/socket.react.js", "diff": "@@ -4,7 +4,8 @@ import type { AppState } from './redux-setup';\nimport { connect } from 'lib/utils/redux-utils';\nimport {\n- clientResponsesSelector,\n+ queuedClientResponsesSelector,\n+ getClientResponsesSelector,\nsessionStateFuncSelector,\n} from 'lib/selectors/socket-selectors';\nimport { logInExtraInfoSelector } from 'lib/selectors/account-selectors';\n@@ -25,7 +26,8 @@ export default connect(\nreturn {\nactive,\nopenSocket: openSocketSelector(state),\n- getClientResponses: clientResponsesSelector(state),\n+ queuedClientResponses: queuedClientResponsesSelector(state),\n+ getClientResponses: getClientResponsesSelector(state),\nactiveThread,\nactiveThreadLatestMessage:\nactiveThread && state.messageStore.threads[activeThread]\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Promise-based mechanism for ClientResponses in Socket component
129,187
26.10.2018 12:30:53
14,400
37efc4a040551cb752b59ea4e6688d59fe4a8253
Move focused time code to separate file in server package
[ { "change_type": "DELETE", "old_path": "lib/shared/activity-utils.js", "new_path": null, "diff": "-// @flow\n-\n-// We can't push yet, so we rely on pings to keep Redux state updated with the\n-// server. As a result, we do them fairly frequently (once every 3s) while the\n-// app is active and the user is logged in.\n-const pingFrequency = 3000; // in milliseconds\n-\n-// If the time column for a given entry in the focused table has a time later\n-// than this, then that entry is considered current, and consequently the thread\n-// in question is considered in focus.\n-function earliestTimeConsideredCurrent() {\n- return Date.now() - pingFrequency - 1500;\n-}\n-\n-// If the time column for a given entry in the focused table has a time earlier\n-// than this, then that entry is considered expired, and consequently we will\n-// remove it from the table in the nightly cronjob.\n-function earliestTimeConsideredExpired() {\n- return Date.now() - pingFrequency * 2 - 1500;\n-}\n-\n-export {\n- pingFrequency,\n- earliestTimeConsideredCurrent,\n- earliestTimeConsideredExpired,\n-};\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/message-creator.js", "new_path": "server/src/creators/message-creator.js", "diff": "@@ -16,7 +16,6 @@ import {\nmessageTypeGeneratesNotifs,\nshimUnsupportedRawMessageInfos,\n} from 'lib/shared/message-utils';\n-import { earliestTimeConsideredCurrent } from 'lib/shared/activity-utils';\nimport { permissionLookup } from 'lib/permissions/thread-permissions';\nimport {\n@@ -31,6 +30,7 @@ import createIDs from './id-creator';\nimport { sendPushNotifs } from '../push/send';\nimport { createUpdates } from './update-creator';\nimport { handleAsyncPromise } from '../responders/handlers';\n+import { earliestFocusedTimeConsideredCurrent } from '../shared/focused-times';\ntype ThreadRestriction = {|\ncreatorID?: ?string,\n@@ -212,7 +212,7 @@ async function updateUnreadStatus(\nsubthreadJoins.push(subthreadJoin(index, subthread));\n}\n- const time = earliestTimeConsideredCurrent();\n+ const time = earliestFocusedTimeConsideredCurrent();\nconst visibleExtractString = `$.${threadPermissions.VISIBLE}.value`;\nconst query = SQL`\nSELECT m.user, m.thread\n@@ -295,7 +295,7 @@ async function sendPushNotifsForNewMessages(\nsubthreadJoins.push(subthreadJoin(index, subthread));\n}\n- const time = earliestTimeConsideredCurrent();\n+ const time = earliestFocusedTimeConsideredCurrent();\nconst visibleExtractString = `$.${threadPermissions.VISIBLE}.value`;\nconst query = SQL`\nSELECT m.user, m.thread, c.platform, c.device_token, c.versions\n" }, { "change_type": "MODIFY", "old_path": "server/src/deleters/activity-deleters.js", "new_path": "server/src/deleters/activity-deleters.js", "diff": "import type { Viewer } from '../session/viewer';\n-import { earliestTimeConsideredExpired } from 'lib/shared/activity-utils';\n-\nimport { dbQuery, SQL } from '../database';\n+import { earliestFocusedTimeConsideredExpired } from '../shared/focused-times';\nasync function deleteForViewerSession(\nviewer: Viewer,\n@@ -21,7 +20,7 @@ async function deleteForViewerSession(\n}\nasync function deleteOrphanedFocused(): Promise<void> {\n- const time = earliestTimeConsideredExpired();\n+ const time = earliestFocusedTimeConsideredExpired();\nawait dbQuery(SQL`\nDELETE f\nFROM focused f\n" }, { "change_type": "ADD", "old_path": null, "new_path": "server/src/shared/focused-times.js", "diff": "+// @flow\n+\n+// While a socket is active (or for legacy clients, on every ping) we keep the\n+// rows in the focused table updated for the session. The server updates these\n+// rows every three seconds to keep them considered \"active\".\n+const focusedTableRefreshFrequency = 3000; // in milliseconds\n+\n+// If the time column for a given entry in the focused table has a time later\n+// than this, then that entry is considered current, and consequently the thread\n+// in question is considered in focus.\n+function earliestFocusedTimeConsideredCurrent() {\n+ return Date.now() - focusedTableRefreshFrequency - 1500;\n+}\n+\n+// If the time column for a given entry in the focused table has a time earlier\n+// than this, then that entry is considered expired, and consequently we will\n+// remove it from the table in the nightly cronjob.\n+function earliestFocusedTimeConsideredExpired() {\n+ return Date.now() - focusedTableRefreshFrequency * 2 - 1500;\n+}\n+\n+export {\n+ earliestFocusedTimeConsideredCurrent,\n+ earliestFocusedTimeConsideredExpired,\n+};\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/activity-updaters.js", "new_path": "server/src/updaters/activity-updaters.js", "diff": "@@ -12,7 +12,6 @@ import { updateTypes } from 'lib/types/update-types';\nimport invariant from 'invariant';\nimport _difference from 'lodash/fp/difference';\n-import { earliestTimeConsideredCurrent } from 'lib/shared/activity-utils';\nimport { ServerError } from 'lib/utils/errors';\nimport { dbQuery, SQL, mergeOrConditions } from '../database';\n@@ -20,6 +19,7 @@ import { verifyThreadIDs } from '../fetchers/thread-fetchers';\nimport { rescindPushNotifs } from '../push/rescind';\nimport { createUpdates } from '../creators/update-creator';\nimport { deleteForViewerSession } from '../deleters/activity-deleters';\n+import { earliestFocusedTimeConsideredCurrent } from '../shared/focused-times';\nasync function activityUpdater(\nviewer: Viewer,\n@@ -232,7 +232,7 @@ async function checkThreadsFocused(\nconst conditions = threadUserPairs.map(\npair => SQL`(user = ${pair[0]} AND thread = ${pair[1]})`,\n);\n- const time = earliestTimeConsideredCurrent();\n+ const time = earliestFocusedTimeConsideredCurrent();\nconst query = SQL`\nSELECT user, thread\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Move focused time code to separate file in server package
129,187
26.10.2018 14:41:25
14,400
c51b16a60532ac3e7e100a04027a77df11f53bb6
Application-level ping/pong to detect server/client "going away" Protocol-level ping/pong can only be initiated by server, and can't be handled at application level on client.
[ { "change_type": "MODIFY", "old_path": "lib/components/socket.react.js", "new_path": "lib/components/socket.react.js", "diff": "@@ -49,6 +49,7 @@ import {\n} from '../utils/action-utils';\nimport { socketAuthErrorResolutionAttempt } from '../actions/user-actions';\nimport { ServerError } from '../utils/errors';\n+import { pingFrequency } from '../shared/timeouts';\ntype Props = {|\n// Redux state\n@@ -91,6 +92,7 @@ class Socket extends React.PureComponent<Props> {\nsocket: ?WebSocket;\nnextClientMessageID = 0;\ninflightRequests: InflightRequest[] = [];\n+ pingTimeoutID: ?TimeoutID\ninitialPlatformDetailsSent = false;\nreopenConnectionAfterClosing = false;\n@@ -141,6 +143,7 @@ class Socket extends React.PureComponent<Props> {\nupdateConnectionStatusActionType,\n{ status: \"connected\" },\n);\n+ this.resetPing();\n}\ncloseSocket(activityUpdates: $ReadOnlyArray<ActivityUpdate>) {\n@@ -152,6 +155,7 @@ class Socket extends React.PureComponent<Props> {\nreturn;\n}\nregisterActiveWebSocket(null);\n+ this.stopPing();\nthis.props.dispatchActionPayload(\nupdateConnectionStatusActionType,\n{ status: \"disconnecting\" },\n@@ -162,6 +166,7 @@ class Socket extends React.PureComponent<Props> {\nforceCloseSocket(activityUpdates: $ReadOnlyArray<ActivityUpdate>) {\nregisterActiveWebSocket(null);\n+ this.stopPing();\nconst { status } = this.props.connection;\nif (status !== \"forcedDisconnecting\" && status !== \"disconnected\") {\nthis.props.dispatchActionPayload(\n@@ -192,6 +197,10 @@ class Socket extends React.PureComponent<Props> {\n// If it's not closing already, close it\nthis.socket.close();\n}\n+ if (this.pingTimeoutID) {\n+ clearTimeout(this.pingTimeoutID);\n+ this.pingTimeoutID = null;\n+ }\nif (this.reopenConnectionAfterClosing) {\nthis.reopenConnectionAfterClosing = false;\nif (this.props.active) {\n@@ -314,6 +323,9 @@ class Socket extends React.PureComponent<Props> {\nif (!message) {\nreturn;\n}\n+ // If we receive any message, that indicates that our connection is healthy,\n+ // so we can reset the ping timeout.\n+ this.resetPing();\nthis.inflightRequests = resolveRequests(\nmessage,\n@@ -405,6 +417,7 @@ class Socket extends React.PureComponent<Props> {\n);\n}\nthis.socket = null;\n+ this.stopPing();\n}\nsendInitialMessage = () => {\n@@ -467,6 +480,41 @@ class Socket extends React.PureComponent<Props> {\nthis.sendMessage(initialMessage);\n}\n+ stopPing() {\n+ if (this.pingTimeoutID) {\n+ clearTimeout(this.pingTimeoutID);\n+ }\n+ }\n+\n+ resetPing() {\n+ this.stopPing();\n+ const socket = this.socket;\n+ this.pingTimeoutID = setTimeout(\n+ () => {\n+ if (this.socket === socket) {\n+ this.sendPing();\n+ }\n+ },\n+ pingFrequency,\n+ );\n+ }\n+\n+ sendPing() {\n+ if (this.props.connection.status !== \"connected\") {\n+ // This generally shouldn't happen because anything that changes the\n+ // connection status should call stopPing(), but it's good to make sure\n+ return;\n+ }\n+ const messageID = this.nextClientMessageID++;\n+ // We don't add the request to this.inflightRequests because we don't need\n+ // the socket to wait for the response before closing, and we have nothing\n+ // that needs to happen after the response arrives\n+ this.sendMessage({\n+ type: clientSocketMessageTypes.PING,\n+ id: messageID,\n+ });\n+ }\n+\nsendAndHandleQueuedClientResponses(\nclientResponses: $ReadOnlyArray<ClientResponse>,\n) {\n" }, { "change_type": "ADD", "old_path": null, "new_path": "lib/shared/timeouts.js", "diff": "+// @flow\n+\n+// Sometimes the connection can just go \"away\", without the client knowing it.\n+// To detect this happening, the client hits the server with a \"ping\" every\n+// three seconds when there hasn't been any other communication.\n+export const pingFrequency = 3000; // in milliseconds\n+\n+// If a request doesn't get a response within three seconds, that means our\n+// connection is questionable. We won't close and reopen the socket yet, but we\n+// will visually indicate to the user that their connection doesn't seem to be\n+// working.\n+export const clientRequestVisualTimeout = 3000; // in milliseconds\n+\n+// If a request doesn't get a response within five seconds, we assume our socket\n+// is dead. It's possible this happened because of some weird shit on the server\n+// side, so we try to close and reopen the socket in the hopes that it will fix\n+// the problem. Of course, this is rather unlikely, as the connectivity issue is\n+// likely on the client side.\n+export const clientRequestSocketTimeout = 5000; // in milliseconds\n+\n+// The server expects to get a request at least every three seconds from the\n+// client. If it doesn't get a request within a fifteen second window, it will\n+// close the connection.\n+export const serverRequestSocketTimeout = 15000; // in milliseconds\n" }, { "change_type": "MODIFY", "old_path": "lib/types/socket-types.js", "new_path": "lib/types/socket-types.js", "diff": "@@ -26,6 +26,7 @@ export const clientSocketMessageTypes = Object.freeze({\nINITIAL: 0,\nRESPONSES: 1,\nACTIVITY_UPDATES: 2,\n+ PING: 3,\n});\nexport type ClientSocketMessageType = $Values<typeof clientSocketMessageTypes>;\nexport function assertClientSocketMessageType(\n@@ -34,7 +35,8 @@ export function assertClientSocketMessageType(\ninvariant(\nourClientSocketMessageType === 0 ||\nourClientSocketMessageType === 1 ||\n- ourClientSocketMessageType === 2,\n+ ourClientSocketMessageType === 2 ||\n+ ourClientSocketMessageType === 3,\n\"number is not ClientSocketMessageType enum\",\n);\nreturn ourClientSocketMessageType;\n@@ -63,10 +65,15 @@ export type ActivityUpdatesClientSocketMessage = {|\nactivityUpdates: $ReadOnlyArray<ActivityUpdate>,\n|},\n|};\n+export type PingClientSocketMessage = {|\n+ type: 3,\n+ id: number,\n+|};\nexport type ClientSocketMessage =\n| InitialClientSocketMessage\n| ResponsesClientSocketMessage\n- | ActivityUpdatesClientSocketMessage;\n+ | ActivityUpdatesClientSocketMessage\n+ | PingClientSocketMessage;\n// The types of messages that the server sends across the socket\nexport const serverSocketMessageTypes = Object.freeze({\n@@ -75,6 +82,7 @@ export const serverSocketMessageTypes = Object.freeze({\nERROR: 2,\nAUTH_ERROR: 3,\nACTIVITY_UPDATE_RESPONSE: 4,\n+ PONG: 5,\n});\nexport type ServerSocketMessageType = $Values<typeof serverSocketMessageTypes>;\nexport function assertServerSocketMessageType(\n@@ -85,7 +93,8 @@ export function assertServerSocketMessageType(\nourServerSocketMessageType === 1 ||\nourServerSocketMessageType === 2 ||\nourServerSocketMessageType === 3 ||\n- ourServerSocketMessageType === 4,\n+ ourServerSocketMessageType === 4 ||\n+ ourServerSocketMessageType === 5,\n\"number is not ServerSocketMessageType enum\",\n);\nreturn ourServerSocketMessageType;\n@@ -159,12 +168,17 @@ export type ActivityUpdateResponseServerSocketMessage = {|\nresponseTo: number,\npayload: UpdateActivityResult,\n|};\n+export type PongServerSocketMessage = {|\n+ type: 5,\n+ responseTo: number,\n+|};\nexport type ServerSocketMessage =\n| StateSyncServerSocketMessage\n| RequestsServerSocketMessage\n| ErrorServerSocketMessage\n| AuthErrorServerSocketMessage\n- | ActivityUpdateResponseServerSocketMessage;\n+ | ActivityUpdateResponseServerSocketMessage\n+ | PongServerSocketMessage;\ntype BaseInflightRequest<Response: ServerSocketMessage> = {|\nexpectedResponseType: $PropertyType<Response, 'type'>,\n" }, { "change_type": "MODIFY", "old_path": "server/src/socket.js", "new_path": "server/src/socket.js", "diff": "@@ -11,6 +11,7 @@ import {\ntype ServerSocketMessage,\ntype ErrorServerSocketMessage,\ntype AuthErrorServerSocketMessage,\n+ type PingClientSocketMessage,\nclientSocketMessageTypes,\nstateSyncPayloadTypes,\nserverSocketMessageTypes,\n@@ -109,6 +110,13 @@ const clientSocketMessageInputValidator = t.union([\nactivityUpdates: activityUpdatesInputValidator,\n}),\n}),\n+ tShape({\n+ type: t.irreducible(\n+ 'clientSocketMessageTypes.PING',\n+ x => x === clientSocketMessageTypes.PING,\n+ ),\n+ id: t.Number,\n+ }),\n]);\ntype SendMessageFunc = (message: ServerSocketMessage) => void;\n@@ -268,6 +276,8 @@ async function handleClientSocketMessage(\nreturn await handleResponsesClientSocketMessage(viewer, message);\n} else if (message.type === clientSocketMessageTypes.ACTIVITY_UPDATES) {\nreturn await handleActivityUpdatesClientSocketMessage(viewer, message);\n+ } else if (message.type === clientSocketMessageTypes.PING) {\n+ return await handlePingClientSocketMessage(viewer, message);\n}\nreturn [];\n}\n@@ -492,6 +502,16 @@ async function handleActivityUpdatesClientSocketMessage(\n}];\n}\n+async function handlePingClientSocketMessage(\n+ viewer: Viewer,\n+ message: PingClientSocketMessage,\n+): Promise<ServerSocketMessage[]> {\n+ return [{\n+ type: serverSocketMessageTypes.PONG,\n+ responseTo: message.id,\n+ }];\n+}\n+\nexport {\nonConnection,\n};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Application-level ping/pong to detect server/client "going away" Protocol-level ping/pong can only be initiated by server, and can't be handled at application level on client.
129,187
26.10.2018 14:45:52
14,400
b1a7ea162b390198ea2d24936ad0e31f7fd588d4
Move Socket to its own folder
[ { "change_type": "RENAME", "old_path": "lib/components/socket.react.js", "new_path": "lib/socket/socket.react.js", "diff": "" }, { "change_type": "MODIFY", "old_path": "native/socket.react.js", "new_path": "native/socket.react.js", "diff": "@@ -9,7 +9,7 @@ import {\nsessionStateFuncSelector,\n} from 'lib/selectors/socket-selectors';\nimport { logInExtraInfoSelector } from 'lib/selectors/account-selectors';\n-import Socket from 'lib/components/socket.react';\n+import Socket from 'lib/socket/socket.react';\nimport {\nopenSocketSelector,\n" }, { "change_type": "MODIFY", "old_path": "web/socket.react.js", "new_path": "web/socket.react.js", "diff": "@@ -9,7 +9,7 @@ import {\nsessionStateFuncSelector,\n} from 'lib/selectors/socket-selectors';\nimport { logInExtraInfoSelector } from 'lib/selectors/account-selectors';\n-import Socket from 'lib/components/socket.react';\n+import Socket from 'lib/socket/socket.react';\nimport {\nopenSocketSelector,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Move Socket to its own folder
129,187
26.10.2018 14:49:33
14,400
6342f72f57a482c1e39cb44e36edda20bcdcc731
Move InflightRequests code to its own file
[ { "change_type": "ADD", "old_path": null, "new_path": "lib/socket/inflight-requests.js", "diff": "+// @flow\n+\n+import {\n+ type ServerSocketMessage,\n+ type RequestsServerSocketMessage,\n+ type ActivityUpdateResponseServerSocketMessage,\n+ type PongServerSocketMessage,\n+ serverSocketMessageTypes,\n+} from '../types/socket-types';\n+\n+import { ServerError } from '../utils/errors';\n+\n+type BaseInflightRequest<Response: ServerSocketMessage> = {|\n+ expectedResponseType: $PropertyType<Response, 'type'>,\n+ resolve: (response: Response) => void,\n+ reject: (error: Error) => void,\n+ messageID: number,\n+|};\n+export type InflightRequest =\n+ | BaseInflightRequest<RequestsServerSocketMessage>\n+ | BaseInflightRequest<ActivityUpdateResponseServerSocketMessage>;\n+\n+function resolveRequests(\n+ message: ServerSocketMessage,\n+ inflightRequests: $ReadOnlyArray<InflightRequest>,\n+): InflightRequest[] {\n+ const remainingInflightRequests = [];\n+ for (let inflightRequest of inflightRequests) {\n+ if (inflightRequest.messageID !== message.responseTo) {\n+ remainingInflightRequests.push(inflightRequest);\n+ continue;\n+ }\n+ if (message.type === serverSocketMessageTypes.ERROR) {\n+ const error = message.payload\n+ ? new ServerError(message.message, message.payload)\n+ : new ServerError(message.message);\n+ inflightRequest.reject(error);\n+ } else if (\n+ message.type === serverSocketMessageTypes.REQUESTS &&\n+ inflightRequest.expectedResponseType === serverSocketMessageTypes.REQUESTS\n+ ) {\n+ inflightRequest.resolve(message);\n+ } else if (\n+ message.type === serverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE &&\n+ inflightRequest.expectedResponseType ===\n+ serverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE\n+ ) {\n+ inflightRequest.resolve(message);\n+ } else {\n+ remainingInflightRequests.push(inflightRequest);\n+ }\n+ }\n+ return remainingInflightRequests;\n+}\n+\n+export {\n+ resolveRequests,\n+};\n" }, { "change_type": "MODIFY", "old_path": "lib/socket/socket.react.js", "new_path": "lib/socket/socket.react.js", "diff": "@@ -29,9 +29,11 @@ import {\nactivityUpdateFailedActionType,\ntype ActivityUpdateResponseServerSocketMessage,\ntype RequestsServerSocketMessage,\n+} from '../types/socket-types';\n+import {\ntype InflightRequest,\nresolveRequests,\n-} from '../types/socket-types';\n+} from './inflight-requests';\nimport type { ActivityUpdate } from '../types/activity-types';\nimport type { Dispatch } from '../types/redux-types';\nimport type { DispatchActionPayload } from '../utils/action-utils';\n" }, { "change_type": "MODIFY", "old_path": "lib/types/socket-types.js", "new_path": "lib/types/socket-types.js", "diff": "@@ -16,7 +16,6 @@ import {\ntype UpdateActivityResult,\nactivityUpdatePropType,\n} from './activity-types';\n-import { ServerError } from '../utils/errors';\nimport invariant from 'invariant';\nimport PropTypes from 'prop-types';\n@@ -180,48 +179,6 @@ export type ServerSocketMessage =\n| ActivityUpdateResponseServerSocketMessage\n| PongServerSocketMessage;\n-type BaseInflightRequest<Response: ServerSocketMessage> = {|\n- expectedResponseType: $PropertyType<Response, 'type'>,\n- resolve: (response: Response) => void,\n- reject: (error: Error) => void,\n- messageID: number,\n-|};\n-export type InflightRequest =\n- | BaseInflightRequest<RequestsServerSocketMessage>\n- | BaseInflightRequest<ActivityUpdateResponseServerSocketMessage>;\n-export function resolveRequests(\n- message: ServerSocketMessage,\n- inflightRequests: $ReadOnlyArray<InflightRequest>,\n-): InflightRequest[] {\n- const remainingInflightRequests = [];\n- for (let inflightRequest of inflightRequests) {\n- if (inflightRequest.messageID !== message.responseTo) {\n- remainingInflightRequests.push(inflightRequest);\n- continue;\n- }\n- if (message.type === serverSocketMessageTypes.ERROR) {\n- const error = message.payload\n- ? new ServerError(message.message, message.payload)\n- : new ServerError(message.message);\n- inflightRequest.reject(error);\n- } else if (\n- message.type === serverSocketMessageTypes.REQUESTS &&\n- inflightRequest.expectedResponseType === serverSocketMessageTypes.REQUESTS\n- ) {\n- inflightRequest.resolve(message);\n- } else if (\n- message.type === serverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE &&\n- inflightRequest.expectedResponseType ===\n- serverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE\n- ) {\n- inflightRequest.resolve(message);\n- } else {\n- remainingInflightRequests.push(inflightRequest);\n- }\n- }\n- return remainingInflightRequests;\n-}\n-\nexport type ConnectionStatus =\n| \"connecting\"\n| \"connected\"\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Move InflightRequests code to its own file
129,187
26.10.2018 19:17:56
14,400
4919525ca23cb10060c6ca8edfd24f033d47334d
Extract InflightRequests functionality into class and handle timeouts
[ { "change_type": "MODIFY", "old_path": "lib/socket/inflight-requests.js", "new_path": "lib/socket/inflight-requests.js", "diff": "@@ -5,29 +5,109 @@ import {\ntype RequestsServerSocketMessage,\ntype ActivityUpdateResponseServerSocketMessage,\ntype PongServerSocketMessage,\n+ type ServerSocketMessageType,\nserverSocketMessageTypes,\n} from '../types/socket-types';\n-import { ServerError } from '../utils/errors';\n+import invariant from 'invariant';\n+import { ServerError, ExtendableError } from '../utils/errors';\n+import { clientRequestSocketTimeout } from '../shared/timeouts';\n+import sleep from '../utils/sleep';\n+\n+type ValidResponseMessageMap = {\n+ a: RequestsServerSocketMessage,\n+ b: ActivityUpdateResponseServerSocketMessage,\n+ c: PongServerSocketMessage,\n+};\ntype BaseInflightRequest<Response: ServerSocketMessage> = {|\nexpectedResponseType: $PropertyType<Response, 'type'>,\nresolve: (response: Response) => void,\nreject: (error: Error) => void,\nmessageID: number,\n|};\n-export type InflightRequest =\n- | BaseInflightRequest<RequestsServerSocketMessage>\n- | BaseInflightRequest<ActivityUpdateResponseServerSocketMessage>;\n-\n-function resolveRequests(\n- message: ServerSocketMessage,\n- inflightRequests: $ReadOnlyArray<InflightRequest>,\n-): InflightRequest[] {\n- const remainingInflightRequests = [];\n- for (let inflightRequest of inflightRequests) {\n+type InflightRequestMap = $ObjMap<\n+ ValidResponseMessageMap,\n+ <T>(T) => BaseInflightRequest<$Exact<T>>,\n+>;\n+\n+type ValidResponseMessage = $Values<ValidResponseMessageMap>;\n+type InflightRequest = $Values<InflightRequestMap>;\n+\n+class SocketTimeout extends ExtendableError {\n+ expectedResponseType: ServerSocketMessageType;\n+ constructor(expectedType: ServerSocketMessageType) {\n+ super(`socket timed out waiting for response type ${expectedType}`);\n+ this.expectedResponseType = expectedType;\n+ }\n+}\n+async function timeout(expectedType: ServerSocketMessageType) {\n+ await sleep(clientRequestSocketTimeout);\n+ throw new SocketTimeout(expectedType);\n+}\n+\n+class InflightRequests {\n+\n+ data: InflightRequest[] = [];\n+\n+ async fetchResponse<M: ValidResponseMessage>(\n+ messageID: number,\n+ expectedType: $PropertyType<M, 'type'>,\n+ ): Promise<M> {\n+ let inflightRequest: ?InflightRequest;\n+ const responsePromise = new Promise((resolve, reject) => {\n+ // Flow makes us do these unnecessary runtime checks...\n+ if (expectedType === serverSocketMessageTypes.REQUESTS) {\n+ inflightRequest = {\n+ expectedResponseType: serverSocketMessageTypes.REQUESTS,\n+ resolve,\n+ reject,\n+ messageID,\n+ };\n+ } else if (\n+ expectedType === serverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE\n+ ) {\n+ inflightRequest = {\n+ expectedResponseType:\n+ serverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE,\n+ resolve,\n+ reject,\n+ messageID,\n+ };\n+ } else if (expectedType === serverSocketMessageTypes.PONG) {\n+ inflightRequest = {\n+ expectedResponseType: serverSocketMessageTypes.PONG,\n+ resolve,\n+ reject,\n+ messageID,\n+ };\n+ }\n+ });\n+ invariant(\n+ inflightRequest,\n+ `${expectedType} is an invalid server response type`,\n+ );\n+ this.data.push(inflightRequest);\n+ try {\n+ const response = await Promise.race([\n+ responsePromise,\n+ timeout(expectedType),\n+ ]);\n+ this.clearRequest(inflightRequest);\n+ return response;\n+ } catch (e) {\n+ this.clearRequest(inflightRequest);\n+ throw e;\n+ }\n+ }\n+\n+ clearRequest(requestToClear: InflightRequest) {\n+ this.data = this.data.filter(request => request !== requestToClear);\n+ }\n+\n+ resolveRequestsForMessage(message: ServerSocketMessage) {\n+ for (let inflightRequest of this.data) {\nif (inflightRequest.messageID !== message.responseTo) {\n- remainingInflightRequests.push(inflightRequest);\ncontinue;\n}\nif (message.type === serverSocketMessageTypes.ERROR) {\n@@ -37,7 +117,8 @@ function resolveRequests(\ninflightRequest.reject(error);\n} else if (\nmessage.type === serverSocketMessageTypes.REQUESTS &&\n- inflightRequest.expectedResponseType === serverSocketMessageTypes.REQUESTS\n+ inflightRequest.expectedResponseType ===\n+ serverSocketMessageTypes.REQUESTS\n) {\ninflightRequest.resolve(message);\n} else if (\n@@ -46,13 +127,27 @@ function resolveRequests(\nserverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE\n) {\ninflightRequest.resolve(message);\n- } else {\n- remainingInflightRequests.push(inflightRequest);\n+ } else if (\n+ message.type === serverSocketMessageTypes.PONG &&\n+ inflightRequest.expectedResponseType === serverSocketMessageTypes.PONG\n+ ) {\n+ inflightRequest.resolve(message);\n+ }\n+ }\n+ }\n+\n+ get allRequestsResolved(): bool {\n+ for (let inflightRequest of this.data) {\n+ const { expectedResponseType } = inflightRequest;\n+ if (expectedResponseType !== serverSocketMessageTypes.PONG) {\n+ return false;\n}\n}\n- return remainingInflightRequests;\n+ return true;\n+ }\n+\n}\nexport {\n- resolveRequests,\n+ InflightRequests,\n};\n" }, { "change_type": "MODIFY", "old_path": "lib/socket/socket.react.js", "new_path": "lib/socket/socket.react.js", "diff": "@@ -15,6 +15,7 @@ import {\n} from '../types/session-types';\nimport {\nclientSocketMessageTypes,\n+ type ServerSocketMessageType,\ntype ClientSocketMessage,\nserverSocketMessageTypes,\ntype ServerSocketMessage,\n@@ -29,11 +30,9 @@ import {\nactivityUpdateFailedActionType,\ntype ActivityUpdateResponseServerSocketMessage,\ntype RequestsServerSocketMessage,\n+ type PongServerSocketMessage,\n} from '../types/socket-types';\n-import {\n- type InflightRequest,\n- resolveRequests,\n-} from './inflight-requests';\n+import { InflightRequests } from './inflight-requests';\nimport type { ActivityUpdate } from '../types/activity-types';\nimport type { Dispatch } from '../types/redux-types';\nimport type { DispatchActionPayload } from '../utils/action-utils';\n@@ -93,7 +92,7 @@ class Socket extends React.PureComponent<Props> {\n};\nsocket: ?WebSocket;\nnextClientMessageID = 0;\n- inflightRequests: InflightRequest[] = [];\n+ inflightRequests: InflightRequests = new InflightRequests();\npingTimeoutID: ?TimeoutID\ninitialPlatformDetailsSent = false;\nreopenConnectionAfterClosing = false;\n@@ -116,7 +115,7 @@ class Socket extends React.PureComponent<Props> {\n}\nif (this.socket.readyState < 2) {\nthis.socket.close();\n- console.warn(`this.socket seems open, but Redux thinks it's ${status}`);\n+ console.log(`this.socket seems open, but Redux thinks it's ${status}`);\n}\n}\nthis.props.dispatchActionPayload(\n@@ -136,7 +135,7 @@ class Socket extends React.PureComponent<Props> {\n}\n};\nthis.socket = socket;\n- this.inflightRequests = [];\n+ this.inflightRequests = new InflightRequests();\n}\nmarkSocketInitialized() {\n@@ -188,7 +187,7 @@ class Socket extends React.PureComponent<Props> {\n}\nfinishClosingSocket() {\n- if (this.inflightRequests.length > 0) {\n+ if (!this.inflightRequests.allRequestsResolved) {\nreturn;\n}\nthis.props.dispatchActionPayload(\n@@ -309,13 +308,13 @@ class Socket extends React.PureComponent<Props> {\nmessageFromEvent(event: MessageEvent): ?ServerSocketMessage {\nif (typeof event.data !== \"string\") {\n- console.warn('socket received a non-string message');\n+ console.log('socket received a non-string message');\nreturn null;\n}\ntry {\nreturn JSON.parse(event.data);\n} catch (e) {\n- console.warn(e);\n+ console.log(e);\nreturn null;\n}\n}\n@@ -329,10 +328,7 @@ class Socket extends React.PureComponent<Props> {\n// so we can reset the ping timeout.\nthis.resetPing();\n- this.inflightRequests = resolveRequests(\n- message,\n- this.inflightRequests,\n- );\n+ this.inflightRequests.resolveRequestsForMessage(message);\nconst { status } = this.props.connection;\nif (status === \"disconnecting\" || status === \"forcedDisconnecting\") {\nthis.finishClosingSocket();\n@@ -372,9 +368,9 @@ class Socket extends React.PureComponent<Props> {\n} else if (message.type === serverSocketMessageTypes.ERROR) {\nconst { message: errorMessage, payload } = message;\nif (payload) {\n- console.warn(`socket sent error ${errorMessage} with payload`, payload);\n+ console.log(`socket sent error ${errorMessage} with payload`, payload);\n} else {\n- console.warn(`socket sent error ${errorMessage}`);\n+ console.log(`socket sent error ${errorMessage}`);\n}\n} else if (message.type === serverSocketMessageTypes.AUTH_ERROR) {\nconst { sessionChange } = message;\n@@ -435,13 +431,9 @@ class Socket extends React.PureComponent<Props> {\n}\nif (nonActivityClientResponses.length > 0) {\n- const clientResponsesPromise = new Promise(\n- (resolve, reject) => this.inflightRequests.push({\n- expectedResponseType: serverSocketMessageTypes.REQUESTS,\n- resolve,\n- reject,\n+ const clientResponsesPromise = this.inflightRequests.fetchResponse(\nmessageID,\n- }),\n+ serverSocketMessageTypes.REQUESTS,\n);\nthis.handleQueuedClientResponses(\nclientResponsesPromise,\n@@ -456,14 +448,9 @@ class Socket extends React.PureComponent<Props> {\ntype: serverRequestTypes.INITIAL_ACTIVITY_UPDATES,\nactivityUpdates: queuedActivityUpdates,\n});\n- const activityUpdatePromise = new Promise(\n- (resolve, reject) => this.inflightRequests.push({\n- expectedResponseType:\n- serverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE,\n- resolve,\n- reject,\n+ const activityUpdatePromise = this.inflightRequests.fetchResponse(\nmessageID,\n- }),\n+ serverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE,\n);\nthis.handleActivityUpdates(activityUpdatePromise, queuedActivityUpdates);\n}\n@@ -501,20 +488,25 @@ class Socket extends React.PureComponent<Props> {\n);\n}\n- sendPing() {\n+ async sendPing() {\nif (this.props.connection.status !== \"connected\") {\n// This generally shouldn't happen because anything that changes the\n// connection status should call stopPing(), but it's good to make sure\nreturn;\n}\nconst messageID = this.nextClientMessageID++;\n- // We don't add the request to this.inflightRequests because we don't need\n- // the socket to wait for the response before closing, and we have nothing\n- // that needs to happen after the response arrives\nthis.sendMessage({\ntype: clientSocketMessageTypes.PING,\nid: messageID,\n});\n+ try {\n+ await this.inflightRequests.fetchResponse(\n+ messageID,\n+ serverSocketMessageTypes.PONG,\n+ );\n+ } catch (e) {\n+ console.log(e);\n+ }\n}\nsendAndHandleQueuedClientResponses(\n@@ -531,13 +523,9 @@ class Socket extends React.PureComponent<Props> {\nclientResponses: $ReadOnlyArray<ClientResponse>,\n): Promise<RequestsServerSocketMessage> {\nconst messageID = this.nextClientMessageID++;\n- const promise = new Promise(\n- (resolve, reject) => this.inflightRequests.push({\n- expectedResponseType: serverSocketMessageTypes.REQUESTS,\n- resolve,\n- reject,\n+ const promise = this.inflightRequests.fetchResponse(\nmessageID,\n- }),\n+ serverSocketMessageTypes.REQUESTS,\n);\nthis.sendMessage({\ntype: clientSocketMessageTypes.RESPONSES,\n@@ -560,7 +548,7 @@ class Socket extends React.PureComponent<Props> {\n);\n} catch (e) {\nif (!(e instanceof ServerError)) {\n- console.warn(e);\n+ console.log(e);\n}\nif (\n!(e instanceof ServerError) ||\n@@ -601,7 +589,7 @@ class Socket extends React.PureComponent<Props> {\nconst response = await promise;\n} catch (e) {\nif (!(e instanceof ServerError)) {\n- console.warn(e);\n+ console.log(e);\n}\nif (\ne instanceof ServerError &&\n@@ -642,14 +630,9 @@ class Socket extends React.PureComponent<Props> {\nactivityUpdates: $ReadOnlyArray<ActivityUpdate>\n): Promise<ActivityUpdateResponseServerSocketMessage> {\nconst messageID = this.nextClientMessageID++;\n- const promise = new Promise(\n- (resolve, reject) => this.inflightRequests.push({\n- expectedResponseType:\n- serverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE,\n- resolve,\n- reject,\n+ const promise = this.inflightRequests.fetchResponse(\nmessageID,\n- }),\n+ serverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE,\n);\nthis.sendMessage({\ntype: clientSocketMessageTypes.ACTIVITY_UPDATES,\n@@ -672,7 +655,7 @@ class Socket extends React.PureComponent<Props> {\n);\n} catch (e) {\nif (!(e instanceof ServerError)) {\n- console.warn(e);\n+ console.log(e);\n}\nif (\n!(e instanceof ServerError) ||\n" }, { "change_type": "MODIFY", "old_path": "lib/utils/errors.js", "new_path": "lib/utils/errors.js", "diff": "@@ -46,6 +46,7 @@ class FetchTimeout extends ExtendableError {\n}\nexport {\n+ ExtendableError,\nServerError,\nFetchTimeout,\n};\n" }, { "change_type": "MODIFY", "old_path": "server/package.json", "new_path": "server/package.json", "diff": "\"babel-plugin-transform-object-rest-spread\": \"^6.26.0\",\n\"babel-preset-react\": \"^6.24.1\",\n\"concurrently\": \"^3.5.1\",\n- \"flow-bin\": \"^0.75.0\",\n+ \"flow-bin\": \"^0.78.0\",\n\"flow-typed\": \"^2.2.3\",\n\"nodemon\": \"^1.14.3\"\n},\n" }, { "change_type": "MODIFY", "old_path": "web/package.json", "new_path": "web/package.json", "diff": "\"concurrently\": \"^3.5.1\",\n\"css-loader\": \"^0.28.4\",\n\"extract-text-webpack-plugin\": \"^2.1.2\",\n- \"flow-bin\": \"^0.75.0\",\n+ \"flow-bin\": \"^0.78.0\",\n\"style-loader\": \"^0.20.3\",\n\"uglifyjs-webpack-plugin\": \"^0.4.6\",\n\"url-loader\": \"^1.0.1\",\n" }, { "change_type": "MODIFY", "old_path": "yarn.lock", "new_path": "yarn.lock", "diff": "@@ -4618,11 +4618,6 @@ flatten@^1.0.2:\nresolved \"https://registry.yarnpkg.com/flatten/-/flatten-1.0.2.tgz#dae46a9d78fbe25292258cc1e780a41d95c03782\"\nintegrity sha1-2uRqnXj74lKSJYzB54CkHZXAN4I=\n-flow-bin@^0.75.0:\n- version \"0.75.0\"\n- resolved \"https://registry.yarnpkg.com/flow-bin/-/flow-bin-0.75.0.tgz#b96d1ee99d3b446a3226be66b4013224ce9df260\"\n- integrity sha1-uW0e6Z07RGoyJr5mtAEyJM6d8mA=\n-\nflow-bin@^0.78.0:\nversion \"0.78.0\"\nresolved \"https://registry.yarnpkg.com/flow-bin/-/flow-bin-0.78.0.tgz#df9fe7f9c9a2dfaff39083949fe2d831b41627b7\"\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Extract InflightRequests functionality into class and handle timeouts
129,187
27.10.2018 12:40:50
14,400
81ca8b56192fb27931862847bdb2a4e2d822c92f
Trigger reject of all inflight requests on any request timeout
[ { "change_type": "MODIFY", "old_path": "lib/socket/inflight-requests.js", "new_path": "lib/socket/inflight-requests.js", "diff": "@@ -49,6 +49,11 @@ async function timeout(expectedType: ServerSocketMessageType) {\nclass InflightRequests {\ndata: InflightRequest[] = [];\n+ timeoutCallback: () => void;\n+\n+ constructor(timeoutCallback: () => void) {\n+ this.timeoutCallback = timeoutCallback;\n+ }\nasync fetchResponse<M: ValidResponseMessage>(\nmessageID: number,\n@@ -97,6 +102,10 @@ class InflightRequests {\nreturn response;\n} catch (e) {\nthis.clearRequest(inflightRequest);\n+ if (e instanceof SocketTimeout) {\n+ this.rejectAll(new Error(\"socket closed due to timeout\"));\n+ this.timeoutCallback();\n+ }\nthrow e;\n}\n}\n@@ -136,6 +145,13 @@ class InflightRequests {\n}\n}\n+ rejectAll(error: Error) {\n+ for (let inflightRequest of this.data) {\n+ const { reject } = inflightRequest;\n+ reject(error);\n+ }\n+ }\n+\nget allRequestsResolved(): bool {\nfor (let inflightRequest of this.data) {\nconst { expectedResponseType } = inflightRequest;\n" }, { "change_type": "MODIFY", "old_path": "lib/socket/socket.react.js", "new_path": "lib/socket/socket.react.js", "diff": "@@ -92,7 +92,7 @@ class Socket extends React.PureComponent<Props> {\n};\nsocket: ?WebSocket;\nnextClientMessageID = 0;\n- inflightRequests: InflightRequests = new InflightRequests();\n+ inflightRequests: ?InflightRequests;\npingTimeoutID: ?TimeoutID\ninitialPlatformDetailsSent = false;\nreopenConnectionAfterClosing = false;\n@@ -135,7 +135,13 @@ class Socket extends React.PureComponent<Props> {\n}\n};\nthis.socket = socket;\n- this.inflightRequests = new InflightRequests();\n+ this.inflightRequests = new InflightRequests(\n+ () => {\n+ if (this.socket === socket) {\n+ this.handleTimeout();\n+ }\n+ },\n+ );\n}\nmarkSocketInitialized() {\n@@ -187,7 +193,7 @@ class Socket extends React.PureComponent<Props> {\n}\nfinishClosingSocket() {\n- if (!this.inflightRequests.allRequestsResolved) {\n+ if (this.inflightRequests && !this.inflightRequests.allRequestsResolved) {\nreturn;\n}\nthis.props.dispatchActionPayload(\n@@ -198,10 +204,8 @@ class Socket extends React.PureComponent<Props> {\n// If it's not closing already, close it\nthis.socket.close();\n}\n- if (this.pingTimeoutID) {\n- clearTimeout(this.pingTimeoutID);\n- this.pingTimeoutID = null;\n- }\n+ this.stopPing();\n+ this.inflightRequests = null;\nif (this.reopenConnectionAfterClosing) {\nthis.reopenConnectionAfterClosing = false;\nif (this.props.active) {\n@@ -328,6 +332,7 @@ class Socket extends React.PureComponent<Props> {\n// so we can reset the ping timeout.\nthis.resetPing();\n+ invariant(this.inflightRequests, \"inflightRequests should exist\");\nthis.inflightRequests.resolveRequestsForMessage(message);\nconst { status } = this.props.connection;\nif (status === \"disconnecting\" || status === \"forcedDisconnecting\") {\n@@ -408,6 +413,10 @@ class Socket extends React.PureComponent<Props> {\n) {\nregisterActiveWebSocket(null);\n}\n+ if (this.inflightRequests) {\n+ this.inflightRequests.rejectAll(new Error(\"socket closed\"));\n+ this.inflightRequests = null;\n+ }\nif (status !== \"disconnected\") {\nthis.props.dispatchActionPayload(\nupdateConnectionStatusActionType,\n@@ -418,6 +427,31 @@ class Socket extends React.PureComponent<Props> {\nthis.stopPing();\n}\n+ handleTimeout() {\n+ registerActiveWebSocket(null);\n+ this.inflightRequests = null;\n+ const { status } = this.props.connection;\n+ if (this.socket && this.socket.readyState < 2) {\n+ if (status !== \"disconnecting\") {\n+ this.props.dispatchActionPayload(\n+ updateConnectionStatusActionType,\n+ { status: \"disconnecting\" },\n+ );\n+ }\n+ // We just call close, onClose will handle the rest\n+ this.socket.close();\n+ } else {\n+ if (status !== \"disconnected\") {\n+ this.props.dispatchActionPayload(\n+ updateConnectionStatusActionType,\n+ { status: \"disconnected\" },\n+ );\n+ }\n+ this.socket = null;\n+ this.stopPing();\n+ }\n+ }\n+\nsendInitialMessage = () => {\nconst messageID = this.nextClientMessageID++;\n@@ -431,6 +465,7 @@ class Socket extends React.PureComponent<Props> {\n}\nif (nonActivityClientResponses.length > 0) {\n+ invariant(this.inflightRequests, \"inflightRequests should exist\");\nconst clientResponsesPromise = this.inflightRequests.fetchResponse(\nmessageID,\nserverSocketMessageTypes.REQUESTS,\n@@ -448,6 +483,7 @@ class Socket extends React.PureComponent<Props> {\ntype: serverRequestTypes.INITIAL_ACTIVITY_UPDATES,\nactivityUpdates: queuedActivityUpdates,\n});\n+ invariant(this.inflightRequests, \"inflightRequests should exist\");\nconst activityUpdatePromise = this.inflightRequests.fetchResponse(\nmessageID,\nserverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE,\n@@ -472,6 +508,7 @@ class Socket extends React.PureComponent<Props> {\nstopPing() {\nif (this.pingTimeoutID) {\nclearTimeout(this.pingTimeoutID);\n+ this.pingTimeoutID = null;\n}\n}\n@@ -500,6 +537,7 @@ class Socket extends React.PureComponent<Props> {\nid: messageID,\n});\ntry {\n+ invariant(this.inflightRequests, \"inflightRequests should exist\");\nawait this.inflightRequests.fetchResponse(\nmessageID,\nserverSocketMessageTypes.PONG,\n@@ -523,6 +561,7 @@ class Socket extends React.PureComponent<Props> {\nclientResponses: $ReadOnlyArray<ClientResponse>,\n): Promise<RequestsServerSocketMessage> {\nconst messageID = this.nextClientMessageID++;\n+ invariant(this.inflightRequests, \"inflightRequests should exist\");\nconst promise = this.inflightRequests.fetchResponse(\nmessageID,\nserverSocketMessageTypes.REQUESTS,\n@@ -630,6 +669,7 @@ class Socket extends React.PureComponent<Props> {\nactivityUpdates: $ReadOnlyArray<ActivityUpdate>\n): Promise<ActivityUpdateResponseServerSocketMessage> {\nconst messageID = this.nextClientMessageID++;\n+ invariant(this.inflightRequests, \"inflightRequests should exist\");\nconst promise = this.inflightRequests.fetchResponse(\nmessageID,\nserverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Trigger reject of all inflight requests on any request timeout
129,187
29.10.2018 11:17:57
14,400
a09d423972f8b5aae830a26e24183855427d39b2
[server] Move socket code to new Socket class
[ { "change_type": "MODIFY", "old_path": "server/src/socket.js", "new_path": "server/src/socket.js", "diff": "@@ -119,33 +119,47 @@ const clientSocketMessageInputValidator = t.union([\n}),\n]);\n-type SendMessageFunc = (message: ServerSocketMessage) => void;\n-\nfunction onConnection(ws: WebSocket, req: $Request) {\nassertSecureRequest(req);\n- let viewer;\n- const sendMessage = (message: ServerSocketMessage) => {\n- ws.send(JSON.stringify(message));\n- };\n- ws.on('message', async messageString => {\n+ new Socket(ws, req);\n+}\n+\n+class Socket {\n+\n+ ws: WebSocket;\n+ httpRequest: $Request;\n+ viewer: ?Viewer;\n+\n+ constructor(ws: WebSocket, httpRequest: $Request) {\n+ this.ws = ws;\n+ this.httpRequest = httpRequest;\n+ ws.on('message', this.onMessage);\n+ ws.on('close', this.onClose);\n+ }\n+\n+ onMessage = async (messageString: string) => {\nlet clientSocketMessage: ?ClientSocketMessage;\ntry {\nconst message = JSON.parse(messageString);\ncheckInputValidator(clientSocketMessageInputValidator, message);\nclientSocketMessage = message;\nif (clientSocketMessage.type === clientSocketMessageTypes.INITIAL) {\n- if (viewer) {\n+ if (this.viewer) {\n// This indicates that the user sent multiple INITIAL messages.\nthrow new ServerError('socket_already_initialized');\n}\n- viewer = await fetchViewerForSocket(req, clientSocketMessage);\n- if (!viewer) {\n+ this.viewer = await fetchViewerForSocket(\n+ this.httpRequest,\n+ clientSocketMessage,\n+ );\n+ if (!this.viewer) {\n// This indicates that the cookie was invalid, but the client is using\n// cookieSources.HEADER and thus can't accept a new cookie over\n// WebSockets. See comment under catch block for socket_deauthorized.\nthrow new ServerError('socket_deauthorized');\n}\n}\n+ const { viewer } = this;\nif (!viewer) {\n// This indicates a non-INITIAL message was sent by the client before\n// the INITIAL message.\n@@ -165,8 +179,7 @@ function onConnection(ws: WebSocket, req: $Request) {\nclientSocketMessageInputValidator,\nclientSocketMessage,\n);\n- const serverResponses = await handleClientSocketMessage(\n- viewer,\n+ const serverResponses = await this.handleClientSocketMessage(\nclientSocketMessage,\n);\nif (viewer.sessionChanged) {\n@@ -177,7 +190,7 @@ function onConnection(ws: WebSocket, req: $Request) {\n}\nhandleAsyncPromise(extendCookieLifespan(viewer.cookieID));\nfor (let response of serverResponses) {\n- sendMessage(response);\n+ this.sendMessage(response);\n}\n} catch (error) {\nconsole.warn(error);\n@@ -190,7 +203,7 @@ function onConnection(ws: WebSocket, req: $Request) {\nif (responseTo !== null) {\nerrorMessage.responseTo = responseTo;\n}\n- sendMessage(errorMessage);\n+ this.sendMessage(errorMessage);\nreturn;\n}\ninvariant(clientSocketMessage, \"should be set\");\n@@ -201,23 +214,24 @@ function onConnection(ws: WebSocket, req: $Request) {\nresponseTo,\nmessage: error.message,\n}\n- if (viewer) {\n+ if (this.viewer) {\n// viewer should only be falsey for cookieSources.HEADER (web)\n// clients. Usually if the cookie is invalid we construct a new\n// anonymous Viewer with a new cookie, and then pass the cookie down\n// in the error. But we can't pass HTTP cookies in WebSocket messages.\nauthErrorMessage.sessionChange = {\n- cookie: viewer.cookiePairString,\n+ cookie: this.viewer.cookiePairString,\ncurrentUserInfo: {\n- id: viewer.cookieID,\n+ id: this.viewer.cookieID,\nanonymous: true,\n},\n};\n}\n- sendMessage(authErrorMessage);\n- ws.close(4100, error.message);\n+ this.sendMessage(authErrorMessage);\n+ this.ws.close(4100, error.message);\nreturn;\n} else if (error.message === \"client_version_unsupported\") {\n+ const { viewer } = this;\ninvariant(viewer, \"should be set\");\nconst promises = {};\npromises.deleteCookie = deleteCookie(viewer.cookieID);\n@@ -243,49 +257,54 @@ function onConnection(ws: WebSocket, req: $Request) {\n},\n};\n}\n- sendMessage(authErrorMessage);\n- ws.close(4101, error.message);\n+ this.sendMessage(authErrorMessage);\n+ this.ws.close(4101, error.message);\nreturn;\n}\n- sendMessage({\n+ this.sendMessage({\ntype: serverSocketMessageTypes.ERROR,\nresponseTo,\nmessage: error.message,\n});\nif (error.message === \"not_logged_in\") {\n- ws.close(4101, error.message);\n+ this.ws.close(4101, error.message);\n} else if (error.message === \"session_mutated_from_socket\") {\n- ws.close(4102, error.message);\n+ this.ws.close(4102, error.message);\n}\n}\n- });\n- ws.on('close', async () => {\n- if (viewer && viewer.hasSessionInfo) {\n- await deleteForViewerSession(viewer);\n}\n- });\n+\n+ onClose = async () => {\n+ if (this.viewer && this.viewer.hasSessionInfo) {\n+ await deleteForViewerSession(this.viewer);\n+ }\n}\n-async function handleClientSocketMessage(\n- viewer: Viewer,\n+ sendMessage(message: ServerSocketMessage) {\n+ this.ws.send(JSON.stringify(message));\n+ }\n+\n+ async handleClientSocketMessage(\nmessage: ClientSocketMessage,\n): Promise<ServerSocketMessage[]> {\nif (message.type === clientSocketMessageTypes.INITIAL) {\n- return await handleInitialClientSocketMessage(viewer, message);\n+ return await this.handleInitialClientSocketMessage(message);\n} else if (message.type === clientSocketMessageTypes.RESPONSES) {\n- return await handleResponsesClientSocketMessage(viewer, message);\n+ return await this.handleResponsesClientSocketMessage(message);\n} else if (message.type === clientSocketMessageTypes.ACTIVITY_UPDATES) {\n- return await handleActivityUpdatesClientSocketMessage(viewer, message);\n+ return await this.handleActivityUpdatesClientSocketMessage(message);\n} else if (message.type === clientSocketMessageTypes.PING) {\n- return await handlePingClientSocketMessage(viewer, message);\n+ return await this.handlePingClientSocketMessage(message);\n}\nreturn [];\n}\n-async function handleInitialClientSocketMessage(\n- viewer: Viewer,\n+ async handleInitialClientSocketMessage(\nmessage: InitialClientSocketMessage,\n): Promise<ServerSocketMessage[]> {\n+ const { viewer } = this;\n+ invariant(viewer, \"should be set\");\n+\nconst responses = [];\nconst { sessionState, clientResponses } = message.payload;\n@@ -453,10 +472,12 @@ async function handleInitialClientSocketMessage(\nreturn responses;\n}\n-async function handleResponsesClientSocketMessage(\n- viewer: Viewer,\n+ async handleResponsesClientSocketMessage(\nmessage: ResponsesClientSocketMessage,\n): Promise<ServerSocketMessage[]> {\n+ const { viewer } = this;\n+ invariant(viewer, \"should be set\");\n+\nconst { clientResponses } = message.payload;\nconst { stateCheckStatus } = await processClientResponses(\nviewer,\n@@ -487,10 +508,11 @@ async function handleResponsesClientSocketMessage(\n}];\n}\n-async function handleActivityUpdatesClientSocketMessage(\n- viewer: Viewer,\n+ async handleActivityUpdatesClientSocketMessage(\nmessage: ActivityUpdatesClientSocketMessage,\n): Promise<ServerSocketMessage[]> {\n+ const { viewer } = this;\n+ invariant(viewer, \"should be set\");\nconst result = await activityUpdater(\nviewer,\n{ updates: message.payload.activityUpdates },\n@@ -502,8 +524,7 @@ async function handleActivityUpdatesClientSocketMessage(\n}];\n}\n-async function handlePingClientSocketMessage(\n- viewer: Viewer,\n+ async handlePingClientSocketMessage(\nmessage: PingClientSocketMessage,\n): Promise<ServerSocketMessage[]> {\nreturn [{\n@@ -512,6 +533,8 @@ async function handlePingClientSocketMessage(\n}];\n}\n+}\n+\nexport {\nonConnection,\n};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Move socket code to new Socket class
129,187
29.10.2018 11:35:09
14,400
04f350e1a5cff2c311d44aeadbabb7d425244204
[server] Rename activity deleters
[ { "change_type": "MODIFY", "old_path": "server/src/cron.js", "new_path": "server/src/cron.js", "diff": "@@ -12,7 +12,7 @@ import { deleteOrphanedEntries } from './deleters/entry-deleters';\nimport { deleteOrphanedRevisions } from './deleters/revision-deleters';\nimport { deleteOrphanedRoles } from './deleters/role-deleters';\nimport { deleteOrphanedMessages } from './deleters/message-deleters';\n-import { deleteOrphanedFocused } from './deleters/activity-deleters';\n+import { deleteOrphanedActivity } from './deleters/activity-deleters';\nimport { deleteOrphanedNotifs } from './deleters/notif-deleters';\nimport { deleteExpiredUpdates } from './deleters/update-deleters';\nimport {\n@@ -40,7 +40,7 @@ if (cluster.isMaster) {\nawait deleteOrphanedRevisions();\nawait deleteOrphanedRoles();\nawait deleteOrphanedMessages();\n- await deleteOrphanedFocused();\n+ await deleteOrphanedActivity();\nawait deleteOrphanedNotifs();\nawait deleteOrphanedSessions();\nawait deleteOldWebSessions();\n" }, { "change_type": "MODIFY", "old_path": "server/src/deleters/activity-deleters.js", "new_path": "server/src/deleters/activity-deleters.js", "diff": "@@ -5,7 +5,7 @@ import type { Viewer } from '../session/viewer';\nimport { dbQuery, SQL } from '../database';\nimport { earliestFocusedTimeConsideredExpired } from '../shared/focused-times';\n-async function deleteForViewerSession(\n+async function deleteActivityForViewerSession(\nviewer: Viewer,\nbeforeTime?: number,\n): Promise<void> {\n@@ -19,7 +19,7 @@ async function deleteForViewerSession(\nawait dbQuery(query);\n}\n-async function deleteOrphanedFocused(): Promise<void> {\n+async function deleteOrphanedActivity(): Promise<void> {\nconst time = earliestFocusedTimeConsideredExpired();\nawait dbQuery(SQL`\nDELETE f\n@@ -32,6 +32,6 @@ async function deleteOrphanedFocused(): Promise<void> {\n}\nexport {\n- deleteForViewerSession,\n- deleteOrphanedFocused,\n+ deleteActivityForViewerSession,\n+ deleteOrphanedActivity,\n};\n" }, { "change_type": "MODIFY", "old_path": "server/src/socket.js", "new_path": "server/src/socket.js", "diff": "@@ -64,7 +64,7 @@ import { commitSessionUpdate } from './updaters/session-updaters';\nimport { handleAsyncPromise } from './responders/handlers';\nimport { deleteCookie } from './deleters/cookie-deleters';\nimport { createNewAnonymousCookie } from './session/cookies';\n-import { deleteForViewerSession } from './deleters/activity-deleters';\n+import { deleteActivityForViewerSession } from './deleters/activity-deleters';\nimport {\nactivityUpdatesInputValidator,\n} from './responders/activity-responders';\n@@ -276,7 +276,7 @@ class Socket {\nonClose = async () => {\nif (this.viewer && this.viewer.hasSessionInfo) {\n- await deleteForViewerSession(this.viewer);\n+ await deleteActivityForViewerSession(this.viewer);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/activity-updaters.js", "new_path": "server/src/updaters/activity-updaters.js", "diff": "@@ -18,7 +18,7 @@ import { dbQuery, SQL, mergeOrConditions } from '../database';\nimport { verifyThreadIDs } from '../fetchers/thread-fetchers';\nimport { rescindPushNotifs } from '../push/rescind';\nimport { createUpdates } from '../creators/update-creator';\n-import { deleteForViewerSession } from '../deleters/activity-deleters';\n+import { deleteActivityForViewerSession } from '../deleters/activity-deleters';\nimport { earliestFocusedTimeConsideredCurrent } from '../shared/focused-times';\nasync function activityUpdater(\n@@ -139,7 +139,7 @@ async function updateFocusedRows(\nON DUPLICATE KEY UPDATE time = VALUES(time)\n`);\n}\n- await deleteForViewerSession(viewer, time);\n+ await deleteActivityForViewerSession(viewer, time);\n}\n// To protect against a possible race condition, we reset the thread to unread\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Rename activity deleters
129,187
29.10.2018 11:37:22
14,400
c6aecc3861b82ddfaf9bf5fb423043a7456ae0bf
[server] Keep updating activity time while socket is active
[ { "change_type": "MODIFY", "old_path": "server/src/shared/focused-times.js", "new_path": "server/src/shared/focused-times.js", "diff": "@@ -20,6 +20,7 @@ function earliestFocusedTimeConsideredExpired() {\n}\nexport {\n+ focusedTableRefreshFrequency,\nearliestFocusedTimeConsideredCurrent,\nearliestFocusedTimeConsideredExpired,\n};\n" }, { "change_type": "MODIFY", "old_path": "server/src/socket.js", "new_path": "server/src/socket.js", "diff": "@@ -68,6 +68,7 @@ import { deleteActivityForViewerSession } from './deleters/activity-deleters';\nimport {\nactivityUpdatesInputValidator,\n} from './responders/activity-responders';\n+import { focusedTableRefreshFrequency } from './shared/focused-times';\nconst clientSocketMessageInputValidator = t.union([\ntShape({\n@@ -129,6 +130,7 @@ class Socket {\nws: WebSocket;\nhttpRequest: $Request;\nviewer: ?Viewer;\n+ updateActivityTimeIntervalID: ?IntervalID;\nconstructor(ws: WebSocket, httpRequest: $Request) {\nthis.ws = ws;\n@@ -192,6 +194,9 @@ class Socket {\nfor (let response of serverResponses) {\nthis.sendMessage(response);\n}\n+ if (clientSocketMessage.type === clientSocketMessageTypes.INITIAL) {\n+ this.onSuccessfulConnection();\n+ }\n} catch (error) {\nconsole.warn(error);\nif (!(error instanceof ServerError)) {\n@@ -275,6 +280,10 @@ class Socket {\n}\nonClose = async () => {\n+ if (this.updateActivityTimeIntervalID) {\n+ clearInterval(this.updateActivityTimeIntervalID);\n+ this.updateActivityTimeIntervalID = null;\n+ }\nif (this.viewer && this.viewer.hasSessionInfo) {\nawait deleteActivityForViewerSession(this.viewer);\n}\n@@ -533,6 +542,19 @@ class Socket {\n}];\n}\n+ onSuccessfulConnection() {\n+ this.updateActivityTimeIntervalID = setInterval(\n+ this.updateActivityTime,\n+ focusedTableRefreshFrequency,\n+ );\n+ }\n+\n+ updateActivityTime = () => {\n+ const { viewer } = this;\n+ invariant(viewer, \"should be set\");\n+ handleAsyncPromise(updateActivityTime(viewer));\n+ }\n+\n}\nexport {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Keep updating activity time while socket is active
129,187
29.10.2018 13:03:38
14,400
ec56da5b3306c4c3afc2b579459f3d08de89aa18
[server] Have server close inactive sockets
[ { "change_type": "MODIFY", "old_path": "server/src/socket.js", "new_path": "server/src/socket.js", "diff": "@@ -28,6 +28,7 @@ import { mostRecentMessageTimestamp } from 'lib/shared/message-utils';\nimport { mostRecentUpdateTimestamp } from 'lib/shared/update-utils';\nimport { promiseAll } from 'lib/utils/promises';\nimport { values } from 'lib/utils/objects';\n+import { serverRequestSocketTimeout } from 'lib/shared/timeouts';\nimport { Viewer } from './session/viewer';\nimport {\n@@ -70,6 +71,8 @@ import {\n} from './responders/activity-responders';\nimport { focusedTableRefreshFrequency } from './shared/focused-times';\n+const timeoutSeconds = serverRequestSocketTimeout / 1000;\n+\nconst clientSocketMessageInputValidator = t.union([\ntShape({\ntype: t.irreducible(\n@@ -131,17 +134,20 @@ class Socket {\nhttpRequest: $Request;\nviewer: ?Viewer;\nupdateActivityTimeIntervalID: ?IntervalID;\n+ pingTimeoutID: ?TimeoutID;\nconstructor(ws: WebSocket, httpRequest: $Request) {\nthis.ws = ws;\nthis.httpRequest = httpRequest;\nws.on('message', this.onMessage);\nws.on('close', this.onClose);\n+ this.resetTimeout();\n}\nonMessage = async (messageString: string) => {\nlet clientSocketMessage: ?ClientSocketMessage;\ntry {\n+ this.resetTimeout();\nconst message = JSON.parse(messageString);\ncheckInputValidator(clientSocketMessageInputValidator, message);\nclientSocketMessage = message;\n@@ -272,9 +278,9 @@ class Socket {\nmessage: error.message,\n});\nif (error.message === \"not_logged_in\") {\n- this.ws.close(4101, error.message);\n- } else if (error.message === \"session_mutated_from_socket\") {\nthis.ws.close(4102, error.message);\n+ } else if (error.message === \"session_mutated_from_socket\") {\n+ this.ws.close(4103, error.message);\n}\n}\n}\n@@ -284,6 +290,7 @@ class Socket {\nclearInterval(this.updateActivityTimeIntervalID);\nthis.updateActivityTimeIntervalID = null;\n}\n+ this.clearTimeout();\nif (this.viewer && this.viewer.hasSessionInfo) {\nawait deleteActivityForViewerSession(this.viewer);\n}\n@@ -555,6 +562,25 @@ class Socket {\nhandleAsyncPromise(updateActivityTime(viewer));\n}\n+ clearTimeout() {\n+ if (this.pingTimeoutID) {\n+ clearTimeout(this.pingTimeoutID);\n+ this.pingTimeoutID = null;\n+ }\n+ }\n+\n+ resetTimeout() {\n+ this.clearTimeout();\n+ this.pingTimeoutID = setTimeout(this.timeout, serverRequestSocketTimeout);\n+ }\n+\n+ timeout = () => {\n+ this.ws.close(\n+ 4103,\n+ `no contact from client within ${timeoutSeconds}s span`,\n+ );\n+ }\n+\n}\nexport {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Have server close inactive sockets
129,187
29.10.2018 15:20:47
14,400
8a9e51b1b0597a741087f07d0cc2e519f90bc97e
[lib] Reconnect every 2 seconds while disconnected and active
[ { "change_type": "MODIFY", "old_path": "lib/socket/socket.react.js", "new_path": "lib/socket/socket.react.js", "diff": "@@ -41,6 +41,7 @@ import type { LogInExtraInfo } from '../types/account-types';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport invariant from 'invariant';\n+import _debounce from 'lodash/fp/debounce';\nimport { getConfig } from '../utils/config';\nimport {\n@@ -214,6 +215,10 @@ class Socket extends React.PureComponent<Props> {\n}\n}\n+ reconnect = _debounce(2000)(() => {\n+ this.openSocket();\n+ })\n+\ncomponentDidMount() {\nif (this.props.active) {\nthis.openSocket();\n@@ -242,6 +247,17 @@ class Socket extends React.PureComponent<Props> {\n}\n}\n+ const { queuedClientResponses, connection } = this.props;\n+ const { status, queuedActivityUpdates } = connection;\n+ const {\n+ queuedClientResponses: prevClientResponses,\n+ connection: prevConnection,\n+ } = prevProps;\n+ const {\n+ status: prevStatus,\n+ queuedActivityUpdates: prevActivityUpdates,\n+ } = prevConnection;\n+\nif (this.props.active && !prevProps.active) {\nthis.openSocket();\n} else if (!this.props.active && prevProps.active) {\n@@ -253,6 +269,12 @@ class Socket extends React.PureComponent<Props> {\n// This case happens when the baseURL/urlPrefix is changed\nthis.reopenConnectionAfterClosing = true;\nthis.forceCloseSocket(activityUpdates);\n+ } else if (\n+ this.props.active &&\n+ status === \"disconnected\" &&\n+ prevStatus !== \"disconnected\"\n+ ) {\n+ this.reconnect();\n}\nif (activityUpdates.length > 0) {\n@@ -262,17 +284,6 @@ class Socket extends React.PureComponent<Props> {\n);\n}\n- const { queuedClientResponses, connection } = this.props;\n- const { status, queuedActivityUpdates } = connection;\n- const {\n- queuedClientResponses: prevClientResponses,\n- connection: prevConnection,\n- } = this.props;\n- const {\n- status: prevStatus,\n- queuedActivityUpdates: prevActivityUpdates,\n- } = prevConnection;\n-\nif (status === \"connected\" && prevStatus !== \"connected\") {\nthis.sendAndHandleQueuedClientResponses(queuedClientResponses);\n} else if (\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Reconnect every 2 seconds while disconnected and active
129,187
29.10.2018 16:49:42
14,400
ebbc2e199b9b24bb561162b38449d9cf3240df01
[server] Set socket to null in finishClosingSocket This means `onClose` won't get called for it, but is necessary for the `this.reopenConnectionAfterClosing` logic to work correctly. We'll just do everything we would do in `onClose` in `finishClosingSocket` as well. Also, moved the socket code to handle `ServerRequest`s to the corresponding two async functions.
[ { "change_type": "MODIFY", "old_path": "lib/socket/socket.react.js", "new_path": "lib/socket/socket.react.js", "diff": "@@ -201,9 +201,11 @@ class Socket extends React.PureComponent<Props> {\nupdateConnectionStatusActionType,\n{ status: \"disconnected\" },\n);\n+ registerActiveWebSocket(null);\nif (this.socket && this.socket.readyState < 2) {\n// If it's not closing already, close it\nthis.socket.close();\n+ this.socket = null;\n}\nthis.stopPing();\nthis.inflightRequests = null;\n@@ -374,13 +376,6 @@ class Socket extends React.PureComponent<Props> {\n);\n}\nthis.markSocketInitialized();\n- } else if (message.type === serverSocketMessageTypes.REQUESTS) {\n- const { serverRequests } = message.payload;\n- this.processServerRequests(serverRequests);\n- const clientResponses = this.props.getClientResponses(serverRequests);\n- if (this.props.connection.status === \"connected\") {\n- this.sendAndHandleClientResponsesToServerRequests(clientResponses);\n- }\n} else if (message.type === serverSocketMessageTypes.ERROR) {\nconst { message: errorMessage, payload } = message;\nif (payload) {\n@@ -596,6 +591,8 @@ class Socket extends React.PureComponent<Props> {\nclearDeliveredClientResponsesActionType,\n{ clientResponses },\n);\n+ const { serverRequests } = response.payload;\n+ this.processServerRequests(serverRequests);\n} catch (e) {\nif (!(e instanceof ServerError)) {\nconsole.log(e);\n@@ -637,6 +634,8 @@ class Socket extends React.PureComponent<Props> {\n): Promise<void> {\ntry {\nconst response = await promise;\n+ const { serverRequests } = response.payload;\n+ this.processServerRequests(serverRequests);\n} catch (e) {\nif (!(e instanceof ServerError)) {\nconsole.log(e);\n@@ -664,6 +663,10 @@ class Socket extends React.PureComponent<Props> {\nprocessServerRequestsActionType,\n{ serverRequests },\n);\n+ const clientResponses = this.props.getClientResponses(serverRequests);\n+ if (this.props.connection.status === \"connected\") {\n+ this.sendAndHandleClientResponsesToServerRequests(clientResponses);\n+ }\n}\nsendAndHandleActivityUpdates(\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Set socket to null in finishClosingSocket This means `onClose` won't get called for it, but is necessary for the `this.reopenConnectionAfterClosing` logic to work correctly. We'll just do everything we would do in `onClose` in `finishClosingSocket` as well. Also, moved the socket code to handle `ServerRequest`s to the corresponding two async functions.
129,187
31.10.2018 18:21:55
14,400
161548ce6417e0ea923a6228b1f3644c8834b883
[lib] Narrow situations where we retry socket requests in
[ { "change_type": "MODIFY", "old_path": "lib/socket/inflight-requests.js", "new_path": "lib/socket/inflight-requests.js", "diff": "@@ -165,5 +165,6 @@ class InflightRequests {\n}\nexport {\n+ SocketTimeout,\nInflightRequests,\n};\n" }, { "change_type": "MODIFY", "old_path": "lib/socket/socket.react.js", "new_path": "lib/socket/socket.react.js", "diff": "@@ -32,7 +32,7 @@ import {\ntype RequestsServerSocketMessage,\ntype PongServerSocketMessage,\n} from '../types/socket-types';\n-import { InflightRequests } from './inflight-requests';\n+import { InflightRequests, SocketTimeout } from './inflight-requests';\nimport type { ActivityUpdate } from '../types/activity-types';\nimport type { Dispatch } from '../types/redux-types';\nimport type { DispatchActionPayload } from '../utils/action-utils';\n@@ -594,14 +594,19 @@ class Socket extends React.PureComponent<Props> {\nconst { serverRequests } = response.payload;\nthis.processServerRequests(serverRequests);\n} catch (e) {\n- if (!(e instanceof ServerError)) {\nconsole.log(e);\n- }\nif (\n- !(e instanceof ServerError) ||\n- retriesLeft === 0 ||\n+ e instanceof SocketTimeout ||\nthis.props.connection.status !== \"connected\"\n) {\n+ // This indicates that the socket will be closed. Do nothing, since when\n+ // it will reopen it will send all the queued ClientResponses again.\n+ } else if (\n+ retriesLeft === 0 ||\n+ (e instanceof ServerError && e.message !== \"unknown_error\")\n+ ) {\n+ // We're giving up on these ClientResponses, as they seem to cause the\n+ // server to error...\nthis.props.dispatchActionPayload(\nclearDeliveredClientResponsesActionType,\n{ clientResponses },\n@@ -637,14 +642,16 @@ class Socket extends React.PureComponent<Props> {\nconst { serverRequests } = response.payload;\nthis.processServerRequests(serverRequests);\n} catch (e) {\n- if (!(e instanceof ServerError)) {\nconsole.log(e);\n- }\nif (\n- e instanceof ServerError &&\n+ !(e instanceof SocketTimeout) &&\n+ (!(e instanceof ServerError) || e.message === \"unknown_error\") &&\nretriesLeft > 0 &&\nthis.props.connection.status === \"connected\"\n) {\n+ // We'll only retry if the connection is healthy and the error is either\n+ // an unknown_error ServerError or something is neither a ServerError\n+ // nor a SocketTimeout.\nconst newPromise = this.sendClientResponses(clientResponses);\nawait this.handleClientResponsesToServerRequests(\nnewPromise,\n@@ -708,14 +715,19 @@ class Socket extends React.PureComponent<Props> {\n{ activityUpdates, result: response.payload },\n);\n} catch (e) {\n- if (!(e instanceof ServerError)) {\nconsole.log(e);\n- }\nif (\n- !(e instanceof ServerError) ||\n- retriesLeft === 0 ||\n+ e instanceof SocketTimeout ||\nthis.props.connection.status !== \"connected\"\n) {\n+ // This indicates that the socket will be closed. Do nothing, since when\n+ // it will reopen it will send all the queued activity updates again.\n+ } else if (\n+ retriesLeft === 0 ||\n+ (e instanceof ServerError && e.message !== \"unknown_error\")\n+ ) {\n+ // We're giving up on these activity updates, as they seem to cause the\n+ // server to error...\nthis.props.dispatchActionPayload(\nactivityUpdateFailedActionType,\n{ activityUpdates },\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Narrow situations where we retry socket requests in
129,187
31.10.2018 18:50:10
14,400
5c91b983f016b1c60096fcdf8afae208cadb114f
[lib] Use promises and async functions for socket initialization code
[ { "change_type": "MODIFY", "old_path": "lib/socket/inflight-requests.js", "new_path": "lib/socket/inflight-requests.js", "diff": "import {\ntype ServerSocketMessage,\n+ type StateSyncServerSocketMessage,\ntype RequestsServerSocketMessage,\ntype ActivityUpdateResponseServerSocketMessage,\ntype PongServerSocketMessage,\n@@ -16,9 +17,10 @@ import { clientRequestSocketTimeout } from '../shared/timeouts';\nimport sleep from '../utils/sleep';\ntype ValidResponseMessageMap = {\n- a: RequestsServerSocketMessage,\n- b: ActivityUpdateResponseServerSocketMessage,\n- c: PongServerSocketMessage,\n+ a: StateSyncServerSocketMessage,\n+ b: RequestsServerSocketMessage,\n+ c: ActivityUpdateResponseServerSocketMessage,\n+ d: PongServerSocketMessage,\n};\ntype BaseInflightRequest<Response: ServerSocketMessage> = {|\nexpectedResponseType: $PropertyType<Response, 'type'>,\n@@ -62,7 +64,14 @@ class InflightRequests {\nlet inflightRequest: ?InflightRequest;\nconst responsePromise = new Promise((resolve, reject) => {\n// Flow makes us do these unnecessary runtime checks...\n- if (expectedType === serverSocketMessageTypes.REQUESTS) {\n+ if (expectedType === serverSocketMessageTypes.STATE_SYNC) {\n+ inflightRequest = {\n+ expectedResponseType: serverSocketMessageTypes.STATE_SYNC,\n+ resolve,\n+ reject,\n+ messageID,\n+ };\n+ } else if (expectedType === serverSocketMessageTypes.REQUESTS) {\ninflightRequest = {\nexpectedResponseType: serverSocketMessageTypes.REQUESTS,\nresolve,\n@@ -124,6 +133,12 @@ class InflightRequests {\n? new ServerError(message.message, message.payload)\n: new ServerError(message.message);\ninflightRequest.reject(error);\n+ } else if (\n+ message.type === serverSocketMessageTypes.STATE_SYNC &&\n+ inflightRequest.expectedResponseType ===\n+ serverSocketMessageTypes.STATE_SYNC\n+ ) {\n+ inflightRequest.resolve(message);\n} else if (\nmessage.type === serverSocketMessageTypes.REQUESTS &&\ninflightRequest.expectedResponseType ===\n" }, { "change_type": "MODIFY", "old_path": "lib/socket/socket.react.js", "new_path": "lib/socket/socket.react.js", "diff": "@@ -31,6 +31,7 @@ import {\ntype ActivityUpdateResponseServerSocketMessage,\ntype RequestsServerSocketMessage,\ntype PongServerSocketMessage,\n+ type StateSyncServerSocketMessage,\n} from '../types/socket-types';\nimport { InflightRequests, SocketTimeout } from './inflight-requests';\nimport type { ActivityUpdate } from '../types/activity-types';\n@@ -52,6 +53,7 @@ import {\nimport { socketAuthErrorResolutionAttempt } from '../actions/user-actions';\nimport { ServerError } from '../utils/errors';\nimport { pingFrequency } from '../shared/timeouts';\n+import { promiseAll } from '../utils/promises';\ntype Props = {|\n// Redux state\n@@ -126,7 +128,7 @@ class Socket extends React.PureComponent<Props> {\nconst socket = this.props.openSocket();\nsocket.onopen = () => {\nif (this.socket === socket) {\n- this.sendInitialMessage();\n+ this.initializeSocket();\n}\n};\nsocket.onmessage = this.receiveMessage;\n@@ -352,31 +354,7 @@ class Socket extends React.PureComponent<Props> {\nthis.finishClosingSocket();\n}\n- if (message.type === serverSocketMessageTypes.STATE_SYNC) {\n- if (message.payload.type === stateSyncPayloadTypes.FULL) {\n- const { sessionID, type, ...actionPayload } = message.payload;\n- this.props.dispatchActionPayload(\n- fullStateSyncActionType,\n- actionPayload,\n- );\n- if (sessionID !== null && sessionID !== undefined) {\n- this.props.dispatchActionPayload(\n- setNewSessionActionType,\n- {\n- sessionChange: { cookieInvalidated: false, sessionID },\n- error: null,\n- },\n- );\n- }\n- } else {\n- const { type, ...actionPayload } = message.payload;\n- this.props.dispatchActionPayload(\n- incrementalStateSyncActionType,\n- actionPayload,\n- );\n- }\n- this.markSocketInitialized();\n- } else if (message.type === serverSocketMessageTypes.ERROR) {\n+ if (message.type === serverSocketMessageTypes.ERROR) {\nconst { message: errorMessage, payload } = message;\nif (payload) {\nconsole.log(`socket sent error ${errorMessage} with payload`, payload);\n@@ -458,8 +436,11 @@ class Socket extends React.PureComponent<Props> {\n}\n}\n- sendInitialMessage = () => {\n+ async sendInitialMessage() {\n+ const { inflightRequests } = this;\n+ invariant(inflightRequests, \"inflightRequests should exist\");\nconst messageID = this.nextClientMessageID++;\n+ const promises = {};\nconst nonActivityClientResponses = [ ...this.props.queuedClientResponses ];\nif (!this.initialPlatformDetailsSent) {\n@@ -471,15 +452,10 @@ class Socket extends React.PureComponent<Props> {\n}\nif (nonActivityClientResponses.length > 0) {\n- invariant(this.inflightRequests, \"inflightRequests should exist\");\n- const clientResponsesPromise = this.inflightRequests.fetchResponse(\n+ promises.serverRequestMessage = inflightRequests.fetchResponse(\nmessageID,\nserverSocketMessageTypes.REQUESTS,\n);\n- this.handleQueuedClientResponses(\n- clientResponsesPromise,\n- nonActivityClientResponses,\n- );\n}\nconst clientResponses = [ ...nonActivityClientResponses];\n@@ -489,12 +465,10 @@ class Socket extends React.PureComponent<Props> {\ntype: serverRequestTypes.INITIAL_ACTIVITY_UPDATES,\nactivityUpdates: queuedActivityUpdates,\n});\n- invariant(this.inflightRequests, \"inflightRequests should exist\");\n- const activityUpdatePromise = this.inflightRequests.fetchResponse(\n+ promises.activityUpdateMessage = inflightRequests.fetchResponse(\nmessageID,\nserverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE,\n);\n- this.handleActivityUpdates(activityUpdatePromise, queuedActivityUpdates);\n}\nconst sessionState = this.props.sessionStateFunc();\n@@ -509,6 +483,86 @@ class Socket extends React.PureComponent<Props> {\n},\n};\nthis.sendMessage(initialMessage);\n+\n+ promises.stateSyncMessage = inflightRequests.fetchResponse(\n+ messageID,\n+ serverSocketMessageTypes.STATE_SYNC,\n+ );\n+\n+ const {\n+ stateSyncMessage,\n+ activityUpdateMessage,\n+ serverRequestMessage,\n+ } = await promiseAll(promises);\n+\n+ if (serverRequestMessage) {\n+ this.props.dispatchActionPayload(\n+ clearDeliveredClientResponsesActionType,\n+ { clientResponses: nonActivityClientResponses },\n+ );\n+ const { serverRequests } = serverRequestMessage.payload;\n+ this.processServerRequests(serverRequests);\n+ }\n+ if (activityUpdateMessage) {\n+ this.props.dispatchActionPayload(\n+ activityUpdateSuccessActionType,\n+ {\n+ activityUpdates: queuedActivityUpdates,\n+ result: activityUpdateMessage.payload,\n+ },\n+ );\n+ }\n+\n+ if (stateSyncMessage.payload.type === stateSyncPayloadTypes.FULL) {\n+ const { sessionID, type, ...actionPayload } = stateSyncMessage.payload;\n+ this.props.dispatchActionPayload(\n+ fullStateSyncActionType,\n+ actionPayload,\n+ );\n+ if (sessionID !== null && sessionID !== undefined) {\n+ this.props.dispatchActionPayload(\n+ setNewSessionActionType,\n+ {\n+ sessionChange: { cookieInvalidated: false, sessionID },\n+ error: null,\n+ },\n+ );\n+ }\n+ } else {\n+ const { type, ...actionPayload } = stateSyncMessage.payload;\n+ this.props.dispatchActionPayload(\n+ incrementalStateSyncActionType,\n+ actionPayload,\n+ );\n+ }\n+\n+ this.markSocketInitialized();\n+ }\n+\n+ initializeSocket = async (\n+ retriesLeft: number = 1,\n+ ) => {\n+ try {\n+ await this.sendInitialMessage();\n+ } catch (e) {\n+ console.log(e);\n+ if (\n+ e instanceof SocketTimeout ||\n+ this.props.connection.status !== \"connecting\"\n+ ) {\n+ // This indicates that the socket will be closed. Do nothing, since the\n+ // connection status update will trigger a reconnect.\n+ } else if (\n+ retriesLeft === 0 ||\n+ (e instanceof ServerError && e.message !== \"unknown_error\")\n+ ) {\n+ if (this.socket) {\n+ this.socket.close();\n+ }\n+ } else {\n+ await this.initializeSocket(retriesLeft - 1);\n+ }\n+ }\n}\nstopPing() {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Use promises and async functions for socket initialization code
129,187
31.10.2018 19:06:06
14,400
694bec9d5c46af4b668c2a38124626b7b154de2e
[lib] Move inflightRequests to Socket component's state So we can automatically update children when it changes.
[ { "change_type": "MODIFY", "old_path": "lib/socket/socket.react.js", "new_path": "lib/socket/socket.react.js", "diff": "@@ -75,7 +75,10 @@ type Props = {|\ndispatch: Dispatch,\ndispatchActionPayload: DispatchActionPayload,\n|};\n-class Socket extends React.PureComponent<Props> {\n+type State = {|\n+ inflightRequests: ?InflightRequests,\n+|};\n+class Socket extends React.PureComponent<Props, State> {\nstatic propTypes = {\nopenSocket: PropTypes.func.isRequired,\n@@ -93,9 +96,11 @@ class Socket extends React.PureComponent<Props> {\ndispatch: PropTypes.func.isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\n};\n+ state = {\n+ inflightRequests: null,\n+ };\nsocket: ?WebSocket;\nnextClientMessageID = 0;\n- inflightRequests: ?InflightRequests;\npingTimeoutID: ?TimeoutID\ninitialPlatformDetailsSent = false;\nreopenConnectionAfterClosing = false;\n@@ -138,13 +143,15 @@ class Socket extends React.PureComponent<Props> {\n}\n};\nthis.socket = socket;\n- this.inflightRequests = new InflightRequests(\n+ this.setState({\n+ inflightRequests: new InflightRequests(\n() => {\nif (this.socket === socket) {\nthis.handleTimeout();\n}\n},\n- );\n+ ),\n+ });\n}\nmarkSocketInitialized() {\n@@ -196,7 +203,8 @@ class Socket extends React.PureComponent<Props> {\n}\nfinishClosingSocket() {\n- if (this.inflightRequests && !this.inflightRequests.allRequestsResolved) {\n+ const { inflightRequests } = this.state;\n+ if (inflightRequests && !inflightRequests.allRequestsResolved) {\nreturn;\n}\nthis.props.dispatchActionPayload(\n@@ -210,7 +218,7 @@ class Socket extends React.PureComponent<Props> {\nthis.socket = null;\n}\nthis.stopPing();\n- this.inflightRequests = null;\n+ this.setState({ inflightRequests: null });\nif (this.reopenConnectionAfterClosing) {\nthis.reopenConnectionAfterClosing = false;\nif (this.props.active) {\n@@ -347,8 +355,8 @@ class Socket extends React.PureComponent<Props> {\n// so we can reset the ping timeout.\nthis.resetPing();\n- invariant(this.inflightRequests, \"inflightRequests should exist\");\n- this.inflightRequests.resolveRequestsForMessage(message);\n+ invariant(this.state.inflightRequests, \"inflightRequests should exist\");\n+ this.state.inflightRequests.resolveRequestsForMessage(message);\nconst { status } = this.props.connection;\nif (status === \"disconnecting\" || status === \"forcedDisconnecting\") {\nthis.finishClosingSocket();\n@@ -397,9 +405,9 @@ class Socket extends React.PureComponent<Props> {\n) {\nregisterActiveWebSocket(null);\n}\n- if (this.inflightRequests) {\n- this.inflightRequests.rejectAll(new Error(\"socket closed\"));\n- this.inflightRequests = null;\n+ if (this.state.inflightRequests) {\n+ this.state.inflightRequests.rejectAll(new Error(\"socket closed\"));\n+ this.setState({ inflightRequests: null });\n}\nif (status !== \"disconnected\") {\nthis.props.dispatchActionPayload(\n@@ -413,7 +421,7 @@ class Socket extends React.PureComponent<Props> {\nhandleTimeout() {\nregisterActiveWebSocket(null);\n- this.inflightRequests = null;\n+ this.setState({ inflightRequests: null });\nconst { status } = this.props.connection;\nif (this.socket && this.socket.readyState < 2) {\nif (status !== \"disconnecting\") {\n@@ -437,7 +445,7 @@ class Socket extends React.PureComponent<Props> {\n}\nasync sendInitialMessage() {\n- const { inflightRequests } = this;\n+ const { inflightRequests } = this.state;\ninvariant(inflightRequests, \"inflightRequests should exist\");\nconst messageID = this.nextClientMessageID++;\nconst promises = {};\n@@ -597,8 +605,8 @@ class Socket extends React.PureComponent<Props> {\nid: messageID,\n});\ntry {\n- invariant(this.inflightRequests, \"inflightRequests should exist\");\n- await this.inflightRequests.fetchResponse(\n+ invariant(this.state.inflightRequests, \"inflightRequests should exist\");\n+ await this.state.inflightRequests.fetchResponse(\nmessageID,\nserverSocketMessageTypes.PONG,\n);\n@@ -621,8 +629,8 @@ class Socket extends React.PureComponent<Props> {\nclientResponses: $ReadOnlyArray<ClientResponse>,\n): Promise<RequestsServerSocketMessage> {\nconst messageID = this.nextClientMessageID++;\n- invariant(this.inflightRequests, \"inflightRequests should exist\");\n- const promise = this.inflightRequests.fetchResponse(\n+ invariant(this.state.inflightRequests, \"inflightRequests should exist\");\n+ const promise = this.state.inflightRequests.fetchResponse(\nmessageID,\nserverSocketMessageTypes.REQUESTS,\n);\n@@ -744,8 +752,8 @@ class Socket extends React.PureComponent<Props> {\nactivityUpdates: $ReadOnlyArray<ActivityUpdate>\n): Promise<ActivityUpdateResponseServerSocketMessage> {\nconst messageID = this.nextClientMessageID++;\n- invariant(this.inflightRequests, \"inflightRequests should exist\");\n- const promise = this.inflightRequests.fetchResponse(\n+ invariant(this.state.inflightRequests, \"inflightRequests should exist\");\n+ const promise = this.state.inflightRequests.fetchResponse(\nmessageID,\nserverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE,\n);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Move inflightRequests to Socket component's state So we can automatically update children when it changes.
129,187
01.11.2018 00:30:05
14,400
e62a227263e449091132c5886d4c456da04ce0e2
Extract ActivityUpdates logic from Socket into ActivityMaintainer
[ { "change_type": "ADD", "old_path": null, "new_path": "lib/socket/activity-maintainer.react.js", "diff": "+// @flow\n+\n+import {\n+ type ActivityUpdateResponseServerSocketMessage,\n+ clientSocketMessageTypes,\n+ serverSocketMessageTypes,\n+ queueActivityUpdatesActionType,\n+ activityUpdateSuccessActionType,\n+ activityUpdateFailedActionType,\n+ type ClientSocketMessageWithoutID,\n+ type ConnectionInfo,\n+ connectionInfoPropType,\n+} from '../types/socket-types';\n+import type { ActivityUpdate } from '../types/activity-types';\n+import type { DispatchActionPayload } from '../utils/action-utils';\n+import type { BaseAppState } from '../types/redux-types';\n+\n+import * as React from 'react';\n+import PropTypes from 'prop-types';\n+import invariant from 'invariant';\n+\n+import { connect } from '../utils/redux-utils';\n+import { InflightRequests, SocketTimeout } from './inflight-requests';\n+import { ServerError } from '../utils/errors';\n+\n+type Props = {|\n+ activeThread: ?string,\n+ inflightRequests: ?InflightRequests,\n+ sendMessage: (message: ClientSocketMessageWithoutID) => number,\n+ // Redux state\n+ connection: ConnectionInfo,\n+ activeThreadLatestMessage: ?string,\n+ // Redux dispatch functions\n+ dispatchActionPayload: DispatchActionPayload,\n+|};\n+class ActivityMaintainer extends React.PureComponent<Props> {\n+\n+ static propTypes = {\n+ activeThread: PropTypes.string,\n+ inflightRequests: PropTypes.object,\n+ sendMessage: PropTypes.func.isRequired,\n+ connection: connectionInfoPropType.isRequired,\n+ activeThreadLatestMessage: PropTypes.string,\n+ dispatchActionPayload: PropTypes.func.isRequired,\n+ };\n+\n+ componentDidUpdate(prevProps: Props) {\n+ const activityUpdates = [];\n+ if (this.props.activeThread !== prevProps.activeThread) {\n+ if (prevProps.activeThread) {\n+ activityUpdates.push({\n+ focus: false,\n+ threadID: prevProps.activeThread,\n+ latestMessage: prevProps.activeThreadLatestMessage,\n+ });\n+ }\n+ if (this.props.activeThread) {\n+ activityUpdates.push({\n+ focus: true,\n+ threadID: this.props.activeThread,\n+ });\n+ }\n+ }\n+\n+ if (activityUpdates.length > 0) {\n+ this.props.dispatchActionPayload(\n+ queueActivityUpdatesActionType,\n+ { activityUpdates },\n+ );\n+ }\n+\n+ const { inflightRequests, connection } = this.props;\n+ if (!inflightRequests || connection.status !== \"connected\") {\n+ return;\n+ }\n+\n+ if (prevProps.connection.status !== \"connected\") {\n+ const { queuedActivityUpdates } = this.props.connection;\n+ this.sendAndHandleActivityUpdates(\n+ [ ...queuedActivityUpdates, ...activityUpdates ],\n+ );\n+ } else {\n+ this.sendAndHandleActivityUpdates(activityUpdates);\n+ }\n+ }\n+\n+ render() {\n+ return null;\n+ }\n+\n+ sendAndHandleActivityUpdates(\n+ activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n+ ) {\n+ if (activityUpdates.length === 0) {\n+ return;\n+ }\n+ const promise = this.sendActivityUpdates(activityUpdates);\n+ this.handleActivityUpdates(promise, activityUpdates);\n+ }\n+\n+ sendActivityUpdates(\n+ activityUpdates: $ReadOnlyArray<ActivityUpdate>\n+ ): Promise<ActivityUpdateResponseServerSocketMessage> {\n+ const { inflightRequests } = this.props;\n+ invariant(inflightRequests, \"inflightRequests should exist\");\n+ const messageID = this.props.sendMessage({\n+ type: clientSocketMessageTypes.ACTIVITY_UPDATES,\n+ payload: { activityUpdates },\n+ });\n+ return inflightRequests.fetchResponse(\n+ messageID,\n+ serverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE,\n+ );\n+ }\n+\n+ async handleActivityUpdates(\n+ promise: Promise<ActivityUpdateResponseServerSocketMessage>,\n+ activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n+ retriesLeft: number = 1,\n+ ): Promise<void> {\n+ try {\n+ const response = await promise;\n+ this.props.dispatchActionPayload(\n+ activityUpdateSuccessActionType,\n+ { activityUpdates, result: response.payload },\n+ );\n+ } catch (e) {\n+ console.log(e);\n+ if (\n+ e instanceof SocketTimeout ||\n+ this.props.connection.status !== \"connected\" ||\n+ !this.props.inflightRequests\n+ ) {\n+ // This indicates that the socket will be closed. Do nothing, since when\n+ // it will reopen it will send all the queued activity updates again.\n+ } else if (\n+ retriesLeft === 0 ||\n+ (e instanceof ServerError && e.message !== \"unknown_error\")\n+ ) {\n+ // We're giving up on these activity updates, as they seem to cause the\n+ // server to error...\n+ this.props.dispatchActionPayload(\n+ activityUpdateFailedActionType,\n+ { activityUpdates },\n+ );\n+ } else {\n+ const newPromise = this.sendActivityUpdates(activityUpdates);\n+ await this.handleActivityUpdates(\n+ newPromise,\n+ activityUpdates,\n+ retriesLeft - 1,\n+ );\n+ }\n+ }\n+ }\n+\n+}\n+\n+export default connect(\n+ (state: BaseAppState<*>, ownProps: { activeThread: ?string }) => {\n+ const { activeThread } = ownProps;\n+ return {\n+ connection: state.connection,\n+ activeThreadLatestMessage:\n+ activeThread && state.messageStore.threads[activeThread]\n+ ? state.messageStore.threads[activeThread].messageIDs[0]\n+ : null,\n+ };\n+ },\n+ null,\n+ true,\n+)(ActivityMaintainer);\n" }, { "change_type": "MODIFY", "old_path": "lib/socket/socket.react.js", "new_path": "lib/socket/socket.react.js", "diff": "@@ -25,16 +25,16 @@ import {\nupdateConnectionStatusActionType,\nconnectionInfoPropType,\ntype ConnectionInfo,\n- queueActivityUpdatesActionType,\nactivityUpdateSuccessActionType,\n- activityUpdateFailedActionType,\n- type ActivityUpdateResponseServerSocketMessage,\ntype RequestsServerSocketMessage,\ntype PongServerSocketMessage,\ntype StateSyncServerSocketMessage,\n+ type InitialClientSocketMessage,\n+ type ResponsesClientSocketMessage,\n+ type ActivityUpdatesClientSocketMessage,\n+ type PingClientSocketMessage,\n+ type ClientSocketMessageWithoutID,\n} from '../types/socket-types';\n-import { InflightRequests, SocketTimeout } from './inflight-requests';\n-import type { ActivityUpdate } from '../types/activity-types';\nimport type { Dispatch } from '../types/redux-types';\nimport type { DispatchActionPayload } from '../utils/action-utils';\nimport type { LogInExtraInfo } from '../types/account-types';\n@@ -54,6 +54,8 @@ import { socketAuthErrorResolutionAttempt } from '../actions/user-actions';\nimport { ServerError } from '../utils/errors';\nimport { pingFrequency } from '../shared/timeouts';\nimport { promiseAll } from '../utils/promises';\n+import { InflightRequests, SocketTimeout } from './inflight-requests';\n+import ActivityMaintainer from './activity-maintainer.react';\ntype Props = {|\n// Redux state\n@@ -64,7 +66,6 @@ type Props = {|\nactiveServerRequests: $ReadOnlyArray<ServerRequest>,\n) => $ReadOnlyArray<ClientResponse>,\nactiveThread: ?string,\n- activeThreadLatestMessage: ?string,\nsessionStateFunc: () => SessionState,\nsessionIdentification: SessionIdentification,\ncookie: ?string,\n@@ -86,7 +87,6 @@ class Socket extends React.PureComponent<Props, State> {\nqueuedClientResponses: PropTypes.arrayOf(clientResponsePropType).isRequired,\ngetClientResponses: PropTypes.func.isRequired,\nactiveThread: PropTypes.string,\n- activeThreadLatestMessage: PropTypes.string,\nsessionStateFunc: PropTypes.func.isRequired,\nsessionIdentification: sessionIdentificationPropType.isRequired,\ncookie: PropTypes.string,\n@@ -163,7 +163,7 @@ class Socket extends React.PureComponent<Props, State> {\nthis.resetPing();\n}\n- closeSocket(activityUpdates: $ReadOnlyArray<ActivityUpdate>) {\n+ closeSocket() {\nconst { status } = this.props.connection;\nif (status === \"disconnected\") {\nreturn;\n@@ -177,11 +177,10 @@ class Socket extends React.PureComponent<Props, State> {\nupdateConnectionStatusActionType,\n{ status: \"disconnecting\" },\n);\n- this.sendFinalActivityUpdates(activityUpdates);\nthis.finishClosingSocket();\n}\n- forceCloseSocket(activityUpdates: $ReadOnlyArray<ActivityUpdate>) {\n+ forceCloseSocket() {\nregisterActiveWebSocket(null);\nthis.stopPing();\nconst { status } = this.props.connection;\n@@ -191,17 +190,9 @@ class Socket extends React.PureComponent<Props, State> {\n{ status: \"forcedDisconnecting\" },\n);\n}\n- this.sendFinalActivityUpdates(activityUpdates);\nthis.finishClosingSocket();\n}\n- sendFinalActivityUpdates(activityUpdates: $ReadOnlyArray<ActivityUpdate>) {\n- const { status } = this.props.connection;\n- if (status === \"connected\") {\n- this.sendAndHandleActivityUpdates(activityUpdates);\n- }\n- }\n-\nfinishClosingSocket() {\nconst { inflightRequests } = this.state;\nif (inflightRequests && !inflightRequests.allRequestsResolved) {\n@@ -238,49 +229,26 @@ class Socket extends React.PureComponent<Props, State> {\n}\ncomponentWillUnmount() {\n- this.closeSocket([]);\n+ this.closeSocket();\n}\ncomponentDidUpdate(prevProps: Props) {\n- const activityUpdates = [];\n- if (this.props.activeThread !== prevProps.activeThread) {\n- if (prevProps.activeThread) {\n- activityUpdates.push({\n- focus: false,\n- threadID: prevProps.activeThread,\n- latestMessage: prevProps.activeThreadLatestMessage,\n- });\n- }\n- if (this.props.activeThread) {\n- activityUpdates.push({\n- focus: true,\n- threadID: this.props.activeThread,\n- });\n- }\n- }\n-\nconst { queuedClientResponses, connection } = this.props;\n- const { status, queuedActivityUpdates } = connection;\n- const {\n- queuedClientResponses: prevClientResponses,\n- connection: prevConnection,\n- } = prevProps;\n- const {\n- status: prevStatus,\n- queuedActivityUpdates: prevActivityUpdates,\n- } = prevConnection;\n+ const { status } = connection;\n+ const prevClientResponses = prevProps.queuedClientResponses;\n+ const prevStatus = prevProps.connection.status;\nif (this.props.active && !prevProps.active) {\nthis.openSocket();\n} else if (!this.props.active && prevProps.active) {\n- this.closeSocket(activityUpdates);\n+ this.closeSocket();\n} else if (\nthis.props.active &&\nprevProps.openSocket !== this.props.openSocket\n) {\n// This case happens when the baseURL/urlPrefix is changed\nthis.reopenConnectionAfterClosing = true;\n- this.forceCloseSocket(activityUpdates);\n+ this.forceCloseSocket();\n} else if (\nthis.props.active &&\nstatus === \"disconnected\" &&\n@@ -289,13 +257,6 @@ class Socket extends React.PureComponent<Props, State> {\nthis.reconnect();\n}\n- if (activityUpdates.length > 0) {\n- this.props.dispatchActionPayload(\n- queueActivityUpdatesActionType,\n- { activityUpdates },\n- );\n- }\n-\nif (status === \"connected\" && prevStatus !== \"connected\") {\nthis.sendAndHandleQueuedClientResponses(queuedClientResponses);\n} else if (\n@@ -308,23 +269,38 @@ class Socket extends React.PureComponent<Props, State> {\n);\nthis.sendAndHandleQueuedClientResponses(newResponses);\n}\n-\n- if (status === \"connected\" && prevStatus !== \"connected\") {\n- this.sendAndHandleActivityUpdates(queuedActivityUpdates);\n- } else if (\n- status === \"connected\" &&\n- queuedActivityUpdates !== prevActivityUpdates\n- ) {\n- const prevUpdates = new Set(prevActivityUpdates);\n- const newUpdates = queuedActivityUpdates.filter(\n- update => !prevUpdates.has(update),\n- );\n- this.sendAndHandleActivityUpdates(newUpdates);\n- }\n}\nrender() {\n- return null;\n+ const inflightRequests = this.props.connection.status === \"connected\"\n+ ? this.state.inflightRequests\n+ : null;\n+ return (\n+ <ActivityMaintainer\n+ activeThread={this.props.activeThread}\n+ inflightRequests={inflightRequests}\n+ sendMessage={this.sendMessageWithoutID}\n+ />\n+ );\n+ }\n+\n+ sendMessageWithoutID = (message: ClientSocketMessageWithoutID) => {\n+ const id = this.nextClientMessageID++;\n+ // These conditions all do the same thing and the runtime checks are only\n+ // necessary for Flow\n+ if (message.type === clientSocketMessageTypes.INITIAL) {\n+ this.sendMessage(({ ...message, id }: InitialClientSocketMessage));\n+ } else if (message.type === clientSocketMessageTypes.RESPONSES) {\n+ this.sendMessage(({ ...message, id }: ResponsesClientSocketMessage));\n+ } else if (message.type === clientSocketMessageTypes.ACTIVITY_UPDATES) {\n+ this.sendMessage(({\n+ ...message,\n+ id,\n+ }: ActivityUpdatesClientSocketMessage));\n+ } else if (message.type === clientSocketMessageTypes.PING) {\n+ this.sendMessage(({ ...message, id }: PingClientSocketMessage));\n+ }\n+ return id;\n}\nsendMessage(message: ClientSocketMessage) {\n@@ -738,73 +714,6 @@ class Socket extends React.PureComponent<Props, State> {\n}\n}\n- sendAndHandleActivityUpdates(\n- activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n- ) {\n- if (activityUpdates.length === 0) {\n- return;\n- }\n- const promise = this.sendActivityUpdates(activityUpdates);\n- this.handleActivityUpdates(promise, activityUpdates);\n- }\n-\n- sendActivityUpdates(\n- activityUpdates: $ReadOnlyArray<ActivityUpdate>\n- ): Promise<ActivityUpdateResponseServerSocketMessage> {\n- const messageID = this.nextClientMessageID++;\n- invariant(this.state.inflightRequests, \"inflightRequests should exist\");\n- const promise = this.state.inflightRequests.fetchResponse(\n- messageID,\n- serverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE,\n- );\n- this.sendMessage({\n- type: clientSocketMessageTypes.ACTIVITY_UPDATES,\n- id: messageID,\n- payload: { activityUpdates },\n- });\n- return promise;\n- }\n-\n- async handleActivityUpdates(\n- promise: Promise<ActivityUpdateResponseServerSocketMessage>,\n- activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n- retriesLeft: number = 1,\n- ): Promise<void> {\n- try {\n- const response = await promise;\n- this.props.dispatchActionPayload(\n- activityUpdateSuccessActionType,\n- { activityUpdates, result: response.payload },\n- );\n- } catch (e) {\n- console.log(e);\n- if (\n- e instanceof SocketTimeout ||\n- this.props.connection.status !== \"connected\"\n- ) {\n- // This indicates that the socket will be closed. Do nothing, since when\n- // it will reopen it will send all the queued activity updates again.\n- } else if (\n- retriesLeft === 0 ||\n- (e instanceof ServerError && e.message !== \"unknown_error\")\n- ) {\n- // We're giving up on these activity updates, as they seem to cause the\n- // server to error...\n- this.props.dispatchActionPayload(\n- activityUpdateFailedActionType,\n- { activityUpdates },\n- );\n- } else {\n- const newPromise = this.sendActivityUpdates(activityUpdates);\n- await this.handleActivityUpdates(\n- newPromise,\n- activityUpdates,\n- retriesLeft - 1,\n- );\n- }\n- }\n- }\n-\n}\nexport default Socket;\n" }, { "change_type": "MODIFY", "old_path": "lib/types/socket-types.js", "new_path": "lib/types/socket-types.js", "diff": "@@ -73,6 +73,8 @@ export type ClientSocketMessage =\n| ResponsesClientSocketMessage\n| ActivityUpdatesClientSocketMessage\n| PingClientSocketMessage;\n+export type ClientSocketMessageWithoutID =\n+ $Diff<ClientSocketMessage, { id: number }>;\n// The types of messages that the server sends across the socket\nexport const serverSocketMessageTypes = Object.freeze({\n" }, { "change_type": "MODIFY", "old_path": "native/socket.react.js", "new_path": "native/socket.react.js", "diff": "@@ -26,17 +26,12 @@ export default connect(\nstate.currentUserInfo &&\n!state.currentUserInfo.anonymous &&\nstate.foreground;\n- const activeThread = active ? activeThreadSelector(state) : null;\nreturn {\nactive,\nopenSocket: openSocketSelector(state),\nqueuedClientResponses: queuedClientResponsesSelector(state),\ngetClientResponses: getClientResponsesSelector(state),\n- activeThread,\n- activeThreadLatestMessage:\n- activeThread && state.messageStore.threads[activeThread]\n- ? state.messageStore.threads[activeThread].messageIDs[0]\n- : null,\n+ activeThread: active ? activeThreadSelector(state) : null,\nsessionStateFunc: sessionStateFuncSelector(state),\nsessionIdentification: sessionIdentificationSelector(state),\ncookie: state.cookie,\n" }, { "change_type": "MODIFY", "old_path": "web/socket.react.js", "new_path": "web/socket.react.js", "diff": "@@ -28,11 +28,7 @@ export default connect(\nopenSocket: openSocketSelector(state),\nqueuedClientResponses: queuedClientResponsesSelector(state),\ngetClientResponses: getClientResponsesSelector(state),\n- activeThread,\n- activeThreadLatestMessage:\n- activeThread && state.messageStore.threads[activeThread]\n- ? state.messageStore.threads[activeThread].messageIDs[0]\n- : null,\n+ activeThread: active ? activeThreadSelector(state) : null,\nsessionStateFunc: sessionStateFuncSelector(state),\nsessionIdentification: sessionIdentificationSelector(state),\ncookie: state.cookie,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Extract ActivityUpdates logic from Socket into ActivityMaintainer
129,187
01.11.2018 17:57:18
14,400
84c865b54ca05cfbdbe772b826937a93c4c23cb3
Extract ClientResponses logic from Socket into ClientResponseMaintainer
[ { "change_type": "ADD", "old_path": null, "new_path": "lib/socket/client-response-maintainer.react.js", "diff": "+// @flow\n+\n+import {\n+ type RequestsServerSocketMessage,\n+ type ServerSocketMessage,\n+ clientSocketMessageTypes,\n+ serverSocketMessageTypes,\n+ type ClientSocketMessageWithoutID,\n+ type SocketListener,\n+ type ConnectionInfo,\n+ connectionInfoPropType,\n+} from '../types/socket-types';\n+import {\n+ clearDeliveredClientResponsesActionType,\n+ processServerRequestsActionType,\n+ type ClientResponse,\n+ type ServerRequest,\n+ clientResponsePropType,\n+} from '../types/request-types';\n+import type { DispatchActionPayload } from '../utils/action-utils';\n+import type { AppState } from '../types/redux-types';\n+\n+import * as React from 'react';\n+import PropTypes from 'prop-types';\n+import invariant from 'invariant';\n+\n+import { connect } from '../utils/redux-utils';\n+import { InflightRequests, SocketTimeout } from './inflight-requests';\n+import { ServerError } from '../utils/errors';\n+import {\n+ queuedClientResponsesSelector,\n+ getClientResponsesSelector,\n+} from '../selectors/socket-selectors';\n+\n+type Props = {|\n+ inflightRequests: ?InflightRequests,\n+ sendMessage: (message: ClientSocketMessageWithoutID) => number,\n+ addListener: (listener: SocketListener) => void,\n+ removeListener: (listener: SocketListener) => void,\n+ // Redux state\n+ connection: ConnectionInfo,\n+ queuedClientResponses: $ReadOnlyArray<ClientResponse>,\n+ getClientResponses: (\n+ activeServerRequests: $ReadOnlyArray<ServerRequest>,\n+ ) => $ReadOnlyArray<ClientResponse>,\n+ // Redux dispatch functions\n+ dispatchActionPayload: DispatchActionPayload,\n+|};\n+\n+class ClientResponseMaintainer extends React.PureComponent<Props> {\n+\n+ static propTypes = {\n+ inflightRequests: PropTypes.object,\n+ sendMessage: PropTypes.func.isRequired,\n+ addListener: PropTypes.func.isRequired,\n+ removeListener: PropTypes.func.isRequired,\n+ connection: connectionInfoPropType.isRequired,\n+ queuedClientResponses: PropTypes.arrayOf(clientResponsePropType).isRequired,\n+ getClientResponses: PropTypes.func.isRequired,\n+ dispatchActionPayload: PropTypes.func.isRequired,\n+ };\n+\n+ componentDidMount() {\n+ this.props.addListener(this.onMessage);\n+ }\n+\n+ componentWillUnmount() {\n+ this.props.removeListener(this.onMessage);\n+ }\n+\n+ componentDidUpdate(prevProps: Props) {\n+ const { inflightRequests, connection } = this.props;\n+ if (!inflightRequests || connection.status !== \"connected\") {\n+ return;\n+ }\n+\n+ const { queuedClientResponses } = this.props;\n+ const prevClientResponses = prevProps.queuedClientResponses;\n+\n+ if (prevProps.connection.status !== \"connected\") {\n+ this.sendAndHandleQueuedClientResponses(queuedClientResponses);\n+ } else if (queuedClientResponses !== prevClientResponses) {\n+ const prevResponses = new Set(prevClientResponses);\n+ const newResponses = queuedClientResponses.filter(\n+ response => !prevResponses.has(response),\n+ );\n+ this.sendAndHandleQueuedClientResponses(newResponses);\n+ }\n+ }\n+\n+ render() {\n+ return null;\n+ }\n+\n+ onMessage = (message: ServerSocketMessage) => {\n+ if (message.type !== serverSocketMessageTypes.REQUESTS) {\n+ return;\n+ }\n+ const { serverRequests } = message.payload;\n+ if (serverRequests.length === 0) {\n+ return;\n+ }\n+ this.props.dispatchActionPayload(\n+ processServerRequestsActionType,\n+ { serverRequests },\n+ );\n+ if (this.props.inflightRequests) {\n+ const clientResponses = this.props.getClientResponses(serverRequests);\n+ this.sendAndHandleClientResponsesToServerRequests(clientResponses);\n+ }\n+ }\n+\n+ sendAndHandleQueuedClientResponses(\n+ clientResponses: $ReadOnlyArray<ClientResponse>,\n+ ) {\n+ if (clientResponses.length === 0) {\n+ return;\n+ }\n+ const promise = this.sendClientResponses(clientResponses);\n+ this.handleQueuedClientResponses(promise, clientResponses);\n+ }\n+\n+ sendClientResponses(\n+ clientResponses: $ReadOnlyArray<ClientResponse>,\n+ ): Promise<RequestsServerSocketMessage> {\n+ const { inflightRequests } = this.props;\n+ invariant(inflightRequests, \"inflightRequests should exist\");\n+ const messageID = this.props.sendMessage({\n+ type: clientSocketMessageTypes.RESPONSES,\n+ payload: { clientResponses },\n+ });\n+ return inflightRequests.fetchResponse(\n+ messageID,\n+ serverSocketMessageTypes.REQUESTS,\n+ );\n+ }\n+\n+ async handleQueuedClientResponses(\n+ promise: Promise<RequestsServerSocketMessage>,\n+ clientResponses: $ReadOnlyArray<ClientResponse>,\n+ retriesLeft: number = 1,\n+ ): Promise<void> {\n+ try {\n+ await promise;\n+ this.props.dispatchActionPayload(\n+ clearDeliveredClientResponsesActionType,\n+ { clientResponses },\n+ );\n+ } catch (e) {\n+ console.log(e);\n+ if (\n+ e instanceof SocketTimeout ||\n+ this.props.connection.status !== \"connected\" ||\n+ !this.props.inflightRequests\n+ ) {\n+ // This indicates that the socket will be closed. Do nothing, since when\n+ // it will reopen it will send all the queued ClientResponses again.\n+ } else if (\n+ retriesLeft === 0 ||\n+ (e instanceof ServerError && e.message !== \"unknown_error\")\n+ ) {\n+ // We're giving up on these ClientResponses, as they seem to cause the\n+ // server to error...\n+ this.props.dispatchActionPayload(\n+ clearDeliveredClientResponsesActionType,\n+ { clientResponses },\n+ );\n+ } else {\n+ const newPromise = this.sendClientResponses(clientResponses);\n+ await this.handleQueuedClientResponses(\n+ newPromise,\n+ clientResponses,\n+ retriesLeft - 1,\n+ );\n+ }\n+ }\n+ }\n+\n+ sendAndHandleClientResponsesToServerRequests(\n+ clientResponses: $ReadOnlyArray<ClientResponse>,\n+ ) {\n+ if (clientResponses.length === 0) {\n+ return;\n+ }\n+ const promise = this.sendClientResponses(clientResponses);\n+ this.handleClientResponsesToServerRequests(promise, clientResponses);\n+ }\n+\n+ async handleClientResponsesToServerRequests(\n+ promise: Promise<RequestsServerSocketMessage>,\n+ clientResponses: $ReadOnlyArray<ClientResponse>,\n+ retriesLeft: number = 1,\n+ ): Promise<void> {\n+ try {\n+ await promise;\n+ } catch (e) {\n+ console.log(e);\n+ if (\n+ !(e instanceof SocketTimeout) &&\n+ (!(e instanceof ServerError) || e.message === \"unknown_error\") &&\n+ retriesLeft > 0 &&\n+ this.props.connection.status === \"connected\" &&\n+ this.props.inflightRequests\n+ ) {\n+ // We'll only retry if the connection is healthy and the error is either\n+ // an unknown_error ServerError or something is neither a ServerError\n+ // nor a SocketTimeout.\n+ const newPromise = this.sendClientResponses(clientResponses);\n+ await this.handleClientResponsesToServerRequests(\n+ newPromise,\n+ clientResponses,\n+ retriesLeft - 1,\n+ );\n+ }\n+ }\n+ }\n+\n+}\n+\n+export default connect(\n+ (state: AppState) => ({\n+ connection: state.connection,\n+ queuedClientResponses: queuedClientResponsesSelector(state),\n+ getClientResponses: getClientResponsesSelector(state),\n+ }),\n+ null,\n+ true,\n+)(ClientResponseMaintainer);\n" }, { "change_type": "MODIFY", "old_path": "lib/socket/socket.react.js", "new_path": "lib/socket/socket.react.js", "diff": "// @flow\nimport {\n- type ServerRequest,\nserverRequestTypes,\ntype ClientResponse,\nclearDeliveredClientResponsesActionType,\n- processServerRequestsActionType,\nclientResponsePropType,\n} from '../types/request-types';\nimport {\n@@ -15,7 +13,6 @@ import {\n} from '../types/session-types';\nimport {\nclientSocketMessageTypes,\n- type ServerSocketMessageType,\ntype ClientSocketMessage,\nserverSocketMessageTypes,\ntype ServerSocketMessage,\n@@ -26,14 +23,12 @@ import {\nconnectionInfoPropType,\ntype ConnectionInfo,\nactivityUpdateSuccessActionType,\n- type RequestsServerSocketMessage,\n- type PongServerSocketMessage,\n- type StateSyncServerSocketMessage,\ntype InitialClientSocketMessage,\ntype ResponsesClientSocketMessage,\ntype ActivityUpdatesClientSocketMessage,\ntype PingClientSocketMessage,\ntype ClientSocketMessageWithoutID,\n+ type SocketListener,\n} from '../types/socket-types';\nimport type { Dispatch } from '../types/redux-types';\nimport type { DispatchActionPayload } from '../utils/action-utils';\n@@ -56,15 +51,13 @@ import { pingFrequency } from '../shared/timeouts';\nimport { promiseAll } from '../utils/promises';\nimport { InflightRequests, SocketTimeout } from './inflight-requests';\nimport ActivityMaintainer from './activity-maintainer.react';\n+import ClientResponseMaintainer from './client-response-maintainer.react';\ntype Props = {|\n// Redux state\nactive: bool,\nopenSocket: () => WebSocket,\nqueuedClientResponses: $ReadOnlyArray<ClientResponse>,\n- getClientResponses: (\n- activeServerRequests: $ReadOnlyArray<ServerRequest>,\n- ) => $ReadOnlyArray<ClientResponse>,\nactiveThread: ?string,\nsessionStateFunc: () => SessionState,\nsessionIdentification: SessionIdentification,\n@@ -85,7 +78,6 @@ class Socket extends React.PureComponent<Props, State> {\nopenSocket: PropTypes.func.isRequired,\nactive: PropTypes.bool.isRequired,\nqueuedClientResponses: PropTypes.arrayOf(clientResponsePropType).isRequired,\n- getClientResponses: PropTypes.func.isRequired,\nactiveThread: PropTypes.string,\nsessionStateFunc: PropTypes.func.isRequired,\nsessionIdentification: sessionIdentificationPropType.isRequired,\n@@ -101,11 +93,12 @@ class Socket extends React.PureComponent<Props, State> {\n};\nsocket: ?WebSocket;\nnextClientMessageID = 0;\n+ listeners: Set<SocketListener> = new Set();\npingTimeoutID: ?TimeoutID\ninitialPlatformDetailsSent = false;\nreopenConnectionAfterClosing = false;\n- openSocket() {\n+ openSocket = () => {\nif (this.socket) {\nconst { status } = this.props.connection;\nif (status === \"forcedDisconnecting\") {\n@@ -218,9 +211,7 @@ class Socket extends React.PureComponent<Props, State> {\n}\n}\n- reconnect = _debounce(2000)(() => {\n- this.openSocket();\n- })\n+ reconnect = _debounce(2000)(this.openSocket)\ncomponentDidMount() {\nif (this.props.active) {\n@@ -233,11 +224,6 @@ class Socket extends React.PureComponent<Props, State> {\n}\ncomponentDidUpdate(prevProps: Props) {\n- const { queuedClientResponses, connection } = this.props;\n- const { status } = connection;\n- const prevClientResponses = prevProps.queuedClientResponses;\n- const prevStatus = prevProps.connection.status;\n-\nif (this.props.active && !prevProps.active) {\nthis.openSocket();\n} else if (!this.props.active && prevProps.active) {\n@@ -251,36 +237,28 @@ class Socket extends React.PureComponent<Props, State> {\nthis.forceCloseSocket();\n} else if (\nthis.props.active &&\n- status === \"disconnected\" &&\n- prevStatus !== \"disconnected\"\n+ this.props.connection.status === \"disconnected\" &&\n+ prevProps.connection.status !== \"disconnected\"\n) {\nthis.reconnect();\n}\n-\n- if (status === \"connected\" && prevStatus !== \"connected\") {\n- this.sendAndHandleQueuedClientResponses(queuedClientResponses);\n- } else if (\n- status === \"connected\" &&\n- queuedClientResponses !== prevClientResponses\n- ) {\n- const prevResponses = new Set(prevClientResponses);\n- const newResponses = queuedClientResponses.filter(\n- response => !prevResponses.has(response),\n- );\n- this.sendAndHandleQueuedClientResponses(newResponses);\n- }\n}\nrender() {\n- const inflightRequests = this.props.connection.status === \"connected\"\n- ? this.state.inflightRequests\n- : null;\nreturn (\n+ <React.Fragment>\n<ActivityMaintainer\nactiveThread={this.props.activeThread}\n- inflightRequests={inflightRequests}\n+ inflightRequests={this.state.inflightRequests}\nsendMessage={this.sendMessageWithoutID}\n/>\n+ <ClientResponseMaintainer\n+ inflightRequests={this.state.inflightRequests}\n+ sendMessage={this.sendMessageWithoutID}\n+ addListener={this.addListener}\n+ removeListener={this.removeListener}\n+ />\n+ </React.Fragment>\n);\n}\n@@ -338,6 +316,10 @@ class Socket extends React.PureComponent<Props, State> {\nthis.finishClosingSocket();\n}\n+ for (let listener of this.listeners) {\n+ listener(message);\n+ }\n+\nif (message.type === serverSocketMessageTypes.ERROR) {\nconst { message: errorMessage, payload } = message;\nif (payload) {\n@@ -372,6 +354,14 @@ class Socket extends React.PureComponent<Props, State> {\n}\n}\n+ addListener = (listener: SocketListener) => {\n+ this.listeners.add(listener);\n+ }\n+\n+ removeListener = (listener: SocketListener) => {\n+ this.listeners.delete(listener);\n+ }\n+\nonClose = (event: CloseEvent) => {\nconst { status } = this.props.connection;\nif (\n@@ -484,8 +474,6 @@ class Socket extends React.PureComponent<Props, State> {\nclearDeliveredClientResponsesActionType,\n{ clientResponses: nonActivityClientResponses },\n);\n- const { serverRequests } = serverRequestMessage.payload;\n- this.processServerRequests(serverRequests);\n}\nif (activityUpdateMessage) {\nthis.props.dispatchActionPayload(\n@@ -575,10 +563,8 @@ class Socket extends React.PureComponent<Props, State> {\n// connection status should call stopPing(), but it's good to make sure\nreturn;\n}\n- const messageID = this.nextClientMessageID++;\n- this.sendMessage({\n+ const messageID = this.sendMessageWithoutID({\ntype: clientSocketMessageTypes.PING,\n- id: messageID,\n});\ntry {\ninvariant(this.state.inflightRequests, \"inflightRequests should exist\");\n@@ -591,129 +577,6 @@ class Socket extends React.PureComponent<Props, State> {\n}\n}\n- sendAndHandleQueuedClientResponses(\n- clientResponses: $ReadOnlyArray<ClientResponse>,\n- ) {\n- if (clientResponses.length === 0) {\n- return;\n- }\n- const promise = this.sendClientResponses(clientResponses);\n- this.handleQueuedClientResponses(promise, clientResponses);\n- }\n-\n- sendClientResponses(\n- clientResponses: $ReadOnlyArray<ClientResponse>,\n- ): Promise<RequestsServerSocketMessage> {\n- const messageID = this.nextClientMessageID++;\n- invariant(this.state.inflightRequests, \"inflightRequests should exist\");\n- const promise = this.state.inflightRequests.fetchResponse(\n- messageID,\n- serverSocketMessageTypes.REQUESTS,\n- );\n- this.sendMessage({\n- type: clientSocketMessageTypes.RESPONSES,\n- id: messageID,\n- payload: { clientResponses },\n- });\n- return promise;\n- }\n-\n- async handleQueuedClientResponses(\n- promise: Promise<RequestsServerSocketMessage>,\n- clientResponses: $ReadOnlyArray<ClientResponse>,\n- retriesLeft: number = 1,\n- ): Promise<void> {\n- try {\n- const response = await promise;\n- this.props.dispatchActionPayload(\n- clearDeliveredClientResponsesActionType,\n- { clientResponses },\n- );\n- const { serverRequests } = response.payload;\n- this.processServerRequests(serverRequests);\n- } catch (e) {\n- console.log(e);\n- if (\n- e instanceof SocketTimeout ||\n- this.props.connection.status !== \"connected\"\n- ) {\n- // This indicates that the socket will be closed. Do nothing, since when\n- // it will reopen it will send all the queued ClientResponses again.\n- } else if (\n- retriesLeft === 0 ||\n- (e instanceof ServerError && e.message !== \"unknown_error\")\n- ) {\n- // We're giving up on these ClientResponses, as they seem to cause the\n- // server to error...\n- this.props.dispatchActionPayload(\n- clearDeliveredClientResponsesActionType,\n- { clientResponses },\n- );\n- } else {\n- const newPromise = this.sendClientResponses(clientResponses);\n- await this.handleQueuedClientResponses(\n- newPromise,\n- clientResponses,\n- retriesLeft - 1,\n- );\n- }\n- }\n- }\n-\n- sendAndHandleClientResponsesToServerRequests(\n- clientResponses: $ReadOnlyArray<ClientResponse>,\n- ) {\n- if (clientResponses.length === 0) {\n- return;\n- }\n- const promise = this.sendClientResponses(clientResponses);\n- this.handleClientResponsesToServerRequests(promise, clientResponses);\n- }\n-\n- async handleClientResponsesToServerRequests(\n- promise: Promise<RequestsServerSocketMessage>,\n- clientResponses: $ReadOnlyArray<ClientResponse>,\n- retriesLeft: number = 1,\n- ): Promise<void> {\n- try {\n- const response = await promise;\n- const { serverRequests } = response.payload;\n- this.processServerRequests(serverRequests);\n- } catch (e) {\n- console.log(e);\n- if (\n- !(e instanceof SocketTimeout) &&\n- (!(e instanceof ServerError) || e.message === \"unknown_error\") &&\n- retriesLeft > 0 &&\n- this.props.connection.status === \"connected\"\n- ) {\n- // We'll only retry if the connection is healthy and the error is either\n- // an unknown_error ServerError or something is neither a ServerError\n- // nor a SocketTimeout.\n- const newPromise = this.sendClientResponses(clientResponses);\n- await this.handleClientResponsesToServerRequests(\n- newPromise,\n- clientResponses,\n- retriesLeft - 1,\n- );\n- }\n- }\n- }\n-\n- processServerRequests(serverRequests: $ReadOnlyArray<ServerRequest>) {\n- if (serverRequests.length === 0) {\n- return;\n- }\n- this.props.dispatchActionPayload(\n- processServerRequestsActionType,\n- { serverRequests },\n- );\n- const clientResponses = this.props.getClientResponses(serverRequests);\n- if (this.props.connection.status === \"connected\") {\n- this.sendAndHandleClientResponsesToServerRequests(clientResponses);\n- }\n- }\n-\n}\nexport default Socket;\n" }, { "change_type": "MODIFY", "old_path": "lib/types/socket-types.js", "new_path": "lib/types/socket-types.js", "diff": "@@ -181,6 +181,8 @@ export type ServerSocketMessage =\n| ActivityUpdateResponseServerSocketMessage\n| PongServerSocketMessage;\n+export type SocketListener = (message: ServerSocketMessage) => void;\n+\nexport type ConnectionStatus =\n| \"connecting\"\n| \"connected\"\n" }, { "change_type": "MODIFY", "old_path": "native/socket.react.js", "new_path": "native/socket.react.js", "diff": "@@ -5,7 +5,6 @@ import type { AppState } from './redux-setup';\nimport { connect } from 'lib/utils/redux-utils';\nimport {\nqueuedClientResponsesSelector,\n- getClientResponsesSelector,\nsessionStateFuncSelector,\n} from 'lib/selectors/socket-selectors';\nimport { logInExtraInfoSelector } from 'lib/selectors/account-selectors';\n@@ -30,7 +29,6 @@ export default connect(\nactive,\nopenSocket: openSocketSelector(state),\nqueuedClientResponses: queuedClientResponsesSelector(state),\n- getClientResponses: getClientResponsesSelector(state),\nactiveThread: active ? activeThreadSelector(state) : null,\nsessionStateFunc: sessionStateFuncSelector(state),\nsessionIdentification: sessionIdentificationSelector(state),\n" }, { "change_type": "MODIFY", "old_path": "web/socket.react.js", "new_path": "web/socket.react.js", "diff": "@@ -5,7 +5,6 @@ import type { AppState } from './redux-setup';\nimport { connect } from 'lib/utils/redux-utils';\nimport {\nqueuedClientResponsesSelector,\n- getClientResponsesSelector,\nsessionStateFuncSelector,\n} from 'lib/selectors/socket-selectors';\nimport { logInExtraInfoSelector } from 'lib/selectors/account-selectors';\n@@ -27,7 +26,6 @@ export default connect(\nactive,\nopenSocket: openSocketSelector(state),\nqueuedClientResponses: queuedClientResponsesSelector(state),\n- getClientResponses: getClientResponsesSelector(state),\nactiveThread: active ? activeThreadSelector(state) : null,\nsessionStateFunc: sessionStateFuncSelector(state),\nsessionIdentification: sessionIdentificationSelector(state),\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Extract ClientResponses logic from Socket into ClientResponseMaintainer
129,187
02.11.2018 17:17:27
14,400
36c1cd63df514bdd4c9f989690064ab4bc5483dd
Prevent user from being logged in while their currentUserInfo indicates otherwise This makes sure the nav state is consistent with the `currentUserInfo` state. Also includes a Socket bugfix to prevent the web from crashing on `AUTH_ERROR`.
[ { "change_type": "MODIFY", "old_path": "lib/utils/action-utils.js", "new_path": "lib/utils/action-utils.js", "diff": "@@ -180,6 +180,10 @@ async function fetchNewCookieFromNativeCredentials(\nsource: LogInActionSource,\nlogInExtraInfo: () => LogInExtraInfo,\n): Promise<?ClientSessionChange> {\n+ const resolveInvalidatedCookie = getConfig().resolveInvalidatedCookie;\n+ if (!resolveInvalidatedCookie) {\n+ return null;\n+ }\nlet newSessionChange = null;\nlet fetchJSONCallback = null;\nconst boundFetchJSON = async (\n@@ -230,11 +234,6 @@ async function fetchNewCookieFromNativeCredentials(\ndispatch(wrapActionPromise(actionTypes, promise, null, startingPayload));\nreturn new Promise(r => fetchJSONCallback = r);\n};\n- const resolveInvalidatedCookie = getConfig().resolveInvalidatedCookie;\n- invariant(\n- resolveInvalidatedCookie,\n- \"cookieInvalidationRecovery should check this before it calls us\",\n- );\nawait resolveInvalidatedCookie(\nboundFetchJSON,\ndispatchRecoveryAttempt,\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/navigation-setup.js", "new_path": "native/navigation/navigation-setup.js", "diff": "@@ -816,4 +816,5 @@ export {\ndefaultNavInfo,\nreduceNavInfo,\nremoveScreensFromStack,\n+ resetNavInfoAndEnsureLoggedOutModalPresence,\n};\n" }, { "change_type": "MODIFY", "old_path": "native/redux-setup.js", "new_path": "native/redux-setup.js", "diff": "@@ -60,6 +60,7 @@ import {\ndefaultNavInfo,\nreduceNavInfo,\nremoveScreensFromStack,\n+ resetNavInfoAndEnsureLoggedOutModalPresence,\n} from './navigation/navigation-setup';\nimport {\nreduceThreadIDsToNotifIDs,\n@@ -362,6 +363,13 @@ function validateState(\n};\n}\n+ if (!state.currentUserInfo || state.currentUserInfo.anonymous) {\n+ const navInfo = resetNavInfoAndEnsureLoggedOutModalPresence(state.navInfo);\n+ if (navInfo.navigationState !== state.navInfo.navigationState) {\n+ state = { ...state, navInfo };\n+ }\n+ }\n+\nreturn state;\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Prevent user from being logged in while their currentUserInfo indicates otherwise This makes sure the nav state is consistent with the `currentUserInfo` state. Also includes a Socket bugfix to prevent the web from crashing on `AUTH_ERROR`.
129,187
02.11.2018 17:42:26
14,400
7d6fe998573d0a8e409dfe6cbe34eaa3bfab9ea6
Hit logOut in Socket when a new anonymous cookie is needed
[ { "change_type": "MODIFY", "old_path": "lib/socket/socket.react.js", "new_path": "lib/socket/socket.react.js", "diff": "@@ -31,8 +31,11 @@ import {\ntype SocketListener,\n} from '../types/socket-types';\nimport type { Dispatch } from '../types/redux-types';\n-import type { DispatchActionPayload } from '../utils/action-utils';\n-import type { LogInExtraInfo } from '../types/account-types';\n+import type {\n+ DispatchActionPayload,\n+ DispatchActionPromise,\n+} from '../utils/action-utils';\n+import type { LogInExtraInfo, LogOutResult } from '../types/account-types';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n@@ -52,6 +55,7 @@ import { promiseAll } from '../utils/promises';\nimport { InflightRequests, SocketTimeout } from './inflight-requests';\nimport ActivityMaintainer from './activity-maintainer.react';\nimport ClientResponseMaintainer from './client-response-maintainer.react';\n+import { logOutActionTypes } from '../actions/user-actions';\ntype Props = {|\n// Redux state\n@@ -68,6 +72,9 @@ type Props = {|\n// Redux dispatch functions\ndispatch: Dispatch,\ndispatchActionPayload: DispatchActionPayload,\n+ dispatchActionPromise: DispatchActionPromise,\n+ // async functions that hit server APIs\n+ logOut: () => Promise<LogOutResult>,\n|};\ntype State = {|\ninflightRequests: ?InflightRequests,\n@@ -87,6 +94,8 @@ class Socket extends React.PureComponent<Props, State> {\nconnection: connectionInfoPropType.isRequired,\ndispatch: PropTypes.func.isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\n+ dispatchActionPromise: PropTypes.func.isRequired,\n+ logOut: PropTypes.func.isRequired,\n};\nstate = {\ninflightRequests: null,\n@@ -350,6 +359,11 @@ class Socket extends React.PureComponent<Props, State> {\nerror: null,\n},\n);\n+ } else if (!recoverySessionChange) {\n+ this.props.dispatchActionPromise(\n+ logOutActionTypes,\n+ this.props.logOut(),\n+ );\n}\n}\n}\n@@ -528,7 +542,12 @@ class Socket extends React.PureComponent<Props, State> {\nretriesLeft === 0 ||\n(e instanceof ServerError && e.message !== \"unknown_error\")\n) {\n- if (this.socket) {\n+ if (e.message === \"not_logged_in\") {\n+ this.props.dispatchActionPromise(\n+ logOutActionTypes,\n+ this.props.logOut(),\n+ );\n+ } else if (this.socket) {\nthis.socket.close();\n}\n} else {\n" }, { "change_type": "MODIFY", "old_path": "native/socket.react.js", "new_path": "native/socket.react.js", "diff": "@@ -8,6 +8,7 @@ import {\nsessionStateFuncSelector,\n} from 'lib/selectors/socket-selectors';\nimport { logInExtraInfoSelector } from 'lib/selectors/account-selectors';\n+import { logOut } from 'lib/actions/user-actions';\nimport Socket from 'lib/socket/socket.react';\nimport {\n@@ -38,6 +39,5 @@ export default connect(\nconnection: state.connection,\n};\n},\n- null,\n- true,\n+ { logOut },\n)(Socket);\n" }, { "change_type": "MODIFY", "old_path": "web/socket.react.js", "new_path": "web/socket.react.js", "diff": "@@ -8,6 +8,7 @@ import {\nsessionStateFuncSelector,\n} from 'lib/selectors/socket-selectors';\nimport { logInExtraInfoSelector } from 'lib/selectors/account-selectors';\n+import { logOut } from 'lib/actions/user-actions';\nimport Socket from 'lib/socket/socket.react';\nimport {\n@@ -35,6 +36,5 @@ export default connect(\nconnection: state.connection,\n};\n},\n- null,\n- true,\n+ { logOut },\n)(Socket);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Hit logOut in Socket when a new anonymous cookie is needed
129,187
02.11.2018 23:25:53
14,400
33d0f0a73089e7c01a0a34d0fa06ce2d31dde360
Use "reconnecting" ConnectionStatus in reconnect This will trigger a red bar to inform the user of the connection issue.
[ { "change_type": "MODIFY", "old_path": "lib/socket/socket.react.js", "new_path": "lib/socket/socket.react.js", "diff": "@@ -29,6 +29,7 @@ import {\ntype PingClientSocketMessage,\ntype ClientSocketMessageWithoutID,\ntype SocketListener,\n+ type ConnectionStatus,\n} from '../types/socket-types';\nimport type { Dispatch } from '../types/redux-types';\nimport type {\n@@ -107,7 +108,7 @@ class Socket extends React.PureComponent<Props, State> {\ninitialPlatformDetailsSent = false;\nreopenConnectionAfterClosing = false;\n- openSocket = () => {\n+ openSocket(newStatus: ConnectionStatus) {\nif (this.socket) {\nconst { status } = this.props.connection;\nif (status === \"forcedDisconnecting\") {\n@@ -130,7 +131,7 @@ class Socket extends React.PureComponent<Props, State> {\n}\nthis.props.dispatchActionPayload(\nupdateConnectionStatusActionType,\n- { status: \"connecting\" },\n+ { status: newStatus },\n);\nconst socket = this.props.openSocket();\nsocket.onopen = () => {\n@@ -215,16 +216,18 @@ class Socket extends React.PureComponent<Props, State> {\nif (this.reopenConnectionAfterClosing) {\nthis.reopenConnectionAfterClosing = false;\nif (this.props.active) {\n- this.openSocket();\n+ this.openSocket(\"connecting\");\n}\n}\n}\n- reconnect = _debounce(2000)(this.openSocket)\n+ reconnect = _debounce(2000)(() => {\n+ this.openSocket(\"reconnecting\");\n+ })\ncomponentDidMount() {\nif (this.props.active) {\n- this.openSocket();\n+ this.openSocket(\"connecting\");\n}\n}\n@@ -234,7 +237,7 @@ class Socket extends React.PureComponent<Props, State> {\ncomponentDidUpdate(prevProps: Props) {\nif (this.props.active && !prevProps.active) {\n- this.openSocket();\n+ this.openSocket(\"connecting\");\n} else if (!this.props.active && prevProps.active) {\nthis.closeSocket();\n} else if (\n@@ -532,9 +535,10 @@ class Socket extends React.PureComponent<Props, State> {\nawait this.sendInitialMessage();\n} catch (e) {\nconsole.log(e);\n+ const { status } = this.props.connection;\nif (\ne instanceof SocketTimeout ||\n- this.props.connection.status !== \"connecting\"\n+ (status !== \"connecting\" && status !== \"reconnecting\")\n) {\n// This indicates that the socket will be closed. Do nothing, since the\n// connection status update will trigger a reconnect.\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Use "reconnecting" ConnectionStatus in reconnect This will trigger a red bar to inform the user of the connection issue.
129,187
03.11.2018 13:58:15
14,400
e9baa498b4db8aeb5d0c4621dbc989ff49bced35
[server] Move socket to its own folder
[ { "change_type": "MODIFY", "old_path": "server/src/server.js", "new_path": "server/src/server.js", "diff": "@@ -61,7 +61,7 @@ import {\nerrorReportFetchInfosResponder,\nerrorReportDownloadHandler,\n} from './responders/report-responders';\n-import { onConnection } from './socket';\n+import { onConnection } from './socket/socket';\nimport urlFacts from '../facts/url';\nimport './cron';\n" }, { "change_type": "RENAME", "old_path": "server/src/socket.js", "new_path": "server/src/socket/socket.js", "diff": "@@ -30,46 +30,46 @@ import { promiseAll } from 'lib/utils/promises';\nimport { values } from 'lib/utils/objects';\nimport { serverRequestSocketTimeout } from 'lib/shared/timeouts';\n-import { Viewer } from './session/viewer';\n+import { Viewer } from '../session/viewer';\nimport {\ncheckInputValidator,\ncheckClientSupported,\ntShape,\ntCookie,\n-} from './utils/validation-utils';\n+} from '../utils/validation-utils';\nimport {\nnewEntryQueryInputValidator,\nverifyCalendarQueryThreadIDs,\n-} from './responders/entry-responders';\n+} from '../responders/entry-responders';\nimport {\nclientResponseInputValidator,\nprocessClientResponses,\ninitializeSession,\ncheckState,\n-} from './responders/ping-responders';\n-import { assertSecureRequest } from './utils/security-utils';\n-import { fetchViewerForSocket, extendCookieLifespan } from './session/cookies';\n-import { fetchMessageInfosSince } from './fetchers/message-fetchers';\n-import { fetchThreadInfos } from './fetchers/thread-fetchers';\n-import { fetchEntryInfos } from './fetchers/entry-fetchers';\n-import { fetchCurrentUserInfo } from './fetchers/user-fetchers';\n+} from '../responders/ping-responders';\n+import { assertSecureRequest } from '../utils/security-utils';\n+import { fetchViewerForSocket, extendCookieLifespan } from '../session/cookies';\n+import { fetchMessageInfosSince } from '../fetchers/message-fetchers';\n+import { fetchThreadInfos } from '../fetchers/thread-fetchers';\n+import { fetchEntryInfos } from '../fetchers/entry-fetchers';\n+import { fetchCurrentUserInfo } from '../fetchers/user-fetchers';\nimport {\nupdateActivityTime,\nactivityUpdater,\n-} from './updaters/activity-updaters';\n+} from '../updaters/activity-updaters';\nimport {\ndeleteUpdatesBeforeTimeTargettingSession,\n-} from './deleters/update-deleters';\n-import { fetchUpdateInfos } from './fetchers/update-fetchers';\n-import { commitSessionUpdate } from './updaters/session-updaters';\n-import { handleAsyncPromise } from './responders/handlers';\n-import { deleteCookie } from './deleters/cookie-deleters';\n-import { createNewAnonymousCookie } from './session/cookies';\n-import { deleteActivityForViewerSession } from './deleters/activity-deleters';\n+} from '../deleters/update-deleters';\n+import { fetchUpdateInfos } from '../fetchers/update-fetchers';\n+import { commitSessionUpdate } from '../updaters/session-updaters';\n+import { handleAsyncPromise } from '../responders/handlers';\n+import { deleteCookie } from '../deleters/cookie-deleters';\n+import { createNewAnonymousCookie } from '../session/cookies';\n+import { deleteActivityForViewerSession } from '../deleters/activity-deleters';\nimport {\nactivityUpdatesInputValidator,\n-} from './responders/activity-responders';\n-import { focusedTableRefreshFrequency } from './shared/focused-times';\n+} from '../responders/activity-responders';\n+import { focusedTableRefreshFrequency } from '../shared/focused-times';\nconst timeoutSeconds = serverRequestSocketTimeout / 1000;\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Move socket to its own folder
129,187
03.11.2018 16:58:18
14,400
1a4b410cc82a2a1aacd31bed0022db75d9b7d64d
Use Redis to keep one socket open for session
[ { "change_type": "MODIFY", "old_path": "lib/socket/socket.react.js", "new_path": "lib/socket/socket.react.js", "diff": "@@ -299,7 +299,7 @@ class Socket extends React.PureComponent<Props, State> {\nsocket.send(JSON.stringify(message));\n}\n- messageFromEvent(event: MessageEvent): ?ServerSocketMessage {\n+ static messageFromEvent(event: MessageEvent): ?ServerSocketMessage {\nif (typeof event.data !== \"string\") {\nconsole.log('socket received a non-string message');\nreturn null;\n@@ -313,7 +313,7 @@ class Socket extends React.PureComponent<Props, State> {\n}\nreceiveMessage = async (event: MessageEvent) => {\n- const message = this.messageFromEvent(event);\n+ const message = Socket.messageFromEvent(event);\nif (!message) {\nreturn;\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "lib/types/redis-types.js", "diff": "+// @flow\n+\n+import type { UpdateData } from './update-types';\n+\n+// The types of messages that can be published to Redis\n+export const redisMessageTypes = Object.freeze({\n+ START_SUBSCRIPTION: 0,\n+ NEW_UPDATES: 1,\n+});\n+export type RedisMessageTypes = $Values<typeof redisMessageTypes>;\n+\n+// This message is sent to a session channel indicating that a client just\n+// connected with this session ID. Since there should only ever be a single\n+// session active for a given sessionID, this message tells all sessions with a\n+// different instanceID to terminate their sockets.\n+type StartSubscriptionRedisMessage = {|\n+ type: 0,\n+ instanceID: string,\n+|};\n+\n+type NewUpdatesRedisMessage = {|\n+ type: 1,\n+ updates: $ReadOnlyArray<UpdateData>,\n+|};\n+\n+export type RedisMessage =\n+ | StartSubscriptionRedisMessage\n+ | NewUpdatesRedisMessage;\n+\n+export type UpdateTarget = {| userID: string, +sessionID?: string |};\n+export type SessionIdentifier = {| userID: string, sessionID: string |};\n" }, { "change_type": "MODIFY", "old_path": "native/ios/SquadCal.xcodeproj/project.pbxproj", "new_path": "native/ios/SquadCal.xcodeproj/project.pbxproj", "diff": "};\nobjectVersion = 46;\nobjects = {\n+\n/* Begin PBXBuildFile section */\n00C302E51ABCBA2D00DB3ED1 /* libRCTActionSheet.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302AC1ABCB8CE00DB3ED1 /* libRCTActionSheet.a */; };\n00C302E71ABCBA2D00DB3ED1 /* libRCTGeolocation.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302BA1ABCB90400DB3ED1 /* libRCTGeolocation.a */; };\n00C302E91ABCBA2D00DB3ED1 /* libRCTNetwork.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302DC1ABCB9D200DB3ED1 /* libRCTNetwork.a */; };\n00C302EA1ABCBA2D00DB3ED1 /* libRCTVibration.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302E41ABCB9EE00DB3ED1 /* libRCTVibration.a */; };\n00E356F31AD99517003FC87E /* SquadCalTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 00E356F21AD99517003FC87E /* SquadCalTests.m */; };\n+ 09369EAAB869410E9C0208B4 /* Feather.ttf in Resources */ = {isa = PBXBuildFile; fileRef = A06F10E4481746D2B76CA60E /* Feather.ttf */; };\n133E29F31AD74F7200F7D852 /* libRCTLinking.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 78C398B91ACF4ADC00677621 /* libRCTLinking.a */; };\n139105C61AF99C1200B5F7CC /* libRCTSettings.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 139105C11AF99BAD00B5F7CC /* libRCTSettings.a */; };\n139FDEF61B0652A700C62182 /* libRCTWebSocket.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 139FDEF41B06529B00C62182 /* libRCTWebSocket.a */; };\n8894ACD632254222B23F69E2 /* Ionicons.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 4ACC468F28D944F293B91ACC /* Ionicons.ttf */; };\n9985FC0D9B2A43E49A4C1789 /* FontAwesome.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 4AB1FC0EFD3A4ED1A082E32F /* FontAwesome.ttf */; };\nA1145AA76F5B4EF5B3ACB31D /* MaterialIcons.ttf in Resources */ = {isa = PBXBuildFile; fileRef = E4E90F44E9F4420080594671 /* MaterialIcons.ttf */; };\n+ A6EF57DD8BDA4D43812D0B13 /* libRNScreens.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7AAA81E566EC47C883CDFA61 /* libRNScreens.a */; };\nAFA44E75249D4766A4ED74C7 /* Octicons.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 2D04F3CCBAFF4A8184206FAC /* Octicons.ttf */; };\nBBC287C467984DA6BF85800E /* libSplashScreen.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 8B6A1FF570694BFCB0D65D0E /* libSplashScreen.a */; };\n- FA7F2215AD7646E2BE985BF3 /* SimpleLineIcons.ttf in Resources */ = {isa = PBXBuildFile; fileRef = AE31AFFF88FB4112A29ADE33 /* SimpleLineIcons.ttf */; };\n- 09369EAAB869410E9C0208B4 /* Feather.ttf in Resources */ = {isa = PBXBuildFile; fileRef = A06F10E4481746D2B76CA60E /* Feather.ttf */; };\nEFBA858A8D2B4909A08D9FE6 /* libRNGestureHandler.a in Frameworks */ = {isa = PBXBuildFile; fileRef = E0952482A8094CE88F96C0EB /* libRNGestureHandler.a */; };\n- A6EF57DD8BDA4D43812D0B13 /* libRNScreens.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7AAA81E566EC47C883CDFA61 /* libRNScreens.a */; };\n+ FA7F2215AD7646E2BE985BF3 /* SimpleLineIcons.ttf in Resources */ = {isa = PBXBuildFile; fileRef = AE31AFFF88FB4112A29ADE33 /* SimpleLineIcons.ttf */; };\n/* End PBXBuildFile section */\n/* Begin PBXContainerItemProxy section */\nremoteGlobalIDString = 134814201AA4EA6300B7C361;\nremoteInfo = RNNotifications;\n};\n+ 7FA2ABCF218E3FC5008EF068 /* PBXContainerItemProxy */ = {\n+ isa = PBXContainerItemProxy;\n+ containerPortal = 95EEFC35D4D14053ACA7E064 /* RNKeychain.xcodeproj */;\n+ proxyType = 2;\n+ remoteGlobalIDString = 6478985F1F38BF9100DA1C12;\n+ remoteInfo = \"RNKeychain-tvOS\";\n+ };\n+ 7FA2ABD9218E3FC5008EF068 /* PBXContainerItemProxy */ = {\n+ isa = PBXContainerItemProxy;\n+ containerPortal = ED28C047C454400D87062E8C /* RNGestureHandler.xcodeproj */;\n+ proxyType = 2;\n+ remoteGlobalIDString = 134814201AA4EA6300B7C361;\n+ remoteInfo = RNGestureHandler;\n+ };\n+ 7FA2ABDC218E3FC5008EF068 /* PBXContainerItemProxy */ = {\n+ isa = PBXContainerItemProxy;\n+ containerPortal = BA72871056D240AEB0706398 /* RNScreens.xcodeproj */;\n+ proxyType = 2;\n+ remoteGlobalIDString = 134814201AA4EA6300B7C361;\n+ remoteInfo = RNScreens;\n+ };\n7FABD008205730E8005F452B /* PBXContainerItemProxy */ = {\nisa = PBXContainerItemProxy;\ncontainerPortal = C2449EA8EFA9461DABF09B72 /* SplashScreen.xcodeproj */;\n4ACC468F28D944F293B91ACC /* Ionicons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Ionicons.ttf; path = \"../node_modules/react-native-vector-icons/Fonts/Ionicons.ttf\"; sourceTree = \"<group>\"; };\n5E91572D1DD0AC6500FF2AA8 /* RCTAnimation.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = \"wrapper.pb-project\"; name = RCTAnimation.xcodeproj; path = \"../node_modules/react-native/Libraries/NativeAnimation/RCTAnimation.xcodeproj\"; sourceTree = \"<group>\"; };\n78C398B01ACF4ADC00677621 /* RCTLinking.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = \"wrapper.pb-project\"; name = RCTLinking.xcodeproj; path = \"../node_modules/react-native/Libraries/LinkingIOS/RCTLinking.xcodeproj\"; sourceTree = \"<group>\"; };\n+ 7AAA81E566EC47C883CDFA61 /* libRNScreens.a */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = archive.ar; path = libRNScreens.a; sourceTree = \"<group>\"; };\n7FB58ABB1E7F6BC600B4C1B1 /* Anaheim-Regular.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = \"Anaheim-Regular.ttf\"; sourceTree = \"<group>\"; };\n7FB58ABC1E7F6BC600B4C1B1 /* OpenSans-Regular.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = \"OpenSans-Regular.ttf\"; sourceTree = \"<group>\"; };\n7FB58ABD1E7F6BC600B4C1B1 /* OpenSans-Semibold.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = \"OpenSans-Semibold.ttf\"; sourceTree = \"<group>\"; };\n8D919BA72D8545CBBBF6B74F /* MaterialCommunityIcons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = MaterialCommunityIcons.ttf; path = \"../node_modules/react-native-vector-icons/Fonts/MaterialCommunityIcons.ttf\"; sourceTree = \"<group>\"; };\n95EA49951E064ECB9B1999EA /* libRNExitApp.a */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = archive.ar; path = libRNExitApp.a; sourceTree = \"<group>\"; };\n95EEFC35D4D14053ACA7E064 /* RNKeychain.xcodeproj */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = \"wrapper.pb-project\"; name = RNKeychain.xcodeproj; path = \"../node_modules/react-native-keychain/RNKeychain.xcodeproj\"; sourceTree = \"<group>\"; };\n+ A06F10E4481746D2B76CA60E /* Feather.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Feather.ttf; path = \"../node_modules/react-native-vector-icons/Fonts/Feather.ttf\"; sourceTree = \"<group>\"; };\nAE31AFFF88FB4112A29ADE33 /* SimpleLineIcons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = SimpleLineIcons.ttf; path = \"../node_modules/react-native-vector-icons/Fonts/SimpleLineIcons.ttf\"; sourceTree = \"<group>\"; };\n+ BA72871056D240AEB0706398 /* RNScreens.xcodeproj */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = \"wrapper.pb-project\"; name = RNScreens.xcodeproj; path = \"../node_modules/react-native-screens/ios/RNScreens.xcodeproj\"; sourceTree = \"<group>\"; };\nC2449EA8EFA9461DABF09B72 /* SplashScreen.xcodeproj */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = \"wrapper.pb-project\"; name = SplashScreen.xcodeproj; path = \"../node_modules/react-native-splash-screen/ios/SplashScreen.xcodeproj\"; sourceTree = \"<group>\"; };\nC3BA31E561EB497494D7882F /* RNVectorIcons.xcodeproj */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = \"wrapper.pb-project\"; name = RNVectorIcons.xcodeproj; path = \"../node_modules/react-native-vector-icons/RNVectorIcons.xcodeproj\"; sourceTree = \"<group>\"; };\n+ E0952482A8094CE88F96C0EB /* libRNGestureHandler.a */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = archive.ar; path = libRNGestureHandler.a; sourceTree = \"<group>\"; };\nE4E90F44E9F4420080594671 /* MaterialIcons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = MaterialIcons.ttf; path = \"../node_modules/react-native-vector-icons/Fonts/MaterialIcons.ttf\"; sourceTree = \"<group>\"; };\nE7D7D614C3184B1BB95EE661 /* OnePassword.xcodeproj */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = \"wrapper.pb-project\"; name = OnePassword.xcodeproj; path = \"../node_modules/react-native-onepassword/OnePassword.xcodeproj\"; sourceTree = \"<group>\"; };\nEA40FBBA484449FAA8915A48 /* Foundation.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Foundation.ttf; path = \"../node_modules/react-native-vector-icons/Fonts/Foundation.ttf\"; sourceTree = \"<group>\"; };\nEBD8879422144B0188A8336F /* Zocial.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Zocial.ttf; path = \"../node_modules/react-native-vector-icons/Fonts/Zocial.ttf\"; sourceTree = \"<group>\"; };\n- A06F10E4481746D2B76CA60E /* Feather.ttf */ = {isa = PBXFileReference; name = \"Feather.ttf\"; path = \"../node_modules/react-native-vector-icons/Fonts/Feather.ttf\"; sourceTree = \"<group>\"; fileEncoding = undefined; lastKnownFileType = unknown; explicitFileType = undefined; includeInIndex = 0; };\n- ED28C047C454400D87062E8C /* RNGestureHandler.xcodeproj */ = {isa = PBXFileReference; name = \"RNGestureHandler.xcodeproj\"; path = \"../node_modules/react-native-gesture-handler/ios/RNGestureHandler.xcodeproj\"; sourceTree = \"<group>\"; fileEncoding = undefined; lastKnownFileType = wrapper.pb-project; explicitFileType = undefined; includeInIndex = 0; };\n- E0952482A8094CE88F96C0EB /* libRNGestureHandler.a */ = {isa = PBXFileReference; name = \"libRNGestureHandler.a\"; path = \"libRNGestureHandler.a\"; sourceTree = \"<group>\"; fileEncoding = undefined; lastKnownFileType = archive.ar; explicitFileType = undefined; includeInIndex = 0; };\n- BA72871056D240AEB0706398 /* RNScreens.xcodeproj */ = {isa = PBXFileReference; name = \"RNScreens.xcodeproj\"; path = \"../node_modules/react-native-screens/ios/RNScreens.xcodeproj\"; sourceTree = \"<group>\"; fileEncoding = undefined; lastKnownFileType = wrapper.pb-project; explicitFileType = undefined; includeInIndex = 0; };\n- 7AAA81E566EC47C883CDFA61 /* libRNScreens.a */ = {isa = PBXFileReference; name = \"libRNScreens.a\"; path = \"libRNScreens.a\"; sourceTree = \"<group>\"; fileEncoding = undefined; lastKnownFileType = archive.ar; explicitFileType = undefined; includeInIndex = 0; };\n+ ED28C047C454400D87062E8C /* RNGestureHandler.xcodeproj */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = \"wrapper.pb-project\"; name = RNGestureHandler.xcodeproj; path = \"../node_modules/react-native-gesture-handler/ios/RNGestureHandler.xcodeproj\"; sourceTree = \"<group>\"; };\n/* End PBXFileReference section */\n/* Begin PBXFrameworksBuildPhase section */\nchildren = (\n95EA49951E064ECB9B1999EA /* libRNExitApp.a */,\n8B6A1FF570694BFCB0D65D0E /* libSplashScreen.a */,\n+ E0952482A8094CE88F96C0EB /* libRNGestureHandler.a */,\n+ 7AAA81E566EC47C883CDFA61 /* libRNScreens.a */,\n);\nname = \"Recovered References\";\nsourceTree = \"<group>\";\nname = Products;\nsourceTree = \"<group>\";\n};\n+ 7FA2ABD4218E3FC5008EF068 /* Products */ = {\n+ isa = PBXGroup;\n+ children = (\n+ 7FA2ABDD218E3FC5008EF068 /* libRNScreens.a */,\n+ );\n+ name = Products;\n+ sourceTree = \"<group>\";\n+ };\n+ 7FA2ABD6218E3FC5008EF068 /* Products */ = {\n+ isa = PBXGroup;\n+ children = (\n+ 7FA2ABDA218E3FC5008EF068 /* libRNGestureHandler.a */,\n+ );\n+ name = Products;\n+ sourceTree = \"<group>\";\n+ };\n7FABCFDD205730E8005F452B /* Products */ = {\nisa = PBXGroup;\nchildren = (\nisa = PBXGroup;\nchildren = (\n7FEB2DEC1E8D64D200C4B763 /* libRNKeychain.a */,\n+ 7FA2ABD0218E3FC5008EF068 /* libRNKeychain.a */,\n);\nname = Products;\nsourceTree = \"<group>\";\nProductGroup = 7F3DD40720521A4C00A0D652 /* Products */;\nProjectRef = 220AE3F9742647538AAD1DD7 /* RNExitApp.xcodeproj */;\n},\n+ {\n+ ProductGroup = 7FA2ABD6218E3FC5008EF068 /* Products */;\n+ ProjectRef = ED28C047C454400D87062E8C /* RNGestureHandler.xcodeproj */;\n+ },\n{\nProductGroup = 7FEB2DCE1E8D64D200C4B763 /* Products */;\nProjectRef = 95EEFC35D4D14053ACA7E064 /* RNKeychain.xcodeproj */;\nProductGroup = 7F5B10E52005349D00FE096A /* Products */;\nProjectRef = 143FA99006A442AFB7B24B3A /* RNNotifications.xcodeproj */;\n},\n+ {\n+ ProductGroup = 7FA2ABD4218E3FC5008EF068 /* Products */;\n+ ProjectRef = BA72871056D240AEB0706398 /* RNScreens.xcodeproj */;\n+ },\n{\nProductGroup = 7FB58A9D1E7F6B4300B4C1B1 /* Products */;\nProjectRef = C3BA31E561EB497494D7882F /* RNVectorIcons.xcodeproj */;\nremoteRef = 7F5B10E82005349D00FE096A /* PBXContainerItemProxy */;\nsourceTree = BUILT_PRODUCTS_DIR;\n};\n+ 7FA2ABD0218E3FC5008EF068 /* libRNKeychain.a */ = {\n+ isa = PBXReferenceProxy;\n+ fileType = archive.ar;\n+ path = libRNKeychain.a;\n+ remoteRef = 7FA2ABCF218E3FC5008EF068 /* PBXContainerItemProxy */;\n+ sourceTree = BUILT_PRODUCTS_DIR;\n+ };\n+ 7FA2ABDA218E3FC5008EF068 /* libRNGestureHandler.a */ = {\n+ isa = PBXReferenceProxy;\n+ fileType = archive.ar;\n+ path = libRNGestureHandler.a;\n+ remoteRef = 7FA2ABD9218E3FC5008EF068 /* PBXContainerItemProxy */;\n+ sourceTree = BUILT_PRODUCTS_DIR;\n+ };\n+ 7FA2ABDD218E3FC5008EF068 /* libRNScreens.a */ = {\n+ isa = PBXReferenceProxy;\n+ fileType = archive.ar;\n+ path = libRNScreens.a;\n+ remoteRef = 7FA2ABDC218E3FC5008EF068 /* PBXContainerItemProxy */;\n+ sourceTree = BUILT_PRODUCTS_DIR;\n+ };\n7FABD009205730E8005F452B /* libSplashScreen.a */ = {\nisa = PBXReferenceProxy;\nfileType = archive.ar;\n" }, { "change_type": "MODIFY", "old_path": "server/flow-typed/npm/ws_vx.x.x.js", "new_path": "server/flow-typed/npm/ws_vx.x.x.js", "diff": "@@ -21,6 +21,7 @@ declare module 'ws' {\nsend: (value: string) => void,\nclose: (code?: number, reason?: string) => void,\nping: () => void,\n+ terminate: () => void,\n};\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "server/src/socket/redis.js", "diff": "+// @flow\n+\n+import type { RedisClient } from 'redis';\n+import {\n+ redisMessageTypes,\n+ type RedisMessage,\n+ type UpdateTarget,\n+ type SessionIdentifier,\n+} from 'lib/types/redis-types';\n+\n+import redis from 'redis';\n+import uuidv4 from 'uuid/v4';\n+\n+function channelNameForUpdateTarget(updateTarget: UpdateTarget): string {\n+ if (updateTarget.sessionID) {\n+ return `user.${updateTarget.userID}.${updateTarget.sessionID}`;\n+ } else {\n+ return `user.${updateTarget.userID}`;\n+ }\n+}\n+\n+class RedisPublisher {\n+\n+ pub: RedisClient;\n+\n+ constructor() {\n+ this.pub = redis.createClient();\n+ }\n+\n+ sendMessage(target: UpdateTarget, message: RedisMessage) {\n+ this.pub.publish(\n+ channelNameForUpdateTarget(target),\n+ JSON.stringify(message),\n+ );\n+ }\n+\n+}\n+const publisher = new RedisPublisher();\n+\n+type OnMessage = (message: RedisMessage) => void;\n+class RedisSubscriber {\n+\n+ sub: RedisClient;\n+ instanceID: string;\n+ onMessageCallback: OnMessage;\n+\n+ constructor(sessionIdentifier: SessionIdentifier, onMessage: OnMessage) {\n+ this.sub = redis.createClient();\n+ this.instanceID = uuidv4();\n+ this.onMessageCallback = onMessage;\n+\n+ const { userID } = sessionIdentifier;\n+ this.sub.subscribe(channelNameForUpdateTarget({ userID }));\n+ this.sub.subscribe(channelNameForUpdateTarget(sessionIdentifier));\n+\n+ publisher.sendMessage(\n+ sessionIdentifier,\n+ {\n+ type: redisMessageTypes.START_SUBSCRIPTION,\n+ instanceID: this.instanceID,\n+ },\n+ );\n+\n+ this.sub.on(\"message\", this.onMessage);\n+ }\n+\n+ static messageFromString(messageString: string): ?RedisMessage {\n+ try {\n+ return JSON.parse(messageString);\n+ } catch (e) {\n+ console.log(e);\n+ return null;\n+ }\n+ }\n+\n+ onMessage = (channel: string, messageString: string) => {\n+ const message = RedisSubscriber.messageFromString(messageString);\n+ if (!message) {\n+ return;\n+ }\n+ if (\n+ message.type === redisMessageTypes.START_SUBSCRIPTION &&\n+ message.instanceID === this.instanceID\n+ ) {\n+ return;\n+ } else {\n+ this.quit();\n+ }\n+ this.onMessageCallback(message);\n+ }\n+\n+ quit() {\n+ this.sub.quit();\n+ }\n+\n+}\n+\n+export {\n+ publisher,\n+ RedisSubscriber,\n+};\n" }, { "change_type": "MODIFY", "old_path": "server/src/socket/socket.js", "new_path": "server/src/socket/socket.js", "diff": "@@ -19,6 +19,7 @@ import {\nimport { cookieSources } from 'lib/types/session-types';\nimport { defaultNumberPerThread } from 'lib/types/message-types';\nimport { serverRequestTypes } from 'lib/types/request-types';\n+import { redisMessageTypes, type RedisMessage } from 'lib/types/redis-types';\nimport t from 'tcomb';\nimport invariant from 'invariant';\n@@ -70,8 +71,7 @@ import {\nactivityUpdatesInputValidator,\n} from '../responders/activity-responders';\nimport { focusedTableRefreshFrequency } from '../shared/focused-times';\n-\n-const timeoutSeconds = serverRequestSocketTimeout / 1000;\n+import { RedisSubscriber } from './redis';\nconst clientSocketMessageInputValidator = t.union([\ntShape({\n@@ -133,6 +133,8 @@ class Socket {\nws: WebSocket;\nhttpRequest: $Request;\nviewer: ?Viewer;\n+ redis: ?RedisSubscriber;\n+\nupdateActivityTimeIntervalID: ?IntervalID;\npingTimeoutID: ?TimeoutID;\n@@ -187,6 +189,12 @@ class Socket {\nclientSocketMessageInputValidator,\nclientSocketMessage,\n);\n+ if (!this.redis) {\n+ this.redis = new RedisSubscriber(\n+ { userID: viewer.userID, sessionID: viewer.session },\n+ this.onRedisMessage,\n+ );\n+ }\nconst serverResponses = await this.handleClientSocketMessage(\nclientSocketMessage,\n);\n@@ -294,6 +302,10 @@ class Socket {\nif (this.viewer && this.viewer.hasSessionInfo) {\nawait deleteActivityForViewerSession(this.viewer);\n}\n+ if (this.redis) {\n+ this.redis.quit();\n+ this.redis = null;\n+ }\n}\nsendMessage(message: ServerSocketMessage) {\n@@ -549,6 +561,12 @@ class Socket {\n}];\n}\n+ onRedisMessage = (message: RedisMessage) => {\n+ if (message.type === redisMessageTypes.START_SUBSCRIPTION) {\n+ this.ws.terminate();\n+ }\n+ }\n+\nonSuccessfulConnection() {\nthis.updateActivityTimeIntervalID = setInterval(\nthis.updateActivityTime,\n@@ -575,10 +593,7 @@ class Socket {\n}\ntimeout = () => {\n- this.ws.close(\n- 4103,\n- `no contact from client within ${timeoutSeconds}s span`,\n- );\n+ this.ws.terminate();\n}\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Use Redis to keep one socket open for session
129,187
03.11.2018 17:26:51
14,400
1640901efba0b67fa3e90567912f6921af439824
[server] Include isSocket on Viewer
[ { "change_type": "MODIFY", "old_path": "server/src/session/bots.js", "new_path": "server/src/session/bots.js", "diff": "@@ -20,6 +20,7 @@ function createBotViewer(userID: string): Viewer {\nthrow new ServerError('invalid_bot_id');\n}\nreturn new Viewer({\n+ isSocket: true,\nloggedIn: true,\nid: userID,\nplatformDetails: null,\n" }, { "change_type": "MODIFY", "old_path": "server/src/session/cookies.js", "new_path": "server/src/session/cookies.js", "diff": "@@ -44,6 +44,12 @@ function cookieIsExpired(lastUsed: number) {\nreturn lastUsed + cookieLifetime <= Date.now();\n}\n+type SessionParameterInfo = {|\n+ isSocket: bool,\n+ sessionID: ?string,\n+ sessionIdentifierType: SessionIdentifierType,\n+|};\n+\ntype FetchViewerResult =\n| {| type: \"valid\", viewer: Viewer |}\n| InvalidFetchViewerResult;\n@@ -53,14 +59,14 @@ type InvalidFetchViewerResult =\ntype: \"nonexistant\",\ncookieName: ?string,\ncookieSource: ?CookieSource,\n- sessionIdentifierType: SessionIdentifierType,\n+ sessionParameterInfo: SessionParameterInfo,\n|}\n| {|\ntype: \"invalidated\",\ncookieName: string,\ncookieID: string,\ncookieSource: CookieSource,\n- sessionIdentifierType: SessionIdentifierType,\n+ sessionParameterInfo: SessionParameterInfo,\nplatformDetails: ?PlatformDetails,\ndeviceToken: ?string,\n|};\n@@ -70,14 +76,13 @@ async function fetchUserViewer(\ncookieSource: CookieSource,\nsessionParameterInfo: SessionParameterInfo,\n): Promise<FetchViewerResult> {\n- const { sessionIdentifierType } = sessionParameterInfo;\nconst [ cookieID, cookiePassword ] = cookie.split(':');\nif (!cookieID || !cookiePassword) {\nreturn {\ntype: \"nonexistant\",\ncookieName: cookieTypes.USER,\ncookieSource,\n- sessionIdentifierType,\n+ sessionParameterInfo,\n};\n}\n@@ -95,7 +100,7 @@ async function fetchUserViewer(\ntype: \"nonexistant\",\ncookieName: cookieTypes.USER,\ncookieSource,\n- sessionIdentifierType,\n+ sessionParameterInfo,\n};\n}\n@@ -126,13 +131,14 @@ async function fetchUserViewer(\ncookieName: cookieTypes.USER,\ncookieID,\ncookieSource,\n- sessionIdentifierType,\n+ sessionParameterInfo,\nplatformDetails,\ndeviceToken,\n};\n}\nconst userID = cookieRow.user.toString();\nconst viewer = new Viewer({\n+ isSocket: sessionParameterInfo.isSocket,\nloggedIn: true,\nid: userID,\nplatformDetails,\n@@ -141,7 +147,7 @@ async function fetchUserViewer(\ncookieSource,\ncookieID,\ncookiePassword,\n- sessionIdentifierType,\n+ sessionIdentifierType: sessionParameterInfo.sessionIdentifierType,\nsessionID,\nsessionInfo,\nisBotViewer: false,\n@@ -154,14 +160,13 @@ async function fetchAnonymousViewer(\ncookieSource: CookieSource,\nsessionParameterInfo: SessionParameterInfo,\n): Promise<FetchViewerResult> {\n- const { sessionIdentifierType } = sessionParameterInfo;\nconst [ cookieID, cookiePassword ] = cookie.split(':');\nif (!cookieID || !cookiePassword) {\nreturn {\ntype: \"nonexistant\",\ncookieName: cookieTypes.ANONYMOUS,\ncookieSource,\n- sessionIdentifierType,\n+ sessionParameterInfo,\n};\n}\n@@ -179,7 +184,7 @@ async function fetchAnonymousViewer(\ntype: \"nonexistant\",\ncookieName: cookieTypes.ANONYMOUS,\ncookieSource,\n- sessionIdentifierType,\n+ sessionParameterInfo,\n};\n}\n@@ -210,12 +215,13 @@ async function fetchAnonymousViewer(\ncookieName: cookieTypes.ANONYMOUS,\ncookieID,\ncookieSource,\n- sessionIdentifierType,\n+ sessionParameterInfo,\nplatformDetails,\ndeviceToken,\n};\n}\nconst viewer = new Viewer({\n+ isSocket: sessionParameterInfo.isSocket,\nloggedIn: false,\nid: cookieID,\nplatformDetails,\n@@ -223,7 +229,7 @@ async function fetchAnonymousViewer(\ncookieSource,\ncookieID,\ncookiePassword,\n- sessionIdentifierType,\n+ sessionIdentifierType: sessionParameterInfo.sessionIdentifierType,\nsessionID,\nsessionInfo,\nisBotViewer: false,\n@@ -231,11 +237,6 @@ async function fetchAnonymousViewer(\nreturn { type: \"valid\", viewer };\n}\n-type SessionParameterInfo = {|\n- sessionID: ?string,\n- sessionIdentifierType: SessionIdentifierType,\n-|};\n-\ntype SessionInfo = {|\nsessionID: ?string,\nlastValidated: number,\n@@ -291,7 +292,7 @@ async function fetchViewerFromCookieData(\ntype: \"nonexistant\",\ncookieName: null,\ncookieSource: null,\n- sessionIdentifierType: sessionParameterInfo.sessionIdentifierType,\n+ sessionParameterInfo,\n};\n}\n@@ -304,7 +305,7 @@ async function fetchViewerFromRequestBody(\ntype: \"nonexistant\",\ncookieName: null,\ncookieSource: null,\n- sessionIdentifierType: sessionParameterInfo.sessionIdentifierType,\n+ sessionParameterInfo,\n};\n}\nconst cookiePair = body.cookie;\n@@ -313,7 +314,7 @@ async function fetchViewerFromRequestBody(\ntype: \"nonexistant\",\ncookieName: null,\ncookieSource: cookieSources.BODY,\n- sessionIdentifierType: sessionParameterInfo.sessionIdentifierType,\n+ sessionParameterInfo,\n};\n}\nif (!cookiePair || typeof cookiePair !== \"string\") {\n@@ -321,7 +322,7 @@ async function fetchViewerFromRequestBody(\ntype: \"nonexistant\",\ncookieName: null,\ncookieSource: null,\n- sessionIdentifierType: sessionParameterInfo.sessionIdentifierType,\n+ sessionParameterInfo,\n};\n}\nconst [ type, cookie ] = cookiePair.split(\"=\");\n@@ -342,7 +343,7 @@ async function fetchViewerFromRequestBody(\ntype: \"nonexistant\",\ncookieName: null,\ncookieSource: null,\n- sessionIdentifierType: sessionParameterInfo.sessionIdentifierType,\n+ sessionParameterInfo,\n};\n}\n@@ -356,7 +357,7 @@ function getSessionParameterInfoFromRequestBody(\nconst sessionIdentifierType = req.method === \"GET\" || sessionID !== undefined\n? sessionIdentifierTypes.BODY_SESSION_ID\n: sessionIdentifierTypes.COOKIE_ID;\n- return { sessionID, sessionIdentifierType };\n+ return { isSocket: false, sessionID, sessionIdentifierType };\n}\nasync function fetchViewerForJSONRequest(req: $Request): Promise<Viewer> {\n@@ -388,6 +389,7 @@ async function fetchViewerForSocket(\nconst { sessionIdentification } = clientMessage.payload;\nconst { sessionID } = sessionIdentification;\nconst sessionParameterInfo = {\n+ isSocket: true,\nsessionID,\nsessionIdentifierType: sessionID !== undefined\n? sessionIdentifierTypes.BODY_SESSION_ID\n@@ -477,7 +479,8 @@ function createViewerForInvalidFetchViewerResult(\nconst viewer = new Viewer({\n...anonymousViewerData,\ncookieSource,\n- sessionIdentifierType: result.sessionIdentifierType,\n+ sessionIdentifierType: result.sessionParameterInfo.sessionIdentifierType,\n+ isSocket: result.sessionParameterInfo.isSocket,\n});\nviewer.sessionChanged = true;\n" }, { "change_type": "MODIFY", "old_path": "server/src/session/viewer.js", "new_path": "server/src/session/viewer.js", "diff": "@@ -27,6 +27,7 @@ export type UserViewerData = {|\n+sessionID: ?string,\n+sessionInfo: ?SessionInfo,\n+isBotViewer: bool,\n+ +isSocket?: bool,\n|};\nexport type AnonymousViewerData = {|\n@@ -42,6 +43,7 @@ export type AnonymousViewerData = {|\n+sessionID: ?string,\n+sessionInfo: ?SessionInfo,\n+isBotViewer: bool,\n+ +isSocket?: bool,\n|};\ntype SessionInfo = {|\n@@ -93,6 +95,14 @@ class Viewer {\ndata = { ...data, sessionIdentifierType: this.sessionIdentifierType };\n}\n}\n+ if (data.isSocket === null || data.isSocket === undefined) {\n+ if (data.loggedIn) {\n+ data = { ...data, isSocket: this.isSocket };\n+ } else {\n+ // This is a separate condition because of Flow\n+ data = { ...data, isSocket: this.isSocket };\n+ }\n+ }\nthis.data = data;\nthis.sessionChanged = true;\n@@ -267,6 +277,14 @@ class Viewer {\nreturn this.data.isBotViewer;\n}\n+ get isSocket(): bool {\n+ invariant(\n+ this.data.isSocket !== null && this.data.isSocket !== undefined,\n+ \"isSocket should be set\",\n+ );\n+ return this.data.isSocket;\n+ }\n+\n}\nexport {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Include isSocket on Viewer
129,187
03.11.2018 18:05:55
14,400
37ed1025509efc636092b921d1afe48d424bf170
Introducing RawUpdateInfo
[ { "change_type": "MODIFY", "old_path": "lib/shared/update-utils.js", "new_path": "lib/shared/update-utils.js", "diff": "import {\ntype UpdateInfo,\ntype UpdateData,\n+ type RawUpdateInfo,\nupdateTypes,\n} from '../types/update-types';\n@@ -74,10 +75,76 @@ function conditionKeyForUpdateDataFromKey(\nreturn `${updateData.userID}|${key}`;\n}\n+function rawUpdateInfoFromUpdateData(\n+ updateData: UpdateData,\n+ id: string,\n+): RawUpdateInfo {\n+ if (updateData.type === updateTypes.DELETE_ACCOUNT) {\n+ return {\n+ type: updateTypes.DELETE_ACCOUNT,\n+ id,\n+ time: updateData.time,\n+ deletedUserID: updateData.deletedUserID,\n+ };\n+ } else if (updateData.type === updateTypes.UPDATE_THREAD) {\n+ return {\n+ type: updateTypes.UPDATE_THREAD,\n+ id,\n+ time: updateData.time,\n+ threadID: updateData.threadID,\n+ };\n+ } else if (updateData.type === updateTypes.UPDATE_THREAD_READ_STATUS) {\n+ return {\n+ type: updateTypes.UPDATE_THREAD_READ_STATUS,\n+ id,\n+ time: updateData.time,\n+ threadID: updateData.threadID,\n+ unread: updateData.unread,\n+ };\n+ } else if (updateData.type === updateTypes.DELETE_THREAD) {\n+ return {\n+ type: updateTypes.DELETE_THREAD,\n+ id,\n+ time: updateData.time,\n+ threadID: updateData.threadID,\n+ };\n+ } else if (updateData.type === updateTypes.JOIN_THREAD) {\n+ return {\n+ type: updateTypes.JOIN_THREAD,\n+ id,\n+ time: updateData.time,\n+ threadID: updateData.threadID,\n+ };\n+ } else if (updateData.type === updateTypes.BAD_DEVICE_TOKEN) {\n+ return {\n+ type: updateTypes.BAD_DEVICE_TOKEN,\n+ id,\n+ time: updateData.time,\n+ deviceToken: updateData.deviceToken,\n+ };\n+ } else if (updateData.type === updateTypes.UPDATE_ENTRY) {\n+ return {\n+ type: updateTypes.UPDATE_ENTRY,\n+ id,\n+ time: updateData.time,\n+ entryID: updateData.entryID,\n+ };\n+ } else if (updateData.type === updateTypes.UPDATE_CURRENT_USER) {\n+ return {\n+ type: updateTypes.UPDATE_CURRENT_USER,\n+ id,\n+ time: updateData.time,\n+ };\n+ } else {\n+ invariant(false, `unrecognized updateType ${updateData.type}`);\n+ }\n+}\n+\nexport {\nmostRecentUpdateTimestamp,\nkeyForUpdateData,\nkeyForUpdateInfo,\nconditionKeyForUpdateData,\nconditionKeyForUpdateDataFromKey,\n+ rawUpdateInfoFromUpdateData,\n};\n" }, { "change_type": "MODIFY", "old_path": "lib/types/redis-types.js", "new_path": "lib/types/redis-types.js", "diff": "// @flow\n-import type { UpdateData } from './update-types';\n+import type { RawUpdateInfo } from './update-types';\n// The types of messages that can be published to Redis\nexport const redisMessageTypes = Object.freeze({\n@@ -20,7 +20,7 @@ type StartSubscriptionRedisMessage = {|\ntype NewUpdatesRedisMessage = {|\ntype: 1,\n- updates: $ReadOnlyArray<UpdateData>,\n+ updates: $ReadOnlyArray<RawUpdateInfo>,\n|};\nexport type RedisMessage =\n" }, { "change_type": "MODIFY", "old_path": "lib/types/update-types.js", "new_path": "lib/types/update-types.js", "diff": "@@ -98,6 +98,64 @@ export type UpdateData =\n| EntryUpdateData\n| CurrentUserUpdateData;\n+type AccountDeletionRawUpdateInfo = {|\n+ type: 0,\n+ id: string,\n+ time: number,\n+ deletedUserID: string,\n+|};\n+type ThreadRawUpdateInfo = {|\n+ type: 1,\n+ id: string,\n+ time: number,\n+ threadID: string,\n+|};\n+type ThreadReadStatusRawUpdateInfo = {|\n+ type: 2,\n+ id: string,\n+ time: number,\n+ threadID: string,\n+ unread: bool,\n+|};\n+type ThreadDeletionRawUpdateInfo = {|\n+ type: 3,\n+ id: string,\n+ time: number,\n+ threadID: string,\n+|};\n+type ThreadJoinRawUpdateInfo = {|\n+ type: 4,\n+ id: string,\n+ time: number,\n+ threadID: string,\n+|};\n+type BadDeviceTokenRawUpdateInfo = {|\n+ type: 5,\n+ id: string,\n+ time: number,\n+ deviceToken: string,\n+|};\n+type EntryRawUpdateInfo = {|\n+ type: 6,\n+ id: string,\n+ time: number,\n+ entryID: string,\n+|};\n+type CurrentUserRawUpdateInfo = {|\n+ type: 7,\n+ id: string,\n+ time: number,\n+|};\n+export type RawUpdateInfo =\n+ | AccountDeletionRawUpdateInfo\n+ | ThreadRawUpdateInfo\n+ | ThreadReadStatusRawUpdateInfo\n+ | ThreadDeletionRawUpdateInfo\n+ | ThreadJoinRawUpdateInfo\n+ | BadDeviceTokenRawUpdateInfo\n+ | EntryRawUpdateInfo\n+ | CurrentUserRawUpdateInfo;\n+\ntype AccountDeletionUpdateInfo = {|\ntype: 0,\nid: string,\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/update-creator.js", "new_path": "server/src/creators/update-creator.js", "diff": "import {\ntype UpdateInfo,\ntype UpdateData,\n+ type RawUpdateInfo,\ntype CreateUpdatesResult,\nupdateTypes,\n} from 'lib/types/update-types';\n@@ -38,6 +39,7 @@ import {\nkeyForUpdateInfo,\nconditionKeyForUpdateData,\nconditionKeyForUpdateDataFromKey,\n+ rawUpdateInfoFromUpdateData,\n} from 'lib/shared/update-utils';\nimport { ServerError } from 'lib/utils/errors';\n@@ -194,7 +196,7 @@ async function createUpdates(\n}\nconst ids = await createIDs(\"updates\", filteredUpdateDatas.length);\n- const viewerUpdateDatas: ViewerUpdateData[] = [];\n+ const viewerRawUpdateInfos: RawUpdateInfo[] = [];\nconst insertRows: (?(number | string))[][] = [];\nconst earliestTime: Map<string, number> = new Map();\nfor (let i = 0; i < filteredUpdateDatas.length; i++) {\n@@ -233,7 +235,8 @@ async function createUpdates(\nupdateData.userID === viewerInfo.viewer.id &&\n(!target || target === viewerInfo.viewer.session)\n) {\n- viewerUpdateDatas.push({ data: updateData, id: ids[i] });\n+ const rawUpdateInfo = rawUpdateInfoFromUpdateData(updateData, ids[i]);\n+ viewerRawUpdateInfos.push(rawUpdateInfo);\n}\nif (viewerInfo && target && viewerInfo.viewer.session === target) {\n@@ -297,10 +300,10 @@ async function createUpdates(\npromises.delete = deleteUpdatesByConditions(deleteSQLConditions);\n}\n- if (viewerUpdateDatas.length > 0) {\n+ if (viewerRawUpdateInfos.length > 0) {\ninvariant(viewerInfo, \"should be set\");\n- promises.updatesResult = fetchUpdateInfosWithUpdateDatas(\n- viewerUpdateDatas,\n+ promises.updatesResult = fetchUpdateInfosWithRawUpdateInfos(\n+ viewerRawUpdateInfos,\nviewerInfo,\n);\n}\n@@ -313,34 +316,32 @@ async function createUpdates(\nreturn { viewerUpdates: updateInfos, userInfos };\n}\n-export type ViewerUpdateData = {| data: UpdateData, id: string |};\nexport type FetchUpdatesResult = {|\nupdateInfos: $ReadOnlyArray<UpdateInfo>,\nuserInfos: {[id: string]: AccountUserInfo},\n|};\n-async function fetchUpdateInfosWithUpdateDatas(\n- updateDatas: $ReadOnlyArray<ViewerUpdateData>,\n+async function fetchUpdateInfosWithRawUpdateInfos(\n+ rawUpdateInfos: $ReadOnlyArray<RawUpdateInfo>,\nviewerInfo: ViewerInfo,\n): Promise<FetchUpdatesResult> {\nconst threadIDsNeedingFetch = new Set();\nconst entryIDsNeedingFetch = new Set();\nconst currentUserIDsNeedingFetch = new Set();\nconst threadIDsNeedingDetailedFetch = new Set(); // entries and messages\n- for (let viewerUpdateData of updateDatas) {\n- const updateData = viewerUpdateData.data;\n+ for (let rawUpdateInfo of rawUpdateInfos) {\nif (\n!viewerInfo.threadInfos &&\n- (updateData.type === updateTypes.UPDATE_THREAD ||\n- updateData.type === updateTypes.JOIN_THREAD)\n+ (rawUpdateInfo.type === updateTypes.UPDATE_THREAD ||\n+ rawUpdateInfo.type === updateTypes.JOIN_THREAD)\n) {\n- threadIDsNeedingFetch.add(updateData.threadID);\n+ threadIDsNeedingFetch.add(rawUpdateInfo.threadID);\n}\n- if (updateData.type === updateTypes.JOIN_THREAD) {\n- threadIDsNeedingDetailedFetch.add(updateData.threadID);\n- } else if (updateData.type === updateTypes.UPDATE_ENTRY) {\n- entryIDsNeedingFetch.add(updateData.entryID);\n- } else if (updateData.type === updateTypes.UPDATE_CURRENT_USER) {\n- currentUserIDsNeedingFetch.add(updateData.userID);\n+ if (rawUpdateInfo.type === updateTypes.JOIN_THREAD) {\n+ threadIDsNeedingDetailedFetch.add(rawUpdateInfo.threadID);\n+ } else if (rawUpdateInfo.type === updateTypes.UPDATE_ENTRY) {\n+ entryIDsNeedingFetch.add(rawUpdateInfo.entryID);\n+ } else if (rawUpdateInfo.type === updateTypes.UPDATE_CURRENT_USER) {\n+ currentUserIDsNeedingFetch.add(viewerInfo.viewer.userID);\n}\n}\n@@ -418,8 +419,9 @@ async function fetchUpdateInfosWithUpdateDatas(\nthreadInfosResult = { threadInfos: {}, userInfos: {} };\n}\n- return await updateInfosFromUpdateDatas(\n- updateDatas,\n+ return await updateInfosFromRawUpdateInfos(\n+ viewerInfo.viewer,\n+ rawUpdateInfos,\n{\nthreadInfosResult,\nmessageInfosResult,\n@@ -437,8 +439,9 @@ export type UpdateInfosRawData = {|\nentryInfosResult: ?$ReadOnlyArray<RawEntryInfo>,\ncurrentUserInfosResult: ?$ReadOnlyArray<LoggedInUserInfo>,\n|};\n-async function updateInfosFromUpdateDatas(\n- updateDatas: $ReadOnlyArray<ViewerUpdateData>,\n+async function updateInfosFromRawUpdateInfos(\n+ viewer: Viewer,\n+ rawUpdateInfos: $ReadOnlyArray<RawUpdateInfo>,\nrawData: UpdateInfosRawData,\n): Promise<FetchUpdatesResult> {\nconst {\n@@ -450,17 +453,16 @@ async function updateInfosFromUpdateDatas(\n} = rawData;\nconst updateInfos = [];\nlet userIDs = new Set();\n- for (let viewerUpdateData of updateDatas) {\n- const { data: updateData, id } = viewerUpdateData;\n- if (updateData.type === updateTypes.DELETE_ACCOUNT) {\n+ for (let rawUpdateInfo of rawUpdateInfos) {\n+ if (rawUpdateInfo.type === updateTypes.DELETE_ACCOUNT) {\nupdateInfos.push({\ntype: updateTypes.DELETE_ACCOUNT,\n- id,\n- time: updateData.time,\n- deletedUserID: updateData.deletedUserID,\n+ id: rawUpdateInfo.id,\n+ time: rawUpdateInfo.time,\n+ deletedUserID: rawUpdateInfo.deletedUserID,\n});\n- } else if (updateData.type === updateTypes.UPDATE_THREAD) {\n- const threadInfo = threadInfosResult.threadInfos[updateData.threadID];\n+ } else if (rawUpdateInfo.type === updateTypes.UPDATE_THREAD) {\n+ const threadInfo = threadInfosResult.threadInfos[rawUpdateInfo.threadID];\ninvariant(threadInfo, \"should be set\");\nuserIDs = new Set([\n...userIDs,\n@@ -468,39 +470,39 @@ async function updateInfosFromUpdateDatas(\n]);\nupdateInfos.push({\ntype: updateTypes.UPDATE_THREAD,\n- id,\n- time: updateData.time,\n+ id: rawUpdateInfo.id,\n+ time: rawUpdateInfo.time,\nthreadInfo,\n});\n- } else if (updateData.type === updateTypes.UPDATE_THREAD_READ_STATUS) {\n+ } else if (rawUpdateInfo.type === updateTypes.UPDATE_THREAD_READ_STATUS) {\nupdateInfos.push({\ntype: updateTypes.UPDATE_THREAD_READ_STATUS,\n- id,\n- time: updateData.time,\n- threadID: updateData.threadID,\n- unread: updateData.unread,\n+ id: rawUpdateInfo.id,\n+ time: rawUpdateInfo.time,\n+ threadID: rawUpdateInfo.threadID,\n+ unread: rawUpdateInfo.unread,\n});\n- } else if (updateData.type === updateTypes.DELETE_THREAD) {\n+ } else if (rawUpdateInfo.type === updateTypes.DELETE_THREAD) {\nupdateInfos.push({\ntype: updateTypes.DELETE_THREAD,\n- id,\n- time: updateData.time,\n- threadID: updateData.threadID,\n+ id: rawUpdateInfo.id,\n+ time: rawUpdateInfo.time,\n+ threadID: rawUpdateInfo.threadID,\n});\n- } else if (updateData.type === updateTypes.JOIN_THREAD) {\n- const threadInfo = threadInfosResult.threadInfos[updateData.threadID];\n+ } else if (rawUpdateInfo.type === updateTypes.JOIN_THREAD) {\n+ const threadInfo = threadInfosResult.threadInfos[rawUpdateInfo.threadID];\ninvariant(threadInfo, \"should be set\");\nconst rawEntryInfos = [];\ninvariant(calendarResult, \"should be set\");\nfor (let entryInfo of calendarResult.rawEntryInfos) {\n- if (entryInfo.threadID === updateData.threadID) {\n+ if (entryInfo.threadID === rawUpdateInfo.threadID) {\nrawEntryInfos.push(entryInfo);\n}\n}\nconst rawMessageInfos = [];\ninvariant(messageInfosResult, \"should be set\");\nfor (let messageInfo of messageInfosResult.rawMessageInfos) {\n- if (messageInfo.threadID === updateData.threadID) {\n+ if (messageInfo.threadID === rawUpdateInfo.threadID) {\nrawMessageInfos.push(messageInfo);\n}\n}\n@@ -512,25 +514,25 @@ async function updateInfosFromUpdateDatas(\n]);\nupdateInfos.push({\ntype: updateTypes.JOIN_THREAD,\n- id,\n- time: updateData.time,\n+ id: rawUpdateInfo.id,\n+ time: rawUpdateInfo.time,\nthreadInfo,\nrawMessageInfos,\ntruncationStatus:\n- messageInfosResult.truncationStatuses[updateData.threadID],\n+ messageInfosResult.truncationStatuses[rawUpdateInfo.threadID],\nrawEntryInfos,\n});\n- } else if (updateData.type === updateTypes.BAD_DEVICE_TOKEN) {\n+ } else if (rawUpdateInfo.type === updateTypes.BAD_DEVICE_TOKEN) {\nupdateInfos.push({\ntype: updateTypes.BAD_DEVICE_TOKEN,\n- id,\n- time: updateData.time,\n- deviceToken: updateData.deviceToken,\n+ id: rawUpdateInfo.id,\n+ time: rawUpdateInfo.time,\n+ deviceToken: rawUpdateInfo.deviceToken,\n});\n- } else if (updateData.type === updateTypes.UPDATE_ENTRY) {\n+ } else if (rawUpdateInfo.type === updateTypes.UPDATE_ENTRY) {\ninvariant(entryInfosResult, \"should be set\");\nconst entryInfo = entryInfosResult.find(\n- candidate => candidate.id === updateData.entryID,\n+ candidate => candidate.id === rawUpdateInfo.entryID,\n);\ninvariant(entryInfo, \"should be set\");\nuserIDs = new Set([\n@@ -539,24 +541,24 @@ async function updateInfosFromUpdateDatas(\n]);\nupdateInfos.push({\ntype: updateTypes.UPDATE_ENTRY,\n- id,\n- time: updateData.time,\n+ id: rawUpdateInfo.id,\n+ time: rawUpdateInfo.time,\nentryInfo,\n});\n- } else if (updateData.type === updateTypes.UPDATE_CURRENT_USER) {\n+ } else if (rawUpdateInfo.type === updateTypes.UPDATE_CURRENT_USER) {\ninvariant(currentUserInfosResult, \"should be set\");\nconst currentUserInfo = currentUserInfosResult.find(\n- candidate => candidate.id === updateData.userID,\n+ candidate => candidate.id === viewer.userID,\n);\ninvariant(currentUserInfo, \"should be set\");\nupdateInfos.push({\ntype: updateTypes.UPDATE_CURRENT_USER,\n- id,\n- time: updateData.time,\n+ id: rawUpdateInfo.id,\n+ time: rawUpdateInfo.time,\ncurrentUserInfo,\n});\n} else {\n- invariant(false, `unrecognized updateType ${updateData.type}`);\n+ invariant(false, `unrecognized updateType ${rawUpdateInfo.type}`);\n}\n}\n@@ -630,5 +632,5 @@ async function updateInfosFromUpdateDatas(\nexport {\ncreateUpdates,\n- fetchUpdateInfosWithUpdateDatas,\n+ fetchUpdateInfosWithRawUpdateInfos,\n};\n" }, { "change_type": "MODIFY", "old_path": "server/src/fetchers/update-fetchers.js", "new_path": "server/src/fetchers/update-fetchers.js", "diff": "// @flow\nimport {\n- type UpdateInfo,\n+ type RawUpdateInfo,\nupdateTypes,\nassertUpdateType,\n} from 'lib/types/update-types';\n@@ -14,9 +14,8 @@ import { ServerError } from 'lib/utils/errors';\nimport { dbQuery, SQL } from '../database';\nimport {\n- type ViewerUpdateData,\ntype FetchUpdatesResult,\n- fetchUpdateInfosWithUpdateDatas,\n+ fetchUpdateInfosWithRawUpdateInfos,\n} from '../creators/update-creator';\nasync function fetchUpdateInfos(\n@@ -38,97 +37,84 @@ async function fetchUpdateInfos(\n`;\nconst [ result ] = await dbQuery(query);\n- const viewerUpdateDatas = [];\n+ const rawUpdateInfos = [];\nfor (let row of result) {\n- viewerUpdateDatas.push(viewerUpdateDataFromRow(viewer, row));\n+ rawUpdateInfos.push(rawUpdateInfoFromRow(row));\n}\n- return await fetchUpdateInfosWithUpdateDatas(\n- viewerUpdateDatas,\n+ return await fetchUpdateInfosWithRawUpdateInfos(\n+ rawUpdateInfos,\n{ viewer, calendarQuery },\n);\n}\n-function viewerUpdateDataFromRow(\n- viewer: Viewer,\n- row: Object,\n-): ViewerUpdateData {\n+function rawUpdateInfoFromRow(row: Object): RawUpdateInfo {\nconst type = assertUpdateType(row.type);\n- let data;\n- const id = row.id.toString();\nif (type === updateTypes.DELETE_ACCOUNT) {\nconst content = JSON.parse(row.content);\n- data = {\n+ return {\ntype: updateTypes.DELETE_ACCOUNT,\n- userID: viewer.id,\n+ id: row.id.toString(),\ntime: row.time,\ndeletedUserID: content.deletedUserID,\n};\n} else if (type === updateTypes.UPDATE_THREAD) {\nconst { threadID } = JSON.parse(row.content);\n- data = {\n+ return {\ntype: updateTypes.UPDATE_THREAD,\n- userID: viewer.id,\n+ id: row.id.toString(),\ntime: row.time,\nthreadID,\n};\n} else if (type === updateTypes.UPDATE_THREAD_READ_STATUS) {\nconst { threadID, unread } = JSON.parse(row.content);\n- data = {\n+ return {\ntype: updateTypes.UPDATE_THREAD_READ_STATUS,\n- userID: viewer.id,\n+ id: row.id.toString(),\ntime: row.time,\nthreadID,\nunread,\n};\n} else if (type === updateTypes.DELETE_THREAD) {\nconst { threadID } = JSON.parse(row.content);\n- data = {\n+ return {\ntype: updateTypes.DELETE_THREAD,\n- userID: viewer.id,\n+ id: row.id.toString(),\ntime: row.time,\nthreadID,\n};\n} else if (type === updateTypes.JOIN_THREAD) {\nconst { threadID } = JSON.parse(row.content);\n- data = {\n+ return {\ntype: updateTypes.JOIN_THREAD,\n- userID: viewer.id,\n+ id: row.id.toString(),\ntime: row.time,\nthreadID,\n};\n} else if (type === updateTypes.BAD_DEVICE_TOKEN) {\nconst { deviceToken } = JSON.parse(row.content);\n- data = {\n+ return {\ntype: updateTypes.BAD_DEVICE_TOKEN,\n- userID: viewer.id,\n+ id: row.id.toString(),\ntime: row.time,\ndeviceToken,\n- // This UpdateData is only used to generate a UpdateInfo,\n- // and UpdateInfo doesn't care about the targetCookie field\n- targetCookie: \"\",\n};\n} else if (type === updateTypes.UPDATE_ENTRY) {\nconst { entryID } = JSON.parse(row.content);\n- data = {\n+ return {\ntype: updateTypes.UPDATE_ENTRY,\n- userID: viewer.id,\n+ id: row.id.toString(),\ntime: row.time,\nentryID,\n- // This UpdateData is only used to generate a UpdateInfo,\n- // and UpdateInfo doesn't care about the targetSession field\n- targetSession: \"\",\n};\n} else if (type === updateTypes.UPDATE_CURRENT_USER) {\n- data = {\n+ return {\ntype: updateTypes.UPDATE_CURRENT_USER,\n- userID: viewer.id,\n+ id: row.id.toString(),\ntime: row.time,\n};\n- } else {\n- invariant(false, `unrecognized updateType ${type}`);\n}\n- return { data, id };\n+ invariant(false, `unrecognized updateType ${type}`);\n}\nexport {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Introducing RawUpdateInfo
129,187
03.11.2018 18:25:30
14,400
f88f0a0a418b9a7ff9dea7321b2f00281fa53c02
[server] Publish new RawUpdateInfos to Redis
[ { "change_type": "MODIFY", "old_path": "server/src/creators/update-creator.js", "new_path": "server/src/creators/update-creator.js", "diff": "@@ -19,6 +19,7 @@ import type {\nFetchEntryInfosResponse,\nCalendarQuery,\n} from 'lib/types/entry-types';\n+import { type UpdateTarget, redisMessageTypes } from 'lib/types/redis-types';\nimport invariant from 'invariant';\nimport _uniq from 'lodash/fp/uniq';\n@@ -59,6 +60,7 @@ import {\nfetchUserInfos,\nfetchLoggedInUserInfos,\n} from '../fetchers/user-fetchers';\n+import { channelNameForUpdateTarget, publisher } from '../socket/redis';\nexport type ViewerInfo =\n| {| viewer: Viewer |}\n@@ -196,6 +198,7 @@ async function createUpdates(\n}\nconst ids = await createIDs(\"updates\", filteredUpdateDatas.length);\n+ const publishInfos: Map<string, PublishInfo> = new Map();\nconst viewerRawUpdateInfos: RawUpdateInfo[] = [];\nconst insertRows: (?(number | string))[][] = [];\nconst earliestTime: Map<string, number> = new Map();\n@@ -230,12 +233,24 @@ async function createUpdates(\ninvariant(false, `unrecognized updateType ${updateData.type}`);\n}\n+ const rawUpdateInfo = rawUpdateInfoFromUpdateData(updateData, ids[i]);\n+ const updateTarget = target\n+ ? { userID: updateData.userID, sessionID: target }\n+ : { userID: updateData.userID };\n+ const channelName = channelNameForUpdateTarget(updateTarget);\n+ let publishInfo = publishInfos.get(channelName);\n+ if (!publishInfo) {\n+ publishInfo = { updateTarget, rawUpdateInfos: [] };\n+ publishInfos.set(channelName, publishInfo);\n+ }\n+ publishInfo.rawUpdateInfos.push(rawUpdateInfo);\n+\nif (\nviewerInfo &&\nupdateData.userID === viewerInfo.viewer.id &&\n- (!target || target === viewerInfo.viewer.session)\n+ (!target || target === viewerInfo.viewer.session) &&\n+ !viewerInfo.viewer.isSocket\n) {\n- const rawUpdateInfo = rawUpdateInfoFromUpdateData(updateData, ids[i]);\nviewerRawUpdateInfos.push(rawUpdateInfo);\n}\n@@ -296,6 +311,10 @@ async function createUpdates(\npromises.insert = dbQuery(insertQuery);\n}\n+ if (publishInfos.size > 0) {\n+ promises.redis = redisPublish(publishInfos.values());\n+ }\n+\nif (deleteSQLConditions.length > 0) {\npromises.delete = deleteUpdatesByConditions(deleteSQLConditions);\n}\n@@ -630,6 +649,23 @@ async function updateInfosFromRawUpdateInfos(\nreturn { updateInfos: mergedUpdates, userInfos };\n}\n+type PublishInfo = {|\n+ updateTarget: UpdateTarget,\n+ rawUpdateInfos: RawUpdateInfo[],\n+|};\n+async function redisPublish(publishInfos: Iterator<PublishInfo>) {\n+ for (let publishInfo of publishInfos) {\n+ const { updateTarget, rawUpdateInfos } = publishInfo;\n+ publisher.sendMessage(\n+ updateTarget,\n+ {\n+ type: redisMessageTypes.NEW_UPDATES,\n+ updates: rawUpdateInfos,\n+ },\n+ );\n+ }\n+}\n+\nexport {\ncreateUpdates,\nfetchUpdateInfosWithRawUpdateInfos,\n" }, { "change_type": "MODIFY", "old_path": "server/src/socket/redis.js", "new_path": "server/src/socket/redis.js", "diff": "@@ -96,6 +96,7 @@ class RedisSubscriber {\n}\nexport {\n+ channelNameForUpdateTarget,\npublisher,\nRedisSubscriber,\n};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Publish new RawUpdateInfos to Redis
129,187
03.11.2018 18:50:55
14,400
ed4a284fae5442dea7d6f23621501b4992c323d0
Send socket message when Redis sends new RawUpdateInfos
[ { "change_type": "MODIFY", "old_path": "lib/socket/inflight-requests.js", "new_path": "lib/socket/inflight-requests.js", "diff": "@@ -125,7 +125,10 @@ class InflightRequests {\nresolveRequestsForMessage(message: ServerSocketMessage) {\nfor (let inflightRequest of this.data) {\n- if (inflightRequest.messageID !== message.responseTo) {\n+ if (\n+ !message.responseTo ||\n+ inflightRequest.messageID !== message.responseTo\n+ ) {\ncontinue;\n}\nif (message.type === serverSocketMessageTypes.ERROR) {\n" }, { "change_type": "MODIFY", "old_path": "lib/types/socket-types.js", "new_path": "lib/types/socket-types.js", "diff": "@@ -84,6 +84,7 @@ export const serverSocketMessageTypes = Object.freeze({\nAUTH_ERROR: 3,\nACTIVITY_UPDATE_RESPONSE: 4,\nPONG: 5,\n+ UPDATES: 6,\n});\nexport type ServerSocketMessageType = $Values<typeof serverSocketMessageTypes>;\nexport function assertServerSocketMessageType(\n@@ -95,7 +96,8 @@ export function assertServerSocketMessageType(\nourServerSocketMessageType === 2 ||\nourServerSocketMessageType === 3 ||\nourServerSocketMessageType === 4 ||\n- ourServerSocketMessageType === 5,\n+ ourServerSocketMessageType === 5 ||\n+ ourServerSocketMessageType === 6,\n\"number is not ServerSocketMessageType enum\",\n);\nreturn ourServerSocketMessageType;\n@@ -173,13 +175,21 @@ export type PongServerSocketMessage = {|\ntype: 5,\nresponseTo: number,\n|};\n+export type UpdatesServerSocketMessage = {|\n+ type: 6,\n+ payload: {|\n+ updatesResult: UpdatesResult,\n+ userInfos: $ReadOnlyArray<UserInfo>,\n+ |};\n+|};\nexport type ServerSocketMessage =\n| StateSyncServerSocketMessage\n| RequestsServerSocketMessage\n| ErrorServerSocketMessage\n| AuthErrorServerSocketMessage\n| ActivityUpdateResponseServerSocketMessage\n- | PongServerSocketMessage;\n+ | PongServerSocketMessage\n+ | UpdatesServerSocketMessage;\nexport type SocketListener = (message: ServerSocketMessage) => void;\n" }, { "change_type": "MODIFY", "old_path": "server/flow-typed/npm/ws_vx.x.x.js", "new_path": "server/flow-typed/npm/ws_vx.x.x.js", "diff": "@@ -22,6 +22,7 @@ declare module 'ws' {\nclose: (code?: number, reason?: string) => void,\nping: () => void,\nterminate: () => void,\n+ readyState: 0 | 1 | 2 | 3,\n};\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/socket/redis.js", "new_path": "server/src/socket/redis.js", "diff": "@@ -37,7 +37,7 @@ class RedisPublisher {\n}\nconst publisher = new RedisPublisher();\n-type OnMessage = (message: RedisMessage) => void;\n+type OnMessage = (message: RedisMessage) => (void | Promise<void>);\nclass RedisSubscriber {\nsub: RedisClient;\n" }, { "change_type": "MODIFY", "old_path": "server/src/socket/socket.js", "new_path": "server/src/socket/socket.js", "diff": "@@ -72,6 +72,7 @@ import {\n} from '../responders/activity-responders';\nimport { focusedTableRefreshFrequency } from '../shared/focused-times';\nimport { RedisSubscriber } from './redis';\n+import { fetchUpdateInfosWithRawUpdateInfos } from '../creators/update-creator';\nconst clientSocketMessageInputValidator = t.union([\ntShape({\n@@ -309,8 +310,14 @@ class Socket {\n}\nsendMessage(message: ServerSocketMessage) {\n+ invariant(\n+ this.ws.readyState > 0,\n+ \"shouldn't send message until connection established\",\n+ );\n+ if (this.ws.readyState === 1) {\nthis.ws.send(JSON.stringify(message));\n}\n+ }\nasync handleClientSocketMessage(\nmessage: ClientSocketMessage,\n@@ -561,9 +568,44 @@ class Socket {\n}];\n}\n- onRedisMessage = (message: RedisMessage) => {\n+ onRedisMessage = async (message: RedisMessage) => {\n+ try {\n+ await this.processRedisMessage(message);\n+ } catch (e) {\n+ console.warn(e);\n+ }\n+ }\n+\n+ async processRedisMessage(message: RedisMessage) {\nif (message.type === redisMessageTypes.START_SUBSCRIPTION) {\nthis.ws.terminate();\n+ } else if (message.type === redisMessageTypes.NEW_UPDATES) {\n+ const { viewer } = this;\n+ invariant(viewer, \"should be set\");\n+ const rawUpdateInfos = message.updates;\n+ const {\n+ updateInfos,\n+ userInfos,\n+ } = await fetchUpdateInfosWithRawUpdateInfos(\n+ rawUpdateInfos,\n+ { viewer },\n+ );\n+ if (updateInfos.length === 0) {\n+ console.warn(\n+ \"could not get any UpdateInfos from redisMessageTypes.NEW_UPDATES\",\n+ );\n+ return;\n+ }\n+ this.sendMessage({\n+ type: serverSocketMessageTypes.UPDATES,\n+ payload: {\n+ updatesResult: {\n+ currentAsOf: mostRecentUpdateTimestamp([...updateInfos], 0),\n+ newUpdates: updateInfos,\n+ },\n+ userInfos: values(userInfos),\n+ },\n+ });\n}\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Send socket message when Redis sends new RawUpdateInfos
129,187
04.11.2018 12:24:27
18,000
16446752076d4decfd6fc21bf9bb1f90b6f0fad0
[server] Refactor createMessages code to reduce SQL queries Code to update unread status and generate push notifs now shares a SQL query, which upcoming Redis updates will also share.
[ { "change_type": "MODIFY", "old_path": "server/src/creators/message-creator.js", "new_path": "server/src/creators/message-creator.js", "diff": "@@ -32,11 +32,6 @@ import { createUpdates } from './update-creator';\nimport { handleAsyncPromise } from '../responders/handlers';\nimport { earliestFocusedTimeConsideredCurrent } from '../shared/focused-times';\n-type ThreadRestriction = {|\n- creatorID?: ?string,\n- subthread?: ?string,\n-|};\n-\n// Does not do permission checks! (checkThreadPermission)\nasync function createMessages(\nviewer: Viewer,\n@@ -48,12 +43,8 @@ async function createMessages(\nconst ids = await createIDs(\"messages\", messageDatas.length);\n- // threadRestrictions contains the conditions that must be met for a\n- // membership row to be set to unread or the corresponding user notified for a\n- // given thread\nconst subthreadPermissionsToCheck: Set<string> = new Set();\n- const threadRestrictions: Map<string, ThreadRestriction> = new Map();\n- const threadsToNotifMessageIndices: Map<string, number[]> = new Map();\n+ const threadsToMessageIndices: Map<string, number[]> = new Map();\nconst messageInsertRows = [];\nconst messageInfos: RawMessageInfo[] = [];\nfor (let i = 0; i < messageDatas.length; i++) {\n@@ -65,51 +56,12 @@ async function createMessages(\nsubthreadPermissionsToCheck.add(messageData.childThreadID);\n}\n- if (!threadRestrictions.has(threadID)) {\n- const newThreadRestriction: ThreadRestriction = { creatorID };\n- if (messageData.type === messageTypes.CREATE_SUB_THREAD) {\n- newThreadRestriction.subthread = messageData.childThreadID;\n- }\n- threadRestrictions.set(threadID, newThreadRestriction);\n- } else {\n- const threadRestriction = threadRestrictions.get(threadID);\n- invariant(\n- threadRestriction,\n- `threadRestriction for thread ${threadID} should exist`,\n- );\n- let newThreadRestriction: ThreadRestriction = threadRestriction;\n- if (\n- threadRestriction.creatorID &&\n- threadRestriction.creatorID !== creatorID\n- ) {\n- newThreadRestriction = {\n- creatorID: undefined,\n- subthread: newThreadRestriction.subthread,\n- };\n- }\n- if (\n- threadRestriction.subthread &&\n- (messageData.type !== messageTypes.CREATE_SUB_THREAD ||\n- threadRestriction.subthread !== messageData.childThreadID)\n- ) {\n- newThreadRestriction = {\n- creatorID: newThreadRestriction.creatorID,\n- subthread: undefined,\n- };\n- }\n- if (newThreadRestriction !== threadRestriction) {\n- threadRestrictions.set(threadID, newThreadRestriction);\n- }\n- }\n-\n- if (messageTypeGeneratesNotifs(messageData.type)) {\n- const messageIndices = threadsToNotifMessageIndices.get(threadID);\n- if (messageIndices) {\n- threadsToNotifMessageIndices.set(threadID, [...messageIndices, i]);\n- } else {\n- threadsToNotifMessageIndices.set(threadID, [i]);\n- }\n+ let messageIndices = threadsToMessageIndices.get(threadID);\n+ if (!messageIndices) {\n+ messageIndices = [];\n+ threadsToMessageIndices.set(threadID, messageIndices);\n}\n+ messageIndices.push(i);\nlet content;\nif (messageData.type === messageTypes.CREATE_THREAD) {\n@@ -155,14 +107,11 @@ async function createMessages(\nmessageInfos.push(rawMessageInfoFromMessageData(messageData, ids[i]));\n}\n- // These return Promises but we don't want to wait on them\n- handleAsyncPromise(sendPushNotifsForNewMessages(\n- threadRestrictions,\n+ handleAsyncPromise(postMessageSend(\n+ threadsToMessageIndices,\nsubthreadPermissionsToCheck,\n- threadsToNotifMessageIndices,\nmessageInfos,\n));\n- handleAsyncPromise(updateUnreadStatus(threadRestrictions));\nconst messageInsertQuery = SQL`\nINSERT INTO messages(id, thread, user, type, content, time)\n@@ -176,112 +125,15 @@ async function createMessages(\n);\n}\n-const knowOfExtractString = `$.${threadPermissions.KNOW_OF}.value`;\n-\n-async function updateUnreadStatus(\n- threadRestrictions: Map<string, ThreadRestriction>,\n-) {\n- let joinIndex = 0;\n- const joinSubthreads: Map<string, number> = new Map();\n- const threadConditionClauses = [];\n- for (let pair of threadRestrictions) {\n- const [ threadID, threadRestriction ] = pair;\n- const conditions = getSQLConditionsForThreadRestriction(\n- threadID,\n- threadRestriction,\n- );\n- if (threadRestriction.subthread) {\n- const subthread = threadRestriction.subthread;\n- let index = joinSubthreads.get(subthread);\n- if (index === undefined) {\n- index = joinIndex++;\n- joinSubthreads.set(subthread, index);\n- }\n- const condition = SQL`JSON_EXTRACT(stm`;\n- condition.append(index);\n- condition.append(SQL`.permissions, ${knowOfExtractString}) IS TRUE`);\n- conditions.push(condition);\n- }\n- threadConditionClauses.push(mergeAndConditions(conditions));\n- }\n- const conditionClause = mergeOrConditions(threadConditionClauses);\n-\n- const subthreadJoins = [];\n- for (let pair of joinSubthreads) {\n- const [ subthread, index ] = pair;\n- subthreadJoins.push(subthreadJoin(index, subthread));\n- }\n-\n- const time = earliestFocusedTimeConsideredCurrent();\n- const visibleExtractString = `$.${threadPermissions.VISIBLE}.value`;\n- const query = SQL`\n- SELECT m.user, m.thread\n- FROM memberships m\n- LEFT JOIN focused f ON f.user = m.user AND f.thread = m.thread\n- AND f.time > ${time}\n- `;\n- appendSQLArray(query, subthreadJoins, SQL` `);\n- query.append(SQL`\n- WHERE m.role != 0 AND f.user IS NULL AND\n- JSON_EXTRACT(m.permissions, ${visibleExtractString}) IS TRUE AND\n- `);\n- query.append(conditionClause);\n- const [ result ] = await dbQuery(query);\n-\n- const setUnreadPairs = result.map(row => ({\n- userID: row.user.toString(),\n- threadID: row.thread.toString(),\n- }));\n- if (setUnreadPairs.length === 0) {\n- return;\n- }\n-\n- const updateConditions = setUnreadPairs.map(\n- pair => SQL`(user = ${pair.userID} AND thread = ${pair.threadID})`,\n- );\n- const updateQuery = SQL`\n- UPDATE memberships\n- SET unread = 1\n- WHERE\n- `;\n- updateQuery.append(mergeOrConditions(updateConditions));\n-\n- const now = Date.now();\n- await Promise.all([\n- dbQuery(updateQuery),\n- createUpdates(setUnreadPairs.map(pair => ({\n- type: updateTypes.UPDATE_THREAD_READ_STATUS,\n- userID: pair.userID,\n- time: now,\n- threadID: pair.threadID,\n- unread: true,\n- }))),\n- ]);\n-}\n-\n-async function sendPushNotifsForNewMessages(\n- threadRestrictions: Map<string, ThreadRestriction>,\n- subthreadPermissionsToCheck: Set<string>,\n+// Handles:\n+// (1) Sending push notifs\n+// (2) Setting threads to unread and generating corresponding UpdateInfos\n+// (3) Publishing to Redis so that active sockets pass on new messages\n+async function postMessageSend(\nthreadsToMessageIndices: Map<string, number[]>,\n+ subthreadPermissionsToCheck: Set<string>,\nmessageInfos: RawMessageInfo[],\n) {\n- const threadConditionClauses = [];\n- for (let pair of threadRestrictions) {\n- const [ threadID, threadRestriction ] = pair;\n- if (!threadsToMessageIndices.has(threadID)) {\n- continue;\n- }\n- const conditions = getSQLConditionsForThreadRestriction(\n- threadID,\n- threadRestriction,\n- );\n- threadConditionClauses.push(mergeAndConditions(conditions));\n- }\n- if (threadConditionClauses.length === 0) {\n- return;\n- }\n- const conditionClause = mergeOrConditions(threadConditionClauses);\n-\nlet joinIndex = 0;\nlet subthreadSelects = \"\";\nconst subthreadJoins = [];\n@@ -292,7 +144,11 @@ async function sendPushNotifsForNewMessages(\nstm${index}.permissions AS subthread${subthread}_permissions,\nstm${index}.role AS subthread${subthread}_role\n`;\n- subthreadJoins.push(subthreadJoin(index, subthread));\n+ const join = SQL`LEFT JOIN memberships `;\n+ join.append(`stm${index} ON stm${index}.`);\n+ join.append(SQL`thread = ${subthread} AND `);\n+ join.append(`stm${index}.user = m.user`);\n+ subthreadJoins.push(join);\n}\nconst time = earliestFocusedTimeConsideredCurrent();\n@@ -309,94 +165,133 @@ async function sendPushNotifsForNewMessages(\n`);\nappendSQLArray(query, subthreadJoins, SQL` `);\nquery.append(SQL`\n- WHERE m.role != 0 AND c.user IS NOT NULL AND f.user IS NULL AND\n+ WHERE m.role != 0 AND f.user IS NULL AND\nJSON_EXTRACT(m.permissions, ${visibleExtractString}) IS TRUE AND\n+ m.thread IN (${[...threadsToMessageIndices.keys()]})\n`);\n- query.append(conditionClause);\n- const prePushInfo = new Map();\n+ const perUserInfo = new Map();\nconst [ result ] = await dbQuery(query);\nfor (let row of result) {\nconst userID = row.user.toString();\nconst threadID = row.thread.toString();\nconst deviceToken = row.device_token;\nconst { platform, versions } = row;\n- let preUserPushInfo = prePushInfo.get(userID);\n- if (!preUserPushInfo) {\n- preUserPushInfo = {\n+ let thisUserInfo = perUserInfo.get(userID);\n+ if (!thisUserInfo) {\n+ thisUserInfo = {\ndevices: new Map(),\nthreadIDs: new Set(),\n- subthreads: new Set(),\n+ subthreadsCanNotify: new Set(),\n+ subthreadsCanSetToUnread: new Set(),\n};\n+ perUserInfo.set(userID, thisUserInfo);\n+ // Subthread info will be the same for each subthread, so we only parse\n+ // it once\nfor (let subthread of subthreadPermissionsToCheck) {\n- const permissions = row[`subthread${subthread}_permissions`];\nconst isSubthreadMember = !!row[`subthread${subthread}_role`];\n+ const permissions = row[`subthread${subthread}_permissions`];\n+ const canSeeSubthread =\n+ permissionLookup(permissions, threadPermissions.KNOW_OF);\n+ if (!canSeeSubthread) {\n+ continue;\n+ }\n+ thisUserInfo.subthreadsCanSetToUnread.add(subthread);\n// Only include the notification from the superthread if there is no\n// notification from the subthread\nif (\n- permissionLookup(permissions, threadPermissions.KNOW_OF) &&\n- (!isSubthreadMember ||\n- !permissionLookup(permissions, threadPermissions.VISIBLE))\n+ !isSubthreadMember ||\n+ !permissionLookup(permissions, threadPermissions.VISIBLE)\n) {\n- preUserPushInfo.subthreads.add(subthread);\n+ thisUserInfo.subthreadsCanNotify.add(subthread);\n}\n}\n}\n- preUserPushInfo.devices.set(deviceToken, {\n+ if (deviceToken) {\n+ thisUserInfo.devices.set(deviceToken, {\ndeviceType: platform,\ndeviceToken,\ncodeVersion: versions ? versions.codeVersion : null,\n});\n- preUserPushInfo.threadIDs.add(threadID);\n- prePushInfo.set(userID, preUserPushInfo);\n+ }\n+ thisUserInfo.threadIDs.add(threadID);\n}\n- const pushInfo = {};\n- for (let pair of prePushInfo) {\n+ const pushInfo = {}, setUnreadPairs = [];\n+ for (let pair of perUserInfo) {\nconst [ userID, preUserPushInfo ] = pair;\n+ const { subthreadsCanSetToUnread, subthreadsCanNotify } = preUserPushInfo;\nconst userPushInfo = {\ndevices: [...preUserPushInfo.devices.values()],\nmessageInfos: [],\n};\n+ const threadIDsToSetToUnread = new Set();\nfor (let threadID of preUserPushInfo.threadIDs) {\nconst messageIndices = threadsToMessageIndices.get(threadID);\ninvariant(messageIndices, `indices should exist for thread ${threadID}`);\nfor (let messageIndex of messageIndices) {\nconst messageInfo = messageInfos[messageIndex];\n+ if (messageInfo.creatorID === userID) {\n+ continue;\n+ }\n+ if (\n+ messageInfo.type !== messageTypes.CREATE_SUB_THREAD ||\n+ subthreadsCanSetToUnread.has(messageInfo.childThreadID)\n+ ) {\n+ threadIDsToSetToUnread.add(threadID);\n+ }\n+ if (!messageTypeGeneratesNotifs(messageInfo.type)) {\n+ continue;\n+ }\nif (\nmessageInfo.type !== messageTypes.CREATE_SUB_THREAD ||\n- preUserPushInfo.subthreads.has(messageInfo.childThreadID)\n+ subthreadsCanNotify.has(messageInfo.childThreadID)\n) {\nuserPushInfo.messageInfos.push(messageInfo);\n}\n}\n}\n- if (userPushInfo.messageInfos.length > 0) {\n+ if (\n+ userPushInfo.devices.length > 0 &&\n+ userPushInfo.messageInfos.length > 0\n+ ) {\npushInfo[userID] = userPushInfo;\n}\n+ for (let threadID of threadIDsToSetToUnread) {\n+ setUnreadPairs.push({ userID, threadID });\n}\n-\n- await sendPushNotifs(pushInfo);\n}\n-// Note: does *not* consider subthread\n-function getSQLConditionsForThreadRestriction(\n- threadID: string,\n- threadRestriction: ThreadRestriction,\n-): SQLStatement[] {\n- const conditions = [SQL`m.thread = ${threadID}`];\n- if (threadRestriction.creatorID) {\n- conditions.push(SQL`m.user != ${threadRestriction.creatorID}`);\n- }\n- return conditions;\n+ await Promise.all([\n+ sendPushNotifs(pushInfo),\n+ updateUnreadStatus(setUnreadPairs),\n+ ]);\n}\n-function subthreadJoin(index: number, subthread: string) {\n- const join = SQL`LEFT JOIN memberships `;\n- join.append(`stm${index} ON stm${index}.`);\n- join.append(SQL`thread = ${subthread} AND `);\n- join.append(`stm${index}.user = m.user`);\n- return join;\n+async function updateUnreadStatus(\n+ setUnreadPairs: $ReadOnlyArray<{| userID: string, threadID: string |}>,\n+) {\n+ const updateConditions = setUnreadPairs.map(\n+ pair => SQL`(user = ${pair.userID} AND thread = ${pair.threadID})`,\n+ );\n+ const updateQuery = SQL`\n+ UPDATE memberships\n+ SET unread = 1\n+ WHERE\n+ `;\n+ updateQuery.append(mergeOrConditions(updateConditions));\n+\n+ const now = Date.now();\n+ await Promise.all([\n+ dbQuery(updateQuery),\n+ createUpdates(setUnreadPairs.map(pair => ({\n+ type: updateTypes.UPDATE_THREAD_READ_STATUS,\n+ userID: pair.userID,\n+ time: now,\n+ threadID: pair.threadID,\n+ unread: true,\n+ }))),\n+ ]);\n}\nexport default createMessages;\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/update-creator.js", "new_path": "server/src/creators/update-creator.js", "diff": "@@ -61,6 +61,7 @@ import {\nfetchLoggedInUserInfos,\n} from '../fetchers/user-fetchers';\nimport { channelNameForUpdateTarget, publisher } from '../socket/redis';\n+import { handleAsyncPromise } from '../responders/handlers';\nexport type ViewerInfo =\n| {| viewer: Viewer |}\n@@ -312,7 +313,7 @@ async function createUpdates(\n}\nif (publishInfos.size > 0) {\n- promises.redis = redisPublish(publishInfos.values());\n+ handleAsyncPromise(redisPublish(publishInfos.values()));\n}\nif (deleteSQLConditions.length > 0) {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Refactor createMessages code to reduce SQL queries Code to update unread status and generate push notifs now shares a SQL query, which upcoming Redis updates will also share.
129,187
04.11.2018 13:22:26
18,000
c8f4553152c5d2a4700e63dbf186945869d96a60
[server] Publish new RawMessageInfos to Redis
[ { "change_type": "MODIFY", "old_path": "lib/types/redis-types.js", "new_path": "lib/types/redis-types.js", "diff": "// @flow\nimport type { RawUpdateInfo } from './update-types';\n+import type { RawMessageInfo } from './message-types';\n// The types of messages that can be published to Redis\nexport const redisMessageTypes = Object.freeze({\nSTART_SUBSCRIPTION: 0,\nNEW_UPDATES: 1,\n+ NEW_MESSAGES: 2,\n});\nexport type RedisMessageTypes = $Values<typeof redisMessageTypes>;\n@@ -17,15 +19,19 @@ type StartSubscriptionRedisMessage = {|\ntype: 0,\ninstanceID: string,\n|};\n-\ntype NewUpdatesRedisMessage = {|\ntype: 1,\nupdates: $ReadOnlyArray<RawUpdateInfo>,\n|};\n+type NewMessagesRedisMessage = {|\n+ type: 2,\n+ messages: $ReadOnlyArray<RawMessageInfo>,\n+|};\nexport type RedisMessage =\n| StartSubscriptionRedisMessage\n- | NewUpdatesRedisMessage;\n+ | NewUpdatesRedisMessage\n+ | NewMessagesRedisMessage;\nexport type UpdateTarget = {| userID: string, +sessionID?: string |};\nexport type SessionIdentifier = {| userID: string, sessionID: string |};\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/message-creator.js", "new_path": "server/src/creators/message-creator.js", "diff": "@@ -7,6 +7,7 @@ import {\n} from 'lib/types/message-types';\nimport { threadPermissions } from 'lib/types/thread-types';\nimport { updateTypes } from 'lib/types/update-types';\n+import { redisMessageTypes } from 'lib/types/redis-types';\nimport type { Viewer } from '../session/viewer';\nimport invariant from 'invariant';\n@@ -31,6 +32,8 @@ import { sendPushNotifs } from '../push/send';\nimport { createUpdates } from './update-creator';\nimport { handleAsyncPromise } from '../responders/handlers';\nimport { earliestFocusedTimeConsideredCurrent } from '../shared/focused-times';\n+import { fetchOtherSessionsForViewer } from '../fetchers/session-fetchers';\n+import { publisher } from '../socket/redis';\n// Does not do permission checks! (checkThreadPermission)\nasync function createMessages(\n@@ -108,6 +111,7 @@ async function createMessages(\n}\nhandleAsyncPromise(postMessageSend(\n+ viewer,\nthreadsToMessageIndices,\nsubthreadPermissionsToCheck,\nmessageInfos,\n@@ -130,6 +134,7 @@ async function createMessages(\n// (2) Setting threads to unread and generating corresponding UpdateInfos\n// (3) Publishing to Redis so that active sockets pass on new messages\nasync function postMessageSend(\n+ viewer: Viewer,\nthreadsToMessageIndices: Map<string, number[]>,\nsubthreadPermissionsToCheck: Set<string>,\nmessageInfos: RawMessageInfo[],\n@@ -154,7 +159,8 @@ async function postMessageSend(\nconst time = earliestFocusedTimeConsideredCurrent();\nconst visibleExtractString = `$.${threadPermissions.VISIBLE}.value`;\nconst query = SQL`\n- SELECT m.user, m.thread, c.platform, c.device_token, c.versions\n+ SELECT m.user, m.thread, c.platform, c.device_token, c.versions,\n+ f.user AS focused_user\n`;\nquery.append(subthreadSelects);\nquery.append(SQL`\n@@ -165,7 +171,7 @@ async function postMessageSend(\n`);\nappendSQLArray(query, subthreadJoins, SQL` `);\nquery.append(SQL`\n- WHERE m.role != 0 AND f.user IS NULL AND\n+ WHERE (m.role != 0 OR f.user IS NOT NULL) AND\nJSON_EXTRACT(m.permissions, ${visibleExtractString}) IS TRUE AND\nm.thread IN (${[...threadsToMessageIndices.keys()]})\n`);\n@@ -176,12 +182,14 @@ async function postMessageSend(\nconst userID = row.user.toString();\nconst threadID = row.thread.toString();\nconst deviceToken = row.device_token;\n+ const focusedUser = !!row.focused_user;\nconst { platform, versions } = row;\nlet thisUserInfo = perUserInfo.get(userID);\nif (!thisUserInfo) {\nthisUserInfo = {\ndevices: new Map(),\nthreadIDs: new Set(),\n+ notFocusedThreadIDs: new Set(),\nsubthreadsCanNotify: new Set(),\nsubthreadsCanSetToUnread: new Set(),\n};\n@@ -215,9 +223,12 @@ async function postMessageSend(\n});\n}\nthisUserInfo.threadIDs.add(threadID);\n+ if (!focusedUser) {\n+ thisUserInfo.notFocusedThreadIDs.add(threadID);\n+ }\n}\n- const pushInfo = {}, setUnreadPairs = [];\n+ const pushInfo = {}, setUnreadPairs = [], messageInfosPerUser = {};\nfor (let pair of perUserInfo) {\nconst [ userID, preUserPushInfo ] = pair;\nconst { subthreadsCanSetToUnread, subthreadsCanNotify } = preUserPushInfo;\n@@ -226,7 +237,7 @@ async function postMessageSend(\nmessageInfos: [],\n};\nconst threadIDsToSetToUnread = new Set();\n- for (let threadID of preUserPushInfo.threadIDs) {\n+ for (let threadID of preUserPushInfo.notFocusedThreadIDs) {\nconst messageIndices = threadsToMessageIndices.get(threadID);\ninvariant(messageIndices, `indices should exist for thread ${threadID}`);\nfor (let messageIndex of messageIndices) {\n@@ -260,11 +271,24 @@ async function postMessageSend(\nfor (let threadID of threadIDsToSetToUnread) {\nsetUnreadPairs.push({ userID, threadID });\n}\n+ const userMessageInfos = [];\n+ for (let threadID of preUserPushInfo.threadIDs) {\n+ const messageIndices = threadsToMessageIndices.get(threadID);\n+ invariant(messageIndices, `indices should exist for thread ${threadID}`);\n+ for (let messageIndex of messageIndices) {\n+ const messageInfo = messageInfos[messageIndex];\n+ userMessageInfos.push(messageInfo);\n+ }\n+ }\n+ if (userMessageInfos.length > 0) {\n+ messageInfosPerUser[userID] = userMessageInfos;\n+ }\n}\nawait Promise.all([\nsendPushNotifs(pushInfo),\nupdateUnreadStatus(setUnreadPairs),\n+ redisPublish(viewer, messageInfosPerUser),\n]);\n}\n@@ -294,4 +318,37 @@ async function updateUnreadStatus(\n]);\n}\n+async function redisPublish(\n+ viewer: Viewer,\n+ messageInfosPerUser: {[userID: string]: $ReadOnlyArray<RawMessageInfo>},\n+) {\n+ for (let userID in messageInfosPerUser) {\n+ if (userID === viewer.userID) {\n+ continue;\n+ }\n+ const messageInfos = messageInfosPerUser[userID];\n+ publisher.sendMessage(\n+ { userID },\n+ {\n+ type: redisMessageTypes.NEW_MESSAGES,\n+ messages: messageInfos,\n+ },\n+ );\n+ }\n+ const viewerMessageInfos = messageInfosPerUser[viewer.userID];\n+ if (!viewerMessageInfos) {\n+ return;\n+ }\n+ const sessionIDs = await fetchOtherSessionsForViewer(viewer);\n+ for (let sessionID of sessionIDs) {\n+ publisher.sendMessage(\n+ { userID: viewer.userID, sessionID },\n+ {\n+ type: redisMessageTypes.NEW_MESSAGES,\n+ messages: viewerMessageInfos,\n+ },\n+ );\n+ }\n+}\n+\nexport default createMessages;\n" }, { "change_type": "MODIFY", "old_path": "server/src/fetchers/session-fetchers.js", "new_path": "server/src/fetchers/session-fetchers.js", "diff": "@@ -31,6 +31,19 @@ async function fetchActiveSessionsForThread(\nreturn filters;\n}\n+async function fetchOtherSessionsForViewer(\n+ viewer: Viewer,\n+): Promise<string[]> {\n+ const query = SQL`\n+ SELECT id\n+ FROM sessions\n+ WHERE user = ${viewer.userID} AND id != ${viewer.session}\n+ `;\n+ const [ result ] = await dbQuery(query);\n+ return result.map(row => row.id.toString());\n+}\n+\nexport {\nfetchActiveSessionsForThread,\n+ fetchOtherSessionsForViewer,\n};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Publish new RawMessageInfos to Redis
129,187
04.11.2018 15:07:59
18,000
c68536bfdb1a43bc9f7955d6a963fb7e547b107c
[server] Check VISIBLE permission for any activity updates
[ { "change_type": "MODIFY", "old_path": "lib/utils/promises.js", "new_path": "lib/utils/promises.js", "diff": "@@ -22,6 +22,15 @@ async function promiseAll<T: {[key: string]: Promisable<*>}>(\nreturn byName;\n}\n+async function promiseFilter<T>(\n+ input: $ReadOnlyArray<T>,\n+ filterFunc: (value: T) => Promise<bool>,\n+): Promise<T[]> {\n+ const filterResults = await Promise.all(input.map(filterFunc));\n+ return input.filter((value, index) => filterResults[index]);\n+}\n+\nexport {\npromiseAll,\n+ promiseFilter,\n};\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/activity-updaters.js", "new_path": "server/src/updaters/activity-updaters.js", "diff": "@@ -13,13 +13,14 @@ import invariant from 'invariant';\nimport _difference from 'lodash/fp/difference';\nimport { ServerError } from 'lib/utils/errors';\n+import { promiseFilter } from 'lib/utils/promises';\nimport { dbQuery, SQL, mergeOrConditions } from '../database';\n-import { verifyThreadIDs } from '../fetchers/thread-fetchers';\nimport { rescindPushNotifs } from '../push/rescind';\nimport { createUpdates } from '../creators/update-creator';\nimport { deleteActivityForViewerSession } from '../deleters/activity-deleters';\nimport { earliestFocusedTimeConsideredCurrent } from '../shared/focused-times';\n+import { checkThreadPermission } from '../fetchers/thread-fetchers';\nasync function activityUpdater(\nviewer: Viewer,\n@@ -46,7 +47,10 @@ async function activityUpdater(\nupdatesForThreadID.push(activityUpdate);\n}\n- const verifiedThreadIDs = await verifyThreadIDs([...unverifiedThreadIDs]);\n+ const verifiedThreadIDs = await checkThreadPermissions(\n+ viewer,\n+ unverifiedThreadIDs,\n+ );\nconst focusedThreadIDs = new Set();\nconst unfocusedThreadIDs = new Set();\n@@ -121,6 +125,20 @@ async function activityUpdater(\nreturn { unfocusedToUnread };\n}\n+async function checkThreadPermissions(\n+ viewer: Viewer,\n+ unverifiedThreadIDs: Set<string>,\n+): Promise<string[]> {\n+ return await promiseFilter(\n+ [...unverifiedThreadIDs],\n+ (threadID: string) => checkThreadPermission(\n+ viewer,\n+ threadID,\n+ threadPermissions.VISIBLE,\n+ ),\n+ );\n+}\n+\nasync function updateFocusedRows(\nviewer: Viewer,\nthreadIDs: $ReadOnlyArray<string>,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Check VISIBLE permission for any activity updates
129,187
04.11.2018 16:28:29
18,000
b2f90421f5633b5d90e980bc07b5768843aaffb9
Send socket message when Redis sends new RawMessageInfos
[ { "change_type": "MODIFY", "old_path": "lib/types/message-types.js", "new_path": "lib/types/message-types.js", "diff": "@@ -514,7 +514,7 @@ export const messageTruncationStatus = Object.freeze({\n// result set for a given thread is contiguous with what the client has in its\n// state. If the client can't verify the contiguousness itself, it needs to\n// replace its Redux store's contents with what it is in this payload.\n- // 1) getMessageInfosSince: Sesult set for thread is equal to max, and the\n+ // 1) getMessageInfosSince: Result set for thread is equal to max, and the\n// truncation status isn't EXHAUSTIVE (ie. doesn't include the very first\n// message).\n// 2) getMessageInfos: ThreadSelectionCriteria does not specify cursors, the\n" }, { "change_type": "MODIFY", "old_path": "lib/types/socket-types.js", "new_path": "lib/types/socket-types.js", "diff": "@@ -85,6 +85,7 @@ export const serverSocketMessageTypes = Object.freeze({\nACTIVITY_UPDATE_RESPONSE: 4,\nPONG: 5,\nUPDATES: 6,\n+ MESSAGES: 7,\n});\nexport type ServerSocketMessageType = $Values<typeof serverSocketMessageTypes>;\nexport function assertServerSocketMessageType(\n@@ -97,7 +98,8 @@ export function assertServerSocketMessageType(\nourServerSocketMessageType === 3 ||\nourServerSocketMessageType === 4 ||\nourServerSocketMessageType === 5 ||\n- ourServerSocketMessageType === 6,\n+ ourServerSocketMessageType === 6 ||\n+ ourServerSocketMessageType === 7,\n\"number is not ServerSocketMessageType enum\",\n);\nreturn ourServerSocketMessageType;\n@@ -182,6 +184,13 @@ export type UpdatesServerSocketMessage = {|\nuserInfos: $ReadOnlyArray<UserInfo>,\n|};\n|};\n+export type MessagesServerSocketMessage = {|\n+ type: 7,\n+ payload: {|\n+ messagesResult: MessagesResponse,\n+ userInfos: $ReadOnlyArray<UserInfo>,\n+ |};\n+|};\nexport type ServerSocketMessage =\n| StateSyncServerSocketMessage\n| RequestsServerSocketMessage\n@@ -189,7 +198,8 @@ export type ServerSocketMessage =\n| AuthErrorServerSocketMessage\n| ActivityUpdateResponseServerSocketMessage\n| PongServerSocketMessage\n- | UpdatesServerSocketMessage;\n+ | UpdatesServerSocketMessage\n+ | MessagesServerSocketMessage;\nexport type SocketListener = (message: ServerSocketMessage) => void;\n" }, { "change_type": "MODIFY", "old_path": "server/src/fetchers/message-fetchers.js", "new_path": "server/src/fetchers/message-fetchers.js", "diff": "@@ -420,7 +420,7 @@ function threadSelectionCriteriaToInitialTruncationStatuses(\n}\nasync function fetchAllUsers(\n- rawMessageInfos: RawMessageInfo[],\n+ rawMessageInfos: $ReadOnlyArray<RawMessageInfo>,\nuserInfos: UserInfos,\n): Promise<UserInfos> {\nconst allAddedUserIDs = [];\n@@ -525,8 +525,30 @@ async function fetchMessageInfosSince(\n};\n}\n+async function getMessageFetchResultFromRedisMessages(\n+ viewer: Viewer,\n+ rawMessageInfos: $ReadOnlyArray<RawMessageInfo>,\n+): Promise<FetchMessageInfosResult> {\n+ const truncationStatuses = {};\n+ for (let rawMessageInfo of rawMessageInfos) {\n+ truncationStatuses[rawMessageInfo.threadID] =\n+ messageTruncationStatus.UNCHANGED;\n+ }\n+ const userInfos = await fetchAllUsers(rawMessageInfos, {});\n+ const shimmedRawMessageInfos = shimUnsupportedRawMessageInfos(\n+ rawMessageInfos,\n+ viewer.platformDetails,\n+ );\n+ return {\n+ rawMessageInfos: shimmedRawMessageInfos,\n+ truncationStatuses,\n+ userInfos,\n+ };\n+}\n+\nexport {\nfetchCollapsableNotifs,\nfetchMessageInfos,\nfetchMessageInfosSince,\n+ getMessageFetchResultFromRedisMessages,\n};\n" }, { "change_type": "MODIFY", "old_path": "server/src/socket/socket.js", "new_path": "server/src/socket/socket.js", "diff": "@@ -50,7 +50,10 @@ import {\n} from '../responders/ping-responders';\nimport { assertSecureRequest } from '../utils/security-utils';\nimport { fetchViewerForSocket, extendCookieLifespan } from '../session/cookies';\n-import { fetchMessageInfosSince } from '../fetchers/message-fetchers';\n+import {\n+ fetchMessageInfosSince,\n+ getMessageFetchResultFromRedisMessages,\n+} from '../fetchers/message-fetchers';\nimport { fetchThreadInfos } from '../fetchers/thread-fetchers';\nimport { fetchEntryInfos } from '../fetchers/entry-fetchers';\nimport { fetchCurrentUserInfo } from '../fetchers/user-fetchers';\n@@ -606,6 +609,35 @@ class Socket {\nuserInfos: values(userInfos),\n},\n});\n+ } else if (message.type === redisMessageTypes.NEW_MESSAGES) {\n+ const { viewer } = this;\n+ invariant(viewer, \"should be set\");\n+ const rawMessageInfos = message.messages;\n+ const messageFetchResult = await getMessageFetchResultFromRedisMessages(\n+ viewer,\n+ rawMessageInfos,\n+ );\n+ if (messageFetchResult.rawMessageInfos.length === 0) {\n+ console.warn(\n+ \"could not get any rawMessageInfos from \" +\n+ \"redisMessageTypes.NEW_MESSAGES\",\n+ );\n+ return;\n+ }\n+ this.sendMessage({\n+ type: serverSocketMessageTypes.MESSAGES,\n+ payload: {\n+ messagesResult: {\n+ rawMessageInfos: messageFetchResult.rawMessageInfos,\n+ truncationStatuses: messageFetchResult.truncationStatuses,\n+ currentAsOf: mostRecentMessageTimestamp(\n+ messageFetchResult.rawMessageInfos,\n+ 0,\n+ ),\n+ },\n+ userInfos: values(messageFetchResult.userInfos),\n+ },\n+ });\n}\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Send socket message when Redis sends new RawMessageInfos
129,187
04.11.2018 16:43:34
18,000
b845df85c066b7a5f3bfb68a0392b602c5a9bf33
Rename "Maintainers" to "Handlers"
[ { "change_type": "RENAME", "old_path": "lib/socket/activity-maintainer.react.js", "new_path": "lib/socket/activity-handler.react.js", "diff": "@@ -33,7 +33,7 @@ type Props = {|\n// Redux dispatch functions\ndispatchActionPayload: DispatchActionPayload,\n|};\n-class ActivityMaintainer extends React.PureComponent<Props> {\n+class ActivityHandler extends React.PureComponent<Props> {\nstatic propTypes = {\nactiveThread: PropTypes.string,\n@@ -169,4 +169,4 @@ export default connect(\n},\nnull,\ntrue,\n-)(ActivityMaintainer);\n+)(ActivityHandler);\n" }, { "change_type": "RENAME", "old_path": "lib/socket/client-response-maintainer.react.js", "new_path": "lib/socket/request-response-handler.react.js", "diff": "@@ -47,7 +47,7 @@ type Props = {|\ndispatchActionPayload: DispatchActionPayload,\n|};\n-class ClientResponseMaintainer extends React.PureComponent<Props> {\n+class RequestResponseHandler extends React.PureComponent<Props> {\nstatic propTypes = {\ninflightRequests: PropTypes.object,\n@@ -225,4 +225,4 @@ export default connect(\n}),\nnull,\ntrue,\n-)(ClientResponseMaintainer);\n+)(RequestResponseHandler);\n" }, { "change_type": "MODIFY", "old_path": "lib/socket/socket.react.js", "new_path": "lib/socket/socket.react.js", "diff": "@@ -54,8 +54,8 @@ import { ServerError } from '../utils/errors';\nimport { pingFrequency } from '../shared/timeouts';\nimport { promiseAll } from '../utils/promises';\nimport { InflightRequests, SocketTimeout } from './inflight-requests';\n-import ActivityMaintainer from './activity-maintainer.react';\n-import ClientResponseMaintainer from './client-response-maintainer.react';\n+import ActivityHandler from './activity-handler.react';\n+import RequestResponseHandler from './request-response-handler.react';\nimport { logOutActionTypes } from '../actions/user-actions';\ntype Props = {|\n@@ -259,12 +259,12 @@ class Socket extends React.PureComponent<Props, State> {\nrender() {\nreturn (\n<React.Fragment>\n- <ActivityMaintainer\n+ <ActivityHandler\nactiveThread={this.props.activeThread}\ninflightRequests={this.state.inflightRequests}\nsendMessage={this.sendMessageWithoutID}\n/>\n- <ClientResponseMaintainer\n+ <RequestResponseHandler\ninflightRequests={this.state.inflightRequests}\nsendMessage={this.sendMessageWithoutID}\naddListener={this.addListener}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Rename "Maintainers" to "Handlers"
129,187
04.11.2018 17:35:31
18,000
e5e0b93366952f28656a5e6b98151347f28fb855
[lib] Handle serverSocketMessageTypes.UPDATES
[ { "change_type": "MODIFY", "old_path": "lib/reducers/calendar-filters-reducer.js", "new_path": "lib/reducers/calendar-filters-reducer.js", "diff": "@@ -10,7 +10,11 @@ import {\n} from '../types/filter-types';\nimport type { BaseAction } from '../types/redux-types';\nimport type { RawThreadInfo } from '../types/thread-types';\n-import { updateTypes, type UpdateInfo } from '../types/update-types';\n+import {\n+ updateTypes,\n+ type UpdateInfo,\n+ processUpdatesActionType,\n+} from '../types/update-types';\nimport {\nfullStateSyncActionType,\nincrementalStateSyncActionType,\n@@ -81,7 +85,8 @@ export default function reduceCalendarFilters(\naction.type === newThreadActionTypes.success ||\naction.type === joinThreadActionTypes.success ||\naction.type === leaveThreadActionTypes.success ||\n- action.type === deleteThreadActionTypes.success\n+ action.type === deleteThreadActionTypes.success ||\n+ action.type === processUpdatesActionType\n) {\nreturn updateFilterListFromUpdateInfos(\nstate,\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/entry-reducer.js", "new_path": "lib/reducers/entry-reducer.js", "diff": "@@ -8,7 +8,11 @@ import type {\nCalendarResult,\n} from '../types/entry-types';\nimport { type RawThreadInfo } from '../types/thread-types';\n-import { updateTypes, type UpdateInfo } from '../types/update-types';\n+import {\n+ updateTypes,\n+ type UpdateInfo,\n+ processUpdatesActionType,\n+} from '../types/update-types';\nimport {\ntype EntryInconsistencyClientResponse,\ntype ServerRequest,\n@@ -593,6 +597,23 @@ function reduceEntryInfos(\nlastUserInteractionCalendar,\ninconsistencyResponses,\n};\n+ } else if (action.type === processUpdatesActionType) {\n+ const updateEntryInfos = mergeUpdateEntryInfos(\n+ [],\n+ action.payload.updatesResult.newUpdates,\n+ );\n+ const [ updatedEntryInfos, updatedDaysToEntries ] = mergeNewEntryInfos(\n+ entryInfos,\n+ updateEntryInfos,\n+ newThreadInfos,\n+ );\n+ return {\n+ entryInfos: updatedEntryInfos,\n+ daysToEntries: updatedDaysToEntries,\n+ actualizedCalendarQuery,\n+ lastUserInteractionCalendar,\n+ inconsistencyResponses,\n+ };\n} else if (action.type === fullStateSyncActionType) {\nconst [ updatedEntryInfos, updatedDaysToEntries ] = mergeNewEntryInfos(\nentryInfos,\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/message-reducer.js", "new_path": "lib/reducers/message-reducer.js", "diff": "@@ -12,7 +12,11 @@ import {\n} from '../types/message-types';\nimport type { BaseAction } from '../types/redux-types';\nimport { type RawThreadInfo, threadPermissions } from '../types/thread-types';\n-import { type UpdateInfo, updateTypes } from '../types/update-types';\n+import {\n+ updateTypes,\n+ type UpdateInfo,\n+ processUpdatesActionType,\n+} from '../types/update-types';\nimport {\nfullStateSyncActionType,\nincrementalStateSyncActionType,\n@@ -379,6 +383,43 @@ function reduceMessageStore(\nthreads: newMessageStore.threads,\ncurrentAsOf: messagesResult.currentAsOf,\n};\n+ } else if (action.type === processUpdatesActionType) {\n+ if (action.payload.updatesResult.newUpdates.length === 0) {\n+ return messageStore;\n+ }\n+\n+ const mergedMessageInfos = [];\n+ const mergedTruncationStatuses = {};\n+ const { newUpdates } = action.payload.updatesResult;\n+ for (let updateInfo of newUpdates) {\n+ if (updateInfo.type !== updateTypes.JOIN_THREAD) {\n+ continue;\n+ }\n+ for (let messageInfo of updateInfo.rawMessageInfos) {\n+ mergedMessageInfos.push(messageInfo);\n+ }\n+ mergedTruncationStatuses[updateInfo.threadInfo.id] =\n+ combineTruncationStatuses(\n+ updateInfo.truncationStatus,\n+ mergedTruncationStatuses[updateInfo.threadInfo.id],\n+ );\n+ }\n+ if (Object.keys(mergedTruncationStatuses).length === 0) {\n+ return messageStore;\n+ }\n+\n+ const newMessageStore = mergeNewMessages(\n+ messageStore,\n+ mergedMessageInfos,\n+ mergedTruncationStatuses,\n+ newThreadInfos,\n+ action.type,\n+ );\n+ return {\n+ messages: newMessageStore.messages,\n+ threads: newMessageStore.threads,\n+ currentAsOf: messageStore.currentAsOf,\n+ };\n} else if (action.type === fullStateSyncActionType) {\nconst { messagesResult } = action.payload;\nconst newMessageStore = mergeNewMessages(\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/thread-reducer.js", "new_path": "lib/reducers/thread-reducer.js", "diff": "import type { BaseAction } from '../types/redux-types';\nimport type { RawThreadInfo, ThreadStore } from '../types/thread-types';\n-import { updateTypes, type UpdateInfo } from '../types/update-types';\n+import {\n+ updateTypes,\n+ type UpdateInfo,\n+ processUpdatesActionType,\n+} from '../types/update-types';\nimport {\ntype ThreadInconsistencyClientResponse,\nserverRequestTypes,\n@@ -187,7 +191,10 @@ export default function reduceThreadInfos(\n),\n],\n};\n- } else if (action.type === incrementalStateSyncActionType) {\n+ } else if (\n+ action.type === incrementalStateSyncActionType ||\n+ action.type === processUpdatesActionType\n+ ) {\nconst updateResult = reduceThreadUpdates(state.threadInfos, action.payload);\nreturn {\nthreadInfos: updateResult,\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/updates-reducer.js", "new_path": "lib/reducers/updates-reducer.js", "diff": "// @flow\nimport type { BaseAction } from '../types/redux-types';\n+import { processUpdatesActionType } from '../types/update-types';\nimport _difference from 'lodash/fp/difference';\n@@ -27,6 +28,11 @@ function reduceUpdatesCurrentAsOf(\nreturn action.payload.updatesCurrentAsOf;\n} else if (action.type === incrementalStateSyncActionType) {\nreturn action.payload.updatesResult.currentAsOf;\n+ } else if (action.type === processUpdatesActionType) {\n+ return Math.max(\n+ action.payload.updatesResult.currentAsOf,\n+ currentAsOf,\n+ );\n}\nreturn currentAsOf;\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/user-reducer.js", "new_path": "lib/reducers/user-reducer.js", "diff": "import type { BaseAction } from '../types/redux-types';\nimport type { CurrentUserInfo, UserInfo } from '../types/user-types';\n-import { updateTypes } from '../types/update-types';\n+import { updateTypes, processUpdatesActionType } from '../types/update-types';\nimport {\nserverRequestTypes,\nprocessServerRequestsActionType,\n@@ -67,7 +67,10 @@ function reduceCurrentUserInfo(\nif (!_isEqual(currentUserInfo)(state)) {\nreturn currentUserInfo;\n}\n- } else if (action.type === incrementalStateSyncActionType) {\n+ } else if (\n+ action.type === incrementalStateSyncActionType ||\n+ action.type === processUpdatesActionType\n+ ) {\nfor (let update of action.payload.updatesResult.newUpdates) {\nif (\nupdate.type === updateTypes.UPDATE_CURRENT_USER &&\n@@ -144,7 +147,10 @@ function reduceUserInfos(\nif (!_isEqual(state)(newUserInfos)) {\nreturn newUserInfos;\n}\n- } else if (action.type === incrementalStateSyncActionType) {\n+ } else if (\n+ action.type === incrementalStateSyncActionType ||\n+ action.type === processUpdatesActionType\n+ ) {\nconst newUserInfos = _keyBy('id')(action.payload.userInfos);\nconst updated = { ...state, ...newUserInfos };\nfor (let update of action.payload.updatesResult.newUpdates) {\n" }, { "change_type": "MODIFY", "old_path": "lib/socket/request-response-handler.react.js", "new_path": "lib/socket/request-response-handler.react.js", "diff": "@@ -46,7 +46,6 @@ type Props = {|\n// Redux dispatch functions\ndispatchActionPayload: DispatchActionPayload,\n|};\n-\nclass RequestResponseHandler extends React.PureComponent<Props> {\nstatic propTypes = {\n" }, { "change_type": "MODIFY", "old_path": "lib/socket/socket.react.js", "new_path": "lib/socket/socket.react.js", "diff": "@@ -56,6 +56,7 @@ import { promiseAll } from '../utils/promises';\nimport { InflightRequests, SocketTimeout } from './inflight-requests';\nimport ActivityHandler from './activity-handler.react';\nimport RequestResponseHandler from './request-response-handler.react';\n+import UpdateHandler from './update-handler.react';\nimport { logOutActionTypes } from '../actions/user-actions';\ntype Props = {|\n@@ -270,6 +271,10 @@ class Socket extends React.PureComponent<Props, State> {\naddListener={this.addListener}\nremoveListener={this.removeListener}\n/>\n+ <UpdateHandler\n+ addListener={this.addListener}\n+ removeListener={this.removeListener}\n+ />\n</React.Fragment>\n);\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "lib/socket/update-handler.react.js", "diff": "+// @flow\n+\n+import {\n+ type ServerSocketMessage,\n+ serverSocketMessageTypes,\n+ type SocketListener,\n+} from '../types/socket-types';\n+import { processUpdatesActionType } from '../types/update-types';\n+import type { DispatchActionPayload } from '../utils/action-utils';\n+\n+import * as React from 'react';\n+import PropTypes from 'prop-types';\n+\n+import { connect } from '../utils/redux-utils';\n+\n+type Props = {|\n+ addListener: (listener: SocketListener) => void,\n+ removeListener: (listener: SocketListener) => void,\n+ // Redux dispatch functions\n+ dispatchActionPayload: DispatchActionPayload,\n+|};\n+class UpdateHandler extends React.PureComponent<Props> {\n+\n+ static propTypes = {\n+ addListener: PropTypes.func.isRequired,\n+ removeListener: PropTypes.func.isRequired,\n+ dispatchActionPayload: PropTypes.func.isRequired,\n+ };\n+\n+ componentDidMount() {\n+ this.props.addListener(this.onMessage);\n+ }\n+\n+ componentWillUnmount() {\n+ this.props.removeListener(this.onMessage);\n+ }\n+\n+ render() {\n+ return null;\n+ }\n+\n+ onMessage = (message: ServerSocketMessage) => {\n+ if (message.type !== serverSocketMessageTypes.UPDATES) {\n+ return;\n+ }\n+ this.props.dispatchActionPayload(\n+ processUpdatesActionType,\n+ message.payload,\n+ );\n+ }\n+\n+}\n+\n+export default connect(\n+ null,\n+ null,\n+ true,\n+)(UpdateHandler);\n" }, { "change_type": "MODIFY", "old_path": "lib/types/redux-types.js", "new_path": "lib/types/redux-types.js", "diff": "@@ -62,6 +62,7 @@ import type {\nActivityUpdateSuccessPayload,\nActivityUpdateFailedPayload,\n} from '../types/socket-types';\n+import type { UpdatesResultWithUserInfos } from '../types/update-types';\nexport type BaseAppState<NavInfo: BaseNavInfo> = {\nnavInfo: NavInfo,\n@@ -576,6 +577,9 @@ export type BaseAction =\n|} | {|\ntype: \"BACKGROUND\",\npayload?: void,\n+ |} | {|\n+ type: \"PROCESS_UPDATES\",\n+ payload: UpdatesResultWithUserInfos,\n|};\nexport type ActionPayload\n" }, { "change_type": "MODIFY", "old_path": "lib/types/socket-types.js", "new_path": "lib/types/socket-types.js", "diff": "@@ -4,7 +4,7 @@ import type { SessionState, SessionIdentification } from './session-types';\nimport type { ServerRequest, ClientResponse } from './request-types';\nimport type { RawThreadInfo } from './thread-types';\nimport type { MessagesResponse } from './message-types';\n-import type { UpdatesResult } from './update-types';\n+import type { UpdatesResult, UpdatesResultWithUserInfos } from './update-types';\nimport type {\nUserInfo,\nCurrentUserInfo,\n@@ -179,10 +179,7 @@ export type PongServerSocketMessage = {|\n|};\nexport type UpdatesServerSocketMessage = {|\ntype: 6,\n- payload: {|\n- updatesResult: UpdatesResult,\n- userInfos: $ReadOnlyArray<UserInfo>,\n- |};\n+ payload: UpdatesResultWithUserInfos,\n|};\nexport type MessagesServerSocketMessage = {|\ntype: 7,\n" }, { "change_type": "MODIFY", "old_path": "lib/types/update-types.js", "new_path": "lib/types/update-types.js", "diff": "@@ -6,7 +6,7 @@ import type {\nMessageTruncationStatus,\n} from './message-types';\nimport type { RawEntryInfo } from './entry-types';\n-import type { AccountUserInfo, LoggedInUserInfo } from './user-types';\n+import type { UserInfo, AccountUserInfo, LoggedInUserInfo } from './user-types';\nimport invariant from 'invariant';\n@@ -222,6 +222,10 @@ export type UpdatesResult = {|\ncurrentAsOf: number,\nnewUpdates: $ReadOnlyArray<UpdateInfo>,\n|};\n+export type UpdatesResultWithUserInfos = {|\n+ updatesResult: UpdatesResult,\n+ userInfos: $ReadOnlyArray<UserInfo>,\n+|};\nexport type CreateUpdatesResult = {|\nviewerUpdates: $ReadOnlyArray<UpdateInfo>,\n@@ -232,3 +236,5 @@ export type CreateUpdatesResponse = {|\nviewerUpdates: $ReadOnlyArray<UpdateInfo>,\nuserInfos: $ReadOnlyArray<AccountUserInfo>,\n|};\n+\n+export const processUpdatesActionType = \"PROCESS_UPDATES\";\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Handle serverSocketMessageTypes.UPDATES
129,187
04.11.2018 18:00:11
18,000
400c5c0bbb900a3563c0b97fd755bc8ff188cb71
[lib] Handle serverSocketMessageTypes.MESSAGES
[ { "change_type": "MODIFY", "old_path": "lib/reducers/message-reducer.js", "new_path": "lib/reducers/message-reducer.js", "diff": "@@ -9,6 +9,7 @@ import {\nmessageTruncationStatus,\nmessageTypes,\ndefaultNumberPerThread,\n+ processMessagesActionType,\n} from '../types/message-types';\nimport type { BaseAction } from '../types/redux-types';\nimport { type RawThreadInfo, threadPermissions } from '../types/thread-types';\n@@ -420,7 +421,10 @@ function reduceMessageStore(\nthreads: newMessageStore.threads,\ncurrentAsOf: messageStore.currentAsOf,\n};\n- } else if (action.type === fullStateSyncActionType) {\n+ } else if (\n+ action.type === fullStateSyncActionType ||\n+ action.type === processMessagesActionType\n+ ) {\nconst { messagesResult } = action.payload;\nconst newMessageStore = mergeNewMessages(\nmessageStore,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "lib/socket/message-handler.react.js", "diff": "+// @flow\n+\n+import {\n+ type ServerSocketMessage,\n+ serverSocketMessageTypes,\n+ type SocketListener,\n+} from '../types/socket-types';\n+import { processMessagesActionType } from '../types/message-types';\n+import type { DispatchActionPayload } from '../utils/action-utils';\n+\n+import * as React from 'react';\n+import PropTypes from 'prop-types';\n+\n+import { connect } from '../utils/redux-utils';\n+\n+type Props = {|\n+ addListener: (listener: SocketListener) => void,\n+ removeListener: (listener: SocketListener) => void,\n+ // Redux dispatch functions\n+ dispatchActionPayload: DispatchActionPayload,\n+|};\n+class MessageHandler extends React.PureComponent<Props> {\n+\n+ static propTypes = {\n+ addListener: PropTypes.func.isRequired,\n+ removeListener: PropTypes.func.isRequired,\n+ dispatchActionPayload: PropTypes.func.isRequired,\n+ };\n+\n+ componentDidMount() {\n+ this.props.addListener(this.onMessage);\n+ }\n+\n+ componentWillUnmount() {\n+ this.props.removeListener(this.onMessage);\n+ }\n+\n+ render() {\n+ return null;\n+ }\n+\n+ onMessage = (message: ServerSocketMessage) => {\n+ if (message.type !== serverSocketMessageTypes.MESSAGES) {\n+ return;\n+ }\n+ this.props.dispatchActionPayload(\n+ processMessagesActionType,\n+ message.payload,\n+ );\n+ }\n+\n+}\n+\n+export default connect(\n+ null,\n+ null,\n+ true,\n+)(MessageHandler);\n" }, { "change_type": "MODIFY", "old_path": "lib/socket/socket.react.js", "new_path": "lib/socket/socket.react.js", "diff": "@@ -57,6 +57,7 @@ import { InflightRequests, SocketTimeout } from './inflight-requests';\nimport ActivityHandler from './activity-handler.react';\nimport RequestResponseHandler from './request-response-handler.react';\nimport UpdateHandler from './update-handler.react';\n+import MessageHandler from './message-handler.react';\nimport { logOutActionTypes } from '../actions/user-actions';\ntype Props = {|\n@@ -275,6 +276,10 @@ class Socket extends React.PureComponent<Props, State> {\naddListener={this.addListener}\nremoveListener={this.removeListener}\n/>\n+ <MessageHandler\n+ addListener={this.addListener}\n+ removeListener={this.removeListener}\n+ />\n</React.Fragment>\n);\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/types/message-types.js", "new_path": "lib/types/message-types.js", "diff": "@@ -604,3 +604,9 @@ export type SaveMessagesPayload = {|\nrawMessageInfos: $ReadOnlyArray<RawMessageInfo>,\nupdatesCurrentAsOf: number,\n|};\n+\n+export type MessagesResultWithUserInfos = {|\n+ messagesResult: MessagesResponse,\n+ userInfos: $ReadOnlyArray<UserInfo>,\n+|};\n+export const processMessagesActionType = \"PROCESS_MESSAGES\";\n" }, { "change_type": "MODIFY", "old_path": "lib/types/redux-types.js", "new_path": "lib/types/redux-types.js", "diff": "@@ -40,6 +40,7 @@ import type {\nFetchMessageInfosPayload,\nSendTextMessagePayload,\nSaveMessagesPayload,\n+ MessagesResultWithUserInfos,\n} from './message-types';\nimport type { SetSessionPayload } from './session-types';\nimport type { ReportCreationResponse } from './report-types';\n@@ -580,6 +581,9 @@ export type BaseAction =\n|} | {|\ntype: \"PROCESS_UPDATES\",\npayload: UpdatesResultWithUserInfos,\n+ |} | {|\n+ type: \"PROCESS_MESSAGES\",\n+ payload: MessagesResultWithUserInfos,\n|};\nexport type ActionPayload\n" }, { "change_type": "MODIFY", "old_path": "lib/types/socket-types.js", "new_path": "lib/types/socket-types.js", "diff": "import type { SessionState, SessionIdentification } from './session-types';\nimport type { ServerRequest, ClientResponse } from './request-types';\nimport type { RawThreadInfo } from './thread-types';\n-import type { MessagesResponse } from './message-types';\n+import type {\n+ MessagesResponse,\n+ MessagesResultWithUserInfos,\n+} from './message-types';\nimport type { UpdatesResult, UpdatesResultWithUserInfos } from './update-types';\nimport type {\nUserInfo,\n@@ -183,10 +186,7 @@ export type UpdatesServerSocketMessage = {|\n|};\nexport type MessagesServerSocketMessage = {|\ntype: 7,\n- payload: {|\n- messagesResult: MessagesResponse,\n- userInfos: $ReadOnlyArray<UserInfo>,\n- |};\n+ payload: MessagesResultWithUserInfos,\n|};\nexport type ServerSocketMessage =\n| StateSyncServerSocketMessage\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Handle serverSocketMessageTypes.MESSAGES
129,187
04.11.2018 22:25:07
18,000
8090e91d44fa25312dc8d7be81210003867994d6
Fix bug preventing response to first message And also don't send any requests response if only activity update request. Also fix bug causing Redis subscriptions to immediately unsubscribe.
[ { "change_type": "MODIFY", "old_path": "lib/socket/inflight-requests.js", "new_path": "lib/socket/inflight-requests.js", "diff": "@@ -126,7 +126,8 @@ class InflightRequests {\nresolveRequestsForMessage(message: ServerSocketMessage) {\nfor (let inflightRequest of this.data) {\nif (\n- !message.responseTo ||\n+ message.responseTo === null ||\n+ message.responseTo === undefined ||\ninflightRequest.messageID !== message.responseTo\n) {\ncontinue;\n" }, { "change_type": "MODIFY", "old_path": "server/src/socket/redis.js", "new_path": "server/src/socket/redis.js", "diff": "@@ -78,14 +78,13 @@ class RedisSubscriber {\nif (!message) {\nreturn;\n}\n- if (\n- message.type === redisMessageTypes.START_SUBSCRIPTION &&\n- message.instanceID === this.instanceID\n- ) {\n+ if (message.type === redisMessageTypes.START_SUBSCRIPTION) {\n+ if (message.instanceID === this.instanceID) {\nreturn;\n} else {\nthis.quit();\n}\n+ }\nthis.onMessageCallback(message);\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/socket/socket.js", "new_path": "server/src/socket/socket.js", "diff": "@@ -498,7 +498,8 @@ class Socket {\n// Clients that support sockets always keep their server aware of their\n// device token, without needing any requests\nconst filteredServerRequests = serverRequests.filter(\n- request => request.type !== serverRequestTypes.DEVICE_TOKEN,\n+ request => request.type !== serverRequestTypes.DEVICE_TOKEN &&\n+ request.type !== serverRequestTypes.INITIAL_ACTIVITY_UPDATES,\n);\nif (filteredServerRequests.length > 0 || clientResponses.length > 0) {\n// We send this message first since the STATE_SYNC triggers the client's\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Fix bug preventing response to first message And also don't send any requests response if only activity update request. Also fix bug causing Redis subscriptions to immediately unsubscribe.
129,187
05.11.2018 10:07:38
18,000
c993a9fcf3a816077895aeedfedc97df879dfd08
[native] Use background color from React Navigation 2 React Navigation 3 changed it to white, and `cardStyle` doesn't seem to be able to override it anymore. (https://github.com/react-navigation/react-navigation-stack/issues/53)
[ { "change_type": "MODIFY", "old_path": "native/chat/chat-thread-list.react.js", "new_path": "native/chat/chat-thread-list.react.js", "diff": "@@ -294,6 +294,7 @@ const styles = StyleSheet.create({\n},\ncontainer: {\nflex: 1,\n+ backgroundColor: \"#E9E9EF\",\n},\nsearchContainer: {\nbackgroundColor: '#F6F6F6',\n" }, { "change_type": "MODIFY", "old_path": "native/chat/compose-thread.react.js", "new_path": "native/chat/compose-thread.react.js", "diff": "@@ -496,6 +496,7 @@ class InnerComposeThread extends React.PureComponent<Props, State> {\nconst styles = StyleSheet.create({\ncontainer: {\nflex: 1,\n+ backgroundColor: \"#E9E9EF\",\n},\nparentThreadRow: {\nflexDirection: 'row',\n" }, { "change_type": "MODIFY", "old_path": "native/chat/message-list.react.js", "new_path": "native/chat/message-list.react.js", "diff": "@@ -535,6 +535,7 @@ class InnerMessageList extends React.PureComponent<Props, State> {\nconst styles = StyleSheet.create({\ncontainer: {\nflex: 1,\n+ backgroundColor: \"#E9E9EF\",\n},\nflatListContainer: {\nflex: 1,\n" }, { "change_type": "MODIFY", "old_path": "native/chat/settings/delete-thread.react.js", "new_path": "native/chat/settings/delete-thread.react.js", "diff": "@@ -143,7 +143,10 @@ class InnerDeleteThread extends React.PureComponent<Props, State> {\n: <Text style={styles.saveText}>Delete thread</Text>;\nconst threadInfo = InnerDeleteThread.getThreadInfo(this.props);\nreturn (\n- <ScrollView contentContainerStyle={styles.scrollView}>\n+ <ScrollView\n+ contentContainerStyle={styles.scrollView}\n+ style={styles.container}\n+ >\n<View>\n<Text style={styles.warningText}>\n{`The thread \"${threadInfo.uiName}\" will be permanently deleted. `}\n@@ -239,6 +242,9 @@ class InnerDeleteThread extends React.PureComponent<Props, State> {\n}\nconst styles = StyleSheet.create({\n+ container: {\n+ backgroundColor: \"#E9E9EF\",\n+ },\nscrollView: {\npaddingTop: 24,\n},\n" }, { "change_type": "MODIFY", "old_path": "native/chat/settings/thread-settings.react.js", "new_path": "native/chat/settings/thread-settings.react.js", "diff": "@@ -562,6 +562,7 @@ class InnerThreadSettings extends React.PureComponent<Props, State> {\nreturn (\n<FlatList\ndata={listData}\n+ style={styles.container}\ncontentContainerStyle={styles.flatList}\nrenderItem={this.renderItem}\n/>\n@@ -716,6 +717,9 @@ class InnerThreadSettings extends React.PureComponent<Props, State> {\n}\nconst styles = StyleSheet.create({\n+ container: {\n+ backgroundColor: \"#E9E9EF\",\n+ },\nflatList: {\npaddingVertical: 16,\n},\n" }, { "change_type": "MODIFY", "old_path": "native/more/build-info.react.js", "new_path": "native/more/build-info.react.js", "diff": "@@ -15,7 +15,10 @@ class BuildInfo extends React.PureComponent<Props> {\nrender() {\nreturn (\n- <ScrollView contentContainerStyle={styles.scrollView}>\n+ <ScrollView\n+ contentContainerStyle={styles.scrollView}\n+ style={styles.container}\n+ >\n<View style={styles.section}>\n<View style={styles.row}>\n<Text style={styles.label}>Release</Text>\n@@ -44,6 +47,9 @@ class BuildInfo extends React.PureComponent<Props> {\n}\nconst styles = StyleSheet.create({\n+ container: {\n+ backgroundColor: \"#E9E9EF\",\n+ },\nscrollView: {\npaddingTop: 24,\n},\n" }, { "change_type": "MODIFY", "old_path": "native/more/delete-account.react.js", "new_path": "native/more/delete-account.react.js", "diff": "@@ -107,7 +107,10 @@ class InnerDeleteAccount extends React.PureComponent<Props, State> {\n? <ActivityIndicator size=\"small\" color=\"white\" />\n: <Text style={styles.saveText}>Delete account</Text>;\nreturn (\n- <ScrollView contentContainerStyle={styles.scrollView}>\n+ <ScrollView\n+ contentContainerStyle={styles.scrollView}\n+ style={styles.container}\n+ >\n<View>\n<Text style={styles.warningText}>\nYour account will be permanently deleted.\n@@ -210,6 +213,9 @@ class InnerDeleteAccount extends React.PureComponent<Props, State> {\n}\nconst styles = StyleSheet.create({\n+ container: {\n+ backgroundColor: \"#E9E9EF\",\n+ },\nscrollView: {\npaddingTop: 24,\n},\n" }, { "change_type": "MODIFY", "old_path": "native/more/dev-tools.react.js", "new_path": "native/more/dev-tools.react.js", "diff": "@@ -171,6 +171,7 @@ class InnerDevTools extends React.PureComponent<Props> {\nconst styles = StyleSheet.create({\ncontainer: {\nflex: 1,\n+ backgroundColor: \"#E9E9EF\",\n},\nscrollView: {\npaddingTop: 24,\n" }, { "change_type": "MODIFY", "old_path": "native/more/edit-email.react.js", "new_path": "native/more/edit-email.react.js", "diff": "@@ -113,7 +113,10 @@ class InnerEditEmail extends React.PureComponent<Props, State> {\n? <ActivityIndicator size=\"small\" color=\"white\" />\n: <Text style={styles.saveText}>Save</Text>;\nreturn (\n- <ScrollView contentContainerStyle={styles.scrollView}>\n+ <ScrollView\n+ contentContainerStyle={styles.scrollView}\n+ style={styles.container}\n+ >\n<Text style={styles.header}>EMAIL</Text>\n<View style={styles.section}>\n<TextInput\n@@ -287,6 +290,9 @@ class InnerEditEmail extends React.PureComponent<Props, State> {\n}\nconst styles = StyleSheet.create({\n+ container: {\n+ backgroundColor: \"#E9E9EF\",\n+ },\nscrollView: {\npaddingTop: 24,\n},\n" }, { "change_type": "MODIFY", "old_path": "native/more/edit-password.react.js", "new_path": "native/more/edit-password.react.js", "diff": "@@ -121,7 +121,10 @@ class InnerEditPassword extends React.PureComponent<Props, State> {\n? <ActivityIndicator size=\"small\" color=\"white\" />\n: <Text style={styles.saveText}>Save</Text>;\nreturn (\n- <ScrollView contentContainerStyle={styles.scrollView}>\n+ <ScrollView\n+ contentContainerStyle={styles.scrollView}\n+ style={styles.container}\n+ >\n<Text style={styles.header}>CURRENT PASSWORD</Text>\n<View style={styles.section}>\n<View style={styles.row}>\n@@ -343,6 +346,9 @@ class InnerEditPassword extends React.PureComponent<Props, State> {\n}\nconst styles = StyleSheet.create({\n+ container: {\n+ backgroundColor: \"#E9E9EF\",\n+ },\nscrollView: {\npaddingTop: 24,\n},\n" }, { "change_type": "MODIFY", "old_path": "native/more/more-screen.react.js", "new_path": "native/more/more-screen.react.js", "diff": "@@ -297,6 +297,7 @@ class InnerMoreScreen extends React.PureComponent<Props> {\nconst styles = StyleSheet.create({\ncontainer: {\nflex: 1,\n+ backgroundColor: \"#E9E9EF\",\n},\nscrollView: {\npaddingVertical: 24,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Use background color from React Navigation 2 React Navigation 3 changed it to white, and `cardStyle` doesn't seem to be able to override it anymore. (https://github.com/react-navigation/react-navigation-stack/issues/53)
129,187
05.11.2018 10:10:46
18,000
918be67c3b852f22ac40046c14cb4d0d6fa4859b
[native] Don't log the user out during REHYDRATE This allows `navInfo` to get rehydrated on dev again.
[ { "change_type": "MODIFY", "old_path": "native/redux-setup.js", "new_path": "native/redux-setup.js", "diff": "@@ -30,7 +30,7 @@ import invariant from 'invariant';\nimport thunk from 'redux-thunk';\nimport { createStore as defaultCreateStore, applyMiddleware } from 'redux';\nimport { composeWithDevTools } from 'redux-devtools-extension';\n-import { persistStore, persistReducer } from 'redux-persist';\n+import { persistStore, persistReducer, REHYDRATE } from 'redux-persist';\nimport PropTypes from 'prop-types';\nimport { NavigationActions, StackActions } from 'react-navigation';\nimport {\n@@ -363,7 +363,10 @@ function validateState(\n};\n}\n- if (!state.currentUserInfo || state.currentUserInfo.anonymous) {\n+ if (\n+ action.type !== REHYDRATE &&\n+ (!state.currentUserInfo || state.currentUserInfo.anonymous)\n+ ) {\nconst navInfo = resetNavInfoAndEnsureLoggedOutModalPresence(state.navInfo);\nif (navInfo.navigationState !== state.navInfo.navigationState) {\nstate = { ...state, navInfo };\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Don't log the user out during REHYDRATE This allows `navInfo` to get rehydrated on dev again.
129,187
05.11.2018 18:32:30
18,000
569ab429ccf82391c421541cbe2ec1d564f8b041
[lib] Use leading & trailing debounce for Socket reconnect
[ { "change_type": "MODIFY", "old_path": "lib/socket/socket.react.js", "new_path": "lib/socket/socket.react.js", "diff": "@@ -42,7 +42,7 @@ import type { LogInExtraInfo, LogOutResult } from '../types/account-types';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport invariant from 'invariant';\n-import _debounce from 'lodash/fp/debounce';\n+import _debounce from 'lodash/debounce';\nimport { getConfig } from '../utils/config';\nimport {\n@@ -204,17 +204,17 @@ class Socket extends React.PureComponent<Props, State> {\nif (inflightRequests && !inflightRequests.allRequestsResolved) {\nreturn;\n}\n- this.props.dispatchActionPayload(\n- updateConnectionStatusActionType,\n- { status: \"disconnected\" },\n- );\nregisterActiveWebSocket(null);\nif (this.socket && this.socket.readyState < 2) {\n// If it's not closing already, close it\nthis.socket.close();\n- this.socket = null;\n}\n+ this.socket = null;\nthis.stopPing();\n+ this.props.dispatchActionPayload(\n+ updateConnectionStatusActionType,\n+ { status: \"disconnected\" },\n+ );\nthis.setState({ inflightRequests: null });\nif (this.reopenConnectionAfterClosing) {\nthis.reopenConnectionAfterClosing = false;\n@@ -224,9 +224,11 @@ class Socket extends React.PureComponent<Props, State> {\n}\n}\n- reconnect = _debounce(2000)(() => {\n- this.openSocket(\"reconnecting\");\n- })\n+ reconnect = _debounce(\n+ () => this.openSocket(\"reconnecting\"),\n+ 2000,\n+ { leading: true, trailing: true },\n+ )\ncomponentDidMount() {\nif (this.props.active) {\n@@ -236,6 +238,7 @@ class Socket extends React.PureComponent<Props, State> {\ncomponentWillUnmount() {\nthis.closeSocket();\n+ this.reconnect.cancel();\n}\ncomponentDidUpdate(prevProps: Props) {\n@@ -395,6 +398,8 @@ class Socket extends React.PureComponent<Props, State> {\nonClose = (event: CloseEvent) => {\nconst { status } = this.props.connection;\n+ this.socket = null;\n+ this.stopPing();\nif (\nstatus !== \"disconnecting\" &&\nstatus !== \"forcedDisconnecting\" &&\n@@ -412,8 +417,6 @@ class Socket extends React.PureComponent<Props, State> {\n{ status: \"disconnected\" },\n);\n}\n- this.socket = null;\n- this.stopPing();\n}\nhandleTimeout() {\n@@ -421,23 +424,23 @@ class Socket extends React.PureComponent<Props, State> {\nthis.setState({ inflightRequests: null });\nconst { status } = this.props.connection;\nif (this.socket && this.socket.readyState < 2) {\n+ // We just call close, onClose will handle the rest\n+ this.socket.close();\nif (status !== \"disconnecting\") {\nthis.props.dispatchActionPayload(\nupdateConnectionStatusActionType,\n{ status: \"disconnecting\" },\n);\n}\n- // We just call close, onClose will handle the rest\n- this.socket.close();\n} else {\n+ this.socket = null;\n+ this.stopPing();\nif (status !== \"disconnected\") {\nthis.props.dispatchActionPayload(\nupdateConnectionStatusActionType,\n{ status: \"disconnected\" },\n);\n}\n- this.socket = null;\n- this.stopPing();\n}\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Use leading & trailing debounce for Socket reconnect
129,187
05.11.2018 18:38:54
18,000
7ca25be4a9e759f8de3f5b0b047277c8aea14f91
[server] Use debounce for server socket timeout
[ { "change_type": "MODIFY", "old_path": "server/src/socket/socket.js", "new_path": "server/src/socket/socket.js", "diff": "@@ -24,6 +24,7 @@ import { redisMessageTypes, type RedisMessage } from 'lib/types/redis-types';\nimport t from 'tcomb';\nimport invariant from 'invariant';\n+import _debounce from 'lodash/debounce';\nimport { ServerError } from 'lib/utils/errors';\nimport { mostRecentMessageTimestamp } from 'lib/shared/message-utils';\n@@ -151,7 +152,6 @@ class Socket {\nredis: ?RedisSubscriber;\nupdateActivityTimeIntervalID: ?IntervalID;\n- pingTimeoutID: ?TimeoutID;\nconstructor(ws: WebSocket, httpRequest: $Request) {\nthis.ws = ws;\n@@ -313,7 +313,7 @@ class Socket {\nclearInterval(this.updateActivityTimeIntervalID);\nthis.updateActivityTimeIntervalID = null;\n}\n- this.clearTimeout();\n+ this.resetTimeout.cancel();\nif (this.viewer && this.viewer.hasSessionInfo) {\nawait deleteActivityForViewerSession(this.viewer);\n}\n@@ -681,21 +681,13 @@ class Socket {\nhandleAsyncPromise(updateActivityTime(viewer));\n}\n- clearTimeout() {\n- if (this.pingTimeoutID) {\n- clearTimeout(this.pingTimeoutID);\n- this.pingTimeoutID = null;\n- }\n- }\n-\n- resetTimeout() {\n- this.clearTimeout();\n- this.pingTimeoutID = setTimeout(this.timeout, serverRequestSocketTimeout);\n- }\n-\n- timeout = () => {\n- this.ws.terminate();\n- }\n+ // The Socket will timeout by calling this.ws.terminate()\n+ // serverRequestSocketTimeout milliseconds after the last\n+ // time resetTimeout is called\n+ resetTimeout = _debounce(\n+ () => this.ws.terminate(),\n+ serverRequestSocketTimeout,\n+ )\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Use debounce for server socket timeout
129,187
05.11.2018 20:43:50
18,000
81b4a636da611ee0529bbc21c294da40fb049d41
Logic for server socket to initiate state check mechanism State check occurs once every `sessionCheckFrequency`ms, but any activity debounces state check by `stateCheckInactivityActivationInterval`ms.
[ { "change_type": "MODIFY", "old_path": "lib/types/session-types.js", "new_path": "lib/types/session-types.js", "diff": "@@ -12,7 +12,9 @@ import PropTypes from 'prop-types';\nexport const cookieLifetime = 30*24*60*60*1000; // in milliseconds\n//export const sessionCheckFrequency = 3*60*60*1000; // in milliseconds\n-export const sessionCheckFrequency = 0;\n+export const sessionCheckFrequency = 0; // in milliseconds\n+// How long the server debounces after activity before initiating a state check\n+export const stateCheckInactivityActivationInterval = 3000; // in milliseconds\n// On native, we specify the cookie directly in the request and response body.\n// We do this because:\n" }, { "change_type": "MODIFY", "old_path": "lib/types/socket-types.js", "new_path": "lib/types/socket-types.js", "diff": "@@ -159,7 +159,7 @@ export type StateSyncServerSocketMessage = {|\n|};\nexport type RequestsServerSocketMessage = {|\ntype: 1,\n- responseTo: number,\n+ responseTo?: number,\npayload: {|\nserverRequests: $ReadOnlyArray<ServerRequest>,\n|},\n" }, { "change_type": "MODIFY", "old_path": "server/src/socket/socket.js", "new_path": "server/src/socket/socket.js", "diff": "@@ -17,7 +17,11 @@ import {\nstateSyncPayloadTypes,\nserverSocketMessageTypes,\n} from 'lib/types/socket-types';\n-import { cookieSources } from 'lib/types/session-types';\n+import {\n+ cookieSources,\n+ sessionCheckFrequency,\n+ stateCheckInactivityActivationInterval,\n+} from 'lib/types/session-types';\nimport { defaultNumberPerThread } from 'lib/types/message-types';\nimport { serverRequestTypes } from 'lib/types/request-types';\nimport { redisMessageTypes, type RedisMessage } from 'lib/types/redis-types';\n@@ -144,6 +148,11 @@ function onConnection(ws: WebSocket, req: $Request) {\nnew Socket(ws, req);\n}\n+type StateCheckConditions = {|\n+ activityRecentlyOccurred: bool,\n+ stateCheckOngoing: bool,\n+|};\n+\nclass Socket {\nws: WebSocket;\n@@ -153,6 +162,12 @@ class Socket {\nupdateActivityTimeIntervalID: ?IntervalID;\n+ stateCheckConditions: StateCheckConditions = {\n+ activityRecentlyOccurred: true,\n+ stateCheckOngoing: false,\n+ };\n+ stateCheckTimeoutID: ?TimeoutID;\n+\nconstructor(ws: WebSocket, httpRequest: $Request) {\nthis.ws = ws;\nthis.httpRequest = httpRequest;\n@@ -237,6 +252,7 @@ class Socket {\nif (responseTo !== null) {\nerrorMessage.responseTo = responseTo;\n}\n+ this.markActivityOccurred();\nthis.sendMessage(errorMessage);\nreturn;\n}\n@@ -304,6 +320,8 @@ class Socket {\nthis.ws.close(4102, error.message);\n} else if (error.message === \"session_mutated_from_socket\") {\nthis.ws.close(4103, error.message);\n+ } else {\n+ this.markActivityOccurred();\n}\n}\n}\n@@ -313,7 +331,9 @@ class Socket {\nclearInterval(this.updateActivityTimeIntervalID);\nthis.updateActivityTimeIntervalID = null;\n}\n+ this.clearStateCheckTimeout();\nthis.resetTimeout.cancel();\n+ this.debouncedAfterActivity.cancel();\nif (this.viewer && this.viewer.hasSessionInfo) {\nawait deleteActivityForViewerSession(this.viewer);\n}\n@@ -337,14 +357,18 @@ class Socket {\nmessage: ClientSocketMessage,\n): Promise<ServerSocketMessage[]> {\nif (message.type === clientSocketMessageTypes.INITIAL) {\n+ this.markActivityOccurred();\nreturn await this.handleInitialClientSocketMessage(message);\n} else if (message.type === clientSocketMessageTypes.RESPONSES) {\n+ this.markActivityOccurred();\nreturn await this.handleResponsesClientSocketMessage(message);\n} else if (message.type === clientSocketMessageTypes.ACTIVITY_UPDATES) {\n+ this.markActivityOccurred();\nreturn await this.handleActivityUpdatesClientSocketMessage(message);\n} else if (message.type === clientSocketMessageTypes.PING) {\nreturn await this.handlePingClientSocketMessage(message);\n} else if (message.type === clientSocketMessageTypes.ACK_UPDATES) {\n+ this.markActivityOccurred();\nreturn await this.handleAckUpdatesClientSocketMessage(message);\n}\nreturn [];\n@@ -380,7 +404,7 @@ class Socket {\nconst threadSelectionCriteria = { threadCursors, joinedThreads: true };\nconst [\nfetchMessagesResult,\n- { serverRequests, stateCheckStatus, activityUpdateResult },\n+ { serverRequests, activityUpdateResult },\n] = await Promise.all([\nfetchMessageInfosSince(\nviewer,\n@@ -440,6 +464,11 @@ class Socket {\npayload,\n});\n} else {\n+ const {\n+ sessionUpdate,\n+ deltaEntryInfoResult,\n+ } = sessionInitializationResult;\n+\nconst promises = {};\npromises.activityUpdate = updateActivityTime(viewer);\npromises.deleteExpiredUpdates = deleteUpdatesBeforeTimeTargettingSession(\n@@ -451,10 +480,8 @@ class Socket {\noldUpdatesCurrentAsOf,\ncalendarQuery,\n);\n- if (stateCheckStatus) {\n- promises.stateCheck = checkState(viewer, stateCheckStatus, calendarQuery);\n- }\n- const { fetchUpdateResult, stateCheck } = await promiseAll(promises);\n+ promises.sessionUpdate = commitSessionUpdate(viewer, sessionUpdate);\n+ const { fetchUpdateResult } = await promiseAll(promises);\nconst updateUserInfos = fetchUpdateResult.userInfos;\nconst { updateInfos } = fetchUpdateResult;\n@@ -467,16 +494,6 @@ class Socket {\ncurrentAsOf: newUpdatesCurrentAsOf,\n};\n- let sessionUpdate = sessionInitializationResult.sessionUpdate;\n- if (stateCheck && stateCheck.sessionUpdate) {\n- sessionUpdate = { ...sessionUpdate, ...stateCheck.sessionUpdate };\n- }\n- await commitSessionUpdate(viewer, sessionUpdate);\n-\n- if (stateCheck && stateCheck.checkStateRequest) {\n- serverRequests.push(stateCheck.checkStateRequest);\n- }\n-\nresponses.push({\ntype: serverSocketMessageTypes.STATE_SYNC,\nresponseTo: message.id,\n@@ -484,12 +501,11 @@ class Socket {\ntype: stateSyncPayloadTypes.INCREMENTAL,\nmessagesResult,\nupdatesResult,\n- deltaEntryInfos:\n- sessionInitializationResult.deltaEntryInfoResult.rawEntryInfos,\n+ deltaEntryInfos: deltaEntryInfoResult.rawEntryInfos,\nuserInfos: values({\n...fetchMessagesResult.userInfos,\n...updateUserInfos,\n- ...sessionInitializationResult.deltaEntryInfoResult.userInfos,\n+ ...deltaEntryInfoResult.userInfos,\n}),\n},\n});\n@@ -545,6 +561,7 @@ class Socket {\n);\nif (sessionUpdate) {\nawait commitSessionUpdate(viewer, sessionUpdate);\n+ this.setStateCheckConditions({ stateCheckOngoing: false });\n}\nif (checkStateRequest) {\nserverRequests.push(checkStateRequest);\n@@ -626,6 +643,7 @@ class Socket {\n);\nreturn;\n}\n+ this.markActivityOccurred();\nthis.sendMessage({\ntype: serverSocketMessageTypes.UPDATES,\npayload: {\n@@ -651,6 +669,7 @@ class Socket {\n);\nreturn;\n}\n+ this.markActivityOccurred();\nthis.sendMessage({\ntype: serverSocketMessageTypes.MESSAGES,\npayload: {\n@@ -673,6 +692,7 @@ class Socket {\nthis.updateActivityTime,\nfocusedTableRefreshFrequency,\n);\n+ this.handleStateCheckConditionsUpdate();\n}\nupdateActivityTime = () => {\n@@ -689,6 +709,77 @@ class Socket {\nserverRequestSocketTimeout,\n)\n+ debouncedAfterActivity = _debounce(\n+ () => this.setStateCheckConditions({ activityRecentlyOccurred: false }),\n+ stateCheckInactivityActivationInterval,\n+ )\n+\n+ markActivityOccurred = () => {\n+ this.setStateCheckConditions({ activityRecentlyOccurred: true });\n+ this.debouncedAfterActivity();\n+ }\n+\n+ clearStateCheckTimeout() {\n+ if (this.stateCheckTimeoutID) {\n+ clearTimeout(this.stateCheckTimeoutID);\n+ this.stateCheckTimeoutID = null;\n+ }\n+ }\n+\n+ setStateCheckConditions(newConditions: $Shape<StateCheckConditions>) {\n+ this.stateCheckConditions = {\n+ ...this.stateCheckConditions,\n+ ...newConditions,\n+ };\n+ this.handleStateCheckConditionsUpdate();\n+ }\n+\n+ get stateCheckCanStart() {\n+ return Object.values(this.stateCheckConditions).every(cond => !cond);\n+ }\n+\n+ handleStateCheckConditionsUpdate() {\n+ if (!this.stateCheckCanStart) {\n+ this.clearStateCheckTimeout();\n+ return;\n+ }\n+ if (this.stateCheckTimeoutID) {\n+ return;\n+ }\n+ const { viewer } = this;\n+ if (!viewer) {\n+ return;\n+ }\n+ const timeUntilStateCheck =\n+ viewer.sessionLastValidated + sessionCheckFrequency - Date.now();\n+ if (timeUntilStateCheck <= 0) {\n+ this.initiateStateCheck();\n+ }\n+ this.stateCheckTimeoutID = setTimeout(\n+ this.initiateStateCheck,\n+ timeUntilStateCheck,\n+ );\n+ }\n+\n+ initiateStateCheck = async () => {\n+ this.setStateCheckConditions({ stateCheckOngoing: true });\n+\n+ const { viewer } = this;\n+ invariant(viewer, \"should be set\");\n+\n+ const { checkStateRequest } = await checkState(\n+ viewer,\n+ { status: \"state_check\" },\n+ viewer.calendarQuery,\n+ );\n+ invariant(checkStateRequest, \"should be set\");\n+\n+ this.sendMessage({\n+ type: serverSocketMessageTypes.REQUESTS,\n+ payload: { serverRequests: [ checkStateRequest ] },\n+ });\n+ }\n+\n}\nexport {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Logic for server socket to initiate state check mechanism State check occurs once every `sessionCheckFrequency`ms, but any activity debounces state check by `stateCheckInactivityActivationInterval`ms.