🐞

Compute@Edge のはじめかた

2021/11/29に公開

Fastly の Compute@Edge を無料で試すことができるようになりました。この記事ではアカウントの作成からサービスのデプロイまでのステップを紹介します。

1. アカウントの作成

アカウントを持っていない場合はこちらから作成してください。
https://www.fastly.com/jp/signup/

2. APIトークンの作成

Compute@Edge サービスのビルドやデプロイは Fastly CLI を使って行います。ここでは Fastly CLI 用の APIトークンを作成しておきます。

  1. アカウントにログインして右上のドロップダウンから Account を選択
  2. 左メニューから Personal API tokens を選択
  3. 以下の項目を選択してトークンを作成
    • Scope: global
    • Service Access: All Services


APIトークンの作成

3. Fastly CLI のセットアップ

Fastly CLI をインストールして作成した APIトークンを適用します。

インストール

MacOS へのインストール

Hombebrew でインストールしてください。

brew install fastly/tap/fastly
Windows へのインストール

Githubリポジトリからバイナリをダウンロードしてください。
https://github.com/fastly/cli/releases/latest

Linux へのインストール

Githubリポジトリからバイナリをダウンロードしてください。
https://github.com/fastly/cli/releases/latest

Debian/Ubuntu, Fedora, CentOS, SUSE のパッケージも用意されています。
https://developer.fastly.com/reference/cli/#installing

プロファイルを作成する

fastly profile create を実行して作成したトークンをセットします。

fastly profile create demo

An API token is used to authenticate requests to the Fastly API. To create a token, visit
https://manage.fastly.com/account/personal/tokens

Fastly API token:


✓ Initializing...
✓ Validating token...
✓ Persisting configuration...

You can find your configuration file at:
	/Users/hkakehashi/Library/Application\ Support/fastly/config.toml


SUCCESS: Profile 'demo' created

4. 言語ごとの開発環境の準備

プロジェクトをビルドするために、言語ごとの開発環境を準備します。

Rust
  1. rustup と Rust の stable をインストールします。
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
  1. コンパイルターゲットとして wasm32-wasi をインストールします。
rustup target add wasm32-wasi --toolchain stable
JavaScript

Node.js (>= 16.6) と npm が必要です。
最新版の Node.js をインストールしていただければ問題ないはずです。
https://nodejs.org/ja/

5. プロジェクトの作成

適当なディレクトリを作成して、ディレクトリ内で fastly compute init を実行します。プロンプトに従って開発言語を選択してください。言語以外はとりあえずデフォルトのままでOKです。


fastly compute init

6. コーディング

fastly compute init で作成したプロジェクトはそのままでもビルド・デプロイ可能な状態になっていますが、ここでは以下の処理をするコードの例を紹介します。

エントリポイントとなるファイルにコードを追加します。もともと含まれていたコードは使わないので削除します。

Rust のコード例

src/main.rs

Rust のエントリポイントは src/main.rs です。

main.rs
use fastly::http::StatusCode;
use fastly::{Error, Request, Response};

#[fastly::main]
fn main(mut req: Request) -> Result<Response, Error> {

    match req.get_path() {
        "/" => {
            req.set_ttl(60);
            Ok(req.send("backend_1")?)
        }

        _ => Ok(Response::from_status(StatusCode::NOT_FOUND)
            .with_body_text_plain("The page you requested could not be found\n")),
    }
}

JavaScript のコード例

src/index.js

JavaScript のエントリポイントは src/index.js です。

index.js
addEventListener("fetch", (event) => event.respondWith(handleRequest(event)));

async function handleRequest(event) {
  let req = event.request;
  let url = new URL(req.url);

  if (url.pathname === "/") {
    return fetch(req, {
      backend: "backend_1",
      cacheOverride: new CacheOverride("override", { ttl: 60 }),
    });
  }

  return new Response("The page you requested could not be found", {
    status: 404,
  });
}

7. プロジェクトのデプロイ

fastly compute publish を実行してビルドとデプロイを行います。初回はビルドが問題なく完了するとサービスを設定するためのプロンプトが表示されます。

  • Create new service は y を入力
  • Domain は自動生成される
  • Backend はそれぞれ以下のように設定する
    • Hostname: httpbin.org
    • Port number: 443
    • Backend name: backend_1


fastly compute publish

デプロイが完了すると URL とサービスの管理コンソールへの URL が表示されます。リクエストを送って動作を確認してみてください。

リンク集

Compute@Edge のはじめかたのより詳細な記事。開発言語ごとのコーディングガイドへのリンクやCompute@Edge のリソース制限についても記載されています。
https://developer.fastly.com/learning/compute/

ローカルマシン上でテストする方法や、ログのライブテーリング等。
https://developer.fastly.com/learning/compute/testing/

コードサンプル集。
https://developer.fastly.com/solutions/examples/

Discussion