@dxos/echo-pipeline 0.7.4 → 0.7.5-labs.071a3e2
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/lib/browser/{chunk-LZK5YFYE.mjs → chunk-YCF2J47S.mjs} +35 -14
- package/dist/lib/browser/chunk-YCF2J47S.mjs.map +7 -0
- package/dist/lib/browser/index.mjs +172 -78
- package/dist/lib/browser/index.mjs.map +4 -4
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/browser/testing/index.mjs +1 -1
- package/dist/lib/node/{chunk-MACQJ2EP.cjs → chunk-ISBFYEHY.cjs} +38 -17
- package/dist/lib/node/chunk-ISBFYEHY.cjs.map +7 -0
- package/dist/lib/node/index.cjs +186 -96
- package/dist/lib/node/index.cjs.map +4 -4
- package/dist/lib/node/meta.json +1 -1
- package/dist/lib/node/testing/index.cjs +10 -10
- package/dist/lib/node-esm/{chunk-JIZPSASG.mjs → chunk-NLVNKCI3.mjs} +35 -14
- package/dist/lib/node-esm/chunk-NLVNKCI3.mjs.map +7 -0
- package/dist/lib/node-esm/index.mjs +172 -78
- package/dist/lib/node-esm/index.mjs.map +4 -4
- package/dist/lib/node-esm/meta.json +1 -1
- package/dist/lib/node-esm/testing/index.mjs +1 -1
- package/dist/types/src/automerge/automerge-host.d.ts +5 -1
- package/dist/types/src/automerge/automerge-host.d.ts.map +1 -1
- package/dist/types/src/automerge/collection-synchronizer.d.ts +1 -0
- package/dist/types/src/automerge/collection-synchronizer.d.ts.map +1 -1
- package/dist/types/src/automerge/echo-network-adapter.d.ts +1 -0
- package/dist/types/src/automerge/echo-network-adapter.d.ts.map +1 -1
- package/dist/types/src/automerge/leveldb-storage-adapter.d.ts +1 -1
- package/dist/types/src/db-host/echo-host.d.ts +3 -2
- package/dist/types/src/db-host/echo-host.d.ts.map +1 -1
- package/dist/types/src/db-host/query-service.d.ts +1 -1
- package/dist/types/src/db-host/query-service.d.ts.map +1 -1
- package/dist/types/src/edge/echo-edge-replicator.d.ts.map +1 -1
- package/dist/types/src/edge/inflight-request-limiter.d.ts +24 -0
- package/dist/types/src/edge/inflight-request-limiter.d.ts.map +1 -0
- package/dist/types/src/pipeline/pipeline.d.ts.map +1 -1
- package/dist/types/src/space/control-pipeline.d.ts.map +1 -1
- package/dist/types/src/space/space-manager.d.ts +1 -0
- package/dist/types/src/space/space-manager.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -0
- package/package.json +34 -34
- package/src/automerge/automerge-host.ts +49 -14
- package/src/automerge/collection-synchronizer.ts +8 -4
- package/src/automerge/echo-network-adapter.ts +7 -0
- package/src/automerge/mesh-echo-replicator.ts +2 -2
- package/src/db-host/echo-host.ts +4 -1
- package/src/db-host/query-service.ts +1 -1
- package/src/edge/echo-edge-replicator.ts +34 -18
- package/src/edge/inflight-request-limiter.ts +69 -0
- package/src/pipeline/pipeline.ts +4 -1
- package/src/space/control-pipeline.ts +1 -2
- package/src/space/space-manager.ts +17 -1
- package/dist/lib/browser/chunk-LZK5YFYE.mjs.map +0 -7
- package/dist/lib/node/chunk-MACQJ2EP.cjs.map +0 -7
- package/dist/lib/node-esm/chunk-JIZPSASG.mjs.map +0 -7
|
@@ -929,7 +929,10 @@ var Pipeline = class {
|
|
|
929
929
|
stallTimeout: 1e3
|
|
930
930
|
});
|
|
931
931
|
this._feedSetIterator.stalled.on((iterator) => {
|
|
932
|
-
log4.warn(`Stalled after ${iterator.options.stallTimeout}ms with ${iterator.size} feeds.`,
|
|
932
|
+
log4.warn(`Stalled after ${iterator.options.stallTimeout}ms with ${iterator.size} feeds.`, {
|
|
933
|
+
currentTimeframe: this._timeframeClock.timeframe,
|
|
934
|
+
targetTimeframe: this._state.targetTimeframe
|
|
935
|
+
}, {
|
|
933
936
|
F: __dxlog_file5,
|
|
934
937
|
L: 426,
|
|
935
938
|
S: this,
|
|
@@ -1257,7 +1260,7 @@ var ControlPipeline = class {
|
|
|
1257
1260
|
seq: msg.seq
|
|
1258
1261
|
}, {
|
|
1259
1262
|
F: __dxlog_file7,
|
|
1260
|
-
L:
|
|
1263
|
+
L: 185,
|
|
1261
1264
|
S: this,
|
|
1262
1265
|
C: (f, a) => f(...a)
|
|
1263
1266
|
});
|
|
@@ -1272,7 +1275,7 @@ var ControlPipeline = class {
|
|
|
1272
1275
|
msg
|
|
1273
1276
|
}, {
|
|
1274
1277
|
F: __dxlog_file7,
|
|
1275
|
-
L:
|
|
1278
|
+
L: 194,
|
|
1276
1279
|
S: this,
|
|
1277
1280
|
C: (f, a) => f(...a)
|
|
1278
1281
|
});
|
|
@@ -1291,7 +1294,7 @@ var ControlPipeline = class {
|
|
|
1291
1294
|
async stop() {
|
|
1292
1295
|
log6("stopping...", void 0, {
|
|
1293
1296
|
F: __dxlog_file7,
|
|
1294
|
-
L:
|
|
1297
|
+
L: 214,
|
|
1295
1298
|
S: this,
|
|
1296
1299
|
C: (f, a) => f(...a)
|
|
1297
1300
|
});
|
|
@@ -1300,7 +1303,7 @@ var ControlPipeline = class {
|
|
|
1300
1303
|
await this._saveTargetTimeframe(this._pipeline.state.timeframe);
|
|
1301
1304
|
log6("stopped", void 0, {
|
|
1302
1305
|
F: __dxlog_file7,
|
|
1303
|
-
L:
|
|
1306
|
+
L: 218,
|
|
1304
1307
|
S: this,
|
|
1305
1308
|
C: (f, a) => f(...a)
|
|
1306
1309
|
});
|
|
@@ -1313,7 +1316,7 @@ var ControlPipeline = class {
|
|
|
1313
1316
|
} catch (err) {
|
|
1314
1317
|
log6(err, void 0, {
|
|
1315
1318
|
F: __dxlog_file7,
|
|
1316
|
-
L:
|
|
1319
|
+
L: 227,
|
|
1317
1320
|
S: this,
|
|
1318
1321
|
C: (f, a) => f(...a)
|
|
1319
1322
|
});
|
|
@@ -1869,6 +1872,8 @@ _ts_decorate6([
|
|
|
1869
1872
|
|
|
1870
1873
|
// packages/core/echo/echo-pipeline/src/space/space-manager.ts
|
|
1871
1874
|
import { synchronized as synchronized4, trackLeaks as trackLeaks3, Trigger as Trigger2 } from "@dxos/async";
|
|
1875
|
+
import { parseAutomergeUrl } from "@dxos/automerge/automerge-repo";
|
|
1876
|
+
import { getCredentialAssertion } from "@dxos/credentials";
|
|
1872
1877
|
import { failUndefined as failUndefined2 } from "@dxos/debug";
|
|
1873
1878
|
import { PublicKey as PublicKey6 } from "@dxos/keys";
|
|
1874
1879
|
import { log as log9 } from "@dxos/log";
|
|
@@ -1907,7 +1912,7 @@ var SpaceManager = class {
|
|
|
1907
1912
|
id: this._instanceId
|
|
1908
1913
|
}), {
|
|
1909
1914
|
F: __dxlog_file11,
|
|
1910
|
-
L:
|
|
1915
|
+
L: 101,
|
|
1911
1916
|
S: this,
|
|
1912
1917
|
C: (f, a) => f(...a)
|
|
1913
1918
|
});
|
|
@@ -1915,7 +1920,7 @@ var SpaceManager = class {
|
|
|
1915
1920
|
spaceKey: metadata.genesisFeedKey
|
|
1916
1921
|
}, {
|
|
1917
1922
|
F: __dxlog_file11,
|
|
1918
|
-
L:
|
|
1923
|
+
L: 102,
|
|
1919
1924
|
S: this,
|
|
1920
1925
|
C: (f, a) => f(...a)
|
|
1921
1926
|
});
|
|
@@ -1947,7 +1952,7 @@ var SpaceManager = class {
|
|
|
1947
1952
|
id: this._instanceId
|
|
1948
1953
|
}), {
|
|
1949
1954
|
F: __dxlog_file11,
|
|
1950
|
-
L:
|
|
1955
|
+
L: 132,
|
|
1951
1956
|
S: this,
|
|
1952
1957
|
C: (f, a) => f(...a)
|
|
1953
1958
|
});
|
|
@@ -1959,7 +1964,7 @@ var SpaceManager = class {
|
|
|
1959
1964
|
id: this._instanceId
|
|
1960
1965
|
}), {
|
|
1961
1966
|
F: __dxlog_file11,
|
|
1962
|
-
L:
|
|
1967
|
+
L: 138,
|
|
1963
1968
|
S: this,
|
|
1964
1969
|
C: (f, a) => f(...a)
|
|
1965
1970
|
});
|
|
@@ -1967,7 +1972,7 @@ var SpaceManager = class {
|
|
|
1967
1972
|
spaceKey: params.spaceKey
|
|
1968
1973
|
}, {
|
|
1969
1974
|
F: __dxlog_file11,
|
|
1970
|
-
L:
|
|
1975
|
+
L: 139,
|
|
1971
1976
|
S: this,
|
|
1972
1977
|
C: (f, a) => f(...a)
|
|
1973
1978
|
});
|
|
@@ -1995,7 +2000,7 @@ var SpaceManager = class {
|
|
|
1995
2000
|
id: this._instanceId
|
|
1996
2001
|
}), {
|
|
1997
2002
|
F: __dxlog_file11,
|
|
1998
|
-
L:
|
|
2003
|
+
L: 163,
|
|
1999
2004
|
S: this,
|
|
2000
2005
|
C: (f, a) => f(...a)
|
|
2001
2006
|
});
|
|
@@ -2006,7 +2011,7 @@ var SpaceManager = class {
|
|
|
2006
2011
|
error: err
|
|
2007
2012
|
}), {
|
|
2008
2013
|
F: __dxlog_file11,
|
|
2009
|
-
L:
|
|
2014
|
+
L: 166,
|
|
2010
2015
|
S: this,
|
|
2011
2016
|
C: (f, a) => f(...a)
|
|
2012
2017
|
});
|
|
@@ -2015,6 +2020,22 @@ var SpaceManager = class {
|
|
|
2015
2020
|
await protocol.stop();
|
|
2016
2021
|
}
|
|
2017
2022
|
}
|
|
2023
|
+
findSpaceByRootDocumentId(documentId) {
|
|
2024
|
+
return [
|
|
2025
|
+
...this._spaces.values()
|
|
2026
|
+
].find((space) => {
|
|
2027
|
+
return space.spaceState.credentials.some((credential) => {
|
|
2028
|
+
const assertion = getCredentialAssertion(credential);
|
|
2029
|
+
if (assertion["@type"] !== "dxos.halo.credentials.Epoch") {
|
|
2030
|
+
return false;
|
|
2031
|
+
}
|
|
2032
|
+
if (!assertion?.automergeRoot) {
|
|
2033
|
+
return false;
|
|
2034
|
+
}
|
|
2035
|
+
return parseAutomergeUrl(assertion.automergeRoot).documentId === documentId;
|
|
2036
|
+
});
|
|
2037
|
+
});
|
|
2038
|
+
}
|
|
2018
2039
|
};
|
|
2019
2040
|
_ts_decorate7([
|
|
2020
2041
|
synchronized4
|
|
@@ -2049,4 +2070,4 @@ export {
|
|
|
2049
2070
|
SpaceProtocolSession,
|
|
2050
2071
|
SpaceManager
|
|
2051
2072
|
};
|
|
2052
|
-
//# sourceMappingURL=chunk-
|
|
2073
|
+
//# sourceMappingURL=chunk-YCF2J47S.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/common/codec.ts", "../../../src/common/feeds.ts", "../../../src/common/space-id.ts", "../../../src/metadata/metadata-store.ts", "../../../src/pipeline/timeframe-clock.ts", "../../../src/pipeline/pipeline.ts", "../../../src/pipeline/message-selector.ts", "../../../src/space/auth.ts", "../../../src/space/space.ts", "../../../src/space/control-pipeline.ts", "../../../src/space/admission-discovery-extension.ts", "../../../src/space/space-protocol.ts", "../../../src/space/space-manager.ts"],
|
|
4
|
+
"sourcesContent": ["//\n// Copyright 2022 DXOS.org\n//\n\nimport { type Codec } from '@dxos/codec-protobuf';\nimport { createCodecEncoding } from '@dxos/hypercore';\nimport { schema } from '@dxos/protocols/proto';\nimport type { FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\n\n/**\n * Codec for feed messages.\n */\nexport const codec: Codec<FeedMessage> = schema.getCodecForType('dxos.echo.feed.FeedMessage');\n\n/**\n * Value encoding used by feed store.\n */\nexport const valueEncoding = createCodecEncoding(codec);\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { type FeedWriter } from '@dxos/feed-store';\nimport { invariant } from '@dxos/invariant';\nimport { type MaybePromise } from '@dxos/util';\n\n/**\n * Maps the written arguments onto a different message type.\n */\nexport const createMappedFeedWriter = <Source extends {}, Target extends {}>(\n mapper: (arg: Source) => MaybePromise<Target>,\n writer: FeedWriter<Target>,\n): FeedWriter<Source> => {\n invariant(mapper);\n invariant(writer);\n\n return {\n write: async (data: Source, options) => await writer.write(await mapper(data), options),\n };\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { subtleCrypto } from '@dxos/crypto';\nimport { PublicKey, SpaceId } from '@dxos/keys';\nimport { ComplexMap } from '@dxos/util';\n\nconst SPACE_IDS_CACHE = new ComplexMap<PublicKey, SpaceId>(PublicKey.hash);\n\n/**\n * Space keys are generated by creating a keypair, and then taking the first 20 bytes of the SHA-256 hash of the public key and encoding them to multibase RFC4648 base-32 format (prefixed with B, see Multibase Table).\n * Inspired by how ethereum addresses are derived.\n */\nexport const createIdFromSpaceKey = async (spaceKey: PublicKey): Promise<SpaceId> => {\n const cachedValue = SPACE_IDS_CACHE.get(spaceKey);\n if (cachedValue !== undefined) {\n return cachedValue;\n }\n\n const digest = await subtleCrypto.digest('SHA-256', spaceKey.asUint8Array());\n\n const bytes = new Uint8Array(digest).slice(0, SpaceId.byteLength);\n const spaceId = SpaceId.encode(bytes);\n SPACE_IDS_CACHE.set(spaceKey, spaceId);\n return spaceId;\n};\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport CRC32 from 'crc-32';\n\nimport { Event, scheduleTaskInterval, synchronized } from '@dxos/async';\nimport { type Codec } from '@dxos/codec-protobuf';\nimport { Context } from '@dxos/context';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { DataCorruptionError, STORAGE_VERSION } from '@dxos/protocols';\nimport { schema } from '@dxos/protocols/proto';\nimport { Invitation, SpaceState } from '@dxos/protocols/proto/dxos/client/services';\nimport {\n type ControlPipelineSnapshot,\n type EchoMetadata,\n type SpaceMetadata,\n type IdentityRecord,\n type SpaceCache,\n type LargeSpaceMetadata,\n type EdgeReplicationSetting,\n} from '@dxos/protocols/proto/dxos/echo/metadata';\nimport { type Directory, type File } from '@dxos/random-access-storage';\nimport { type Timeframe } from '@dxos/timeframe';\nimport { ComplexMap, arrayToBuffer, forEachAsync, isNotNullOrUndefined } from '@dxos/util';\n\nconst EXPIRED_INVITATION_CLEANUP_INTERVAL = 60 * 60 * 1000; // 1 hour\n\nexport interface AddSpaceOptions {\n key: PublicKey;\n genesisFeed: PublicKey;\n}\n\nconst emptyEchoMetadata = (): EchoMetadata => ({\n version: STORAGE_VERSION,\n spaces: [],\n created: new Date(),\n updated: new Date(),\n});\n\nconst emptyLargeSpaceMetadata = (): LargeSpaceMetadata => ({});\n\nconst EchoMetadata = schema.getCodecForType('dxos.echo.metadata.EchoMetadata');\nconst LargeSpaceMetadata = schema.getCodecForType('dxos.echo.metadata.LargeSpaceMetadata');\n\nexport class MetadataStore {\n private _metadata: EchoMetadata = emptyEchoMetadata();\n private _spaceLargeMetadata = new ComplexMap<PublicKey, LargeSpaceMetadata>(PublicKey.hash);\n\n private _metadataFile?: File = undefined;\n\n public readonly update = new Event<EchoMetadata>();\n private readonly _invitationCleanupCtx = new Context();\n\n /**\n * @internal\n */\n readonly _directory: Directory;\n\n constructor(directory: Directory) {\n this._directory = directory;\n }\n\n get metadata(): EchoMetadata {\n return this._metadata;\n }\n\n get version(): number {\n return this._metadata.version ?? 0;\n }\n\n /**\n * Returns a list of currently saved spaces. The list and objects in it can be modified addSpace and\n * addSpaceFeed functions.\n */\n get spaces(): SpaceMetadata[] {\n return this._metadata.spaces ?? [];\n }\n\n private async _readFile<T>(file: File, codec: Codec<T>): Promise<T | undefined> {\n try {\n const { size: fileLength } = await file.stat();\n if (fileLength < 8) {\n return;\n }\n // Loading file size from first 4 bytes.\n const dataSize = fromBytesInt32(await file.read(0, 4));\n const checksum = fromBytesInt32(await file.read(4, 4));\n log('loaded', { size: dataSize, checksum, name: file.filename });\n\n if (fileLength < dataSize + 8) {\n throw new DataCorruptionError('Metadata size is smaller than expected.', { fileLength, dataSize });\n }\n\n const data = await file.read(8, dataSize);\n\n const calculatedChecksum = CRC32.buf(data);\n if (calculatedChecksum !== checksum) {\n throw new DataCorruptionError('Metadata checksum is invalid.');\n }\n\n return codec.decode(data);\n } finally {\n await file.close();\n }\n }\n\n /**\n * @internal\n */\n async _writeFile<T>(file: File, codec: Codec<T>, data: T): Promise<void> {\n const encoded = arrayToBuffer(codec.encode(data));\n const checksum = CRC32.buf(encoded);\n\n const result = Buffer.alloc(8 + encoded.length);\n\n result.writeInt32LE(encoded.length, 0);\n result.writeInt32LE(checksum, 4);\n encoded.copy(result, 8);\n\n // NOTE: This must be done in one write operation, otherwise the file can be corrupted.\n await file.write(0, result);\n\n log('saved', { size: encoded.length, checksum });\n }\n\n async close() {\n await this._invitationCleanupCtx.dispose();\n await this.flush();\n await this._metadataFile?.close();\n this._metadataFile = undefined;\n this._metadata = emptyEchoMetadata();\n this._spaceLargeMetadata.clear();\n }\n\n /**\n * Loads metadata from persistent storage.\n */\n @synchronized\n async load(): Promise<void> {\n if (!this._metadataFile || this._metadataFile.closed) {\n this._metadataFile = this._directory.getOrCreateFile('EchoMetadata');\n }\n\n try {\n const metadata = await this._readFile(this._metadataFile, EchoMetadata);\n if (metadata) {\n this._metadata = metadata;\n }\n\n // post-processing\n this._metadata.spaces?.forEach((space) => {\n space.state ??= SpaceState.SPACE_ACTIVE;\n });\n } catch (err: any) {\n log.error('failed to load metadata', { err });\n this._metadata = emptyEchoMetadata();\n }\n\n await forEachAsync(\n [this._metadata.identity?.haloSpace.key, ...(this._metadata.spaces?.map((space) => space.key) ?? [])].filter(\n isNotNullOrUndefined,\n ),\n async (key) => {\n try {\n await this._loadSpaceLargeMetadata(key);\n } catch (err: any) {\n log.error('failed to load space large metadata', { err });\n }\n },\n );\n\n // Cleanup expired persistent invitations.\n scheduleTaskInterval(\n this._invitationCleanupCtx,\n async () => {\n for (const invitation of this._metadata.invitations ?? []) {\n if (hasInvitationExpired(invitation) || isLegacyInvitationFormat(invitation)) {\n await this.removeInvitation(invitation.invitationId);\n }\n }\n },\n EXPIRED_INVITATION_CLEANUP_INTERVAL,\n );\n }\n\n @synchronized\n private async _save(): Promise<void> {\n const data: EchoMetadata = {\n ...this._metadata,\n version: STORAGE_VERSION,\n created: this._metadata.created ?? new Date(),\n updated: new Date(),\n };\n this.update.emit(data);\n\n const file = this._directory.getOrCreateFile('EchoMetadata');\n\n await this._writeFile(file, EchoMetadata, data);\n }\n\n private async _loadSpaceLargeMetadata(key: PublicKey): Promise<void> {\n const file = this._directory.getOrCreateFile(`space_${key.toHex()}_large`);\n try {\n const metadata = await this._readFile(file, LargeSpaceMetadata);\n if (metadata) {\n this._spaceLargeMetadata.set(key, metadata);\n }\n } catch (err: any) {\n log.error('failed to load space large metadata', { err });\n }\n }\n\n @synchronized\n private async _saveSpaceLargeMetadata(key: PublicKey): Promise<void> {\n const data = this._getLargeSpaceMetadata(key);\n const file = this._directory.getOrCreateFile(`space_${key.toHex()}_large`);\n await this._writeFile(file, LargeSpaceMetadata, data);\n }\n\n async flush() {\n await this._directory.flush();\n }\n\n _getSpace(spaceKey: PublicKey): SpaceMetadata {\n if (this._metadata.identity?.haloSpace.key.equals(spaceKey)) {\n // Check if the space is the identity space.\n return this._metadata.identity.haloSpace;\n }\n\n const space = this.spaces.find((space) => space.key.equals(spaceKey));\n invariant(space, 'Space not found');\n return space;\n }\n\n hasSpace(spaceKey: PublicKey): boolean {\n if (this._metadata.identity?.haloSpace.key.equals(spaceKey)) {\n // Check if the space is the identity space.\n return true;\n }\n\n return !!this.spaces.find((space) => space.key.equals(spaceKey));\n }\n\n private _getLargeSpaceMetadata(key: PublicKey): LargeSpaceMetadata {\n let entry = this._spaceLargeMetadata.get(key);\n if (entry) {\n return entry;\n }\n\n entry = emptyLargeSpaceMetadata();\n this._spaceLargeMetadata.set(key, entry);\n return entry;\n }\n\n /**\n * Clears storage - doesn't work for now.\n */\n async clear(): Promise<void> {\n log('clearing all metadata');\n await this._directory.delete();\n this._metadata = emptyEchoMetadata();\n }\n\n getIdentityRecord(): IdentityRecord | undefined {\n return this._metadata.identity;\n }\n\n async setIdentityRecord(record: IdentityRecord) {\n invariant(!this._metadata.identity, 'Cannot overwrite existing identity in metadata');\n\n this._metadata.identity = record;\n await this._save();\n await this.flush();\n }\n\n getInvitations(): Invitation[] {\n return this._metadata.invitations ?? [];\n }\n\n async addInvitation(invitation: Invitation) {\n if (this._metadata.invitations?.find((i) => i.invitationId === invitation.invitationId)) {\n return;\n }\n\n (this._metadata.invitations ??= []).push(invitation);\n await this._save();\n await this.flush();\n }\n\n async removeInvitation(invitationId: string) {\n this._metadata.invitations = (this._metadata.invitations ?? []).filter((i) => i.invitationId !== invitationId);\n await this._save();\n await this.flush();\n }\n\n async addSpace(record: SpaceMetadata) {\n invariant(\n !(this._metadata.spaces ?? []).find((space) => space.key.equals(record.key)),\n 'Cannot overwrite existing space in metadata',\n );\n\n (this._metadata.spaces ??= []).push(record);\n await this._save();\n await this.flush();\n }\n\n async setSpaceDataLatestTimeframe(spaceKey: PublicKey, timeframe: Timeframe) {\n this._getSpace(spaceKey).dataTimeframe = timeframe;\n await this._save();\n }\n\n async setSpaceControlLatestTimeframe(spaceKey: PublicKey, timeframe: Timeframe) {\n this._getSpace(spaceKey).controlTimeframe = timeframe;\n await this._save();\n await this.flush();\n }\n\n async setCache(spaceKey: PublicKey, cache: SpaceCache) {\n this._getSpace(spaceKey).cache = cache;\n await this._save();\n }\n\n async setWritableFeedKeys(spaceKey: PublicKey, controlFeedKey: PublicKey, dataFeedKey: PublicKey) {\n const space = this._getSpace(spaceKey);\n space.controlFeedKey = controlFeedKey;\n space.dataFeedKey = dataFeedKey;\n await this._save();\n await this.flush();\n }\n\n async setSpaceState(spaceKey: PublicKey, state: SpaceState) {\n this._getSpace(spaceKey).state = state;\n await this._save();\n await this.flush();\n }\n\n getSpaceControlPipelineSnapshot(spaceKey: PublicKey): ControlPipelineSnapshot | undefined {\n return this._getLargeSpaceMetadata(spaceKey).controlPipelineSnapshot;\n }\n\n async setSpaceControlPipelineSnapshot(spaceKey: PublicKey, snapshot: ControlPipelineSnapshot) {\n this._getLargeSpaceMetadata(spaceKey).controlPipelineSnapshot = snapshot;\n await this._saveSpaceLargeMetadata(spaceKey);\n await this.flush();\n }\n\n getSpaceEdgeReplicationSetting(spaceKey: PublicKey): EdgeReplicationSetting | undefined {\n return this.hasSpace(spaceKey) ? this._getSpace(spaceKey).edgeReplication : undefined;\n }\n\n async setSpaceEdgeReplicationSetting(spaceKey: PublicKey, setting: EdgeReplicationSetting) {\n this._getSpace(spaceKey).edgeReplication = setting;\n await this._save();\n await this.flush();\n }\n}\n\nconst fromBytesInt32 = (buf: Buffer) => buf.readInt32LE(0);\n\nexport const hasInvitationExpired = (invitation: Invitation): boolean => {\n return Boolean(\n invitation.created &&\n invitation.lifetime &&\n invitation.lifetime !== 0 &&\n invitation.created.getTime() + invitation.lifetime * 1000 < Date.now(),\n );\n};\n\n// TODO: remove once \"multiuse\" type invitations get removed from local metadata of existing profiles\nconst isLegacyInvitationFormat = (invitation: Invitation): boolean => {\n return invitation.type === Invitation.Type.MULTIUSE;\n};\n", "//\n// Copyright 2020 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { timed } from '@dxos/debug';\nimport { type FeedIndex } from '@dxos/feed-store';\nimport { type PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { Timeframe } from '@dxos/timeframe';\n\nexport const mapTimeframeToFeedIndexes = (timeframe: Timeframe): FeedIndex[] =>\n timeframe.frames().map(([feedKey, index]) => ({ feedKey, index }));\n\nexport const mapFeedIndexesToTimeframe = (indexes: FeedIndex[]): Timeframe =>\n new Timeframe(indexes.map(({ feedKey, index }) => [feedKey, index]));\n\nexport const startAfter = (timeframe: Timeframe): FeedIndex[] =>\n timeframe.frames().map(([feedKey, index]) => ({ feedKey, index: index + 1 }));\n\n/**\n * Keeps state of the last timeframe that was processed by ECHO.\n */\nexport class TimeframeClock {\n readonly update = new Event<Timeframe>();\n\n private _pendingTimeframe: Timeframe;\n\n constructor(private _timeframe = new Timeframe()) {\n this._pendingTimeframe = _timeframe;\n }\n\n /**\n * Timeframe that was processed by ECHO.\n */\n get timeframe() {\n return this._timeframe;\n }\n\n /**\n * Timeframe that is currently being processed by ECHO.\n * Will be equal to `timeframe` after the processing is complete.\n */\n get pendingTimeframe() {\n return this._pendingTimeframe;\n }\n\n setTimeframe(timeframe: Timeframe) {\n this._timeframe = timeframe;\n this._pendingTimeframe = timeframe;\n this.update.emit(this._timeframe);\n }\n\n updatePendingTimeframe(key: PublicKey, seq: number) {\n this._pendingTimeframe = Timeframe.merge(this._pendingTimeframe, new Timeframe([[key, seq]]));\n }\n\n updateTimeframe() {\n this._timeframe = this._pendingTimeframe;\n this.update.emit(this._timeframe);\n }\n\n hasGaps(timeframe: Timeframe) {\n const gaps = Timeframe.dependencies(timeframe, this._timeframe);\n return !gaps.isEmpty();\n }\n\n @timed(5_000)\n async waitUntilReached(target: Timeframe) {\n log('waitUntilReached', { target, current: this._timeframe });\n await this.update.waitForCondition(() => {\n log('check if reached', {\n target,\n current: this._timeframe,\n deps: Timeframe.dependencies(target, this._timeframe),\n });\n\n return Timeframe.dependencies(target, this._timeframe).isEmpty();\n });\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Event, sleepWithContext, synchronized, Trigger } from '@dxos/async';\nimport { Context, rejectOnDispose } from '@dxos/context';\nimport { failUndefined } from '@dxos/debug';\nimport { FeedSetIterator, type FeedWrapper, type FeedWriter } from '@dxos/feed-store';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type FeedMessageBlock } from '@dxos/protocols';\nimport type { FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\nimport { Timeframe } from '@dxos/timeframe';\nimport { ComplexMap } from '@dxos/util';\n\nimport { createMessageSelector } from './message-selector';\nimport { mapFeedIndexesToTimeframe, startAfter, TimeframeClock } from './timeframe-clock';\nimport { createMappedFeedWriter } from '../common';\n\nexport type WaitUntilReachedTargetParams = {\n /**\n * For cancellation.\n */\n ctx?: Context;\n timeout?: number;\n\n /**\n * @default true\n */\n breakOnStall?: boolean;\n};\n\n/**\n * External state accessor.\n */\nexport class PipelineState {\n /**\n * @internal\n */\n _ctx = new Context();\n\n // TODO(dmaretskyi): Remove?.\n public readonly timeframeUpdate = this._timeframeClock.update;\n\n public readonly stalled = new Event();\n\n /**\n * @internal\n */\n _startTimeframe: Timeframe = new Timeframe();\n\n /**\n * Target timeframe we are waiting to reach.\n */\n private _targetTimeframe: Timeframe | undefined;\n\n /**\n * @internal\n */\n _reachedTargetPromise: Promise<void> | undefined;\n\n /**\n * @internal\n */\n _reachedTarget: boolean = false;\n\n constructor(\n private _feeds: ComplexMap<PublicKey, FeedWrapper<FeedMessage>>,\n private _timeframeClock: TimeframeClock,\n ) {}\n\n /**\n * Latest theoretical timeframe based on the last mutation in each feed.\n * NOTE: This might never be reached if the mutation dependencies\n */\n // TODO(dmaretskyi): Rename `totalTimeframe`? or `lastTimeframe`.\n get endTimeframe() {\n return mapFeedIndexesToTimeframe(\n Array.from(this._feeds.values())\n .filter((feed) => feed.length > 0)\n .map((feed) => ({\n feedKey: feed.key,\n index: feed.length - 1,\n })),\n );\n }\n\n get startTimeframe() {\n return this._startTimeframe;\n }\n\n get timeframe() {\n return this._timeframeClock.timeframe;\n }\n\n get pendingTimeframe() {\n return this._timeframeClock.pendingTimeframe;\n }\n\n get targetTimeframe() {\n return this._targetTimeframe ? this._targetTimeframe : new Timeframe();\n }\n\n get reachedTarget() {\n return this._reachedTarget;\n }\n\n get feeds() {\n return Array.from(this._feeds.values());\n }\n\n async waitUntilTimeframe(target: Timeframe) {\n await this._timeframeClock.waitUntilReached(target);\n }\n\n setTargetTimeframe(target: Timeframe) {\n this._targetTimeframe = target;\n }\n\n /**\n * Wait until the pipeline processes all messages in the feed and reaches the target timeframe if that is set.\n *\n * This function will resolve immediately if the pipeline is stalled.\n *\n * @param timeout Timeout in milliseconds to specify the maximum wait time.\n */\n async waitUntilReachedTargetTimeframe({\n ctx = new Context(),\n timeout,\n breakOnStall = true,\n }: WaitUntilReachedTargetParams = {}) {\n log('waitUntilReachedTargetTimeframe', {\n timeout,\n current: this.timeframe,\n target: this.targetTimeframe,\n });\n\n this._reachedTargetPromise ??= Promise.race([\n this._timeframeClock.update.waitForCondition(() => {\n return Timeframe.dependencies(this.targetTimeframe, this.timeframe).isEmpty();\n }),\n ...(breakOnStall ? [this.stalled.discardParameter().waitForCount(1)] : []),\n ]);\n\n let done = false;\n\n if (timeout) {\n return Promise.race([\n rejectOnDispose(ctx),\n rejectOnDispose(this._ctx),\n this._reachedTargetPromise.then(() => {\n done = true;\n this._reachedTarget = true;\n }),\n sleepWithContext(this._ctx, timeout).then(() => {\n if (done) {\n return;\n }\n\n log.warn('waitUntilReachedTargetTimeframe timed out', {\n timeout,\n current: this.timeframe,\n target: this.targetTimeframe,\n dependencies: Timeframe.dependencies(this.targetTimeframe, this.timeframe),\n });\n }),\n ]);\n } else {\n return this._reachedTargetPromise;\n }\n }\n}\n\n// TODO(mykola): Extract to `@dxos/echo-protocol`\nexport interface PipelineAccessor {\n state: PipelineState;\n writer: FeedWriter<FeedMessage.Payload>;\n}\n\n/**\n * A multi-reader pipeline that operates on feeds.\n * Might have a single writable feed.\n * Has a timeframe clock to handle message ordering.\n *\n * NOTE:\n * - Feeds passed in must have value encoding consistent with the type expected by the iterator/writer.\n *\n * # Usage examples\n *\n * ## Create a new space.\n *\n * 1. Generate space key, genesis feed key.\n * 2. Create and open pipeline reading from {}.\n * 3. Create and add the writable genesis feed.\n * 4. Write the initial sequence of control and credential messages.\n *\n * ## Load an existing space from storage\n *\n * 1. Load space key, genesis feed key, get starting timeframe from saved snapshot.\n * 2. Create and open pipeline reading from the initial timeframe.\n * 3. Open and add the genesis feed.\n * 4. Once the writable feed is added, the pipeline becomes writable.\n *\n * ## Join an existing space created by another agent/device.\n *\n * 1. Get the space key, genesis feed key from another agent.\n * 2. (optionally) Download the snapshot from another agent.\n * 3. Create and open pipeline.\n * 4. Generate the writable feed key.\n * 5. Wait for the writable feed to be added.\n */\nexport class Pipeline implements PipelineAccessor {\n private readonly _timeframeClock = new TimeframeClock(new Timeframe());\n private readonly _feeds = new ComplexMap<PublicKey, FeedWrapper<FeedMessage>>(PublicKey.hash);\n\n // External state accessor.\n private readonly _state: PipelineState = new PipelineState(this._feeds, this._timeframeClock);\n\n // Waits for the message consumer to process the message and yield control back to the pipeline.\n private readonly _processingTrigger = new Trigger().wake();\n private readonly _pauseTrigger = new Trigger().wake();\n\n // Pending downloads.\n private readonly _downloads = new ComplexMap<FeedWrapper<FeedMessage>, any>((value) => PublicKey.hash(value.key));\n\n // Inbound feed stream.\n private _feedSetIterator?: FeedSetIterator<FeedMessage>;\n\n // Outbound feed writer.\n private _writer: FeedWriter<FeedMessage.Payload> | undefined;\n\n private _isStopping = false;\n private _isStarted = false;\n private _isBeingConsumed = false;\n private _isPaused = false;\n\n get state() {\n return this._state;\n }\n\n get writer(): FeedWriter<FeedMessage.Payload> {\n invariant(this._writer, 'Writer not set.');\n return this._writer;\n }\n\n hasFeed(feedKey: PublicKey) {\n return this._feeds.has(feedKey);\n }\n\n getFeeds(): FeedWrapper<FeedMessage>[] {\n return this._feedSetIterator!.feeds;\n }\n\n // NOTE: This cannot be synchronized with `stop` because stop waits for the mutation processing to complete,\n // which might be opening feeds during the mutation processing, which w\n async addFeed(feed: FeedWrapper<FeedMessage>) {\n this._feeds.set(feed.key, feed);\n\n if (this._feedSetIterator) {\n await this._feedSetIterator.addFeed(feed);\n }\n\n if (this._isStarted && !this._isPaused) {\n this._setFeedDownloadState(feed);\n }\n }\n\n setWriteFeed(feed: FeedWrapper<FeedMessage>) {\n invariant(!this._writer, 'Writer already set.');\n invariant(feed.properties.writable, 'Feed must be writable.');\n\n this._writer = createMappedFeedWriter<FeedMessage.Payload, FeedMessage>(\n (payload: FeedMessage.Payload) => ({\n timeframe: this._timeframeClock.timeframe,\n payload,\n }),\n feed.createFeedWriter(),\n );\n }\n\n @synchronized\n async start() {\n invariant(!this._isStarted, 'Pipeline is already started.');\n log('starting...');\n await this._initIterator();\n await this._feedSetIterator!.open();\n this._isStarted = true;\n log('started');\n\n if (!this._isPaused) {\n for (const feed of this._feeds.values()) {\n this._setFeedDownloadState(feed);\n }\n }\n }\n\n @synchronized\n async stop() {\n log('stopping...');\n this._isStopping = true;\n for (const [feed, handle] of this._downloads.entries()) {\n feed.undownload(handle);\n }\n this._downloads.clear();\n await this._feedSetIterator?.close();\n await this._processingTrigger.wait(); // Wait for the in-flight message to be processed.\n await this._state._ctx.dispose();\n this._state._ctx = new Context();\n this._state._reachedTargetPromise = undefined;\n this._state._reachedTarget = false;\n this._isStarted = false;\n log('stopped');\n }\n\n /**\n * @param timeframe Timeframe of already processed messages.\n * The pipeline will start processing messages AFTER this timeframe.\n */\n @synchronized\n async setCursor(timeframe: Timeframe) {\n invariant(!this._isStarted || this._isPaused, 'Invalid state.');\n\n this._state._startTimeframe = timeframe;\n this._timeframeClock.setTimeframe(timeframe);\n\n // Cancel downloads of mutations before the cursor.\n if (this._feedSetIterator) {\n await this._feedSetIterator.close();\n await this._initIterator();\n await this._feedSetIterator.open();\n }\n }\n\n /**\n * Calling pause while processing will cause a deadlock.\n */\n @synchronized\n async pause() {\n if (this._isPaused) {\n return;\n }\n\n this._pauseTrigger.reset();\n await this._processingTrigger.wait();\n this._isPaused = true;\n }\n\n @synchronized\n async unpause() {\n invariant(this._isPaused, 'Pipeline is not paused.');\n\n this._pauseTrigger.wake();\n this._isPaused = false;\n\n for (const feed of this._feeds.values()) {\n this._setFeedDownloadState(feed);\n }\n }\n\n /**\n * Starts to iterate over the ordered messages from the added feeds.\n * Updates the timeframe clock after the message has bee processed.\n */\n async *consume(): AsyncIterable<FeedMessageBlock> {\n invariant(!this._isBeingConsumed, 'Pipeline is already being consumed.');\n this._isBeingConsumed = true;\n\n invariant(this._feedSetIterator, 'Iterator not initialized.');\n let lastFeedSetIterator = this._feedSetIterator;\n let iterable = lastFeedSetIterator[Symbol.asyncIterator]();\n\n while (!this._isStopping) {\n await this._pauseTrigger.wait();\n\n // Iterator might have been changed while we were waiting for the processing to complete.\n if (lastFeedSetIterator !== this._feedSetIterator) {\n invariant(this._feedSetIterator, 'Iterator not initialized.');\n lastFeedSetIterator = this._feedSetIterator;\n iterable = lastFeedSetIterator[Symbol.asyncIterator]();\n }\n\n // Will be canceled when the iterator gets closed.\n const { done, value } = await iterable.next();\n if (!done) {\n const block = value ?? failUndefined();\n this._processingTrigger.reset();\n this._timeframeClock.updatePendingTimeframe(PublicKey.from(block.feedKey), block.seq);\n yield block;\n this._processingTrigger.wake();\n this._timeframeClock.updateTimeframe();\n }\n }\n\n // TODO(burdon): Test re-entrant?\n this._isBeingConsumed = false;\n }\n\n private _setFeedDownloadState(feed: FeedWrapper<FeedMessage>) {\n let handle = this._downloads.get(feed); // TODO(burdon): Always undefined?\n if (handle) {\n feed.undownload(handle);\n }\n\n const timeframe = this._state._startTimeframe;\n const seq = timeframe.get(feed.key) ?? -1;\n log('download', { feed: feed.key.truncate(), seq, length: feed.length });\n handle = feed.download({ start: seq + 1, linear: true }, (err: any, data: any) => {\n if (err) {\n // log.warn(err); // TODO(burdon): Feed is closed/Download was cancelled.\n } else {\n log.info('downloaded', { data }); // TODO(burdon): Never called.\n }\n });\n\n this._downloads.set(feed, handle);\n }\n\n private async _initIterator() {\n this._feedSetIterator = new FeedSetIterator<FeedMessage>(createMessageSelector(this._timeframeClock), {\n start: startAfter(this._timeframeClock.timeframe),\n stallTimeout: 1000,\n });\n\n this._feedSetIterator.stalled.on((iterator) => {\n log.warn(`Stalled after ${iterator.options.stallTimeout}ms with ${iterator.size} feeds.`, {\n currentTimeframe: this._timeframeClock.timeframe,\n targetTimeframe: this._state.targetTimeframe,\n });\n this._state.stalled.emit();\n });\n\n for (const feed of this._feeds.values()) {\n await this._feedSetIterator.addFeed(feed);\n }\n }\n}\n", "//\n// Copyright 2020 DXOS.org\n//\n\nimport { type FeedBlock, type FeedBlockSelector } from '@dxos/feed-store';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport type { FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\n\nimport { type TimeframeClock } from './timeframe-clock';\n\n/**\n * The MessageSelector makes sure that we read in a trusted order.\n * The first message we wish to process is the SpaceGenesis, which will admit a Feed.\n * As we encounter and process FeedAdmit messages those are added to the Space's trust,\n * and we begin processing messages from them as well.\n */\nexport const createMessageSelector = (timeframeClock: TimeframeClock): FeedBlockSelector<FeedMessage> => {\n return (messages: FeedBlock<FeedMessage>[]) => {\n // Pick the first candidate with a valid timeframe that has no gaps.\n for (let i = 0; i < messages.length; i++) {\n const {\n data: { timeframe },\n } = messages[i];\n invariant(timeframe);\n\n if (!timeframeClock.hasGaps(timeframe)) {\n return i;\n }\n }\n\n // Not ready for this message yet.\n log('Skipping...');\n };\n};\n", "//\n// Copyright 2019 DXOS.org\n//\n\nimport { runInContext, scheduleTask } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { randomBytes } from '@dxos/crypto';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { schema } from '@dxos/protocols/proto';\nimport { type AuthService } from '@dxos/protocols/proto/dxos/mesh/teleport/auth';\nimport { type ExtensionContext, RpcExtension } from '@dxos/teleport';\n\nexport type AuthProvider = (nonce: Uint8Array) => Promise<Uint8Array | undefined>;\n\nexport type AuthVerifier = (nonce: Uint8Array, credential: Uint8Array) => Promise<boolean>;\n\nexport type AuthExtensionParams = {\n provider: AuthProvider;\n verifier: AuthVerifier;\n onAuthSuccess: () => void;\n onAuthFailure: () => void;\n};\n\nexport class AuthExtension extends RpcExtension<Services, Services> {\n private readonly _ctx = new Context({\n onError: (err) => {\n log.catch(err);\n },\n });\n\n constructor(private readonly _authParams: AuthExtensionParams) {\n super({\n requested: {\n AuthService: schema.getService('dxos.mesh.teleport.auth.AuthService'),\n },\n exposed: {\n AuthService: schema.getService('dxos.mesh.teleport.auth.AuthService'),\n },\n timeout: 60 * 1000, // Long timeout because auth can wait for sync in certain cases.\n });\n }\n\n protected async getHandlers(): Promise<Services> {\n return {\n AuthService: {\n authenticate: async ({ challenge }) => {\n try {\n const credential = await this._authParams.provider(challenge);\n if (!credential) {\n throw new Error('auth rejected');\n }\n return { credential };\n } catch (err) {\n log.error('failed to generate auth credentials', err);\n throw new Error('auth rejected');\n }\n },\n },\n };\n }\n\n override async onOpen(context: ExtensionContext): Promise<void> {\n await super.onOpen(context);\n scheduleTask(this._ctx, async () => {\n try {\n const challenge = randomBytes(32);\n const { credential } = await this.rpc.AuthService.authenticate({ challenge });\n invariant(credential?.length > 0, 'invalid credential');\n const success = await this._authParams.verifier(challenge, credential);\n invariant(success, 'credential not verified');\n runInContext(this._ctx, () => this._authParams.onAuthSuccess());\n } catch (err) {\n log('auth failed', err);\n this.close();\n this._authParams.onAuthFailure();\n }\n });\n }\n\n override async onClose(): Promise<void> {\n await this._ctx.dispose();\n await super.onClose();\n }\n\n override async onAbort(): Promise<void> {\n await this._ctx.dispose();\n await super.onAbort();\n }\n}\n\ntype Services = { AuthService: AuthService };\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Event, scheduleMicroTask, synchronized, trackLeaks } from '@dxos/async';\nimport { type Context, Resource } from '@dxos/context';\nimport { type DelegateInvitationCredential, type FeedInfo, type MemberInfo } from '@dxos/credentials';\nimport { type FeedOptions, type FeedWrapper } from '@dxos/feed-store';\nimport { invariant } from '@dxos/invariant';\nimport { type PublicKey, type SpaceId } from '@dxos/keys';\nimport { log, logInfo } from '@dxos/log';\nimport type { FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\nimport { AdmittedFeed, type Credential } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { type Timeframe } from '@dxos/timeframe';\nimport { trace } from '@dxos/tracing';\nimport { type AsyncCallback, Callback } from '@dxos/util';\n\nimport { ControlPipeline } from './control-pipeline';\nimport { type SpaceProtocol } from './space-protocol';\nimport { type MetadataStore } from '../metadata';\nimport { type PipelineAccessor } from '../pipeline';\n\n// TODO(burdon): Factor out?\ntype FeedProvider = (feedKey: PublicKey, opts?: FeedOptions) => Promise<FeedWrapper<FeedMessage>>;\n\nexport type SpaceParams = {\n id: SpaceId;\n spaceKey: PublicKey;\n protocol: SpaceProtocol;\n genesisFeed: FeedWrapper<FeedMessage>;\n feedProvider: FeedProvider;\n metadataStore: MetadataStore;\n memberKey: PublicKey;\n\n // TODO(dmaretskyi): Superseded by epochs.\n snapshotId?: string | undefined;\n\n onDelegatedInvitationStatusChange: (invitation: DelegateInvitationCredential, isActive: boolean) => Promise<void>;\n onMemberRolesChanged: (member: MemberInfo[]) => Promise<void>;\n};\n\nexport type CreatePipelineParams = {\n start: Timeframe;\n // designation: AdmittedFeed.Designation;\n};\n\n/**\n * Spaces are globally addressable databases with access control.\n */\n// TODO(dmaretskyi): Extract database stuff.\n// TODO(dmaretskyi): Rename HaloGraph move to HALO.\n@trackLeaks('open', 'close')\n@trace.resource()\nexport class Space extends Resource {\n public readonly onCredentialProcessed = new Callback<AsyncCallback<Credential>>();\n public readonly stateUpdate = new Event();\n @trace.info()\n public readonly protocol: SpaceProtocol;\n\n private readonly _id: SpaceId;\n private readonly _key: PublicKey;\n private readonly _genesisFeedKey: PublicKey;\n private readonly _feedProvider: FeedProvider;\n @trace.info()\n private readonly _controlPipeline: ControlPipeline;\n\n private _controlFeed?: FeedWrapper<FeedMessage>;\n private _dataFeed?: FeedWrapper<FeedMessage>;\n\n constructor(params: SpaceParams) {\n super();\n invariant(params.spaceKey && params.feedProvider);\n this._id = params.id;\n this._key = params.spaceKey;\n this._genesisFeedKey = params.genesisFeed.key;\n this._feedProvider = params.feedProvider;\n\n this._controlPipeline = new ControlPipeline({\n spaceKey: params.spaceKey,\n genesisFeed: params.genesisFeed,\n feedProvider: params.feedProvider,\n metadataStore: params.metadataStore,\n });\n\n // TODO(dmaretskyi): Feed set abstraction.\n this._controlPipeline.onFeedAdmitted.set(async (info) => {\n // Enable sparse replication to not download mutations covered by prior epochs.\n const sparse = info.assertion.designation === AdmittedFeed.Designation.DATA;\n\n if (!info.key.equals(params.genesisFeed.key)) {\n scheduleMicroTask(this._ctx, async () => {\n await this.protocol.addFeed(await params.feedProvider(info.key, { sparse }));\n });\n }\n });\n\n this._controlPipeline.onCredentialProcessed.set(async (credential) => {\n await this.onCredentialProcessed.callIfSet(credential);\n log('onCredentialProcessed', { credential });\n this.stateUpdate.emit();\n });\n this._controlPipeline.onDelegatedInvitation.set(async (invitation) => {\n log('onDelegatedInvitation', { invitation });\n await params.onDelegatedInvitationStatusChange(invitation, true);\n });\n this._controlPipeline.onDelegatedInvitationRemoved.set(async (invitation) => {\n log('onDelegatedInvitationRemoved', { invitation });\n await params.onDelegatedInvitationStatusChange(invitation, false);\n });\n this._controlPipeline.onMemberRoleChanged.set(async (changedMembers) => {\n log('onMemberRoleChanged', () => ({ changedMembers: changedMembers.map((m) => [m.key, m.role]) }));\n await params.onMemberRolesChanged(changedMembers);\n });\n\n // Start replicating the genesis feed.\n this.protocol = params.protocol;\n }\n\n @logInfo\n @trace.info()\n get id() {\n return this._id;\n }\n\n @logInfo\n @trace.info()\n get key() {\n return this._key;\n }\n\n get genesisFeedKey(): PublicKey {\n return this._genesisFeedKey;\n }\n\n get controlFeedKey() {\n return this._controlFeed?.key;\n }\n\n get dataFeedKey() {\n return this._dataFeed?.key;\n }\n\n get spaceState() {\n return this._controlPipeline.spaceState;\n }\n\n /**\n * @test-only\n */\n get controlPipeline(): PipelineAccessor {\n return this._controlPipeline.pipeline;\n }\n\n async setControlFeed(feed: FeedWrapper<FeedMessage>) {\n invariant(!this._controlFeed, 'Control feed already set.');\n this._controlFeed = feed;\n await this._controlPipeline.setWriteFeed(feed);\n return this;\n }\n\n async setDataFeed(feed: FeedWrapper<FeedMessage>) {\n invariant(!this._dataFeed, 'Data feed already set.');\n this._dataFeed = feed;\n return this;\n }\n\n /**\n * Use for diagnostics.\n */\n getControlFeeds(): FeedInfo[] {\n return Array.from(this._controlPipeline.spaceState.feeds.values());\n }\n\n @trace.span()\n protected override async _open(ctx: Context) {\n log('opening...');\n\n // Order is important.\n await this._controlPipeline.start();\n\n log('opened');\n }\n\n @synchronized\n public async startProtocol() {\n invariant(this.isOpen);\n await this.protocol.start();\n await this.protocol.addFeed(await this._feedProvider(this._genesisFeedKey));\n }\n\n @synchronized\n protected override async _close() {\n log('closing...', { key: this._key });\n\n // Closes in reverse order to open.\n await this.protocol.stop();\n await this._controlPipeline.stop();\n\n log('closed');\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { DeferredTask, sleepWithContext, trackLeaks } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport {\n SpaceStateMachine,\n type SpaceState,\n type MemberInfo,\n type FeedInfo,\n type DelegateInvitationCredential,\n} from '@dxos/credentials';\nimport { type FeedWrapper } from '@dxos/feed-store';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type FeedMessageBlock } from '@dxos/protocols';\nimport type { FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\nimport { type ControlPipelineSnapshot } from '@dxos/protocols/proto/dxos/echo/metadata';\nimport { AdmittedFeed, type Credential } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { Timeframe } from '@dxos/timeframe';\nimport { TimeSeriesCounter, TimeUsageCounter, trace } from '@dxos/tracing';\nimport { type AsyncCallback, Callback, tracer } from '@dxos/util';\n\nimport { type MetadataStore } from '../metadata';\nimport { Pipeline, type PipelineAccessor } from '../pipeline';\n\nexport type ControlPipelineParams = {\n spaceKey: PublicKey;\n genesisFeed: FeedWrapper<FeedMessage>;\n feedProvider: (feedKey: PublicKey) => Promise<FeedWrapper<FeedMessage>>;\n metadataStore: MetadataStore;\n};\n\nconst TIMEFRAME_SAVE_DEBOUNCE_INTERVAL = 500;\n\nconst CONTROL_PIPELINE_SNAPSHOT_DELAY = 10_000;\n\nconst USE_SNAPSHOTS = true;\n\n/**\n * Processes HALO credentials, which include genesis and invitations.\n */\n@trace.resource()\n@trackLeaks('start', 'stop')\nexport class ControlPipeline {\n private readonly _ctx = new Context();\n private readonly _pipeline: Pipeline;\n private readonly _spaceStateMachine: SpaceStateMachine;\n\n private readonly _spaceKey: PublicKey;\n private readonly _metadata: MetadataStore;\n private _targetTimeframe?: Timeframe;\n private _lastTimeframeSaveTime: number = Date.now();\n\n public readonly onFeedAdmitted = new Callback<AsyncCallback<FeedInfo>>();\n public readonly onMemberRoleChanged: Callback<AsyncCallback<MemberInfo[]>>;\n public readonly onCredentialProcessed: Callback<AsyncCallback<Credential>>;\n public readonly onDelegatedInvitation: Callback<AsyncCallback<DelegateInvitationCredential>>;\n public readonly onDelegatedInvitationRemoved: Callback<AsyncCallback<DelegateInvitationCredential>>;\n\n @trace.metricsCounter()\n private _usage = new TimeUsageCounter();\n\n @trace.metricsCounter()\n private _mutations = new TimeSeriesCounter();\n\n private _snapshotTask = new DeferredTask(this._ctx, async () => {\n await sleepWithContext(this._ctx, CONTROL_PIPELINE_SNAPSHOT_DELAY);\n await this._saveSnapshot();\n });\n\n constructor({ spaceKey, genesisFeed, feedProvider, metadataStore }: ControlPipelineParams) {\n this._spaceKey = spaceKey;\n this._metadata = metadataStore;\n this._pipeline = new Pipeline();\n void this._pipeline.addFeed(genesisFeed); // TODO(burdon): Require async open/close?\n\n this._spaceStateMachine = new SpaceStateMachine(spaceKey);\n this._spaceStateMachine.onFeedAdmitted.set(async (info) => {\n // log('feed admitted', { info });\n log('feed admitted', { key: info.key });\n\n // TODO(burdon): Check not stopping.\n if (info.assertion.designation === AdmittedFeed.Designation.CONTROL && !info.key.equals(genesisFeed.key)) {\n queueMicrotask(async () => {\n try {\n const feed = await feedProvider(info.key);\n if (!this._pipeline.hasFeed(feed.key)) {\n await this._pipeline.addFeed(feed);\n }\n } catch (err: any) {\n log.catch(err);\n }\n });\n }\n\n await this.onFeedAdmitted.callIfSet(info);\n });\n\n this.onMemberRoleChanged = this._spaceStateMachine.onMemberRoleChanged;\n this.onCredentialProcessed = this._spaceStateMachine.onCredentialProcessed;\n this.onDelegatedInvitation = this._spaceStateMachine.onDelegatedInvitation;\n this.onDelegatedInvitationRemoved = this._spaceStateMachine.onDelegatedInvitationRemoved;\n }\n\n get spaceState(): SpaceState {\n return this._spaceStateMachine;\n }\n\n get pipeline(): PipelineAccessor {\n return this._pipeline;\n }\n\n async setWriteFeed(feed: FeedWrapper<FeedMessage>) {\n await this._pipeline.addFeed(feed);\n this._pipeline.setWriteFeed(feed);\n }\n\n @trace.span({ showInBrowserTimeline: true })\n async start() {\n const snapshot = this._metadata.getSpaceControlPipelineSnapshot(this._spaceKey);\n log('load snapshot', { key: this._spaceKey, present: !!snapshot, tf: snapshot?.timeframe });\n if (USE_SNAPSHOTS && snapshot) {\n await this._processSnapshot(snapshot);\n }\n\n log('starting...');\n setTimeout(async () => {\n void this._consumePipeline(new Context());\n });\n\n await this._pipeline.start();\n log('started');\n }\n\n private async _processSnapshot(snapshot: ControlPipelineSnapshot) {\n await this._pipeline.setCursor(snapshot.timeframe);\n\n for (const message of snapshot.messages ?? []) {\n const result = await this._spaceStateMachine.process(message.credential, {\n sourceFeed: message.feedKey,\n skipVerification: true,\n });\n\n if (!result) {\n log.warn('credential processing failed from snapshot', { message });\n }\n }\n }\n\n private async _saveSnapshot() {\n await this._pipeline.pause();\n const snapshot: ControlPipelineSnapshot = {\n timeframe: this._pipeline.state.timeframe,\n messages: this._spaceStateMachine.credentialEntries.map((entry) => ({\n feedKey: entry.sourceFeed,\n credential: entry.credential,\n })),\n };\n await this._pipeline.unpause();\n\n log('save snapshot', { key: this._spaceKey, snapshot: getSnapshotLoggerContext(snapshot) });\n await this._metadata.setSpaceControlPipelineSnapshot(this._spaceKey, snapshot);\n }\n\n @trace.span()\n private async _consumePipeline(ctx: Context) {\n for await (const msg of this._pipeline.consume()) {\n const span = this._usage.beginRecording();\n this._mutations.inc();\n\n try {\n await this._processMessage(ctx, msg);\n } catch (err: any) {\n log.catch(err);\n }\n\n span.end();\n }\n }\n\n @trace.span()\n private async _processMessage(ctx: Context, msg: FeedMessageBlock): Promise<void> {\n log('processing', { key: msg.feedKey, seq: msg.seq });\n if (msg.data.payload.credential) {\n const timer = tracer.mark('dxos.echo.pipeline.control');\n const result = await this._spaceStateMachine.process(msg.data.payload.credential.credential, {\n sourceFeed: PublicKey.from(msg.feedKey),\n });\n\n timer.end();\n if (!result) {\n log.warn('processing failed', { msg });\n } else {\n await this._noteTargetStateIfNeeded(this._pipeline.state.pendingTimeframe);\n }\n\n this._snapshotTask.schedule();\n }\n }\n\n private async _noteTargetStateIfNeeded(timeframe: Timeframe) {\n // TODO(dmaretskyi): Replace this with a proper debounce/throttle.\n\n if (Date.now() - this._lastTimeframeSaveTime > TIMEFRAME_SAVE_DEBOUNCE_INTERVAL) {\n this._lastTimeframeSaveTime = Date.now();\n\n await this._saveTargetTimeframe(timeframe);\n }\n }\n\n async stop() {\n log('stopping...');\n await this._ctx.dispose();\n await this._pipeline.stop();\n await this._saveTargetTimeframe(this._pipeline.state.timeframe);\n log('stopped');\n }\n\n private async _saveTargetTimeframe(timeframe: Timeframe) {\n try {\n const newTimeframe = Timeframe.merge(this._targetTimeframe ?? new Timeframe(), timeframe);\n await this._metadata.setSpaceControlLatestTimeframe(this._spaceKey, newTimeframe);\n this._targetTimeframe = newTimeframe;\n } catch (err: any) {\n log(err);\n }\n }\n}\n\nconst getSnapshotLoggerContext = (snapshot: ControlPipelineSnapshot) => {\n return snapshot.messages?.map((msg) => {\n const issuer = msg.credential.issuer;\n const subject = msg.credential.subject.id;\n const type = msg.credential.subject.assertion['@type'];\n return { issuer, subject, type };\n });\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { scheduleTask, type Trigger } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { ProtocolError } from '@dxos/protocols';\nimport { schema } from '@dxos/protocols/proto';\nimport { type Credential } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport {\n type AdmissionDiscoveryService,\n type GetAdmissionCredentialResponse,\n type GetAdmissionCredentialRequest,\n} from '@dxos/protocols/proto/dxos/mesh/teleport';\nimport { type ExtensionContext, RpcExtension } from '@dxos/teleport';\n\nimport { type Space } from './space';\n\n/**\n * Guest's side for a connection to a concrete peer in p2p network during invitation.\n */\nexport class CredentialRetrieverExtension extends RpcExtension<\n { AdmissionDiscoveryService: AdmissionDiscoveryService },\n {}\n> {\n private _ctx = new Context();\n\n constructor(\n private readonly _request: GetAdmissionCredentialRequest,\n private readonly _onResult: Trigger<Credential>,\n ) {\n super({\n requested: {\n AdmissionDiscoveryService: schema.getService('dxos.mesh.teleport.AdmissionDiscoveryService'),\n },\n });\n }\n\n protected override async getHandlers(): Promise<{}> {\n return {};\n }\n\n override async onOpen(context: ExtensionContext) {\n await super.onOpen(context);\n scheduleTask(this._ctx, async () => {\n try {\n const result = await this.rpc.AdmissionDiscoveryService.getAdmissionCredential(this._request);\n this._onResult.wake(result.admissionCredential);\n } catch (err: any) {\n context.close(err);\n }\n });\n }\n\n override async onClose() {\n await this._ctx.dispose();\n }\n\n override async onAbort(): Promise<void> {\n await this._ctx.dispose();\n }\n}\n\nexport class CredentialServerExtension extends RpcExtension<\n {},\n { AdmissionDiscoveryService: AdmissionDiscoveryService }\n> {\n constructor(private readonly _space: Space) {\n super({\n exposed: {\n AdmissionDiscoveryService: schema.getService('dxos.mesh.teleport.AdmissionDiscoveryService'),\n },\n });\n }\n\n protected override async getHandlers(): Promise<{ AdmissionDiscoveryService: AdmissionDiscoveryService }> {\n return {\n AdmissionDiscoveryService: {\n getAdmissionCredential: async (\n request: GetAdmissionCredentialRequest,\n ): Promise<GetAdmissionCredentialResponse> => {\n const memberInfo = this._space.spaceState.members.get(request.memberKey);\n if (!memberInfo?.credential) {\n throw new ProtocolError('Space member not found.', request);\n }\n return { admissionCredential: memberInfo.credential };\n },\n },\n };\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { type Event } from '@dxos/async';\nimport { discoveryKey, subtleCrypto } from '@dxos/crypto';\nimport { type FeedWrapper } from '@dxos/feed-store';\nimport { PublicKey } from '@dxos/keys';\nimport { log, logInfo } from '@dxos/log';\nimport {\n MMSTTopology,\n type SwarmNetworkManager,\n type SwarmConnection,\n type WireProtocol,\n type WireProtocolParams,\n type WireProtocolProvider,\n} from '@dxos/network-manager';\nimport type { FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\nimport { type MuxerStats, Teleport } from '@dxos/teleport';\nimport { type BlobStore, BlobSync } from '@dxos/teleport-extension-object-sync';\nimport { ReplicatorExtension } from '@dxos/teleport-extension-replicator';\nimport { trace } from '@dxos/tracing';\nimport { CallbackCollection, ComplexMap, type AsyncCallback } from '@dxos/util';\n\nimport { AuthExtension, type AuthProvider, type AuthVerifier } from './auth';\n\nexport const MOCK_AUTH_PROVIDER: AuthProvider = async (nonce: Uint8Array) => Buffer.from('mock');\nexport const MOCK_AUTH_VERIFIER: AuthVerifier = async (nonce: Uint8Array, credential: Uint8Array) => true;\n\n// TODO(burdon): Reconcile with SigningContext (define types together).\nexport interface SwarmIdentity {\n peerKey: PublicKey;\n identityKey: PublicKey;\n credentialProvider: AuthProvider;\n credentialAuthenticator: AuthVerifier;\n}\n\nexport type SpaceProtocolOptions = {\n topic: PublicKey; // TODO(burdon): Rename?\n swarmIdentity: SwarmIdentity;\n networkManager: SwarmNetworkManager;\n\n blobStore: BlobStore;\n\n onFeed?: (feed: FeedWrapper<FeedMessage>) => Promise<void>;\n\n /**\n * Called when new session is authenticated.\n * Additional extensions can be added here.\n */\n onSessionAuth?: (session: Teleport) => void;\n onAuthFailure?: (session: Teleport) => void;\n\n disableP2pReplication?: boolean;\n};\n\n/**\n * Manages Teleport protocol stream creation and joining swarms with replication and presence extensions.\n */\n@trace.resource()\nexport class SpaceProtocol {\n private readonly _networkManager: SwarmNetworkManager;\n private readonly _swarmIdentity: SwarmIdentity;\n private readonly _onSessionAuth?: (session: Teleport) => void;\n private readonly _onAuthFailure?: (session: Teleport) => void;\n\n public readonly blobSync: BlobSync;\n\n private readonly _disableP2pReplication: boolean;\n\n @logInfo\n @trace.info()\n private readonly _topic: Promise<PublicKey>;\n\n @trace.info()\n private readonly _spaceKey: PublicKey;\n\n private readonly _feeds = new Set<FeedWrapper<FeedMessage>>();\n private readonly _sessions = new ComplexMap<PublicKey, SpaceProtocolSession>(PublicKey.hash);\n // TODO(burdon): Move to config (with sensible defaults).\n private readonly _topology = new MMSTTopology({\n originateConnections: 4,\n maxPeers: 10,\n sampleSize: 20,\n });\n\n private _connection?: SwarmConnection;\n\n public readonly feedAdded = new CallbackCollection<AsyncCallback<FeedWrapper<FeedMessage>>>();\n\n get sessions(): ReadonlyMap<PublicKey, SpaceProtocolSession> {\n return this._sessions;\n }\n\n get feeds(): ReadonlySet<FeedWrapper<FeedMessage>> {\n return this._feeds;\n }\n\n @logInfo\n private get _ownPeerKey() {\n return this._swarmIdentity.peerKey;\n }\n\n constructor({\n topic,\n swarmIdentity,\n networkManager,\n onSessionAuth,\n onAuthFailure,\n blobStore,\n disableP2pReplication,\n }: SpaceProtocolOptions) {\n this._spaceKey = topic;\n this._networkManager = networkManager;\n this._swarmIdentity = swarmIdentity;\n this._onSessionAuth = onSessionAuth;\n this._onAuthFailure = onAuthFailure;\n this.blobSync = new BlobSync({ blobStore });\n\n // TODO(burdon): Async race condition? Move to start?\n this._topic = subtleCrypto.digest('SHA-256', topic.asBuffer()).then(discoveryKey).then(PublicKey.from);\n\n this._disableP2pReplication = disableP2pReplication ?? false;\n }\n\n // TODO(burdon): Create abstraction for Space (e.g., add keys and have provider).\n async addFeed(feed: FeedWrapper<FeedMessage>) {\n log('addFeed', { key: feed.key });\n\n this._feeds.add(feed);\n for (const session of this._sessions.values()) {\n session.replicator.addFeed(feed);\n }\n\n await this.feedAdded.callSerial(feed);\n }\n\n // TODO(burdon): Rename open? Common open/close interfaces for all services?\n async start() {\n if (this._connection) {\n return;\n }\n\n // TODO(burdon): Document why empty buffer.\n const credentials = await this._swarmIdentity.credentialProvider(Buffer.from(''));\n\n await this.blobSync.open();\n\n log('starting...');\n const topic = await this._topic;\n this._connection = await this._networkManager.joinSwarm({\n protocolProvider: this._createProtocolProvider(credentials),\n topic,\n topology: this._topology,\n label: `swarm ${topic.truncate()} for space ${this._spaceKey.truncate()}`,\n });\n\n log('started');\n }\n\n public updateTopology() {\n this._topology.forceUpdate();\n }\n\n async stop() {\n await this.blobSync.close();\n\n if (this._connection) {\n log('stopping...');\n await this._connection.close();\n log('stopped');\n }\n }\n\n private _createProtocolProvider(credentials: Uint8Array | undefined): WireProtocolProvider {\n return (wireParams) => {\n const session = new SpaceProtocolSession({\n wireParams,\n swarmIdentity: this._swarmIdentity,\n onSessionAuth: this._onSessionAuth,\n onAuthFailure: this._onAuthFailure,\n blobSync: this.blobSync,\n disableP2pReplication: this._disableP2pReplication,\n });\n this._sessions.set(wireParams.remotePeerId, session);\n\n for (const feed of this._feeds) {\n session.replicator.addFeed(feed);\n }\n\n return session;\n };\n }\n}\n\nexport type SpaceProtocolSessionParams = {\n wireParams: WireProtocolParams;\n swarmIdentity: SwarmIdentity;\n\n blobSync: BlobSync;\n\n /**\n * Called when new session is authenticated.\n * Additional extensions can be added here.\n */\n onSessionAuth?: (session: Teleport) => void;\n\n onAuthFailure?: (session: Teleport) => void;\n\n disableP2pReplication?: boolean;\n};\n\nexport enum AuthStatus {\n INITIAL = 'INITIAL',\n SUCCESS = 'SUCCESS',\n FAILURE = 'FAILURE',\n}\n\n// TODO(dmaretskyi): Move to a separate file.\n/**\n * Represents a single connection to a remote peer\n */\nexport class SpaceProtocolSession implements WireProtocol {\n @logInfo\n private readonly _wireParams: WireProtocolParams;\n\n private readonly _disableP2pReplication: boolean;\n\n private readonly _onSessionAuth?: (session: Teleport) => void;\n private readonly _onAuthFailure?: (session: Teleport) => void;\n private readonly _swarmIdentity: SwarmIdentity;\n private readonly _blobSync: BlobSync;\n\n private readonly _teleport: Teleport;\n\n // TODO(dmaretskyi): Start with upload=false when switching it on the fly works.\n public readonly replicator = new ReplicatorExtension().setOptions({ upload: true });\n\n private _authStatus = AuthStatus.INITIAL;\n\n @logInfo\n get authStatus() {\n return this._authStatus;\n }\n\n get stats(): Event<MuxerStats> {\n return this._teleport.stats;\n }\n\n // TODO(dmaretskyi): Allow to pass in extra extensions.\n constructor({\n wireParams,\n swarmIdentity,\n onSessionAuth,\n onAuthFailure,\n blobSync,\n disableP2pReplication,\n }: SpaceProtocolSessionParams) {\n this._wireParams = wireParams;\n this._swarmIdentity = swarmIdentity;\n this._onSessionAuth = onSessionAuth;\n this._onAuthFailure = onAuthFailure;\n this._blobSync = blobSync;\n\n this._teleport = new Teleport(wireParams);\n\n this._disableP2pReplication = disableP2pReplication ?? false;\n }\n\n get stream() {\n return this._teleport.stream;\n }\n\n async open(sessionId?: PublicKey): Promise<void> {\n await this._teleport.open(sessionId);\n this._teleport.addExtension(\n 'dxos.mesh.teleport.auth',\n new AuthExtension({\n provider: this._swarmIdentity.credentialProvider,\n verifier: this._swarmIdentity.credentialAuthenticator,\n onAuthSuccess: () => {\n log('Peer authenticated');\n this._authStatus = AuthStatus.SUCCESS;\n this._onSessionAuth?.(this._teleport);\n // TODO(dmaretskyi): Configure replicator to upload.\n },\n onAuthFailure: () => {\n this._authStatus = AuthStatus.FAILURE;\n this._onAuthFailure?.(this._teleport);\n },\n }),\n );\n\n if (!this._disableP2pReplication) {\n this._teleport.addExtension('dxos.mesh.teleport.replicator', this.replicator);\n }\n this._teleport.addExtension('dxos.mesh.teleport.blobsync', this._blobSync.createExtension());\n }\n\n async close(): Promise<void> {\n log('close');\n await this._teleport.close();\n }\n\n async abort(): Promise<void> {\n await this._teleport.abort();\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { synchronized, trackLeaks, Trigger } from '@dxos/async';\nimport { type AutomergeUrl, parseAutomergeUrl } from '@dxos/automerge/automerge-repo';\nimport { getCredentialAssertion, type DelegateInvitationCredential, type MemberInfo } from '@dxos/credentials';\nimport { failUndefined } from '@dxos/debug';\nimport { type FeedStore } from '@dxos/feed-store';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type SwarmNetworkManager } from '@dxos/network-manager';\nimport { trace } from '@dxos/protocols';\nimport type { FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\nimport { type SpaceMetadata } from '@dxos/protocols/proto/dxos/echo/metadata';\nimport type { Credential } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { type Teleport } from '@dxos/teleport';\nimport { type BlobStore } from '@dxos/teleport-extension-object-sync';\nimport { ComplexMap } from '@dxos/util';\n\nimport { CredentialRetrieverExtension } from './admission-discovery-extension';\nimport { Space } from './space';\nimport { SpaceProtocol, type SwarmIdentity } from './space-protocol';\nimport { createIdFromSpaceKey } from '../common/space-id';\nimport { type MetadataStore } from '../metadata';\n\nexport type SpaceManagerParams = {\n feedStore: FeedStore<FeedMessage>;\n networkManager: SwarmNetworkManager;\n metadataStore: MetadataStore;\n\n blobStore: BlobStore;\n\n disableP2pReplication?: boolean;\n};\n\nexport type ConstructSpaceParams = {\n metadata: SpaceMetadata;\n swarmIdentity: SwarmIdentity;\n memberKey: PublicKey;\n /**\n * Called when connection auth passed successful.\n */\n onAuthorizedConnection: (session: Teleport) => void;\n onAuthFailure?: (session: Teleport) => void;\n onDelegatedInvitationStatusChange: (invitation: DelegateInvitationCredential, isActive: boolean) => Promise<void>;\n onMemberRolesChanged: (member: MemberInfo[]) => Promise<void>;\n};\n\nexport type RequestSpaceAdmissionCredentialParams = {\n spaceKey: PublicKey;\n identityKey: PublicKey;\n swarmIdentity: SwarmIdentity;\n timeout: number;\n};\n\n/**\n * Manages a collection of ECHO (Data) Spaces.\n */\n@trackLeaks('open', 'close')\nexport class SpaceManager {\n private readonly _spaces = new ComplexMap<PublicKey, Space>(PublicKey.hash);\n private readonly _feedStore: FeedStore<FeedMessage>;\n private readonly _networkManager: SwarmNetworkManager;\n private readonly _metadataStore: MetadataStore;\n private readonly _blobStore: BlobStore;\n private readonly _instanceId = PublicKey.random().toHex();\n private readonly _disableP2pReplication: boolean;\n\n constructor({ feedStore, networkManager, metadataStore, blobStore, disableP2pReplication }: SpaceManagerParams) {\n // TODO(burdon): Assert.\n this._feedStore = feedStore;\n this._networkManager = networkManager;\n this._metadataStore = metadataStore;\n this._blobStore = blobStore;\n this._disableP2pReplication = disableP2pReplication ?? false;\n }\n\n // TODO(burdon): Remove.\n get spaces() {\n return this._spaces;\n }\n\n @synchronized\n async open() {}\n\n @synchronized\n async close() {\n await Promise.all([...this._spaces.values()].map((space) => space.close()));\n }\n\n async constructSpace({\n metadata,\n swarmIdentity,\n onAuthorizedConnection,\n onAuthFailure,\n onDelegatedInvitationStatusChange,\n onMemberRolesChanged,\n memberKey,\n }: ConstructSpaceParams) {\n log.trace('dxos.echo.space-manager.construct-space', trace.begin({ id: this._instanceId }));\n log('constructing space...', { spaceKey: metadata.genesisFeedKey });\n\n // The genesis feed will be the same as the control feed if the space was created by the local agent.\n const genesisFeed = await this._feedStore.openFeed(metadata.genesisFeedKey ?? failUndefined());\n\n const spaceKey = metadata.key;\n const spaceId = await createIdFromSpaceKey(spaceKey);\n const protocol = new SpaceProtocol({\n topic: spaceKey,\n swarmIdentity,\n networkManager: this._networkManager,\n onSessionAuth: onAuthorizedConnection,\n onAuthFailure,\n blobStore: this._blobStore,\n disableP2pReplication: this._disableP2pReplication,\n });\n\n const space = new Space({\n id: spaceId,\n spaceKey,\n protocol,\n genesisFeed,\n feedProvider: (feedKey, opts) => this._feedStore.openFeed(feedKey, opts),\n metadataStore: this._metadataStore,\n memberKey,\n onDelegatedInvitationStatusChange,\n onMemberRolesChanged,\n });\n this._spaces.set(space.key, space);\n\n log.trace('dxos.echo.space-manager.construct-space', trace.end({ id: this._instanceId }));\n return space;\n }\n\n public async requestSpaceAdmissionCredential(params: RequestSpaceAdmissionCredentialParams): Promise<Credential> {\n const traceKey = 'dxos.echo.space-manager.request-space-admission';\n log.trace(traceKey, trace.begin({ id: this._instanceId }));\n log('requesting space admission credential...', { spaceKey: params.spaceKey });\n\n const onCredentialResolved = new Trigger<Credential>();\n const protocol = new SpaceProtocol({\n topic: params.spaceKey,\n swarmIdentity: params.swarmIdentity,\n networkManager: this._networkManager,\n onSessionAuth: (session: Teleport) => {\n session.addExtension(\n 'dxos.mesh.teleport.admission-discovery',\n new CredentialRetrieverExtension(\n { spaceKey: params.spaceKey, memberKey: params.identityKey },\n onCredentialResolved,\n ),\n );\n },\n onAuthFailure: (session: Teleport) => session.close(),\n blobStore: this._blobStore,\n disableP2pReplication: this._disableP2pReplication,\n });\n\n try {\n await protocol.start();\n const credential = await onCredentialResolved.wait({ timeout: params.timeout });\n log.trace(traceKey, trace.end({ id: this._instanceId }));\n return credential;\n } catch (err: any) {\n log.trace(traceKey, trace.error({ id: this._instanceId, error: err }));\n throw err;\n } finally {\n await protocol.stop();\n }\n }\n\n public findSpaceByRootDocumentId(documentId: string): Space | undefined {\n return [...this._spaces.values()].find((space) => {\n return space.spaceState.credentials.some((credential) => {\n const assertion = getCredentialAssertion(credential);\n if (assertion['@type'] !== 'dxos.halo.credentials.Epoch') {\n return false;\n }\n if (!assertion?.automergeRoot) {\n return false;\n }\n return parseAutomergeUrl(assertion.automergeRoot as AutomergeUrl).documentId === documentId;\n });\n });\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;AAKA,SAASA,2BAA2B;AACpC,SAASC,cAAc;AAMhB,IAAMC,QAA4BC,OAAOC,gBAAgB,4BAAA;AAKzD,IAAMC,gBAAgBC,oBAAoBJ,KAAAA;;;ACZjD,SAASK,iBAAiB;;AAMnB,IAAMC,yBAAyB,CACpCC,QACAC,WAAAA;AAEAH,YAAUE,QAAAA,QAAAA;;;;;;;;;AACVF,YAAUG,QAAAA,QAAAA;;;;;;;;;AAEV,SAAO;IACLC,OAAO,OAAOC,MAAcC,YAAY,MAAMH,OAAOC,MAAM,MAAMF,OAAOG,IAAAA,GAAOC,OAAAA;EACjF;AACF;;;ACjBA,SAASC,oBAAoB;AAC7B,SAASC,WAAWC,eAAe;AACnC,SAASC,kBAAkB;AAE3B,IAAMC,kBAAkB,IAAIC,WAA+BC,UAAUC,IAAI;AAMlE,IAAMC,uBAAuB,OAAOC,aAAAA;AACzC,QAAMC,cAAcN,gBAAgBO,IAAIF,QAAAA;AACxC,MAAIC,gBAAgBE,QAAW;AAC7B,WAAOF;EACT;AAEA,QAAMG,S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F;GA1BUnF,aAAAA,WAAAA,SAAAA,IAAAA;AAAAA,eAAAA,cAAAA;EADZoF,YAAW,QAAQ,OAAA;GACPpF,YAAAA;",
|
|
6
|
+
"names": ["createCodecEncoding", "schema", "codec", "schema", "getCodecForType", "valueEncoding", "createCodecEncoding", "invariant", "createMappedFeedWriter", "mapper", "writer", "write", "data", "options", "subtleCrypto", "PublicKey", "SpaceId", "ComplexMap", "SPACE_IDS_CACHE", "ComplexMap", "PublicKey", "hash", "createIdFromSpaceKey", "spaceKey", "cachedValue", "get", "undefined", "digest", "subtleCrypto", "asUint8Array", "bytes", "Uint8Array", "slice", "SpaceId", "byteLength", "spaceId", "encode", "set", "CRC32", "Event", "scheduleTaskInterval", "synchronized", "Context", "invariant", "PublicKey", "log", "DataCorruptionError", "STORAGE_VERSION", "schema", "Invitation", "SpaceState", "ComplexMap", "arrayToBuffer", "forEachAsync", "isNotNullOrUndefined", "EXPIRED_INVITATION_CLEANUP_INTERVAL", "emptyEchoMetadata", "version", "spaces", "created", "Date", "updated", "emptyLargeSpaceMetadata", "EchoMetadata", "getCodecForType", "LargeSpaceMetadata", "MetadataStore", "constructor", "directory", "_metadata", "_spaceLargeMetadata", "hash", "_metadataFile", "undefined", "update", "_invitationCleanupCtx", "_directory", "metadata", "_readFile", "file", "codec", "size", "fileLength", "stat", "dataSize", "fromBytesInt32", "read", "checksum", "name", "filename", "data", "calculatedChecksum", "buf", "decode", "close", "_writeFile", "encoded", "encode", "result", "Buffer", "alloc", "length", "writeInt32LE", "copy", "write", "dispose", "flush", "clear", "load", "closed", "getOrCreateFile", "forEach", "space", "state", "SPACE_ACTIVE", "err", "error", "identity", "haloSpace", "key", "map", "filter", "_loadSpaceLargeMetadata", "invitation", "invitations", "hasInvitationExpired", "isLegacyInvitationFormat", "removeInvitation", "invitationId", "_save", "emit", "toHex", "set", "_saveSpaceLargeMetadata", "_getLargeSpaceMetadata", "_getSpace", "spaceKey", "equals", "find", "hasSpace", "entry", "get", "delete", "getIdentityRecord", "setIdentityRecord", "record", "getInvitations", "addInvitation", "i", "push", "addSpace", "setSpaceDataLatestTimeframe", "timeframe", "dataTimeframe", "setSpaceControlLatestTimeframe", "controlTimeframe", "setCache", "cache", "setWritableFeedKeys", "controlFeedKey", "dataFeedKey", "setSpaceState", "getSpaceControlPipelineSnapshot", "controlPipelineSnapshot", "setSpaceControlPipelineSnapshot", "snapshot", "getSpaceEdgeReplicationSetting", "edgeReplication", "setSpaceEdgeReplicationSetting", "setting", "readInt32LE", "Boolean", "lifetime", "getTime", "now", "type", "Type", "MULTIUSE", "Event", "timed", "log", "Timeframe", "mapTimeframeToFeedIndexes", "timeframe", "frames", "map", "feedKey", "index", "mapFeedIndexesToTimeframe", "indexes", "startAfter", "TimeframeClock", "constructor", "_timeframe", "update", "_pendingTimeframe", "pendingTimeframe", "setTimeframe", "emit", "updatePendingTimeframe", "key", "seq", "merge", "updateTimeframe", "hasGaps", "gaps", "dependencies", "isEmpty", "waitUntilReached", "target", "current", "waitForCondition", "deps", "Event", "sleepWithContext", "synchronized", "Trigger", "Context", "rejectOnDispose", "failUndefined", "FeedSetIterator", "invariant", "PublicKey", "log", "Timeframe", "ComplexMap", "invariant", "log", "createMessageSelector", "timeframeClock", "messages", "i", "length", "data", "timeframe", "hasGaps", "PipelineState", "constructor", "_feeds", "_timeframeClock", "_ctx", "Context", "timeframeUpdate", "update", "stalled", "Event", "_startTimeframe", "Timeframe", "_reachedTarget", "endTimeframe", "mapFeedIndexesToTimeframe", "Array", "from", "values", "filter", "feed", "length", "map", "feedKey", "key", "index", "startTimeframe", "timeframe", "pendingTimeframe", "targetTimeframe", "_targetTimeframe", "reachedTarget", "feeds", "waitUntilTimeframe", "target", "waitUntilReached", "setTargetTimeframe", "waitUntilReachedTargetTimeframe", "ctx", "timeout", "breakOnStall", "log", "current", "_reachedTargetPromise", "Promise", "race", "waitForCondition", "dependencies", "isEmpty", "discardParameter", "waitForCount", "done", "rejectOnDispose", "then", "sleepWithContext", "warn", "Pipeline", "TimeframeClock", "ComplexMap", "PublicKey", "hash", "_state", "_processingTrigger", "Trigger", "wake", "_pauseTrigger", "_downloads", "value", "_isStopping", "_isStarted", "_isBeingConsumed", "_isPaused", "state", "writer", "invariant", "_writer", "hasFeed", "has", "getFeeds", "_feedSetIterator", "addFeed", "set", "_setFeedDownloadState", "setWriteFeed", "properties", "writable", "createMappedFeedWriter", "payload", "createFeedWriter", "start", "_initIterator", "open", "stop", "handle", "entries", "undownload", "clear", "close", "wait", "dispose", "undefined", "setCursor", "setTimeframe", "pause", "reset", "unpause", "consume", "lastFeedSetIterator", "iterable", "Symbol", "asyncIterator", "next", "block", "failUndefined", "updatePendingTimeframe", "seq", "updateTimeframe", "get", "truncate", "download", "linear", "err", "data", "info", "FeedSetIterator", "createMessageSelector", "startAfter", "stallTimeout", "on", "iterator", "options", "size", "currentTimeframe", "emit", "synchronized", "runInContext", "scheduleTask", "Context", "randomBytes", "invariant", "log", "schema", "RpcExtension", "AuthExtension", "constructor", "_authParams", "requested", "AuthService", "getService", "exposed", "timeout", "_ctx", "onError", "err", "catch", "getHandlers", "authenticate", "challenge", "credential", "provider", "Error", "error", "onOpen", "context", "rpc", "length", "success", "verifier", "onAuthSuccess", "close", "onAuthFailure", "onClose", "dispose", "onAbort", "Event", "scheduleMicroTask", "synchronized", "trackLeaks", "Resource", "invariant", "log", "logInfo", "AdmittedFeed", "trace", "Callback", "DeferredTask", "sleepWithContext", "trackLeaks", "Context", "SpaceStateMachine", "PublicKey", "log", "AdmittedFeed", "Timeframe", "TimeSeriesCounter", "TimeUsageCounter", "trace", "Callback", "tracer", "TIMEFRAME_SAVE_DEBOUNCE_INTERVAL", "CONTROL_PIPELINE_SNAPSHOT_DELAY", "USE_SNAPSHOTS", "ControlPipeline", "constructor", "spaceKey", "genesisFeed", "feedProvider", "metadataStore", "_ctx", "Context", "_lastTimeframeSaveTime", "Date", "now", "onFeedAdmitted", "Callback", "_usage", "TimeUsageCounter", "_mutations", "TimeSeriesCounter", "_snapshotTask", "DeferredTask", "sleepWithContext", "_saveSnapshot", "_spaceKey", "_metadata", "_pipeline", "Pipeline", "addFeed", "_spaceStateMachine", "SpaceStateMachine", "set", "info", "log", "key", "assertion", "designation", "AdmittedFeed", "Designation", "CONTROL", "equals", "queueMicrotask", "feed", "hasFeed", "err", "catch", "callIfSet", "onMemberRoleChanged", "onCredentialProcessed", "onDelegatedInvitation", "onDelegatedInvitationRemoved", "spaceState", "pipeline", "setWriteFeed", "start", "snapshot", "getSpaceControlPipelineSnapshot", "present", "tf", "timeframe", "_processSnapshot", "setTimeout", "_consumePipeline", "setCursor", "message", "messages", "result", "process", "credential", "sourceFeed", "feedKey", "skipVerification", "warn", "pause", "state", "credentialEntries", "map", "entry", "unpause", "getSnapshotLoggerContext", "setSpaceControlPipelineSnapshot", "ctx", "msg", "consume", "span", "beginRecording", "inc", "_processMessage", "end", "seq", "data", "payload", "timer", "tracer", "mark", "PublicKey", "from", "_noteTargetStateIfNeeded", "pendingTimeframe", "schedule", "_saveTargetTimeframe", "stop", "dispose", "newTimeframe", "Timeframe", "merge", "_targetTimeframe", "setSpaceControlLatestTimeframe", "trace", "metricsCounter", "showInBrowserTimeline", "resource", "trackLeaks", "issuer", "subject", "id", "type", "Space", "Resource", "constructor", "params", "onCredentialProcessed", "Callback", "stateUpdate", "Event", "invariant", "spaceKey", "feedProvider", "_id", "id", "_key", "_genesisFeedKey", "genesisFeed", "key", "_feedProvider", "_controlPipeline", "ControlPipeline", "metadataStore", "onFeedAdmitted", "set", "info", "sparse", "assertion", "designation", "AdmittedFeed", "Designation", "DATA", "equals", "scheduleMicroTask", "_ctx", "protocol", "addFeed", "credential", "callIfSet", "log", "emit", "onDelegatedInvitation", "invitation", "onDelegatedInvitationStatusChange", "onDelegatedInvitationRemoved", "onMemberRoleChanged", "changedMembers", "map", "m", "role", "onMemberRolesChanged", "genesisFeedKey", "controlFeedKey", "_controlFeed", "dataFeedKey", "_dataFeed", "spaceState", "controlPipeline", "pipeline", "setControlFeed", "feed", "setWriteFeed", "setDataFeed", "getControlFeeds", "Array", "from", "feeds", "values", "_open", "ctx", "start", "startProtocol", "isOpen", "_close", "stop", "trace", "logInfo", "span", "synchronized", "trackLeaks", "resource", "scheduleTask", "Context", "ProtocolError", "schema", "RpcExtension", "CredentialRetrieverExtension", "constructor", "_request", "_onResult", "requested", "AdmissionDiscoveryService", "getService", "_ctx", "getHandlers", "onOpen", "context", "result", "rpc", "getAdmissionCredential", "wake", "admissionCredential", "err", "close", "onClose", "dispose", "onAbort", "CredentialServerExtension", "_space", "exposed", "request", "memberInfo", "spaceState", "members", "get", "memberKey", "credential", "discoveryKey", "subtleCrypto", "PublicKey", "log", "logInfo", "MMSTTopology", "Teleport", "BlobSync", "ReplicatorExtension", "trace", "CallbackCollection", "ComplexMap", "MOCK_AUTH_PROVIDER", "nonce", "Buffer", "from", "MOCK_AUTH_VERIFIER", "credential", "SpaceProtocol", "constructor", "topic", "swarmIdentity", "networkManager", "onSessionAuth", "onAuthFailure", "blobStore", "disableP2pReplication", "_feeds", "Set", "_sessions", "ComplexMap", "PublicKey", "hash", "_topology", "MMSTTopology", "originateConnections", "maxPeers", "sampleSize", "feedAdded", "CallbackCollection", "_spaceKey", "_networkManager", "_swarmIdentity", "_onSessionAuth", "_onAuthFailure", "blobSync", "BlobSync", "_topic", "subtleCrypto", "digest", "asBuffer", "then", "discoveryKey", "_disableP2pReplication", "sessions", "feeds", "_ownPeerKey", "peerKey", "addFeed", "feed", "log", "key", "add", "session", "values", "replicator", "callSerial", "start", "_connection", "credentials", "credentialProvider", "open", "joinSwarm", "protocolProvider", "_createProtocolProvider", "topology", "label", "truncate", "updateTopology", "forceUpdate", "stop", "close", "wireParams", "SpaceProtocolSession", "set", "remotePeerId", "logInfo", "trace", "info", "resource", "AuthStatus", "ReplicatorExtension", "setOptions", "upload", "_authStatus", "_wireParams", "_blobSync", "_teleport", "Teleport", "authStatus", "stats", "stream", "sessionId", "addExtension", "AuthExtension", "provider", "verifier", "credentialAuthenticator", "onAuthSuccess", "createExtension", "abort", "synchronized", "trackLeaks", "Trigger", "parseAutomergeUrl", "getCredentialAssertion", "failUndefined", "PublicKey", "log", "trace", "ComplexMap", "SpaceManager", "constructor", "feedStore", "networkManager", "metadataStore", "blobStore", "disableP2pReplication", "_spaces", "ComplexMap", "PublicKey", "hash", "_instanceId", "random", "toHex", "_feedStore", "_networkManager", "_metadataStore", "_blobStore", "_disableP2pReplication", "spaces", "open", "close", "Promise", "all", "values", "map", "space", "constructSpace", "metadata", "swarmIdentity", "onAuthorizedConnection", "onAuthFailure", "onDelegatedInvitationStatusChange", "onMemberRolesChanged", "memberKey", "log", "trace", "begin", "id", "spaceKey", "genesisFeedKey", "genesisFeed", "openFeed", "failUndefined", "key", "spaceId", "createIdFromSpaceKey", "protocol", "SpaceProtocol", "topic", "onSessionAuth", "Space", "feedProvider", "feedKey", "opts", "set", "end", "requestSpaceAdmissionCredential", "params", "traceKey", "onCredentialResolved", "Trigger", "session", "addExtension", "CredentialRetrieverExtension", "identityKey", "start", "credential", "wait", "timeout", "err", "error", "stop", "findSpaceByRootDocumentId", "documentId", "find", "spaceState", "credentials", "some", "assertion", "getCredentialAssertion", "automergeRoot", "parseAutomergeUrl", "synchronized", "trackLeaks"]
|
|
7
|
+
}
|