Closed3

2024年3月の学習記録

miroscularmiroscular

3 月の目標

lambda foundationsを完了したものの、座学的で実践が足りないと感じたので、
AWS、Terraformは下記ハンズオン資料で実践したものをTerraformで再現する方法下学習
https://aws.amazon.com/jp/events/aws-event-resource/hands-on/
サーバーレスアーキテクチャの構築をTerraformで再現した。

上記ドキュメントの読了 (data-fetchはまだ1つ)
下記は未完、4月の目標とする

https://nextjs.org/docs/app/building-your-application/rendering
rendering * 3
https://nextjs.org/docs/app/building-your-application/testing
testing * 2
https://nextjs.org/docs/app/building-your-application/authentication
authentication
https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config
route-segment-config

  • AOJ 10 問
    実際には6問。

  • Otaku-GPaT のバックエンド最低限基本機能完成
    未完。3つのAPIの連携、プレイリスト作成までの流れは一通り理解した。
    検索結果の大量取得、保持と、検索精度の向上が今後の課題。

  • Otaku-GPaT のUI作成、リリース
    未完。まずは基本的なUIの作成と1~10個程度のキャッシュデータの作成を優先したい。

  • Terraform AWS のチュートリアル全部

  • Terraform Cloud チュートリアル
    完了

  • Terraform Scale DynamoDB チュートリアル
    今のところは不要と判断したので未完

  • その他
    Frontend Mentorで問題を1つ。80%ぐらいまで完成。
    MDN CSS記事でCSSの基礎を理解することを始めた。

記録

テンプレ

3/

leetcode

AOJ

個人開発

Terraform / AWS

Frontend Mentor

Next.js

MDN CSS

その他

3/30

leetcode

https://leetcode.com/problems/reformat-department-table/description/
難易度はeasyだがハマると普通に難しい。
group byしてsumを利用する解法に気づかなかった

個人開発

useEffectの分離によりpage.tsのstateの削減、可読性向上
オンラインのデータの取得がないと表示ができないUI部分に関して、コンポーネントで分離して
サンプルデータでUIの調整が簡単に出来るように環境を整備

Terraform / AWS

aws_dynamodb_table
hash_key はprimary key、range_key はsort key

以下のような書き方で、jsonを完結に記載可能

resource "aws_dynamodb_table_item" "example" {
  table_name = aws_dynamodb_table.example.name
  hash_key   = aws_dynamodb_table.example.hash_key

  item = jsonencode({
    title: { S: "hogehoge" }
  })
}

attributeの指定は必須
そこで指定した中から、hash_keyを選択する

resource "aws_dynamodb_table" "example" {
  name           = "example"
  billing_mode   = "PROVISIONED"
  read_capacity  = 1
  write_capacity = 1
  hash_key       = "timestamp"

  attribute {
    name = "timestamp"
    type = "S"
  }
}

Frontend Mentor

max-w-md クラスを使うことで要素の最大幅に制約を決定できる

arbitary values を使うことで、TailwindCSSに存在しない色味を利用する
https://tailwindcss.com/docs/adding-custom-styles#using-arbitrary-values

このような使い方が紹介されているので、もしかしたらstyleを使わなくてもclassだけでbgイメージのインポートができる?

<div class="bg-[url('/what_a_rush.png')]">

hsl, rgb カラーコードの相互変換
https://kforce-ueda.hatenablog.com/entry/tools/color_cnv#google_vignette

Next.js

'use server'と書いたものがサーバーアクションとして定義される

つまり、何も書いていない場合はRSCとして扱われ、クライアント側で実行される?
検証の結果、やはり 'use server' がない場合の関数はブラウザ側で実行される

https://zenn.dev/cybozu_frontend/articles/think-about-pe
progressive enhancement とは?
javascriptが利用できない状態でも最低限動作するようにする

server actionの引数、戻り値はReactによってseriarizableな値でないといけない
https://react.dev/reference/react/use-server#serializable-parameters-and-return-values
これを守っていないとよく見るエラーが出る

formでのactionは自動的にFormDataオブジェクトを受け取るので、useStateを使ってfieldを管理する必要がない

https://github.com/vercel/next.js/tree/canary/examples/next-forms
TODO あとで動かして見る

次回ここから
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#pending-states

MDN CSS

https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/Cascade_layers#オリジンとカスケード
難しすぎて何を言っているのか全くわからない。

https://ebisu.com/note/css-cascade-layers/#:~:text=カスケードレイヤーは CSS の,を設定できる機能です。
代わりにカスケードレイヤーを具体的に利用している例

@layer default, theme;
などとすることでlayerごとにcssの適用優先順位を決めることが出来る
この場合themeの優先順位が高い
Q. TailwindCSS、その他のCSSフレームワークなどを併用する場合、layerをどのように活用していけるのか?

https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/Selectors
次回セレクターから

3/29

AOJ

https://onlinejudge.u-aizu.ac.jp/problems/ALDS1_6_D

4 3 2 7 1 6 5
7 3 2 4 1 6 5
5 3 2 4 1 6 7
1 3 2 4 5 6 7
1 2 3 4 5 6 7

1 2 3 4 5 6 7

最小コストソート
値を交換することで、最初のインデックスに戻ってくる交換の組み合わせ→サイクル
まずソート後の配列を用意
配列がソート配列になるためのサイクルを見つけて、最小コストを計算する
サイクル外の要素を使ったほうが最小コストが小さくなる場合があるので、2通りの方法で計算する

1 2 7 8 9 10

2 1 8 10 7 9
1 2 8 10 7 9
7 2 8 10 1 9 (最小値交換)
7 2 8 10 9 1
7 2 8 1 9 10
7 2 1 8 9 10
1 2 7 8 9 10 (元に戻す)

8 10 7 9
8 10 9 7
8 7 9 10
7 8 9 10
n = 4
交換回数は3回では?
交換回数がn - 2 は成り立たないのでは?

最後の交換の手前までで n - 2 回
シグマ計算のところで、最小値自身の交換が一回計算されている

個人開発

jsonの取り出しとOP, ED, artist情報の表示など
速度問題の解決のため、 extractAnimeInfo 関数が返す値を配列ではなくオブジェクトに変更

そろそろ単体テストの実装が必要になりそう

次回
AnimeTheme APIの情報の表示方法を整理する

Terraform / AWS

https://developer.hashicorp.com/terraform/language/meta-arguments/lifecycle#create_before_destroy
lifecycle ブロックというものが存在する
全てのresourceが使うことが出来る
create_before_destroy
新しい置換オブジェクトを作る際、新しいオブジェクトを作ってからresourceを削除する

https://zenn.dev/motoyannn/articles/238c7860d3b280
https://qiita.com/nisim/items/e177204cff65bdfcc828
DynamoDBの料金概説

https://tmokmss.hatenablog.com/entry/20220611/1654931458
サーバーレスで趣味ウェブサービスを作る例
AWS CDKで色々作ってる模様
github リポジトリつき

プロビジョン済みとオンデマンドキャパシティ、どっちが安い?
個人サービスならオンデマンドの方がやすそうだが、コストが青天井になる恐れも

ただキャッシュを使いたいだけであれば、S3を検討しても良いかも

次回 DynamoDBテーブルの作成
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/dynamodb_table

Frontend Mentor

preventDefaultでform上のbuttonをクリックした際の動作を無効化出来る

  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
  }

フォームのバリデーションをオレオレ関数で追加
zodなどを使って実践しても良さそう?

3/28

leetcode

https://leetcode.com/problems/immediate-food-delivery-ii/description/

group by, max/min を使ってgroup内の日付順に並べたときの最新の列を取り出せるか?
--> maxでは、あくまで指定した列の最大値、最小値のみ得られる

個人開発

https://github.com/axios/axios
fetchをaxiosで代替する

paramsが書けるので、複数のクエリパラメータをキレイに書ける

https://github.com/aspida/aspida/tree/main/packages/aspida/docs/ja#readme
aspidaの使い方を大体理解
apiディレクトリをルートに作成してリクエストとレスポンスの型を定義

Terraform / AWS

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/api_gateway_resource
REST APIにとってのresourceは、route
メソッドの設定は別途行う

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/api_gateway_integration
integrationでresource_idを指定し、http_methodをベタ書きすることで、aws_api_gateway_methodを定義することなく
ルーティングが設定できる、わけではない

まずはaws_api_gateway_methodリソースを定義する必要があり、その後はベタ書きで

resource "aws_api_gateway_integration" "example2" {
  rest_api_id = aws_api_gateway_rest_api.example.id
  resource_id = aws_api_gateway_resource.example.id
  http_method = "GET"
  # http_method = aws_api_gateway_method.example.http_method
  type = "MOCK"
}

このように書くこともできるが、メリットはほぼない

Execution failed due to configuration error: Unable to parse statusCode. It should be an integer that is defined in the request template.

request_templatesに、statusCodeの記載がないと起きるエラー

resource "aws_api_gateway_integration" "example2" {
  rest_api_id = aws_api_gateway_rest_api.example.id
  resource_id = aws_api_gateway_resource.example.id
  http_method = aws_api_gateway_method.example.http_method
  type        = "MOCK"

  request_templates = {
        "application/json" = "{ \"statusCode\": 200 }"
  }
}

完成したマッピングテンプレート付きモックAPI
https://github.com/sniper-fly/tutorials/blob/master/terraform_api_lambda_dynamodb/mock_rest_api.tf

Frontend Mentor

hidden と invisibleの違い
https://qiita.com/rico/items/0f645e84028d4fe00be6

Next.js

https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#revalidating-data
fetch の revalidate オプションで時間を指定することで cacheを一掃するpurgingする時間を決定できる
また、 segment config optionとして、 revalidate変数を宣言することで全ての挙動を制御することも可能

fetchにtagをつけて、特定のtagを対象にrevalidateすることもできる

The fetch request comes after the usage of headers or cookies.
headers, cookiesメソッドの後のfetchはキャッシュされない

DBの用意したメソッドを使う場合などでfetchが使えない場合、
cache functionを利用して一定時間データをキャッシュできる。
2回DBのAPIを利用しても1回しかリクエストされない

次回以下
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations

MDN CSS

次回 以下より
https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/Cascade_layers#オリジンとカスケード

その他

vscodeのextensionHostがCPUを使いすぎる件
.vscodeで無効化するextensionをworkspaceごとに決めて特定する

3/26

leetcode

https://leetcode.com/problems/product-price-at-a-given-date/solutions/4575793/simple-query-using-only-join-and-coalesce-in-7-lines/

subquery, ifnull

個人開発

Response jsonをいい感じに型定義して使いたい形式のオブジェクトに変換する

https://github.com/axios/axios
axiosを使うことでqueryをキレイにかける

https://developer.mozilla.org/ja/docs/Web/API/Request
https://developer.mozilla.org/ja/docs/Web/API/URL/URL
fetchの引数に指定できる

次回 取得したJSONをAnime型に変換して情報を一緒に一覧表示する
Anime型のstateを用意する

Terraform / AWS

https://qiita.com/Shoma0210/items/17193f254180396fb8e1
リソースベースのポリシーとは?
AWSでは、IAM roleにポリシーを付与するようなアイデンティティベースのポリシー付与、
Lambdaに付与するようなリソースベースのポリシー付与が存在する

https://qiita.com/miyuki_samitani/items/2d38d29c0f602931dd1a
プリンシパルとは?
アクションを実行する人

https://docs.aws.amazon.com/ja_jp/apigateway/latest/developerguide/http-api-vs-rest.html
http apiとREST APIの違い
aws_apigatewayv2_api で作成できるのはHTTPのほう

Frontend Mentor

https://tailwindcss.com/docs/outline-style
outline-noneでブラウザの選択時のアウトラインを無効に出来る

https://tailwindcss.com/docs/adding-custom-styles#using-arbitrary-values
既存のクラスにいい感じの値がなかったとき、arbitary valuesが使える

Next.js

https://nextjs.org/docs/app/building-your-application/caching

fetch(`https://...`, { cache: 'no-store' })

これによってfetchを毎回通信させられる

cacheはリクエスト間で共有される
memoizationは、一回のリクエストの無駄を省くために使われる

https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating
Next.jsはデフォルトのfetchを拡張している
caching や revalidating の挙動を変更している

fetchはデフォルトでキャッシュされるが、Data Cacheにキャッシュされるが、
server action, route handlerで使われているときなどにはキャッシュされない

https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#revalidating-data

MDN CSS

https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance#ソース順
CSS優先度の計算方法
id-class-tag
より上位の数字が高いほう、順番が遅い方が優先される

次回は以下より
https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Cascade_tasks
https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/Cascade_layers

3/25

AOJ

マージソート、クイックソートの復習

swap は fとcの数字を入れ替える
++cは記載省略
xは最初の数字のインデックスの前の任意の数字を表す

fx c3 9 8 1 5 6 2 | 5
x fc3 9 8 1 5 6 2 | 5 ++f
x fc3 9 8 1 5 6 2 | 5 swap
x f3 c9 8 1 5 6 2 | 5
x f3 9 c8 1 5 6 2 | 5
x f3 9 8 c1 5 6 2 | 5
x 3 f9 8 c1 5 6 2 | 5 ++f
x 3 f1 8 c9 5 6 2 | 5 swap
x 3 f1 8 9 c5 6 2 | 5
x 3 1 f8 9 c5 6 2 | 5 ++f
x 3 1 f5 9 c8 6 2 | 5 swap
x 3 1 f5 9 8 c6 2 | 5
x 3 1 f5 9 8 6 c2 | 5
x 3 1 5 f9 8 6 c2 | 5 ++f
x 3 1 5 f2 8 6 c9 | 5 swap

x 3 1 5 f2 8 6 9 | 5
x 3 1 5 f2 5 6 9 | 8 swap(f + 1, last)

アルゴリズム改良
https://onlinejudge.u-aizu.ac.jp/status/users/DJ_wata/submissions/1/ALDS1_6_B/judge/9026538/C++14
fc3 9 8 1 5 6 2 | 5
fc3 9 8 1 5 6 2 | 5 swap
c3 f9 8 1 5 6 2 | 5 ++f
3 fc9 8 1 5 6 2 | 5
3 f9 c8 1 5 6 2 | 5
3 f9 8 c1 5 6 2 | 5
3 f1 8 c9 5 6 2 | 5 swap
3 1 f8 c9 5 6 2 | 5 ++f
3 1 f8 9 c5 6 2 | 5
3 1 f5 9 c8 6 2 | 5 swap
3 1 5 f9 c8 6 2 | 5 ++f
3 1 5 f9 8 c6 2 | 5
3 1 5 f9 8 6 c2 | 5
3 1 5 f2 8 6 c9 | 5 swap
3 1 5 2 f8 6 c9 | 5 ++f

3 1 5 2 f8 6 9 | 5
3 1 5 2 f5 6 9 | 8 swap(f, last)

個人開発

Imageコンポーネントのsrcに外部サイトのURLを指定すると

          <Image
            src={m?.coverImage?.large}
            alt={m?.title?.romaji}
            width={100}
            height={200}
          />

下記のエラー

Unhandled Runtime Error
Error: Invalid src prop (https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx104051-tFMIbiffwBLs.jpg) on `next/image`, hostname "s4.anilist.co" is not configured under images in your `next.config.js`
See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host

ここなどを参考に、
https://nextjs.org/docs/app/api-reference/next-config-js
以下のようにして解決

/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 's4.anilist.co',
        port: '',
        pathname: '/file/anilistcdn/media/anime/cover/medium/**',
      },
    ]
  }
};

export default nextConfig;

Imageのheightやwidthを適当な値を入れて表示していると、開発者ツールでは以下のエラーが見える

Image with src "https://s4.anilist.co/file/anilistcdn/media/anime/cover/medium/bx97986-8oxwTF84hzue.jpg" has either width or height modified, but not the other. If you use CSS to change the size of your image, also include the styles 'width: "auto"' or 'height: "auto"' to maintain the aspect ratio.

以下のaspidaを使えばレスポンスに型を指定可能になる
https://github.com/aspida/aspida/tree/main/packages/aspida/docs/ja#readme

aspida 開発者の記事
https://zenn.dev/solufa/articles/getting-started-with-aspida

Terraform / AWS

  • メソッドリクエスト
    認証の設定、必須パラメータなど
  • 統合リクエスト
    バックエンドの種別選択
    バックエンドへのinput変換
  • 統合レスポンス
    バックエンドからのoutput変換
  • メソッドレスポンス
    ステータスコード、レスポンスヘッダの設定など

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/apigatewayv2_integration
統合タイプの選択
Mock, Lambda関数などを選択可能

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/apigatewayv2_integration_response#response_templates
おそらくここで統合レスポンスの中身を色々編集可能

applyに失敗し以下のエラー

│ Error: creating API Gateway v2 integration: BadRequestException: Currently, an API with a protocol type of HTTP may only be associated with proxy integrations (AWS_PROXY, HTTP_PROXY)
│ 

https://github.com/hashicorp/terraform-provider-aws/issues/17289
MOCKのAPIはTerraformでは作成できない?

resource "aws_apigatewayv2_integration" "hello_world" {
  ...
  integration_method = "POST"

integration_methodとは何なのか?

copilot曰く

The integration_method property is typically used when defining an API Gateway Integration in AWS. This property specifies the type of request method (HTTP verb) that the API Gateway should use when integrating with another service, such as a Lambda function or another HTTP endpoint.

In this case, "POST" is being used, which means that the API Gateway will use the HTTP POST method for requests to the integrated service. POST is a request method supported by HTTP used to send data to a server to create/update a resource.

API gatewayがlambdaと通信する際に何のメソッドを使うか?ということ。。。?

Frontend Mentor

referenceディレクトリを作成して参考文献を同じエディタ内でアクセスできるように

https://adatype.co.jp/info/archives/staff_blog/76
block, inline-block, inlineの違いについて

https://tailwindcss.com/docs/line-height
leading-relaxed

https://tailwindcss.com/docs/letter-spacing
tracking-widest
Tailwindcssでは、文字間のspace調整に限界がある

Next.js

https://nextjs.org/docs/app/building-your-application/caching
caching

個別具体のリクエストに応じてキャッシュの動作を変えることが出来る

Reactはfetchを拡張しているので、同じオプションのfetchを色んな場所で使ってデータを使っても
一回のリクエストで済むようになっている

効率を気にしてtreeのtopで呼び出したり、forward props (propsの転送)をする必要はない

https://nextjs.org/docs/app/building-your-application/caching#duration
次回 durationから

3/19

AOJ

https://onlinejudge.u-aizu.ac.jp/problems/ALDS1_5_D
マージソートの復習

個人開発

https://christina04.hatenablog.com/entry/docker-init
initフラグをcomposeで使う方法
https://docs.docker.jp/engine/reference/run.html#init

https://zenn.dev/yumemi_inc/articles/3d327557af3554
名前付きボリュームをnode_modulesに適用した際にホスト側でnode_modulesが空になってしまう

https://qiita.com/P-man_Brown/items/5a82ad98cb96206343b9
こちらの方法で解決できるが、空のnode_modulesディレクトリが必要になるなど結局面倒

entrypointで、node_modulesがないときだけnpm ciするようにすれば良いのでは?
この方法なら初回起動時にのみnpm ciが走り、ビルド時間も短くなり、イメージサイズも小さくなる

https://kechako.dev/posts/2015/05/27/210459/index.html
親、子、孫プロセスについて

Terraform / AWS

resource "aws_lambda_function" "hello_world" {
  handler = "hello.lambda_handler"
}

handlerに指定したものがlambdaのエントリーポイントになる
helloはファイル名、lambda_handlerは関数名
ファイル名は、圧縮前のhello.pyのことを表す。

iam roleに複数のポリシーをアタッチしたい場合、以下のように複数記述する必要がありそう。

resource "aws_iam_role_policy_attachment" "lambda_policy" {
  role       = aws_iam_role.lambda_exec.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}

resource "aws_iam_role_policy_attachment" "translate_policy" {
  role       = aws_iam_role.lambda_exec.name
  policy_arn = "arn:aws:iam::aws:policy/TranslateFullAccess"
}

resource "aws_iam_role_policy_attachment" "dynamodb_policy" {
  role       = aws_iam_role.lambda_exec.name
  policy_arn = "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess"
}

cloud watchのロググループは特に作成していないが、AWSが自動で作成してるっぽい?
自前で明示的に用意する場合となにが違うのか

ARN とは?
Amazon Resource Name
URIのようなもの

Frontend Mentor

https://tailwindpractice-baseapparel.netlify.app/
こちらのページを参考に、TailwindCSS のクラスの使われ方を逐一分解していく

https://tailwindcss.com/docs/customizing-colors
こちらを探しても適当な色がない、自分で追加しないとダメそう

とりあえずスマホ対応などは考えず、愚直にウェブ画面の構成のみを考えていく

参考レポジトリやデータなどを reference/ に入れ、gitignoreしておくとエディタですぐ開けて便利

Next.js

GETでResponse オブジェクトを使うと、デフォルトでキャッシュされる

Using the Request object with the GET method.
Request オブジェクトと使うことでopt outされる

route segment config で、特定の名前の変数を初期化することでそのルートセグメントの動作を変更できる
https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config
強制的にページを動的生成したり、基本は出来る限りstatic rendreingを採用する

cookieをセットしたり使ったりなどの動作はmiddlewareとroute handler で同じ

Route Handlers have an isomorphic Web API to support both Edge and Node.js runtimes seamlessly, including support for streaming. Since Route Handlers use the same route segment configuration as Pages and Layouts, they support long-awaited features like general-purpose statically regenerated Route Handlers.

全く意味がわからない...
具体例等も特にないのでスキップ

MDN CSS

https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance
カスケード
定義された順序が後の方が優先される

詳細度
より具体的な、狭い範囲に適用される定義が優先される

継承
https://developer.mozilla.org/ja/docs/Web/CSS/color#公式定義
公式定義のところから、継承ありかなしか判断できる

unset, initial などで継承しているスタイルをリセットできたりする

次回
https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance#カスケードを理解する

3/18

個人開発

Dockerの話題

docker compose run では、ENTRYPOINTが使われるが
docker compose exec ではENTRYPOINTは関係ないので、普通にログインするとrootログインになってしまう

https://docs.docker.jp/v1.11/engine/reference/builder.html
ENVはRUN命令の変数展開には使えない

ARGで定義した変数は、そのDockerfile内でのみ変数展開を使うことが出来る

WORKDIR でディレクトリを新たに作成する必要があるときは、何もしなければrootとして作られてしまう

miroscularmiroscular

3/17

AOJ

https://onlinejudge.u-aizu.ac.jp/problems/ALDS1_6_A
計数ソート
ソート対象の数をインデックスとして、カウントの累積和がそのままソート後のインデックスになる

個人開発

Docker Ctrl-Cを押した時にすぐに終了しない問題の解決
https://matsuand.github.io/docs.docker.jp.onthefly/compose/faq/
stop_signal でコンテナに送るシグナルを変えられる

https://hynek.me/articles/docker-signals/
なぜDockerがすぐ終了しないのか?という問題に色々と答えている

ここでもtiniコマンドが紹介されている
https://github.com/krallin/tini

やはりnodeでdockerコンテナを作る際はPID 1にしてはいけないという記事が多い
https://mzqvis6akmakplpmcjx3.hatenablog.com/entry/2020/11/10/231047

なぜnode_moduleディレクトリをボリュームとして保存するのか?
https://zenn.dev/tamanugi/articles/6f372d45b85c18
https://jdlm.info/articles/2016/03/06/lessons-building-node-app-docker.html
ビルド時にnpm ci含めて全部済ませて、ボリュームマウントした際にnode_modulesが消えないようにする

node_moduleの名前付きボリュームを作成したら、Dockerを通常ユーザーで実行する必要も無くなる?
node_moduleをrootでビルドしてしまうと、実行時のユーザがnodeのときアプリが機能しなくなる可能性
かといってnodeでnode_moduleをビルドすると、コンテナ実行時にホスト側のファイルをマウントした際、
node_moduleのUIDと各種ファイルのUIDがズレる可能性がある
entrypointでuidの変更後にnode_moduleのchownを行う必要がある?

.next ディレクトリもボリュームマウントしたほうが良い?

https://blog.kapiecii.com/posts/2022/07/24/docker-and-nextjs/
ポーリングを行うことで高速化を期待できる場合がある

Terraform / AWS

cloudとの同期で動作がもっさりするので、一旦cloudブロックをコメントアウトして実行する

結果は以下

> terraform init

Initializing the backend...
Migrating from Terraform Cloud to local state.
╷
│ Error: Migrating state from Terraform Cloud to another backend is not yet implemented.
│
│ Please use the API to do this: https://www.terraform.io/docs/cloud/api/state-versions.html
│
│
╵

https://nedinthecloud.com/2022/03/03/migrating-state-data-off-terraform-cloud/
こちらを参考に

ただ .terraform/terraform.tfstate を消すだけで上手く行くようになった
事前にリソースのdestroyは忘れずに

やはり、ローカルで動かすと3秒ぐらいでplanの結果が返ってくる
https://aws.amazon.com/jp/blogs/news/extend-aws-iam-roles-to-workloads-outside-of-aws-with-iam-roles-anywhere/
iam roles anywhereを利用することで、AWS外部のリソースに対してもロール付与と同じようなやり方で認可できる

aws_iam_role, でロールを作成し、aws_iam_role_policy_attachment でどんな許可を与えるかを決める
aws_iam_role_policy_attachmentが許可ポリシーに合致する
assume_role_policyは信頼関係のところと合致する

lambdaをデプロイ
コンソール上でテストすると、まだエラーが出る

Response
{
  "errorMessage": "Handler 'handler' missing on module 'hello'",
  "errorType": "Runtime.HandlerNotFound",
  "stackTrace": []
}

Frontend Mentor

imagesディレクトリをpublic配下に移動して参照しやすく
style属性からも参照可能

        <div
          className="bg-cover w-2/5 h-screen"
          style={{
            backgroundImage: `url(${imagePath}/hero-desktop.jpg)`,
          }}
        ></div>

パディングを利用したロゴの位置調整
bg-cover あるなしで微妙に変わるが、用途がわからない

Next.js

https://developer.mozilla.org/ja/docs/Glossary/Preflight_request
preflight requesetなるものが存在する

Response.json を使ってresponseを直接作ることも可能

export function middleware(request: NextRequest) {
  // 先頭が /hoge の場合
  if (request.nextUrl.pathname.startsWith('/hoge')) {
    return Response.json(
      { success: false, message: 'authentication failed' },
      { status: 401 },
    );
  }
}

NextFetchEventを使うことで、waitUntil()メソッドを使うことができ、
ミドルウェアのライフタイムを延長できたりする。

https://nextjs.org/docs/app/building-your-application/routing/route-handlers
page.tsと同時に存在はできない。APIのようなもの?

次回 Cachingから
https://nextjs.org/docs/app/building-your-application/routing/route-handlers#caching

MDN CSS

https://developer.mozilla.org/ja/docs/Learn/CSS/First_steps/How_CSS_works

古いブラウザをサポートするために、予防的に500pxを書き、新しいブラウザでは新しい命令が採用される

p {
  width: 500px;
  width: calc(90% - 50px);
}

練習問題の模範解答
https://css-design-sandbox.glitch.me/

次回
https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks

3/16

leetcode

https://leetcode.com/problems/article-views-i/description/
https://leetcode.com/problems/market-analysis-i/description
ifnull を使うだけ

個人開発

root userでのコンテナ立ち上げは可能

https://zenn.dev/anyakichi/articles/0fb5865cc5e1e3
ホスト側と同じUIDでdocker run が出来るようにしたい

https://qiita.com/hihihiroro/items/d7ceaadc9340a4dbeb8f
そう言えば、entrypoint と cmd はなにが違うのか

cmdは普通に上書き可能
entrypointは特殊なオプションで可能
併用すると entrypoint cmd
のような形式で実行される
cmdに npm run dev をしていしておき
entrypointに必要な設定等を書き、最後に exec $@ しておく
普通に run したときは npm run dev が実行され
なにか特定のコマンドをコンテナで実行したいときは上書きされたコマンドが実行される

## in hoge.sh
exec $@

同じプロセスで、引数をコマンドとして解釈して実行する

./hoge.sh echo aa
# ==> aa

https://zenn.dev/forcia_tech/articles/20210716_docker_best_practice#おまけ%3A-参考になりそうなdocker-compose
その他 Dockerfileのベストプラクティス

alpine linux では、useraddではなく adduser コマンドを使う

statコマンド
ファイルの情報の表示
printfみたく特定のフォーマットにすることもできる

https://github.com/tianon/gosu
https://github.com/ncopa/su-exec
alpine linux では簡単なので su-exec を使う

alpine linux でusermodなどが使いたい場合
https://amaya382.hatenablog.jp/entry/2017/04/10/104759
shadowをinstallする

ユーザーを削除する際はuserdelを使う

https://docs.docker.jp/engine/articles/dockerfile_best-practice.html#user
Dockerfile上で USER 命令を使うと、docker run した際もそのユーザーでログインされる
usermod, groupmod などのコマンドでUIDを書き換える際は、rootでないとできない
rootとしてデーモンを初期化し、実行はroot以外で、となるとgosuを使う
alpineではsu-execを使う
https://qiita.com/ao_log/items/1f4fcf09fb53e4fb7ebd

https://zenn.dev/hohner/articles/43a0da20181d34
dockercomposeの ttyについて
基本的に npm run devするので不要

ARGはDockerfile内で使う変数
ENVはビルド時、コンテナ内で使われる

https://ngzm.hateblo.jp/entry/2017/08/22/185224
ctrl-c したときにシャットダウンが遅い

https://rheb.hatenablog.com/entry/setpriv
setprivの利点について あとで読む

Terraform / AWS

https://dev.classmethod.jp/articles/amazon-s3-acl-basics/
acl とは何か?
基本的にポリシーで管理する
デフォルトではS3のACLは無効

Frontend Mentor

バックグラウンド画像を 3:2 で設定
画像の読み込みでいちいちimportするのが面倒
/public 以下にディレクトリを配置して簡単に読み込めるようにしたほうが良さそう

Next.js

middlewareで下記のように設定することで

  const response = NextResponse.next()
  response.cookies.set({
    name: 'foo',
    value: 'bar',
    path: '/dashboard/customers',
  })
  return response

以下のようなresponse headerになる

Set-Cookie: foo=bar; Path=/dashboard/customers

headerのセットが可能
当然ながら、ブラウザの動作が変わるわけではない
ブラウザのリクエストにヘッダーを付与する

  const requestHeaders = new Headers(request.headers);
  requestHeaders.set('x-hello-from-middleware1', 'hello');

この動作は、headers functionを使うことで、server component上で確認が出来る
https://nextjs.org/docs/app/api-reference/functions/headers

import { headers } from 'next/headers'

export default function Page() {
  const headersList = headers()
  console.log(headersList.get('x-hello-from-middleware1'))

  return <p>Customers Page</p>;
}

https://nextjs.org/docs/app/building-your-application/routing/route-handlers
route-handlers なるものがある、こちらも用途がまだわからないので一見の価値あり

MDN CSS

CSSの名称

セレクタ {
  プロパティ:}

h1 {
  color: blue;
}
background-image: linear-gradient(rgba(0, 10, 255, 0.5), rgba(255, 255, 0, 0.5)),
                  url("../../media/examples/lizard.png");

グラデーションの設定、左より順に、上から下にグラデーションする

その他

~/.config/Code/CachedExtensionVSIXs
以下のファイルを消すことでvscodeは今の所快適に動作している

tailwind css のよくある md:flex みたいな記述は、メディアクエリに関係している

次回
https://developer.mozilla.org/ja/docs/Learn/CSS/First_steps/How_CSS_works

3/15

AOJ

計数ソート
値をインデックスとして使う
https://onlinejudge.u-aizu.ac.jp/problems/ALDS1_6_A

個人開発

https://github.com/vercel/next.js/tree/canary/examples/with-docker-compose
上記のディレクトリを参考にローカル開発環境をdockernizeする

https://vercel.com/guides/does-vercel-support-docker-deployments

Dockerfileで特に設定することもない
node20 alpine をそのままdocker-composeで指定したほうがメンテナンス負荷を下げられそう

コンテナ内の実行ユーザーIDをホストと揃えたい

Terraform / AWS

terraform.tf を作成してまずはterraformの設定を書く

https://github.com/hashicorp/terraform
こちらのレポジトリを見ればterraformの最新バージョンがわかる

default_tags とは?
https://atsum.in/terraform/default-tags/#google_vignette
とりあえず色々追加してみて、UIでどうなるか確認する
https://dev.classmethod.jp/articles/terraform-aws-provider-default-tags/
AWSリソースに割り当てられるタグなるものがある
検索で便利だったり、認可やアクセス制御に使える
https://blog.serverworks.co.jp/aws-tags

https://stackoverflow.com/questions/68010489/how-to-print-terraform-variable-values
output ブロックでデバッグする

Frontend Mentor

https://www.frontendmentor.io/challenges/base-apparel-coming-soon-page-5d46b47f8db8a7063f9331a0/hub
まず、背景を設定したい
https://tailwindcss.com/docs/background-attachment
styleでurlを直接指定する模様

next.js でbgイメージを表示したい場合、普通のCSSの指定方法だと表示できない
https://stackoverflow.com/questions/51842419/next-js-background-image-css-property-cant-load-the-image
まずファイルをimportして、

import bg from "./images/bg-pattern-desktop.svg"

export default function Page() {
  return (
      <div
        className="bg-cover bg-center w-full h-screen"
        style={{ backgroundImage: `url(${bg.src})` }}
      >

このような形でimportする

https://nextjs.org/learn/dashboard-app/css-styling#css-modules
CSS module を使ってみる
使う場合は、hoge.module.css のように名前にmoduleが入っていないと上手くインポートできない模様

Next.js

Middleware について
https://nextjs.org/docs/app/building-your-application/routing/middleware#using-cookies

  response.cookies.set({
    name: 'aaa',
    value: 'fast',
    path: '/aaa',
  });

上記のように書くと、 path /aaa でのみ有効なcookieを定義できる

  console.log(request.cookies.get('fuga'))
  request.cookies.delete('fuga')
  console.log(request.cookies.get('fuga'))

クッキーを消すかどうかはあくまでクライアントの判断
これはサーバー側で読み取ったクッキーを削除するかどうか、という話

chrome devtoolsで検証可能

次回
https://nextjs.org/docs/app/building-your-application/routing/middleware#setting-headers

MDN CSS

https://developer.mozilla.org/ja/docs/Learn/CSS/First_steps/What_is_CSS

w3c の CSS working group によって開発, 現在も仕様が作られている

p,
li {
  color: green;
}

カンマ区切りの書き方で複数のセレクタにルールを適用できる

デフォルトCSS, ほぼ全てのブラウザで同じようにデフォルトで適用される
見出しの太線、リストの箇条書きなど

https://developer.mozilla.org/ja/docs/Learn/CSS/First_steps/Getting_started#文書内の場所に基づいてスタイリングする

ディセンダント・コンビネーター

li em {
  color: rebeccapurple;
}

リストアイテムの中にある em だけを選んでスタイル適用できる

(adjacent sibling combinator:アジェイセント・シブリング・コンビネーター)
直後に来る要素だけにスタイルを指定

h1 + p {
  font-size: 200%;
}

次回 詳細度から
https://developer.mozilla.org/ja/docs/Learn/CSS/First_steps/How_CSS_is_structured#詳細度

その他

vscode 不調を直す
vscodeのアンインストール
https://code.visualstudio.com/docs/setup/uninstall#_linux

クラウドで同期出来るデータは?
アンインストールで破棄されるデータは?

~/.config/Code
~/.vscode

にpersonal configが含まれている
とりあえず、vscodeのapt remove -> apt install を試す
全く直らない。

~/.config/Code
cacheデータを削除してみる
Cache
CachedData
CachedExtensions
効果なし

~/.vscode/extensions
gitlens, vscode vim の拡張機能を完全削除してから再インストール

3/14

leetcode

date_sub 関数

date_sub

下の方が速い。固定値を使ったほうが負荷が下がる模様

  activity_date between DATE_SUB('2019-07-27', INTERVAL 29 DAY)
  and '2019-07-27'
  =================================
  activity_date > '2019-06-27'
  and activity_date <= '2019-07-27'
SELECT DATE_SUB('2019-07-27', INTERVAL 30 DAY) AS minus_30_days;

個人開発

自動生成した型情報から、Anilist のMediaList に当たる部分を抜き出して型Mediumを生成
User_Anime_ListQuery から安全にMediumを抜き出す関数の作成

  useEffect(() => {
    if (loading || error || !data) return;
    setMedium(extractMedium(data));
  }, [loading, error, data]);

  useEffect(() => {
    if (medium.length === 0) return;
    ...
  }, [medium]);

extractMedium した直後にanimetheme api と通信したいものの、
setMedium の直後mediumをいじる動作を行うと、
更新される前の素のmediumを使ってしまうので、ちょっと形を変える必要がある

Terraform / AWS

resource "aws_lambda_function" "hello_world" {
  function_name = "HelloWorld"

  s3_bucket = aws_s3_bucket.lambda_bucket.id
  s3_key    = aws_s3_object.lambda_hello_world.key

なぜ s3_bucketの指定が必要?
-> archive_fileを指定するのはあくまでs3にアップロードするため。
基本的にs3にコードをアップロードしてそれを読み取るように設定する

assume roleとは何か?

resource "aws_iam_role" "lambda_exec" {
  name = "serverless_lambda"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Action = "sts:AssumeRole"
      Effect = "Allow"
      Sid    = ""
      Principal = {
        Service = "lambda.amazonaws.com"
      }
      }
    ]
  })
}

https://developer.hashicorp.com/terraform/tutorials/aws/aws-assumerole
こちらで詳しく

今回作成したリソースがコンソールでも作成されていることを確認

https://github.com/sniper-fly/tutorials/commit/4a5131a3232866598c74102198aa2c46cfca7f60

Frontend Mentor

Next.js with TailwindCSSでプロジェクトを作成
app/src 以下にダウンロードしたzipを展開して、index.htmlを参考にページを作成する
いちいちレポジトリを増やさなくても、node_modulesを都度インストールしなくても、
つど別のプロジェクトとしてデプロイする必要もなくなる

課題を行う際のお作法について確認

Next.js

https://nextjs.org/docs/app/building-your-application/routing/middleware#conditional-statements
サーバー側のコンソールでlogが出力されることを確認

export function middleware(request: NextRequest) {
  if (request.nextUrl.pathname.startsWith('/test')) {
    const url = new URL('/dashboard', request.url)
    console.log(url.pathname)
    console.log(request.url)
    // return NextResponse.rewrite('http://localhost:3000/dashboard/')
    return NextResponse.rewrite(url)
  }
}

configと同時に、conditional statementsも同時に動かせる
rewriteによって、リバースプロキシっぽい動作になる
上記では、test_middleware routeにアクセスするとアドレスはそのままだが dashboard のページが表示される

別に test_middleware/page.tsx を用意しなくても良い

new URL の使い方として、第ニ引数にまずbaseとなるurlを用意して、第一引数にサイトのパスを指定することで絶対URLを表現できる

3/12

leetcode

https://leetcode.com/problems/project-employees-i/description/
group by, join, avg を組み合わせるだけ

https://leetcode.com/problems/sales-analysis-iii/description/
not exists を使う方法と min, max を組み合わせて絞り込む方法2種で回答

個人開発

最低限のトップページの作成
Anilist API, animetheme.moe API と連携ができているか確認

form系のコンポーネントが煩雑で邪魔なので分離
次回 アニメリストを表のように行列にして表示する

Terraform AWS

https://developer.hashicorp.com/terraform/tutorials/aws/lambda-api-gateway
lambda のアップロードのためには、ソースコードと依存をアーカイブしたパッケージを用意する
s3にアップロード → lambdaデプロイ って感じの流れか

archive_file
https://registry.terraform.io/providers/hashicorp/archive/latest/docs/data-sources/file
ファイルなどからアーカイブ作成

resource "aws_lambda_function" "hello_world" {

source_code_hash を設定することでlambdaに関数が変わったことをしらせられる

次回 outputs.tfの作成

Next.js

middlewareはredirectのあと、routesの前に呼ばれる

2種類の書き方が存在する
Custom matcher config
Conditional statements

Custom matcher config
独特な書き方が出来る
https://github.com/pillarjs/path-to-regexp#path-to-regexp-1
/hoge/:path は /hoge/a にマッチする、など

次回Nextresponse より
https://nextjs.org/docs/app/building-your-application/routing/middleware#nextresponse

Q. Custom matcher config, Conditional statements は同時に使える?
試しに動作を変更, 検証したい

Frontend Mentor

https://tailwindcss.com/docs/installation
まずプロジェクトにtailwindcssのダウンロード

3/10

leetcode

https://leetcode.com/problems/product-sales-analysis-iii/submissions/
row_number, rank ウィンドウ関数の利用

個人開発

/spotify route で認証を行い、
/hoge に一旦リダイレクトする

サーバーアクションでプレイリストを作るボタンを設置する
anilistからデータ取得
animethemeから対応曲取得
spotifyで曲検索
dynamodbに検索履歴保存
spotifyでプレイリスト作成&アイテム追加は完了

あとは交通整理&UI作成のみ

Terraform

ポリシーの構成要素
rule
enforcement_level

VCSに接続可能なpolicy setはfreeだと1つまで
organizationごとに作れる
まだ一つも作成していないのに、なぜかsetを作れない

AWS

https://developer.hashicorp.com/terraform/tutorials/aws/lambda-api-gateway
Terraform で lambda と API Gateway をデプロイする

cloudブロックの設定を変えることでorganizationを設定できることを確認
新規workspaceを作成
既存のチュートリアルで使ったworkspaceはVCSとリンクしていて、
VCSをsource of truthとして利用するためterraform initができない
VCSとのリンクを切るか、新しくワークスペースを作る

terraform loginは一度行えば不要?
terraform でs3のオブジェクトを作成

terraform でリソースを作成して、UIで何か設定をいじってからdestroy出来る?

Next.js

https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming
Loading UI and Streaming

It will automatically wrap the page.js file and any children below in a <Suspense> boundary.
これの意味がわからない...
Suspenceタグのchildrenや、page.jsのタグを自動でラップするから、特に気にしなくても良いってこと?

App router ではloading.js以外でもSuspence Boundaryを作成可能

SSR についてとその制限
サーバーが必要なページのレンダリングにデータを集める
HTMLレンダーする
CSSやJavascriptも含めてクライアントに送る
non-interactiveなページが表示される
React が hydrates する
https://react.dev/reference/react-dom/client/hydrateRoot#hydrating-server-rendered-html

サーバーは全てのデータが揃ってからレンダリングする
クライアントは、全てのコンポーネントが揃ってからhydratesする

サーバーが全てのデータが揃うまで表示を待つのは遅いことがある
そのためにstreamingがある

待つのが不要なデータ、優先度高めなデータを先に送り、あとでロードが遅いデータを送る

web のUIの快適さ指標についての資料
https://developer.chrome.com/docs/lighthouse/performance/first-contentful-paint?hl=ja
https://developer.chrome.com/docs/lighthouse/performance/interactive?hl=ja
https://web.dev/articles/ttfb?hl=ja

Suspenseは、非同期のアクションを実行するコンポーネントをラップすることで機能する

Q. 実際のネットワークとしては、streamingはどう機能しているのか?
一つのリクエストでやり取りをしているのか

3/9

AOJ

クイックソート

個人開発

BatchExecuteStatementCommand ではcountなどが使えない

{
  Statement: "SELECT query, tracks FROM SpotifySearchCache WHERE query=?",
  Parameters: ["Rakuen no Tsubasa", "dororo"],
  ConsistentRead: true,
},

不定数のorをつなげる条件指定を書く方法がわからない
今回はBatchGetCommandで用途を満たせているので、sqlは不要

まずキャッシュから検索し、SearchResult に変換
SearchResultに存在しないqueryのリストを作る
上記のリストは自分でspotifyに検索をかける

次回 spotify APIでプレイリスト作成
アニメリスト取得から画面表示までつなぎこみ

Terraform

VCS githubとterraform cloudを連携
speculative plan で実際にapplyする前にインフラの変更をレビューしてくれる
githubのコメントに書き込んでくれる

VCSに接続する場合は cloud ブロックがいらなくなる
UIからインフラの削除ができる

AWS

lambda関数
ハンドラとコンテキスト

理論偏重で実践がほぼゼロなので、あまり成長できている気がしない。

Next.js

learn Next.js 復習記事

3/8

AOJ

https://onlinejudge.u-aizu.ac.jp/status/users/DJ_wata/submissions/1/ALDS1_6_B/judge/8977824/C++14
partition分割
ある値を基準にそれより小さいグループ、大きいグループに分ける

個人開発

export function Click({ action }: { action: AsyncFunction }) {
# と書くか
export const Click: FC<{ action: AsyncFunction}> = ({ action }) =>{

Next.jsのドキュメントはfunctionを使うケースしかない。

BatchGetCommand でqueryを複数指定して項目を取得できることを確認

Click コンポーネントからサーバーアクションをリフトアップして
呼び出し元からサーバーアクションを指定可能にした

次はpartiQLをバッチ実行した際の挙動の確認

Terraform

Policy as Code
Terraform Cloud で時間、月あたりのコストの計算が出来る
https://qiita.com/jerichon/items/7ec5b41ec3d20831149a
https://dev.classmethod.jp/articles/terraformcloud-sentinel-policy-sets/
ポリシー違反している場合はデプロイできないようにも出来る

https://developer.hashicorp.com/terraform/tutorials/cloud-get-started/policy-quickstart
次はここから

AWS

イベントソース

データストア系
S3、DynamoDB, Cognitなどがなりうる

エンドポイント
API Gateway

ポーリングとは?
lambda側から、送信したいデータが無いか定期的に問い合わせる

デッドレターキュー
lambda宛先指定

コールドスタートとウォームスタート
最初にlambdaが実行される際はコールドスタートになる
連続で処理が発生した場合はウォームスタートで速いレスポンスを期待できる
最後のリクエストから長い時間がたつと、またコールドスタートが必要に

設定次第である程度のリソースをウォームスタートで保ち続けることができる

コンソールからのテストは全てコールドスタート

Next.js

learn Next.js 復習記事

https://chromewebstore.google.com/detail/codetospan-for-translatio/ebnohmjaodacnofjhknnjjnchanjleng?utm_source=zenn&utm_medium=article&utm_campaign=how_to_fix_machine_translation
https://zenn.dev/dev_inui/articles/da2c282f7da040
google翻訳に掛けると、コードタグが翻訳でおかしくなってしまう
解消する拡張機能

miroscularmiroscular

3/7

leetcode

外部キーを参照してテーブルを表示する
2列の値を利用してgroup by

個人開発

DynamoDBClientを使う
@aws-sdk/lib-dynamodb を使うことで、より簡単にDynamoDBにアクセスできる
https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-lib-dynamodb/Class/PutCommand/

PutCommand は同じprimary keyでputされた場合はあとで追加した値に更新してしまう

curlでAPIを叩いた時と、SpotifyのAPI example pageで
APIを叩いたときで結果が違う
example pageで取得した結果が欲しい

ACCESS TOKENが変わると、取得結果の順番が変わってしまう

node_moduleパッケージの改造をテストしたいとき
https://github.com/spotify/spotify-web-api-ts-sdk
例えば、これ
git clone してrootでnpm i
scriptsにbuildのコマンドがあるので、
npm run build
これでdist/cjs, dist/mjs にコンパイルされる
src上のファイルをいじって、npm run build すればまたコンパイルされるので、そのファイルを利用してexample_nodeなどを動かせる

withClientCredentials で取得するaccess tokenではあまり
正確な検索結果が得られなさそう

https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-lib-dynamodb/Class/BatchWriteCommand/
BatchWriteCommandを使うことで大量データの書き込みができそう

https://docs.aws.amazon.com/ja_jp/sdk-for-javascript/v3/developer-guide/javascript_dynamodb_code_examples.html
項目のバッチを取得する 項目のバッチを書き込む
に使い方が載っている

SearchResults をインメモリで保持し、曲名またはアニメタイトルでTrackInfoを検索できるようにする
DynamoDBにキャッシュが存在しない場合はSpotifyAPIを叩いてキャッシュを作成する
BatchGetCommand でレコードがなかった時、どのようなレスポンスになるか確認する
対応レコードがなかったときは、SpotityAPIを叩いてキャッシュを作成し、
SearchResults の適切なキーに追加する

  • 目標
    • ユーザー数100人
    • 収益50$
    • ポートフォリオとしての制作物ではなく、本当に自分がほしいと思えるサービス
    • 課金機能の作成、課金に応えうる十分なサービス提供
    • 一朝一夕では作れない作品
  • 重要度測定
    • 100
  • 自信
    • 50
  • 問題
    • (1)利用規約の作成など、開発以外での雑務の発生
    • (2)セキュリティ
    • (3)APIの機能変更
    • (4)収益化に伴うメンテナンスの責任
    • (5)インフラのベストプラクティスがわからない
    • (6)難しい機能になればなるほど、困った時に聞ける人がいない
  • 資料/理由/使用法
    • (1)
    • (2)
    • (3)
    • (4)
    • (5)
    • (6)

3/6

leetcode

count(distinct ~~~) の使い方
update 文の中でもifは式として使える

個人開発

Spotify SDKでどんなデータがとれるか確認
検索結果をキャッシュするDynamoDBのデータ形式を決定

Terraform

Terraform Cloud とは
stateやenv var の管理がセキュアに出来る

CLI-driven workflow
VCS-driven workflow
API driven workflow

CLI-driven では、local executionとremote execution が選べる
remote executionでは、terraform cloudからプロビジョニングが実行され
localでは自分のマシンから。
環境変数を自分のマシンにだけ収めたい場合はローカル実行もあり?
複数人で共有するインフラなら、環境変数の共有が面倒なのでリモート実行が良さそう

AWS

https://explore.skillbuilder.aws/learn/course/621/play/1727/aws-lambda-foundations-japanese
lambda foundations

lambdaはEC2のようにAuto Scalingを設定する必要がなく、自動でスケールする

S3からイベント駆動でlambdaを動かせる
S3からlambdaを呼び出すアクセス許可がIAMリソースポリシー
lambdaが他のサービスを呼び出す権限設定がIAM実行ロール

デフォルトではVPC内リソースにlambdaからアクセスできない
lambdaはAWSが所有するVPC内に存在している

Next.js

Learn Next.js 復習記事

3/5

AOJ

マージソートで再帰、分割統治法を学ぶ
https://onlinejudge.u-aizu.ac.jp/problems/ALDS1_5_B

個人開発

相変わらず、AWSのアプリケーションの適切な認証方法がわからない...
今はcredentialで多分認証できているが、アプリをデプロイした際には
別の設定が必要になりそう。使っているアクセストークンをそのまま環境変数で渡しても良いものか...?

権限を絞って認証情報を渡したいが、なにがベストプラクティスなのか。
ChatGPT曰く、必要な権限のみを持ったIAM roleを作成し、クレデンシャルを
環境変数に格納するのが良いとのこと。Docker環境でも同じことができる?

https://docs.aws.amazon.com/ja_jp/sdk-for-javascript/v3/developer-guide/javascript_dynamodb_code_examples.html
DynamoDB のSDKの例を元に、テーブル一覧取得とテーブル追加まで

下記コマンドでpackage.jsonを初期化可能

node init -y

package.json"type": "module" を追加することで
EcmaScriptのモジュールとして認識してもらう

Terraform

variable の default = ~~~ で変数の値を宣言できる
terraformコマンドはカレントディレクトリの.tfファイルを全て読み込む
拡張子が合ってれば名前はなんでもよし

https://developer.hashicorp.com/terraform/tutorials/configuration-language/variables
variableを使って設定に柔軟性をもたせる
main.tfは複数インフラで使いまわして、
変数で状況に合わせてインスタンスの数を調整したりなど、といった使い方ができそう

tfファイル内の、
terraform, provider, などはブロックと呼ぶ

output ブロック
apply したあとなどにインスタンスの情報をoutputする
これによって他のインフラとつなぎこみができたりする

terraform cloudを使うことで、tfstateを安全に管理し、
インフラの状態をチームメイトと共同管理できる

次回 Terraform cloudのアカウント作成

AWS

AWS Skill Builder CloudQuest 感想まとめ記事

Next.js

Learn Next.js 感想まとめ記事

3/4

AOJ

マージソート、分割統治法
clang-format で AllowShortIfStatementsOnASingleLine を追加

個人開発

サーバー側で、ユーザー認証を通さずにAPIを叩いている例を確認
withClientCredentials を使うことでとりあえず検索だけは出来る

secretを読むのに、サーバー側でコードを実行させるのに苦戦

onClickみたいなイベントハンドラが必要なものは全部client component
apiルートのときは、イベントハンドラからAPI呼び出しができたはず
app router ではどうする?

下記の方法でいける。(hogeはserver側のアクション)

'use server'

import { SpotifyApi } from "@spotify/web-api-ts-sdk";

export async function hoge() {
  const api = SpotifyApi.withClientCredentials(
    process.env.NEXT_PUBLIC_SPOTIFY_CLIENT_ID!,
    process.env.SPOTIFY_CLIENT_SECRET!
  );

  const items = await api.search("The Beatles", ["artist"]);

  console.table(
    items.artists.items.map((item) => ({
      name: item.name,
      followers: item.followers.total,
      popularity: item.popularity,
    }))
  );
}

ポイントは、handleClick内でサーバーアクションを呼び出すこと。

'use client'

import { Button } from "@/components/ui/button";
import { hoge } from "../spotify/searchSong";
// import { SpotifyApi } from "@spotify/web-api-ts-sdk";

export default function Page() {
  function handleClick() {
    hoge();
  }

  return (
    <>
      <Button onClick={handleClick}>log</Button>
    </>
  );
}

onClickイベントの引数として直接呼び出すと、ブラウザ側で実行されてしまう

'use client'

import { Button } from "@/components/ui/button";
import { hoge } from "../spotify/searchSong";
// import { SpotifyApi } from "@spotify/web-api-ts-sdk";

export default function Page() {
  return (
    <>
      <Button onClick={hoge}>log</Button>
    </>
  );
}

Terraform

known after apply →作ってみないとわからない値
terraform.tfstate
AWSのインスタンスIDなど、AWSのAPIから返ってきた情報が逐一格納される
これのおかげでインスタンスの操作が出来る(削除など)
センシティブな情報が入る可能性がある野江、セキュアに格納する必要がある
プロダクション環境ではTerraform Cloudを使うと良い

日本リージョンでEC2インスタンスを起動してみる

AMIカタログで検索し、 ami-**** で始まるのがid

削除の際、依存関係がある場合は適切な順番でTerraformは削除する

AWS

AWS Skill Builder CloudQuest 感想まとめ記事

Next.js

Learn Next.js 感想まとめ記事

3/2

leetcode

https://leetcode.com/problems/exchange-seats/solutions/4437058/mysql-easy-solution-with-case-statement/
id を入れ替えてから id でorder by して元に戻すという画期的な解法

個人開発

authenticate() メソッドがエラーを吐く
(no verifier found in cache)
useEffectが2回マウントするのが原因の可能性がある
next.js でstrict mode をオフにする

const nextConfig = {
  reactStrictMode: false,
};

やはりオフにすると出なくなる。authenticate()メソッドの使い方は間違っていない
https://docs.aws.amazon.com/ja_jp/sdk-for-javascript/v2/developer-guide/setting-credentials-node.html
AWS SDK for javascript
認証情報をロードする方法

https://chat.openai.com/share/2d284128-fb1c-49a9-8c7e-844cc359d1a1
AWS IAM roleを使って、DynamoDB read write 権限を
アプリケーションに付与する

https://docs.aws.amazon.com/ja_jp/sdk-for-javascript/v2/developer-guide/setting-credentials-node.html
javascript sdkで認証情報を設定する方法

Terraform

Terraform configuration

blockの説明
terraform 必要なproviderの宣言
provider 特定のproviderの設定
resource EC2など、インフラのコンポーネントを定義する

terraform fmt
フォーマット
terraform validate
コンフィグが文法的に合っているかどうか

AWS

VPC間の通信

CIDR
classless inter domain routing
8bit単位に区切ることにこだわらずにネットワークとサブネットを分ける表記

172.31.0.177
ピアリング接続を確立したら、ルーティングテーブルを設定する
さらに、接続先のセキュリティルールを変更する

Next.js

記事執筆

3/1

AOJ

https://cpprefjp.github.io/lang/cpp17/extension_to_aggregate_initialization.html
集成体初期化の拡張
コンストラクタを定義しなくても、初期化を簡単にできる
デフォルトコンストラクタ、コピーコンストラクタがないと簡単に宣言できず、
point.x = 1, point.y = 1 を全部書かないといけない

個人開発

Spotify Api の Next 版公式実装を解読する
https://github.com/spotify/spotify-web-api-ts-sdk
example_next を動かす
下記コマンドで spotify の sdk をインストールして npm run dev

npm install @spotify/web-api-ts-sdk

import エラーや、Invalid redirect_uri など多数のエラーが発生し
手動で直しきれず断念

example_react
これはそのまま動く。

なぜか useEffect の際に
"No verifier found in cache" が発生し、event のときに発生しないか
React が useEffect を 2 回呼ぶために発生している可能性がある
一度、2 回読み込む設定をいじって発生するかどうか調べる

以前使った方法で基本的に間違いは無し
サーバーサイドで検索などを行う可能性があるので、node のコードもチェックする

Terraform

https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli
main.tf を配置し、terraform init で初期化
terraform.lock などはバージョンコントロール必須
次に init したときに同じ環境を再現するため
terraform apply で環境を構築し、 terraform destroy で破棄

asdf で aws-cli を再インストール

AWS

高可用なウェブアプリ
Elastic Load Balancing
Auto Scaling
メトリクスデータに関しては cloudwatch と直接連携
ホストの追加・削除も直接ロードバランサと連携
CPU 使用率が 80%を超えたら、(cloudwatch による報告)
EC2 インスタンスを増やしてロードバランサーに追加

cloudfront
静的コンテンツの配信、キャッシュサーバー

failover
障害発生時の DB などの自動切り替えシステム

ロードバランサーヘルスモニタリング

セキュリティグループとは?
VPC 上で通信制御するファイアウォール機能

ターゲットグループでロードバランサーのヘルスチェックの設定ができる

Auto Scaling グループで、ネットワークから
別アベイラビリティーゾーンにサブネットを追加
詳細設定から希望するキャパシティ、最大キャパシティを増やすことで分散できる

Next.js

partial pre-rendering
Suspence を使うことで、どの部分が dynamic なのか、境界を明示できる
通常、ウェブページは HTML を動的に生成するか、静的に生成するかが
url route にごとに決まっているが、Next.js では 1 ページの中に混在させられる
ショッピングカートなど、大部分は静的に生成したくとも、一部のカートなどは
動的に画面を生成したいことがある

このスクラップは15日前にクローズされました