Skip to content

Commit

Permalink
Revert "1206 error responses occasionally being cached by cached util…
Browse files Browse the repository at this point in the history
…ity" (#1372)
  • Loading branch information
mhgbrown authored Dec 2, 2024
1 parent 1bf86c6 commit 5365d24
Show file tree
Hide file tree
Showing 17 changed files with 99 additions and 107 deletions.
2 changes: 1 addition & 1 deletion src/hooks.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ PuppeteerManager.launch({
}),
headless: true,
args: ['--no-sandbox', '--disable-setuid-sandbox'],
});
})

export const handle = sequence(sentryHandle());
export const handleError = handleErrorWithSentry();
2 changes: 1 addition & 1 deletion src/lib/components/collect-button/collect-button.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@
loading ||
amountToShow?.fiatEstimateCents === 0 ||
amountToShow?.includesUnknownPrice === true;
const newWidth = shouldHide ? 0 : amountElem?.getBoundingClientRect().width ?? 0;
const newWidth = shouldHide ? 0 : (amountElem?.getBoundingClientRect().width ?? 0);
if (newWidth === 24) {
amountElemWidth.set(0);
Expand Down
2 changes: 1 addition & 1 deletion src/lib/flows/top-up-flow/enter-amount.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
export let backButton: boolean;
$: tokenAddress = $context.tokenAddress;
$: tokenInfo = tokenAddress ? tokens.getByAddress(tokenAddress) ?? unreachable() : undefined;
$: tokenInfo = tokenAddress ? (tokens.getByAddress(tokenAddress) ?? unreachable()) : undefined;
let amount: bigint | undefined = undefined;
Expand Down
2 changes: 1 addition & 1 deletion src/lib/utils/base-url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ import getOptionalEnvVar from './get-optional-env-var/public';

const envBaseUrl = getOptionalEnvVar('PUBLIC_BASE_URL');

export const BASE_URL = browser ? window.location.origin : envBaseUrl ?? 'http://localhost:5173';
export const BASE_URL = browser ? window.location.origin : (envBaseUrl ?? 'http://localhost:5173');
46 changes: 0 additions & 46 deletions src/lib/utils/blog-posts.ts

This file was deleted.

6 changes: 2 additions & 4 deletions src/lib/utils/cmc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,10 @@ export const getCmcPrices = async (tokenAddresses: string[], fetch = window.fetc
}

try {
// get id map and ensure the response does not indicate an error
const idMapResponse = await fetch('/api/fiat-estimates/id-map');
// get response of known token address => token id
const idMapJson = await idMapResponse.json();
const idMapRes = await (await fetch('/api/fiat-estimates/id-map')).json();
// produce map of response
const tokenAddressToId = z.record(z.string(), z.number()).parse(idMapJson);
const tokenAddressToId = z.record(z.string(), z.number()).parse(idMapRes);
// create parameter for /api/fiat-estimates/price endpoint, removing unknown token ids
const tokenIdsString = tokenAddresses
.reduce((memo, address) => {
Expand Down
13 changes: 0 additions & 13 deletions src/lib/utils/fetch.ts

This file was deleted.

2 changes: 1 addition & 1 deletion src/lib/utils/get-connected-address.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ export default function getConnectedAddress() {

return isTest()
? // eslint-disable-next-line @typescript-eslint/no-explicit-any
(window as any).playwrightAddress ?? '0x433220a86126eFe2b8C98a723E73eBAd2D0CbaDc'
((window as any).playwrightAddress ?? '0x433220a86126eFe2b8C98a723E73eBAd2D0CbaDc')
: get(walletStore).address;
}
22 changes: 12 additions & 10 deletions src/lib/utils/puppeteer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@ import puppeteer, { type Browser, type PuppeteerNodeLaunchOptions } from 'puppet
*/
export class PuppeteerManager {
static browser: Browser | undefined;
static browserConfig: PuppeteerNodeLaunchOptions | undefined;
static browserConfig: PuppeteerNodeLaunchOptions | undefined

static #onBrowserExit = () => {
// eslint-disable-next-line no-console
console.warn('PuppeteerManager: browser exited');
console.warn('PuppeteerManager: browser exited')
// if the browser process exits for any reason, mark the browser as dead
// so that we can perform re-launch on the next call to this.launch
this.browser = undefined;
};
}

/**
* Launch a Puppeteer Browser with the specified configuration. Subsequent calls to
Expand All @@ -28,18 +28,20 @@ export class PuppeteerManager {
*/
static async launch(browserConfig?: PuppeteerNodeLaunchOptions): Promise<Browser> {
if (browserConfig && this.browser) {
await this.browser.close();
await this.browser.close()
}

if (!this.browser) {
this.browserConfig =
this.browserConfig && !browserConfig ? this.browserConfig : browserConfig;
this.browser = await puppeteer.launch(this.browserConfig);
this.browserConfig = this.browserConfig && !browserConfig ? this.browserConfig : browserConfig
this.browser = await puppeteer.launch(this.browserConfig)

const childProcess = this.browser.process();
childProcess?.on('exit', this.#onBrowserExit);
const childProcess = this.browser.process()
childProcess?.on('exit', this.#onBrowserExit)
}

return this.browser;
return this.browser
}
}



2 changes: 0 additions & 2 deletions src/lib/utils/total-dripped-approx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,6 @@ export const cachedTotalDrippedPrices = (
);

return cached(redis, TOTAL_DRIPPED_PRICES_CACHE_KEY, 60 * 60 * 6, async () => {
// if the underlying getCmcPrices function fails, {} is returned
// and will become cached
return totalDrippedPrices(fetch);
});
};
19 changes: 17 additions & 2 deletions src/routes/(pages)/+page.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ import { cachedTotalDrippedPrices } from '$lib/utils/total-dripped-approx';
import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
import { redis } from '../api/redis';
import { metadataSchema } from '../api/blog/posts/schema';
import assert from '$lib/utils/assert';
import type { DripListQuery, DripListQueryVariables } from './__generated__/gql.generated';
import query from '$lib/graphql/dripsQL';
import { DRIP_LIST_CARD_FRAGMENT } from '$lib/components/drip-list-card/drip-list-card.svelte';
import { gql } from 'graphql-request';
import { PUBLIC_NETWORK } from '$env/static/public';
import network from '$lib/stores/wallet/network';
import { fetchBlogPosts } from '$lib/utils/blog-posts';

const FEATURED_DRIP_LISTS =
{
Expand Down Expand Up @@ -71,7 +72,21 @@ export const load = (async ({ fetch, request }) => {
const [prices, featuredLists, blogPosts] = await Promise.all([
cachedTotalDrippedPrices(redis, fetch),
fetchFeaturedLists(),
fetchBlogPosts(),
Promise.all(
Object.entries(import.meta.glob('/src/blog-posts/*.md')).map(async ([path, resolver]) => {
const resolved = await resolver();

assert(typeof resolved === 'object' && resolved && 'metadata' in resolved);

const metadata = metadataSchema.parse(resolved.metadata);

const slug = path.split('/').pop()?.slice(0, -3);

assert(slug);

return { ...metadata, slug };
}),
),
]);

return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ import {
SortDirection,
} from '$lib/graphql/__generated__/base-types';
import network from '$lib/stores/wallet/network';
import { fetchBlogPosts } from '../../../../../lib/utils/blog-posts';
import { ensureResponseOk } from '$lib/utils/fetch';

const FEATURED_DRIP_LISTS =
{
Expand Down Expand Up @@ -99,8 +97,12 @@ export default async function loadDefaultExplorePageData(f: typeof fetch) {
return results.map((res) => res.dripList);
};

const fetchBlogPosts = async () => {
return (await f('/api/blog/posts')).json();
};

const fetchTlv = async () => {
return (await ensureResponseOk(f('/api/tlv'))).json();
return (await f('/api/tlv')).json();
};

const [blogPosts, projects, featuredDripLists, totalDrippedPrices, tlv] = await cached(
Expand Down
20 changes: 18 additions & 2 deletions src/routes/(pages)/blog/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,30 @@
import network from '$lib/stores/wallet/network';
import assert from '$lib/utils/assert';
import { redirect } from '@sveltejs/kit';
import { fetchBlogPosts } from '$lib/utils/blog-posts';
import { metadataSchema } from '../../api/blog/posts/schema';

export const load = async ({ route }) => {
if (network.alternativeChainMode) {
// Serve from the `mainnet` instance
return redirect(308, `https://drips.network${route.id}`);
}

const posts = await fetchBlogPosts();
const posts = await Promise.all(
Object.entries(import.meta.glob('/src/blog-posts/*.md')).map(async ([path, resolver]) => {
const resolved = await resolver();

assert(typeof resolved === 'object' && resolved && 'metadata' in resolved);

const metadata = metadataSchema.parse(resolved.metadata);

const slug = path.split('/').pop()?.slice(0, -3);

assert(slug);

return { ...metadata, slug };
}),
);

const sortedPosts = posts.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());

return {
Expand Down
21 changes: 19 additions & 2 deletions src/routes/api/blog/posts/+server.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,25 @@
import { json } from '@sveltejs/kit';
import { fetchRawBlogPosts } from '../../../../lib/utils/blog-posts';
import { compile } from 'mdsvex';
import assert from '$lib/utils/assert';

export const GET = async () => {
const posts = await fetchRawBlogPosts();
const posts = await Promise.all(
Object.entries(import.meta.glob('/src/blog-posts/*.md', { as: 'raw' })).map(
async ([path, resolver]) => {
const resolved = await resolver();
const compiled = await compile(resolved);

const slug = path.split('/').pop()?.slice(0, -3);
assert(slug);

// Get the frontmatter
const fm = (compiled?.data && 'fm' in compiled.data && compiled.data.fm) ?? {};

return { ...fm, slug };
},
),
);

return json(posts);
};

Expand Down
9 changes: 3 additions & 6 deletions src/routes/api/fiat-estimates/id-map/+server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import mapFilterUndefined from '$lib/utils/map-filter-undefined';
import type { RequestHandler } from './$types';
import { redis } from '../../redis';
import cached from '$lib/utils/cache/remote/cached';
import { ensureResponseOk } from '$lib/utils/fetch';

const cmcResponseSchema = z.object({
data: z.array(
Expand All @@ -28,12 +27,10 @@ const COINMARKETCAP_ETHEREUM_PLATFORM_ID = 1;
// TODO: Find some way to not fetch and send back the entire list of all tokens on CoinMarketCap,
// but only the ones currently needed for estimates.

export const GET: RequestHandler = async ({ fetch }) => {
export const GET: RequestHandler = async () => {
const cmcIdMapRes = await cached(redis, 'cmc-id-map', 24 * 60 * 60, async () => {
const idMapRes = await ensureResponseOk(
fetch(
`https://pro-api.coinmarketcap.com/v1/cryptocurrency/map?CMC_PRO_API_KEY=${COINMARKETCAP_API_KEY}`,
),
const idMapRes = await fetch(
`https://pro-api.coinmarketcap.com/v1/cryptocurrency/map?CMC_PRO_API_KEY=${COINMARKETCAP_API_KEY}`,
);

return cmcResponseSchema.parse(await idMapRes.json());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { error } from '@sveltejs/kit';
import { z } from 'zod';
import type { EntryGenerator } from './$types.js';
import Jimp from 'jimp';
import { getSlug } from '$lib/utils/blog-posts.js';

export const GET = async ({ params }) => {
const { slug, target } = params;
Expand Down Expand Up @@ -49,7 +48,14 @@ export const prerender = true;
export const entries: EntryGenerator = async () => {
const allPosts = import.meta.glob('/src/blog-posts/*.md', { as: 'raw' });

const slugs = await Promise.all(Object.entries(allPosts).map(async ([path]) => getSlug(path)));
const slugs = await Promise.all(
Object.entries(allPosts).map(async ([path]) => {
const slug = path.split('/').pop()?.slice(0, -3);
assert(slug);

return slug;
}),
);

return slugs.reduce<{ slug: string; target: string }[]>((acc, slug) => {
return [...acc, { slug, target: 'twitter' }, { slug, target: 'og' }];
Expand Down
20 changes: 10 additions & 10 deletions tailwind.config.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ module.exports = {
theme: {
extend: {
screens: {
xs: '440px' /* just above most phones in portrait-mode */,
sm: '540px',
mlg: '896px',
'xs': '440px', /* just above most phones in portrait-mode */
'sm': '540px',
'mlg': '896px',
'2xl': '1440px',
mouse: { raw: '(hover:hover)' }, // targets only browser with mouse hover
'mouse': { raw: '(hover:hover)' } // targets only browser with mouse hover
},
spacing: {
18: '4.5rem',
Expand Down Expand Up @@ -65,17 +65,17 @@ module.exports = {
hi: 'var(--elevation-high)',
},
translate: {
'2px': '2px',
'2px': '2px'
},
animation: {
blink: 'blink 1000ms infinite linear',
'blink': 'blink 1000ms infinite linear',
},
keyframes: {
blink: {
'blink': {
'0%, 49%': { opacity: 0 },
'50%, 100%': { opacity: 1 },
},
},
'50%, 100%': { opacity: 1 }
}
}
},
},
plugins: [],
Expand Down

0 comments on commit 5365d24

Please sign in to comment.