@furvester/upstream-sync 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +5 -0
- package/dist/index.d.ts +67 -0
- package/dist/index.js +155 -0
- package/package.json +59 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Furvester
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/// <reference types="node" resolution-mode="require"/>
|
|
2
|
+
import type { EntityClass, EntityManager, MikroORM } from "@mikro-orm/postgresql";
|
|
3
|
+
import { type CollectionPageParams, type Selector } from "jsonapi-zod-query";
|
|
4
|
+
import type { Logger } from "logforth";
|
|
5
|
+
import { type ConnectionOptions } from "rabbitmq-client";
|
|
6
|
+
import type { z } from "zod";
|
|
7
|
+
export type SyncManagerConfig = {
|
|
8
|
+
rabbitmq: ConnectionOptions;
|
|
9
|
+
orm: MikroORM;
|
|
10
|
+
logger: Logger;
|
|
11
|
+
namespace: string;
|
|
12
|
+
apiGatewayUrl: string;
|
|
13
|
+
apiKey: string;
|
|
14
|
+
};
|
|
15
|
+
export type SyncableEntityClass = EntityClass<{
|
|
16
|
+
id: string;
|
|
17
|
+
upstreamVersion: number;
|
|
18
|
+
}>;
|
|
19
|
+
export type PreSyncResource = {
|
|
20
|
+
id: string;
|
|
21
|
+
version: number;
|
|
22
|
+
};
|
|
23
|
+
export type PreSyncDocument<T extends PreSyncResource> = {
|
|
24
|
+
data: T[];
|
|
25
|
+
pageParams: CollectionPageParams;
|
|
26
|
+
};
|
|
27
|
+
export type MessageEventHandler<T = unknown> = (em: EntityManager, data: T) => Promise<void> | void;
|
|
28
|
+
export type MessageEvent<T extends z.ZodTypeAny> = {
|
|
29
|
+
key: string;
|
|
30
|
+
schema: T;
|
|
31
|
+
handler: MessageEventHandler<ReturnType<T["parse"]>>;
|
|
32
|
+
};
|
|
33
|
+
export type PreSyncHandler<T> = (em: EntityManager, resource: T) => Promise<void> | void;
|
|
34
|
+
export type PreSync<TSelector extends Selector<PreSyncDocument<PreSyncResource>>> = {
|
|
35
|
+
basePath: string;
|
|
36
|
+
searchParams?: URLSearchParams;
|
|
37
|
+
selector: TSelector;
|
|
38
|
+
entityClass: SyncableEntityClass;
|
|
39
|
+
create: PreSyncHandler<ReturnType<TSelector>["data"][number]>;
|
|
40
|
+
update: PreSyncHandler<ReturnType<TSelector>["data"][number]>;
|
|
41
|
+
};
|
|
42
|
+
export type UpstreamEntity = {
|
|
43
|
+
routingKeyPrefix: string;
|
|
44
|
+
events: MessageEvent<z.ZodTypeAny>[];
|
|
45
|
+
preSync: PreSync<Selector<PreSyncDocument<PreSyncResource>>>;
|
|
46
|
+
};
|
|
47
|
+
export type UpstreamService = {
|
|
48
|
+
serviceName: string;
|
|
49
|
+
entities: UpstreamEntity[];
|
|
50
|
+
};
|
|
51
|
+
export declare const createMessageEvent: <T extends z.ZodTypeAny>(event: MessageEvent<T>) => MessageEvent<T>;
|
|
52
|
+
export declare const createPreSync: <T extends Selector<PreSyncDocument<PreSyncResource>>>(preSync: PreSync<T>) => PreSync<T>;
|
|
53
|
+
export declare const createUpstreamEntity: (entity: UpstreamEntity) => UpstreamEntity;
|
|
54
|
+
export declare const createUpstreamService: (service: UpstreamService) => UpstreamService;
|
|
55
|
+
export declare class SyncManager {
|
|
56
|
+
private readonly rabbitmq;
|
|
57
|
+
private readonly config;
|
|
58
|
+
private readonly upstreamServices;
|
|
59
|
+
private readonly initialSyncMutex;
|
|
60
|
+
constructor(config: SyncManagerConfig);
|
|
61
|
+
addUpstreamService(service: UpstreamService): this;
|
|
62
|
+
run(): Promise<void>;
|
|
63
|
+
private createConsumer;
|
|
64
|
+
private runPreSync;
|
|
65
|
+
private preSyncEntity;
|
|
66
|
+
private waitReady;
|
|
67
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { Mutex } from "async-mutex";
|
|
2
|
+
import { handleJsonApiError, injectPageParams, } from "jsonapi-zod-query";
|
|
3
|
+
import { Connection, } from "rabbitmq-client";
|
|
4
|
+
export const createMessageEvent = (event) => event;
|
|
5
|
+
export const createPreSync = (preSync) => preSync;
|
|
6
|
+
export const createUpstreamEntity = (entity) => entity;
|
|
7
|
+
export const createUpstreamService = (service) => service;
|
|
8
|
+
export class SyncManager {
|
|
9
|
+
rabbitmq;
|
|
10
|
+
config;
|
|
11
|
+
upstreamServices = [];
|
|
12
|
+
initialSyncMutex = new Mutex();
|
|
13
|
+
constructor(config) {
|
|
14
|
+
this.config = config;
|
|
15
|
+
this.rabbitmq = new Connection(config.rabbitmq);
|
|
16
|
+
this.rabbitmq.on("error", (error) => {
|
|
17
|
+
config.logger.info("RabbitMQ connection error", { error });
|
|
18
|
+
});
|
|
19
|
+
this.rabbitmq.on("connection", () => {
|
|
20
|
+
config.logger.info("RabbitMQ connection successfully (re)established");
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
addUpstreamService(service) {
|
|
24
|
+
this.upstreamServices.push(service);
|
|
25
|
+
return this;
|
|
26
|
+
}
|
|
27
|
+
async run() {
|
|
28
|
+
await this.initialSyncMutex.acquire();
|
|
29
|
+
const consumer = this.createConsumer();
|
|
30
|
+
const handleShutdown = async () => {
|
|
31
|
+
await consumer.close();
|
|
32
|
+
await this.rabbitmq.close();
|
|
33
|
+
await this.config.orm.close(true);
|
|
34
|
+
};
|
|
35
|
+
process.on("SIGINT", handleShutdown);
|
|
36
|
+
process.on("SIGTERM", handleShutdown);
|
|
37
|
+
await this.runPreSync();
|
|
38
|
+
this.initialSyncMutex.release();
|
|
39
|
+
}
|
|
40
|
+
createConsumer() {
|
|
41
|
+
const queue = `${this.config.namespace}.upstream-sync`;
|
|
42
|
+
const exchanges = [];
|
|
43
|
+
const queueBindings = [];
|
|
44
|
+
const eventHandlers = new Map();
|
|
45
|
+
for (const service of this.upstreamServices) {
|
|
46
|
+
exchanges.push({
|
|
47
|
+
exchange: service.serviceName,
|
|
48
|
+
type: "topic",
|
|
49
|
+
});
|
|
50
|
+
for (const entity of service.entities) {
|
|
51
|
+
queueBindings.push({
|
|
52
|
+
exchange: service.serviceName,
|
|
53
|
+
queue,
|
|
54
|
+
routingKey: `${entity.routingKeyPrefix}.*`,
|
|
55
|
+
});
|
|
56
|
+
for (const event of entity.events) {
|
|
57
|
+
eventHandlers.set(`${entity.routingKeyPrefix}.${event.key}`, event);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return this.rabbitmq.createConsumer({
|
|
62
|
+
queue,
|
|
63
|
+
concurrency: 1,
|
|
64
|
+
qos: { prefetchCount: 1 },
|
|
65
|
+
exchanges,
|
|
66
|
+
queueBindings,
|
|
67
|
+
}, async (message) => {
|
|
68
|
+
await this.initialSyncMutex.waitForUnlock();
|
|
69
|
+
const eventHandler = eventHandlers.get(message.routingKey);
|
|
70
|
+
if (!eventHandler) {
|
|
71
|
+
this.config.logger.debug(`No event handler found for ${message.routingKey}`);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
const result = eventHandler.schema.safeParse(message.body);
|
|
75
|
+
if (!result.success) {
|
|
76
|
+
this.config.logger.error("Failed to parse message", {
|
|
77
|
+
issues: result.error.issues,
|
|
78
|
+
});
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
await this.config.orm.em.fork().transactional(async (em) => {
|
|
82
|
+
await eventHandler.handler(em, result.data);
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
async runPreSync() {
|
|
87
|
+
for (const service of this.upstreamServices) {
|
|
88
|
+
await this.waitReady(`/${service.serviceName}/health`, service.serviceName);
|
|
89
|
+
for (const entity of service.entities) {
|
|
90
|
+
await this.preSyncEntity(service, entity);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
async preSyncEntity(service, entity) {
|
|
95
|
+
const em = this.config.orm.em.fork();
|
|
96
|
+
const versions = new Map((await em
|
|
97
|
+
.createQueryBuilder(entity.preSync.entityClass)
|
|
98
|
+
.select(["id", "upstreamVersion"])
|
|
99
|
+
.execute("all", false)).map(({ id, upstream_version }) => [id, upstream_version]));
|
|
100
|
+
const baseUrl = new URL(`/${service.serviceName}${entity.preSync.basePath}`, this.config.apiGatewayUrl);
|
|
101
|
+
if (entity.preSync.searchParams) {
|
|
102
|
+
baseUrl.search = entity.preSync.searchParams.toString();
|
|
103
|
+
}
|
|
104
|
+
let url = baseUrl;
|
|
105
|
+
do {
|
|
106
|
+
const response = await fetch(url, {
|
|
107
|
+
headers: {
|
|
108
|
+
accept: "application/vnd.api+json",
|
|
109
|
+
authorization: `Bearer ${this.config.apiKey}`,
|
|
110
|
+
},
|
|
111
|
+
});
|
|
112
|
+
await handleJsonApiError(response);
|
|
113
|
+
const document = entity.preSync.selector(await response.json());
|
|
114
|
+
for (const resource of document.data) {
|
|
115
|
+
const version = versions.get(resource.id);
|
|
116
|
+
if (version === undefined) {
|
|
117
|
+
await entity.preSync.create(em, resource);
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
versions.delete(resource.id);
|
|
121
|
+
if (version === resource.version) {
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
await entity.preSync.update(em, resource);
|
|
125
|
+
}
|
|
126
|
+
if (document.pageParams.next) {
|
|
127
|
+
url = new URL(baseUrl);
|
|
128
|
+
injectPageParams(url, document.pageParams.next);
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
url = null;
|
|
132
|
+
} while (url !== null);
|
|
133
|
+
if (versions.size > 0) {
|
|
134
|
+
await em.nativeDelete(entity.preSync.entityClass, {
|
|
135
|
+
id: { $in: [...versions.keys()] },
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
async waitReady(path, serviceName) {
|
|
140
|
+
const healthUrl = new URL(path, this.config.apiGatewayUrl);
|
|
141
|
+
for (let i = 0; i < 12; ++i) {
|
|
142
|
+
try {
|
|
143
|
+
const response = await fetch(healthUrl);
|
|
144
|
+
if (response.ok) {
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
this.config.logger.info("Unable to verify health, backing off");
|
|
150
|
+
await new Promise((resolve) => setTimeout(resolve, 5000));
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
throw new Error(`Service "${serviceName}" didn't turn ready within 60 seconds`);
|
|
154
|
+
}
|
|
155
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@furvester/upstream-sync",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Sync from upstream via RabbitMQ",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"author": "Ben Scholzen 'DASPRiD'",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/furvester/upstream-sync.git"
|
|
11
|
+
},
|
|
12
|
+
"publishConfig": {
|
|
13
|
+
"access": "public"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist/**/*"
|
|
17
|
+
],
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"import": {
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"default": "./dist/index.js"
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"module": "./dist/index.js",
|
|
28
|
+
"scripts": {
|
|
29
|
+
"build": "tsc",
|
|
30
|
+
"coverage": "vitest run --coverage",
|
|
31
|
+
"format": "biome format . --write",
|
|
32
|
+
"check": "biome check . --apply"
|
|
33
|
+
},
|
|
34
|
+
"devDependencies": {
|
|
35
|
+
"@biomejs/biome": "1.7.1",
|
|
36
|
+
"@commitlint/cli": "^19.3.0",
|
|
37
|
+
"@commitlint/config-conventional": "^19.2.2",
|
|
38
|
+
"@mikro-orm/postgresql": "^6.3.13",
|
|
39
|
+
"@tsconfig/node20": "^20.1.4",
|
|
40
|
+
"@types/node": "^20.12.7",
|
|
41
|
+
"jsonapi-zod-query": "^2.1.1",
|
|
42
|
+
"lefthook": "^1.6.10",
|
|
43
|
+
"logforth": "^1.2.2",
|
|
44
|
+
"rabbitmq-client": "^5.0.0",
|
|
45
|
+
"typescript": "^5.4.5",
|
|
46
|
+
"zod": "^3.23.4"
|
|
47
|
+
},
|
|
48
|
+
"peerDependencies": {
|
|
49
|
+
"@mikro-orm/postgresql": "^6.3.13",
|
|
50
|
+
"jsonapi-zod-query": "^2.1.1",
|
|
51
|
+
"logforth": "^1.2.2",
|
|
52
|
+
"rabbitmq-client": "^5.0.0",
|
|
53
|
+
"zod": "^3.22.4"
|
|
54
|
+
},
|
|
55
|
+
"packageManager": "pnpm@9.9.0+sha512.60c18acd138bff695d339be6ad13f7e936eea6745660d4cc4a776d5247c540d0edee1a563695c183a66eb917ef88f2b4feb1fc25f32a7adcadc7aaf3438e99c1",
|
|
56
|
+
"dependencies": {
|
|
57
|
+
"async-mutex": "^0.5.0"
|
|
58
|
+
}
|
|
59
|
+
}
|