@credo-ts/didcomm-transport-queue-postgres 0.0.0-alpha.1
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/LICENSE +202 -0
- package/README.md +136 -0
- package/build/TransportQueuePostgres.d.ts +108 -0
- package/build/TransportQueuePostgres.js +448 -0
- package/build/TransportQueuePostgres.js.map +1 -0
- package/build/index.d.ts +2 -0
- package/build/index.js +3 -0
- package/build/index.js.map +1 -0
- package/build/interfaces.d.ts +27 -0
- package/build/interfaces.js +2 -0
- package/build/interfaces.js.map +1 -0
- package/build/utils/buildPgDatabaseWithMigrations.d.ts +17 -0
- package/build/utils/buildPgDatabaseWithMigrations.js +91 -0
- package/build/utils/buildPgDatabaseWithMigrations.js.map +1 -0
- package/migrations/001-initial-schema.sql +34 -0
- package/package.json +39 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2020-present Hyperledger Contributors.
|
|
190
|
+
Copyright 2021 Queen’s Printer for Ontario. Mostafa Youssef (https://github.com/MosCD3), Amit Padmani (https://github.com/nbAmit), Prasad Katkar (https://github.com/NB-PrasadKatkar), Mike Richardson (https://github.com/NB-MikeRichardson)
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
# DIDComm Transport Queue (Postgres) for Credo
|
|
2
|
+
|
|
3
|
+
## Overview
|
|
4
|
+
|
|
5
|
+
This package provides a simple but efficient Message Pickup Repository implementation to use with a [Credo](https://github.com/openwallet-foundation/credo-ts) mediator that wishes to persist queued messages for offline users in a shared database that will allow using multiple Credo instances. And everything without the need of using extra components, since the same Postgres database host used to store Credo wallet can be used for the Pickup Messages database!
|
|
6
|
+
|
|
7
|
+

|
|
8
|
+
|
|
9
|
+
## Features
|
|
10
|
+
|
|
11
|
+
- Message storage and retrieval: save and fetch messages from a PostgreSQL database.
|
|
12
|
+
- Pub/Sub integration: automatically notify other instances about new messages that arrived to a certain client.
|
|
13
|
+
|
|
14
|
+
- Live session management: handle [Message Pickup V2 Live sessions](https://github.com/hyperledger/aries-rfcs/tree/main/features/0685-pickup-v2#live-mode) for efficient message delivery.
|
|
15
|
+
|
|
16
|
+
- Automatic database initialization: set up the database structure required for message operations at startup.
|
|
17
|
+
|
|
18
|
+
- Event-driven notifications: emit a `MessagePickupRepositoryMessageQueued` event whenever a message is queued, allowing external listeners to implement flexible notification mechanisms like push notifications or webhooks when a message has arrived for an offline user (not connected to any instance).
|
|
19
|
+
|
|
20
|
+
## How does it work?
|
|
21
|
+
|
|
22
|
+
`DidCommTransportQueuePostgres` creates two tables in its PostgreSQL database: one to store the queued messages, and another one to keep track of Live sessions when clients connect and disconnect from it. It also registers to a [PG PubSub](https://github.com/voxpelli/node-pg-pubsub) channel to be notified when a message arrives (for any connection).
|
|
23
|
+
|
|
24
|
+
When a new message for a certain DIDComm connection is added to the queue, `DidCommTransportQueuePostgres` looks if there is an existing session with it:
|
|
25
|
+
|
|
26
|
+
- If there is a local Live mode session, it will pack and deliver the message directly, adding it to the persistent queue with a particular status flag (`sending`) to reflect that it is expected to be delivered and acknowledged soon
|
|
27
|
+
- If there is not any local session, the client could be connected to another instance. Therefore, it adds the message to the persistent queue and looks into the shared message pickup session database:
|
|
28
|
+
- If there is a session registered to another instance, it will publish a notification
|
|
29
|
+
- If no session is found, it emits a `MessagePickupRepositoryMessageQueued` event, which external listeners can use to handle notifications (push/webhooks).
|
|
30
|
+
|
|
31
|
+
> **Note**: at the moment, all instances are notified when a message arrives for any online DIDComm connection. A possible improvement could be to create a channel per connection, so only the instance connected to that client is triggered. But it is uncertain for us yet how well it would scale when there is a large number of connected users at the same time.
|
|
32
|
+
|
|
33
|
+
The following diagrams show the operation when messages arrive in both online and offline scenarios.
|
|
34
|
+
|
|
35
|
+

|
|
36
|
+
|
|
37
|
+

|
|
38
|
+
|
|
39
|
+
## Installation
|
|
40
|
+
|
|
41
|
+
This module is designed to work with Credo 0.5.X. Newer versions may include breaking changes in its API and therefore would require code updates to this module.
|
|
42
|
+
|
|
43
|
+
To use it, install package in your DIDComm Mediator application. For example:
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
npm i @credo-ts/didcomm-transport-queue-postgres
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
or
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
yarn add @credo-ts/didcomm-transport-queue-postgres
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Usage
|
|
56
|
+
|
|
57
|
+
Setting up DidCommTransportQueuePostgres is quite simple if you have some prior experience with Credo. We can summarize it in three steps: create, initialize and inject into a Credo instance.
|
|
58
|
+
|
|
59
|
+
### Constructing the Repository
|
|
60
|
+
|
|
61
|
+
You need to instance `DidCommTransportQueuePostgres` with explicit database configuration (remember: it could be the same used for Credo wallet). If `postgresDatabaseName` is not specified, default `messagepickuprepository` will be used (if it does not exist, it will try to automatically create it using the provided credentials).
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
const messageRepository = new DidCommTransportQueuePostgres({
|
|
65
|
+
logger: yourLoggerInstance,
|
|
66
|
+
postgresUser: "your_postgres_user",
|
|
67
|
+
postgresPassword: "your_postgres_password",
|
|
68
|
+
postgresHost: "your_postgres_host",
|
|
69
|
+
postgresDatabaseName: "your_database_name",
|
|
70
|
+
});
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### Initializing the Repository
|
|
74
|
+
|
|
75
|
+
To start using the `DidCommTransportQueuePostgres`, initialize it with an agent and a callback function for retrieving connection information.
|
|
76
|
+
|
|
77
|
+
This callback must return another callback function that will be called by `DidCommTransportQueuePostgres` when it determines that a Push Notification must be sent. It is a generic approach that makes you free to implement the Push notification service you want.
|
|
78
|
+
|
|
79
|
+
Note that in this example, notification token is stored as a tag in connection records, so it is used to determine whether to create a Push notification callback or not for a given DIDComm connection.
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
await messagePickupRepository.initialize({ agent });
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### Handling `MessagePickupRepositoryMessageQueued` Event
|
|
86
|
+
|
|
87
|
+
Listeners can handle queued messages by listening for the emitted event:
|
|
88
|
+
|
|
89
|
+
```typescript
|
|
90
|
+
agent.events.on(MessageQueuedEventType, async ({ payload }) => {
|
|
91
|
+
const { connectionId, messageId } = payload;
|
|
92
|
+
|
|
93
|
+
// Example: call external notification service
|
|
94
|
+
await notificationService.notify(connectionId, messageId);
|
|
95
|
+
});
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
### Injecting into an Agent instance
|
|
99
|
+
|
|
100
|
+
This full example shows how `DidCommTransportQueuePostgres` is created an initialized alongside an `Agent` instance:
|
|
101
|
+
|
|
102
|
+
```javascript
|
|
103
|
+
import { Agent, MediatorModule, MessagePickupModule } from "@credo-ts/core";
|
|
104
|
+
import { agentDependencies } from "@credo-ts/node";
|
|
105
|
+
import { MessageForwardingStrategy } from "@credo-ts/core/build/modules/routing/MessageForwardingStrategy";
|
|
106
|
+
import { DidCommTransportQueuePostgres } from "@credo-ts/didcomm-transport-queue-postgres";
|
|
107
|
+
|
|
108
|
+
const messagePickupRepository = new DidCommTransportQueuePostgres({
|
|
109
|
+
postgresHost: "postgres",
|
|
110
|
+
postgresUser: "user",
|
|
111
|
+
postgresPassword: "pass",
|
|
112
|
+
});
|
|
113
|
+
const agent = new Agent({
|
|
114
|
+
dependencies: agentDependencies,
|
|
115
|
+
config: { label: "Test" },
|
|
116
|
+
modules: {
|
|
117
|
+
mediator: new MediatorModule({
|
|
118
|
+
messageForwardingStrategy: MessageForwardingStrategy.QueueOnly,
|
|
119
|
+
}),
|
|
120
|
+
messagePickup: new MessagePickupModule({
|
|
121
|
+
messagePickupRepository,
|
|
122
|
+
}),
|
|
123
|
+
},
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
await messagePickupRepository.initialize({ agent });
|
|
127
|
+
await agent.initialize();
|
|
128
|
+
|
|
129
|
+
agent.events.on("MessagePickupRepositoryMessageQueued", async ({ payload }) => {
|
|
130
|
+
const { connectionId, messageId } = payload;
|
|
131
|
+
|
|
132
|
+
// Custom logic for notification, webhook, etc here
|
|
133
|
+
});
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
As you can see, all you have to do is to set up your Credo agent's `ForwardingStrategy` to to `QueueOnly` and provide a `DidCommTransportQueuePostgres` instance (with the appropriate callbacks) to `MessagePickupModuleConfig`. Then, initialize both your agent and DidCommTransportQueuePostgres` and have fun!
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { Agent, AgentContext } from '@credo-ts/core';
|
|
2
|
+
import { AddMessageOptions, DidCommQueueTransportRepository, GetAvailableMessageCountOptions, QueuedDidCommMessage, RemoveMessagesOptions, TakeFromQueueOptions } from '@credo-ts/didcomm';
|
|
3
|
+
import { PostgresTransportQueuePostgresConfig } from './interfaces.js';
|
|
4
|
+
export declare class DidCommTransportQueuePostgres implements DidCommQueueTransportRepository {
|
|
5
|
+
private logger?;
|
|
6
|
+
private messagesCollection?;
|
|
7
|
+
private pubSubInstance;
|
|
8
|
+
private instanceName;
|
|
9
|
+
private postgresUser;
|
|
10
|
+
private postgresPassword;
|
|
11
|
+
private postgresHost;
|
|
12
|
+
private postgresDatabaseName;
|
|
13
|
+
constructor(options: PostgresTransportQueuePostgresConfig);
|
|
14
|
+
/**
|
|
15
|
+
* Initializes the service by setting up the database, message listeners, and the agent.
|
|
16
|
+
* This method also configures the Pub/Sub system and registers event handlers.
|
|
17
|
+
*
|
|
18
|
+
* @returns {Promise<void>} A promise that resolves when the initialization is complete.
|
|
19
|
+
* @throws {Error} Throws an error if initialization fails due to database, Pub/Sub, or agent setup issues.
|
|
20
|
+
*/
|
|
21
|
+
initialize(agent: Agent): Promise<void>;
|
|
22
|
+
/**
|
|
23
|
+
* Fetches messages from the queue based on the specified options.
|
|
24
|
+
*
|
|
25
|
+
* @param {TakeFromQueueOptions} options - The options for fetching messages.
|
|
26
|
+
* @param {string} options.connectionId - The ID of the connection.
|
|
27
|
+
* @param {number} [options.limit] - The maximum number of messages to fetch.
|
|
28
|
+
* @param {boolean} options.deleteMessages - Whether to delete messages after retrieval.
|
|
29
|
+
* @param {string} options.recipientDid - The DID of the recipient.
|
|
30
|
+
* @returns {Promise<QueuedMessage[]>} A promise resolving to an array of queued messages.
|
|
31
|
+
*/
|
|
32
|
+
takeFromQueue(agentContext: AgentContext, options: TakeFromQueueOptions): Promise<QueuedDidCommMessage[]>;
|
|
33
|
+
/**
|
|
34
|
+
* Retrieves the count of available messages in the queue for a given connection.
|
|
35
|
+
*
|
|
36
|
+
* @param {GetAvailableMessageCountOptions} options - Options for retrieving the message count.
|
|
37
|
+
* @param {string} options.connectionId - The ID of the connection to check.
|
|
38
|
+
* @returns {Promise<number>} A promise resolving to the count of available messages.
|
|
39
|
+
*/
|
|
40
|
+
getAvailableMessageCount(agentContext: AgentContext, options: GetAvailableMessageCountOptions): Promise<number>;
|
|
41
|
+
/**
|
|
42
|
+
* Adds a new message to the queue and processes it based on live session status.
|
|
43
|
+
*
|
|
44
|
+
* @param {AddMessageOptions} options - The options for adding a message.
|
|
45
|
+
* @param {string} options.connectionId - The ID of the connection.
|
|
46
|
+
* @param {string[]} options.recipientDids - Recipient DIDs for the message.
|
|
47
|
+
* @param {string} options.payload - The encrypted message payload.
|
|
48
|
+
* @returns {Promise<string> }- A promise resolving to the messageId and receivedAt of the added message.
|
|
49
|
+
* @throws {Error} Throws an error if the agent is not defined or if an error occurs during message insertion or processing.
|
|
50
|
+
*/
|
|
51
|
+
addMessage(agentContext: AgentContext, options: AddMessageOptions): Promise<string>;
|
|
52
|
+
/**
|
|
53
|
+
* Removes specified messages from the queue for a given connection.
|
|
54
|
+
*
|
|
55
|
+
* @param {RemoveMessagesOptions} options - Options for removing messages.
|
|
56
|
+
* @param {string} options.connectionId - The ID of the connection.
|
|
57
|
+
* @param {string[]} options.messageIds - Array of message IDs to be removed.
|
|
58
|
+
* @returns {Promise<void>} A promise resolving when the operation completes.
|
|
59
|
+
*/
|
|
60
|
+
removeMessages(agentContext: AgentContext, options: RemoveMessagesOptions): Promise<void>;
|
|
61
|
+
shutdown(agentContext: AgentContext): Promise<void>;
|
|
62
|
+
/**
|
|
63
|
+
* Subscribes to a specific Pub/Sub channel and handles incoming messages.
|
|
64
|
+
*
|
|
65
|
+
* @param {string} channel - The name of the channel to subscribe to.
|
|
66
|
+
* @returns {Promise<void>} A promise resolving when the listener is initialized.
|
|
67
|
+
*/
|
|
68
|
+
private initializeMessageListener;
|
|
69
|
+
/**
|
|
70
|
+
* This function checks that messages from the connectionId, which were left in the 'sending'
|
|
71
|
+
* state after a liveSessionRemove event, are updated to the 'pending' state for subsequent sending
|
|
72
|
+
* @param connectionID
|
|
73
|
+
*/
|
|
74
|
+
private checkQueueMessages;
|
|
75
|
+
/**
|
|
76
|
+
* Get current active live mode message pickup session for a given connection
|
|
77
|
+
* @param connectionId
|
|
78
|
+
* @returns
|
|
79
|
+
*/
|
|
80
|
+
private findLocalLiveSession;
|
|
81
|
+
/**
|
|
82
|
+
* This method allow find record into DB to determine if the connectionID has a liveSession in another instance
|
|
83
|
+
* @param connectionId
|
|
84
|
+
* @returns liveSession object or false
|
|
85
|
+
*/
|
|
86
|
+
private findLiveSessionInDb;
|
|
87
|
+
/**
|
|
88
|
+
* This method adds a new connectionId and instance name to DB upon LiveSessionSave event
|
|
89
|
+
* @param connectionId
|
|
90
|
+
* @param instance
|
|
91
|
+
*/
|
|
92
|
+
private addLiveSessionOnDb;
|
|
93
|
+
/**
|
|
94
|
+
*This method remove connectionId record to DB upon LiveSessionRemove event
|
|
95
|
+
* @param connectionId
|
|
96
|
+
*/
|
|
97
|
+
private removeLiveSessionOnDb;
|
|
98
|
+
/**
|
|
99
|
+
* Emits a MessageQueuedEvent using the agent's EventEmitter.
|
|
100
|
+
*
|
|
101
|
+
* @param {object} options - Event payload containing at least connectionId and messageId.
|
|
102
|
+
* @param {string} options.connectionId - The connection identifier.
|
|
103
|
+
* @param {string} options.messageId - The message identifier.
|
|
104
|
+
* @param {any} [options.*] - Additional optional properties for the event payload.
|
|
105
|
+
* @throws {Error} Throws if the agent is not initialized.
|
|
106
|
+
*/
|
|
107
|
+
private emitMessageQueuedEvent;
|
|
108
|
+
}
|
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import * as os from 'node:os';
|
|
3
|
+
import { EventEmitter } from '@credo-ts/core';
|
|
4
|
+
import { DidCommMessagePickupApi, DidCommMessagePickupEventTypes, DidCommMessagePickupSessionRole, } from '@credo-ts/didcomm';
|
|
5
|
+
import { Pool } from 'pg';
|
|
6
|
+
import PGPubsub from 'pg-pubsub';
|
|
7
|
+
import { PostgresMessageQueuedEventType, } from './interfaces.js';
|
|
8
|
+
import { buildPgDatabaseWithMigrations } from './utils/buildPgDatabaseWithMigrations.js';
|
|
9
|
+
export class DidCommTransportQueuePostgres {
|
|
10
|
+
constructor(options) {
|
|
11
|
+
const { logger, postgresUser, postgresPassword, postgresHost, postgresDatabaseName } = options;
|
|
12
|
+
this.logger = logger;
|
|
13
|
+
this.postgresUser = postgresUser;
|
|
14
|
+
this.postgresPassword = postgresPassword;
|
|
15
|
+
this.postgresHost = postgresHost;
|
|
16
|
+
this.postgresDatabaseName = postgresDatabaseName || 'messagepickuprepository';
|
|
17
|
+
// Initialize instanceName
|
|
18
|
+
this.instanceName = `${os.hostname()}-${process.pid}-${randomUUID()}`;
|
|
19
|
+
this.logger?.info(`[initialize] Instance identifier set to: ${this.instanceName}`);
|
|
20
|
+
// Initialize Pub/Sub instance if database listener is enabled
|
|
21
|
+
this.logger?.debug('[initialize] Initializing pubSubInstance');
|
|
22
|
+
this.pubSubInstance = new PGPubsub(`postgres://${postgresUser}:${postgresPassword}@${postgresHost}/${postgresDatabaseName}`);
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Initializes the service by setting up the database, message listeners, and the agent.
|
|
26
|
+
* This method also configures the Pub/Sub system and registers event handlers.
|
|
27
|
+
*
|
|
28
|
+
* @returns {Promise<void>} A promise that resolves when the initialization is complete.
|
|
29
|
+
* @throws {Error} Throws an error if initialization fails due to database, Pub/Sub, or agent setup issues.
|
|
30
|
+
*/
|
|
31
|
+
async initialize(agent) {
|
|
32
|
+
try {
|
|
33
|
+
// Initialize the database
|
|
34
|
+
await buildPgDatabaseWithMigrations(this.logger, {
|
|
35
|
+
user: this.postgresUser,
|
|
36
|
+
password: this.postgresPassword,
|
|
37
|
+
host: this.postgresHost,
|
|
38
|
+
}, this.postgresDatabaseName);
|
|
39
|
+
this.logger?.info('[initialize] The database has been build successfully');
|
|
40
|
+
// Configure PostgreSQL pool for the messages collections
|
|
41
|
+
this.messagesCollection = new Pool({
|
|
42
|
+
user: this.postgresUser,
|
|
43
|
+
password: this.postgresPassword,
|
|
44
|
+
host: this.postgresHost,
|
|
45
|
+
database: this.postgresDatabaseName,
|
|
46
|
+
port: 5432,
|
|
47
|
+
});
|
|
48
|
+
// Initialize Listener PUB/SUB
|
|
49
|
+
await this.initializeMessageListener(agent.context, 'newMessage');
|
|
50
|
+
// Register event handlers
|
|
51
|
+
agent.events.on(DidCommMessagePickupEventTypes.LiveSessionRemoved, async (data) => {
|
|
52
|
+
const connectionId = data.payload.session.connectionId;
|
|
53
|
+
agent.context.config.logger.info(`*** Session removed for connectionId: ${connectionId} ***`);
|
|
54
|
+
try {
|
|
55
|
+
// Verify message sending method and delete session record from DB
|
|
56
|
+
await this.checkQueueMessages(agent.context, connectionId);
|
|
57
|
+
await this.removeLiveSessionOnDb(agent.context, connectionId);
|
|
58
|
+
}
|
|
59
|
+
catch (handlerError) {
|
|
60
|
+
agent.context.config.logger.error(`Error handling LiveSessionRemoved: ${handlerError}`);
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
agent.events.on(DidCommMessagePickupEventTypes.LiveSessionSaved, async (data) => {
|
|
64
|
+
const liveSessionData = data.payload.session;
|
|
65
|
+
agent.context.config.logger.info(`*** Session saved for connectionId: ${liveSessionData.connectionId} ***`);
|
|
66
|
+
try {
|
|
67
|
+
// Add the live session record to the database
|
|
68
|
+
await this.addLiveSessionOnDb(agent.context, liveSessionData, this.instanceName);
|
|
69
|
+
}
|
|
70
|
+
catch (handlerError) {
|
|
71
|
+
agent.context.config.logger.error(`Error handling LiveSessionSaved: ${handlerError}`);
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
catch (error) {
|
|
76
|
+
agent.context.config.logger.error(`[initialize] Initialization failed: ${error}`);
|
|
77
|
+
throw new Error(`Failed to initialize the service: ${error}`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Fetches messages from the queue based on the specified options.
|
|
82
|
+
*
|
|
83
|
+
* @param {TakeFromQueueOptions} options - The options for fetching messages.
|
|
84
|
+
* @param {string} options.connectionId - The ID of the connection.
|
|
85
|
+
* @param {number} [options.limit] - The maximum number of messages to fetch.
|
|
86
|
+
* @param {boolean} options.deleteMessages - Whether to delete messages after retrieval.
|
|
87
|
+
* @param {string} options.recipientDid - The DID of the recipient.
|
|
88
|
+
* @returns {Promise<QueuedMessage[]>} A promise resolving to an array of queued messages.
|
|
89
|
+
*/
|
|
90
|
+
async takeFromQueue(agentContext, options) {
|
|
91
|
+
const { connectionId, limit, deleteMessages, recipientDid } = options;
|
|
92
|
+
agentContext.config.logger.info(`[takeFromQueue] Initializing method for ConnectionId: ${connectionId}, Limit: ${limit}`);
|
|
93
|
+
try {
|
|
94
|
+
// If deleteMessages is true, just fetch messages without updating their state
|
|
95
|
+
if (deleteMessages) {
|
|
96
|
+
const query = `
|
|
97
|
+
SELECT id, encrypted_message, state, created_at
|
|
98
|
+
FROM queued_message
|
|
99
|
+
WHERE (connection_id = $1 OR $2 = ANY (recipient_dids)) AND state = 'pending'
|
|
100
|
+
ORDER BY created_at
|
|
101
|
+
LIMIT $3
|
|
102
|
+
`;
|
|
103
|
+
const params = [connectionId, recipientDid, limit ?? 0];
|
|
104
|
+
const result = await this.messagesCollection?.query(query, params);
|
|
105
|
+
if (!result || result.rows.length === 0) {
|
|
106
|
+
agentContext.config.logger.debug(`[takeFromQueue] No messages found for ConnectionId: ${connectionId}`);
|
|
107
|
+
return [];
|
|
108
|
+
}
|
|
109
|
+
return result.rows.map((message) => ({
|
|
110
|
+
id: message.id,
|
|
111
|
+
encryptedMessage: message.encrypted_message,
|
|
112
|
+
receivedAt: new Date(message.created_at),
|
|
113
|
+
state: message.state,
|
|
114
|
+
}));
|
|
115
|
+
}
|
|
116
|
+
// Use UPDATE and RETURNING to fetch and update messages in one step
|
|
117
|
+
const query = `
|
|
118
|
+
UPDATE queued_message
|
|
119
|
+
SET state = 'sending'
|
|
120
|
+
WHERE id IN (
|
|
121
|
+
SELECT id
|
|
122
|
+
FROM queued_message
|
|
123
|
+
WHERE (connection_id = $1 OR $2 = ANY (recipient_dids))
|
|
124
|
+
AND state = 'pending'
|
|
125
|
+
ORDER BY created_at
|
|
126
|
+
LIMIT $3
|
|
127
|
+
)
|
|
128
|
+
RETURNING id, encrypted_message, state, created_at;
|
|
129
|
+
`;
|
|
130
|
+
const params = [connectionId, recipientDid, limit ?? 0];
|
|
131
|
+
const result = await this.messagesCollection?.query(query, params);
|
|
132
|
+
if (!result || result.rows.length === 0) {
|
|
133
|
+
agentContext.config.logger.debug(`[takeFromQueue] No messages updated for ConnectionId: ${connectionId}`);
|
|
134
|
+
return [];
|
|
135
|
+
}
|
|
136
|
+
agentContext.config.logger.debug(`[takeFromQueue] ${result.rows.length} messages updated to "sending" state.`);
|
|
137
|
+
// Return the messages as QueuedMessage objects
|
|
138
|
+
return result.rows.map((message) => ({
|
|
139
|
+
id: message.id,
|
|
140
|
+
encryptedMessage: message.encrypted_message,
|
|
141
|
+
receivedAt: new Date(message.created_at),
|
|
142
|
+
state: 'sending',
|
|
143
|
+
}));
|
|
144
|
+
}
|
|
145
|
+
catch (error) {
|
|
146
|
+
agentContext.config.logger.error(`[takeFromQueue] Error: ${error}`);
|
|
147
|
+
return [];
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Retrieves the count of available messages in the queue for a given connection.
|
|
152
|
+
*
|
|
153
|
+
* @param {GetAvailableMessageCountOptions} options - Options for retrieving the message count.
|
|
154
|
+
* @param {string} options.connectionId - The ID of the connection to check.
|
|
155
|
+
* @returns {Promise<number>} A promise resolving to the count of available messages.
|
|
156
|
+
*/
|
|
157
|
+
async getAvailableMessageCount(agentContext, options) {
|
|
158
|
+
const { connectionId } = options;
|
|
159
|
+
agentContext.config.logger.debug(`[getAvailableMessageCount] Initializing method for ConnectionId: ${connectionId}`);
|
|
160
|
+
try {
|
|
161
|
+
// Query to count pending messages for the specified connection ID
|
|
162
|
+
const query = `
|
|
163
|
+
SELECT COUNT(*) AS count
|
|
164
|
+
FROM queued_message
|
|
165
|
+
WHERE connection_id = $1 AND state = 'pending'
|
|
166
|
+
`;
|
|
167
|
+
const params = [connectionId];
|
|
168
|
+
const result = await this.messagesCollection?.query(query, params);
|
|
169
|
+
if (!result || result.rows.length === 0) {
|
|
170
|
+
agentContext.config.logger.debug(`[getAvailableMessageCount] No pending messages found for ConnectionId: ${connectionId}`);
|
|
171
|
+
return 0;
|
|
172
|
+
}
|
|
173
|
+
// Parse the count result
|
|
174
|
+
const numberMessage = Number.parseInt(result.rows[0].count, 10);
|
|
175
|
+
agentContext.config.logger.debug(`[getAvailableMessageCount] Count of available messages: ${numberMessage}`);
|
|
176
|
+
return numberMessage;
|
|
177
|
+
}
|
|
178
|
+
catch (error) {
|
|
179
|
+
agentContext.config.logger.error(`[getAvailableMessageCount] Error while retrieving message count: ${error}`);
|
|
180
|
+
return 0;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Adds a new message to the queue and processes it based on live session status.
|
|
185
|
+
*
|
|
186
|
+
* @param {AddMessageOptions} options - The options for adding a message.
|
|
187
|
+
* @param {string} options.connectionId - The ID of the connection.
|
|
188
|
+
* @param {string[]} options.recipientDids - Recipient DIDs for the message.
|
|
189
|
+
* @param {string} options.payload - The encrypted message payload.
|
|
190
|
+
* @returns {Promise<string> }- A promise resolving to the messageId and receivedAt of the added message.
|
|
191
|
+
* @throws {Error} Throws an error if the agent is not defined or if an error occurs during message insertion or processing.
|
|
192
|
+
*/
|
|
193
|
+
async addMessage(agentContext, options) {
|
|
194
|
+
const { connectionId, recipientDids, payload } = options;
|
|
195
|
+
agentContext.config.logger.debug(`[addMessage] Initializing new message for connectionId: ${connectionId}`);
|
|
196
|
+
const receivedAt = new Date();
|
|
197
|
+
if (!this.messagesCollection) {
|
|
198
|
+
throw new Error('messagesCollection is not defined');
|
|
199
|
+
}
|
|
200
|
+
try {
|
|
201
|
+
// Retrieve local live session details
|
|
202
|
+
const localLiveSession = await this.findLocalLiveSession(agentContext, connectionId);
|
|
203
|
+
// Insert message into database
|
|
204
|
+
const query = `
|
|
205
|
+
INSERT INTO queued_message(connection_id, recipient_dids, encrypted_message, state, created_at)
|
|
206
|
+
VALUES($1, $2, $3, $4, $5)
|
|
207
|
+
RETURNING id
|
|
208
|
+
`;
|
|
209
|
+
const state = localLiveSession ? 'sending' : 'pending';
|
|
210
|
+
const result = await this.messagesCollection.query(query, [
|
|
211
|
+
connectionId,
|
|
212
|
+
recipientDids,
|
|
213
|
+
payload,
|
|
214
|
+
state,
|
|
215
|
+
receivedAt,
|
|
216
|
+
]);
|
|
217
|
+
const messageRecord = result?.rows[0];
|
|
218
|
+
this.logger?.debug(`[addMessage] Message added with ID: ${messageRecord.id}, receivedAt: ${receivedAt.toISOString()} for connectionId: ${connectionId}`);
|
|
219
|
+
// Verify if a live session exists in DB (other instances)
|
|
220
|
+
const liveSessionInPostgres = await this.findLiveSessionInDb(agentContext, connectionId);
|
|
221
|
+
// Always emit MessageQueued event with complete payload
|
|
222
|
+
await this.emitMessageQueuedEvent(agentContext, {
|
|
223
|
+
message: {
|
|
224
|
+
id: messageRecord.id,
|
|
225
|
+
connectionId,
|
|
226
|
+
recipientDids,
|
|
227
|
+
encryptedMessage: payload,
|
|
228
|
+
receivedAt,
|
|
229
|
+
state,
|
|
230
|
+
},
|
|
231
|
+
session: localLiveSession || liveSessionInPostgres || undefined,
|
|
232
|
+
});
|
|
233
|
+
if (localLiveSession) {
|
|
234
|
+
agentContext.config.logger.debug(`[addMessage] Local live session exists for connectionId: ${connectionId}`);
|
|
235
|
+
const messagePickupApi = agentContext.resolve(DidCommMessagePickupApi);
|
|
236
|
+
await messagePickupApi.deliverMessages({
|
|
237
|
+
pickupSessionId: localLiveSession.id,
|
|
238
|
+
messages: [{ id: messageRecord.id, encryptedMessage: payload, receivedAt }],
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
else if (liveSessionInPostgres) {
|
|
242
|
+
agentContext.config.logger.debug(`[addMessage] Publishing new message event to Pub/Sub channel for connectionId: ${connectionId}`);
|
|
243
|
+
await this.pubSubInstance.publish('newMessage', connectionId);
|
|
244
|
+
}
|
|
245
|
+
return messageRecord.id;
|
|
246
|
+
}
|
|
247
|
+
catch (error) {
|
|
248
|
+
agentContext.config.logger.error(`[addMessage] Error during message insertion or processing: ${error}`);
|
|
249
|
+
throw new Error(`Failed to add message: ${error}`);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Removes specified messages from the queue for a given connection.
|
|
254
|
+
*
|
|
255
|
+
* @param {RemoveMessagesOptions} options - Options for removing messages.
|
|
256
|
+
* @param {string} options.connectionId - The ID of the connection.
|
|
257
|
+
* @param {string[]} options.messageIds - Array of message IDs to be removed.
|
|
258
|
+
* @returns {Promise<void>} A promise resolving when the operation completes.
|
|
259
|
+
*/
|
|
260
|
+
async removeMessages(agentContext, options) {
|
|
261
|
+
const { connectionId, messageIds } = options;
|
|
262
|
+
agentContext.config.logger.debug(`[removeMessages] Attempting to remove messages with IDs: ${messageIds} for ConnectionId: ${connectionId}`);
|
|
263
|
+
// Validate messageIds
|
|
264
|
+
if (!messageIds || messageIds.length === 0) {
|
|
265
|
+
agentContext.config.logger.debug('[removeMessages] No message IDs provided. No messages will be removed.');
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
try {
|
|
269
|
+
// Generate placeholders for the SQL query dynamically based on messageIds length
|
|
270
|
+
const placeholders = messageIds.map((_, index) => `$${index + 2}`).join(', ');
|
|
271
|
+
// Construct the SQL DELETE query
|
|
272
|
+
const query = `DELETE FROM queued_message WHERE connection_id = $1 AND id IN (${placeholders})`;
|
|
273
|
+
// Combine connectionId with messageIds as query parameters
|
|
274
|
+
const queryParams = [connectionId, ...messageIds];
|
|
275
|
+
// Execute the query
|
|
276
|
+
await this.messagesCollection?.query(query, queryParams);
|
|
277
|
+
agentContext.config.logger.debug(`[removeMessages] Successfully removed messages with IDs: ${messageIds} for ConnectionId: ${connectionId}`);
|
|
278
|
+
}
|
|
279
|
+
catch (error) {
|
|
280
|
+
agentContext.config.logger.error(`[removeMessages] Error occurred while removing messages: ${error}`);
|
|
281
|
+
throw new Error(`Failed to remove messages: ${error}`);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
async shutdown(agentContext) {
|
|
285
|
+
agentContext.config.logger.info('[shutdown] Close connection to postgres');
|
|
286
|
+
await this.messagesCollection?.end();
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Subscribes to a specific Pub/Sub channel and handles incoming messages.
|
|
290
|
+
*
|
|
291
|
+
* @param {string} channel - The name of the channel to subscribe to.
|
|
292
|
+
* @returns {Promise<void>} A promise resolving when the listener is initialized.
|
|
293
|
+
*/
|
|
294
|
+
async initializeMessageListener(agentContext, channel) {
|
|
295
|
+
agentContext.config.logger.info(`[initializeMessageListener] Initializing method for channel: ${channel}`);
|
|
296
|
+
try {
|
|
297
|
+
// Add a listener to the specified Pub/Sub channel
|
|
298
|
+
await this.pubSubInstance.addChannel(channel, async (connectionId) => {
|
|
299
|
+
agentContext.config.logger.debug(`[initializeMessageListener] Received new message on channel: ${channel} for connectionId: ${connectionId}`);
|
|
300
|
+
// Fetch the local live session for the given connectionId
|
|
301
|
+
const pickupLiveSession = await this.findLocalLiveSession(agentContext, connectionId);
|
|
302
|
+
if (pickupLiveSession) {
|
|
303
|
+
agentContext.config.logger.debug(`[initializeMessageListener] ${this.instanceName} found a LiveSession on channel: ${channel} for connectionId: ${connectionId}. Delivering messages.`);
|
|
304
|
+
const messagePickupApi = agentContext.resolve(DidCommMessagePickupApi);
|
|
305
|
+
// Deliver messages from the queue for the live session
|
|
306
|
+
await messagePickupApi.deliverMessagesFromQueue({
|
|
307
|
+
pickupSessionId: pickupLiveSession.id,
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
else {
|
|
311
|
+
agentContext.config.logger.debug(`[initializeMessageListener] No LiveSession found on channel: ${channel} for connectionId: ${connectionId}.`);
|
|
312
|
+
}
|
|
313
|
+
});
|
|
314
|
+
agentContext.config.logger.info(`[initializeMessageListener] Listener successfully added for channel: ${channel}`);
|
|
315
|
+
}
|
|
316
|
+
catch (error) {
|
|
317
|
+
agentContext.config.logger.error(`[initializeMessageListener] Error initializing listener for channel ${channel}: ${error}`);
|
|
318
|
+
throw new Error(`Failed to initialize listener for channel ${channel}: ${error}`);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* This function checks that messages from the connectionId, which were left in the 'sending'
|
|
323
|
+
* state after a liveSessionRemove event, are updated to the 'pending' state for subsequent sending
|
|
324
|
+
* @param connectionID
|
|
325
|
+
*/
|
|
326
|
+
async checkQueueMessages(agentContext, connectionId) {
|
|
327
|
+
try {
|
|
328
|
+
agentContext.config.logger.debug(`[checkQueueMessages] Init verify messages state 'sending'`);
|
|
329
|
+
const messagesToSend = await this.messagesCollection?.query('SELECT * FROM queued_message WHERE state = $1 and connection_id = $2', ['sending', connectionId]);
|
|
330
|
+
if (messagesToSend && messagesToSend.rows.length > 0) {
|
|
331
|
+
for (const message of messagesToSend.rows) {
|
|
332
|
+
// Update the message state to 'pending'
|
|
333
|
+
await this.messagesCollection?.query('UPDATE queued_message SET state = $1 WHERE id = $2', [
|
|
334
|
+
'pending',
|
|
335
|
+
message.id,
|
|
336
|
+
]);
|
|
337
|
+
}
|
|
338
|
+
agentContext.config.logger.debug(`[checkQueueMessages] ${messagesToSend.rows.length} messages updated to 'pending'.`);
|
|
339
|
+
}
|
|
340
|
+
else {
|
|
341
|
+
agentContext.config.logger.debug('[checkQueueMessages] No messages in "sending" state.');
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
catch (error) {
|
|
345
|
+
agentContext.config.logger.error(`[checkQueueMessages] Error processing messages: ${error}`);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* Get current active live mode message pickup session for a given connection
|
|
350
|
+
* @param connectionId
|
|
351
|
+
* @returns
|
|
352
|
+
*/
|
|
353
|
+
async findLocalLiveSession(agentContext, connectionId) {
|
|
354
|
+
agentContext.config.logger.debug(`[findLocalLiveSession] Verify current active live mode for connectionId ${connectionId}`);
|
|
355
|
+
try {
|
|
356
|
+
const messagePickupApi = agentContext.resolve(DidCommMessagePickupApi);
|
|
357
|
+
const localSession = await messagePickupApi.getLiveModeSession({ connectionId });
|
|
358
|
+
return localSession ? { ...localSession, isLocalSession: true } : undefined;
|
|
359
|
+
}
|
|
360
|
+
catch (error) {
|
|
361
|
+
agentContext.config.logger.error(`[findLocalLiveSession] error in getLocalliveSession: ${error}`);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* This method allow find record into DB to determine if the connectionID has a liveSession in another instance
|
|
366
|
+
* @param connectionId
|
|
367
|
+
* @returns liveSession object or false
|
|
368
|
+
*/
|
|
369
|
+
async findLiveSessionInDb(agentContext, connectionId) {
|
|
370
|
+
agentContext.config.logger.debug(`[findLiveSessionInDb] initializing find registry for connectionId ${connectionId}`);
|
|
371
|
+
if (!connectionId)
|
|
372
|
+
throw new Error('connectionId is not defined');
|
|
373
|
+
try {
|
|
374
|
+
const queryLiveSession = await this.messagesCollection?.query('SELECT session_id, connection_id, protocol_version FROM live_session WHERE connection_id = $1 LIMIT $2', [connectionId, 1]);
|
|
375
|
+
// Check if liveSession is not empty (record found)
|
|
376
|
+
const recordFound = queryLiveSession?.rows && queryLiveSession.rows.length > 0;
|
|
377
|
+
agentContext.config.logger.debug(`[findLiveSessionInDb] record found status ${recordFound} to connectionId ${connectionId}`);
|
|
378
|
+
return recordFound
|
|
379
|
+
? { ...queryLiveSession.rows[0], role: DidCommMessagePickupSessionRole.MessageHolder, isLocalSession: false }
|
|
380
|
+
: undefined;
|
|
381
|
+
}
|
|
382
|
+
catch (_error) {
|
|
383
|
+
agentContext.config.logger.debug(`[findLiveSessionInDb] Error find to connectionId ${connectionId}`);
|
|
384
|
+
return undefined; // Return false in case of an error
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* This method adds a new connectionId and instance name to DB upon LiveSessionSave event
|
|
389
|
+
* @param connectionId
|
|
390
|
+
* @param instance
|
|
391
|
+
*/
|
|
392
|
+
async addLiveSessionOnDb(agentContext, session, instance) {
|
|
393
|
+
const { id, connectionId, protocolVersion } = session;
|
|
394
|
+
agentContext.config.logger.debug(`[addLiveSessionOnDb] initializing add LiveSession DB to connectionId ${connectionId}`);
|
|
395
|
+
if (!session)
|
|
396
|
+
throw new Error('session is not defined');
|
|
397
|
+
try {
|
|
398
|
+
const insertMessageDB = await this.messagesCollection?.query('INSERT INTO live_session (session_id, connection_id, protocol_version, instance) VALUES($1, $2, $3, $4) RETURNING session_id', [id, connectionId, protocolVersion, instance]);
|
|
399
|
+
const liveSessionId = insertMessageDB?.rows[0].session_id;
|
|
400
|
+
this.logger?.debug(`[addLiveSessionOnDb] add liveSession to liveSessionId ${liveSessionId} to connectionId ${connectionId}`);
|
|
401
|
+
}
|
|
402
|
+
catch (_error) {
|
|
403
|
+
agentContext.config.logger.debug(`[addLiveSessionOnDb] error add liveSession DB ${connectionId}`);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
*This method remove connectionId record to DB upon LiveSessionRemove event
|
|
408
|
+
* @param connectionId
|
|
409
|
+
*/
|
|
410
|
+
async removeLiveSessionOnDb(agentContext, connectionId) {
|
|
411
|
+
agentContext.config.logger.debug(`[removeLiveSessionOnDb] initializing remove LiveSession to connectionId ${connectionId}`);
|
|
412
|
+
if (!connectionId)
|
|
413
|
+
throw new Error('connectionId is not defined');
|
|
414
|
+
try {
|
|
415
|
+
// Construct the SQL query with the placeholders
|
|
416
|
+
const query = 'DELETE FROM live_session WHERE connection_id = $1';
|
|
417
|
+
// Add connectionId for query parameters
|
|
418
|
+
const queryParams = [connectionId];
|
|
419
|
+
await this.messagesCollection?.query(query, queryParams);
|
|
420
|
+
agentContext.config.logger.debug(`[removeLiveSessionOnDb] removed LiveSession to connectionId ${connectionId}`);
|
|
421
|
+
}
|
|
422
|
+
catch (error) {
|
|
423
|
+
agentContext.config.logger.error(`[removeLiveSessionOnDb] Error removing LiveSession: ${error}`);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* Emits a MessageQueuedEvent using the agent's EventEmitter.
|
|
428
|
+
*
|
|
429
|
+
* @param {object} options - Event payload containing at least connectionId and messageId.
|
|
430
|
+
* @param {string} options.connectionId - The connection identifier.
|
|
431
|
+
* @param {string} options.messageId - The message identifier.
|
|
432
|
+
* @param {any} [options.*] - Additional optional properties for the event payload.
|
|
433
|
+
* @throws {Error} Throws if the agent is not initialized.
|
|
434
|
+
*/
|
|
435
|
+
async emitMessageQueuedEvent(agentContext, options) {
|
|
436
|
+
const { message, session } = options;
|
|
437
|
+
agentContext.config.logger.debug(`[emitMessageQueuedEvent] Emitting MessageQueuedEvent for connectionId: ${options.message.connectionId}, messageId: ${options.message.id}`);
|
|
438
|
+
const eventEmitter = agentContext.resolve(EventEmitter);
|
|
439
|
+
eventEmitter.emit(agentContext, {
|
|
440
|
+
type: PostgresMessageQueuedEventType,
|
|
441
|
+
payload: {
|
|
442
|
+
message,
|
|
443
|
+
session,
|
|
444
|
+
},
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
//# sourceMappingURL=TransportQueuePostgres.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"TransportQueuePostgres.js","sourceRoot":"","sources":["../src/TransportQueuePostgres.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,KAAK,EAAE,MAAM,SAAS,CAAA;AAC7B,OAAO,EAAuB,YAAY,EAAU,MAAM,gBAAgB,CAAA;AAC1E,OAAO,EAEL,uBAAuB,EACvB,8BAA8B,EAG9B,+BAA+B,GAOhC,MAAM,mBAAmB,CAAA;AAC1B,OAAO,EAAE,IAAI,EAAE,MAAM,IAAI,CAAA;AACzB,OAAO,QAAQ,MAAM,WAAW,CAAA;AAChC,OAAO,EAGL,8BAA8B,GAE/B,MAAM,iBAAiB,CAAA;AACxB,OAAO,EAAE,6BAA6B,EAAE,MAAM,0CAA0C,CAAA;AAExF,MAAM,OAAO,6BAA6B;IAUxC,YAAmB,OAA6C;QAC9D,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,gBAAgB,EAAE,YAAY,EAAE,oBAAoB,EAAE,GAAG,OAAO,CAAA;QAE9F,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAA;QAChC,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAA;QACxC,IAAI,CAAC,YAA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,KAAK,EAAE,CAAC,CAAA;QAClG,CAAC;IACH,CAAC;IAED;;;;;;;;OAQG;IACK,KAAK,CAAC,sBAAsB,CAAC,YAA0B,EAAE,OAA8C;QAC7G,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,OAAO,CAAA;QAEpC,YAAY,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAC9B,0EAA0E,OAAO,CAAC,OAAO,CAAC,YAAY,gBAAgB,OAAO,CAAC,OAAO,CAAC,EAAE,EAAE,CAC3I,CAAA;QAED,MAAM,YAAY,GAAG,YAAY,CAAC,OAAO,CAAC,YAAY,CAAC,CAAA;QACvD,YAAY,CAAC,IAAI,CAA6B,YAAY,EAAE;YAC1D,IAAI,EAAE,8BAA8B;YACpC,OAAO,EAAE;gBACP,OAAO;gBACP,OAAO;aACR;SACF,CAAC,CAAA;IACJ,CAAC;CACF"}
|
package/build/index.d.ts
ADDED
package/build/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,8BAA8B,GAE/B,MAAM,iBAAiB,CAAA;AACxB,OAAO,EAAE,6BAA6B,EAAE,MAAM,6BAA6B,CAAA"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { BaseEvent, Logger } from '@credo-ts/core';
|
|
2
|
+
import { DidCommEncryptedMessage, DidCommMessagePickupSession } from '@credo-ts/didcomm';
|
|
3
|
+
export interface PostgresTransportQueuePostgresConfig {
|
|
4
|
+
logger?: Logger;
|
|
5
|
+
postgresUser: string;
|
|
6
|
+
postgresPassword: string;
|
|
7
|
+
postgresHost: string;
|
|
8
|
+
postgresDatabaseName?: string;
|
|
9
|
+
}
|
|
10
|
+
export declare const PostgresMessageQueuedEventType: "TransportQueuePostgresMessageQueued";
|
|
11
|
+
export interface PostgresMessageQueuedEvent extends BaseEvent {
|
|
12
|
+
type: typeof PostgresMessageQueuedEventType;
|
|
13
|
+
payload: {
|
|
14
|
+
message: {
|
|
15
|
+
id: string;
|
|
16
|
+
connectionId: string;
|
|
17
|
+
recipientDids: string[];
|
|
18
|
+
encryptedMessage: DidCommEncryptedMessage;
|
|
19
|
+
receivedAt: Date;
|
|
20
|
+
state: 'pending' | 'sending';
|
|
21
|
+
};
|
|
22
|
+
session?: DidCommMessagePickupSession;
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
export interface ExtendedMessagePickupSession extends DidCommMessagePickupSession {
|
|
26
|
+
isLocalSession: boolean;
|
|
27
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../src/interfaces.ts"],"names":[],"mappings":"AAWA,MAAM,CAAC,MAAM,8BAA8B,GAAG,qCAA8C,CAAA"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Logger } from '@credo-ts/core';
|
|
2
|
+
/**
|
|
3
|
+
* Runs all pending SQL migrations in a target PostgreSQL database.
|
|
4
|
+
* - Automatically creates the database if it does not exist.
|
|
5
|
+
* - Applies versioned `.sql` files from a directory.
|
|
6
|
+
*
|
|
7
|
+
* @param logger - Optional Credo-compatible logger instance
|
|
8
|
+
* @param postgresConfig - Connection config to connect as superuser (to create DB if needed).
|
|
9
|
+
* @param targetDatabase - Name of the target database to migrate.
|
|
10
|
+
* @param migrationsDir - Directory where migration `.sql` files are located.
|
|
11
|
+
*/
|
|
12
|
+
export declare function buildPgDatabaseWithMigrations(logger: Logger | undefined, postgresConfig: {
|
|
13
|
+
user: string;
|
|
14
|
+
password: string;
|
|
15
|
+
host: string;
|
|
16
|
+
port?: number;
|
|
17
|
+
}, targetDatabase: string, migrationsDir?: string): Promise<void>;
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { Client, Pool } from 'pg';
|
|
4
|
+
/**
|
|
5
|
+
* Runs all pending SQL migrations in a target PostgreSQL database.
|
|
6
|
+
* - Automatically creates the database if it does not exist.
|
|
7
|
+
* - Applies versioned `.sql` files from a directory.
|
|
8
|
+
*
|
|
9
|
+
* @param logger - Optional Credo-compatible logger instance
|
|
10
|
+
* @param postgresConfig - Connection config to connect as superuser (to create DB if needed).
|
|
11
|
+
* @param targetDatabase - Name of the target database to migrate.
|
|
12
|
+
* @param migrationsDir - Directory where migration `.sql` files are located.
|
|
13
|
+
*/
|
|
14
|
+
export async function buildPgDatabaseWithMigrations(logger, postgresConfig, targetDatabase, migrationsDir = path.resolve(import.meta.dirname, '../../migrations')) {
|
|
15
|
+
const adminClient = new Client(postgresConfig);
|
|
16
|
+
try {
|
|
17
|
+
await adminClient.connect();
|
|
18
|
+
// Try to create the target database if it doesn't exist
|
|
19
|
+
const existsResult = await adminClient.query('SELECT 1 FROM pg_database WHERE datname = $1', [targetDatabase]);
|
|
20
|
+
if (existsResult.rowCount === 0) {
|
|
21
|
+
await adminClient.query(`CREATE DATABASE ${targetDatabase}`);
|
|
22
|
+
logger?.info(`[migration] Database "${targetDatabase}" created.`);
|
|
23
|
+
}
|
|
24
|
+
else {
|
|
25
|
+
logger?.info(`[migration] Database "${targetDatabase}" already exists.`);
|
|
26
|
+
}
|
|
27
|
+
await adminClient.end();
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
logger?.error(`[migration] Failed to create database "${targetDatabase}": ${error.message}`);
|
|
31
|
+
await adminClient.end();
|
|
32
|
+
throw error;
|
|
33
|
+
}
|
|
34
|
+
// Now connect to the target database using a pool
|
|
35
|
+
const pool = new Pool({ ...postgresConfig, database: targetDatabase });
|
|
36
|
+
const client = await pool.connect();
|
|
37
|
+
try {
|
|
38
|
+
await client.query('BEGIN');
|
|
39
|
+
await client.query(`
|
|
40
|
+
CREATE TABLE IF NOT EXISTS schema_version (
|
|
41
|
+
id SERIAL PRIMARY KEY,
|
|
42
|
+
version INTEGER NOT NULL,
|
|
43
|
+
updated_at TIMESTAMP DEFAULT now()
|
|
44
|
+
)
|
|
45
|
+
`);
|
|
46
|
+
const result = await client.query('SELECT version FROM schema_version ORDER BY id DESC LIMIT 1');
|
|
47
|
+
const currentVersion = result.rows.length > 0 ? result.rows[0].version : 0;
|
|
48
|
+
logger?.info(`[migration] Current schema version: ${currentVersion}`);
|
|
49
|
+
if (!fs.existsSync(migrationsDir)) {
|
|
50
|
+
logger?.warn(`[migration] Migrations directory not found: ${migrationsDir}. Skipping.`);
|
|
51
|
+
await client.query('COMMIT');
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
const files = fs
|
|
55
|
+
.readdirSync(migrationsDir)
|
|
56
|
+
.filter((file) => /^\d{3,}-[\w-]+\.sql$/.test(file))
|
|
57
|
+
.sort();
|
|
58
|
+
for (const file of files) {
|
|
59
|
+
const versionMatch = file.match(/^(\d{3,})-/);
|
|
60
|
+
if (!versionMatch) {
|
|
61
|
+
logger?.warn(`[migration] Skipping invalid filename: ${file}`);
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
const version = Number.parseInt(versionMatch[1], 10);
|
|
65
|
+
if (version <= currentVersion) {
|
|
66
|
+
logger?.debug(`[migration] Skipping already applied: ${file}`);
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
const sql = fs.readFileSync(path.join(migrationsDir, file), 'utf-8');
|
|
70
|
+
logger?.info(`[migration] Applying migration: ${file}`);
|
|
71
|
+
try {
|
|
72
|
+
await client.query(sql);
|
|
73
|
+
await client.query('INSERT INTO schema_version (version) VALUES ($1)', [version]);
|
|
74
|
+
logger?.info(`[migration] Applied successfully: ${file}`);
|
|
75
|
+
}
|
|
76
|
+
catch (fileErr) {
|
|
77
|
+
throw new Error(`[migration] Failed to apply ${file}: ${fileErr.message}`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
await client.query('COMMIT');
|
|
81
|
+
}
|
|
82
|
+
catch (err) {
|
|
83
|
+
logger?.error(`[migration] Migration process failed: ${err.message}`);
|
|
84
|
+
await client.query('ROLLBACK');
|
|
85
|
+
}
|
|
86
|
+
finally {
|
|
87
|
+
client.release();
|
|
88
|
+
await pool.end();
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
//# sourceMappingURL=buildPgDatabaseWithMigrations.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"buildPgDatabaseWithMigrations.js","sourceRoot":"","sources":["../../src/utils/buildPgDatabaseWithMigrations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAA;AACxB,OAAO,IAAI,MAAM,WAAW,CAAA;AAE5B,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,IAAI,CAAA;AAEjC;;;;;;;;;GASG;AACH,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,MAA0B,EAC1B,cAA+E,EAC/E,cAAsB,EACtB,gBAAwB,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,kBAAkB,CAAC;IAE7E,MAAM,WAAW,GAAG,IAAI,MAAM,CAAC,cAAc,CAAC,CAAA;IAE9C,IAAI,CAAC;QACH,MAAM,WAAW,CAAC,OAAO,EAAE,CAAA;QAE3B,wDAAwD;QACxD,MAAM,YAAY,GAAG,MAAM,WAAW,CAAC,KAAK,CAAC,8CAA8C,EAAE,CAAC,cAAc,CAAC,CAAC,CAAA;QAE9G,IAAI,YAAY,CAAC,QAAQ,KAAK,CAAC,EAAE,CAAC;YAChC,MAAM,WAAW,CAAC,KAAK,CAAC,mBAAmB,cAAc,EAAE,CAAC,CAAA;YAC5D,MAAM,EAAE,IAAI,CAAC,yBAAyB,cAAc,YAAY,CAAC,CAAA;QACnE,CAAC;aAAM,CAAC;YACN,MAAM,EAAE,IAAI,CAAC,yBAAyB,cAAc,mBAAmB,CAAC,CAAA;QAC1E,CAAC;QAED,MAAM,WAAW,CAAC,GAAG,EAAE,CAAA;IACzB,CAAC;IAAC,OAAO,KAAK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,OAAO,EAAE,CAAA;QAChB,MAAM,IAAI,CAAC,GAAG,EAAE,CAAA;IAClB,CAAC;AACH,CAAC"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
-- Create new type
|
|
2
|
+
DO $$
|
|
3
|
+
BEGIN
|
|
4
|
+
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'message_state') THEN
|
|
5
|
+
CREATE TYPE message_state AS ENUM ('pending', 'sending');
|
|
6
|
+
END IF;
|
|
7
|
+
END$$;
|
|
8
|
+
|
|
9
|
+
-- Create tables
|
|
10
|
+
|
|
11
|
+
CREATE TABLE IF NOT EXISTS queued_message (
|
|
12
|
+
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
|
|
13
|
+
connection_id UUID,
|
|
14
|
+
recipient_dids TEXT[],
|
|
15
|
+
encrypted_message JSONB,
|
|
16
|
+
state message_state NOT NULL,
|
|
17
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
18
|
+
);
|
|
19
|
+
|
|
20
|
+
CREATE INDEX IF NOT EXISTS queued_message_connection_id_idx ON queued_message (connection_id);
|
|
21
|
+
|
|
22
|
+
CREATE INDEX IF NOT EXISTS queued_message_connection_id_state_idx ON queued_message (connection_id, state);
|
|
23
|
+
|
|
24
|
+
CREATE INDEX IF NOT EXISTS queued_message_created_at_idx ON queued_message (created_at);
|
|
25
|
+
|
|
26
|
+
CREATE TABLE IF NOT EXISTS live_session (
|
|
27
|
+
session_id UUID PRIMARY KEY,
|
|
28
|
+
connection_id VARCHAR(50),
|
|
29
|
+
protocol_version VARCHAR(50),
|
|
30
|
+
instance VARCHAR(100),
|
|
31
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
32
|
+
);
|
|
33
|
+
|
|
34
|
+
CREATE INDEX IF NOT EXISTS live_session_connection_id_idx ON live_session USING btree (connection_id);
|
package/package.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@credo-ts/didcomm-transport-queue-postgres",
|
|
3
|
+
"main": "build/index.js",
|
|
4
|
+
"types": "build/index.d.ts",
|
|
5
|
+
"version": "0.0.0-alpha.1",
|
|
6
|
+
"files": [
|
|
7
|
+
"build",
|
|
8
|
+
"migrations"
|
|
9
|
+
],
|
|
10
|
+
"publishConfig": {
|
|
11
|
+
"access": "public"
|
|
12
|
+
},
|
|
13
|
+
"type": "module",
|
|
14
|
+
"description": "Credo DIDComm Transport Queue Postgres module",
|
|
15
|
+
"license": "Apache-2.0",
|
|
16
|
+
"homepage": "https://github.com/openwallet-foundation/didcomm-mediator-credo/tree/main/packages/transport-queue-postgres",
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "https://github.com/openwallet-foundation/didcomm-mediator-credo",
|
|
20
|
+
"directory": "packages/transport-queue-postgres"
|
|
21
|
+
},
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"pg": "^8.16.3",
|
|
24
|
+
"pg-pubsub": "^0.8.1"
|
|
25
|
+
},
|
|
26
|
+
"devDependencies": {
|
|
27
|
+
"@credo-ts/core": "^0.6.0",
|
|
28
|
+
"@credo-ts/didcomm": "^0.6.0",
|
|
29
|
+
"@types/pg": "^8.15.5",
|
|
30
|
+
"typescript": "^5.6.3"
|
|
31
|
+
},
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"@credo-ts/core": "^0.6.0",
|
|
34
|
+
"@credo-ts/didcomm": "^0.6.0"
|
|
35
|
+
},
|
|
36
|
+
"scripts": {
|
|
37
|
+
"build": "tsc -p tsconfig.build.json"
|
|
38
|
+
}
|
|
39
|
+
}
|