This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/texera.git

commit 95e2748b97e0cdd29069971fe74349ac5f28134b
Author: Tanishq Gandhi <[email protected]>
AuthorDate: Sun Nov 22 19:55:52 2026 +0000

    fix(amber): store anonymous hub views with a NULL uid (#9226)
    
    ### What changes were proposed in this PR?
    
    A logged-out viewer's page sends `POST /api/hub/view` with `userId: 0`.
    `postView` incremented the view count, then inserted a `user_action` row
    with `uid = 0`. That breaks the foreign key to `user(uid)`, since no
    user has uid 0, so the request returned 500 and the view was never
    recorded, though the count had already gone up.
    
    - `postView` now records the view with a `NULL` uid when `userId` is `0`
    or missing. `user_action.uid` is nullable, and migration `13.sql`
    already stored the old anonymous views as `NULL`.
    - `recordUserAction` now takes `userId: Option[Integer] = None` and sets
    the uid only when one is given, so the default can't hit the same
    foreign key.
    - `postView` bumps the count and inserts the `user_action` row in one
    transaction, so a view that can't be recorded (for example, a uid whose
    account was deleted) no longer raises the count.
    
    Before and after, sending the logged-out request
    (`{"entityId":8,"userId":0,"entityType":"workflow"}`) three times:
    
    | | Responses | view_count (from 42) | user_action view rows |
    |---|---|---|---|
    | Before | 500, 500, 500 | 45 | 0 |
    | After | 200, 200, 200 | 45 | 3, uid NULL |
    
    ### Any related issues, documentation, discussions?
    
    Closes #9225.
    
    ### How was this PR tested?
    
    New `HubResourceSpec` tests:
    - a view with `userId: 0` and one with no `userId` both return the next
    count and are recorded with a `NULL` uid;
    - a view whose uid has no user row fails and leaves the count unchanged.
    
    Each fails without its part of the fix. `HubResourceSpec` passes
    (75/75), and `scalafmtCheckAll` and `scalafixAll --check` are clean. The
    before/after table above came from running the requests against a local
    server.
    
    ### Was this PR authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Code (Claude Opus 5.5)
---
 .../web/resource/dashboard/hub/HubResource.scala   | 46 ++++++++++++----------
 .../resource/dashboard/hub/HubResourceSpec.scala   | 44 ++++++++++++++++++---
 2 files changed, 65 insertions(+), 25 deletions(-)

diff --git 
a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/hub/HubResource.scala
 
b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/hub/HubResource.scala
index 0c703067f2..3740c90a0d 100644
--- 
a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/hub/HubResource.scala
+++ 
b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/hub/HubResource.scala
@@ -37,7 +37,7 @@ import 
org.apache.texera.web.resource.dashboard.user.workflow.WorkflowResource.{
   mapWorkflowEntries
 }
 import org.jooq.impl.DSL
-import org.jooq.{Record, Table, TableField}
+import org.jooq.{DSLContext, Record, Table, TableField}
 
 import java.util.regex.Pattern
 import javax.annotation.security.RolesAllowed
@@ -140,28 +140,30 @@ object HubResource {
     * Records a user's action in the system.
     *
     * @param request The HTTP request object to extract the user's IP address.
-    * @param userId The ID of the user performing the action (default is 0 for 
anonymous users).
+    * @param userId The ID of the user performing the action; omitted (NULL) 
for an anonymous user.
     * @param entityId The ID of the entity associated with the action.
     * @param entityType The type of entity being acted upon (validated before 
processing).
     * @param action The action performed by the user ("like", "unlike", 
"view", "clone").
+    * @param ctx The context to write with, so a caller can include the row in 
its transaction.
     */
   def recordUserAction(
       request: HttpServletRequest,
-      userId: Integer = Integer.valueOf(0),
+      userId: Option[Integer] = None,
       entityId: Integer,
       entityType: EntityType,
-      action: ActionType
+      action: ActionType,
+      ctx: DSLContext = context
   ): Unit = {
     val userIp = request.getRemoteAddr
     val actionEnum = 
ActionEnum.values().find(_.getLiteral.equalsIgnoreCase(action.value)).get
 
-    val query = context
+    val query = ctx
       .insertInto(USER_ACTION)
-      .set(USER_ACTION.UID, userId)
       .set(USER_ACTION.RESOURCE_ID, entityId)
       .set(USER_ACTION.RESOURCE_TYPE, entityType.value)
       .set(USER_ACTION.ACTION, actionEnum)
 
+    userId.foreach(query.set(USER_ACTION.UID, _))
     if (ipv4Pattern.matcher(userIp).matches()) {
       query.set(USER_ACTION.IP, userIp)
     }
@@ -203,7 +205,7 @@ object HubResource {
         .set(idColumn, entityId)
         .execute()
 
-      recordUserAction(request, userId, entityId, entityType, Like)
+      recordUserAction(request, Some(userId), entityId, entityType, Like)
       true
     } else if (!isLike && alreadyLiked) {
       context
@@ -211,7 +213,7 @@ object HubResource {
         .where(uidColumn.eq(userId).and(idColumn.eq(entityId)))
         .execute()
 
-      recordUserAction(request, userId, entityId, entityType, Unlike)
+      recordUserAction(request, Some(userId), entityId, entityType, Unlike)
       true
     } else {
       false
@@ -237,7 +239,7 @@ object HubResource {
     val (table, uidColumn, idColumn) =
       (entityTables.table, entityTables.uidColumn, entityTables.idColumn)
 
-    recordUserAction(request, userId, entityId, entityType, Clone)
+    recordUserAction(request, Some(userId), entityId, entityType, Clone)
 
     val existingCloneRecord = context
       .selectFrom(table)
@@ -409,18 +411,22 @@ class HubResource {
     val (table, idColumn, viewCountColumn) =
       (entityTables.table, entityTables.idColumn, entityTables.viewCountColumn)
 
-    val record = context
-      .insertInto(table)
-      .set(idColumn, entityID)
-      .set(viewCountColumn, Integer.valueOf(1))
-      .onDuplicateKeyUpdate()
-      .set(viewCountColumn, viewCountColumn.add(1))
-      .returning(viewCountColumn)
-      .fetchOne()
-
-    recordUserAction(request, userId, entityID, entityType, View)
+    // An anonymous viewer has no user row, so the view is recorded with a 
NULL uid.
+    val viewerUid = Option(userId).filter(_.intValue() > 0)
 
-    record.get(viewCountColumn)
+    // One transaction, so a view whose record cannot be stored does not raise 
the count either.
+    SqlServer.withTransaction(context) { ctx =>
+      val record = ctx
+        .insertInto(table)
+        .set(idColumn, entityID)
+        .set(viewCountColumn, Integer.valueOf(1))
+        .onDuplicateKeyUpdate()
+        .set(viewCountColumn, viewCountColumn.add(1))
+        .returning(viewCountColumn)
+        .fetchOne()
+      recordUserAction(request, viewerUid, entityID, entityType, View, ctx)
+      record.get(viewCountColumn)
+    }
   }
 
   /**
diff --git 
a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/hub/HubResourceSpec.scala
 
b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/hub/HubResourceSpec.scala
index d634392a2d..d5c53b59e4 100644
--- 
a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/hub/HubResourceSpec.scala
+++ 
b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/hub/HubResourceSpec.scala
@@ -432,13 +432,19 @@ class HubResourceSpec
   }
 
   "recordUserAction" should "insert a user_action row for the entity" in {
-    recordUserAction(req, Integer.valueOf(likerUid), Integer.valueOf(wid), Wf, 
ActionType.Like)
+    recordUserAction(
+      req,
+      Some(Integer.valueOf(likerUid)),
+      Integer.valueOf(wid),
+      Wf,
+      ActionType.Like
+    )
     userActionRows shouldBe 1
   }
 
   it should "persist uid, resource type, resource id, action and an IPv4 
address" in {
     val id = seedWorkflow(810101, "wf_audit")
-    recordUserAction(req, Integer.valueOf(likerUid), id, Wf, ActionType.View)
+    recordUserAction(req, Some(Integer.valueOf(likerUid)), id, Wf, 
ActionType.View)
 
     auditRows() shouldBe Seq(
       (Integer.valueOf(likerUid), "workflow", 810101, "view", "127.0.0.1")
@@ -447,20 +453,27 @@ class HubResourceSpec
 
   it should "leave the ip column null when the remote address is not 
IPv4-shaped" in {
     val id = seedWorkflow(810102, "wf_audit_v6")
-    recordUserAction(nonIpv4Req, Integer.valueOf(ownerUid), id, Wf, 
ActionType.Clone)
+    recordUserAction(nonIpv4Req, Some(Integer.valueOf(ownerUid)), id, Wf, 
ActionType.Clone)
 
     // Everything but the address is still recorded; only the ip column is 
skipped.
     auditRows() shouldBe Seq((Integer.valueOf(ownerUid), "workflow", 810102, 
"clone", null))
   }
 
+  it should "store a NULL uid when userId is omitted" in {
+    val id = seedWorkflow(810103, "wf_audit_anonymous")
+    recordUserAction(req, entityId = id, entityType = Wf, action = 
ActionType.View)
+
+    auditRows() shouldBe Seq((null, "workflow", 810103, "view", "127.0.0.1"))
+  }
+
   it should "tag each row with its own entity type, keeping equal ids apart" 
in {
     // Same numeric id on purpose: only resource_type separates the two rows.
     seedWorkflow(830001, "wf_shared_id")
     seedDataset(830001, "ds_shared_id")
     val shared = Integer.valueOf(830001)
 
-    recordUserAction(req, Integer.valueOf(ownerUid), shared, Wf, 
ActionType.Like)
-    recordUserAction(req, Integer.valueOf(ownerUid), shared, Ds, 
ActionType.Unlike)
+    recordUserAction(req, Some(Integer.valueOf(ownerUid)), shared, Wf, 
ActionType.Like)
+    recordUserAction(req, Some(Integer.valueOf(ownerUid)), shared, Ds, 
ActionType.Unlike)
 
     auditRows().map { case (_, resourceType, _, action, _) => (resourceType, 
action) } shouldBe
       Seq(("workflow", "like"), ("dataset", "unlike"))
@@ -795,6 +808,27 @@ class HubResourceSpec
     )
   }
 
+  it should "record an anonymous view (uid 0 or none) with a NULL uid" in {
+    val id = seedWorkflow(810603, "wf_view_anonymous")
+    hub.postView(req, ViewRequest(id, Integer.valueOf(0), Wf)) shouldBe 1
+    hub.postView(req, ViewRequest(id, null, Wf)) shouldBe 2
+
+    auditRows() shouldBe Seq(
+      (null, "workflow", 810603, "view", "127.0.0.1"),
+      (null, "workflow", 810603, "view", "127.0.0.1")
+    )
+  }
+
+  it should "leave the count unchanged when the view cannot be recorded" in {
+    val id = seedWorkflow(810605, "wf_view_missing_user")
+    hub.postView(req, ViewRequest(id, Integer.valueOf(likerUid), Wf)) shouldBe 
1
+
+    // A uid with no user row, e.g. an account deleted while another tab was 
still open.
+    an[Exception] should be thrownBy hub.postView(req, ViewRequest(id, 
Integer.valueOf(999999), Wf))
+
+    workflowViewCount(810605) shouldBe Some(1)
+  }
+
   it should "keep workflow and dataset view counts apart when the ids collide" 
in {
     seedWorkflow(830001, "wf_view_shared_id")
     seedDataset(830001, "ds_view_shared_id")

Reply via email to