@instantdb/core 0.22.92-experimental.sync-table-fixes.20350175943.1 → 0.22.92
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/commonjs/Reactor.d.ts.map +1 -1
- package/dist/commonjs/SyncTable.d.ts.map +1 -1
- package/dist/commonjs/SyncTable.js +6 -7
- package/dist/commonjs/SyncTable.js.map +1 -1
- package/dist/esm/Reactor.d.ts.map +1 -1
- package/dist/esm/SyncTable.d.ts.map +1 -1
- package/dist/esm/SyncTable.js +6 -7
- package/dist/esm/SyncTable.js.map +1 -1
- package/dist/standalone/index.js +6 -6
- package/dist/standalone/index.umd.cjs +2 -2
- package/package.json +2 -2
- package/src/SyncTable.ts +14 -18
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SyncTable.js","sourceRoot":"","sources":["../../src/SyncTable.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,KAAK,CAAC,MAAM,YAAY,CAAC;AAChC,OAAO,QAAQ,MAAM,qBAAqB,CAAC;AAC3C,OAAO,IAAI,MAAM,eAAe,CAAC;AAEjC,OAAO,OAAO,EAAE,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAsGrD,oEAAoE;AACpE,SAAS,kBAAkB,CAAC,GAAiB,EAAE,cAAuB;IACpE,MAAM,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC;IAC1B,IAAI,MAAM,EAAE,CAAC;QACX,MAAM,UAAU,GAAG,CAAC,CAAC,kBAAkB,CAAC,MAAM,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;QACjE,IAAI,UAAU,EAAE,CAAC;YACf,KAAK,MAAM,CAAC,IAAI,MAAM,CAAC,QAAQ,IAAI,EAAE,EAAE,CAAC;gBACtC,CAAC,CAAC,KAAK,CAAC,cAAc,GAAG,cAAc,CAAC;gBACvC,CAA0B,CAAC,KAAK,GA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C,GAKpB;QACC,mEAAmE;QACnE,sEAAsE;QACtE,qDAAqD;QACrD,MAAM,cAAc,GAAG,GAAG,CAAC,gBAAgB,CAAC,CAAC,iBAAiB,CAAC,CAAC;QAChE,MAAM,UAAU,GAAG,IAAI,CAAC,qBAAqB,CAAC,cAAc,EAAE,KAAK,CAAC,CAAC;QACrE,IAAI,UAAU,EAAE,CAAC;YACf,IAAI,CAAC,gBAAgB,CAAC,UAAU,CAAC,KAAK,EAAE,UAAU,CAAC,IAAI,CAAC,CAAC;QAC3D,CAAC;IACH,CAAC;CACF","sourcesContent":["import { PersistedObject } from './utils/PersistedObject.ts';\nimport * as s from './store.ts';\nimport weakHash from './utils/weakHash.ts';\nimport uuid from './utils/id.ts';\nimport { Logger } from './Reactor.js';\nimport instaql, { compareOrder } from './instaql.ts';\nimport { InstaQLResponse, ValidQuery } from './queryTypes.ts';\nimport { EntitiesDef, IContainEntitiesAndLinks } from './schemaTypes.ts';\nimport { StorageInterface } from './index.ts';\n\ntype SubState = {\n txId?: number;\n subscriptionId: string;\n token: string;\n};\n\ntype SubEntity = {\n entity: any;\n store: s.Store;\n serverCreatedAt: number;\n};\n\ntype SubValues = {\n attrsStore: s.AttrsStore;\n entities: Array<SubEntity>;\n};\n\ntype Sub = {\n query: any;\n hash: string;\n table: string;\n orderField: string;\n orderDirection: 'asc' | 'desc';\n orderFieldType?: 'string' | 'number' | 'date' | 'boolean' | null;\n state?: SubState;\n values?: SubValues;\n createdAt: number;\n updatedAt: number;\n};\n\ntype SubEntityInStorage = {\n entity: any;\n store: s.StoreJson;\n serverCreatedAt: number;\n};\n\ntype SubValuesInStorage = {\n attrsStore: s.AttrsStoreJson;\n entities: Array<SubEntityInStorage>;\n};\n\n// We could make a better type for this if we had a return type for s.toJSON\ntype SubInStorage = Omit<Sub, 'values'> & {\n values: SubValuesInStorage;\n};\n\ntype StartMsg = {\n op: 'start-sync';\n q: string;\n};\n\ntype EndMsg = {\n op: 'remove-sync';\n 'subscription-id': string;\n 'keep-subscription': boolean;\n};\n\ntype ResyncMsg = {\n op: 'resync-table';\n 'subscription-id': string;\n 'tx-id': number;\n token: string;\n};\n\ntype SendMsg = StartMsg | EndMsg | ResyncMsg;\n\ntype StartSyncOkMsg = {\n 'subscription-id': string;\n 'client-event-id': string;\n q: string;\n token: string;\n};\n\ntype Triple = [string, string, any, number];\n\ntype SyncLoadBatchMsg = {\n 'subscription-id': string;\n 'join-rows': Array<Triple[]>;\n};\n\ntype SyncInitFinishMsg = {\n 'subscription-id': string;\n 'tx-id': number;\n};\n\ntype SyncUpdateTriplesMsg = {\n 'subscription-id': string;\n txes: {\n 'tx-id': number;\n changes: { action: 'added' | 'removed'; triple: Triple }[];\n }[];\n};\n\ntype TrySend = (eventId: string, msg: SendMsg) => void;\n\ntype Config = { useDateObjects: boolean };\n\n// Modifies the data in place because it comes directly from storage\nfunction syncSubFromStorage(sub: SubInStorage, useDateObjects: boolean): Sub {\n const values = sub.values;\n if (values) {\n const attrsStore = s.attrsStoreFromJSON(values.attrsStore, null);\n if (attrsStore) {\n for (const e of values.entities || []) {\n e.store.useDateObjects = useDateObjects;\n (e as unknown as SubEntity).store = s.fromJSON(attrsStore, e.store);\n }\n (values as unknown as SubValues).attrsStore = attrsStore;\n }\n }\n\n return sub as unknown as Sub;\n}\n\nfunction syncSubToStorage(_k: string, sub: Sub): SubInStorage {\n if (sub.values) {\n const entities: SubEntityInStorage[] = [];\n for (const e of sub.values?.entities) {\n const store = s.toJSON(e.store);\n entities.push({ ...e, store });\n }\n return {\n ...sub,\n values: { attrsStore: sub.values.attrsStore.toJSON(), entities },\n };\n } else {\n return sub as unknown as SubInStorage;\n }\n}\n\nfunction onMergeSub(\n _key: string,\n storageSub: Sub,\n inMemorySub: Sub | null,\n): Sub {\n const storageTxId = storageSub?.state?.txId;\n const memoryTxId = inMemorySub?.state?.txId;\n\n if (storageTxId && (!memoryTxId || storageTxId > memoryTxId)) {\n return storageSub;\n }\n\n if (memoryTxId && (!storageTxId || memoryTxId > storageTxId)) {\n return inMemorySub;\n }\n\n return storageSub || inMemorySub;\n}\n\nfunction queryEntity(sub: Sub, store: s.Store, attrsStore: s.AttrsStore) {\n const res = instaql(\n { store, attrsStore, pageInfo: null, aggregate: null },\n sub.query,\n );\n return res.data[sub.table][0];\n}\n\nfunction getServerCreatedAt(\n sub: Sub,\n store: s.Store,\n attrsStore: s.AttrsStore,\n entityId: string,\n): number {\n const aid = s.getAttrByFwdIdentName(attrsStore, sub.table, 'id')?.id;\n if (!aid) {\n return -1;\n }\n const t = s.getInMap(store.eav, [entityId, aid, entityId]);\n if (!t) {\n return -1;\n }\n return t[3];\n}\n\nfunction applyChangesToStore(\n store: s.Store,\n attrsStore: s.AttrsStore,\n changes: SyncUpdateTriplesMsg['txes'][number]['changes'],\n): void {\n for (const { action, triple } of changes) {\n switch (action) {\n case 'added':\n s.addTriple(store, attrsStore, triple);\n break;\n case 'removed':\n s.retractTriple(store, attrsStore, triple);\n break;\n }\n }\n}\n\ntype ChangedFieldsOfChanges = {\n [eid: string]: { [field: string]: { oldValue: unknown; newValue: unknown } };\n};\n\nfunction changedFieldsOfChanges(\n store: s.Store,\n attrsStore: s.AttrsStore,\n changes: SyncUpdateTriplesMsg['txes'][number]['changes'],\n): ChangedFieldsOfChanges {\n // This will be more complicated when we include links, we can either add a\n // changedLinks field or we can have something like 'bookshelves.title`\n const changedFields: ChangedFieldsOfChanges = {};\n for (const { action, triple } of changes) {\n const [e, a, v] = triple;\n const field = attrsStore.getAttr(a)?.['forward-identity']?.[2];\n if (!field) continue;\n\n const fields = changedFields[e] ?? {};\n changedFields[e] = fields;\n\n const oldNew = fields[field] ?? {};\n\n switch (action) {\n case 'added':\n oldNew.newValue = v;\n break;\n case 'removed':\n // Only take the first thing that was removed, in case we modified things in the middle\n if (oldNew.oldValue === undefined) {\n oldNew.oldValue = v;\n }\n break;\n }\n\n fields[field] = oldNew;\n }\n\n for (const [_eid, fields] of Object.entries(changedFields)) {\n for (const [k, { oldValue, newValue }] of Object.entries(fields)) {\n if (oldValue === newValue) {\n delete fields[k];\n }\n }\n }\n return changedFields;\n}\n\nfunction subData(sub: Sub, entities: NonNullable<Sub['values']>['entities']) {\n return { [sub.table]: entities.map((e) => e.entity) };\n}\n\ntype CreateStore = (triples: Triple[]) => s.Store;\n\n// Updates the sub order field type if it hasn't been set\n// and returns the type. We have to wait until the attrs\n// are loaded before we can determine the type.\nfunction orderFieldTypeMutative(sub: Sub, getAttrs: () => s.AttrsStore) {\n if (sub.orderFieldType) {\n return sub.orderFieldType;\n }\n const orderFieldType =\n sub.orderField === 'serverCreatedAt'\n ? 'number'\n : s.getAttrByFwdIdentName(getAttrs(), sub.table, sub.orderField)?.[\n 'checked-data-type'\n ];\n\n sub.orderFieldType = orderFieldType;\n return orderFieldType;\n}\n\nfunction sortEntitiesInPlace(\n sub: Sub,\n orderFieldType: NonNullable<Sub['orderFieldType']>,\n entities: NonNullable<Sub['values']>['entities'],\n) {\n const dataType = orderFieldType;\n if (sub.orderField === 'serverCreatedAt') {\n entities.sort(\n sub.orderDirection === 'asc'\n ? function compareEntities(a, b) {\n return compareOrder(\n a.entity.id,\n a.serverCreatedAt,\n b.entity.id,\n b.serverCreatedAt,\n dataType,\n );\n }\n : function compareEntities(b, a) {\n return compareOrder(\n a.entity.id,\n a.serverCreatedAt,\n b.entity.id,\n b.serverCreatedAt,\n dataType,\n );\n },\n );\n return;\n }\n\n const field = sub.orderField;\n\n entities.sort(\n sub.orderDirection === 'asc'\n ? function compareEntities(a, b) {\n return compareOrder(\n a.entity.id,\n a.entity[field],\n b.entity.id,\n b.entity[field],\n dataType,\n );\n }\n : function compareEntities(b, a) {\n return compareOrder(\n a.entity.id,\n a.entity[field],\n b.entity.id,\n b.entity[field],\n dataType,\n );\n },\n );\n}\n\nexport enum CallbackEventType {\n InitialSyncBatch = 'InitialSyncBatch',\n InitialSyncComplete = 'InitialSyncComplete',\n LoadFromStorage = 'LoadFromStorage',\n SyncTransaction = 'SyncTransaction',\n Error = 'Error',\n}\n\ntype QueryEntities<\n Schema extends IContainEntitiesAndLinks<EntitiesDef, any>,\n Q extends ValidQuery<Q, Schema>,\n UseDates extends boolean,\n> = InstaQLResponse<Schema, Q, UseDates>[keyof InstaQLResponse<\n Schema,\n Q,\n UseDates\n>];\n\ntype QueryEntity<\n Schema extends IContainEntitiesAndLinks<EntitiesDef, any>,\n Q extends ValidQuery<Q, Schema>,\n UseDates extends boolean,\n> = QueryEntities<Schema, Q, UseDates> extends (infer E)[] ? E : never;\n\ntype ChangedFields<Entity> = {\n [K in keyof Entity]?: {\n oldValue: Entity[K];\n newValue: Entity[K];\n };\n};\n\nexport interface BaseCallbackEvent<\n Schema extends IContainEntitiesAndLinks<EntitiesDef, any>,\n Q extends ValidQuery<Q, Schema>,\n UseDates extends boolean,\n> {\n type: CallbackEventType;\n data: InstaQLResponse<Schema, Q, UseDates>;\n}\n\nexport interface InitialSyncBatch<\n Schema extends IContainEntitiesAndLinks<EntitiesDef, any>,\n Q extends ValidQuery<Q, Schema>,\n UseDates extends boolean,\n> extends BaseCallbackEvent<Schema, Q, UseDates> {\n type: CallbackEventType.InitialSyncBatch;\n batch: QueryEntities<Schema, Q, UseDates>;\n}\n\nexport interface InitialSyncComplete<\n Schema extends IContainEntitiesAndLinks<EntitiesDef, any>,\n Q extends ValidQuery<Q, Schema>,\n UseDates extends boolean,\n> extends BaseCallbackEvent<Schema, Q, UseDates> {\n type: CallbackEventType.InitialSyncComplete;\n}\n\nexport interface SyncTransaction<\n Schema extends IContainEntitiesAndLinks<EntitiesDef, any>,\n Q extends ValidQuery<Q, Schema>,\n UseDates extends boolean,\n> extends BaseCallbackEvent<Schema, Q, UseDates> {\n type: CallbackEventType.SyncTransaction;\n added: QueryEntities<Schema, Q, UseDates>;\n removed: QueryEntities<Schema, Q, UseDates>;\n updated: {\n oldEntity: QueryEntity<Schema, Q, UseDates>;\n newEntity: QueryEntity<Schema, Q, UseDates>;\n changedFields: ChangedFields<QueryEntity<Schema, Q, UseDates>>;\n }[];\n}\n\nexport interface LoadFromStorage<\n Schema extends IContainEntitiesAndLinks<EntitiesDef, any>,\n Q extends ValidQuery<Q, Schema>,\n UseDates extends boolean,\n> extends BaseCallbackEvent<Schema, Q, UseDates> {\n type: CallbackEventType.LoadFromStorage;\n}\n\nexport interface SetupError<\n Schema extends IContainEntitiesAndLinks<EntitiesDef, any>,\n Q extends ValidQuery<Q, Schema>,\n UseDates extends boolean,\n> extends BaseCallbackEvent<Schema, Q, UseDates> {\n type: CallbackEventType.Error;\n error: { message: string; hint?: any; type: string; status: number };\n}\n\nexport type CallbackEvent<\n Schema extends IContainEntitiesAndLinks<EntitiesDef, any>,\n Q extends ValidQuery<Q, Schema>,\n UseDates extends boolean,\n> =\n | InitialSyncBatch<Schema, Q, UseDates>\n | InitialSyncComplete<Schema, Q, UseDates>\n | SyncTransaction<Schema, Q, UseDates>\n | LoadFromStorage<Schema, Q, UseDates>\n | SetupError<Schema, Q, UseDates>;\n\nexport type SyncTableCallback<\n Schema extends IContainEntitiesAndLinks<EntitiesDef, any>,\n Q extends ValidQuery<Q, Schema>,\n UseDates extends boolean,\n> = (event: CallbackEvent<Schema, Q, UseDates>) => void;\n\nexport class SyncTable {\n private trySend: TrySend;\n private subs: PersistedObject<string, Sub, SubInStorage>;\n // Using any for the SyncCallback because we'd need Reactor to be typed\n private callbacks: { [hash: string]: SyncTableCallback<any, any, any>[] } =\n {};\n private config: Config;\n private idToHash: { [subscriptionId: string]: string } = {};\n private log: Logger;\n private createStore: CreateStore;\n private getAttrs: () => s.AttrsStore;\n\n constructor(\n trySend: TrySend,\n storage: StorageInterface,\n config: Config,\n log: Logger,\n createStore: CreateStore,\n getAttrs: () => s.AttrsStore,\n ) {\n this.trySend = trySend;\n this.config = config;\n this.log = log;\n this.createStore = createStore;\n this.getAttrs = getAttrs;\n\n this.subs = new PersistedObject<string, Sub, SubInStorage>({\n persister: storage,\n merge: onMergeSub,\n serialize: syncSubToStorage,\n parse: (_key, x) => syncSubFromStorage(x, this.config.useDateObjects),\n objectSize: (sub) => sub.values?.entities.length || 0,\n logger: log,\n gc: {\n maxAgeMs: 1000 * 60 * 60 * 24 * 7 * 52, // 1 year\n maxEntries: 1000,\n // Size of each sub is the number of entity\n maxSize: 1_000_000, // 1 million entities\n },\n });\n }\n\n public beforeUnload() {\n this.subs.flush();\n }\n\n public subscribe(\n q: any,\n cb: SyncTableCallback<any, any, any>,\n ): (\n opts?: { keepSubscription?: boolean | null | undefined } | null | undefined,\n ) => void {\n const hash = weakHash(q);\n this.callbacks[hash] = this.callbacks[hash] || [];\n this.callbacks[hash].push(cb);\n\n this.initSubscription(q, hash, cb);\n\n return (opts?: { keepSubscription?: boolean | null | undefined }) => {\n this.unsubscribe(hash, cb, opts?.keepSubscription);\n };\n }\n\n private unsubscribe(\n hash: string,\n cb: SyncTableCallback<any, any, any>,\n keepSubscription: boolean | null | undefined,\n ) {\n const cbs = (this.callbacks[hash] || []).filter((x) => x !== cb);\n this.callbacks[hash] = cbs;\n\n if (!cbs.length) {\n delete this.callbacks[hash];\n const sub = this.subs.currentValue[hash];\n if (sub?.state) {\n this.clearSubscriptionData(\n sub.state.subscriptionId,\n !!keepSubscription,\n );\n }\n if (!keepSubscription) {\n this.subs.updateInPlace((prev) => {\n delete prev[hash];\n });\n }\n }\n }\n\n private sendStart(query: string) {\n this.trySend(uuid(), {\n op: 'start-sync',\n q: query,\n });\n }\n\n private sendResync(sub: Sub, state: SubState, txId: number) {\n // Make sure we can find the hash from the subscriptionId\n this.idToHash[state.subscriptionId] = sub.hash;\n this.trySend(state.subscriptionId, {\n op: 'resync-table',\n 'subscription-id': state.subscriptionId,\n 'tx-id': txId,\n token: state.token,\n });\n }\n\n private sendRemove(state: SubState, keepSubscription: boolean) {\n this.trySend(uuid(), {\n op: 'remove-sync',\n 'subscription-id': state.subscriptionId,\n 'keep-subscription': keepSubscription,\n });\n }\n\n private async initSubscription(\n query: any,\n hash: string,\n cb?: SyncTableCallback<any, any, any>,\n ) {\n // Wait for storage to load so that we know if we already have an existing subscription\n await this.subs.waitForKeyToLoad(hash);\n const existingSub = this.subs.currentValue[hash];\n\n if (existingSub && existingSub.state && existingSub.state.txId) {\n this.sendResync(existingSub, existingSub.state, existingSub.state.txId);\n\n if (existingSub.values?.entities && cb) {\n cb({\n type: CallbackEventType.LoadFromStorage,\n data: subData(existingSub, existingSub.values?.entities),\n });\n }\n\n return;\n }\n\n const table = Object.keys(query)[0];\n const orderBy = query[table]?.$?.order || { serverCreatedAt: 'asc' };\n const [orderField, orderDirection] = Object.entries(orderBy)[0] as [\n string,\n 'asc' | 'desc',\n ];\n\n this.subs.updateInPlace((prev) => {\n prev[hash] = {\n query,\n hash: hash,\n table,\n orderDirection,\n orderField,\n createdAt: Date.now(),\n updatedAt: Date.now(),\n };\n });\n\n this.sendStart(query);\n }\n\n public async flushPending() {\n for (const hash of Object.keys(this.callbacks)) {\n await this.subs.waitForKeyToLoad(hash);\n const sub = this.subs.currentValue[hash];\n if (sub) {\n await this.initSubscription(sub.query, sub.hash);\n } else {\n this.log.error('Missing sub for hash in flushPending', hash);\n }\n }\n }\n\n public onStartSyncOk(msg: StartSyncOkMsg) {\n const subscriptionId = msg['subscription-id'];\n const q = msg.q;\n const hash = weakHash(q);\n\n this.idToHash[subscriptionId] = hash;\n\n this.subs.updateInPlace((prev) => {\n const sub = prev[hash];\n if (!sub) {\n this.log.error(\n 'Missing sub for hash',\n hash,\n 'subscription-id',\n subscriptionId,\n 'query',\n q,\n );\n return prev;\n }\n\n sub.state = {\n subscriptionId: subscriptionId,\n token: msg.token,\n };\n });\n }\n\n private notifyCbs(hash: string, event: CallbackEvent<any, any, any>) {\n for (const cb of this.callbacks[hash] || []) {\n cb(event);\n }\n }\n\n public onSyncLoadBatch(msg: SyncLoadBatchMsg) {\n const subscriptionId = msg['subscription-id'];\n const joinRows = msg['join-rows'];\n const hash = this.idToHash[subscriptionId];\n if (!hash) {\n this.log.error('Missing hash for subscription', msg);\n return;\n }\n\n const batch: any[] = [];\n const sub = this.subs.currentValue[hash];\n if (!sub) {\n this.log.error('Missing sub for hash', hash, msg);\n return;\n }\n\n const values: SubValues = sub.values ?? {\n entities: [],\n attrsStore: this.getAttrs(),\n };\n sub.values = values;\n const entities = values.entities;\n\n for (const entRows of joinRows) {\n const store = this.createStore(entRows);\n const entity = queryEntity(sub, store, values.attrsStore);\n entities.push({\n store,\n entity,\n serverCreatedAt: getServerCreatedAt(\n sub,\n store,\n values.attrsStore,\n entity.id,\n ),\n });\n batch.push(entity);\n }\n\n this.subs.updateInPlace((prev) => {\n prev[hash] = sub;\n // Make sure we write a field or mutative won't\n // see the change because sub === prev[hash]\n prev[hash].updatedAt = Date.now();\n });\n\n if (sub.values) {\n this.notifyCbs(hash, {\n type: CallbackEventType.InitialSyncBatch,\n data: subData(sub, sub.values.entities),\n batch,\n });\n }\n }\n\n public onSyncInitFinish(msg: SyncInitFinishMsg) {\n const subscriptionId = msg['subscription-id'];\n const hash = this.idToHash[subscriptionId];\n if (!hash) {\n this.log.error('Missing hash for subscription', msg);\n return;\n }\n this.subs.updateInPlace((prev) => {\n const sub = prev[hash];\n if (!sub) {\n this.log.error('Missing sub for hash', hash, msg);\n return;\n }\n const state = sub.state;\n if (!state) {\n this.log.error('Sub never set init, missing result', sub, msg);\n return prev;\n }\n state.txId = msg['tx-id'];\n sub.updatedAt = Date.now();\n });\n\n const sub = this.subs.currentValue[hash];\n\n if (sub) {\n this.notifyCbs(hash, {\n type: CallbackEventType.InitialSyncComplete,\n data: subData(sub, sub.values?.entities || []),\n });\n }\n }\n\n public onSyncUpdateTriples(msg: SyncUpdateTriplesMsg) {\n const subscriptionId = msg['subscription-id'];\n const hash = this.idToHash[subscriptionId];\n if (!hash) {\n this.log.error('Missing hash for subscription', msg);\n return;\n }\n\n const sub = this.subs.currentValue[hash];\n if (!sub) {\n this.log.error('Missing sub for hash', hash, msg);\n return;\n }\n\n const state = sub.state;\n if (!state) {\n this.log.error('Missing state for sub', sub, msg);\n return;\n }\n\n for (const tx of msg.txes) {\n if (state.txId && state.txId >= tx['tx-id']) {\n continue;\n }\n state.txId = tx['tx-id'];\n const idxesToDelete: number[] = [];\n // Note: this won't work as well when links are involved\n const byEid: {\n [eid: string]: SyncUpdateTriplesMsg['txes'][number]['changes'];\n } = {};\n for (const change of tx.changes) {\n const eidChanges = byEid[change.triple[0]] ?? [];\n byEid[change.triple[0]] = eidChanges;\n eidChanges.push(change);\n }\n\n const values: SubValues = sub.values ?? {\n entities: [],\n attrsStore: this.getAttrs(),\n };\n const entities = values.entities;\n sub.values = values;\n\n const updated: SyncTransaction<any, any, any>['updated'] = [];\n // Update the existing stores, if we already know about this entity\n eidLoop: for (const [eid, changes] of Object.entries(byEid)) {\n for (let i = 0; i < entities.length; i++) {\n const ent = entities[i];\n if (s.hasEntity(ent.store, eid)) {\n applyChangesToStore(ent.store, values.attrsStore, changes);\n const entity = queryEntity(sub, ent.store, values.attrsStore);\n const changedFields = changedFieldsOfChanges(\n ent.store,\n values.attrsStore,\n changes,\n )[eid];\n if (entity) {\n updated.push({\n oldEntity: ent.entity,\n newEntity: entity,\n changedFields: (changedFields || {}) as SyncTransaction<\n any,\n any,\n any\n >['updated'][number]['changedFields'],\n });\n ent.entity = entity;\n } else {\n idxesToDelete.push(i);\n }\n delete byEid[eid];\n continue eidLoop;\n }\n }\n }\n\n const added: any[] = [];\n // If we have anything left in byEid, then this must be a new entity we don't know about\n for (const [_eid, changes] of Object.entries(byEid)) {\n const store = this.createStore([]);\n applyChangesToStore(store, values.attrsStore, changes);\n const entity = queryEntity(sub, store, values.attrsStore);\n if (!entity) {\n this.log.error('No entity found after applying change', {\n sub,\n changes,\n store,\n });\n continue;\n }\n entities.push({\n store,\n entity,\n serverCreatedAt: getServerCreatedAt(\n sub,\n store,\n values.attrsStore,\n entity.id,\n ),\n });\n added.push(entity);\n }\n\n const removed: any[] = [];\n\n for (const idx of idxesToDelete.sort().reverse()) {\n removed.push(entities[idx].entity);\n entities.splice(idx, 1);\n }\n\n const orderFieldType = orderFieldTypeMutative(sub, this.getAttrs);\n\n sortEntitiesInPlace(sub, orderFieldType!, entities);\n this.notifyCbs(hash, {\n type: CallbackEventType.SyncTransaction,\n data: subData(sub, sub.values?.entities),\n added,\n removed,\n updated,\n });\n }\n this.subs.updateInPlace((prev) => {\n prev[hash] = sub;\n // Make sure we write a field or mutative won't\n // see the change because sub === prev[hash]\n prev[hash].updatedAt = Date.now();\n });\n }\n\n private clearSubscriptionData(\n subscriptionId: string,\n keepSubscription: boolean,\n ) {\n const hash = this.idToHash[subscriptionId];\n if (hash) {\n delete this.idToHash[subscriptionId];\n const sub = this.subs.currentValue[hash];\n if (sub.state) {\n this.sendRemove(sub.state, keepSubscription);\n }\n if (keepSubscription) {\n this.subs.unloadKey(hash);\n } else {\n this.subs.updateInPlace((prev) => {\n delete prev[hash];\n });\n }\n if (sub) {\n return sub;\n }\n }\n }\n\n public onStartSyncError(msg: {\n op: 'error';\n 'original-event': StartMsg;\n 'client-event-id': string;\n status: number;\n type: string;\n message?: string;\n hint?: any;\n }) {\n const hash = weakHash(msg['original-event']['q']);\n const error = {\n message: msg.message || 'Uh-oh, something went wrong. Ping Joe & Stopa.',\n status: msg.status,\n type: msg.type,\n hint: msg.hint,\n };\n\n const k = Object.keys(msg['original-event']['q'])[0];\n this.notifyCbs(hash, {\n type: CallbackEventType.Error,\n data: { [k]: [] },\n error,\n });\n }\n\n public onResyncError(msg: {\n op: 'error';\n 'original-event': ResyncMsg;\n status: number;\n type: string;\n }) {\n // Clear the subscription and start from scrath on any resync error\n // This can happen if the auth changed and we need to refetch with the\n // new auth or if the subscription is too far behind.\n const subscriptionId = msg['original-event']['subscription-id'];\n const removedSub = this.clearSubscriptionData(subscriptionId, false);\n if (removedSub) {\n this.initSubscription(removedSub.query, removedSub.hash);\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"SyncTable.js","sourceRoot":"","sources":["../../src/SyncTable.ts"],"names":[],"mappings":";;;;;;;;;AA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AAgB,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;QAClD,MAAM,KAAK,GAAG;YACZ,OAAO,EAAE,GAAG,CAAC,OAAO,IAAI,gDAAgD;YACxE,MAAM,EAAE,GAAG,CAAC,MAAM;YAClB,IAAI,EAAE,GAAG,CAAC,IAAI;YACd,IAAI,EAAE,GAAG,CAAC,IAAI;SACf,CAAC;QAEF,MAAM,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACrD,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE;YACnB,IAAI,EAAE,iBAAiB,CAAC,KAAK;YAC7B,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE;YACjB,KAAK;SACN,CAAC,CAAC;IACL,CAAC;IAEM,aAAa,CAAC,GAKpB;QACC,mEAAmE;QACnE,sEAAsE;QACtE,qDAAqD;QACrD,MAAM,cAAc,GAAG,GAAG,CAAC,gBAAgB,CAAC,CAAC,iBAAiB,CAAC,CAAC;QAChE,MAAM,UAAU,GAAG,IAAI,CAAC,qBAAqB,CAAC,cAAc,EAAE,KAAK,CAAC,CAAC;QACrE,IAAI,UAAU,EAAE,CAAC;YACf,IAAI,CAAC,gBAAgB,CAAC,UAAU,CAAC,KAAK,EAAE,UAAU,CAAC,IAAI,CAAC,CAAC;QAC3D,CAAC;IACH,CAAC;CACF","sourcesContent":["import { PersistedObject } from './utils/PersistedObject.ts';\nimport * as s from './store.ts';\nimport weakHash from './utils/weakHash.ts';\nimport uuid from './utils/id.ts';\nimport { Logger } from './Reactor.js';\nimport instaql, { compareOrder } from './instaql.ts';\nimport { InstaQLResponse, ValidQuery } from './queryTypes.ts';\nimport { EntitiesDef, IContainEntitiesAndLinks } from './schemaTypes.ts';\nimport { StorageInterface } from './index.ts';\n\ntype SubState = {\n txId?: number;\n subscriptionId: string;\n token: string;\n};\n\ntype SubEntity = {\n entity: any;\n store: s.Store;\n serverCreatedAt: number;\n};\n\ntype SubValues = {\n attrsStore: s.AttrsStore;\n entities: Array<SubEntity>;\n};\n\ntype Sub = {\n query: any;\n hash: string;\n table: string;\n orderField: string;\n orderDirection: 'asc' | 'desc';\n orderFieldType?: 'string' | 'number' | 'date' | 'boolean' | null;\n state?: SubState;\n values?: SubValues;\n createdAt: number;\n updatedAt: number;\n};\n\ntype SubEntityInStorage = {\n entity: any;\n store: s.StoreJson;\n serverCreatedAt: number;\n};\n\ntype SubValuesInStorage = {\n attrsStore: s.AttrsStoreJson;\n entities: Array<SubEntityInStorage>;\n};\n\n// We could make a better type for this if we had a return type for s.toJSON\ntype SubInStorage = Omit<Sub, 'values'> & {\n values: SubValuesInStorage;\n};\n\ntype StartMsg = {\n op: 'start-sync';\n q: string;\n};\n\ntype EndMsg = {\n op: 'remove-sync';\n 'subscription-id': string;\n 'keep-subscription': boolean;\n};\n\ntype ResyncMsg = {\n op: 'resync-table';\n 'subscription-id': string;\n 'tx-id': number;\n token: string;\n};\n\ntype SendMsg = StartMsg | EndMsg | ResyncMsg;\n\ntype StartSyncOkMsg = {\n 'subscription-id': string;\n 'client-event-id': string;\n q: string;\n token: string;\n};\n\ntype Triple = [string, string, any, number];\n\ntype SyncLoadBatchMsg = {\n 'subscription-id': string;\n 'join-rows': Array<Triple[]>;\n};\n\ntype SyncInitFinishMsg = {\n 'subscription-id': string;\n 'tx-id': number;\n};\n\ntype SyncUpdateTriplesMsg = {\n 'subscription-id': string;\n txes: {\n 'tx-id': number;\n changes: { action: 'added' | 'removed'; triple: Triple }[];\n }[];\n};\n\ntype TrySend = (eventId: string, msg: SendMsg) => void;\n\ntype Config = { useDateObjects: boolean };\n\n// Modifies the data in place because it comes directly from storage\nfunction syncSubFromStorage(sub: SubInStorage, useDateObjects: boolean): Sub {\n const values = sub.values;\n if (values) {\n const attrsStore = s.attrsStoreFromJSON(values.attrsStore, null);\n if (attrsStore) {\n for (const e of values.entities || []) {\n e.store.useDateObjects = useDateObjects;\n (e as unknown as SubEntity).store = s.fromJSON(attrsStore, e.store);\n }\n (values as unknown as SubValues).attrsStore = attrsStore;\n }\n }\n\n return sub as unknown as Sub;\n}\n\nfunction syncSubToStorage(_k: string, sub: Sub): SubInStorage {\n if (sub.values) {\n const entities: SubEntityInStorage[] = [];\n for (const e of sub.values?.entities) {\n const store = s.toJSON(e.store);\n entities.push({ ...e, store });\n }\n return {\n ...sub,\n values: { attrsStore: sub.values.attrsStore.toJSON(), entities },\n };\n } else {\n return sub as unknown as SubInStorage;\n }\n}\n\nfunction onMergeSub(\n _key: string,\n storageSub: Sub,\n inMemorySub: Sub | null,\n): Sub {\n const storageTxId = storageSub?.state?.txId;\n const memoryTxId = inMemorySub?.state?.txId;\n\n if (storageTxId && (!memoryTxId || storageTxId > memoryTxId)) {\n return storageSub;\n }\n\n if (memoryTxId && (!storageTxId || memoryTxId > storageTxId)) {\n return inMemorySub;\n }\n\n return storageSub || inMemorySub;\n}\n\nfunction queryEntity(sub: Sub, store: s.Store, attrsStore: s.AttrsStore) {\n const res = instaql(\n { store, attrsStore, pageInfo: null, aggregate: null },\n sub.query,\n );\n return res.data[sub.table][0];\n}\n\nfunction getServerCreatedAt(\n sub: Sub,\n store: s.Store,\n attrsStore: s.AttrsStore,\n entityId: string,\n): number {\n const aid = s.getAttrByFwdIdentName(attrsStore, sub.table, 'id')?.id;\n if (!aid) {\n return -1;\n }\n const t = s.getInMap(store.eav, [entityId, aid, entityId]);\n if (!t) {\n return -1;\n }\n return t[3];\n}\n\nfunction applyChangesToStore(\n store: s.Store,\n attrsStore: s.AttrsStore,\n changes: SyncUpdateTriplesMsg['txes'][number]['changes'],\n): void {\n for (const { action, triple } of changes) {\n switch (action) {\n case 'added':\n s.addTriple(store, attrsStore, triple);\n break;\n case 'removed':\n s.retractTriple(store, attrsStore, triple);\n break;\n }\n }\n}\n\nfunction changedFieldsOfChanges(\n store: s.Store,\n attrsStore: s.AttrsStore,\n changes: SyncUpdateTriplesMsg['txes'][number]['changes'],\n): {\n [eid: string]: SyncTransaction<\n any,\n any,\n any\n >['updated'][number]['changedFields'];\n} {\n // This will be more complicated when we include links, we can either add a\n // changedLinks field or we can have something like 'bookshelves.title`\n const changedFields = {};\n for (const { action, triple } of changes) {\n const [e, a, v] = triple;\n const field = attrsStore.getAttr(a)?.['forward-identity']?.[2];\n if (!field) continue;\n\n const fields = changedFields[e] ?? {};\n changedFields[e] = fields;\n\n const oldNew = fields[field] ?? {};\n fields[field] = oldNew;\n\n switch (action) {\n case 'added':\n oldNew.newValue = v;\n break;\n case 'removed':\n // Only take the first thing that was removed, in case we modified things in the middle\n if (oldNew.oldValue === undefined) {\n oldNew.oldValue = v;\n }\n break;\n }\n }\n\n for (const k of Object.keys(changedFields)) {\n const { oldValue, newValue } = changedFields[k];\n if (oldValue === newValue) {\n delete changedFields[k];\n }\n }\n return changedFields;\n}\n\nfunction subData(sub: Sub, entities: NonNullable<Sub['values']>['entities']) {\n return { [sub.table]: entities.map((e) => e.entity) };\n}\n\ntype CreateStore = (triples: Triple[]) => s.Store;\n\n// Updates the sub order field type if it hasn't been set\n// and returns the type. We have to wait until the attrs\n// are loaded before we can determine the type.\nfunction orderFieldTypeMutative(sub: Sub, getAttrs: () => s.AttrsStore) {\n if (sub.orderFieldType) {\n return sub.orderFieldType;\n }\n const orderFieldType =\n sub.orderField === 'serverCreatedAt'\n ? 'number'\n : s.getAttrByFwdIdentName(getAttrs(), sub.table, sub.orderField)?.[\n 'checked-data-type'\n ];\n\n sub.orderFieldType = orderFieldType;\n return orderFieldType;\n}\n\nfunction sortEntitiesInPlace(\n sub: Sub,\n orderFieldType: NonNullable<Sub['orderFieldType']>,\n entities: NonNullable<Sub['values']>['entities'],\n) {\n const dataType = orderFieldType;\n if (sub.orderField === 'serverCreatedAt') {\n entities.sort(\n sub.orderDirection === 'asc'\n ? function compareEntities(a, b) {\n return compareOrder(\n a.entity.id,\n a.serverCreatedAt,\n b.entity.id,\n b.serverCreatedAt,\n dataType,\n );\n }\n : function compareEntities(b, a) {\n return compareOrder(\n a.entity.id,\n a.serverCreatedAt,\n b.entity.id,\n b.serverCreatedAt,\n dataType,\n );\n },\n );\n return;\n }\n\n const field = sub.orderField;\n\n entities.sort(\n sub.orderDirection === 'asc'\n ? function compareEntities(a, b) {\n return compareOrder(\n a.entity.id,\n a.entity[field],\n b.entity.id,\n b.entity[field],\n dataType,\n );\n }\n : function compareEntities(b, a) {\n return compareOrder(\n a.entity.id,\n a.entity[field],\n b.entity.id,\n b.entity[field],\n dataType,\n );\n },\n );\n}\n\nexport enum CallbackEventType {\n InitialSyncBatch = 'InitialSyncBatch',\n InitialSyncComplete = 'InitialSyncComplete',\n LoadFromStorage = 'LoadFromStorage',\n SyncTransaction = 'SyncTransaction',\n Error = 'Error',\n}\n\ntype QueryEntities<\n Schema extends IContainEntitiesAndLinks<EntitiesDef, any>,\n Q extends ValidQuery<Q, Schema>,\n UseDates extends boolean,\n> = InstaQLResponse<Schema, Q, UseDates>[keyof InstaQLResponse<\n Schema,\n Q,\n UseDates\n>];\n\ntype QueryEntity<\n Schema extends IContainEntitiesAndLinks<EntitiesDef, any>,\n Q extends ValidQuery<Q, Schema>,\n UseDates extends boolean,\n> = QueryEntities<Schema, Q, UseDates> extends (infer E)[] ? E : never;\n\ntype ChangedFields<Entity> = {\n [K in keyof Entity]?: {\n oldValue: Entity[K];\n newValue: Entity[K];\n };\n};\n\nexport interface BaseCallbackEvent<\n Schema extends IContainEntitiesAndLinks<EntitiesDef, any>,\n Q extends ValidQuery<Q, Schema>,\n UseDates extends boolean,\n> {\n type: CallbackEventType;\n data: InstaQLResponse<Schema, Q, UseDates>;\n}\n\nexport interface InitialSyncBatch<\n Schema extends IContainEntitiesAndLinks<EntitiesDef, any>,\n Q extends ValidQuery<Q, Schema>,\n UseDates extends boolean,\n> extends BaseCallbackEvent<Schema, Q, UseDates> {\n type: CallbackEventType.InitialSyncBatch;\n batch: QueryEntities<Schema, Q, UseDates>;\n}\n\nexport interface InitialSyncComplete<\n Schema extends IContainEntitiesAndLinks<EntitiesDef, any>,\n Q extends ValidQuery<Q, Schema>,\n UseDates extends boolean,\n> extends BaseCallbackEvent<Schema, Q, UseDates> {\n type: CallbackEventType.InitialSyncComplete;\n}\n\nexport interface SyncTransaction<\n Schema extends IContainEntitiesAndLinks<EntitiesDef, any>,\n Q extends ValidQuery<Q, Schema>,\n UseDates extends boolean,\n> extends BaseCallbackEvent<Schema, Q, UseDates> {\n type: CallbackEventType.SyncTransaction;\n added: QueryEntities<Schema, Q, UseDates>;\n removed: QueryEntities<Schema, Q, UseDates>;\n updated: {\n oldEntity: QueryEntity<Schema, Q, UseDates>;\n newEntity: QueryEntity<Schema, Q, UseDates>;\n changedFields: ChangedFields<QueryEntity<Schema, Q, UseDates>>;\n }[];\n}\n\nexport interface LoadFromStorage<\n Schema extends IContainEntitiesAndLinks<EntitiesDef, any>,\n Q extends ValidQuery<Q, Schema>,\n UseDates extends boolean,\n> extends BaseCallbackEvent<Schema, Q, UseDates> {\n type: CallbackEventType.LoadFromStorage;\n}\n\nexport interface SetupError<\n Schema extends IContainEntitiesAndLinks<EntitiesDef, any>,\n Q extends ValidQuery<Q, Schema>,\n UseDates extends boolean,\n> extends BaseCallbackEvent<Schema, Q, UseDates> {\n type: CallbackEventType.Error;\n error: { message: string; hint?: any; type: string; status: number };\n}\n\nexport type CallbackEvent<\n Schema extends IContainEntitiesAndLinks<EntitiesDef, any>,\n Q extends ValidQuery<Q, Schema>,\n UseDates extends boolean,\n> =\n | InitialSyncBatch<Schema, Q, UseDates>\n | InitialSyncComplete<Schema, Q, UseDates>\n | SyncTransaction<Schema, Q, UseDates>\n | LoadFromStorage<Schema, Q, UseDates>\n | SetupError<Schema, Q, UseDates>;\n\nexport type SyncTableCallback<\n Schema extends IContainEntitiesAndLinks<EntitiesDef, any>,\n Q extends ValidQuery<Q, Schema>,\n UseDates extends boolean,\n> = (event: CallbackEvent<Schema, Q, UseDates>) => void;\n\nexport class SyncTable {\n private trySend: TrySend;\n private subs: PersistedObject<string, Sub, SubInStorage>;\n // Using any for the SyncCallback because we'd need Reactor to be typed\n private callbacks: { [hash: string]: SyncTableCallback<any, any, any>[] } =\n {};\n private config: Config;\n private idToHash: { [subscriptionId: string]: string } = {};\n private log: Logger;\n private createStore: CreateStore;\n private getAttrs: () => s.AttrsStore;\n\n constructor(\n trySend: TrySend,\n storage: StorageInterface,\n config: Config,\n log: Logger,\n createStore: CreateStore,\n getAttrs: () => s.AttrsStore,\n ) {\n this.trySend = trySend;\n this.config = config;\n this.log = log;\n this.createStore = createStore;\n this.getAttrs = getAttrs;\n\n this.subs = new PersistedObject<string, Sub, SubInStorage>({\n persister: storage,\n merge: onMergeSub,\n serialize: syncSubToStorage,\n parse: (_key, x) => syncSubFromStorage(x, this.config.useDateObjects),\n objectSize: (sub) => sub.values?.entities.length || 0,\n logger: log,\n gc: {\n maxAgeMs: 1000 * 60 * 60 * 24 * 7 * 52, // 1 year\n maxEntries: 1000,\n // Size of each sub is the number of entity\n maxSize: 1_000_000, // 1 million entities\n },\n });\n }\n\n public beforeUnload() {\n this.subs.flush();\n }\n\n public subscribe(\n q: any,\n cb: SyncTableCallback<any, any, any>,\n ): (\n opts?: { keepSubscription?: boolean | null | undefined } | null | undefined,\n ) => void {\n const hash = weakHash(q);\n this.callbacks[hash] = this.callbacks[hash] || [];\n this.callbacks[hash].push(cb);\n\n this.initSubscription(q, hash, cb);\n\n return (opts?: { keepSubscription?: boolean | null | undefined }) => {\n this.unsubscribe(hash, cb, opts?.keepSubscription);\n };\n }\n\n private unsubscribe(\n hash: string,\n cb: SyncTableCallback<any, any, any>,\n keepSubscription: boolean | null | undefined,\n ) {\n const cbs = (this.callbacks[hash] || []).filter((x) => x !== cb);\n this.callbacks[hash] = cbs;\n\n if (!cbs.length) {\n delete this.callbacks[hash];\n const sub = this.subs.currentValue[hash];\n if (sub?.state) {\n this.clearSubscriptionData(\n sub.state.subscriptionId,\n !!keepSubscription,\n );\n }\n if (!keepSubscription) {\n this.subs.updateInPlace((prev) => {\n delete prev[hash];\n });\n }\n }\n }\n\n private sendStart(query: string) {\n this.trySend(uuid(), {\n op: 'start-sync',\n q: query,\n });\n }\n\n private sendResync(sub: Sub, state: SubState, txId: number) {\n // Make sure we can find the hash from the subscriptionId\n this.idToHash[state.subscriptionId] = sub.hash;\n this.trySend(state.subscriptionId, {\n op: 'resync-table',\n 'subscription-id': state.subscriptionId,\n 'tx-id': txId,\n token: state.token,\n });\n }\n\n private sendRemove(state: SubState, keepSubscription: boolean) {\n this.trySend(uuid(), {\n op: 'remove-sync',\n 'subscription-id': state.subscriptionId,\n 'keep-subscription': keepSubscription,\n });\n }\n\n private async initSubscription(\n query: any,\n hash: string,\n cb?: SyncTableCallback<any, any, any>,\n ) {\n // Wait for storage to load so that we know if we already have an existing subscription\n await this.subs.waitForKeyToLoad(hash);\n const existingSub = this.subs.currentValue[hash];\n\n if (existingSub && existingSub.state && existingSub.state.txId) {\n this.sendResync(existingSub, existingSub.state, existingSub.state.txId);\n\n if (existingSub.values?.entities && cb) {\n cb({\n type: CallbackEventType.LoadFromStorage,\n data: subData(existingSub, existingSub.values?.entities),\n });\n }\n\n return;\n }\n\n const table = Object.keys(query)[0];\n const orderBy = query[table]?.$?.order || { serverCreatedAt: 'asc' };\n const [orderField, orderDirection] = Object.entries(orderBy)[0] as [\n string,\n 'asc' | 'desc',\n ];\n\n this.subs.updateInPlace((prev) => {\n prev[hash] = {\n query,\n hash: hash,\n table,\n orderDirection,\n orderField,\n createdAt: Date.now(),\n updatedAt: Date.now(),\n };\n });\n\n this.sendStart(query);\n }\n\n public async flushPending() {\n for (const hash of Object.keys(this.callbacks)) {\n await this.subs.waitForKeyToLoad(hash);\n const sub = this.subs.currentValue[hash];\n if (sub) {\n await this.initSubscription(sub.query, sub.hash);\n } else {\n this.log.error('Missing sub for hash in flushPending', hash);\n }\n }\n }\n\n public onStartSyncOk(msg: StartSyncOkMsg) {\n const subscriptionId = msg['subscription-id'];\n const q = msg.q;\n const hash = weakHash(q);\n\n this.idToHash[subscriptionId] = hash;\n\n this.subs.updateInPlace((prev) => {\n const sub = prev[hash];\n if (!sub) {\n this.log.error(\n 'Missing sub for hash',\n hash,\n 'subscription-id',\n subscriptionId,\n 'query',\n q,\n );\n return prev;\n }\n\n sub.state = {\n subscriptionId: subscriptionId,\n token: msg.token,\n };\n });\n }\n\n private notifyCbs(hash: string, event: CallbackEvent<any, any, any>) {\n for (const cb of this.callbacks[hash] || []) {\n cb(event);\n }\n }\n\n public onSyncLoadBatch(msg: SyncLoadBatchMsg) {\n const subscriptionId = msg['subscription-id'];\n const joinRows = msg['join-rows'];\n const hash = this.idToHash[subscriptionId];\n if (!hash) {\n this.log.error('Missing hash for subscription', msg);\n return;\n }\n\n const batch: any[] = [];\n const sub = this.subs.currentValue[hash];\n if (!sub) {\n this.log.error('Missing sub for hash', hash, msg);\n return;\n }\n\n const values: SubValues = sub.values ?? {\n entities: [],\n attrsStore: this.getAttrs(),\n };\n sub.values = values;\n const entities = values.entities;\n\n for (const entRows of joinRows) {\n const store = this.createStore(entRows);\n const entity = queryEntity(sub, store, values.attrsStore);\n entities.push({\n store,\n entity,\n serverCreatedAt: getServerCreatedAt(\n sub,\n store,\n values.attrsStore,\n entity.id,\n ),\n });\n batch.push(entity);\n }\n\n this.subs.updateInPlace((prev) => {\n prev[hash] = sub;\n // Make sure we write a field or mutative won't\n // see the change because sub === prev[hash]\n prev[hash].updatedAt = Date.now();\n });\n\n if (sub.values) {\n this.notifyCbs(hash, {\n type: CallbackEventType.InitialSyncBatch,\n data: subData(sub, sub.values.entities),\n batch,\n });\n }\n }\n\n public onSyncInitFinish(msg: SyncInitFinishMsg) {\n const subscriptionId = msg['subscription-id'];\n const hash = this.idToHash[subscriptionId];\n if (!hash) {\n this.log.error('Missing hash for subscription', msg);\n return;\n }\n this.subs.updateInPlace((prev) => {\n const sub = prev[hash];\n if (!sub) {\n this.log.error('Missing sub for hash', hash, msg);\n return;\n }\n const state = sub.state;\n if (!state) {\n this.log.error('Sub never set init, missing result', sub, msg);\n return prev;\n }\n state.txId = msg['tx-id'];\n sub.updatedAt = Date.now();\n });\n\n const sub = this.subs.currentValue[hash];\n\n if (sub) {\n this.notifyCbs(hash, {\n type: CallbackEventType.InitialSyncComplete,\n data: subData(sub, sub.values?.entities || []),\n });\n }\n }\n\n public onSyncUpdateTriples(msg: SyncUpdateTriplesMsg) {\n const subscriptionId = msg['subscription-id'];\n const hash = this.idToHash[subscriptionId];\n if (!hash) {\n this.log.error('Missing hash for subscription', msg);\n return;\n }\n\n const sub = this.subs.currentValue[hash];\n if (!sub) {\n this.log.error('Missing sub for hash', hash, msg);\n return;\n }\n\n const state = sub.state;\n if (!state) {\n this.log.error('Missing state for sub', sub, msg);\n return;\n }\n\n for (const tx of msg.txes) {\n if (state.txId && state.txId >= tx['tx-id']) {\n continue;\n }\n state.txId = tx['tx-id'];\n const idxesToDelete: number[] = [];\n // Note: this won't work as well when links are involved\n const byEid: {\n [eid: string]: SyncUpdateTriplesMsg['txes'][number]['changes'];\n } = {};\n for (const change of tx.changes) {\n const eidChanges = byEid[change.triple[0]] ?? [];\n byEid[change.triple[0]] = eidChanges;\n eidChanges.push(change);\n }\n\n const values: SubValues = sub.values ?? {\n entities: [],\n attrsStore: this.getAttrs(),\n };\n const entities = values.entities;\n sub.values = values;\n\n const updated: SyncTransaction<any, any, any>['updated'] = [];\n // Update the existing stores, if we already know about this entity\n eidLoop: for (const [eid, changes] of Object.entries(byEid)) {\n for (let i = 0; i < entities.length; i++) {\n const ent = entities[i];\n if (s.hasEntity(ent.store, eid)) {\n applyChangesToStore(ent.store, values.attrsStore, changes);\n const entity = queryEntity(sub, ent.store, values.attrsStore);\n const changedFields = changedFieldsOfChanges(\n ent.store,\n values.attrsStore,\n changes,\n )[eid];\n if (entity) {\n updated.push({\n oldEntity: ent.entity,\n newEntity: entity,\n changedFields: changedFields || {},\n });\n ent.entity = entity;\n } else {\n idxesToDelete.push(i);\n }\n delete byEid[eid];\n continue eidLoop;\n }\n }\n }\n\n const added: any[] = [];\n // If we have anything left in byEid, then this must be a new entity we don't know about\n for (const [_eid, changes] of Object.entries(byEid)) {\n const store = this.createStore([]);\n applyChangesToStore(store, values.attrsStore, changes);\n const entity = queryEntity(sub, store, values.attrsStore);\n if (!entity) {\n this.log.error('No entity found after applying change', {\n sub,\n changes,\n store,\n });\n continue;\n }\n entities.push({\n store,\n entity,\n serverCreatedAt: getServerCreatedAt(\n sub,\n store,\n values.attrsStore,\n entity.id,\n ),\n });\n added.push(entity);\n }\n\n const removed: any[] = [];\n\n for (const idx of idxesToDelete.sort().reverse()) {\n removed.push(entities[idx].entity);\n entities.splice(idx, 1);\n }\n\n const orderFieldType = orderFieldTypeMutative(sub, this.getAttrs);\n\n sortEntitiesInPlace(sub, orderFieldType!, entities);\n this.notifyCbs(hash, {\n type: CallbackEventType.SyncTransaction,\n data: subData(sub, sub.values?.entities),\n added,\n removed,\n updated,\n });\n }\n this.subs.updateInPlace((prev) => {\n prev[hash] = sub;\n // Make sure we write a field or mutative won't\n // see the change because sub === prev[hash]\n prev[hash].updatedAt = Date.now();\n });\n }\n\n private clearSubscriptionData(\n subscriptionId: string,\n keepSubscription: boolean,\n ) {\n const hash = this.idToHash[subscriptionId];\n if (hash) {\n delete this.idToHash[subscriptionId];\n const sub = this.subs.currentValue[hash];\n if (sub.state) {\n this.sendRemove(sub.state, keepSubscription);\n }\n if (keepSubscription) {\n this.subs.unloadKey(hash);\n } else {\n this.subs.updateInPlace((prev) => {\n delete prev[hash];\n });\n }\n if (sub) {\n return sub;\n }\n }\n }\n\n public onStartSyncError(msg: {\n op: 'error';\n 'original-event': StartMsg;\n 'client-event-id': string;\n status: number;\n type: string;\n message?: string;\n hint?: any;\n }) {\n const hash = weakHash(msg['original-event']['q']);\n const error = {\n message: msg.message || 'Uh-oh, something went wrong. Ping Joe & Stopa.',\n status: msg.status,\n type: msg.type,\n hint: msg.hint,\n };\n\n const k = Object.keys(msg['original-event']['q'])[0];\n this.notifyCbs(hash, {\n type: CallbackEventType.Error,\n data: { [k]: [] },\n error,\n });\n }\n\n public onResyncError(msg: {\n op: 'error';\n 'original-event': ResyncMsg;\n status: number;\n type: string;\n }) {\n // Clear the subscription and start from scrath on any resync error\n // This can happen if the auth changed and we need to refetch with the\n // new auth or if the subscription is too far behind.\n const subscriptionId = msg['original-event']['subscription-id'];\n const removedSub = this.clearSubscriptionData(subscriptionId, false);\n if (removedSub) {\n this.initSubscription(removedSub.query, removedSub.hash);\n }\n }\n}\n"]}
|
package/dist/standalone/index.js
CHANGED
|
@@ -3639,7 +3639,7 @@ function Kt(t) {
|
|
|
3639
3639
|
}, e;
|
|
3640
3640
|
}, {});
|
|
3641
3641
|
}
|
|
3642
|
-
const Rn = "v0.22.92
|
|
3642
|
+
const Rn = "v0.22.92";
|
|
3643
3643
|
function Mi(t, e) {
|
|
3644
3644
|
return {
|
|
3645
3645
|
info: t ? (...n) => console.info(...n, e()) : () => {
|
|
@@ -4372,7 +4372,7 @@ function Vi(t, e, n) {
|
|
|
4372
4372
|
const d = r[c] ?? {};
|
|
4373
4373
|
r[c] = d;
|
|
4374
4374
|
const h = d[f] ?? {};
|
|
4375
|
-
switch (o) {
|
|
4375
|
+
switch (d[f] = h, o) {
|
|
4376
4376
|
case "added":
|
|
4377
4377
|
h.newValue = l;
|
|
4378
4378
|
break;
|
|
@@ -4380,11 +4380,11 @@ function Vi(t, e, n) {
|
|
|
4380
4380
|
h.oldValue === void 0 && (h.oldValue = l);
|
|
4381
4381
|
break;
|
|
4382
4382
|
}
|
|
4383
|
-
d[f] = h;
|
|
4384
4383
|
}
|
|
4385
|
-
for (const
|
|
4386
|
-
|
|
4387
|
-
|
|
4384
|
+
for (const o of Object.keys(r)) {
|
|
4385
|
+
const { oldValue: a, newValue: c } = r[o];
|
|
4386
|
+
a === c && delete r[o];
|
|
4387
|
+
}
|
|
4388
4388
|
return r;
|
|
4389
4389
|
}
|
|
4390
4390
|
function _e(t, e) {
|