@pikku/lambda 0.12.2 → 0.12.4
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/CHANGELOG.md +35 -0
- package/dist/handler-factories.d.ts +17 -0
- package/dist/handler-factories.js +91 -0
- package/dist/handler-factories.js.map +1 -0
- package/dist/http/index.d.ts +3 -0
- package/dist/http/index.js +3 -0
- package/dist/http/index.js.map +1 -1
- package/dist/http/request-converter-v2.d.ts +2 -0
- package/dist/http/request-converter-v2.js +25 -0
- package/dist/http/request-converter-v2.js.map +1 -0
- package/dist/http/response-converter-v2.d.ts +2 -0
- package/dist/http/response-converter-v2.js +31 -0
- package/dist/http/response-converter-v2.js.map +1 -0
- package/dist/http/run-fetch-v2.d.ts +2 -0
- package/dist/http/run-fetch-v2.js +25 -0
- package/dist/http/run-fetch-v2.js.map +1 -0
- package/dist/http/run-fetch.js +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/dist/lambda-deployment-service.d.ts +14 -0
- package/dist/lambda-deployment-service.js +89 -0
- package/dist/lambda-deployment-service.js.map +1 -0
- package/dist/queue/sqs-worker.js +1 -1
- package/dist/queue/sqs-worker.js.map +1 -1
- package/dist/scheduled/index.d.ts +1 -0
- package/dist/scheduled/index.js +2 -0
- package/dist/scheduled/index.js.map +1 -0
- package/dist/scheduled/run-scheduled.d.ts +2 -0
- package/dist/scheduled/run-scheduled.js +14 -0
- package/dist/scheduled/run-scheduled.js.map +1 -0
- package/dist/sqs-queue-service.d.ts +10 -0
- package/dist/sqs-queue-service.js +52 -0
- package/dist/sqs-queue-service.js.map +1 -0
- package/dist/websocket/utils.d.ts +1 -1
- package/package.json +12 -6
- package/src/handler-factories.ts +165 -0
- package/src/http/index.ts +3 -0
- package/src/http/request-converter-v2.ts +36 -0
- package/src/http/response-converter-v2.ts +40 -0
- package/src/http/run-fetch-v2.ts +42 -0
- package/src/http/run-fetch.ts +1 -1
- package/src/index.test.ts +13 -0
- package/src/index.ts +4 -0
- package/src/lambda-deployment-service.ts +134 -0
- package/src/queue/sqs-worker.ts +1 -1
- package/src/scheduled/index.ts +1 -0
- package/src/scheduled/run-scheduled.ts +30 -0
- package/src/sqs-queue-service.ts +91 -0
- package/src/websocket/lambda-eventhub-service.ts +3 -3
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lambda handler factories — mirrors Cloudflare's handler-factories.ts.
|
|
3
|
+
*
|
|
4
|
+
* Creates combined Lambda handlers based on which handler types a unit needs
|
|
5
|
+
* (fetch, queue, scheduled). Services are cached across warm invocations.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { LocalVariablesService, LocalSecretService } from '@pikku/core/services'
|
|
9
|
+
import type { CoreSingletonServices } from '@pikku/core'
|
|
10
|
+
import type { ChannelStore } from '@pikku/core/channel'
|
|
11
|
+
import { runFetchV2 } from './http/run-fetch-v2.js'
|
|
12
|
+
import { runSQSQueueWorker } from './queue/sqs-worker.js'
|
|
13
|
+
import { runLambdaScheduled } from './scheduled/run-scheduled.js'
|
|
14
|
+
import type {
|
|
15
|
+
APIGatewayEvent,
|
|
16
|
+
APIGatewayProxyEventV2,
|
|
17
|
+
SQSEvent,
|
|
18
|
+
ScheduledEvent,
|
|
19
|
+
} from 'aws-lambda'
|
|
20
|
+
|
|
21
|
+
export interface LambdaServiceFactories {
|
|
22
|
+
createConfig: (
|
|
23
|
+
variables: LocalVariablesService,
|
|
24
|
+
...args: unknown[]
|
|
25
|
+
) => Promise<unknown>
|
|
26
|
+
createSingletonServices: (
|
|
27
|
+
config: unknown,
|
|
28
|
+
existingServices?: Partial<Record<string, unknown>>
|
|
29
|
+
) => Promise<CoreSingletonServices>
|
|
30
|
+
/**
|
|
31
|
+
* Optional callback to create platform services from environment.
|
|
32
|
+
* Returns services to merge into existingServices.
|
|
33
|
+
* Generated by the deploy codegen based on unit capabilities.
|
|
34
|
+
*/
|
|
35
|
+
createPlatformServices?: () =>
|
|
36
|
+
| Record<string, unknown>
|
|
37
|
+
| Promise<Record<string, unknown>>
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
let cachedServices: CoreSingletonServices | null = null
|
|
41
|
+
|
|
42
|
+
async function setupServices(
|
|
43
|
+
factories: LambdaServiceFactories
|
|
44
|
+
): Promise<CoreSingletonServices> {
|
|
45
|
+
if (cachedServices) return cachedServices
|
|
46
|
+
const variables = new LocalVariablesService(
|
|
47
|
+
process.env as Record<string, string | undefined>
|
|
48
|
+
)
|
|
49
|
+
const config = await factories.createConfig(variables)
|
|
50
|
+
const secrets = new LocalSecretService(variables)
|
|
51
|
+
|
|
52
|
+
const platformServices = factories.createPlatformServices
|
|
53
|
+
? await factories.createPlatformServices()
|
|
54
|
+
: {}
|
|
55
|
+
|
|
56
|
+
cachedServices = await factories.createSingletonServices(config, {
|
|
57
|
+
variables,
|
|
58
|
+
secrets,
|
|
59
|
+
...platformServices,
|
|
60
|
+
})
|
|
61
|
+
return cachedServices
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Creates a combined Lambda handler based on which handler types the unit needs.
|
|
66
|
+
*
|
|
67
|
+
* Returns an object with named exports that serverless.yml references:
|
|
68
|
+
* - `handler` for HTTP (API Gateway)
|
|
69
|
+
* - `queue` for SQS
|
|
70
|
+
* - `scheduled` for EventBridge
|
|
71
|
+
*/
|
|
72
|
+
export function createLambdaHandler(
|
|
73
|
+
factories: LambdaServiceFactories,
|
|
74
|
+
handlerTypes: string[]
|
|
75
|
+
) {
|
|
76
|
+
const result: Record<string, unknown> = {}
|
|
77
|
+
|
|
78
|
+
if (handlerTypes.includes('fetch')) {
|
|
79
|
+
result.handler = async (event: APIGatewayProxyEventV2) => {
|
|
80
|
+
await setupServices(factories)
|
|
81
|
+
return runFetchV2(event)
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (handlerTypes.includes('queue')) {
|
|
86
|
+
result.queue = async (event: SQSEvent) => {
|
|
87
|
+
const services = await setupServices(factories)
|
|
88
|
+
return runSQSQueueWorker(services.logger, event)
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (handlerTypes.includes('scheduled')) {
|
|
93
|
+
result.scheduled = async (event: ScheduledEvent) => {
|
|
94
|
+
await setupServices(factories)
|
|
95
|
+
return runLambdaScheduled(event)
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// If no fetch handler was requested, add a health check
|
|
100
|
+
if (!handlerTypes.includes('fetch')) {
|
|
101
|
+
const activeHandlers = handlerTypes.join(', ')
|
|
102
|
+
result.handler = async () => ({
|
|
103
|
+
statusCode: 200,
|
|
104
|
+
body: `Lambda active (handlers: ${activeHandlers})`,
|
|
105
|
+
})
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
return result
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Creates a Lambda handler with a fetch() entrypoint for HTTP, agent, RPC,
|
|
113
|
+
* and workflow-orchestrator units.
|
|
114
|
+
*/
|
|
115
|
+
export function createLambdaWorkerHandler(factories: LambdaServiceFactories) {
|
|
116
|
+
return {
|
|
117
|
+
async handler(event: APIGatewayProxyEventV2) {
|
|
118
|
+
await setupServices(factories)
|
|
119
|
+
return runFetchV2(event)
|
|
120
|
+
},
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Creates a Lambda handler for WebSocket channel units.
|
|
126
|
+
* Exports separate handlers for $connect, $disconnect, and $default routes.
|
|
127
|
+
*/
|
|
128
|
+
export function createLambdaWebSocketHandler(
|
|
129
|
+
factories: LambdaServiceFactories
|
|
130
|
+
) {
|
|
131
|
+
// Import dynamically to avoid pulling in websocket deps for non-channel units
|
|
132
|
+
const getChannelStore = () => {
|
|
133
|
+
if (!cachedServices) {
|
|
134
|
+
throw new Error('Services not initialized for WebSocket handler')
|
|
135
|
+
}
|
|
136
|
+
const channelStore = (cachedServices as unknown as Record<string, unknown>)
|
|
137
|
+
.channelStore as ChannelStore | undefined
|
|
138
|
+
if (!channelStore) {
|
|
139
|
+
throw new Error(
|
|
140
|
+
'channelStore not found in singleton services. Ensure it is configured for channel units.'
|
|
141
|
+
)
|
|
142
|
+
}
|
|
143
|
+
return channelStore
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return {
|
|
147
|
+
async connect(event: APIGatewayEvent) {
|
|
148
|
+
await setupServices(factories)
|
|
149
|
+
const { connectWebsocket } = await import('./websocket/index.js')
|
|
150
|
+
return connectWebsocket(event, { channelStore: getChannelStore() })
|
|
151
|
+
},
|
|
152
|
+
async disconnect(event: APIGatewayEvent) {
|
|
153
|
+
await setupServices(factories)
|
|
154
|
+
const { disconnectWebsocket } = await import('./websocket/index.js')
|
|
155
|
+
return disconnectWebsocket(event, { channelStore: getChannelStore() })
|
|
156
|
+
},
|
|
157
|
+
async default(event: APIGatewayEvent) {
|
|
158
|
+
await setupServices(factories)
|
|
159
|
+
const { processWebsocketMessage } = await import('./websocket/index.js')
|
|
160
|
+
return processWebsocketMessage(event, {
|
|
161
|
+
channelStore: getChannelStore(),
|
|
162
|
+
})
|
|
163
|
+
},
|
|
164
|
+
}
|
|
165
|
+
}
|
package/src/http/index.ts
CHANGED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { APIGatewayProxyEventV2 } from 'aws-lambda'
|
|
2
|
+
|
|
3
|
+
export const lambdaV2EventToRequest = (
|
|
4
|
+
event: APIGatewayProxyEventV2
|
|
5
|
+
): Request => {
|
|
6
|
+
const host =
|
|
7
|
+
event.headers?.host ?? event.requestContext?.domainName ?? 'localhost'
|
|
8
|
+
const url = new URL(event.rawPath, `https://${host}`)
|
|
9
|
+
|
|
10
|
+
if (event.rawQueryString) {
|
|
11
|
+
// rawQueryString is already encoded, append directly
|
|
12
|
+
url.search = `?${event.rawQueryString}`
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const body =
|
|
16
|
+
event.body && event.isBase64Encoded
|
|
17
|
+
? Buffer.from(event.body, 'base64')
|
|
18
|
+
: event.body || undefined
|
|
19
|
+
|
|
20
|
+
const method = event.requestContext?.http?.method || 'GET'
|
|
21
|
+
|
|
22
|
+
const headers: Record<string, string> = {}
|
|
23
|
+
if (event.headers) {
|
|
24
|
+
for (const [key, value] of Object.entries(event.headers)) {
|
|
25
|
+
if (value != null) {
|
|
26
|
+
headers[key] = value
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
return new Request(url.toString(), {
|
|
32
|
+
method,
|
|
33
|
+
headers,
|
|
34
|
+
body: ['GET', 'HEAD'].includes(method.toUpperCase()) ? undefined : body,
|
|
35
|
+
})
|
|
36
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { APIGatewayProxyStructuredResultV2 } from 'aws-lambda'
|
|
2
|
+
|
|
3
|
+
export const responseToLambdaV2Result = async (
|
|
4
|
+
response: Response
|
|
5
|
+
): Promise<APIGatewayProxyStructuredResultV2> => {
|
|
6
|
+
// Extract Set-Cookie headers as cookies array (v2 format)
|
|
7
|
+
const cookies: string[] = response.headers.getSetCookie
|
|
8
|
+
? response.headers.getSetCookie()
|
|
9
|
+
: []
|
|
10
|
+
|
|
11
|
+
const headers: Record<string, string> = {}
|
|
12
|
+
response.headers.forEach((value, key) => {
|
|
13
|
+
if (key.toLowerCase() === 'set-cookie' && cookies.length > 0) return
|
|
14
|
+
headers[key.toLowerCase()] = value
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
let body: string
|
|
18
|
+
let isBase64Encoded = false
|
|
19
|
+
|
|
20
|
+
const contentType = response.headers.get('content-type') || ''
|
|
21
|
+
const isBinary = !/^text\/|application\/(json|javascript|xml)/.test(
|
|
22
|
+
contentType
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
const buffer = Buffer.from(await response.arrayBuffer())
|
|
26
|
+
if (isBinary) {
|
|
27
|
+
body = buffer.toString('base64')
|
|
28
|
+
isBase64Encoded = true
|
|
29
|
+
} else {
|
|
30
|
+
body = buffer.toString('utf-8')
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
return {
|
|
34
|
+
statusCode: response.status,
|
|
35
|
+
headers,
|
|
36
|
+
body,
|
|
37
|
+
isBase64Encoded,
|
|
38
|
+
...(cookies.length > 0 ? { cookies } : {}),
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { PikkuFetchHTTPResponse, fetchData } from '@pikku/core/http'
|
|
2
|
+
import type {
|
|
3
|
+
APIGatewayProxyEventV2,
|
|
4
|
+
APIGatewayProxyStructuredResultV2,
|
|
5
|
+
} from 'aws-lambda'
|
|
6
|
+
import { responseToLambdaV2Result } from './response-converter-v2.js'
|
|
7
|
+
import { lambdaV2EventToRequest } from './request-converter-v2.js'
|
|
8
|
+
|
|
9
|
+
export const runFetchV2 = async (
|
|
10
|
+
event: APIGatewayProxyEventV2
|
|
11
|
+
): Promise<APIGatewayProxyStructuredResultV2> => {
|
|
12
|
+
const request = lambdaV2EventToRequest(event)
|
|
13
|
+
const response = new PikkuFetchHTTPResponse()
|
|
14
|
+
|
|
15
|
+
if (request.method === 'OPTIONS') {
|
|
16
|
+
response.header(
|
|
17
|
+
'Access-Control-Allow-Origin',
|
|
18
|
+
request.headers.get('origin') || '*'
|
|
19
|
+
)
|
|
20
|
+
response.header(
|
|
21
|
+
'Access-Control-Allow-Headers',
|
|
22
|
+
'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'
|
|
23
|
+
)
|
|
24
|
+
response.header(
|
|
25
|
+
'Access-Control-Allow-Methods',
|
|
26
|
+
'OPTIONS,DELETE,GET,HEAD,PATCH,POST,PUT'
|
|
27
|
+
)
|
|
28
|
+
response.status(200)
|
|
29
|
+
return responseToLambdaV2Result(response.toResponse())
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
try {
|
|
33
|
+
await fetchData(request, response)
|
|
34
|
+
} catch (err) {
|
|
35
|
+
console.error('fetchData error:', err)
|
|
36
|
+
response.status(500)
|
|
37
|
+
response.header('content-type', 'application/json')
|
|
38
|
+
response.json({ error: 'Internal Server Error' })
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return responseToLambdaV2Result(response.toResponse())
|
|
42
|
+
}
|
package/src/http/run-fetch.ts
CHANGED
|
@@ -9,7 +9,7 @@ export const runFetch = async (
|
|
|
9
9
|
const request = lambdaEventToRequest(event)
|
|
10
10
|
const response = new PikkuFetchHTTPResponse()
|
|
11
11
|
|
|
12
|
-
if (request.method === '
|
|
12
|
+
if (request.method === 'OPTIONS') {
|
|
13
13
|
response.header(
|
|
14
14
|
'Access-Control-Allow-Headers',
|
|
15
15
|
'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import { describe, test } from 'node:test'
|
|
3
|
+
|
|
4
|
+
import * as lambdaRuntime from './index.js'
|
|
5
|
+
|
|
6
|
+
describe('@pikku/lambda', () => {
|
|
7
|
+
test('exports the lambda runtime API', () => {
|
|
8
|
+
assert.equal(typeof lambdaRuntime.createLambdaHandler, 'function')
|
|
9
|
+
assert.equal(typeof lambdaRuntime.LambdaDeploymentService, 'function')
|
|
10
|
+
assert.equal(typeof lambdaRuntime.SQSQueueService, 'function')
|
|
11
|
+
assert.equal(typeof lambdaRuntime.runFetch, 'function')
|
|
12
|
+
})
|
|
13
|
+
})
|
package/src/index.ts
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
1
|
export * from './http/index.js'
|
|
2
2
|
export * from './websocket/index.js'
|
|
3
3
|
export * from './queue/index.js'
|
|
4
|
+
export * from './scheduled/index.js'
|
|
5
|
+
export * from './handler-factories.js'
|
|
6
|
+
export { SQSQueueService } from './sqs-queue-service.js'
|
|
7
|
+
export { LambdaDeploymentService } from './lambda-deployment-service.js'
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lambda deployment service — routes remote() calls via Lambda Invoke.
|
|
3
|
+
*
|
|
4
|
+
* When a gateway (agent, MCP, channel, workflow orchestrator) calls
|
|
5
|
+
* remote('funcName'), this service dispatches to the function's Lambda
|
|
6
|
+
* via the AWS SDK InvokeCommand. Equivalent to Cloudflare's service bindings.
|
|
7
|
+
*
|
|
8
|
+
* Session propagation uses the existing pikkuRemoteAuthMiddleware:
|
|
9
|
+
* JWT signed with PIKKU_REMOTE_SECRET, session encrypted in payload.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { LambdaClient, InvokeCommand } from '@aws-sdk/client-lambda'
|
|
13
|
+
import type { DeploymentService, DeploymentConfig } from '@pikku/core/services'
|
|
14
|
+
import type { JWTService } from '@pikku/core/services'
|
|
15
|
+
import type { SecretService } from '@pikku/core/services'
|
|
16
|
+
import { encryptJSON } from '@pikku/core/crypto-utils'
|
|
17
|
+
|
|
18
|
+
export class LambdaDeploymentService implements DeploymentService {
|
|
19
|
+
private client: LambdaClient
|
|
20
|
+
private bindings: Map<string, string>
|
|
21
|
+
|
|
22
|
+
constructor(
|
|
23
|
+
private jwt: JWTService | undefined,
|
|
24
|
+
private secrets: SecretService,
|
|
25
|
+
functionBindings: Record<string, string>
|
|
26
|
+
) {
|
|
27
|
+
this.client = new LambdaClient({})
|
|
28
|
+
this.bindings = new Map(Object.entries(functionBindings))
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async init(): Promise<void> {}
|
|
32
|
+
async start(_config: DeploymentConfig): Promise<void> {}
|
|
33
|
+
async stop(): Promise<void> {}
|
|
34
|
+
|
|
35
|
+
async invoke(
|
|
36
|
+
funcName: string,
|
|
37
|
+
data: unknown,
|
|
38
|
+
session?: unknown,
|
|
39
|
+
traceId?: string
|
|
40
|
+
): Promise<unknown> {
|
|
41
|
+
const lambdaFunctionName = this.bindings.get(funcName)
|
|
42
|
+
if (!lambdaFunctionName) {
|
|
43
|
+
throw new Error(
|
|
44
|
+
`No Lambda binding for function '${funcName}'. ` +
|
|
45
|
+
`Available bindings: ${[...this.bindings.keys()].join(', ')}`
|
|
46
|
+
)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const headers: Record<string, string> = {
|
|
50
|
+
'content-type': 'application/json',
|
|
51
|
+
...(traceId && { 'x-request-id': traceId }),
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Sign session as JWT for pikkuRemoteAuthMiddleware
|
|
55
|
+
let secret: string | undefined
|
|
56
|
+
try {
|
|
57
|
+
secret = await this.secrets.getSecret('PIKKU_REMOTE_SECRET')
|
|
58
|
+
} catch {}
|
|
59
|
+
|
|
60
|
+
if (secret && this.jwt) {
|
|
61
|
+
const sessionEnc = session
|
|
62
|
+
? await encryptJSON(secret, { session })
|
|
63
|
+
: undefined
|
|
64
|
+
const token = await this.jwt.encode(
|
|
65
|
+
{ value: 5, unit: 'minute' },
|
|
66
|
+
{
|
|
67
|
+
aud: 'pikku-remote',
|
|
68
|
+
fn: funcName,
|
|
69
|
+
iat: Math.floor(Date.now() / 1000),
|
|
70
|
+
session: sessionEnc,
|
|
71
|
+
}
|
|
72
|
+
)
|
|
73
|
+
headers.authorization = `Bearer ${token}`
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Build an API Gateway v2 event for the target Lambda
|
|
77
|
+
const rpcPath = `/remote/rpc/${encodeURIComponent(funcName)}`
|
|
78
|
+
const apiGatewayEvent = {
|
|
79
|
+
httpMethod: 'POST',
|
|
80
|
+
path: rpcPath,
|
|
81
|
+
headers,
|
|
82
|
+
body: JSON.stringify({ data }),
|
|
83
|
+
isBase64Encoded: false,
|
|
84
|
+
queryStringParameters: null,
|
|
85
|
+
pathParameters: null,
|
|
86
|
+
stageVariables: null,
|
|
87
|
+
requestContext: {
|
|
88
|
+
httpMethod: 'POST',
|
|
89
|
+
path: rpcPath,
|
|
90
|
+
stage: 'prod',
|
|
91
|
+
requestId: crypto.randomUUID(),
|
|
92
|
+
identity: {},
|
|
93
|
+
},
|
|
94
|
+
resource: rpcPath,
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const response = await this.client.send(
|
|
98
|
+
new InvokeCommand({
|
|
99
|
+
FunctionName: lambdaFunctionName,
|
|
100
|
+
Payload: JSON.stringify(apiGatewayEvent),
|
|
101
|
+
})
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
if (response.FunctionError) {
|
|
105
|
+
const errorPayload = response.Payload
|
|
106
|
+
? new TextDecoder().decode(response.Payload)
|
|
107
|
+
: 'Unknown error'
|
|
108
|
+
throw new Error(
|
|
109
|
+
`Remote RPC call to '${funcName}' failed: Lambda error: ${errorPayload}`
|
|
110
|
+
)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (!response.Payload) {
|
|
114
|
+
throw new Error(`Remote RPC call to '${funcName}' returned no payload`)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// The Lambda returns an API Gateway response shape
|
|
118
|
+
const lambdaResult = JSON.parse(new TextDecoder().decode(response.Payload))
|
|
119
|
+
|
|
120
|
+
if (lambdaResult.statusCode && lambdaResult.statusCode >= 400) {
|
|
121
|
+
throw new Error(
|
|
122
|
+
`Remote RPC call to '${funcName}' failed: ${lambdaResult.statusCode} ${lambdaResult.body}`
|
|
123
|
+
)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Parse the body from the API Gateway response
|
|
127
|
+
const body = lambdaResult.body
|
|
128
|
+
try {
|
|
129
|
+
return JSON.parse(body)
|
|
130
|
+
} catch {
|
|
131
|
+
return body
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
package/src/queue/sqs-worker.ts
CHANGED
|
@@ -60,7 +60,7 @@ export const runSQSQueueWorker = async (
|
|
|
60
60
|
logger: Logger,
|
|
61
61
|
event: SQSEvent
|
|
62
62
|
): Promise<SQSBatchResponse> => {
|
|
63
|
-
|
|
63
|
+
logger.info(`Processing ${event.Records.length} SQS messages`)
|
|
64
64
|
const jobs = event.Records.map(mapSQSRecordToQueueJob)
|
|
65
65
|
|
|
66
66
|
// Process all jobs in parallel
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { runLambdaScheduled } from './run-scheduled.js'
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lambda handler for EventBridge scheduled events.
|
|
3
|
+
*
|
|
4
|
+
* Since each Lambda corresponds to a single unit, and each unit has
|
|
5
|
+
* specific scheduled tasks registered, we run all tasks in this unit
|
|
6
|
+
* when the schedule fires.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { ScheduledEvent } from 'aws-lambda'
|
|
10
|
+
import { runScheduledTask, getScheduledTasks } from '@pikku/core/scheduler'
|
|
11
|
+
|
|
12
|
+
export const runLambdaScheduled = async (
|
|
13
|
+
_event: ScheduledEvent
|
|
14
|
+
): Promise<void> => {
|
|
15
|
+
const scheduledTasks = getScheduledTasks()
|
|
16
|
+
|
|
17
|
+
// Run all scheduled tasks registered in this unit.
|
|
18
|
+
// Typically one task per unit, but iterate all to be safe.
|
|
19
|
+
for (const [name] of scheduledTasks) {
|
|
20
|
+
const traceId = `cron-${crypto.randomUUID()}`
|
|
21
|
+
try {
|
|
22
|
+
await runScheduledTask({ name, traceId })
|
|
23
|
+
} catch (err) {
|
|
24
|
+
console.error(
|
|
25
|
+
`Scheduled task '${name}' (traceId: ${traceId}) failed:`,
|
|
26
|
+
err
|
|
27
|
+
)
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SQS implementation of QueueService (producer side).
|
|
3
|
+
*
|
|
4
|
+
* Sends messages to SQS queues. Queue URLs are resolved from environment
|
|
5
|
+
* variables following the convention: SQS_QUEUE_URL_<SCREAMING_SNAKE_NAME>.
|
|
6
|
+
*
|
|
7
|
+
* The consumer side is handled by sqs-worker.ts (runSQSQueueWorker).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { SQSClient, SendMessageCommand } from '@aws-sdk/client-sqs'
|
|
11
|
+
import type { QueueService, QueueJob, JobOptions } from '@pikku/core/queue'
|
|
12
|
+
|
|
13
|
+
export class SQSQueueService implements QueueService {
|
|
14
|
+
readonly supportsResults = false
|
|
15
|
+
private client: SQSClient
|
|
16
|
+
|
|
17
|
+
constructor(private queueUrlMap?: Record<string, string>) {
|
|
18
|
+
this.client = new SQSClient({})
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async add<T>(
|
|
22
|
+
queueName: string,
|
|
23
|
+
data: T,
|
|
24
|
+
options?: JobOptions
|
|
25
|
+
): Promise<string> {
|
|
26
|
+
const queueUrl = this.resolveQueueUrl(queueName)
|
|
27
|
+
const messageId = crypto.randomUUID()
|
|
28
|
+
|
|
29
|
+
const message = {
|
|
30
|
+
id: messageId,
|
|
31
|
+
queueName,
|
|
32
|
+
data,
|
|
33
|
+
pikkuUserId: options?.pikkuUserId,
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const result = await this.client.send(
|
|
37
|
+
new SendMessageCommand({
|
|
38
|
+
QueueUrl: queueUrl,
|
|
39
|
+
MessageBody: JSON.stringify(message),
|
|
40
|
+
DelaySeconds: options?.delay
|
|
41
|
+
? Math.min(Math.ceil(options.delay / 1000), 900)
|
|
42
|
+
: undefined,
|
|
43
|
+
})
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
return result.MessageId ?? messageId
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async getJob<T, R>(
|
|
50
|
+
_queueName: string,
|
|
51
|
+
_jobId: string
|
|
52
|
+
): Promise<QueueJob<T, R> | null> {
|
|
53
|
+
throw new Error(
|
|
54
|
+
'SQSQueueService does not support getJob(). ' +
|
|
55
|
+
'SQS is fire-and-forget. ' +
|
|
56
|
+
'Use BullMQ or PgBoss if you need job result tracking.'
|
|
57
|
+
)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Resolves the SQS queue URL for a given queue name.
|
|
62
|
+
*
|
|
63
|
+
* Checks in order:
|
|
64
|
+
* 1. Explicit queueUrlMap passed in constructor
|
|
65
|
+
* 2. Environment variable SQS_QUEUE_URL_<SCREAMING_SNAKE>
|
|
66
|
+
*/
|
|
67
|
+
private resolveQueueUrl(queueName: string): string {
|
|
68
|
+
if (this.queueUrlMap?.[queueName]) {
|
|
69
|
+
return this.queueUrlMap[queueName]
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const envKey = `SQS_QUEUE_URL_${toScreamingSnake(queueName)}`
|
|
73
|
+
const url = process.env[envKey]
|
|
74
|
+
|
|
75
|
+
if (!url) {
|
|
76
|
+
throw new Error(
|
|
77
|
+
`SQS queue URL not found for queue "${queueName}". ` +
|
|
78
|
+
`Set environment variable ${envKey} or pass queueUrlMap to constructor.`
|
|
79
|
+
)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return url
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function toScreamingSnake(name: string): string {
|
|
87
|
+
return name
|
|
88
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1_$2')
|
|
89
|
+
.replace(/-/g, '_')
|
|
90
|
+
.toUpperCase()
|
|
91
|
+
}
|
|
@@ -8,9 +8,9 @@ import { getApiGatewayManagementApiClient, sendMessages } from './utils.js'
|
|
|
8
8
|
import type { Logger } from '@pikku/core/services'
|
|
9
9
|
import type { APIGatewayEvent } from 'aws-lambda'
|
|
10
10
|
|
|
11
|
-
export class LambdaEventHubService<
|
|
12
|
-
|
|
13
|
-
{
|
|
11
|
+
export class LambdaEventHubService<
|
|
12
|
+
EventTopics extends Record<string, any> = {},
|
|
13
|
+
> implements EventHubService<EventTopics> {
|
|
14
14
|
private callbackAPI: ApiGatewayManagementApiClient
|
|
15
15
|
|
|
16
16
|
constructor(
|
package/tsconfig.tsbuildinfo
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"root":["./src/index.ts","./src/request-converter.ts","./src/response-converter.ts","./src/http/index.ts","./src/http/run-fetch.ts","./src/queue/index.ts","./src/queue/sqs-worker.ts","./src/websocket/index.ts","./src/websocket/lambda-channel-handler.ts","./src/websocket/lambda-eventhub-service.ts","./src/websocket/utils.ts","./src/websocket/websocket-connect.ts","./src/websocket/websocket-disconnect.ts","./src/websocket/websocket-message.ts","./src/websocket/websocket-types.ts"],"version":"
|
|
1
|
+
{"root":["./src/handler-factories.ts","./src/index.ts","./src/lambda-deployment-service.ts","./src/request-converter.ts","./src/response-converter.ts","./src/sqs-queue-service.ts","./src/http/index.ts","./src/http/request-converter-v2.ts","./src/http/response-converter-v2.ts","./src/http/run-fetch-v2.ts","./src/http/run-fetch.ts","./src/queue/index.ts","./src/queue/sqs-worker.ts","./src/scheduled/index.ts","./src/scheduled/run-scheduled.ts","./src/websocket/index.ts","./src/websocket/lambda-channel-handler.ts","./src/websocket/lambda-eventhub-service.ts","./src/websocket/utils.ts","./src/websocket/websocket-connect.ts","./src/websocket/websocket-disconnect.ts","./src/websocket/websocket-message.ts","./src/websocket/websocket-types.ts"],"version":"6.0.3"}
|