@pikku/lambda 0.12.10 → 0.12.12
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/dist/lambda-deployment-service.js.map +1 -1
- package/dist/sqs-queue-service.js.map +1 -1
- package/dist/websocket/lambda-channel-handler.js.map +1 -1
- package/dist/websocket/lambda-eventhub-service.js.map +1 -1
- package/package.json +21 -11
- package/CHANGELOG.md +0 -679
- package/run-tests.sh +0 -53
- package/src/handler-factories.ts +0 -164
- package/src/http/index.ts +0 -2
- package/src/http/request-converter-v2.ts +0 -36
- package/src/http/response-converter-v2.ts +0 -40
- package/src/http/run-fetch-v2.ts +0 -42
- package/src/http/run-fetch.ts +0 -32
- package/src/index.test.ts +0 -13
- package/src/index.ts +0 -11
- package/src/lambda-deployment-service.ts +0 -115
- package/src/queue/index.ts +0 -1
- package/src/queue/sqs-worker.ts +0 -101
- package/src/request-converter.ts +0 -24
- package/src/response-converter.ts +0 -33
- package/src/scheduled/index.ts +0 -1
- package/src/scheduled/run-scheduled.ts +0 -31
- package/src/sqs-queue-service.ts +0 -92
- package/src/websocket/index.ts +0 -4
- package/src/websocket/lambda-channel-handler.ts +0 -58
- package/src/websocket/lambda-eventhub-service.ts +0 -66
- package/src/websocket/utils.ts +0 -96
- package/src/websocket/websocket-connect.ts +0 -23
- package/src/websocket/websocket-disconnect.ts +0 -14
- package/src/websocket/websocket-message.ts +0 -23
- package/src/websocket/websocket-types.ts +0 -5
- package/tsconfig.json +0 -17
- package/tsconfig.tsbuildinfo +0 -1
package/run-tests.sh
DELETED
|
@@ -1,53 +0,0 @@
|
|
|
1
|
-
#!/bin/bash
|
|
2
|
-
|
|
3
|
-
# Enable nullglob to handle cases where no files match the pattern
|
|
4
|
-
shopt -s nullglob
|
|
5
|
-
|
|
6
|
-
# Initialize variables for options
|
|
7
|
-
watch_mode=false
|
|
8
|
-
coverage_mode=false
|
|
9
|
-
|
|
10
|
-
# Parse command-line options
|
|
11
|
-
while [[ $# -gt 0 ]]; do
|
|
12
|
-
case $1 in
|
|
13
|
-
--watch)
|
|
14
|
-
watch_mode=true
|
|
15
|
-
shift
|
|
16
|
-
;;
|
|
17
|
-
--coverage)
|
|
18
|
-
coverage_mode=true
|
|
19
|
-
shift
|
|
20
|
-
;;
|
|
21
|
-
*)
|
|
22
|
-
echo "Unknown option: $1"
|
|
23
|
-
exit 1
|
|
24
|
-
;;
|
|
25
|
-
esac
|
|
26
|
-
done
|
|
27
|
-
|
|
28
|
-
# Define the pattern to match your test files
|
|
29
|
-
pattern="src/*.test.ts"
|
|
30
|
-
|
|
31
|
-
# Expand the pattern into an array of files
|
|
32
|
-
files=($(find src -type f -name "*.test.ts"))
|
|
33
|
-
|
|
34
|
-
# Check if any files matched the pattern
|
|
35
|
-
if [ ${#files[@]} -eq 0 ]; then
|
|
36
|
-
echo "No test files found matching pattern: $pattern"
|
|
37
|
-
exit 0
|
|
38
|
-
fi
|
|
39
|
-
|
|
40
|
-
# Construct the node command
|
|
41
|
-
node_cmd=(node --import tsx --test)
|
|
42
|
-
|
|
43
|
-
# Append options based on flags
|
|
44
|
-
if [ "$watch_mode" = true ]; then
|
|
45
|
-
node_cmd+=(--watch)
|
|
46
|
-
fi
|
|
47
|
-
|
|
48
|
-
if [ "$coverage_mode" = true ]; then
|
|
49
|
-
node_cmd+=(--test-coverage-include="src/**/*.{ts,js}" --test-coverage-exclude="**/dist/**" --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=lcov.info)
|
|
50
|
-
fi
|
|
51
|
-
|
|
52
|
-
# Execute the node command with the expanded list of files
|
|
53
|
-
"${node_cmd[@]}" "${files[@]}"
|
package/src/handler-factories.ts
DELETED
|
@@ -1,164 +0,0 @@
|
|
|
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/types'
|
|
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> | Promise<Record<string, unknown>>
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
let cachedServices: CoreSingletonServices | null = null
|
|
40
|
-
|
|
41
|
-
async function setupServices(
|
|
42
|
-
factories: LambdaServiceFactories
|
|
43
|
-
): Promise<CoreSingletonServices> {
|
|
44
|
-
if (cachedServices) return cachedServices
|
|
45
|
-
const variables = new LocalVariablesService(
|
|
46
|
-
process.env as Record<string, string | undefined>
|
|
47
|
-
)
|
|
48
|
-
const config = await factories.createConfig(variables)
|
|
49
|
-
const secrets = new LocalSecretService(variables)
|
|
50
|
-
|
|
51
|
-
const platformServices = factories.createPlatformServices
|
|
52
|
-
? await factories.createPlatformServices()
|
|
53
|
-
: {}
|
|
54
|
-
|
|
55
|
-
cachedServices = await factories.createSingletonServices(config, {
|
|
56
|
-
variables,
|
|
57
|
-
secrets,
|
|
58
|
-
...platformServices,
|
|
59
|
-
})
|
|
60
|
-
return cachedServices
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
/**
|
|
64
|
-
* Creates a combined Lambda handler based on which handler types the unit needs.
|
|
65
|
-
*
|
|
66
|
-
* Returns an object with named exports that serverless.yml references:
|
|
67
|
-
* - `handler` for HTTP (API Gateway)
|
|
68
|
-
* - `queue` for SQS
|
|
69
|
-
* - `scheduled` for EventBridge
|
|
70
|
-
*/
|
|
71
|
-
export function createLambdaHandler(
|
|
72
|
-
factories: LambdaServiceFactories,
|
|
73
|
-
handlerTypes: string[]
|
|
74
|
-
) {
|
|
75
|
-
const result: Record<string, unknown> = {}
|
|
76
|
-
|
|
77
|
-
if (handlerTypes.includes('fetch')) {
|
|
78
|
-
result.handler = async (event: APIGatewayProxyEventV2) => {
|
|
79
|
-
await setupServices(factories)
|
|
80
|
-
return runFetchV2(event)
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
if (handlerTypes.includes('queue')) {
|
|
85
|
-
result.queue = async (event: SQSEvent) => {
|
|
86
|
-
const services = await setupServices(factories)
|
|
87
|
-
return runSQSQueueWorker(services.logger, event)
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
if (handlerTypes.includes('scheduled')) {
|
|
92
|
-
result.scheduled = async (event: ScheduledEvent) => {
|
|
93
|
-
await setupServices(factories)
|
|
94
|
-
return runLambdaScheduled(event)
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
// If no fetch handler was requested, add a health check
|
|
99
|
-
if (!handlerTypes.includes('fetch')) {
|
|
100
|
-
const activeHandlers = handlerTypes.join(', ')
|
|
101
|
-
result.handler = async () => ({
|
|
102
|
-
statusCode: 200,
|
|
103
|
-
body: `Lambda active (handlers: ${activeHandlers})`,
|
|
104
|
-
})
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
return result
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
/**
|
|
111
|
-
* Creates a Lambda handler with a fetch() entrypoint for HTTP, agent, RPC,
|
|
112
|
-
* and workflow-orchestrator units.
|
|
113
|
-
*/
|
|
114
|
-
export function createLambdaWorkerHandler(factories: LambdaServiceFactories) {
|
|
115
|
-
return {
|
|
116
|
-
async handler(event: APIGatewayProxyEventV2) {
|
|
117
|
-
await setupServices(factories)
|
|
118
|
-
return runFetchV2(event)
|
|
119
|
-
},
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
/**
|
|
124
|
-
* Creates a Lambda handler for WebSocket channel units.
|
|
125
|
-
* Exports separate handlers for $connect, $disconnect, and $default routes.
|
|
126
|
-
*/
|
|
127
|
-
export function createLambdaWebSocketHandler(
|
|
128
|
-
factories: LambdaServiceFactories
|
|
129
|
-
) {
|
|
130
|
-
// Import dynamically to avoid pulling in websocket deps for non-channel units
|
|
131
|
-
const getChannelStore = () => {
|
|
132
|
-
if (!cachedServices) {
|
|
133
|
-
throw new Error('Services not initialized for WebSocket handler')
|
|
134
|
-
}
|
|
135
|
-
const channelStore = (cachedServices as unknown as Record<string, unknown>)
|
|
136
|
-
.channelStore as ChannelStore | undefined
|
|
137
|
-
if (!channelStore) {
|
|
138
|
-
throw new Error(
|
|
139
|
-
'channelStore not found in singleton services. Ensure it is configured for channel units.'
|
|
140
|
-
)
|
|
141
|
-
}
|
|
142
|
-
return channelStore
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
return {
|
|
146
|
-
async connect(event: APIGatewayEvent) {
|
|
147
|
-
await setupServices(factories)
|
|
148
|
-
const { connectWebsocket } = await import('./websocket/index.js')
|
|
149
|
-
return connectWebsocket(event, { channelStore: getChannelStore() })
|
|
150
|
-
},
|
|
151
|
-
async disconnect(event: APIGatewayEvent) {
|
|
152
|
-
await setupServices(factories)
|
|
153
|
-
const { disconnectWebsocket } = await import('./websocket/index.js')
|
|
154
|
-
return disconnectWebsocket(event, { channelStore: getChannelStore() })
|
|
155
|
-
},
|
|
156
|
-
async default(event: APIGatewayEvent) {
|
|
157
|
-
await setupServices(factories)
|
|
158
|
-
const { processWebsocketMessage } = await import('./websocket/index.js')
|
|
159
|
-
return processWebsocketMessage(event, {
|
|
160
|
-
channelStore: getChannelStore(),
|
|
161
|
-
})
|
|
162
|
-
},
|
|
163
|
-
}
|
|
164
|
-
}
|
package/src/http/index.ts
DELETED
|
@@ -1,36 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1,40 +0,0 @@
|
|
|
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
|
-
}
|
package/src/http/run-fetch-v2.ts
DELETED
|
@@ -1,42 +0,0 @@
|
|
|
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
DELETED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
import { PikkuFetchHTTPResponse, fetchData } from '@pikku/core/http'
|
|
2
|
-
import type { APIGatewayEvent, APIGatewayProxyResult } from 'aws-lambda'
|
|
3
|
-
import { responseToLambdaResult } from '../response-converter.js'
|
|
4
|
-
import { lambdaEventToRequest } from '../request-converter.js'
|
|
5
|
-
|
|
6
|
-
export const runFetch = async (
|
|
7
|
-
event: APIGatewayEvent
|
|
8
|
-
): Promise<APIGatewayProxyResult> => {
|
|
9
|
-
const request = lambdaEventToRequest(event)
|
|
10
|
-
const response = new PikkuFetchHTTPResponse()
|
|
11
|
-
|
|
12
|
-
if (request.method === 'OPTIONS') {
|
|
13
|
-
response.header(
|
|
14
|
-
'Access-Control-Allow-Headers',
|
|
15
|
-
'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'
|
|
16
|
-
)
|
|
17
|
-
response.header(
|
|
18
|
-
'Access-Control-Allow-Methods',
|
|
19
|
-
'OPTIONS,DELETE,GET,HEAD,PATCH,POST,PUT'
|
|
20
|
-
)
|
|
21
|
-
response.status(200)
|
|
22
|
-
return responseToLambdaResult(response.toResponse())
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
try {
|
|
26
|
-
await fetchData(request, response)
|
|
27
|
-
} catch {
|
|
28
|
-
// Error should have already been handled by fetch
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
return responseToLambdaResult(response.toResponse())
|
|
32
|
-
}
|
package/src/index.test.ts
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
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
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
export * from './http/index.js'
|
|
2
|
-
export * from './websocket/index.js'
|
|
3
|
-
export * from './queue/index.js'
|
|
4
|
-
export * from './scheduled/index.js'
|
|
5
|
-
export {
|
|
6
|
-
createLambdaHandler,
|
|
7
|
-
createLambdaWorkerHandler,
|
|
8
|
-
createLambdaWebSocketHandler,
|
|
9
|
-
} from './handler-factories.js'
|
|
10
|
-
export { SQSQueueService } from './sqs-queue-service.js'
|
|
11
|
-
export { LambdaDeploymentService } from './lambda-deployment-service.js'
|
|
@@ -1,115 +0,0 @@
|
|
|
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 { buildRemoteHeaders } from '@pikku/core/remote'
|
|
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 = await buildRemoteHeaders(
|
|
50
|
-
this.jwt,
|
|
51
|
-
this.secrets,
|
|
52
|
-
funcName,
|
|
53
|
-
session,
|
|
54
|
-
traceId
|
|
55
|
-
)
|
|
56
|
-
|
|
57
|
-
// Build an API Gateway v2 event for the target Lambda
|
|
58
|
-
const rpcPath = `/remote/rpc/${encodeURIComponent(funcName)}`
|
|
59
|
-
const apiGatewayEvent = {
|
|
60
|
-
httpMethod: 'POST',
|
|
61
|
-
path: rpcPath,
|
|
62
|
-
headers,
|
|
63
|
-
body: JSON.stringify({ data }),
|
|
64
|
-
isBase64Encoded: false,
|
|
65
|
-
queryStringParameters: null,
|
|
66
|
-
pathParameters: null,
|
|
67
|
-
stageVariables: null,
|
|
68
|
-
requestContext: {
|
|
69
|
-
httpMethod: 'POST',
|
|
70
|
-
path: rpcPath,
|
|
71
|
-
stage: 'prod',
|
|
72
|
-
requestId: crypto.randomUUID(),
|
|
73
|
-
identity: {},
|
|
74
|
-
},
|
|
75
|
-
resource: rpcPath,
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
const response = await this.client.send(
|
|
79
|
-
new InvokeCommand({
|
|
80
|
-
FunctionName: lambdaFunctionName,
|
|
81
|
-
Payload: JSON.stringify(apiGatewayEvent),
|
|
82
|
-
})
|
|
83
|
-
)
|
|
84
|
-
|
|
85
|
-
if (response.FunctionError) {
|
|
86
|
-
const errorPayload = response.Payload
|
|
87
|
-
? new TextDecoder().decode(response.Payload)
|
|
88
|
-
: 'Unknown error'
|
|
89
|
-
throw new Error(
|
|
90
|
-
`Remote RPC call to '${funcName}' failed: Lambda error: ${errorPayload}`
|
|
91
|
-
)
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
if (!response.Payload) {
|
|
95
|
-
throw new Error(`Remote RPC call to '${funcName}' returned no payload`)
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
// The Lambda returns an API Gateway response shape
|
|
99
|
-
const lambdaResult = JSON.parse(new TextDecoder().decode(response.Payload))
|
|
100
|
-
|
|
101
|
-
if (lambdaResult.statusCode && lambdaResult.statusCode >= 400) {
|
|
102
|
-
throw new Error(
|
|
103
|
-
`Remote RPC call to '${funcName}' failed: ${lambdaResult.statusCode} ${lambdaResult.body}`
|
|
104
|
-
)
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
// Parse the body from the API Gateway response
|
|
108
|
-
const body = lambdaResult.body
|
|
109
|
-
try {
|
|
110
|
-
return JSON.parse(body)
|
|
111
|
-
} catch {
|
|
112
|
-
return body
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
}
|
package/src/queue/index.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { runSQSQueueWorker } from './sqs-worker.js'
|
package/src/queue/sqs-worker.ts
DELETED
|
@@ -1,101 +0,0 @@
|
|
|
1
|
-
import type { SQSBatchResponse, SQSEvent, SQSRecord } from 'aws-lambda'
|
|
2
|
-
import { runQueueJob } from '@pikku/core/queue'
|
|
3
|
-
import { QueueJobFailedError, QueueJobDiscardedError } from '@pikku/core/queue'
|
|
4
|
-
import type { Logger } from '@pikku/core/services'
|
|
5
|
-
import type { QueueJob, QueueJobStatus } from '@pikku/core/queue'
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* Enhanced version with additional SQS-specific features
|
|
9
|
-
*/
|
|
10
|
-
export function mapSQSRecordToQueueJob(
|
|
11
|
-
record: SQSRecord,
|
|
12
|
-
maxAttempts?: number
|
|
13
|
-
): QueueJob {
|
|
14
|
-
let data: any
|
|
15
|
-
|
|
16
|
-
try {
|
|
17
|
-
data = JSON.parse(record.body)
|
|
18
|
-
} catch {
|
|
19
|
-
data = record.body
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
if (!record.eventSourceARN) {
|
|
23
|
-
throw new Error('SQS record does not have eventSourceARN')
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
const queueName = record.eventSourceARN.split(':').pop()!
|
|
27
|
-
|
|
28
|
-
const job: QueueJob = {
|
|
29
|
-
queueName,
|
|
30
|
-
data,
|
|
31
|
-
id: record.messageId,
|
|
32
|
-
status: async () => 'active' as QueueJobStatus,
|
|
33
|
-
metadata: () => ({
|
|
34
|
-
processedAt: new Date(),
|
|
35
|
-
attemptsMade: parseInt(record.attributes.ApproximateReceiveCount) - 1,
|
|
36
|
-
maxAttempts,
|
|
37
|
-
result: undefined,
|
|
38
|
-
progress: 0,
|
|
39
|
-
createdAt: new Date(parseInt(record.attributes.SentTimestamp)),
|
|
40
|
-
completedAt: undefined,
|
|
41
|
-
failedAt: undefined,
|
|
42
|
-
error: undefined,
|
|
43
|
-
}),
|
|
44
|
-
waitForCompletion: async () => {
|
|
45
|
-
throw new Error(
|
|
46
|
-
'SQS does not support waitForCompletion - jobs are fire-and-forget'
|
|
47
|
-
)
|
|
48
|
-
},
|
|
49
|
-
}
|
|
50
|
-
return job
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* Create an SQS handler that processes queue jobs using Pikku
|
|
55
|
-
*/
|
|
56
|
-
export const runSQSQueueWorker = async (
|
|
57
|
-
logger: Logger,
|
|
58
|
-
event: SQSEvent
|
|
59
|
-
): Promise<SQSBatchResponse> => {
|
|
60
|
-
logger.info(`Processing ${event.Records.length} SQS messages`)
|
|
61
|
-
const jobs = event.Records.map(mapSQSRecordToQueueJob)
|
|
62
|
-
|
|
63
|
-
// Process all jobs in parallel
|
|
64
|
-
const results = await Promise.allSettled(
|
|
65
|
-
jobs.map(async (job) => {
|
|
66
|
-
try {
|
|
67
|
-
return await runQueueJob({ job })
|
|
68
|
-
} catch (error: unknown) {
|
|
69
|
-
if (error instanceof QueueJobFailedError) {
|
|
70
|
-
// Let SQS handle this as a failed job (will go to retry or DLQ)
|
|
71
|
-
throw error
|
|
72
|
-
} else if (error instanceof QueueJobDiscardedError) {
|
|
73
|
-
// For SQS, discarding means completing successfully (no retry)
|
|
74
|
-
logger.info(`SQS job ${job.id} discarded: ${error.message}`)
|
|
75
|
-
return
|
|
76
|
-
}
|
|
77
|
-
throw error
|
|
78
|
-
}
|
|
79
|
-
})
|
|
80
|
-
)
|
|
81
|
-
|
|
82
|
-
// Log any failures but don't throw (SQS will handle retries)
|
|
83
|
-
results.forEach((result, index) => {
|
|
84
|
-
if (result.status === 'rejected') {
|
|
85
|
-
logger.error(
|
|
86
|
-
`Failed to process SQS message ${jobs[index]!.id}:`,
|
|
87
|
-
result.reason
|
|
88
|
-
)
|
|
89
|
-
}
|
|
90
|
-
})
|
|
91
|
-
|
|
92
|
-
return {
|
|
93
|
-
batchItemFailures: results
|
|
94
|
-
.map((result, index) => ({
|
|
95
|
-
result,
|
|
96
|
-
itemIdentifier: jobs[index]!.id || `message-${index}`,
|
|
97
|
-
}))
|
|
98
|
-
.filter(({ result }) => result.status === 'rejected')
|
|
99
|
-
.map(({ itemIdentifier }) => ({ itemIdentifier })),
|
|
100
|
-
}
|
|
101
|
-
}
|
package/src/request-converter.ts
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import type { APIGatewayProxyEvent } from 'aws-lambda'
|
|
2
|
-
|
|
3
|
-
export const lambdaEventToRequest = (event: APIGatewayProxyEvent): Request => {
|
|
4
|
-
const url = new URL(event.path, `https://${event.headers.host}`)
|
|
5
|
-
|
|
6
|
-
if (event.queryStringParameters) {
|
|
7
|
-
for (const [key, value] of Object.entries(event.queryStringParameters)) {
|
|
8
|
-
if (value !== undefined) url.searchParams.set(key, value)
|
|
9
|
-
}
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
const body =
|
|
13
|
-
event.body && event.isBase64Encoded
|
|
14
|
-
? Buffer.from(event.body, 'base64')
|
|
15
|
-
: event.body || undefined
|
|
16
|
-
|
|
17
|
-
const method = event.httpMethod || 'GET'
|
|
18
|
-
|
|
19
|
-
return new Request(url.toString(), {
|
|
20
|
-
method,
|
|
21
|
-
headers: event.headers as HeadersInit,
|
|
22
|
-
body: ['GET', 'HEAD'].includes(method.toUpperCase()) ? undefined : body,
|
|
23
|
-
})
|
|
24
|
-
}
|
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
import type { APIGatewayProxyResult } from 'aws-lambda'
|
|
2
|
-
|
|
3
|
-
export const responseToLambdaResult = async (
|
|
4
|
-
response: Response
|
|
5
|
-
): Promise<APIGatewayProxyResult> => {
|
|
6
|
-
const headers: Record<string, string> = {}
|
|
7
|
-
response.headers.forEach((value, key) => {
|
|
8
|
-
headers[key.toLowerCase()] = value
|
|
9
|
-
})
|
|
10
|
-
|
|
11
|
-
let body: string
|
|
12
|
-
let isBase64Encoded = false
|
|
13
|
-
|
|
14
|
-
const contentType = response.headers.get('content-type') || ''
|
|
15
|
-
const isBinary = !/^text\/|application\/(json|javascript|xml)/.test(
|
|
16
|
-
contentType
|
|
17
|
-
)
|
|
18
|
-
|
|
19
|
-
const buffer = Buffer.from(await response.arrayBuffer())
|
|
20
|
-
if (isBinary) {
|
|
21
|
-
body = buffer.toString('base64')
|
|
22
|
-
isBase64Encoded = true
|
|
23
|
-
} else {
|
|
24
|
-
body = buffer.toString('utf-8')
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
return {
|
|
28
|
-
statusCode: response.status,
|
|
29
|
-
headers,
|
|
30
|
-
body,
|
|
31
|
-
isBase64Encoded,
|
|
32
|
-
}
|
|
33
|
-
}
|
package/src/scheduled/index.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { runLambdaScheduled } from './run-scheduled.js'
|