Skip to content

Commit 3d2d687

Browse files
committed
fix(rune): serialize response
1 parent 2a9c497 commit 3d2d687

File tree

7 files changed

+68
-23
lines changed

7 files changed

+68
-23
lines changed

docs/backend.md

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,32 @@
1-
# Backend Architecture
2-
3-
> TODO: update
4-
5-
# Cyb local backend
1+
# CYB local backend(in-browser)
62

73
Cyb plays singinficat role in cyber infrastructure. The app reconstruct self-sufficient backend+frontend pattern inside the browser.
84
In big view app consist from 3 parts:
95

106
```mermaid
117
graph TD;
12-
App["Frontend\n(main thread)"]-.proxy.->Backend["Backend\n(shared worker)"];
13-
App-.proxy.->Db["Graph Db\n(shared worker)"];
8+
App["frontend\n(main thread)"]-.proxy.->Backend["backend\n(shared worker)"];
9+
App-.proxy.->Db["graph db\n(shared worker)"];
1410
Backend-.proxy.->Db;
1511
App<-.message\nchannels.->Backend;
1612
```
1713

1814
To reduce overload of main thread we have created 2 separate shared workers, where all the stuff is hosted. Bi-interraction between all layers occurs using proxy(comlink abstraction) or directly using broadcast channels.
1915

20-
## Db
16+
## Db layer
2117

22-
Db worker is pretty simple it it's host only local relational-graph-vector database - [[cozo]].
18+
Db worker is pretty simple it it's host only local relational-graph-vector database - [[cozo]]. It's represented with DbApi in frontend and backend layers.
2319
Cozo provide bazing fast access to brain and ipfs data in relational form and also in vector format, processing by [ml]embedder.
2420

2521
```mermaid
2622
graph TD;
23+
dbApi["dbApi"]--odb_meta_orm;
2724
subgraph rune["cozo db"]
2825
db_meta_orm[["meta orm"]]-.->db;
2926
end
3027
```
3128

32-
### Entities
29+
### Db entities
3330

3431
- brain:
3532
- particles
@@ -45,7 +42,7 @@ graph TD;
4542
- config
4643
- queue messages
4744

48-
## Backend
45+
## Backend layer
4946

5047
Backend worker is more complicated it contains significant elements of cyb architecture:
5148

src/services/CozoDb/cozoDb.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import { clearIndexedDBStore, toListOfObjects } from './utils';
1616
import { createCozoDbCommandFactory } from './cozoDbCommandFactory';
1717

1818
import initializeScript from './migrations/schema.cozo';
19+
import { fetchInitialEmbeddings } from './migrations/migrations';
1920

2021
export const DB_NAME = 'cyb-cozo-idb';
2122

@@ -25,6 +26,8 @@ export const DB_VERSION = 1.2;
2526

2627
type OnWrite = (writesCount: number) => void;
2728

29+
let shouldInitialize = false;
30+
2831
function createCozoDb() {
2932
let db: CozoDb | undefined;
3033

@@ -82,7 +85,7 @@ function createCozoDb() {
8285
const initDbSchema = async (): Promise<void> => {
8386
let relations = await getRelations();
8487

85-
const shouldInitialize = relations.length === 0;
88+
shouldInitialize = relations.length === 0;
8689
if (shouldInitialize) {
8790
cyblogCh.info('CozoDb: apply DB schema', initializeScript);
8891
const result = await runCommand(initializeScript);
@@ -107,6 +110,10 @@ function createCozoDb() {
107110
if (shouldInitialize) {
108111
// if initialized set initial version
109112
await setDbVersion(DB_VERSION);
113+
await fetchInitialEmbeddings(async (items: Partial<DbEntity>[]) => {
114+
console.log(' [initial]save initial particles...');
115+
await put('sync_queue', items);
116+
});
110117
}
111118
};
112119

src/services/CozoDb/migrations/migrations.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,28 @@
1+
import { getRelevance } from 'src/utils/search/utils';
12
import { DB_VERSION, type CybCozoDb } from '../cozoDb';
3+
import { DbEntity, SyncQueueJobType } from '../types/entities';
4+
import { QueuePriority } from 'src/services/QueueManager/types';
5+
import { SyncQueueDto } from '../types/dto';
6+
import { dtoListToEntity } from 'src/utils/dto';
7+
import { ParticleCid } from 'src/types/base';
8+
9+
export const fetchInitialEmbeddings = async (
10+
saveSyncQueue: (syncItems: Partial<DbEntity>[]) => Promise<void>
11+
) => {
12+
console.log(' [initial]fetch initial particles...');
13+
const relevancePaticles = await getRelevance(0, 400);
14+
15+
const items = relevancePaticles.result.map(
16+
({ particle }: { particle: ParticleCid }) => ({
17+
id: particle,
18+
data: '',
19+
jobType: SyncQueueJobType.particle,
20+
priority: QueuePriority.LOW,
21+
})
22+
) as SyncQueueDto[];
23+
24+
await saveSyncQueue(dtoListToEntity(items));
25+
};
226

327
const migrate = async (db: CybCozoDb) => {
428
const version = await db.getDbVersion();

src/services/backend/channels/BackendQueueChannel/BackendQueueChannel.ts

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -55,13 +55,17 @@ class BackendQueueChannelListener {
5555
}
5656

5757
private async saveParticles(content: IPFSContent) {
58-
const dbApi = await this.getDeffredDbApi();
59-
const entity = mapParticleToEntity(content);
60-
const result = await dbApi.putParticles(entity);
61-
if (result.ok) {
62-
await enqueueParticleEmbeddingMaybe(content);
58+
try {
59+
const dbApi = await this.getDeffredDbApi();
60+
const entity = mapParticleToEntity(content);
61+
const result = await dbApi.putParticles(entity);
62+
if (result.ok) {
63+
await enqueueParticleEmbeddingMaybe(content);
64+
}
65+
} catch (e) {
66+
console.log('---saveParticle e', content, e);
67+
throw e;
6368
}
64-
// console.log('---saveParticles done', content);
6569
}
6670

6771
private async enquueSync(data: SyncQueueItem | SyncQueueItem[]) {

src/services/backend/services/sync/services/ParticlesResolverQueue/ParticlesResolverQueue.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import { SyncQueueItem } from './types';
3636
import { MAX_DATABASE_PUT_SIZE } from '../consts';
3737

3838
import DbApi from '../../../DbApi/DbApi';
39+
import { PATTERN_COSMOS, PATTERN_CYBER } from 'src/constants/patterns';
3940

4041
const QUEUE_BATCH_SIZE = 100;
4142

@@ -60,7 +61,11 @@ export const getTextContentIfShouldEmbed = async (
6061
) => {
6162
const [contentType, data] = await getContentToEmbed(content);
6263

63-
const shouldEmbed = contentType === 'text' && !!data;
64+
let shouldEmbed = contentType === 'text' && !!data;
65+
66+
shouldEmbed =
67+
shouldEmbed &&
68+
(!data!.match(PATTERN_COSMOS) || !data!.match(PATTERN_CYBER));
6469

6570
return shouldEmbed ? data : undefined;
6671
};

src/services/scripting/engine.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import {
2929
} from './types';
3030

3131
import runtimeScript from './rune/runtime.rn';
32+
import { deserializeString, serializeString } from 'src/utils/string';
3233

3334
const compileConfig = {
3435
budget: 1_000_000,
@@ -232,16 +233,23 @@ function enigine(): RuneEngine {
232233
const { cid, contentType, content } = params;
233234
const output = await run(script, {
234235
funcName: 'personal_processor',
235-
funcParams: [cid, contentType, content], //params as EntrypointParams,
236+
funcParams: [cid, contentType, serializeString(content || '')], //params as EntrypointParams,
236237
});
237238

238-
if (output.result.action === 'error') {
239+
const { action, content: outputContent } = output.result;
240+
241+
if (action === 'error') {
239242
console.error(
240243
`[rune].personalProcessor error: ${params.cid}`,
241244
params,
242245
output
243246
);
244247
}
248+
249+
if (outputContent) {
250+
return { ...output.result, content: deserializeString(outputContent) };
251+
}
252+
245253
return output.result;
246254
};
247255

src/services/scripting/rune/default/particle.rn

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,8 +80,8 @@ pub async fn personal_processor(cid, content_type, content) {
8080

8181
// example of content modification
8282
// replaces cyber with cyber❤
83-
let highlight_text = "cyber";
84-
let highlight_with = "❤";
83+
let highlight_text = "cyber ";
84+
let highlight_with = "❤ ";
8585

8686
if content.contains(highlight_text) {
8787
cyb::log(`Update ${cid} content, highlight ${highlight_text}${highlight_with}`);

0 commit comments

Comments
 (0)