@metamask-previews/profile-metrics-controller 5.2.2-preview-955a450b9 → 5.2.2-preview-20f24a578
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/CHANGELOG.md +0 -12
- package/dist/ProfileMetricsController-method-action-types.d.ts +1 -13
- package/dist/ProfileMetricsController-method-action-types.d.ts.map +1 -1
- package/dist/ProfileMetricsController-method-action-types.js.map +1 -1
- package/dist/ProfileMetricsController.d.ts +0 -9
- package/dist/ProfileMetricsController.d.ts.map +1 -1
- package/dist/ProfileMetricsController.js +3 -53
- package/dist/ProfileMetricsController.js.map +1 -1
- package/dist/ProfileMetricsService.d.ts +0 -5
- package/dist/ProfileMetricsService.d.ts.map +1 -1
- package/dist/ProfileMetricsService.js +2 -21
- package/dist/ProfileMetricsService.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
package/CHANGELOG.md
CHANGED
|
@@ -7,11 +7,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
-
### Added
|
|
11
|
-
|
|
12
|
-
- Add `ProfileMetricsService.resetCircuitBreakers` method, which closes the nonce and metrics circuit breakers so clients can call it next to `clearState` on wallet reset ([#11632](https://github.com/MetaMask/core/pull/11632))
|
|
13
|
-
- Add `ProfileMetricsController.clearState` method and `ProfileMetricsController:clearState` messenger action, which reset the controller to its default state so clients can clear the sync queue and reported accounts on wallet reset ([#11632](https://github.com/MetaMask/core/pull/11632))
|
|
14
|
-
|
|
15
10
|
### Changed
|
|
16
11
|
|
|
17
12
|
- Bump `@metamask/transaction-controller` from `^74.0.0` to `^74.2.0` ([#11579](https://github.com/MetaMask/core/pull/11579), [#11605](https://github.com/MetaMask/core/pull/11605))
|
|
@@ -19,13 +14,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
19
14
|
- Bump `@metamask/profile-sync-controller` from `^36.1.1` to `^36.1.2` ([#11474](https://github.com/MetaMask/core/pull/11474))
|
|
20
15
|
- Bump `@metamask/utils` from `^12.0.1` to `^12.0.2` ([#11474](https://github.com/MetaMask/core/pull/11474))
|
|
21
16
|
- Bump `@metamask/snaps-sdk` from `^11.0.0` to `^11.2.0` ([#10737](https://github.com/MetaMask/core/pull/10737))
|
|
22
|
-
- Bump `uuid` from `^14.0.2` to `^14.0.3` ([#11645](https://github.com/MetaMask/core/pull/11645))
|
|
23
|
-
|
|
24
|
-
### Fixed
|
|
25
|
-
|
|
26
|
-
- Drop sync queue batches whose entropy source no longer has any account, so a reset or recreated vault no longer leaves batches that can never be submitted and keep the service circuit breaker open ([#11632](https://github.com/MetaMask/core/pull/11632))
|
|
27
|
-
- Stop retrying `ProfileMetricsService` requests that fail with a 4xx response, so a rejected nonce or submit request is made once per call instead of four times. Network errors and 5xx responses are still retried ([#11632](https://github.com/MetaMask/core/pull/11632))
|
|
28
|
-
- Stop submitting the remaining batches for the current poll when the circuit breaker is open, logging once instead of once per batch ([#11632](https://github.com/MetaMask/core/pull/11632))
|
|
29
17
|
|
|
30
18
|
## [5.2.2]
|
|
31
19
|
|
|
@@ -11,20 +11,8 @@ export type ProfileMetricsControllerSkipInitialDelayAction = {
|
|
|
11
11
|
type: `ProfileMetricsController:skipInitialDelay`;
|
|
12
12
|
handler: ProfileMetricsController['skipInitialDelay'];
|
|
13
13
|
};
|
|
14
|
-
/**
|
|
15
|
-
* Reset the controller to its default state. Clients call this on wallet
|
|
16
|
-
* reset so the next wallet does not inherit the previous wallet's sync queue
|
|
17
|
-
* and reported accounts.
|
|
18
|
-
*
|
|
19
|
-
* Waits for an in-flight poll to finish first, so that it cannot write back
|
|
20
|
-
* to the cleared state.
|
|
21
|
-
*/
|
|
22
|
-
export type ProfileMetricsControllerClearStateAction = {
|
|
23
|
-
type: `ProfileMetricsController:clearState`;
|
|
24
|
-
handler: ProfileMetricsController['clearState'];
|
|
25
|
-
};
|
|
26
14
|
/**
|
|
27
15
|
* Union of all ProfileMetricsController action types.
|
|
28
16
|
*/
|
|
29
|
-
export type ProfileMetricsControllerMethodActions = ProfileMetricsControllerSkipInitialDelayAction
|
|
17
|
+
export type ProfileMetricsControllerMethodActions = ProfileMetricsControllerSkipInitialDelayAction;
|
|
30
18
|
//# sourceMappingURL=ProfileMetricsController-method-action-types.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProfileMetricsController-method-action-types.d.ts","sourceRoot":"","sources":["../src/ProfileMetricsController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAE9E;;;GAGG;AACH,MAAM,MAAM,8CAA8C,GAAG;IAC3D,IAAI,EAAE,2CAA2C,CAAC;IAClD,OAAO,EAAE,wBAAwB,CAAC,kBAAkB,CAAC,CAAC;CACvD,CAAC;AAEF
|
|
1
|
+
{"version":3,"file":"ProfileMetricsController-method-action-types.d.ts","sourceRoot":"","sources":["../src/ProfileMetricsController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAE9E;;;GAGG;AACH,MAAM,MAAM,8CAA8C,GAAG;IAC3D,IAAI,EAAE,2CAA2C,CAAC;IAClD,OAAO,EAAE,wBAAwB,CAAC,kBAAkB,CAAC,CAAC;CACvD,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,qCAAqC,GAC/C,8CAA8C,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProfileMetricsController-method-action-types.js","sourceRoot":"","sources":["../src/ProfileMetricsController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { ProfileMetricsController } from './ProfileMetricsController.js';\n\n/**\n * Skip the initial delay period by setting the end timestamp to the current time.\n * Metrics will be sent on the next poll.\n */\nexport type ProfileMetricsControllerSkipInitialDelayAction = {\n type: `ProfileMetricsController:skipInitialDelay`;\n handler: ProfileMetricsController['skipInitialDelay'];\n};\n\n/**\n *
|
|
1
|
+
{"version":3,"file":"ProfileMetricsController-method-action-types.js","sourceRoot":"","sources":["../src/ProfileMetricsController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { ProfileMetricsController } from './ProfileMetricsController.js';\n\n/**\n * Skip the initial delay period by setting the end timestamp to the current time.\n * Metrics will be sent on the next poll.\n */\nexport type ProfileMetricsControllerSkipInitialDelayAction = {\n type: `ProfileMetricsController:skipInitialDelay`;\n handler: ProfileMetricsController['skipInitialDelay'];\n};\n\n/**\n * Union of all ProfileMetricsController action types.\n */\nexport type ProfileMetricsControllerMethodActions =\n ProfileMetricsControllerSkipInitialDelayAction;\n"]}
|
|
@@ -150,15 +150,6 @@ export declare class ProfileMetricsController extends ProfileMetricsController_b
|
|
|
150
150
|
* Metrics will be sent on the next poll.
|
|
151
151
|
*/
|
|
152
152
|
skipInitialDelay(): void;
|
|
153
|
-
/**
|
|
154
|
-
* Reset the controller to its default state. Clients call this on wallet
|
|
155
|
-
* reset so the next wallet does not inherit the previous wallet's sync queue
|
|
156
|
-
* and reported accounts.
|
|
157
|
-
*
|
|
158
|
-
* Waits for an in-flight poll to finish first, so that it cannot write back
|
|
159
|
-
* to the cleared state.
|
|
160
|
-
*/
|
|
161
|
-
clearState(): Promise<void>;
|
|
162
153
|
/**
|
|
163
154
|
* Execute a single poll to sync user profile data.
|
|
164
155
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProfileMetricsController.d.ts","sourceRoot":"","sources":["../src/ProfileMetricsController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mCAAmC,EACnC,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AAM,CAAC;QAC/B,oBAAoB,CAAC,EAAE,MAAM,CAAC;KAC/B,EAiDA;IAED;;;OAGG;IACH,gBAAgB,IAAI,IAAI,CAIvB;IAED;;;;;;;;;;;;;OAaG;IACG,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC,CAkDlC;CAgMF"}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { BrokenCircuitError } from '@metamask/controller-utils';
|
|
2
1
|
import { KeyringTypes } from '@metamask/keyring-controller';
|
|
3
2
|
import { StaticIntervalPollingController } from '@metamask/polling-controller';
|
|
4
3
|
import { Duration, inMilliseconds, parseCaipChainId } from '@metamask/utils';
|
|
@@ -80,7 +79,7 @@ export function getDefaultProfileMetricsControllerState() {
|
|
|
80
79
|
reportedAccounts: [],
|
|
81
80
|
};
|
|
82
81
|
}
|
|
83
|
-
const MESSENGER_EXPOSED_METHODS = ['skipInitialDelay'
|
|
82
|
+
const MESSENGER_EXPOSED_METHODS = ['skipInitialDelay'];
|
|
84
83
|
/**
|
|
85
84
|
* Manages user profile metrics.
|
|
86
85
|
*
|
|
@@ -151,19 +150,6 @@ export class ProfileMetricsController extends StaticIntervalPollingController()
|
|
|
151
150
|
state.initialDelayEndTimestamp = Date.now();
|
|
152
151
|
});
|
|
153
152
|
}
|
|
154
|
-
/**
|
|
155
|
-
* Reset the controller to its default state. Clients call this on wallet
|
|
156
|
-
* reset so the next wallet does not inherit the previous wallet's sync queue
|
|
157
|
-
* and reported accounts.
|
|
158
|
-
*
|
|
159
|
-
* Waits for an in-flight poll to finish first, so that it cannot write back
|
|
160
|
-
* to the cleared state.
|
|
161
|
-
*/
|
|
162
|
-
async clearState() {
|
|
163
|
-
await this.#mutex.runExclusive(() => {
|
|
164
|
-
this.update(() => getDefaultProfileMetricsControllerState());
|
|
165
|
-
});
|
|
166
|
-
}
|
|
167
153
|
/**
|
|
168
154
|
* Execute a single poll to sync user profile data.
|
|
169
155
|
*
|
|
@@ -187,11 +173,10 @@ export class ProfileMetricsController extends StaticIntervalPollingController()
|
|
|
187
173
|
if (!this.#isInitialDelayComplete()) {
|
|
188
174
|
return;
|
|
189
175
|
}
|
|
190
|
-
|
|
176
|
+
const batches = Object.entries(this.state.syncQueue);
|
|
177
|
+
if (batches.length === 0) {
|
|
191
178
|
return;
|
|
192
179
|
}
|
|
193
|
-
this.#pruneStaleBatches();
|
|
194
|
-
const batches = Object.entries(this.state.syncQueue);
|
|
195
180
|
const proofCandidates = this.#getProofCandidatesByAddress();
|
|
196
181
|
for (const [queueKey, accounts] of batches) {
|
|
197
182
|
const entropySourceId = queueKey === NON_MNEMONIC_QUEUE_KEY ? null : queueKey;
|
|
@@ -216,47 +201,12 @@ export class ProfileMetricsController extends StaticIntervalPollingController()
|
|
|
216
201
|
});
|
|
217
202
|
}
|
|
218
203
|
catch (error) {
|
|
219
|
-
if (error instanceof BrokenCircuitError) {
|
|
220
|
-
// Every remaining batch would fail the same way. Keep them queued
|
|
221
|
-
// for a later poll instead of logging one error per batch.
|
|
222
|
-
console.error('Profile metrics submission paused: the circuit breaker is open.', error);
|
|
223
|
-
break;
|
|
224
|
-
}
|
|
225
204
|
// We want to log the error but continue processing other batches.
|
|
226
205
|
console.error(`Failed to submit profile metrics for sync queue key ${queueKey}:`, error);
|
|
227
206
|
}
|
|
228
207
|
}
|
|
229
208
|
});
|
|
230
209
|
}
|
|
231
|
-
/**
|
|
232
|
-
* Drop the batches of entropy sources that no longer have any account.
|
|
233
|
-
*
|
|
234
|
-
* A reset or recreated vault leaves the previous keyrings' batches in the
|
|
235
|
-
* persisted queue. They can never be submitted (the bearer token cannot be
|
|
236
|
-
* resolved for an unknown entropy source), and their failures would open the
|
|
237
|
-
* service circuit breaker for every other batch.
|
|
238
|
-
*
|
|
239
|
-
* Nothing is dropped while `AccountsController` has no accounts, as its
|
|
240
|
-
* state may not be loaded yet. The non-mnemonic batch is always kept.
|
|
241
|
-
*/
|
|
242
|
-
#pruneStaleBatches() {
|
|
243
|
-
const { accounts } = this.messenger.call('AccountsController:getState').internalAccounts;
|
|
244
|
-
const liveAccounts = Object.values(accounts);
|
|
245
|
-
if (liveAccounts.length === 0) {
|
|
246
|
-
return;
|
|
247
|
-
}
|
|
248
|
-
const liveEntropySourceIds = new Set(liveAccounts.map(getAccountEntropySourceId));
|
|
249
|
-
const staleQueueKeys = Object.keys(this.state.syncQueue).filter((queueKey) => queueKey !== NON_MNEMONIC_QUEUE_KEY &&
|
|
250
|
-
!liveEntropySourceIds.has(queueKey));
|
|
251
|
-
if (staleQueueKeys.length === 0) {
|
|
252
|
-
return;
|
|
253
|
-
}
|
|
254
|
-
this.update((state) => {
|
|
255
|
-
for (const queueKey of staleQueueKeys) {
|
|
256
|
-
delete state.syncQueue[queueKey];
|
|
257
|
-
}
|
|
258
|
-
});
|
|
259
|
-
}
|
|
260
210
|
/**
|
|
261
211
|
* Attach a proof of ownership to each account in a single entropy-source
|
|
262
212
|
* batch when possible.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProfileMetricsController.js","sourceRoot":"","sources":["../src/ProfileMetricsController.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAKhE,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAG5D,OAAO,EAAE,+BAA+B,EAAE,MAAM,8BAA8B,CAAC;AAE/E,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAC7E,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AASpC,OAAO,EACL,mBAAmB,EACnB,8BAA8B,GAC/B,MAAM,yBAAyB,CAAC;AAEjC;;;;GAIG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,0BAA0B,CAAC;AAEzD;;GAEG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,cAAc,CAC1D,CAAC,EACD,QAAQ,CAAC,MAAM,CAChB,CAAC;AAEF;;;;;;GAMG;A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e,CACtB,KAAoC,EACpC,QAA2B;IAE3B,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC;QAC7B,GAAG,KAAK,CAAC,gBAAgB;QACzB,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE,CAClD,KAAK,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,OAAO,CAAC,CACpC;KACF,CAAC,CAAC;IACH,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAC/B,MAAM,aAAa,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;QAC/C,IAAI,cAAc,CAAC,GAAG,CAAC,aAAa,CAAC,OAAO,CAAC,EAAE,CAAC;YAC9C,SAAS;QACX,CAAC;QACD,cAAc,CAAC,GAAG,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;QAC1C,MAAM,QAAQ,GACZ,yBAAyB,CAAC,OAAO,CAAC,IAAI,sBAAsB,CAAC;QAC/D,CAAC,KAAK,CAAC,SAAS,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;IACzD,CAAC;AACH,CAAC","sourcesContent":["import type {\n AccountsControllerAccountAddedEvent,\n AccountsControllerAccountRemovedEvent,\n AccountsControllerGetStateAction,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BrokenCircuitError } from '@metamask/controller-utils';\nimport type {\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport { KeyringTypes } from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport type { Messenger } from '@metamask/messenger';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport { TransactionControllerTransactionSubmittedEvent } from '@metamask/transaction-controller';\nimport { Duration, inMilliseconds, parseCaipChainId } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\n\nimport type { ProfileMetricsControllerMethodActions } from './ProfileMetricsController-method-action-types.js';\nimport type { ProfileMetricsServiceMethodActions } from './ProfileMetricsService-method-action-types.js';\nimport type {\n AccountSource,\n AccountWithScopes,\n} from './ProfileMetricsService.js';\nimport type { ProofOfOwnershipServiceMethodActions } from './ProofOfOwnershipService-method-action-types.js';\nimport {\n canonicalizeAddress,\n ProofUnsupportedNamespaceError,\n} from './utils/canonicalize.js';\n\n/**\n * The name of the {@link ProfileMetricsController}, used to namespace the\n * controller's actions and events and to namespace the controller's state data\n * when composed with other controllers.\n */\nexport const controllerName = 'ProfileMetricsController';\n\n/**\n * The default delay duration before data is sent for the first time.\n */\nexport const DEFAULT_INITIAL_DELAY_DURATION = inMilliseconds(\n 1,\n Duration.Minute,\n);\n\n/**\n * The sync queue key for accounts that are not backed by a mnemonic (hardware,\n * imported private key, and non-mnemonic Snap accounts). These are submitted\n * without an entropy source ID, which the AuthenticationController resolves\n * to the primary SRP. The value is `String(null)` so that queues persisted by\n * earlier versions keep draining.\n */\nconst NON_MNEMONIC_QUEUE_KEY = 'null';\n\n/**\n * Describes the shape of the state object for {@link ProfileMetricsController}.\n */\nexport type ProfileMetricsControllerState = {\n /**\n * Whether existing accounts have been added\n * to the queue.\n */\n initialEnqueueCompleted: boolean;\n /**\n * The queue of accounts to be synced, with canonical addresses.\n * Each key is an entropy source ID, and each value is an array of account\n * addresses associated with that entropy source. Accounts with no entropy\n * source ID are grouped under {@link NON_MNEMONIC_QUEUE_KEY}.\n */\n syncQueue: Record<string, AccountWithScopes[]>;\n /**\n * The timestamp when the first data sending can be attempted.\n */\n initialDelayEndTimestamp?: number;\n /**\n * Whether previously-synced accounts have been re-enqueued so their\n * proofs of ownership are submitted alongside everything else. Set on\n * the first unlock after upgrading to a version that signs proofs of\n * ownership; fresh installs flip this on their initial sync since the\n * first poll already attaches proofs.\n */\n proofBackfillEnqueued: boolean;\n /**\n * Whether known accounts have been re-enqueued once so that they are\n * reported with canonical addresses and an account source. Set on the\n * first unlock after upgrading; fresh installs\n * flip this on their initial sync.\n */\n accountSourceBackfillEnqueued: boolean;\n /**\n * Canonical addresses that have already been reported. Enqueuing one of\n * these again is a no-op.\n */\n reportedAccounts: string[];\n};\n\n/**\n * The metadata for each property in {@link ProfileMetricsControllerState}.\n */\nconst profileMetricsControllerMetadata = {\n initialEnqueueCompleted: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: false,\n },\n syncQueue: {\n persist: true,\n includeInDebugSnapshot: false,\n includeInStateLogs: true,\n usedInUi: false,\n },\n initialDelayEndTimestamp: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: false,\n },\n proofBackfillEnqueued: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: false,\n },\n accountSourceBackfillEnqueued: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: false,\n },\n reportedAccounts: {\n persist: true,\n includeInDebugSnapshot: false,\n includeInStateLogs: true,\n usedInUi: false,\n },\n} satisfies StateMetadata<ProfileMetricsControllerState>;\n\n/**\n * Constructs the default {@link ProfileMetricsController} state. This allows\n * consumers to provide a partial state object when initializing the controller\n * and also helps in constructing complete state objects for this controller in\n * tests.\n *\n * @returns The default {@link ProfileMetricsController} state.\n */\nexport function getDefaultProfileMetricsControllerState(): ProfileMetricsControllerState {\n return {\n initialEnqueueCompleted: false,\n syncQueue: {},\n proofBackfillEnqueued: false,\n accountSourceBackfillEnqueued: false,\n reportedAccounts: [],\n };\n}\n\nconst MESSENGER_EXPOSED_METHODS = ['skipInitialDelay', 'clearState'] as const;\n\n/**\n * Retrieves the state of the {@link ProfileMetricsController}.\n */\nexport type ProfileMetricsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n ProfileMetricsControllerState\n>;\n\n/**\n * Actions that {@link ProfileMetricsControllerMessenger} exposes to other consumers.\n */\nexport type ProfileMetricsControllerActions =\n | ProfileMetricsControllerGetStateAction\n | ProfileMetricsControllerMethodActions;\n\n/**\n * Actions from other messengers that {@link ProfileMetricsControllerMessenger} calls.\n */\ntype AllowedActions =\n | ProfileMetricsServiceMethodActions\n | ProofOfOwnershipServiceMethodActions\n | AccountsControllerGetStateAction;\n\n/**\n * Published when the state of {@link ProfileMetricsController} changes.\n */\nexport type ProfileMetricsControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n ProfileMetricsControllerState\n >;\n\n/**\n * Events that {@link ProfileMetricsControllerMessenger} exposes to other consumers.\n */\nexport type ProfileMetricsControllerEvents =\n ProfileMetricsControllerStateChangeEvent;\n\n/**\n * Events from other messengers that {@link ProfileMetricsControllerMessenger} subscribes\n * to.\n */\ntype AllowedEvents =\n | KeyringControllerUnlockEvent\n | KeyringControllerLockEvent\n | AccountsControllerAccountAddedEvent\n | AccountsControllerAccountRemovedEvent\n | TransactionControllerTransactionSubmittedEvent;\n\n/**\n * The messenger restricted to actions and events accessed by\n * {@link ProfileMetricsController}.\n */\nexport type ProfileMetricsControllerMessenger = Messenger<\n typeof controllerName,\n ProfileMetricsControllerActions | AllowedActions,\n ProfileMetricsControllerEvents | AllowedEvents\n>;\n\n/**\n * Manages user profile metrics.\n *\n * For users who opt-in to metrics, this controller ensures we have metrics about their user\n * profile (metrics ID and accounts).\n */\nexport class ProfileMetricsController extends StaticIntervalPollingController()<\n typeof controllerName,\n ProfileMetricsControllerState,\n ProfileMetricsControllerMessenger\n> {\n readonly #mutex = new Mutex();\n\n readonly #assertUserOptedIn: () => boolean;\n\n readonly #getMetaMetricsId: () => string;\n\n readonly #initialDelayDuration: number;\n\n /**\n * Constructs a new {@link ProfileMetricsController}.\n *\n * @param args - The constructor arguments.\n * @param args.messenger - The messenger suited for this controller.\n * @param args.state - The desired state with which to initialize this\n * controller. Missing properties will be filled in with defaults.\n * @param args.assertUserOptedIn - A function that asserts whether the user has\n * opted in to user profile features. If the user has not opted in, sync\n * operations will be no-ops.\n * @param args.getMetaMetricsId - A function that returns the MetaMetrics ID\n * of the user.\n * @param args.interval - The interval, in milliseconds, at which the controller will\n * attempt to send user profile data. Defaults to 10 seconds.\n * @param args.initialDelayDuration - The delay duration before data is sent\n * for the first time, in milliseconds. Defaults to 10 minutes.\n */\n constructor({\n messenger,\n state,\n assertUserOptedIn,\n getMetaMetricsId,\n interval = 10 * 1000,\n initialDelayDuration = DEFAULT_INITIAL_DELAY_DURATION,\n }: {\n messenger: ProfileMetricsControllerMessenger;\n state?: Partial<ProfileMetricsControllerState>;\n interval?: number;\n assertUserOptedIn: () => boolean;\n getMetaMetricsId: () => string;\n initialDelayDuration?: number;\n }) {\n super({\n messenger,\n metadata: profileMetricsControllerMetadata,\n name: controllerName,\n state: {\n ...getDefaultProfileMetricsControllerState(),\n ...state,\n },\n });\n\n this.#assertUserOptedIn = assertUserOptedIn;\n this.#getMetaMetricsId = getMetaMetricsId;\n this.#initialDelayDuration = initialDelayDuration;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n\n this.messenger.subscribe('KeyringController:unlock', () => {\n if (this.#assertUserOptedIn()) {\n // If the user has already opted in at the start of the session,\n // it must have opted in during onboarding, or during a previous session.\n this.skipInitialDelay();\n }\n this.#enqueueAccountsIfNeeded().catch(\n this.messenger.captureException ?? console.error,\n );\n this.startPolling(null);\n });\n\n this.messenger.subscribe('KeyringController:lock', () =>\n this.stopAllPolling(),\n );\n\n this.messenger.subscribe('TransactionController:transactionSubmitted', () =>\n this.skipInitialDelay(),\n );\n\n this.messenger.subscribe('AccountsController:accountAdded', (account) => {\n this.#addAccountToQueue(account).catch(console.error);\n });\n\n this.messenger.subscribe('AccountsController:accountRemoved', (account) => {\n this.#removeAccountFromQueue(account).catch(console.error);\n });\n\n this.setIntervalLength(interval);\n }\n\n /**\n * Skip the initial delay period by setting the end timestamp to the current time.\n * Metrics will be sent on the next poll.\n */\n skipInitialDelay(): void {\n this.update((state) => {\n state.initialDelayEndTimestamp = Date.now();\n });\n }\n\n /**\n * Reset the controller to its default state. Clients call this on wallet\n * reset so the next wallet does not inherit the previous wallet's sync queue\n * and reported accounts.\n *\n * Waits for an in-flight poll to finish first, so that it cannot write back\n * to the cleared state.\n */\n async clearState(): Promise<void> {\n await this.#mutex.runExclusive(() => {\n this.update(() => getDefaultProfileMetricsControllerState());\n });\n }\n\n /**\n * Execute a single poll to sync user profile data.\n *\n * Each batch of queued accounts is sent to the ProfileMetricsService and\n * then dropped from the sync queue, with its addresses recorded as\n * reported. Mnemonic batches are attributed to their own entropy source\n * and carry proofs of ownership when one can be produced (see\n * {@link #attachProofs}); the non-mnemonic batch is submitted without an\n * entropy source ID (resolved to the primary SRP downstream) and never\n * carries proofs. This operation is mutexed to prevent concurrent\n * executions.\n *\n * @returns A promise that resolves when the poll is complete.\n */\n async _executePoll(): Promise<void> {\n await this.#mutex.runExclusive(async () => {\n if (!this.#assertUserOptedIn()) {\n return;\n }\n this.#setInitialDelayEndTimestampIfNull();\n if (!this.#isInitialDelayComplete()) {\n return;\n }\n if (Object.keys(this.state.syncQueue).length === 0) {\n return;\n }\n this.#pruneStaleBatches();\n const batches = Object.entries(this.state.syncQueue);\n const proofCandidates = this.#getProofCandidatesByAddress();\n for (const [queueKey, accounts] of batches) {\n const entropySourceId =\n queueKey === NON_MNEMONIC_QUEUE_KEY ? null : queueKey;\n try {\n const accountsToSubmit =\n entropySourceId === null\n ? accounts\n : await this.#attachProofs(\n accounts,\n proofCandidates,\n entropySourceId,\n );\n await this.messenger.call('ProfileMetricsService:submitMetrics', {\n metametricsId: this.#getMetaMetricsId(),\n entropySourceId,\n accounts: accountsToSubmit,\n });\n this.update((state) => {\n const reportedAccounts = new Set(state.reportedAccounts);\n for (const { address } of accountsToSubmit) {\n if (!reportedAccounts.has(address)) {\n reportedAccounts.add(address);\n state.reportedAccounts.push(address);\n }\n }\n delete state.syncQueue[queueKey];\n });\n } catch (error) {\n if (error instanceof BrokenCircuitError) {\n // Every remaining batch would fail the same way. Keep them queued\n // for a later poll instead of logging one error per batch.\n console.error(\n 'Profile metrics submission paused: the circuit breaker is open.',\n error,\n );\n break;\n }\n // We want to log the error but continue processing other batches.\n console.error(\n `Failed to submit profile metrics for sync queue key ${queueKey}:`,\n error,\n );\n }\n }\n });\n }\n\n /**\n * Drop the batches of entropy sources that no longer have any account.\n *\n * A reset or recreated vault leaves the previous keyrings' batches in the\n * persisted queue. They can never be submitted (the bearer token cannot be\n * resolved for an unknown entropy source), and their failures would open the\n * service circuit breaker for every other batch.\n *\n * Nothing is dropped while `AccountsController` has no accounts, as its\n * state may not be loaded yet. The non-mnemonic batch is always kept.\n */\n #pruneStaleBatches(): void {\n const { accounts } = this.messenger.call(\n 'AccountsController:getState',\n ).internalAccounts;\n const liveAccounts = Object.values(accounts);\n if (liveAccounts.length === 0) {\n return;\n }\n const liveEntropySourceIds = new Set(\n liveAccounts.map(getAccountEntropySourceId),\n );\n const staleQueueKeys = Object.keys(this.state.syncQueue).filter(\n (queueKey) =>\n queueKey !== NON_MNEMONIC_QUEUE_KEY &&\n !liveEntropySourceIds.has(queueKey),\n );\n if (staleQueueKeys.length === 0) {\n return;\n }\n this.update((state) => {\n for (const queueKey of staleQueueKeys) {\n delete state.syncQueue[queueKey];\n }\n });\n }\n\n /**\n * Attach a proof of ownership to each account in a single entropy-source\n * batch when possible.\n *\n * Per-account failures (snap missing the `signProofOfOwnership` method,\n * snap rejection) and whole-batch nonce failures are caught and\n * downgraded to \"submit without a proof\" so the batch still goes through\n * and the proof is retried on the next poll.\n *\n * @param accounts - The queued accounts for a single batch.\n * @param proofCandidates - Live accounts that can produce a proof, keyed by\n * canonical address (see {@link #getProofCandidatesByAddress}).\n * @param entropySourceId - The entropy source ID for this batch.\n * @returns The accounts with `proof` populated where signing succeeded.\n */\n async #attachProofs(\n accounts: AccountWithScopes[],\n proofCandidates: Map<string, InternalAccount>,\n entropySourceId: string,\n ): Promise<AccountWithScopes[]> {\n const identifiers = new Set(\n accounts\n .map(({ address }) => address)\n .filter((address) => proofCandidates.has(address)),\n );\n if (identifiers.size === 0) {\n return accounts;\n }\n\n let nonces: Record<string, string> = {};\n try {\n nonces = await this.messenger.call('ProfileMetricsService:fetchNonces', {\n identifiers: [...identifiers],\n entropySourceId,\n });\n } catch (error) {\n console.error(\n `Failed to fetch proof-of-ownership nonces for entropy source ID ${entropySourceId}:`,\n error,\n );\n }\n\n return await Promise.all(\n accounts.map(async (queued): Promise<AccountWithScopes> => {\n const account = proofCandidates.get(queued.address);\n const nonce = nonces[queued.address];\n if (!account || !nonce) {\n return queued;\n }\n try {\n const proof = await this.messenger.call(\n 'ProofOfOwnershipService:sign',\n { account, nonce },\n );\n return { ...queued, proof };\n } catch (error) {\n console.error(\n `Failed to sign proof of ownership for account ${account.id}:`,\n error,\n );\n return queued;\n }\n }),\n );\n }\n\n /**\n * Snapshot the live accounts keyed by canonical address, so they can be\n * matched against queued accounts when signing proofs of ownership.\n * Accounts whose namespace has no canonical form cannot produce a proof\n * and are left out.\n *\n * @returns A map of canonical address → `InternalAccount`.\n */\n #getProofCandidatesByAddress(): Map<string, InternalAccount> {\n const candidates = new Map<string, InternalAccount>();\n const { accounts } = this.messenger.call(\n 'AccountsController:getState',\n ).internalAccounts;\n for (const account of Object.values(accounts)) {\n const canonicalAddress = getCanonicalAddress(account);\n if (canonicalAddress) {\n candidates.set(canonicalAddress, account);\n }\n }\n return candidates;\n }\n\n /**\n * Enqueue all currently-known accounts onto the sync queue if needed.\n * Single entry point covering the fresh-install first sync and the\n * one-time backfills for users upgrading (proofs of ownership, then\n * canonical addresses and account sources).\n *\n * Bails for opted-out users (the poll wouldn't drain the queue\n * anyway), and bails once every bootstrap step has already run.\n * Otherwise enqueues all known accounts and flips every flag so this\n * becomes a permanent no-op for the lifetime of the install.\n */\n async #enqueueAccountsIfNeeded(): Promise<void> {\n await this.#mutex.runExclusive(async () => {\n if (!this.#assertUserOptedIn()) {\n return;\n }\n if (\n this.state.initialEnqueueCompleted &&\n this.state.proofBackfillEnqueued &&\n this.state.accountSourceBackfillEnqueued\n ) {\n return;\n }\n const { accounts } = this.messenger.call(\n 'AccountsController:getState',\n ).internalAccounts;\n this.update((state) => {\n // Replace the queue rather than append. `AccountsController` is\n // the source of truth, so this drops stale entries that survived\n // from a prior session and re-derives each account's canonical\n // address and source.\n state.syncQueue = {};\n enqueueAccounts(state, Object.values(accounts));\n state.initialEnqueueCompleted = true;\n state.proofBackfillEnqueued = true;\n state.accountSourceBackfillEnqueued = true;\n });\n });\n }\n\n /**\n * Set the initial delay end timestamp if it is not already set.\n */\n #setInitialDelayEndTimestampIfNull(): void {\n this.update((state) => {\n state.initialDelayEndTimestamp ??=\n Date.now() + this.#initialDelayDuration;\n });\n }\n\n /**\n * Check if the initial delay end timestamp is in the past.\n *\n * @returns True if the initial delay period has completed, false otherwise.\n */\n #isInitialDelayComplete(): boolean {\n return (\n this.state.initialDelayEndTimestamp !== undefined &&\n Date.now() >= this.state.initialDelayEndTimestamp\n );\n }\n\n /**\n * Queue the given account to be synced at the next poll, unless it has\n * already been reported or queued.\n *\n * @param account - The account to sync.\n */\n async #addAccountToQueue(account: InternalAccount): Promise<void> {\n await this.#mutex.runExclusive(async () => {\n this.update((state) => {\n enqueueAccounts(state, [account]);\n });\n });\n }\n\n /**\n * Remove the given account from the sync queue.\n *\n * @param account - The account address to remove.\n */\n async #removeAccountFromQueue(account: string): Promise<void> {\n await this.#mutex.runExclusive(async () => {\n this.update((state) => {\n for (const [entropySourceId, groupedAddresses] of Object.entries(\n state.syncQueue,\n )) {\n const index = groupedAddresses.findIndex(\n ({ address }) => address === account,\n );\n if (index === -1) {\n continue;\n }\n groupedAddresses.splice(index, 1);\n if (groupedAddresses.length === 0) {\n delete state.syncQueue[entropySourceId];\n }\n break;\n }\n });\n });\n }\n}\n\n/**\n * Retrieves the entropy source ID from the given account, if it exists.\n *\n * @param account - The account from which to retrieve the entropy source ID.\n * @returns The entropy source ID, or null if it does not exist.\n */\nfunction getAccountEntropySourceId(account: InternalAccount): string | null {\n if (account.options.entropy?.type === 'mnemonic') {\n return account.options.entropy.id;\n }\n return null;\n}\n\n/**\n * Derive the account source to report for the given account, from its\n * entropy source and keyring type.\n *\n * @param account - The account to classify.\n * @returns The account source, or undefined for unrecognized keyring types\n * (the auth API rejects unknown values, so those are left untagged).\n */\nfunction getAccountSource(account: InternalAccount): AccountSource | undefined {\n if (getAccountEntropySourceId(account) !== null) {\n return 'mnemonic';\n }\n switch (account.metadata.keyring.type) {\n case KeyringTypes.simple:\n return 'imported';\n case KeyringTypes.snap:\n return 'snap';\n case KeyringTypes.qr:\n case KeyringTypes.trezor:\n case KeyringTypes.oneKey:\n case KeyringTypes.ledger:\n case KeyringTypes.lattice:\n return 'hardware';\n default:\n return undefined;\n }\n}\n\n/**\n * Retrieves the canonical address of the given account, as expected by the\n * auth API (see {@link canonicalizeAddress}).\n *\n * @param account - The account whose address to canonicalize.\n * @returns The canonical address, or undefined when the account's namespace\n * has no canonical form (in which case it cannot produce a proof of\n * ownership either).\n */\nfunction getCanonicalAddress(account: InternalAccount): string | undefined {\n try {\n const [scope] = account.scopes;\n if (!scope) {\n throw new Error(`Scope not found for account ${account.id}`);\n }\n return canonicalizeAddress(\n account.address,\n parseCaipChainId(scope).namespace,\n );\n } catch (error) {\n // Unsupported namespaces are an expected pass-through; anything\n // else is logged so a new namespace doesn't go unnoticed.\n if (!(error instanceof ProofUnsupportedNamespaceError)) {\n console.error(\n `Failed to canonicalize address for account ${account.id}:`,\n error,\n );\n }\n return undefined;\n }\n}\n\n/**\n * Convert an internal account to the payload stored in the sync queue and\n * submitted to the ProfileMetricsService.\n *\n * @param account - The internal account.\n * @returns The queued account, with a canonical address and, when known, an\n * account source.\n */\nfunction toQueuedAccount(account: InternalAccount): AccountWithScopes {\n const accountSource = getAccountSource(account);\n return {\n address: getCanonicalAddress(account) ?? account.address,\n scopes: account.scopes,\n ...(accountSource ? { accountSource } : {}),\n };\n}\n\n/**\n * Push the given accounts onto the sync queue held in `state`, skipping any\n * whose canonical address has already been reported or is already queued.\n *\n * Duplicates must be caught here: two entries for one address would share a\n * single queue key, hence a single batch, and `#attachProofs` would sign the\n * same single-use nonce twice. The known addresses are collected into a set\n * once so that enqueuing `n` accounts stays linear.\n *\n * @param state - The controller state to mutate.\n * @param accounts - The accounts to enqueue.\n */\nfunction enqueueAccounts(\n state: ProfileMetricsControllerState,\n accounts: InternalAccount[],\n): void {\n const knownAddresses = new Set([\n ...state.reportedAccounts,\n ...Object.values(state.syncQueue).flatMap((batch) =>\n batch.map(({ address }) => address),\n ),\n ]);\n for (const account of accounts) {\n const queuedAccount = toQueuedAccount(account);\n if (knownAddresses.has(queuedAccount.address)) {\n continue;\n }\n knownAddresses.add(queuedAccount.address);\n const queueKey =\n getAccountEntropySourceId(account) ?? NON_MNEMONIC_QUEUE_KEY;\n (state.syncQueue[queueKey] ??= []).push(queuedAccount);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ProfileMetricsController.js","sourceRoot":"","sources":["../src/ProfileMetricsController.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAG5D,OAAO,EAAE,+BAA+B,EAAE,MAAM,8BAA8B,CAAC;AAE/E,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAC7E,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AASpC,OAAO,EACL,mBAAmB,EACnB,8BAA8B,GAC/B,MAAM,yBAAyB,CAAC;AAEjC;;;;GAIG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,0BAA0B,CAAC;AAEzD;;GAEG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,cAAc,CAC1D,CAAC,EACD,QAAQ,CAAC,MAAM,CAChB,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,sBAAsB,GAAG,MAA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,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE,CAClD,KAAK,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,OAAO,CAAC,CACpC;KACF,CAAC,CAAC;IACH,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAC/B,MAAM,aAAa,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;QAC/C,IAAI,cAAc,CAAC,GAAG,CAAC,aAAa,CAAC,OAAO,CAAC,EAAE,CAAC;YAC9C,SAAS;QACX,CAAC;QACD,cAAc,CAAC,GAAG,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;QAC1C,MAAM,QAAQ,GACZ,yBAAyB,CAAC,OAAO,CAAC,IAAI,sBAAsB,CAAC;QAC/D,CAAC,KAAK,CAAC,SAAS,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;IACzD,CAAC;AACH,CAAC","sourcesContent":["import type {\n AccountsControllerAccountAddedEvent,\n AccountsControllerAccountRemovedEvent,\n AccountsControllerGetStateAction,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport type {\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport { KeyringTypes } from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport type { Messenger } from '@metamask/messenger';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport { TransactionControllerTransactionSubmittedEvent } from '@metamask/transaction-controller';\nimport { Duration, inMilliseconds, parseCaipChainId } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\n\nimport type { ProfileMetricsControllerMethodActions } from './ProfileMetricsController-method-action-types.js';\nimport type { ProfileMetricsServiceMethodActions } from './ProfileMetricsService-method-action-types.js';\nimport type {\n AccountSource,\n AccountWithScopes,\n} from './ProfileMetricsService.js';\nimport type { ProofOfOwnershipServiceMethodActions } from './ProofOfOwnershipService-method-action-types.js';\nimport {\n canonicalizeAddress,\n ProofUnsupportedNamespaceError,\n} from './utils/canonicalize.js';\n\n/**\n * The name of the {@link ProfileMetricsController}, used to namespace the\n * controller's actions and events and to namespace the controller's state data\n * when composed with other controllers.\n */\nexport const controllerName = 'ProfileMetricsController';\n\n/**\n * The default delay duration before data is sent for the first time.\n */\nexport const DEFAULT_INITIAL_DELAY_DURATION = inMilliseconds(\n 1,\n Duration.Minute,\n);\n\n/**\n * The sync queue key for accounts that are not backed by a mnemonic (hardware,\n * imported private key, and non-mnemonic Snap accounts). These are submitted\n * without an entropy source ID, which the AuthenticationController resolves\n * to the primary SRP. The value is `String(null)` so that queues persisted by\n * earlier versions keep draining.\n */\nconst NON_MNEMONIC_QUEUE_KEY = 'null';\n\n/**\n * Describes the shape of the state object for {@link ProfileMetricsController}.\n */\nexport type ProfileMetricsControllerState = {\n /**\n * Whether existing accounts have been added\n * to the queue.\n */\n initialEnqueueCompleted: boolean;\n /**\n * The queue of accounts to be synced, with canonical addresses.\n * Each key is an entropy source ID, and each value is an array of account\n * addresses associated with that entropy source. Accounts with no entropy\n * source ID are grouped under {@link NON_MNEMONIC_QUEUE_KEY}.\n */\n syncQueue: Record<string, AccountWithScopes[]>;\n /**\n * The timestamp when the first data sending can be attempted.\n */\n initialDelayEndTimestamp?: number;\n /**\n * Whether previously-synced accounts have been re-enqueued so their\n * proofs of ownership are submitted alongside everything else. Set on\n * the first unlock after upgrading to a version that signs proofs of\n * ownership; fresh installs flip this on their initial sync since the\n * first poll already attaches proofs.\n */\n proofBackfillEnqueued: boolean;\n /**\n * Whether known accounts have been re-enqueued once so that they are\n * reported with canonical addresses and an account source. Set on the\n * first unlock after upgrading; fresh installs\n * flip this on their initial sync.\n */\n accountSourceBackfillEnqueued: boolean;\n /**\n * Canonical addresses that have already been reported. Enqueuing one of\n * these again is a no-op.\n */\n reportedAccounts: string[];\n};\n\n/**\n * The metadata for each property in {@link ProfileMetricsControllerState}.\n */\nconst profileMetricsControllerMetadata = {\n initialEnqueueCompleted: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: false,\n },\n syncQueue: {\n persist: true,\n includeInDebugSnapshot: false,\n includeInStateLogs: true,\n usedInUi: false,\n },\n initialDelayEndTimestamp: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: false,\n },\n proofBackfillEnqueued: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: false,\n },\n accountSourceBackfillEnqueued: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: false,\n },\n reportedAccounts: {\n persist: true,\n includeInDebugSnapshot: false,\n includeInStateLogs: true,\n usedInUi: false,\n },\n} satisfies StateMetadata<ProfileMetricsControllerState>;\n\n/**\n * Constructs the default {@link ProfileMetricsController} state. This allows\n * consumers to provide a partial state object when initializing the controller\n * and also helps in constructing complete state objects for this controller in\n * tests.\n *\n * @returns The default {@link ProfileMetricsController} state.\n */\nexport function getDefaultProfileMetricsControllerState(): ProfileMetricsControllerState {\n return {\n initialEnqueueCompleted: false,\n syncQueue: {},\n proofBackfillEnqueued: false,\n accountSourceBackfillEnqueued: false,\n reportedAccounts: [],\n };\n}\n\nconst MESSENGER_EXPOSED_METHODS = ['skipInitialDelay'] as const;\n\n/**\n * Retrieves the state of the {@link ProfileMetricsController}.\n */\nexport type ProfileMetricsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n ProfileMetricsControllerState\n>;\n\n/**\n * Actions that {@link ProfileMetricsControllerMessenger} exposes to other consumers.\n */\nexport type ProfileMetricsControllerActions =\n | ProfileMetricsControllerGetStateAction\n | ProfileMetricsControllerMethodActions;\n\n/**\n * Actions from other messengers that {@link ProfileMetricsControllerMessenger} calls.\n */\ntype AllowedActions =\n | ProfileMetricsServiceMethodActions\n | ProofOfOwnershipServiceMethodActions\n | AccountsControllerGetStateAction;\n\n/**\n * Published when the state of {@link ProfileMetricsController} changes.\n */\nexport type ProfileMetricsControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n ProfileMetricsControllerState\n >;\n\n/**\n * Events that {@link ProfileMetricsControllerMessenger} exposes to other consumers.\n */\nexport type ProfileMetricsControllerEvents =\n ProfileMetricsControllerStateChangeEvent;\n\n/**\n * Events from other messengers that {@link ProfileMetricsControllerMessenger} subscribes\n * to.\n */\ntype AllowedEvents =\n | KeyringControllerUnlockEvent\n | KeyringControllerLockEvent\n | AccountsControllerAccountAddedEvent\n | AccountsControllerAccountRemovedEvent\n | TransactionControllerTransactionSubmittedEvent;\n\n/**\n * The messenger restricted to actions and events accessed by\n * {@link ProfileMetricsController}.\n */\nexport type ProfileMetricsControllerMessenger = Messenger<\n typeof controllerName,\n ProfileMetricsControllerActions | AllowedActions,\n ProfileMetricsControllerEvents | AllowedEvents\n>;\n\n/**\n * Manages user profile metrics.\n *\n * For users who opt-in to metrics, this controller ensures we have metrics about their user\n * profile (metrics ID and accounts).\n */\nexport class ProfileMetricsController extends StaticIntervalPollingController()<\n typeof controllerName,\n ProfileMetricsControllerState,\n ProfileMetricsControllerMessenger\n> {\n readonly #mutex = new Mutex();\n\n readonly #assertUserOptedIn: () => boolean;\n\n readonly #getMetaMetricsId: () => string;\n\n readonly #initialDelayDuration: number;\n\n /**\n * Constructs a new {@link ProfileMetricsController}.\n *\n * @param args - The constructor arguments.\n * @param args.messenger - The messenger suited for this controller.\n * @param args.state - The desired state with which to initialize this\n * controller. Missing properties will be filled in with defaults.\n * @param args.assertUserOptedIn - A function that asserts whether the user has\n * opted in to user profile features. If the user has not opted in, sync\n * operations will be no-ops.\n * @param args.getMetaMetricsId - A function that returns the MetaMetrics ID\n * of the user.\n * @param args.interval - The interval, in milliseconds, at which the controller will\n * attempt to send user profile data. Defaults to 10 seconds.\n * @param args.initialDelayDuration - The delay duration before data is sent\n * for the first time, in milliseconds. Defaults to 10 minutes.\n */\n constructor({\n messenger,\n state,\n assertUserOptedIn,\n getMetaMetricsId,\n interval = 10 * 1000,\n initialDelayDuration = DEFAULT_INITIAL_DELAY_DURATION,\n }: {\n messenger: ProfileMetricsControllerMessenger;\n state?: Partial<ProfileMetricsControllerState>;\n interval?: number;\n assertUserOptedIn: () => boolean;\n getMetaMetricsId: () => string;\n initialDelayDuration?: number;\n }) {\n super({\n messenger,\n metadata: profileMetricsControllerMetadata,\n name: controllerName,\n state: {\n ...getDefaultProfileMetricsControllerState(),\n ...state,\n },\n });\n\n this.#assertUserOptedIn = assertUserOptedIn;\n this.#getMetaMetricsId = getMetaMetricsId;\n this.#initialDelayDuration = initialDelayDuration;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n\n this.messenger.subscribe('KeyringController:unlock', () => {\n if (this.#assertUserOptedIn()) {\n // If the user has already opted in at the start of the session,\n // it must have opted in during onboarding, or during a previous session.\n this.skipInitialDelay();\n }\n this.#enqueueAccountsIfNeeded().catch(\n this.messenger.captureException ?? console.error,\n );\n this.startPolling(null);\n });\n\n this.messenger.subscribe('KeyringController:lock', () =>\n this.stopAllPolling(),\n );\n\n this.messenger.subscribe('TransactionController:transactionSubmitted', () =>\n this.skipInitialDelay(),\n );\n\n this.messenger.subscribe('AccountsController:accountAdded', (account) => {\n this.#addAccountToQueue(account).catch(console.error);\n });\n\n this.messenger.subscribe('AccountsController:accountRemoved', (account) => {\n this.#removeAccountFromQueue(account).catch(console.error);\n });\n\n this.setIntervalLength(interval);\n }\n\n /**\n * Skip the initial delay period by setting the end timestamp to the current time.\n * Metrics will be sent on the next poll.\n */\n skipInitialDelay(): void {\n this.update((state) => {\n state.initialDelayEndTimestamp = Date.now();\n });\n }\n\n /**\n * Execute a single poll to sync user profile data.\n *\n * Each batch of queued accounts is sent to the ProfileMetricsService and\n * then dropped from the sync queue, with its addresses recorded as\n * reported. Mnemonic batches are attributed to their own entropy source\n * and carry proofs of ownership when one can be produced (see\n * {@link #attachProofs}); the non-mnemonic batch is submitted without an\n * entropy source ID (resolved to the primary SRP downstream) and never\n * carries proofs. This operation is mutexed to prevent concurrent\n * executions.\n *\n * @returns A promise that resolves when the poll is complete.\n */\n async _executePoll(): Promise<void> {\n await this.#mutex.runExclusive(async () => {\n if (!this.#assertUserOptedIn()) {\n return;\n }\n this.#setInitialDelayEndTimestampIfNull();\n if (!this.#isInitialDelayComplete()) {\n return;\n }\n const batches = Object.entries(this.state.syncQueue);\n if (batches.length === 0) {\n return;\n }\n const proofCandidates = this.#getProofCandidatesByAddress();\n for (const [queueKey, accounts] of batches) {\n const entropySourceId =\n queueKey === NON_MNEMONIC_QUEUE_KEY ? null : queueKey;\n try {\n const accountsToSubmit =\n entropySourceId === null\n ? accounts\n : await this.#attachProofs(\n accounts,\n proofCandidates,\n entropySourceId,\n );\n await this.messenger.call('ProfileMetricsService:submitMetrics', {\n metametricsId: this.#getMetaMetricsId(),\n entropySourceId,\n accounts: accountsToSubmit,\n });\n this.update((state) => {\n const reportedAccounts = new Set(state.reportedAccounts);\n for (const { address } of accountsToSubmit) {\n if (!reportedAccounts.has(address)) {\n reportedAccounts.add(address);\n state.reportedAccounts.push(address);\n }\n }\n delete state.syncQueue[queueKey];\n });\n } catch (error) {\n // We want to log the error but continue processing other batches.\n console.error(\n `Failed to submit profile metrics for sync queue key ${queueKey}:`,\n error,\n );\n }\n }\n });\n }\n\n /**\n * Attach a proof of ownership to each account in a single entropy-source\n * batch when possible.\n *\n * Per-account failures (snap missing the `signProofOfOwnership` method,\n * snap rejection) and whole-batch nonce failures are caught and\n * downgraded to \"submit without a proof\" so the batch still goes through\n * and the proof is retried on the next poll.\n *\n * @param accounts - The queued accounts for a single batch.\n * @param proofCandidates - Live accounts that can produce a proof, keyed by\n * canonical address (see {@link #getProofCandidatesByAddress}).\n * @param entropySourceId - The entropy source ID for this batch.\n * @returns The accounts with `proof` populated where signing succeeded.\n */\n async #attachProofs(\n accounts: AccountWithScopes[],\n proofCandidates: Map<string, InternalAccount>,\n entropySourceId: string,\n ): Promise<AccountWithScopes[]> {\n const identifiers = new Set(\n accounts\n .map(({ address }) => address)\n .filter((address) => proofCandidates.has(address)),\n );\n if (identifiers.size === 0) {\n return accounts;\n }\n\n let nonces: Record<string, string> = {};\n try {\n nonces = await this.messenger.call('ProfileMetricsService:fetchNonces', {\n identifiers: [...identifiers],\n entropySourceId,\n });\n } catch (error) {\n console.error(\n `Failed to fetch proof-of-ownership nonces for entropy source ID ${entropySourceId}:`,\n error,\n );\n }\n\n return await Promise.all(\n accounts.map(async (queued): Promise<AccountWithScopes> => {\n const account = proofCandidates.get(queued.address);\n const nonce = nonces[queued.address];\n if (!account || !nonce) {\n return queued;\n }\n try {\n const proof = await this.messenger.call(\n 'ProofOfOwnershipService:sign',\n { account, nonce },\n );\n return { ...queued, proof };\n } catch (error) {\n console.error(\n `Failed to sign proof of ownership for account ${account.id}:`,\n error,\n );\n return queued;\n }\n }),\n );\n }\n\n /**\n * Snapshot the live accounts keyed by canonical address, so they can be\n * matched against queued accounts when signing proofs of ownership.\n * Accounts whose namespace has no canonical form cannot produce a proof\n * and are left out.\n *\n * @returns A map of canonical address → `InternalAccount`.\n */\n #getProofCandidatesByAddress(): Map<string, InternalAccount> {\n const candidates = new Map<string, InternalAccount>();\n const { accounts } = this.messenger.call(\n 'AccountsController:getState',\n ).internalAccounts;\n for (const account of Object.values(accounts)) {\n const canonicalAddress = getCanonicalAddress(account);\n if (canonicalAddress) {\n candidates.set(canonicalAddress, account);\n }\n }\n return candidates;\n }\n\n /**\n * Enqueue all currently-known accounts onto the sync queue if needed.\n * Single entry point covering the fresh-install first sync and the\n * one-time backfills for users upgrading (proofs of ownership, then\n * canonical addresses and account sources).\n *\n * Bails for opted-out users (the poll wouldn't drain the queue\n * anyway), and bails once every bootstrap step has already run.\n * Otherwise enqueues all known accounts and flips every flag so this\n * becomes a permanent no-op for the lifetime of the install.\n */\n async #enqueueAccountsIfNeeded(): Promise<void> {\n await this.#mutex.runExclusive(async () => {\n if (!this.#assertUserOptedIn()) {\n return;\n }\n if (\n this.state.initialEnqueueCompleted &&\n this.state.proofBackfillEnqueued &&\n this.state.accountSourceBackfillEnqueued\n ) {\n return;\n }\n const { accounts } = this.messenger.call(\n 'AccountsController:getState',\n ).internalAccounts;\n this.update((state) => {\n // Replace the queue rather than append. `AccountsController` is\n // the source of truth, so this drops stale entries that survived\n // from a prior session and re-derives each account's canonical\n // address and source.\n state.syncQueue = {};\n enqueueAccounts(state, Object.values(accounts));\n state.initialEnqueueCompleted = true;\n state.proofBackfillEnqueued = true;\n state.accountSourceBackfillEnqueued = true;\n });\n });\n }\n\n /**\n * Set the initial delay end timestamp if it is not already set.\n */\n #setInitialDelayEndTimestampIfNull(): void {\n this.update((state) => {\n state.initialDelayEndTimestamp ??=\n Date.now() + this.#initialDelayDuration;\n });\n }\n\n /**\n * Check if the initial delay end timestamp is in the past.\n *\n * @returns True if the initial delay period has completed, false otherwise.\n */\n #isInitialDelayComplete(): boolean {\n return (\n this.state.initialDelayEndTimestamp !== undefined &&\n Date.now() >= this.state.initialDelayEndTimestamp\n );\n }\n\n /**\n * Queue the given account to be synced at the next poll, unless it has\n * already been reported or queued.\n *\n * @param account - The account to sync.\n */\n async #addAccountToQueue(account: InternalAccount): Promise<void> {\n await this.#mutex.runExclusive(async () => {\n this.update((state) => {\n enqueueAccounts(state, [account]);\n });\n });\n }\n\n /**\n * Remove the given account from the sync queue.\n *\n * @param account - The account address to remove.\n */\n async #removeAccountFromQueue(account: string): Promise<void> {\n await this.#mutex.runExclusive(async () => {\n this.update((state) => {\n for (const [entropySourceId, groupedAddresses] of Object.entries(\n state.syncQueue,\n )) {\n const index = groupedAddresses.findIndex(\n ({ address }) => address === account,\n );\n if (index === -1) {\n continue;\n }\n groupedAddresses.splice(index, 1);\n if (groupedAddresses.length === 0) {\n delete state.syncQueue[entropySourceId];\n }\n break;\n }\n });\n });\n }\n}\n\n/**\n * Retrieves the entropy source ID from the given account, if it exists.\n *\n * @param account - The account from which to retrieve the entropy source ID.\n * @returns The entropy source ID, or null if it does not exist.\n */\nfunction getAccountEntropySourceId(account: InternalAccount): string | null {\n if (account.options.entropy?.type === 'mnemonic') {\n return account.options.entropy.id;\n }\n return null;\n}\n\n/**\n * Derive the account source to report for the given account, from its\n * entropy source and keyring type.\n *\n * @param account - The account to classify.\n * @returns The account source, or undefined for unrecognized keyring types\n * (the auth API rejects unknown values, so those are left untagged).\n */\nfunction getAccountSource(account: InternalAccount): AccountSource | undefined {\n if (getAccountEntropySourceId(account) !== null) {\n return 'mnemonic';\n }\n switch (account.metadata.keyring.type) {\n case KeyringTypes.simple:\n return 'imported';\n case KeyringTypes.snap:\n return 'snap';\n case KeyringTypes.qr:\n case KeyringTypes.trezor:\n case KeyringTypes.oneKey:\n case KeyringTypes.ledger:\n case KeyringTypes.lattice:\n return 'hardware';\n default:\n return undefined;\n }\n}\n\n/**\n * Retrieves the canonical address of the given account, as expected by the\n * auth API (see {@link canonicalizeAddress}).\n *\n * @param account - The account whose address to canonicalize.\n * @returns The canonical address, or undefined when the account's namespace\n * has no canonical form (in which case it cannot produce a proof of\n * ownership either).\n */\nfunction getCanonicalAddress(account: InternalAccount): string | undefined {\n try {\n const [scope] = account.scopes;\n if (!scope) {\n throw new Error(`Scope not found for account ${account.id}`);\n }\n return canonicalizeAddress(\n account.address,\n parseCaipChainId(scope).namespace,\n );\n } catch (error) {\n // Unsupported namespaces are an expected pass-through; anything\n // else is logged so a new namespace doesn't go unnoticed.\n if (!(error instanceof ProofUnsupportedNamespaceError)) {\n console.error(\n `Failed to canonicalize address for account ${account.id}:`,\n error,\n );\n }\n return undefined;\n }\n}\n\n/**\n * Convert an internal account to the payload stored in the sync queue and\n * submitted to the ProfileMetricsService.\n *\n * @param account - The internal account.\n * @returns The queued account, with a canonical address and, when known, an\n * account source.\n */\nfunction toQueuedAccount(account: InternalAccount): AccountWithScopes {\n const accountSource = getAccountSource(account);\n return {\n address: getCanonicalAddress(account) ?? account.address,\n scopes: account.scopes,\n ...(accountSource ? { accountSource } : {}),\n };\n}\n\n/**\n * Push the given accounts onto the sync queue held in `state`, skipping any\n * whose canonical address has already been reported or is already queued.\n *\n * Duplicates must be caught here: two entries for one address would share a\n * single queue key, hence a single batch, and `#attachProofs` would sign the\n * same single-use nonce twice. The known addresses are collected into a set\n * once so that enqueuing `n` accounts stays linear.\n *\n * @param state - The controller state to mutate.\n * @param accounts - The accounts to enqueue.\n */\nfunction enqueueAccounts(\n state: ProfileMetricsControllerState,\n accounts: InternalAccount[],\n): void {\n const knownAddresses = new Set([\n ...state.reportedAccounts,\n ...Object.values(state.syncQueue).flatMap((batch) =>\n batch.map(({ address }) => address),\n ),\n ]);\n for (const account of accounts) {\n const queuedAccount = toQueuedAccount(account);\n if (knownAddresses.has(queuedAccount.address)) {\n continue;\n }\n knownAddresses.add(queuedAccount.address);\n const queueKey =\n getAccountEntropySourceId(account) ?? NON_MNEMONIC_QUEUE_KEY;\n (state.syncQueue[queueKey] ??= []).push(queuedAccount);\n }\n}\n"]}
|
|
@@ -192,11 +192,6 @@ export declare class ProfileMetricsService {
|
|
|
192
192
|
* @throws {RangeError} if no identifiers are provided.
|
|
193
193
|
*/
|
|
194
194
|
fetchNonces(data: ProfileMetricsFetchNoncesRequest): Promise<Record<string, string>>;
|
|
195
|
-
/**
|
|
196
|
-
* Close the circuit breakers of the nonce and metrics policies, so requests
|
|
197
|
-
* are attempted again right away instead of after the circuit break duration.
|
|
198
|
-
*/
|
|
199
|
-
resetCircuitBreakers(): void;
|
|
200
195
|
/**
|
|
201
196
|
* Submit metrics to the API.
|
|
202
197
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProfileMetricsService.d.ts","sourceRoot":"","sources":["../src/ProfileMetricsService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,0BAA0B,EAC1B,aAAa,EACd,MAAM,4BAA4B,CAAC;
|
|
1
|
+
{"version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AC,CAAC,CAAC,GACnD,WAAW,CASb;IAED;;;;;;;;;;;;;;;;;;;;OAoBG;IACG,WAAW,CACf,IAAI,EAAE,gCAAgC,GACrC,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAgBjC;IA2DD;;;;;OAKG;IACG,aAAa,CAAC,IAAI,EAAE,kCAAkC,GAAG,OAAO,CAAC,IAAI,CAAC,CAmC3E;CACF;AAED;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,GAAG,MAAM,CAE/C"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createServicePolicy,
|
|
1
|
+
import { createServicePolicy, HttpError } from '@metamask/controller-utils';
|
|
2
2
|
import { SDK } from '@metamask/profile-sync-controller';
|
|
3
3
|
import { array, number, string, type as structType, } from '@metamask/superstruct';
|
|
4
4
|
/**
|
|
@@ -29,13 +29,6 @@ export const serviceName = 'ProfileMetricsService';
|
|
|
29
29
|
export const MAX_NONCE_BATCH_SIZE = 50;
|
|
30
30
|
// === MESSENGER ===
|
|
31
31
|
const MESSENGER_EXPOSED_METHODS = ['submitMetrics', 'fetchNonces'];
|
|
32
|
-
/**
|
|
33
|
-
* A 4xx response will not change on an immediate retry, so retrying it only
|
|
34
|
-
* adds load on the API. Network errors and 5xx responses stay retryable.
|
|
35
|
-
*/
|
|
36
|
-
const DO_NOT_RETRY_CLIENT_ERRORS = handleWhen((error) => !(error instanceof HttpError &&
|
|
37
|
-
error.httpStatus >= 400 &&
|
|
38
|
-
error.httpStatus < 500));
|
|
39
32
|
// === SERVICE DEFINITION ===
|
|
40
33
|
/**
|
|
41
34
|
* A service for submitting user profile metrics (metrics ID and accounts).
|
|
@@ -92,16 +85,12 @@ export class ProfileMetricsService {
|
|
|
92
85
|
this.name = serviceName;
|
|
93
86
|
this.#messenger = messenger;
|
|
94
87
|
this.#fetch = fetchFunction;
|
|
95
|
-
this.#fetchNoncesPolicy = createServicePolicy(
|
|
96
|
-
retryFilterPolicy: DO_NOT_RETRY_CLIENT_ERRORS,
|
|
97
|
-
...policyOptions,
|
|
98
|
-
});
|
|
88
|
+
this.#fetchNoncesPolicy = createServicePolicy(policyOptions);
|
|
99
89
|
// Keep the circuit breaker scaled to the retry count the same way
|
|
100
90
|
// `createServicePolicy` derives `DEFAULT_MAX_CONSECUTIVE_FAILURES`:
|
|
101
91
|
// `(1 + maxRetries) * 3` failed attempts ≈ 3 failed `execute()` calls.
|
|
102
92
|
const submitMaxRetries = policyOptions.maxRetries ?? 0;
|
|
103
93
|
this.#submitMetricsPolicy = createServicePolicy({
|
|
104
|
-
retryFilterPolicy: DO_NOT_RETRY_CLIENT_ERRORS,
|
|
105
94
|
...policyOptions,
|
|
106
95
|
maxRetries: submitMaxRetries,
|
|
107
96
|
maxConsecutiveFailures: policyOptions.maxConsecutiveFailures ?? (1 + submitMaxRetries) * 3,
|
|
@@ -249,14 +238,6 @@ export class ProfileMetricsService {
|
|
|
249
238
|
return result;
|
|
250
239
|
});
|
|
251
240
|
}
|
|
252
|
-
/**
|
|
253
|
-
* Close the circuit breakers of the nonce and metrics policies, so requests
|
|
254
|
-
* are attempted again right away instead of after the circuit break duration.
|
|
255
|
-
*/
|
|
256
|
-
resetCircuitBreakers() {
|
|
257
|
-
this.#fetchNoncesPolicy.reset();
|
|
258
|
-
this.#submitMetricsPolicy.reset();
|
|
259
|
-
}
|
|
260
241
|
/**
|
|
261
242
|
* Submit metrics to the API.
|
|
262
243
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProfileMetricsService.js","sourceRoot":"","sources":["../src/ProfileMetricsService.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,mBAAmB,EACnB,UAAU,EACV,SAAS,GACV,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAE,GAAG,EAAE,MAAM,mCAAmC,CAAC;AAExD,OAAO,EACL,KAAK,EACL,MAAM,EACN,MAAM,EACN,IAAI,IAAI,U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BACjE,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,aAAa,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;qBAC5D,CAAC,CAAC;iBACJ,CAAC;gBACF,8CAA8C;gBAC9C,sCAAsC;gBACtC,iDAAiD;gBACjD,qDAAqD;gBACrD,WAAW,EAAE,MAAM;aACpB,CAAC,CAAC;YACH,IAAI,CAAC,aAAa,CAAC,EAAE,EAAE,CAAC;gBACtB,MAAM,IAAI,SAAS,CACjB,aAAa,CAAC,MAAM,EACpB,aAAa,GAAG,CAAC,QAAQ,EAAE,yBAAyB,aAAa,CAAC,MAAM,GAAG,CAC5E,CAAC;YACJ,CAAC;YACD,OAAO,aAAa,CAAC;QACvB,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAED;;;;;GAKG;AACH,MAAM,UAAU,UAAU,CAAC,GAAY;IACrC,OAAO,GAAG,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,UAAU,SAAS,CAAC;AACpD,CAAC","sourcesContent":["import type {\n CreateServicePolicyOptions,\n ServicePolicy,\n} from '@metamask/controller-utils';\nimport {\n createServicePolicy,\n handleWhen,\n HttpError,\n} from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport { SDK } from '@metamask/profile-sync-controller';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\nimport {\n array,\n number,\n string,\n type as structType,\n} from '@metamask/superstruct';\nimport type { IDisposable } from 'cockatiel';\n\nimport type { ProfileMetricsServiceMethodActions } from './ProfileMetricsService-method-action-types.js';\n\n/**\n * The shape of an entry in the `POST /api/v2/nonce/batch` response body.\n *\n * `identifier` echoes the request identifier verbatim, mirroring the\n * documented behavior of the single-account `GET /api/v2/nonce` endpoint on\n * the same auth service. Defined with `type()` (not `object()`) so the\n * client tolerates additive server-side schema changes.\n */\nconst NonceBatchResponseStruct = array(\n structType({\n expires_in: number(),\n identifier: string(),\n nonce: string(),\n }),\n);\n\n// === GENERAL ===\n\n/**\n * The name of the {@link ProfileMetricsService}, used to namespace the\n * service's actions and events.\n */\nexport const serviceName = 'ProfileMetricsService';\n\n/**\n * A cryptographic proof that the caller controls the private key of an\n * account, as defined by the `PUT /api/v2/profile/accounts` endpoint of the\n * auth API. When present, the server verifies the signature against\n * `metamask:proof-of-ownership:<nonce>:<canonical address>` and permanently\n * marks the account as `verified: true`.\n */\nexport type AccountOwnershipProof = {\n /**\n * Single-use nonce obtained from {@link ProfileMetricsService.fetchNonces}.\n * Consumed by the server on verification; replay is not possible.\n */\n nonce: string;\n /**\n * Chain-native signature of `metamask:proof-of-ownership:<nonce>:<address>`,\n * always 0x-prefixed. The exact format varies by chain (see the auth API\n * spec — EIP-191 for `eip155`, ed25519 for `solana`, TIP-191 for `tron`,\n * BIP-322 for `bip122`).\n */\n signature: string;\n};\n\n/**\n * The kind of keyring that controls an account, as accepted by the auth API.\n * Any other value is rejected by the API, so unrecognized keyrings must be\n * left untagged rather than passed through.\n */\nexport type AccountSource = 'mnemonic' | 'hardware' | 'imported' | 'snap';\n\n/**\n * An account address along with its associated scopes, an optional account\n * source, and an optional ownership proof.\n */\nexport type AccountWithScopes = {\n address: string;\n scopes: `${string}:${string}`[];\n accountSource?: AccountSource;\n proof?: AccountOwnershipProof;\n};\n\n/**\n * The shape of the request object for submitting metrics.\n */\nexport type ProfileMetricsSubmitMetricsRequest = {\n metametricsId: string;\n entropySourceId?: string | null;\n accounts: AccountWithScopes[];\n};\n\n/**\n * The shape of the request object for fetching a batch of single-use nonces.\n */\nexport type ProfileMetricsFetchNoncesRequest = {\n /**\n * The identifiers (canonical addresses) to mint a nonce for. The auth API\n * accepts between 1 and {@link MAX_NONCE_BATCH_SIZE} identifiers per call.\n */\n identifiers: string[];\n /**\n * The entropy source ID to use when fetching a bearer token. Pass `null` or\n * omit for accounts that do not belong to any entropy source.\n */\n entropySourceId?: string | null;\n};\n\n/**\n * Maximum number of identifiers the auth API will mint nonces for in a single\n * `POST /api/v2/nonce/batch` request. {@link ProfileMetricsService.fetchNonces}\n * uses this as the chunk size when the caller requests more than this many\n * nonces at once.\n */\nexport const MAX_NONCE_BATCH_SIZE = 50;\n\n// === MESSENGER ===\n\nconst MESSENGER_EXPOSED_METHODS = ['submitMetrics', 'fetchNonces'] as const;\n\n/**\n * A 4xx response will not change on an immediate retry, so retrying it only\n * adds load on the API. Network errors and 5xx responses stay retryable.\n */\nconst DO_NOT_RETRY_CLIENT_ERRORS = handleWhen(\n (error) =>\n !(\n error instanceof HttpError &&\n error.httpStatus >= 400 &&\n error.httpStatus < 500\n ),\n);\n\n/**\n * Actions that {@link ProfileMetricsService} exposes to other consumers.\n */\nexport type ProfileMetricsServiceActions = ProfileMetricsServiceMethodActions;\n\n/**\n * Actions from other messengers that {@link ProfileMetricsService} calls.\n */\ntype AllowedActions =\n AuthenticationController.AuthenticationControllerGetBearerTokenAction;\n\n/**\n * Events that {@link ProfileMetricsService} exposes to other consumers.\n */\nexport type ProfileMetricsServiceEvents = never;\n\n/**\n * Events from other messengers that {@link ProfileMetricsService} subscribes\n * to.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger which is restricted to actions and events accessed by\n * {@link ProfileMetricsService}.\n */\nexport type ProfileMetricsServiceMessenger = Messenger<\n typeof serviceName,\n ProfileMetricsServiceActions | AllowedActions,\n ProfileMetricsServiceEvents | AllowedEvents\n>;\n\n// === SERVICE DEFINITION ===\n\n/**\n * A service for submitting user profile metrics (metrics ID and accounts).\n */\nexport class ProfileMetricsService {\n /**\n * The name of the service.\n */\n readonly name: typeof serviceName;\n\n /**\n * The messenger suited for this service.\n */\n readonly #messenger: ConstructorParameters<\n typeof ProfileMetricsService\n >[0]['messenger'];\n\n /**\n * A function that can be used to make an HTTP request.\n */\n readonly #fetch: ConstructorParameters<\n typeof ProfileMetricsService\n >[0]['fetch'];\n\n /**\n * Policy for `fetchNonces`. Minting new nonces is safe to retry.\n *\n * @see {@link createServicePolicy}\n */\n readonly #fetchNoncesPolicy: ServicePolicy;\n\n /**\n * Policy for `submitMetrics`. Proof payloads embed single-use nonces, so\n * in-request retries are disabled by default.\n *\n * @see {@link createServicePolicy}\n */\n readonly #submitMetricsPolicy: ServicePolicy;\n\n /**\n * The API base URL environment.\n */\n readonly #baseURL: string;\n\n /**\n * Constructs a new ProfileMetricsService object.\n *\n * @param args - The constructor arguments.\n * @param args.messenger - The messenger suited for this service.\n * @param args.fetch - A function that can be used to make an HTTP request. If\n * your JavaScript environment supports `fetch` natively, you'll probably want\n * to pass that; otherwise you can pass an equivalent (such as `fetch` via\n * `node-fetch`).\n * @param args.policyOptions - Options to pass to `createServicePolicy`, which\n * is used to wrap each request. See {@link CreateServicePolicyOptions}.\n * `submitMetrics` defaults to `maxRetries: 0` (proof nonces are single-use;\n * the controller poll re-fetches nonces and retries failed submits).\n * `fetchNonces` keeps the normal retry defaults — a failed nonce fetch\n * soft-degrades to a proof-less submit that clears the queue, so retries\n * here are what preserve proofs across transient errors.\n * @param args.env - The environment to determine the correct API endpoints.\n */\n constructor({\n messenger,\n fetch: fetchFunction,\n policyOptions = {},\n env = SDK.Env.DEV,\n }: {\n messenger: ProfileMetricsServiceMessenger;\n fetch: typeof fetch;\n policyOptions?: CreateServicePolicyOptions;\n env?: SDK.Env;\n }) {\n this.name = serviceName;\n this.#messenger = messenger;\n this.#fetch = fetchFunction;\n this.#fetchNoncesPolicy = createServicePolicy({\n retryFilterPolicy: DO_NOT_RETRY_CLIENT_ERRORS,\n ...policyOptions,\n });\n // Keep the circuit breaker scaled to the retry count the same way\n // `createServicePolicy` derives `DEFAULT_MAX_CONSECUTIVE_FAILURES`:\n // `(1 + maxRetries) * 3` failed attempts ≈ 3 failed `execute()` calls.\n const submitMaxRetries = policyOptions.maxRetries ?? 0;\n this.#submitMetricsPolicy = createServicePolicy({\n retryFilterPolicy: DO_NOT_RETRY_CLIENT_ERRORS,\n ...policyOptions,\n maxRetries: submitMaxRetries,\n maxConsecutiveFailures:\n policyOptions.maxConsecutiveFailures ?? (1 + submitMaxRetries) * 3,\n });\n this.#baseURL = getAuthUrl(env);\n\n this.#messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Registers a handler that will be called after a request returns a non-500\n * response, causing a retry. Primarily useful in tests where timers are being\n * mocked.\n *\n * @param listener - The handler to be called.\n * @returns An object that can be used to unregister the handler. See\n * {@link CockatielEvent}.\n * @see {@link createServicePolicy}\n */\n onRetry(listener: Parameters<ServicePolicy['onRetry']>[0]): IDisposable {\n const fetchDisposable = this.#fetchNoncesPolicy.onRetry(listener);\n const submitDisposable = this.#submitMetricsPolicy.onRetry(listener);\n return {\n dispose: (): void => {\n fetchDisposable.dispose();\n submitDisposable.dispose();\n },\n };\n }\n\n /**\n * Registers a handler that will be called after a set number of retry rounds\n * prove that requests to the API endpoint consistently return a 5xx response.\n *\n * @param listener - The handler to be called.\n * @returns An object that can be used to unregister the handler. See\n * {@link CockatielEvent}.\n * @see {@link createServicePolicy}\n */\n onBreak(listener: Parameters<ServicePolicy['onBreak']>[0]): IDisposable {\n const fetchDisposable = this.#fetchNoncesPolicy.onBreak(listener);\n const submitDisposable = this.#submitMetricsPolicy.onBreak(listener);\n return {\n dispose: (): void => {\n fetchDisposable.dispose();\n submitDisposable.dispose();\n },\n };\n }\n\n /**\n * Registers a handler that will be called under one of two circumstances:\n *\n * 1. After a set number of retries prove that requests to the API\n * consistently result in one of the following failures:\n * 1. A connection initiation error\n * 2. A connection reset error\n * 3. A timeout error\n * 4. A non-JSON response\n * 5. A 502, 503, or 504 response\n * 2. After a successful request is made to the API, but the response takes\n * longer than a set duration to return.\n *\n * @param listener - The handler to be called.\n * @returns An object that can be used to unregister the handler. See\n * {@link CockatielEvent}.\n */\n onDegraded(\n listener: Parameters<ServicePolicy['onDegraded']>[0],\n ): IDisposable {\n const fetchDisposable = this.#fetchNoncesPolicy.onDegraded(listener);\n const submitDisposable = this.#submitMetricsPolicy.onDegraded(listener);\n return {\n dispose: (): void => {\n fetchDisposable.dispose();\n submitDisposable.dispose();\n },\n };\n }\n\n /**\n * Fetch single-use nonces from the auth API, one per identifier.\n *\n * Requests larger than {@link MAX_NONCE_BATCH_SIZE} are split into multiple\n * `POST /api/v2/nonce/batch` calls fired in parallel; the resulting maps are\n * merged into a single record. Each chunk independently goes through the\n * service policy (retry, circuit-breaker, degraded). If any chunk ultimately\n * fails, the whole call rejects so the caller can soft-degrade the entire\n * entropy-source batch consistently.\n *\n * The returned record is keyed by the auth API's echoed `identifier` field\n * (`response[i].identifier -> response[i].nonce`). The call asserts that\n * the response identifier set is exactly the requested set; any mismatch\n * (missing, extra, or duplicated identifier) causes the chunk to throw so\n * the caller never silently proceeds with partial nonces.\n *\n * @param data - The identifiers to mint nonces for, plus the optional\n * entropy source ID used to scope the bearer token.\n * @returns A map of identifier -> nonce.\n * @throws {RangeError} if no identifiers are provided.\n */\n async fetchNonces(\n data: ProfileMetricsFetchNoncesRequest,\n ): Promise<Record<string, string>> {\n if (data.identifiers.length === 0) {\n throw new RangeError(\n 'ProfileMetricsService.fetchNonces requires at least 1 identifier.',\n );\n }\n const chunks: string[][] = [];\n for (let i = 0; i < data.identifiers.length; i += MAX_NONCE_BATCH_SIZE) {\n chunks.push(data.identifiers.slice(i, i + MAX_NONCE_BATCH_SIZE));\n }\n const chunkResults = await Promise.all(\n chunks.map((identifiers) =>\n this.#fetchNoncesChunk(identifiers, data.entropySourceId),\n ),\n );\n return Object.assign({}, ...chunkResults);\n }\n\n /**\n * Mint nonces for a single ≤ {@link MAX_NONCE_BATCH_SIZE}-sized chunk of\n * identifiers. Wrapped in {@link #fetchNoncesPolicy} for retry / degraded /\n * circuit semantics.\n *\n * @param identifiers - The identifiers in this chunk. Must be 1..MAX_NONCE_BATCH_SIZE.\n * @param entropySourceId - The entropy source ID forwarded to the bearer\n * token resolver.\n * @returns A map of identifier -> nonce for this chunk.\n */\n async #fetchNoncesChunk(\n identifiers: string[],\n entropySourceId: string | null | undefined,\n ): Promise<Record<string, string>> {\n return await this.#fetchNoncesPolicy.execute(async () => {\n const authToken = await this.#messenger.call(\n 'AuthenticationController:getBearerToken',\n entropySourceId ?? undefined,\n );\n const url = new URL(`${this.#baseURL}/nonce/batch`);\n const localResponse = await this.#fetch(url, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${authToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ identifiers }),\n credentials: 'omit',\n });\n if (!localResponse.ok) {\n throw new HttpError(\n localResponse.status,\n `Fetching '${url.toString()}' failed with status '${localResponse.status}'`,\n );\n }\n const body: unknown = await localResponse.json();\n if (!NonceBatchResponseStruct.is(body)) {\n throw new Error(`Malformed response received from '${url.toString()}'`);\n }\n const result: Record<string, string> = {};\n for (const entry of body) {\n result[entry.identifier] = entry.nonce;\n }\n const echoesRequest =\n body.length === identifiers.length &&\n identifiers.every((id) =>\n Object.prototype.hasOwnProperty.call(result, id),\n );\n if (!echoesRequest) {\n throw new Error(\n `Fetching '${url.toString()}' returned a response whose identifier set does not match the request`,\n );\n }\n return result;\n });\n }\n\n /**\n * Close the circuit breakers of the nonce and metrics policies, so requests\n * are attempted again right away instead of after the circuit break duration.\n */\n resetCircuitBreakers(): void {\n this.#fetchNoncesPolicy.reset();\n this.#submitMetricsPolicy.reset();\n }\n\n /**\n * Submit metrics to the API.\n *\n * @param data - The data to send in the metrics update request.\n * @returns The response from the API.\n */\n async submitMetrics(data: ProfileMetricsSubmitMetricsRequest): Promise<void> {\n await this.#submitMetricsPolicy.execute(async () => {\n const authToken = await this.#messenger.call(\n 'AuthenticationController:getBearerToken',\n data.entropySourceId ?? undefined,\n );\n const url = new URL(`${this.#baseURL}/profile/accounts`);\n const localResponse = await this.#fetch(url, {\n method: 'PUT',\n headers: {\n Authorization: `Bearer ${authToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n metametrics_id: data.metametricsId,\n accounts: data.accounts.map(({ accountSource, ...account }) => ({\n ...account,\n // Omitted rather than sent empty when unknown, per the API spec.\n ...(accountSource ? { account_source: accountSource } : {}),\n })),\n }),\n // The auth API is stateless (no cookies used)\n // prevent marketing cookies scoped to\n // .metamask.io from being forwarded to api which\n // causes 431 Request Header Fields Too Large errors.\n credentials: 'omit',\n });\n if (!localResponse.ok) {\n throw new HttpError(\n localResponse.status,\n `Fetching '${url.toString()}' failed with status '${localResponse.status}'`,\n );\n }\n return localResponse;\n });\n }\n}\n\n/**\n * Returns the base URL for the given environment.\n *\n * @param env - The environment to get the URL for.\n * @returns The base URL for the environment.\n */\nexport function getAuthUrl(env: SDK.Env): string {\n return `${SDK.getEnvUrls(env).authApiUrl}/api/v2`;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ProfileMetricsService.js","sourceRoot":"","sources":["../src/ProfileMetricsService.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,mBAAmB,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAC;AAE5E,OAAO,EAAE,GAAG,EAAE,MAAM,mCAAmC,CAAC;AAExD,OAAO,EACL,KAAK,EACL,MAAM,EACN,MAAM,EACN,IAAI,IAAI,UAAU,GACnB,MAAM,uBAAuB,CAAC;AAK/B;;;;;;;GAOG;AACH,MAAM,wBAAwB,GAAG,KAAK,CACpC,UAAU,CAAC;IACT,UAAU,EAAE,MAAM,EAAE;IACpB,UAAU,EAAE,MAAM,EAAE;IACpB,KAAK,EAAE,MAAM,EAAE;CAChB,CAAC,CACH,CAAC;AAEF,kBAAkB;AAElB;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,uBAAuB,CAAC;AAmEnD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAEvC,oBAAoB;AAEpB,MAAM,yBAAyB,GAAG,CAAC,eAAe,EAAE,aAAa,CAAU,CAAC;AAkC5E,6BAA6B;AAE7B;;GAEG;AACH,MAAM,OAAO,qBAAqB;IAChC;;OAEG;IACM,IAAI,CAAqB;IAElC;;OAEG;IACM,UAAU,CAED;IAElB;;OAEG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BACnC;gBACD,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC;oBACnB,cAAc,EAAE,IAAI,CAAC,aAAa;oBAClC,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,aAAa,EAAE,GAAG,OAAO,EAAE,EAAE,EAAE,CAAC,CAAC;wBAC9D,GAAG,OAAO;wBACV,iEAAiE;wBACjE,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,aAAa,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;qBAC5D,CAAC,CAAC;iBACJ,CAAC;gBACF,8CAA8C;gBAC9C,sCAAsC;gBACtC,iDAAiD;gBACjD,qDAAqD;gBACrD,WAAW,EAAE,MAAM;aACpB,CAAC,CAAC;YACH,IAAI,CAAC,aAAa,CAAC,EAAE,EAAE,CAAC;gBACtB,MAAM,IAAI,SAAS,CACjB,aAAa,CAAC,MAAM,EACpB,aAAa,GAAG,CAAC,QAAQ,EAAE,yBAAyB,aAAa,CAAC,MAAM,GAAG,CAC5E,CAAC;YACJ,CAAC;YACD,OAAO,aAAa,CAAC;QACvB,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAED;;;;;GAKG;AACH,MAAM,UAAU,UAAU,CAAC,GAAY;IACrC,OAAO,GAAG,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,UAAU,SAAS,CAAC;AACpD,CAAC","sourcesContent":["import type {\n CreateServicePolicyOptions,\n ServicePolicy,\n} from '@metamask/controller-utils';\nimport { createServicePolicy, HttpError } from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport { SDK } from '@metamask/profile-sync-controller';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\nimport {\n array,\n number,\n string,\n type as structType,\n} from '@metamask/superstruct';\nimport type { IDisposable } from 'cockatiel';\n\nimport type { ProfileMetricsServiceMethodActions } from './ProfileMetricsService-method-action-types.js';\n\n/**\n * The shape of an entry in the `POST /api/v2/nonce/batch` response body.\n *\n * `identifier` echoes the request identifier verbatim, mirroring the\n * documented behavior of the single-account `GET /api/v2/nonce` endpoint on\n * the same auth service. Defined with `type()` (not `object()`) so the\n * client tolerates additive server-side schema changes.\n */\nconst NonceBatchResponseStruct = array(\n structType({\n expires_in: number(),\n identifier: string(),\n nonce: string(),\n }),\n);\n\n// === GENERAL ===\n\n/**\n * The name of the {@link ProfileMetricsService}, used to namespace the\n * service's actions and events.\n */\nexport const serviceName = 'ProfileMetricsService';\n\n/**\n * A cryptographic proof that the caller controls the private key of an\n * account, as defined by the `PUT /api/v2/profile/accounts` endpoint of the\n * auth API. When present, the server verifies the signature against\n * `metamask:proof-of-ownership:<nonce>:<canonical address>` and permanently\n * marks the account as `verified: true`.\n */\nexport type AccountOwnershipProof = {\n /**\n * Single-use nonce obtained from {@link ProfileMetricsService.fetchNonces}.\n * Consumed by the server on verification; replay is not possible.\n */\n nonce: string;\n /**\n * Chain-native signature of `metamask:proof-of-ownership:<nonce>:<address>`,\n * always 0x-prefixed. The exact format varies by chain (see the auth API\n * spec — EIP-191 for `eip155`, ed25519 for `solana`, TIP-191 for `tron`,\n * BIP-322 for `bip122`).\n */\n signature: string;\n};\n\n/**\n * The kind of keyring that controls an account, as accepted by the auth API.\n * Any other value is rejected by the API, so unrecognized keyrings must be\n * left untagged rather than passed through.\n */\nexport type AccountSource = 'mnemonic' | 'hardware' | 'imported' | 'snap';\n\n/**\n * An account address along with its associated scopes, an optional account\n * source, and an optional ownership proof.\n */\nexport type AccountWithScopes = {\n address: string;\n scopes: `${string}:${string}`[];\n accountSource?: AccountSource;\n proof?: AccountOwnershipProof;\n};\n\n/**\n * The shape of the request object for submitting metrics.\n */\nexport type ProfileMetricsSubmitMetricsRequest = {\n metametricsId: string;\n entropySourceId?: string | null;\n accounts: AccountWithScopes[];\n};\n\n/**\n * The shape of the request object for fetching a batch of single-use nonces.\n */\nexport type ProfileMetricsFetchNoncesRequest = {\n /**\n * The identifiers (canonical addresses) to mint a nonce for. The auth API\n * accepts between 1 and {@link MAX_NONCE_BATCH_SIZE} identifiers per call.\n */\n identifiers: string[];\n /**\n * The entropy source ID to use when fetching a bearer token. Pass `null` or\n * omit for accounts that do not belong to any entropy source.\n */\n entropySourceId?: string | null;\n};\n\n/**\n * Maximum number of identifiers the auth API will mint nonces for in a single\n * `POST /api/v2/nonce/batch` request. {@link ProfileMetricsService.fetchNonces}\n * uses this as the chunk size when the caller requests more than this many\n * nonces at once.\n */\nexport const MAX_NONCE_BATCH_SIZE = 50;\n\n// === MESSENGER ===\n\nconst MESSENGER_EXPOSED_METHODS = ['submitMetrics', 'fetchNonces'] as const;\n\n/**\n * Actions that {@link ProfileMetricsService} exposes to other consumers.\n */\nexport type ProfileMetricsServiceActions = ProfileMetricsServiceMethodActions;\n\n/**\n * Actions from other messengers that {@link ProfileMetricsService} calls.\n */\ntype AllowedActions =\n AuthenticationController.AuthenticationControllerGetBearerTokenAction;\n\n/**\n * Events that {@link ProfileMetricsService} exposes to other consumers.\n */\nexport type ProfileMetricsServiceEvents = never;\n\n/**\n * Events from other messengers that {@link ProfileMetricsService} subscribes\n * to.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger which is restricted to actions and events accessed by\n * {@link ProfileMetricsService}.\n */\nexport type ProfileMetricsServiceMessenger = Messenger<\n typeof serviceName,\n ProfileMetricsServiceActions | AllowedActions,\n ProfileMetricsServiceEvents | AllowedEvents\n>;\n\n// === SERVICE DEFINITION ===\n\n/**\n * A service for submitting user profile metrics (metrics ID and accounts).\n */\nexport class ProfileMetricsService {\n /**\n * The name of the service.\n */\n readonly name: typeof serviceName;\n\n /**\n * The messenger suited for this service.\n */\n readonly #messenger: ConstructorParameters<\n typeof ProfileMetricsService\n >[0]['messenger'];\n\n /**\n * A function that can be used to make an HTTP request.\n */\n readonly #fetch: ConstructorParameters<\n typeof ProfileMetricsService\n >[0]['fetch'];\n\n /**\n * Policy for `fetchNonces`. Minting new nonces is safe to retry.\n *\n * @see {@link createServicePolicy}\n */\n readonly #fetchNoncesPolicy: ServicePolicy;\n\n /**\n * Policy for `submitMetrics`. Proof payloads embed single-use nonces, so\n * in-request retries are disabled by default.\n *\n * @see {@link createServicePolicy}\n */\n readonly #submitMetricsPolicy: ServicePolicy;\n\n /**\n * The API base URL environment.\n */\n readonly #baseURL: string;\n\n /**\n * Constructs a new ProfileMetricsService object.\n *\n * @param args - The constructor arguments.\n * @param args.messenger - The messenger suited for this service.\n * @param args.fetch - A function that can be used to make an HTTP request. If\n * your JavaScript environment supports `fetch` natively, you'll probably want\n * to pass that; otherwise you can pass an equivalent (such as `fetch` via\n * `node-fetch`).\n * @param args.policyOptions - Options to pass to `createServicePolicy`, which\n * is used to wrap each request. See {@link CreateServicePolicyOptions}.\n * `submitMetrics` defaults to `maxRetries: 0` (proof nonces are single-use;\n * the controller poll re-fetches nonces and retries failed submits).\n * `fetchNonces` keeps the normal retry defaults — a failed nonce fetch\n * soft-degrades to a proof-less submit that clears the queue, so retries\n * here are what preserve proofs across transient errors.\n * @param args.env - The environment to determine the correct API endpoints.\n */\n constructor({\n messenger,\n fetch: fetchFunction,\n policyOptions = {},\n env = SDK.Env.DEV,\n }: {\n messenger: ProfileMetricsServiceMessenger;\n fetch: typeof fetch;\n policyOptions?: CreateServicePolicyOptions;\n env?: SDK.Env;\n }) {\n this.name = serviceName;\n this.#messenger = messenger;\n this.#fetch = fetchFunction;\n this.#fetchNoncesPolicy = createServicePolicy(policyOptions);\n // Keep the circuit breaker scaled to the retry count the same way\n // `createServicePolicy` derives `DEFAULT_MAX_CONSECUTIVE_FAILURES`:\n // `(1 + maxRetries) * 3` failed attempts ≈ 3 failed `execute()` calls.\n const submitMaxRetries = policyOptions.maxRetries ?? 0;\n this.#submitMetricsPolicy = createServicePolicy({\n ...policyOptions,\n maxRetries: submitMaxRetries,\n maxConsecutiveFailures:\n policyOptions.maxConsecutiveFailures ?? (1 + submitMaxRetries) * 3,\n });\n this.#baseURL = getAuthUrl(env);\n\n this.#messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Registers a handler that will be called after a request returns a non-500\n * response, causing a retry. Primarily useful in tests where timers are being\n * mocked.\n *\n * @param listener - The handler to be called.\n * @returns An object that can be used to unregister the handler. See\n * {@link CockatielEvent}.\n * @see {@link createServicePolicy}\n */\n onRetry(listener: Parameters<ServicePolicy['onRetry']>[0]): IDisposable {\n const fetchDisposable = this.#fetchNoncesPolicy.onRetry(listener);\n const submitDisposable = this.#submitMetricsPolicy.onRetry(listener);\n return {\n dispose: (): void => {\n fetchDisposable.dispose();\n submitDisposable.dispose();\n },\n };\n }\n\n /**\n * Registers a handler that will be called after a set number of retry rounds\n * prove that requests to the API endpoint consistently return a 5xx response.\n *\n * @param listener - The handler to be called.\n * @returns An object that can be used to unregister the handler. See\n * {@link CockatielEvent}.\n * @see {@link createServicePolicy}\n */\n onBreak(listener: Parameters<ServicePolicy['onBreak']>[0]): IDisposable {\n const fetchDisposable = this.#fetchNoncesPolicy.onBreak(listener);\n const submitDisposable = this.#submitMetricsPolicy.onBreak(listener);\n return {\n dispose: (): void => {\n fetchDisposable.dispose();\n submitDisposable.dispose();\n },\n };\n }\n\n /**\n * Registers a handler that will be called under one of two circumstances:\n *\n * 1. After a set number of retries prove that requests to the API\n * consistently result in one of the following failures:\n * 1. A connection initiation error\n * 2. A connection reset error\n * 3. A timeout error\n * 4. A non-JSON response\n * 5. A 502, 503, or 504 response\n * 2. After a successful request is made to the API, but the response takes\n * longer than a set duration to return.\n *\n * @param listener - The handler to be called.\n * @returns An object that can be used to unregister the handler. See\n * {@link CockatielEvent}.\n */\n onDegraded(\n listener: Parameters<ServicePolicy['onDegraded']>[0],\n ): IDisposable {\n const fetchDisposable = this.#fetchNoncesPolicy.onDegraded(listener);\n const submitDisposable = this.#submitMetricsPolicy.onDegraded(listener);\n return {\n dispose: (): void => {\n fetchDisposable.dispose();\n submitDisposable.dispose();\n },\n };\n }\n\n /**\n * Fetch single-use nonces from the auth API, one per identifier.\n *\n * Requests larger than {@link MAX_NONCE_BATCH_SIZE} are split into multiple\n * `POST /api/v2/nonce/batch` calls fired in parallel; the resulting maps are\n * merged into a single record. Each chunk independently goes through the\n * service policy (retry, circuit-breaker, degraded). If any chunk ultimately\n * fails, the whole call rejects so the caller can soft-degrade the entire\n * entropy-source batch consistently.\n *\n * The returned record is keyed by the auth API's echoed `identifier` field\n * (`response[i].identifier -> response[i].nonce`). The call asserts that\n * the response identifier set is exactly the requested set; any mismatch\n * (missing, extra, or duplicated identifier) causes the chunk to throw so\n * the caller never silently proceeds with partial nonces.\n *\n * @param data - The identifiers to mint nonces for, plus the optional\n * entropy source ID used to scope the bearer token.\n * @returns A map of identifier -> nonce.\n * @throws {RangeError} if no identifiers are provided.\n */\n async fetchNonces(\n data: ProfileMetricsFetchNoncesRequest,\n ): Promise<Record<string, string>> {\n if (data.identifiers.length === 0) {\n throw new RangeError(\n 'ProfileMetricsService.fetchNonces requires at least 1 identifier.',\n );\n }\n const chunks: string[][] = [];\n for (let i = 0; i < data.identifiers.length; i += MAX_NONCE_BATCH_SIZE) {\n chunks.push(data.identifiers.slice(i, i + MAX_NONCE_BATCH_SIZE));\n }\n const chunkResults = await Promise.all(\n chunks.map((identifiers) =>\n this.#fetchNoncesChunk(identifiers, data.entropySourceId),\n ),\n );\n return Object.assign({}, ...chunkResults);\n }\n\n /**\n * Mint nonces for a single ≤ {@link MAX_NONCE_BATCH_SIZE}-sized chunk of\n * identifiers. Wrapped in {@link #fetchNoncesPolicy} for retry / degraded /\n * circuit semantics.\n *\n * @param identifiers - The identifiers in this chunk. Must be 1..MAX_NONCE_BATCH_SIZE.\n * @param entropySourceId - The entropy source ID forwarded to the bearer\n * token resolver.\n * @returns A map of identifier -> nonce for this chunk.\n */\n async #fetchNoncesChunk(\n identifiers: string[],\n entropySourceId: string | null | undefined,\n ): Promise<Record<string, string>> {\n return await this.#fetchNoncesPolicy.execute(async () => {\n const authToken = await this.#messenger.call(\n 'AuthenticationController:getBearerToken',\n entropySourceId ?? undefined,\n );\n const url = new URL(`${this.#baseURL}/nonce/batch`);\n const localResponse = await this.#fetch(url, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${authToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ identifiers }),\n credentials: 'omit',\n });\n if (!localResponse.ok) {\n throw new HttpError(\n localResponse.status,\n `Fetching '${url.toString()}' failed with status '${localResponse.status}'`,\n );\n }\n const body: unknown = await localResponse.json();\n if (!NonceBatchResponseStruct.is(body)) {\n throw new Error(`Malformed response received from '${url.toString()}'`);\n }\n const result: Record<string, string> = {};\n for (const entry of body) {\n result[entry.identifier] = entry.nonce;\n }\n const echoesRequest =\n body.length === identifiers.length &&\n identifiers.every((id) =>\n Object.prototype.hasOwnProperty.call(result, id),\n );\n if (!echoesRequest) {\n throw new Error(\n `Fetching '${url.toString()}' returned a response whose identifier set does not match the request`,\n );\n }\n return result;\n });\n }\n\n /**\n * Submit metrics to the API.\n *\n * @param data - The data to send in the metrics update request.\n * @returns The response from the API.\n */\n async submitMetrics(data: ProfileMetricsSubmitMetricsRequest): Promise<void> {\n await this.#submitMetricsPolicy.execute(async () => {\n const authToken = await this.#messenger.call(\n 'AuthenticationController:getBearerToken',\n data.entropySourceId ?? undefined,\n );\n const url = new URL(`${this.#baseURL}/profile/accounts`);\n const localResponse = await this.#fetch(url, {\n method: 'PUT',\n headers: {\n Authorization: `Bearer ${authToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n metametrics_id: data.metametricsId,\n accounts: data.accounts.map(({ accountSource, ...account }) => ({\n ...account,\n // Omitted rather than sent empty when unknown, per the API spec.\n ...(accountSource ? { account_source: accountSource } : {}),\n })),\n }),\n // The auth API is stateless (no cookies used)\n // prevent marketing cookies scoped to\n // .metamask.io from being forwarded to api which\n // causes 431 Request Header Fields Too Large errors.\n credentials: 'omit',\n });\n if (!localResponse.ok) {\n throw new HttpError(\n localResponse.status,\n `Fetching '${url.toString()}' failed with status '${localResponse.status}'`,\n );\n }\n return localResponse;\n });\n }\n}\n\n/**\n * Returns the base URL for the given environment.\n *\n * @param env - The environment to get the URL for.\n * @returns The base URL for the environment.\n */\nexport function getAuthUrl(env: SDK.Env): string {\n return `${SDK.getEnvUrls(env).authApiUrl}/api/v2`;\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -5,5 +5,5 @@ export { ProfileMetricsService, serviceName, serviceName as profileMetricsServic
|
|
|
5
5
|
export type { ProfileMetricsServiceMethodActions } from './ProfileMetricsService-method-action-types.js';
|
|
6
6
|
export type { ProofOfOwnershipServiceActions, ProofOfOwnershipServiceEvents, ProofOfOwnershipServiceMessenger, } from './ProofOfOwnershipService.js';
|
|
7
7
|
export { ProofOfOwnershipService, serviceName as proofOfOwnershipServiceName, } from './ProofOfOwnershipService.js';
|
|
8
|
-
export type {
|
|
8
|
+
export type { ProfileMetricsControllerMethodActions, ProfileMetricsControllerSkipInitialDelayAction, } from './ProfileMetricsController-method-action-types.js';
|
|
9
9
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,+BAA+B,EAC/B,8BAA8B,EAC9B,sCAAsC,EACtC,iCAAiC,EACjC,6BAA6B,EAC7B,wCAAwC,GACzC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,wBAAwB,EACxB,uCAAuC,GACxC,MAAM,+BAA+B,CAAC;AACvC,YAAY,EACV,4BAA4B,EAC5B,2BAA2B,EAC3B,8BAA8B,EAC9B,kCAAkC,GACnC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,qBAAqB,EACrB,WAAW,EACX,WAAW,IAAI,yBAAyB,GACzC,MAAM,4BAA4B,CAAC;AACpC,YAAY,EAAE,kCAAkC,EAAE,MAAM,gDAAgD,CAAC;AACzG,YAAY,EACV,8BAA8B,EAC9B,6BAA6B,EAC7B,gCAAgC,GACjC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,uBAAuB,EACvB,WAAW,IAAI,2BAA2B,GAC3C,MAAM,8BAA8B,CAAC;AACtC,YAAY,EACV,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,+BAA+B,EAC/B,8BAA8B,EAC9B,sCAAsC,EACtC,iCAAiC,EACjC,6BAA6B,EAC7B,wCAAwC,GACzC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,wBAAwB,EACxB,uCAAuC,GACxC,MAAM,+BAA+B,CAAC;AACvC,YAAY,EACV,4BAA4B,EAC5B,2BAA2B,EAC3B,8BAA8B,EAC9B,kCAAkC,GACnC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,qBAAqB,EACrB,WAAW,EACX,WAAW,IAAI,yBAAyB,GACzC,MAAM,4BAA4B,CAAC;AACpC,YAAY,EAAE,kCAAkC,EAAE,MAAM,gDAAgD,CAAC;AACzG,YAAY,EACV,8BAA8B,EAC9B,6BAA6B,EAC7B,gCAAgC,GACjC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,uBAAuB,EACvB,WAAW,IAAI,2BAA2B,GAC3C,MAAM,8BAA8B,CAAC;AACtC,YAAY,EACV,qCAAqC,EACrC,8CAA8C,GAC/C,MAAM,mDAAmD,CAAC"}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAQA,OAAO,EACL,wBAAwB,EACxB,uCAAuC,GACxC,MAAM,+BAA+B,CAAC;AAOvC,OAAO,EACL,qBAAqB,EACrB,WAAW,EACX,WAAW,IAAI,yBAAyB,GACzC,MAAM,4BAA4B,CAAC;AAOpC,OAAO,EACL,uBAAuB,EACvB,WAAW,IAAI,2BAA2B,GAC3C,MAAM,8BAA8B,CAAC","sourcesContent":["export type {\n ProfileMetricsControllerActions,\n ProfileMetricsControllerEvents,\n ProfileMetricsControllerGetStateAction,\n ProfileMetricsControllerMessenger,\n ProfileMetricsControllerState,\n ProfileMetricsControllerStateChangeEvent,\n} from './ProfileMetricsController.js';\nexport {\n ProfileMetricsController,\n getDefaultProfileMetricsControllerState,\n} from './ProfileMetricsController.js';\nexport type {\n ProfileMetricsServiceActions,\n ProfileMetricsServiceEvents,\n ProfileMetricsServiceMessenger,\n ProfileMetricsSubmitMetricsRequest,\n} from './ProfileMetricsService.js';\nexport {\n ProfileMetricsService,\n serviceName,\n serviceName as profileMetricsServiceName,\n} from './ProfileMetricsService.js';\nexport type { ProfileMetricsServiceMethodActions } from './ProfileMetricsService-method-action-types.js';\nexport type {\n ProofOfOwnershipServiceActions,\n ProofOfOwnershipServiceEvents,\n ProofOfOwnershipServiceMessenger,\n} from './ProofOfOwnershipService.js';\nexport {\n ProofOfOwnershipService,\n serviceName as proofOfOwnershipServiceName,\n} from './ProofOfOwnershipService.js';\nexport type {\n
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAQA,OAAO,EACL,wBAAwB,EACxB,uCAAuC,GACxC,MAAM,+BAA+B,CAAC;AAOvC,OAAO,EACL,qBAAqB,EACrB,WAAW,EACX,WAAW,IAAI,yBAAyB,GACzC,MAAM,4BAA4B,CAAC;AAOpC,OAAO,EACL,uBAAuB,EACvB,WAAW,IAAI,2BAA2B,GAC3C,MAAM,8BAA8B,CAAC","sourcesContent":["export type {\n ProfileMetricsControllerActions,\n ProfileMetricsControllerEvents,\n ProfileMetricsControllerGetStateAction,\n ProfileMetricsControllerMessenger,\n ProfileMetricsControllerState,\n ProfileMetricsControllerStateChangeEvent,\n} from './ProfileMetricsController.js';\nexport {\n ProfileMetricsController,\n getDefaultProfileMetricsControllerState,\n} from './ProfileMetricsController.js';\nexport type {\n ProfileMetricsServiceActions,\n ProfileMetricsServiceEvents,\n ProfileMetricsServiceMessenger,\n ProfileMetricsSubmitMetricsRequest,\n} from './ProfileMetricsService.js';\nexport {\n ProfileMetricsService,\n serviceName,\n serviceName as profileMetricsServiceName,\n} from './ProfileMetricsService.js';\nexport type { ProfileMetricsServiceMethodActions } from './ProfileMetricsService-method-action-types.js';\nexport type {\n ProofOfOwnershipServiceActions,\n ProofOfOwnershipServiceEvents,\n ProofOfOwnershipServiceMessenger,\n} from './ProofOfOwnershipService.js';\nexport {\n ProofOfOwnershipService,\n serviceName as proofOfOwnershipServiceName,\n} from './ProofOfOwnershipService.js';\nexport type {\n ProfileMetricsControllerMethodActions,\n ProfileMetricsControllerSkipInitialDelayAction,\n} from './ProfileMetricsController-method-action-types.js';\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/profile-metrics-controller",
|
|
3
|
-
"version": "5.2.2-preview-
|
|
3
|
+
"version": "5.2.2-preview-20f24a578",
|
|
4
4
|
"description": "Manages user profile metrics",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"Ethereum",
|
|
@@ -66,18 +66,18 @@
|
|
|
66
66
|
"@metamask/transaction-controller": "^74.2.0",
|
|
67
67
|
"@metamask/utils": "^12.0.2",
|
|
68
68
|
"async-mutex": "^0.5.0",
|
|
69
|
-
"uuid": "^14.0.
|
|
69
|
+
"uuid": "^14.0.2"
|
|
70
70
|
},
|
|
71
71
|
"devDependencies": {
|
|
72
72
|
"@metamask/auto-changelog": "^7.1.0",
|
|
73
73
|
"@metamask/keyring-internal-api": "^12.1.2",
|
|
74
74
|
"@typescript/native": "npm:typescript@^7.0.2",
|
|
75
|
-
"nock": "^15.0.
|
|
76
|
-
"rimraf": "^6.1.
|
|
75
|
+
"nock": "^15.0.5",
|
|
76
|
+
"rimraf": "^6.1.3",
|
|
77
77
|
"typedoc": "^0.28.20",
|
|
78
78
|
"typedoc-plugin-missing-exports": "^4.1.4",
|
|
79
79
|
"typescript": "npm:@typescript/typescript6@^6.0.2",
|
|
80
|
-
"vitest": "5.
|
|
80
|
+
"vitest": "5.0.3"
|
|
81
81
|
},
|
|
82
82
|
"engines": {
|
|
83
83
|
"node": "^22.14.0 || ^24 || ^26"
|