Skip to content

Commit

Permalink
Merge 16dd888 into 56112c7
Browse files Browse the repository at this point in the history
  • Loading branch information
kneth committed Apr 30, 2024
2 parents 56112c7 + 16dd888 commit c97f43c
Show file tree
Hide file tree
Showing 13 changed files with 83 additions and 68 deletions.
4 changes: 1 addition & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@
* File format: generates Realms with format v24 (reads and upgrades file format v10.

### Internal
<!-- * Either mention core version or upgrade -->
<!-- * Using Realm Core vX.Y.Z -->
<!-- * Upgraded Realm Core from vX.Y.Z to vA.B.C -->
* Upgraded Realm Core from v14.5.1 to v14.6.0.

## 12.7.1 (2024-04-19)

Expand Down
2 changes: 1 addition & 1 deletion integration-tests/tests/src/tests/sync/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ describe("App", () => {
expect(MetadataMode).deep.equals({
NoEncryption: "noEncryption",
Encryption: "encryption",
NoMetadata: "noMetadata",
NoMetadata: "inMemory",
});
});

Expand Down
40 changes: 26 additions & 14 deletions packages/realm/bindgen/js_opt_in_spec.yml
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,6 @@ records:

SyncClientConfig:
fields:
- base_file_path
- metadata_mode
- custom_encryption_key
- user_agent_binding_info
- multiplex_sessions
- timeouts
Expand Down Expand Up @@ -186,8 +183,13 @@ records:
- app_id
- transport
- base_url
- base_file_path
- default_request_timeout_ms
- device_info
- sync_client_config
- metadata_mode
- custom_encryption_key
# - security_access_group

CompensatingWriteErrorInfo:
fields:
Expand Down Expand Up @@ -262,6 +264,7 @@ classes:
- feed_buffer
- make_ssl_verify_callback
- needs_file_format_upgrade
- sync_user_as_app_user

LogCategoryRef:
methods:
Expand Down Expand Up @@ -443,21 +446,30 @@ classes:
- api_key

SyncUser:
methods: []

User:
methods:
- all_sessions
- is_logged_in
- identity
- access_token
- refresh_token
- has_device_id
- device_id
- user_profile
- identities
- custom_data
- sync_manager
- state
- session_for_on_disk_path
- subscribe
- unsubscribe
- path_for_realm
- app
- is_logged_in
- user_id
- app_id
- legacy_identities
- access_token
- refresh_token
- state
- access_token_refresh_required
- request_refresh_location
- request_access_token
- track_realm

UserProfile:
methods:
Expand Down Expand Up @@ -520,13 +532,13 @@ classes:
SyncManager:
methods:
- has_existing_sessions
- immediately_run_file_actions
- set_session_multiplexing
- set_log_level
- set_logger_factory
- set_user_agent
- reconnect
- path_for_realm
- get_existing_active_session
- get_all_sessions_for

AsyncOpenTask:
methods:
Expand All @@ -540,7 +552,6 @@ classes:
methods:
- state
- connection_state
- user
- config
- full_realm_url
- wait_for_upload_completion
Expand All @@ -552,6 +563,7 @@ classes:
- revive_if_needed
- force_close
- handle_reconnect
- user
# JS-specific
- DOLLAR_resetSharedPtr

Expand Down
5 changes: 0 additions & 5 deletions packages/realm/bindgen/src/templates/jsi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -781,11 +781,6 @@ class JsiCppDecls extends CppDecls {
}

for (const cls of spec.classes) {
assert(
!cls.sharedPtrWrapped || (!cls.base && cls.subclasses.length == 0),
`We don't support mixing sharedPtrWrapped and class hierarchies. ${cls.name} requires this.`,
);

this.addon.addClass(cls);

// TODO look into more efficient storage for types that aren't part of a hierarchy
Expand Down
6 changes: 1 addition & 5 deletions packages/realm/bindgen/src/templates/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -709,18 +709,14 @@ class NodeCppDecls extends CppDecls {
}

for (const cls of spec.classes) {
assert(
!cls.sharedPtrWrapped || (!cls.base && cls.subclasses.length == 0),
`We don't support mixing sharedPtrWrapped and class hierarchies. ${cls.name} requires this.`,
);

this.addon.addClass(cls);

// TODO look into using enabled_shared_from for all shared thingies so we can just store T*.
const baseType = cls.sharedPtrWrapped ? `std::shared_ptr<${cls.cppName}>` : cls.rootBase().cppName;
const derivedType = cls.sharedPtrWrapped ? `std::shared_ptr<${cls.cppName}>` : cls.cppName;
const ptr = (expr: string) => `${expr}.As<Napi::External<${baseType}>>().Data()`;
const casted = (expr: string) => (cls.base ? `static_cast<${derivedType}*>(${ptr(expr)})` : ptr(expr));

const self = `(${cls.needsDeref ? "**" : "*"}${casted("info[0]")})`;

const selfCheck = (isStatic: boolean) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/realm/bindgen/vendor/realm-core
Submodule realm-core updated 306 files
2 changes: 1 addition & 1 deletion packages/realm/src/Realm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,7 @@ export class Realm {
return Realm.normalizePath(config.path);
} else {
const bindingSyncConfig = toBindingSyncConfig(config.sync);
return config.sync.user.internal.syncManager.pathForRealm(bindingSyncConfig, config.path);
return config.sync.user.internal.pathForRealm(bindingSyncConfig, undefined);
}
} else {
return Realm.normalizePath(config.path);
Expand Down
4 changes: 2 additions & 2 deletions packages/realm/src/app-services/ApiKeyAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,12 @@ export type SecretApiKey = ApiKey & {
*/
export class ApiKeyAuth {
/** @internal */
private user: binding.SyncUser;
private user: binding.User;
/** @internal */
private internal: binding.UserApiKeyProviderClient;

/** @internal */
constructor(user: binding.SyncUser, internal: binding.UserApiKeyProviderClient) {
constructor(user: binding.User, internal: binding.UserApiKeyProviderClient) {
this.user = user;
this.internal = internal;
}
Expand Down
51 changes: 28 additions & 23 deletions packages/realm/src/app-services/App.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,9 @@ export enum MetadataMode {
Encryption = "encryption",
/**
* Do not persist {@link User} objects.
* @deprecated will be renamed to `InMemory`
*/
NoMetadata = "noMetadata",
NoMetadata = "inMemory",
}

/**
Expand Down Expand Up @@ -82,7 +83,7 @@ function toBindingMetadataMode(arg: MetadataMode): binding.MetadataMode {
const translationTable: Record<binding.MetadataMode, MetadataMode> = {
[binding.MetadataMode.NoEncryption]: MetadataMode.NoEncryption,
[binding.MetadataMode.Encryption]: MetadataMode.Encryption,
[binding.MetadataMode.NoMetadata]: MetadataMode.NoMetadata,
[binding.MetadataMode.InMemory]: MetadataMode.NoMetadata, // TODO: should we rename NoMetadata to InMemory?
};

const inverseTranslationTable: Record<MetadataMode, binding.MetadataMode> = Object.fromEntries(
Expand Down Expand Up @@ -217,17 +218,17 @@ export class App<
public static userAgent = `RealmJS/${App.deviceInfo.sdkVersion} (v${App.deviceInfo.platformVersion})`;

/** @internal */
public static getAppByUser(userInternal: binding.SyncUser): App {
const app = App.appByUserId.get(userInternal.identity)?.deref();
public static getAppByUser(userInternal: binding.User): App {
const app = App.appByUserId.get(userInternal.userId)?.deref();
if (!app) {
throw new Error(`Cannot determine which app is associated with user (id = ${userInternal.identity})`);
throw new Error(`Cannot determine which app is associated with user (id = ${userInternal.userId})`);
}
return app;
}

/** @internal */
public static setAppByUser(userInternal: binding.SyncUser, currentApp: AnyApp): void {
App.appByUserId.set(userInternal.identity, new binding.WeakRef(currentApp));
public static setAppByUser(userInternal: binding.User, currentApp: AnyApp): void {
App.appByUserId.set(userInternal.userId, new binding.WeakRef(currentApp));
}

/** @internal */
Expand Down Expand Up @@ -280,23 +281,27 @@ export class App<

fs.ensureDirectoryForFile(fs.joinPaths(baseFilePath || fs.getDefaultDirectoryPath(), "mongodb-realm"));
// TODO: This used getSharedApp in the legacy SDK, but it's failing AppTests
this.internal = binding.App.getApp(
binding.AppCacheMode.Disabled,
{
appId: id,
deviceInfo: App.deviceInfo,
transport: createNetworkTransport(fetch),
baseUrl,
defaultRequestTimeoutMs: timeout ? binding.Int64.numToInt(timeout) : undefined,
},
{
baseFilePath: baseFilePath ? baseFilePath : fs.getDefaultDirectoryPath(),
metadataMode: metadata ? toBindingMetadataMode(metadata.mode) : binding.MetadataMode.NoEncryption,
customEncryptionKey: metadata?.encryptionKey,
userAgentBindingInfo: App.userAgent,
this.internal = binding.App.getApp(binding.AppCacheMode.Disabled, {
appId: id,
deviceInfo: App.deviceInfo,
transport: createNetworkTransport(fetch),
baseUrl,
defaultRequestTimeoutMs: timeout ? binding.Int64.numToInt(timeout) : undefined,
baseFilePath: baseFilePath ? baseFilePath : fs.getDefaultDirectoryPath(),
metadataMode: metadata ? toBindingMetadataMode(metadata.mode) : binding.MetadataMode.NoEncryption,
customEncryptionKey: metadata?.encryptionKey,
syncClientConfig: {
multiplexSessions,
userAgentBindingInfo: App.userAgent,
},
);
});
}

/**
* @internal
*/
public get syncManager(): binding.SyncManager {
return this.internal.syncManager;
}

/**
Expand Down Expand Up @@ -341,7 +346,7 @@ export class App<
* @returns A mapping from user ID to user.
*/
public get allUsers(): Readonly<Record<string, User<FunctionsFactoryType, CustomDataType>>> {
return Object.fromEntries(this.internal.allUsers.map((user) => [user.identity, User.get(user, this)]));
return Object.fromEntries(this.internal.allUsers.map((user) => [user.userId, User.get(user, this)]));
}

/**
Expand Down
4 changes: 2 additions & 2 deletions packages/realm/src/app-services/PushClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@ import { binding } from "../internal";
*/
export class PushClient {
/** @internal */
private user: binding.SyncUser;
private user: binding.User;
/** @internal */
public internal: binding.PushClient;

/** @internal */
public constructor(user: binding.SyncUser, internal: binding.PushClient) {
public constructor(user: binding.User, internal: binding.PushClient) {
this.user = user;
this.internal = internal;
}
Expand Down
8 changes: 4 additions & 4 deletions packages/realm/src/app-services/Sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export class Sync {
* @since 10.0.0
*/
static getAllSyncSessions(user: User): SyncSession[] {
return user.internal.allSessions.map((session) => new SyncSession(session));
return user.internal.app.syncManager.getAllSessionsFor(user.internal).map((session) => new SyncSession(session));
}
/**
* Get the session associated with a particular user and partition value.
Expand All @@ -65,8 +65,8 @@ export class Sync {
static getSyncSession(user: User, partitionValue: PartitionValue): SyncSession | null {
validateSyncConfiguration({ user, partitionValue });
const config = toBindingSyncConfig({ user, partitionValue });
const path = user.app.internal.syncManager.pathForRealm(config, undefined);
const session = user.internal.sessionForOnDiskPath(path);
const path = user.internal.pathForRealm(config, undefined);
const session = user.internal.app.syncManager.getExistingActiveSession(path);
if (session) {
return new SyncSession(session);
} else {
Expand Down Expand Up @@ -139,7 +139,7 @@ export class Sync {
* }
*/
static initiateClientReset(app: App, path: string) {
const success = app.internal.syncManager.immediatelyRunFileActions(path);
const success = app.internal.immediatelyRunFileActions(path);
// TODO: Consider a better error message
assert(success, `Realm was not configured correctly. Client Reset could not be run for Realm at: ${path}`);
}
Expand Down
13 changes: 11 additions & 2 deletions packages/realm/src/app-services/SyncSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,11 @@ export class SyncSession {
*/
get config(): SyncConfiguration {
return this.withInternal((internal) => {
const user = new User(internal.user, mockApp);
const appUser = binding.Helpers.syncUserAsAppUser(internal.user);
if (!appUser) {
throw new Error("User is null");
}
const user = new User(appUser, mockApp);
const { partitionValue, flxSyncRequested, customHttpHeaders, clientValidateSsl, sslTrustCertificatePath } =
internal.config;
if (flxSyncRequested) {
Expand Down Expand Up @@ -349,8 +353,13 @@ export class SyncSession {
* Gets the User that this session was created with.
*/
get user() {
return User.get(this.withInternal((internal) => internal.user));
const appUser = this.withInternal((internal) => binding.Helpers.syncUserAsAppUser(internal.user));
if (!appUser) {
throw new Error("User is null");
}
return User.get(appUser);
}

/**
* Gets the current state of the connection to the server. Multiple sessions might share the same underlying
* connection. In that case, any connection change is sent to all sessions.
Expand Down
10 changes: 5 additions & 5 deletions packages/realm/src/app-services/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export interface UserIdentity {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type AnyUser = User<any, any, any>;

type UserListenerToken = binding.SyncUserSubscriptionToken;
type UserListenerToken = binding.UserSubscriptionToken;

/**
* Representation of an authenticated user of an {@link App}.
Expand All @@ -90,7 +90,7 @@ export class User<
public readonly app: App;

/** @internal */
public readonly internal: binding.SyncUser;
public readonly internal: binding.User;

/** @internal */
private cachedProfile: UserProfileDataType | undefined;
Expand All @@ -110,7 +110,7 @@ export class User<
FunctionsFactoryType extends DefaultFunctionsFactory = DefaultFunctionsFactory,
CustomDataType extends DefaultObject = DefaultObject,
UserProfileDataType extends DefaultUserProfileData = DefaultUserProfileData,
>(internal: binding.SyncUser, app?: AnyApp) {
>(internal: binding.User, app?: AnyApp) {
// Update the static user reference to the current app
if (app) {
App.setAppByUser(internal, app);
Expand All @@ -120,7 +120,7 @@ export class User<
}

/** @internal */
constructor(internal: binding.SyncUser, app: App) {
constructor(internal: binding.User, app: App) {
this.internal = internal;
this.app = app;
this.cachedProfile = undefined;
Expand Down Expand Up @@ -152,7 +152,7 @@ export class User<
* @returns The user ID as a string.
*/
get id(): string {
return this.internal.identity;
return this.internal.userId;
}

/**
Expand Down

0 comments on commit c97f43c

Please sign in to comment.