changeset 6456:5fe14cbe8b9a queues-timeout

fix the management of reservation timestamps
author Sebastien Jodogne <s.jodogne@gmail.com>
date Wed, 19 Nov 2025 15:23:36 +0100
parents 32c3413ff6ee
children ec8dd6953bba
files OrthancServer/Sources/Database/AddTimeoutToQueues.sql OrthancServer/Sources/Database/InstallKeyValueStoresAndQueues.sql OrthancServer/Sources/Database/SQLiteDatabaseWrapper.cpp OrthancServer/UnitTestsSources/ServerIndexTests.cpp
diffstat 4 files changed, 52 insertions(+), 18 deletions(-) [+]
line wrap: on
line diff
--- a/OrthancServer/Sources/Database/AddTimeoutToQueues.sql	Wed Nov 19 13:46:34 2025 +0100
+++ b/OrthancServer/Sources/Database/AddTimeoutToQueues.sql	Wed Nov 19 15:23:36 2025 +0100
@@ -19,5 +19,8 @@
 -- along with this program. If not, see <http://www.gnu.org/licenses/>.
 
 
+-- "reservedUntil" is interpreted exclusively, as the number of seconds
+-- since the Epoch. The reservation is valid as long as "now() < reservedUntil",
+-- and it expires as soon as "reservedUntil <= now()".
 ALTER TABLE Queues
-ADD COLUMN reservedUntil TIMESTAMP DEFAULT NULL;
+ADD COLUMN reservedUntil INTEGER DEFAULT NULL;
--- a/OrthancServer/Sources/Database/InstallKeyValueStoresAndQueues.sql	Wed Nov 19 13:46:34 2025 +0100
+++ b/OrthancServer/Sources/Database/InstallKeyValueStoresAndQueues.sql	Wed Nov 19 15:23:36 2025 +0100
@@ -30,7 +30,7 @@
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        queueId TEXT NOT NULL,
        value BLOB NOT NULL
-       --- reservedUntil TIMESTAMP DEFAULT NULL  -- added in AddTimeoutToQueues.sql
+       --- reservedUntil INTEGER DEFAULT NULL  -- added in AddTimeoutToQueues.sql
 );
 
 CREATE INDEX QueuesIndex ON Queues (queueId, id);
--- a/OrthancServer/Sources/Database/SQLiteDatabaseWrapper.cpp	Wed Nov 19 13:46:34 2025 +0100
+++ b/OrthancServer/Sources/Database/SQLiteDatabaseWrapper.cpp	Wed Nov 19 15:23:36 2025 +0100
@@ -2286,6 +2286,16 @@
       s.Run();
     }
 
+
+    static int64_t GetSecondsSinceEpoch()
+    {
+      // https://www.boost.org/doc/libs/1_69_0/doc/html/date_time/examples.html#date_time.examples.seconds_since_epoch
+      static const boost::posix_time::ptime EPOCH(boost::gregorian::date(1970, 1, 1));
+      const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
+      return (now - EPOCH).total_seconds();
+    }
+
+
     // New in Orthanc 1.12.8 (but deprecated, you should use ReserveQueueValue() instead)
     virtual bool DequeueValue(std::string& value,
                               const std::string& queueId,
@@ -2306,14 +2316,17 @@
           throw OrthancException(ErrorCode_InternalError);
       }
 
+      // "reservedUntil <= ?" indicates that the reservation has expired
       const std::string sql = ("WITH RowToDelete AS (SELECT id FROM Queues WHERE queueId=? AND "
-                               "(reservedUntil IS NULL OR reservedUntil < datetime('now')) ORDER BY id " + order + " LIMIT 1) "
+                               "(reservedUntil IS NULL OR reservedUntil <= ?) ORDER BY id " + order + " LIMIT 1) "
                                "DELETE FROM Queues WHERE id IN (SELECT id FROM RowToDelete) "
                                "RETURNING value");
 
       SQLite::Statement s(db_, SQLITE_FROM_HERE_DYNAMIC(sql), sql);
 
       s.BindString(0, queueId);
+      s.BindInt64(1, GetSecondsSinceEpoch() /* now */);
+
       if (!s.Step())
       {
         // No value found
@@ -2330,6 +2343,7 @@
       }    
     }
 
+
     // New in Orthanc 1.12.8
     virtual uint64_t GetQueueSize(const std::string& queueId) ORTHANC_OVERRIDE
     {
@@ -2339,6 +2353,7 @@
       return s.ColumnInt64(0);
     }
 
+
     // New in Orthanc 1.12.10
     virtual bool ReserveQueueValue(std::string& value,
                                    uint64_t& valueId,
@@ -2361,17 +2376,20 @@
           throw OrthancException(ErrorCode_InternalError);
       }
 
-      std::string sql = ("WITH RowToUpdate AS (SELECT id FROM Queues WHERE queueId=? AND "
-                         "(reservedUntil IS NULL OR reservedUntil < datetime('now')) ORDER BY id " + order + " LIMIT 1) "
-                         "UPDATE Queues SET reservedUntil = datetime('now', ?) WHERE id IN (SELECT id FROM RowToUpdate) "
-                         "RETURNING id, value");
+      // "reservedUntil <= ?" indicates that the reservation has expired
+      const std::string sql = ("WITH RowToUpdate AS (SELECT id FROM Queues WHERE queueId=? AND "
+                               "(reservedUntil IS NULL OR reservedUntil <= ?) ORDER BY id " + order + " LIMIT 1) "
+                               "UPDATE Queues SET reservedUntil = ? WHERE id IN (SELECT id FROM RowToUpdate) "
+                               "RETURNING id, value");
 
       SQLite::Statement s(db_, SQLITE_FROM_HERE_DYNAMIC(sql), sql);
 
       s.BindString(0, queueId);
-      std::string timeout = "+" + boost::lexical_cast<std::string>(releaseTimeout) + " seconds";
-
-      s.BindString(1, timeout);
+
+      const int64_t now = GetSecondsSinceEpoch();
+      s.BindInt64(1, now);
+      s.BindInt64(2, now + releaseTimeout /* reservedUntil */);
+
       if (!s.Step())
       {
         // No value found
@@ -2392,13 +2410,23 @@
 
 
     // New in Orthanc 1.12.10
-    virtual void AcknowledgeQueueValue(const std::string& /* queueId */,
-                                        uint64_t valueId) ORTHANC_OVERRIDE
+    virtual void AcknowledgeQueueValue(const std::string& queueId,
+                                       uint64_t valueId) ORTHANC_OVERRIDE
     {
+      // "? < reservedUntil" indicates that the reservation is still valid
       SQLite::Statement s(db_, SQLITE_FROM_HERE,
-                          "DELETE FROM Queues WHERE id = ?");
-      s.BindInt64(0, static_cast<int64_t>(valueId));
+                          "DELETE FROM Queues WHERE queueId=? AND id=? AND "
+                          "reservedUntil IS NOT NULL AND ? < reservedUntil");
+      s.BindString(0, queueId);
+      s.BindInt64(1, static_cast<int64_t>(valueId));
+      s.BindInt64(2, GetSecondsSinceEpoch() /* now */);
       s.Run();
+
+      if (db_.GetLastChangeCount() == 0)
+      {
+        // This occurs if the acknowledgment occurs after the reservation has expired
+        throw OrthancException(ErrorCode_UnknownResource);
+      }
     }
   };
 
--- a/OrthancServer/UnitTestsSources/ServerIndexTests.cpp	Wed Nov 19 13:46:34 2025 +0100
+++ b/OrthancServer/UnitTestsSources/ServerIndexTests.cpp	Wed Nov 19 15:23:36 2025 +0100
@@ -1353,6 +1353,7 @@
 
     op.AcknowledgeQueueValue("test", valueId1);
     ASSERT_EQ(2u, op.GetQueueSize("test"));
+    ASSERT_THROW(op.AcknowledgeQueueValue("test", valueId1), OrthancException);  // Cannot acknowledge twice
     op.AcknowledgeQueueValue("test", valueId2);
     op.AcknowledgeQueueValue("test", valueId0);
     ASSERT_EQ(0u, op.GetQueueSize("test"));
@@ -1375,16 +1376,18 @@
     ASSERT_EQ("g", s);
     op.AcknowledgeQueueValue("test", valueId0);
 
+    // "DequeueValue()" must ignore the reserved values
+    ASSERT_TRUE(op.DequeueValue(s, "test", QueueOrigin_Front));
+    ASSERT_EQ("f", s);
+
     SystemToolbox::USleep(2000000); // the granularity being the second, we might have to wait up to 2 seconds
 
-    // "d", "f" and "h" remains
+    // "d" and "h" remain
     ASSERT_TRUE(op.ReserveQueueValue(s, valueId0, "test", QueueOrigin_Front, 1));  
     ASSERT_EQ("d", s);
-    ASSERT_TRUE(op.ReserveQueueValue(s, valueId0, "test", QueueOrigin_Front, 1));  
-    ASSERT_EQ("f", s);
     ASSERT_TRUE(op.ReserveQueueValue(s, valueId0, "test", QueueOrigin_Back, 1));  
     ASSERT_EQ("h", s);
-    
+
     // the queue is empty at this point since "f" has been reserved already
     ASSERT_FALSE(op.ReserveQueueValue(s, valueId0, "test", QueueOrigin_Back, 1));  
   }