Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
/*
* Copyright 2020-2026 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.prebid.mobile;

import org.prebid.mobile.api.eid.ExtendedId;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import org.prebid.mobile.api.eid.ExtendedIdProvider;
import org.prebid.mobile.api.eid.ExtendedIdProvider.Info;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
* Central, thread-safe registry for external user IDs (EIDs).
* <p>
* All EID sources are {@link ExtendedIdProvider} instances. The registry
* calls {@link ExtendedIdProvider#getExtendedIds()} on every registered provider
* at each bid request, so values are always fresh.
* <p>
* For backward compatibility, the registry also exposes convenience methods
* ({@link #addStaticExternalUserId}, {@link #setStaticExternalUserIds}, etc.) that manage
* a built-in {@link StaticExtendedIdProvider} internally.
* <p>
* {@link #getAllExtendedIds()} collects EIDs from all providers and is called by
* the bid request builder to populate {@code user.ext.eids} in the OpenRTB payload.
*
* @see ExtendedIdProvider
*/
class ExtendedIdRegistry {

private static final String TAG = "ExtendedIdRegistry";

private static final ExtendedIdRegistry INSTANCE = new ExtendedIdRegistry();

private final ConcurrentHashMap<Info, ExtendedIdProvider> providers = new ConcurrentHashMap<>();
private final StaticExtendedIdProvider staticProvider = new StaticExtendedIdProvider();

private ExtendedIdRegistry() {
providers.put(staticProvider.getProviderInfo(), staticProvider);

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 built-in static provider lives in the same public map under a guessable Info("_static", "1.0"). PrebidMobile.unregisterExtendedIdProvider(anyProviderWithThatInfo) removes it. After that, IDs set through TargetingParams.addExternalUserId / setExternalUserIds are still stored and still returned by getExternalUserIds(), but never sent, and nothing is logged. Registering a vendor provider with that Info is silently ignored too. Keeping staticProvider out of the map, as a field that getAllExtendedIds() always includes, avoids the collision and the re-insert special case in clearProviders().

}

/**
* Returns the singleton registry instance.
*/
@NonNull
static ExtendedIdRegistry getInstance() {
return INSTANCE;
}

// --- Static EIDs (convenience API delegating to built-in StaticExtendedIdProvider) ---

/**
* Replaces all static EIDs with the provided list.
* Existing static EIDs are discarded. Pass {@code null} to clear.
* <p>
* Typed as {@link ExternalUserId} to stay compatible
* with the deprecated {@link TargetingParams} API.
*/
void setStaticExternalUserIds(@Nullable List<ExternalUserId> userIds) {
staticProvider.setUserIds(userIds);
}

/**
* Adds or replaces a single static external user ID, keyed by its source.
*/
void addStaticExternalUserId(@NonNull ExternalUserId userId) {
staticProvider.addUserId(userId);
}

/**
* Removes the static EID with the given source identifier.
* No-op if no EID with that source exists.
*/
void removeStaticExternalUserId(@NonNull String source) {
staticProvider.removeUserId(source);
}

/**
* Removes all static EIDs. Does not affect other providers.
*/
void clearStaticExternalUserIds() {
staticProvider.clear();
}

/**
* Returns only the static EIDs. Does not include EIDs from other providers.
* Use {@link #getAllExtendedIds()} to get the full list.
* <p>
* Typed as {@link ExternalUserId} to stay compatible
* with the deprecated {@link TargetingParams} API.
*/
@NonNull
List<ExternalUserId> getStaticExternalUserIds() {
return staticProvider.getExternalUserIds();
}

// --- Providers ---

/**
* Returns all EIDs from all registered providers (including the built-in
* static provider). Each provider's {@link ExtendedIdProvider#getExtendedIds()}
* is called on-demand. This is the list sent in each auction request.
*/
@NonNull
List<ExtendedId> getAllExtendedIds() {
List<ExtendedId> result = new ArrayList<>();
for (ExtendedIdProvider provider : providers.values()) {
try {
List<ExtendedId> ids = provider.getExtendedIds();
if (ids == null) {
continue;
}
for (ExtendedId id : ids) {
if (id != null) {
result.add(id);
}
}
} catch (Exception e) {
LogUtil.warning(TAG, "Provider " + provider.getProviderInfo()
+ " failed to supply EIDs, skipping: " + e.getMessage());
}
}
return result;
}

/**
* Registers a provider and calls its {@link ExtendedIdProvider#onRegister()}.
* Duplicate registrations (same {@link Info}) are silently ignored.
* The provider's EIDs will be included in all subsequent auction requests.
* Reached through {@link org.prebid.mobile.PrebidMobile#registerExtendedIdProvider}.
*/
void addProvider(@NonNull ExtendedIdProvider provider) {
Info info = provider.getProviderInfo();
if (providers.putIfAbsent(info, provider) != null) {
LogUtil.warning(TAG, "Provider " + info + " already registered, ignoring duplicate");
return;
}
LogUtil.debug(TAG, "Provider " + info + " registered");
provider.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 provider is visible to getAllExtendedIds() (via putIfAbsent) before onRegister() runs, so a concurrent auction can call getExtendedIds() before setup. That contradicts the lifecycle described in the ExtendedIdProvider javadoc. And if onRegister() throws, the exception reaches the caller of PrebidMobile.registerExtendedIdProvider (often Application.onCreate), while the half-initialized provider stays registered, so a retry is ignored as a duplicate.

Suggest wrapping onRegister() in try/catch and calling providers.remove(info, provider) on failure. If the ordering matters, run onRegister() before publishing the provider to the map (and call onUnregister() if putIfAbsent then loses a race).

}

/**
* Removes a previously registered provider and calls its
* {@link ExtendedIdProvider#onUnregister()}.
* Its EIDs will no longer be included in auction requests.
* Reached through {@link org.prebid.mobile.PrebidMobile#unregisterExtendedIdProvider}.
*/
void removeProvider(@NonNull ExtendedIdProvider provider) {
Info info = provider.getProviderInfo();
ExtendedIdProvider removed = providers.remove(info);
if (removed == null) {
return;
}
removed.onUnregister();
LogUtil.debug(TAG, "Provider " + info + " removed");
}

/**
* Removes all registered providers (calling {@link ExtendedIdProvider#onUnregister()}
* on each) and clears all static EIDs. The built-in static provider is
* re-registered automatically.
* Typically used during SDK teardown or testing.
*/
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.

}
providers.clear();
staticProvider.clear();
providers.put(staticProvider.getProviderInfo(), staticProvider);
LogUtil.debug(TAG, "All providers cleared");
}

/**
* Returns {@code true} if the given provider is currently registered.
* Reached through {@link org.prebid.mobile.PrebidMobile#containsExtendedIdProvider}.
*/
boolean hasProvider(@NonNull ExtendedIdProvider provider) {
return providers.containsKey(provider.getProviderInfo());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

package org.prebid.mobile;

import org.prebid.mobile.api.eid.ExtendedId;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

Expand All @@ -32,7 +34,7 @@
* <a href="https://github.com/InteractiveAdvertisingBureau/openrtb2.x/blob/main/2.6.md#3227---object-eid-">OpenRTB 2.6 EID object</a>,
* <a href="https://github.com/InteractiveAdvertisingBureau/openrtb/blob/main/extensions/2.x_official_extensions/eids.md">OpenRTB 2.5 extended identifiers</a>.
*/
public class ExternalUserId {
public class ExternalUserId implements ExtendedId {

private static final String TAG = "ExternalUserId";

Expand All @@ -50,14 +52,18 @@ public class ExternalUserId {
private Integer mm;

/**
* Default constructor.
* Creates an external user ID for a given source.
*
* @param source identifier of the ID source (e.g. {@code "criteo.com"}, {@code "pubcid.org"})
* @param uniqueIds one or more unique identifiers from this source
*/
public ExternalUserId(@NonNull String source, @NonNull List<UniqueId> uniqueIds) {
this.source = source;
this.uniqueIds = uniqueIds;
}

@NonNull
@Override
public String getSource() {
return source;
}
Expand Down Expand Up @@ -113,6 +119,7 @@ public void setMm(@Nullable Integer mm) {
}

@Nullable
@Override
public JSONObject getJson() {
if (source == null || source.isEmpty()) {
LogUtil.warning(TAG, "Empty source");
Expand Down Expand Up @@ -156,6 +163,11 @@ public static class UniqueId {
@Nullable
private Map<String, Object> ext;

/**
* @param id the user identifier string
* @param atype agent type that produced this ID
* (see <a href="https://github.com/InteractiveAdvertisingBureau/openrtb/blob/main/extensions/2.x_official_extensions/eids.md">OpenRTB EIDs spec</a>)
*/
public UniqueId(@NonNull String id, @NonNull Integer atype) {
this.id = id;
this.atype = atype;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import org.prebid.mobile.api.data.InitializationStatus;
import org.prebid.mobile.api.rendering.pluginrenderer.PrebidMobilePluginRegister;
import org.prebid.mobile.api.rendering.pluginrenderer.PrebidMobilePluginRenderer;
import org.prebid.mobile.api.eid.ExtendedIdProvider;
import org.prebid.mobile.configuration.PBSConfig;
import org.prebid.mobile.core.BuildConfig;
import org.prebid.mobile.rendering.listeners.SdkInitializationListener;
Expand Down Expand Up @@ -569,6 +570,39 @@ public static Boolean containsPluginRenderer(PrebidMobilePluginRenderer prebidMo
return PrebidMobilePluginRegister.getInstance().containsPlugin(prebidMobilePluginRenderer);
}

/**
* Registers an extended ID provider. Its EIDs (via {@code getExtendedIds()})
* are included in all subsequent auction requests. {@code onRegister()} is called immediately.
* For simple static IDs use {@link TargetingParams#addExternalUserId} instead.
* <p>
* A provider whose {@link ExtendedIdProvider.Info} equals an already-registered one is ignored.
*
* @see ExtendedIdProvider
* @see ExtendedIdProvider.Info
*/
public static void registerExtendedIdProvider(@NonNull ExtendedIdProvider provider) {
ExtendedIdRegistry.getInstance().addProvider(provider);
}

/**
* Removes a previously registered provider and calls its {@code onUnregister} method.
* The provider's EIDs will no longer appear in auction requests.
*
* @see #registerExtendedIdProvider(ExtendedIdProvider)
*/
public static void unregisterExtendedIdProvider(@NonNull ExtendedIdProvider provider) {
ExtendedIdRegistry.getInstance().removeProvider(provider);
}

/**
* Returns whether the given extended ID provider is currently registered.
*
* @see #registerExtendedIdProvider(ExtendedIdProvider)
*/
public static boolean containsExtendedIdProvider(@NonNull ExtendedIdProvider provider) {
return ExtendedIdRegistry.getInstance().hasProvider(provider);
}

/**
* {@link #setEventDelegate(PrebidEventDelegate)}
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,24 +16,76 @@

package org.prebid.mobile;

import org.prebid.mobile.api.eid.ExtendedId;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import org.prebid.mobile.api.eid.ExtendedIdProvider;
import org.prebid.mobile.rendering.sdk.PrebidContextHolder;

import java.util.Collections;
import java.util.List;
import java.util.UUID;

public class SharedId {
static final String TAG = SharedId.class.getSimpleName();
public class SharedId implements ExtendedIdProvider {

static final String TAG = SharedId.class.getSimpleName();
static final String PB_SharedIdKey = "PB_SharedIdKey";

private static final SharedId INSTANCE = new SharedId();
private static final Info INFO = new Info("sharedId", PrebidMobile.SDK_VERSION);

private static ExternalUserId sessionId = null;

static ExternalUserId getIdentifier() {
private SharedId() {
}

/**
* Returns the singleton instance.
*/
@NonNull
public static SharedId getInstance() {
return INSTANCE;
}

@NonNull
@Override
public Info getProviderInfo() {
return INFO;
}

/**
* Returns the current SharedId as a singleton list.
* Called by the registry on every bid request — delegates to {@link #getIdentifier()},
* which checks the current consent state each time.
*/
@NonNull
@Override
public List<ExtendedId> getExtendedIds() {
return Collections.singletonList(getIdentifier());
}

@Override
public void onRegister() {
// do nothing
}

@Override
public void onUnregister() {
// do nothing
}

/**
* Returns the current SharedId, reusing the session value when present, otherwise the value from
* persistent storage (when device access consent allows), otherwise a newly generated one.
*/
@NonNull
public ExternalUserId getIdentifier() {
Boolean persistentStorageAllowed = TargetingParams.getDeviceAccessConsent();

// If sharedId was used previously in this session, then use that id
Expand Down Expand Up @@ -69,7 +121,7 @@ static ExternalUserId getIdentifier() {
return eid;
}

static void resetIdentifier() {
void resetIdentifier() {
sessionId = null;
storeSharedId(null);
}
Expand Down
Loading
Loading