Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Added an example of server selection by latency #1516

Open
wants to merge 7 commits into
base: development
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions src/common/api/hive.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Client, RCAPI, utils } from "@hiveio/dhive";
import { Client, RCAPI } from "@hiveio/dhive";

import { RCAccount } from "@hiveio/dhive/lib/chain/rc";

import { TrendingTag } from "../store/trending-tags/types";
import { DynamicProps } from "../store/dynamic-props/types";
import { FullAccount, AccountProfile, AccountFollowStats } from "../store/accounts/types";
import { AccountFollowStats, AccountProfile, FullAccount } from "../store/accounts/types";
import { Entry } from "../store/entries/types";

import parseAsset from "../helper/parse-asset";
Expand All @@ -14,6 +14,7 @@ import isCommunity from "../helper/is-community";
import SERVERS from "../constants/servers.json";
import { dataLimit } from "./bridge";
import moment, { Moment } from "moment";
import { useHiveClientQuery } from "../core/hive";

export const client = new Client(SERVERS, {
timeout: 3000,
Expand Down Expand Up @@ -147,6 +148,7 @@ export interface Reputations {
account: string;
reputation: number;
}

interface ApiError {
error: string;
data: any;
Expand Down Expand Up @@ -663,3 +665,17 @@ export const getRcOperationStats = (): Promise<any> => client.call("rc_api", "ge

export const getContentReplies = (author: string, permlink: string): Promise<Entry[] | null> =>
client.call("condenser_api", "get_content_replies", { author, permlink });

export const getPostQuery = (username?: string, permlink?: string) =>
useHiveClientQuery<Entry>("condenser_api", "get_content", [username, permlink], {
enabled: !!username && !!permlink
});

export const getProposalsQuery = () =>
useHiveClientQuery<{ proposals: Proposal[] }>("database_api", "list_proposals", {
start: [-1],
limit: 500,
order: "by_total_votes",
order_direction: "descending",
status: "all"
});
187 changes: 101 additions & 86 deletions src/common/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,11 @@ import loadable from "@loadable/component";
import Announcement from "./components/announcement";
import FloatingFAQ from "./components/floating-faq";
import { useMappedStore } from "./store/use-mapped-store";
import { EntriesCacheManager } from "./core";
import { CoreProvider, EntriesCacheManager } from "./core";

import { UserActivityRecorder } from "./components/user-activity-recorder";
import { BottomStatusBar } from "./components/bottom-status-bar";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";

// Define lazy pages
const ProfileContainer = loadable(() => import("./pages/profile-functional"));
Expand Down Expand Up @@ -92,91 +94,104 @@ const App = (props: any) => {
}, []);

return (
<EntriesCacheManager>
{/*Excluded from production*/}
{/*<ReactQueryDevtools initialIsOpen={false} />*/}
<Tracker />
<UserActivityRecorder />
<Switch>
<Route exact={true} path={routes.HOME} component={EntryIndexContainer} />
<Route exact={true} strict={true} path={routes.FILTER} component={EntryIndexContainer} />
<Route exact={true} strict={true} path={routes.USER_FEED} component={EntryIndexContainer} />
<Route exact={true} strict={true} path={routes.PURCHASE} component={PurchasePage} />
<Route exact={true} strict={true} path={routes.USER} component={ProfilePage} />
<Route exact={true} strict={true} path={routes.USER_SECTION} component={ProfilePage} />
<Route exact={true} strict={true} path={routes.ENTRY} component={EntryPage} />
<Route exact={true} strict={true} path={routes.COMMUNITIES} component={CommunitiesPage} />
<Route
exact={true}
strict={true}
path={routes.COMMUNITIES_CREATE}
component={CommunityCreatePage}
/>
<Route
exact={true}
strict={true}
path={routes.COMMUNITIES_CREATE_HS}
component={CommunityCreateHSPage}
/>
<Route exact={true} strict={true} path={routes.COMMUNITY} component={CommunityPage} />
<Route
exact={true}
strict={true}
path={routes.FILTER_TAG}
component={EntryIndexContainer}
/>
<Route exact={true} strict={true} path={routes.DISCOVER} component={DiscoverPage} />
<Route exact={true} path={routes.SEARCH} component={SearchPageContainer} />
<Route exact={true} path={routes.SEARCH_MORE} component={SearchMorePageContainer} />
<Route exact={true} strict={true} path={routes.AUTH} component={AuthPage} />
<Route exact={true} strict={true} path={routes.SUBMIT} component={SubmitPage} />
<Route exact={true} strict={true} path={routes.MARKET} component={MarketPage} />
<Route exact={true} strict={true} path={routes.EDIT} component={SubmitPage} />
<Route exact={true} strict={true} path={routes.SIGN_UP} component={SignUpPage} />
<Route exact={true} strict={true} path={routes.ONBOARD} component={OnboardPage} />
<Route exact={true} strict={true} path={routes.EDIT_DRAFT} component={SubmitPage} />
<Route exact={true} strict={true} path={routes.WITNESSES} component={WitnessesPage} />
<Route
exact={true}
strict={true}
path={routes.PROPOSALS}
component={ProposalsIndexContainer}
/>
<Route
exact={true}
strict={true}
path={routes.PROPOSAL_DETAIL}
component={ProposalDetailContainer}
/>
<Route
exact={true}
strict={true}
path={`/me${routes.PROPOSAL_DETAIL}`}
component={ProposalDetailContainer}
/>
<Route exact={true} strict={true} path={routes.ABOUT} component={AboutPage} />
<Route exact={true} strict={true} path={routes.GUESTS} component={GuestPostPage} />
<Route exact={true} strict={true} path={routes.CONTRIBUTE} component={ContributePage} />
<Route exact={true} strict={true} path={routes.PRIVACY} component={PrivacyPage} />
<Route exact={true} strict={true} path={routes.WHITE_PAPER} component={WhitePaperPage} />
<Route exact={true} strict={true} path={routes.TOS} component={TosPage} />
<Route exact={true} strict={true} path={routes.FAQ} component={FaqPage} />
<Route exact={true} strict={true} path={routes.CONTRIBUTORS} component={ContributorsPage} />
<Route
exact={true}
strict={true}
path={routes.DECKS}
component={global.usePrivate ? DecksPage : NotFound}
/>
<Route component={NotFound} />
</Switch>

<Announcement activeUser={props.activeUser} />
<FloatingFAQ />
<div id="popper-container" />
<div id="modal-overlay-container" />
<div id="modal-dialog-container" />
</EntriesCacheManager>
<CoreProvider>
<EntriesCacheManager>
{/*Excluded from production*/}
<ReactQueryDevtools initialIsOpen={false} />
<Tracker />
<UserActivityRecorder />
<Switch>
<Route exact={true} path={routes.HOME} component={EntryIndexContainer} />
<Route exact={true} strict={true} path={routes.FILTER} component={EntryIndexContainer} />
<Route
exact={true}
strict={true}
path={routes.USER_FEED}
component={EntryIndexContainer}
/>
<Route exact={true} strict={true} path={routes.PURCHASE} component={PurchasePage} />
<Route exact={true} strict={true} path={routes.USER} component={ProfilePage} />
<Route exact={true} strict={true} path={routes.USER_SECTION} component={ProfilePage} />
<Route exact={true} strict={true} path={routes.ENTRY} component={EntryPage} />
<Route exact={true} strict={true} path={routes.COMMUNITIES} component={CommunitiesPage} />
<Route
exact={true}
strict={true}
path={routes.COMMUNITIES_CREATE}
component={CommunityCreatePage}
/>
<Route
exact={true}
strict={true}
path={routes.COMMUNITIES_CREATE_HS}
component={CommunityCreateHSPage}
/>
<Route exact={true} strict={true} path={routes.COMMUNITY} component={CommunityPage} />
<Route
exact={true}
strict={true}
path={routes.FILTER_TAG}
component={EntryIndexContainer}
/>
<Route exact={true} strict={true} path={routes.DISCOVER} component={DiscoverPage} />
<Route exact={true} path={routes.SEARCH} component={SearchPageContainer} />
<Route exact={true} path={routes.SEARCH_MORE} component={SearchMorePageContainer} />
<Route exact={true} strict={true} path={routes.AUTH} component={AuthPage} />
<Route exact={true} strict={true} path={routes.SUBMIT} component={SubmitPage} />
<Route exact={true} strict={true} path={routes.MARKET} component={MarketPage} />
<Route exact={true} strict={true} path={routes.EDIT} component={SubmitPage} />
<Route exact={true} strict={true} path={routes.SIGN_UP} component={SignUpPage} />
<Route exact={true} strict={true} path={routes.ONBOARD} component={OnboardPage} />
<Route exact={true} strict={true} path={routes.EDIT_DRAFT} component={SubmitPage} />
<Route exact={true} strict={true} path={routes.WITNESSES} component={WitnessesPage} />
<Route
exact={true}
strict={true}
path={routes.PROPOSALS}
component={ProposalsIndexContainer}
/>
<Route
exact={true}
strict={true}
path={routes.PROPOSAL_DETAIL}
component={ProposalDetailContainer}
/>
<Route
exact={true}
strict={true}
path={`/me${routes.PROPOSAL_DETAIL}`}
component={ProposalDetailContainer}
/>
<Route exact={true} strict={true} path={routes.ABOUT} component={AboutPage} />
<Route exact={true} strict={true} path={routes.GUESTS} component={GuestPostPage} />
<Route exact={true} strict={true} path={routes.CONTRIBUTE} component={ContributePage} />
<Route exact={true} strict={true} path={routes.PRIVACY} component={PrivacyPage} />
<Route exact={true} strict={true} path={routes.WHITE_PAPER} component={WhitePaperPage} />
<Route exact={true} strict={true} path={routes.TOS} component={TosPage} />
<Route exact={true} strict={true} path={routes.FAQ} component={FaqPage} />
<Route
exact={true}
strict={true}
path={routes.CONTRIBUTORS}
component={ContributorsPage}
/>
<Route
exact={true}
strict={true}
path={routes.DECKS}
component={global.usePrivate ? DecksPage : NotFound}
/>
<Route component={NotFound} />
</Switch>

<Announcement activeUser={props.activeUser} />
<FloatingFAQ />
<BottomStatusBar />
<div id="popper-container" />
<div id="modal-overlay-container" />
<div id="modal-dialog-container" />
</EntriesCacheManager>
</CoreProvider>
);
};

Expand Down
10 changes: 10 additions & 0 deletions src/common/components/bottom-status-bar/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import React from "react";
import { LatencyStatusBar } from "./latency-status-bar";

export function BottomStatusBar() {
return (
<div className="fixed flex justify-start bottom-0 left-0 right-0 duration-300 overflow-hidden border-r w-[2rem] border-[--border-color] hover:w-full whitespace-nowrap">
<LatencyStatusBar />
</div>
);
}
43 changes: 43 additions & 0 deletions src/common/components/bottom-status-bar/latency-status-bar.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import React, { useContext, useMemo } from "react";
import { CoreContext } from "../../core";
import { classNameObject } from "../../helper/class-name-object";

export function LatencyStatusBar() {
const { lastLatency, server } = useContext(CoreContext);

const status = useMemo(() => {
if (lastLatency < 150) {
return "Stable connection";
} else if (lastLatency !== Infinity) {
return "Poor connection";
} else {
return "No connection";
}
}, [lastLatency]);

return (
<div
className={classNameObject({
"bg-white flex leading-0 items-center gap-2 border-t text-xs font-[500] py-0.5 px-2 border-[--border-color]":
true,
"text-green-dark": status === "Stable connection",
"text-orange": status === "Poor connection",
"text-red": status === "No connection"
})}
>
<svg width={16} height={12} viewBox="0 0 24 16" fill="currentColor">
<rect width={2} height={4} x={0} y={12} />
<rect width={2} height={8} x={6} y={10} />
{lastLatency < 150 && <rect width={2} height={12} x={12} y={4} />}
{lastLatency < 150 && <rect width={2} height={16} x={18} />}
</svg>

<div className="flex items-center">
<span>
{lastLatency}ms – {status}
</span>
<div className="text-gray-600 dark:text-gray-400 pl-1">– {server}</div>
</div>
</div>
);
}
48 changes: 48 additions & 0 deletions src/common/core/core-provider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import React, { createContext, PropsWithChildren, useState } from "react";
import { Client } from "@hiveio/dhive";
import { useFindNearHiveServer } from "./hive";
import SERVERS from "../constants/servers.json";

export const CoreContext = createContext<{
hiveClient: Client | undefined;
lastLatency: number;
server: string;
setLastLatency: (v: number) => void;
setFindNearHiveServer: (v: boolean) => void;
}>({
lastLatency: 0,
server: "",
hiveClient: undefined,
setLastLatency: () => {},
setFindNearHiveServer: () => {}
});

export function CoreProvider(props: PropsWithChildren<unknown>) {
const [hiveClient, setHiveClient] = useState<Client | undefined>(undefined);
const [lastLatency, setLastLatency] = useState(0);
const [server, setServer] = useState("");
const [findNearHiveServer, setFindNearHiveServer] = useState(true);

useFindNearHiveServer(findNearHiveServer, (server, latency) => {
if (server) {
setServer(server);
}
setLastLatency(latency);
setHiveClient(
new Client(server ?? SERVERS, {
timeout: 3000,
failoverThreshold: 3,
consoleOnFailover: true
})
);
setFindNearHiveServer(false);
});

return (
<CoreContext.Provider
value={{ hiveClient, lastLatency, setFindNearHiveServer, setLastLatency, server }}
>
{props.children}
</CoreContext.Provider>
);
}
1 change: 1 addition & 0 deletions src/common/core/hive/errors/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./no-hive-client-error";
1 change: 1 addition & 0 deletions src/common/core/hive/errors/no-hive-client-error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export class NoHiveClientError extends Error {}
32 changes: 32 additions & 0 deletions src/common/core/hive/find-near-hive-server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import SERVERS from "../../constants/servers.json";
import { useGetRequestLatency } from "./get-request-latency";
import useDebounce from "react-use/lib/useDebounce";

export function useFindNearHiveServer(
isFind: boolean,
onFind?: (server: string | undefined, latency: number) => void
) {
const { mutateAsync: getRequestLatency } = useGetRequestLatency();

useDebounce(
async () => {
if (!isFind) {
return;
}

let minLatencyServer: [string | undefined, number] = [undefined, Infinity];
for (const server of SERVERS) {
try {
const { latency } = await getRequestLatency(server);
if (latency < minLatencyServer[1]) {
minLatencyServer = [server, latency];
}
} catch (e) {}
}

onFind?.(minLatencyServer[0], minLatencyServer[1]);
},
100,
[isFind]
);
}
Loading