@defra/lis-hubs-infra-core 0.29.0 → 0.30.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/README.md CHANGED
@@ -138,9 +138,14 @@ await server.register(proxy.plugin)
138
138
  ```
139
139
 
140
140
  Each module is a `Spoke`, which owns the module's service name, base URL and
141
- [circuit breaker](#circuit-breaker) and builds the h2o2 route. A spoke that does not answer within
141
+ [circuit breaker](#circuit-breaker) and builds the h2o2 routes. A spoke that does not answer within
142
142
  `proxyTimeout` gets a 504; one that cannot be reached, a 502.
143
143
 
144
+ A spoke gets one route per registry mount (`/holdings/{cph*3}/cattle/{path*}`,
145
+ `/animals/cattle/{path*}`), under which the request path is forwarded unchanged, so the spoke
146
+ registers the same full patterns and sees the URL the browser asked for. hapi matches routes by specificity, not registration order, so
147
+ `/holdings/12/345/0001/cattle/register` reaches cattle-register, not cattle-home.
148
+
144
149
  ### Circuit breaker
145
150
 
146
151
  `CircuitBreaker` protects calls to one downstream service, and is what `BaseClient` and the hub
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defra/lis-hubs-infra-core",
3
- "version": "0.29.0",
3
+ "version": "0.30.0",
4
4
  "description": "Shared hub mechanics for livestock platform.",
5
5
  "main": "src/index.js",
6
6
  "repository": {
@@ -41,7 +41,7 @@
41
41
  "pino-pretty": "13.1.3"
42
42
  },
43
43
  "devDependencies": {
44
- "@defra/lis-hubs-infra-registry": "^0.6.0",
44
+ "@defra/lis-hubs-infra-registry": "^0.13.0",
45
45
  "@defra/lis-infra-eslint-config": "^0.6.0",
46
46
  "@types/node": "^26.4.0",
47
47
  "@vitest/coverage-istanbul": "^4.1.10",
@@ -52,6 +52,6 @@
52
52
  "vitest": "^4.1.10"
53
53
  },
54
54
  "peerDependencies": {
55
- "@defra/lis-hubs-infra-registry": ">=0.6.0 <1.0.0"
55
+ "@defra/lis-hubs-infra-registry": ">=0.13.0 <1.0.0"
56
56
  }
57
57
  }
@@ -40,21 +40,20 @@ export function createProxyPlugin({
40
40
  const cookieNames = [hubJwtCookieName, ...forwardedCookieNames]
41
41
  const timeout = positiveInteger('proxyTimeout', proxyTimeout)
42
42
 
43
- // Longest path first, so a shorter prefix does not swallow a longer one.
44
- const spokes = getModulesForHub(hubId)
45
- .toSorted((a, b) => b.path.split('/').length - a.path.split('/').length)
46
- .map(
47
- ({ id: moduleName, path, port }) =>
48
- new Spoke({
49
- moduleName,
50
- path,
51
- port,
52
- environment,
53
- timeout,
54
- cookieNames,
55
- circuitBreaker
56
- })
57
- )
43
+ // One route per mount; hapi matches by specificity, so a verb spoke under
44
+ // a species home wins without any ordering here.
45
+ const spokes = getModulesForHub(hubId).map(
46
+ ({ id: moduleName, mounts, port }) =>
47
+ new Spoke({
48
+ moduleName,
49
+ mounts: Object.values(mounts),
50
+ port,
51
+ environment,
52
+ timeout,
53
+ cookieNames,
54
+ circuitBreaker
55
+ })
56
+ )
58
57
 
59
58
  return {
60
59
  plugin: {
@@ -62,7 +61,7 @@ export function createProxyPlugin({
62
61
  async register(server) {
63
62
  await server.register(h2o2)
64
63
  for (const spoke of spokes) {
65
- server.route(spoke.route)
64
+ server.route(spoke.routes)
66
65
  }
67
66
  }
68
67
  }
@@ -25,12 +25,23 @@ function createOptions(options = {}) {
25
25
  describe('createProxyPlugin()', () => {
26
26
  beforeEach(() => {
27
27
  mocks.getModulesForHub.mockReturnValue([
28
- { id: 'cattle-home', path: '/cattle', port: 3222 }
28
+ {
29
+ id: 'cattle-home',
30
+ path: '/holdings/{cph*3}/cattle',
31
+ mounts: {
32
+ holding: '/holdings/{cph*3}/cattle',
33
+ animal: '/animals/cattle'
34
+ },
35
+ port: 3222
36
+ }
29
37
  ])
30
- mocks.Spoke.mockImplementation(function ({ path }) {
31
- // The automock keeps the real class's `route` getter on the prototype.
32
- Object.defineProperty(this, 'route', {
33
- value: { method: '*', path: `${path}/{path*}` }
38
+ mocks.Spoke.mockImplementation(function ({ mounts }) {
39
+ // The automock keeps the real class's `routes` getter on the prototype.
40
+ Object.defineProperty(this, 'routes', {
41
+ value: mounts.map((prefix) => ({
42
+ method: '*',
43
+ path: `${prefix}/{path*}`
44
+ }))
34
45
  })
35
46
  })
36
47
  })
@@ -111,7 +122,7 @@ describe('createProxyPlugin()', () => {
111
122
  expect(mocks.Spoke).toHaveBeenCalledTimes(1)
112
123
  expect(mocks.Spoke).toHaveBeenCalledWith({
113
124
  moduleName: 'cattle-home',
114
- path: '/cattle',
125
+ mounts: ['/holdings/{cph*3}/cattle', '/animals/cattle'],
115
126
  port: 3222,
116
127
  environment: 'local',
117
128
  timeout: 30000,
@@ -134,7 +145,7 @@ describe('createProxyPlugin()', () => {
134
145
  // Assert
135
146
  expect(mocks.Spoke).toHaveBeenCalledWith({
136
147
  moduleName: 'cattle-home',
137
- path: '/cattle',
148
+ mounts: ['/holdings/{cph*3}/cattle', '/animals/cattle'],
138
149
  port: 3222,
139
150
  environment: 'prod',
140
151
  timeout: 5000,
@@ -156,30 +167,7 @@ describe('createProxyPlugin()', () => {
156
167
  expect(server.register).toHaveBeenCalledWith(h2o2)
157
168
  expect(server.route).toHaveBeenCalledTimes(1)
158
169
  expect(server.route).toHaveBeenCalledWith(
159
- mocks.Spoke.mock.instances[0].route
170
+ mocks.Spoke.mock.instances[0].routes
160
171
  )
161
172
  })
162
-
163
- test('sorts modules with the longest path first so a shorter prefix does not swallow a longer one', async () => {
164
- // Arrange
165
- mocks.getModulesForHub.mockReturnValue([
166
- { id: 'cattle-home', path: '/cattle', port: 3221 },
167
- { id: 'cattle-register', path: '/cattle/register', port: 3201 }
168
- ])
169
- const server = { route: vi.fn(), register: vi.fn() }
170
- const proxy = createProxyPlugin(createOptions({ hubId: 'front-office' }))
171
-
172
- // Act
173
- await proxy.plugin.register(server)
174
-
175
- // Assert
176
- expect(mocks.getModulesForHub).toHaveBeenCalledWith('front-office')
177
- expect(
178
- mocks.Spoke.mock.calls.map(([{ moduleName }]) => moduleName)
179
- ).toEqual(['cattle-register', 'cattle-home'])
180
- expect(server.route.mock.calls.map(([{ path }]) => path)).toEqual([
181
- '/cattle/register/{path*}',
182
- '/cattle/{path*}'
183
- ])
184
- })
185
173
  })
package/src/spoke.js CHANGED
@@ -26,12 +26,16 @@ function pickCookies(cookieHeader, names) {
26
26
  }
27
27
 
28
28
  /**
29
- * A module's app as a hub sees it: where it is, the path it is mounted at,
30
- * its circuit breaker, and the h2o2 route that proxies to it.
29
+ * A module's app as a hub sees it: where it is, the mounts it is served at,
30
+ * its circuit breaker, and the h2o2 routes that proxy to it.
31
+ *
32
+ * A mount is a URL pattern from the registry, such as
33
+ * `/holdings/{cph*3}/cattle`. Requests under a mount are forwarded with their
34
+ * path unchanged, so the spoke registers the same full patterns.
31
35
  */
32
36
  export class Spoke {
33
37
  #serviceName
34
- #path
38
+ #mounts
35
39
  #baseUri
36
40
  #timeout
37
41
  #cookieNames
@@ -40,7 +44,7 @@ export class Spoke {
40
44
  /**
41
45
  * @param {object} options
42
46
  * @param {string} options.moduleName - the module id from the registry
43
- * @param {string} options.path - the hub path prefix the spoke is mounted at
47
+ * @param {string[]} options.mounts - the mount patterns the hub serves the spoke at
44
48
  * @param {number} options.port - the spoke's port, used for local environments only
45
49
  * @param {string} options.environment
46
50
  * @param {number} options.timeout - milliseconds to wait for the spoke's response headers before answering 504
@@ -49,15 +53,18 @@ export class Spoke {
49
53
  */
50
54
  constructor({
51
55
  moduleName,
52
- path,
56
+ mounts,
53
57
  port,
54
58
  environment,
55
59
  timeout,
56
60
  cookieNames,
57
61
  circuitBreaker = {}
58
62
  }) {
63
+ if (!Array.isArray(mounts) || mounts.length === 0) {
64
+ throw new Error(`Spoke ${moduleName} has no mounts`)
65
+ }
59
66
  this.#serviceName = `lis-apps-${moduleName}`
60
- this.#path = path
67
+ this.#mounts = mounts
61
68
  this.#baseUri = getServiceBaseUrl(
62
69
  environment,
63
70
  this.#serviceName,
@@ -76,9 +83,9 @@ export class Spoke {
76
83
  return this.#serviceName
77
84
  }
78
85
 
79
- /** @returns {string} the hub path prefix the spoke is mounted at */
80
- get path() {
81
- return this.#path
86
+ /** @returns {string[]} the mount patterns the hub serves the spoke at */
87
+ get mounts() {
88
+ return this.#mounts
82
89
  }
83
90
 
84
91
  /** @returns {CircuitBreaker} */
@@ -87,12 +94,13 @@ export class Spoke {
87
94
  }
88
95
 
89
96
  /**
90
- * @returns {object} a hapi route proxying `${path}/{path*}` to the spoke
97
+ * @returns {object[]} a hapi route proxying `${mount}/{path*}` to the
98
+ * spoke for each mount
91
99
  */
92
- get route() {
93
- return {
100
+ get routes() {
101
+ return this.#mounts.map((mount) => ({
94
102
  method: '*',
95
- path: `${this.#path}/{path*}`,
103
+ path: `${mount}/{path*}`,
96
104
  handler: {
97
105
  proxy: {
98
106
  passThrough: true,
@@ -103,12 +111,15 @@ export class Spoke {
103
111
  this.onResponse(err, res, request, h)
104
112
  }
105
113
  }
106
- }
114
+ }))
107
115
  }
108
116
 
109
117
  /**
110
118
  * h2o2 mapUri. Fails fast with a 503 while the spoke's circuit is open.
111
119
  *
120
+ * The request path is forwarded unchanged, so the spoke sees the URL the
121
+ * browser asked for.
122
+ *
112
123
  * @param {object} request the hub request
113
124
  * @returns {Promise<{ uri: string, headers: object }>}
114
125
  * @throws {ServiceTokenError} naming the spoke, so the hub's error log says which one
@@ -119,10 +130,6 @@ export class Spoke {
119
130
  // Nothing may throw between here and h2o2 making the call, or a
120
131
  // half-open probe would never report back.
121
132
  this.#breaker.assertCallAllowed()
122
- const subPath = request.params.path ?? ''
123
- const uri =
124
- (subPath ? `${this.#baseUri}/${subPath}` : this.#baseUri) +
125
- request.url.search
126
133
 
127
134
  // passThrough copies request.headers itself and merges these headers on
128
135
  // top, so a header can only be withheld from the spoke by removing it
@@ -136,9 +143,8 @@ export class Spoke {
136
143
  delete request.headers.cookie
137
144
 
138
145
  return {
139
- uri,
146
+ uri: `${this.#baseUri}${request.path}${request.url.search}`,
140
147
  headers: {
141
- 'x-forwarded-prefix': this.#path,
142
148
  authorization: `Bearer ${serviceToken}`,
143
149
  ...(forwardedCookies && { cookie: forwardedCookies })
144
150
  }
package/src/spoke.test.js CHANGED
@@ -21,7 +21,7 @@ const mocks = {
21
21
  function createSpoke(options = {}) {
22
22
  return new Spoke({
23
23
  moduleName: 'cattle-home',
24
- path: '/cattle',
24
+ mounts: ['/holdings/{cph*3}/cattle', '/animals/cattle'],
25
25
  port: 3222,
26
26
  environment: 'local',
27
27
  timeout: 30000,
@@ -30,11 +30,18 @@ function createSpoke(options = {}) {
30
30
  })
31
31
  }
32
32
 
33
- function createRequest({ path = 'animals', search = '', headers = {} } = {}) {
33
+ function createRequest({
34
+ path = 'animals',
35
+ search = '',
36
+ headers = {},
37
+ prefix = '/holdings/12/345/0001/cattle'
38
+ } = {}) {
34
39
  const subPath = path ? `/${path}` : ''
40
+ const url = new URL(`http://hub.test${prefix}${subPath}${search}`)
35
41
  return {
36
42
  params: path ? { path } : {},
37
- url: new URL(`http://hub.test/cattle${subPath}${search}`),
43
+ path: url.pathname,
44
+ url,
38
45
  headers
39
46
  }
40
47
  }
@@ -64,9 +71,28 @@ describe('Spoke', () => {
64
71
 
65
72
  // Assert
66
73
  expect(spoke.serviceName).toBe('lis-apps-cattle-home')
67
- expect(spoke.path).toBe('/cattle')
74
+ expect(spoke.mounts).toEqual([
75
+ '/holdings/{cph*3}/cattle',
76
+ '/animals/cattle'
77
+ ])
68
78
  })
69
79
 
80
+ test.each([[[]], [undefined]])(
81
+ 'it rejects a module whose mounts are %j',
82
+ (mounts) => {
83
+ // Act
84
+ let error
85
+ try {
86
+ createSpoke({ mounts })
87
+ } catch (e) {
88
+ error = e
89
+ }
90
+
91
+ // Assert
92
+ expect(error.message).toBe('Spoke cattle-home has no mounts')
93
+ }
94
+ )
95
+
70
96
  test('it rejects an unsupported environment', () => {
71
97
  // Act
72
98
  let error
@@ -92,22 +118,72 @@ describe('Spoke', () => {
92
118
  expect(spoke.circuitBreaker).toBe(mocks.CircuitBreaker.mock.instances[0])
93
119
  })
94
120
 
95
- test('it proxies every method under its path with the timeout', () => {
121
+ test('it proxies every method under each mount with the timeout', () => {
96
122
  // Act
97
- const { route } = createSpoke({ timeout: 5000 })
123
+ const { routes } = createSpoke({ timeout: 5000 })
98
124
 
99
125
  // Assert
100
- expect(route).toMatchObject({ method: '*', path: '/cattle/{path*}' })
101
- expect(route.handler.proxy).toMatchObject({
102
- passThrough: true,
103
- xforward: true,
104
- timeout: 5000
105
- })
106
- expect(route.handler.proxy.mapUri).toBeTypeOf('function')
107
- expect(route.handler.proxy.onResponse).toBeTypeOf('function')
126
+ expect(routes.map(({ method, path }) => ({ method, path }))).toEqual([
127
+ { method: '*', path: '/holdings/{cph*3}/cattle/{path*}' },
128
+ { method: '*', path: '/animals/cattle/{path*}' }
129
+ ])
130
+ for (const route of routes) {
131
+ expect(route.handler.proxy).toMatchObject({
132
+ passThrough: true,
133
+ xforward: true,
134
+ timeout: 5000
135
+ })
136
+ expect(route.handler.proxy.mapUri).toBeTypeOf('function')
137
+ expect(route.handler.proxy.onResponse).toBeTypeOf('function')
138
+ }
108
139
  })
109
140
 
110
141
  describe('mapUri()', () => {
142
+ test('it forwards the request path unchanged', async () => {
143
+ // Arrange
144
+ const spoke = createSpoke()
145
+ const request = createRequest({ path: 'animals', search: '?page=2' })
146
+
147
+ // Act
148
+ const mapped = await spoke.routes[0].handler.proxy.mapUri(request)
149
+
150
+ // Assert
151
+ expect(mapped.uri).toBe(
152
+ 'http://localhost:3222/holdings/12/345/0001/cattle/animals?page=2'
153
+ )
154
+ })
155
+
156
+ test('it forwards the bare mount', async () => {
157
+ // Arrange
158
+ const spoke = createSpoke()
159
+ const request = createRequest({ path: '' })
160
+
161
+ // Act
162
+ const mapped = await spoke.routes[0].handler.proxy.mapUri(request)
163
+
164
+ // Assert
165
+ expect(mapped.uri).toBe(
166
+ 'http://localhost:3222/holdings/12/345/0001/cattle'
167
+ )
168
+ })
169
+
170
+ test('it forwards a request under a mount without parameters', async () => {
171
+ // Arrange
172
+ const spoke = createSpoke()
173
+ const request = createRequest({
174
+ prefix: '/animals/cattle',
175
+ path: 'UK123456700001'
176
+ })
177
+
178
+ // Act
179
+ const mapped = await spoke.routes[1].handler.proxy.mapUri(request)
180
+
181
+ // Assert
182
+ expect(mapped.uri).toBe(
183
+ 'http://localhost:3222/animals/cattle/UK123456700001'
184
+ )
185
+ })
186
+
111
187
  test.each([
112
188
  // Local proxying intentionally uses HTTP because the services run locally.
113
189
  ['local', 'http://localhost:3222'],
@@ -127,8 +203,12 @@ describe('Spoke', () => {
127
203
  const withoutPath = await spoke.mapUri(createRequest({ path: '' }))
128
204
 
129
205
  // Assert
130
- expect(withPath.uri).toBe(`${expectedBaseUri}/summary-data`)
131
- expect(withoutPath.uri).toBe(expectedBaseUri)
206
+ expect(withPath.uri).toBe(
207
+ `${expectedBaseUri}/holdings/12/345/0001/cattle/summary-data`
208
+ )
209
+ expect(withoutPath.uri).toBe(
210
+ `${expectedBaseUri}/holdings/12/345/0001/cattle`
211
+ )
132
212
  })
133
213
 
134
214
  test('it forwards the incoming query string', async () => {
@@ -142,7 +222,7 @@ describe('Spoke', () => {
142
222
 
143
223
  // Assert
144
224
  expect(mapped.uri).toBe(
145
- 'http://localhost:3222/animals?sort=sex&direction=asc&page=1'
225
+ 'http://localhost:3222/holdings/12/345/0001/cattle/animals?sort=sex&direction=asc&page=1'
146
226
  )
147
227
  })
148
228
 
@@ -154,12 +234,11 @@ describe('Spoke', () => {
154
234
  })
155
235
 
156
236
  // Act
157
- const mapped = await spoke.route.handler.proxy.mapUri(request)
237
+ const mapped = await spoke.routes[0].handler.proxy.mapUri(request)
158
238
 
159
239
  // Assert
160
240
  expect(mocks.getServiceToken).toHaveBeenCalledWith('lis-apps-cattle-home')
161
241
  expect(mapped.headers).toEqual({
162
- 'x-forwarded-prefix': '/cattle',
163
242
  authorization: 'Bearer service-token'
164
243
  })
165
244
  expect(request.headers).toEqual({ accept: 'text/html' })
@@ -233,7 +312,6 @@ describe('Spoke', () => {
233
312
 
234
313
  // Assert
235
314
  expect(mapped.headers).toEqual({
236
- 'x-forwarded-prefix': '/cattle',
237
315
  authorization: 'Bearer service-token'
238
316
  })
239
317
  expect(request.headers).toEqual({})
@@ -317,10 +395,10 @@ describe('Spoke', () => {
317
395
  })
318
396
 
319
397
  // Act
320
- const result = spoke.route.handler.proxy.onResponse(
398
+ const result = spoke.routes[0].handler.proxy.onResponse(
321
399
  upstreamError,
322
400
  undefined,
323
- { method: 'get', path: '/cattle/animals' },
401
+ { method: 'get', path: '/holdings/12/345/0001/cattle/animals' },
324
402
  {}
325
403
  )
326
404