# コードからエンドポイントのスケーリング、リリース、ログを扱う

このページでは、コンソールの **スケーリングと支出** カード、**リリース** カード、エンドポイントのワーカーログで行う操作をスクリプトから行います。例ではエンドポイント ID `ep_ID` を使います。読み取りは `read` キーで行えますが、変更にはスコープ `full` のキーが必要です。1 つのエンドポイントに紐づいたキーはそのエンドポイントを呼び出すことしかできないため、ここにある操作はできません。サーバーレスエンドポイントはお使いのアカウントでまだ有効になっていない場合があります。各設定の意味は [サーバーレスエンドポイント](/docs/endpoints) で説明しています。

## スケーリングプリセットを適用する

3 つのプリセットを、今日の価格での 1 時間あたりの費用（トラフィックなしの `idleHourlyMicros` と全負荷時の `maxHourlyMicros`）とともに一覧表示します。`current` はエンドポイントがすでに一致しているプリセットを示します。その後 1 つを適用します。プリセットは他の変更と同じように保存されるのでリリースにもなり、ローリング更新を始めることはありません。

```bash
curl "https://apidly.com/api/v1/endpoints/ep_ID/presets" \
  -H "Authorization: Bearer $APIDLY_API_KEY"

curl -X POST "https://apidly.com/api/v1/endpoints/ep_ID/presets" \
  -H "Authorization: Bearer $APIDLY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"preset":"scale_to_zero"}'

apidly endpoints presets ep_ID
apidly endpoints preset ep_ID scale_to_zero
```

```js
import { Apidly } from "@apidly/sdk";

const apidly = new Apidly({ apiKey: process.env.APIDLY_API_KEY });
const { presets } = await apidly.endpoints.presets("ep_ID");
for (const p of presets) {
  console.log(p.name, p.idleHourlyMicros, p.maxHourlyMicros, p.current);
}
await apidly.endpoints.applyPreset("ep_ID", "scale_to_zero");
```

```python
import os
from apidly import Client

client = Client(api_key=os.environ["APIDLY_API_KEY"])
for p in client.endpoints.presets("ep_ID")["presets"]:
    print(p["name"], p["idleHourlyMicros"], p["maxHourlyMicros"], p["current"])
client.endpoints.apply_preset("ep_ID", "scale_to_zero")
```

## 月間利用上限を設定する

上限は暦月（UTC）あたりの米ドルで指定します。上限に達すると、エンドポイントは自動で一時停止し、ワーカーを解放してオーナーにメールを送ります。`resumeAtNewMonth` を指定すると、翌月が始まったときに自動で再開します。上限を外すには `null`（CLI では `none`）を送ります。

```bash
curl -X PATCH "https://apidly.com/api/v1/endpoints/ep_ID" \
  -H "Authorization: Bearer $APIDLY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"monthlySpendCapUsd":50,"resumeAtNewMonth":true}'

apidly endpoints update ep_ID --monthly-cap 50 --resume-at-new-month on
apidly endpoints update ep_ID --monthly-cap none
```

```js
import { Apidly } from "@apidly/sdk";

const apidly = new Apidly({ apiKey: process.env.APIDLY_API_KEY });
await apidly.endpoints.update("ep_ID", {
  monthlySpendCapUsd: 50,
  resumeAtNewMonth: true,
});
const { endpoint } = await apidly.endpoints.get("ep_ID");
console.log(endpoint.spendCap);
```

```python
import os
from apidly import Client

client = Client(api_key=os.environ["APIDLY_API_KEY"])
client.endpoints.update("ep_ID", {"monthlySpendCapUsd": 50, "resumeAtNewMonth": True})
print(client.endpoints.get("ep_ID")["endpoint"]["spendCap"])
```

## リリースを一覧表示して復元する

保存された変更はそれぞれ番号付きのリリースになり、新しい順に並びます。環境変数は名前だけが表示されます。復元すると、そのリリースの設定が新しいリリースとして戻ります。ワーカーの設定が変わる場合はローリング更新が始まります。CLI は `--yes` を付けない限り、復元前に確認します。

```bash
curl "https://apidly.com/api/v1/endpoints/ep_ID/releases?limit=20" \
  -H "Authorization: Bearer $APIDLY_API_KEY"

curl -X POST "https://apidly.com/api/v1/endpoints/ep_ID/releases/VERSION/restore" \
  -H "Authorization: Bearer $APIDLY_API_KEY"

apidly endpoints releases ep_ID --limit 20
apidly endpoints restore ep_ID 3
```

```js
import { Apidly } from "@apidly/sdk";

const apidly = new Apidly({ apiKey: process.env.APIDLY_API_KEY });
const { releases } = await apidly.endpoints.releases("ep_ID", { limit: 20 });
console.log(releases.map((r) => r.version));
const { changed } = await apidly.endpoints.restoreRelease("ep_ID", 3);
console.log(changed);
```

```python
import os
from apidly import Client

client = Client(api_key=os.environ["APIDLY_API_KEY"])
for r in client.endpoints.releases("ep_ID", limit=20)["releases"]:
    print(r["version"], r["changes"])
print(client.endpoints.restore_release("ep_ID", 3)["changed"])
```

## ワーカーログを読む

エンドポイントのログは各ワーカーの最新の行で、1 回の呼び出しで最大 12 ワーカー分、`worker` を指定すれば 1 つのワーカー分です。ジョブのログは、そのジョブを実行したワーカーのログです。`available: false` で `reason` が `not_dispatched` または `worker_gone` のときは、読めるログがありません。`tail` で行数を指定します（最大 500）。秘密の値はどのログでも隠されます。

```bash
curl "https://apidly.com/api/v1/endpoints/ep_ID/logs?tail=100" \
  -H "Authorization: Bearer $APIDLY_API_KEY"

curl "https://apidly.com/api/v1/endpoints/ep_ID/logs?worker=ins_ID&tail=200" \
  -H "Authorization: Bearer $APIDLY_API_KEY"

curl "https://apidly.com/api/v1/endpoints/ep_ID/jobs/job_ID/logs?tail=200" \
  -H "Authorization: Bearer $APIDLY_API_KEY"

apidly endpoints logs ep_ID --tail 100
apidly endpoints logs ep_ID --worker ins_ID
apidly endpoints job-logs ep_ID job_ID
```

```js
import { Apidly } from "@apidly/sdk";

const apidly = new Apidly({ apiKey: process.env.APIDLY_API_KEY });
const { workers } = await apidly.endpoints.logs("ep_ID", { tail: 100 });
for (const w of workers) {
  console.log(`== ${w.serverId} (${w.status})\n${w.logs}`);
}
const { job } = await apidly.endpoints.jobLogs("ep_ID", "job_ID", { tail: 200 });
console.log(job.available ? job.logs : job.reason);
```

```python
import os
from apidly import Client

client = Client(api_key=os.environ["APIDLY_API_KEY"])
for w in client.endpoints.logs("ep_ID", tail=100, worker="ins_ID")["workers"]:
    print(w["serverId"], w["logs"])
job = client.endpoints.job_logs("ep_ID", "job_ID", tail=200)["job"]
print(job["logs"] if job["available"] else job["reason"])
```
