@openpeepshq/core 0.1.32 → 0.1.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/accessTokens/helpers.d.ts +2 -2
- package/dist/accessTokens/tokens.js +14 -7
- package/dist/accounts/mutations.d.ts +2 -2
- package/dist/analytics/cache.js +12 -7
- package/dist/analytics/pdfReport.d.ts +1 -0
- package/dist/analytics/pdfReport.js +5 -4
- package/dist/analytics/privacy.d.ts +18 -0
- package/dist/analytics/privacy.js +10 -0
- package/dist/analytics/read.js +24 -11
- package/dist/analytics/report.d.ts +1 -1
- package/dist/analytics/report.js +9 -2
- package/dist/backups/index.js +6 -3
- package/dist/backups/metadata.d.ts +7 -0
- package/dist/config/defaults/community.js +0 -6
- package/dist/config/defaults/db.d.ts +0 -2
- package/dist/config/defaults/db.js +0 -2
- package/dist/config/index.d.ts +10 -9
- package/dist/db/helpers.d.ts +6 -28
- package/dist/db/helpers.js +19 -149
- package/dist/db/index.d.ts +2 -0
- package/dist/db/index.js +4 -0
- package/dist/db/init.js +3 -2
- package/dist/db/migration/detect.d.ts +0 -3
- package/dist/db/migration/detect.js +0 -54
- package/dist/db/migration/importCollections.d.ts +1 -1
- package/dist/db/migration/importCollections.js +22 -6
- package/dist/db/migration/shared.d.ts +0 -4
- package/dist/db/migration/shared.js +0 -7
- package/dist/db/migration/transform.d.ts +2 -0
- package/dist/db/migration/transform.js +23 -0
- package/dist/db/pg/client.js +4 -0
- package/dist/db/pg/filters/edges.d.ts +1 -1
- package/dist/db/pg/filters/edges.js +1 -1
- package/dist/db/pg/filters/posts.d.ts +1 -0
- package/dist/db/pg/filters/posts.js +11 -1
- package/dist/db/pg/map/filters.js +5 -0
- package/dist/db/pg/map/relations.d.ts +1 -1
- package/dist/db/pg/map/relations.js +89 -41
- package/dist/db/pg/migrate.d.ts +23 -0
- package/dist/db/pg/migrate.js +87 -1
- package/dist/db/pg/schema/documents.d.ts +143 -0
- package/dist/db/pg/schema/documents.js +22 -1
- package/dist/db/pg/schema/edges.d.ts +1 -0
- package/dist/db/pg/schema/edges.js +2 -1
- package/dist/db/pg/schema/index.d.ts +143 -0
- package/dist/db/pg/sql/0007_shallow_oracle.sql +3 -0
- package/dist/db/pg/sql/0008_group_owner_roles.sql +31 -0
- package/dist/db/pg/sql/0009_event_occurrences.sql +26 -0
- package/dist/db/pg/sql/meta/0007_snapshot.json +4179 -0
- package/dist/db/pg/sql/meta/0009_snapshot.json +4299 -0
- package/dist/db/pg/sql/meta/_journal.json +21 -0
- package/dist/db/replaceOrigin.js +6 -0
- package/dist/db/types.d.ts +0 -4
- package/dist/events/index.d.ts +2 -1
- package/dist/events/index.js +54 -33
- package/dist/groups/finders.d.ts +2 -2
- package/dist/groups/helpers.d.ts +6 -6
- package/dist/groups/mapping.d.ts +4 -4
- package/dist/groups/mapping.js +2 -2
- package/dist/groups/mutations.js +1 -1
- package/dist/inviteLinks/helpers.d.ts +4 -4
- package/dist/jams/cache.d.ts +1 -1
- package/dist/jams/cache.js +2 -1
- package/dist/jams/finders.d.ts +2 -1
- package/dist/jams/finders.js +18 -7
- package/dist/jams/helpers.d.ts +4 -0
- package/dist/jams/index.d.ts +4 -3
- package/dist/jams/index.js +20 -13
- package/dist/jams/livekit.d.ts +46 -8
- package/dist/jams/livekit.js +103 -21
- package/dist/jams/mapping.d.ts +14 -4
- package/dist/jams/mutations.d.ts +2 -0
- package/dist/jams/rtmp.d.ts +5 -0
- package/dist/jams/rtmp.js +8 -0
- package/dist/jams/token.d.ts +3 -3
- package/dist/jams/token.js +15 -12
- package/dist/jams/waitingRoom.d.ts +6 -6
- package/dist/jams/waitingRoom.js +24 -23
- package/dist/migration/index.d.ts +4 -0
- package/dist/migration/index.js +4 -0
- package/dist/notifications/defaultNotifications/groupMemberJoined/index.js +3 -1
- package/dist/notifications/defaultNotifications/groupMemberLeft/index.js +3 -1
- package/dist/notifications/helpers.js +6 -2
- package/dist/notifications/push.js +11 -4
- package/dist/plugins/helpers.d.ts +1 -0
- package/dist/plugins/helpers.js +1 -8
- package/dist/plugins/index.d.ts +5 -0
- package/dist/plugins/index.js +41 -4
- package/dist/plugins/install.d.ts +20 -0
- package/dist/plugins/install.js +223 -0
- package/dist/plugins/state.d.ts +4 -0
- package/dist/plugins/state.js +29 -0
- package/dist/posts/eventAgenda.d.ts +165 -0
- package/dist/posts/eventAgenda.js +120 -0
- package/dist/posts/eventOccurrenceJobs.d.ts +4 -0
- package/dist/posts/eventOccurrenceJobs.js +23 -0
- package/dist/posts/eventOccurrences.d.ts +4 -0
- package/dist/posts/eventOccurrences.js +40 -0
- package/dist/posts/finders.d.ts +32 -8
- package/dist/posts/finders.js +27 -45
- package/dist/posts/helpers/filters.js +1 -1
- package/dist/posts/helpers/index.d.ts +102 -16
- package/dist/posts/helpers/index.js +33 -20
- package/dist/posts/index.d.ts +3 -0
- package/dist/posts/index.js +3 -0
- package/dist/posts/mapping.d.ts +275 -0
- package/dist/posts/mapping.js +37 -3
- package/dist/posts/mutations.d.ts +1 -1
- package/dist/posts/mutations.js +29 -18
- package/dist/posts/rsvpConfirmationEmail.js +2 -1
- package/dist/posts/unseenCounts.d.ts +2 -0
- package/dist/posts/unseenCounts.js +25 -8
- package/dist/profiles/cache.d.ts +3 -1
- package/dist/profiles/cache.js +9 -1
- package/dist/profiles/helpers.d.ts +5 -5
- package/dist/profiles/index.d.ts +1 -1
- package/dist/profiles/index.js +1 -1
- package/dist/profiles/mapping.d.ts +5 -5
- package/dist/profiles/mutations.js +12 -14
- package/dist/pushSubscriptions/helpers.d.ts +2 -2
- package/dist/pushSubscriptions/mutations.js +13 -1
- package/dist/reports/helpers.d.ts +6 -6
- package/dist/roles/defaults.js +1 -0
- package/dist/server/index.d.ts +7 -7
- package/dist/server/index.js +15 -8
- package/dist/stats/finders.d.ts +1692 -142
- package/dist/stats/mapping.d.ts +21 -0
- package/package.json +4 -9
- package/dist/db/arango.d.ts +0 -2
- package/dist/db/arango.js +0 -110
- package/dist/db/migration/autoMigrate.d.ts +0 -2
- package/dist/db/migration/autoMigrate.js +0 -111
- package/dist/db/migration/cli.d.ts +0 -1
- package/dist/db/migration/cli.js +0 -56
- package/dist/db/migration/exportArango.d.ts +0 -4
- package/dist/db/migration/exportArango.js +0 -80
package/dist/db/helpers.js
CHANGED
|
@@ -1,152 +1,9 @@
|
|
|
1
|
-
import { CollectionType, } from 'arangojs/collections';
|
|
2
|
-
import { uuidv7 } from 'uuidv7';
|
|
3
|
-
import { collectionElement, query, literal, } from '@openpeepshq/arango-querybuilder';
|
|
4
1
|
import { deleteEdge as deletePgEdge, insertEdge } from './pg/helpers.js';
|
|
5
2
|
import { asTable, edgeRegistry } from './pg/map/registry.js';
|
|
6
3
|
import { nowIso } from './pg/mappers.js';
|
|
7
4
|
import { and, eq } from 'drizzle-orm';
|
|
8
5
|
import { documentKeyAfter, documentKeyBefore } from './pg/filters/index.js';
|
|
9
6
|
import { sorts } from './pg/queries/index.js';
|
|
10
|
-
import { asyncFilter } from '@openpeepshq/common/lib';
|
|
11
|
-
import { logger } from '../log/index.js';
|
|
12
|
-
const log = logger('openpeeps:db');
|
|
13
|
-
const collectionName = (collectionOrName) => typeof collectionOrName === 'string'
|
|
14
|
-
? collectionOrName
|
|
15
|
-
: collectionOrName.name;
|
|
16
|
-
export const addModificationDates = async (collection) => {
|
|
17
|
-
await collection.properties({
|
|
18
|
-
computedValues: [
|
|
19
|
-
{
|
|
20
|
-
name: 'createdAt',
|
|
21
|
-
expression: 'RETURN DATE_ISO8601(DATE_NOW())',
|
|
22
|
-
computeOn: ['insert'],
|
|
23
|
-
overwrite: false,
|
|
24
|
-
failOnWarning: false,
|
|
25
|
-
keepNull: true,
|
|
26
|
-
},
|
|
27
|
-
{
|
|
28
|
-
name: 'updatedAt',
|
|
29
|
-
expression: 'RETURN DATE_ISO8601(DATE_NOW())',
|
|
30
|
-
computeOn: ['update', 'replace', 'insert'],
|
|
31
|
-
overwrite: false,
|
|
32
|
-
failOnWarning: false,
|
|
33
|
-
keepNull: true,
|
|
34
|
-
},
|
|
35
|
-
],
|
|
36
|
-
});
|
|
37
|
-
};
|
|
38
|
-
export const addIndices = async (collection, indices) => {
|
|
39
|
-
for (const index of indices) {
|
|
40
|
-
if (!index.name) {
|
|
41
|
-
return;
|
|
42
|
-
}
|
|
43
|
-
try {
|
|
44
|
-
log.info('ensuring index', index.name);
|
|
45
|
-
await collection.ensureIndex(index);
|
|
46
|
-
}
|
|
47
|
-
catch (error) {
|
|
48
|
-
const message = error.message;
|
|
49
|
-
if (message.includes('duplicate value')) {
|
|
50
|
-
log.info('index already exists', index.name);
|
|
51
|
-
log.info('dropping and recreating...');
|
|
52
|
-
await collection.dropIndex(index.name);
|
|
53
|
-
await collection.ensureIndex(index);
|
|
54
|
-
log.info('index recreated');
|
|
55
|
-
}
|
|
56
|
-
else {
|
|
57
|
-
log.error('error ensuring index', index.name, message);
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
};
|
|
62
|
-
export const ensureIndexedCollection = async (db, collectionInfo) => {
|
|
63
|
-
var _a;
|
|
64
|
-
const maybeCollection = db.collection(collectionInfo.name);
|
|
65
|
-
const collection = (await maybeCollection.exists())
|
|
66
|
-
? maybeCollection
|
|
67
|
-
: collectionInfo.edge
|
|
68
|
-
? await db.createEdgeCollection(collectionInfo.name)
|
|
69
|
-
: await db.createCollection(collectionInfo.name);
|
|
70
|
-
await addModificationDates(collection);
|
|
71
|
-
await addIndices(collection, ((_a = collectionInfo.indices) !== null && _a !== void 0 ? _a : []));
|
|
72
|
-
return collection;
|
|
73
|
-
};
|
|
74
|
-
const isEqualView = (viewInfo1, viewInfo2) => viewInfo1.indexes.length === viewInfo2.indexes.length &&
|
|
75
|
-
viewInfo1.indexes.every((index1) => viewInfo2.indexes.find((index2) => index1.collection === index2.collection &&
|
|
76
|
-
index1.index === index2.index)) &&
|
|
77
|
-
viewInfo2.indexes.every((index2) => viewInfo1.indexes.find((index1) => index1.collection === index2.collection &&
|
|
78
|
-
index1.index === index2.index));
|
|
79
|
-
export const ensureView = async (db, viewInfo) => {
|
|
80
|
-
const view = db.view(viewInfo.name);
|
|
81
|
-
if (await view.exists()) {
|
|
82
|
-
const viewData = await view.properties();
|
|
83
|
-
if (viewData.type === 'search-alias' && isEqualView(viewData, viewInfo)) {
|
|
84
|
-
return view;
|
|
85
|
-
}
|
|
86
|
-
else {
|
|
87
|
-
await view.drop();
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
await view.create(viewInfo);
|
|
91
|
-
};
|
|
92
|
-
const replaceEdgeDefinition = (db) => (edgeDefinition) => db
|
|
93
|
-
.listGraphs()
|
|
94
|
-
.then((graphInfos) => graphInfos.map((gi) => gi.edgeDefinitions).flat())
|
|
95
|
-
.then((edgeDefinitions) => edgeDefinitions.find((ed) => ed.collection === edgeDefinition.collection) || edgeDefinition);
|
|
96
|
-
export const ensureGraph = async (db, name, edgeDefinitions) => {
|
|
97
|
-
const replacedEdgeDefinitions = await Promise.all(edgeDefinitions.map(replaceEdgeDefinition(db)));
|
|
98
|
-
const graph = db.graph(name);
|
|
99
|
-
if (await graph.exists()) {
|
|
100
|
-
const edgeDefinitionsToAdd = await asyncFilter(replacedEdgeDefinitions, (ed) => graph
|
|
101
|
-
.listEdgeCollections()
|
|
102
|
-
.then((ecs) => !ecs.includes(collectionName(ed.collection))));
|
|
103
|
-
const edgeDefinitionsToRemove = await graph
|
|
104
|
-
.listEdgeCollections()
|
|
105
|
-
.then((ecs) => ecs.filter((ec) => !replacedEdgeDefinitions
|
|
106
|
-
.map((ed) => collectionName(ed.collection))
|
|
107
|
-
.includes(ec)));
|
|
108
|
-
for (const edgeDefinition of edgeDefinitionsToAdd) {
|
|
109
|
-
await graph.addEdgeDefinition(edgeDefinition);
|
|
110
|
-
}
|
|
111
|
-
for (const edgeDefinitionCollectionName of edgeDefinitionsToRemove) {
|
|
112
|
-
await graph.removeEdgeDefinition(edgeDefinitionCollectionName);
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
else {
|
|
116
|
-
return await db.createGraph(name, replacedEdgeDefinitions);
|
|
117
|
-
}
|
|
118
|
-
return graph;
|
|
119
|
-
};
|
|
120
|
-
export const ensureFunction = async (db, { name, dbFunction }) => {
|
|
121
|
-
console.log('--------------------------------');
|
|
122
|
-
console.log('ensureFunction', name);
|
|
123
|
-
console.log('--------------------------------');
|
|
124
|
-
console.log(dbFunction.toString());
|
|
125
|
-
console.log('--------------------------------');
|
|
126
|
-
db.createUserFunction(`ALLPEEP::${name}`, dbFunction.toString(), true);
|
|
127
|
-
};
|
|
128
|
-
const setId = (document) => (Object.assign(Object.assign({}, document), { id: document._key }));
|
|
129
|
-
export const createEdge = async (collection, document) => {
|
|
130
|
-
var _a;
|
|
131
|
-
const data = Object.assign(Object.assign({}, document), { _key: (_a = document.id) !== null && _a !== void 0 ? _a : uuidv7() });
|
|
132
|
-
const createdEdge = (await collection.save(data, { returnNew: true })).new;
|
|
133
|
-
if (createdEdge) {
|
|
134
|
-
return setId(createdEdge);
|
|
135
|
-
}
|
|
136
|
-
else {
|
|
137
|
-
throw Error(`Edge in collection ${collection.name} could not be created.`);
|
|
138
|
-
}
|
|
139
|
-
};
|
|
140
|
-
export const updateEdge = async (collection, documentKey, document) => (await collection.update(documentKey, document, { returnNew: true })).new;
|
|
141
|
-
export const deleteEdge = async (collection, documentKey) => await collection.remove(documentKey);
|
|
142
|
-
export const findOneBy = (db, collectionInfo) => (filter) => query().collection(collectionInfo.name).filter(filter).first(db);
|
|
143
|
-
export const edgeCollections = async (database) => database
|
|
144
|
-
.collections()
|
|
145
|
-
.then((collections) => asyncFilter(collections, async (c) => c.properties().then((p) => p.type === CollectionType.EDGE_COLLECTION)));
|
|
146
|
-
const getEdge = async (db, collection, from, to) => findOneBy(db, collection)({
|
|
147
|
-
name: literal(collectionElement(collection)),
|
|
148
|
-
matches: { _from: from, _to: to },
|
|
149
|
-
});
|
|
150
7
|
const getPgEdge = async (db, edgeCollectionName, fromId, toId) => {
|
|
151
8
|
const edgeConfig = edgeRegistry[edgeCollectionName];
|
|
152
9
|
if (!edgeConfig) {
|
|
@@ -171,14 +28,14 @@ export const connector = (fromCollectionInfo, toCollectionInfo, edgeCollectionIn
|
|
|
171
28
|
const id = await insertEdge(db, edgeConfig.table, from.id, to.id, data);
|
|
172
29
|
return Object.assign(Object.assign({}, data), { id, _from: `${fromCollectionInfo.name}/${from.id}`, _to: `${toCollectionInfo.name}/${to.id}` });
|
|
173
30
|
};
|
|
174
|
-
export const disconnector = (
|
|
31
|
+
export const disconnector = (_fromCollectionInfo, _toCollectionInfo, edgeCollectionInfo) => async (db, from, to) => {
|
|
175
32
|
const edgeConfig = edgeRegistry[edgeCollectionInfo.name];
|
|
176
33
|
if (!edgeConfig) {
|
|
177
34
|
throw new Error(`Unknown edge collection: ${edgeCollectionInfo.name}`);
|
|
178
35
|
}
|
|
179
36
|
await deletePgEdge(db, edgeConfig.table, from.id, to.id);
|
|
180
37
|
};
|
|
181
|
-
export const connectionUpdater = (
|
|
38
|
+
export const connectionUpdater = (_fromCollectionInfo, _toCollectionInfo, edgeCollectionInfo) => async (db, from, to, data) => {
|
|
182
39
|
const edgeConfig = edgeRegistry[edgeCollectionInfo.name];
|
|
183
40
|
if (!edgeConfig) {
|
|
184
41
|
throw new Error(`Unknown edge collection: ${edgeCollectionInfo.name}`);
|
|
@@ -205,17 +62,30 @@ export const sortOldestFirst = (mapping) => mapping.sort(sorts.idAsc);
|
|
|
205
62
|
export const addStartLimit = (mapping, start, limit = 100) => filterBefore(sortNewestFirst(mapping.limit(limit)), start);
|
|
206
63
|
export const addStart = (mapping, start) => filterBefore(sortNewestFirst(mapping), start);
|
|
207
64
|
const buildLimit = (limit, offset) => limit && offset ? [offset, limit] : limit;
|
|
65
|
+
/**
|
|
66
|
+
* Ceiling on base rows read for one page, as a multiple of the page size. A
|
|
67
|
+
* post-filter that rejects everything would otherwise walk (and hydrate) the
|
|
68
|
+
* whole collection before returning an empty page.
|
|
69
|
+
*/
|
|
70
|
+
const MAX_SCAN_FACTOR = 10;
|
|
208
71
|
export const filterAndTransform = async (queryResult, db, options) => {
|
|
209
|
-
const { filter = (
|
|
72
|
+
const { filter = () => true, transform = async (i) => i, limit = 100, offset = 0, } = options;
|
|
210
73
|
const result = [];
|
|
74
|
+
const maxScan = limit * MAX_SCAN_FACTOR;
|
|
75
|
+
let scanned = 0;
|
|
211
76
|
let pageOffset = 0;
|
|
212
|
-
while (result.length < limit) {
|
|
213
|
-
const
|
|
77
|
+
while (result.length < limit && scanned < maxScan) {
|
|
78
|
+
const shortfall = limit - result.length;
|
|
79
|
+
// Transform is the expensive part, so read only what the page still needs
|
|
80
|
+
// until a page proves the filter is dropping rows; then over-fetch to
|
|
81
|
+
// converge without a round trip per remaining row.
|
|
82
|
+
const nextPageLength = Math.min(pageOffset === 0 ? shortfall : shortfall * 2, maxScan - scanned);
|
|
214
83
|
const list = await queryResult
|
|
215
84
|
.limit(buildLimit(nextPageLength, offset + pageOffset))
|
|
216
85
|
.all(db);
|
|
217
86
|
const filteredList = await Promise.all(list.map(transform)).then((items) => items.filter(filter));
|
|
218
|
-
result.push(...filteredList.slice(0,
|
|
87
|
+
result.push(...filteredList.slice(0, shortfall));
|
|
88
|
+
scanned += list.length;
|
|
219
89
|
if (list.length < nextPageLength) {
|
|
220
90
|
break;
|
|
221
91
|
}
|
package/dist/db/index.d.ts
CHANGED
|
@@ -10,4 +10,6 @@ export type { PgFilter, SqlFilter } from './pg/map/queryTypes';
|
|
|
10
10
|
export { combine, createdAtBetween, documentKeyAfter, documentKeyBefore, edgeFilters, eventTimeFilters, groupFilters, isSqlFilter, notificationFilters, pgSql, postFilters, profileFilters, } from './pg/filters';
|
|
11
11
|
export { computedFields, sorts } from './pg/queries';
|
|
12
12
|
export declare const allpeepDb: () => Promise<OpenpeepsDatabase>;
|
|
13
|
+
/** Clear the cached DB after `closePostgres()` so the next call re-inits. */
|
|
14
|
+
export declare const resetAllpeepDb: () => void;
|
|
13
15
|
export declare const database: () => Promise<PgDb>;
|
package/dist/db/index.js
CHANGED
|
@@ -12,4 +12,8 @@ export const allpeepDb = () => {
|
|
|
12
12
|
}
|
|
13
13
|
return dbPromise;
|
|
14
14
|
};
|
|
15
|
+
/** Clear the cached DB after `closePostgres()` so the next call re-inits. */
|
|
16
|
+
export const resetAllpeepDb = () => {
|
|
17
|
+
dbPromise = undefined;
|
|
18
|
+
};
|
|
15
19
|
export const database = () => allpeepDb().then(({ db }) => db);
|
package/dist/db/init.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { logger } from '../log/index.js';
|
|
2
|
-
import { maybeAutoMigrateFromArango } from './migration/autoMigrate.js';
|
|
3
2
|
import { initPostgres } from './pg/client.js';
|
|
4
3
|
const log = logger('openpeeps:db');
|
|
5
4
|
export const initDb = async () => {
|
|
6
5
|
log.info('Initializing Postgres');
|
|
6
|
+
if (process.env.AUTO_MIGRATE_FROM_ARANGO === 'true') {
|
|
7
|
+
log.warn('AUTO_MIGRATE_FROM_ARANGO is ignored at runtime. Use @openpeepshq/arango-migrate (archive/arango-migrate) for Arango cutover.');
|
|
8
|
+
}
|
|
7
9
|
const db = await initPostgres();
|
|
8
|
-
await maybeAutoMigrateFromArango();
|
|
9
10
|
return { db };
|
|
10
11
|
};
|
|
@@ -1,6 +1,3 @@
|
|
|
1
1
|
declare const isUndefinedTableError: (err: unknown) => boolean;
|
|
2
2
|
export declare const tableCount: (collection: string) => Promise<number>;
|
|
3
|
-
export declare const isPostgresEmpty: () => Promise<boolean>;
|
|
4
3
|
export { isUndefinedTableError };
|
|
5
|
-
export declare const isArangoAvailable: () => Promise<boolean>;
|
|
6
|
-
export declare const arangoHasSourceData: () => Promise<boolean>;
|
|
@@ -1,12 +1,6 @@
|
|
|
1
|
-
import { aql, Database } from 'arangojs';
|
|
2
1
|
import { getTableName, sql } from 'drizzle-orm';
|
|
3
|
-
import { logger } from '../../log/index.js';
|
|
4
2
|
import { pgDb } from '../pg/client.js';
|
|
5
3
|
import { getTableForCollection } from '../pg/map/registry.js';
|
|
6
|
-
import { connectArango } from './exportArango.js';
|
|
7
|
-
import { arangoConfig, DOCUMENT_IMPORT_ORDER, EDGE_IMPORT_ORDER, } from './shared.js';
|
|
8
|
-
const log = logger('core:migration:detect');
|
|
9
|
-
const ARANGO_SOURCE_COLLECTIONS = ['accounts', 'profiles', 'posts'];
|
|
10
4
|
const isUndefinedTableError = (err) => {
|
|
11
5
|
const candidates = [
|
|
12
6
|
err,
|
|
@@ -36,52 +30,4 @@ export const tableCount = async (collection) => {
|
|
|
36
30
|
throw err;
|
|
37
31
|
}
|
|
38
32
|
};
|
|
39
|
-
export const isPostgresEmpty = async () => {
|
|
40
|
-
for (const collection of [
|
|
41
|
-
...DOCUMENT_IMPORT_ORDER,
|
|
42
|
-
...EDGE_IMPORT_ORDER,
|
|
43
|
-
]) {
|
|
44
|
-
if ((await tableCount(collection)) > 0) {
|
|
45
|
-
return false;
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
return true;
|
|
49
|
-
};
|
|
50
33
|
export { isUndefinedTableError };
|
|
51
|
-
export const isArangoAvailable = async () => {
|
|
52
|
-
const config = arangoConfig();
|
|
53
|
-
const systemDb = new Database({ url: config.url, databaseName: '_system' });
|
|
54
|
-
try {
|
|
55
|
-
return Boolean(await systemDb.availability());
|
|
56
|
-
}
|
|
57
|
-
catch (_a) {
|
|
58
|
-
return false;
|
|
59
|
-
}
|
|
60
|
-
};
|
|
61
|
-
export const arangoHasSourceData = async () => {
|
|
62
|
-
if (!(await isArangoAvailable())) {
|
|
63
|
-
return false;
|
|
64
|
-
}
|
|
65
|
-
const config = arangoConfig();
|
|
66
|
-
if (config.databaseName) {
|
|
67
|
-
const systemDb = new Database(Object.assign(Object.assign({}, config), { databaseName: '_system' }));
|
|
68
|
-
if (!(await systemDb.database(config.databaseName).exists())) {
|
|
69
|
-
log.info('Arango database %s does not exist; skipping auto migration', config.databaseName);
|
|
70
|
-
return false;
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
const db = connectArango();
|
|
74
|
-
for (const collectionName of ARANGO_SOURCE_COLLECTIONS) {
|
|
75
|
-
if (!(await db.collection(collectionName).exists())) {
|
|
76
|
-
continue;
|
|
77
|
-
}
|
|
78
|
-
const cursor = await db.query(aql `
|
|
79
|
-
RETURN LENGTH(FOR doc IN ${db.collection(collectionName)} LIMIT 1 RETURN 1)
|
|
80
|
-
`);
|
|
81
|
-
const hasDocuments = (await cursor.next()) === 1;
|
|
82
|
-
if (hasDocuments) {
|
|
83
|
-
return true;
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
return false;
|
|
87
|
-
};
|
|
@@ -12,7 +12,7 @@ export declare const importAllArangoCollections: (collectionsDir: string) => Pro
|
|
|
12
12
|
imported: Record<string, number>;
|
|
13
13
|
total: number;
|
|
14
14
|
}>;
|
|
15
|
-
export declare const importAllPostgresCollections: (collectionsDir: string) => Promise<{
|
|
15
|
+
export declare const importAllPostgresCollections: (collectionsDir: string, schemaVersionFromBackup?: string) => Promise<{
|
|
16
16
|
imported: Record<string, number>;
|
|
17
17
|
total: number;
|
|
18
18
|
}>;
|
|
@@ -5,7 +5,7 @@ import { join } from 'node:path';
|
|
|
5
5
|
import { getTableName, sql } from 'drizzle-orm';
|
|
6
6
|
import { logger } from '../../log/index.js';
|
|
7
7
|
import { pgDb } from '../pg/client.js';
|
|
8
|
-
import { runMigrations } from '../pg/migrate.js';
|
|
8
|
+
import { resetAndMigrateToSchemaVersion, resolveRestoreSchemaVersion, runMigrations, } from '../pg/migrate.js';
|
|
9
9
|
import { documentRegistry, edgeRegistry, getTableForCollection, } from '../pg/map/registry.js';
|
|
10
10
|
import { arangoDocToDocumentRow, arangoDocToEdgeRow, buildPostCreatorIdByPostId, isEdgeCollection, normalizeImportId, } from './transform.js';
|
|
11
11
|
import { BATCH_SIZE, DOCUMENT_IMPORT_ORDER, EDGE_IMPORT_ORDER, readJsonl, } from './shared.js';
|
|
@@ -230,27 +230,41 @@ export const importPostgresRowCollection = async (collection, collectionsDir) =>
|
|
|
230
230
|
return imported;
|
|
231
231
|
};
|
|
232
232
|
const sumImported = (imported) => Object.values(imported).reduce((sum, count) => sum + count, 0);
|
|
233
|
-
|
|
234
|
-
|
|
233
|
+
const prepareSchemaForRestore = async (databaseType, schemaVersionFromBackup) => {
|
|
234
|
+
const schemaVersion = resolveRestoreSchemaVersion(databaseType, schemaVersionFromBackup);
|
|
235
|
+
log.info('Preparing %s restore at schema %s', databaseType, schemaVersion);
|
|
236
|
+
await resetAndMigrateToSchemaVersion(schemaVersion);
|
|
237
|
+
// 0006 added a unique (from_id, to_id) on post_seen; that was wrong for
|
|
238
|
+
// impressions. Drop it before import so pre-0007 backups with duplicate
|
|
239
|
+
// view rows can restore. 0007 (and later) drop it permanently.
|
|
240
|
+
await pgDb().execute(sql.raw('DROP INDEX IF EXISTS "post_seen_from_to_unique"'));
|
|
235
241
|
await truncateAllTables();
|
|
242
|
+
};
|
|
243
|
+
export const importAllArangoCollections = async (collectionsDir) => {
|
|
244
|
+
await prepareSchemaForRestore('arango');
|
|
236
245
|
const imported = {};
|
|
237
246
|
const context = {
|
|
238
247
|
postCreatorIdByPostId: await buildPostCreatorIdByPostId(collectionsDir),
|
|
239
248
|
hashtagIdRemap: new Map(),
|
|
240
249
|
};
|
|
250
|
+
// Skip dataMigrations — Arango-era migration ledger is unused on Postgres.
|
|
241
251
|
for (const collection of DOCUMENT_IMPORT_ORDER) {
|
|
252
|
+
if (collection === 'dataMigrations') {
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
242
255
|
imported[collection] = await importArangoCollection(collection, collectionsDir, context);
|
|
243
256
|
}
|
|
244
257
|
for (const collection of EDGE_IMPORT_ORDER) {
|
|
245
258
|
imported[collection] = await importArangoCollection(collection, collectionsDir, context);
|
|
246
259
|
}
|
|
260
|
+
log.info('Arango rows loaded; migrating schema forward to latest');
|
|
261
|
+
await runMigrations();
|
|
247
262
|
const total = sumImported(imported);
|
|
248
263
|
log.info('Arango JSONL import complete: %d rows across %d collections', total, Object.keys(imported).filter((key) => imported[key] > 0).length);
|
|
249
264
|
return { imported, total };
|
|
250
265
|
};
|
|
251
|
-
export const importAllPostgresCollections = async (collectionsDir) => {
|
|
252
|
-
await
|
|
253
|
-
await truncateAllTables();
|
|
266
|
+
export const importAllPostgresCollections = async (collectionsDir, schemaVersionFromBackup) => {
|
|
267
|
+
await prepareSchemaForRestore('postgres', schemaVersionFromBackup);
|
|
254
268
|
const imported = {};
|
|
255
269
|
for (const collection of DOCUMENT_IMPORT_ORDER) {
|
|
256
270
|
imported[collection] = await importPostgresRowCollection(collection, collectionsDir);
|
|
@@ -258,6 +272,8 @@ export const importAllPostgresCollections = async (collectionsDir) => {
|
|
|
258
272
|
for (const collection of EDGE_IMPORT_ORDER) {
|
|
259
273
|
imported[collection] = await importPostgresRowCollection(collection, collectionsDir);
|
|
260
274
|
}
|
|
275
|
+
log.info('Postgres rows loaded; ensuring schema is at latest');
|
|
276
|
+
await runMigrations();
|
|
261
277
|
const total = sumImported(imported);
|
|
262
278
|
log.info('Postgres JSONL import complete: %d rows across %d collections', total, Object.keys(imported).filter((key) => imported[key] > 0).length);
|
|
263
279
|
return { imported, total };
|
|
@@ -22,10 +22,6 @@ export type MigrationManifest = {
|
|
|
22
22
|
postIds: string;
|
|
23
23
|
};
|
|
24
24
|
};
|
|
25
|
-
export declare const arangoConfig: () => {
|
|
26
|
-
url: string;
|
|
27
|
-
databaseName: string | undefined;
|
|
28
|
-
};
|
|
29
25
|
export declare const sha256: (value: string) => string;
|
|
30
26
|
export declare const sortedChecksum: (values: string[]) => string;
|
|
31
27
|
export declare const readJsonl: (filePath: string) => Promise<Record<string, unknown>[]>;
|
|
@@ -67,13 +67,6 @@ export const EDGE_IMPORT_ORDER = [
|
|
|
67
67
|
'inviteLinkRedeemers',
|
|
68
68
|
'jamRecordings',
|
|
69
69
|
];
|
|
70
|
-
export const arangoConfig = () => {
|
|
71
|
-
var _a;
|
|
72
|
-
return ({
|
|
73
|
-
url: (_a = process.env.DB_URL) !== null && _a !== void 0 ? _a : 'http://localhost:8529',
|
|
74
|
-
databaseName: process.env.DB_NAME,
|
|
75
|
-
});
|
|
76
|
-
};
|
|
77
70
|
export const sha256 = (value) => createHash('sha256').update(value).digest('hex');
|
|
78
71
|
export const sortedChecksum = (values) => sha256(values.filter(Boolean).sort().join('\n'));
|
|
79
72
|
export const readJsonl = async (filePath) => {
|
|
@@ -13,6 +13,8 @@ export declare const buildPostCreatorIdByPostId: (collectionsDir: string) => Pro
|
|
|
13
13
|
* later via an Arango-only data migration that never runs on Postgres restores.
|
|
14
14
|
*/
|
|
15
15
|
export declare const capabilitiesFromLegacyGroupFlags: (data: Record<string, unknown>) => Record<string, unknown> | undefined;
|
|
16
|
+
export declare const normalizeGroupMembershipRoles: (roles: unknown) => unknown;
|
|
17
|
+
export declare const normalizeGroupCapabilityMap: (capabilities: Record<string, unknown>) => Record<string, unknown>;
|
|
16
18
|
export declare const arangoDocToDocumentRow: (collection: string, doc: Record<string, unknown>, context?: ImportContext) => Record<string, unknown>;
|
|
17
19
|
export declare const arangoDocToEdgeRow: (collection: string, doc: Record<string, unknown>) => Record<string, unknown>;
|
|
18
20
|
export declare const isEdgeCollection: (collection: string) => boolean;
|
|
@@ -13,6 +13,7 @@ import { access } from 'node:fs/promises';
|
|
|
13
13
|
import { constants } from 'node:fs';
|
|
14
14
|
import { join } from 'node:path';
|
|
15
15
|
import { groupCapabilityTemplates } from '@openpeepshq/common/lib';
|
|
16
|
+
import { defaultGroupAdminCapabilityAdds } from '@openpeepshq/common/types';
|
|
16
17
|
import { documentRegistry, edgeRegistry, parseDocRef, } from '../pg/map/registry.js';
|
|
17
18
|
import { nowIso } from '../pg/mappers.js';
|
|
18
19
|
import { uuidv7 } from 'uuidv7';
|
|
@@ -110,6 +111,22 @@ export const capabilitiesFromLegacyGroupFlags = (data) => {
|
|
|
110
111
|
: privateGroup;
|
|
111
112
|
return template.capabilities;
|
|
112
113
|
};
|
|
114
|
+
export const normalizeGroupMembershipRoles = (roles) => {
|
|
115
|
+
if (!Array.isArray(roles))
|
|
116
|
+
return roles;
|
|
117
|
+
return [...new Set(roles.map((role) => (role === 'admin' ? 'owner' : role)))];
|
|
118
|
+
};
|
|
119
|
+
export const normalizeGroupCapabilityMap = (capabilities) => {
|
|
120
|
+
const next = Object.assign({}, capabilities);
|
|
121
|
+
if (next.admin && !next.owner) {
|
|
122
|
+
next.owner = next.admin;
|
|
123
|
+
delete next.admin;
|
|
124
|
+
}
|
|
125
|
+
if (!next.admin) {
|
|
126
|
+
next.admin = { add: [...defaultGroupAdminCapabilityAdds] };
|
|
127
|
+
}
|
|
128
|
+
return next;
|
|
129
|
+
};
|
|
113
130
|
export const arangoDocToDocumentRow = (collection, doc, context) => {
|
|
114
131
|
var _a, _b, _e, _f, _g, _h, _j, _k, _m, _o, _p, _q, _r, _s;
|
|
115
132
|
const model = arangoDocToModel(doc);
|
|
@@ -177,6 +194,9 @@ export const arangoDocToDocumentRow = (collection, doc, context) => {
|
|
|
177
194
|
if (capabilities) {
|
|
178
195
|
body.capabilities = capabilities;
|
|
179
196
|
}
|
|
197
|
+
else if (body.capabilities && typeof body.capabilities === 'object') {
|
|
198
|
+
body.capabilities = normalizeGroupCapabilityMap(body.capabilities);
|
|
199
|
+
}
|
|
180
200
|
}
|
|
181
201
|
return Object.assign(Object.assign({ id }, scalars), { body,
|
|
182
202
|
createdAt,
|
|
@@ -197,6 +217,9 @@ export const arangoDocToEdgeRow = (collection, doc) => {
|
|
|
197
217
|
const model = arangoDocToModel(doc);
|
|
198
218
|
const { createdAt, updatedAt } = timestampsFromModel(model);
|
|
199
219
|
const { createdAt: _c, updatedAt: _u, id: _id } = model, body = __rest(model, ["createdAt", "updatedAt", "id"]);
|
|
220
|
+
if (collection === 'userGroups' && 'roles' in body) {
|
|
221
|
+
body.roles = normalizeGroupMembershipRoles(body.roles);
|
|
222
|
+
}
|
|
200
223
|
return {
|
|
201
224
|
id: (_b = normalizeImportId((_a = doc._key) !== null && _a !== void 0 ? _a : doc.id)) !== null && _b !== void 0 ? _b : String((_e = doc._key) !== null && _e !== void 0 ? _e : doc.id),
|
|
202
225
|
fromId: (_f = normalizeImportId(fromRef.id)) !== null && _f !== void 0 ? _f : fromRef.id,
|
package/dist/db/pg/client.js
CHANGED
|
@@ -95,6 +95,10 @@ export const closePostgres = async () => {
|
|
|
95
95
|
await (pool === null || pool === void 0 ? void 0 : pool.end());
|
|
96
96
|
pool = undefined;
|
|
97
97
|
dbInstance = undefined;
|
|
98
|
+
// DROP SCHEMA / pool.end leaves allpeepDb() holding a dead Pool; next caller
|
|
99
|
+
// must re-run initDb() (e.g. setDefaultRoles after backup restore).
|
|
100
|
+
const { resetAllpeepDb } = await import('../index.js');
|
|
101
|
+
resetAllpeepDb();
|
|
98
102
|
};
|
|
99
103
|
/**
|
|
100
104
|
* Drop and recreate app schemas. Drizzle stores its migration journal in
|
|
@@ -6,5 +6,5 @@ export const edgeFilters = {
|
|
|
6
6
|
entryType: (type) => pgSql(eq(sql `${entries.body}->>'type'`, type)),
|
|
7
7
|
entryCreated: (start, end) => createdAtBetween(entries, start, end),
|
|
8
8
|
bodyFieldEq: (table, field, value) => pgSql(eq(sql `${table.body}->>${field}`, value)),
|
|
9
|
-
|
|
9
|
+
groupOwnerRole: () => pgSql(sql `${userGroups.body}->'roles' ? 'owner'`),
|
|
10
10
|
};
|
|
@@ -4,6 +4,7 @@ export declare const postFilters: {
|
|
|
4
4
|
isDirect: () => SqlFilter;
|
|
5
5
|
hasJam: () => SqlFilter;
|
|
6
6
|
creatorId: (id: string) => SqlFilter;
|
|
7
|
+
myFeed: (profileId: string, followedProfileIds: string[], groupIds: string[]) => SqlFilter;
|
|
7
8
|
type: (type: string) => SqlFilter;
|
|
8
9
|
replyCount: (op: "==" | "!=" | ">" | ">=" | "<" | "<=", count: number) => SqlFilter;
|
|
9
10
|
replyCountZero: () => SqlFilter;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { and, eq, isNotNull, ne, or, sql } from 'drizzle-orm';
|
|
1
|
+
import { and, eq, inArray, isNotNull, ne, or, sql } from 'drizzle-orm';
|
|
2
2
|
import { posts } from '../schema/documents.js';
|
|
3
|
+
import { postGroups } from '../schema/edges.js';
|
|
3
4
|
import { postHasYesOrMaybeRsvpExpr, postReplyCountExpr, } from '../queries/activity.js';
|
|
4
5
|
import { compareCount } from './common.js';
|
|
5
6
|
import { pgSql } from './types.js';
|
|
@@ -11,6 +12,15 @@ export const postFilters = {
|
|
|
11
12
|
isDirect: () => pgSql(eq(posts.visibility, 'direct')),
|
|
12
13
|
hasJam: () => pgSql(isNotNull(sql `${posts.body}->'jam'`)),
|
|
13
14
|
creatorId: (id) => pgSql(eq(posts.creatorId, id)),
|
|
15
|
+
myFeed: (profileId, followedProfileIds, groupIds) => {
|
|
16
|
+
const followed = followedProfileIds.length
|
|
17
|
+
? inArray(posts.creatorId, followedProfileIds)
|
|
18
|
+
: sql `false`;
|
|
19
|
+
const groupMemberPost = groupIds.length
|
|
20
|
+
? and(eq(posts.visibility, 'group'), sql `EXISTS (SELECT 1 FROM ${postGroups} WHERE ${postGroups.fromId} = ${posts.id}::text AND ${inArray(postGroups.toId, groupIds)})`)
|
|
21
|
+
: sql `false`;
|
|
22
|
+
return pgSql(or(eq(posts.creatorId, profileId), followed, groupMemberPost));
|
|
23
|
+
},
|
|
14
24
|
type: (type) => pgSql(eq(posts.type, type)),
|
|
15
25
|
replyCount: (op, count) => pgSql(compareCount(postsReplyCountExpr, op, count)),
|
|
16
26
|
replyCountZero: () => postFilters.replyCount('==', 0),
|
|
@@ -438,6 +438,11 @@ export const filterToSql = (collection, table, filter) => {
|
|
|
438
438
|
const matches = Array.isArray(filter.matches)
|
|
439
439
|
? filter.matches
|
|
440
440
|
: [filter.matches];
|
|
441
|
+
// An empty match list is a valid predicate that can never match. Keeping
|
|
442
|
+
// it in SQL prevents an empty OR branch from demoting the whole filter to
|
|
443
|
+
// post-hydration evaluation.
|
|
444
|
+
if (!matches.length)
|
|
445
|
+
return sql `false`;
|
|
441
446
|
const parts = matches
|
|
442
447
|
.map((match) => matchToSql(collection, table, match))
|
|
443
448
|
.filter(Boolean);
|
|
@@ -18,7 +18,7 @@ export declare const executeCount: (db: PgDb, mapData: MapData<object, object>)
|
|
|
18
18
|
export declare const executeFirst: (db: PgDb, mapData: MapData<object, object>) => Promise<Doc | undefined>;
|
|
19
19
|
export declare const relationsFrom: (db: PgDb, start: {
|
|
20
20
|
id: string;
|
|
21
|
-
},
|
|
21
|
+
}, _parentCollection: string, relation: Relation & {
|
|
22
22
|
mapping: MapData<object, object>;
|
|
23
23
|
}) => Promise<Doc[]>;
|
|
24
24
|
export declare const evaluateDerived: (db: PgDb, doc: Doc, derived: DerivedProperty) => Promise<unknown>;
|