s3db.js 7.2.0 → 7.3.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/PLUGINS.md +200 -10
- package/dist/s3db.cjs.js +149 -1458
- package/dist/s3db.cjs.min.js +1 -1
- package/dist/s3db.d.ts +14 -15
- package/dist/s3db.es.js +150 -1459
- package/dist/s3db.es.min.js +1 -1
- package/dist/s3db.iife.js +149 -1458
- package/dist/s3db.iife.min.js +1 -1
- package/package.json +19 -8
- package/src/behaviors/body-only.js +2 -2
- package/src/behaviors/truncate-data.js +2 -2
- package/src/client.class.js +1 -1
- package/src/database.class.js +1 -1
- package/src/errors.js +1 -1
- package/src/plugins/audit.plugin.js +5 -5
- package/src/plugins/cache/filesystem-cache.class.js +661 -0
- package/src/plugins/cache/index.js +4 -0
- package/src/plugins/cache/partition-aware-filesystem-cache.class.js +480 -0
- package/src/plugins/cache.plugin.js +159 -9
- package/src/plugins/consumers/index.js +3 -3
- package/src/plugins/consumers/sqs-consumer.js +2 -2
- package/src/plugins/fulltext.plugin.js +5 -5
- package/src/plugins/metrics.plugin.js +2 -2
- package/src/plugins/queue-consumer.plugin.js +3 -3
- package/src/plugins/replicator.plugin.js +259 -362
- package/src/plugins/replicators/bigquery-replicator.class.js +102 -68
- package/src/plugins/replicators/postgres-replicator.class.js +19 -109
- package/src/plugins/replicators/s3db-replicator.class.js +56 -68
- package/src/plugins/replicators/sqs-replicator.class.js +34 -121
- package/src/resource.class.js +14 -14
- package/src/s3db.d.ts +14 -15
- package/src/schema.class.js +3 -3
package/dist/s3db.cjs.js
CHANGED
|
@@ -7917,583 +7917,6 @@ class MetricsPlugin extends plugin_class_default {
|
|
|
7917
7917
|
}
|
|
7918
7918
|
}
|
|
7919
7919
|
|
|
7920
|
-
class BaseReplicator extends EventEmitter {
|
|
7921
|
-
constructor(config = {}) {
|
|
7922
|
-
super();
|
|
7923
|
-
this.config = config;
|
|
7924
|
-
this.name = this.constructor.name;
|
|
7925
|
-
this.enabled = config.enabled !== false;
|
|
7926
|
-
}
|
|
7927
|
-
/**
|
|
7928
|
-
* Initialize the replicator
|
|
7929
|
-
* @param {Object} database - The s3db database instance
|
|
7930
|
-
* @returns {Promise<void>}
|
|
7931
|
-
*/
|
|
7932
|
-
async initialize(database) {
|
|
7933
|
-
this.database = database;
|
|
7934
|
-
this.emit("initialized", { replicator: this.name });
|
|
7935
|
-
}
|
|
7936
|
-
/**
|
|
7937
|
-
* Replicate data to the target
|
|
7938
|
-
* @param {string} resourceName - Name of the resource being replicated
|
|
7939
|
-
* @param {string} operation - Operation type (insert, update, delete)
|
|
7940
|
-
* @param {Object} data - The data to replicate
|
|
7941
|
-
* @param {string} id - Record ID
|
|
7942
|
-
* @returns {Promise<Object>} replicator result
|
|
7943
|
-
*/
|
|
7944
|
-
async replicate(resourceName, operation, data, id) {
|
|
7945
|
-
throw new Error(`replicate() method must be implemented by ${this.name}`);
|
|
7946
|
-
}
|
|
7947
|
-
/**
|
|
7948
|
-
* Replicate multiple records in batch
|
|
7949
|
-
* @param {string} resourceName - Name of the resource being replicated
|
|
7950
|
-
* @param {Array} records - Array of records to replicate
|
|
7951
|
-
* @returns {Promise<Object>} Batch replicator result
|
|
7952
|
-
*/
|
|
7953
|
-
async replicateBatch(resourceName, records) {
|
|
7954
|
-
throw new Error(`replicateBatch() method must be implemented by ${this.name}`);
|
|
7955
|
-
}
|
|
7956
|
-
/**
|
|
7957
|
-
* Test the connection to the target
|
|
7958
|
-
* @returns {Promise<boolean>} True if connection is successful
|
|
7959
|
-
*/
|
|
7960
|
-
async testConnection() {
|
|
7961
|
-
throw new Error(`testConnection() method must be implemented by ${this.name}`);
|
|
7962
|
-
}
|
|
7963
|
-
/**
|
|
7964
|
-
* Get replicator status and statistics
|
|
7965
|
-
* @returns {Promise<Object>} Status information
|
|
7966
|
-
*/
|
|
7967
|
-
async getStatus() {
|
|
7968
|
-
return {
|
|
7969
|
-
name: this.name,
|
|
7970
|
-
// Removed: enabled: this.enabled,
|
|
7971
|
-
config: this.config,
|
|
7972
|
-
connected: false
|
|
7973
|
-
};
|
|
7974
|
-
}
|
|
7975
|
-
/**
|
|
7976
|
-
* Cleanup resources
|
|
7977
|
-
* @returns {Promise<void>}
|
|
7978
|
-
*/
|
|
7979
|
-
async cleanup() {
|
|
7980
|
-
this.emit("cleanup", { replicator: this.name });
|
|
7981
|
-
}
|
|
7982
|
-
/**
|
|
7983
|
-
* Validate replicator configuration
|
|
7984
|
-
* @returns {Object} Validation result
|
|
7985
|
-
*/
|
|
7986
|
-
validateConfig() {
|
|
7987
|
-
return { isValid: true, errors: [] };
|
|
7988
|
-
}
|
|
7989
|
-
}
|
|
7990
|
-
var base_replicator_class_default = BaseReplicator;
|
|
7991
|
-
|
|
7992
|
-
class BigqueryReplicator extends base_replicator_class_default {
|
|
7993
|
-
constructor(config = {}, resources = {}) {
|
|
7994
|
-
super(config);
|
|
7995
|
-
this.projectId = config.projectId;
|
|
7996
|
-
this.datasetId = config.datasetId;
|
|
7997
|
-
this.bigqueryClient = null;
|
|
7998
|
-
this.credentials = config.credentials;
|
|
7999
|
-
this.location = config.location || "US";
|
|
8000
|
-
this.logTable = config.logTable;
|
|
8001
|
-
this.resources = this.parseResourcesConfig(resources);
|
|
8002
|
-
}
|
|
8003
|
-
parseResourcesConfig(resources) {
|
|
8004
|
-
const parsed = {};
|
|
8005
|
-
for (const [resourceName, config] of Object.entries(resources)) {
|
|
8006
|
-
if (typeof config === "string") {
|
|
8007
|
-
parsed[resourceName] = [{
|
|
8008
|
-
table: config,
|
|
8009
|
-
actions: ["insert"]
|
|
8010
|
-
}];
|
|
8011
|
-
} else if (Array.isArray(config)) {
|
|
8012
|
-
parsed[resourceName] = config.map((item) => {
|
|
8013
|
-
if (typeof item === "string") {
|
|
8014
|
-
return { table: item, actions: ["insert"] };
|
|
8015
|
-
}
|
|
8016
|
-
return {
|
|
8017
|
-
table: item.table,
|
|
8018
|
-
actions: item.actions || ["insert"]
|
|
8019
|
-
};
|
|
8020
|
-
});
|
|
8021
|
-
} else if (typeof config === "object") {
|
|
8022
|
-
parsed[resourceName] = [{
|
|
8023
|
-
table: config.table,
|
|
8024
|
-
actions: config.actions || ["insert"]
|
|
8025
|
-
}];
|
|
8026
|
-
}
|
|
8027
|
-
}
|
|
8028
|
-
return parsed;
|
|
8029
|
-
}
|
|
8030
|
-
validateConfig() {
|
|
8031
|
-
const errors = [];
|
|
8032
|
-
if (!this.projectId) errors.push("projectId is required");
|
|
8033
|
-
if (!this.datasetId) errors.push("datasetId is required");
|
|
8034
|
-
if (Object.keys(this.resources).length === 0) errors.push("At least one resource must be configured");
|
|
8035
|
-
for (const [resourceName, tables] of Object.entries(this.resources)) {
|
|
8036
|
-
for (const tableConfig of tables) {
|
|
8037
|
-
if (!tableConfig.table) {
|
|
8038
|
-
errors.push(`Table name is required for resource '${resourceName}'`);
|
|
8039
|
-
}
|
|
8040
|
-
if (!Array.isArray(tableConfig.actions) || tableConfig.actions.length === 0) {
|
|
8041
|
-
errors.push(`Actions array is required for resource '${resourceName}'`);
|
|
8042
|
-
}
|
|
8043
|
-
const validActions = ["insert", "update", "delete"];
|
|
8044
|
-
const invalidActions = tableConfig.actions.filter((action) => !validActions.includes(action));
|
|
8045
|
-
if (invalidActions.length > 0) {
|
|
8046
|
-
errors.push(`Invalid actions for resource '${resourceName}': ${invalidActions.join(", ")}. Valid actions: ${validActions.join(", ")}`);
|
|
8047
|
-
}
|
|
8048
|
-
}
|
|
8049
|
-
}
|
|
8050
|
-
return { isValid: errors.length === 0, errors };
|
|
8051
|
-
}
|
|
8052
|
-
async initialize(database) {
|
|
8053
|
-
await super.initialize(database);
|
|
8054
|
-
const [ok, err, sdk] = await try_fn_default(() => import('@google-cloud/bigquery'));
|
|
8055
|
-
if (!ok) {
|
|
8056
|
-
this.emit("initialization_error", { replicator: this.name, error: err.message });
|
|
8057
|
-
throw err;
|
|
8058
|
-
}
|
|
8059
|
-
const { BigQuery } = sdk;
|
|
8060
|
-
this.bigqueryClient = new BigQuery({
|
|
8061
|
-
projectId: this.projectId,
|
|
8062
|
-
credentials: this.credentials,
|
|
8063
|
-
location: this.location
|
|
8064
|
-
});
|
|
8065
|
-
this.emit("initialized", {
|
|
8066
|
-
replicator: this.name,
|
|
8067
|
-
projectId: this.projectId,
|
|
8068
|
-
datasetId: this.datasetId,
|
|
8069
|
-
resources: Object.keys(this.resources)
|
|
8070
|
-
});
|
|
8071
|
-
}
|
|
8072
|
-
shouldReplicateResource(resourceName) {
|
|
8073
|
-
return this.resources.hasOwnProperty(resourceName);
|
|
8074
|
-
}
|
|
8075
|
-
shouldReplicateAction(resourceName, operation) {
|
|
8076
|
-
if (!this.resources[resourceName]) return false;
|
|
8077
|
-
return this.resources[resourceName].some(
|
|
8078
|
-
(tableConfig) => tableConfig.actions.includes(operation)
|
|
8079
|
-
);
|
|
8080
|
-
}
|
|
8081
|
-
getTablesForResource(resourceName, operation) {
|
|
8082
|
-
if (!this.resources[resourceName]) return [];
|
|
8083
|
-
return this.resources[resourceName].filter((tableConfig) => tableConfig.actions.includes(operation)).map((tableConfig) => tableConfig.table);
|
|
8084
|
-
}
|
|
8085
|
-
async replicate(resourceName, operation, data, id, beforeData = null) {
|
|
8086
|
-
if (!this.enabled || !this.shouldReplicateResource(resourceName)) {
|
|
8087
|
-
return { skipped: true, reason: "resource_not_included" };
|
|
8088
|
-
}
|
|
8089
|
-
if (!this.shouldReplicateAction(resourceName, operation)) {
|
|
8090
|
-
return { skipped: true, reason: "action_not_included" };
|
|
8091
|
-
}
|
|
8092
|
-
const tables = this.getTablesForResource(resourceName, operation);
|
|
8093
|
-
if (tables.length === 0) {
|
|
8094
|
-
return { skipped: true, reason: "no_tables_for_action" };
|
|
8095
|
-
}
|
|
8096
|
-
const results = [];
|
|
8097
|
-
const errors = [];
|
|
8098
|
-
const [ok, err, result] = await try_fn_default(async () => {
|
|
8099
|
-
const dataset = this.bigqueryClient.dataset(this.datasetId);
|
|
8100
|
-
for (const tableId of tables) {
|
|
8101
|
-
const [okTable, errTable] = await try_fn_default(async () => {
|
|
8102
|
-
const table = dataset.table(tableId);
|
|
8103
|
-
let job;
|
|
8104
|
-
if (operation === "insert") {
|
|
8105
|
-
const row = { ...data };
|
|
8106
|
-
job = await table.insert([row]);
|
|
8107
|
-
} else if (operation === "update") {
|
|
8108
|
-
const keys = Object.keys(data).filter((k) => k !== "id");
|
|
8109
|
-
const setClause = keys.map((k) => `${k}=@${k}`).join(", ");
|
|
8110
|
-
const params = { id };
|
|
8111
|
-
keys.forEach((k) => {
|
|
8112
|
-
params[k] = data[k];
|
|
8113
|
-
});
|
|
8114
|
-
const query = `UPDATE \`${this.projectId}.${this.datasetId}.${tableId}\` SET ${setClause} WHERE id=@id`;
|
|
8115
|
-
const [updateJob] = await this.bigqueryClient.createQueryJob({
|
|
8116
|
-
query,
|
|
8117
|
-
params
|
|
8118
|
-
});
|
|
8119
|
-
await updateJob.getQueryResults();
|
|
8120
|
-
job = [updateJob];
|
|
8121
|
-
} else if (operation === "delete") {
|
|
8122
|
-
const query = `DELETE FROM \`${this.projectId}.${this.datasetId}.${tableId}\` WHERE id=@id`;
|
|
8123
|
-
const [deleteJob] = await this.bigqueryClient.createQueryJob({
|
|
8124
|
-
query,
|
|
8125
|
-
params: { id }
|
|
8126
|
-
});
|
|
8127
|
-
await deleteJob.getQueryResults();
|
|
8128
|
-
job = [deleteJob];
|
|
8129
|
-
} else {
|
|
8130
|
-
throw new Error(`Unsupported operation: ${operation}`);
|
|
8131
|
-
}
|
|
8132
|
-
results.push({
|
|
8133
|
-
table: tableId,
|
|
8134
|
-
success: true,
|
|
8135
|
-
jobId: job[0]?.id
|
|
8136
|
-
});
|
|
8137
|
-
});
|
|
8138
|
-
if (!okTable) {
|
|
8139
|
-
errors.push({
|
|
8140
|
-
table: tableId,
|
|
8141
|
-
error: errTable.message
|
|
8142
|
-
});
|
|
8143
|
-
}
|
|
8144
|
-
}
|
|
8145
|
-
if (this.logTable) {
|
|
8146
|
-
const [okLog, errLog] = await try_fn_default(async () => {
|
|
8147
|
-
const logTable = dataset.table(this.logTable);
|
|
8148
|
-
await logTable.insert([{
|
|
8149
|
-
resource_name: resourceName,
|
|
8150
|
-
operation,
|
|
8151
|
-
record_id: id,
|
|
8152
|
-
data: JSON.stringify(data),
|
|
8153
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
8154
|
-
source: "s3db-replicator"
|
|
8155
|
-
}]);
|
|
8156
|
-
});
|
|
8157
|
-
if (!okLog) {
|
|
8158
|
-
}
|
|
8159
|
-
}
|
|
8160
|
-
const success = errors.length === 0;
|
|
8161
|
-
this.emit("replicated", {
|
|
8162
|
-
replicator: this.name,
|
|
8163
|
-
resourceName,
|
|
8164
|
-
operation,
|
|
8165
|
-
id,
|
|
8166
|
-
tables,
|
|
8167
|
-
results,
|
|
8168
|
-
errors,
|
|
8169
|
-
success
|
|
8170
|
-
});
|
|
8171
|
-
return {
|
|
8172
|
-
success,
|
|
8173
|
-
results,
|
|
8174
|
-
errors,
|
|
8175
|
-
tables
|
|
8176
|
-
};
|
|
8177
|
-
});
|
|
8178
|
-
if (ok) return result;
|
|
8179
|
-
this.emit("replicator_error", {
|
|
8180
|
-
replicator: this.name,
|
|
8181
|
-
resourceName,
|
|
8182
|
-
operation,
|
|
8183
|
-
id,
|
|
8184
|
-
error: err.message
|
|
8185
|
-
});
|
|
8186
|
-
return { success: false, error: err.message };
|
|
8187
|
-
}
|
|
8188
|
-
async replicateBatch(resourceName, records) {
|
|
8189
|
-
const results = [];
|
|
8190
|
-
const errors = [];
|
|
8191
|
-
for (const record of records) {
|
|
8192
|
-
const [ok, err, res] = await try_fn_default(() => this.replicate(
|
|
8193
|
-
resourceName,
|
|
8194
|
-
record.operation,
|
|
8195
|
-
record.data,
|
|
8196
|
-
record.id,
|
|
8197
|
-
record.beforeData
|
|
8198
|
-
));
|
|
8199
|
-
if (ok) results.push(res);
|
|
8200
|
-
else errors.push({ id: record.id, error: err.message });
|
|
8201
|
-
}
|
|
8202
|
-
return {
|
|
8203
|
-
success: errors.length === 0,
|
|
8204
|
-
results,
|
|
8205
|
-
errors
|
|
8206
|
-
};
|
|
8207
|
-
}
|
|
8208
|
-
async testConnection() {
|
|
8209
|
-
const [ok, err] = await try_fn_default(async () => {
|
|
8210
|
-
if (!this.bigqueryClient) await this.initialize();
|
|
8211
|
-
const dataset = this.bigqueryClient.dataset(this.datasetId);
|
|
8212
|
-
await dataset.getMetadata();
|
|
8213
|
-
return true;
|
|
8214
|
-
});
|
|
8215
|
-
if (ok) return true;
|
|
8216
|
-
this.emit("connection_error", { replicator: this.name, error: err.message });
|
|
8217
|
-
return false;
|
|
8218
|
-
}
|
|
8219
|
-
async cleanup() {
|
|
8220
|
-
}
|
|
8221
|
-
getStatus() {
|
|
8222
|
-
return {
|
|
8223
|
-
...super.getStatus(),
|
|
8224
|
-
projectId: this.projectId,
|
|
8225
|
-
datasetId: this.datasetId,
|
|
8226
|
-
resources: this.resources,
|
|
8227
|
-
logTable: this.logTable
|
|
8228
|
-
};
|
|
8229
|
-
}
|
|
8230
|
-
}
|
|
8231
|
-
var bigquery_replicator_class_default = BigqueryReplicator;
|
|
8232
|
-
|
|
8233
|
-
class PostgresReplicator extends base_replicator_class_default {
|
|
8234
|
-
constructor(config = {}, resources = {}) {
|
|
8235
|
-
super(config);
|
|
8236
|
-
this.connectionString = config.connectionString;
|
|
8237
|
-
this.host = config.host;
|
|
8238
|
-
this.port = config.port || 5432;
|
|
8239
|
-
this.database = config.database;
|
|
8240
|
-
this.user = config.user;
|
|
8241
|
-
this.password = config.password;
|
|
8242
|
-
this.client = null;
|
|
8243
|
-
this.ssl = config.ssl;
|
|
8244
|
-
this.logTable = config.logTable;
|
|
8245
|
-
this.resources = this.parseResourcesConfig(resources);
|
|
8246
|
-
}
|
|
8247
|
-
parseResourcesConfig(resources) {
|
|
8248
|
-
const parsed = {};
|
|
8249
|
-
for (const [resourceName, config] of Object.entries(resources)) {
|
|
8250
|
-
if (typeof config === "string") {
|
|
8251
|
-
parsed[resourceName] = [{
|
|
8252
|
-
table: config,
|
|
8253
|
-
actions: ["insert"]
|
|
8254
|
-
}];
|
|
8255
|
-
} else if (Array.isArray(config)) {
|
|
8256
|
-
parsed[resourceName] = config.map((item) => {
|
|
8257
|
-
if (typeof item === "string") {
|
|
8258
|
-
return { table: item, actions: ["insert"] };
|
|
8259
|
-
}
|
|
8260
|
-
return {
|
|
8261
|
-
table: item.table,
|
|
8262
|
-
actions: item.actions || ["insert"]
|
|
8263
|
-
};
|
|
8264
|
-
});
|
|
8265
|
-
} else if (typeof config === "object") {
|
|
8266
|
-
parsed[resourceName] = [{
|
|
8267
|
-
table: config.table,
|
|
8268
|
-
actions: config.actions || ["insert"]
|
|
8269
|
-
}];
|
|
8270
|
-
}
|
|
8271
|
-
}
|
|
8272
|
-
return parsed;
|
|
8273
|
-
}
|
|
8274
|
-
validateConfig() {
|
|
8275
|
-
const errors = [];
|
|
8276
|
-
if (!this.connectionString && (!this.host || !this.database)) {
|
|
8277
|
-
errors.push("Either connectionString or host+database must be provided");
|
|
8278
|
-
}
|
|
8279
|
-
if (Object.keys(this.resources).length === 0) {
|
|
8280
|
-
errors.push("At least one resource must be configured");
|
|
8281
|
-
}
|
|
8282
|
-
for (const [resourceName, tables] of Object.entries(this.resources)) {
|
|
8283
|
-
for (const tableConfig of tables) {
|
|
8284
|
-
if (!tableConfig.table) {
|
|
8285
|
-
errors.push(`Table name is required for resource '${resourceName}'`);
|
|
8286
|
-
}
|
|
8287
|
-
if (!Array.isArray(tableConfig.actions) || tableConfig.actions.length === 0) {
|
|
8288
|
-
errors.push(`Actions array is required for resource '${resourceName}'`);
|
|
8289
|
-
}
|
|
8290
|
-
const validActions = ["insert", "update", "delete"];
|
|
8291
|
-
const invalidActions = tableConfig.actions.filter((action) => !validActions.includes(action));
|
|
8292
|
-
if (invalidActions.length > 0) {
|
|
8293
|
-
errors.push(`Invalid actions for resource '${resourceName}': ${invalidActions.join(", ")}. Valid actions: ${validActions.join(", ")}`);
|
|
8294
|
-
}
|
|
8295
|
-
}
|
|
8296
|
-
}
|
|
8297
|
-
return { isValid: errors.length === 0, errors };
|
|
8298
|
-
}
|
|
8299
|
-
async initialize(database) {
|
|
8300
|
-
await super.initialize(database);
|
|
8301
|
-
const [ok, err, sdk] = await try_fn_default(() => import('pg'));
|
|
8302
|
-
if (!ok) {
|
|
8303
|
-
this.emit("initialization_error", {
|
|
8304
|
-
replicator: this.name,
|
|
8305
|
-
error: err.message
|
|
8306
|
-
});
|
|
8307
|
-
throw err;
|
|
8308
|
-
}
|
|
8309
|
-
const { Client } = sdk;
|
|
8310
|
-
const config = this.connectionString ? {
|
|
8311
|
-
connectionString: this.connectionString,
|
|
8312
|
-
ssl: this.ssl
|
|
8313
|
-
} : {
|
|
8314
|
-
host: this.host,
|
|
8315
|
-
port: this.port,
|
|
8316
|
-
database: this.database,
|
|
8317
|
-
user: this.user,
|
|
8318
|
-
password: this.password,
|
|
8319
|
-
ssl: this.ssl
|
|
8320
|
-
};
|
|
8321
|
-
this.client = new Client(config);
|
|
8322
|
-
await this.client.connect();
|
|
8323
|
-
if (this.logTable) {
|
|
8324
|
-
await this.createLogTableIfNotExists();
|
|
8325
|
-
}
|
|
8326
|
-
this.emit("initialized", {
|
|
8327
|
-
replicator: this.name,
|
|
8328
|
-
database: this.database || "postgres",
|
|
8329
|
-
resources: Object.keys(this.resources)
|
|
8330
|
-
});
|
|
8331
|
-
}
|
|
8332
|
-
async createLogTableIfNotExists() {
|
|
8333
|
-
const createTableQuery = `
|
|
8334
|
-
CREATE TABLE IF NOT EXISTS ${this.logTable} (
|
|
8335
|
-
id SERIAL PRIMARY KEY,
|
|
8336
|
-
resource_name VARCHAR(255) NOT NULL,
|
|
8337
|
-
operation VARCHAR(50) NOT NULL,
|
|
8338
|
-
record_id VARCHAR(255) NOT NULL,
|
|
8339
|
-
data JSONB,
|
|
8340
|
-
timestamp TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
|
8341
|
-
source VARCHAR(100) DEFAULT 's3db-replicator',
|
|
8342
|
-
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
|
8343
|
-
);
|
|
8344
|
-
CREATE INDEX IF NOT EXISTS idx_${this.logTable}_resource_name ON ${this.logTable}(resource_name);
|
|
8345
|
-
CREATE INDEX IF NOT EXISTS idx_${this.logTable}_operation ON ${this.logTable}(operation);
|
|
8346
|
-
CREATE INDEX IF NOT EXISTS idx_${this.logTable}_record_id ON ${this.logTable}(record_id);
|
|
8347
|
-
CREATE INDEX IF NOT EXISTS idx_${this.logTable}_timestamp ON ${this.logTable}(timestamp);
|
|
8348
|
-
`;
|
|
8349
|
-
await this.client.query(createTableQuery);
|
|
8350
|
-
}
|
|
8351
|
-
shouldReplicateResource(resourceName) {
|
|
8352
|
-
return this.resources.hasOwnProperty(resourceName);
|
|
8353
|
-
}
|
|
8354
|
-
shouldReplicateAction(resourceName, operation) {
|
|
8355
|
-
if (!this.resources[resourceName]) return false;
|
|
8356
|
-
return this.resources[resourceName].some(
|
|
8357
|
-
(tableConfig) => tableConfig.actions.includes(operation)
|
|
8358
|
-
);
|
|
8359
|
-
}
|
|
8360
|
-
getTablesForResource(resourceName, operation) {
|
|
8361
|
-
if (!this.resources[resourceName]) return [];
|
|
8362
|
-
return this.resources[resourceName].filter((tableConfig) => tableConfig.actions.includes(operation)).map((tableConfig) => tableConfig.table);
|
|
8363
|
-
}
|
|
8364
|
-
async replicate(resourceName, operation, data, id, beforeData = null) {
|
|
8365
|
-
if (!this.enabled || !this.shouldReplicateResource(resourceName)) {
|
|
8366
|
-
return { skipped: true, reason: "resource_not_included" };
|
|
8367
|
-
}
|
|
8368
|
-
if (!this.shouldReplicateAction(resourceName, operation)) {
|
|
8369
|
-
return { skipped: true, reason: "action_not_included" };
|
|
8370
|
-
}
|
|
8371
|
-
const tables = this.getTablesForResource(resourceName, operation);
|
|
8372
|
-
if (tables.length === 0) {
|
|
8373
|
-
return { skipped: true, reason: "no_tables_for_action" };
|
|
8374
|
-
}
|
|
8375
|
-
const results = [];
|
|
8376
|
-
const errors = [];
|
|
8377
|
-
const [ok, err, result] = await try_fn_default(async () => {
|
|
8378
|
-
for (const table of tables) {
|
|
8379
|
-
const [okTable, errTable] = await try_fn_default(async () => {
|
|
8380
|
-
let result2;
|
|
8381
|
-
if (operation === "insert") {
|
|
8382
|
-
const keys = Object.keys(data);
|
|
8383
|
-
const values = keys.map((k) => data[k]);
|
|
8384
|
-
const columns = keys.map((k) => `"${k}"`).join(", ");
|
|
8385
|
-
const params = keys.map((_, i) => `$${i + 1}`).join(", ");
|
|
8386
|
-
const sql = `INSERT INTO ${table} (${columns}) VALUES (${params}) ON CONFLICT (id) DO NOTHING RETURNING *`;
|
|
8387
|
-
result2 = await this.client.query(sql, values);
|
|
8388
|
-
} else if (operation === "update") {
|
|
8389
|
-
const keys = Object.keys(data).filter((k) => k !== "id");
|
|
8390
|
-
const setClause = keys.map((k, i) => `"${k}"=$${i + 1}`).join(", ");
|
|
8391
|
-
const values = keys.map((k) => data[k]);
|
|
8392
|
-
values.push(id);
|
|
8393
|
-
const sql = `UPDATE ${table} SET ${setClause} WHERE id=$${keys.length + 1} RETURNING *`;
|
|
8394
|
-
result2 = await this.client.query(sql, values);
|
|
8395
|
-
} else if (operation === "delete") {
|
|
8396
|
-
const sql = `DELETE FROM ${table} WHERE id=$1 RETURNING *`;
|
|
8397
|
-
result2 = await this.client.query(sql, [id]);
|
|
8398
|
-
} else {
|
|
8399
|
-
throw new Error(`Unsupported operation: ${operation}`);
|
|
8400
|
-
}
|
|
8401
|
-
results.push({
|
|
8402
|
-
table,
|
|
8403
|
-
success: true,
|
|
8404
|
-
rows: result2.rows,
|
|
8405
|
-
rowCount: result2.rowCount
|
|
8406
|
-
});
|
|
8407
|
-
});
|
|
8408
|
-
if (!okTable) {
|
|
8409
|
-
errors.push({
|
|
8410
|
-
table,
|
|
8411
|
-
error: errTable.message
|
|
8412
|
-
});
|
|
8413
|
-
}
|
|
8414
|
-
}
|
|
8415
|
-
if (this.logTable) {
|
|
8416
|
-
const [okLog, errLog] = await try_fn_default(async () => {
|
|
8417
|
-
await this.client.query(
|
|
8418
|
-
`INSERT INTO ${this.logTable} (resource_name, operation, record_id, data, timestamp, source) VALUES ($1, $2, $3, $4, $5, $6)`,
|
|
8419
|
-
[resourceName, operation, id, JSON.stringify(data), (/* @__PURE__ */ new Date()).toISOString(), "s3db-replicator"]
|
|
8420
|
-
);
|
|
8421
|
-
});
|
|
8422
|
-
if (!okLog) {
|
|
8423
|
-
}
|
|
8424
|
-
}
|
|
8425
|
-
const success = errors.length === 0;
|
|
8426
|
-
this.emit("replicated", {
|
|
8427
|
-
replicator: this.name,
|
|
8428
|
-
resourceName,
|
|
8429
|
-
operation,
|
|
8430
|
-
id,
|
|
8431
|
-
tables,
|
|
8432
|
-
results,
|
|
8433
|
-
errors,
|
|
8434
|
-
success
|
|
8435
|
-
});
|
|
8436
|
-
return {
|
|
8437
|
-
success,
|
|
8438
|
-
results,
|
|
8439
|
-
errors,
|
|
8440
|
-
tables
|
|
8441
|
-
};
|
|
8442
|
-
});
|
|
8443
|
-
if (ok) return result;
|
|
8444
|
-
this.emit("replicator_error", {
|
|
8445
|
-
replicator: this.name,
|
|
8446
|
-
resourceName,
|
|
8447
|
-
operation,
|
|
8448
|
-
id,
|
|
8449
|
-
error: err.message
|
|
8450
|
-
});
|
|
8451
|
-
return { success: false, error: err.message };
|
|
8452
|
-
}
|
|
8453
|
-
async replicateBatch(resourceName, records) {
|
|
8454
|
-
const results = [];
|
|
8455
|
-
const errors = [];
|
|
8456
|
-
for (const record of records) {
|
|
8457
|
-
const [ok, err, res] = await try_fn_default(() => this.replicate(
|
|
8458
|
-
resourceName,
|
|
8459
|
-
record.operation,
|
|
8460
|
-
record.data,
|
|
8461
|
-
record.id,
|
|
8462
|
-
record.beforeData
|
|
8463
|
-
));
|
|
8464
|
-
if (ok) results.push(res);
|
|
8465
|
-
else errors.push({ id: record.id, error: err.message });
|
|
8466
|
-
}
|
|
8467
|
-
return {
|
|
8468
|
-
success: errors.length === 0,
|
|
8469
|
-
results,
|
|
8470
|
-
errors
|
|
8471
|
-
};
|
|
8472
|
-
}
|
|
8473
|
-
async testConnection() {
|
|
8474
|
-
const [ok, err] = await try_fn_default(async () => {
|
|
8475
|
-
if (!this.client) await this.initialize();
|
|
8476
|
-
await this.client.query("SELECT 1");
|
|
8477
|
-
return true;
|
|
8478
|
-
});
|
|
8479
|
-
if (ok) return true;
|
|
8480
|
-
this.emit("connection_error", { replicator: this.name, error: err.message });
|
|
8481
|
-
return false;
|
|
8482
|
-
}
|
|
8483
|
-
async cleanup() {
|
|
8484
|
-
if (this.client) await this.client.end();
|
|
8485
|
-
}
|
|
8486
|
-
getStatus() {
|
|
8487
|
-
return {
|
|
8488
|
-
...super.getStatus(),
|
|
8489
|
-
database: this.database || "postgres",
|
|
8490
|
-
resources: this.resources,
|
|
8491
|
-
logTable: this.logTable
|
|
8492
|
-
};
|
|
8493
|
-
}
|
|
8494
|
-
}
|
|
8495
|
-
var postgres_replicator_class_default = PostgresReplicator;
|
|
8496
|
-
|
|
8497
7920
|
const S3_DEFAULT_REGION = "us-east-1";
|
|
8498
7921
|
const S3_DEFAULT_ENDPOINT = "https://s3.us-east-1.amazonaws.com";
|
|
8499
7922
|
class ConnectionString {
|
|
@@ -12211,7 +11634,7 @@ class Database extends EventEmitter {
|
|
|
12211
11634
|
super();
|
|
12212
11635
|
this.version = "1";
|
|
12213
11636
|
this.s3dbVersion = (() => {
|
|
12214
|
-
const [ok, err, version] = try_fn_default(() => true ? "7.2.
|
|
11637
|
+
const [ok, err, version] = try_fn_default(() => true ? "7.2.1" : "latest");
|
|
12215
11638
|
return ok ? version : "latest";
|
|
12216
11639
|
})();
|
|
12217
11640
|
this.resources = {};
|
|
@@ -12686,580 +12109,34 @@ class Database extends EventEmitter {
|
|
|
12686
12109
|
class S3db extends Database {
|
|
12687
12110
|
}
|
|
12688
12111
|
|
|
12689
|
-
function normalizeResourceName$1(name) {
|
|
12690
|
-
return typeof name === "string" ? name.trim().toLowerCase() : name;
|
|
12691
|
-
}
|
|
12692
|
-
class S3dbReplicator extends base_replicator_class_default {
|
|
12693
|
-
constructor(config = {}, resources = [], client = null) {
|
|
12694
|
-
super(config);
|
|
12695
|
-
this.instanceId = Math.random().toString(36).slice(2, 10);
|
|
12696
|
-
this.client = client;
|
|
12697
|
-
this.connectionString = config.connectionString;
|
|
12698
|
-
let normalizedResources = resources;
|
|
12699
|
-
if (!resources) normalizedResources = {};
|
|
12700
|
-
else if (Array.isArray(resources)) {
|
|
12701
|
-
normalizedResources = {};
|
|
12702
|
-
for (const res of resources) {
|
|
12703
|
-
if (typeof res === "string") normalizedResources[normalizeResourceName$1(res)] = res;
|
|
12704
|
-
}
|
|
12705
|
-
} else if (typeof resources === "string") {
|
|
12706
|
-
normalizedResources[normalizeResourceName$1(resources)] = resources;
|
|
12707
|
-
}
|
|
12708
|
-
this.resourcesMap = this._normalizeResources(normalizedResources);
|
|
12709
|
-
}
|
|
12710
|
-
_normalizeResources(resources) {
|
|
12711
|
-
if (!resources) return {};
|
|
12712
|
-
if (Array.isArray(resources)) {
|
|
12713
|
-
const map = {};
|
|
12714
|
-
for (const res of resources) {
|
|
12715
|
-
if (typeof res === "string") map[normalizeResourceName$1(res)] = res;
|
|
12716
|
-
else if (Array.isArray(res) && typeof res[0] === "string") map[normalizeResourceName$1(res[0])] = res;
|
|
12717
|
-
else if (typeof res === "object" && res.resource) {
|
|
12718
|
-
map[normalizeResourceName$1(res.resource)] = { ...res };
|
|
12719
|
-
}
|
|
12720
|
-
}
|
|
12721
|
-
return map;
|
|
12722
|
-
}
|
|
12723
|
-
if (typeof resources === "object") {
|
|
12724
|
-
const map = {};
|
|
12725
|
-
for (const [src, dest] of Object.entries(resources)) {
|
|
12726
|
-
const normSrc = normalizeResourceName$1(src);
|
|
12727
|
-
if (typeof dest === "string") map[normSrc] = dest;
|
|
12728
|
-
else if (Array.isArray(dest)) {
|
|
12729
|
-
map[normSrc] = dest.map((item) => {
|
|
12730
|
-
if (typeof item === "string") return item;
|
|
12731
|
-
if (typeof item === "function") return item;
|
|
12732
|
-
if (typeof item === "object" && item.resource) {
|
|
12733
|
-
return { ...item };
|
|
12734
|
-
}
|
|
12735
|
-
return item;
|
|
12736
|
-
});
|
|
12737
|
-
} else if (typeof dest === "function") map[normSrc] = dest;
|
|
12738
|
-
else if (typeof dest === "object" && dest.resource) {
|
|
12739
|
-
map[normSrc] = { ...dest };
|
|
12740
|
-
}
|
|
12741
|
-
}
|
|
12742
|
-
return map;
|
|
12743
|
-
}
|
|
12744
|
-
if (typeof resources === "function") {
|
|
12745
|
-
return resources;
|
|
12746
|
-
}
|
|
12747
|
-
if (typeof resources === "string") {
|
|
12748
|
-
const map = { [normalizeResourceName$1(resources)]: resources };
|
|
12749
|
-
return map;
|
|
12750
|
-
}
|
|
12751
|
-
return {};
|
|
12752
|
-
}
|
|
12753
|
-
validateConfig() {
|
|
12754
|
-
const errors = [];
|
|
12755
|
-
if (!this.client && !this.connectionString) {
|
|
12756
|
-
errors.push("You must provide a client or a connectionString");
|
|
12757
|
-
}
|
|
12758
|
-
if (!this.resourcesMap || typeof this.resourcesMap === "object" && Object.keys(this.resourcesMap).length === 0) {
|
|
12759
|
-
errors.push("You must provide a resources map or array");
|
|
12760
|
-
}
|
|
12761
|
-
return { isValid: errors.length === 0, errors };
|
|
12762
|
-
}
|
|
12763
|
-
async initialize(database) {
|
|
12764
|
-
try {
|
|
12765
|
-
await super.initialize(database);
|
|
12766
|
-
if (this.client) {
|
|
12767
|
-
this.targetDatabase = this.client;
|
|
12768
|
-
} else if (this.connectionString) {
|
|
12769
|
-
const targetConfig = {
|
|
12770
|
-
connectionString: this.connectionString,
|
|
12771
|
-
region: this.region,
|
|
12772
|
-
keyPrefix: this.keyPrefix,
|
|
12773
|
-
verbose: this.config.verbose || false
|
|
12774
|
-
};
|
|
12775
|
-
this.targetDatabase = new S3db(targetConfig);
|
|
12776
|
-
await this.targetDatabase.connect();
|
|
12777
|
-
} else {
|
|
12778
|
-
throw new Error("S3dbReplicator: No client or connectionString provided");
|
|
12779
|
-
}
|
|
12780
|
-
this.emit("connected", {
|
|
12781
|
-
replicator: this.name,
|
|
12782
|
-
target: this.connectionString || "client-provided"
|
|
12783
|
-
});
|
|
12784
|
-
} catch (err) {
|
|
12785
|
-
throw err;
|
|
12786
|
-
}
|
|
12787
|
-
}
|
|
12788
|
-
// Change signature to accept id
|
|
12789
|
-
async replicate({ resource, operation, data, id: explicitId }) {
|
|
12790
|
-
const normResource = normalizeResourceName$1(resource);
|
|
12791
|
-
const destResource = this._resolveDestResource(normResource, data);
|
|
12792
|
-
const destResourceObj = this._getDestResourceObj(destResource);
|
|
12793
|
-
const transformedData = this._applyTransformer(normResource, data);
|
|
12794
|
-
let result;
|
|
12795
|
-
if (operation === "insert") {
|
|
12796
|
-
result = await destResourceObj.insert(transformedData);
|
|
12797
|
-
} else if (operation === "update") {
|
|
12798
|
-
result = await destResourceObj.update(explicitId, transformedData);
|
|
12799
|
-
} else if (operation === "delete") {
|
|
12800
|
-
result = await destResourceObj.delete(explicitId);
|
|
12801
|
-
} else {
|
|
12802
|
-
throw new Error(`Invalid operation: ${operation}. Supported operations are: insert, update, delete`);
|
|
12803
|
-
}
|
|
12804
|
-
return result;
|
|
12805
|
-
}
|
|
12806
|
-
_applyTransformer(resource, data) {
|
|
12807
|
-
const normResource = normalizeResourceName$1(resource);
|
|
12808
|
-
const entry = this.resourcesMap[normResource];
|
|
12809
|
-
let result;
|
|
12810
|
-
if (!entry) return data;
|
|
12811
|
-
if (Array.isArray(entry) && typeof entry[1] === "function") {
|
|
12812
|
-
result = entry[1](data);
|
|
12813
|
-
} else if (typeof entry === "function") {
|
|
12814
|
-
result = entry(data);
|
|
12815
|
-
} else if (typeof entry === "object") {
|
|
12816
|
-
if (typeof entry.transform === "function") result = entry.transform(data);
|
|
12817
|
-
else if (typeof entry.transformer === "function") result = entry.transformer(data);
|
|
12818
|
-
} else {
|
|
12819
|
-
result = data;
|
|
12820
|
-
}
|
|
12821
|
-
if (result && data && data.id && !result.id) result.id = data.id;
|
|
12822
|
-
if (!result && data) result = data;
|
|
12823
|
-
return result;
|
|
12824
|
-
}
|
|
12825
|
-
_resolveDestResource(resource, data) {
|
|
12826
|
-
const normResource = normalizeResourceName$1(resource);
|
|
12827
|
-
const entry = this.resourcesMap[normResource];
|
|
12828
|
-
if (!entry) return resource;
|
|
12829
|
-
if (Array.isArray(entry)) {
|
|
12830
|
-
if (typeof entry[0] === "string") return entry[0];
|
|
12831
|
-
if (typeof entry[0] === "object" && entry[0].resource) return entry[0].resource;
|
|
12832
|
-
if (typeof entry[0] === "function") return resource;
|
|
12833
|
-
}
|
|
12834
|
-
if (typeof entry === "string") return entry;
|
|
12835
|
-
if (typeof entry === "function") return resource;
|
|
12836
|
-
if (typeof entry === "object" && entry.resource) return entry.resource;
|
|
12837
|
-
return resource;
|
|
12838
|
-
}
|
|
12839
|
-
_getDestResourceObj(resource) {
|
|
12840
|
-
if (!this.client || !this.client.resources) return null;
|
|
12841
|
-
const available = Object.keys(this.client.resources);
|
|
12842
|
-
const norm = normalizeResourceName$1(resource);
|
|
12843
|
-
const found = available.find((r) => normalizeResourceName$1(r) === norm);
|
|
12844
|
-
if (!found) {
|
|
12845
|
-
throw new Error(`[S3dbReplicator] Destination resource not found: ${resource}. Available: ${available.join(", ")}`);
|
|
12846
|
-
}
|
|
12847
|
-
return this.client.resources[found];
|
|
12848
|
-
}
|
|
12849
|
-
async replicateBatch(resourceName, records) {
|
|
12850
|
-
if (!this.enabled || !this.shouldReplicateResource(resourceName)) {
|
|
12851
|
-
return { skipped: true, reason: "resource_not_included" };
|
|
12852
|
-
}
|
|
12853
|
-
const results = [];
|
|
12854
|
-
const errors = [];
|
|
12855
|
-
for (const record of records) {
|
|
12856
|
-
const [ok, err, result] = await try_fn_default(() => this.replicate({
|
|
12857
|
-
resource: resourceName,
|
|
12858
|
-
operation: record.operation,
|
|
12859
|
-
id: record.id,
|
|
12860
|
-
data: record.data,
|
|
12861
|
-
beforeData: record.beforeData
|
|
12862
|
-
}));
|
|
12863
|
-
if (ok) results.push(result);
|
|
12864
|
-
else errors.push({ id: record.id, error: err.message });
|
|
12865
|
-
}
|
|
12866
|
-
this.emit("batch_replicated", {
|
|
12867
|
-
replicator: this.name,
|
|
12868
|
-
resourceName,
|
|
12869
|
-
total: records.length,
|
|
12870
|
-
successful: results.length,
|
|
12871
|
-
errors: errors.length
|
|
12872
|
-
});
|
|
12873
|
-
return {
|
|
12874
|
-
success: errors.length === 0,
|
|
12875
|
-
results,
|
|
12876
|
-
errors,
|
|
12877
|
-
total: records.length
|
|
12878
|
-
};
|
|
12879
|
-
}
|
|
12880
|
-
async testConnection() {
|
|
12881
|
-
const [ok, err] = await try_fn_default(async () => {
|
|
12882
|
-
if (!this.targetDatabase) {
|
|
12883
|
-
await this.initialize(this.database);
|
|
12884
|
-
}
|
|
12885
|
-
await this.targetDatabase.listResources();
|
|
12886
|
-
return true;
|
|
12887
|
-
});
|
|
12888
|
-
if (ok) return true;
|
|
12889
|
-
this.emit("connection_error", {
|
|
12890
|
-
replicator: this.name,
|
|
12891
|
-
error: err.message
|
|
12892
|
-
});
|
|
12893
|
-
return false;
|
|
12894
|
-
}
|
|
12895
|
-
async getStatus() {
|
|
12896
|
-
const baseStatus = await super.getStatus();
|
|
12897
|
-
return {
|
|
12898
|
-
...baseStatus,
|
|
12899
|
-
connected: !!this.targetDatabase,
|
|
12900
|
-
targetDatabase: this.connectionString || "client-provided",
|
|
12901
|
-
resources: Object.keys(this.resourcesMap || {}),
|
|
12902
|
-
totalreplicators: this.listenerCount("replicated"),
|
|
12903
|
-
totalErrors: this.listenerCount("replicator_error")
|
|
12904
|
-
};
|
|
12905
|
-
}
|
|
12906
|
-
async cleanup() {
|
|
12907
|
-
if (this.targetDatabase) {
|
|
12908
|
-
this.targetDatabase.removeAllListeners();
|
|
12909
|
-
}
|
|
12910
|
-
await super.cleanup();
|
|
12911
|
-
}
|
|
12912
|
-
shouldReplicateResource(resource, action) {
|
|
12913
|
-
const normResource = normalizeResourceName$1(resource);
|
|
12914
|
-
const entry = this.resourcesMap[normResource];
|
|
12915
|
-
if (!entry) return false;
|
|
12916
|
-
if (!action) return true;
|
|
12917
|
-
if (Array.isArray(entry)) {
|
|
12918
|
-
for (const item of entry) {
|
|
12919
|
-
if (typeof item === "object" && item.resource) {
|
|
12920
|
-
if (item.actions && Array.isArray(item.actions)) {
|
|
12921
|
-
if (item.actions.includes(action)) return true;
|
|
12922
|
-
} else {
|
|
12923
|
-
return true;
|
|
12924
|
-
}
|
|
12925
|
-
} else if (typeof item === "string" || typeof item === "function") {
|
|
12926
|
-
return true;
|
|
12927
|
-
}
|
|
12928
|
-
}
|
|
12929
|
-
return false;
|
|
12930
|
-
}
|
|
12931
|
-
if (typeof entry === "object" && entry.resource) {
|
|
12932
|
-
if (entry.actions && Array.isArray(entry.actions)) {
|
|
12933
|
-
return entry.actions.includes(action);
|
|
12934
|
-
}
|
|
12935
|
-
return true;
|
|
12936
|
-
}
|
|
12937
|
-
if (typeof entry === "string" || typeof entry === "function") {
|
|
12938
|
-
return true;
|
|
12939
|
-
}
|
|
12940
|
-
return false;
|
|
12941
|
-
}
|
|
12942
|
-
}
|
|
12943
|
-
var s3db_replicator_class_default = S3dbReplicator;
|
|
12944
|
-
|
|
12945
|
-
class SqsReplicator extends base_replicator_class_default {
|
|
12946
|
-
constructor(config = {}, resources = [], client = null) {
|
|
12947
|
-
super(config);
|
|
12948
|
-
this.resources = resources;
|
|
12949
|
-
this.client = client;
|
|
12950
|
-
this.queueUrl = config.queueUrl;
|
|
12951
|
-
this.queues = config.queues || {};
|
|
12952
|
-
this.defaultQueue = config.defaultQueue || config.defaultQueueUrl || config.queueUrlDefault;
|
|
12953
|
-
this.region = config.region || "us-east-1";
|
|
12954
|
-
this.sqsClient = client || null;
|
|
12955
|
-
this.messageGroupId = config.messageGroupId;
|
|
12956
|
-
this.deduplicationId = config.deduplicationId;
|
|
12957
|
-
if (resources && typeof resources === "object") {
|
|
12958
|
-
for (const [resourceName, resourceConfig] of Object.entries(resources)) {
|
|
12959
|
-
if (resourceConfig.queueUrl) {
|
|
12960
|
-
this.queues[resourceName] = resourceConfig.queueUrl;
|
|
12961
|
-
}
|
|
12962
|
-
}
|
|
12963
|
-
}
|
|
12964
|
-
}
|
|
12965
|
-
validateConfig() {
|
|
12966
|
-
const errors = [];
|
|
12967
|
-
if (!this.queueUrl && Object.keys(this.queues).length === 0 && !this.defaultQueue && !this.resourceQueueMap) {
|
|
12968
|
-
errors.push("Either queueUrl, queues object, defaultQueue, or resourceQueueMap must be provided");
|
|
12969
|
-
}
|
|
12970
|
-
return {
|
|
12971
|
-
isValid: errors.length === 0,
|
|
12972
|
-
errors
|
|
12973
|
-
};
|
|
12974
|
-
}
|
|
12975
|
-
getQueueUrlsForResource(resource) {
|
|
12976
|
-
if (this.resourceQueueMap && this.resourceQueueMap[resource]) {
|
|
12977
|
-
return this.resourceQueueMap[resource];
|
|
12978
|
-
}
|
|
12979
|
-
if (this.queues[resource]) {
|
|
12980
|
-
return [this.queues[resource]];
|
|
12981
|
-
}
|
|
12982
|
-
if (this.queueUrl) {
|
|
12983
|
-
return [this.queueUrl];
|
|
12984
|
-
}
|
|
12985
|
-
if (this.defaultQueue) {
|
|
12986
|
-
return [this.defaultQueue];
|
|
12987
|
-
}
|
|
12988
|
-
throw new Error(`No queue URL found for resource '${resource}'`);
|
|
12989
|
-
}
|
|
12990
|
-
_applyTransformer(resource, data) {
|
|
12991
|
-
const entry = this.resources[resource];
|
|
12992
|
-
let result = data;
|
|
12993
|
-
if (!entry) return data;
|
|
12994
|
-
if (typeof entry.transform === "function") {
|
|
12995
|
-
result = entry.transform(data);
|
|
12996
|
-
} else if (typeof entry.transformer === "function") {
|
|
12997
|
-
result = entry.transformer(data);
|
|
12998
|
-
}
|
|
12999
|
-
return result || data;
|
|
13000
|
-
}
|
|
13001
|
-
/**
|
|
13002
|
-
* Create standardized message structure
|
|
13003
|
-
*/
|
|
13004
|
-
createMessage(resource, operation, data, id, beforeData = null) {
|
|
13005
|
-
const baseMessage = {
|
|
13006
|
-
resource,
|
|
13007
|
-
// padronizado para 'resource'
|
|
13008
|
-
action: operation,
|
|
13009
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
13010
|
-
source: "s3db-replicator"
|
|
13011
|
-
};
|
|
13012
|
-
switch (operation) {
|
|
13013
|
-
case "insert":
|
|
13014
|
-
return {
|
|
13015
|
-
...baseMessage,
|
|
13016
|
-
data
|
|
13017
|
-
};
|
|
13018
|
-
case "update":
|
|
13019
|
-
return {
|
|
13020
|
-
...baseMessage,
|
|
13021
|
-
before: beforeData,
|
|
13022
|
-
data
|
|
13023
|
-
};
|
|
13024
|
-
case "delete":
|
|
13025
|
-
return {
|
|
13026
|
-
...baseMessage,
|
|
13027
|
-
data
|
|
13028
|
-
};
|
|
13029
|
-
default:
|
|
13030
|
-
return {
|
|
13031
|
-
...baseMessage,
|
|
13032
|
-
data
|
|
13033
|
-
};
|
|
13034
|
-
}
|
|
13035
|
-
}
|
|
13036
|
-
async initialize(database, client) {
|
|
13037
|
-
await super.initialize(database);
|
|
13038
|
-
if (!this.sqsClient) {
|
|
13039
|
-
const [ok, err, sdk] = await try_fn_default(() => import('@aws-sdk/client-sqs'));
|
|
13040
|
-
if (!ok) {
|
|
13041
|
-
this.emit("initialization_error", {
|
|
13042
|
-
replicator: this.name,
|
|
13043
|
-
error: err.message
|
|
13044
|
-
});
|
|
13045
|
-
throw err;
|
|
13046
|
-
}
|
|
13047
|
-
const { SQSClient } = sdk;
|
|
13048
|
-
this.sqsClient = client || new SQSClient({
|
|
13049
|
-
region: this.region,
|
|
13050
|
-
credentials: this.config.credentials
|
|
13051
|
-
});
|
|
13052
|
-
this.emit("initialized", {
|
|
13053
|
-
replicator: this.name,
|
|
13054
|
-
queueUrl: this.queueUrl,
|
|
13055
|
-
queues: this.queues,
|
|
13056
|
-
defaultQueue: this.defaultQueue
|
|
13057
|
-
});
|
|
13058
|
-
}
|
|
13059
|
-
}
|
|
13060
|
-
async replicate(resource, operation, data, id, beforeData = null) {
|
|
13061
|
-
if (!this.enabled || !this.shouldReplicateResource(resource)) {
|
|
13062
|
-
return { skipped: true, reason: "resource_not_included" };
|
|
13063
|
-
}
|
|
13064
|
-
const [ok, err, result] = await try_fn_default(async () => {
|
|
13065
|
-
const { SendMessageCommand } = await import('@aws-sdk/client-sqs');
|
|
13066
|
-
const queueUrls = this.getQueueUrlsForResource(resource);
|
|
13067
|
-
const transformedData = this._applyTransformer(resource, data);
|
|
13068
|
-
const message = this.createMessage(resource, operation, transformedData, id, beforeData);
|
|
13069
|
-
const results = [];
|
|
13070
|
-
for (const queueUrl of queueUrls) {
|
|
13071
|
-
const command = new SendMessageCommand({
|
|
13072
|
-
QueueUrl: queueUrl,
|
|
13073
|
-
MessageBody: JSON.stringify(message),
|
|
13074
|
-
MessageGroupId: this.messageGroupId,
|
|
13075
|
-
MessageDeduplicationId: this.deduplicationId ? `${resource}:${operation}:${id}` : void 0
|
|
13076
|
-
});
|
|
13077
|
-
const result2 = await this.sqsClient.send(command);
|
|
13078
|
-
results.push({ queueUrl, messageId: result2.MessageId });
|
|
13079
|
-
this.emit("replicated", {
|
|
13080
|
-
replicator: this.name,
|
|
13081
|
-
resource,
|
|
13082
|
-
operation,
|
|
13083
|
-
id,
|
|
13084
|
-
queueUrl,
|
|
13085
|
-
messageId: result2.MessageId,
|
|
13086
|
-
success: true
|
|
13087
|
-
});
|
|
13088
|
-
}
|
|
13089
|
-
return { success: true, results };
|
|
13090
|
-
});
|
|
13091
|
-
if (ok) return result;
|
|
13092
|
-
this.emit("replicator_error", {
|
|
13093
|
-
replicator: this.name,
|
|
13094
|
-
resource,
|
|
13095
|
-
operation,
|
|
13096
|
-
id,
|
|
13097
|
-
error: err.message
|
|
13098
|
-
});
|
|
13099
|
-
return { success: false, error: err.message };
|
|
13100
|
-
}
|
|
13101
|
-
async replicateBatch(resource, records) {
|
|
13102
|
-
if (!this.enabled || !this.shouldReplicateResource(resource)) {
|
|
13103
|
-
return { skipped: true, reason: "resource_not_included" };
|
|
13104
|
-
}
|
|
13105
|
-
const [ok, err, result] = await try_fn_default(async () => {
|
|
13106
|
-
const { SendMessageBatchCommand } = await import('@aws-sdk/client-sqs');
|
|
13107
|
-
const queueUrls = this.getQueueUrlsForResource(resource);
|
|
13108
|
-
const batchSize = 10;
|
|
13109
|
-
const batches = [];
|
|
13110
|
-
for (let i = 0; i < records.length; i += batchSize) {
|
|
13111
|
-
batches.push(records.slice(i, i + batchSize));
|
|
13112
|
-
}
|
|
13113
|
-
const results = [];
|
|
13114
|
-
const errors = [];
|
|
13115
|
-
for (const batch of batches) {
|
|
13116
|
-
const [okBatch, errBatch] = await try_fn_default(async () => {
|
|
13117
|
-
const entries = batch.map((record, index) => ({
|
|
13118
|
-
Id: `${record.id}-${index}`,
|
|
13119
|
-
MessageBody: JSON.stringify(this.createMessage(
|
|
13120
|
-
resource,
|
|
13121
|
-
record.operation,
|
|
13122
|
-
record.data,
|
|
13123
|
-
record.id,
|
|
13124
|
-
record.beforeData
|
|
13125
|
-
)),
|
|
13126
|
-
MessageGroupId: this.messageGroupId,
|
|
13127
|
-
MessageDeduplicationId: this.deduplicationId ? `${resource}:${record.operation}:${record.id}` : void 0
|
|
13128
|
-
}));
|
|
13129
|
-
const command = new SendMessageBatchCommand({
|
|
13130
|
-
QueueUrl: queueUrls[0],
|
|
13131
|
-
// Assuming all queueUrls in a batch are the same for batching
|
|
13132
|
-
Entries: entries
|
|
13133
|
-
});
|
|
13134
|
-
const result2 = await this.sqsClient.send(command);
|
|
13135
|
-
results.push(result2);
|
|
13136
|
-
});
|
|
13137
|
-
if (!okBatch) {
|
|
13138
|
-
errors.push({ batch: batch.length, error: errBatch.message });
|
|
13139
|
-
if (errBatch.message && (errBatch.message.includes("Batch error") || errBatch.message.includes("Connection") || errBatch.message.includes("Network"))) {
|
|
13140
|
-
throw errBatch;
|
|
13141
|
-
}
|
|
13142
|
-
}
|
|
13143
|
-
}
|
|
13144
|
-
this.emit("batch_replicated", {
|
|
13145
|
-
replicator: this.name,
|
|
13146
|
-
resource,
|
|
13147
|
-
queueUrl: queueUrls[0],
|
|
13148
|
-
// Assuming all queueUrls in a batch are the same for batching
|
|
13149
|
-
total: records.length,
|
|
13150
|
-
successful: results.length,
|
|
13151
|
-
errors: errors.length
|
|
13152
|
-
});
|
|
13153
|
-
return {
|
|
13154
|
-
success: errors.length === 0,
|
|
13155
|
-
results,
|
|
13156
|
-
errors,
|
|
13157
|
-
total: records.length,
|
|
13158
|
-
queueUrl: queueUrls[0]
|
|
13159
|
-
// Assuming all queueUrls in a batch are the same for batching
|
|
13160
|
-
};
|
|
13161
|
-
});
|
|
13162
|
-
if (ok) return result;
|
|
13163
|
-
const errorMessage = err?.message || err || "Unknown error";
|
|
13164
|
-
this.emit("batch_replicator_error", {
|
|
13165
|
-
replicator: this.name,
|
|
13166
|
-
resource,
|
|
13167
|
-
error: errorMessage
|
|
13168
|
-
});
|
|
13169
|
-
return { success: false, error: errorMessage };
|
|
13170
|
-
}
|
|
13171
|
-
async testConnection() {
|
|
13172
|
-
const [ok, err] = await try_fn_default(async () => {
|
|
13173
|
-
if (!this.sqsClient) {
|
|
13174
|
-
await this.initialize(this.database);
|
|
13175
|
-
}
|
|
13176
|
-
const { GetQueueAttributesCommand } = await import('@aws-sdk/client-sqs');
|
|
13177
|
-
const command = new GetQueueAttributesCommand({
|
|
13178
|
-
QueueUrl: this.queueUrl,
|
|
13179
|
-
AttributeNames: ["QueueArn"]
|
|
13180
|
-
});
|
|
13181
|
-
await this.sqsClient.send(command);
|
|
13182
|
-
return true;
|
|
13183
|
-
});
|
|
13184
|
-
if (ok) return true;
|
|
13185
|
-
this.emit("connection_error", {
|
|
13186
|
-
replicator: this.name,
|
|
13187
|
-
error: err.message
|
|
13188
|
-
});
|
|
13189
|
-
return false;
|
|
13190
|
-
}
|
|
13191
|
-
async getStatus() {
|
|
13192
|
-
const baseStatus = await super.getStatus();
|
|
13193
|
-
return {
|
|
13194
|
-
...baseStatus,
|
|
13195
|
-
connected: !!this.sqsClient,
|
|
13196
|
-
queueUrl: this.queueUrl,
|
|
13197
|
-
region: this.region,
|
|
13198
|
-
resources: this.resources,
|
|
13199
|
-
totalreplicators: this.listenerCount("replicated"),
|
|
13200
|
-
totalErrors: this.listenerCount("replicator_error")
|
|
13201
|
-
};
|
|
13202
|
-
}
|
|
13203
|
-
async cleanup() {
|
|
13204
|
-
if (this.sqsClient) {
|
|
13205
|
-
this.sqsClient.destroy();
|
|
13206
|
-
}
|
|
13207
|
-
await super.cleanup();
|
|
13208
|
-
}
|
|
13209
|
-
shouldReplicateResource(resource) {
|
|
13210
|
-
const result = this.resourceQueueMap && Object.keys(this.resourceQueueMap).includes(resource) || this.queues && Object.keys(this.queues).includes(resource) || !!(this.defaultQueue || this.queueUrl) || this.resources && Object.keys(this.resources).includes(resource) || false;
|
|
13211
|
-
return result;
|
|
13212
|
-
}
|
|
13213
|
-
}
|
|
13214
|
-
var sqs_replicator_class_default = SqsReplicator;
|
|
13215
|
-
|
|
13216
|
-
const REPLICATOR_DRIVERS = {
|
|
13217
|
-
s3db: s3db_replicator_class_default,
|
|
13218
|
-
sqs: sqs_replicator_class_default,
|
|
13219
|
-
bigquery: bigquery_replicator_class_default,
|
|
13220
|
-
postgres: postgres_replicator_class_default
|
|
13221
|
-
};
|
|
13222
|
-
function createReplicator(driver, config = {}, resources = [], client = null) {
|
|
13223
|
-
const ReplicatorClass = REPLICATOR_DRIVERS[driver];
|
|
13224
|
-
if (!ReplicatorClass) {
|
|
13225
|
-
throw new Error(`Unknown replicator driver: ${driver}. Available drivers: ${Object.keys(REPLICATOR_DRIVERS).join(", ")}`);
|
|
13226
|
-
}
|
|
13227
|
-
return new ReplicatorClass(config, resources, client);
|
|
13228
|
-
}
|
|
13229
|
-
|
|
13230
12112
|
function normalizeResourceName(name) {
|
|
13231
12113
|
return typeof name === "string" ? name.trim().toLowerCase() : name;
|
|
13232
12114
|
}
|
|
13233
12115
|
class ReplicatorPlugin extends plugin_class_default {
|
|
13234
12116
|
constructor(options = {}) {
|
|
13235
12117
|
super();
|
|
13236
|
-
if (options.verbose) {
|
|
13237
|
-
console.log("[PLUGIN][CONSTRUCTOR] ReplicatorPlugin constructor called");
|
|
13238
|
-
}
|
|
13239
|
-
if (options.verbose) {
|
|
13240
|
-
console.log("[PLUGIN][constructor] New ReplicatorPlugin instance created with config:", options);
|
|
13241
|
-
}
|
|
13242
12118
|
if (!options.replicators || !Array.isArray(options.replicators)) {
|
|
13243
12119
|
throw new Error("ReplicatorPlugin: replicators array is required");
|
|
13244
12120
|
}
|
|
13245
12121
|
for (const rep of options.replicators) {
|
|
13246
12122
|
if (!rep.driver) throw new Error("ReplicatorPlugin: each replicator must have a driver");
|
|
12123
|
+
if (!rep.resources || typeof rep.resources !== "object") throw new Error("ReplicatorPlugin: each replicator must have resources config");
|
|
12124
|
+
if (Object.keys(rep.resources).length === 0) throw new Error("ReplicatorPlugin: each replicator must have at least one resource configured");
|
|
13247
12125
|
}
|
|
13248
12126
|
this.config = {
|
|
13249
|
-
|
|
13250
|
-
|
|
13251
|
-
replicatorLogResource: options.replicatorLogResource
|
|
13252
|
-
|
|
12127
|
+
replicators: options.replicators || [],
|
|
12128
|
+
logErrors: options.logErrors !== false,
|
|
12129
|
+
replicatorLogResource: options.replicatorLogResource || "replicator_log",
|
|
12130
|
+
enabled: options.enabled !== false,
|
|
12131
|
+
batchSize: options.batchSize || 100,
|
|
12132
|
+
maxRetries: options.maxRetries || 3,
|
|
12133
|
+
timeout: options.timeout || 3e4,
|
|
12134
|
+
verbose: options.verbose || false,
|
|
12135
|
+
...options
|
|
13253
12136
|
};
|
|
13254
12137
|
this.replicators = [];
|
|
13255
|
-
this.
|
|
13256
|
-
this.
|
|
13257
|
-
this.stats = {
|
|
13258
|
-
totalOperations: 0,
|
|
13259
|
-
totalErrors: 0,
|
|
13260
|
-
lastError: null
|
|
13261
|
-
};
|
|
13262
|
-
this._installedListeners = [];
|
|
12138
|
+
this.database = null;
|
|
12139
|
+
this.eventListenersInstalled = /* @__PURE__ */ new Set();
|
|
13263
12140
|
}
|
|
13264
12141
|
/**
|
|
13265
12142
|
* Decompress data if it was compressed
|
|
@@ -13278,79 +12155,34 @@ class ReplicatorPlugin extends plugin_class_default {
|
|
|
13278
12155
|
}
|
|
13279
12156
|
return filtered;
|
|
13280
12157
|
}
|
|
13281
|
-
installEventListeners(resource) {
|
|
13282
|
-
|
|
13283
|
-
|
|
13284
|
-
console.log("[PLUGIN] installEventListeners called for:", resource && resource.name, {
|
|
13285
|
-
hasDatabase: !!resource.database,
|
|
13286
|
-
sameDatabase: resource.database === plugin.database,
|
|
13287
|
-
alreadyInstalled: resource._replicatorListenersInstalled,
|
|
13288
|
-
resourceObj: resource,
|
|
13289
|
-
resourceObjId: resource && resource.id,
|
|
13290
|
-
resourceObjType: typeof resource,
|
|
13291
|
-
resourceObjIs: resource && Object.is(resource, plugin.database.resources && plugin.database.resources[resource.name]),
|
|
13292
|
-
resourceObjEq: resource === (plugin.database.resources && plugin.database.resources[resource.name])
|
|
13293
|
-
});
|
|
13294
|
-
}
|
|
13295
|
-
if (!resource || resource.name === plugin.config.replicatorLogResource || !resource.database || resource.database !== plugin.database) return;
|
|
13296
|
-
if (resource._replicatorListenersInstalled) return;
|
|
13297
|
-
resource._replicatorListenersInstalled = true;
|
|
13298
|
-
this._installedListeners.push(resource);
|
|
13299
|
-
if (plugin.config.verbose) {
|
|
13300
|
-
console.log(`[PLUGIN] installEventListeners INSTALLED for resource: ${resource && resource.name}`);
|
|
12158
|
+
installEventListeners(resource, database, plugin) {
|
|
12159
|
+
if (!resource || this.eventListenersInstalled.has(resource.name)) {
|
|
12160
|
+
return;
|
|
13301
12161
|
}
|
|
13302
12162
|
resource.on("insert", async (data) => {
|
|
13303
|
-
if (plugin.config.verbose) {
|
|
13304
|
-
console.log("[PLUGIN] Listener INSERT on", resource.name, "plugin.replicators.length:", plugin.replicators.length, plugin.replicators.map((r) => ({ id: r.id, driver: r.driver })));
|
|
13305
|
-
}
|
|
13306
12163
|
try {
|
|
13307
|
-
const completeData =
|
|
13308
|
-
|
|
13309
|
-
|
|
13310
|
-
}
|
|
13311
|
-
await plugin.processReplicatorEvent(resource.name, "insert", data.id, completeData, null);
|
|
13312
|
-
} catch (err) {
|
|
13313
|
-
if (plugin.config.verbose) {
|
|
13314
|
-
console.error(`[PLUGIN] Listener INSERT error on ${resource.name} id=${data && data.id}:`, err);
|
|
13315
|
-
}
|
|
12164
|
+
const completeData = { ...data, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
12165
|
+
await plugin.processReplicatorEvent("insert", resource.name, completeData.id, completeData);
|
|
12166
|
+
} catch (error) {
|
|
12167
|
+
this.emit("error", { operation: "insert", error: error.message, resource: resource.name });
|
|
13316
12168
|
}
|
|
13317
12169
|
});
|
|
13318
|
-
resource.on("update", async (data) => {
|
|
13319
|
-
console.log("[PLUGIN][Listener][UPDATE][START] triggered for resource:", resource.name, "data:", data);
|
|
13320
|
-
const beforeData = data && data.$before;
|
|
13321
|
-
if (plugin.config.verbose) {
|
|
13322
|
-
console.log("[PLUGIN] Listener UPDATE on", resource.name, "plugin.replicators.length:", plugin.replicators.length, plugin.replicators.map((r) => ({ id: r.id, driver: r.driver })), "data:", data, "beforeData:", beforeData);
|
|
13323
|
-
}
|
|
12170
|
+
resource.on("update", async (data, beforeData) => {
|
|
13324
12171
|
try {
|
|
13325
|
-
|
|
13326
|
-
|
|
13327
|
-
|
|
13328
|
-
|
|
13329
|
-
} else {
|
|
13330
|
-
completeData = data;
|
|
13331
|
-
}
|
|
13332
|
-
await plugin.processReplicatorEvent(resource.name, "update", data.id, completeData, beforeData);
|
|
13333
|
-
} catch (err) {
|
|
13334
|
-
if (plugin.config.verbose) {
|
|
13335
|
-
console.error(`[PLUGIN] Listener UPDATE erro em ${resource.name} id=${data && data.id}:`, err);
|
|
13336
|
-
}
|
|
12172
|
+
const completeData = { ...data, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
12173
|
+
await plugin.processReplicatorEvent("update", resource.name, completeData.id, completeData, beforeData);
|
|
12174
|
+
} catch (error) {
|
|
12175
|
+
this.emit("error", { operation: "update", error: error.message, resource: resource.name });
|
|
13337
12176
|
}
|
|
13338
12177
|
});
|
|
13339
|
-
resource.on("delete", async (data
|
|
13340
|
-
if (plugin.config.verbose) {
|
|
13341
|
-
console.log("[PLUGIN] Listener DELETE on", resource.name, "plugin.replicators.length:", plugin.replicators.length, plugin.replicators.map((r) => ({ id: r.id, driver: r.driver })));
|
|
13342
|
-
}
|
|
12178
|
+
resource.on("delete", async (data) => {
|
|
13343
12179
|
try {
|
|
13344
|
-
await plugin.processReplicatorEvent(resource.name,
|
|
13345
|
-
} catch (
|
|
13346
|
-
|
|
13347
|
-
console.error(`[PLUGIN] Listener DELETE erro em ${resource.name} id=${data && data.id}:`, err);
|
|
13348
|
-
}
|
|
12180
|
+
await plugin.processReplicatorEvent("delete", resource.name, data.id, data);
|
|
12181
|
+
} catch (error) {
|
|
12182
|
+
this.emit("error", { operation: "delete", error: error.message, resource: resource.name });
|
|
13349
12183
|
}
|
|
13350
12184
|
});
|
|
13351
|
-
|
|
13352
|
-
console.log(`[PLUGIN] Listeners instalados para resource: ${resource && resource.name} (insert: ${resource.listenerCount("insert")}, update: ${resource.listenerCount("update")}, delete: ${resource.listenerCount("delete")})`);
|
|
13353
|
-
}
|
|
12185
|
+
this.eventListenersInstalled.add(resource.name);
|
|
13354
12186
|
}
|
|
13355
12187
|
/**
|
|
13356
12188
|
* Get complete data by always fetching the full record from the resource
|
|
@@ -13361,112 +12193,53 @@ class ReplicatorPlugin extends plugin_class_default {
|
|
|
13361
12193
|
return ok ? completeRecord : data;
|
|
13362
12194
|
}
|
|
13363
12195
|
async setup(database) {
|
|
13364
|
-
console.log("[PLUGIN][SETUP] setup called");
|
|
13365
|
-
if (this.config.verbose) {
|
|
13366
|
-
console.log("[PLUGIN][setup] called with database:", database && database.name);
|
|
13367
|
-
}
|
|
13368
12196
|
this.database = database;
|
|
13369
|
-
|
|
13370
|
-
|
|
13371
|
-
|
|
13372
|
-
|
|
12197
|
+
try {
|
|
12198
|
+
await this.initializeReplicators(database);
|
|
12199
|
+
} catch (error) {
|
|
12200
|
+
this.emit("error", { operation: "setup", error: error.message });
|
|
12201
|
+
throw error;
|
|
12202
|
+
}
|
|
12203
|
+
try {
|
|
12204
|
+
if (this.config.replicatorLogResource) {
|
|
12205
|
+
const logRes = await database.createResource({
|
|
13373
12206
|
name: this.config.replicatorLogResource,
|
|
13374
|
-
behavior: "
|
|
12207
|
+
behavior: "body-overflow",
|
|
13375
12208
|
attributes: {
|
|
13376
|
-
|
|
13377
|
-
|
|
13378
|
-
|
|
13379
|
-
data: "
|
|
13380
|
-
|
|
13381
|
-
|
|
13382
|
-
|
|
13383
|
-
|
|
13384
|
-
byDate: { fields: { "createdAt": "string|maxlength:10" } }
|
|
12209
|
+
operation: "string",
|
|
12210
|
+
resourceName: "string",
|
|
12211
|
+
recordId: "string",
|
|
12212
|
+
data: "string",
|
|
12213
|
+
error: "string|optional",
|
|
12214
|
+
replicator: "string",
|
|
12215
|
+
timestamp: "string",
|
|
12216
|
+
status: "string"
|
|
13385
12217
|
}
|
|
13386
12218
|
});
|
|
13387
|
-
if (this.config.verbose) {
|
|
13388
|
-
console.log("[PLUGIN] Log resource created:", this.config.replicatorLogResource, !!logRes);
|
|
13389
|
-
}
|
|
13390
|
-
}
|
|
13391
|
-
database.resources[normalizeResourceName(this.config.replicatorLogResource)] = logRes;
|
|
13392
|
-
this.replicatorLog = logRes;
|
|
13393
|
-
if (this.config.verbose) {
|
|
13394
|
-
console.log("[PLUGIN] Log resource created and registered:", this.config.replicatorLogResource, !!database.resources[normalizeResourceName(this.config.replicatorLogResource)]);
|
|
13395
|
-
}
|
|
13396
|
-
if (typeof database.uploadMetadataFile === "function") {
|
|
13397
|
-
await database.uploadMetadataFile();
|
|
13398
|
-
if (this.config.verbose) {
|
|
13399
|
-
console.log("[PLUGIN] uploadMetadataFile called. database.resources keys:", Object.keys(database.resources));
|
|
13400
|
-
}
|
|
13401
|
-
}
|
|
13402
|
-
}
|
|
13403
|
-
if (this.config.replicators && this.config.replicators.length > 0 && this.replicators.length === 0) {
|
|
13404
|
-
await this.initializeReplicators();
|
|
13405
|
-
console.log("[PLUGIN][SETUP] after initializeReplicators, replicators.length:", this.replicators.length);
|
|
13406
|
-
if (this.config.verbose) {
|
|
13407
|
-
console.log("[PLUGIN][setup] After initializeReplicators, replicators.length:", this.replicators.length, this.replicators.map((r) => ({ id: r.id, driver: r.driver })));
|
|
13408
|
-
}
|
|
13409
|
-
}
|
|
13410
|
-
for (const resourceName in database.resources) {
|
|
13411
|
-
if (normalizeResourceName(resourceName) !== normalizeResourceName(this.config.replicatorLogResource)) {
|
|
13412
|
-
this.installEventListeners(database.resources[resourceName]);
|
|
13413
12219
|
}
|
|
12220
|
+
} catch (error) {
|
|
13414
12221
|
}
|
|
13415
|
-
|
|
13416
|
-
for (const resourceName in database.resources) {
|
|
13417
|
-
if (normalizeResourceName(resourceName) !== normalizeResourceName(this.config.replicatorLogResource)) {
|
|
13418
|
-
this.installEventListeners(database.resources[resourceName]);
|
|
13419
|
-
}
|
|
13420
|
-
}
|
|
13421
|
-
});
|
|
12222
|
+
await this.uploadMetadataFile(database);
|
|
13422
12223
|
const originalCreateResource = database.createResource.bind(database);
|
|
13423
12224
|
database.createResource = async (config) => {
|
|
13424
|
-
if (this.config.verbose) {
|
|
13425
|
-
console.log("[PLUGIN] createResource proxy called for:", config && config.name);
|
|
13426
|
-
}
|
|
13427
12225
|
const resource = await originalCreateResource(config);
|
|
13428
|
-
if (resource
|
|
13429
|
-
this.installEventListeners(resource);
|
|
12226
|
+
if (resource) {
|
|
12227
|
+
this.installEventListeners(resource, database, this);
|
|
13430
12228
|
}
|
|
13431
12229
|
return resource;
|
|
13432
12230
|
};
|
|
13433
|
-
|
|
13434
|
-
const resource = database.resources[resourceName];
|
|
13435
|
-
if (resource && resource.name !== this.config.replicatorLogResource) {
|
|
13436
|
-
this.installEventListeners(resource);
|
|
13437
|
-
}
|
|
13438
|
-
});
|
|
13439
|
-
database.on("s3db.resourceUpdated", (resourceName) => {
|
|
12231
|
+
for (const resourceName in database.resources) {
|
|
13440
12232
|
const resource = database.resources[resourceName];
|
|
13441
|
-
|
|
13442
|
-
|
|
13443
|
-
}
|
|
13444
|
-
});
|
|
12233
|
+
this.installEventListeners(resource, database, this);
|
|
12234
|
+
}
|
|
13445
12235
|
}
|
|
13446
|
-
async initializeReplicators() {
|
|
13447
|
-
console.log("[PLUGIN][INIT] initializeReplicators called");
|
|
12236
|
+
async initializeReplicators(database) {
|
|
13448
12237
|
for (const replicatorConfig of this.config.replicators) {
|
|
13449
|
-
|
|
13450
|
-
|
|
13451
|
-
|
|
13452
|
-
|
|
13453
|
-
|
|
13454
|
-
const replicator = createReplicator(driver, replicatorConfig, resources, client);
|
|
13455
|
-
if (replicator) {
|
|
13456
|
-
await replicator.initialize(this.database);
|
|
13457
|
-
this.replicators.push({
|
|
13458
|
-
id: Math.random().toString(36).slice(2),
|
|
13459
|
-
driver,
|
|
13460
|
-
config: replicatorConfig,
|
|
13461
|
-
resources,
|
|
13462
|
-
instance: replicator
|
|
13463
|
-
});
|
|
13464
|
-
console.log("[PLUGIN][INIT] pushed replicator:", driver, resources);
|
|
13465
|
-
} else {
|
|
13466
|
-
console.log("[PLUGIN][INIT] createReplicator returned null/undefined for driver:", driver);
|
|
13467
|
-
}
|
|
13468
|
-
} catch (err) {
|
|
13469
|
-
console.error("[PLUGIN][INIT] Error creating replicator:", err);
|
|
12238
|
+
const { driver, config, resources } = replicatorConfig;
|
|
12239
|
+
const replicator = this.createReplicator(driver, config, resources);
|
|
12240
|
+
if (replicator) {
|
|
12241
|
+
await replicator.initialize(database);
|
|
12242
|
+
this.replicators.push(replicator);
|
|
13470
12243
|
}
|
|
13471
12244
|
}
|
|
13472
12245
|
}
|
|
@@ -13474,160 +12247,102 @@ class ReplicatorPlugin extends plugin_class_default {
|
|
|
13474
12247
|
}
|
|
13475
12248
|
async stop() {
|
|
13476
12249
|
}
|
|
13477
|
-
async processReplicatorEvent(
|
|
13478
|
-
if (this.config.
|
|
13479
|
-
console.log("[PLUGIN][processReplicatorEvent] replicators.length:", this.replicators.length, this.replicators.map((r) => ({ id: r.id, driver: r.driver })));
|
|
13480
|
-
console.log(`[PLUGIN][processReplicatorEvent] operation: ${operation}, resource: ${resourceName}, recordId: ${recordId}, data:`, data, "beforeData:", beforeData);
|
|
13481
|
-
}
|
|
13482
|
-
if (this.config.verbose) {
|
|
13483
|
-
console.log(`[PLUGIN] processReplicatorEvent: resource=${resourceName} op=${operation} id=${recordId} data=`, data);
|
|
13484
|
-
}
|
|
13485
|
-
if (this.config.verbose) {
|
|
13486
|
-
console.log(`[PLUGIN] processReplicatorEvent: resource=${resourceName} op=${operation} replicators=${this.replicators.length}`);
|
|
13487
|
-
}
|
|
13488
|
-
if (this.replicators.length === 0) {
|
|
13489
|
-
if (this.config.verbose) {
|
|
13490
|
-
console.log("[PLUGIN] No replicators registered");
|
|
13491
|
-
}
|
|
13492
|
-
return;
|
|
13493
|
-
}
|
|
12250
|
+
async processReplicatorEvent(operation, resourceName, recordId, data, beforeData = null) {
|
|
12251
|
+
if (!this.config.enabled) return;
|
|
13494
12252
|
const applicableReplicators = this.replicators.filter((replicator) => {
|
|
13495
|
-
const should = replicator.
|
|
13496
|
-
if (this.config.verbose) {
|
|
13497
|
-
console.log(`[PLUGIN] Replicator ${replicator.driver} shouldReplicateResource(${resourceName}, ${operation}):`, should);
|
|
13498
|
-
}
|
|
12253
|
+
const should = replicator.shouldReplicateResource && replicator.shouldReplicateResource(resourceName, operation);
|
|
13499
12254
|
return should;
|
|
13500
12255
|
});
|
|
13501
|
-
if (this.config.verbose) {
|
|
13502
|
-
console.log(`[PLUGIN] processReplicatorEvent: applicableReplicators for resource=${resourceName}:`, applicableReplicators.map((r) => r.driver));
|
|
13503
|
-
}
|
|
13504
12256
|
if (applicableReplicators.length === 0) {
|
|
13505
|
-
if (this.config.verbose) {
|
|
13506
|
-
console.log("[PLUGIN] No applicable replicators for resource", resourceName);
|
|
13507
|
-
}
|
|
13508
12257
|
return;
|
|
13509
12258
|
}
|
|
13510
|
-
const
|
|
13511
|
-
|
|
13512
|
-
|
|
13513
|
-
|
|
13514
|
-
|
|
13515
|
-
|
|
13516
|
-
|
|
13517
|
-
|
|
13518
|
-
|
|
13519
|
-
|
|
13520
|
-
|
|
13521
|
-
|
|
13522
|
-
|
|
13523
|
-
const [ok, err, result] = await try_fn_default(async () => this.processreplicatorItem(item));
|
|
13524
|
-
if (ok) {
|
|
13525
|
-
if (logId) {
|
|
13526
|
-
await this.updatereplicatorLog(logId, {
|
|
13527
|
-
status: result.success ? "success" : "failed",
|
|
13528
|
-
attempts: 1,
|
|
13529
|
-
error: result.success ? "" : JSON.stringify(result.results)
|
|
12259
|
+
const promises = applicableReplicators.map(async (replicator) => {
|
|
12260
|
+
try {
|
|
12261
|
+
const result = await this.retryWithBackoff(
|
|
12262
|
+
() => replicator.replicate(resourceName, operation, data, recordId, beforeData),
|
|
12263
|
+
this.config.maxRetries
|
|
12264
|
+
);
|
|
12265
|
+
this.emit("replicated", {
|
|
12266
|
+
replicator: replicator.name || replicator.id,
|
|
12267
|
+
resourceName,
|
|
12268
|
+
operation,
|
|
12269
|
+
recordId,
|
|
12270
|
+
result,
|
|
12271
|
+
success: true
|
|
13530
12272
|
});
|
|
13531
|
-
|
|
13532
|
-
|
|
13533
|
-
|
|
13534
|
-
|
|
13535
|
-
|
|
13536
|
-
|
|
13537
|
-
|
|
13538
|
-
|
|
13539
|
-
if (logId) {
|
|
13540
|
-
await this.updatereplicatorLog(logId, {
|
|
13541
|
-
status: "failed",
|
|
13542
|
-
attempts: 1,
|
|
13543
|
-
error: err.message
|
|
12273
|
+
return result;
|
|
12274
|
+
} catch (error) {
|
|
12275
|
+
this.emit("replicator_error", {
|
|
12276
|
+
replicator: replicator.name || replicator.id,
|
|
12277
|
+
resourceName,
|
|
12278
|
+
operation,
|
|
12279
|
+
recordId,
|
|
12280
|
+
error: error.message
|
|
13544
12281
|
});
|
|
12282
|
+
if (this.config.logErrors && this.database) {
|
|
12283
|
+
await this.logError(replicator, resourceName, operation, recordId, data, error);
|
|
12284
|
+
}
|
|
12285
|
+
throw error;
|
|
13545
12286
|
}
|
|
13546
|
-
|
|
13547
|
-
|
|
12287
|
+
});
|
|
12288
|
+
return Promise.allSettled(promises);
|
|
13548
12289
|
}
|
|
13549
12290
|
async processreplicatorItem(item) {
|
|
13550
|
-
if (this.config.verbose) {
|
|
13551
|
-
console.log("[PLUGIN][processreplicatorItem] called with item:", item);
|
|
13552
|
-
}
|
|
13553
12291
|
const applicableReplicators = this.replicators.filter((replicator) => {
|
|
13554
|
-
const should = replicator.
|
|
13555
|
-
if (this.config.verbose) {
|
|
13556
|
-
console.log(`[PLUGIN] processreplicatorItem: Replicator ${replicator.driver} shouldReplicateResource(${item.resourceName}, ${item.operation}):`, should);
|
|
13557
|
-
}
|
|
12292
|
+
const should = replicator.shouldReplicateResource && replicator.shouldReplicateResource(item.resourceName, item.operation);
|
|
13558
12293
|
return should;
|
|
13559
12294
|
});
|
|
13560
|
-
if (this.config.verbose) {
|
|
13561
|
-
console.log(`[PLUGIN] processreplicatorItem: applicableReplicators for resource=${item.resourceName}:`, applicableReplicators.map((r) => r.driver));
|
|
13562
|
-
}
|
|
13563
12295
|
if (applicableReplicators.length === 0) {
|
|
13564
|
-
|
|
13565
|
-
console.log("[PLUGIN] processreplicatorItem: No applicable replicators for resource", item.resourceName);
|
|
13566
|
-
}
|
|
13567
|
-
return { success: true, skipped: true, reason: "no_applicable_replicators" };
|
|
12296
|
+
return;
|
|
13568
12297
|
}
|
|
13569
|
-
const
|
|
13570
|
-
|
|
13571
|
-
|
|
13572
|
-
|
|
13573
|
-
|
|
13574
|
-
|
|
13575
|
-
|
|
12298
|
+
const promises = applicableReplicators.map(async (replicator) => {
|
|
12299
|
+
try {
|
|
12300
|
+
const [ok, err, result] = await try_fn_default(
|
|
12301
|
+
() => replicator.replicate(item.resourceName, item.operation, item.data, item.recordId, item.beforeData)
|
|
12302
|
+
);
|
|
12303
|
+
if (!ok) {
|
|
12304
|
+
this.emit("replicator_error", {
|
|
12305
|
+
replicator: replicator.name || replicator.id,
|
|
12306
|
+
resourceName: item.resourceName,
|
|
12307
|
+
operation: item.operation,
|
|
12308
|
+
recordId: item.recordId,
|
|
12309
|
+
error: err.message
|
|
12310
|
+
});
|
|
12311
|
+
if (this.config.logErrors && this.database) {
|
|
12312
|
+
await this.logError(replicator, item.resourceName, item.operation, item.recordId, item.data, err);
|
|
12313
|
+
}
|
|
12314
|
+
return { success: false, error: err.message };
|
|
12315
|
+
}
|
|
12316
|
+
this.emit("replicated", {
|
|
12317
|
+
replicator: replicator.name || replicator.id,
|
|
12318
|
+
resourceName: item.resourceName,
|
|
13576
12319
|
operation: item.operation,
|
|
13577
|
-
|
|
13578
|
-
|
|
13579
|
-
|
|
12320
|
+
recordId: item.recordId,
|
|
12321
|
+
result,
|
|
12322
|
+
success: true
|
|
13580
12323
|
});
|
|
12324
|
+
return { success: true, result };
|
|
12325
|
+
} catch (error) {
|
|
12326
|
+
this.emit("replicator_error", {
|
|
12327
|
+
replicator: replicator.name || replicator.id,
|
|
12328
|
+
resourceName: item.resourceName,
|
|
12329
|
+
operation: item.operation,
|
|
12330
|
+
recordId: item.recordId,
|
|
12331
|
+
error: error.message
|
|
12332
|
+
});
|
|
12333
|
+
if (this.config.logErrors && this.database) {
|
|
12334
|
+
await this.logError(replicator, item.resourceName, item.operation, item.recordId, item.data, error);
|
|
12335
|
+
}
|
|
12336
|
+
return { success: false, error: error.message };
|
|
13581
12337
|
}
|
|
13582
|
-
|
|
13583
|
-
|
|
13584
|
-
() => replicator.instance.replicate({
|
|
13585
|
-
resource: item.resourceName,
|
|
13586
|
-
operation: item.operation,
|
|
13587
|
-
data: item.data,
|
|
13588
|
-
id: item.recordId,
|
|
13589
|
-
beforeData: item.beforeData
|
|
13590
|
-
})
|
|
13591
|
-
);
|
|
13592
|
-
} else {
|
|
13593
|
-
[ok, err, result] = await try_fn_default(
|
|
13594
|
-
() => replicator.instance.replicate(
|
|
13595
|
-
item.resourceName,
|
|
13596
|
-
item.operation,
|
|
13597
|
-
item.data,
|
|
13598
|
-
item.recordId,
|
|
13599
|
-
item.beforeData
|
|
13600
|
-
)
|
|
13601
|
-
);
|
|
13602
|
-
}
|
|
13603
|
-
results.push({
|
|
13604
|
-
replicatorId: replicator.id,
|
|
13605
|
-
driver: replicator.driver,
|
|
13606
|
-
success: result && result.success,
|
|
13607
|
-
error: result && result.error,
|
|
13608
|
-
skipped: result && result.skipped
|
|
13609
|
-
});
|
|
13610
|
-
}
|
|
13611
|
-
return {
|
|
13612
|
-
success: results.every((r) => r.success || r.skipped),
|
|
13613
|
-
results
|
|
13614
|
-
};
|
|
12338
|
+
});
|
|
12339
|
+
return Promise.allSettled(promises);
|
|
13615
12340
|
}
|
|
13616
12341
|
async logreplicator(item) {
|
|
13617
12342
|
const logRes = this.replicatorLog || this.database.resources[normalizeResourceName(this.config.replicatorLogResource)];
|
|
13618
12343
|
if (!logRes) {
|
|
13619
|
-
if (this.config.verbose) {
|
|
13620
|
-
console.error("[PLUGIN] replicator log resource not found!");
|
|
13621
|
-
}
|
|
13622
12344
|
if (this.database) {
|
|
13623
|
-
if (this.
|
|
13624
|
-
console.warn("[PLUGIN] database.resources keys:", Object.keys(this.database.resources));
|
|
13625
|
-
}
|
|
13626
|
-
if (this.database.options && this.database.options.connectionString) {
|
|
13627
|
-
if (this.config.verbose) {
|
|
13628
|
-
console.warn("[PLUGIN] database connectionString:", this.database.options.connectionString);
|
|
13629
|
-
}
|
|
13630
|
-
}
|
|
12345
|
+
if (this.database.options && this.database.options.connectionString) ;
|
|
13631
12346
|
}
|
|
13632
12347
|
this.emit("replicator.log.failed", { error: "replicator log resource not found", item });
|
|
13633
12348
|
return;
|
|
@@ -13643,9 +12358,6 @@ class ReplicatorPlugin extends plugin_class_default {
|
|
|
13643
12358
|
try {
|
|
13644
12359
|
await logRes.insert(logItem);
|
|
13645
12360
|
} catch (err) {
|
|
13646
|
-
if (this.config.verbose) {
|
|
13647
|
-
console.error("[PLUGIN] Error writing to replicator log:", err);
|
|
13648
|
-
}
|
|
13649
12361
|
this.emit("replicator.log.failed", { error: err, item });
|
|
13650
12362
|
}
|
|
13651
12363
|
}
|
|
@@ -13727,10 +12439,6 @@ class ReplicatorPlugin extends plugin_class_default {
|
|
|
13727
12439
|
});
|
|
13728
12440
|
if (ok) {
|
|
13729
12441
|
retried++;
|
|
13730
|
-
} else {
|
|
13731
|
-
if (this.config.verbose) {
|
|
13732
|
-
console.error("Failed to retry replicator:", err);
|
|
13733
|
-
}
|
|
13734
12442
|
}
|
|
13735
12443
|
}
|
|
13736
12444
|
return { retried };
|
|
@@ -13755,40 +12463,23 @@ class ReplicatorPlugin extends plugin_class_default {
|
|
|
13755
12463
|
this.emit("replicator.sync.completed", { replicatorId, stats: this.stats });
|
|
13756
12464
|
}
|
|
13757
12465
|
async cleanup() {
|
|
13758
|
-
|
|
13759
|
-
|
|
13760
|
-
|
|
13761
|
-
|
|
13762
|
-
|
|
13763
|
-
|
|
13764
|
-
|
|
13765
|
-
|
|
13766
|
-
|
|
13767
|
-
}
|
|
13768
|
-
|
|
13769
|
-
}
|
|
13770
|
-
this._installedListeners = [];
|
|
13771
|
-
}
|
|
13772
|
-
if (this.database && typeof this.database.removeAllListeners === "function") {
|
|
13773
|
-
this.database.removeAllListeners();
|
|
13774
|
-
}
|
|
13775
|
-
if (this.replicators && Array.isArray(this.replicators)) {
|
|
13776
|
-
for (const rep of this.replicators) {
|
|
13777
|
-
if (rep.instance && typeof rep.instance.cleanup === "function") {
|
|
13778
|
-
await rep.instance.cleanup();
|
|
13779
|
-
}
|
|
12466
|
+
try {
|
|
12467
|
+
if (this.replicators && this.replicators.length > 0) {
|
|
12468
|
+
const cleanupPromises = this.replicators.map(async (replicator) => {
|
|
12469
|
+
try {
|
|
12470
|
+
if (replicator && typeof replicator.cleanup === "function") {
|
|
12471
|
+
await replicator.cleanup();
|
|
12472
|
+
}
|
|
12473
|
+
} catch (error) {
|
|
12474
|
+
}
|
|
12475
|
+
});
|
|
12476
|
+
await Promise.allSettled(cleanupPromises);
|
|
13780
12477
|
}
|
|
13781
12478
|
this.replicators = [];
|
|
13782
|
-
|
|
13783
|
-
|
|
13784
|
-
|
|
13785
|
-
|
|
13786
|
-
totalOperations: 0,
|
|
13787
|
-
totalErrors: 0,
|
|
13788
|
-
lastError: null
|
|
13789
|
-
};
|
|
13790
|
-
if (this.config.verbose) {
|
|
13791
|
-
console.log("[PLUGIN][CLEANUP] ReplicatorPlugin cleanup complete");
|
|
12479
|
+
this.database = null;
|
|
12480
|
+
this.eventListenersInstalled.clear();
|
|
12481
|
+
this.removeAllListeners();
|
|
12482
|
+
} catch (error) {
|
|
13792
12483
|
}
|
|
13793
12484
|
}
|
|
13794
12485
|
}
|