关于 encore-infrastructure
面向 Encore.ts 应用的基础设施声明指南,介绍资源应在包级定义,并涵盖数据库、消息传递、存储、缓存、密钥和定时任务。
主要功能
- 01包级基础设施声明
- 02PostgreSQL 数据库与迁移
- 03Pub/Sub 主题与订阅
- 04对象存储与签名 URL
- 05Redis 缓存与过期策略
- 06密钥与定时任务
适用场景
- 01组织 Encore.ts 服务的基础设施定义
- 02添加数据库架构迁移
- 03发布和接收 Pub/Sub 事件
- 04存储文件并生成临时访问 URL
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ encoredev/ skills --skill encore-infrastructure安装后在 Claude Code 中输入/encore-infrastructure确认已加载。
详细介绍
Encore 基础设施声明
说明
Encore.ts 使用声明式基础设施:你在代码中定义资源,Encore 负责配置:
- 本地(
encore run)— Encore 在 Docker 中运行基础设施(Postgres、Redis 等) - 生产环境 — 通过 Encore Cloud 部署到你的 AWS/GCP,或使用生成的基础设施配置进行自托管
重要规则
所有基础设施都必须在包级别(文件顶部)声明,不能在函数内部声明。
数据库(PostgreSQL)
import { SQLDatabase } from "encore.dev/storage/sqldb";
// CORRECT: Package level
const db = new SQLDatabase("mydb", {
migrations: "./migrations",
});
// WRONG: Inside function
async function setup() {
const db = new SQLDatabase("mydb", { migrations: "./migrations" });
}
迁移
在 migrations/ 目录中创建迁移:
service/
├── encore.service.ts
├── api.ts
├── db.ts
└── migrations/
├── 001_create_users.up.sql
└── 002_add_email_index.up.sql
迁移命名格式:{number}_{description}.up.sql
Pub/Sub
主题
import { Topic } from "encore.dev/pubsub";
interface OrderCreatedEvent {
orderId: string;
userId: string;
total: number;
}
// Package level declaration
export const orderCreated = new Topic<OrderCreatedEvent>("order-created", {
deliveryGuarantee: "at-least-once",
});
发布
await orderCreated.publish({
orderId: "123",
userId: "user-456",
total: 99.99,
});
订阅
import { Subscription } from "encore.dev/pubsub";
const _ = new Subscription(orderCreated, "send-confirmation-email", {
handler: async (event) => {
await sendEmail(event.userId, event.orderId);
},
});
消息属性
对于应作为消息属性的字段(用于过滤/排序),请使用 Attribute<T>:
import { Topic, Attribute } from "encore.dev/pubsub";
interface CartEvent {
cartId: Attribute<string>; // Used for ordering
userId: string;
action: "add" | "remove";
productId: string;
}
// Ordered topic - events with same cartId delivered in order
export const cartEvents = new Topic<CartEvent>("cart-events", {
deliveryGuarantee: "at-least-once",
orderingAttribute: "cartId",
});
主题引用
在保持静态分析的同时,将主题访问权限传递给其他代码:
import { Publisher } from "encore.dev/pubsub";
// Create a reference with publish permission
const publisherRef = orderCreated.ref<Publisher>();
// Use the reference
async function notifyOrder(ref: typeof publisherRef, orderId: string) {
await ref.publish({ orderId, userId: "123", total: 99.99 });
}
定时任务
import { CronJob } from "encore.dev/cron";
import { api } from "encore.dev/api";
// The endpoint to call
export const cleanupExpiredSessions = api(
{ expose: false },
async (): Promise<void> => {
// Cleanup logic
}
);
// Package level cron declaration
const _ = new CronJob("cleanup-sessions", {
title: "Clean up expired sessions",
schedule: "0 * * * *", // Every hour
endpoint: cleanupExpiredSessions,
});
调度格式
| 格式 | 示例 | 说明 |
|---|---|---|
every | "1h"、"30m" | 简单间隔(必须能整除 24h) |
schedule | "0 9 * * 1" | Cron 表达式(每周一上午 9 点) |
对象存储
import { Bucket } from "encore.dev/storage/objects";
// Package level
export const uploads = new Bucket("user-uploads", {
versioned: false, // Set to true to keep multiple versions of objects
});
// Public bucket (files accessible via public URL)
export const publicAssets = new Bucket("public-assets", {
public: true,
versioned: false,
});
操作
// Upload
const attrs = await uploads.upload("path/to/file.jpg", buffer, {
contentType: "image/jpeg",
});
// Download
const data = await uploads.download("path/to/file.jpg");
// Check existence
const exists = await uploads.exists("path/to/file.jpg");
// Get attributes (size, content type, ETag)
const attrs = await uploads.attrs("path/to/file.jpg");
// Delete
await uploads.remove("path/to/file.jpg");
// List objects
for await (const entry of uploads.list({})) {
console.log(entry.key, entry.size);
}
// Public URL (only for public buckets)
const url = publicAssets.publicUrl("image.jpg");
签名 URL
生成用于上传/下载的临时 URL,无需公开你的存储桶:
// Signed upload URL (expires in 2 hours)
const uploadUrl = await uploads.signedUploadUrl("user-uploads/avatar.jpg", { ttl: 7200 });
// Signed download URL
const downloadUrl = await uploads.signedDownloadUrl("documents/report.pdf", { ttl: 7200 });
存储桶引用
将具有特定权限的存储桶访问权限传递给其他代码:
import { Uploader, Downloader } from "encore.dev/storage/objects";
// Create a reference with upload permission only
const uploaderRef = uploads.ref<Uploader>();
// Create a reference with download permission only
const downloaderRef = uploads.ref<Downloader>();
// Permission types: Downloader, Uploader, Lister, Attrser, Remover,
// SignedDownloader, SignedUploader, ReadWriter
缓存(Redis)
缓存集群
import { CacheCluster } from "encore.dev/storage/cache";
// Package level
const cluster = new CacheCluster("my-cache", {
evictionPolicy: "allkeys-lru",
});
引用在其他服务中定义的集群:
const cluster = CacheCluster.named("my-cache");
淘汰策略:"allkeys-lru"(默认)、"noeviction"、"allkeys-lfu"、"allkeys-random"、"volatile-lru"、"volatile-lfu"、"volatile-ttl"、"volatile-random"。
键空间类型
每个键空间都有键类型(用于生成 Redis 键)和值类型。
import {
StringKeyspace,
IntKeyspace,
FloatKeyspace,
StructKeyspace,
StringListKeyspace,
NumberListKeyspace,
StringSetKeyspace,
NumberSetKeyspace,
expireIn,
} from "encore.dev/storage/cache";
// String values
const tokens = new StringKeyspace<{ tokenId: string }>(cluster, {
keyPattern: "token/:tokenId",
defaultExpiry: expireIn(3600 * 1000), // 1 hour in ms
});
await tokens.set({ tokenId: "abc" }, "value");
const val = await tokens.get({ tokenId: "abc" }); // undefined on miss
await tokens.delete({ tokenId: "abc" });
// Integer values (supports increment/decrement)
const counters = new IntKeyspace<{ userId: string }>(cluster, {
keyPattern: "requests/:userId",
defaultExpiry: expireIn(10 * 1000),
});
const count = await counters.increment({ userId: "user123" }, 1);
await counters.decrement({ userId: "user123" }, 1);
// Float values
const scores = new FloatKeyspace<{ oddsId: string }>(cluster, {
keyPattern: "odds/:oddsId",
});
// Structured data (stored as JSON)
interface UserProfile {
name: string;
email: string;
}
const profiles = new StructKeyspace<{ userId: string }, UserProfile>(cluster, {
keyPattern: "profile/:userId",
defaultExpiry: expireIn(3600 * 1000),
});
await profiles.set({ userId: "123" }, { name: "Alice", email: "[email protected]" });
// Lists
const recentItems = new StringListKeyspace<{ userId: string }>(cluster, {
keyPattern: "recent/:userId",
});
await recentItems.pushRight({ userId: "user123" }, "item1", "item2");
const items = await recentItems.getRange({ userId: "user123" }, 0, -1);
// Sets
const tags = new StringSetKeyspace<{ articleId: string }>(cluster, {
keyPattern: "tags/:articleId",
});
await tags.add({ articleId: "post1" }, "typescript", "encore", "backend");
const hasTag = await tags.contains({ articleId: "post1" }, "typescript");
包含多个字段的键模式
interface ResourceKey {
userId: string;
resourcePath: string;
}
const resourceRequests = new IntKeyspace<ResourceKey>(cluster, {
keyPattern: "requests/:userId/:resourcePath",
defaultExpiry: expireIn(10 * 1000),
});
过期选项
import {
expireIn, // milliseconds
expireInSeconds,
expireInMinutes,
expireInHours,
expireDailyAt, // specific UTC time each day
neverExpire,
keepTTL, // keep existing TTL when updating
} from "encore.dev/storage/cache";
写入选项
// Override default expiry
await keyspace.set(key, value, { expiry: expireInMinutes(30) });
// Keep existing TTL
await keyspace.set(key, value, { expiry: keepTTL });
// Only set if key doesn't exist (throws CacheKeyExists otherwise)
await keyspace.setIfNotExists(key, value);
// Only set if key already exists (throws CacheMiss otherwise)
await keyspace.replace(key, value);
错误处理
import { CacheMiss, CacheKeyExists } from "encore.dev/storage/cache";
// get() returns undefined on miss (does not throw)
const value = await keyspace.get(key);
// replace() throws CacheMiss if key doesn't exist
// setIfNotExists() throws CacheKeyExists if key already exists
密钥
import { secret } from "encore.dev/config";
// Package level
const stripeKey = secret("StripeSecretKey");
// Usage (call as function)
const key = stripeKey();
通过 CLI 设置密钥:
encore secret set --type prod StripeSecretKey
指南
- 基础设施声明必须位于包级别
- 为资源使用描述性名称
- 迁移应按顺序编号
- 订阅处理程序必须具备幂等性(至少一次投递)
- 通过将密钥作为函数调用来访问密钥
- Cron 端点应设置为
expose: false(仅限内部使用)
评论
支持 Markdown