@geekmidas/constructs 9.3.0 → 9.5.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 (177) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/dist/{AWSScheduledFunction-Dg6TPIxn.d.mts → AWSScheduledFunction--49dTSUQ.d.mts} +8 -2
  3. package/dist/AWSScheduledFunction--49dTSUQ.d.mts.map +1 -0
  4. package/dist/{AWSScheduledFunction-CU7mMGFA.mjs → AWSScheduledFunction-BXmRm9W6.mjs} +4 -3
  5. package/dist/{AWSScheduledFunction-CU7mMGFA.mjs.map → AWSScheduledFunction-BXmRm9W6.mjs.map} +1 -1
  6. package/dist/{AWSScheduledFunction-CKhVurOa.cjs → AWSScheduledFunction-C-JBSNak.cjs} +6 -5
  7. package/dist/{AWSScheduledFunction-CKhVurOa.cjs.map → AWSScheduledFunction-C-JBSNak.cjs.map} +1 -1
  8. package/dist/{AWSScheduledFunction-DAGP_vz5.d.cts → AWSScheduledFunction-D0_HIJj8.d.cts} +8 -2
  9. package/dist/AWSScheduledFunction-D0_HIJj8.d.cts.map +1 -0
  10. package/dist/{Construct-D_3yZ9m5.d.cts → Construct-BEh2DSMe.d.cts} +7 -13
  11. package/dist/Construct-BEh2DSMe.d.cts.map +1 -0
  12. package/dist/{Construct-D09WUUOf.cjs → Construct-Cf_0pAvo.cjs} +2 -10
  13. package/dist/Construct-Cf_0pAvo.cjs.map +1 -0
  14. package/dist/{Construct-D0uZvbr3.mjs → Construct-D5LZBFhb.mjs} +3 -11
  15. package/dist/Construct-D5LZBFhb.mjs.map +1 -0
  16. package/dist/{Construct-DsqpiAym.d.mts → Construct-qnOnQTcP.d.mts} +7 -13
  17. package/dist/Construct-qnOnQTcP.d.mts.map +1 -0
  18. package/dist/{Endpoint-CxBdXNZm.d.cts → Endpoint-DIQblT3d.d.cts} +2 -2
  19. package/dist/Endpoint-DIQblT3d.d.cts.map +1 -0
  20. package/dist/{Endpoint-DEydLuBs.d.mts → Endpoint-ZtG0zVz1.d.mts} +4 -4
  21. package/dist/{Endpoint-DEydLuBs.d.mts.map → Endpoint-ZtG0zVz1.d.mts.map} +1 -1
  22. package/dist/{HonoEndpointAdaptor-DCD0rhFg.cjs → HonoEndpointAdaptor-1aMXc8F3.cjs} +12 -19
  23. package/dist/HonoEndpointAdaptor-1aMXc8F3.cjs.map +1 -0
  24. package/dist/{HonoEndpointAdaptor-CJfFQ5KR.mjs → HonoEndpointAdaptor-BcVAeMLW.mjs} +11 -18
  25. package/dist/HonoEndpointAdaptor-BcVAeMLW.mjs.map +1 -0
  26. package/dist/Queue-915lgS2D.mjs +62 -0
  27. package/dist/Queue-915lgS2D.mjs.map +1 -0
  28. package/dist/Queue-HbdYCQ-X.cjs +73 -0
  29. package/dist/Queue-HbdYCQ-X.cjs.map +1 -0
  30. package/dist/{Queue-Brw--scg.d.cts → Queue-I5NfFV0V.d.mts} +30 -5
  31. package/dist/{Queue-Brw--scg.d.cts.map → Queue-I5NfFV0V.d.mts.map} +1 -1
  32. package/dist/{Queue-D5z1bwFu.d.mts → Queue-XQNGO6_-.d.cts} +30 -5
  33. package/dist/{Queue-D5z1bwFu.d.mts.map → Queue-XQNGO6_-.d.cts.map} +1 -1
  34. package/dist/{Subscriber-CJ22tp8r.d.mts → Subscriber-Bjil86Ub.d.mts} +2 -2
  35. package/dist/{Subscriber-CJ22tp8r.d.mts.map → Subscriber-Bjil86Ub.d.mts.map} +1 -1
  36. package/dist/{Subscriber-DvKSp0N4.d.cts → Subscriber-YwPpHrBc.d.cts} +2 -2
  37. package/dist/{Subscriber-DvKSp0N4.d.cts.map → Subscriber-YwPpHrBc.d.cts.map} +1 -1
  38. package/dist/{Topic-BMfrIFdX.d.cts → Topic-D8-wkoh4.d.mts} +3 -3
  39. package/dist/{Topic-B-fxOsR2.d.mts.map → Topic-D8-wkoh4.d.mts.map} +1 -1
  40. package/dist/{Topic-B-fxOsR2.d.mts → Topic-dIcPqSLa.d.cts} +3 -3
  41. package/dist/{Topic-BMfrIFdX.d.cts.map → Topic-dIcPqSLa.d.cts.map} +1 -1
  42. package/dist/adaptors/aws.cjs +29 -22
  43. package/dist/adaptors/aws.cjs.map +1 -1
  44. package/dist/adaptors/aws.d.cts +10 -9
  45. package/dist/adaptors/aws.d.cts.map +1 -1
  46. package/dist/adaptors/aws.d.mts +12 -11
  47. package/dist/adaptors/aws.d.mts.map +1 -1
  48. package/dist/adaptors/aws.mjs +29 -22
  49. package/dist/adaptors/aws.mjs.map +1 -1
  50. package/dist/adaptors/hono.cjs +7 -7
  51. package/dist/adaptors/hono.d.cts +3 -3
  52. package/dist/adaptors/hono.d.cts.map +1 -1
  53. package/dist/adaptors/hono.d.mts +5 -5
  54. package/dist/adaptors/hono.d.mts.map +1 -1
  55. package/dist/adaptors/hono.mjs +7 -7
  56. package/dist/adaptors/testing.cjs +32 -31
  57. package/dist/adaptors/testing.cjs.map +1 -1
  58. package/dist/adaptors/testing.d.cts +12 -6
  59. package/dist/adaptors/testing.d.cts.map +1 -1
  60. package/dist/adaptors/testing.d.mts +14 -8
  61. package/dist/adaptors/testing.d.mts.map +1 -1
  62. package/dist/adaptors/testing.mjs +32 -31
  63. package/dist/adaptors/testing.mjs.map +1 -1
  64. package/dist/{clone-I_WIpiFf.cjs → clone-BQnYiRgm.cjs} +1 -1
  65. package/dist/{clone-I_WIpiFf.cjs.map → clone-BQnYiRgm.cjs.map} +1 -1
  66. package/dist/{clone-pdXxc0t3.mjs → clone-BWIwx6vL.mjs} +1 -1
  67. package/dist/{clone-pdXxc0t3.mjs.map → clone-BWIwx6vL.mjs.map} +1 -1
  68. package/dist/crons/index.cjs +27 -6
  69. package/dist/crons/index.cjs.map +1 -1
  70. package/dist/crons/index.d.cts +13 -3
  71. package/dist/crons/index.d.cts.map +1 -1
  72. package/dist/crons/index.d.mts +13 -3
  73. package/dist/crons/index.d.mts.map +1 -1
  74. package/dist/crons/index.mjs +27 -6
  75. package/dist/crons/index.mjs.map +1 -1
  76. package/dist/endpoints/index.cjs +7 -32
  77. package/dist/endpoints/index.cjs.map +1 -1
  78. package/dist/endpoints/index.d.cts +6 -14
  79. package/dist/endpoints/index.d.cts.map +1 -1
  80. package/dist/endpoints/index.d.mts +6 -14
  81. package/dist/endpoints/index.d.mts.map +1 -1
  82. package/dist/endpoints/index.mjs +7 -32
  83. package/dist/endpoints/index.mjs.map +1 -1
  84. package/dist/functions/index.cjs +3 -3
  85. package/dist/functions/index.d.cts +2 -2
  86. package/dist/functions/index.d.mts +2 -2
  87. package/dist/functions/index.mjs +3 -3
  88. package/dist/{functions-DhkDodl0.mjs → functions-CNJbRq0O.mjs} +4 -89
  89. package/dist/functions-CNJbRq0O.mjs.map +1 -0
  90. package/dist/{functions-B3OFv3QV.cjs → functions-DzjxHo1V.cjs} +3 -100
  91. package/dist/functions-DzjxHo1V.cjs.map +1 -0
  92. package/dist/{index-B8LNLQXD.d.mts → index-CbhtERFB.d.mts} +2 -8
  93. package/dist/index-CbhtERFB.d.mts.map +1 -0
  94. package/dist/{index-CeoLMr7c.d.cts → index-XJKTxGx7.d.cts} +6 -12
  95. package/dist/index-XJKTxGx7.d.cts.map +1 -0
  96. package/dist/index.cjs +1 -1
  97. package/dist/index.d.cts +1 -1
  98. package/dist/index.d.mts +3 -3
  99. package/dist/index.mjs +1 -1
  100. package/dist/{lazyAccessors-C1n1QfEj.cjs → lazyAccessors-BZJl6bx_.cjs} +3 -3
  101. package/dist/{lazyAccessors-C1n1QfEj.cjs.map → lazyAccessors-BZJl6bx_.cjs.map} +1 -1
  102. package/dist/{lazyAccessors-fFIQrblM.mjs → lazyAccessors-BjAZqRqK.mjs} +3 -3
  103. package/dist/{lazyAccessors-fFIQrblM.mjs.map → lazyAccessors-BjAZqRqK.mjs.map} +1 -1
  104. package/dist/monitor-D3uHJ8DU.cjs +67 -0
  105. package/dist/monitor-D3uHJ8DU.cjs.map +1 -0
  106. package/dist/monitor-Dt7fiasS.mjs +61 -0
  107. package/dist/monitor-Dt7fiasS.mjs.map +1 -0
  108. package/dist/monitors/index.cjs +2 -2
  109. package/dist/monitors/index.cjs.map +1 -1
  110. package/dist/monitors/index.d.cts +2 -2
  111. package/dist/monitors/index.d.cts.map +1 -1
  112. package/dist/monitors/index.d.mts +2 -2
  113. package/dist/monitors/index.mjs +2 -2
  114. package/dist/monitors/index.mjs.map +1 -1
  115. package/dist/{processAudits-CwyaaSQc.mjs → processAudits-BEiSkgH3.mjs} +1 -1
  116. package/dist/{processAudits-CwyaaSQc.mjs.map → processAudits-BEiSkgH3.mjs.map} +1 -1
  117. package/dist/{processAudits-94Ar_EJF.cjs → processAudits-Cd912Eck.cjs} +2 -2
  118. package/dist/{processAudits-94Ar_EJF.cjs.map → processAudits-Cd912Eck.cjs.map} +1 -1
  119. package/dist/{publisher-BZgcrVPy.cjs → publisher-B6Wu-JNv.cjs} +1 -1
  120. package/dist/{publisher-BZgcrVPy.cjs.map → publisher-B6Wu-JNv.cjs.map} +1 -1
  121. package/dist/{publisher-CnpeMv-r.mjs → publisher-Cs7WcvJl.mjs} +1 -1
  122. package/dist/{publisher-CnpeMv-r.mjs.map → publisher-Cs7WcvJl.mjs.map} +1 -1
  123. package/dist/queue/index.cjs +6 -57
  124. package/dist/queue/index.cjs.map +1 -1
  125. package/dist/queue/index.d.cts +3 -3
  126. package/dist/queue/index.d.cts.map +1 -1
  127. package/dist/queue/index.d.mts +3 -3
  128. package/dist/queue/index.d.mts.map +1 -1
  129. package/dist/queue/index.mjs +5 -57
  130. package/dist/queue/index.mjs.map +1 -1
  131. package/dist/subscribers/index.cjs +2 -2
  132. package/dist/subscribers/index.d.cts +3 -3
  133. package/dist/subscribers/index.d.mts +3 -3
  134. package/dist/subscribers/index.mjs +2 -2
  135. package/dist/{telemetry-C--EgYVr.d.mts → telemetry-vq7C0ZBy.d.mts} +1 -1
  136. package/dist/{telemetry-C--EgYVr.d.mts.map → telemetry-vq7C0ZBy.d.mts.map} +1 -1
  137. package/dist/topic/index.cjs +2 -2
  138. package/dist/topic/index.d.cts +2 -2
  139. package/dist/topic/index.d.mts +2 -2
  140. package/dist/topic/index.mjs +2 -2
  141. package/dist/{types-DNngH0fX.d.mts → types-X37z95fN.d.mts} +1 -1
  142. package/dist/{types-DNngH0fX.d.mts.map → types-X37z95fN.d.mts.map} +1 -1
  143. package/dist/types.d.mts +1 -1
  144. package/package.json +22 -22
  145. package/src/Construct.ts +2 -13
  146. package/src/__tests__/uptime.spec.ts +340 -0
  147. package/src/crons/Cron.ts +10 -0
  148. package/src/crons/CronBuilder.ts +15 -1
  149. package/src/endpoints/AmazonApiGatewayEndpointAdaptor.ts +2 -23
  150. package/src/endpoints/EndpointBuilder.ts +1 -4
  151. package/src/endpoints/EndpointFactory.ts +0 -31
  152. package/src/endpoints/HonoEndpointAdaptor.ts +1 -16
  153. package/src/endpoints/TestEndpointAdaptor.ts +4 -20
  154. package/src/functions/BaseFunctionBuilder.ts +0 -10
  155. package/src/functions/FunctionBuilder.ts +0 -2
  156. package/src/monitor.ts +14 -55
  157. package/src/monitors/heartbeat.ts +4 -2
  158. package/src/queue/AWSLambdaQueueAdaptor.ts +33 -8
  159. package/src/queue/Queue.ts +35 -1
  160. package/src/queue/TestQueueAdaptor.ts +18 -4
  161. package/src/queue/__tests__/AWSLambdaQueueAdaptor.spec.ts +131 -0
  162. package/src/queue/__tests__/TestQueueAdaptor.spec.ts +58 -0
  163. package/src/queue/index.ts +3 -0
  164. package/dist/AWSScheduledFunction-DAGP_vz5.d.cts.map +0 -1
  165. package/dist/AWSScheduledFunction-Dg6TPIxn.d.mts.map +0 -1
  166. package/dist/Construct-D09WUUOf.cjs.map +0 -1
  167. package/dist/Construct-D0uZvbr3.mjs.map +0 -1
  168. package/dist/Construct-D_3yZ9m5.d.cts.map +0 -1
  169. package/dist/Construct-DsqpiAym.d.mts.map +0 -1
  170. package/dist/Endpoint-CxBdXNZm.d.cts.map +0 -1
  171. package/dist/HonoEndpointAdaptor-CJfFQ5KR.mjs.map +0 -1
  172. package/dist/HonoEndpointAdaptor-DCD0rhFg.cjs.map +0 -1
  173. package/dist/functions-B3OFv3QV.cjs.map +0 -1
  174. package/dist/functions-DhkDodl0.mjs.map +0 -1
  175. package/dist/index-B8LNLQXD.d.mts.map +0 -1
  176. package/dist/index-CeoLMr7c.d.cts.map +0 -1
  177. package/src/__tests__/monitor.spec.ts +0 -696
@@ -0,0 +1,340 @@
1
+ import { EnvironmentParser } from '@geekmidas/envkit';
2
+ import { ServiceDiscovery } from '@geekmidas/services';
3
+ import { createMockContext } from '@geekmidas/testkit/aws';
4
+ import { HttpResponse, http } from 'msw';
5
+ import { setupServer } from 'msw/node';
6
+ import {
7
+ afterAll,
8
+ afterEach,
9
+ beforeAll,
10
+ beforeEach,
11
+ describe,
12
+ expect,
13
+ it,
14
+ vi,
15
+ } from 'vitest';
16
+ import { z } from 'zod';
17
+ import { AWSScheduledFunction } from '../crons/AWSScheduledFunction';
18
+ import { CronBuilder } from '../crons/CronBuilder';
19
+ import { EndpointFactory } from '../endpoints/EndpointFactory';
20
+ import { FunctionBuilder } from '../functions/FunctionBuilder';
21
+ import { TestFunctionAdaptor } from '../functions/TestFunctionAdaptor';
22
+ import type { ConstructMonitor, MonitorService } from '../monitor';
23
+ import { heartbeat } from '../monitors';
24
+
25
+ const HEARTBEAT = 'https://heartbeat.test/api/v1/heartbeat/abc';
26
+
27
+ /** Every heartbeat request MSW saw, as `path`. */
28
+ const pings: string[] = [];
29
+
30
+ const server = setupServer(
31
+ http.get('https://heartbeat.test/*', ({ request }) => {
32
+ pings.push(new URL(request.url).pathname.replace('/api/v1/heartbeat', ''));
33
+ return new HttpResponse(null, { status: 200 });
34
+ }),
35
+ );
36
+
37
+ /** A monitor that writes down what it was told, in order. */
38
+ function recorder(serviceName = 'recorder') {
39
+ const calls: string[] = [];
40
+ const service = {
41
+ serviceName,
42
+ async register(): Promise<ConstructMonitor<string>> {
43
+ return {
44
+ async start() {
45
+ calls.push('start');
46
+ return 'run-1';
47
+ },
48
+ async success({ run }) {
49
+ calls.push(`success:${run}`);
50
+ },
51
+ async failure({ run, error }) {
52
+ calls.push(`failure:${run}:${(error as Error).message}`);
53
+ },
54
+ };
55
+ },
56
+ } satisfies MonitorService;
57
+
58
+ return { calls, service };
59
+ }
60
+
61
+ const throwing = {
62
+ serviceName: 'throwing',
63
+ async register(): Promise<ConstructMonitor> {
64
+ return {
65
+ async start() {
66
+ throw new Error('start failed');
67
+ },
68
+ async success() {
69
+ throw new Error('success failed');
70
+ },
71
+ async failure() {
72
+ throw new Error('failure failed');
73
+ },
74
+ };
75
+ },
76
+ } satisfies MonitorService;
77
+
78
+ function discovery(env: Record<string, string> = {}) {
79
+ return ServiceDiscovery.getInstance(new EnvironmentParser(env));
80
+ }
81
+
82
+ beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
83
+ afterAll(() => server.close());
84
+ beforeEach(() => {
85
+ // Services are cached by name, so each test starts from its own env.
86
+ ServiceDiscovery.reset();
87
+ pings.length = 0;
88
+ });
89
+ afterEach(() => server.resetHandlers());
90
+
91
+ const cron = (monitor: MonitorService) =>
92
+ new CronBuilder()
93
+ .input(z.object({}))
94
+ .schedule('cron(0 0 * * *)')
95
+ .uptime(monitor);
96
+
97
+ describe('cron.uptime() with a heartbeat', () => {
98
+ it('pings the URL when a run succeeds', async () => {
99
+ await new TestFunctionAdaptor(
100
+ cron(heartbeat.betterStack()).handle(async () => ({ ok: true })),
101
+ discovery({ HEARTBEAT_URL: HEARTBEAT }),
102
+ ).invoke({ input: {}, services: {} });
103
+
104
+ expect(pings).toEqual(['/abc']);
105
+ });
106
+
107
+ it('pings the failure URL and rethrows when a run fails', async () => {
108
+ await expect(
109
+ new TestFunctionAdaptor(
110
+ cron(heartbeat.betterStack()).handle(async () => {
111
+ throw new Error('boom');
112
+ }),
113
+ discovery({ HEARTBEAT_URL: HEARTBEAT }),
114
+ ).invoke({ input: {}, services: {} }),
115
+ ).rejects.toThrow('boom');
116
+
117
+ expect(pings).toEqual(['/abc/fail']);
118
+ });
119
+
120
+ it('pings start before success for providers that take one', async () => {
121
+ await new TestFunctionAdaptor(
122
+ cron(heartbeat.healthchecks()).handle(async () => ({})),
123
+ discovery({ HEARTBEAT_URL: HEARTBEAT }),
124
+ ).invoke({ input: {}, services: {} });
125
+
126
+ expect(pings).toEqual(['/abc/start', '/abc']);
127
+ });
128
+
129
+ it('skips the heartbeat but still runs when its env var is missing', async () => {
130
+ const output = await new TestFunctionAdaptor(
131
+ cron(heartbeat.betterStack())
132
+ .output(z.object({ ok: z.boolean() }))
133
+ .handle(async () => ({ ok: true })),
134
+ discovery(),
135
+ ).invoke({ input: {}, services: {} });
136
+
137
+ expect(output).toEqual({ ok: true });
138
+ expect(pings).toEqual([]);
139
+ });
140
+
141
+ it('reads the env var it was given', async () => {
142
+ await new TestFunctionAdaptor(
143
+ cron(heartbeat.betterStack('NIGHTLY_HEARTBEAT_URL')).handle(
144
+ async () => ({}),
145
+ ),
146
+ discovery({ NIGHTLY_HEARTBEAT_URL: `${HEARTBEAT}/nightly` }),
147
+ ).invoke({ input: {}, services: {} });
148
+
149
+ expect(pings).toEqual(['/abc/nightly']);
150
+ });
151
+
152
+ it('does not fail the run when the provider is down', async () => {
153
+ server.use(
154
+ http.get('https://heartbeat.test/*', () =>
155
+ HttpResponse.json({ error: 'down' }, { status: 503 }),
156
+ ),
157
+ );
158
+
159
+ const output = await new TestFunctionAdaptor(
160
+ cron(heartbeat.betterStack())
161
+ .output(z.object({ ok: z.boolean() }))
162
+ .handle(async () => ({ ok: true })),
163
+ discovery({ HEARTBEAT_URL: HEARTBEAT }),
164
+ ).invoke({ input: {}, services: {} });
165
+
166
+ expect(output).toEqual({ ok: true });
167
+ });
168
+
169
+ it('declares its env var as required', async () => {
170
+ const environment = await cron(
171
+ heartbeat.betterStack('NIGHTLY_HEARTBEAT_URL'),
172
+ )
173
+ .handle(async () => ({}))
174
+ .getEnvironment({ markOptional: true });
175
+
176
+ expect(environment).toContain('NIGHTLY_HEARTBEAT_URL');
177
+ expect(environment).not.toContain('NIGHTLY_HEARTBEAT_URL?');
178
+ });
179
+ });
180
+
181
+ describe('cron.uptime()', () => {
182
+ it('reports start, then success with what start returned', async () => {
183
+ const { calls, service } = recorder();
184
+
185
+ await new TestFunctionAdaptor(
186
+ cron(service).handle(async () => ({})),
187
+ discovery(),
188
+ ).invoke({ input: {}, services: {} });
189
+
190
+ expect(calls).toEqual(['start', 'success:run-1']);
191
+ });
192
+
193
+ it('ignores a monitor that throws', async () => {
194
+ const output = await new TestFunctionAdaptor(
195
+ cron(throwing)
196
+ .output(z.object({ ok: z.boolean() }))
197
+ .handle(async () => ({ ok: true })),
198
+ discovery(),
199
+ ).invoke({ input: {}, services: {} });
200
+
201
+ expect(output).toEqual({ ok: true });
202
+ });
203
+
204
+ it('replaces the monitor when called again', () => {
205
+ const first = recorder('first');
206
+ const second = recorder('second');
207
+
208
+ const nightly = cron(first.service)
209
+ .uptime(second.service)
210
+ .handle(async () => ({}));
211
+
212
+ expect(nightly.monitors.map((m) => m.serviceName)).toEqual(['second']);
213
+ });
214
+
215
+ it('is inherited from a shared base', () => {
216
+ const shared = recorder('shared');
217
+ const base = new CronBuilder().uptime(shared.service);
218
+
219
+ const nightly = base.schedule('cron(0 0 * * *)').handle(async () => ({}));
220
+ const hourly = base.schedule('cron(0 * * * *)').handle(async () => ({}));
221
+
222
+ expect(nightly.monitors.map((m) => m.serviceName)).toEqual(['shared']);
223
+ expect(hourly.monitors.map((m) => m.serviceName)).toEqual(['shared']);
224
+ });
225
+
226
+ it('is not available on functions or endpoints', () => {
227
+ // @ts-expect-error uptime is for crons only
228
+ expect(new FunctionBuilder().uptime).toBeUndefined();
229
+ // @ts-expect-error monitor() is removed
230
+ expect(new FunctionBuilder().monitor).toBeUndefined();
231
+ // @ts-expect-error monitor() is removed
232
+ expect(new EndpointFactory().monitor).toBeUndefined();
233
+ // @ts-expect-error monitor() is removed
234
+ expect(new EndpointFactory().get('/x').monitor).toBeUndefined();
235
+ });
236
+ });
237
+
238
+ describe('cron.uptime() in the AWS Lambda handler', () => {
239
+ const invoke = (construct: any, env = { HEARTBEAT_URL: HEARTBEAT }) =>
240
+ new AWSScheduledFunction(new EnvironmentParser(env), construct).handler(
241
+ {},
242
+ createMockContext(),
243
+ vi.fn(),
244
+ );
245
+
246
+ it('sends the success ping', async () => {
247
+ await invoke(cron(heartbeat.betterStack()).handle(async () => ({})));
248
+ expect(pings).toEqual(['/abc']);
249
+ });
250
+
251
+ it('sends the failure ping', async () => {
252
+ await expect(
253
+ invoke(
254
+ cron(heartbeat.betterStack()).handle(async () => {
255
+ throw new Error('boom');
256
+ }),
257
+ ),
258
+ ).rejects.toThrow();
259
+ expect(pings).toEqual(['/abc/fail']);
260
+ });
261
+
262
+ it('reports the original error, not the wrapped one', async () => {
263
+ const { calls, service } = recorder();
264
+ discovery();
265
+
266
+ await expect(
267
+ invoke(
268
+ cron(service).handle(async () => {
269
+ throw new Error('boom');
270
+ }),
271
+ ),
272
+ ).rejects.toThrow();
273
+ expect(calls).toEqual(['start', 'failure:run-1:boom']);
274
+ });
275
+
276
+ it('sends the start ping first, for Healthchecks.io', async () => {
277
+ await invoke(cron(heartbeat.healthchecks()).handle(async () => ({})));
278
+ expect(pings).toEqual(['/abc/start', '/abc']);
279
+ });
280
+
281
+ it('sends one ping per run, from a shared base', async () => {
282
+ const base = new CronBuilder().uptime(heartbeat.betterStack());
283
+
284
+ await invoke(base.schedule('cron(0 0 * * *)').handle(async () => ({})));
285
+ await invoke(base.schedule('cron(0 * * * *)').handle(async () => ({})));
286
+
287
+ expect(pings).toEqual(['/abc', '/abc']);
288
+ });
289
+ });
290
+
291
+ describe('getUptime', () => {
292
+ it('records the monitor for the manifest', () => {
293
+ expect(
294
+ cron(heartbeat.betterStack('MONITORING_URL'))
295
+ .handle(async () => ({}))
296
+ .getUptime(),
297
+ ).toEqual({
298
+ type: 'heartbeat',
299
+ provider: 'betterStack',
300
+ env: 'MONITORING_URL',
301
+ });
302
+ });
303
+
304
+ it('records a custom heartbeat without a provider, on its default env var', () => {
305
+ expect(
306
+ cron(heartbeat())
307
+ .handle(async () => ({}))
308
+ .getUptime(),
309
+ ).toEqual({
310
+ type: 'heartbeat',
311
+ env: 'HEARTBEAT_URL',
312
+ });
313
+ });
314
+
315
+ it('records a hand-written monitor by its service name', () => {
316
+ const custom = {
317
+ serviceName: 'custom',
318
+ async register() {
319
+ return { async success() {}, async failure() {} };
320
+ },
321
+ } satisfies MonitorService;
322
+
323
+ expect(
324
+ cron(custom)
325
+ .handle(async () => ({}))
326
+ .getUptime(),
327
+ ).toEqual({
328
+ type: 'custom',
329
+ });
330
+ });
331
+
332
+ it('records nothing for a cron without one', () => {
333
+ expect(
334
+ new CronBuilder()
335
+ .schedule('cron(0 0 * * *)')
336
+ .handle(async () => ({}))
337
+ .getUptime(),
338
+ ).toBeUndefined();
339
+ });
340
+ });
package/src/crons/Cron.ts CHANGED
@@ -7,6 +7,7 @@ import type { StandardSchemaV1 } from '@standard-schema/spec';
7
7
 
8
8
  import { ConstructType } from '../Construct';
9
9
  import { Function, type FunctionHandler } from '../functions';
10
+ import type { MonitorInfo } from '../monitor';
10
11
 
11
12
  export class Cron<
12
13
  TInput extends ComposableStandardSchema | undefined = undefined,
@@ -71,6 +72,15 @@ export class Cron<
71
72
  get schedule(): ScheduleExpression | undefined {
72
73
  return this._schedule;
73
74
  }
75
+
76
+ /**
77
+ * The monitor set with `.uptime()` as the build manifest records it, or
78
+ * nothing when the cron has none.
79
+ */
80
+ getUptime(): MonitorInfo | undefined {
81
+ const [uptime] = this.monitors;
82
+ return uptime && (uptime.monitor ?? { type: uptime.serviceName });
83
+ }
74
84
  }
75
85
 
76
86
  // ---- Cron expression types ------------------------------------------------
@@ -7,6 +7,7 @@ import uniqBy from 'lodash.uniqby';
7
7
  import { ConstructType } from '../Construct';
8
8
  import { cloneWith } from '../clone';
9
9
  import { FunctionBuilder, type FunctionHandler } from '../functions';
10
+ import type { MonitorService } from '../monitor';
10
11
  import { Cron, type CronExpression, type ScheduleExpression } from './Cron';
11
12
 
12
13
  export class CronBuilder<
@@ -31,6 +32,7 @@ export class CronBuilder<
31
32
  TDatabaseServiceName
32
33
  > {
33
34
  private _schedule?: ScheduleExpression;
35
+ private _uptime?: MonitorService;
34
36
 
35
37
  constructor() {
36
38
  super(ConstructType.Cron);
@@ -61,6 +63,18 @@ export class CronBuilder<
61
63
  });
62
64
  }
63
65
 
66
+ /**
67
+ * Report each run to an uptime monitor, so a cron that stops running is
68
+ * noticed: `heartbeat.betterStack()` pings on success and reports a
69
+ * failure. Calling it again replaces the monitor.
70
+ *
71
+ * `gkm build` records it in the manifest with the schedule's period, the
72
+ * longest gap between runs, so infrastructure can create the heartbeat.
73
+ */
74
+ uptime(monitor: MonitorService): this {
75
+ return cloneWith(this, { _uptime: monitor });
76
+ }
77
+
64
78
  override input<T extends ComposableStandardSchema>(
65
79
  schema: T,
66
80
  ): CronBuilder<
@@ -260,7 +274,7 @@ export class CronBuilder<
260
274
  // configured base keeps its configuration for every construct built
261
275
  // from it. The reset that used to be here wiped the base on first use.
262
276
 
263
- cron.monitors = this._monitors;
277
+ cron.monitors = this._uptime ? [this._uptime] : [];
264
278
 
265
279
  return cron;
266
280
  }
@@ -37,7 +37,6 @@ import {
37
37
  ServiceDiscovery,
38
38
  type ServiceRecord,
39
39
  } from '@geekmidas/services';
40
- import { startMonitors } from '../monitor';
41
40
  import { publishConstructEvents } from '../publisher';
42
41
  import type { MappedAudit } from './audit';
43
42
  import type { CookieFn, HeaderFn } from './Endpoint';
@@ -134,8 +133,6 @@ export abstract class AmazonApiGatewayEndpoint<
134
133
  'Error processing request',
135
134
  );
136
135
  const wrappedError = wrapError(req.error);
137
- // Kept for the monitors, which only see the response otherwise.
138
- (req.event as any).__error = req.error;
139
136
 
140
137
  // Set the response with the proper status code from the HttpError
141
138
  req.response = {
@@ -595,26 +592,8 @@ export abstract class AmazonApiGatewayEndpoint<
595
592
 
596
593
  // Cast event to any since Middy middlewares enrich the event with
597
594
  // services, logger, session, etc. during the middleware chain execution
598
- return runWithRequestContext(
599
- { logger, requestId, startTime },
600
- async () => {
601
- const monitor = await startMonitors(
602
- this.endpoint,
603
- ServiceDiscovery.getInstance(this.envParser),
604
- logger,
605
- );
606
- const response = await chain(
607
- event as unknown as Parameters<typeof chain>[0],
608
- context,
609
- );
610
- // Awaited: Lambda freezes the process once the response is
611
- // returned, so an unawaited ping may never be sent.
612
- await monitor.settle(
613
- (response as any)?.statusCode ?? 200,
614
- (event as any).__error,
615
- );
616
- return response;
617
- },
595
+ return runWithRequestContext({ logger, requestId, startTime }, () =>
596
+ chain(event as unknown as Parameters<typeof chain>[0], context),
618
597
  );
619
598
  };
620
599
 
@@ -715,7 +715,7 @@ export class EndpointBuilder<
715
715
  }
716
716
  }
717
717
 
718
- const endpoint = new Endpoint({
718
+ return new Endpoint({
719
719
  fn,
720
720
  method: this.method,
721
721
  route: this.route,
@@ -742,8 +742,5 @@ export class EndpointBuilder<
742
742
  rlsBypass: this._rlsBypass,
743
743
  responseType: this._responseType,
744
744
  });
745
- endpoint.monitors = this._monitors;
746
-
747
- return endpoint;
748
745
  }
749
746
  }
@@ -8,8 +8,6 @@ import type { Logger } from '@geekmidas/logger';
8
8
  import { ConsoleLogger } from '@geekmidas/logger/console';
9
9
  import type { Service } from '@geekmidas/services';
10
10
  import uniqBy from 'lodash.uniqby';
11
- import { cloneWith } from '../clone';
12
- import { addMonitor, type MonitorService } from '../monitor';
13
11
  import type { HttpMethod } from '../types';
14
12
  import {
15
13
  type Authorizer,
@@ -81,7 +79,6 @@ export class EndpointFactory<
81
79
  private defaultActorExtractor?: ActorExtractor<TServices, TSession, TLogger>;
82
80
  private customSecuritySchemes: TSecuritySchemes = {} as TSecuritySchemes;
83
81
  private defaultRlsConfig?: TRlsConfig;
84
- private defaultMonitors: MonitorService[] = [];
85
82
 
86
83
  constructor({
87
84
  basePath,
@@ -98,7 +95,6 @@ export class EndpointFactory<
98
95
  defaultActorExtractor,
99
96
  customSecuritySchemes = {} as TSecuritySchemes,
100
97
  defaultRlsConfig,
101
- defaultMonitors = [],
102
98
  }: EndpointFactoryOptions<
103
99
  TServices,
104
100
  TBasePath,
@@ -132,17 +128,6 @@ export class EndpointFactory<
132
128
  this.defaultActorExtractor = defaultActorExtractor;
133
129
  this.customSecuritySchemes = customSecuritySchemes;
134
130
  this.defaultRlsConfig = defaultRlsConfig;
135
- this.defaultMonitors = defaultMonitors;
136
- }
137
-
138
- /**
139
- * Report every endpoint's requests to a monitor. Endpoints built from this
140
- * factory inherit it, and can add their own with `.monitor()`.
141
- */
142
- monitor(monitor: MonitorService): this {
143
- return cloneWith(this, {
144
- defaultMonitors: addMonitor(this.defaultMonitors, monitor),
145
- });
146
131
  }
147
132
 
148
133
  static joinPaths<TBasePath extends string, P extends string>(
@@ -227,7 +212,6 @@ export class EndpointFactory<
227
212
  defaultLogger: this.defaultLogger,
228
213
  defaultSessionExtractor: this.defaultSessionExtractor,
229
214
  defaultEventPublisher: this.defaultEventPublisher,
230
- defaultMonitors: this.defaultMonitors,
231
215
  availableAuthorizers: authorizerConfigs,
232
216
  defaultAuthorizerName: this.defaultAuthorizerName,
233
217
  defaultAuditorStorage: this.defaultAuditorStorage,
@@ -294,7 +278,6 @@ export class EndpointFactory<
294
278
  defaultLogger: this.defaultLogger,
295
279
  defaultSessionExtractor: this.defaultSessionExtractor,
296
280
  defaultEventPublisher: this.defaultEventPublisher,
297
- defaultMonitors: this.defaultMonitors,
298
281
  availableAuthorizers: this.availableAuthorizers,
299
282
  defaultAuthorizerName: this.defaultAuthorizerName,
300
283
  defaultAuditorStorage: this.defaultAuditorStorage,
@@ -377,7 +360,6 @@ export class EndpointFactory<
377
360
  defaultLogger: this.defaultLogger,
378
361
  defaultSessionExtractor: this.defaultSessionExtractor,
379
362
  defaultEventPublisher: this.defaultEventPublisher,
380
- defaultMonitors: this.defaultMonitors,
381
363
  availableAuthorizers: this.availableAuthorizers,
382
364
  defaultAuthorizerName:
383
365
  name === 'none' ? undefined : (name as TAuthorizers[number]),
@@ -431,7 +413,6 @@ export class EndpointFactory<
431
413
  defaultLogger: this.defaultLogger,
432
414
  defaultSessionExtractor: this.defaultSessionExtractor,
433
415
  defaultEventPublisher: this.defaultEventPublisher,
434
- defaultMonitors: this.defaultMonitors,
435
416
  availableAuthorizers: this.availableAuthorizers,
436
417
  defaultAuthorizerName: this.defaultAuthorizerName,
437
418
  defaultAuditorStorage: this.defaultAuditorStorage,
@@ -483,7 +464,6 @@ export class EndpointFactory<
483
464
  defaultLogger: this.defaultLogger,
484
465
  defaultSessionExtractor: this.defaultSessionExtractor,
485
466
  defaultEventPublisher: this.defaultEventPublisher,
486
- defaultMonitors: this.defaultMonitors,
487
467
  availableAuthorizers: this.availableAuthorizers,
488
468
  defaultAuthorizerName: this.defaultAuthorizerName,
489
469
  defaultAuditorStorage: this.defaultAuditorStorage,
@@ -541,7 +521,6 @@ export class EndpointFactory<
541
521
  | SessionFn<[...S, ...TServices], TLogger, TSession, TDatabase>
542
522
  | undefined,
543
523
  defaultEventPublisher: this.defaultEventPublisher,
544
- defaultMonitors: this.defaultMonitors,
545
524
  availableAuthorizers: this.availableAuthorizers,
546
525
  defaultAuthorizerName: this.defaultAuthorizerName,
547
526
  defaultAuditorStorage: this.defaultAuditorStorage,
@@ -605,7 +584,6 @@ export class EndpointFactory<
605
584
  TSession
606
585
  >,
607
586
  defaultEventPublisher: this.defaultEventPublisher,
608
- defaultMonitors: this.defaultMonitors,
609
587
  availableAuthorizers: this.availableAuthorizers,
610
588
  defaultAuthorizerName: this.defaultAuthorizerName,
611
589
  defaultAuditorStorage: this.defaultAuditorStorage,
@@ -666,7 +644,6 @@ export class EndpointFactory<
666
644
  defaultLogger: this.defaultLogger,
667
645
  defaultSessionExtractor: this.defaultSessionExtractor,
668
646
  defaultEventPublisher: publisher,
669
- defaultMonitors: this.defaultMonitors,
670
647
  availableAuthorizers: this.availableAuthorizers,
671
648
  defaultAuthorizerName: this.defaultAuthorizerName,
672
649
  defaultAuditorStorage: this.defaultAuditorStorage,
@@ -721,7 +698,6 @@ export class EndpointFactory<
721
698
  defaultLogger: this.defaultLogger,
722
699
  defaultSessionExtractor: session,
723
700
  defaultEventPublisher: this.defaultEventPublisher,
724
- defaultMonitors: this.defaultMonitors,
725
701
  availableAuthorizers: this.availableAuthorizers,
726
702
  defaultAuthorizerName: this.defaultAuthorizerName,
727
703
  defaultAuditorStorage: this.defaultAuditorStorage,
@@ -789,7 +765,6 @@ export class EndpointFactory<
789
765
  | SessionFn<TServices, TLogger, TSession, T>
790
766
  | undefined,
791
767
  defaultEventPublisher: this.defaultEventPublisher,
792
- defaultMonitors: this.defaultMonitors,
793
768
  availableAuthorizers: this.availableAuthorizers,
794
769
  defaultAuthorizerName: this.defaultAuthorizerName,
795
770
  defaultAuditorStorage: this.defaultAuditorStorage,
@@ -844,7 +819,6 @@ export class EndpointFactory<
844
819
  defaultLogger: this.defaultLogger,
845
820
  defaultSessionExtractor: this.defaultSessionExtractor,
846
821
  defaultEventPublisher: this.defaultEventPublisher,
847
- defaultMonitors: this.defaultMonitors,
848
822
  availableAuthorizers: this.availableAuthorizers,
849
823
  defaultAuthorizerName: this.defaultAuthorizerName,
850
824
  defaultAuditorStorage: storage,
@@ -904,7 +878,6 @@ export class EndpointFactory<
904
878
  defaultLogger: this.defaultLogger,
905
879
  defaultSessionExtractor: this.defaultSessionExtractor,
906
880
  defaultEventPublisher: this.defaultEventPublisher,
907
- defaultMonitors: this.defaultMonitors,
908
881
  availableAuthorizers: this.availableAuthorizers,
909
882
  defaultAuthorizerName: this.defaultAuthorizerName,
910
883
  defaultAuditorStorage: this.defaultAuditorStorage,
@@ -973,7 +946,6 @@ export class EndpointFactory<
973
946
  defaultLogger: this.defaultLogger,
974
947
  defaultSessionExtractor: this.defaultSessionExtractor,
975
948
  defaultEventPublisher: this.defaultEventPublisher,
976
- defaultMonitors: this.defaultMonitors,
977
949
  availableAuthorizers: this.availableAuthorizers,
978
950
  defaultAuthorizerName: this.defaultAuthorizerName,
979
951
  defaultAuditorStorage: this.defaultAuditorStorage,
@@ -1047,8 +1019,6 @@ export class EndpointFactory<
1047
1019
  builder._setPublisher(this.defaultEventPublisher);
1048
1020
  }
1049
1021
 
1050
- builder._monitors = [...this.defaultMonitors];
1051
-
1052
1022
  // Set available authorizers and default
1053
1023
  builder._availableAuthorizers = this.availableAuthorizers;
1054
1024
  if (this.defaultAuthorizerName) {
@@ -1173,7 +1143,6 @@ export interface EndpointFactoryOptions<
1173
1143
  defaultActorExtractor?: ActorExtractor<TServices, TSession, TLogger>;
1174
1144
  customSecuritySchemes?: TSecuritySchemes;
1175
1145
  defaultRlsConfig?: TRlsConfig;
1176
- defaultMonitors?: MonitorService[];
1177
1146
  }
1178
1147
 
1179
1148
  export const e = new EndpointFactory();
@@ -18,7 +18,6 @@ import { logger as honoLogger } from 'hono/logger';
18
18
  import { timing } from 'hono/timing';
19
19
  import type { ContentfulStatusCode } from 'hono/utils/http-status';
20
20
  import { validator } from 'hono/validator';
21
- import { startMonitors } from '../monitor';
22
21
  import { publishConstructEvents } from '../publisher';
23
22
  import type { HttpMethod, LowerHttpMethod } from '../types';
24
23
  import type { MappedAudit } from './audit';
@@ -67,7 +66,6 @@ interface EndpointFeatures {
67
66
  hasEvents: boolean;
68
67
  hasRateLimit: boolean;
69
68
  hasRls: boolean;
70
- hasMonitors: boolean;
71
69
  }
72
70
 
73
71
  /**
@@ -113,7 +111,6 @@ function analyzeEndpointFeatures(
113
111
  hasEvents: (endpoint.events?.length ?? 0) > 0,
114
112
  hasRateLimit: !!endpoint.rateLimit,
115
113
  hasRls: !!endpoint.rlsConfig && !endpoint.rlsBypass,
116
- hasMonitors: endpoint.monitors.length > 0,
117
114
  };
118
115
  }
119
116
 
@@ -364,13 +361,8 @@ export class HonoEndpoint<
364
361
  // Set response header
365
362
  c.header('X-Request-ID', requestId);
366
363
 
367
- const monitor = features.hasMonitors
368
- ? await startMonitors(endpoint, serviceDiscovery, logger)
369
- : undefined;
370
- let failure: unknown;
371
-
372
364
  // Wrap entire handler in request context for services to access
373
- const response = await runWithRequestContext(
365
+ return runWithRequestContext(
374
366
  { logger, requestId, startTime },
375
367
  async () => {
376
368
  try {
@@ -639,7 +631,6 @@ export class HonoEndpoint<
639
631
  return c.json(error, error.statusCode as ContentfulStatusCode);
640
632
  }
641
633
  } catch (e: any) {
642
- failure = e;
643
634
  logger.error(e, 'Error processing endpoint request');
644
635
  const error = wrapError(e, 500, 'Internal Server Error');
645
636
  if (HonoEndpoint.isDev) {
@@ -652,12 +643,6 @@ export class HonoEndpoint<
652
643
  }
653
644
  },
654
645
  );
655
-
656
- // Not awaited: a server stays up after responding, so the request
657
- // does not wait on the monitoring service. `settle` never throws.
658
- void monitor?.settle(response.status, failure);
659
-
660
- return response;
661
646
  };
662
647
 
663
648
  // Register route with conditional validators