@defra/lis-hubs-infra-core

中文文档
0.34.0发布于 2026/11/12OGL-UK-3.0ES Module构建来源已验证近 30 天下载 1.2万

Shared hub mechanics for livestock platform.

原始使用文档
文档目录19 节
  1. Installation
  2. Usage
  3. Logging
  4. Request context
  5. Calling other LIS services
  6. Hub proxy
  7. Circuit breaker
  8. Environment variables
  9. Prerequisites
  10. Setup
  11. Development
  12. Test
  13. Running in development
  14. Running tests
  15. Pipelines
  16. Branching policy
  17. Contributing to this project
  18. Licence
  19. About the licence

lis-hubs-infra-core

Part of the Livestock Information Service (LIS), which lets livestock keepers, owners, agents and delegates record and manage their animals.

@defra/lis-hubs-infra-core is a shared npm package with the runtime plumbing that every LIS hub and spoke needs: request context and correlation IDs, logging, calls to other LIS services with service-to-service tokens, and the hub's proxy to its spokes.

It deliberately does not cover authentication, sessions, roles or permissions (see lis-hubs-infra-access) or which modules a hub serves (see lis-hubs-infra-registry).

Used by:

Installation

npm install @defra/lis-hubs-infra-core @defra/lis-hubs-infra-registry

@defra/lis-hubs-infra-registry is a peer dependency, so the consuming app must install it too.

Usage

Logging

logger is a single, shared pino logger that writes ECS format for CDP's OpenSearch. Log through it everywhere, including in request handlers. Don't use hapi's request.logger.

import { logger } from '@defra/lis-hubs-infra-core'

logger.level = config.get('log.level')
logger.enabled = config.get('log.enabled')
logger.format = 'ecs' // or 'pretty-print' for local development
logger.serviceName = 'lis-apps-cattle-home' // defaults to SERVICE_NAME
logger.serviceVersion = config.get('serviceVersion') // defaults to SERVICE_VERSION
logger.context.hashSecret = config.get('log.hashSecret')

await server.register(logger.hapiPlugin) // request and response logging

logger.info('Holding loaded')

logger.context holds request-scoped values that are added to every log line in the request. Pass true as the third argument to hash a value with hashSecret, so you can correlate identifiers without logging them:

logger.context.set('cph', cph, true)

Request context

requestContext.plugin takes the correlation ID from the x-cdp-request-id header, or generates one, and keeps it for the rest of the request. Register it before any other plugin.

import { requestContext } from '@defra/lis-hubs-infra-core'

await server.register(requestContext.plugin)

requestContext.getHeaders() // { 'x-cdp-request-id': '...' }, for your own outbound calls

Calling other LIS services

Use createServiceClient to call another LIS service (for example a spoke's be4fe). It:

  • works out the service's base URL for the current environment (getServiceBaseUrl)
  • adds the correlation ID header
  • adds an Authorization: Bearer service token from AWS STS (GetWebIdentityToken), with the target service's name as the audience
  • sends x-api-key if you give it an apiKey
  • times out after 3 seconds by default (timeout, in milliseconds, is the total budget for the response headers and body; a timeout is thrown as a 504)
  • holds a circuit breaker for the service (circuitBreaker sets its failureThreshold and resetTimeout, or false disables it)
import { createServiceClient } from '@defra/lis-hubs-infra-core'

const be4fe = createServiceClient({
  environment,
  serviceName: 'lis-be4fe-cattle-home',
  port: 8087, // only used for 'local' and 'docker_compose'
  apiKey
})

export async function getHolding(cph) {
  const { payload } = await be4fe.get(`api/cphs/${encodeURIComponent(cph)}`)
  return payload
}

It returns get, post, put, patch and delete, each taking a path relative to the service's base URL and Wreck options. They are plain functions, so they can be destructured or passed around, and nothing the client holds can be reached or replaced from outside. If a service token can't be obtained, they throw ServiceTokenError; while the service's circuit is open, CircuitOpenError. Both carry a statusCode of 503. A call that fails any other way (the service can't be reached, times out, or answers with an error status) throws ServiceRequestError, which carries statusCode, serviceName, method, path and cause for code that catches the error. The shared logger emits only the error's type, message and stack, so a caller that wants them in a log line must put them in the message or logger.context.

Locally, lis-dev's lis-fake-sts service stands in for AWS STS. See Service-to-service auth in lis-dev.

Hub proxy

createProxyPlugin is used by hubs. It registers a proxy route for every module that @defra/lis-hubs-infra-registry lists for the hub, forwarding requests to that module's spoke and sending the spoke the signed-in user's hub JWT, taken from the hub session by getUserToken, in the x-lis-jwt-assertion request header (the JWT_ASSERTION_HEADER constant exported by this package). It forwards only the cookies_policy consent cookie (the COOKIES_POLICY_COOKIE_NAME constant exported by this package), so the spoke's layout can render the cookie banner state. It never sends the hub session cookie, any other cookie or the browser's Authorization header, and strips any client-supplied copy of that header. It sends the session's CSRF token, published by the lis-csrf plugin from @defra/lis-infra-ui-services/csrf at request.plugins['lis-csrf'].token, in the x-lis-csrf-token header, and strips any client-supplied copy. Its routes set plugins: { 'lis-csrf': { token: false } }: the hub checks a proxied request's origin, and the spoke checks the token in its body, which the hub streams through unread.

import { createProxyPlugin } from '@defra/lis-hubs-infra-core'
import { getHubJwt } from '@defra/lis-hubs-infra-access/authentication'

const proxy = createProxyPlugin({
  hubId: 'front-office',
  environment: config.get('environment'),
  getUserToken: getHubJwt,
  proxyTimeout: 30000, // optional, milliseconds to wait for a spoke's response headers; 30s by default
  circuitBreaker: { failureThreshold: 5, resetTimeout: 30000 } // optional, see below for the defaults
})

await server.register(proxy.plugin)

Each module is a Spoke, which owns the module's service name, base URL and circuit breaker and builds the h2o2 routes. A spoke that does not answer within proxyTimeout gets a 504; one that cannot be reached, a 502.

A spoke gets one route per registry mount (/holdings/{cph*3}/cattle/{path*}, /animals/cattle/{path*}), under which the request path is forwarded unchanged, so the spoke registers the same full patterns and sees the URL the browser asked for. hapi matches routes by specificity, not registration order, so /holdings/12/345/0001/cattle/register reaches cattle-register, not cattle-home.

Circuit breaker

CircuitBreaker protects calls to one downstream service, and is what createServiceClient and the hub proxy use. Only a transport failure (connection refused, timeout) counts against it; any response, whatever its status, proves the service is up. Outcomes of calls that started before the circuit opened are ignored.

  • Closed: calls go through. failureThreshold consecutive failures (5 by default) open it.
  • Open: calls fail fast with CircuitOpenError, a 503, for resetTimeout milliseconds (30 seconds by default). The UI catch-all renders the "service unavailable, try again later" page.
  • Half-open: one probe call goes through and the rest fail fast. Its success closes the circuit; its failure reopens it for another resetTimeout.

The state is per process, so each hub or spoke instance decides for itself. Every transition is logged through the shared logger: a warning when a circuit opens, info when it goes half-open and when the probe closes it.

import { CircuitBreaker } from '@defra/lis-hubs-infra-core'

const breaker = new CircuitBreaker({ name: 'lis-be4fe-cattle-home' })

breaker.assertCallAllowed() // throws CircuitOpenError while open; call immediately before the transport call
try {
  res = await Wreck.request('GET', url, options)
} catch (error) {
  breaker.recordFailure() // no response at all
  throw error
}
breaker.recordSuccess() // any response, whatever its status

Environment variables

The package reads these, falling back to them when the consumer doesn't set the values directly:

VariableUsed for
SERVICE_NAMElogger.serviceName
SERVICE_VERSIONlogger.serviceVersion
AWS_REGIONAWS STS region, for service tokens
AWS_ENDPOINT_URL_STSAWS STS endpoint override (lis-dev's fake STS)

On CDP the platform sets these. In lis-dev, the compose files set them.

Prerequisites

  • Node.js 24 (see .nvmrc, use nvm use)
  • To check changes against a consuming app: a local clone of lis-dev with its one-time setup done

Setup

Development

nvm use
npm install

Test

There are no tools to install beyond npm install. Tests use Vitest.

Running in development

This is a library, so it has no server of its own. To try a change in a consuming app without publishing, link the local copy into the lis-dev stack:

cd lis-dev
.bin/sideload link hubs/infra-core # every installed copy now points at this repo
.bin/sideload up front-office       # optional: run a consumer locally with hot reload
.bin/sideload unlink hubs/infra-core # when done

Running tests

npm test                 # unit tests
npm run test:coverage    # with coverage
npm run lint             # ESLint
npm run format:check     # Prettier

Before releasing a change, also run the tests of each consuming repo against the linked package.

Pipelines

Build, versioning and publishing run in GitHub Actions (.github/workflows) using Cake scripts (*.cake):

  • Pull request to main: validate (format, lint, test), Sonar analysis, version check
  • Push to a feature/ or hotfix/ branch: prerelease version and tag
  • Merge to main: release tag, then publish to npm

Versions come from git tags (SemVer). After a merge, wait for the publish job to finish before bumping the package in consuming repos.

Branching policy

The repo uses mainline development. Branch from main and name the branch:

  • feature/LREG-<ticket>-<short-kebab-description>
  • hotfix/LREG-<ticket>-<short-kebab-description>

LREG must be uppercase, because the GitHub ruleset rejects other branch names. Rebase onto main rather than merging main in.

Contributing to this project

  • Follow the Defra software development standards.
  • npm install sets up a pre-commit hook (Husky) that runs the security audit, format check and lint.
  • Open a pull request against main using the PR template. CI must pass and the Sonar quality gate must be green before merge.

Licence

THIS INFORMATION IS LICENSED UNDER THE CONDITIONS OF THE OPEN GOVERNMENT LICENCE found at:

http://www.nationalarchives.gov.uk/doc/open-government-licence/version/3

The following attribution statement MUST be cited in your products and applications when using this information.

Contains public sector information licensed under the Open Government licence v3

About the licence

The Open Government Licence (OGL) was developed by the Controller of His Majesty's Stationery Office (HMSO) to enable information providers in the public sector to license the use and re-use of their information under a common open licence.

It is designed to encourage use and re-use of information freely and flexibly, with only a few conditions.

版本与发布记录

@defra/lis-hubs-infra-core 共发布 89 个版本,首次发布于 2026/08/10;过去 12 个月发布了 89 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.34.0latest2026/11/12今天
0.34.0-lreg-945.alpha.2alpha2026/11/12今天
0.34.0-lreg-945.alpha.12026/11/12今天
0.33.72026/11/101 天前
0.33.62026/11/092 天前
0.33.52026/11/092 天前

关于 @defra/lis-hubs-infra-core 的常见问题

@defra/lis-hubs-infra-core 是什么?

Shared hub mechanics for livestock platform.

如何安装 @defra/lis-hubs-infra-core?

在项目目录运行 npm install @defra/lis-hubs-infra-core,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@defra/lis-hubs-infra-registry(>=0.13.0 <1.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@defra/lis-hubs-infra-core 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/defra__lis-hubs-infra-core 是否存在。

@defra/lis-hubs-infra-core 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@defra/lis-hubs-infra-core 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=24。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@defra/lis-hubs-infra-core 可以商用吗?

@defra/lis-hubs-infra-core 使用 OGL-UK-3.0 许可。声明的许可为 OGL-UK-3.0,请阅读许可原文确认使用条件。以上为概括,不构成法律意见,请以许可原文为准。

@defra/lis-hubs-infra-core 的下载量有多少?

根据 npm 官方下载统计,@defra/lis-hubs-infra-core 在 2026/10/12 – 2026/11/10 这 30 天内被下载 11,627 次,日均约 388 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@defra/lis-hubs-infra-core 还在维护吗?

最新版本 0.34.0 发布于 2026/11/12(今天);至今共发布 89 个版本,其中过去 12 个月发布了 89 个;首次发布于 2026/08/10。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。