otoyo / astro-notion-blog

🚀 Begin building your very own Notion Blog with Astro.
https://astro-notion-blog.pages.dev/
MIT License
732 stars 478 forks source link

ビルド高速化機能の検証に参加する方法 #25

Closed otoyo closed 1 year ago

otoyo commented 1 year ago

ビルド高速化機能の検証にご参加いただきありがとうございます。 この機能は astro-notin-blog にとって重要で複雑な機能であるため、リリース前に検証したいと思っています。 検証にご協力いただける方は、後述の手順を実行し最後に下記をご報告ください。

期間

2023/2/3(金)まで(予定)

報告いただく内容

  1. ビルドの成否
    • エラーの場合はエラーメッセージの内容
    • デバッグに協力いただけるか否か
  2. ビルドしたブログの記事数とビルドにかかった時間
  3. 手順でわかりにくかったところ

機能の概要

検証手順

ローカルの開発環境はすでにあるものとします。 ブランチ feature-speedup-build https://github.com/otoyo/astro-notion-blog/pull/21 をローカルにチェックアウトします。

  1. 下記コマンドを実行し Nx Cloud のアクセストークンを生成します
yarn install && yarn nx g @nrwl/nx-cloud:init
  1. プロジェクトルートにある nx.json を開き accessToken の値をメモします
  2. 下記コマンドを実行して nx.json から accessToken を削除します
git checkout -- nx.json
  1. ブラウザで Nx Cloud を開いてアカウントを作成しサインインします
  2. "Connect a Workspace" を選択します
  1. "01 Check for Nx Cloud package" で "Yes, I'm using @nrwl/nx-cloud" を選択します
  1. "03 Setup The Access Token" でメモした accessToken を入力し "Connect The Workspace" を選択します
  1. "View Your Workspace" を選択したら一度ターミナルに戻ります
  2. NOTION_API_SECRET が正しくセットされていることを確認します
echo $NOTION_API_SECRET

設定されていなければ下記のように設定します。

export NOTION_API_SECRET=<YOUR_NOTION_API_SECRET>
  1. DATABASE_ID が Cloudflare Pages のビルド環境と同じであることを確認します
echo $DATABASE_ID

異なる場合は同じ値を設定します。

export DATABASE_ID=<YOUR_DATABASE_ID>
  1. メモした accessToken を環境変数 NX_CLOUD_ACCESS_TOKEN に設定し、コマンドを実行してキャッシュを生成します
    • 記事数約300で20~30分程度時間がかかります

NX_CLOUD_ACCESS_TOKEN を環境変数にセットし、正しくセットされていることを確認します。

export NX_CLOUD_ACCESS_TOKEN=<メモしたaccessToken>
echo $NX_CLOUD_ACCESS_TOKEN

キャッシュを生成します。

yarn cache:fetch
  1. 再度コマンドを実行しキャッシュが生成されているか確認します(正常にキャッシュが生成されていると今回は実行が速くなります)
    • キャッシュは Notion Page の last_edited_time を見て以降は自動で更新されるため、この操作は再度行う必要はありません
yarn cache:fetch
  1. ブラウザで Nx Cloud の Workspace を開きキャッシュの結果が "Local Cache Hit" になっていることを確認します
  1. 下記コマンドを実行してローカルでビルドし、かかった時間を報告してください(ローカルビルド)
yarn build:cached
  1. Cloudflare Pages のダッシュボードから環境変数を開きメモしたアクセストークンを NX_CLOUD_ACCESS_TOKEN として Production と Preview の両方に追加します
  1. ビルド設定を開きます
  1. "Build command" を下記に変更して保存します
npm run build:cached
  1. ブランチを GitHub に push してデプロイし、Nx Cloud でキャッシュの結果が "Remote Cache Hit" になっていることを確認します
    • ビルドにかかった時間をご報告ください(リモートビルド)
  1. 検証が終了したらステップ17で設定したビルドコマンドをデフォルトの npm run build に戻し、ローカルで書きコマンドを実行してキャッシュを削除します
yarn cache:purge
midnight480 commented 1 year ago

(個人的注意ポイント) 自分は、Cloudflareのステージング環境を使っているので、 otoyoさんのRepositoryをrootとして登録しているため、

git fetch root
git checkout -b speedup-build root/feature-speedup-build

で、ブランチを作成しました。

  1. export NOTION_API_SECRET=hogehoge
    echo ${NOTION_API_SECRET}
  2. で Cloudflareの環境変数 NX_CLOUD_ACCESS_TOKEN


(追記7) 環境変数 CACHE_CONCURRENCY を追加したら、次のエラーにハマりました。

00:07:10.091 | > astro-notion-blog@0.1.0 cache:fetch
-- | --
00:07:10.091 | > node scripts/blog-contents-cache.cjs
00:07:10.091 |  
00:07:55.343 | exec error: Error: Command failed: NX_BRANCH=main npx nx run astro-notion-blog:_fetch-notion-blocks 33219958-6104-4e79-b5ef-41514c31bf74 2023-01-28T05:10:00.000Z
00:07:55.344 |  
00:07:55.347 | /opt/buildhome/repo/scripts/blog-contents-cache.cjs:74
00:07:55.348 | throw err;
00:07:55.351 | ^
00:07:55.351 |  
00:07:55.351 | Error: Command failed: NX_BRANCH=main npx nx run astro-notion-blog:_fetch-notion-blocks 33219958-6104-4e79-b5ef-41514c31bf74 2023-01-28T05:10:00.000Z
00:07:55.351 |  
00:07:55.352 | at ChildProcess.exithandler (node:child_process:397:12)
00:07:55.352 | at ChildProcess.emit (node:events:390:28)
00:07:55.352 | at maybeClose (node:internal/child_process:1064:16)
00:07:55.352 | at Process.ChildProcess._handle.onexit (node:internal/child_process:301:5) {
00:07:55.352 | killed: false,
00:07:55.352 | code: 1,
00:07:55.353 | signal: null,
00:07:55.353 | cmd: 'NX_BRANCH=main npx nx run astro-notion-blog:_fetch-notion-blocks 33219958-6104-4e79-b5ef-41514c31bf74 2023-01-28T05:10:00.000Z'
00:07:55.353 | }
00:07:55.407 | Failed: build command exited with code: 1
00:07:56.371 | Failed: an internal error occurred

(追記6) ビルドはステージング環境(ブランチもmainではなく) 環境変数 NX_CLOUD_ACCESS_TOKEN を追加して実施

23:48:31.929 | Cloning repository...
...
23:58:49.323 | ✨ Success! Uploaded 137 files (5 already uploaded) (237.25 sec)
23:58:49.323 |  
23:58:50.051 | ✨ Upload complete!
23:58:51.507 | Success: Assets published!
23:58:52.053 | Success: Your site was deployed!

(追記5)

% yarn build:cached
yarn run v1.22.19
$ npm run cache:fetch && astro build

> astro-notion-blog@0.1.0 cache:fetch
> node scripts/blog-contents-cache.cjs

 ████████████████████████████████████████ 100% | ETA: 0s | 85/85
23:28:01 [build] output target: static
23:28:01 [build] Collecting build info...
23:28:01 [build] Completed in 34ms.
23:28:01 [build] Building static entrypoints...
23:28:01 [build] Completed in 694ms.

 building client 

(!) Some chunks are larger than 500 KiB after minification. Consider:
- Using dynamic import() to code-split the application
- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/guide/en/#outputmanualchunks
- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.
Completed in 2.11s.

 generating static routes 
▶ src/pages/index.astro
  └─ /index.html (+16ms)
▶ src/pages/blog/index.astro
  └─ /blog/index.html (+2.84s)
▶ src/pages/blog/page/[page].astro
....
λ src/pages/feed.ts
  └─ /feed (+3ms)
Completed in 166.78s.

23:30:50 [build] 133 page(s) built in 169.63s
23:30:50 [build] Complete!
✨  Done in 234.48s.
% 

(追記4)

% yarn cache:fetch
yarn run v1.22.19
$ node scripts/blog-contents-cache.cjs
 ████████████████████████████████████████ 100% | ETA: 0s | 85/85
✨  Done in 72.67s.
% 

(追記3)

% yarn cache:fetch                                                           
yarn run v1.22.19
$ node scripts/blog-contents-cache.cjs
 ████████████████████████████████████████ 100% | ETA: 0s | 85/85
✨  Done in 527.18s.
% 

(追記2)

export NOTION_API_SECRET をしていませんでしたmm


(追記1) ■確認状況

% echo $DATABASE_ID          
% 
% echo $NX_CLOUD_ACCESS_TOKEN
% 

DATABASE_IDは、ビルド対象のNotionのデータベースID、 NX_CLOUD_ACCESS_TOKENは、Workspace Option > Manage Access Tokens で表示されるIDと一致しているところまでは再度確認しました。


  1. でエラーになりました。 NxCloud上ではAPI Token自体は読み込めているのですが、 ローカルでそのAPI Tokenを使おうとすると認証が通らない... ?

■エラーログ

% yarn cache:fetch           
yarn run v1.22.19
$ node scripts/blog-contents-cache.cjs
@notionhq/client warn: request fail { code: 'unauthorized', message: 'API token is invalid.' }
/Users/tetsuya/Documents/astro-notion-blog/node_modules/@notionhq/client/build/src/errors.js:162
        return new APIResponseError({
               ^

APIResponseError: API token is invalid.
    at buildRequestError (/Users/tetsuya/Documents/astro-notion-blog/node_modules/@notionhq/client/build/src/errors.js:162:16)
    at Client.request (/Users/tetsuya/Documents/astro-notion-blog/node_modules/@notionhq/client/build/src/Client.js:347:54)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async getAllPages (/Users/tetsuya/Documents/astro-notion-blog/scripts/blog-contents-cache.cjs:31:17)
    at async /Users/tetsuya/Documents/astro-notion-blog/scripts/blog-contents-cache.cjs:55:17 {
  code: 'unauthorized',
  status: 401,
  headers: Headers {
    [Symbol(map)]: [Object: null prototype] {
      date: [ 'Mon, 30 Jan 2023 13:40:34 GMT' ],
      'content-type': [ 'application/json; charset=utf-8' ],
      'content-length': [ '87' ],
      connection: [ 'close' ],
      'set-cookie': [
        'notion_browser_id=29168cba-9089-4767-9980-3883cabf99d8; Domain=www.notion.so; Path=/; Expires=Tue, 30 Jan 2024 13:40:34 GMT; Secure',
        'notion_check_cookie_consent=false; Domain=www.notion.so; Path=/; Expires=Tue, 31 Jan 2023 13:40:34 GMT; Secure',
        '__cf_bm=tzUGXX9v.kgjyqA5uvmX6xV7G3fH4iTfxrbl9Wbc_Ms-1675086034-0-AS7kaquvTfcFcWJV4p4TFECNHkjA5oIHztVTHujfryc1ViKRp+SYxQm+NRzA+JvBBMNqrO40T5XydC9CpCJRFe8=; path=/; expires=Mon, 30-Jan-23 14:10:34 GMT; domain=.notion.com; HttpOnly; Secure; SameSite=None'
      ],
      'content-security-policy': [
        "script-src 'self' 'unsafe-inline' 'unsafe-eval' https://gist.github.com https://apis.google.com https://www.google.com https://www.gstatic.com https://cdn.amplitude.com https://api.amplitude.com http://dev-embed.notion.co https://widget.intercom.io https://js.intercomcdn.com https://static.zdassets.com https://api.smooch.io\t https://logs-01.loggly.com https://http-inputs-notion.splunkcloud.com https://cdn.segment.com https://analytics.pgncs.notion.so https://o324374.ingest.sentry.io https://checkout.stripe.com https://js.stripe.com https://embed.typeform.com https://admin.typeform.com https://public.profitwell.com https://static.profitwell.com js.sentry-cdn.com https://js.chilipiper.com https://platform.twitter.com https://cdn.syndication.twimg.com https://accounts.google.com https://www.googletagmanager.com https://www.googleadservices.com https://googleads.g.doubleclick.net https://api-v2.mutinyhq.io https://client-registry.mutinycdn.com https://client.mutinycdn.com https://user-data.mutinycdn.com https://cdn.metadata.io https://platformapi.metadata.io https://d2hrivdxn8ekm8.cloudfront.net https://d1lu3pmaz2ilpx.cloudfront.net https://dvqigh9b7wa32.cloudfront.net https://d330aiyvva2oww.cloudfront.net https://cdn.transcend.io https://cdn01.boxcdn.net https://cdn.sprig.com;connect-src 'self' data: blob: https://msgstore.www.notion.so wss://msgstore.www.notion.so ws://localhost:* ws://127.0.0.1:* https://notion-emojis.s3-us-west-2.amazonaws.com https://s3-us-west-2.amazonaws.com https://s3.us-west-2.amazonaws.com https://notion-production-snapshots-2.s3.us-west-2.amazonaws.com https://cdn.amplitude.com https://api.amplitude.com https://www.notion.so https://api.embed.ly http://dev-embed.notion.co https://js.intercomcdn.com https://api-iam.intercom.io https://uploads.intercomcdn.com wss://nexus-websocket-a.intercom.io https://ekr.zdassets.com https://ekr.zendesk.com\t https://makenotion.zendesk.com\t https://api.smooch.io\t wss://api.smooch.io\t https://logs-01.loggly.com https://http-inputs-notion.splunkcloud.com https://cdn.segment.com https://api.segment.io https://analytics.pgncs.notion.so https://api.pgncs.notion.so https://o324374.ingest.sentry.io https://checkout.stripe.com https://js.stripe.com https://cdn.contentful.com https://preview.contentful.com https://images.ctfassets.net https://www2.profitwell.com https://tracking.chilipiper.com https://api.chilipiper.com https://api.unsplash.com https://boards-api.greenhouse.io https://accounts.google.com https://oauth2.googleapis.com https://www.googletagmanager.com https://analytics.google.com https://www.googleadservices.com https://googleads.g.doubleclick.net https://region1.google-analytics.com https://region1.analytics.google.com https://www.google-analytics.com https://api-v2.mutinyhq.io https://client-registry.mutinycdn.com https://client.mutinycdn.com https://user-data.mutinycdn.com https://cdn.metadata.io https://platformapi.metadata.io https://d2hrivdxn8ekm8.cloudfront.net https://d1lu3pmaz2ilpx.cloudfront.net https://dvqigh9b7wa32.cloudfront.net https://d330aiyvva2oww.cloudfront.net https://cdn.transcend.io https://telemetry.transcend.io https://api.statuspage.io https://pgncd.notion.so https://api.statsig.com https://statsigapi.net https://exp.notion.so https://file.notion.so notion://file.notion.so https://api.box.com https://*.mux.com https://api.sprig.com https://storage.googleapis.com https://cdn.sprig.com https://cdn.userleap.com;font-src 'self' data: https://cdnjs.cloudflare.com https://js.intercomcdn.com https://cdn01.boxcdn.net;img-src 'self' data: blob: https: https://platform.twitter.com https://syndication.twitter.com https://pbs.twimg.com https://ton.twimg.com https://region1.google-analytics.com https://region1.analytics.google.com https://*.mux.com;style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://github.githubassets.com https://js.chilipiper.com https://platform.twitter.com https://ton.twimg.com https://accounts.google.com https://cdn.transcend.io https://cdn01.boxcdn.net;media-src blob: https: http: https://file.notion.so notion://file.notion.so https://*.mux.com;worker-src blob:;frame-src https: http: https://accounts.google.com"
      ],
      'x-dns-prefetch-control': [ 'off' ],
      'x-frame-options': [ 'SAMEORIGIN' ],
      'strict-transport-security': [ 'max-age=5184000; includeSubDomains' ],
      'x-download-options': [ 'noopen' ],
      'x-content-type-options': [ 'nosniff' ],
      'x-permitted-cross-domain-policies': [ 'none' ],
      'referrer-policy': [ 'strict-origin-when-cross-origin' ],
      'x-xss-protection': [ '0' ],
      etag: [ 'W/"57-QCRLT3IovYEW+CkwyJQlFtiXiG8"' ],
      vary: [ 'Accept-Encoding' ],
      'cf-cache-status': [ 'DYNAMIC' ],
      server: [ 'cloudflare' ],
      'cf-ray': [ '791a9ebdca968d18-KIX' ]
    }
  },
  body: '{"object":"error","status":401,"code":"unauthorized","message":"API token is invalid."}'
}

Node.js v18.10.0
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
otoyo commented 1 year ago

@midnight480 検証ありがとうございます! 環境変数 CACHE_CONCURRENCY のエラーを調べようとしたところ、Notion DB側で列を編集すると全てのページの最終更新日が更新されてキャッシュが切れてしまうことがわかったので、危ないので機能からは外そうと思います(キャッシュがないとNotion APIにリクエストするため)。

その他コメントいただいた点を手順に反映しました!

otoyo commented 1 year ago

memo: ハッシュ値が変わってしまうケースがあるので調査する。 スクリーンショット 2023-01-31 9 26 43

ドットファイルが除外されてなさそう。

otoyo commented 1 year ago

👆対応済み https://github.com/otoyo/astro-notion-blog/pull/21/commits/533407c38300993556a63ef55e01c9293e208551

nuovotaka commented 1 year ago
otoyo commented 1 year ago

検証ありがとうございます。

Nx Cloud でキャッシュの結果が "Remote Cache Hit" になっていること確認しましたがローカルでのみ上手く動作していましたがリモートは動作していないようでした。

これはローカルで cache:fetch を実行した際に "Remote Cache Hit" になっていたということでしょうか? ローカルで cache:fetch を実行した後に再度 cache:fetch を行ったり build:cached を行った場合には "Local Cache Hit" になるかと思います。 リモートで動作していないというのは何を根拠に判断されたのでしょうか?

ちなみにVercelでデプロイすると平均で4−5分でのデプロイになります。(キャッシュロジック無しで)

それだけ速ければVercelで運用する場合はキャッシュは不要そうですね。

nuovotaka commented 1 year ago

ローカルで cache:fetch を実行した際は 'Local Cache Hit' になりました。 githubにプッシュしデプロイした後 Nx Cloud を確認したところ"Remote Cache Hit"になっていませんでした。

リモートで動作していないというのは何を根拠に判断されたのでしょうか? Nx Cloud の Workspace を開きキャッシュの結果を確認したところ

スクリーンショット 2023-02-01 20 52 00
otoyo commented 1 year ago

githubにプッシュしデプロイした後 Nx Cloud を確認したところ"Remote Cache Hit"になっていませんでした。

念のため確認ですが、デプロイ後最新のRunで確認されてますか?

image

nuovotaka commented 1 year ago

リロードして最新のものを利用しましたが、ローカルで行った結果ですね。 今も、githubにプッシュしたブランチを削除してCloudflareで試しましたがNx Cloudの結果がローカルで行った結果以降変わっていません。3時間前のままですね。

nuovotaka commented 1 year ago

ちなみにCloudflareでの結果は。。。

スクリーンショット 2023-02-01 20 58 39
otoyo commented 1 year ago

今も、githubにプッシュしたブランチを削除してCloudflareで試しましたがNx Cloudの結果がローカルで行った結果以降変わっていません。3時間前のままですね。

これはおそらくVercelで環境変数NX_CLOUD_ACCESS_TOKEN が正しく設定されていなさそうです。ご確認いただけますか?

nuovotaka commented 1 year ago

NX_CLOUD_ACCESS_TOKEN トークンの設定していなかったです。 今、CloudflareおよびVercelそれぞれでやり直しを行っているところです。少々お待ちください。

nuovotaka commented 1 year ago

アクセストークンを設定して再度やり直した結果です。

nuovotaka commented 1 year ago
  1. ビルドの成否 > 成功
  2. エラーの場合はエラーメッセージの内容 > エラーはなし
  3. デバッグに協力いただけるか否か > 時間が合えば協力します。
  4. ビルドしたブログの記事数とビルドにかかった時間 > 記事数 : 236
  5. 手順でわかりにくかったところ > Vercel, Cloudflare それぞれで環境変数(Nx Cloudのアクセストークン設定の抜け落ち)

以上

otoyo commented 1 year ago

@nuovotaka ご確認ありがとうございます。 やはりVercelのビルドめちゃくちゃ速いですね。見た感じ独自にビルドをキャッシュしてるみたいですね。

手順でわかりにくかったところ > Vercel, Cloudflare それぞれで環境変数(Nx Cloudのアクセストークン設定の抜け落ち)

ここはごもっともですので手順に追加しました。

otoyo commented 1 year ago

みなさまご協力ありがとうございました!