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

Fix Chat button, autolock when worker dies & update cache times #3533

Merged
merged 4 commits into from
Apr 1, 2023
Merged
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
2 changes: 1 addition & 1 deletion backend/native/backpack-api/src/routes/v1/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import router from "./preferences";
router.get("/*", async (req, res) => {
const url = (req.path || "")?.slice(1);
try {
const req = request("https://swr.xnfts.dev/web/" + url.toString());
const req = request("https://swr.xnfts.dev/1min/" + url.toString());
req.on("error", function () {
// Failures here are common due to spam NFTs (domain expiry, bad certs,
// etc) so don't log anything to avoid cluttering the logs
Expand Down
9 changes: 8 additions & 1 deletion backend/workers/swr-cache/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,13 +90,20 @@ const executeRequest: (c: ExecutionContext, env: Env) => ExecuteRequest =
}

if (service === "web") {
const proxiedUrl = url.pathname.slice(1);
const fetched = await fetch(proxiedUrl);
const response = new Response(fetched.body, fetched);
return response;
}

if (service === "1min") {
const proxiedUrl = url.pathname.slice(1);
console.log("web", proxiedUrl);
const fetched = await fetch(proxiedUrl);
const response = new Response(fetched.body, fetched);
response.headers.set(
"Cache-Control",
`max-age=${1}, s-maxage=${1}, stale-while-revalidate=${5}`
`max-age=${60}, s-maxage=${60}, stale-while-revalidate=${60}`
);
return response;
}
Expand Down
10 changes: 4 additions & 6 deletions backend/workers/xnft-gateway/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ const executeRequest: (c: ExecutionContext, env: Env) => ExecuteRequest =
if (isImmutable) {
response.headers.set(
"Cache-Control",
`max-age=31536000, s-maxage=31536000, immutable`
);
`max-age=${60}, s-maxage=${60}, stale-while-revalidate=${60}`
); //1min swr
}
// WHITELIST SPECIAL CASE
else if (
Expand All @@ -64,10 +64,8 @@ const executeRequest: (c: ExecutionContext, env: Env) => ExecuteRequest =
) {
response.headers.set(
"Cache-Control",
`max-age=${60 * 60}, s-maxage=${60 * 60}, stale-while-revalidate=${
60 * 60
}`
); //1hr swr
`max-age=${60}, s-maxage=${60}, stale-while-revalidate=${60}`
); //1min swr
}

return response;
Expand Down
7 changes: 2 additions & 5 deletions packages/app-extension/src/app/App.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import { lazy, Suspense, useLayoutEffect } from "react";
import { HashRouter } from "react-router-dom";
import { EXTENSION_HEIGHT, EXTENSION_WIDTH } from "@coral-xyz/common";
import {
NotificationsProvider,
useBackgroundKeepAlive,
} from "@coral-xyz/recoil";
import { NotificationsProvider, useKeyringStoreState } from "@coral-xyz/recoil";
import {
BACKGROUND_BACKDROP_COLOR,
LIGHT_BACKGROUND_BACKDROP_COLOR,
Expand Down Expand Up @@ -96,7 +93,7 @@ export default function App() {
}

function _App() {
useBackgroundKeepAlive();
useKeyringStoreState();
return (
<NotificationsProvider>
<ErrorBoundary>
Expand Down
37 changes: 16 additions & 21 deletions packages/app-extension/src/components/Onboarding/pages/Finish.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { useEffect, useState } from "react";
import {
BrowserRuntimeExtension,
UI_RPC_METHOD_KEYRING_STORE_KEEP_ALIVE,
XNFT_GG_LINK,
} from "@coral-xyz/common";
import { BrowserRuntimeExtension, XNFT_GG_LINK } from "@coral-xyz/common";
import { Loading } from "@coral-xyz/react-common";
import { useBackgroundClient, useOnboarding } from "@coral-xyz/recoil";
import {
useBackgroundClient,
useKeyringStoreState,
useOnboarding,
} from "@coral-xyz/recoil";

import {
registerNotificationServiceWorker,
Expand All @@ -14,6 +14,16 @@ import {
import { SetupComplete } from "../../common/Account/SetupComplete";

export const Finish = ({ isAddingAccount }: { isAddingAccount?: boolean }) => {
// This is a mitigation to ensure the keyring store doesn't lock before
// creating the user on the server.
//
// Would be better (though probably not a priority atm) to ensure atomicity.
// E.g. we could generate the UUID here on the client, create the keyring store,
// and only then create the user on the server. If the server fails, then
// rollback on the client.
//
// An improvement for the future!
useKeyringStoreState();
const [loading, setLoading] = useState(true);
const { onboardingData, maybeCreateUser } = useOnboarding();
const background = useBackgroundClient();
Expand All @@ -33,21 +43,6 @@ export const Finish = ({ isAddingAccount }: { isAddingAccount?: boolean }) => {

useEffect(() => {
(async () => {
// This is a mitigation to ensure the keyring store doesn't lock before
// creating the user on the server.
//
// Would be better (though probably not a priority atm) to ensure atomicity.
// E.g. we could generate the UUID here on the client, create the keyring store,
// and only then create the user on the server. If the server fails, then
// rollback on the client.
//
// An improvement for the future!
if (isAddingAccount) {
await background.request({
method: UI_RPC_METHOD_KEYRING_STORE_KEEP_ALIVE,
params: [],
});
}
const res = await maybeCreateUser({ ...onboardingData, isAddingAccount });
if (!res.ok) {
if (
Expand Down
7 changes: 2 additions & 5 deletions packages/app-extension/src/options/Options.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,7 @@ import {
QUERY_CONNECT_HARDWARE,
QUERY_ONBOARDING,
} from "@coral-xyz/common";
import {
NotificationsProvider,
useBackgroundKeepAlive,
} from "@coral-xyz/recoil";
import { NotificationsProvider, useKeyringStoreState } from "@coral-xyz/recoil";
import { RecoilRoot } from "recoil";

import { WithSuspense } from "../app/Router";
Expand All @@ -35,7 +32,7 @@ function Options() {
}

function _Options() {
useBackgroundKeepAlive();
useKeyringStoreState(); // starts polling to keep worker alive
return (
<WithTheme>
<NotificationsProvider>
Expand Down
3 changes: 0 additions & 3 deletions packages/background/src/frontend/server-ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ import {
UI_RPC_METHOD_KEYRING_SET_MNEMONIC,
UI_RPC_METHOD_KEYRING_STORE_CHECK_PASSWORD,
UI_RPC_METHOD_KEYRING_STORE_CREATE,
UI_RPC_METHOD_KEYRING_STORE_KEEP_ALIVE,
UI_RPC_METHOD_KEYRING_STORE_LOCK,
UI_RPC_METHOD_KEYRING_STORE_MNEMONIC_CREATE,
UI_RPC_METHOD_KEYRING_STORE_MNEMONIC_SYNC,
Expand Down Expand Up @@ -179,8 +178,6 @@ async function handle<T = any>(
return await handleKeyringKeyDelete(ctx, params[0], params[1]);
case UI_RPC_METHOD_KEYRING_STORE_STATE:
return await handleKeyringStoreState(ctx);
case UI_RPC_METHOD_KEYRING_STORE_KEEP_ALIVE:
return handleKeyringStoreKeepAlive(ctx);
case UI_RPC_METHOD_KEYRING_DERIVE_WALLET:
return await handleKeyringDeriveWallet(ctx, params[0]);
case UI_RPC_METHOD_KEYRING_READ_NEXT_DERIVATION_PATH:
Expand Down
2 changes: 0 additions & 2 deletions packages/common/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,6 @@ export const UI_RPC_METHOD_KEYRING_STORE_CHECK_PASSWORD =
"ui-rpc-method-keyring-store-check-password";
export const UI_RPC_METHOD_KEYRING_STORE_CREATE =
"ui-rpc-method-keyring-store-create";
export const UI_RPC_METHOD_KEYRING_STORE_KEEP_ALIVE =
"ui-rpc-method-keyring-store-keep-alive";
export const UI_RPC_METHOD_KEYRING_STORE_LOCK =
"ui-rpc-method-keyring-store-lock";
export const UI_RPC_METHOD_KEYRING_STORE_MNEMONIC_CREATE =
Expand Down
2 changes: 1 addition & 1 deletion packages/common/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export function externalResourceUri(
return uri.replace("ar://", "https://arweave.net/");
}
if (options.cached) {
return `https://swr.xnfts.dev/web/${uri}`;
return `https://swr.xnfts.dev/1min/${uri}`;
}
return `${uri}`;
}
Expand Down
24 changes: 15 additions & 9 deletions packages/recoil/src/atoms/keyring.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,22 @@ export const KeyringStoreStateEnum: { [key: string]: KeyringStoreState } = {
*/
export const keyringStoreState = atom<KeyringStoreState | null>({
key: "keyringStoreState",
default: selector({
key: "keyringStoreStateDefault",
get: ({ get }) => {
const background = get(backgroundClient);
return background.request({
method: UI_RPC_METHOD_KEYRING_STORE_STATE,
params: [],
});
default: null,
effects: [
({ setSelf, getPromise }) => {
const checkState = async () => {
const background = await getPromise(backgroundClient);
const newState = await background.request({
method: UI_RPC_METHOD_KEYRING_STORE_STATE,
params: [],
});
setSelf(newState);
await new Promise((resolve) => setTimeout(() => resolve(null), 5000));
requestAnimationFrame(checkState);
};
checkState().catch(null);
},
}),
],
});

/**
Expand Down
8 changes: 4 additions & 4 deletions packages/recoil/src/atoms/nft.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -239,13 +239,13 @@ export const chatByNftId = selectorFamily<
const whitelistedChatCollections = get(collectionChatWL);

const whitelistedChatCollection = whitelistedChatCollections.find((x) => {
if (
x.collectionId !== nft?.metadataCollectionId ||
!x.attributeMapping
) {
if (x.collectionId !== nft?.metadataCollectionId) {
return false;
}

if (!x.attributeMapping) {
return true;
}
const doesNOThaveAttributes = Object.keys(
x.attributeMapping || {}
).find((attrName) => {
Expand Down
15 changes: 0 additions & 15 deletions packages/recoil/src/hooks/client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import type {
ChannelAppUiClient,
ChannelAppUiResponder,
} from "@coral-xyz/common";
import { UI_RPC_METHOD_KEYRING_STORE_KEEP_ALIVE } from "@coral-xyz/common";
import { useRecoilValue } from "recoil";

import { backgroundClient, backgroundResponder } from "../atoms";
Expand All @@ -15,17 +14,3 @@ export function useBackgroundClient(): ChannelAppUiClient {
export function useBackgroundResponder(): ChannelAppUiResponder {
return useRecoilValue(backgroundResponder);
}

export function useBackgroundKeepAlive() {
const bg = useBackgroundClient();
useEffect(() => {
const interval = setInterval(() => {
bg.request({
method: UI_RPC_METHOD_KEYRING_STORE_KEEP_ALIVE,
params: [],
});
}, 5 * 60 * 1000);

return () => clearInterval(interval);
}, []);
}