@pikku/core 0.6.9

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 (167) hide show
  1. package/CHANGELOG.md +339 -0
  2. package/README.md +5 -0
  3. package/dist/channel/channel-handler.d.ts +3 -0
  4. package/dist/channel/channel-handler.js +97 -0
  5. package/dist/channel/channel-runner.d.ts +26 -0
  6. package/dist/channel/channel-runner.js +86 -0
  7. package/dist/channel/channel-store.d.ts +14 -0
  8. package/dist/channel/channel-store.js +2 -0
  9. package/dist/channel/channel.types.d.ts +106 -0
  10. package/dist/channel/channel.types.js +1 -0
  11. package/dist/channel/eventhub-forwarder.d.ts +17 -0
  12. package/dist/channel/eventhub-forwarder.js +1 -0
  13. package/dist/channel/eventhub-service.d.ts +23 -0
  14. package/dist/channel/eventhub-service.js +1 -0
  15. package/dist/channel/eventhub-store.d.ts +5 -0
  16. package/dist/channel/eventhub-store.js +2 -0
  17. package/dist/channel/index.d.ts +9 -0
  18. package/dist/channel/index.js +9 -0
  19. package/dist/channel/local/index.d.ts +3 -0
  20. package/dist/channel/local/index.js +3 -0
  21. package/dist/channel/local/local-channel-handler.d.ts +17 -0
  22. package/dist/channel/local/local-channel-handler.js +41 -0
  23. package/dist/channel/local/local-channel-runner.d.ts +3 -0
  24. package/dist/channel/local/local-channel-runner.js +46 -0
  25. package/dist/channel/local/local-eventhub-service.d.ts +44 -0
  26. package/dist/channel/local/local-eventhub-service.js +81 -0
  27. package/dist/channel/log-channels.d.ts +6 -0
  28. package/dist/channel/log-channels.js +17 -0
  29. package/dist/channel/pikku-abstract-channel-handler.d.ts +15 -0
  30. package/dist/channel/pikku-abstract-channel-handler.js +33 -0
  31. package/dist/channel/serverless/index.d.ts +1 -0
  32. package/dist/channel/serverless/index.js +1 -0
  33. package/dist/channel/serverless/serverless-channel-runner.d.ts +10 -0
  34. package/dist/channel/serverless/serverless-channel-runner.js +98 -0
  35. package/dist/errors/error-handler.d.ts +39 -0
  36. package/dist/errors/error-handler.js +54 -0
  37. package/dist/errors/errors.d.ts +190 -0
  38. package/dist/errors/errors.js +315 -0
  39. package/dist/errors/index.d.ts +2 -0
  40. package/dist/errors/index.js +2 -0
  41. package/dist/http/http-route-runner.d.ts +30 -0
  42. package/dist/http/http-route-runner.js +208 -0
  43. package/dist/http/http-routes.types.d.ts +127 -0
  44. package/dist/http/http-routes.types.js +1 -0
  45. package/dist/http/http-session-service.d.ts +15 -0
  46. package/dist/http/http-session-service.js +1 -0
  47. package/dist/http/index.d.ts +6 -0
  48. package/dist/http/index.js +5 -0
  49. package/dist/http/log-http-routes.d.ts +6 -0
  50. package/dist/http/log-http-routes.js +17 -0
  51. package/dist/http/pikku-http-abstract-request.d.ts +57 -0
  52. package/dist/http/pikku-http-abstract-request.js +69 -0
  53. package/dist/http/pikku-http-abstract-response.d.ts +58 -0
  54. package/dist/http/pikku-http-abstract-response.js +54 -0
  55. package/dist/http/pikku-http-session-service.d.ts +45 -0
  56. package/dist/http/pikku-http-session-service.js +92 -0
  57. package/dist/index.d.ts +14 -0
  58. package/dist/index.js +14 -0
  59. package/dist/permissions.d.ts +10 -0
  60. package/dist/permissions.js +32 -0
  61. package/dist/pikku-request.d.ts +14 -0
  62. package/dist/pikku-request.js +21 -0
  63. package/dist/pikku-response.d.ts +6 -0
  64. package/dist/pikku-response.js +6 -0
  65. package/dist/scheduler/index.d.ts +3 -0
  66. package/dist/scheduler/index.js +3 -0
  67. package/dist/scheduler/log-schedulers.d.ts +6 -0
  68. package/dist/scheduler/log-schedulers.js +17 -0
  69. package/dist/scheduler/scheduler-runner.d.ts +21 -0
  70. package/dist/scheduler/scheduler-runner.js +73 -0
  71. package/dist/scheduler/scheduler.types.d.ts +21 -0
  72. package/dist/scheduler/scheduler.types.js +1 -0
  73. package/dist/schema.d.ts +26 -0
  74. package/dist/schema.js +100 -0
  75. package/dist/services/content-service.d.ts +55 -0
  76. package/dist/services/content-service.js +1 -0
  77. package/dist/services/index.d.ts +12 -0
  78. package/dist/services/index.js +14 -0
  79. package/dist/services/jwt-service.d.ts +29 -0
  80. package/dist/services/jwt-service.js +1 -0
  81. package/dist/services/local-content.d.ts +33 -0
  82. package/dist/services/local-content.js +6 -0
  83. package/dist/services/local-secrets.d.ts +26 -0
  84. package/dist/services/local-secrets.js +39 -0
  85. package/dist/services/local-variables.d.ts +7 -0
  86. package/dist/services/local-variables.js +12 -0
  87. package/dist/services/logger-console.d.ts +52 -0
  88. package/dist/services/logger-console.js +82 -0
  89. package/dist/services/logger.d.ts +48 -0
  90. package/dist/services/logger.js +9 -0
  91. package/dist/services/schema-service.d.ts +24 -0
  92. package/dist/services/schema-service.js +1 -0
  93. package/dist/services/secret-service.d.ts +17 -0
  94. package/dist/services/secret-service.js +1 -0
  95. package/dist/services/user-session-service.d.ts +6 -0
  96. package/dist/services/user-session-service.js +1 -0
  97. package/dist/services/variables-service.d.ts +4 -0
  98. package/dist/services/variables-service.js +1 -0
  99. package/dist/types/core.types.d.ts +109 -0
  100. package/dist/types/core.types.js +1 -0
  101. package/dist/types/functions.types.d.ts +27 -0
  102. package/dist/types/functions.types.js +1 -0
  103. package/dist/utils.d.ts +2 -0
  104. package/dist/utils.js +15 -0
  105. package/package.json +48 -0
  106. package/run-tests.sh +53 -0
  107. package/src/channel/channel-handler.ts +179 -0
  108. package/src/channel/channel-runner.ts +156 -0
  109. package/src/channel/channel-store.ts +32 -0
  110. package/src/channel/channel.types.ts +202 -0
  111. package/src/channel/eventhub-forwarder.ts +25 -0
  112. package/src/channel/eventhub-service.ts +30 -0
  113. package/src/channel/eventhub-store.ts +8 -0
  114. package/src/channel/index.ts +9 -0
  115. package/src/channel/local/index.ts +3 -0
  116. package/src/channel/local/local-channel-handler.ts +56 -0
  117. package/src/channel/local/local-channel-runner.test.ts +128 -0
  118. package/src/channel/local/local-channel-runner.ts +94 -0
  119. package/src/channel/local/local-eventhub-service.test.ts +95 -0
  120. package/src/channel/local/local-eventhub-service.ts +95 -0
  121. package/src/channel/log-channels.ts +20 -0
  122. package/src/channel/pikku-abstract-channel-handler.test.ts +77 -0
  123. package/src/channel/pikku-abstract-channel-handler.ts +44 -0
  124. package/src/channel/serverless/index.ts +1 -0
  125. package/src/channel/serverless/serverless-channel-runner.ts +190 -0
  126. package/src/errors/error-handler.ts +74 -0
  127. package/src/errors/error.test.ts +54 -0
  128. package/src/errors/errors.ts +340 -0
  129. package/src/errors/index.ts +2 -0
  130. package/src/http/http-route-runner.test.ts +193 -0
  131. package/src/http/http-route-runner.ts +365 -0
  132. package/src/http/http-routes.types.ts +189 -0
  133. package/src/http/http-session-service.ts +19 -0
  134. package/src/http/index.ts +16 -0
  135. package/src/http/log-http-routes.ts +20 -0
  136. package/src/http/pikku-http-abstract-request.ts +95 -0
  137. package/src/http/pikku-http-abstract-response.ts +79 -0
  138. package/src/http/pikku-http-session-service.test.ts +106 -0
  139. package/src/http/pikku-http-session-service.ts +135 -0
  140. package/src/index.ts +15 -0
  141. package/src/permissions.test.ts +58 -0
  142. package/src/permissions.ts +45 -0
  143. package/src/pikku-request.ts +19 -0
  144. package/src/pikku-response.ts +5 -0
  145. package/src/scheduler/index.ts +11 -0
  146. package/src/scheduler/log-schedulers.ts +20 -0
  147. package/src/scheduler/scheduler-runner.ts +132 -0
  148. package/src/scheduler/scheduler.types.ts +27 -0
  149. package/src/schema.test.ts +57 -0
  150. package/src/schema.ts +124 -0
  151. package/src/services/content-service.ts +69 -0
  152. package/src/services/index.ts +16 -0
  153. package/src/services/jwt-service.ts +36 -0
  154. package/src/services/local-content.ts +39 -0
  155. package/src/services/local-secrets.ts +43 -0
  156. package/src/services/local-variables.ts +17 -0
  157. package/src/services/logger-console.ts +97 -0
  158. package/src/services/logger.ts +57 -0
  159. package/src/services/schema-service.ts +26 -0
  160. package/src/services/secret-service.ts +17 -0
  161. package/src/services/user-session-service.ts +7 -0
  162. package/src/services/variables-service.ts +6 -0
  163. package/src/types/core.types.ts +162 -0
  164. package/src/types/functions.types.ts +44 -0
  165. package/src/utils.ts +21 -0
  166. package/tsconfig.json +13 -0
  167. package/tsconfig.tsbuildinfo +1 -0
@@ -0,0 +1,56 @@
1
+ import { CoreUserSession } from '../../types/core.types.js'
2
+ import { PikkuAbstractChannelHandler } from '../pikku-abstract-channel-handler.js'
3
+
4
+ export class PikkuLocalChannelHandler<
5
+ UserSession extends CoreUserSession = CoreUserSession,
6
+ OpeningData = unknown,
7
+ Out = unknown,
8
+ > extends PikkuAbstractChannelHandler<UserSession, OpeningData, Out> {
9
+ private onMessageCallback?: (message: unknown) => void
10
+ private openCallBack?: () => void
11
+ private closeCallback?: () => void
12
+ private sendCallback?: (message: Out, isBinary?: boolean) => void
13
+
14
+ public registerOnOpen(callback: () => void): void {
15
+ this.openCallBack = callback
16
+ }
17
+
18
+ public open() {
19
+ this.getChannel().state = 'open'
20
+ if (this.openCallBack) {
21
+ this.openCallBack()
22
+ }
23
+ }
24
+
25
+ public registerOnMessage(callback: (data: any) => Promise<unknown>): void {
26
+ this.onMessageCallback = callback
27
+ }
28
+
29
+ public async message(data: unknown): Promise<unknown> {
30
+ return this.onMessageCallback?.(data)
31
+ }
32
+
33
+ public registerOnClose(callback: () => void): void {
34
+ this.closeCallback = callback
35
+ }
36
+
37
+ public close() {
38
+ super.close()
39
+ this.closeCallback?.()
40
+ }
41
+
42
+ public registerOnSend(send: (message: Out) => void) {
43
+ this.sendCallback = send
44
+ }
45
+
46
+ public send(message: Out, isBinary?: boolean): void {
47
+ if (!this.sendCallback) {
48
+ throw new Error('No send callback registered')
49
+ }
50
+ return this.sendCallback?.(message, isBinary)
51
+ }
52
+
53
+ public setUserSession(userSession: UserSession): void {
54
+ this.getChannel().userSession = userSession
55
+ }
56
+ }
@@ -0,0 +1,128 @@
1
+ import { test, beforeEach, afterEach } from 'node:test'
2
+ import * as assert from 'node:assert/strict'
3
+ import { JSONValue } from '../../types/core.types.js'
4
+ import { PikkuHTTPAbstractRequest } from '../../http/pikku-http-abstract-request.js'
5
+ import { PikkuHTTPAbstractResponse } from '../../http/pikku-http-abstract-response.js'
6
+ import { runLocalChannel } from './local-channel-runner.js'
7
+
8
+ /**
9
+ * Minimal stubs for dependencies that runChannel expects.
10
+ * In a real test setup, you may provide more comprehensive mocks
11
+ * or refactor your code to allow dependency injection.
12
+ */
13
+ const mockLogger = {
14
+ info: () => {},
15
+ error: () => {},
16
+ warn: () => {},
17
+ debug: () => {},
18
+ }
19
+
20
+ const mockSingletonServices = {
21
+ logger: mockLogger,
22
+ // Provide a mock channelPermissionService only when needed
23
+ // e.g., channelPermissionService: { verifyChannelAccess: async () => {} },
24
+ httpSessionService: {},
25
+ } as any
26
+
27
+ // Mock request and response objects
28
+ class MockRequest extends PikkuHTTPAbstractRequest {
29
+ public getBody(): Promise<unknown> {
30
+ throw new Error('Method not implemented.')
31
+ }
32
+ public getHeader(headerName: string): string | undefined {
33
+ throw new Error('Method not implemented.')
34
+ }
35
+ public async getData() {
36
+ return { test: 'data' }
37
+ }
38
+ }
39
+
40
+ class MockResponse extends PikkuHTTPAbstractResponse {
41
+ public statusSet: boolean | undefined
42
+ public ended: boolean | undefined
43
+
44
+ public setJson(body: JSONValue): void {}
45
+ public setResponse(response: string | Buffer): void {}
46
+ public setStatus(code) {
47
+ this.statusSet = code
48
+ }
49
+ public end() {
50
+ this.ended = true
51
+ }
52
+ }
53
+
54
+ const mockCreateSessionServices = async () => ({ sessionServiceMock: true })
55
+ function resetGlobalChannels(channels: any[] = [], channelsMeta: any[] = []) {
56
+ // If necessary, reinitialize globalThis.pikku
57
+ if (!globalThis.pikku) {
58
+ globalThis.pikku = {}
59
+ }
60
+ globalThis.pikku.channels = channels
61
+ globalThis.pikku.channelsMeta = channelsMeta
62
+ globalThis.pikku.openChannels = new Map()
63
+ }
64
+
65
+ beforeEach(() => {
66
+ resetGlobalChannels()
67
+ })
68
+
69
+ afterEach(() => {
70
+ resetGlobalChannels()
71
+ })
72
+
73
+ test('runChannel should return undefined and 404 if no matching channel is found', async () => {
74
+ // No channels configured
75
+ resetGlobalChannels()
76
+
77
+ const mockResponse = new MockResponse()
78
+
79
+ const result = await runLocalChannel({
80
+ singletonServices: mockSingletonServices,
81
+ channelId: 'test-channel-id',
82
+ request: new MockRequest(),
83
+ response: mockResponse,
84
+ route: '/non-existent-channel',
85
+ createSessionServices: mockCreateSessionServices,
86
+ })
87
+
88
+ assert.equal(
89
+ result,
90
+ undefined,
91
+ 'Should return undefined if no channel matches'
92
+ )
93
+ assert.equal(mockResponse.statusSet, 404, 'Should set response status to 404')
94
+ assert.equal(mockResponse.ended, true, 'Should end the response')
95
+ })
96
+
97
+ test('runChannel should return a channel handler if channel matches and no auth required', async () => {
98
+ resetGlobalChannels([
99
+ {
100
+ route: '/test-channel',
101
+ auth: false,
102
+ },
103
+ ])
104
+
105
+ // Provide a fake channelPermissionService if needed
106
+ const singletonServicesWithPerm = {
107
+ ...mockSingletonServices,
108
+ channelPermissionService: {
109
+ verifyChannelAccess: async () => {},
110
+ },
111
+ }
112
+
113
+ const result = await runLocalChannel({
114
+ singletonServices: singletonServicesWithPerm,
115
+ channelId: 'test-channel-id',
116
+ request: new MockRequest(),
117
+ response: new MockResponse(),
118
+ route: '/test-channel',
119
+ createSessionServices: mockCreateSessionServices,
120
+ })
121
+
122
+ assert.ok(result, 'Should return a PikkuChannelHandler instance')
123
+
124
+ // Simulate opening the channel
125
+ result.open()
126
+
127
+ // TODO: Test that the opened channel works
128
+ })
@@ -0,0 +1,94 @@
1
+ import { openChannel } from '../channel-runner.js'
2
+ import {
3
+ createHTTPInteraction,
4
+ handleError,
5
+ } from '../../http/http-route-runner.js'
6
+ import { closeSessionServices } from '../../utils.js'
7
+ import { processMessageHandlers } from '../channel-handler.js'
8
+ import {
9
+ CoreAPIChannel,
10
+ RunChannelOptions,
11
+ RunChannelParams,
12
+ } from '../channel.types.js'
13
+ import { PikkuLocalChannelHandler } from './local-channel-handler.js'
14
+ import { SessionServices } from '../../types/core.types.js'
15
+
16
+ export const runLocalChannel = async ({
17
+ singletonServices,
18
+ channelId,
19
+ request,
20
+ response,
21
+ route,
22
+ createSessionServices,
23
+ skipUserSession = false,
24
+ respondWith404 = true,
25
+ coerceToArray = false,
26
+ logWarningsForStatusCodes = [],
27
+ bubbleErrors = false,
28
+ }: Pick<CoreAPIChannel<unknown, any>, 'route'> &
29
+ RunChannelOptions &
30
+ RunChannelParams<unknown>): Promise<PikkuLocalChannelHandler | void> => {
31
+ let sessionServices: SessionServices<typeof singletonServices> | undefined
32
+
33
+ const http = createHTTPInteraction(request, response)
34
+ try {
35
+ const { userSession, openingData, channelConfig } = await openChannel({
36
+ channelId,
37
+ createSessionServices,
38
+ respondWith404,
39
+ http,
40
+ route,
41
+ singletonServices,
42
+ skipUserSession,
43
+ coerceToArray,
44
+ })
45
+
46
+ const channelHandler = new PikkuLocalChannelHandler(
47
+ channelId,
48
+ channelConfig.name,
49
+ userSession,
50
+ openingData
51
+ )
52
+ const channel = channelHandler.getChannel()
53
+
54
+ if (createSessionServices) {
55
+ sessionServices = await createSessionServices(
56
+ singletonServices,
57
+ { http },
58
+ userSession
59
+ )
60
+ }
61
+ const allServices = { ...singletonServices, ...sessionServices }
62
+
63
+ channelHandler.registerOnOpen(() => {
64
+ channelConfig.onConnect?.(allServices, channel)
65
+ })
66
+
67
+ channelHandler.registerOnClose(async () => {
68
+ channelConfig.onDisconnect?.(allServices, channel)
69
+ if (sessionServices) {
70
+ await closeSessionServices(singletonServices.logger, sessionServices)
71
+ }
72
+ })
73
+
74
+ channelHandler.registerOnMessage(
75
+ processMessageHandlers(allServices, channelConfig, channelHandler)
76
+ )
77
+
78
+ return channelHandler
79
+ } catch (e: any) {
80
+ handleError(
81
+ e,
82
+ http,
83
+ channelId,
84
+ singletonServices.logger,
85
+ logWarningsForStatusCodes,
86
+ respondWith404,
87
+ bubbleErrors
88
+ )
89
+ } finally {
90
+ if (sessionServices) {
91
+ await closeSessionServices(singletonServices.logger, sessionServices)
92
+ }
93
+ }
94
+ }
@@ -0,0 +1,95 @@
1
+ import * as assert from 'assert'
2
+ import { test } from 'node:test'
3
+ import { PikkuChannelHandler } from '../channel.types.js'
4
+ import { CoreUserSession } from '../../types/core.types.js'
5
+ import { LocalEventHubService } from './local-eventhub-service.js'
6
+
7
+ class MockChannelHandler implements PikkuChannelHandler {
8
+ private channelId: string
9
+
10
+ constructor(channelId: string) {
11
+ this.channelId = channelId
12
+ }
13
+
14
+ setUserSession(session: CoreUserSession): Promise<void> | void {
15
+ throw new Error('Method not needed.')
16
+ }
17
+
18
+ getChannel() {
19
+ return { channelId: this.channelId } as any
20
+ }
21
+
22
+ send(data: unknown, isBinary?: boolean) {
23
+ // Mock send functionality
24
+ console.log(`Sent to ${this.channelId}:`, { data, isBinary })
25
+ }
26
+ }
27
+
28
+ test('LocalEventHubService: subscribe and unsubscribe', () => {
29
+ const eventHub = new LocalEventHubService()
30
+
31
+ // Subscribe a channel to a topic
32
+ eventHub.subscribe('topic1', 'channel1')
33
+ assert.strictEqual(eventHub['subscriptions'].get('topic1')!.size, 1)
34
+
35
+ // Unsubscribe the channel
36
+ eventHub.unsubscribe('topic1', 'channel1')
37
+ assert.strictEqual(eventHub['subscriptions'].has('topic1'), false)
38
+ })
39
+
40
+ test('LocalEventHubService: publish messages', () => {
41
+ const eventHub = new LocalEventHubService()
42
+
43
+ // Register mock channels
44
+ const channel1 = new MockChannelHandler('channel1')
45
+ const channel2 = new MockChannelHandler('channel2')
46
+ eventHub.onChannelOpened(channel1)
47
+ eventHub.onChannelOpened(channel2)
48
+
49
+ // Subscribe channels to a topic
50
+ eventHub.subscribe('topic1', 'channel1')
51
+ eventHub.subscribe('topic1', 'channel2')
52
+
53
+ // Mock `send` method to track calls
54
+ let sendCallCount = 0
55
+ channel1.send = () => {
56
+ sendCallCount++
57
+ }
58
+ channel2.send = () => {
59
+ sendCallCount++
60
+ }
61
+
62
+ // Publish a message
63
+ eventHub.publish('topic1', 'channel1', { message: 'Hello!' })
64
+
65
+ // Ensure the message was sent only to channel2
66
+ assert.strictEqual(sendCallCount, 1)
67
+ })
68
+
69
+ test('LocalEventHubService: onChannelOpened and onChannelClosed', () => {
70
+ const eventHub = new LocalEventHubService()
71
+
72
+ // Register and verify channel
73
+ const channel1 = new MockChannelHandler('channel1')
74
+ eventHub.onChannelOpened(channel1)
75
+ assert.strictEqual(eventHub['channels'].has('channel1'), true)
76
+
77
+ // Close and verify removal
78
+ eventHub.onChannelClosed('channel1')
79
+ assert.strictEqual(eventHub['channels'].has('channel1'), false)
80
+ })
81
+
82
+ test('LocalEventHubService: clean up empty topics on channel close', () => {
83
+ const eventHub = new LocalEventHubService()
84
+
85
+ // Register and subscribe channels
86
+ const channel1 = new MockChannelHandler('channel1')
87
+ eventHub.onChannelOpened(channel1)
88
+ eventHub.subscribe('topic1', 'channel1')
89
+
90
+ // Close channel
91
+ eventHub.onChannelClosed('channel1')
92
+
93
+ // Ensure topic1 is removed
94
+ assert.strictEqual(eventHub['subscriptions'].has('topic1'), false)
95
+ })
@@ -0,0 +1,95 @@
1
+ import { PikkuChannelHandler } from '../channel.types.js'
2
+ import { EventHubService } from '../eventhub-service.js'
3
+
4
+ /**
5
+ * Implementation of the SubscriptionService interface.
6
+ * Manages subscriptions and publishes messages to subscribers.
7
+ */
8
+ export class LocalEventHubService<Data = unknown>
9
+ implements EventHubService<Data>
10
+ {
11
+ private channels = new Map<string, PikkuChannelHandler>()
12
+
13
+ /**
14
+ * A map storing topics and their associated connection IDs.
15
+ */
16
+ private subscriptions: Map<string, Set<string>> = new Map()
17
+
18
+ /**
19
+ * Subscribes a connection to a specific topic.
20
+ * Creates the topic if it does not already exist.
21
+ * @param topic - The topic to subscribe to.
22
+ * @param channelId - The unique ID of the connection to subscribe.
23
+ */
24
+ public subscribe(topic: string, channelId: string): void {
25
+ if (!this.subscriptions.has(topic)) {
26
+ this.subscriptions.set(topic, new Set())
27
+ }
28
+ this.subscriptions.get(topic)!.add(channelId)
29
+ }
30
+
31
+ /**
32
+ * Unsubscribes a connection from a specific topic.
33
+ * Removes the topic if it has no more subscribers.
34
+ * @param topic - The topic to unsubscribe from.
35
+ * @param channelId - The unique ID of the connection to unsubscribe.
36
+ */
37
+ public unsubscribe(topic: string, channelId: string): void {
38
+ const topicSubscriptions = this.subscriptions.get(topic)
39
+ if (topicSubscriptions) {
40
+ topicSubscriptions.delete(channelId)
41
+ if (topicSubscriptions.size === 0) {
42
+ this.subscriptions.delete(topic) // Cleanup empty subscriptions
43
+ }
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Sends data to all connections subscribed to a topic.
49
+ * @param topic - The topic to send data to.
50
+ * @param data - The data to send to the subscribers.
51
+ */
52
+ public publish(
53
+ topic: string,
54
+ channelId: string,
55
+ data: Data,
56
+ isBinary?: boolean
57
+ ): void {
58
+ const subscribedChannelIds = this.subscriptions.get(topic)
59
+ if (!subscribedChannelIds) {
60
+ return
61
+ }
62
+ for (const toChannelId of subscribedChannelIds) {
63
+ if (channelId === toChannelId) continue // Skip sending to the sender
64
+ const channel = this.channels.get(toChannelId)
65
+ if (channel) {
66
+ channel.send(data, isBinary)
67
+ } else {
68
+ // TODO: Websocket is closed, remove the channel from the topic
69
+ }
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Registers a channel on open
75
+ */
76
+ public onChannelOpened(channelHandler: PikkuChannelHandler): void {
77
+ this.channels.set(channelHandler.getChannel().channelId, channelHandler)
78
+ }
79
+
80
+ /**
81
+ * Handles cleanup when a channel is closed.
82
+ * Removes the channel from all topics it is subscribed to.
83
+ * Deletes the topic if no more channels are subscribed to it.
84
+ * @param channelId - The ID of the channel that was closed.
85
+ */
86
+ public onChannelClosed(channelId: string): void {
87
+ for (const [topic, channelIds] of this.subscriptions.entries()) {
88
+ channelIds.delete(channelId)
89
+ if (channelIds.size === 0) {
90
+ this.subscriptions.delete(topic) // Cleanup empty topics
91
+ }
92
+ }
93
+ this.channels.delete(channelId)
94
+ }
95
+ }
@@ -0,0 +1,20 @@
1
+ import { Logger } from '../services/index.js'
2
+ import { getChannels } from './channel-runner.js'
3
+
4
+ /**
5
+ * Logs all the loaded channels.
6
+ * @param logger - A logger for logging information.
7
+ */
8
+ export const logChannels = (logger: Logger) => {
9
+ const { channels } = getChannels()
10
+ if (channels.length === 0) {
11
+ logger.info('No channels added')
12
+ return
13
+ }
14
+
15
+ let scheduledChannels = 'Channels:'
16
+ for (const { name, route } of channels) {
17
+ scheduledChannels += `\n\t- ${name} at ${route}`
18
+ }
19
+ logger.info(scheduledChannels)
20
+ }
@@ -0,0 +1,77 @@
1
+ import { test, beforeEach } from 'node:test'
2
+ import * as assert from 'node:assert/strict'
3
+ import { CoreUserSession } from '../types/core.types.js'
4
+ import { PikkuAbstractChannelHandler } from './pikku-abstract-channel-handler.js'
5
+
6
+ // A concrete implementation of the abstract class for testing
7
+ class TestChannelHandler extends PikkuAbstractChannelHandler<
8
+ CoreUserSession,
9
+ { param: string },
10
+ { msg: string }
11
+ > {
12
+ public async setUserSession(session: CoreUserSession): Promise<void> {
13
+ this.userSession = session
14
+ }
15
+
16
+ public async send(message: { msg: string }, isBinary = false): Promise<void> {
17
+ // Mock send implementation
18
+ }
19
+ }
20
+
21
+ let handler: TestChannelHandler
22
+
23
+ beforeEach(() => {
24
+ handler = new TestChannelHandler(
25
+ 'test-channel-id',
26
+ 'channel-name',
27
+ undefined,
28
+ { param: 'testParam' }
29
+ )
30
+ })
31
+
32
+ test('getChannel should return a channel with initial state', () => {
33
+ const channel = handler.getChannel()
34
+ assert.equal(channel.channelId, 'test-channel-id', 'Channel ID should match')
35
+ assert.equal(channel.state, 'initial', 'Initial state should be "initial"')
36
+ assert.deepEqual(
37
+ channel.openingData,
38
+ { param: 'testParam' },
39
+ 'Opening data should be accessible'
40
+ )
41
+ assert.equal(
42
+ channel.userSession,
43
+ undefined,
44
+ 'Session should initially be undefined'
45
+ )
46
+ })
47
+
48
+ test('setUserSession should update the channel session', async () => {
49
+ const session = { userId: 'user123' } as CoreUserSession
50
+ await handler.setUserSession(session)
51
+ const channel = handler.getChannel()
52
+ assert.deepEqual(
53
+ channel.userSession,
54
+ session,
55
+ 'Session should be updated correctly'
56
+ )
57
+ })
58
+
59
+ test('open should change channel state to open', () => {
60
+ handler.open()
61
+ const channel = handler.getChannel()
62
+ assert.equal(
63
+ channel.state,
64
+ 'open',
65
+ 'State should be "open" after calling open()'
66
+ )
67
+ })
68
+
69
+ test('close should change channel state to closed', () => {
70
+ handler.close()
71
+ const channel = handler.getChannel()
72
+ assert.equal(
73
+ channel.state,
74
+ 'closed',
75
+ 'State should be "closed" after calling close()'
76
+ )
77
+ })
@@ -0,0 +1,44 @@
1
+ import { CoreUserSession } from '../types/core.types.js'
2
+ import { PikkuChannel, PikkuChannelHandler } from './channel.types.js'
3
+
4
+ export abstract class PikkuAbstractChannelHandler<
5
+ UserSession extends CoreUserSession = CoreUserSession,
6
+ OpeningData = unknown,
7
+ Out = unknown,
8
+ > implements PikkuChannelHandler<UserSession, OpeningData, Out>
9
+ {
10
+ protected channel?: PikkuChannel<UserSession, OpeningData, Out>
11
+
12
+ constructor(
13
+ public channelId: string,
14
+ public channelName: string,
15
+ protected userSession: UserSession | undefined,
16
+ protected openingData: OpeningData
17
+ ) {}
18
+
19
+ public abstract setUserSession(userSession: UserSession): Promise<void> | void
20
+ public abstract send(message: Out, isBinary?: boolean): Promise<void> | void
21
+
22
+ public getChannel(): PikkuChannel<UserSession, OpeningData, Out> {
23
+ if (!this.channel) {
24
+ this.channel = {
25
+ channelId: this.channelId,
26
+ userSession: this.userSession,
27
+ openingData: this.openingData,
28
+ setUserSession: this.setUserSession.bind(this),
29
+ send: this.send.bind(this),
30
+ close: this.close.bind(this),
31
+ state: 'initial',
32
+ }
33
+ }
34
+ return this.channel
35
+ }
36
+
37
+ public open(): void {
38
+ this.getChannel().state = 'open'
39
+ }
40
+
41
+ public close(): Promise<void> | void {
42
+ this.getChannel().state = 'closed'
43
+ }
44
+ }
@@ -0,0 +1 @@
1
+ export * from './serverless-channel-runner.js'