Skip to content

Commit

Permalink
fix: search loading state/performance (#506)
Browse files Browse the repository at this point in the history
# Pull Request type



Please check the type of change your PR introduces:

- [x] Bugfix
- [ ] Feature
- [ ] Code style update (formatting, renaming)
- [ ] Refactoring (no functional changes, no API changes)
- [ ] Build-related changes
- [ ] Documentation content changes
- [ ] Other (please describe):

## What is the current behavior?



Issue Number: IN-874

## What is the new behavior?



-
-
-

## Does this introduce a breaking change?

- [ ] Yes
- [ ] No



## Other information




PR-URL: #506
Co-authored-by: Joe Karow <58997957+JoeKarow@users.noreply.github.com>
  • Loading branch information
kodiakhq[bot] and JoeKarow committed May 29, 2023
2 parents eca09aa + 604b9e2 commit 772b74e
Show file tree
Hide file tree
Showing 59 changed files with 1,658 additions and 619 deletions.
2 changes: 1 addition & 1 deletion InReach.code-workspace
Expand Up @@ -235,7 +235,7 @@
},
"tms.stringsCompletionFileExtensions": "ts,tsx,json",
"typescript.preferences.importModuleSpecifier": "relative",
"typescript.tsdk": "🚀 InReach App (@weareinreach/app)/node_modules/typescript/lib",
"typescript.tsdk": " InReach (root)/node_modules/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true,
"typescript.workspaceSymbols.scope": "allOpenProjects"
},
Expand Down
9 changes: 4 additions & 5 deletions apps/app/next-i18next.config.mjs
Expand Up @@ -2,19 +2,18 @@
/* eslint-disable node/no-process-env */
// @ts-check
/* eslint-disable import/no-unused-modules */
// @ts-ignore
// const HttpBackend = require('i18next-http-backend/cjs')
import { I18nextKeysOnDemand } from '@weareinreach/i18next-keys-ondemand'
import axios from 'axios'
import ChainedBackend from 'i18next-chained-backend'
import HttpBackend from 'i18next-http-backend'
import intervalPlural from 'i18next-intervalplural-postprocessor'
import LocalStorageBackend from 'i18next-localstorage-backend'
// import LocalStorageBackend from 'i18next-localstorage-backend'
import MultiBackend from 'i18next-multiload-backend-adapter'
import { z } from 'zod'

import path from 'path'

import { I18nextKeysOnDemand } from '@weareinreach/i18next-keys-ondemand'

export const namespaces = [
'attribute',
'common',
Expand Down Expand Up @@ -94,7 +93,7 @@ const config = {
localePath: path.resolve('./public/locales'),
fallbackLng: ['en'],
reloadOnPrerender: process.env.NODE_ENV !== 'production',
debug: process.env.NODE_ENV !== 'production' && isBrowser, //&& !!process.env.NEXT_VERBOSE,
debug: process.env.NODE_ENV !== 'production' && isBrowser && !!process.env.NEXT_VERBOSE,
partialBundledLanguages: true,
nonExplicitSupportedLngs: true,
cleanCode: true,
Expand Down
31 changes: 13 additions & 18 deletions apps/app/next.config.mjs
Expand Up @@ -11,13 +11,19 @@ import path from 'path'
import { fileURLToPath } from 'url'

import i18nConfig from './next-i18next.config.mjs'
import * as otel from './otel.mjs'
// import * as otel from './otel.mjs'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

const isVercelActiveDev = process.env.VERCEL_ENV === 'preview' && process.env.VERCEL_GIT_COMMIT_REF !== 'dev'

const loadOtel = async () => {
if (process.env.NEXT_RUNTIME === 'nodejs') {
await import('./otel.mjs')
}
}

/* eslint-disable-next-line turbo/no-undeclared-env-vars */
const withBundleAnalyzer = bundleAnalyze({ enabled: process.env.ANALYZE === 'true' })
/** @type {import('next').NextConfig} */
Expand All @@ -26,33 +32,20 @@ const nextConfig = {
reactStrictMode: true,
swcMinify: true,
transpilePackages: ['@weareinreach/ui', '@weareinreach/db', '@weareinreach/auth', '@weareinreach/api'],
compiler: {
...(process.env.VERCEL_ENV === 'production' ? { removeConsole: { exclude: ['error'] } } : {}),
},
experimental: {
// fontLoaders: [{ loader: 'next/font/google', options: { subsets: ['latin'] } }],
/**
* OutputFileTracingIgnores will be in a future version
* https://github.com/vercel/next.js/issues/42641#issuecomment-1320713368
*/
// outputFileTracingIgnores: ['**swc+core**', '**esbuild**'],
outputFileTracingExcludes: {
'*': ['**swc+core**', '**esbuild**'],
},
outputFileTracingRoot: path.join(__dirname, '../../'),
instrumentationHook: true,
// instrumentationHook: true,
// turbotrace: {
// logDetail: true,
// },
},

// async rewrites() {
// return {
// fallback: [
// {
// source: '/:path*',
// destination: 'https://inreach-v1.vercel.app/:path*',
// },
// ],
// }
// },
eslint: {
ignoreDuringBuilds: isVercelActiveDev,
},
Expand All @@ -75,6 +68,8 @@ const nextConfig = {
* @returns {T}
*/
function defineNextConfig(config) {
loadOtel()
return withBundleAnalyzer(withRoutes()(config))
}

export default defineNextConfig(nextConfig)
39 changes: 17 additions & 22 deletions apps/app/otel.mjs
@@ -1,31 +1,26 @@
// Imports
/* eslint-disable turbo/no-undeclared-env-vars */
/* eslint-disable node/no-process-env */
// import { context, trace } from '@opentelemetry/api'
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'
import { registerInstrumentations } from '@opentelemetry/instrumentation'
import { Resource } from '@opentelemetry/resources'
import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base'
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'
import { NodeSDK } from '@opentelemetry/sdk-node'
import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-node'
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions'
import { PrismaInstrumentation } from '@prisma/instrumentation'
import { config } from 'dotenv'

// Configure the trace provider
const provider = new NodeTracerProvider({
config({ path: '../../.env' })
const otelTraceOptions = process.env.OTEL_SERVER ? { url: process.env.OTEL_SERVER } : undefined
console.log('Initializing OpenTelemetry...')

if (otelTraceOptions) {
console.log(`Using custom server: ${otelTraceOptions.url}`)
}
const sdk = new NodeSDK({
resource: new Resource({
[SemanticResourceAttributes.SERVICE_NAME]: 'nextjs',
[SemanticResourceAttributes.SERVICE_NAME]: 'inreach-app',
}),
})

// Configure how spans are processed and exported. In this case we're sending spans
// as we receive them to an OTLP-compatible collector (e.g. Jaeger).
provider.addSpanProcessor(
new SimpleSpanProcessor(new OTLPTraceExporter({ url: 'http://10.42.0.123:4318/v1/traces' }))
)

// Register your auto-instrumentors
registerInstrumentations({
tracerProvider: provider,
spanProcessor: new SimpleSpanProcessor(new OTLPTraceExporter(otelTraceOptions)),
instrumentations: [new PrismaInstrumentation({ middleware: true })],
})
console.log('nextjs otel')

// Register the provider globally
provider.register()
sdk.start()
7 changes: 6 additions & 1 deletion apps/app/package.json
Expand Up @@ -16,7 +16,8 @@
"lint": "next lint",
"lint:fix": "next lint --fix",
"start": "next start",
"type-check": "tsc --noEmit"
"type-check": "tsc --noEmit",
"with-env": "dotenv -e ../../.env --"
},
"dependencies": {
"@aws-crypto/sha256-js": "4.0.0",
Expand All @@ -42,9 +43,11 @@
"@mantine/tiptap": "6.0.11",
"@mantine/utils": "6.0.11",
"@next/bundle-analyzer": "13.4.3",
"@opentelemetry/api": "1.4.1",
"@opentelemetry/exporter-trace-otlp-http": "0.39.1",
"@opentelemetry/instrumentation": "0.39.1",
"@opentelemetry/resources": "1.13.0",
"@opentelemetry/sdk-node": "0.39.1",
"@opentelemetry/sdk-trace-base": "1.13.0",
"@opentelemetry/sdk-trace-node": "1.13.0",
"@opentelemetry/semantic-conventions": "1.13.0",
Expand Down Expand Up @@ -79,6 +82,7 @@
"i18next-multiload-backend-adapter": "2.2.0",
"ioredis": "5.3.2",
"just-compact": "3.2.0",
"just-compare": "2.3.0",
"luxon": "3.3.0",
"next": "13.4.3",
"next-auth": "4.22.1",
Expand All @@ -87,6 +91,7 @@
"nextjs-routes": "1.0.9",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-error-boundary": "4.0.7",
"react-i18next": "12.3.1",
"zod": "3.21.4"
},
Expand Down
17 changes: 9 additions & 8 deletions apps/app/public/locales/en/common.json
Expand Up @@ -190,8 +190,9 @@
"search": {
"location-placeholder": "Enter state, city, or zip code...",
"look-up-org": "Look up an organization",
"no-results": "No results found. Please try again.",
"organization-placeholder": "Enter organization name...",
"suggest-resource": "Cant find it? <1>Suggest an organization</1> you think should be included."
"suggest-resource": "Can't find it? <1>Suggest an organization</1> you think should be included."
},
"send-email": "Send email",
"service": {
Expand Down Expand Up @@ -262,21 +263,21 @@
"suggest-a-resource": "Suggest a Resource",
"support": "Support",
"survey": {
"birthyear-req-value": "Year must be between {{year1}} and {{year2}}, i.e 2005",
"finish": "Finish",
"not-right-now": "Not right now",
"start-survey": "Start Survey",
"thank-you": "Thank you!",
"thank-you-message": "The information you shared helps us to improve our product.",
"question-subtitle": "Your answers are anonymous.",
"question-1-title": "How would you describe yourself?",
"question-2-title": "What is your country of origin?",
"question-2-placeholder": "Enter country...",
"question-2-title": "What is your country of origin?",
"question-3-title": "How do you identify?",
"question-4-title": "What is your ethnicity/race?",
"question-5-title": "How old are you?",
"question-5-label": "Year of birth",
"question-5-placeholder": "Enter your birth year...",
"birthyear-req-value": "Year must be between {{year1}} and {{year2}}, i.e 2005"
"question-5-title": "How old are you?",
"question-subtitle": "Your answers are anonymous.",
"start-survey": "Start Survey",
"thank-you": "Thank you!",
"thank-you-message": "The information you shared helps us to improve our product."
},
"take-action": "Take Action",
"uncheck-all": "Uncheck all",
Expand Down
13 changes: 8 additions & 5 deletions apps/app/src/pages/_app.tsx
Expand Up @@ -14,6 +14,7 @@ import { PageLoadProgress } from '@weareinreach/ui/components/core/PageLoadProgr
import { Footer } from '@weareinreach/ui/components/sections/Footer'
import { Navbar } from '@weareinreach/ui/components/sections/Navbar'
import { BodyGrid } from '@weareinreach/ui/layouts/BodyGrid'
import { SearchStateProvider } from '@weareinreach/ui/providers/SearchState'
import { appCache, appTheme } from '@weareinreach/ui/theme'
import { api } from '~app/utils/api'

Expand Down Expand Up @@ -77,11 +78,13 @@ const MyApp = (appProps: AppPropsWithGridSwitch) => {
emotionCache={appCache}
>
<ModalsProvider>
<PageLoadProgress />
<Navbar />
{PageContent}
<Footer />
<Notifications />
<SearchStateProvider>
<PageLoadProgress />
<Navbar />
{PageContent}
<Footer />
<Notifications />
</SearchStateProvider>
</ModalsProvider>
<ReactQueryDevtools initialIsOpen={false} toggleButtonProps={{ style: { zIndex: 99998 } }} />
</MantineProvider>
Expand Down
17 changes: 17 additions & 0 deletions apps/app/src/pages/api/trpc/[trpc].ts
Expand Up @@ -18,4 +18,21 @@ export default createNextApiHandler({
: typeof window === 'undefined'
? ({ path, error, type }) => log.error({ type, path, error })
: undefined,
responseMeta(opts) {
const { ctx, errors, type } = opts

const shouldSkip = ctx?.skipCache ?? true
const allOk = errors.length === 0
const isQuery = type === 'query'

if (ctx?.res && !shouldSkip && allOk && isQuery) {
const ONE_DAY_IN_SECONDS = 60 * 60 * 24
return {
headers: {
'cache-control': `s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,
},
}
}
return {}
},
})
24 changes: 18 additions & 6 deletions apps/app/src/pages/index.tsx
Expand Up @@ -12,7 +12,7 @@ import {
useMantineTheme,
} from '@mantine/core'
import Autoplay from 'embla-carousel-autoplay'
import { type GetServerSidePropsContext } from 'next'
import { type GetServerSidePropsContext, type GetStaticProps } from 'next'
import Head from 'next/head'
import { type TFunction, Trans, useTranslation } from 'next-i18next'
import { useRef, useState } from 'react'
Expand Down Expand Up @@ -249,19 +249,31 @@ const Home: NextPageWithoutGrid = () => {
</>
)
}
Home.omitGrid = true

export const getServerSideProps = async ({ locale, req, res }: GetServerSidePropsContext) => {
const session = await getServerSession({ req, res })
const ssg = await trpcServerClient({ session })
export const getStaticProps: GetStaticProps = async ({ locale }) => {
const ssg = await trpcServerClient({ session: null })
await ssg.review.getFeatured.prefetch(3)

return {
props: {
session,
trpcState: ssg.dehydrate(),
...(await getServerSideTranslations(locale, ['common', 'landingPage'])),
},
revalidate: 60 * 60 * 24, // 24 hours
}
}
Home.omitGrid = true
// export const getServerSideProps = async ({ locale, req, res }: GetServerSidePropsContext) => {
// const session = await getServerSession({ req, res })
// const ssg = await trpcServerClient({ session })
// await ssg.review.getFeatured.prefetch(3)

// return {
// props: {
// session,
// trpcState: ssg.dehydrate(),
// ...(await getServerSideTranslations(locale, ['common', 'landingPage'])),
// },
// }
// }
export default Home

0 comments on commit 772b74e

Please sign in to comment.