Services
Introduction
多くのアプリケーションは、決済プロバイダのクライアント、検索クライアント、ジオコーダーなどを起動時に一度構築し、複数のハンドラーやジョブで共有します。毎リクエストで作ると接続を浪費し環境の読み取りを繰り返しますが、全依存をルート、ジョブ構造体、ヘルパへ逐一渡すとシグネチャが煩雑になります。
services/services.go の services パッケージで解決できます。共有依存を格納する Services、起動時に環境から一度構築する New、リクエストや context から取り出す From を定義します。
// services/services.go
package services
import (
"context"
laravel "go.laravel.com"
"go.laravel.com/config"
)
type Services struct{}
func New(env *config.Env, app *laravel.App) Services {
return Services{}
}
func From(ctx context.Context) *Services {
return laravel.ServicesOf[*Services](ctx)
}
bootstrap/app.go の Services: laravel.BuildServices(services.New) がコンストラクタを登録します。Laravel はデータベース、キャッシュ、キュー、トレーシングなどを構築後、services.New を一度呼び、*Services をアプリケーションに付けます。パッケージのグローバルではないため、各テストが独立した Services を構築し、並行テストに影響せずフィールドを交換できます。
データベース、キャッシュ、メーラー、ストレージ、キューは db.Table や mail.To などのパッケージからコンテキストに接続済みです。services.Services に追加するのは独自のクライアント、SDK、設定だけです。
Building your services
Stripe などと通信する場合は billing などの独立したパッケージにクライアントを作り、services/services.go で接続します。次の billing は決済プロバイダを Client 型で包みます。
// billing/client.go
package billing
import (
"context"
"errors"
"net/url"
"strconv"
"go.laravel.com/httpclient"
)
type Client struct {
key string
currency string
}
func NewClient(key, currency string) *Client {
return &Client{key: key, currency: currency}
}
func (c *Client) Charge(ctx context.Context, cents int64) error {
if c.key == "" {
return errors.New("billing: STRIPE_KEY is not set")
}
_, err := httpclient.Token(c.key).
Form(url.Values{
"amount": {strconv.FormatInt(cents, 10)},
"currency": {c.currency},
}).
EnsureSuccessful().
Post(ctx, "https://api.stripe.com/v1/payment_intents")
return err
}
次に Services に Billing を加え、services.New で構築します。Laravel は自身と同じ *config.Env を渡すため、ローカルでは .env、本番ではプロセス環境から変数を読みます。
// services/services.go
package services
import (
"context"
laravel "go.laravel.com"
"go.laravel.com/config"
"app/billing"
)
type Services struct {
Billing *billing.Client
}
func New(env *config.Env, app *laravel.App) Services {
return Services{
Billing: billing.NewClient(
env.String("STRIPE_KEY", ""),
env.String("BILLING_CURRENCY", "usd"),
),
}
}
func From(ctx context.Context) *Services {
return laravel.ServicesOf[*Services](ctx)
}
env.Int に数値以外が入るなど無効な値があると、起動を止めて問題を表示します。env の型付き読み取りは your own settings を参照してください。
STRIPE_KEYなどはservices.Newで空のフォールバックを与え、キーなしで実際にクライアントを呼んだ時点でエラーにします。全コンソールコマンドがサービスを構築するため、services.Newで失敗すると、複製直後で.envのない状態のlaravel key:generateなども実行できなくなります。
Depending on other services
別サービスに依存する場合は services.New で先に依存先を構築して次のコンストラクタへ渡します。たとえば billing.Client が決済前の税計算に tax.Calculator を必要とするなら、taxCalculator を先に作り billing.NewClient へ渡します。
// services/services.go
func New(env *config.Env, app *laravel.App) Services {
taxCalculator := tax.NewCalculator(env.String("TAX_API_KEY", ""))
billingClient := billing.NewClient(
env.String("STRIPE_KEY", ""),
env.String("BILLING_CURRENCY", "usd"),
taxCalculator,
)
return Services{
Tax: taxCalculator,
Billing: billingClient,
}
}
明示的に渡すことで依存グラフが一箇所にまとまり、実行前に Go コンパイラーが引数不足を検出できます。
Interfaces and concrete types
最初は Services に *billing.Client などの具体的なポインター型を使います。実装が複数ある場合や、HTTP テストサーバーなしで軽量なメモリ内フェイクに替えたい場合はインターフェイスを使います。
たとえば geo は Mapbox の実装と小さな Geocoder インターフェイスを定義できます。
// geo/geocoder.go
package geo
import "context"
type Coordinates struct {
Latitude float64
Longitude float64
}
type Geocoder interface {
Locate(ctx context.Context, address string) (Coordinates, error)
}
services/services.go の型を geo.Geocoder とし、New で本番用実装を接続します。
// services/services.go
type Services struct {
Billing *billing.Client
Geocoder geo.Geocoder
}
func New(env *config.Env, app *laravel.App) Services {
return Services{
Billing: billing.NewClient(
env.String("STRIPE_KEY", ""),
env.String("BILLING_CURRENCY", "usd"),
),
Geocoder: geo.NewMapbox(env.String("MAPBOX_TOKEN", "")),
}
}
Reusable HTTP clients
ベース URL、Bearer トークン、タイムアウトだけが必要なら独自のラッパーパッケージは不要です。再利用する *httpclient.Client テンプレートを Services に直接保存します。
// services/services.go
type Services struct {
GitHub *httpclient.Client
}
func New(env *config.Env, app *laravel.App) Services {
return Services{
GitHub: httpclient.BaseURL("https://api.github.com").
Token(env.String("GITHUB_TOKEN", "")).
AcceptJSON().
EnsureSuccessful(),
}
}
httpclient.BaseURL から始めると、Get や Post のコンテキストにあるアプリケーション経由でリクエストするため、テストでも httpclienttest が捕捉できます。詳細は base URLs and reusable clients を参照してください。
Using services
In handlers and middleware
ハンドラーや middleware で r を services.From に渡し、サービスを取得します。
// handlers/invoices/invoices.go
package invoices
import (
"go.laravel.com/web"
"app/services"
)
func Store(r *web.Request) *web.Response {
if err := services.From(r).Billing.Charge(r, 2000); err != nil {
return web.Fail(err)
}
return web.Back()
}
In jobs, commands, and domain packages
ハンドラー以外では、関数は *web.Request の代わりに ctx context.Context を受け取ります。その ctx を services.From(ctx) に渡せば、キューに入れたジョブ、イベントリスナ、コンソールコマンド、スケジュールタスク、ハンドラーのどこからでもコードを使用できます。次のキュージョブは、同じ Billing クライアントで請求書の決済を行います。
// jobs/charge_invoice.go
package jobs
import (
"context"
"app/services"
)
type ChargeInvoice struct {
AmountCents int64
}
func (j ChargeInvoice) Handle(ctx context.Context) error {
return services.From(ctx).Billing.Charge(ctx, j.AmountCents)
}
インストールしたパッケージは独自にサービスを登録し、inspire.From(r) などの From を公開します。作成方法は services を参照してください。
Organizing services as your application grows
小さなアプリケーションなら services 内に小さな設定構造体やヘルパを置けます。規模が増えたら services を薄く保ち、services/services.go は Services、New、From に集中させ、連携先やドメインをそれぞれルート階層のパッケージに分けます。
bootstrap/
app.go # Registers Services: laravel.BuildServices(services.New)
services/
services.go # Holds Services, New, and From
billing/
client.go # Stripe client and types
middleware.go # billing.Subscribed middleware
search/
client.go # Search index client
geo/
geocoder.go # Geocoder interface
mapbox.go # Mapbox implementation
orders/
place.go # Domain functions such as orders.Place(ctx, ...)
handlers/
orders/ # HTTP handlers calling orders.Place(r, ...)
jobs/
charge_invoice.go # Queued jobs calling services.From(ctx) or orders
services/ の全ファイルは同じ package services です。十個の連携を同居させると、衝突回避のため StripeClient、StripeError、SearchClient、SearchError など全型やヘルパに接頭辞が要ります。分ければ billing.Client、search.Client、geo.Geocoder と明確になり、billing.Subscribed を billing.Client の隣に置くなど関連コードをまとめられます。
What belongs on Services
起動時設定、外部 SDK や接続プール、再利用する httpclient.Client、バッファ付きメトリクスライターなど共有状態を必要とする値は、services.Services に追加します。
状態を持たないドメインロジックに構造体や Services フィールドは不要です。空の OrderService を services.New に登録せず、orders などに最初の引数が ctx context.Context の関数を書きます。DB クエリ、イベント送信、services.From(ctx) の直接呼び出しができます。
// orders/place.go
package orders
import (
"context"
"go.laravel.com/model"
"app/models"
"app/services"
)
func Place(ctx context.Context, userID int64, totalCents int64) (models.Order, error) {
if err := services.From(ctx).Billing.Charge(ctx, totalCents); err != nil {
return models.Order{}, err
}
order := models.Order{
UserID: userID,
TotalCents: totalCents,
}
if err := model.Create(ctx, &order); err != nil {
return models.Order{}, err
}
return order, nil
}
ログインユーザーや現在のテナントなど単一リクエストの値も Services に置きません。r.User(ctx なら auth.User)で読むか、adding values of your own のようにコンテキストへ値を追加します。
Avoiding import cycles
Go は循環 import を禁止するため、パッケージの依存は一方向になります。
bootstrap -> handlers, jobs, commands -> orders -> services -> billing, search, geo
bootstrapはルート、ハンドラー、ジョブ、コマンド、servicesを import します。handlers、jobs、commands、listeners、ordersなどはservices.From(ctx)を呼ぶためservicesを import します。servicesはservices.Newで構築するbilling、search、geoなどを import します。
services が billing を import するため、billing パッケージから services を import してはいけません。billing に別のサービスが必要なら、depending on other services のように billing.NewClient の引数で受け取り、services.New から渡します。連携パッケージを services から独立させると、単体テストでも直接テストしやすくなります。
Shared state and concurrency
全 HTTP リクエスト、キュージョブ、リスナ、コマンドは services.New が作った同じ *services.Services を共有します。Services 内のサービスは複数の goroutine から同時に呼んでも安全でなければなりません。
ユーザーやロケールなどのリクエスト単位の値をサービスのフィールドへ保存してはいけません。引数で渡すか ctx から読みます。キャッシュマップやメトリクスバッファなど変更可能な状態は sync.Mutex やアトミックな値で保護し、go test -race ./... でデータ競合を早期に検出してください。
Testing with services
tests.New(t) を呼ぶ各テストは、その環境(.env.testing または .env、tests/tests.go と個別の laraveltest.Env による上書き)から新しい *services.Services を構築します。共有しないため、機能テストの外部依存を次の三通りで制御できます。
- テスト環境変数を渡します。
services.Newが読む特定の設定には、laraveltest.Env(map[string]string{"BILLING_CURRENCY": "eur"})のようにtests.Newへlaraveltest.Envを渡します。 services.From(client.Context())のフィールドを置き換えます。 送信前に、フェイクやhttptest.Serverを指すクライアントをServicesに代入します。例はservices.From(client.Context()).Geocoder = &fakeGeocoder{}です。終了時の復元は不要です。httpclienttestで HTTP リクエストをフェイク化します。 Laravel のhttpclientを使うサービスなら、交換せずhttpclienttest.New(t, client)で外部呼び出しをフェイク化できます。
サービス交換と HTTP レスポンスのフェイクの完全な例は replacing dependencies と testing を参照してください。