# 服务

桌面服务是随桌面启停、在后台运行的 JS 模块. 它把方法暴露成 `acde:<命名空间>` 模块, `api` 的每个键一个 (通常只有一个, 和服务同名), 给桌面和列出了这个服务的应用调用. 适合放全局状态、和外部进程打交道的逻辑 (比如 AI 助手、同步服务).

## 写一个服务

```ts
// services/clock.ts
import type { ServiceFactory } from '@dopame/acde-api'

const clock: ServiceFactory = (ctx) => {
  ctx.log('clock started')
  return {
    api: {
      clock: {
        now: () => Date.now(),
        async uptime() {
          return new Promise((resolve) => {
            ctx.spawn(['uptime'], { onLine: resolve })
          })
        },
      },
    },
    close() {
      ctx.log('clock stopped')
    },
  }
}
export default clock
```

在桌面配置里用服务的名字登记:

```jsonc
{ "type": "desktop", "services": { "clock": "services/clock.ts" } }
```

用到 shell 模块的服务写成一个对象, 里面还要列出这些模块; 见 [服务里的 shell 模块](#服务里的-shell-模块).

## 调用

桌面直接导入; 应用要在 `services` 里写**服务名**:

```jsonc
{ "services": ["clock"] }
```

```js
import { clock } from 'acde:clock'

console.log(await clock.now())
```

应用列出的服务是必需的, 不能设成可选: 服务没在跑的地方应用不启动 (`Notes needs "clock" (service not running)`). 单独对应用工程跑 `acdev dev` 也是这样, 因为它不跑桌面; 让应用跑在有这个服务的桌面里: `acdev dev ./my-app --desktop ./my-desktop`. 把服务写在 `capabilities` 下, `acdev check` 会报错 (`capability "clock" is not a system capability; list desktop services under services`).

`api` 的每个键是一个模块名 (命名空间), 值是方法的集合. 调用都是异步的 (服务在 `sync` 里列出的方法除外, 见 [服务接口](https://docs.dopame.ai/zh/reference/service.md)), 参数和返回值要能结构化克隆; 回调函数可以传过去.

名字:

- 应用列的是**服务名**, 拿到的是这个服务的所有命名空间: 服务 `clock` 里写了 `api: { clock: …, timer: … }` 时, 列出 `clock` 的应用 `acde:clock` 和 `acde:timer` 都能导入. 不要列命名空间: 列出 `timer` 的应用必需一个叫这个名字的服务, 不会启动 (`Notes needs "timer" (service not running)`).
- `acdev check` 和 `acdev build` 没法知道一个服务有哪些命名空间 (它们是工厂函数在运行时返回的). 导入服务自己的名字, 检查通过, 什么都不说. 在列出了服务的应用里, 导入任何别的不是系统模块的名字, 检查也通过, 但带一条提示, 退出码仍是 0:

  ```text
  note: src/main.js:1: app "notes": acde:timer resolves only if the service Notes lists ("clock") provides the "timer" namespace
  ```

  列出的服务都不提供它时, 这个导入在页面载入时抛 `AcdeError` (`code: 'forbidden'`, `status: 403`) (`'acde:timer' is not given to …`). 在没有列出任何服务的应用里, 同样的导入是错误: `error: src/main.js:1: app "notes": acde:timer is not a system module; if a desktop service provides it, list that service's name in the services of Notes`. 只有一个命名空间、而且它和服务同名的服务, 不会有这条提示.
- 服务不能用系统模块或系统能力的名字 (`fs`、`open`、`window`、`windows`、`apps`、`launch`、`desktop`、`session`、`capabilities`、`notifications` ……): `acdev check` 会报 `service "fs" has the name of a system module (acde:fs); system module names are reserved`. 用了这种名字的命名空间在服务启动时会被去掉, 运行时写一行日志, 结尾一字不差是 `[clock] acde.fs is taken; left out` (它把命名空间写成 `acde.fs`, 用的是点).

## ServiceContext

工厂函数收到的 `ctx`:

| 字段 | 是什么 |
| --- | --- |
| `name` | 服务名 |
| `package` | 桌面包的目录 |
| `state` | 这个服务自己的状态目录 (`$XDG_STATE_HOME/acde/<包名>/<服务>`, 包名是桌面包的 `name` 去掉 `@`、`/` 换成 `-`), 已建好 |
| `env` | 环境变量 |
| `log(line)` | 写日志, 前缀 `[<服务名>]` |
| `spawn(argv, options?)` | 起一个子进程 |
| `inspect` | `acde:inspect` 的接口 |
| `import(specifier)` | 桌面授给这个服务的 shell 模块, 见下文 |

`spawn` 的选项 `{cwd, env, onLine(line), onExit(code, signal)}`, 返回 `{pid, write(text), end(), kill(signal?)}`. 子进程在自己的进程组里, stderr 进日志; 服务关闭时先 SIGTERM, 3 秒后 SIGKILL.

服务只该用 `ServiceContext` 和标准 Web 接口. 重的活放进 `spawn` 起的进程.

## 服务里的 shell 模块

服务不能 `import` `acde:` 模块; 构建会拒绝:

```text
acdev: service clock: services/clock.ts imports acde:windows: a service gets shell modules from ctx.import('acde:<name>'), listed in its modules in acde.config.jsonc ("services": { "clock": { "module": "<file>", "modules": ["<name>"] } })
```

它向自己的上下文要桌面授给它的 shell 模块. 授权写在桌面配置里: 把服务写成一个对象, 里面是它的模块文件和它可以用的 shell 模块.

```jsonc
{
  "type": "desktop",
  "services": {
    "clock": { "module": "services/clock.ts", "modules": ["windows"] }
  }
}
```

```ts
// services/clock.ts
import type { ServiceFactory } from '@dopame/acde-api'

const clock: ServiceFactory = async (ctx) => {
  const { windows } = await ctx.import('acde:windows')
  windows.on('open', (event) => ctx.log(`window ${event.window} opened`))
  return {
    api: {
      clock: {
        now: () => Date.now(),
        windows: () => windows.list(),
      },
    },
  }
}
export default clock
```

开着一个应用窗口时, `clock.windows()` 回 `[{ "id": 1048576, "appId": "tools", "title": "Tools", "web": true, "state": "normal" }]`.

`modules` 里写 shell 模块的名字. 写了别的, `acdev check` 和 `acdev build` 都报错:

```text
error: services in acde.config.jsonc: service "clock": modules lists shell modules (windows, packages, session, desktops, inspect, desktop, setDefault, permissions)
```

`acdev build` 把这项授权写进包清单里桌面那一项, 写成 `{ "name": "clock", "modules": ["windows"] }`; 手写的包自己写这一项 (见 [包清单](https://docs.dopame.ai/zh/reference/manifest.md#desktopmanifest)).

`ctx.import()` 给出的东西:

| 模块 | 在服务里 |
| --- | --- |
| `acde:windows` | 整个模块, 和桌面页拿到的一样: `list()`、事件、`requestState()` 等等 |
| `acde:packages` | 整个模块, 包括它的 `changed` 事件 |
| `acde:session`、`acde:desktops`、`acde:inspect`、`acde:setDefault` | 整个模块 |
| `acde:desktop` | 只有 `apps()`: 服务没有可以拿来钉面板的页面 |
| `acde:permissions` | 不给: `acde:permissions is not available to services here` |

`ctx.inspect` 不需要授权. 对没有授给这个服务的 shell 模块 (`acde:session is a shell module: list it in the modules of service "clock" in the desktop manifest`), 以及对任何不是 shell 模块的东西 (`import(acde:fs): a service imports shell modules (acde:windows, acde:packages, …)`), `ctx.import()` 都以 `TypeError` reject. 工厂函数不接住这个 reject 的话, 它的服务不启动; 运行时在日志里写 `[clock] not started: TypeError: …`.
