Deployer
Deployerは、Mastraアプリケーションのデプロイを担当し、コードのパッケージング、環境ファイルの管理、Honoフレームワークを使用したアプリケーションの提供を行います。具体的な実装では、特定のデプロイ先に合わせたdeployメソッドを定義する必要があります。
使用例
import { Deployer } from "@mastra/deployer";
// Create a custom deployer by extending the abstract Deployer class
class CustomDeployer extends Deployer {
constructor() {
super({ name: "custom-deployer" });
}
// Implement the abstract deploy method
async deploy(outputDirectory: string): Promise<void> {
// Prepare the output directory
await this.prepare(outputDirectory);
// Bundle the application
await this._bundle("server.ts", "mastra.ts", outputDirectory);
// Custom deployment logic
// ...
}
}
パラメーター
コンストラクターのパラメーター
args:
object
Deployer の設定オプション。
args.name:
string
deployer インスタンスの一意の名前。
deploy のパラメーター
outputDirectory:
string
バンドルおよびデプロイ準備が整ったアプリケーションが出力されるディレクトリ。
メソッド
getEnvFiles:
() => Promise<string[]>
デプロイ時に使用する環境ファイルのリストを返します。デフォルトでは、'.env.production' および '.env' ファイルを探します。
deploy:
(outputDirectory: string) => Promise<void>
サブクラスで実装する必要がある抽象メソッドです。指定された出力ディレクトリへのデプロイ処理を行います。
Bundler から継承されたメソッド
Deployer クラスは、Bundler クラスから以下の主要なメソッドを継承しています。
prepare:
(outputDirectory: string) => Promise<void>
出力ディレクトリをクリーンアップし、必要なサブディレクトリを作成して準備します。
writeInstrumentationFile:
(outputDirectory: string) => Promise<void>
テレメトリ目的のために、出力ディレクトリにインストゥルメンテーションファイルを書き込みます。
writePackageJson:
(outputDirectory: string, dependencies: Map<string, string>) => Promise<void>
指定された依存関係を含む package.json ファイルを出力ディレクトリに生成します。
_bundle:
(serverFile: string, mastraEntryFile: string, outputDirectory: string, bundleLocation?: string) => Promise<void>
指定されたサーバーファイルと Mastra エントリーファイルを使用してアプリケーションをバンドルします。
コアコンセプト
デプロイメントライフサイクル
Deployer 抽象クラスは、構造化されたデプロイメントライフサイクルを実装しています。
- 初期化: Deployer は名前で初期化され、依存関係管理のために Deps インスタンスを作成します。
- 環境設定:
getEnvFiles
メソッドは、デプロイ時に使用する環境ファイル(.env.production, .env)を特定します。 - 準備:
prepare
メソッド(Bundler から継承)は、出力ディレクトリをクリーンアップし、必要なサブディレクトリを作成します。 - バンドル:
_bundle
メソッド(Bundler から継承)は、アプリケーションコードとその依存関係をパッケージ化します。 - デプロイ: 抽象メソッド
deploy
は、サブクラスによって実装され、実際のデプロイプロセスを処理します。
環境ファイル管理
Deployer クラスには、getEnvFiles
メソッドを通じて環境ファイル管理のための組み込みサポートがあります。このメソッドは以下を行います。
- あらかじめ定義された順序(.env.production, .env)で環境ファイルを探します
- FileService を使用して最初に存在するファイルを見つけます
- 見つかった環境ファイルの配列を返します
- 環境ファイルが見つからない場合は空の配列を返します
getEnvFiles(): Promise<string[]> {
const possibleFiles = ['.env.production', '.env.local', '.env'];
try {
const fileService = new FileService();
const envFile = fileService.getFirstExistingFile(possibleFiles);
return Promise.resolve([envFile]);
} catch {}
return Promise.resolve([]);
}
バンドルとデプロイメントの関係
Deployer クラスは Bundler クラスを継承しており、バンドルとデプロイメントの明確な関係を確立しています。
- バンドルは前提条件: バンドルはデプロイメントの前提となるステップであり、アプリケーションコードがデプロイ可能な形式にパッケージ化されます。
- 共通インフラストラクチャ: バンドルとデプロイメントは、依存関係管理やファイルシステム操作などの共通インフラストラクチャを共有します。
- 特化したデプロイメントロジック: バンドルがコードのパッケージ化に特化しているのに対し、デプロイメントはバンドル済みコードをデプロイするための環境固有のロジックを追加します。
- 拡張性: 抽象メソッド
deploy
により、さまざまなターゲット環境向けに特化したデプロイヤーを作成できます。