-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathpublishNode.ts
More file actions
526 lines (508 loc) · 16.9 KB
/
publishNode.ts
File metadata and controls
526 lines (508 loc) · 16.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
import type { FrontMatterCache, TFile } from "obsidian";
import type { default as DiscourseGraphPlugin } from "~/index";
import { getLoggedInClient, getSupabaseContext } from "./supabaseContext";
import type { DGSupabaseClient } from "@repo/database/lib/client";
import {
getRelationsForNodeInstanceId,
getFileForNodeInstanceId,
getFileForNodeInstanceIds,
loadRelations,
saveRelations,
type RelationsFile,
} from "./relationsStore";
import type { RelationInstance } from "~/types";
import { getAvailableGroupIds } from "./importNodes";
import {
syncAllNodesAndRelations,
syncPublishedNodeAssets,
} from "./syncDgNodesToSupabase";
import type { DiscourseNodeInVault } from "./getDiscourseNodes";
import type { SupabaseContext } from "./supabaseContext";
import type { TablesInsert } from "@repo/database/dbTypes";
const publishSchema = async ({
client,
spaceId,
nodeTypeId,
groupId,
}: {
client: DGSupabaseClient;
spaceId: number;
nodeTypeId: string;
groupId: string;
}): Promise<void> => {
// Check if schema exists
const schemaResponse = await client
.from("Concept")
.select("source_local_id")
.eq("space_id", spaceId)
.eq("is_schema", true)
.eq("source_local_id", nodeTypeId)
.maybeSingle();
if (schemaResponse.error) {
console.error("Error checking schema existence:", schemaResponse.error);
return; // Don't fail node publishing if schema check fails
}
if (!schemaResponse.data) {
return; // Schema doesn't exist, skip publishing
}
// Publish schema to group via ResourceAccess
const publishResponse = await client.from("ResourceAccess").upsert(
{
/* eslint-disable @typescript-eslint/naming-convention */
account_uid: groupId,
source_local_id: nodeTypeId,
space_id: spaceId,
/* eslint-enable @typescript-eslint/naming-convention */
},
{ ignoreDuplicates: true },
);
if (publishResponse.error && publishResponse.error.code !== "23505") {
// 23505 is duplicate key, which counts as a success.
console.error("Error publishing schema:", publishResponse.error);
// Don't throw - schema publishing failure shouldn't block node publishing
}
};
const intersection = <T>(set1: Set<T>, set2: Set<T>): Set<T> => {
// @ts-expect-error - Set.intersection is ES2025 feature
if (set1.intersection) return set1.intersection(set2); // eslint-disable-line
const r: Set<T> = new Set();
for (const x of set1) {
if (set2.has(x)) r.add(x);
}
return r;
};
const difference = <T>(set1: Set<T>, set2: Set<T>): Set<T> => {
// @ts-expect-error - Set.difference is ES2025 feature
if (set1.difference) return set1.difference(set2); // eslint-disable-line
const result = new Set(set1);
if (set1.size <= set2.size)
for (const e of set1) {
if (set2.has(e)) result.delete(e);
}
else
for (const e of set2) {
if (result.has(e)) result.delete(e);
}
return result;
};
export const publishNewRelation = async (
plugin: DiscourseGraphPlugin,
relation: RelationInstance,
): Promise<boolean> => {
const client = await getLoggedInClient(plugin);
if (!client) throw new Error("Cannot get client");
const context = await getSupabaseContext(plugin);
if (!context) throw new Error("Cannot get context");
const sourceFile = getFileForNodeInstanceId(plugin, relation.source);
const destinationFile = getFileForNodeInstanceId(
plugin,
relation.destination,
);
if (!sourceFile || !destinationFile) return false;
const sourceFm =
plugin.app.metadataCache.getFileCache(sourceFile)?.frontmatter;
const destinationFm =
plugin.app.metadataCache.getFileCache(destinationFile)?.frontmatter;
if (!sourceFm || !destinationFm) return false;
const sourceGroups = sourceFm.publishedToGroups as string[] | undefined;
const destinationGroups = destinationFm.publishedToGroups as
| string[]
| undefined;
if (!Array.isArray(sourceGroups) || !Array.isArray(destinationGroups))
return false;
const relationTriples = plugin.settings.discourseRelations ?? [];
const triple = relationTriples.find(
(triple) =>
triple.relationshipTypeId === relation.type &&
triple.sourceId === sourceFm.nodeTypeId &&
triple.destinationId === destinationFm.nodeTypeId,
);
if (!triple) return false;
const resourceIds = [relation.id, relation.type, triple.id];
const myGroups = await getAvailableGroupIds(client);
const targetGroups = intersection(
new Set(myGroups),
intersection(
new Set<string>(sourceGroups),
new Set<string>(destinationGroups),
),
);
if (!targetGroups.size) return false;
// in that case, sync all relations (only) before publishing
await syncAllNodesAndRelations(plugin, context, true);
const entries = [];
for (const group of targetGroups) {
for (const id of resourceIds) {
entries.push({
/* eslint-disable @typescript-eslint/naming-convention */
account_uid: group,
source_local_id: id,
space_id: context.spaceId,
/* eslint-enable @typescript-eslint/naming-convention */
});
}
}
const publishResponse = await client
.from("ResourceAccess")
.upsert(entries, { ignoreDuplicates: true });
if (publishResponse.error && publishResponse.error.code !== "23505")
throw publishResponse.error;
relation.publishedToGroupId = [
...new Set([
...(relation.publishedToGroupId || []),
...targetGroups.values(),
]).values(),
];
return true;
};
export const publishNodeRelations = async ({
plugin,
client,
nodeId,
myGroup,
spaceId,
}: {
plugin: DiscourseGraphPlugin;
client: DGSupabaseClient;
nodeId: string;
myGroup: string;
spaceId: number;
}): Promise<void> => {
const relations = await getRelationsForNodeInstanceId(plugin, nodeId);
const resourceIds: Set<string> = new Set();
const relationTriples = plugin.settings.discourseRelations ?? [];
const relevantNodeIds: Set<string> = new Set();
relations.map((relation) => {
relevantNodeIds.add(relation.source);
relevantNodeIds.add(relation.destination);
});
const relevantNodeFiles = getFileForNodeInstanceIds(plugin, relevantNodeIds);
const relevantNodeTypeById: Record<string, string | undefined> = {};
Object.entries(relevantNodeFiles).map(([id, file]: [string, TFile]) => {
const fm = plugin.app.metadataCache.getFileCache(file)?.frontmatter;
if (fm === undefined) return;
if (fm.nodeInstanceId !== nodeId) {
// check if published to same group.
// Note: current node's pub status not in cache yet!
if (!Array.isArray(fm.publishedToGroups)) return;
const publishedToGroups: string[] =
(fm.publishedToGroups as string[]) || [];
if (!publishedToGroups.includes(myGroup)) return;
}
relevantNodeTypeById[id] = fm.nodeTypeId as string;
});
relations.map((relation) => {
if ((relation.publishedToGroupId ?? []).includes(myGroup)) return;
const triple = relationTriples.find(
(triple) =>
triple.relationshipTypeId === relation.type &&
triple.sourceId === relevantNodeTypeById[relation.source] &&
triple.destinationId === relevantNodeTypeById[relation.destination],
);
if (triple) {
resourceIds.add(relation.id);
resourceIds.add(relation.type);
resourceIds.add(triple.id);
}
});
if (resourceIds.size === 0) return;
const publishResponse = await client.from("ResourceAccess").upsert(
[...resourceIds.values()].map((sourceLocalId: string) => ({
/* eslint-disable @typescript-eslint/naming-convention */
account_uid: myGroup,
source_local_id: sourceLocalId,
space_id: spaceId,
/* eslint-enable @typescript-eslint/naming-convention */
})),
{ ignoreDuplicates: true },
);
if (publishResponse.error && publishResponse.error.code !== "23505")
throw publishResponse.error;
const relData = await loadRelations(plugin);
let dataChanged = false;
relations
.filter((rel) => resourceIds.has(rel.id))
.map((rel) => {
const savedRel = relData.relations[rel.id];
if (!savedRel) return;
const publishedTo = savedRel.publishedToGroupId;
if (!publishedTo) {
savedRel.publishedToGroupId = [myGroup];
dataChanged = true;
} else if (!publishedTo.includes(myGroup)) {
publishedTo.push(myGroup);
dataChanged = true;
}
});
if (dataChanged) await saveRelations(plugin, relData);
};
export const publishNode = async ({
plugin,
file,
frontmatter,
}: {
plugin: DiscourseGraphPlugin;
file: TFile;
frontmatter: FrontMatterCache;
}): Promise<void> => {
const client = await getLoggedInClient(plugin);
if (!client) throw new Error("Cannot get client");
const myGroups = new Set(await getAvailableGroupIds(client));
if (myGroups.size === 0) throw new Error("Cannot get group");
const existingPublish =
(frontmatter.publishedToGroups as undefined | string[]) || [];
// Hopefully temporary workaround for sync bug
await syncAllNodesAndRelations(plugin);
const commonGroups = existingPublish.filter((g) => myGroups.has(g));
// temporary single-group assumption
const myGroup = (commonGroups.length > 0 ? commonGroups : [...myGroups])[0]!;
return await publishNodeToGroup({ plugin, file, frontmatter, myGroup });
};
export const ensurePublishedRelationsAccuracy = async ({
client,
context,
plugin,
allNodesById,
relationInstancesData,
}: {
client: DGSupabaseClient;
context: SupabaseContext;
plugin: DiscourseGraphPlugin;
allNodesById: Record<string, DiscourseNodeInVault>;
relationInstancesData: RelationsFile;
}): Promise<void> => {
const myGroups = await getAvailableGroupIds(client);
const relationInstances = Object.values(relationInstancesData.relations);
const syncedRelationIdsResult = await client
.from("Concept")
.select("source_local_id")
.eq("space_id", context.spaceId)
.eq("is_schema", false)
.gt("arity", 0);
if (syncedRelationIdsResult.error) {
console.error(
"Could not get synced relation ids",
syncedRelationIdsResult.error,
);
return;
}
const syncedRelationIds = new Set(
(syncedRelationIdsResult.data || []).map((x) => x.source_local_id!),
);
// Also a good time to look at orphan relations
const existingRelationIds = new Set(relationInstances.map((r) => r.id));
const orphanRelationIds = difference(syncedRelationIds, existingRelationIds);
if (orphanRelationIds.size) {
const r = await client
.from("Concept")
.delete()
.eq("space_id", context.spaceId)
.in("source_local_id", [...orphanRelationIds]);
if (!r.error) {
for (const id of orphanRelationIds) {
syncedRelationIds.delete(id);
}
}
}
let changed = false;
const missingPublishRecords: TablesInsert<"ResourceAccess">[] = [];
for (const group of myGroups) {
const publishableRelations = relationInstances.filter(
(r) =>
!r.importedFromRid &&
syncedRelationIds.has(r.id) &&
(
(allNodesById[r.source]?.frontmatter?.publishedToGroups as
| string[]
| undefined) || []
).indexOf(group) >= 0 &&
(
(allNodesById[r.destination]?.frontmatter?.publishedToGroups as
| string[]
| undefined) || []
).indexOf(group) >= 0,
);
const publishableRelationIds = new Set(
publishableRelations.map((x) => x.id),
);
const publishedIds = await client
.from("ResourceAccess")
.select("source_local_id")
.eq("account_uid", group)
.eq("space_id", context.spaceId);
if (publishedIds.error) {
console.error("Could not get synced relation ids", publishedIds.error);
continue;
}
const publishedRelationIds = intersection(
syncedRelationIds,
new Set((publishedIds.data || []).map((x) => x.source_local_id)),
);
const missingPublishableIds = difference(
publishableRelationIds,
publishedRelationIds,
);
if (missingPublishableIds.size > 0) {
missingPublishRecords.push(
/* eslint-disable @typescript-eslint/naming-convention */
...[...missingPublishableIds].map((source_local_id) => ({
source_local_id,
space_id: context.spaceId,
account_uid: group,
})),
/* eslint-enable @typescript-eslint/naming-convention */
);
}
const extraPublishableIds = difference(
publishedRelationIds,
publishableRelationIds,
);
if (extraPublishableIds.size > 0) {
const r = await client
.from("ResourceAccess")
.delete()
.eq("account_uid", group)
.eq("space_id", context.spaceId)
.in("source_local_id", [...extraPublishableIds]);
if (r.error) console.error(r.error);
else {
for (const id of extraPublishableIds) {
const rel = relationInstancesData.relations[id];
const pos = (rel?.publishedToGroupId || []).indexOf(group);
if (pos >= 0) {
rel!.publishedToGroupId!.splice(pos, 1);
changed = true;
}
}
}
}
}
if (missingPublishRecords.length > 0) {
const r = await client.from("ResourceAccess").upsert(missingPublishRecords);
if (r.error) console.error(r.error);
else {
for (const record of missingPublishRecords) {
const rel = relationInstancesData.relations[record.source_local_id];
const group = record.account_uid;
const pos = (rel?.publishedToGroupId || []).indexOf(group);
if (rel && pos < 0) {
if (rel.publishedToGroupId === undefined) rel.publishedToGroupId = [];
rel.publishedToGroupId.push(group);
changed = true;
}
}
}
}
if (changed) {
await saveRelations(plugin, relationInstancesData);
}
};
export const publishNodeToGroup = async ({
plugin,
file,
frontmatter,
myGroup,
}: {
plugin: DiscourseGraphPlugin;
file: TFile;
frontmatter: FrontMatterCache;
myGroup: string;
}): Promise<void> => {
const nodeId = frontmatter.nodeInstanceId as string | undefined;
if (!nodeId) throw new Error("Please sync the node first");
const context = await getSupabaseContext(plugin);
if (!context) throw new Error("Cannot get context");
const spaceId = context.spaceId;
const client = await getLoggedInClient(plugin);
if (!client) throw new Error("Cannot get client");
const existingPublish =
(frontmatter.publishedToGroups as undefined | string[]) || [];
const idResponse = await client
.from("my_contents")
.select("last_modified")
.eq("source_local_id", nodeId)
.eq("space_id", spaceId)
.eq("variant", "full")
.maybeSingle();
if (idResponse.error || !idResponse.data) {
throw idResponse.error || new Error("no data while fetching node");
}
const lastModifiedDb = new Date(
idResponse.data.last_modified + "Z",
).getTime();
try {
await publishNodeRelations({ plugin, client, nodeId, myGroup, spaceId });
} catch (error) {
// do not fail to publish node for that reason
console.error("Could not publish relations", error);
}
const embeds = plugin.app.metadataCache.getFileCache(file)?.embeds ?? [];
const attachments = embeds
.map(({ link }) => {
const attachment = plugin.app.metadataCache.getFirstLinkpathDest(
link,
file.path,
);
return attachment;
})
.filter((a) => !!a);
const lastModified = Math.max(
file.stat.mtime,
...attachments.map((a) => a.stat.mtime),
);
const skipPublishAccess =
existingPublish.includes(myGroup) && lastModified <= lastModifiedDb;
if (!skipPublishAccess) {
const publishSpaceResponse = await client.from("SpaceAccess").upsert(
{
/* eslint-disable @typescript-eslint/naming-convention */
account_uid: myGroup,
space_id: spaceId,
/* eslint-enable @typescript-eslint/naming-convention */
permissions: "partial",
},
{ ignoreDuplicates: true },
);
if (
publishSpaceResponse.error &&
publishSpaceResponse.error.code !== "23505"
)
throw publishSpaceResponse.error;
const publishResponse = await client.from("ResourceAccess").upsert(
{
/* eslint-disable @typescript-eslint/naming-convention */
account_uid: myGroup,
source_local_id: nodeId,
space_id: spaceId,
/* eslint-enable @typescript-eslint/naming-convention */
},
{ ignoreDuplicates: true },
);
if (publishResponse.error && publishResponse.error.code !== "23505")
throw publishResponse.error;
const nodeTypeId = frontmatter.nodeTypeId as string | undefined;
if (nodeTypeId) {
await publishSchema({
client,
spaceId,
nodeTypeId,
groupId: myGroup,
});
}
}
await syncPublishedNodeAssets({
plugin,
client,
nodeId,
spaceId,
file,
attachments,
});
if (!existingPublish.includes(myGroup))
await plugin.app.fileManager.processFrontMatter(
file,
(fm: Record<string, unknown>) => {
fm.publishedToGroups = [...existingPublish, myGroup];
},
);
};