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

Remove the use of import.meta.env #4705

Merged
merged 23 commits into from
Aug 8, 2024
Merged

Remove the use of import.meta.env #4705

merged 23 commits into from
Aug 8, 2024

Conversation

obulat
Copy link
Contributor

@obulat obulat commented Aug 2, 2024

Fixes

Fixes #4703, the incident caused by incorrectly setting buildtime/runtime variables

Description

The logger in utils does not work as expected: only logging on the server or on the client when running locally.
When we call getLogger, we cannot get the information about the current deployment environment (useNuxtApp returns null)

Testing Instructions

Checklist

  • My pull request has a descriptive title (not a vague title likeUpdate index.md).
  • My pull request targets the default branch of the repository (main) or a parent feature branch.
  • My commit messages follow best practices.
  • My code follows the established code style of the repository.
  • I added or updated tests for the changes I made (if applicable).
  • I added or updated documentation (if applicable).
  • I tried running the project locally and verified that there are no visible errors.
  • I ran the DAG documentation generator (ov just catalog/generate-docs for catalog
    PRs) or the media properties generator (ov just catalog/generate-docs media-props
    for the catalog or ov just api/generate-docs for the API) where applicable.

Developer Certificate of Origin

Developer Certificate of Origin
Developer Certificate of Origin
Version 1.1

Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
1 Letterman Drive
Suite D4700
San Francisco, CA, 94129

Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.


Developer's Certificate of Origin 1.1

By making a contribution to this project, I certify that:

(a) The contribution was created in whole or in part by me and I
    have the right to submit it under the open source license
    indicated in the file; or

(b) The contribution is based upon previous work that, to the best
    of my knowledge, is covered under an appropriate open source
    license and I have the right under that license to submit that
    work with modifications, whether created in whole or in part
    by me, under the same open source license (unless I am
    permitted to submit under a different license), as indicated
    in the file; or

(c) The contribution was provided directly to me by some other
    person who certified (a), (b) or (c) and I have not modified
    it.

(d) I understand and agree that this project and the contribution
    are public and that a record of the contribution (including all
    personal information I submit with it, including my sign-off) is
    maintained indefinitely and may be redistributed consistent with
    this project or the open source license(s) involved.

@openverse-bot openverse-bot added 🧱 stack: documentation Related to Sphinx documentation 🧱 stack: frontend Related to the Nuxt frontend 🚦 status: awaiting triage Has not been triaged & therefore, not ready for work labels Aug 2, 2024
@obulat obulat added 🟧 priority: high Stalls work on the project or its dependents 🛠 goal: fix Bug fix 💻 aspect: code Concerns the software code in the repository and removed 🧱 stack: documentation Related to Sphinx documentation 🚦 status: awaiting triage Has not been triaged & therefore, not ready for work labels Aug 2, 2024
frontend/nuxt.config.ts Outdated Show resolved Hide resolved
frontend/nuxt.config.ts Show resolved Hide resolved
frontend/src/stores/feature-flag.ts Outdated Show resolved Hide resolved
frontend/.env.template Outdated Show resolved Hide resolved
@@ -31,7 +31,9 @@ const config: PlaywrightTestConfig = {
NUXT_PUBLIC_API_URL: API_URL,
UPDATE_TAPES: UPDATE_TAPES,
DEPLOYMENT_ENV: PRODUCTION,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
DEPLOYMENT_ENV: PRODUCTION,

Can be safely removed.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like this got added back.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replaced with NUXT_PUBLIC_DEPLOYMENT_ENV, which is necessary for the feature flags to work correctly.

@openverse-bot openverse-bot added the 🧱 stack: documentation Related to Sphinx documentation label Aug 2, 2024
frontend/.env.template Outdated Show resolved Hide resolved
providerUpdateFrequency: 3600000,
savedSearchCount: 4,
sentry: {
dsn: "",
environment: deploymentEnv,
environment: "local",
release: import.meta.env.SEMANTIC_VERSION,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even better @obulat, you should move this to inside the sentry plugin. Then, the variable will not be added to the runtime config and cannot be overwritten accidentally.

Copy link
Contributor Author

@obulat obulat Aug 2, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have two Sentry plugins: one for the nitro server, and one for Nuxt itself (client). In the second one, I don't think we can get the value of an env variable. So, I got the release from runtimeConfig there, too.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll test, but I believe the client plugin would also be able to reference import.meta.env.SEMANTIC_VERSION and it would be statically replaced + added to the bundle at build time.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've mentioned it in another comment, but it should go in the app.config.ts, rather than runtime config: https://nuxt.com/docs/getting-started/configuration#app-configuration

Copy link

github-actions bot commented Aug 2, 2024

Full-stack documentation: https://docs.openverse.org/_preview/4705

Please note that GitHub pages takes a little time to deploy newly pushed code, if the links above don't work or you see old versions, wait 5 minutes and try again.

You can check the GitHub pages deployment action list to see the current status of the deployments.

@zackkrida
Copy link
Member

@obulat we should also be able to delete /server/plugins/indexable.ts as part of this and rely on the runtime env var.

@obulat obulat self-assigned this Aug 2, 2024
@obulat obulat marked this pull request as ready for review August 2, 2024 17:00
@obulat obulat requested a review from a team as a code owner August 2, 2024 17:00
@obulat obulat requested review from zackkrida and dhruvkb August 2, 2024 17:00
Copy link
Member

@zackkrida zackkrida left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@obulat I have tested this extensively locally and I'm able to set values at build or runtime and see the expected output. Using ov env like ov env NUXT_PUBLIC_SENTRY_RELEASE=1.2.3.4 NUXT_PUBLIC_SITE_INDEXABLE="false" NUXT_PUBLIC_SITE_URL="http://localhost:8443" just frontend/run start made this easy to test.

Copy link
Collaborator

@sarayourfriend sarayourfriend left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The only specifically blocking change I am requesting is to move semantic version to app.config.ts, which I've got working locally with the diff below. The diff also includes suggestions for changes to the documentation, but you can take them or leave them based on your opinion of how and what to document. I prefer not to duplicate Nuxt's documentation regarding the purpose and usage of particular variables, but do agree we can be explicit when deliniating which variables go where. Luckily, Nuxt's documentation is actually pretty clear about this, and the purpose for runtimeConfig and app.config are explicit and straightforward in the documentation. We can point to that, but from my perspective it isn't necessary to repeat the documentation. Up to you and other reviewers where the line is there, though.

As I said, and just to clarify, the only blocking change is to move semantic version to app.config (and use it from there). The rest are just suggestions.

Edit: Oh, I forgot about part of the diff, the removal of type overrides from typings/nuxt... We don't need those anymore, because defineNuxtConfig and defineAppConfig hook into Nuxt's build-time type generation.

diff --git a/frontend/nuxt.config.ts b/frontend/nuxt.config.ts
index dfac91444..a2addf8db 100644
--- a/frontend/nuxt.config.ts
+++ b/frontend/nuxt.config.ts
@@ -5,28 +5,6 @@ import locales from "./src/locales/scripts/valid-locales.json"
 
 import type { LocaleObject } from "@nuxtjs/i18n"
 
-/**
- * This configuration sets values necessary at *build time*
- * to build the app and prerender our pages.
- *
- * Pay special attention when setting runtimeConfig values
- * in this file.
- *
- * Any key in `{runtimeConfig: {}}` can be
- * overwritten with a NUXT_ environment variable,
- * with the camelCase key converted to SCREAMING_SNAKE_CASE.
- *
- * The runtimeConfig values here are either defaults for local
- * development, or placeholders used to register the NUXT_
- * environment variables.
- *
- * See our .env.template for a definitive list of runtime values.
- *
- * Do not use import.meta.env to retrieve environment variables
- * here without careful consideration.
- *
- * @see {@link https://nuxt.com/docs/guide/going-further/runtime-config#example}
- */
 export default defineNuxtConfig({
   srcDir: "src/",
   serverDir: "server/",
@@ -39,11 +17,17 @@ export default defineNuxtConfig({
   },
   compatibilityDate: "2024-07-23",
   css: ["~/assets/fonts.css", "~/styles/accent.css"],
-  // Remember: Can be overwritten by NUXT_* env vars
+  /**
+   * Define available runtime configuration values and their defaults.
+   *
+   * See linked documentation for details, including how to override defaults
+   * with runtime values using environment variables.
+   *
+   * @see {@link https://nuxt.com/docs/api/nuxt-config#runtimeconfig-1}
+   */
   runtimeConfig: {
     apiClientId: "",
     apiClientSecret: "",
-    // Remember: Can be overwritten by NUXT_PUBLIC_* env vars
     public: {
       deploymentEnv: "local",
       apiUrl: "https://api.openverse.org/",
@@ -52,7 +36,7 @@ export default defineNuxtConfig({
       sentry: {
         dsn: "",
         environment: "local",
-        release: import.meta.env.SEMANTIC_VERSION,
+        // Release is a build time variable, and as such, is defined in app.config.ts
       },
     },
   },
diff --git a/frontend/server/plugins/sentry.ts b/frontend/server/plugins/sentry.ts
index dc467a10b..ae4f3cfb5 100644
--- a/frontend/server/plugins/sentry.ts
+++ b/frontend/server/plugins/sentry.ts
@@ -1,4 +1,4 @@
-import { useRuntimeConfig } from "#imports"
+import { useRuntimeConfig, useAppConfig } from "#imports"
 
 import { defineNitroPlugin } from "nitropack/runtime"
 import * as Sentry from "@sentry/node"
@@ -10,13 +10,18 @@ export default defineNitroPlugin((nitroApp) => {
     public: { sentry },
   } = useRuntimeConfig()
 
-  Sentry.init({
+  const appConfig = useAppConfig()
+
+  const sentryConfig = {
     dsn: sentry.dsn,
     environment: sentry.environment,
-    release: sentry.release,
-  })
+    release: appConfig.semanticVersion,
+  }
+
+  Sentry.init(sentryConfig)
+
   Sentry.setContext("render context", { platform: "server" })
-  logger.success("Initialized sentry on the server with config\n", sentry)
+  logger.success("Initialized sentry on the server with config\n", sentryConfig)
 
   nitroApp.hooks.hook("request", (event) => {
     event.context.$sentry = Sentry
diff --git a/frontend/src/app.config.ts b/frontend/src/app.config.ts
new file mode 100644
index 000000000..35052894b
--- /dev/null
+++ b/frontend/src/app.config.ts
@@ -0,0 +1,5 @@
+import { defineAppConfig } from "#imports"
+
+export default defineAppConfig({
+  semanticVersion: import.meta.env.SEMANTIC_VERSION as string,
+})
diff --git a/frontend/src/plugins/01.sentry.client.ts b/frontend/src/plugins/01.sentry.client.ts
index 97c8f2994..d5208c78b 100644
--- a/frontend/src/plugins/01.sentry.client.ts
+++ b/frontend/src/plugins/01.sentry.client.ts
@@ -1,4 +1,4 @@
-import { defineNuxtPlugin, useRuntimeConfig } from "#imports"
+import { defineNuxtPlugin, useRuntimeConfig, useAppConfig } from "#imports"
 
 import * as Sentry from "@sentry/vue"
 
@@ -7,6 +7,8 @@ export default defineNuxtPlugin((nuxtApp) => {
     public: { sentry },
   } = useRuntimeConfig()
 
+  const { semanticVersion } = useAppConfig()
+
   if (!sentry.dsn) {
     console.warn("Sentry DSN wasn't provided")
   }
@@ -14,7 +16,7 @@ export default defineNuxtPlugin((nuxtApp) => {
   Sentry.init({
     dsn: sentry.dsn,
     environment: sentry.environment,
-    release: sentry.release,
+    release: semanticVersion,
     app: nuxtApp.vueApp,
   })
   Sentry.setContext("render context", { platform: "client" })
diff --git a/frontend/typings/nuxt__types/index.d.ts b/frontend/typings/nuxt__types/index.d.ts
index c446f88c4..31b05109c 100644
--- a/frontend/typings/nuxt__types/index.d.ts
+++ b/frontend/typings/nuxt__types/index.d.ts
@@ -21,14 +21,3 @@ declare module "@nuxtjs/i18n" {
     translated: number
   }
 }
-
-declare module "nuxt/schema" {
-  interface RuntimeConfig {
-    apiSecret: string
-  }
-  interface PublicRuntimeConfig {
-    apiUrl: string
-    providerUpdateFrequency: number
-    savedSearchCount: number
-  }
-}

# NUXT_API_CLIENT_SECRET=""
NUXT_PUBLIC_SENTRY_DSN=""
NUXT_PUBLIC_SENTRY_ENVIRONMENT="local"
NUXT_PUBLIC_SENTRY_RELEASE="latest"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sentry release should be in app.config.ts, I think, and specifically should not be a runtime configurable variable, as discussed: https://nuxt.com/docs/getting-started/configuration#app-configuration

appConfig might also work in nuxt.config.ts, if we want to centralise it. In which case, we should still be reading that from import.env.meta.

As I've said a few times, it's really important that this distinction is absolutely clarified and understood by all who may be touching the Nuxt configuration.

providerUpdateFrequency: 3600000,
savedSearchCount: 4,
sentry: {
dsn: "",
environment: deploymentEnv,
environment: "local",
release: import.meta.env.SEMANTIC_VERSION,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've mentioned it in another comment, but it should go in the app.config.ts, rather than runtime config: https://nuxt.com/docs/getting-started/configuration#app-configuration

Comment on lines 25 to 26
* Do not use import.meta.env to retrieve environment variables
* here without careful consideration.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can add an ESLint rule for this, if we like. Probably a good idea, considering how difficult it's been to achieve full clarity on this subject.

Comment on lines 15 to 17
* Any key in `{runtimeConfig: {}}` can be
* overwritten with a NUXT_ environment variable,
* with the camelCase key converted to SCREAMING_SNAKE_CASE.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doesn't this duplicate Nuxt's documentation for runtimeConfig? https://nuxt.com/docs/api/nuxt-config#runtimeconfig-1

It does a good job explaining this concept and includes examples.

If we absolutely must link to it from this file, rather than rely on upstream documentation correlating to the keys and being searchable, it's probably clearer to link it as a comment on the runtimeConfig property itself instead.

Comment on lines 15 to 21
* Any key in `{runtimeConfig: {}}` can be
* overwritten with a NUXT_ environment variable,
* with the camelCase key converted to SCREAMING_SNAKE_CASE.
*
* The runtimeConfig values here are either defaults for local
* development, or placeholders used to register the NUXT_
* environment variables.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doesn't this duplicate Nuxt's documentation for runtimeConfig? https://nuxt.com/docs/api/nuxt-config#runtimeconfig-1

It does a good job explaining this concept and includes examples.

If we absolutely must link to it from this file, rather than rely on upstream documentation correlating to the keys and being searchable, it's probably clearer to link it as a comment on the runtimeConfig property itself instead.

Comment on lines 9 to 10
* This configuration sets values necessary at *build time*
* to build the app and prerender our pages.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is kind of confusing documentation, to me. The configuration sets defaults for runtime values too. And this ignores app.config.ts, which Nuxt makes available as an explicit place to configure build time variables.

I think it's more accurate to say that the configuration in this file is static and determined at build time, and should be used for configuring Nuxt. Whereas app.config.ts is for configuring the static, build-time information of our application.

We're maybe confusing the runtimeConfig entry in the Nuxt configuration as the configuration of specific runtime variables, when in fact it's merely configuring the defaults of those runtime variables and defining what runtime variables are available.

In that sense, the "definitive" list of supported variables shouldn't be .env.template, but the runtimeConfig property of this nuxt configuration and whatever is defined in app.config.ts and pulled from import.meta.env.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In that sense, the "definitive" list of supported variables shouldn't be .env.template, but the runtimeConfig property of this nuxt configuration and whatever is defined in app.config.ts and pulled from import.meta.env.

If the .env.template is the union of the runtimeConfig values in nuxt.config.ts and the values is defined in app.config.ts, isn't it actually a pretty good "definitive" list of supported variables? Perhaps then a comment in the .env.template explaining that the values come from those two locations would be a better replacement for these docs.

Copy link
Collaborator

@sarayourfriend sarayourfriend Aug 6, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suppose so. Why is .env.template is necessary, though? It encourages (and almost requires) us to define defaults in two places: that .env.template file and in nux.config.ts's runtimeConfig object. Using just nuxt.config.ts and app.config.ts as the reference points for supported configuration values removes that duplication.

(PS: to clarify, this is not a big sticking point to me, a minor nit-pick if anything!)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a fair point. We probably don't even document it well, and since the frontend doesn't require a .env for local development, we might not even need the template. Provided we have some documentation about ov env or other mechanisms for setting local runtime variables.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've added the patch, @sarayourfriend.

I also removed the env.template because it's not necessary, as is stated in the comments here.

Runtime config in nuxt.config should have the values used for the dev environment, if they are different from the default values. These should be overriden by the runtime variables in the infrastructure, specific for each environment (staging/production).

Build time variables are in set in appConfig.

@zackkrida zackkrida mentioned this pull request Aug 6, 2024
8 tasks
@obulat obulat force-pushed the fix/env-variables branch 2 times, most recently from 91e0e0c to 4ad6500 Compare August 6, 2024 17:37
@obulat obulat requested a review from sarayourfriend August 6, 2024 17:49
Copy link
Collaborator

@sarayourfriend sarayourfriend left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! I noticed two small things, but they are not blockers. Feel free to resolve them now (remove DEPLOYMENT_ENV from the playwright.config, use import.meta.test instead of NODE_ENV === 'test') or as a follow up issue; neither need to block this PR any further.

Thanks for hanging in with the several rounds of review and feedback @obulat 🙏 Glad we've sorted out how this works. The Nuxt documentation ended up being pretty good in the end, at least I just needed to actually read the various pages on configuration in whole, lol! 🙂

frontend/nuxt.config.ts Show resolved Hide resolved
frontend/src/utils/focus-management.ts Outdated Show resolved Hide resolved
@@ -31,7 +31,9 @@ const config: PlaywrightTestConfig = {
NUXT_PUBLIC_API_URL: API_URL,
UPDATE_TAPES: UPDATE_TAPES,
DEPLOYMENT_ENV: PRODUCTION,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like this got added back.

@obulat obulat force-pushed the fix/env-variables branch from 6829987 to 52799fe Compare August 7, 2024 13:29
@sarayourfriend
Copy link
Collaborator

LGTM @obulat! In any case, we can easily verify things are working correctly in staging.

obulat and others added 23 commits August 8, 2024 11:27
Signed-off-by: Olga Bulat <[email protected]>
Signed-off-by: Olga Bulat <[email protected]>
Signed-off-by: Olga Bulat <[email protected]>
Signed-off-by: Olga Bulat <[email protected]>
Signed-off-by: Olga Bulat <[email protected]>
Signed-off-by: Olga Bulat <[email protected]>
Signed-off-by: Olga Bulat <[email protected]>
Signed-off-by: Olga Bulat <[email protected]>
Signed-off-by: Olga Bulat <[email protected]>
@obulat obulat force-pushed the fix/env-variables branch from a103691 to ca4d310 Compare August 8, 2024 08:27
@obulat obulat merged commit de0079d into main Aug 8, 2024
43 checks passed
@obulat obulat deleted the fix/env-variables branch August 8, 2024 08:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
💻 aspect: code Concerns the software code in the repository 🛠 goal: fix Bug fix 🟧 priority: high Stalls work on the project or its dependents 🧱 stack: documentation Related to Sphinx documentation 🧱 stack: frontend Related to the Nuxt frontend
Projects
Archived in project
Development

Successfully merging this pull request may close these issues.

Nuxt 3 frontend is using build-time environment variables (import.meta.env) for runtime variables
4 participants