Rustのshuttleを使ってみる【1】

にあえん

November 2, 2023

Rustで無料で建てられるサーバーがあるだって?やったー!ナナオです。

今回はそんなshuttleが気になったので使ってみます。

Installation - Shuttle

Shuttleとは

インフラ構築なしでバックエンドをデプロイできるサービスです。

firebaseと似たような、いわゆるBaaSってやつですね。

主な使い方としては簡易なWebサーバーの構築や、Discordクライアントとして使用できるようです。

無料プランの中でデータ永続化サービスとしてPostgresも使えるので、結構充実しています。

#[shuttle_runtime::main]
async fn main(
    // automatic db provisioning + hands you back an authenticated connection pool
    #[shuttle_shared_db::Postgres] pool: PgPool,
) -> ShuttleRocket<...> {
    // application code
}

以下のライブラリをサポートしているため、これらのライブラリの使用経験があればすぐにでもデプロイができると思います。

早速使ってみる

まずはshuttle cliをインストールしておきます。

cargo install shuttle

CLIからshuttleアプリケーションを初期化できます。

質問形式でプロジェクトをセットアップできます。

> cargo shuttle init
First, let's log in to your Shuttle account.
If your browser did not automatically open, go to https://console.shuttle.rs/new-project
✔ API key · ********

What do you want to name your project?
It will be hosted at ${project_name}.shuttleapp.rs, so choose something unique!
✔ Project name · shuttle-playground-nanao

Where should we create this project?
✔ Directory · C:\Users\Nanao\Project\study\shuttle-playground

Shuttle works with a range of web frameworks. Which one do you want to use?
✔ Framework · actix-web

Creating project "shuttle-playground-nanao" in "C:\Users\Nanao\Project\study\shuttle-playground"

Hint: Check the examples repo for a full list of templates:
      https://github.com/shuttle-hq/shuttle-examples
Hint: You can also use `cargo shuttle init --from` to clone templates.
      See https://docs.shuttle.rs/getting-started/shuttle-commands
      or run `cargo shuttle init --help`

✔ Claim the project name "shuttle-playground-nanao" by starting a project container on Shuttle? · yes

Project "shuttle-playground-nanao" is ready
Your project will sleep if it is idle for 30 minutes.
To change the idle time refer to the docs: https://docs.shuttle.rs/getting-started/idle-projects

Run `cargo shuttle deploy --allow-dirty` to deploy your Shuttle service.
You can `cd` to the directory, then:
Run `cargo shuttle run` to run the app locally.

APIキーが必要なため、事前にブラウザ側でshuttleのコンソールにログインしている必要があります。

以下のコマンドでログインできます。

cargo shuttle login

また、プロジェクト名はユニークなものを使用しないといけないので注意が必要です。

それ以外は難なく初期化ができました!簡単ですね。

早速生成されたコードを見てみましょう。

/// src/main.rs
use actix_web::{get, web::ServiceConfig};
use shuttle_actix_web::ShuttleActixWeb;

#[get("/")]
async fn hello_world() -> &'static str {
    "Hello World!"
}

#[shuttle_runtime::main]
async fn main() -> ShuttleActixWeb<impl FnOnce(&mut ServiceConfig) + Send + Clone + 'static> {
    let config = move |cfg: &mut ServiceConfig| {
        cfg.service(hello_world);
    };

    Ok(config.into())
}

ある程度もうセットアップできていますね。

まずはこれをローカルで実行してみましょう。

> cargo shuttle run
    Building C:\Users\Nanao\Project\study\shuttle-playground
   Compiling shuttle-playground-nanao v0.1.0 (C:\Users\Nanao\Project\study\shuttle-playground)
    Finished dev [unoptimized + debuginfo] target(s) in 8.86s
2023-11-02T19:55:44.848+09:00 [Runtime] shuttle-runtime executable started (version 0.30.1)
2023-11-02T19:55:44.848+09:00 [Runtime] ===============================================================
2023-11-02T19:55:44.848+09:00 [Runtime] Shuttle's default tracing subscriber is initialized!
2023-11-02T19:55:44.848+09:00 [Runtime] To disable the subscriber and use your own,
2023-11-02T19:55:44.848+09:00 [Runtime] turn off the default features for shuttle-runtime:
2023-11-02T19:55:44.848+09:00 [Runtime]
2023-11-02T19:55:44.848+09:00 [Runtime] shuttle-runtime = { version = "...", default-features = false }
2023-11-02T19:55:44.848+09:00 [Runtime] ===============================================================
2023-11-02T19:55:44.850+09:00 [Runtime] loading alpha service at C:\Users\Nanao\Project\study\shuttle-playground\target\debug\shuttle-playground-nanao.exe
No resources are linked to this service

    Starting shuttle-playground-nanao on http://127.0.0.1:8000

2023-11-02T19:55:45.227+09:00 [Runtime] Starting on 127.0.0.1:8000
2023-11-02T19:55:45.227+09:00 [Runtime]  INFO actix_server::builder: starting 4 workers
2023-11-02T19:55:45.227+09:00 [Runtime]  INFO actix_server::server: Tokio runtime found; starting in existing Tokio runtime

起動しました。

試しにリクエストを送ってみましょう。

> curl http://127.0.0.1:8000


StatusCode        : 200
StatusDescription : OK
Content           : Hello World!
RawContent        : HTTP/1.1 200 OK
                    Content-Length: 12
                    Content-Type: text/plain; charset=utf-8
                    Date: Thu, 02 Nov 2023 13:44:06 GMT

                    Hello World!
Forms             : {}
Headers           : {[Content-Length, 12], [Content-Type, text/plain; charset=utf-8], [Date, Thu, 02 Nov 2023 13:44:06 GMT]}
Images            : {}
InputFields       : {}
Links             : {}
ParsedHtml        : System.__ComObject
RawContentLength  : 12

はい、リクエストできました。

ローカルで起動テストするのも結構簡単にできますね。

ということでこのアプリケーションをデプロイしてみましょう。

> cargo shuttle deploy
Warning:
    A newer version of cargo-shuttle exists (0.31.0).
    It is recommended to upgrade.
    Refer to the upgrading docs: https://docs.shuttle.rs/configuration/shuttle-versions#upgrading-shuttle-version
Error: 4 files in the working directory contain changes that were not yet committed into git:
.gitignore
Cargo.lock
Cargo.toml
src/

デプロイしようとしたら、コミットしていないと怒られたので、コミットしてから改めてデプロイします。

> cargo shuttle deploy
2023-11-02T22:51:08.336+09:00 [Deployer]  INFO Starting deployment
...中略...
2023-11-02T22:53:16.352+09:00 [Runtime] Starting on 127.0.0.1:18006
2023-11-02T22:53:16.352+09:00 [Deployer]  INFO shuttle_deployer::deployment::run: Runtime started successully
No resources are linked to this service

Service Name:  shuttle-playground-nanao
Deployment ID: 1c927495-fd07-4e92-b49e-108e61511e6d
Status:        running
Last Updated:  2023-11-02T13:53:16Z
URI:           https://shuttle-playground-nanao.shuttleapp.rs

Warning:
    A newer version of cargo-shuttle exists (0.31.0).
    It is recommended to upgrade.
    Refer to the upgrading docs: https://docs.shuttle.rs/configuration/shuttle-versions#upgrading-shuttle-version
Warning:
    A newer version of shuttle-deployer is available (0.31.0).
    Use `cargo shuttle project restart` to upgrade.
Warning:
    A newer version of shuttle-runtime is available (0.31.0).
    Update it and any other shuttle dependencies in Cargo.toml.

デプロイできました!

ということでアクセスしてみます。

ブラウザからアクセスした様子

アクセスできました!

まとめ

Rust、どんどん便利なサービスができていますね。

こういうサービスが増えてくれると個人開発にも力が入るので、どんどんこういうツールを吸収していこうと思います。

次回はまたもう少しShuttleの掘り下げを行いたいと思います。