Skip to content

Pluggable User ID Providers #936 - #1024

Closed
pkowalski-id5 wants to merge 2 commits into
prebid:masterfrom
id5io:pr/936-user-id-provider
Closed

pkowalski-id5 wants to merge 2 commits into
prebid:masterfrom
id5io:pr/936-user-id-provider

Conversation

@pkowalski-id5

Copy link
Copy Markdown
Contributor

Implements #936

UserId provider

See merge request id5-sync/prebid-mobile-android!2

@mdanylov-sigma mdanylov-sigma left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the PR, the API reads well and CI is green. Inline comments below; a few general points here.

Pull vs. push. #936 proposed a push model (providers call UserIdRegistration.setUserId, with "zero provider code execution in the bid request path"). This PR instead runs provider code (getExtendedIds(), ExtendedId.getJson()) synchronously while the request is being built, on whatever thread called loadAd/fetchDemand or the refresh timer, which is usually main. Was that switch agreed with the maintainers? Several inline comments (unguarded getJson(), onRegister ordering, the thread note in the javadoc) follow from it. Either model can work, but we'll want the same contract on iOS (prebid/prebid-mobile-ios#461), so it's worth settling now.

Tests. Dropping the SharedId append from BasicParameterBuilder and routing setSendSharedId/getSendSharedId through the registry isn't covered: no test turns on setSendSharedId(true) and checks for pubcid.org in the built request. The new addExternalUserId / removeExternalUserId / clearExternalUserIds and PrebidMobile.containsExtendedIdProvider have no tests either.

Demo apps. Example/PrebidDemoJava/.../CustomApplication.java:87 and Example/PrebidInternalTestApp/.../CommandLineArgumentParser.kt:133 still use the now-deprecated setExternalUserIds. Worth switching them to addExternalUserId (and maybe showing registerExtendedIdProvider), since that's what integrators copy.

if (userIds == null) return;
for (ExternalUserId userId : userIds) {
if (userId == null) continue;
eids.put(userId.getSource(), userId);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

ConcurrentHashMap rejects null keys, and eids.clear() has already run above, so an ExternalUserId with a null source (Java callers can pass one despite @NonNull) now throws NPE out of TargetingParams.setExternalUserIds after wiping every stored ID. The previous HashMap accepted it, and ExternalUserId.getJson() still has an explicit source == null branch that logged and skipped it. addUserId / removeUserId have the same NPE.

Suggest skipping (and logging) null/empty sources here and in addUserId:

String source = userId.getSource();
if (source == null || source.isEmpty()) {
    LogUtil.warning(TAG, "Skipping external user id without source");
    continue;
}

for (ExternalUserId id : extendedIds) {
for (ExtendedId id : extendedIds) {
if (id != null) {
JSONObject idJson = id.getJson();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

ExtendedId is a public interface now, so getJson() can be vendor code. The registry guards getExtendedIds() with try/catch, but this call isn't guarded, and nothing above it catches (URLBuilder.buildParameters → Requester.makeAdRequest → BidLoader.load). It runs on the thread that called loadAd()/fetchDemand() or on the refresh timer, which is usually main. A vendor getJson() that throws therefore crashes the app instead of dropping one EID. I'd guard it the same way as getExtendedIds(): catch, log, skip.

Related: the ExtendedIdProvider#getExtendedIds javadoc says it's called on "the bid-request thread". In practice it's the caller's thread, usually main. Worth saying that explicitly, since that's where the non-blocking requirement really matters.

private final String source;

RawExtendedId(@NonNull JSONObject json) {
String src = json.optString("source", "");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

optString converts non-string values, so {"source": null} passes this check as the string "null" (and {"source": 123} as "123"), while the JSON that goes on the wire still has "source": null. PBS-Java's RequestValidator rejects the whole request on a blank user.eids[].source. Checking json.opt("source") instanceof String plus non-empty would close that.

Minor: ExternalUserId.getJson() drops EIDs without uids locally, but wrapped JSON skips that check. PBS-Go strips those with a warning, so the impact is low, but validating uids here too would keep the two paths consistent.

if (src.isEmpty()) {
throw new IllegalArgumentException("JSON must contain a non-empty \"source\" field");
}
this.json = json;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This keeps the caller's JSONObject by reference, and getJson() puts that same instance into the request tree, which is serialized later. An async provider that updates uids in place on its own thread (a natural way to refresh a token) races with serialization, because JSONObject wraps an unsynchronized LinkedHashMap. The result is a ConcurrentModificationException or a half-updated EID. A defensive copy in the constructor (new JSONObject(json.toString())) closes this and is cheap at this size.

/**
* Returns all external user IDs that will be sent in auction requests: static IDs plus IDs from
* every registered {@link org.prebid.mobile.api.eid.ExtendedIdProvider}, in no particular order.
* Every ID from every source is included; the server resolves any duplicates.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I checked both servers: neither PBS-Go (validateEIDs) nor PBS-Java (RequestValidator) de-duplicates user.eids by source, so duplicates reach bidders as they are. Before this PR, the static store was keyed by source, so every source was unique (SharedId aside). Now a publisher who keeps addExternalUserId(id5-sync.com …) and also registers the ID5 provider sends two id5-sync.com entries, in ConcurrentHashMap iteration order. Either dedupe by source in getAllExtendedIds() with a defined precedence, or reword this line so it doesn't promise server-side resolution.

if (this == o) return true;
if (!(o instanceof Info)) return false;
Info info = (Info) o;
return name.equals(info.name) && version.equals(info.version);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Identity includes version, so two versions of the same vendor's provider both register and both send their source (for example, a publisher wrapper built against 1.1 plus the vendor library's own 1.2). unregisterExtendedIdProvider with the 1.2 instance also leaves 1.1 in place. The class doc above tells integrators to choose a unique name, which reads as if name is meant to be the identity. Should equals/hashCode use name only, and keep version for logging?

*/
void clearProviders() {
for (ExtendedIdProvider provider : providers.values()) {
provider.onUnregister();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

If one provider's onUnregister() throws, the loop aborts: providers.clear() and staticProvider.clear() never run, and the registry keeps everything. Separately, a concurrent getAllExtendedIds() that runs between providers.clear() and the re-put misses the static IDs. This is package-private and test-only today, so it's minor, but a try/catch per provider is cheap.

* via {@link org.prebid.mobile.PrebidMobile#registerExtendedIdProvider}.
* Use it for one-time initialization if needed.
*/
void onRegister();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The class-level usage example implements only getProviderInfo() / getExtendedIds(), so it doesn't compile while onRegister / onUnregister are abstract. SharedId and StaticExtendedIdProvider also implement both as empty bodies. Making them default void onRegister() {} / default void onUnregister() {} fixes the example and removes the boilerplate.

TargetingParams.sendSharedId = sendSharedId;
SharedId sharedIdProvider = SharedId.getInstance();
if (Boolean.TRUE.equals(sendSharedId)) {
extendedIdRegistry.addProvider(sharedIdProvider);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit: setSendSharedId(true) isn't idempotent log-wise. A second call goes through addProvider, which logs a WARN ("already registered, ignoring duplicate"). Apps often call this on every consent change or screen. A hasProvider check like the one in the false branch would keep it quiet.

* Useful in test teardown to get a clean slate between test cases.
*/
@VisibleForTesting
public static void reset() {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

SdkInitializer.reset() / InitializationNotifier.reset() have no callers in this PR or anywhere else in the repo, but they add two public static methods to the SDK. Also, reset() doesn't cancel an initializationCompleted runnable that's still queued on the main looper, which sets tasksCompletedSuccessfully = true again afterwards. I'd drop them from this PR, or add the test that needs them.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is for testing purposes in a 3rd-party repo that hosts the plugin based on this new API. That's why no reference can be found here

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for explaining, @pkowalski-id5, that helps. We'd still prefer not to make SdkInitializer.reset() / InitializationNotifier.reset() public in the SDK, for these reasons:

  1. Public API is a long-term commitment. Anything public in the AAR can be called by apps, and @VisibleForTesting is only a lint hint. An app that calls reset() in production clears the SDK context while ad units may still be loading. Once released, we'd have to keep supporting it.
  2. The reset isn't safe as written. initializationCompleted() posts a task to the main thread that sets tasksCompletedSuccessfully = true and initializationInProgress = false, and calls the listener of that initialization. If reset() runs while the task is still queued (for example in Robolectric, where main-thread tasks wait until the test idles the looper), the task runs afterwards. It calls the previous test's listener, and it marks the SDK as initialized and not in progress while the next test's initialization is still running. That makes test suites flaky in ways that are hard to trace.
  3. iOS has no such method, and doesn't need one. On iOS, Prebid.initializeSDK can be called again and always calls its completion. We're keeping the two platforms aligned, so we'd rather fix the Android behavior than add an Android-only reset.

My guess is that your tests call PrebidMobile.initializeSdk in each test and wait for the listener. On Android, a second call returns right away, without calling the listener, when the SDK is already initialized or initialization is in progress. So from the second test on, the listener never fires. Please correct me if your tests need something else.

Here are the options we could offer. Could you tell us which one works for your tests?

A. A repeat initializeSdk call calls its listener, as on iOS (preferred). No new API. A separate small PR would change SdkInitializer.init roughly like this:

if (PrebidMobile.isSdkInitialized()) {
    // Posted on the main thread, as for the first initialization.
    notifyListener(listener, InitializationStatus.SUCCEEDED);
    return;
}
if (InitializationNotifier.isInitializationInProgress()) {
    // Called when the running initialization finishes.
    InitializationNotifier.addListener(listener);
    return;
}

The alternative is to re-run the server status check on every call, as iOS does. Your tests could then call initializeSdk in every test and wait for the callback.

B. Test the provider without initializing the SDK. Nothing on the extended ID path checks whether the SDK is initialized. With the plugin API, a provider test can be:

PrebidMobile.registerPlugin(provider, PluginCapability.EXTENDED_IDS);
List<ExtendedId> ids = TargetingParams.getExtendedIds(); // exactly what the next bid request will contain
PrebidMobile.unregisterPlugin(provider, PluginCapability.EXTENDED_IDS);

This covers registration, ordering, the duplicate-source skip and your provider's output, with no SDK change.

C. A clean slate between tests, without public SDK API. If you also need isSdkInitialized() to be false again, for example to test your plugin before the SDK is initialized:

  • In your own Robolectric tests, no SDK change: idle the main looper first (shadowOf(Looper.getMainLooper()).idle()), then call PrebidContextHolder.clearContext() (already public) and reset the two InitializationNotifier flags by reflection. The SDK's own InitializationManagerTest does it this way. It's free, but it can break when SDK internals change.
  • Or a fixed reset that ignores tasks left over from the previous initialization and clears the listener. It would ship outside the production API, for example in a separate test artifact or behind @RestrictTo. We'd propose it for both platforms. It's a bigger change, so we'd only do it if A and B don't cover your case.

Could you share a bit about what your tests do (Robolectric or instrumented, whether they call initializeSdk per test and wait for the listener, whether they rely on isSdkInitialized())? Then we can agree on the option and follow up in a separate PR, so it doesn't block the extended ID providers.

@YuriyVelichkoPI

Copy link
Copy Markdown
Contributor

FYI, I’ve returned to the SDK plugin-system spec referenced in the issue:

https://docs.google.com/document/d/1t6J7lBHsLvKvKn7J92BgTIj-CG4WJ3Luh-FnsOI5s1k/edit?usp=sharing

The EIDs plugin should be included as part of this system.

The spec is still rough, but it captures the core design and is largely aligned with the implementation in this PR. Finalizing the spec, the broader modules system, and user-ID providers are top priorities for the next request.

Please add your thoughts directly to the spec as they arise so we can steer the finalization in the right direction.

mdanylov-sigma added a commit to prebid/prebid-mobile-ios that referenced this pull request Oct 13, 2026
iOS counterpart of prebid/prebid-mobile-android#1024. Adds the
ExtendedIdProvider protocol and Prebid.register/unregister/
containsExtendedIdProvider, so ID vendors can supply EIDs that are read
on every bid request. Static IDs move to Targeting.addExternalUserId /
removeExternalUserId / clearExternalUserIds (setExternalUserIds and
getExternalUserIds are deprecated), and sendSharedId now registers
SharedID as a provider.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@mdanylov-sigma

mdanylov-sigma commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Please add your thoughts directly to the spec as they arise so we can steer the finalization in the right direction.

@YuriyVelichkoPI could you please grant access for commenting/editing ?

mdanylov-sigma added a commit to prebid/prebid-mobile-ios that referenced this pull request Oct 22, 2026
iOS counterpart of prebid/prebid-mobile-android#1024. Adds the
ExtendedIdProvider protocol and Prebid.register/unregister/
containsExtendedIdProvider, so ID vendors can supply EIDs that are read
on every bid request. Static IDs move to Targeting.addExternalUserId /
removeExternalUserId / clearExternalUserIds (setExternalUserIds and
getExternalUserIds are deprecated), and sendSharedId now registers
SharedID as a provider.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
mdanylov-sigma added a commit to prebid/prebid-mobile-ios that referenced this pull request Nov 4, 2026
iOS counterpart of prebid/prebid-mobile-android#1024. Adds the
ExtendedIdProvider protocol and Prebid.register/unregister/
containsExtendedIdProvider, so ID vendors can supply EIDs that are read
on every bid request. Static IDs move to Targeting.addExternalUserId /
removeExternalUserId / clearExternalUserIds (setExternalUserIds and
getExternalUserIds are deprecated), and sendSharedId now registers
SharedID as a provider.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
mdanylov-sigma added a commit to prebid/prebid-mobile-ios that referenced this pull request Nov 4, 2026
iOS counterpart of prebid/prebid-mobile-android#1024. Adds the
ExtendedIdProvider protocol and Prebid.register/unregister/
containsExtendedIdProvider, so ID vendors can supply EIDs that are read
on every bid request. Static IDs move to Targeting.addExternalUserId /
removeExternalUserId / clearExternalUserIds (setExternalUserIds and
getExternalUserIds are deprecated), and sendSharedId now registers
SharedID as a provider.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
mdanylov-sigma added a commit to prebid/prebid-mobile-ios that referenced this pull request Nov 4, 2026
iOS counterpart of prebid/prebid-mobile-android#1024. Adds the
ExtendedIdProvider protocol and Prebid.register/unregister/
containsExtendedIdProvider, so ID vendors can supply EIDs that are read
on every bid request. Static IDs move to Targeting.addExternalUserId /
removeExternalUserId / clearExternalUserIds (setExternalUserIds and
getExternalUserIds are deprecated), and sendSharedId now registers
SharedID as a provider.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@YuriyVelichkoPI

Copy link
Copy Markdown
Contributor

Hi @pkowalski-id5,

@mdanylov-sigma has merged the updates to the SDK plugin system:
#1054

Please update your PR to follow the new plugin API. The PR includes references to the spec, if needed. You can also find the design docs listed in this comment.

Feel free to propose API changes if you think anything could be improved.

@mdanylov-sigma

Copy link
Copy Markdown
Collaborator

Hi @pkowalski-id5,

@mdanylov-sigma has merged the updates to the SDK plugin system: #1054

Please update your PR to follow the new plugin API. The PR includes references to the spec, if needed. You can also find the design docs listed in this comment.

Feel free to propose API changes if you think anything could be improved.

Please let us know if you’re short on capacity at the moment and would like us to take over the PR

@pkowalski-id5

Copy link
Copy Markdown
Contributor Author

Hi @pkowalski-id5,
@mdanylov-sigma has merged the updates to the SDK plugin system: #1054
Please update your PR to follow the new plugin API. The PR includes references to the spec, if needed. You can also find the design docs listed in this comment.
Feel free to propose API changes if you think anything could be improved.

Please let us know if you’re short on capacity at the moment and would like us to take over the PR

Yes, please take it, thank you!

@mdanylov-sigma

Copy link
Copy Markdown
Collaborator

Thanks, @pkowalski-id5! I've moved this onto the plugin registry from #1054 in #1057, which supersedes this PR. Your commit is kept there as the first commit.

The main changes: providers register with PrebidMobile.registerPlugin(provider, PluginCapability.EXTENDED_IDS), a provider ID whose source is already present is skipped (static IDs and SharedID come first), and the review comments above are addressed. It matches the iOS version, prebid/prebid-mobile-ios#1361.

SdkInitializer.reset() isn't included. I've replied in its review thread above with the reasons and the options we can offer instead; let's settle it there, in a separate PR, so it doesn't block this one.

mdanylov-sigma added a commit to prebid/prebid-mobile-ios that referenced this pull request Nov 19, 2026
iOS counterpart of prebid/prebid-mobile-android#1024. Adds the
ExtendedIdProvider protocol and Prebid.register/unregister/
containsExtendedIdProvider, so ID vendors can supply EIDs that are read
on every bid request. Static IDs move to Targeting.addExternalUserId /
removeExternalUserId / clearExternalUserIds (setExternalUserIds and
getExternalUserIds are deprecated), and sendSharedId now registers
SharedID as a provider.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants