@geekmidas/constructs 9.0.2 → 9.2.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.
Files changed (186) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/dist/{AWSScheduledFunction-Bn99MceY.d.cts → AWSScheduledFunction-B0thZRJU.d.cts} +2 -2
  3. package/dist/{AWSScheduledFunction-ysaCsdWx.d.mts.map → AWSScheduledFunction-B0thZRJU.d.cts.map} +1 -1
  4. package/dist/{AWSScheduledFunction-DbkDr8CA.cjs → AWSScheduledFunction-CKhVurOa.cjs} +16 -5
  5. package/dist/AWSScheduledFunction-CKhVurOa.cjs.map +1 -0
  6. package/dist/{AWSScheduledFunction-CufMMhGB.mjs → AWSScheduledFunction-CU7mMGFA.mjs} +15 -4
  7. package/dist/AWSScheduledFunction-CU7mMGFA.mjs.map +1 -0
  8. package/dist/{AWSScheduledFunction-ysaCsdWx.d.mts → AWSScheduledFunction-a6hRp3nk.d.mts} +2 -2
  9. package/dist/{AWSScheduledFunction-Bn99MceY.d.cts.map → AWSScheduledFunction-a6hRp3nk.d.mts.map} +1 -1
  10. package/dist/{Construct-vXMZJgRp.cjs → Construct-D09WUUOf.cjs} +13 -2
  11. package/dist/Construct-D09WUUOf.cjs.map +1 -0
  12. package/dist/{Construct-r0U2zBwW.mjs → Construct-D0uZvbr3.mjs} +13 -2
  13. package/dist/Construct-D0uZvbr3.mjs.map +1 -0
  14. package/dist/{Construct-_1wX7p_Y.d.cts → Construct-D_3yZ9m5.d.cts} +59 -4
  15. package/dist/Construct-D_3yZ9m5.d.cts.map +1 -0
  16. package/dist/{Construct-DCMuYOox.d.mts → Construct-DsqpiAym.d.mts} +59 -4
  17. package/dist/Construct-DsqpiAym.d.mts.map +1 -0
  18. package/dist/{Endpoint-DgfRslct.d.cts → Endpoint-BmnuNbF1.d.cts} +2 -2
  19. package/dist/Endpoint-BmnuNbF1.d.cts.map +1 -0
  20. package/dist/{Endpoint-CLPSIl6S.d.mts → Endpoint-DEydLuBs.d.mts} +3 -3
  21. package/dist/{Endpoint-CLPSIl6S.d.mts.map → Endpoint-DEydLuBs.d.mts.map} +1 -1
  22. package/dist/{HonoEndpointAdaptor-DJDT3PMx.mjs → HonoEndpointAdaptor-Dd-S7gV_.mjs} +18 -11
  23. package/dist/HonoEndpointAdaptor-Dd-S7gV_.mjs.map +1 -0
  24. package/dist/{HonoEndpointAdaptor-CkJENANP.cjs → HonoEndpointAdaptor-INisd3XZ.cjs} +19 -12
  25. package/dist/HonoEndpointAdaptor-INisd3XZ.cjs.map +1 -0
  26. package/dist/{Queue-HBDf0fqz.d.mts → Queue-Brw--scg.d.cts} +3 -3
  27. package/dist/{Queue-DaxjwmOQ.d.cts.map → Queue-Brw--scg.d.cts.map} +1 -1
  28. package/dist/{Queue-DaxjwmOQ.d.cts → Queue-D5z1bwFu.d.mts} +3 -3
  29. package/dist/{Queue-HBDf0fqz.d.mts.map → Queue-D5z1bwFu.d.mts.map} +1 -1
  30. package/dist/{Subscriber-D8Xm-86W.d.mts → Subscriber-CJ22tp8r.d.mts} +2 -2
  31. package/dist/{Subscriber-D8Xm-86W.d.mts.map → Subscriber-CJ22tp8r.d.mts.map} +1 -1
  32. package/dist/{Subscriber-B69ngPwl.d.cts → Subscriber-DvKSp0N4.d.cts} +2 -2
  33. package/dist/{Subscriber-B69ngPwl.d.cts.map → Subscriber-DvKSp0N4.d.cts.map} +1 -1
  34. package/dist/{Topic-DT10AqHk.d.mts → Topic-B-fxOsR2.d.mts} +2 -2
  35. package/dist/{Topic-C5ZMfveW.d.cts.map → Topic-B-fxOsR2.d.mts.map} +1 -1
  36. package/dist/{Topic-C5ZMfveW.d.cts → Topic-BMfrIFdX.d.cts} +2 -2
  37. package/dist/{Topic-DT10AqHk.d.mts.map → Topic-BMfrIFdX.d.cts.map} +1 -1
  38. package/dist/adaptors/aws.cjs +14 -7
  39. package/dist/adaptors/aws.cjs.map +1 -1
  40. package/dist/adaptors/aws.d.cts +6 -6
  41. package/dist/adaptors/aws.d.cts.map +1 -1
  42. package/dist/adaptors/aws.d.mts +8 -8
  43. package/dist/adaptors/aws.d.mts.map +1 -1
  44. package/dist/adaptors/aws.mjs +14 -7
  45. package/dist/adaptors/aws.mjs.map +1 -1
  46. package/dist/adaptors/hono.cjs +7 -6
  47. package/dist/adaptors/hono.d.cts +3 -3
  48. package/dist/adaptors/hono.d.cts.map +1 -1
  49. package/dist/adaptors/hono.d.mts +4 -4
  50. package/dist/adaptors/hono.d.mts.map +1 -1
  51. package/dist/adaptors/hono.mjs +7 -6
  52. package/dist/adaptors/testing.cjs +161 -126
  53. package/dist/adaptors/testing.cjs.map +1 -1
  54. package/dist/adaptors/testing.d.cts +7 -5
  55. package/dist/adaptors/testing.d.cts.map +1 -1
  56. package/dist/adaptors/testing.d.mts +8 -6
  57. package/dist/adaptors/testing.d.mts.map +1 -1
  58. package/dist/adaptors/testing.mjs +162 -127
  59. package/dist/adaptors/testing.mjs.map +1 -1
  60. package/dist/clone-I_WIpiFf.cjs +45 -0
  61. package/dist/clone-I_WIpiFf.cjs.map +1 -0
  62. package/dist/clone-pdXxc0t3.mjs +39 -0
  63. package/dist/clone-pdXxc0t3.mjs.map +1 -0
  64. package/dist/crons/index.cjs +14 -32
  65. package/dist/crons/index.cjs.map +1 -1
  66. package/dist/crons/index.d.cts +3 -3
  67. package/dist/crons/index.d.cts.map +1 -1
  68. package/dist/crons/index.d.mts +3 -3
  69. package/dist/crons/index.d.mts.map +1 -1
  70. package/dist/crons/index.mjs +14 -32
  71. package/dist/crons/index.mjs.map +1 -1
  72. package/dist/endpoints/index.cjs +74 -61
  73. package/dist/endpoints/index.cjs.map +1 -1
  74. package/dist/endpoints/index.d.cts +14 -6
  75. package/dist/endpoints/index.d.cts.map +1 -1
  76. package/dist/endpoints/index.d.mts +13 -5
  77. package/dist/endpoints/index.d.mts.map +1 -1
  78. package/dist/endpoints/index.mjs +74 -61
  79. package/dist/endpoints/index.mjs.map +1 -1
  80. package/dist/functions/index.cjs +3 -2
  81. package/dist/functions/index.d.cts +2 -2
  82. package/dist/functions/index.d.mts +2 -2
  83. package/dist/functions/index.mjs +3 -2
  84. package/dist/{functions-C8i1kCMM.cjs → functions-B3OFv3QV.cjs} +118 -45
  85. package/dist/functions-B3OFv3QV.cjs.map +1 -0
  86. package/dist/{functions-B-qt91O7.mjs → functions-DhkDodl0.mjs} +107 -46
  87. package/dist/functions-DhkDodl0.mjs.map +1 -0
  88. package/dist/{index-DP6fqv0I.d.mts → index-B8LNLQXD.d.mts} +8 -2
  89. package/dist/index-B8LNLQXD.d.mts.map +1 -0
  90. package/dist/{index-BVs9DvIj.d.cts → index-HWHPZv8u.d.cts} +12 -6
  91. package/dist/index-HWHPZv8u.d.cts.map +1 -0
  92. package/dist/index.cjs +1 -1
  93. package/dist/index.d.cts +2 -2
  94. package/dist/index.d.mts +4 -4
  95. package/dist/index.mjs +1 -1
  96. package/dist/{lazyAccessors-DfqZR6C4.mjs → lazyAccessors-DzxZVtPR.mjs} +3 -3
  97. package/dist/{lazyAccessors-DfqZR6C4.mjs.map → lazyAccessors-DzxZVtPR.mjs.map} +1 -1
  98. package/dist/{lazyAccessors-DmTG8sQH.cjs → lazyAccessors-iwvg1Pv4.cjs} +3 -3
  99. package/dist/{lazyAccessors-DmTG8sQH.cjs.map → lazyAccessors-iwvg1Pv4.cjs.map} +1 -1
  100. package/dist/monitors/index.cjs +56 -0
  101. package/dist/monitors/index.cjs.map +1 -0
  102. package/dist/monitors/index.d.cts +58 -0
  103. package/dist/monitors/index.d.cts.map +1 -0
  104. package/dist/monitors/index.d.mts +54 -0
  105. package/dist/monitors/index.d.mts.map +1 -0
  106. package/dist/monitors/index.mjs +55 -0
  107. package/dist/monitors/index.mjs.map +1 -0
  108. package/dist/{processAudits-CKjjivyz.cjs → processAudits-94Ar_EJF.cjs} +2 -2
  109. package/dist/{processAudits-CKjjivyz.cjs.map → processAudits-94Ar_EJF.cjs.map} +1 -1
  110. package/dist/{processAudits-ySnizdMG.mjs → processAudits-CwyaaSQc.mjs} +1 -1
  111. package/dist/{processAudits-ySnizdMG.mjs.map → processAudits-CwyaaSQc.mjs.map} +1 -1
  112. package/dist/{publisher-lFQleddL.cjs → publisher-BZgcrVPy.cjs} +1 -1
  113. package/dist/{publisher-lFQleddL.cjs.map → publisher-BZgcrVPy.cjs.map} +1 -1
  114. package/dist/{publisher-BrFOF847.mjs → publisher-CnpeMv-r.mjs} +1 -1
  115. package/dist/{publisher-BrFOF847.mjs.map → publisher-CnpeMv-r.mjs.map} +1 -1
  116. package/dist/queue/index.cjs +9 -22
  117. package/dist/queue/index.cjs.map +1 -1
  118. package/dist/queue/index.d.cts +4 -4
  119. package/dist/queue/index.d.cts.map +1 -1
  120. package/dist/queue/index.d.mts +2 -2
  121. package/dist/queue/index.d.mts.map +1 -1
  122. package/dist/queue/index.mjs +9 -22
  123. package/dist/queue/index.mjs.map +1 -1
  124. package/dist/subscribers/index.cjs +9 -22
  125. package/dist/subscribers/index.cjs.map +1 -1
  126. package/dist/subscribers/index.d.cts +5 -5
  127. package/dist/subscribers/index.d.cts.map +1 -1
  128. package/dist/subscribers/index.d.mts +3 -3
  129. package/dist/subscribers/index.d.mts.map +1 -1
  130. package/dist/subscribers/index.mjs +9 -22
  131. package/dist/subscribers/index.mjs.map +1 -1
  132. package/dist/{telemetry-3vdxGn4q.d.mts → telemetry-C--EgYVr.d.mts} +1 -1
  133. package/dist/{telemetry-3vdxGn4q.d.mts.map → telemetry-C--EgYVr.d.mts.map} +1 -1
  134. package/dist/topic/index.cjs +4 -7
  135. package/dist/topic/index.cjs.map +1 -1
  136. package/dist/topic/index.d.cts +2 -2
  137. package/dist/topic/index.d.cts.map +1 -1
  138. package/dist/topic/index.d.mts +2 -2
  139. package/dist/topic/index.d.mts.map +1 -1
  140. package/dist/topic/index.mjs +4 -7
  141. package/dist/topic/index.mjs.map +1 -1
  142. package/dist/{types-BDNGr7pv.d.mts → types-DNngH0fX.d.mts} +1 -1
  143. package/dist/{types-BDNGr7pv.d.mts.map → types-DNngH0fX.d.mts.map} +1 -1
  144. package/dist/types.d.mts +1 -1
  145. package/package.json +32 -22
  146. package/src/Construct.ts +16 -0
  147. package/src/__tests__/builder-reuse.spec.ts +587 -0
  148. package/src/__tests__/monitor.spec.ts +696 -0
  149. package/src/clone.ts +38 -0
  150. package/src/crons/CronBuilder.ts +35 -45
  151. package/src/crons/__tests__/Cron.spec.ts +10 -2
  152. package/src/crons/__tests__/CronBuilder.state-isolation.spec.ts +64 -18
  153. package/src/endpoints/AmazonApiGatewayEndpointAdaptor.ts +23 -2
  154. package/src/endpoints/EndpointBuilder.ts +61 -70
  155. package/src/endpoints/EndpointFactory.ts +31 -0
  156. package/src/endpoints/HonoEndpointAdaptor.ts +16 -1
  157. package/src/endpoints/TestEndpointAdaptor.ts +194 -150
  158. package/src/endpoints/__tests__/EndpointBuilder.audit.spec.ts +6 -3
  159. package/src/endpoints/__tests__/EndpointBuilder.responseType.spec.ts +4 -1
  160. package/src/endpoints/__tests__/EndpointBuilder.spec.ts +16 -8
  161. package/src/functions/AWSLambdaFunction.ts +28 -2
  162. package/src/functions/BaseFunctionBuilder.ts +33 -22
  163. package/src/functions/FunctionBuilder.ts +41 -51
  164. package/src/functions/TestFunctionAdaptor.ts +66 -31
  165. package/src/functions/__tests__/FunctionBuilder.state-isolation.spec.ts +55 -12
  166. package/src/index.ts +7 -0
  167. package/src/monitor.ts +161 -0
  168. package/src/monitors/heartbeat.ts +96 -0
  169. package/src/monitors/index.ts +6 -0
  170. package/src/queue/QueueBuilder.ts +22 -22
  171. package/src/subscribers/SubscriberBuilder.ts +19 -22
  172. package/src/topic/TopicBuilder.ts +9 -7
  173. package/tsdown.config.ts +1 -0
  174. package/dist/AWSScheduledFunction-CufMMhGB.mjs.map +0 -1
  175. package/dist/AWSScheduledFunction-DbkDr8CA.cjs.map +0 -1
  176. package/dist/Construct-DCMuYOox.d.mts.map +0 -1
  177. package/dist/Construct-_1wX7p_Y.d.cts.map +0 -1
  178. package/dist/Construct-r0U2zBwW.mjs.map +0 -1
  179. package/dist/Construct-vXMZJgRp.cjs.map +0 -1
  180. package/dist/Endpoint-DgfRslct.d.cts.map +0 -1
  181. package/dist/HonoEndpointAdaptor-CkJENANP.cjs.map +0 -1
  182. package/dist/HonoEndpointAdaptor-DJDT3PMx.mjs.map +0 -1
  183. package/dist/functions-B-qt91O7.mjs.map +0 -1
  184. package/dist/functions-C8i1kCMM.cjs.map +0 -1
  185. package/dist/index-BVs9DvIj.d.cts.map +0 -1
  186. package/dist/index-DP6fqv0I.d.mts.map +0 -1
@@ -0,0 +1,696 @@
1
+ import { EnvironmentParser } from '@geekmidas/envkit';
2
+ import { NotFoundError } from '@geekmidas/errors';
3
+ import { ServiceDiscovery } from '@geekmidas/services';
4
+ import { createMockContext, createMockV2Event } from '@geekmidas/testkit/aws';
5
+ import { Hono } from 'hono';
6
+ import { HttpResponse, http } from 'msw';
7
+ import { setupServer } from 'msw/node';
8
+ import {
9
+ afterAll,
10
+ afterEach,
11
+ beforeAll,
12
+ beforeEach,
13
+ describe,
14
+ expect,
15
+ it,
16
+ vi,
17
+ } from 'vitest';
18
+ import { z } from 'zod';
19
+ import { AWSScheduledFunction } from '../crons/AWSScheduledFunction';
20
+ import { CronBuilder } from '../crons/CronBuilder';
21
+ import { AmazonApiGatewayV2Endpoint } from '../endpoints/AmazonApiGatewayV2EndpointAdaptor';
22
+ import { EndpointFactory } from '../endpoints/EndpointFactory';
23
+ import { HonoEndpoint } from '../endpoints/HonoEndpointAdaptor';
24
+ import { TestEndpointAdaptor } from '../endpoints/TestEndpointAdaptor';
25
+ import { AWSLambdaFunction } from '../functions/AWSLambdaFunction';
26
+ import { FunctionBuilder } from '../functions/FunctionBuilder';
27
+ import { TestFunctionAdaptor } from '../functions/TestFunctionAdaptor';
28
+ import type { ConstructMonitor, MonitorService } from '../monitor';
29
+ import { heartbeat } from '../monitors';
30
+
31
+ const HEARTBEAT = 'https://heartbeat.test/api/v1/heartbeat/abc';
32
+
33
+ /** Every heartbeat request MSW saw, as `path`. */
34
+ const pings: string[] = [];
35
+
36
+ const server = setupServer(
37
+ http.get('https://heartbeat.test/*', ({ request }) => {
38
+ pings.push(new URL(request.url).pathname.replace('/api/v1/heartbeat', ''));
39
+ return new HttpResponse(null, { status: 200 });
40
+ }),
41
+ );
42
+
43
+ /** A monitor that writes down what it was told, in order. */
44
+ function recorder(serviceName = 'recorder') {
45
+ const calls: string[] = [];
46
+ const service = {
47
+ serviceName,
48
+ async register(): Promise<ConstructMonitor<string>> {
49
+ return {
50
+ async start() {
51
+ calls.push('start');
52
+ return 'run-1';
53
+ },
54
+ async success({ run, status }) {
55
+ calls.push(`success:${run}${status ? `:${status}` : ''}`);
56
+ },
57
+ async failure({ run, status, error }) {
58
+ calls.push(
59
+ `failure:${run}${status ? `:${status}` : ''}:${(error as Error).message}`,
60
+ );
61
+ },
62
+ };
63
+ },
64
+ } satisfies MonitorService;
65
+
66
+ return { calls, service };
67
+ }
68
+
69
+ const throwing = {
70
+ serviceName: 'throwing',
71
+ async register(): Promise<ConstructMonitor> {
72
+ return {
73
+ async start() {
74
+ throw new Error('start failed');
75
+ },
76
+ async success() {
77
+ throw new Error('success failed');
78
+ },
79
+ async failure() {
80
+ throw new Error('failure failed');
81
+ },
82
+ };
83
+ },
84
+ } satisfies MonitorService;
85
+
86
+ function discovery(env: Record<string, string> = {}) {
87
+ return ServiceDiscovery.getInstance(new EnvironmentParser(env));
88
+ }
89
+
90
+ beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
91
+ afterAll(() => server.close());
92
+ beforeEach(() => {
93
+ // Services are cached by name, so each test starts from its own env.
94
+ ServiceDiscovery.reset();
95
+ pings.length = 0;
96
+ });
97
+ afterEach(() => server.resetHandlers());
98
+
99
+ describe('heartbeat', () => {
100
+ it('pings the URL when a run succeeds', async () => {
101
+ const cron = new CronBuilder()
102
+ .input(z.object({}))
103
+ .schedule('rate(1 day)')
104
+ .monitor(heartbeat.betterStack())
105
+ .handle(async () => ({ ok: true }));
106
+
107
+ await new TestFunctionAdaptor(
108
+ cron,
109
+ discovery({ HEARTBEAT_URL: HEARTBEAT }),
110
+ ).invoke({ input: {}, services: {} });
111
+
112
+ expect(pings).toEqual(['/abc']);
113
+ });
114
+
115
+ it('pings the failure URL and rethrows when a run fails', async () => {
116
+ const cron = new CronBuilder()
117
+ .input(z.object({}))
118
+ .schedule('rate(1 day)')
119
+ .monitor(heartbeat.betterStack())
120
+ .handle(async () => {
121
+ throw new Error('boom');
122
+ });
123
+
124
+ await expect(
125
+ new TestFunctionAdaptor(
126
+ cron,
127
+ discovery({ HEARTBEAT_URL: HEARTBEAT }),
128
+ ).invoke({ input: {}, services: {} }),
129
+ ).rejects.toThrow('boom');
130
+
131
+ expect(pings).toEqual(['/abc/fail']);
132
+ });
133
+
134
+ it('pings start before success for providers that take one', async () => {
135
+ const fn = new FunctionBuilder()
136
+ .input(z.object({}))
137
+ .monitor(heartbeat.healthchecks())
138
+ .handle(async () => ({}));
139
+
140
+ await new TestFunctionAdaptor(
141
+ fn,
142
+ discovery({ HEARTBEAT_URL: HEARTBEAT }),
143
+ ).invoke({ input: {}, services: {} });
144
+
145
+ expect(pings).toEqual(['/abc/start', '/abc']);
146
+ });
147
+
148
+ it('skips the heartbeat but still runs when its env var is missing', async () => {
149
+ const cron = new CronBuilder()
150
+ .input(z.object({}))
151
+ .schedule('rate(1 day)')
152
+ .monitor(heartbeat.betterStack())
153
+ .output(z.object({ ok: z.boolean() }))
154
+ .handle(async () => ({ ok: true }));
155
+
156
+ const output = await new TestFunctionAdaptor(cron, discovery()).invoke({
157
+ input: {},
158
+ services: {},
159
+ });
160
+
161
+ expect(output).toEqual({ ok: true });
162
+ expect(pings).toEqual([]);
163
+ });
164
+
165
+ it('reads the env var it was given', async () => {
166
+ const cron = new CronBuilder()
167
+ .input(z.object({}))
168
+ .schedule('rate(1 day)')
169
+ .monitor(heartbeat.betterStack('NIGHTLY_HEARTBEAT_URL'))
170
+ .handle(async () => ({}));
171
+
172
+ await new TestFunctionAdaptor(
173
+ cron,
174
+ discovery({ NIGHTLY_HEARTBEAT_URL: `${HEARTBEAT}/nightly` }),
175
+ ).invoke({ input: {}, services: {} });
176
+
177
+ expect(pings).toEqual(['/abc/nightly']);
178
+ });
179
+
180
+ it('does not fail the run when the provider is down', async () => {
181
+ server.use(
182
+ http.get('https://heartbeat.test/*', () =>
183
+ HttpResponse.json({ error: 'down' }, { status: 503 }),
184
+ ),
185
+ );
186
+ const cron = new CronBuilder()
187
+ .input(z.object({}))
188
+ .schedule('rate(1 day)')
189
+ .monitor(heartbeat.betterStack())
190
+ .output(z.object({ ok: z.boolean() }))
191
+ .handle(async () => ({ ok: true }));
192
+
193
+ const output = await new TestFunctionAdaptor(
194
+ cron,
195
+ discovery({ HEARTBEAT_URL: HEARTBEAT }),
196
+ ).invoke({ input: {}, services: {} });
197
+
198
+ expect(output).toEqual({ ok: true });
199
+ });
200
+
201
+ it('declares its env var as required', async () => {
202
+ const cron = new CronBuilder()
203
+ .input(z.object({}))
204
+ .schedule('rate(1 day)')
205
+ .monitor(heartbeat.betterStack('NIGHTLY_HEARTBEAT_URL'))
206
+ .handle(async () => ({}));
207
+
208
+ const environment = await cron.getEnvironment({ markOptional: true });
209
+
210
+ expect(environment).toContain('NIGHTLY_HEARTBEAT_URL');
211
+ expect(environment).not.toContain('NIGHTLY_HEARTBEAT_URL?');
212
+ });
213
+ });
214
+
215
+ describe('duplicate monitors', () => {
216
+ it('refuses two heartbeats reading the same env var', () => {
217
+ expect(() =>
218
+ new CronBuilder()
219
+ .monitor(heartbeat.betterStack())
220
+ .monitor(heartbeat.healthchecks()),
221
+ ).toThrow('Monitor "heartbeat:HEARTBEAT_URL" is already set');
222
+ });
223
+
224
+ it('refuses an endpoint repeating its factory’s monitor', () => {
225
+ const e = new EndpointFactory().monitor(heartbeat.betterStack());
226
+
227
+ expect(() => e.get('/x').monitor(heartbeat.betterStack())).toThrow(
228
+ 'is already set',
229
+ );
230
+ });
231
+
232
+ it('refuses the same monitor twice on a factory', () => {
233
+ expect(() =>
234
+ new EndpointFactory()
235
+ .monitor(heartbeat.betterStack())
236
+ .monitor(heartbeat.healthchecks()),
237
+ ).toThrow('is already set');
238
+ });
239
+
240
+ it('allows two heartbeats on their own env vars', async () => {
241
+ const fn = new FunctionBuilder()
242
+ .input(z.object({}))
243
+ .monitor(heartbeat.betterStack('BETTER_STACK_HEARTBEAT_URL'))
244
+ .monitor(heartbeat.healthchecks('HEALTHCHECKS_HEARTBEAT_URL'))
245
+ .handle(async () => ({}));
246
+
247
+ await new TestFunctionAdaptor(
248
+ fn,
249
+ discovery({
250
+ BETTER_STACK_HEARTBEAT_URL: `${HEARTBEAT}/bs`,
251
+ HEALTHCHECKS_HEARTBEAT_URL: `${HEARTBEAT}/hc`,
252
+ }),
253
+ ).invoke({ input: {}, services: {} });
254
+
255
+ // Each provider gets its own pings, in its own URL shape.
256
+ expect(pings.sort()).toEqual(['/abc/bs', '/abc/hc', '/abc/hc/start']);
257
+ });
258
+ });
259
+
260
+ describe('functions and crons', () => {
261
+ it('report start, then success with what start returned', async () => {
262
+ const { calls, service } = recorder();
263
+ const fn = new FunctionBuilder()
264
+ .input(z.object({}))
265
+ .monitor(service)
266
+ .handle(async () => ({}));
267
+
268
+ await new TestFunctionAdaptor(fn, discovery()).invoke({
269
+ input: {},
270
+ services: {},
271
+ });
272
+
273
+ expect(calls).toEqual(['start', 'success:run-1']);
274
+ });
275
+
276
+ it('tell every monitor, in the AWS Lambda handler', async () => {
277
+ const one = recorder('one');
278
+ const two = recorder('two');
279
+ const cron = new CronBuilder()
280
+ .input(z.object({}))
281
+ .schedule('rate(1 day)')
282
+ .monitor(one.service)
283
+ .monitor(two.service)
284
+ .handle(async () => {
285
+ throw new Error('boom');
286
+ });
287
+ discovery();
288
+
289
+ const handler = new AWSScheduledFunction(new EnvironmentParser({}), cron)
290
+ .handler;
291
+
292
+ // The handler rethrows the wrapped error; monitors get the original.
293
+ await expect(handler({}, createMockContext(), vi.fn())).rejects.toThrow();
294
+ expect(one.calls).toEqual(['start', 'failure:run-1:boom']);
295
+ expect(two.calls).toEqual(['start', 'failure:run-1:boom']);
296
+ });
297
+
298
+ it('ignore a monitor that throws', async () => {
299
+ const fn = new FunctionBuilder()
300
+ .input(z.object({}))
301
+ .monitor(throwing)
302
+ .output(z.object({ ok: z.boolean() }))
303
+ .handle(async () => ({ ok: true }));
304
+
305
+ const output = await new TestFunctionAdaptor(fn, discovery()).invoke({
306
+ input: {},
307
+ services: {},
308
+ });
309
+
310
+ expect(output).toEqual({ ok: true });
311
+ });
312
+
313
+ it('inherit a shared base’s monitor, and add their own', async () => {
314
+ const shared = recorder('shared');
315
+ const own = recorder('own');
316
+ const base = new CronBuilder().monitor(shared.service);
317
+
318
+ const nightly = base
319
+ .schedule('rate(1 day)')
320
+ .monitor(own.service)
321
+ .handle(async () => ({}));
322
+ const hourly = base.schedule('rate(1 hour)').handle(async () => ({}));
323
+
324
+ expect(nightly.monitors.map((m) => m.serviceName)).toEqual([
325
+ 'shared',
326
+ 'own',
327
+ ]);
328
+ expect(hourly.monitors.map((m) => m.serviceName)).toEqual(['shared']);
329
+ });
330
+ });
331
+
332
+ describe('endpoints', () => {
333
+ function api(monitor: MonitorService) {
334
+ const e = new EndpointFactory().monitor(monitor);
335
+ return {
336
+ ok: e.get('/ok').handle(async () => ({ ok: true })),
337
+ missing: e.get('/missing').handle(async () => {
338
+ throw new NotFoundError('nope');
339
+ }),
340
+ broken: e.get('/broken').handle(async () => {
341
+ throw new Error('boom');
342
+ }),
343
+ };
344
+ }
345
+
346
+ it('inherit the factory’s monitor, and add their own', () => {
347
+ const shared = recorder('shared');
348
+ const own = recorder('own');
349
+ const e = new EndpointFactory().monitor(shared.service);
350
+
351
+ const withOwn = e
352
+ .get('/a')
353
+ .monitor(own.service)
354
+ .handle(async () => ({}));
355
+ const without = e.get('/b').handle(async () => ({}));
356
+
357
+ expect(withOwn.monitors.map((m) => m.serviceName)).toEqual([
358
+ 'shared',
359
+ 'own',
360
+ ]);
361
+ expect(without.monitors.map((m) => m.serviceName)).toEqual(['shared']);
362
+ });
363
+
364
+ describe('TestEndpointAdaptor', () => {
365
+ const request = (endpoint: any) =>
366
+ new TestEndpointAdaptor(endpoint, discovery()).fullRequest({
367
+ services: {},
368
+ headers: {},
369
+ } as any);
370
+
371
+ it('reports a 2xx as a success', async () => {
372
+ const { calls, service } = recorder();
373
+ await request(api(service).ok);
374
+ expect(calls).toEqual(['start', 'success:run-1:200']);
375
+ });
376
+
377
+ it('reports a 4xx as a success: the caller erred, not the service', async () => {
378
+ const { calls, service } = recorder();
379
+ await expect(request(api(service).missing)).rejects.toThrow('nope');
380
+ expect(calls).toEqual(['start', 'success:run-1:404']);
381
+ });
382
+
383
+ it('reports a thrown error as a 500 failure', async () => {
384
+ const { calls, service } = recorder();
385
+ await expect(request(api(service).broken)).rejects.toThrow('boom');
386
+ expect(calls).toEqual(['start', 'failure:run-1:500:boom']);
387
+ });
388
+ });
389
+
390
+ describe('Hono', () => {
391
+ async function serve(endpoint: any, path: string) {
392
+ const app = new Hono();
393
+ new HonoEndpoint(endpoint).addRoute(discovery(), app);
394
+ return app.request(path);
395
+ }
396
+
397
+ it('reports a 2xx as a success, without holding the response', async () => {
398
+ const { calls, service } = recorder();
399
+ const response = await serve(api(service).ok, '/ok');
400
+
401
+ expect(response.status).toBe(200);
402
+ await vi.waitFor(() =>
403
+ expect(calls).toEqual(['start', 'success:run-1:200']),
404
+ );
405
+ });
406
+
407
+ it('reports a 4xx as a success', async () => {
408
+ const { calls, service } = recorder();
409
+ const response = await serve(api(service).missing, '/missing');
410
+
411
+ expect(response.status).toBe(404);
412
+ await vi.waitFor(() =>
413
+ expect(calls).toEqual(['start', 'success:run-1:404']),
414
+ );
415
+ });
416
+
417
+ it('reports a 5xx as a failure, with the error', async () => {
418
+ const { calls, service } = recorder();
419
+ const response = await serve(api(service).broken, '/broken');
420
+
421
+ expect(response.status).toBe(500);
422
+ await vi.waitFor(() =>
423
+ expect(calls).toEqual(['start', 'failure:run-1:500:boom']),
424
+ );
425
+ });
426
+ });
427
+
428
+ describe('API Gateway', () => {
429
+ async function invoke(endpoint: any) {
430
+ discovery();
431
+ const handler = new AmazonApiGatewayV2Endpoint(
432
+ new EnvironmentParser({}),
433
+ endpoint,
434
+ ).handler;
435
+ return handler(createMockV2Event(), createMockContext(), vi.fn());
436
+ }
437
+
438
+ it('reports a 2xx as a success', async () => {
439
+ const { calls, service } = recorder();
440
+ const response: any = await invoke(api(service).ok);
441
+
442
+ expect(response.statusCode).toBe(200);
443
+ expect(calls).toEqual(['start', 'success:run-1:200']);
444
+ });
445
+
446
+ it('reports a 4xx as a success', async () => {
447
+ const { calls, service } = recorder();
448
+ const response: any = await invoke(api(service).missing);
449
+
450
+ expect(response.statusCode).toBe(404);
451
+ expect(calls).toEqual(['start', 'success:run-1:404']);
452
+ });
453
+
454
+ it('reports a 5xx as a failure, with the error', async () => {
455
+ const { calls, service } = recorder();
456
+ const response: any = await invoke(api(service).broken);
457
+
458
+ expect(response.statusCode).toBe(500);
459
+ expect(calls).toEqual(['start', 'failure:run-1:500:boom']);
460
+ });
461
+ });
462
+ });
463
+
464
+ /**
465
+ * The heartbeat over real HTTP (MSW), on every construct and runtime: what
466
+ * actually reaches the provider when a run succeeds or fails.
467
+ */
468
+ describe('heartbeat requests, per construct', () => {
469
+ const env = { HEARTBEAT_URL: HEARTBEAT };
470
+
471
+ function endpoints() {
472
+ const e = new EndpointFactory().monitor(heartbeat.betterStack());
473
+ return {
474
+ ok: e.get('/ok').handle(async () => ({ ok: true })),
475
+ missing: e.get('/missing').handle(async () => {
476
+ throw new NotFoundError('nope');
477
+ }),
478
+ broken: e.get('/broken').handle(async () => {
479
+ throw new Error('boom');
480
+ }),
481
+ };
482
+ }
483
+
484
+ describe('function, AWS Lambda handler', () => {
485
+ const invoke = (fn: any) =>
486
+ new AWSLambdaFunction(new EnvironmentParser(env), fn).handler(
487
+ {},
488
+ createMockContext(),
489
+ vi.fn(),
490
+ );
491
+
492
+ it('sends the success ping', async () => {
493
+ await invoke(
494
+ new FunctionBuilder()
495
+ .monitor(heartbeat.betterStack())
496
+ .handle(async () => ({})),
497
+ );
498
+ expect(pings).toEqual(['/abc']);
499
+ });
500
+
501
+ it('sends the failure ping', async () => {
502
+ await expect(
503
+ invoke(
504
+ new FunctionBuilder()
505
+ .monitor(heartbeat.betterStack())
506
+ .handle(async () => {
507
+ throw new Error('boom');
508
+ }),
509
+ ),
510
+ ).rejects.toThrow();
511
+ expect(pings).toEqual(['/abc/fail']);
512
+ });
513
+ });
514
+
515
+ describe('cron, AWS Lambda handler', () => {
516
+ const invoke = (cron: any) =>
517
+ new AWSScheduledFunction(new EnvironmentParser(env), cron).handler(
518
+ {},
519
+ createMockContext(),
520
+ vi.fn(),
521
+ );
522
+
523
+ it('sends the success ping', async () => {
524
+ await invoke(
525
+ new CronBuilder()
526
+ .schedule('rate(1 day)')
527
+ .monitor(heartbeat.betterStack())
528
+ .handle(async () => ({})),
529
+ );
530
+ expect(pings).toEqual(['/abc']);
531
+ });
532
+
533
+ it('sends the failure ping', async () => {
534
+ await expect(
535
+ invoke(
536
+ new CronBuilder()
537
+ .schedule('rate(1 day)')
538
+ .monitor(heartbeat.betterStack())
539
+ .handle(async () => {
540
+ throw new Error('boom');
541
+ }),
542
+ ),
543
+ ).rejects.toThrow();
544
+ expect(pings).toEqual(['/abc/fail']);
545
+ });
546
+
547
+ it('sends the start ping first, for Healthchecks.io', async () => {
548
+ await invoke(
549
+ new CronBuilder()
550
+ .schedule('rate(1 day)')
551
+ .monitor(heartbeat.healthchecks())
552
+ .handle(async () => ({})),
553
+ );
554
+ expect(pings).toEqual(['/abc/start', '/abc']);
555
+ });
556
+
557
+ it('sends one ping per run, from a shared base', async () => {
558
+ const base = new CronBuilder().monitor(heartbeat.betterStack());
559
+
560
+ await invoke(base.schedule('rate(1 day)').handle(async () => ({})));
561
+ await invoke(base.schedule('rate(1 hour)').handle(async () => ({})));
562
+
563
+ expect(pings).toEqual(['/abc', '/abc']);
564
+ });
565
+ });
566
+
567
+ describe('endpoint, TestEndpointAdaptor', () => {
568
+ const request = (endpoint: any) =>
569
+ new TestEndpointAdaptor(endpoint, discovery(env)).fullRequest({
570
+ services: {},
571
+ headers: {},
572
+ } as any);
573
+
574
+ it('sends the success ping on a 2xx', async () => {
575
+ await request(endpoints().ok);
576
+ expect(pings).toEqual(['/abc']);
577
+ });
578
+
579
+ it('sends the success ping on a 4xx', async () => {
580
+ await expect(request(endpoints().missing)).rejects.toThrow();
581
+ expect(pings).toEqual(['/abc']);
582
+ });
583
+
584
+ it('sends the failure ping on a 5xx', async () => {
585
+ await expect(request(endpoints().broken)).rejects.toThrow();
586
+ expect(pings).toEqual(['/abc/fail']);
587
+ });
588
+ });
589
+
590
+ describe('endpoint, Hono', () => {
591
+ async function serve(endpoint: any, path: string) {
592
+ const app = new Hono();
593
+ new HonoEndpoint(endpoint).addRoute(discovery(env), app);
594
+ return app.request(path);
595
+ }
596
+
597
+ // Hono does not wait on the ping, so each test waits for it to land.
598
+ it('sends the success ping on a 2xx', async () => {
599
+ expect((await serve(endpoints().ok, '/ok')).status).toBe(200);
600
+ await vi.waitFor(() => expect(pings).toEqual(['/abc']));
601
+ });
602
+
603
+ it('sends the success ping on a 4xx', async () => {
604
+ expect((await serve(endpoints().missing, '/missing')).status).toBe(404);
605
+ await vi.waitFor(() => expect(pings).toEqual(['/abc']));
606
+ });
607
+
608
+ it('sends the failure ping on a 5xx', async () => {
609
+ expect((await serve(endpoints().broken, '/broken')).status).toBe(500);
610
+ await vi.waitFor(() => expect(pings).toEqual(['/abc/fail']));
611
+ });
612
+ });
613
+
614
+ describe('endpoint, API Gateway', () => {
615
+ const invoke = (endpoint: any) =>
616
+ new AmazonApiGatewayV2Endpoint(
617
+ new EnvironmentParser(env),
618
+ endpoint,
619
+ ).handler(createMockV2Event(), createMockContext(), vi.fn()) as Promise<{
620
+ statusCode: number;
621
+ }>;
622
+
623
+ // Awaited before the response returns: the ping is there already.
624
+ it('sends the success ping on a 2xx', async () => {
625
+ expect((await invoke(endpoints().ok)).statusCode).toBe(200);
626
+ expect(pings).toEqual(['/abc']);
627
+ });
628
+
629
+ it('sends the success ping on a 4xx', async () => {
630
+ expect((await invoke(endpoints().missing)).statusCode).toBe(404);
631
+ expect(pings).toEqual(['/abc']);
632
+ });
633
+
634
+ it('sends the failure ping on a 5xx', async () => {
635
+ expect((await invoke(endpoints().broken)).statusCode).toBe(500);
636
+ expect(pings).toEqual(['/abc/fail']);
637
+ });
638
+ });
639
+ });
640
+
641
+ describe('getMonitoring', () => {
642
+ it('records each monitor for the manifest', () => {
643
+ const cron = new CronBuilder()
644
+ .schedule('rate(1 day)')
645
+ .monitor(heartbeat.betterStack('MONITORING_URL'))
646
+ .monitor(heartbeat.healthchecks('HEALTHCHECKS_URL'))
647
+ .handle(async () => ({}));
648
+
649
+ expect(cron.getMonitoring()).toEqual([
650
+ { type: 'heartbeat', provider: 'betterStack', env: 'MONITORING_URL' },
651
+ { type: 'heartbeat', provider: 'healthchecks', env: 'HEALTHCHECKS_URL' },
652
+ ]);
653
+ });
654
+
655
+ it('records a custom heartbeat without a provider, on its default env var', () => {
656
+ const fn = new FunctionBuilder()
657
+ .monitor(heartbeat())
658
+ .handle(async () => ({}));
659
+
660
+ expect(fn.getMonitoring()).toEqual([
661
+ { type: 'heartbeat', env: 'HEARTBEAT_URL' },
662
+ ]);
663
+ });
664
+
665
+ it('records a hand-written monitor by its service name', () => {
666
+ const fn = new FunctionBuilder()
667
+ .monitor({
668
+ serviceName: 'errors',
669
+ async register() {
670
+ return { async success() {}, async failure() {} };
671
+ },
672
+ })
673
+ .handle(async () => ({}));
674
+
675
+ expect(fn.getMonitoring()).toEqual([{ type: 'errors' }]);
676
+ });
677
+
678
+ it('records an endpoint’s monitors inherited from its factory', () => {
679
+ const endpoint = new EndpointFactory()
680
+ .monitor(heartbeat.betterStack())
681
+ .get('/health')
682
+ .handle(async () => ({}));
683
+
684
+ expect(endpoint.getMonitoring()).toEqual([
685
+ { type: 'heartbeat', provider: 'betterStack', env: 'HEARTBEAT_URL' },
686
+ ]);
687
+ });
688
+
689
+ it('records nothing for a construct without monitors', () => {
690
+ const cron = new CronBuilder()
691
+ .schedule('rate(1 day)')
692
+ .handle(async () => ({}));
693
+
694
+ expect(cron.getMonitoring()).toBeUndefined();
695
+ });
696
+ });