# daemon 套件

本頁列出 `core/daemon` 的公開 API：生命週期、資料方法、傳輸型別與錯誤。

## 生命週期

```go
func New(dir string, apiKey ...string) (*Daemon, error)
func (d *Daemon) Start() error
func (d *Daemon) Stop() error
func (d *Daemon) Close() error
func (d *Daemon) Mode() Mode
func (d *Daemon) Socket() string
func (d *Daemon) Store() *store.Store

type Mode int
const (
    ModeServer Mode = iota
    ModeClient
)
```

Client 模式下 `Store()` 為 `nil`。各模式的生命週期行為見 [Socket Daemon](/zh/socket-daemon-lifecycle)。

## 資料

```go
func (d *Daemon) Get(ctx context.Context, db int, key string) (*Record, error)
func (d *Daemon) Entries(ctx context.Context, db int, pattern string, option *ScanOption) ([]Record, error)
func (d *Daemon) Set(ctx context.Context, db int, key string, content any, expireAt *int64) error
func (d *Daemon) SetVector(ctx context.Context, db int, key string, content any, expireAt *int64) error
func (d *Daemon) Del(ctx context.Context, db int, keys ...string) (int, error)
func (d *Daemon) TTL(ctx context.Context, db int, key string) (int64, error)
func (d *Daemon) Expire(ctx context.Context, db int, ttl int64, keys ...string) (int, error)
func (d *Daemon) Keys(ctx context.Context, db int, pattern string, limit, page int) (*ListResult, error)
func (d *Daemon) VSearch(ctx context.Context, db int, text, pattern string, limit int) ([]string, error)
func (d *Daemon) HasEmbedder(ctx context.Context) (bool, error)
```

## 型別與錯誤

```go
type ScanOption struct {
    Contains string
    After    int64
    Limit    int
}

type Record struct {
    DB        int             `json:"db"`
    Key       string          `json:"key"`
    Type      string          `json:"type"`
    Content   json.RawMessage `json:"content,omitempty"`
    CreatedAt int64           `json:"created_at,omitempty"`
    UpdatedAt *int64          `json:"updated_at,omitempty"`
    ExpireAt  *int64          `json:"expire_at,omitempty"`
}

func (r *Record) Value() (string, error)

type ListResult struct {
    DB    int      `json:"db"`
    Page  int      `json:"page"`
    Limit int      `json:"limit"`
    Total int      `json:"total"`
    Keys  []string `json:"keys"`
}

var (
    ErrAlreadyRunning = errors.New("another daemon is serving this socket")
    ErrNotFound       = errors.New("not found")
    ErrBadRequest     = errors.New("bad request")
    ErrNoEmbedder     = store.ErrNoEmbedder
)
```

`Record` 與 `ListResult` 本身就是 wire 型別。對於 `json`/`int`/`float`/`bool` 且為合法 JSON 的值，`Content` 存放原始 JSON，其餘為 JSON 字串；`Value()` 在兩種情況下都回傳儲存的文字。

## 相關頁面

- [模式判定](/zh/socket-daemon)
- [資料方法](/zh/socket-daemon-methods)
- [錯誤](/zh/core-concepts-errors)
