message_cache_test.go 22 KB

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