@openreachtech/hora-skills-ort-renchan 0.0.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 +201 -0
- package/README.ja.md +135 -0
- package/README.md +135 -0
- package/dist/skills/hor-agent-loop/SKILL.md +123 -0
- package/dist/skills/hor-agent-loop/references/core.md +485 -0
- package/dist/skills/hor-agent-loop/references/graphql-integration.md +178 -0
- package/dist/skills/hor-agent-loop/references/renchan-job-integration.md +368 -0
- package/dist/skills/hor-agent-loop/references/testing.md +492 -0
- package/dist/skills/hor-ai-agent-structure/SKILL.md +403 -0
- package/dist/skills/hor-ai-agent-structure/references/loop-and-actions.md +100 -0
- package/dist/skills/hor-ai-prompt-document-store/SKILL.md +220 -0
- package/dist/skills/hor-ai-prompt-document-store/references/models-and-composition.md +156 -0
- package/dist/skills/hor-backend-testing/SKILL.md +118 -0
- package/dist/skills/hor-backend-testing/references/placement-and-ordering.md +89 -0
- package/dist/skills/hor-backend-testing/references/purity-and-mocks.md +82 -0
- package/dist/skills/hor-backend-testing/references/running-tests.md +186 -0
- package/dist/skills/hor-bank-id/SKILL.md +91 -0
- package/dist/skills/hor-build-e2e-test-environment/SKILL.md +609 -0
- package/dist/skills/hor-build-e2e-test-environment/references/compose-definition.md +368 -0
- package/dist/skills/hor-build-e2e-test-environment/references/edge-and-proxy.md +287 -0
- package/dist/skills/hor-build-e2e-test-environment/references/environment-and-ports.md +201 -0
- package/dist/skills/hor-build-e2e-test-environment/references/runner-and-lifecycle.md +330 -0
- package/dist/skills/hor-build-e2e-test-environment/references/seed-data.md +145 -0
- package/dist/skills/hor-build-e2e-test-environment/references/windows-runner.md +146 -0
- package/dist/skills/hor-constant-definition/SKILL.md +139 -0
- package/dist/skills/hor-cookie-authentication/SKILL.md +33 -0
- package/dist/skills/hor-cookie-authentication/references/auth-filter.md +55 -0
- package/dist/skills/hor-cookie-authentication/references/cookie-context.md +53 -0
- package/dist/skills/hor-cookie-authentication/references/dev-login-seeder.md +22 -0
- package/dist/skills/hor-cookie-authentication/references/environment.md +64 -0
- package/dist/skills/hor-cookie-authentication/references/error-codes.md +24 -0
- package/dist/skills/hor-cookie-authentication/references/migrations.md +18 -0
- package/dist/skills/hor-cookie-authentication/references/resolvers.md +97 -0
- package/dist/skills/hor-cookie-authentication/references/session-clerk.md +41 -0
- package/dist/skills/hor-cookie-authentication/references/token-models.md +125 -0
- package/dist/skills/hor-database-design/SKILL.md +54 -0
- package/dist/skills/hor-database-design/references/column-types.md +92 -0
- package/dist/skills/hor-database-design/references/datetimes.md +88 -0
- package/dist/skills/hor-database-design/references/master-tables.md +117 -0
- package/dist/skills/hor-database-design/references/normalization.md +40 -0
- package/dist/skills/hor-database-design/references/update-history.md +35 -0
- package/dist/skills/hor-execution-placement-pattern/SKILL.md +216 -0
- package/dist/skills/hor-external-api-client/SKILL.md +99 -0
- package/dist/skills/hor-external-api-client/references/architecture.md +127 -0
- package/dist/skills/hor-external-api-client/references/authorization.md +105 -0
- package/dist/skills/hor-external-api-client/references/capsule.md +130 -0
- package/dist/skills/hor-external-api-client/references/conventions.md +68 -0
- package/dist/skills/hor-external-api-client/references/launcher.md +138 -0
- package/dist/skills/hor-external-api-client/references/payload.md +176 -0
- package/dist/skills/hor-external-api-client/references/sdk-wrapper.md +291 -0
- package/dist/skills/hor-external-api-client/references/testing.md +130 -0
- package/dist/skills/hor-external-api-client/references/usage.md +152 -0
- package/dist/skills/hor-graphql-schema/SKILL.md +360 -0
- package/dist/skills/hor-graphql-server-engine/SKILL.md +356 -0
- package/dist/skills/hor-light-rag/SKILL.md +242 -0
- package/dist/skills/hor-light-rag/references/retrieval-internals.md +143 -0
- package/dist/skills/hor-multi-llm-provider/SKILL.md +288 -0
- package/dist/skills/hor-multi-llm-provider/references/provider-internals.md +153 -0
- package/dist/skills/hor-mutation-resolver/SKILL.md +360 -0
- package/dist/skills/hor-mutation-resolver/references/dependency-injection.md +148 -0
- package/dist/skills/hor-mutation-resolver/references/errors.md +120 -0
- package/dist/skills/hor-mutation-resolver/references/resolve-flow.md +275 -0
- package/dist/skills/hor-mutation-resolver/references/testing.md +125 -0
- package/dist/skills/hor-mutation-resolver/references/transaction.md +197 -0
- package/dist/skills/hor-post-worker/SKILL.md +320 -0
- package/dist/skills/hor-query-resolver/SKILL.md +246 -0
- package/dist/skills/hor-query-resolver/references/anatomy.md +384 -0
- package/dist/skills/hor-query-resolver/references/data-access.md +248 -0
- package/dist/skills/hor-query-resolver/references/errors-and-context.md +172 -0
- package/dist/skills/hor-query-resolver/references/testing.md +241 -0
- package/dist/skills/hor-renchan-job-bullmq/SKILL.md +178 -0
- package/dist/skills/hor-renchan-job-bullmq/references/daemon-and-scheduler.md +182 -0
- package/dist/skills/hor-renchan-job-bullmq/references/engine-and-infra.md +106 -0
- package/dist/skills/hor-renchan-job-bullmq/references/job-triple.md +189 -0
- package/dist/skills/hor-renchan-job-bullmq/references/queues.md +74 -0
- package/dist/skills/hor-renchan-job-bullmq/references/subscriptions.md +113 -0
- package/dist/skills/hor-resolver-share/SKILL.md +262 -0
- package/dist/skills/hor-resolver-validator/SKILL.md +194 -0
- package/dist/skills/hor-resolver-validator/references/inspector-api.md +115 -0
- package/dist/skills/hor-resolver-validator/references/validator-pattern.md +281 -0
- package/dist/skills/hor-restfulapi-architecture/SKILL.md +275 -0
- package/dist/skills/hor-restfulapi-architecture/references/engine-and-context.md +192 -0
- package/dist/skills/hor-restfulapi-architecture/references/renderers.md +204 -0
- package/dist/skills/hor-restfulapi-architecture/references/response-and-flusher.md +118 -0
- package/dist/skills/hor-restfulapi-architecture/references/validation.md +229 -0
- package/dist/skills/hor-security-audit/SKILL.md +110 -0
- package/dist/skills/hor-security-audit/references/application-surface.md +90 -0
- package/dist/skills/hor-security-audit/references/auth-and-transport.md +147 -0
- package/dist/skills/hor-security-audit/references/code-safety.md +74 -0
- package/dist/skills/hor-security-audit/references/dependencies.md +72 -0
- package/dist/skills/hor-security-audit/references/network-and-logging.md +56 -0
- package/dist/skills/hor-security-audit/references/secrets.md +95 -0
- package/dist/skills/hor-sequelize-migration/SKILL.md +336 -0
- package/dist/skills/hor-sequelize-migration/references/alter-table.md +147 -0
- package/dist/skills/hor-sequelize-migration/references/foreign-keys.md +107 -0
- package/dist/skills/hor-sequelize-migration/references/indexes.md +149 -0
- package/dist/skills/hor-sequelize-migration/references/notation.md +215 -0
- package/dist/skills/hor-sequelize-model/SKILL.md +69 -0
- package/dist/skills/hor-sequelize-model/references/associations.md +218 -0
- package/dist/skills/hor-sequelize-model/references/default-methods.md +244 -0
- package/dist/skills/hor-sequelize-model/references/mixins.md +247 -0
- package/dist/skills/hor-sequelize-model/references/notation.md +225 -0
- package/dist/skills/hor-sequelize-model/references/timestamps.md +74 -0
- package/dist/skills/hor-sequelize-seeder/SKILL.md +275 -0
- package/dist/skills/hor-sequelize-seeder/references/development-coverage.md +74 -0
- package/dist/skills/hor-sequelize-seeder/references/directory-structure.md +113 -0
- package/dist/skills/hor-sequelize-seeder/references/id-numbering.md +133 -0
- package/dist/skills/hor-sequelize-seeder/references/naming.md +59 -0
- package/dist/skills/hor-sequelize-seeder/references/notation.md +170 -0
- package/dist/skills/hor-sequelize-subquery/SKILL.md +369 -0
- package/dist/skills/hor-strategy-pattern/SKILL.md +371 -0
- package/dist/skills/hor-stub-api/SKILL.md +330 -0
- package/dist/skills/hor-subscription-resolver/SKILL.md +105 -0
- package/dist/skills/hor-subscription-resolver/references/authentication.md +99 -0
- package/dist/skills/hor-subscription-resolver/references/basic-notation.md +116 -0
- package/dist/skills/hor-subscription-resolver/references/design-philosophy.md +68 -0
- package/dist/skills/hor-type-interface/SKILL.md +200 -0
- package/docs/skills.ja.md +40 -0
- package/docs/skills.md +40 -0
- package/lib/equip/CommandLineArguments.js +178 -0
- package/lib/equip/HoraSkillsCli.js +590 -0
- package/lib/equip/SkillsInstaller.js +443 -0
- package/lib/equip/SkillsManifestFile.js +260 -0
- package/lib/equip/constants/CLI_COMMAND.js +8 -0
- package/lib/equip/hora-skills-ort-renchan.js +8 -0
- package/package.json +51 -0
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
# Errors, context, and actual-vs-stub
|
|
2
|
+
|
|
3
|
+
The errorCodeHash prefix families, the validator↔errorHash contract, domain-error creators, reading
|
|
4
|
+
auth and injected providers off `context`, and the actual-vs-stub split. Referenced from §1 and §4 of
|
|
5
|
+
[SKILL.md](../SKILL.md).
|
|
6
|
+
|
|
7
|
+
> The `users` / `User` / `Department` names and the `Q001` / `Q002` identifiers are placeholders —
|
|
8
|
+
> swap in your resource and this resolver's own identifier.
|
|
9
|
+
|
|
10
|
+
## errorCodeHash: families and identifiers
|
|
11
|
+
|
|
12
|
+
`errorCodeHash` maps each error **name** to a **string code**; the framework's `create()` turns those
|
|
13
|
+
into the `this.errorHash.<Name>` constructors the resolver and its validator throw. Always spread
|
|
14
|
+
`...super.errorCodeHash` first, then group this resolver's codes with a one-line family comment.
|
|
15
|
+
|
|
16
|
+
```js
|
|
17
|
+
/** @override */
|
|
18
|
+
static get errorCodeHash () {
|
|
19
|
+
return {
|
|
20
|
+
...super.errorCodeHash,
|
|
21
|
+
|
|
22
|
+
// Invalid Input Errors (203 prefix)
|
|
23
|
+
InvalidUserId: '203.Q002.001',
|
|
24
|
+
InvalidDepartmentId: '203.Q002.002',
|
|
25
|
+
|
|
26
|
+
// Database Errors (204 prefix)
|
|
27
|
+
UserNotFound: '204.Q002.001',
|
|
28
|
+
DepartmentNotFound: '204.Q002.002',
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Code format is `<family>.<identifier>.<seq>`:
|
|
34
|
+
|
|
35
|
+
- **`<family>`** — the leading number classifies the error:
|
|
36
|
+
- `203` — invalid input (raised by the `*InputValidator`).
|
|
37
|
+
- `204` — database / not-found (thrown from `resolve()`).
|
|
38
|
+
- `205` — business logic / external API.
|
|
39
|
+
- Framework standards sit above these and are already defined by the engine — do **not** redeclare
|
|
40
|
+
them: `102` unauthenticated / unauthorized / denied-permission, `104` database, `100` unknown,
|
|
41
|
+
`101` concrete-member-not-found.
|
|
42
|
+
- **`<identifier>`** (`Q002`, …) is a **stable per-query id**. Keep one resolver on one identifier;
|
|
43
|
+
the letter tracks the endpoint family (`Q` for the query endpoints).
|
|
44
|
+
- **`<seq>`** (`001`, `002`, …) numbers the errors within this resolver, per family.
|
|
45
|
+
|
|
46
|
+
## The validator ↔ errorHash contract
|
|
47
|
+
|
|
48
|
+
Input-shape errors are **not** thrown by the resolver directly — the `*InputValidator` raises them
|
|
49
|
+
through the **same `errorHash`** the resolver passes in. So every `InvalidXxx` the validator can raise
|
|
50
|
+
must have a matching key in the resolver's `errorCodeHash`.
|
|
51
|
+
|
|
52
|
+
- The resolver's `createInputValidator()` forwards `errorHash = this.errorHash`
|
|
53
|
+
([SKILL.md §5](../SKILL.md)); the validator's `ErrorHash` typedef lists those same `InvalidXxx`
|
|
54
|
+
names (`hor-resolver-validator`).
|
|
55
|
+
- `validateInput()` returns the error or `null`; `resolve()` decides to throw. Keeping the throw in
|
|
56
|
+
`resolve()` (not the validator) keeps the entrypoint's control flow visible.
|
|
57
|
+
|
|
58
|
+
## Domain errors: throw from resolve(), optionally via a creator
|
|
59
|
+
|
|
60
|
+
Not-found and empty-result errors are thrown where they are detected — right after the finder — with
|
|
61
|
+
`this.errorHash.<Name>.create()`:
|
|
62
|
+
|
|
63
|
+
```js
|
|
64
|
+
const user = await this.findUser({ userId })
|
|
65
|
+
|
|
66
|
+
if (!user) {
|
|
67
|
+
throw this.errorHash.UserNotFound.create()
|
|
68
|
+
}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
- **Never wrap the read/throw in `try/catch`.** The GraphQL layer maps a thrown declared error to the
|
|
72
|
+
response; a `try/catch` that swallows or re-wraps it hides which code the caller receives. Let the
|
|
73
|
+
declared error propagate.
|
|
74
|
+
|
|
75
|
+
When a resolver throws several domain errors, wrap each in a **creator method** so `resolve()` stays
|
|
76
|
+
readable and the construction is unit-testable. Creators sit at the bottom of the class (after
|
|
77
|
+
`formatResponse`) and default `errorHash` to `this.errorHash`:
|
|
78
|
+
|
|
79
|
+
```js
|
|
80
|
+
if (users.length === 0) {
|
|
81
|
+
throw this.createUserNotFoundError()
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// ... lower in the class ...
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Create a UserNotFoundError instance.
|
|
88
|
+
*
|
|
89
|
+
* @param {{
|
|
90
|
+
* errorHash?: ErrorHash
|
|
91
|
+
* }} [params]
|
|
92
|
+
* @returns {InstanceType<RenchanGraphqlErrorCtor>}
|
|
93
|
+
*/
|
|
94
|
+
createUserNotFoundError ({
|
|
95
|
+
errorHash = this.errorHash,
|
|
96
|
+
} = {}) {
|
|
97
|
+
return errorHash.UserNotFound.create()
|
|
98
|
+
}
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## Reading context (auth + injected providers)
|
|
102
|
+
|
|
103
|
+
`resolve()` receives `{ variables, context, information, parent }`. **`context`** carries the
|
|
104
|
+
authenticated principal and request-scoped providers the engine injects. Destructure only what you
|
|
105
|
+
use; omit `context` entirely when the query needs nothing from it.
|
|
106
|
+
|
|
107
|
+
```js
|
|
108
|
+
async resolve ({
|
|
109
|
+
context,
|
|
110
|
+
}) {
|
|
111
|
+
const roleIds = context.employee.EmployeeRoleAssignments
|
|
112
|
+
.map(employeeRoleAssignment => employeeRoleAssignment.RoleId)
|
|
113
|
+
|
|
114
|
+
// ...
|
|
115
|
+
}
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
```js
|
|
119
|
+
async resolve ({
|
|
120
|
+
variables: {
|
|
121
|
+
input,
|
|
122
|
+
},
|
|
123
|
+
context: {
|
|
124
|
+
modelProvider, // an injected provider, destructured directly
|
|
125
|
+
},
|
|
126
|
+
}) {
|
|
127
|
+
// ... use modelProvider ...
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
- The principal lives under the endpoint's name: `context.user` (user endpoint), `context.customer`
|
|
132
|
+
(customer endpoint), `context.employee` (admin endpoint), etc. — with its associations preloaded
|
|
133
|
+
(e.g. `context.employee.EmployeeRoleAssignments`).
|
|
134
|
+
- Request-scoped providers the engine injects also live on `context`.
|
|
135
|
+
- **Authentication/authorization is enforced by the engine before `resolve()` runs** (the `102`
|
|
136
|
+
standard codes). Do not re-check auth here; just read the trusted principal.
|
|
137
|
+
- Alias the context type in the typedef block:
|
|
138
|
+
`@typedef {import('../../../../contexts/AdminGraphqlContext.js').default} AdminGraphqlContext`, and
|
|
139
|
+
reference it from the `resolve()` param JSDoc.
|
|
140
|
+
|
|
141
|
+
## Actual vs stub
|
|
142
|
+
|
|
143
|
+
Every endpoint has parallel `actual/` and `stub/` trees; the engine wires each via
|
|
144
|
+
`actualResolversPath` / `stubResolversPath`.
|
|
145
|
+
|
|
146
|
+
- **`actual/queries/`** — the real resolver: validate, read the DB, throw domain errors, format. This
|
|
147
|
+
is what this skill describes.
|
|
148
|
+
- **`stub/queries/`** — a same-`schema` resolver returning **fixed fake data** so the frontend can
|
|
149
|
+
build against the contract before the real query exists. Stubs skip validation and the DB, often
|
|
150
|
+
`await sleep(...)` to mimic latency, and return literal objects:
|
|
151
|
+
|
|
152
|
+
```js
|
|
153
|
+
export default class UserSummaryQueryResolver extends BaseQueryResolver {
|
|
154
|
+
/** @override */
|
|
155
|
+
static get schema () {
|
|
156
|
+
return 'userSummary'
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** @override */
|
|
160
|
+
async resolve () {
|
|
161
|
+
await sleep(200)
|
|
162
|
+
|
|
163
|
+
return {
|
|
164
|
+
totalUsers: 1234,
|
|
165
|
+
activeUsers: 987,
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
- A stub and its actual share the `schema` name and the GraphQL result shape; only the body differs.
|
|
172
|
+
Keep stub data **obviously fake** so it is never mistaken for real output.
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
# Testing a query resolver
|
|
2
|
+
|
|
3
|
+
The member-by-member test layout for a `*QueryResolver`, building on the `hoc-jest`
|
|
4
|
+
skill. Referenced from §7 of [SKILL.md](../SKILL.md). This file only covers what is
|
|
5
|
+
resolver-specific; describe/test structure, `cases` data rules, AAA, and naming come from the jest
|
|
6
|
+
skill.
|
|
7
|
+
|
|
8
|
+
> The `Users` / `User` names, the `203.Q001.*` codes, and the `users` schema below are placeholders —
|
|
9
|
+
> swap in your resolver's own names and codes.
|
|
10
|
+
|
|
11
|
+
## File location and construction
|
|
12
|
+
|
|
13
|
+
- The test mirrors the resolver path under `tests/__tests__/` but **without the `actual/` segment**:
|
|
14
|
+
`server/graphql/resolvers/admin/actual/queries/UsersQueryResolver.js`
|
|
15
|
+
→ `tests/__tests__/server/graphql/resolvers/admin/queries/UsersQueryResolver.js`.
|
|
16
|
+
- A DB-backed resolver test reads the seeded database (`npm test` seeds `dev-master` + `development`),
|
|
17
|
+
so finder cases assert against known seed rows.
|
|
18
|
+
- Build the resolver with the framework factory, **no args**: `const resolver = Resolver.create()`.
|
|
19
|
+
`create()` injects `errorHash` from `errorCodeHash` for you.
|
|
20
|
+
|
|
21
|
+
## One top-level describe per member
|
|
22
|
+
|
|
23
|
+
Per the jest skill, give **each** public member its own top-level `describe('<Resolver>')` →
|
|
24
|
+
`describe('#member()')`. A query resolver typically tests: `#resolve()`, `#validateInput()`,
|
|
25
|
+
`#createInputValidator()`, the finders (`#buildWhereClause()`, `#countX()`, `#findX()`),
|
|
26
|
+
`#formatResponse()`, and `.get:schema`.
|
|
27
|
+
|
|
28
|
+
## `#resolve()`: happy path + a throws-case per error code
|
|
29
|
+
|
|
30
|
+
Split valid and error runs into sub-`describe`s. The happy path asserts the whole formatted result;
|
|
31
|
+
the error path asserts the **error code** for each way the query can fail.
|
|
32
|
+
|
|
33
|
+
```js
|
|
34
|
+
describe('UsersQueryResolver', () => {
|
|
35
|
+
describe('#resolve()', () => {
|
|
36
|
+
describe('when input is valid', () => {
|
|
37
|
+
const cases = [
|
|
38
|
+
{
|
|
39
|
+
params: {
|
|
40
|
+
variables: {
|
|
41
|
+
input: {
|
|
42
|
+
keyword: null,
|
|
43
|
+
departmentId: null,
|
|
44
|
+
pagination: {
|
|
45
|
+
limit: 10,
|
|
46
|
+
offset: 0,
|
|
47
|
+
sort: {
|
|
48
|
+
targetColumn: 'name',
|
|
49
|
+
orderBy: 'ASC',
|
|
50
|
+
},
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
expected: {
|
|
56
|
+
users: [
|
|
57
|
+
// ... rows from the seed, fully spelled out ...
|
|
58
|
+
],
|
|
59
|
+
pagination: {
|
|
60
|
+
limit: 10,
|
|
61
|
+
offset: 0,
|
|
62
|
+
sort: {
|
|
63
|
+
targetColumn: 'name',
|
|
64
|
+
orderBy: 'ASC',
|
|
65
|
+
},
|
|
66
|
+
totalRecords: 11,
|
|
67
|
+
},
|
|
68
|
+
},
|
|
69
|
+
},
|
|
70
|
+
]
|
|
71
|
+
|
|
72
|
+
test.each(cases)('keyword: $params.variables.input.keyword', async ({
|
|
73
|
+
params,
|
|
74
|
+
expected,
|
|
75
|
+
}) => {
|
|
76
|
+
const resolver = UsersQueryResolver.create()
|
|
77
|
+
|
|
78
|
+
const actual = await resolver.resolve(params)
|
|
79
|
+
|
|
80
|
+
expect(actual)
|
|
81
|
+
.toEqual(expected)
|
|
82
|
+
})
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
describe('should throw error', () => {
|
|
86
|
+
const cases = [
|
|
87
|
+
{
|
|
88
|
+
params: {
|
|
89
|
+
variables: {
|
|
90
|
+
input: {
|
|
91
|
+
keyword: /** @type {*} */ (1),
|
|
92
|
+
pagination: {
|
|
93
|
+
limit: 1,
|
|
94
|
+
offset: 0,
|
|
95
|
+
},
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
},
|
|
99
|
+
errorCode: '203.Q001.001',
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
params: {
|
|
103
|
+
variables: {
|
|
104
|
+
input: {
|
|
105
|
+
keyword: null,
|
|
106
|
+
pagination: {
|
|
107
|
+
limit: -1,
|
|
108
|
+
offset: 0,
|
|
109
|
+
},
|
|
110
|
+
},
|
|
111
|
+
},
|
|
112
|
+
},
|
|
113
|
+
errorCode: '203.Q001.003',
|
|
114
|
+
},
|
|
115
|
+
]
|
|
116
|
+
|
|
117
|
+
test.each(cases)('limit: $params.variables.input.pagination.limit', async ({
|
|
118
|
+
params,
|
|
119
|
+
errorCode,
|
|
120
|
+
}) => {
|
|
121
|
+
const resolver = UsersQueryResolver.create()
|
|
122
|
+
|
|
123
|
+
const actual = resolver.resolve(params)
|
|
124
|
+
|
|
125
|
+
await expect(actual)
|
|
126
|
+
.rejects
|
|
127
|
+
.toThrow(errorCode)
|
|
128
|
+
})
|
|
129
|
+
})
|
|
130
|
+
})
|
|
131
|
+
})
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
- Assert the **thrown error by its code string** with `.rejects.toThrow('203.Q001.003')`. Cover at
|
|
135
|
+
least one case per `InvalidXxx` (via bad input) and per domain error (`XxxNotFound`, by asking for a
|
|
136
|
+
missing id).
|
|
137
|
+
- Cast deliberately-wrong input to `/** @type {*} */ (...)` so the type checker allows the invalid
|
|
138
|
+
case.
|
|
139
|
+
|
|
140
|
+
## `#validateInput()` and `#createInputValidator()`
|
|
141
|
+
|
|
142
|
+
Test the wiring, not the validator's internals (those belong to
|
|
143
|
+
`hor-resolver-validator`'s own test).
|
|
144
|
+
|
|
145
|
+
- **`#validateInput()`** — `jest.spyOn(resolver, 'createInputValidator')` to return a mock validator
|
|
146
|
+
whose `validateInput()` is stubbed; assert `#validateInput()` returns exactly what the validator
|
|
147
|
+
returned (an error or `null`) and that the mock was called.
|
|
148
|
+
- **`#createInputValidator()`** — assert the returned instance `toBeInstanceOf` the expected
|
|
149
|
+
`*InputValidator` and that its `errorHash` is the resolver's `errorHash` (`toBe(resolver.errorHash)`).
|
|
150
|
+
|
|
151
|
+
## Finders and `#formatResponse()`
|
|
152
|
+
|
|
153
|
+
- **Finders** (`#countX`, `#findX`, `#buildWhereClause`) are tested directly against the seed. For
|
|
154
|
+
`buildWhereClause`, assert the returned Sequelize `where` object with `toEqual` — including `Op`
|
|
155
|
+
symbol keys and any `Model.subquery(...)` expression, which you reproduce in `expected`.
|
|
156
|
+
- **`#formatResponse()`** is pure and DB-free: **build** model instances with `Model.build({...})` for
|
|
157
|
+
the input entities, call `formatResponse`, and `toEqual` the exact GraphQL shape (renamed fields,
|
|
158
|
+
defaulted scalars, echoed pagination).
|
|
159
|
+
|
|
160
|
+
```js
|
|
161
|
+
describe('UsersQueryResolver', () => {
|
|
162
|
+
describe('#formatResponse()', () => {
|
|
163
|
+
/** @type {Array<*>} */
|
|
164
|
+
const cases = [
|
|
165
|
+
{
|
|
166
|
+
params: {
|
|
167
|
+
users: [
|
|
168
|
+
User.build({
|
|
169
|
+
id: 1,
|
|
170
|
+
name: 'Alpha',
|
|
171
|
+
email: 'alpha@example.com',
|
|
172
|
+
isActive: true,
|
|
173
|
+
}),
|
|
174
|
+
],
|
|
175
|
+
pagination: {
|
|
176
|
+
limit: 10,
|
|
177
|
+
offset: 0,
|
|
178
|
+
},
|
|
179
|
+
totalRecords: 1,
|
|
180
|
+
},
|
|
181
|
+
expected: {
|
|
182
|
+
users: [
|
|
183
|
+
{
|
|
184
|
+
userId: 1,
|
|
185
|
+
name: 'Alpha',
|
|
186
|
+
email: 'alpha@example.com',
|
|
187
|
+
isActive: true,
|
|
188
|
+
},
|
|
189
|
+
],
|
|
190
|
+
pagination: {
|
|
191
|
+
limit: 10,
|
|
192
|
+
offset: 0,
|
|
193
|
+
sort: null,
|
|
194
|
+
totalRecords: 1,
|
|
195
|
+
},
|
|
196
|
+
},
|
|
197
|
+
},
|
|
198
|
+
]
|
|
199
|
+
|
|
200
|
+
test.each(cases)('totalRecords: $params.totalRecords', ({
|
|
201
|
+
params,
|
|
202
|
+
expected,
|
|
203
|
+
}) => {
|
|
204
|
+
const resolver = UsersQueryResolver.create()
|
|
205
|
+
|
|
206
|
+
const actual = resolver.formatResponse(params)
|
|
207
|
+
|
|
208
|
+
expect(actual)
|
|
209
|
+
.toEqual(expected)
|
|
210
|
+
})
|
|
211
|
+
})
|
|
212
|
+
})
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
## `.get:schema`
|
|
216
|
+
|
|
217
|
+
The static getter is a single-value contract — a plain `test` (no `test.each`) is fine here, per the
|
|
218
|
+
jest skill's exception for argument-less static getters:
|
|
219
|
+
|
|
220
|
+
```js
|
|
221
|
+
describe('UsersQueryResolver', () => {
|
|
222
|
+
describe('.get:schema', () => {
|
|
223
|
+
test('should return correct schema name', () => {
|
|
224
|
+
const actual = UsersQueryResolver.schema
|
|
225
|
+
|
|
226
|
+
expect(actual)
|
|
227
|
+
.toBe('users')
|
|
228
|
+
})
|
|
229
|
+
})
|
|
230
|
+
})
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
## Reminders from the jest skill
|
|
234
|
+
|
|
235
|
+
- **Unique, explicitly-fake data** across every field and row; comments in the test `.js` in English.
|
|
236
|
+
- **Do not shrink coverage using implementation knowledge** — test each member's contract as a black
|
|
237
|
+
box, including `formatResponse`'s field renames and defaulting (feed values that make the transform
|
|
238
|
+
visible, not no-op values).
|
|
239
|
+
- For a resolver that reads `context`, pass a **stub context** in `params` shaped like the real
|
|
240
|
+
principal (`{ context: { employee: { EmployeeRoleAssignments: [...] } } }`); see
|
|
241
|
+
[errors-and-context.md](./errors-and-context.md).
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: hor-renchan-job-bullmq
|
|
3
|
+
description: >
|
|
4
|
+
Write and wire background jobs with @openreachtech/renchan-job-bullmq (BullMQ on Redis). Use
|
|
5
|
+
this skill whenever the user asks to add or edit a job under app/jobs/** — a Manifest / Worker /
|
|
6
|
+
Dispatcher triple, a cron or interval (repeatable) job, enqueuing from a GraphQL/REST resolver,
|
|
7
|
+
publishing progress to a GraphQL subscription, the worker daemon entry point, splitting work
|
|
8
|
+
across queues, or tuning concurrency / retries / rate limits.
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
# renchan-job-bullmq
|
|
12
|
+
|
|
13
|
+
`@openreachtech/renchan-job-bullmq` is this repo's job framework: **BullMQ queues on Redis**, wrapped
|
|
14
|
+
in renchan base classes. A job is a small **template of class files in one directory** under
|
|
15
|
+
`app/jobs/<job-name>/`. Two long-running processes share **one Redis** (`pm2.config.cjs`):
|
|
16
|
+
|
|
17
|
+
- **GraphQL API** (`server/index.js`) — handles requests and **enqueues** jobs (producer).
|
|
18
|
+
- **Job Daemon** (`scripts/startJobDaemon.js`) — **runs** the workers (consumer) and
|
|
19
|
+
**publishes progress** back over Redis PubSub to the API's GraphQL subscriptions.
|
|
20
|
+
|
|
21
|
+
This overview maps each topic to a section; the specifics are in the detail files under
|
|
22
|
+
`references/`. The package's own usage samples live in `samples/confirm-01` (dispatch + daemon) and
|
|
23
|
+
`samples/confirm-02` (cron + interval schedulers) of the `hor-renchan-job-bullmq` package.
|
|
24
|
+
|
|
25
|
+
## Core principle: a job is a filled-in template of 3–4 files
|
|
26
|
+
|
|
27
|
+
Each job is a directory `app/jobs/<kebab-job-name>/` holding a fixed set of classes, each extending a
|
|
28
|
+
renchan base, all pointing at one central **Engine**:
|
|
29
|
+
|
|
30
|
+
| File | Base class | Responsibility |
|
|
31
|
+
| --- | --- | --- |
|
|
32
|
+
| `<Name>JobManifest.js` | `BaseJobManifest` | the **queue name** (`jobName`) + the **body schema** |
|
|
33
|
+
| `<Name>JobWorker.js` | `BaseJobWorker` | **consume**: `executeJob()` + lifecycle hooks |
|
|
34
|
+
| `<Name>JobDispatcher.js` | `BaseJobDispatcher` | **produce**: enqueue + per-queue `optionHash` |
|
|
35
|
+
| `<Name>CronJobScheduler.js` / `<Name>IntervalJobScheduler.js` | `BaseCronJobScheduler` / `BaseIntervalJobScheduler` | (scheduled jobs) register a repeatable job |
|
|
36
|
+
|
|
37
|
+
Keep the layout identical across jobs so review attention goes to the job's *logic*. Directory =
|
|
38
|
+
kebab = `jobName`; classes are PascalCase with those fixed suffixes. Structural comments are English;
|
|
39
|
+
the domain-explanation comments in the real files are Japanese (they cite the plan, `T-JOB-*`) —
|
|
40
|
+
match the surrounding code.
|
|
41
|
+
|
|
42
|
+
## 1. Basic usage — the Manifest / Worker / Dispatcher triple
|
|
43
|
+
|
|
44
|
+
- **Manifest** — `jobName` (the queue name, == the directory) + `bodySchema` (`ScalarHash` scalars
|
|
45
|
+
`Text` / `Integer` / … from `@openreachtech/mentsu-schema`). Keep the body minimal (ids/tokens).
|
|
46
|
+
- **Worker** — `static get ManifestCtor()` + `async executeJob({ body, context, parcel })` + the four
|
|
47
|
+
abstract lifecycle hooks (`onJobCompleted` / `onJobFailed` / `onJobProgress` / `onWorkerError`).
|
|
48
|
+
**`executeJob`'s return value is stored in Redis — return only the minimum**, never entity arrays.
|
|
49
|
+
Override `buildOptionHash()` for `concurrency` / `limiter`.
|
|
50
|
+
- **Dispatcher** — `static get EngineCtor()` + `static get ManifestCtor()` + optional
|
|
51
|
+
`static get optionHash()` (BullMQ `QueueOptions`, e.g. `defaultJobOptions.attempts`). To stay DRY,
|
|
52
|
+
a base app dispatcher can set `EngineCtor` once so each job dispatcher only sets `ManifestCtor`.
|
|
53
|
+
|
|
54
|
+
```js
|
|
55
|
+
// Manifest — the source of truth for the queue name and payload shape
|
|
56
|
+
export default class SendReportEmailJobManifest extends BaseJobManifest {
|
|
57
|
+
/** @override */ static get jobName () { return 'send-report-email' }
|
|
58
|
+
|
|
59
|
+
/** @override */
|
|
60
|
+
static get bodySchema () {
|
|
61
|
+
return {
|
|
62
|
+
sessionToken: Text,
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
**Enqueue** from a resolver via the request-scope `JobDispatcherProvider` (connection reuse):
|
|
69
|
+
|
|
70
|
+
```js
|
|
71
|
+
await context.share.jobDispatcherProvider.dispatchJob({
|
|
72
|
+
DispatcherCtor: SendReportEmailJobDispatcher,
|
|
73
|
+
body: {
|
|
74
|
+
sessionToken,
|
|
75
|
+
},
|
|
76
|
+
})
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Standalone (one-off): `const dispatcher = await Dispatcher.createAsync(); await dispatcher.dispatchJob({ body }); await dispatcher.teardown()`
|
|
80
|
+
— `dispatchJob` returns a response with `hasError()` / `hasResponse()` / `createDispatchedAt()`.
|
|
81
|
+
|
|
82
|
+
Full classes, hooks, the base-app-dispatcher pattern, and the enqueue paths are in
|
|
83
|
+
[job-triple.md](./references/job-triple.md).
|
|
84
|
+
|
|
85
|
+
## 2. Engine / Share / Context / RedisConnection
|
|
86
|
+
|
|
87
|
+
- **Engine** (`ContentGenerationJobEngine.js`) —
|
|
88
|
+
the one config object: `config` = `{ workersPath, schedulersPath, redisConfig }` (both paths point
|
|
89
|
+
at `app/jobs`), plus `ShareCtor` / `ContextCtor`, error codes, log path. `createAsync({ subscriptionBroker })`
|
|
90
|
+
injects the progress broker (§4).
|
|
91
|
+
- **Share** — per-**process** DI (holds `subscriptionBroker` or `null`, `env`, `timber`, …).
|
|
92
|
+
- **Context** — per-**job** DI, created for each run and passed to `executeJob`.
|
|
93
|
+
- **RedisConnection** (`app/queue/RedisConnection.js`) —
|
|
94
|
+
`generateConnectionOptions()` for BullMQ (**`maxRetriesPerRequest: null` required**) and
|
|
95
|
+
`generatePubSubOptions()` for the broker. **API and Daemon must share one Redis.**
|
|
96
|
+
|
|
97
|
+
Details and the package-exports table are in [engine-and-infra.md](./references/engine-and-infra.md).
|
|
98
|
+
|
|
99
|
+
## 3. Entry points — the worker Daemon and the scheduler
|
|
100
|
+
|
|
101
|
+
**Worker Daemon** — `JobWorkersDaemon` auto-discovers every `BaseJobWorker` under `workersPath`
|
|
102
|
+
(`DeepBulkClassLoader`), binds each to its `jobName`, and installs graceful SIGINT/SIGTERM shutdown.
|
|
103
|
+
Two boot shapes:
|
|
104
|
+
|
|
105
|
+
- **Simple** (no progress broker): `JobWorkersDaemon.createAsync({ EngineCtor }).then(daemon => daemon.startDaemon())`.
|
|
106
|
+
- **With a broker** (this repo, `scripts/startJobDaemon.js`):
|
|
107
|
+
build a `SubscriptionBroker`, inject it via `Engine.createAsync({ subscriptionBroker })`, then
|
|
108
|
+
`JobWorkersDaemon.loadWorkerCtors({ engine })` → `.create({ engine, WorkerCtors }).startDaemon()`.
|
|
109
|
+
|
|
110
|
+
**Scheduler registration** is a **one-shot** script (`scripts/start-schedule.js`):
|
|
111
|
+
`SchedulerService.createAsync({ EngineCtor })` → `startAllSchedulers()` → exit. It writes repeatable
|
|
112
|
+
jobs to Redis; the Daemon consumes them. `stopAllSchedulers()` removes them without stopping the
|
|
113
|
+
Daemon.
|
|
114
|
+
|
|
115
|
+
**pm2** (`pm2.config.cjs`) runs `GraphQL API` and `Job Daemon`.
|
|
116
|
+
|
|
117
|
+
Both boot paths, cron **and interval** schedulers, and the start/stop scripts are in
|
|
118
|
+
[daemon-and-scheduler.md](./references/daemon-and-scheduler.md).
|
|
119
|
+
|
|
120
|
+
## 4. Integrating with subscriptions (progress → GraphQL)
|
|
121
|
+
|
|
122
|
+
A worker in the Daemon **publishes** progress on a `channel` namespaced by a `scope`; a GraphQL
|
|
123
|
+
subscription in the API process **subscribes** with the **same channel + scope**, over the shared
|
|
124
|
+
Redis PubSub broker.
|
|
125
|
+
|
|
126
|
+
- The Daemon injects the broker (§3, Path B); enqueue-only processes pass none → publish is a no-op.
|
|
127
|
+
- AI workers get this automatically from `BaseAgentJobWorker`; the app base
|
|
128
|
+
`BaseContentGenerationJobWorker.js` sets
|
|
129
|
+
`channel = 'reportProgress'` and `buildScope` (`accessToken` else `jobId`).
|
|
130
|
+
- The subscriber
|
|
131
|
+
(`OnReportProgressSubscriptionResolver.js`)
|
|
132
|
+
must match the channel and scope. This is why the public-lp queue body carries `accessToken` (§5).
|
|
133
|
+
|
|
134
|
+
The publish/subscribe wiring and checklist are in [subscriptions.md](./references/subscriptions.md).
|
|
135
|
+
|
|
136
|
+
## 5. Splitting queues
|
|
137
|
+
|
|
138
|
+
**One queue == one job directory == one Manifest `jobName`.** The repo splits the same content-generation
|
|
139
|
+
work into `content-generation-internal` (`{ jobId }`) and `content-generation-public-lp`
|
|
140
|
+
(`{ jobId, accessToken }`) so they scale and subscribe independently.
|
|
141
|
+
|
|
142
|
+
- **Share logic** via an app base worker, but **place that base OUTSIDE `workersPath`** — the Daemon
|
|
143
|
+
boots every `BaseJobWorker` under `app/jobs`, and an abstract base without a `jobName` crashes
|
|
144
|
+
startup. Only concrete workers go under `app/jobs/**`.
|
|
145
|
+
- Run a **subset** of queues per Daemon with `skipJobHash` (`{ [jobName]: true }`).
|
|
146
|
+
- Tune per queue: Dispatcher `optionHash` (attempts) + Worker `buildOptionHash()` (concurrency,
|
|
147
|
+
limiter).
|
|
148
|
+
|
|
149
|
+
Details and the directory diagram are in [queues.md](./references/queues.md).
|
|
150
|
+
|
|
151
|
+
## 6. Other building blocks
|
|
152
|
+
|
|
153
|
+
- **Cron / interval jobs** — `BaseCronJobScheduler` (`{ cronExpression }`) or `BaseIntervalJobScheduler`
|
|
154
|
+
(`{ millisecond, isImmediately }`), listed in `SchedulerService.collectScheduleInputs()` with a
|
|
155
|
+
`schedulerId` matching the scheduler class. See [daemon-and-scheduler.md](./references/daemon-and-scheduler.md).
|
|
156
|
+
- **Connection reuse** — `JobDispatcherProvider`
|
|
157
|
+
(`app/tools/JobDispatcherProvider.js`) caches one
|
|
158
|
+
Dispatcher per `DispatcherCtor` and dispatches with `keepsConnection: true`; the request Share
|
|
159
|
+
holds one, torn down on process exit. Prefer it over `Dispatcher.createAsync()` per request.
|
|
160
|
+
- **Retries & idempotency** — set `attempts` in `optionHash`; make `executeJob` idempotent (BullMQ may
|
|
161
|
+
re-run). Expensive AI jobs checkpoint to `content_generations.intermediate_steps_json` and
|
|
162
|
+
resume on retry.
|
|
163
|
+
- **Concurrency & rate limiting** — `buildOptionHash()` forwards `concurrency` + `limiter`
|
|
164
|
+
(`app/tools/ContentGenerationRateLimiter.js`).
|
|
165
|
+
- **Testing** — unit-test workers/dispatchers with the `hoc-jest` skill.
|
|
166
|
+
|
|
167
|
+
## Detail files
|
|
168
|
+
|
|
169
|
+
- [job-triple.md](./references/job-triple.md) — Manifest / Worker / Dispatcher in full, body schema,
|
|
170
|
+
lifecycle hooks, the return-value-in-Redis rule, base-app-dispatcher DRY, enqueue paths (§1)
|
|
171
|
+
- [engine-and-infra.md](./references/engine-and-infra.md) — Engine config, Share, Context,
|
|
172
|
+
RedisConnection, package exports (§2)
|
|
173
|
+
- [daemon-and-scheduler.md](./references/daemon-and-scheduler.md) — `JobWorkersDaemon` (both boot
|
|
174
|
+
paths), `scripts/*`, cron + interval schedulers, the scheduler service, pm2 (§3, §6)
|
|
175
|
+
- [subscriptions.md](./references/subscriptions.md) — progress publish/subscribe, channel + scope,
|
|
176
|
+
AI-worker plumbing (§4)
|
|
177
|
+
- [queues.md](./references/queues.md) — splitting queues, shared-base placement, `skipJobHash`,
|
|
178
|
+
per-queue tuning (§5)
|