Skip to content

Upgrade to HEAD of Realm Core's master #6637

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
May 1, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions integration-tests/tests/src/tests/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1052,9 +1052,11 @@ describe("Queries", () => {
expect(aged14Or15.length).to.equal(2);

const aged17 = persons.filtered("age IN $0", [17]);
console.log({ aged17 });
expect(aged17.length).to.equal(1);

const dennis = persons.filtered("name in {'Dennis'}");
console.log({ dennis });
expect(dennis.length).to.equal(0);

const bobs = persons.filtered("name in $0", ["Bob"]);
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
33 changes: 22 additions & 11 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 @@ -444,20 +446,30 @@ classes:

SyncUser:
methods:
- all_sessions
- is_logged_in
- identity
- user_id
- app_id
- legacy_identities
- access_token
- refresh_token
- state
- access_token_refresh_required
- request_refresh_user
- request_refresh_location
- request_access_token
- track_realm

User:
methods:
- has_device_id
- device_id
- user_profile
- identities
- custom_data
- sync_manager
- state
- session_for_on_disk_path
- subscribe
- unsubscribe
- path_for_realm
- app

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 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 187 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 @@
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 Expand Up @@ -825,7 +825,7 @@

/**
* Deletes a Realm model, including all of its objects.
* If called outside a migration function, {@link schema} and {@link schemaVersion} are updated.

Check warning on line 828 in packages/realm/src/Realm.ts

View workflow job for this annotation

GitHub Actions / Lint

The type 'schemaVersion' is undefined
* @param name - The model name.
*/
deleteModel(name: string): void {
Expand Down Expand Up @@ -985,7 +985,7 @@
* Remove the listener {@link callback} for the specified event {@link eventName}.
* @param eventName - The event name.
* @param callback - Function that was previously added as a listener for this event through the {@link addListener} method.
* @throws an {@link Error} If an invalid event {@link eventName} is supplied, if Realm is closed or if {@link callback} is not a function.

Check warning on line 988 in packages/realm/src/Realm.ts

View workflow job for this annotation

GitHub Actions / Lint

The type 'addListener' is undefined
*/
removeListener(eventName: RealmEventName, callback: RealmListenerCallback): void {
assert.open(this);
Expand Down Expand Up @@ -1029,7 +1029,7 @@
}

/**
* Synchronously call the provided {@link callback} inside a write transaction. If an exception happens inside a transaction,

Check warning on line 1032 in packages/realm/src/Realm.ts

View workflow job for this annotation

GitHub Actions / Lint

The type 'beginTransaction' is undefined

Check warning on line 1032 in packages/realm/src/Realm.ts

View workflow job for this annotation

GitHub Actions / Lint

The type 'commitTransaction' is undefined

Check warning on line 1032 in packages/realm/src/Realm.ts

View workflow job for this annotation

GitHub Actions / Lint

The type 'cancelTransaction' is undefined

Check warning on line 1032 in packages/realm/src/Realm.ts

View workflow job for this annotation

GitHub Actions / Lint

The type 'commitTransaction' is undefined

Check warning on line 1032 in packages/realm/src/Realm.ts

View workflow job for this annotation

GitHub Actions / Lint

The type 'write' is undefined

Check warning on line 1032 in packages/realm/src/Realm.ts

View workflow job for this annotation

GitHub Actions / Lint

The type 'write' is undefined
* you’ll lose the changes in that transaction, but the Realm itself won’t be affected (or corrupted).
* More precisely, {@link beginTransaction} and {@link commitTransaction} will be called
* automatically. If any exception is thrown during the transaction {@link cancelTransaction} will
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
58 changes: 34 additions & 24 deletions packages/realm/src/app-services/App.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,9 @@
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 @@
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?
Copy link
Contributor

@elle-j elle-j Apr 26, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regarding the TODO comment, I don't think we should rename unless this will be part of a new next major SDK version.

};

const inverseTranslationTable: Record<MetadataMode, binding.MetadataMode> = Object.fromEntries(
Expand Down Expand Up @@ -217,17 +218,17 @@
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 @@ -278,25 +279,34 @@
assert.function(fetch, "fetch");
}

const syncClientConfig: binding.SyncClientConfig_Relaxed = {

Check failure on line 282 in packages/realm/src/app-services/App.ts

View workflow job for this annotation

GitHub Actions / Lint

'syncClientConfig' is assigned a value but never used
multiplexSessions,
userAgentBindingInfo: App.userAgent,
};

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,
}

Check failure on line 301 in packages/realm/src/app-services/App.ts

View workflow job for this annotation

GitHub Actions / Lint

Insert `,`
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Linting 👍

Suggested change
}
},

});
}

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

/**
Expand Down Expand Up @@ -341,7 +351,7 @@
* @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
5 changes: 3 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,7 @@ export class SyncSession {
*/
get config(): SyncConfiguration {
return this.withInternal((internal) => {
const user = new User(internal.user, mockApp);
const user = new User(internal.config.user, mockApp);
const { partitionValue, flxSyncRequested, customHttpHeaders, clientValidateSsl, sslTrustCertificatePath } =
internal.config;
if (flxSyncRequested) {
Expand Down Expand Up @@ -349,8 +349,9 @@ export class SyncSession {
* Gets the User that this session was created with.
*/
get user() {
return User.get(this.withInternal((internal) => internal.user));
return User.get(this.withInternal((internal) => internal.config.user));
}

/**
* 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
Loading