Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
16 changes: 8 additions & 8 deletions __test__/support/helpers/core.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import { SupportedIdentity } from '../../../src/core/models/IdentityModel';
import { Identity } from 'src/core/models/UserData';
import CoreModule from '../../../src/core/CoreModule';
import { CoreModuleDirector } from '../../../src/core/CoreModuleDirector';
import { OSModel } from '../../../src/core/modelRepo/OSModel';
import { CoreChangeType } from '../../../src/core/models/CoreChangeType';
import { CoreDelta } from '../../../src/core/models/CoreDeltas';
import {
SupportedSubscription,
SubscriptionType,
SupportedSubscription,
} from '../../../src/core/models/SubscriptionModels';
import { ModelName } from '../../../src/core/models/SupportedModels';
import { UserPropertiesModel } from '../../../src/core/models/UserPropertiesModel';
import {
DUMMY_MODEL_ID,
DUMMY_PUSH_TOKEN,
DUMMY_SUBSCRIPTION_ID,
} from '../constants';
import CoreModule from '../../../src/core/CoreModule';
import { CoreModuleDirector } from '../../../src/core/CoreModuleDirector';
import { UserPropertiesModel } from '../../../src/core/models/UserPropertiesModel';

export function generateNewSubscription(modelId = '0000000000') {
return new OSModel<SupportedSubscription>(
Expand All @@ -28,7 +28,7 @@ export function generateNewSubscription(modelId = '0000000000') {
);
}

export function getMockDeltas(): CoreDelta<SupportedIdentity>[] {
export function getMockDeltas(): CoreDelta<Identity>[] {
return [
{
model: getDummyIdentityOSModel(),
Expand All @@ -39,8 +39,8 @@ export function getMockDeltas(): CoreDelta<SupportedIdentity>[] {

export function getDummyIdentityOSModel(
modelId = DUMMY_MODEL_ID,
): OSModel<SupportedIdentity> {
return new OSModel<SupportedIdentity>(ModelName.Identity, {}, modelId);
): OSModel<Identity> {
return new OSModel<Identity>(ModelName.Identity, {}, modelId);
}

export function getDummyPropertyOSModel(
Expand Down
2 changes: 1 addition & 1 deletion __test__/support/helpers/pushSubscription.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import {
ModelName,
SupportedModel,
} from '../../../src/core/models/SupportedModels';
import { getDummyPushSubscriptionOSModel } from './core';
import { TestEnvironment } from '../environment/TestEnvironment';
import { getDummyPushSubscriptionOSModel } from './core';

export async function initializeWithPermission(
permission: NotificationPermission,
Expand Down
2 changes: 1 addition & 1 deletion __test__/unit/core/modelCache.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import ModelCache from '../../../src/core/caching/ModelCache';
import { IdentityExecutor } from '../../../src/core/executors/IdentityExecutor';
import { PropertiesExecutor } from '../../../src/core/executors/PropertiesExecutor';
import { SubscriptionExecutor } from '../../../src/core/executors/SubscriptionExecutor';
import ModelCache from '../../../src/core/caching/ModelCache';
import { OSModel } from '../../../src/core/modelRepo/OSModel';
import { ModelName } from '../../../src/core/models/SupportedModels';
import { TestEnvironment } from '../../support/environment/TestEnvironment';
Expand Down
4 changes: 2 additions & 2 deletions __test__/unit/core/osModel.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { ModelName } from '../../../src/core/models/SupportedModels';
import { OSModel } from '../../../src/core/modelRepo/OSModel';
import {
SubscriptionModel,
SubscriptionType,
} from '../../../src/core/models/SubscriptionModels';
import { ModelName } from '../../../src/core/models/SupportedModels';
import { generateNewSubscription } from '../../support/helpers/core';
import { OSModel } from '../../../src/core/modelRepo/OSModel';

describe('OSModel tests', () => {
test('Set function updates data', async () => {
Expand Down
9 changes: 3 additions & 6 deletions src/core/CoreModuleDirector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import Database from '../shared/services/Database';
import { logMethodCall } from '../shared/utils/utils';
import CoreModule from './CoreModule';
import { OSModel } from './modelRepo/OSModel';
import { SupportedIdentity } from './models/IdentityModel';
import { ModelStoresMap } from './models/ModelStoresMap';
import {
SubscriptionChannel,
Expand All @@ -21,7 +20,7 @@ import {
SupportedSubscription,
} from './models/SubscriptionModels';
import { ModelName, SupportedModel } from './models/SupportedModels';
import UserData from './models/UserData';
import UserData, { Identity } from './models/UserData';
import { UserPropertiesModel } from './models/UserPropertiesModel';

/* Contains OneSignal User-Model-specific logic*/
Expand Down Expand Up @@ -307,13 +306,11 @@ export class CoreModuleDirector {
);
}

public getIdentityModel(): OSModel<SupportedIdentity> | undefined {
public getIdentityModel(): OSModel<Identity> | undefined {
logMethodCall('CoreModuleDirector.getIdentityModel');
const modelStores = this.getModelStores();
const modelKeys = Object.keys(modelStores.identity.models);
return modelStores.identity.models[
modelKeys[0]
] as OSModel<SupportedIdentity>;
return modelStores.identity.models[modelKeys[0]] as OSModel<Identity>;
}

public getPropertiesModel(): OSModel<UserPropertiesModel> | undefined {
Expand Down
2 changes: 1 addition & 1 deletion src/core/executors/ExecutorBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { CoreChangeType } from '../models/CoreChangeType';
import { CoreDelta } from '../models/CoreDeltas';
import { ExecutorConfig } from '../models/ExecutorConfig';
import { SupportedModel } from '../models/SupportedModels';
import { Operation } from '../operationRepo/Operation';
import { Operation } from '../operations/Operation';
import { ExecutorResult } from './ExecutorResult';

const RETRY_AFTER = 5_000;
Expand Down
1 change: 1 addition & 0 deletions src/core/executors/IdentityExecutor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { LegacyOperation } from '../operationRepo/LegacyOperation';
import { isPropertyDelta } from '../utils/typePredicates';
import ExecutorBase from './ExecutorBase';

// TODO: Remove this with later Web SDK Prs
export class IdentityExecutor extends ExecutorBase {
constructor(
executorConfig: ExecutorConfig<SupportedModel>,
Expand Down
210 changes: 210 additions & 0 deletions src/core/executors/IdentityOperationExecutor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
import { BackendError } from 'src/shared/errors/BackendError';
import {
getResponseStatusType,
ResponseStatusType,
} from 'src/shared/helpers/NetworkUtils';
import Log from 'src/shared/libraries/Log';
import { IdentityConstants, IIdentityBackendService } from 'src/types/backend';
import { ModelChangeTags } from 'src/types/models';
import { ExecutionResult, IOperationExecutor } from 'src/types/operation';
import { IRebuildUserService } from 'src/types/user';
import { type IdentityModelStore } from '../models/IdentityModelStore';
import { type NewRecordsState } from '../operationRepo/NewRecordsState';
import { DeleteAliasOperation } from '../operations/DeleteAliasOperation';
import { ExecutionResponse } from '../operations/ExecutionResponse';
import { type Operation } from '../operations/Operation';
import { SetAliasOperation } from '../operations/SetAliasOperation';
import { OPERATION_NAME } from './constants';

// Implements logic similar to Android SDK's IdentityOperationExecutor
// Reference: https://github.com/OneSignal/OneSignal-Android-SDK/blob/5.1.31/OneSignalSDK/onesignal/core/src/main/java/com/onesignal/user/internal/operations/impl/executors/IdentityOperationExecutor.kt
export class IdentityOperationExecutor implements IOperationExecutor {
private readonly _identityBackend: IIdentityBackendService;
private readonly _identityModelStore: IdentityModelStore;
private readonly _buildUserService: IRebuildUserService;
private readonly _newRecordState: NewRecordsState;

constructor(
identityBackend: IIdentityBackendService,
identityModelStore: IdentityModelStore,
buildUserService: IRebuildUserService,
newRecordState: NewRecordsState,
) {
this._identityBackend = identityBackend;
this._identityModelStore = identityModelStore;
this._buildUserService = buildUserService;
this._newRecordState = newRecordState;
}

get operations(): string[] {
return [OPERATION_NAME.SET_ALIAS, OPERATION_NAME.DELETE_ALIAS];
}

async execute(operations: Operation[]): Promise<ExecutionResponse> {
Log.debug(
`IdentityOperationExecutor(operations: ${JSON.stringify(operations)})`,
);

const invalidOps = operations.filter(
(op) =>
!(
op instanceof SetAliasOperation || op instanceof DeleteAliasOperation
),
);
if (invalidOps.length > 0) {
throw new Error(
`Unrecognized operation(s)! Attempted operations:\n${JSON.stringify(
operations,
)}`,
);
}

const hasSetAlias = operations.some(
(op) => op instanceof SetAliasOperation,
);
const hasDeleteAlias = operations.some(
(op) => op instanceof DeleteAliasOperation,
);
if (hasSetAlias && hasDeleteAlias) {
throw new Error(
`Can't process SetAliasOperation and DeleteAliasOperation at the same time.`,
);
}

const lastOperation = operations[operations.length - 1];

if (lastOperation instanceof SetAliasOperation) {
try {
await this._identityBackend.setAlias(
lastOperation.appId,
IdentityConstants.ONESIGNAL_ID,
lastOperation.onesignalId,
{ [lastOperation.label]: lastOperation.value },
);

if (
this._identityModelStore.model.onesignalId ===
lastOperation.onesignalId
) {
this._identityModelStore.model.setProperty<string>(
lastOperation.label,
lastOperation.value,
ModelChangeTags.HYDRATE,
);
}
} catch (ex) {
if (ex instanceof BackendError) {
const responseType = getResponseStatusType(ex.statusCode);

switch (responseType) {
case ResponseStatusType.RETRYABLE:
return new ExecutionResponse(
ExecutionResult.FAIL_RETRY,
ex.retryAfterSeconds,
);

case ResponseStatusType.INVALID:
return new ExecutionResponse(ExecutionResult.FAIL_NORETRY);

case ResponseStatusType.CONFLICT:
return new ExecutionResponse(
ExecutionResult.FAIL_CONFLICT,
ex.retryAfterSeconds,
);

case ResponseStatusType.MISSING: {
if (
ex.statusCode === 404 &&
this._newRecordState.isInMissingRetryWindow(
lastOperation.onesignalId,
)
) {
return new ExecutionResponse(
ExecutionResult.FAIL_RETRY,
ex.retryAfterSeconds,
);
}

const rebuildOps =
this._buildUserService.getRebuildOperationsIfCurrentUser(
lastOperation.appId,
lastOperation.onesignalId,
);
if (!rebuildOps) {
return new ExecutionResponse(ExecutionResult.FAIL_NORETRY);
}
return new ExecutionResponse(
ExecutionResult.FAIL_RETRY,
ex.retryAfterSeconds,
rebuildOps,
);
}
}
}
}
} else if (lastOperation instanceof DeleteAliasOperation) {
try {
await this._identityBackend.deleteAlias(
lastOperation.appId,
IdentityConstants.ONESIGNAL_ID,
lastOperation.onesignalId,
lastOperation.label,
);

if (
this._identityModelStore.model.onesignalId ===
lastOperation.onesignalId
) {
this._identityModelStore.model.setProperty<string | null>(
lastOperation.label,
null,
ModelChangeTags.HYDRATE,
);
}
} catch (ex) {
if (ex instanceof BackendError) {
const responseType = getResponseStatusType(ex.statusCode);

switch (responseType) {
case ResponseStatusType.RETRYABLE:
return new ExecutionResponse(
ExecutionResult.FAIL_RETRY,
ex.retryAfterSeconds,
);
case ResponseStatusType.CONFLICT:
return new ExecutionResponse(ExecutionResult.SUCCESS); // alias doesn’t exist = good

case ResponseStatusType.INVALID:
return new ExecutionResponse(ExecutionResult.FAIL_NORETRY);

case ResponseStatusType.UNAUTHORIZED:
return new ExecutionResponse(
ExecutionResult.FAIL_UNAUTHORIZED,
ex.retryAfterSeconds,
);

case ResponseStatusType.MISSING:
if (
ex.statusCode === 404 &&
this._newRecordState.isInMissingRetryWindow(
lastOperation.onesignalId,
)
) {
return new ExecutionResponse(
ExecutionResult.FAIL_RETRY,
ex.retryAfterSeconds,
);
} else {
// This means either the User or the Alias was already
// deleted, either way the end state is the same, the
// alias no longer exists on that User.
return new ExecutionResponse(ExecutionResult.SUCCESS);
}
}
}
}
}

return new ExecutionResponse(ExecutionResult.SUCCESS);
}
}
4 changes: 4 additions & 0 deletions src/core/executors/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export const OPERATION_NAME = {
SET_ALIAS: 'set-alias',
DELETE_ALIAS: 'delete-alias',
} as const;
19 changes: 14 additions & 5 deletions src/core/modelRepo/ModelStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@
import { EventProducer } from 'src/shared/helpers/EventProducer';
import Log from 'src/shared/libraries/Log';
import type { IEventNotifier } from 'src/types/events';
import type { IModelStore, IModelStoreChangeHandler } from 'src/types/models';
import {
ModelChangeTags,
ModelChangeTagValue,
type IModelStore,
type IModelStoreChangeHandler,
} from 'src/types/models';
import type { IPreferencesService } from 'src/types/preferences';
import type {
IModelChangedHandler,
Expand Down Expand Up @@ -52,15 +57,19 @@ export abstract class ModelStore<TModel extends Model>
/**
* Create a model from JSON data
*/
abstract create(json: object): TModel | null;
abstract create(json?: object | null): TModel | null;

add(model: TModel, tag: string): void {
add(model: TModel, tag: ModelChangeTagValue = ModelChangeTags.NORMAL): void {
const oldModel = this.models.find((m) => m.id === model.id);
if (oldModel) this.removeItem(oldModel, tag);
this.addItem(model, tag);
}

addAt(index: number, model: TModel, tag: string): void {
addAt(
index: number,
model: TModel,
tag: ModelChangeTagValue = ModelChangeTags.NORMAL,
): void {
const oldModel = this.models.find((m) => m.id === model.id);
if (oldModel) this.removeItem(oldModel, tag);
this.addItem(model, tag, index);
Expand Down Expand Up @@ -90,7 +99,7 @@ export abstract class ModelStore<TModel extends Model>
);
}

replaceAll(newModels: TModel[], tag: string): void {
replaceAll(newModels: TModel[], tag: ModelChangeTagValue): void {
this.clear(tag);
for (const model of newModels) {
this.add(model, tag);
Expand Down
Loading
Loading