message_cache_test.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. package server
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "net/netip"
  6. "path/filepath"
  7. "testing"
  8. "time"
  9. "github.com/stretchr/testify/require"
  10. )
  11. func TestSqliteCache_Messages(t *testing.T) {
  12. testCacheMessages(t, newSqliteTestCache(t))
  13. }
  14. func TestMemCache_Messages(t *testing.T) {
  15. testCacheMessages(t, newMemTestCache(t))
  16. }
  17. func testCacheMessages(t *testing.T, c *messageCache) {
  18. m1 := newDefaultMessage("mytopic", "my message")
  19. m1.Time = 1
  20. m2 := newDefaultMessage("mytopic", "my other message")
  21. m2.Time = 2
  22. require.Nil(t, c.AddMessage(m1))
  23. require.Nil(t, c.AddMessage(newDefaultMessage("example", "my example message")))
  24. require.Nil(t, c.AddMessage(m2))
  25. // Adding invalid
  26. require.Equal(t, errUnexpectedMessageType, c.AddMessage(newKeepaliveMessage("mytopic"))) // These should not be added!
  27. require.Equal(t, errUnexpectedMessageType, c.AddMessage(newOpenMessage("example"))) // These should not be added!
  28. // mytopic: count
  29. counts, err := c.MessageCounts()
  30. require.Nil(t, err)
  31. require.Equal(t, 2, counts["mytopic"])
  32. // mytopic: since all
  33. messages, _ := c.Messages("mytopic", sinceAllMessages, false)
  34. require.Equal(t, 2, len(messages))
  35. require.Equal(t, "my message", messages[0].Message)
  36. require.Equal(t, "mytopic", messages[0].Topic)
  37. require.Equal(t, messageEvent, messages[0].Event)
  38. require.Equal(t, "", messages[0].Title)
  39. require.Equal(t, 0, messages[0].Priority)
  40. require.Nil(t, messages[0].Tags)
  41. require.Equal(t, "my other message", messages[1].Message)
  42. // mytopic: since none
  43. messages, _ = c.Messages("mytopic", sinceNoMessages, false)
  44. require.Empty(t, messages)
  45. // mytopic: since m1 (by ID)
  46. messages, _ = c.Messages("mytopic", newSinceID(m1.ID), false)
  47. require.Equal(t, 1, len(messages))
  48. require.Equal(t, m2.ID, messages[0].ID)
  49. require.Equal(t, "my other message", messages[0].Message)
  50. require.Equal(t, "mytopic", messages[0].Topic)
  51. // mytopic: since 2
  52. messages, _ = c.Messages("mytopic", newSinceTime(2), false)
  53. require.Equal(t, 1, len(messages))
  54. require.Equal(t, "my other message", messages[0].Message)
  55. // example: count
  56. counts, err = c.MessageCounts()
  57. require.Nil(t, err)
  58. require.Equal(t, 1, counts["example"])
  59. // example: since all
  60. messages, _ = c.Messages("example", sinceAllMessages, false)
  61. require.Equal(t, "my example message", messages[0].Message)
  62. // non-existing: count
  63. counts, err = c.MessageCounts()
  64. require.Nil(t, err)
  65. require.Equal(t, 0, counts["doesnotexist"])
  66. // non-existing: since all
  67. messages, _ = c.Messages("doesnotexist", sinceAllMessages, false)
  68. require.Empty(t, messages)
  69. }
  70. func TestSqliteCache_MessagesScheduled(t *testing.T) {
  71. testCacheMessagesScheduled(t, newSqliteTestCache(t))
  72. }
  73. func TestMemCache_MessagesScheduled(t *testing.T) {
  74. testCacheMessagesScheduled(t, newMemTestCache(t))
  75. }
  76. func testCacheMessagesScheduled(t *testing.T, c *messageCache) {
  77. m1 := newDefaultMessage("mytopic", "message 1")
  78. m2 := newDefaultMessage("mytopic", "message 2")
  79. m2.Time = time.Now().Add(time.Hour).Unix()
  80. m3 := newDefaultMessage("mytopic", "message 3")
  81. m3.Time = time.Now().Add(time.Minute).Unix() // earlier than m2!
  82. m4 := newDefaultMessage("mytopic2", "message 4")
  83. m4.Time = time.Now().Add(time.Minute).Unix()
  84. require.Nil(t, c.AddMessage(m1))
  85. require.Nil(t, c.AddMessage(m2))
  86. require.Nil(t, c.AddMessage(m3))
  87. messages, _ := c.Messages("mytopic", sinceAllMessages, false) // exclude scheduled
  88. require.Equal(t, 1, len(messages))
  89. require.Equal(t, "message 1", messages[0].Message)
  90. messages, _ = c.Messages("mytopic", sinceAllMessages, true) // include scheduled
  91. require.Equal(t, 3, len(messages))
  92. require.Equal(t, "message 1", messages[0].Message)
  93. require.Equal(t, "message 3", messages[1].Message) // Order!
  94. require.Equal(t, "message 2", messages[2].Message)
  95. messages, _ = c.MessagesDue()
  96. require.Empty(t, messages)
  97. }
  98. func TestSqliteCache_Topics(t *testing.T) {
  99. testCacheTopics(t, newSqliteTestCache(t))
  100. }
  101. func TestMemCache_Topics(t *testing.T) {
  102. testCacheTopics(t, newMemTestCache(t))
  103. }
  104. func testCacheTopics(t *testing.T, c *messageCache) {
  105. require.Nil(t, c.AddMessage(newDefaultMessage("topic1", "my example message")))
  106. require.Nil(t, c.AddMessage(newDefaultMessage("topic2", "message 1")))
  107. require.Nil(t, c.AddMessage(newDefaultMessage("topic2", "message 2")))
  108. require.Nil(t, c.AddMessage(newDefaultMessage("topic2", "message 3")))
  109. topics, err := c.Topics()
  110. if err != nil {
  111. t.Fatal(err)
  112. }
  113. require.Equal(t, 2, len(topics))
  114. require.Equal(t, "topic1", topics["topic1"].ID)
  115. require.Equal(t, "topic2", topics["topic2"].ID)
  116. }
  117. func TestSqliteCache_MessagesTagsPrioAndTitle(t *testing.T) {
  118. testCacheMessagesTagsPrioAndTitle(t, newSqliteTestCache(t))
  119. }
  120. func TestMemCache_MessagesTagsPrioAndTitle(t *testing.T) {
  121. testCacheMessagesTagsPrioAndTitle(t, newMemTestCache(t))
  122. }
  123. func testCacheMessagesTagsPrioAndTitle(t *testing.T, c *messageCache) {
  124. m := newDefaultMessage("mytopic", "some message")
  125. m.Tags = []string{"tag1", "tag2"}
  126. m.Priority = 5
  127. m.Title = "some title"
  128. require.Nil(t, c.AddMessage(m))
  129. messages, _ := c.Messages("mytopic", sinceAllMessages, false)
  130. require.Equal(t, []string{"tag1", "tag2"}, messages[0].Tags)
  131. require.Equal(t, 5, messages[0].Priority)
  132. require.Equal(t, "some title", messages[0].Title)
  133. }
  134. func TestSqliteCache_MessagesSinceID(t *testing.T) {
  135. testCacheMessagesSinceID(t, newSqliteTestCache(t))
  136. }
  137. func TestMemCache_MessagesSinceID(t *testing.T) {
  138. testCacheMessagesSinceID(t, newMemTestCache(t))
  139. }
  140. func testCacheMessagesSinceID(t *testing.T, c *messageCache) {
  141. m1 := newDefaultMessage("mytopic", "message 1")
  142. m1.Time = 100
  143. m2 := newDefaultMessage("mytopic", "message 2")
  144. m2.Time = 200
  145. m3 := newDefaultMessage("mytopic", "message 3")
  146. m3.Time = time.Now().Add(time.Hour).Unix() // Scheduled, in the future, later than m7 and m5
  147. m4 := newDefaultMessage("mytopic", "message 4")
  148. m4.Time = 400
  149. m5 := newDefaultMessage("mytopic", "message 5")
  150. m5.Time = time.Now().Add(time.Minute).Unix() // Scheduled, in the future, later than m7
  151. m6 := newDefaultMessage("mytopic", "message 6")
  152. m6.Time = 600
  153. m7 := newDefaultMessage("mytopic", "message 7")
  154. m7.Time = 700
  155. require.Nil(t, c.AddMessage(m1))
  156. require.Nil(t, c.AddMessage(m2))
  157. require.Nil(t, c.AddMessage(m3))
  158. require.Nil(t, c.AddMessage(m4))
  159. require.Nil(t, c.AddMessage(m5))
  160. require.Nil(t, c.AddMessage(m6))
  161. require.Nil(t, c.AddMessage(m7))
  162. // Case 1: Since ID exists, exclude scheduled
  163. messages, _ := c.Messages("mytopic", newSinceID(m2.ID), false)
  164. require.Equal(t, 3, len(messages))
  165. require.Equal(t, "message 4", messages[0].Message)
  166. require.Equal(t, "message 6", messages[1].Message) // Not scheduled m3/m5!
  167. require.Equal(t, "message 7", messages[2].Message)
  168. // Case 2: Since ID exists, include scheduled
  169. messages, _ = c.Messages("mytopic", newSinceID(m2.ID), true)
  170. require.Equal(t, 5, len(messages))
  171. require.Equal(t, "message 4", messages[0].Message)
  172. require.Equal(t, "message 6", messages[1].Message)
  173. require.Equal(t, "message 7", messages[2].Message)
  174. require.Equal(t, "message 5", messages[3].Message) // Order!
  175. require.Equal(t, "message 3", messages[4].Message) // Order!
  176. // Case 3: Since ID does not exist (-> Return all messages), include scheduled
  177. messages, _ = c.Messages("mytopic", newSinceID("doesntexist"), true)
  178. require.Equal(t, 7, len(messages))
  179. require.Equal(t, "message 1", messages[0].Message)
  180. require.Equal(t, "message 2", messages[1].Message)
  181. require.Equal(t, "message 4", messages[2].Message)
  182. require.Equal(t, "message 6", messages[3].Message)
  183. require.Equal(t, "message 7", messages[4].Message)
  184. require.Equal(t, "message 5", messages[5].Message) // Order!
  185. require.Equal(t, "message 3", messages[6].Message) // Order!
  186. // Case 4: Since ID exists and is last message (-> Return no messages), exclude scheduled
  187. messages, _ = c.Messages("mytopic", newSinceID(m7.ID), false)
  188. require.Equal(t, 0, len(messages))
  189. // Case 5: Since ID exists and is last message (-> Return no messages), include scheduled
  190. messages, _ = c.Messages("mytopic", newSinceID(m7.ID), true)
  191. require.Equal(t, 2, len(messages))
  192. require.Equal(t, "message 5", messages[0].Message)
  193. require.Equal(t, "message 3", messages[1].Message)
  194. }
  195. func TestSqliteCache_Prune(t *testing.T) {
  196. testCachePrune(t, newSqliteTestCache(t))
  197. }
  198. func TestMemCache_Prune(t *testing.T) {
  199. testCachePrune(t, newMemTestCache(t))
  200. }
  201. func testCachePrune(t *testing.T, c *messageCache) {
  202. now := time.Now().Unix()
  203. m1 := newDefaultMessage("mytopic", "my message")
  204. m1.Time = now - 10
  205. m1.Expires = now - 5
  206. m2 := newDefaultMessage("mytopic", "my other message")
  207. m2.Time = now - 5
  208. m2.Expires = now + 5 // In the future
  209. m3 := newDefaultMessage("another_topic", "and another one")
  210. m3.Time = now - 12
  211. m3.Expires = now - 2
  212. require.Nil(t, c.AddMessage(m1))
  213. require.Nil(t, c.AddMessage(m2))
  214. require.Nil(t, c.AddMessage(m3))
  215. counts, err := c.MessageCounts()
  216. require.Nil(t, err)
  217. require.Equal(t, 2, counts["mytopic"])
  218. require.Equal(t, 1, counts["another_topic"])
  219. expiredMessageIDs, err := c.MessagesExpired()
  220. require.Nil(t, err)
  221. require.Nil(t, c.DeleteMessages(expiredMessageIDs...))
  222. counts, err = c.MessageCounts()
  223. require.Nil(t, err)
  224. require.Equal(t, 1, counts["mytopic"])
  225. require.Equal(t, 0, counts["another_topic"])
  226. messages, err := c.Messages("mytopic", sinceAllMessages, false)
  227. require.Nil(t, err)
  228. require.Equal(t, 1, len(messages))
  229. require.Equal(t, "my other message", messages[0].Message)
  230. }
  231. func TestSqliteCache_Attachments(t *testing.T) {
  232. testCacheAttachments(t, newSqliteTestCache(t))
  233. }
  234. func TestMemCache_Attachments(t *testing.T) {
  235. testCacheAttachments(t, newMemTestCache(t))
  236. }
  237. func testCacheAttachments(t *testing.T, c *messageCache) {
  238. expires1 := time.Now().Add(-4 * time.Hour).Unix() // Expired
  239. m := newDefaultMessage("mytopic", "flower for you")
  240. m.ID = "m1"
  241. m.Sender = netip.MustParseAddr("1.2.3.4")
  242. m.Attachment = &attachment{
  243. Name: "flower.jpg",
  244. Type: "image/jpeg",
  245. Size: 5000,
  246. Expires: expires1,
  247. URL: "https://ntfy.sh/file/AbDeFgJhal.jpg",
  248. }
  249. require.Nil(t, c.AddMessage(m))
  250. expires2 := time.Now().Add(2 * time.Hour).Unix() // Future
  251. m = newDefaultMessage("mytopic", "sending you a car")
  252. m.ID = "m2"
  253. m.Sender = netip.MustParseAddr("1.2.3.4")
  254. m.Attachment = &attachment{
  255. Name: "car.jpg",
  256. Type: "image/jpeg",
  257. Size: 10000,
  258. Expires: expires2,
  259. URL: "https://ntfy.sh/file/aCaRURL.jpg",
  260. }
  261. require.Nil(t, c.AddMessage(m))
  262. expires3 := time.Now().Add(1 * time.Hour).Unix() // Future
  263. m = newDefaultMessage("another-topic", "sending you another car")
  264. m.ID = "m3"
  265. m.User = "u_BAsbaAa"
  266. m.Sender = netip.MustParseAddr("5.6.7.8")
  267. m.Attachment = &attachment{
  268. Name: "another-car.jpg",
  269. Type: "image/jpeg",
  270. Size: 20000,
  271. Expires: expires3,
  272. URL: "https://ntfy.sh/file/zakaDHFW.jpg",
  273. }
  274. require.Nil(t, c.AddMessage(m))
  275. messages, err := c.Messages("mytopic", sinceAllMessages, false)
  276. require.Nil(t, err)
  277. require.Equal(t, 2, len(messages))
  278. require.Equal(t, "flower for you", messages[0].Message)
  279. require.Equal(t, "flower.jpg", messages[0].Attachment.Name)
  280. require.Equal(t, "image/jpeg", messages[0].Attachment.Type)
  281. require.Equal(t, int64(5000), messages[0].Attachment.Size)
  282. require.Equal(t, expires1, messages[0].Attachment.Expires)
  283. require.Equal(t, "https://ntfy.sh/file/AbDeFgJhal.jpg", messages[0].Attachment.URL)
  284. require.Equal(t, "1.2.3.4", messages[0].Sender.String())
  285. require.Equal(t, "sending you a car", messages[1].Message)
  286. require.Equal(t, "car.jpg", messages[1].Attachment.Name)
  287. require.Equal(t, "image/jpeg", messages[1].Attachment.Type)
  288. require.Equal(t, int64(10000), messages[1].Attachment.Size)
  289. require.Equal(t, expires2, messages[1].Attachment.Expires)
  290. require.Equal(t, "https://ntfy.sh/file/aCaRURL.jpg", messages[1].Attachment.URL)
  291. require.Equal(t, "1.2.3.4", messages[1].Sender.String())
  292. size, err := c.AttachmentBytesUsedBySender("1.2.3.4")
  293. require.Nil(t, err)
  294. require.Equal(t, int64(10000), size)
  295. size, err = c.AttachmentBytesUsedBySender("5.6.7.8")
  296. require.Nil(t, err)
  297. require.Equal(t, int64(0), size) // Accounted to the user, not the IP!
  298. size, err = c.AttachmentBytesUsedByUser("u_BAsbaAa")
  299. require.Nil(t, err)
  300. require.Equal(t, int64(20000), size)
  301. }
  302. func TestSqliteCache_Attachments_Expired(t *testing.T) {
  303. testCacheAttachmentsExpired(t, newSqliteTestCache(t))
  304. }
  305. func TestMemCache_Attachments_Expired(t *testing.T) {
  306. testCacheAttachmentsExpired(t, newMemTestCache(t))
  307. }
  308. func testCacheAttachmentsExpired(t *testing.T, c *messageCache) {
  309. m := newDefaultMessage("mytopic", "flower for you")
  310. m.ID = "m1"
  311. m.Expires = time.Now().Add(time.Hour).Unix()
  312. require.Nil(t, c.AddMessage(m))
  313. m = newDefaultMessage("mytopic", "message with attachment")
  314. m.ID = "m2"
  315. m.Expires = time.Now().Add(2 * time.Hour).Unix()
  316. m.Attachment = &attachment{
  317. Name: "car.jpg",
  318. Type: "image/jpeg",
  319. Size: 10000,
  320. Expires: time.Now().Add(2 * time.Hour).Unix(),
  321. URL: "https://ntfy.sh/file/aCaRURL.jpg",
  322. }
  323. require.Nil(t, c.AddMessage(m))
  324. m = newDefaultMessage("mytopic", "message with external attachment")
  325. m.ID = "m3"
  326. m.Expires = time.Now().Add(2 * time.Hour).Unix()
  327. m.Attachment = &attachment{
  328. Name: "car.jpg",
  329. Type: "image/jpeg",
  330. Expires: 0, // Unknown!
  331. URL: "https://somedomain.com/car.jpg",
  332. }
  333. require.Nil(t, c.AddMessage(m))
  334. m = newDefaultMessage("mytopic2", "message with expired attachment")
  335. m.ID = "m4"
  336. m.Expires = time.Now().Add(2 * time.Hour).Unix()
  337. m.Attachment = &attachment{
  338. Name: "expired-car.jpg",
  339. Type: "image/jpeg",
  340. Size: 20000,
  341. Expires: time.Now().Add(-1 * time.Hour).Unix(),
  342. URL: "https://ntfy.sh/file/aCaRURL.jpg",
  343. }
  344. require.Nil(t, c.AddMessage(m))
  345. ids, err := c.AttachmentsExpired()
  346. require.Nil(t, err)
  347. require.Equal(t, 1, len(ids))
  348. require.Equal(t, "m4", ids[0])
  349. }
  350. func TestSqliteCache_Migration_From0(t *testing.T) {
  351. filename := newSqliteTestCacheFile(t)
  352. db, err := sql.Open("sqlite3", filename)
  353. require.Nil(t, err)
  354. // Create "version 0" schema
  355. _, err = db.Exec(`
  356. BEGIN;
  357. CREATE TABLE IF NOT EXISTS messages (
  358. id VARCHAR(20) PRIMARY KEY,
  359. time INT NOT NULL,
  360. topic VARCHAR(64) NOT NULL,
  361. message VARCHAR(1024) NOT NULL
  362. );
  363. CREATE INDEX IF NOT EXISTS idx_topic ON messages (topic);
  364. COMMIT;
  365. `)
  366. require.Nil(t, err)
  367. // Insert a bunch of messages
  368. for i := 0; i < 10; i++ {
  369. _, err = db.Exec(`INSERT INTO messages (id, time, topic, message) VALUES (?, ?, ?, ?)`,
  370. fmt.Sprintf("abcd%d", i), time.Now().Unix(), "mytopic", fmt.Sprintf("some message %d", i))
  371. require.Nil(t, err)
  372. }
  373. require.Nil(t, db.Close())
  374. // Create cache to trigger migration
  375. c := newSqliteTestCacheFromFile(t, filename, "")
  376. checkSchemaVersion(t, c.db)
  377. messages, err := c.Messages("mytopic", sinceAllMessages, false)
  378. require.Nil(t, err)
  379. require.Equal(t, 10, len(messages))
  380. require.Equal(t, "some message 5", messages[5].Message)
  381. require.Equal(t, "", messages[5].Title)
  382. require.Nil(t, messages[5].Tags)
  383. require.Equal(t, 0, messages[5].Priority)
  384. }
  385. func TestSqliteCache_Migration_From1(t *testing.T) {
  386. filename := newSqliteTestCacheFile(t)
  387. db, err := sql.Open("sqlite3", filename)
  388. require.Nil(t, err)
  389. // Create "version 1" schema
  390. _, err = db.Exec(`
  391. CREATE TABLE IF NOT EXISTS messages (
  392. id VARCHAR(20) PRIMARY KEY,
  393. time INT NOT NULL,
  394. topic VARCHAR(64) NOT NULL,
  395. message VARCHAR(512) NOT NULL,
  396. title VARCHAR(256) NOT NULL,
  397. priority INT NOT NULL,
  398. tags VARCHAR(256) NOT NULL
  399. );
  400. CREATE INDEX IF NOT EXISTS idx_topic ON messages (topic);
  401. CREATE TABLE IF NOT EXISTS schemaVersion (
  402. id INT PRIMARY KEY,
  403. version INT NOT NULL
  404. );
  405. INSERT INTO schemaVersion (id, version) VALUES (1, 1);
  406. `)
  407. require.Nil(t, err)
  408. // Insert a bunch of messages
  409. for i := 0; i < 10; i++ {
  410. _, err = db.Exec(`INSERT INTO messages (id, time, topic, message, title, priority, tags) VALUES (?, ?, ?, ?, ?, ?, ?)`,
  411. fmt.Sprintf("abcd%d", i), time.Now().Unix(), "mytopic", fmt.Sprintf("some message %d", i), "", 0, "")
  412. require.Nil(t, err)
  413. }
  414. require.Nil(t, db.Close())
  415. // Create cache to trigger migration
  416. c := newSqliteTestCacheFromFile(t, filename, "")
  417. checkSchemaVersion(t, c.db)
  418. // Add delayed message
  419. delayedMessage := newDefaultMessage("mytopic", "some delayed message")
  420. delayedMessage.Time = time.Now().Add(time.Minute).Unix()
  421. require.Nil(t, c.AddMessage(delayedMessage))
  422. // 10, not 11!
  423. messages, err := c.Messages("mytopic", sinceAllMessages, false)
  424. require.Nil(t, err)
  425. require.Equal(t, 10, len(messages))
  426. // 11!
  427. messages, err = c.Messages("mytopic", sinceAllMessages, true)
  428. require.Nil(t, err)
  429. require.Equal(t, 11, len(messages))
  430. // Check that index "idx_topic" exists
  431. rows, err := c.db.Query(`SELECT name FROM sqlite_master WHERE type='index' AND name='idx_topic'`)
  432. require.Nil(t, err)
  433. require.True(t, rows.Next())
  434. var indexName string
  435. require.Nil(t, rows.Scan(&indexName))
  436. require.Equal(t, "idx_topic", indexName)
  437. }
  438. func TestSqliteCache_Migration_From9(t *testing.T) {
  439. // This primarily tests the awkward migration that introduces the "expires" column.
  440. // The migration logic has to update the column, using the existing "cache-duration" value.
  441. filename := newSqliteTestCacheFile(t)
  442. db, err := sql.Open("sqlite3", filename)
  443. require.Nil(t, err)
  444. // Create "version 8" schema
  445. _, err = db.Exec(`
  446. BEGIN;
  447. CREATE TABLE IF NOT EXISTS messages (
  448. id INTEGER PRIMARY KEY AUTOINCREMENT,
  449. mid TEXT NOT NULL,
  450. time INT NOT NULL,
  451. topic TEXT NOT NULL,
  452. message TEXT NOT NULL,
  453. title TEXT NOT NULL,
  454. priority INT NOT NULL,
  455. tags TEXT NOT NULL,
  456. click TEXT NOT NULL,
  457. icon TEXT NOT NULL,
  458. actions TEXT NOT NULL,
  459. attachment_name TEXT NOT NULL,
  460. attachment_type TEXT NOT NULL,
  461. attachment_size INT NOT NULL,
  462. attachment_expires INT NOT NULL,
  463. attachment_url TEXT NOT NULL,
  464. sender TEXT NOT NULL,
  465. encoding TEXT NOT NULL,
  466. published INT NOT NULL
  467. );
  468. CREATE INDEX IF NOT EXISTS idx_mid ON messages (mid);
  469. CREATE INDEX IF NOT EXISTS idx_time ON messages (time);
  470. CREATE INDEX IF NOT EXISTS idx_topic ON messages (topic);
  471. CREATE TABLE IF NOT EXISTS schemaVersion (
  472. id INT PRIMARY KEY,
  473. version INT NOT NULL
  474. );
  475. INSERT INTO schemaVersion (id, version) VALUES (1, 9);
  476. COMMIT;
  477. `)
  478. require.Nil(t, err)
  479. // Insert a bunch of messages
  480. insertQuery := `
  481. INSERT INTO messages (mid, time, topic, message, title, priority, tags, click, icon, actions, attachment_name, attachment_type, attachment_size, attachment_expires, attachment_url, sender, encoding, published)
  482. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  483. `
  484. for i := 0; i < 10; i++ {
  485. _, err = db.Exec(
  486. insertQuery,
  487. fmt.Sprintf("abcd%d", i),
  488. time.Now().Unix(),
  489. "mytopic",
  490. fmt.Sprintf("some message %d", i),
  491. "", // title
  492. 0, // priority
  493. "", // tags
  494. "", // click
  495. "", // icon
  496. "", // actions
  497. "", // attachment_name
  498. "", // attachment_type
  499. 0, // attachment_size
  500. 0, // attachment_type
  501. "", // attachment_url
  502. "9.9.9.9", // sender
  503. "", // encoding
  504. 1, // published
  505. )
  506. require.Nil(t, err)
  507. }
  508. // Create cache to trigger migration
  509. cacheDuration := 17 * time.Hour
  510. c, err := newSqliteCache(filename, "", cacheDuration, 0, 0, false)
  511. require.Nil(t, err)
  512. checkSchemaVersion(t, c.db)
  513. // Check version
  514. rows, err := db.Query(`SELECT version FROM main.schemaVersion WHERE id = 1`)
  515. require.Nil(t, err)
  516. require.True(t, rows.Next())
  517. var version int
  518. require.Nil(t, rows.Scan(&version))
  519. require.Equal(t, currentSchemaVersion, version)
  520. messages, err := c.Messages("mytopic", sinceAllMessages, false)
  521. require.Nil(t, err)
  522. require.Equal(t, 10, len(messages))
  523. for _, m := range messages {
  524. require.True(t, m.Expires > time.Now().Add(cacheDuration-5*time.Second).Unix())
  525. require.True(t, m.Expires < time.Now().Add(cacheDuration+5*time.Second).Unix())
  526. }
  527. }
  528. func TestSqliteCache_StartupQueries_WAL(t *testing.T) {
  529. filename := newSqliteTestCacheFile(t)
  530. startupQueries := `pragma journal_mode = WAL;
  531. pragma synchronous = normal;
  532. pragma temp_store = memory;`
  533. db, err := newSqliteCache(filename, startupQueries, time.Hour, 0, 0, false)
  534. require.Nil(t, err)
  535. require.Nil(t, db.AddMessage(newDefaultMessage("mytopic", "some message")))
  536. require.FileExists(t, filename)
  537. require.FileExists(t, filename+"-wal")
  538. require.FileExists(t, filename+"-shm")
  539. }
  540. func TestSqliteCache_StartupQueries_None(t *testing.T) {
  541. filename := newSqliteTestCacheFile(t)
  542. startupQueries := ""
  543. db, err := newSqliteCache(filename, startupQueries, time.Hour, 0, 0, false)
  544. require.Nil(t, err)
  545. require.Nil(t, db.AddMessage(newDefaultMessage("mytopic", "some message")))
  546. require.FileExists(t, filename)
  547. require.NoFileExists(t, filename+"-wal")
  548. require.NoFileExists(t, filename+"-shm")
  549. }
  550. func TestSqliteCache_StartupQueries_Fail(t *testing.T) {
  551. filename := newSqliteTestCacheFile(t)
  552. startupQueries := `xx error`
  553. _, err := newSqliteCache(filename, startupQueries, time.Hour, 0, 0, false)
  554. require.Error(t, err)
  555. }
  556. func TestSqliteCache_Sender(t *testing.T) {
  557. testSender(t, newSqliteTestCache(t))
  558. }
  559. func TestMemCache_Sender(t *testing.T) {
  560. testSender(t, newMemTestCache(t))
  561. }
  562. func testSender(t *testing.T, c *messageCache) {
  563. m1 := newDefaultMessage("mytopic", "mymessage")
  564. m1.Sender = netip.MustParseAddr("1.2.3.4")
  565. require.Nil(t, c.AddMessage(m1))
  566. m2 := newDefaultMessage("mytopic", "mymessage without sender")
  567. require.Nil(t, c.AddMessage(m2))
  568. messages, err := c.Messages("mytopic", sinceAllMessages, false)
  569. require.Nil(t, err)
  570. require.Equal(t, 2, len(messages))
  571. require.Equal(t, messages[0].Sender, netip.MustParseAddr("1.2.3.4"))
  572. require.Equal(t, messages[1].Sender, netip.Addr{})
  573. }
  574. func checkSchemaVersion(t *testing.T, db *sql.DB) {
  575. rows, err := db.Query(`SELECT version FROM schemaVersion`)
  576. require.Nil(t, err)
  577. require.True(t, rows.Next())
  578. var schemaVersion int
  579. require.Nil(t, rows.Scan(&schemaVersion))
  580. require.Equal(t, currentSchemaVersion, schemaVersion)
  581. require.Nil(t, rows.Close())
  582. }
  583. func TestMemCache_NopCache(t *testing.T) {
  584. c, _ := newNopCache()
  585. require.Nil(t, c.AddMessage(newDefaultMessage("mytopic", "my message")))
  586. messages, err := c.Messages("mytopic", sinceAllMessages, false)
  587. require.Nil(t, err)
  588. require.Empty(t, messages)
  589. topics, err := c.Topics()
  590. require.Nil(t, err)
  591. require.Empty(t, topics)
  592. }
  593. func newSqliteTestCache(t *testing.T) *messageCache {
  594. c, err := newSqliteCache(newSqliteTestCacheFile(t), "", time.Hour, 0, 0, false)
  595. if err != nil {
  596. t.Fatal(err)
  597. }
  598. return c
  599. }
  600. func newSqliteTestCacheFile(t *testing.T) string {
  601. return filepath.Join(t.TempDir(), "cache.db")
  602. }
  603. func newSqliteTestCacheFromFile(t *testing.T, filename, startupQueries string) *messageCache {
  604. c, err := newSqliteCache(filename, startupQueries, time.Hour, 0, 0, false)
  605. require.Nil(t, err)
  606. return c
  607. }
  608. func newMemTestCache(t *testing.T) *messageCache {
  609. c, err := newMemCache()
  610. require.Nil(t, err)
  611. return c
  612. }