@appweaver/skill 0.0.0-stage → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +29 -2
- package/index.d.ts +39 -0
- package/index.js +105 -0
- package/package.json +41 -3
- package/skill/GUIDELINES.md +383 -0
- package/skill/SKILL.md +121 -0
- package/skill/references/ai.md +231 -0
- package/skill/references/audit.md +220 -0
- package/skill/references/cache.md +233 -0
- package/skill/references/cli.md +760 -0
- package/skill/references/client.md +982 -0
- package/skill/references/configuration.md +1224 -0
- package/skill/references/database.md +349 -0
- package/skill/references/dependency-injection.md +301 -0
- package/skill/references/errors.md +486 -0
- package/skill/references/events.md +203 -0
- package/skill/references/logging.md +157 -0
- package/skill/references/mailer.md +393 -0
- package/skill/references/mcp.md +245 -0
- package/skill/references/modules.md +509 -0
- package/skill/references/patterns.md +1217 -0
- package/skill/references/payments.md +795 -0
- package/skill/references/queue.md +281 -0
- package/skill/references/realtime.md +572 -0
- package/skill/references/resources.md +2238 -0
- package/skill/references/scheduler.md +228 -0
- package/skill/references/security.md +1185 -0
- package/skill/references/sms.md +143 -0
- package/skill/references/spatial.md +197 -0
- package/skill/references/storage.md +500 -0
- package/skill/references/telemetry.md +207 -0
- package/skill/references/templates.md +488 -0
- package/skill/references/timeseries.md +312 -0
- package/skill/references/workflow.md +224 -0
|
@@ -0,0 +1,509 @@
|
|
|
1
|
+
# Modules
|
|
2
|
+
|
|
3
|
+
Every part of an Appweaver application is a module: a manifest declared with `defineModule` of `@appweaver/common`,
|
|
4
|
+
naming the contracts it declares, the providers (drivers) implementing them, its services, models, routes and startup
|
|
5
|
+
code. The framework uses the same format for itself, so an application or an npm package can do everything a
|
|
6
|
+
first-party module does.
|
|
7
|
+
|
|
8
|
+
## First-party modules
|
|
9
|
+
|
|
10
|
+
| Module | Enabled | Brings |
|
|
11
|
+
| -------------------------- | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
12
|
+
| `@appweaver/core` | Always | The contracts and the in-process drivers: `memory`, `node` events, `memory` pub/sub, `local` storage, `memory` queue, `json` mailer, `json` SMS sender, `memory` time series |
|
|
13
|
+
| `@appweaver/data` | Installed | The `prisma` database, the resources, `FileService`, the `database` security store, the `database` and `timescale` time series |
|
|
14
|
+
| `@appweaver/web` | Installed (requires `data`) | The Fastify server (`HttpServer`), authentication, account, 2FA (`TwoFactorService`) and OAuth2 services |
|
|
15
|
+
| `@appweaver/redis` | Installed | The `redis` memory, also the store of the cache and the rate limit, and the `redis` pub/sub |
|
|
16
|
+
| `@appweaver/bullmq` | Installed (requires `redis`) | The `bullmq` queue |
|
|
17
|
+
| `@appweaver/cron` | Installed | The `cron` scheduler |
|
|
18
|
+
| `@appweaver/nodemailer` | Installed | The `smtp` mailer |
|
|
19
|
+
| `@appweaver/twilio` | Installed | The `twilio` SMS sender (`SmsSender`), with the REST API of Twilio and no SDK |
|
|
20
|
+
| `@appweaver/realtime` | Installed (requires `web`) | The realtime connections (`RealtimeGateway`) over WebSocket and SSE: channels, resource events and actions, see [realtime](./realtime.md) |
|
|
21
|
+
| `@appweaver/ai` | Installed | `AiService` calling the AI models of the endpoints of the `ai` config, the tools, the built-in `mock` driver, see [ai](./ai.md) |
|
|
22
|
+
| `@appweaver/openai` | Installed (requires `ai`) | The `openai` AI driver (`AiDriver`), for OpenAI and every OpenAI-compatible server (Ollama, OpenRouter, vLLM, ...), with the `openai` SDK |
|
|
23
|
+
| `@appweaver/mcp` | Installed (requires `web`) | The MCP server of the AI agents: the resource actions of the `mcp` route config and `createMcpTool`, see [mcp](./mcp.md) |
|
|
24
|
+
| `@appweaver/opentelemetry` | Installed | The OpenTelemetry SDK (`TelemetryService`) exporting the traces, metrics and logs over OTLP, see [telemetry](./telemetry.md) |
|
|
25
|
+
| `@appweaver/payments` | Installed (requires `data`) | `PaymentsService` and `SubscriptionsService`: one-time and recurring payments on the gateways of the `payments` config, several at once, their webhooks, events and emails, the built-in `fake` gateway, see [payments](./payments.md) |
|
|
26
|
+
| `@appweaver/stripe` | Installed (requires `payments`) | The `stripe` payment gateway driver (`PaymentGateway`), with the official `stripe` SDK |
|
|
27
|
+
| `@appweaver/handlebars` | Installed | The `handlebars` template engine |
|
|
28
|
+
| `@appweaver/sharp` | Installed | The `sharp` image processor |
|
|
29
|
+
|
|
30
|
+
Every first-party module but core is a package of its own, enabled like any [package module](#package-modules): by
|
|
31
|
+
being a dependency of the application's `package.json`. A driver package carries the library it wraps as a dependency,
|
|
32
|
+
so `npm install @appweaver/redis` moves the memory, the cache and the rate limit to Redis without any config, and
|
|
33
|
+
installing `ioredis` alone enables nothing. The scaffold modules of `weaver module add` (`data`, `web`, `redis`,
|
|
34
|
+
`queue`, `mailer`, `sms`, `payments`,
|
|
35
|
+
...) install these packages along with their config and files.
|
|
36
|
+
|
|
37
|
+
## Discovery
|
|
38
|
+
|
|
39
|
+
The enabled modules come from:
|
|
40
|
+
|
|
41
|
+
| Source | Found |
|
|
42
|
+
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
43
|
+
| Core | `@appweaver/core`, always |
|
|
44
|
+
| Packages | The `dependencies` and `optionalDependencies` of the project's `package.json` whose own `package.json` has `"appweaver": { "module": "./dist/module.js" }`, and the modules they `require` |
|
|
45
|
+
| Local modules | Every manifest matching `APP_MODULES_PATTERN` (`app.modulesPattern`, default `<srcPath>/modules/*/module.ts`), without any config |
|
|
46
|
+
| Explicit paths | `APP_MODULES` (`app.modules`), manifest paths relative to the project root, i.e. `../shared/dist/module.js` |
|
|
47
|
+
|
|
48
|
+
- `APP_MODULES_DISABLED` (`app.modulesDisabled`) leaves modules out by name, i.e. `["@appweaver/web"]` for a worker or
|
|
49
|
+
a scheduled job runner without a server, which can also leave the package out of its dependencies.
|
|
50
|
+
- The local pattern resolves against the build output on Node (`./dist/src/modules/*/module.js`) and against the
|
|
51
|
+
sources with Bun and in `weaver generate`. An empty pattern turns the scan off.
|
|
52
|
+
- Every module comes after the modules it `requires`, otherwise in the order above.
|
|
53
|
+
- The startup fails with a `ModuleError` for a file not exporting a manifest (`MODULE_INVALID`), two modules of one
|
|
54
|
+
name (`MODULE_DUPLICATE`), a required module that is not enabled (`MODULE_MISSING`), or a `framework` range the
|
|
55
|
+
version of `@appweaver/core` does not satisfy (`MODULE_INCOMPATIBLE`).
|
|
56
|
+
|
|
57
|
+
`isModuleEnabled(modules, name)` and `loadModuleParts(modules, part)` of `@appweaver/core` take the result of
|
|
58
|
+
`discoverModules`, for tooling that loads the modules itself.
|
|
59
|
+
|
|
60
|
+
## Load order
|
|
61
|
+
|
|
62
|
+
`createApp()` loads the enabled modules in this order:
|
|
63
|
+
|
|
64
|
+
1. The providers selected for every declared contract, then the `services` of every module whose `requires` are all
|
|
65
|
+
provided.
|
|
66
|
+
2. The `setup` of every module, in the module order. `@appweaver/data` loads the resources of the application, then
|
|
67
|
+
the `resources` of the modules. `@appweaver/web` loads the resource routes of the application
|
|
68
|
+
(`RESOURCE_ROUTES_PATTERN`), then the `web` part of every module.
|
|
69
|
+
3. The `main` part of every module.
|
|
70
|
+
4. The application files (`APP_SCAN_FILES_PATTERN`).
|
|
71
|
+
|
|
72
|
+
The server of `@appweaver/web` is created by its `HttpServer` service once everything is loaded, and listens when the
|
|
73
|
+
application starts. The resources and the routes of the application and the modules are all loaded before the `main`
|
|
74
|
+
parts and the application files.
|
|
75
|
+
|
|
76
|
+
A provider or a service of a module is defined with the `default` mode of `define`: it keeps a definition the
|
|
77
|
+
application made before `createApp`, and a later `define` of the application replaces it in the `ignore` (default),
|
|
78
|
+
`override` and `fail` modes (`define(MyService, ModuleService)` in an application file), while `append` adds a
|
|
79
|
+
definition beside it, which `inject` does not return.
|
|
80
|
+
|
|
81
|
+
## Provider selection
|
|
82
|
+
|
|
83
|
+
Each contract a module declares has a config key (`storage.provider`, ...), which takes `auto` (the default), `none`, a
|
|
84
|
+
provider name or a module path (see [providers](./configuration.md#providers)):
|
|
85
|
+
|
|
86
|
+
- `auto` selects the providers whose `auto` is `true` (the default), or when there is none, the one whose `auto` is
|
|
87
|
+
`'fallback'` (the in-process drivers of core). A provider with `auto: false` is selected only by its name (the `json`
|
|
88
|
+
mailer, the `memory` security store). Two candidates fail with `MODULE_PROVIDER_AMBIGUOUS`.
|
|
89
|
+
- `none` defines nothing for the contract, and no service requiring it.
|
|
90
|
+
- A name selects the provider of that name of any enabled module, `MODULE_PROVIDER_MISSING` when none has it.
|
|
91
|
+
- A value with `.`, `/` or `@` is a module path, loaded with `loadProvider` (`@/infra/my-storage`).
|
|
92
|
+
|
|
93
|
+
The selected provider is defined under its contract, so `inject(Storage)` returns it. `selectedProvider(Storage)`
|
|
94
|
+
returns its name.
|
|
95
|
+
|
|
96
|
+
## Manifest
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
// module.ts
|
|
100
|
+
import { defineModule } from '@appweaver/common';
|
|
101
|
+
|
|
102
|
+
export default defineModule({ name: 'appweaver-newsletter' /* ... */ });
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
| Field | Type | Purpose |
|
|
106
|
+
| ----------- | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
107
|
+
| `name` | `string` | The name, the package name for a package module |
|
|
108
|
+
| `framework` | `string` | The supported Appweaver version range, i.e. `^2.0.0`, checked at startup |
|
|
109
|
+
| `requires` | `string[]` | The modules that must be enabled with it (`@appweaver/bullmq` requires `@appweaver/redis`) |
|
|
110
|
+
| `config` | `object[]` | Its config sections, defined with `defineConfig`, validated at start and listed in `appweaver.schema.json` (a driver's validated only when selected) |
|
|
111
|
+
| `loggers` | `string[]` | The names of the loggers it creates with `createLogger`, suggested as the keys of `log.levels` in `appweaver.schema.json` |
|
|
112
|
+
| `contracts` | `{ contract, provider: () => string }[]` | The contracts it declares, with the function reading the provider key, i.e. `() => searchConfig.PROVIDER` |
|
|
113
|
+
| `providers` | `{ contract, name, load, auto? }[]` | Its contract implementations. `load` imports the class lazily (`() => import('./gcs-storage')`), `auto` is `true`, `'fallback'` or `false` |
|
|
114
|
+
| `services` | `{ load, requires? }[]` | Classes defined at startup by their class name, with their lifecycle hooks and health checks; `requires` lists the contracts that must be provided |
|
|
115
|
+
| `setup` | `(context) => unknown` | Run after the providers and services of every module, before the `main` parts and the application files (see below) |
|
|
116
|
+
| `resources` | `() => import(...)` | A file exporting its models, resource services and policies, loaded by the `setup` of `@appweaver/data`, and by `weaver generate` |
|
|
117
|
+
| `main` | `() => import(...)` | Code run at startup: scheduled jobs, queue workers, event listeners |
|
|
118
|
+
| `web` | `() => import(...)` | Its resource routes, custom routes (`registerRoute`) and plugins (`registerPlugin`), loaded by the `setup` of `@appweaver/web` |
|
|
119
|
+
| `seeders` | `string` | The absolute path of its seeders directory, run by `weaver seed` before the seeders of the application |
|
|
120
|
+
| `tasks` | `string` | The absolute path of its tasks directory (`createTask` files), listed and run by `weaver run`, overridden by a task of the application |
|
|
121
|
+
| `locales` | `string` | The absolute path of its translations, overridden by the ones of the application |
|
|
122
|
+
| `templates` | `string` | The absolute path of its templates, overridden by the ones of the application |
|
|
123
|
+
|
|
124
|
+
Every part is imported lazily and only when used: a driver only when it is selected, `web` only with a server. Keep
|
|
125
|
+
the routes in `web`, not in `resources`, so the module also works without a server.
|
|
126
|
+
|
|
127
|
+
`setup` receives `{ modules, scanPath, params }`: the enabled manifests in their load order, the source directory of
|
|
128
|
+
the application (`./dist/src`) and the parameters given to `createApp` (`resourcePaths`, `autoLoadResources`, ...).
|
|
129
|
+
It is how a module loads what it brings from the application or the other modules, the way `@appweaver/data` loads the
|
|
130
|
+
resources and `@appweaver/web` the routes:
|
|
131
|
+
|
|
132
|
+
```ts
|
|
133
|
+
export default defineModule({
|
|
134
|
+
name: '@acme/appweaver-jobs',
|
|
135
|
+
setup: async ({ modules, scanPath }) =>
|
|
136
|
+
(await import('./load-jobs')).loadJobs(modules, scanPath)
|
|
137
|
+
});
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
`isModule(value)` checks a manifest, and `PROVIDER_AUTO` / `PROVIDER_NONE` hold `'auto'` and `'none'`. A manifest is
|
|
141
|
+
marked with `Symbol.for('appweaver.module')`, so it is recognized whichever copy of `@appweaver/common` defined it.
|
|
142
|
+
|
|
143
|
+
The directories of `seeders`, `tasks`, `locales` and `templates` are absolute, i.e. `path.join(__dirname, 'locales')` in
|
|
144
|
+
`module.ts`, so they point to the build output of a package or a local module:
|
|
145
|
+
|
|
146
|
+
- `weaver seed` (`createSeeder`) runs the seeders of the modules first, in their load order, each recorded under the
|
|
147
|
+
name of its module (`appweaver-newsletter/1-lists`), then the seeders of the application. A module declaring
|
|
148
|
+
`seeders` keeps the `Seeder` model in `weaver generate`.
|
|
149
|
+
- The `LocaleService` reads the translation files of the modules, then of `LOCALE_PATH`, a key of the application
|
|
150
|
+
replacing the same key of a module.
|
|
151
|
+
- The Handlebars engine reads the templates of the modules, then of `TEMPLATE_PATH`, a template of the application
|
|
152
|
+
replacing the template of a module with the same name and locale, so an application restyles the email of a module
|
|
153
|
+
by adding the file of the same name.
|
|
154
|
+
|
|
155
|
+
`moduleDirectories('locales' | 'templates' | 'seeders')` of `@appweaver/core` returns the directories of the enabled
|
|
156
|
+
modules, for a driver of another engine. A config section is registered when its file is imported (the manifest
|
|
157
|
+
imports it to list it), and the sections of `config` are parsed when the application starts, so an invalid value fails
|
|
158
|
+
the start instead of the first read of its key. A module ships its commands as tasks (`createTask`) in its `tasks`
|
|
159
|
+
directory, run by `weaver run`. Prefix their names with the module (`billing:sync`), so they never take the name of an
|
|
160
|
+
application task, which would replace them.
|
|
161
|
+
|
|
162
|
+
A module model relates to the application only through a reference resolved when the app loads, i.e. the auth model.
|
|
163
|
+
|
|
164
|
+
## Local modules
|
|
165
|
+
|
|
166
|
+
A local module lives in `src/modules/<name>/`, compiled with the application and enabled by `APP_MODULES_PATTERN`
|
|
167
|
+
without any config. `weaver module new <name>` creates its files:
|
|
168
|
+
|
|
169
|
+
```sh
|
|
170
|
+
weaver module new audit-log # src/modules/audit-log/{module.ts,config.ts,main.ts}
|
|
171
|
+
weaver module new audit-log --dry-run # print the files without writing them
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
The name is kebab-case, and the config section the camelCase of it (`auditLog`, read from `config.auditLog` and the
|
|
175
|
+
`AUDIT_LOG_*` variables), with an `ENABLED` key. `module.ts` names the module, its config, its `main` and its
|
|
176
|
+
`loggers` (`['auditLog']`), with commented `providers` and `services` entries to fill in; `main.ts` is its startup
|
|
177
|
+
code, logging with `createLogger('auditLog')` (see [logging](./logging.md)). The command refuses to
|
|
178
|
+
overwrite an existing module. A driver nests its section under its contract, so rename the section of a new driver
|
|
179
|
+
module (`defineConfig('storage.gcs', ...)`), as in the example below.
|
|
180
|
+
|
|
181
|
+
## Example: a Google Cloud Storage driver
|
|
182
|
+
|
|
183
|
+
The files of a local driver module:
|
|
184
|
+
|
|
185
|
+
```
|
|
186
|
+
src/modules/gcs/
|
|
187
|
+
module.ts the manifest
|
|
188
|
+
config.ts its config section
|
|
189
|
+
gcs-storage.ts class GcsStorage extends Storage
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
```ts
|
|
193
|
+
// src/modules/gcs/config.ts
|
|
194
|
+
import { Type } from 'typebox';
|
|
195
|
+
import { defineConfig, Duration } from '@appweaver/common';
|
|
196
|
+
|
|
197
|
+
export const gcsConfig = defineConfig('storage.gcs', {
|
|
198
|
+
/** The bucket the files are stored in. */
|
|
199
|
+
BUCKET: Type.String(),
|
|
200
|
+
/** The validity of a signed URL, milliseconds or a duration string, unless the caller gives one. Default: `'15m'`. */
|
|
201
|
+
SIGNED_URL_TTL: Duration({ default: '15m' })
|
|
202
|
+
});
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
```ts
|
|
206
|
+
// src/modules/gcs/gcs-storage.ts
|
|
207
|
+
import { Readable } from 'node:stream';
|
|
208
|
+
import { pipeline } from 'node:stream/promises';
|
|
209
|
+
import { Storage as GcsClient } from '@google-cloud/storage';
|
|
210
|
+
import {
|
|
211
|
+
ContentStream,
|
|
212
|
+
FileUrlOptions,
|
|
213
|
+
HealthCheckResult,
|
|
214
|
+
Storage,
|
|
215
|
+
StoreOptions
|
|
216
|
+
} from '@appweaver/common';
|
|
217
|
+
import { gcsConfig } from './config';
|
|
218
|
+
|
|
219
|
+
export class GcsStorage extends Storage {
|
|
220
|
+
private readonly _bucket = new GcsClient().bucket(gcsConfig.BUCKET);
|
|
221
|
+
|
|
222
|
+
async onInit(): Promise<void> {}
|
|
223
|
+
|
|
224
|
+
async store(
|
|
225
|
+
fileName: string,
|
|
226
|
+
data: Readable,
|
|
227
|
+
options?: StoreOptions
|
|
228
|
+
): Promise<string | null> {
|
|
229
|
+
await pipeline(
|
|
230
|
+
data,
|
|
231
|
+
this._bucket
|
|
232
|
+
.file(fileName)
|
|
233
|
+
.createWriteStream({ contentType: options?.contentType })
|
|
234
|
+
);
|
|
235
|
+
return fileName;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async stream(
|
|
239
|
+
fileName: string,
|
|
240
|
+
start: number,
|
|
241
|
+
end?: number
|
|
242
|
+
): Promise<ContentStream | null> {
|
|
243
|
+
const file = this._bucket.file(fileName);
|
|
244
|
+
const [exists] = await file.exists();
|
|
245
|
+
if (!exists) return null;
|
|
246
|
+
const [metadata] = await file.getMetadata();
|
|
247
|
+
return {
|
|
248
|
+
stream: file.createReadStream({ start, end }),
|
|
249
|
+
size: Number(metadata.size)
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
async delete(fileName: string): Promise<boolean> {
|
|
254
|
+
await this._bucket.file(fileName).delete({ ignoreNotFound: true });
|
|
255
|
+
return true;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
async exists(fileName: string): Promise<boolean> {
|
|
259
|
+
const [exists] = await this._bucket.file(fileName).exists();
|
|
260
|
+
return exists;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// The files route redirects to the signed URL instead of streaming the file
|
|
264
|
+
async url(
|
|
265
|
+
fileName: string,
|
|
266
|
+
options?: FileUrlOptions
|
|
267
|
+
): Promise<string | null> {
|
|
268
|
+
const ttl = options?.expiresIn ?? gcsConfig.SIGNED_URL_TTL;
|
|
269
|
+
const [url] = await this._bucket
|
|
270
|
+
.file(fileName)
|
|
271
|
+
.getSignedUrl({ action: 'read', expires: Date.now() + ttl });
|
|
272
|
+
return url;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
async checkHealth(): Promise<HealthCheckResult> {
|
|
276
|
+
const [exists] = await this._bucket.exists();
|
|
277
|
+
return { success: exists };
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
```ts
|
|
283
|
+
// src/modules/gcs/module.ts
|
|
284
|
+
import { defineModule, Storage } from '@appweaver/common';
|
|
285
|
+
import { gcsConfig } from './config';
|
|
286
|
+
|
|
287
|
+
export default defineModule({
|
|
288
|
+
name: 'gcs',
|
|
289
|
+
config: [gcsConfig],
|
|
290
|
+
providers: [
|
|
291
|
+
{ contract: Storage, name: 'gcs', load: () => import('./gcs-storage') }
|
|
292
|
+
]
|
|
293
|
+
});
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
With the module enabled, `STORAGE_PROVIDER=auto` selects `gcs` over the `local` fallback. Its config is read under the
|
|
297
|
+
section of its contract, and only when the driver is selected, so the tests can keep the `local` storage:
|
|
298
|
+
|
|
299
|
+
```json
|
|
300
|
+
{
|
|
301
|
+
"config": {
|
|
302
|
+
"storage": {
|
|
303
|
+
"gcs": {
|
|
304
|
+
"bucket": "app-files"
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
},
|
|
308
|
+
"environments": {
|
|
309
|
+
"test": {
|
|
310
|
+
"storage": {
|
|
311
|
+
"provider": "local"
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
The same values as environment variables: `STORAGE_PROVIDER=gcs`, `STORAGE_GCS_BUCKET=app-files`.
|
|
319
|
+
|
|
320
|
+
## Maintenance jobs
|
|
321
|
+
|
|
322
|
+
The jobs keeping the data in shape run on their schedule in every instance, never two runs of a job at once, registered
|
|
323
|
+
with `defineMaintenanceJob` of `@appweaver/core` by the framework or by a module or the application:
|
|
324
|
+
|
|
325
|
+
| Job | Module | Deletes | Schedule |
|
|
326
|
+
| ------------------------ | -------- | ------------------------------------------------------------------------------------------------ | -------- |
|
|
327
|
+
| `auditRetention` | data | The audit log entries older than the retention of their category (`audit.retention`) | `1h` |
|
|
328
|
+
| `timeseriesRetention` | data | The time series points older than the retention of their model (the `database` provider) | `1h` |
|
|
329
|
+
| `fileVersionsPrune` | data | The file versions older than the `maxAge` of their field | `1h` |
|
|
330
|
+
| `oneTimeTokens` | data | The expired one-time tokens of the `database` security store | `1h` |
|
|
331
|
+
| `softDeletePurge` | data | The records soft deleted longer ago than the `softDelete.purgeAfter` of their model | `1d` |
|
|
332
|
+
| `paymentEventsRetention` | payments | The processed webhook events and the delivered events of the payments older than their retention | `1h` |
|
|
333
|
+
|
|
334
|
+
`@appweaver/payments` also registers two jobs deleting nothing: `paymentsReconcile` (`5m`) reads the payments and
|
|
335
|
+
subscriptions in a state that is not final from their gateways again, and `paymentsRedeliver` (`1m`) queues the
|
|
336
|
+
webhook events and the events of the payments no job finished (see [payments](./payments.md#maintenance-jobs)).
|
|
337
|
+
|
|
338
|
+
A job runs only when it applies (the audit log enabled with a retention, a model with a `purgeAfter`, ...), on a
|
|
339
|
+
timer for an interval, or as a job of the `Scheduler` (`@appweaver/cron`) for a cron expression, and takes a lock of
|
|
340
|
+
the `Memory` provider for its run, so with `redis` one instance runs it and the others skip it. A run is recorded in
|
|
341
|
+
the `Memory` too, so it happens once per interval (or once per cron tick, within 30 seconds) whatever the instances
|
|
342
|
+
starting at different times, and an interval longer than the 24.8 days of a Node timer is waited in steps. Its deletes
|
|
343
|
+
run in batches of `maintenance.batchSize` (`1000`). `maintenance.jobs.<name>.schedule` and `.enabled` change a job,
|
|
344
|
+
`maintenance.enabled: false` turns them off in an instance, i.e. the API instances of a cluster running them from a
|
|
345
|
+
Kubernetes cron job with `weaver run maintenance <name>` (`weaver run maintenance` lists them, and refuses a job that
|
|
346
|
+
does not apply, its feature being off).
|
|
347
|
+
|
|
348
|
+
```ts
|
|
349
|
+
// src/invites/index.ts, an application file (app.scanFilesPattern), or the main of a module: never src/main.ts,
|
|
350
|
+
// which weaver run does not load
|
|
351
|
+
import { defineMaintenanceJob } from '@appweaver/core';
|
|
352
|
+
|
|
353
|
+
defineMaintenanceJob({
|
|
354
|
+
name: 'expiredInvites',
|
|
355
|
+
description: 'Deletes the invites expired a week ago.',
|
|
356
|
+
schedule: '0 4 * * *', // a cron expression, or an interval: '1h', 3_600_000
|
|
357
|
+
applies: () => invitesConfig.ENABLED,
|
|
358
|
+
run: async ({ now, batchSize }) => deleteExpiredInvites(now, batchSize) // the number of records removed
|
|
359
|
+
});
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
A model removes its soft deleted records once deleted for a time with `softDelete: { purgeAfter: '90d' }`, the rows
|
|
363
|
+
deleted directly, their related rows following the `onDelete` of the database, and the stored files of the `files`
|
|
364
|
+
of the model deleted with them.
|
|
365
|
+
|
|
366
|
+
## Package modules
|
|
367
|
+
|
|
368
|
+
The `src/` directory of a package is what a local module is in `src/modules/<name>/`, so a local module that imports
|
|
369
|
+
nothing of the application through the `@/` aliases moves into a package unchanged:
|
|
370
|
+
|
|
371
|
+
```jsonc
|
|
372
|
+
// package.json
|
|
373
|
+
{
|
|
374
|
+
"name": "@acme/appweaver-gcs",
|
|
375
|
+
"keywords": ["appweaver-module"],
|
|
376
|
+
"appweaver": { "module": "./dist/module.js" },
|
|
377
|
+
"dependencies": { "@google-cloud/storage": "^7.0.0" },
|
|
378
|
+
"peerDependencies": {
|
|
379
|
+
"@appweaver/common": "^2.0.0",
|
|
380
|
+
"@appweaver/core": "^2.0.0"
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
```
|
|
384
|
+
|
|
385
|
+
```ts
|
|
386
|
+
// src/module.ts
|
|
387
|
+
export default defineModule({
|
|
388
|
+
name: '@acme/appweaver-gcs', // the package name
|
|
389
|
+
framework: '^2.0.0',
|
|
390
|
+
config: [gcsConfig],
|
|
391
|
+
loggers: ['gcs'], // the createLogger('gcs') of its sources
|
|
392
|
+
providers: [
|
|
393
|
+
{ contract: Storage, name: 'gcs', load: () => import('./gcs-storage') }
|
|
394
|
+
]
|
|
395
|
+
});
|
|
396
|
+
```
|
|
397
|
+
|
|
398
|
+
- Name the package `appweaver-<name>` or `@scope/appweaver-<name>`, with the npm keyword `appweaver-module`.
|
|
399
|
+
- `@appweaver/common` and `@appweaver/core` are peer dependencies, never dependencies, so the application keeps one
|
|
400
|
+
dependency injection context, as are `@appweaver/data` and `@appweaver/web` for a module importing their factories,
|
|
401
|
+
services or routes.
|
|
402
|
+
- A module the package `requires` is a dependency of it (`@appweaver/bullmq` depends on `@appweaver/redis`), so
|
|
403
|
+
installing the package brings and enables it, or a peer dependency the application installs too (`@appweaver/web`
|
|
404
|
+
on `@appweaver/data`).
|
|
405
|
+
- The application enables the package by installing it as a dependency (not a dev dependency).
|
|
406
|
+
- Never ship a `ResourceRegistry` augmentation for the models of the package: the application's `weaver generate`
|
|
407
|
+
registers them (it skips the registry when run in a module package, and leaves out the models of a package that
|
|
408
|
+
registers them anyway).
|
|
409
|
+
- Import the framework by its entry points only, since every `@appweaver/*` package declares them in its `exports`:
|
|
410
|
+
the package names, `@appweaver/core/config` and `@appweaver/data/config` (the config sections),
|
|
411
|
+
`@appweaver/core/drivers` (the in-process drivers) and `@appweaver/core/internal` (the application `context`, the
|
|
412
|
+
transaction scope, `LifecycleManager` and `loadProviders`, which can change in a minor release, so pin the
|
|
413
|
+
`framework` range). Node refuses a deep import such as `@appweaver/core/context/context`.
|
|
414
|
+
- A driver nests its config section under its contract (`storage.gcs`, like `mailer.smtp`), any other module takes its
|
|
415
|
+
own top-level section. Two packages may define the same section path with their own keys (`healthCheck` in core and
|
|
416
|
+
web, `security.oauth2` in data and web), but a flattened key belongs to one section only.
|
|
417
|
+
|
|
418
|
+
### Creating a module package
|
|
419
|
+
|
|
420
|
+
`npm create @appweaver module` creates a module package, ready to test and publish:
|
|
421
|
+
|
|
422
|
+
```sh
|
|
423
|
+
npm create @appweaver module @acme/appweaver-gcs "Google Cloud Storage driver" -- --contract storage
|
|
424
|
+
npx @appweaver/create module @acme/appweaver-audit # a feature module
|
|
425
|
+
npx @appweaver/create module appweaver-postmark --contract mailer -o ./postmark
|
|
426
|
+
npx @appweaver/create module @acme/appweaver-vonage "Vonage SMS sender" --contract sms
|
|
427
|
+
```
|
|
428
|
+
|
|
429
|
+
| Option | Description | Default |
|
|
430
|
+
| ------------------------ | -------------------------------------------------------------------------------- | ------------------------------ |
|
|
431
|
+
| `<package>` | npm name of the package, i.e. `@acme/appweaver-gcs` | — |
|
|
432
|
+
| `[description]` | Description of the package | `Appweaver module` |
|
|
433
|
+
| `-o, --output-dir <dir>` | Directory of the package | package name without its scope |
|
|
434
|
+
| `--contract <contract>` | Contract its driver implements: `storage`, `mailer`, `sms`, `none` for a feature | `none` |
|
|
435
|
+
|
|
436
|
+
The short name of the module strips the scope and the `appweaver-` prefix (`@acme/appweaver-gcs` → `gcs`), and is the
|
|
437
|
+
name of its provider. The package holds:
|
|
438
|
+
|
|
439
|
+
| File | Holds |
|
|
440
|
+
| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
441
|
+
| `package.json` | The `appweaver.module` field, the keyword `appweaver-module`, `@appweaver/common`, `@appweaver/core` and TypeBox as peer dependencies |
|
|
442
|
+
| `src/module.ts` | The manifest, named after the package, with its `framework` range and its provider or `main` |
|
|
443
|
+
| `src/config.ts` | Its section: `<contract>.<name>` for a driver (`storage.gcs`, `STORAGE_GCS_*`), `<name>` for a feature module |
|
|
444
|
+
| `src/storage.ts` / `src/mailer.ts` / `src/sms.ts` | The driver class `<Name>Storage` / `<Name>Mailer` / `<Name>Sms`, an in-memory stub passing the contract suite, to replace with the service calls |
|
|
445
|
+
| `src/main.ts` | The startup code of a feature module, logging with `createLogger('<name>')` (`log.levels.<name>`) |
|
|
446
|
+
| `test/*.test.ts` | The contract suite of the driver, or a test of the manifest and its `loggers` (`sourceLoggerNames`) |
|
|
447
|
+
| `tsconfig*.json`, `jest.config.json`, `README.md` | The build, the Jest setup with SWC, and the usage |
|
|
448
|
+
|
|
449
|
+
```sh
|
|
450
|
+
cd appweaver-gcs && npm install && npm test && npm publish
|
|
451
|
+
```
|
|
452
|
+
|
|
453
|
+
### Testing a driver
|
|
454
|
+
|
|
455
|
+
`@appweaver/testing` holds a contract suite per contract, testing a driver against the behavior every driver of it
|
|
456
|
+
shares. Call it at the top level of a test file with the name of the driver and a function creating it, a fresh
|
|
457
|
+
instance for every test:
|
|
458
|
+
|
|
459
|
+
```ts
|
|
460
|
+
// test/gcs-storage.test.ts
|
|
461
|
+
import { testStorageContract } from '@appweaver/testing';
|
|
462
|
+
import { GcsStorage } from '../src/gcs-storage';
|
|
463
|
+
|
|
464
|
+
testStorageContract('GcsStorage', () => new GcsStorage());
|
|
465
|
+
```
|
|
466
|
+
|
|
467
|
+
A driver of an external service runs the suite on an in-memory stand-in of its client, the way `@appweaver/redis` runs
|
|
468
|
+
`testMemoryContract` on `ioredis-mock` (`jest.mock('ioredis', ...)`), or on a real service in an integration test.
|
|
469
|
+
|
|
470
|
+
| Suite | Contract | Tests |
|
|
471
|
+
| ---------------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
472
|
+
| `testMemoryContract` | `Memory` | Values and their expiry, a value JSON cannot hold refused, `exists` and `delete`, key patterns, locks, the health check |
|
|
473
|
+
| `testStorageContract` | `Storage` | Storing and streaming a file and a byte range, `exists`, `delete`, `url`, the health check |
|
|
474
|
+
| `testQueueContract` | `Queue` | A job processed by a worker and its result, outside of the context of its sender, a failed job, a given job id and an ignored send of one still queued, closing a queue, the health check |
|
|
475
|
+
| `testSchedulerContract` | `Scheduler` | Adding, starting, stopping and removing a job, an unknown job id (yearly jobs, none ticks) |
|
|
476
|
+
| `testMailerContract` | `Mailer` | Sending an email with every field of the contract, the health check |
|
|
477
|
+
| `testAiDriverContract` | `AiDriver` | A text answer, a tool call and a conversation with its result, the JSON mode, a stream and a streamed tool call, the embeddings (unless `embeddings: false`), the capabilities and the health check |
|
|
478
|
+
| `testSmsContract` | `SmsSender` | Sending a text message with and without a sender, the name of its health check, the health check |
|
|
479
|
+
| `testPaymentGatewayContract` | `PaymentGateway` | The capabilities (an undeclared one throws `PAYMENT_CAPABILITY_UNSUPPORTED`), a customer, a payment the client confirms and its idempotency key, cancelling, an unknown payment, a hosted checkout, a setup, the prices and the portal, a rejected webhook signature, the health check; with the `savedMethod`, `priceId` and `signedWebhook` options also a charge, a refund, a capture, the saved methods, a subscription and a verified webhook |
|
|
480
|
+
| `testTimeSeriesContract` | `TimeSeries` | Writing and merging points, selecting fields and ranges, ordering and limiting, every aggregate by bucket and over the range, deleting a range (a store with `supportsDelete`), the health check |
|
|
481
|
+
|
|
482
|
+
The suites use the `describe`, `test`, `beforeEach`, `afterEach` and `expect` globals, so they run under Jest, Vitest
|
|
483
|
+
(with `globals: true`) and Bun. A driver of a remote service runs them against a test instance or emulator, the
|
|
484
|
+
mailer suite against a test inbox or a mocked transport, since it sends a real email, and the SMS suite against a test
|
|
485
|
+
number or a mocked API (`jest.spyOn(global, 'fetch')` for Twilio), and the payment gateway suite against a mocked
|
|
486
|
+
API or a test account of the provider, since it creates payments. Set the config the driver reads
|
|
487
|
+
with `configOverrides` of `@appweaver/common` in the factory or a `beforeAll`.
|
|
488
|
+
|
|
489
|
+
A driver delivering work later in its own process (a timer, an immediate, the events of a connection) creates it in
|
|
490
|
+
`runInRootContext(fn)` of `@appweaver/core`, so a job, a message or a tick never runs as the request that sent it or
|
|
491
|
+
started the loop: with its user, its `withoutPolicies`, its transaction or its request scope. The queue and pub/sub
|
|
492
|
+
suites check it.
|
|
493
|
+
|
|
494
|
+
### Adding a module package
|
|
495
|
+
|
|
496
|
+
An application enables a module package by installing it as a dependency. `weaver module add` does that without
|
|
497
|
+
running its install scripts, then prints what it brings:
|
|
498
|
+
|
|
499
|
+
```sh
|
|
500
|
+
weaver module add @acme/appweaver-gcs
|
|
501
|
+
# Module @acme/appweaver-gcs is enabled.
|
|
502
|
+
# provides Storage "gcs", select it in the provider key of the contract
|
|
503
|
+
```
|
|
504
|
+
|
|
505
|
+
A name that is not a scaffold module, with a scope, a `-` or a `/`, is a package, installed with
|
|
506
|
+
`npm install --ignore-scripts` (`bun add` on Bun), and can be mixed with the scaffold modules
|
|
507
|
+
(`weaver module add redis @acme/appweaver-gcs`). A package without the `appweaver.module` field, or without a valid
|
|
508
|
+
manifest, is reported as not a module. `--dry-run` prints the install command, and `--no-install` only adds the packages
|
|
509
|
+
to `package.json` and the lockfile.
|