1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
|
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/indexed_db/indexed_db_backing_store.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/format_macros.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/indexed_db/indexed_db_blob_info.h"
#include "content/browser/indexed_db/indexed_db_database_error.h"
#include "content/browser/indexed_db/indexed_db_leveldb_coding.h"
#include "content/browser/indexed_db/indexed_db_metadata.h"
#include "content/browser/indexed_db/indexed_db_tracing.h"
#include "content/browser/indexed_db/indexed_db_value.h"
#include "content/browser/indexed_db/leveldb/leveldb_comparator.h"
#include "content/browser/indexed_db/leveldb/leveldb_database.h"
#include "content/browser/indexed_db/leveldb/leveldb_iterator.h"
#include "content/browser/indexed_db/leveldb/leveldb_transaction.h"
#include "content/common/indexed_db/indexed_db_key.h"
#include "content/common/indexed_db/indexed_db_key_path.h"
#include "content/common/indexed_db/indexed_db_key_range.h"
#include "content/public/browser/browser_thread.h"
#include "net/url_request/url_request_context.h"
#include "third_party/WebKit/public/platform/WebIDBTypes.h"
#include "third_party/WebKit/public/web/WebSerializedScriptValueVersion.h"
#include "third_party/leveldatabase/env_chromium.h"
#include "webkit/browser/blob/blob_data_handle.h"
#include "webkit/browser/fileapi/file_stream_writer.h"
#include "webkit/browser/fileapi/file_writer_delegate.h"
#include "webkit/browser/fileapi/local_file_stream_writer.h"
#include "webkit/common/database/database_identifier.h"
using base::FilePath;
using base::StringPiece;
using fileapi::FileWriterDelegate;
namespace content {
namespace {
FilePath GetBlobDirectoryName(const FilePath& pathBase, int64 database_id) {
return pathBase.AppendASCII(base::StringPrintf("%" PRIx64, database_id));
}
FilePath GetBlobDirectoryNameForKey(const FilePath& pathBase,
int64 database_id,
int64 key) {
FilePath path = GetBlobDirectoryName(pathBase, database_id);
path = path.AppendASCII(base::StringPrintf(
"%02x", static_cast<int>(key & 0x000000000000ff00) >> 8));
return path;
}
FilePath GetBlobFileNameForKey(const FilePath& pathBase,
int64 database_id,
int64 key) {
FilePath path = GetBlobDirectoryNameForKey(pathBase, database_id, key);
path = path.AppendASCII(base::StringPrintf("%" PRIx64, key));
return path;
}
bool MakeIDBBlobDirectory(const FilePath& pathBase,
int64 database_id,
int64 key) {
FilePath path = GetBlobDirectoryNameForKey(pathBase, database_id, key);
return base::CreateDirectory(path);
}
static std::string ComputeOriginIdentifier(const GURL& origin_url) {
return webkit_database::GetIdentifierFromOrigin(origin_url) + "@1";
}
static base::FilePath ComputeFileName(const GURL& origin_url) {
return base::FilePath()
.AppendASCII(webkit_database::GetIdentifierFromOrigin(origin_url))
.AddExtension(FILE_PATH_LITERAL(".indexeddb.leveldb"));
}
static base::FilePath ComputeBlobPath(const GURL& origin_url) {
return base::FilePath()
.AppendASCII(webkit_database::GetIdentifierFromOrigin(origin_url))
.AddExtension(FILE_PATH_LITERAL(".indexeddb.blob"));
}
static base::FilePath ComputeCorruptionFileName(const GURL& origin_url) {
return ComputeFileName(origin_url)
.Append(FILE_PATH_LITERAL("corruption_info.json"));
}
} // namespace
static const int64 kKeyGeneratorInitialNumber =
1; // From the IndexedDB specification.
enum IndexedDBBackingStoreErrorSource {
// 0 - 2 are no longer used.
FIND_KEY_IN_INDEX = 3,
GET_IDBDATABASE_METADATA,
GET_INDEXES,
GET_KEY_GENERATOR_CURRENT_NUMBER,
GET_OBJECT_STORES,
GET_RECORD,
KEY_EXISTS_IN_OBJECT_STORE,
LOAD_CURRENT_ROW,
SET_UP_METADATA,
GET_PRIMARY_KEY_VIA_INDEX,
KEY_EXISTS_IN_INDEX,
VERSION_EXISTS,
DELETE_OBJECT_STORE,
SET_MAX_OBJECT_STORE_ID,
SET_MAX_INDEX_ID,
GET_NEW_DATABASE_ID,
GET_NEW_VERSION_NUMBER,
CREATE_IDBDATABASE_METADATA,
DELETE_DATABASE,
TRANSACTION_COMMIT_METHOD, // TRANSACTION_COMMIT is a WinNT.h macro
GET_DATABASE_NAMES,
DELETE_INDEX,
CLEAR_OBJECT_STORE,
READ_BLOB_JOURNAL,
DECODE_BLOB_JOURNAL,
INTERNAL_ERROR_MAX,
};
static void RecordInternalError(const char* type,
IndexedDBBackingStoreErrorSource location) {
std::string name;
name.append("WebCore.IndexedDB.BackingStore.").append(type).append("Error");
base::Histogram::FactoryGet(name,
1,
INTERNAL_ERROR_MAX,
INTERNAL_ERROR_MAX + 1,
base::HistogramBase::kUmaTargetedHistogramFlag)
->Add(location);
}
// Use to signal conditions caused by data corruption.
// A macro is used instead of an inline function so that the assert and log
// report the line number.
#define REPORT_ERROR(type, location) \
do { \
LOG(ERROR) << "IndexedDB " type " Error: " #location; \
RecordInternalError(type, location); \
} while (0)
#define INTERNAL_READ_ERROR(location) REPORT_ERROR("Read", location)
#define INTERNAL_CONSISTENCY_ERROR(location) \
REPORT_ERROR("Consistency", location)
#define INTERNAL_WRITE_ERROR(location) REPORT_ERROR("Write", location)
// Use to signal conditions that usually indicate developer error, but
// could be caused by data corruption. A macro is used instead of an
// inline function so that the assert and log report the line number.
// TODO: Improve test coverage so that all error conditions are "tested" and
// then delete this macro.
#define REPORT_ERROR_UNTESTED(type, location) \
do { \
LOG(ERROR) << "IndexedDB " type " Error: " #location; \
NOTREACHED(); \
RecordInternalError(type, location); \
} while (0)
#define INTERNAL_READ_ERROR_UNTESTED(location) \
REPORT_ERROR_UNTESTED("Read", location)
#define INTERNAL_CONSISTENCY_ERROR_UNTESTED(location) \
REPORT_ERROR_UNTESTED("Consistency", location)
#define INTERNAL_WRITE_ERROR_UNTESTED(location) \
REPORT_ERROR_UNTESTED("Write", location)
static void PutBool(LevelDBTransaction* transaction,
const StringPiece& key,
bool value) {
std::string buffer;
EncodeBool(value, &buffer);
transaction->Put(key, &buffer);
}
// Was able to use LevelDB to read the data w/o error, but the data read was not
// in the expected format.
static leveldb::Status InternalInconsistencyStatus() {
return leveldb::Status::Corruption("Internal inconsistency");
}
static leveldb::Status InvalidDBKeyStatus() {
return leveldb::Status::InvalidArgument("Invalid database key ID");
}
static leveldb::Status IOErrorStatus() {
return leveldb::Status::IOError("IO Error");
}
template <typename DBOrTransaction>
static leveldb::Status GetInt(DBOrTransaction* db,
const StringPiece& key,
int64* found_int,
bool* found) {
std::string result;
leveldb::Status s = db->Get(key, &result, found);
if (!s.ok())
return s;
if (!*found)
return leveldb::Status::OK();
StringPiece slice(result);
if (DecodeInt(&slice, found_int) && slice.empty())
return s;
return InternalInconsistencyStatus();
}
static void PutInt(LevelDBTransaction* transaction,
const StringPiece& key,
int64 value) {
DCHECK_GE(value, 0);
std::string buffer;
EncodeInt(value, &buffer);
transaction->Put(key, &buffer);
}
template <typename DBOrTransaction>
WARN_UNUSED_RESULT static leveldb::Status GetVarInt(DBOrTransaction* db,
const StringPiece& key,
int64* found_int,
bool* found) {
std::string result;
leveldb::Status s = db->Get(key, &result, found);
if (!s.ok())
return s;
if (!*found)
return leveldb::Status::OK();
StringPiece slice(result);
if (DecodeVarInt(&slice, found_int) && slice.empty())
return s;
return InternalInconsistencyStatus();
}
static void PutVarInt(LevelDBTransaction* transaction,
const StringPiece& key,
int64 value) {
std::string buffer;
EncodeVarInt(value, &buffer);
transaction->Put(key, &buffer);
}
template <typename DBOrTransaction>
WARN_UNUSED_RESULT static leveldb::Status GetString(
DBOrTransaction* db,
const StringPiece& key,
base::string16* found_string,
bool* found) {
std::string result;
*found = false;
leveldb::Status s = db->Get(key, &result, found);
if (!s.ok())
return s;
if (!*found)
return leveldb::Status::OK();
StringPiece slice(result);
if (DecodeString(&slice, found_string) && slice.empty())
return s;
return InternalInconsistencyStatus();
}
static void PutString(LevelDBTransaction* transaction,
const StringPiece& key,
const base::string16& value) {
std::string buffer;
EncodeString(value, &buffer);
transaction->Put(key, &buffer);
}
static void PutIDBKeyPath(LevelDBTransaction* transaction,
const StringPiece& key,
const IndexedDBKeyPath& value) {
std::string buffer;
EncodeIDBKeyPath(value, &buffer);
transaction->Put(key, &buffer);
}
static int CompareKeys(const StringPiece& a, const StringPiece& b) {
return Compare(a, b, false /*index_keys*/);
}
static int CompareIndexKeys(const StringPiece& a, const StringPiece& b) {
return Compare(a, b, true /*index_keys*/);
}
int IndexedDBBackingStore::Comparator::Compare(const StringPiece& a,
const StringPiece& b) const {
return content::Compare(a, b, false /*index_keys*/);
}
const char* IndexedDBBackingStore::Comparator::Name() const {
return "idb_cmp1";
}
// 0 - Initial version.
// 1 - Adds UserIntVersion to DatabaseMetaData.
// 2 - Adds DataVersion to to global metadata.
static const int64 kLatestKnownSchemaVersion = 2;
WARN_UNUSED_RESULT static bool IsSchemaKnown(LevelDBDatabase* db, bool* known) {
int64 db_schema_version = 0;
bool found = false;
leveldb::Status s =
GetInt(db, SchemaVersionKey::Encode(), &db_schema_version, &found);
if (!s.ok())
return false;
if (!found) {
*known = true;
return true;
}
if (db_schema_version > kLatestKnownSchemaVersion) {
*known = false;
return true;
}
const uint32 latest_known_data_version =
blink::kSerializedScriptValueVersion;
int64 db_data_version = 0;
s = GetInt(db, DataVersionKey::Encode(), &db_data_version, &found);
if (!s.ok())
return false;
if (!found) {
*known = true;
return true;
}
if (db_data_version > latest_known_data_version) {
*known = false;
return true;
}
*known = true;
return true;
}
WARN_UNUSED_RESULT static bool SetUpMetadata(
LevelDBDatabase* db,
const std::string& origin_identifier) {
const uint32 latest_known_data_version =
blink::kSerializedScriptValueVersion;
const std::string schema_version_key = SchemaVersionKey::Encode();
const std::string data_version_key = DataVersionKey::Encode();
scoped_refptr<LevelDBTransaction> transaction = new LevelDBTransaction(db);
int64 db_schema_version = 0;
int64 db_data_version = 0;
bool found = false;
leveldb::Status s =
GetInt(transaction.get(), schema_version_key, &db_schema_version, &found);
if (!s.ok()) {
INTERNAL_READ_ERROR_UNTESTED(SET_UP_METADATA);
return false;
}
if (!found) {
// Initialize new backing store.
db_schema_version = kLatestKnownSchemaVersion;
PutInt(transaction.get(), schema_version_key, db_schema_version);
db_data_version = latest_known_data_version;
PutInt(transaction.get(), data_version_key, db_data_version);
} else {
// Upgrade old backing store.
DCHECK_LE(db_schema_version, kLatestKnownSchemaVersion);
if (db_schema_version < 1) {
db_schema_version = 1;
PutInt(transaction.get(), schema_version_key, db_schema_version);
const std::string start_key =
DatabaseNameKey::EncodeMinKeyForOrigin(origin_identifier);
const std::string stop_key =
DatabaseNameKey::EncodeStopKeyForOrigin(origin_identifier);
scoped_ptr<LevelDBIterator> it = db->CreateIterator();
for (s = it->Seek(start_key);
s.ok() && it->IsValid() && CompareKeys(it->Key(), stop_key) < 0;
s = it->Next()) {
int64 database_id = 0;
found = false;
s = GetInt(transaction.get(), it->Key(), &database_id, &found);
if (!s.ok()) {
INTERNAL_READ_ERROR_UNTESTED(SET_UP_METADATA);
return false;
}
if (!found) {
INTERNAL_CONSISTENCY_ERROR_UNTESTED(SET_UP_METADATA);
return false;
}
std::string int_version_key = DatabaseMetaDataKey::Encode(
database_id, DatabaseMetaDataKey::USER_INT_VERSION);
PutVarInt(transaction.get(),
int_version_key,
IndexedDBDatabaseMetadata::DEFAULT_INT_VERSION);
}
}
if (s.ok() && db_schema_version < 2) {
db_schema_version = 2;
PutInt(transaction.get(), schema_version_key, db_schema_version);
db_data_version = blink::kSerializedScriptValueVersion;
PutInt(transaction.get(), data_version_key, db_data_version);
}
}
if (!s.ok()) {
INTERNAL_READ_ERROR_UNTESTED(SET_UP_METADATA);
return false;
}
// All new values will be written using this serialization version.
found = false;
s = GetInt(transaction.get(), data_version_key, &db_data_version, &found);
if (!s.ok()) {
INTERNAL_READ_ERROR_UNTESTED(SET_UP_METADATA);
return false;
}
if (!found) {
INTERNAL_CONSISTENCY_ERROR_UNTESTED(SET_UP_METADATA);
return false;
}
if (db_data_version < latest_known_data_version) {
db_data_version = latest_known_data_version;
PutInt(transaction.get(), data_version_key, db_data_version);
}
DCHECK_EQ(db_schema_version, kLatestKnownSchemaVersion);
DCHECK_EQ(db_data_version, latest_known_data_version);
s = transaction->Commit();
if (!s.ok()) {
INTERNAL_WRITE_ERROR_UNTESTED(SET_UP_METADATA);
return false;
}
return true;
}
template <typename DBOrTransaction>
WARN_UNUSED_RESULT static leveldb::Status GetMaxObjectStoreId(
DBOrTransaction* db,
int64 database_id,
int64* max_object_store_id) {
const std::string max_object_store_id_key = DatabaseMetaDataKey::Encode(
database_id, DatabaseMetaDataKey::MAX_OBJECT_STORE_ID);
return GetMaxObjectStoreId(db, max_object_store_id_key, max_object_store_id);
}
template <typename DBOrTransaction>
WARN_UNUSED_RESULT static leveldb::Status GetMaxObjectStoreId(
DBOrTransaction* db,
const std::string& max_object_store_id_key,
int64* max_object_store_id) {
*max_object_store_id = -1;
bool found = false;
leveldb::Status s =
GetInt(db, max_object_store_id_key, max_object_store_id, &found);
if (!s.ok())
return s;
if (!found)
*max_object_store_id = 0;
DCHECK_GE(*max_object_store_id, 0);
return s;
}
class DefaultLevelDBFactory : public LevelDBFactory {
public:
virtual leveldb::Status OpenLevelDB(const base::FilePath& file_name,
const LevelDBComparator* comparator,
scoped_ptr<LevelDBDatabase>* db,
bool* is_disk_full) OVERRIDE {
return LevelDBDatabase::Open(file_name, comparator, db, is_disk_full);
}
virtual leveldb::Status DestroyLevelDB(const base::FilePath& file_name)
OVERRIDE {
return LevelDBDatabase::Destroy(file_name);
}
};
// TODO(ericu): Error recovery. If we persistently can't read the
// blob journal, the safe thing to do is to clear it and leak the blobs,
// though that may be costly. Still, database/directory deletion should always
// clean things up, and we can write an fsck that will do a full correction if
// need be.
template <typename T>
static leveldb::Status GetBlobJournal(const StringPiece& leveldb_key,
T* leveldb_transaction,
BlobJournalType* journal) {
std::string data;
bool found = false;
leveldb::Status s = leveldb_transaction->Get(leveldb_key, &data, &found);
if (!s.ok()) {
INTERNAL_READ_ERROR_UNTESTED(READ_BLOB_JOURNAL);
return s;
}
journal->clear();
if (!found || !data.size())
return leveldb::Status::OK();
StringPiece slice(data);
if (!DecodeBlobJournal(&slice, journal)) {
INTERNAL_READ_ERROR_UNTESTED(DECODE_BLOB_JOURNAL);
s = InternalInconsistencyStatus();
}
return s;
}
static void ClearBlobJournal(LevelDBTransaction* leveldb_transaction,
const std::string& level_db_key) {
leveldb_transaction->Remove(level_db_key);
}
static void UpdatePrimaryJournalWithBlobList(
LevelDBTransaction* leveldb_transaction,
const BlobJournalType& journal) {
const std::string leveldb_key = BlobJournalKey::Encode();
std::string data;
EncodeBlobJournal(journal, &data);
leveldb_transaction->Put(leveldb_key, &data);
}
static void UpdateLiveBlobJournalWithBlobList(
LevelDBTransaction* leveldb_transaction,
const BlobJournalType& journal) {
const std::string leveldb_key = LiveBlobJournalKey::Encode();
std::string data;
EncodeBlobJournal(journal, &data);
leveldb_transaction->Put(leveldb_key, &data);
}
static leveldb::Status MergeBlobsIntoLiveBlobJournal(
LevelDBTransaction* leveldb_transaction,
const BlobJournalType& journal) {
BlobJournalType old_journal;
const std::string key = LiveBlobJournalKey::Encode();
leveldb::Status s = GetBlobJournal(key, leveldb_transaction, &old_journal);
if (!s.ok())
return s;
old_journal.insert(old_journal.end(), journal.begin(), journal.end());
UpdateLiveBlobJournalWithBlobList(leveldb_transaction, old_journal);
return leveldb::Status::OK();
}
static void UpdateBlobJournalWithDatabase(
LevelDBDirectTransaction* leveldb_transaction,
int64 database_id) {
BlobJournalType journal;
journal.push_back(
std::make_pair(database_id, DatabaseMetaDataKey::kAllBlobsKey));
const std::string key = BlobJournalKey::Encode();
std::string data;
EncodeBlobJournal(journal, &data);
leveldb_transaction->Put(key, &data);
}
static leveldb::Status MergeDatabaseIntoLiveBlobJournal(
LevelDBDirectTransaction* leveldb_transaction,
int64 database_id) {
BlobJournalType journal;
const std::string key = LiveBlobJournalKey::Encode();
leveldb::Status s = GetBlobJournal(key, leveldb_transaction, &journal);
if (!s.ok())
return s;
journal.push_back(
std::make_pair(database_id, DatabaseMetaDataKey::kAllBlobsKey));
std::string data;
EncodeBlobJournal(journal, &data);
leveldb_transaction->Put(key, &data);
return leveldb::Status::OK();
}
IndexedDBBackingStore::IndexedDBBackingStore(
IndexedDBFactory* indexed_db_factory,
const GURL& origin_url,
const base::FilePath& blob_path,
net::URLRequestContext* request_context,
scoped_ptr<LevelDBDatabase> db,
scoped_ptr<LevelDBComparator> comparator,
base::TaskRunner* task_runner)
: indexed_db_factory_(indexed_db_factory),
origin_url_(origin_url),
blob_path_(blob_path),
origin_identifier_(ComputeOriginIdentifier(origin_url)),
request_context_(request_context),
task_runner_(task_runner),
db_(db.Pass()),
comparator_(comparator.Pass()),
active_blob_registry_(this) {}
IndexedDBBackingStore::~IndexedDBBackingStore() {
if (!blob_path_.empty() && !child_process_ids_granted_.empty()) {
ChildProcessSecurityPolicyImpl* policy =
ChildProcessSecurityPolicyImpl::GetInstance();
std::set<int>::const_iterator iter;
for (iter = child_process_ids_granted_.begin();
iter != child_process_ids_granted_.end();
++iter) {
policy->RevokeAllPermissionsForFile(*iter, blob_path_);
}
}
// db_'s destructor uses comparator_. The order of destruction is important.
db_.reset();
comparator_.reset();
}
IndexedDBBackingStore::RecordIdentifier::RecordIdentifier(
const std::string& primary_key,
int64 version)
: primary_key_(primary_key), version_(version) {
DCHECK(!primary_key.empty());
}
IndexedDBBackingStore::RecordIdentifier::RecordIdentifier()
: primary_key_(), version_(-1) {}
IndexedDBBackingStore::RecordIdentifier::~RecordIdentifier() {}
IndexedDBBackingStore::Cursor::CursorOptions::CursorOptions() {}
IndexedDBBackingStore::Cursor::CursorOptions::~CursorOptions() {}
enum IndexedDBBackingStoreOpenResult {
INDEXED_DB_BACKING_STORE_OPEN_MEMORY_SUCCESS,
INDEXED_DB_BACKING_STORE_OPEN_SUCCESS,
INDEXED_DB_BACKING_STORE_OPEN_FAILED_DIRECTORY,
INDEXED_DB_BACKING_STORE_OPEN_FAILED_UNKNOWN_SCHEMA,
INDEXED_DB_BACKING_STORE_OPEN_CLEANUP_DESTROY_FAILED,
INDEXED_DB_BACKING_STORE_OPEN_CLEANUP_REOPEN_FAILED,
INDEXED_DB_BACKING_STORE_OPEN_CLEANUP_REOPEN_SUCCESS,
INDEXED_DB_BACKING_STORE_OPEN_FAILED_IO_ERROR_CHECKING_SCHEMA,
INDEXED_DB_BACKING_STORE_OPEN_FAILED_UNKNOWN_ERR,
INDEXED_DB_BACKING_STORE_OPEN_MEMORY_FAILED,
INDEXED_DB_BACKING_STORE_OPEN_ATTEMPT_NON_ASCII,
INDEXED_DB_BACKING_STORE_OPEN_DISK_FULL_DEPRECATED,
INDEXED_DB_BACKING_STORE_OPEN_ORIGIN_TOO_LONG,
INDEXED_DB_BACKING_STORE_OPEN_NO_RECOVERY,
INDEXED_DB_BACKING_STORE_OPEN_FAILED_PRIOR_CORRUPTION,
INDEXED_DB_BACKING_STORE_OPEN_MAX,
};
// static
scoped_refptr<IndexedDBBackingStore> IndexedDBBackingStore::Open(
IndexedDBFactory* indexed_db_factory,
const GURL& origin_url,
const base::FilePath& path_base,
net::URLRequestContext* request_context,
blink::WebIDBDataLoss* data_loss,
std::string* data_loss_message,
bool* disk_full,
base::TaskRunner* task_runner,
bool clean_journal) {
*data_loss = blink::WebIDBDataLossNone;
DefaultLevelDBFactory leveldb_factory;
return IndexedDBBackingStore::Open(indexed_db_factory,
origin_url,
path_base,
request_context,
data_loss,
data_loss_message,
disk_full,
&leveldb_factory,
task_runner,
clean_journal);
}
static std::string OriginToCustomHistogramSuffix(const GURL& origin_url) {
if (origin_url.host() == "docs.google.com")
return ".Docs";
return std::string();
}
static void HistogramOpenStatus(IndexedDBBackingStoreOpenResult result,
const GURL& origin_url) {
UMA_HISTOGRAM_ENUMERATION("WebCore.IndexedDB.BackingStore.OpenStatus",
result,
INDEXED_DB_BACKING_STORE_OPEN_MAX);
const std::string suffix = OriginToCustomHistogramSuffix(origin_url);
// Data from the WebCore.IndexedDB.BackingStore.OpenStatus histogram is used
// to generate a graph. So as not to alter the meaning of that graph,
// continue to collect all stats there (above) but also now collect docs stats
// separately (below).
if (!suffix.empty()) {
base::LinearHistogram::FactoryGet(
"WebCore.IndexedDB.BackingStore.OpenStatus" + suffix,
1,
INDEXED_DB_BACKING_STORE_OPEN_MAX,
INDEXED_DB_BACKING_STORE_OPEN_MAX + 1,
base::HistogramBase::kUmaTargetedHistogramFlag)->Add(result);
}
}
static bool IsPathTooLong(const base::FilePath& leveldb_dir) {
int limit = base::GetMaximumPathComponentLength(leveldb_dir.DirName());
if (limit == -1) {
DLOG(WARNING) << "GetMaximumPathComponentLength returned -1";
// In limited testing, ChromeOS returns 143, other OSes 255.
#if defined(OS_CHROMEOS)
limit = 143;
#else
limit = 255;
#endif
}
size_t component_length = leveldb_dir.BaseName().value().length();
if (component_length > static_cast<uint32_t>(limit)) {
DLOG(WARNING) << "Path component length (" << component_length
<< ") exceeds maximum (" << limit
<< ") allowed by this filesystem.";
const int min = 140;
const int max = 300;
const int num_buckets = 12;
UMA_HISTOGRAM_CUSTOM_COUNTS(
"WebCore.IndexedDB.BackingStore.OverlyLargeOriginLength",
component_length,
min,
max,
num_buckets);
return true;
}
return false;
}
leveldb::Status IndexedDBBackingStore::DestroyBackingStore(
const base::FilePath& path_base,
const GURL& origin_url) {
const base::FilePath file_path =
path_base.Append(ComputeFileName(origin_url));
DefaultLevelDBFactory leveldb_factory;
return leveldb_factory.DestroyLevelDB(file_path);
}
bool IndexedDBBackingStore::ReadCorruptionInfo(const base::FilePath& path_base,
const GURL& origin_url,
std::string& message) {
const base::FilePath info_path =
path_base.Append(ComputeCorruptionFileName(origin_url));
if (IsPathTooLong(info_path))
return false;
const int64 max_json_len = 4096;
int64 file_size(0);
if (!GetFileSize(info_path, &file_size) || file_size > max_json_len)
return false;
if (!file_size) {
NOTREACHED();
return false;
}
base::File file(info_path, base::File::FLAG_OPEN | base::File::FLAG_READ);
bool success = false;
if (file.IsValid()) {
std::vector<char> bytes(file_size);
if (file_size == file.Read(0, &bytes[0], file_size)) {
std::string input_js(&bytes[0], file_size);
base::JSONReader reader;
scoped_ptr<base::Value> val(reader.ReadToValue(input_js));
if (val && val->GetType() == base::Value::TYPE_DICTIONARY) {
base::DictionaryValue* dict_val =
static_cast<base::DictionaryValue*>(val.get());
success = dict_val->GetString("message", &message);
}
}
file.Close();
}
base::DeleteFile(info_path, false);
return success;
}
bool IndexedDBBackingStore::RecordCorruptionInfo(
const base::FilePath& path_base,
const GURL& origin_url,
const std::string& message) {
const base::FilePath info_path =
path_base.Append(ComputeCorruptionFileName(origin_url));
if (IsPathTooLong(info_path))
return false;
base::DictionaryValue root_dict;
root_dict.SetString("message", message);
std::string output_js;
base::JSONWriter::Write(&root_dict, &output_js);
base::File file(info_path,
base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
if (!file.IsValid())
return false;
int written = file.Write(0, output_js.c_str(), output_js.length());
return size_t(written) == output_js.length();
}
// static
scoped_refptr<IndexedDBBackingStore> IndexedDBBackingStore::Open(
IndexedDBFactory* indexed_db_factory,
const GURL& origin_url,
const base::FilePath& path_base,
net::URLRequestContext* request_context,
blink::WebIDBDataLoss* data_loss,
std::string* data_loss_message,
bool* is_disk_full,
LevelDBFactory* leveldb_factory,
base::TaskRunner* task_runner,
bool clean_journal) {
IDB_TRACE("IndexedDBBackingStore::Open");
DCHECK(!path_base.empty());
*data_loss = blink::WebIDBDataLossNone;
*data_loss_message = "";
*is_disk_full = false;
scoped_ptr<LevelDBComparator> comparator(new Comparator());
if (!IsStringASCII(path_base.AsUTF8Unsafe())) {
HistogramOpenStatus(INDEXED_DB_BACKING_STORE_OPEN_ATTEMPT_NON_ASCII,
origin_url);
}
if (!base::CreateDirectory(path_base)) {
LOG(ERROR) << "Unable to create IndexedDB database path "
<< path_base.AsUTF8Unsafe();
HistogramOpenStatus(INDEXED_DB_BACKING_STORE_OPEN_FAILED_DIRECTORY,
origin_url);
return scoped_refptr<IndexedDBBackingStore>();
}
const base::FilePath file_path =
path_base.Append(ComputeFileName(origin_url));
const base::FilePath blob_path =
path_base.Append(ComputeBlobPath(origin_url));
if (IsPathTooLong(file_path)) {
HistogramOpenStatus(INDEXED_DB_BACKING_STORE_OPEN_ORIGIN_TOO_LONG,
origin_url);
return scoped_refptr<IndexedDBBackingStore>();
}
scoped_ptr<LevelDBDatabase> db;
leveldb::Status status = leveldb_factory->OpenLevelDB(
file_path, comparator.get(), &db, is_disk_full);
DCHECK(!db == !status.ok());
if (!status.ok()) {
if (leveldb_env::IndicatesDiskFull(status)) {
*is_disk_full = true;
} else if (leveldb_env::IsCorruption(status)) {
*data_loss = blink::WebIDBDataLossTotal;
*data_loss_message = leveldb_env::GetCorruptionMessage(status);
}
}
bool is_schema_known = false;
if (db) {
std::string corruption_message;
if (ReadCorruptionInfo(path_base, origin_url, corruption_message)) {
LOG(ERROR) << "IndexedDB recovering from a corrupted (and deleted) "
"database.";
HistogramOpenStatus(INDEXED_DB_BACKING_STORE_OPEN_FAILED_PRIOR_CORRUPTION,
origin_url);
db.reset();
*data_loss = blink::WebIDBDataLossTotal;
*data_loss_message =
"IndexedDB (database was corrupt): " + corruption_message;
} else if (!IsSchemaKnown(db.get(), &is_schema_known)) {
LOG(ERROR) << "IndexedDB had IO error checking schema, treating it as "
"failure to open";
HistogramOpenStatus(
INDEXED_DB_BACKING_STORE_OPEN_FAILED_IO_ERROR_CHECKING_SCHEMA,
origin_url);
db.reset();
*data_loss = blink::WebIDBDataLossTotal;
*data_loss_message = "I/O error checking schema";
} else if (!is_schema_known) {
LOG(ERROR) << "IndexedDB backing store had unknown schema, treating it "
"as failure to open";
HistogramOpenStatus(INDEXED_DB_BACKING_STORE_OPEN_FAILED_UNKNOWN_SCHEMA,
origin_url);
db.reset();
*data_loss = blink::WebIDBDataLossTotal;
*data_loss_message = "Unknown schema";
}
}
DCHECK(status.ok() || !is_schema_known || leveldb_env::IsIOError(status) ||
leveldb_env::IsCorruption(status));
if (db) {
HistogramOpenStatus(INDEXED_DB_BACKING_STORE_OPEN_SUCCESS, origin_url);
} else if (leveldb_env::IsIOError(status)) {
LOG(ERROR) << "Unable to open backing store, not trying to recover - "
<< status.ToString();
HistogramOpenStatus(INDEXED_DB_BACKING_STORE_OPEN_NO_RECOVERY, origin_url);
return scoped_refptr<IndexedDBBackingStore>();
} else {
DCHECK(!is_schema_known || leveldb_env::IsCorruption(status));
LOG(ERROR) << "IndexedDB backing store open failed, attempting cleanup";
status = leveldb_factory->DestroyLevelDB(file_path);
if (!status.ok()) {
LOG(ERROR) << "IndexedDB backing store cleanup failed";
HistogramOpenStatus(INDEXED_DB_BACKING_STORE_OPEN_CLEANUP_DESTROY_FAILED,
origin_url);
return scoped_refptr<IndexedDBBackingStore>();
}
LOG(ERROR) << "IndexedDB backing store cleanup succeeded, reopening";
leveldb_factory->OpenLevelDB(file_path, comparator.get(), &db, NULL);
if (!db) {
LOG(ERROR) << "IndexedDB backing store reopen after recovery failed";
HistogramOpenStatus(INDEXED_DB_BACKING_STORE_OPEN_CLEANUP_REOPEN_FAILED,
origin_url);
return scoped_refptr<IndexedDBBackingStore>();
}
HistogramOpenStatus(INDEXED_DB_BACKING_STORE_OPEN_CLEANUP_REOPEN_SUCCESS,
origin_url);
}
if (!db) {
NOTREACHED();
HistogramOpenStatus(INDEXED_DB_BACKING_STORE_OPEN_FAILED_UNKNOWN_ERR,
origin_url);
return scoped_refptr<IndexedDBBackingStore>();
}
return Create(indexed_db_factory,
origin_url,
blob_path,
request_context,
db.Pass(),
comparator.Pass(),
task_runner);
}
// static
scoped_refptr<IndexedDBBackingStore> IndexedDBBackingStore::OpenInMemory(
const GURL& origin_url,
base::TaskRunner* task_runner) {
DefaultLevelDBFactory leveldb_factory;
return IndexedDBBackingStore::OpenInMemory(
origin_url, &leveldb_factory, task_runner);
}
// static
scoped_refptr<IndexedDBBackingStore> IndexedDBBackingStore::OpenInMemory(
const GURL& origin_url,
LevelDBFactory* leveldb_factory,
base::TaskRunner* task_runner) {
IDB_TRACE("IndexedDBBackingStore::OpenInMemory");
scoped_ptr<LevelDBComparator> comparator(new Comparator());
scoped_ptr<LevelDBDatabase> db =
LevelDBDatabase::OpenInMemory(comparator.get());
if (!db) {
LOG(ERROR) << "LevelDBDatabase::OpenInMemory failed.";
HistogramOpenStatus(INDEXED_DB_BACKING_STORE_OPEN_MEMORY_FAILED,
origin_url);
return scoped_refptr<IndexedDBBackingStore>();
}
HistogramOpenStatus(INDEXED_DB_BACKING_STORE_OPEN_MEMORY_SUCCESS, origin_url);
return Create(NULL /* indexed_db_factory */,
origin_url,
base::FilePath(),
NULL /* request_context */,
db.Pass(),
comparator.Pass(),
task_runner);
}
// static
scoped_refptr<IndexedDBBackingStore> IndexedDBBackingStore::Create(
IndexedDBFactory* indexed_db_factory,
const GURL& origin_url,
const base::FilePath& blob_path,
net::URLRequestContext* request_context,
scoped_ptr<LevelDBDatabase> db,
scoped_ptr<LevelDBComparator> comparator,
base::TaskRunner* task_runner) {
// TODO(jsbell): Handle comparator name changes.
scoped_refptr<IndexedDBBackingStore> backing_store(
new IndexedDBBackingStore(indexed_db_factory,
origin_url,
blob_path,
request_context,
db.Pass(),
comparator.Pass(),
task_runner));
if (!SetUpMetadata(backing_store->db_.get(),
backing_store->origin_identifier_))
return scoped_refptr<IndexedDBBackingStore>();
return backing_store;
}
void IndexedDBBackingStore::GrantChildProcessPermissions(int child_process_id) {
if (!child_process_ids_granted_.count(child_process_id)) {
child_process_ids_granted_.insert(child_process_id);
ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
child_process_id, blob_path_);
}
}
std::vector<base::string16> IndexedDBBackingStore::GetDatabaseNames(
leveldb::Status* s) {
*s = leveldb::Status::OK();
std::vector<base::string16> found_names;
const std::string start_key =
DatabaseNameKey::EncodeMinKeyForOrigin(origin_identifier_);
const std::string stop_key =
DatabaseNameKey::EncodeStopKeyForOrigin(origin_identifier_);
DCHECK(found_names.empty());
scoped_ptr<LevelDBIterator> it = db_->CreateIterator();
for (*s = it->Seek(start_key);
s->ok() && it->IsValid() && CompareKeys(it->Key(), stop_key) < 0;
*s = it->Next()) {
StringPiece slice(it->Key());
DatabaseNameKey database_name_key;
if (!DatabaseNameKey::Decode(&slice, &database_name_key)) {
INTERNAL_CONSISTENCY_ERROR_UNTESTED(GET_DATABASE_NAMES);
continue;
}
found_names.push_back(database_name_key.database_name());
}
if (!s->ok())
INTERNAL_READ_ERROR_UNTESTED(GET_DATABASE_NAMES);
return found_names;
}
leveldb::Status IndexedDBBackingStore::GetIDBDatabaseMetaData(
const base::string16& name,
IndexedDBDatabaseMetadata* metadata,
bool* found) {
const std::string key = DatabaseNameKey::Encode(origin_identifier_, name);
*found = false;
leveldb::Status s = GetInt(db_.get(), key, &metadata->id, found);
if (!s.ok()) {
INTERNAL_READ_ERROR(GET_IDBDATABASE_METADATA);
return s;
}
if (!*found)
return leveldb::Status::OK();
s = GetString(db_.get(),
DatabaseMetaDataKey::Encode(metadata->id,
DatabaseMetaDataKey::USER_VERSION),
&metadata->version,
found);
if (!s.ok()) {
INTERNAL_READ_ERROR_UNTESTED(GET_IDBDATABASE_METADATA);
return s;
}
if (!*found) {
INTERNAL_CONSISTENCY_ERROR_UNTESTED(GET_IDBDATABASE_METADATA);
return InternalInconsistencyStatus();
}
s = GetVarInt(db_.get(),
DatabaseMetaDataKey::Encode(
metadata->id, DatabaseMetaDataKey::USER_INT_VERSION),
&metadata->int_version,
found);
if (!s.ok()) {
INTERNAL_READ_ERROR_UNTESTED(GET_IDBDATABASE_METADATA);
return s;
}
if (!*found) {
INTERNAL_CONSISTENCY_ERROR_UNTESTED(GET_IDBDATABASE_METADATA);
return InternalInconsistencyStatus();
}
if (metadata->int_version == IndexedDBDatabaseMetadata::DEFAULT_INT_VERSION)
metadata->int_version = IndexedDBDatabaseMetadata::NO_INT_VERSION;
s = GetMaxObjectStoreId(
db_.get(), metadata->id, &metadata->max_object_store_id);
if (!s.ok()) {
INTERNAL_READ_ERROR_UNTESTED(GET_IDBDATABASE_METADATA);
}
return s;
}
WARN_UNUSED_RESULT static leveldb::Status GetNewDatabaseId(
LevelDBTransaction* transaction,
int64* new_id) {
*new_id = -1;
int64 max_database_id = -1;
bool found = false;
leveldb::Status s =
GetInt(transaction, MaxDatabaseIdKey::Encode(), &max_database_id, &found);
if (!s.ok()) {
INTERNAL_READ_ERROR_UNTESTED(GET_NEW_DATABASE_ID);
return s;
}
if (!found)
max_database_id = 0;
DCHECK_GE(max_database_id, 0);
int64 database_id = max_database_id + 1;
PutInt(transaction, MaxDatabaseIdKey::Encode(), database_id);
*new_id = database_id;
return leveldb::Status::OK();
}
leveldb::Status IndexedDBBackingStore::CreateIDBDatabaseMetaData(
const base::string16& name,
const base::string16& version,
int64 int_version,
int64* row_id) {
scoped_refptr<LevelDBTransaction> transaction =
new LevelDBTransaction(db_.get());
leveldb::Status s = GetNewDatabaseId(transaction.get(), row_id);
if (!s.ok())
return s;
DCHECK_GE(*row_id, 0);
if (int_version == IndexedDBDatabaseMetadata::NO_INT_VERSION)
int_version = IndexedDBDatabaseMetadata::DEFAULT_INT_VERSION;
PutInt(transaction.get(),
DatabaseNameKey::Encode(origin_identifier_, name),
*row_id);
PutString(
transaction.get(),
DatabaseMetaDataKey::Encode(*row_id, DatabaseMetaDataKey::USER_VERSION),
version);
PutVarInt(transaction.get(),
DatabaseMetaDataKey::Encode(*row_id,
DatabaseMetaDataKey::USER_INT_VERSION),
int_version);
s = transaction->Commit();
if (!s.ok())
INTERNAL_WRITE_ERROR_UNTESTED(CREATE_IDBDATABASE_METADATA);
return s;
}
bool IndexedDBBackingStore::UpdateIDBDatabaseIntVersion(
IndexedDBBackingStore::Transaction* transaction,
int64 row_id,
int64 int_version) {
if (int_version == IndexedDBDatabaseMetadata::NO_INT_VERSION)
int_version = IndexedDBDatabaseMetadata::DEFAULT_INT_VERSION;
DCHECK_GE(int_version, 0) << "int_version was " << int_version;
PutVarInt(transaction->transaction(),
DatabaseMetaDataKey::Encode(row_id,
DatabaseMetaDataKey::USER_INT_VERSION),
int_version);
return true;
}
static leveldb::Status DeleteRange(LevelDBTransaction* transaction,
const std::string& begin,
const std::string& end) {
scoped_ptr<LevelDBIterator> it = transaction->CreateIterator();
leveldb::Status s;
for (s = it->Seek(begin);
s.ok() && it->IsValid() && CompareKeys(it->Key(), end) < 0;
s = it->Next())
transaction->Remove(it->Key());
return s;
}
leveldb::Status IndexedDBBackingStore::DeleteDatabase(
const base::string16& name) {
IDB_TRACE("IndexedDBBackingStore::DeleteDatabase");
scoped_ptr<LevelDBDirectTransaction> transaction =
LevelDBDirectTransaction::Create(db_.get());
IndexedDBDatabaseMetadata metadata;
bool success = false;
leveldb::Status s = GetIDBDatabaseMetaData(name, &metadata, &success);
if (!s.ok())
return s;
if (!success)
return leveldb::Status::OK();
const std::string start_key = DatabaseMetaDataKey::Encode(
metadata.id, DatabaseMetaDataKey::ORIGIN_NAME);
const std::string stop_key = DatabaseMetaDataKey::Encode(
metadata.id + 1, DatabaseMetaDataKey::ORIGIN_NAME);
scoped_ptr<LevelDBIterator> it = db_->CreateIterator();
for (s = it->Seek(start_key);
s.ok() && it->IsValid() && CompareKeys(it->Key(), stop_key) < 0;
s = it->Next())
transaction->Remove(it->Key());
if (!s.ok()) {
INTERNAL_WRITE_ERROR_UNTESTED(DELETE_DATABASE);
return s;
}
const std::string key = DatabaseNameKey::Encode(origin_identifier_, name);
transaction->Remove(key);
// TODO(ericu): Put the real calls to the blob journal code here. For now,
// I've inserted fake calls so that we don't get "you didn't use this static
// function" compiler errors.
if (false) {
scoped_refptr<LevelDBTransaction> fake_transaction =
new LevelDBTransaction(NULL);
BlobJournalType fake_journal;
MergeDatabaseIntoLiveBlobJournal(transaction.get(), metadata.id);
UpdateBlobJournalWithDatabase(transaction.get(), metadata.id);
MergeBlobsIntoLiveBlobJournal(fake_transaction.get(), fake_journal);
}
s = transaction->Commit();
if (!s.ok()) {
INTERNAL_WRITE_ERROR_UNTESTED(DELETE_DATABASE);
return s;
}
db_->Compact(start_key, stop_key);
return s;
}
static bool CheckObjectStoreAndMetaDataType(const LevelDBIterator* it,
const std::string& stop_key,
int64 object_store_id,
int64 meta_data_type) {
if (!it->IsValid() || CompareKeys(it->Key(), stop_key) >= 0)
return false;
StringPiece slice(it->Key());
ObjectStoreMetaDataKey meta_data_key;
bool ok = ObjectStoreMetaDataKey::Decode(&slice, &meta_data_key);
DCHECK(ok);
if (meta_data_key.ObjectStoreId() != object_store_id)
return false;
if (meta_data_key.MetaDataType() != meta_data_type)
return false;
return true;
}
// TODO(jsbell): This should do some error handling rather than
// plowing ahead when bad data is encountered.
leveldb::Status IndexedDBBackingStore::GetObjectStores(
int64 database_id,
IndexedDBDatabaseMetadata::ObjectStoreMap* object_stores) {
IDB_TRACE("IndexedDBBackingStore::GetObjectStores");
if (!KeyPrefix::IsValidDatabaseId(database_id))
return InvalidDBKeyStatus();
const std::string start_key =
ObjectStoreMetaDataKey::Encode(database_id, 1, 0);
const std::string stop_key =
ObjectStoreMetaDataKey::EncodeMaxKey(database_id);
DCHECK(object_stores->empty());
scoped_ptr<LevelDBIterator> it = db_->CreateIterator();
leveldb::Status s = it->Seek(start_key);
while (s.ok() && it->IsValid() && CompareKeys(it->Key(), stop_key) < 0) {
StringPiece slice(it->Key());
ObjectStoreMetaDataKey meta_data_key;
bool ok = ObjectStoreMetaDataKey::Decode(&slice, &meta_data_key);
DCHECK(ok);
if (meta_data_key.MetaDataType() != ObjectStoreMetaDataKey::NAME) {
INTERNAL_CONSISTENCY_ERROR_UNTESTED(GET_OBJECT_STORES);
// Possible stale metadata, but don't fail the load.
s = it->Next();
if (!s.ok())
break;
continue;
}
int64 object_store_id = meta_data_key.ObjectStoreId();
// TODO(jsbell): Do this by direct key lookup rather than iteration, to
// simplify.
base::string16 object_store_name;
{
StringPiece slice(it->Value());
if (!DecodeString(&slice, &object_store_name) || !slice.empty())
INTERNAL_CONSISTENCY_ERROR_UNTESTED(GET_OBJECT_STORES);
}
s = it->Next();
if (!s.ok())
break;
if (!CheckObjectStoreAndMetaDataType(it.get(),
stop_key,
object_store_id,
ObjectStoreMetaDataKey::KEY_PATH)) {
INTERNAL_CONSISTENCY_ERROR_UNTESTED(GET_OBJECT_STORES);
break;
}
IndexedDBKeyPath key_path;
{
StringPiece slice(it->Value());
if (!DecodeIDBKeyPath(&slice, &key_path) || !slice.empty())
INTERNAL_CONSISTENCY_ERROR_UNTESTED(GET_OBJECT_STORES);
}
s = it->Next();
if (!s.ok())
break;
if (!CheckObjectStoreAndMetaDataType(
it.get(),
stop_key,
object_store_id,
ObjectStoreMetaDataKey::AUTO_INCREMENT)) {
INTERNAL_CONSISTENCY_ERROR_UNTESTED(GET_OBJECT_STORES);
break;
}
bool auto_increment;
{
StringPiece slice(it->Value());
if (!DecodeBool(&slice, &auto_increment) || !slice.empty())
INTERNAL_CONSISTENCY_ERROR_UNTESTED(GET_OBJECT_STORES);
}
s = it->Next(); // Is evictable.
if (!s.ok())
break;
if (!CheckObjectStoreAndMetaDataType(it.get(),
stop_key,
object_store_id,
ObjectStoreMetaDataKey::EVICTABLE)) {
INTERNAL_CONSISTENCY_ERROR_UNTESTED(GET_OBJECT_STORES);
break;
}
s = it->Next(); // Last version.
if (!s.ok())
break;
if (!CheckObjectStoreAndMetaDataType(
it.get(),
stop_key,
object_store_id,
ObjectStoreMetaDataKey::LAST_VERSION)) {
INTERNAL_CONSISTENCY_ERROR_UNTESTED(GET_OBJECT_STORES);
break;
}
s = it->Next(); // Maximum index id allocated.
if (!s.ok())
break;
if (!CheckObjectStoreAndMetaDataType(
it.get(),
stop_key,
object_store_id,
ObjectStoreMetaDataKey::MAX_INDEX_ID)) {
INTERNAL_CONSISTENCY_ERROR_UNTESTED(GET_OBJECT_STORES);
break;
}
int64 max_index_id;
{
StringPiece slice(it->Value());
if (!DecodeInt(&slice, &max_index_id) || !slice.empty())
INTERNAL_CONSISTENCY_ERROR_UNTESTED(GET_OBJECT_STORES);
}
s = it->Next(); // [optional] has key path (is not null)
if (!s.ok())
break;
if (CheckObjectStoreAndMetaDataType(it.get(),
stop_key,
object_store_id,
ObjectStoreMetaDataKey::HAS_KEY_PATH)) {
bool has_key_path;
{
StringPiece slice(it->Value());
if (!DecodeBool(&slice, &has_key_path))
INTERNAL_CONSISTENCY_ERROR_UNTESTED(GET_OBJECT_STORES);
}
// This check accounts for two layers of legacy coding:
// (1) Initially, has_key_path was added to distinguish null vs. string.
// (2) Later, null vs. string vs. array was stored in the key_path itself.
// So this check is only relevant for string-type key_paths.
if (!has_key_path &&
(key_path.type() == blink::WebIDBKeyPathTypeString &&
!key_path.string().empty())) {
INTERNAL_CONSISTENCY_ERROR_UNTESTED(GET_OBJECT_STORES);
break;
}
if (!has_key_path)
key_path = IndexedDBKeyPath();
s = it->Next();
if (!s.ok())
break;
}
int64 key_generator_current_number = -1;
if (CheckObjectStoreAndMetaDataType(
it.get(),
stop_key,
object_store_id,
ObjectStoreMetaDataKey::KEY_GENERATOR_CURRENT_NUMBER)) {
StringPiece slice(it->Value());
if (!DecodeInt(&slice, &key_generator_current_number) || !slice.empty())
INTERNAL_CONSISTENCY_ERROR_UNTESTED(GET_OBJECT_STORES);
// TODO(jsbell): Return key_generator_current_number, cache in
// object store, and write lazily to backing store. For now,
// just assert that if it was written it was valid.
DCHECK_GE(key_generator_current_number, kKeyGeneratorInitialNumber);
s = it->Next();
if (!s.ok())
break;
}
IndexedDBObjectStoreMetadata metadata(object_store_name,
object_store_id,
key_path,
auto_increment,
max_index_id);
s = GetIndexes(database_id, object_store_id, &metadata.indexes);
if (!s.ok())
break;
(*object_stores)[object_store_id] = metadata;
}
if (!s.ok())
INTERNAL_READ_ERROR_UNTESTED(GET_OBJECT_STORES);
return s;
}
WARN_UNUSED_RESULT static leveldb::Status SetMaxObjectStoreId(
LevelDBTransaction* transaction,
int64 database_id,
int64 object_store_id) {
const std::string max_object_store_id_key = DatabaseMetaDataKey::Encode(
database_id, DatabaseMetaDataKey::MAX_OBJECT_STORE_ID);
int64 max_object_store_id = -1;
leveldb::Status s = GetMaxObjectStoreId(
transaction, max_object_store_id_key, &max_object_store_id);
if (!s.ok()) {
INTERNAL_READ_ERROR_UNTESTED(SET_MAX_OBJECT_STORE_ID);
return s;
}
if (object_store_id <= max_object_store_id) {
INTERNAL_CONSISTENCY_ERROR_UNTESTED(SET_MAX_OBJECT_STORE_ID);
return InternalInconsistencyStatus();
}
PutInt(transaction, max_object_store_id_key, object_store_id);
return s;
}
void IndexedDBBackingStore::Compact() { db_->CompactAll(); }
leveldb::Status IndexedDBBackingStore::CreateObjectStore(
IndexedDBBackingStore::Transaction* transaction,
int64 database_id,
int64 object_store_id,
const base::string16& name,
const IndexedDBKeyPath& key_path,
bool auto_increment) {
IDB_TRACE("IndexedDBBackingStore::CreateObjectStore");
if (!KeyPrefix::ValidIds(database_id, object_store_id))
return InvalidDBKeyStatus();
LevelDBTransaction* leveldb_transaction = transaction->transaction();
leveldb::Status s =
SetMaxObjectStoreId(leveldb_transaction, database_id, object_store_id);
if (!s.ok())
return s;
const std::string name_key = ObjectStoreMetaDataKey::Encode(
database_id, object_store_id, ObjectStoreMetaDataKey::NAME);
const std::string key_path_key = ObjectStoreMetaDataKey::Encode(
database_id, object_store_id, ObjectStoreMetaDataKey::KEY_PATH);
const std::string auto_increment_key = ObjectStoreMetaDataKey::Encode(
database_id, object_store_id, ObjectStoreMetaDataKey::AUTO_INCREMENT);
const std::string evictable_key = ObjectStoreMetaDataKey::Encode(
database_id, object_store_id, ObjectStoreMetaDataKey::EVICTABLE);
const std::string last_version_key = ObjectStoreMetaDataKey::Encode(
database_id, object_store_id, ObjectStoreMetaDataKey::LAST_VERSION);
const std::string max_index_id_key = ObjectStoreMetaDataKey::Encode(
database_id, object_store_id, ObjectStoreMetaDataKey::MAX_INDEX_ID);
const std::string has_key_path_key = ObjectStoreMetaDataKey::Encode(
database_id, object_store_id, ObjectStoreMetaDataKey::HAS_KEY_PATH);
const std::string key_generator_current_number_key =
ObjectStoreMetaDataKey::Encode(
database_id,
object_store_id,
ObjectStoreMetaDataKey::KEY_GENERATOR_CURRENT_NUMBER);
const std::string names_key = ObjectStoreNamesKey::Encode(database_id, name);
PutString(leveldb_transaction, name_key, name);
PutIDBKeyPath(leveldb_transaction, key_path_key, key_path);
PutInt(leveldb_transaction, auto_increment_key, auto_increment);
PutInt(leveldb_transaction, evictable_key, false);
PutInt(leveldb_transaction, last_version_key, 1);
PutInt(leveldb_transaction, max_index_id_key, kMinimumIndexId);
PutBool(leveldb_transaction, has_key_path_key, !key_path.IsNull());
PutInt(leveldb_transaction,
key_generator_current_number_key,
kKeyGeneratorInitialNumber);
PutInt(leveldb_transaction, names_key, object_store_id);
return s;
}
leveldb::Status IndexedDBBackingStore::DeleteObjectStore(
IndexedDBBackingStore::Transaction* transaction,
int64 database_id,
int64 object_store_id) {
IDB_TRACE("IndexedDBBackingStore::DeleteObjectStore");
if (!KeyPrefix::ValidIds(database_id, object_store_id))
return InvalidDBKeyStatus();
LevelDBTransaction* leveldb_transaction = transaction->transaction();
base::string16 object_store_name;
bool found = false;
leveldb::Status s =
GetString(leveldb_transaction,
ObjectStoreMetaDataKey::Encode(
database_id, object_store_id, ObjectStoreMetaDataKey::NAME),
&object_store_name,
&found);
if (!s.ok()) {
INTERNAL_READ_ERROR_UNTESTED(DELETE_OBJECT_STORE);
return s;
}
if (!found) {
INTERNAL_CONSISTENCY_ERROR_UNTESTED(DELETE_OBJECT_STORE);
return InternalInconsistencyStatus();
}
s = DeleteRange(
leveldb_transaction,
ObjectStoreMetaDataKey::Encode(database_id, object_store_id, 0),
ObjectStoreMetaDataKey::EncodeMaxKey(database_id, object_store_id));
if (s.ok()) {
leveldb_transaction->Remove(
ObjectStoreNamesKey::Encode(database_id, object_store_name));
s = DeleteRange(
leveldb_transaction,
IndexFreeListKey::Encode(database_id, object_store_id, 0),
IndexFreeListKey::EncodeMaxKey(database_id, object_store_id));
}
if (s.ok()) {
s = DeleteRange(
leveldb_transaction,
IndexMetaDataKey::Encode(database_id, object_store_id, 0, 0),
IndexMetaDataKey::EncodeMaxKey(database_id, object_store_id));
}
if (!s.ok()) {
INTERNAL_WRITE_ERROR_UNTESTED(DELETE_OBJECT_STORE);
return s;
}
return ClearObjectStore(transaction, database_id, object_store_id);
}
leveldb::Status IndexedDBBackingStore::GetRecord(
IndexedDBBackingStore::Transaction* transaction,
int64 database_id,
int64 object_store_id,
const IndexedDBKey& key,
IndexedDBValue* record) {
IDB_TRACE("IndexedDBBackingStore::GetRecord");
if (!KeyPrefix::ValidIds(database_id, object_store_id))
return InvalidDBKeyStatus();
LevelDBTransaction* leveldb_transaction = transaction->transaction();
const std::string leveldb_key =
ObjectStoreDataKey::Encode(database_id, object_store_id, key);
std::string data;
record->clear();
bool found = false;
leveldb::Status s = leveldb_transaction->Get(leveldb_key, &data, &found);
if (!s.ok()) {
INTERNAL_READ_ERROR(GET_RECORD);
return s;
}
if (!found)
return s;
if (data.empty()) {
INTERNAL_READ_ERROR_UNTESTED(GET_RECORD);
return leveldb::Status::NotFound("Record contained no data");
}
int64 version;
StringPiece slice(data);
if (!DecodeVarInt(&slice, &version)) {
INTERNAL_READ_ERROR_UNTESTED(GET_RECORD);
return InternalInconsistencyStatus();
}
record->bits = slice.as_string();
return s;
}
WARN_UNUSED_RESULT static leveldb::Status GetNewVersionNumber(
LevelDBTransaction* transaction,
int64 database_id,
int64 object_store_id,
int64* new_version_number) {
const std::string last_version_key = ObjectStoreMetaDataKey::Encode(
database_id, object_store_id, ObjectStoreMetaDataKey::LAST_VERSION);
*new_version_number = -1;
int64 last_version = -1;
bool found = false;
leveldb::Status s =
GetInt(transaction, last_version_key, &last_version, &found);
if (!s.ok()) {
INTERNAL_READ_ERROR_UNTESTED(GET_NEW_VERSION_NUMBER);
return s;
}
if (!found)
last_version = 0;
DCHECK_GE(last_version, 0);
int64 version = last_version + 1;
PutInt(transaction, last_version_key, version);
// TODO(jsbell): Think about how we want to handle the overflow scenario.
DCHECK(version > last_version);
*new_version_number = version;
return s;
}
leveldb::Status IndexedDBBackingStore::PutRecord(
IndexedDBBackingStore::Transaction* transaction,
int64 database_id,
int64 object_store_id,
const IndexedDBKey& key,
IndexedDBValue& value,
ScopedVector<webkit_blob::BlobDataHandle>* handles,
RecordIdentifier* record_identifier) {
IDB_TRACE("IndexedDBBackingStore::PutRecord");
if (!KeyPrefix::ValidIds(database_id, object_store_id))
return InvalidDBKeyStatus();
DCHECK(key.IsValid());
LevelDBTransaction* leveldb_transaction = transaction->transaction();
int64 version = -1;
leveldb::Status s = GetNewVersionNumber(
leveldb_transaction, database_id, object_store_id, &version);
if (!s.ok())
return s;
DCHECK_GE(version, 0);
const std::string object_store_data_key =
ObjectStoreDataKey::Encode(database_id, object_store_id, key);
std::string v;
EncodeVarInt(version, &v);
v.append(value.bits);
leveldb_transaction->Put(object_store_data_key, &v);
transaction->PutBlobInfo(database_id,
object_store_id,
object_store_data_key,
&value.blob_info,
handles);
DCHECK(!handles->size());
const std::string exists_entry_key =
ExistsEntryKey::Encode(database_id, object_store_id, key);
std::string version_encoded;
EncodeInt(version, &version_encoded);
leveldb_transaction->Put(exists_entry_key, &version_encoded);
std::string key_encoded;
EncodeIDBKey(key, &key_encoded);
record_identifier->Reset(key_encoded, version);
return s;
}
leveldb::Status IndexedDBBackingStore::ClearObjectStore(
IndexedDBBackingStore::Transaction* transaction,
int64 database_id,
int64 object_store_id) {
IDB_TRACE("IndexedDBBackingStore::ClearObjectStore");
if (!KeyPrefix::ValidIds(database_id, object_store_id))
return InvalidDBKeyStatus();
const std::string start_key =
KeyPrefix(database_id, object_store_id).Encode();
const std::string stop_key =
KeyPrefix(database_id, object_store_id + 1).Encode();
leveldb::Status s =
DeleteRange(transaction->transaction(), start_key, stop_key);
if (!s.ok())
INTERNAL_WRITE_ERROR(CLEAR_OBJECT_STORE);
return s;
}
leveldb::Status IndexedDBBackingStore::DeleteRecord(
IndexedDBBackingStore::Transaction* transaction,
int64 database_id,
int64 object_store_id,
const RecordIdentifier& record_identifier) {
IDB_TRACE("IndexedDBBackingStore::DeleteRecord");
if (!KeyPrefix::ValidIds(database_id, object_store_id))
return InvalidDBKeyStatus();
LevelDBTransaction* leveldb_transaction = transaction->transaction();
const std::string object_store_data_key = ObjectStoreDataKey::Encode(
database_id, object_store_id, record_identifier.primary_key());
leveldb_transaction->Remove(object_store_data_key);
transaction->PutBlobInfo(
database_id, object_store_id, object_store_data_key, NULL, NULL);
const std::string exists_entry_key = ExistsEntryKey::Encode(
database_id, object_store_id, record_identifier.primary_key());
leveldb_transaction->Remove(exists_entry_key);
return leveldb::Status::OK();
}
leveldb::Status IndexedDBBackingStore::GetKeyGeneratorCurrentNumber(
IndexedDBBackingStore::Transaction* transaction,
int64 database_id,
int64 object_store_id,
int64* key_generator_current_number) {
if (!KeyPrefix::ValidIds(database_id, object_store_id))
return InvalidDBKeyStatus();
LevelDBTransaction* leveldb_transaction = transaction->transaction();
const std::string key_generator_current_number_key =
ObjectStoreMetaDataKey::Encode(
database_id,
object_store_id,
ObjectStoreMetaDataKey::KEY_GENERATOR_CURRENT_NUMBER);
*key_generator_current_number = -1;
std::string data;
bool found = false;
leveldb::Status s =
leveldb_transaction->Get(key_generator_current_number_key, &data, &found);
if (!s.ok()) {
INTERNAL_READ_ERROR_UNTESTED(GET_KEY_GENERATOR_CURRENT_NUMBER);
return s;
}
if (found && !data.empty()) {
StringPiece slice(data);
if (!DecodeInt(&slice, key_generator_current_number) || !slice.empty()) {
INTERNAL_READ_ERROR_UNTESTED(GET_KEY_GENERATOR_CURRENT_NUMBER);
return InternalInconsistencyStatus();
}
return s;
}
// Previously, the key generator state was not stored explicitly
// but derived from the maximum numeric key present in existing
// data. This violates the spec as the data may be cleared but the
// key generator state must be preserved.
// TODO(jsbell): Fix this for all stores on database open?
const std::string start_key =
ObjectStoreDataKey::Encode(database_id, object_store_id, MinIDBKey());
const std::string stop_key =
ObjectStoreDataKey::Encode(database_id, object_store_id, MaxIDBKey());
scoped_ptr<LevelDBIterator> it = leveldb_transaction->CreateIterator();
int64 max_numeric_key = 0;
for (s = it->Seek(start_key);
s.ok() && it->IsValid() && CompareKeys(it->Key(), stop_key) < 0;
s = it->Next()) {
StringPiece slice(it->Key());
ObjectStoreDataKey data_key;
if (!ObjectStoreDataKey::Decode(&slice, &data_key)) {
INTERNAL_READ_ERROR_UNTESTED(GET_KEY_GENERATOR_CURRENT_NUMBER);
return InternalInconsistencyStatus();
}
scoped_ptr<IndexedDBKey> user_key = data_key.user_key();
if (user_key->type() == blink::WebIDBKeyTypeNumber) {
int64 n = static_cast<int64>(user_key->number());
if (n > max_numeric_key)
max_numeric_key = n;
}
}
if (s.ok())
*key_generator_current_number = max_numeric_key + 1;
else
INTERNAL_READ_ERROR_UNTESTED(GET_KEY_GENERATOR_CURRENT_NUMBER);
return s;
}
leveldb::Status IndexedDBBackingStore::MaybeUpdateKeyGeneratorCurrentNumber(
IndexedDBBackingStore::Transaction* transaction,
int64 database_id,
int64 object_store_id,
int64 new_number,
bool check_current) {
if (!KeyPrefix::ValidIds(database_id, object_store_id))
return InvalidDBKeyStatus();
if (check_current) {
int64 current_number;
leveldb::Status s = GetKeyGeneratorCurrentNumber(
transaction, database_id, object_store_id, ¤t_number);
if (!s.ok())
return s;
if (new_number <= current_number)
return s;
}
const std::string key_generator_current_number_key =
ObjectStoreMetaDataKey::Encode(
database_id,
object_store_id,
ObjectStoreMetaDataKey::KEY_GENERATOR_CURRENT_NUMBER);
PutInt(
transaction->transaction(), key_generator_current_number_key, new_number);
return leveldb::Status::OK();
}
leveldb::Status IndexedDBBackingStore::KeyExistsInObjectStore(
IndexedDBBackingStore::Transaction* transaction,
int64 database_id,
int64 object_store_id,
const IndexedDBKey& key,
RecordIdentifier* found_record_identifier,
bool* found) {
IDB_TRACE("IndexedDBBackingStore::KeyExistsInObjectStore");
if (!KeyPrefix::ValidIds(database_id, object_store_id))
return InvalidDBKeyStatus();
*found = false;
const std::string leveldb_key =
ObjectStoreDataKey::Encode(database_id, object_store_id, key);
std::string data;
leveldb::Status s =
transaction->transaction()->Get(leveldb_key, &data, found);
if (!s.ok()) {
INTERNAL_READ_ERROR_UNTESTED(KEY_EXISTS_IN_OBJECT_STORE);
return s;
}
if (!*found)
return leveldb::Status::OK();
if (!data.size()) {
INTERNAL_READ_ERROR_UNTESTED(KEY_EXISTS_IN_OBJECT_STORE);
return InternalInconsistencyStatus();
}
int64 version;
StringPiece slice(data);
if (!DecodeVarInt(&slice, &version))
return InternalInconsistencyStatus();
std::string encoded_key;
EncodeIDBKey(key, &encoded_key);
found_record_identifier->Reset(encoded_key, version);
return s;
}
class IndexedDBBackingStore::Transaction::ChainedBlobWriterImpl
: public IndexedDBBackingStore::Transaction::ChainedBlobWriter {
public:
typedef IndexedDBBackingStore::Transaction::WriteDescriptorVec
WriteDescriptorVec;
ChainedBlobWriterImpl(
int64 database_id,
IndexedDBBackingStore* backingStore,
WriteDescriptorVec& blobs,
scoped_refptr<IndexedDBBackingStore::BlobWriteCallback> callback)
: waiting_for_callback_(false),
database_id_(database_id),
backing_store_(backingStore),
callback_(callback),
aborted_(false) {
blobs_.swap(blobs);
iter_ = blobs_.begin();
WriteNextFile();
}
virtual void set_delegate(scoped_ptr<FileWriterDelegate> delegate) OVERRIDE {
delegate_.reset(delegate.release());
}
virtual void ReportWriteCompletion(bool succeeded,
int64 bytes_written) OVERRIDE {
// TODO(ericu): Check bytes_written against the blob's snapshot value.
DCHECK(waiting_for_callback_);
DCHECK(!succeeded || bytes_written >= 0);
waiting_for_callback_ = false;
if (delegate_.get()) // Only present for Blob, not File.
content::BrowserThread::DeleteSoon(
content::BrowserThread::IO, FROM_HERE, delegate_.release());
if (aborted_) {
self_ref_ = NULL;
return;
}
if (succeeded)
WriteNextFile();
else
callback_->Run(false);
}
virtual void Abort() OVERRIDE {
if (!waiting_for_callback_)
return;
self_ref_ = this;
aborted_ = true;
}
private:
virtual ~ChainedBlobWriterImpl() {}
void WriteNextFile() {
DCHECK(!waiting_for_callback_);
DCHECK(!aborted_);
if (iter_ == blobs_.end()) {
DCHECK(!self_ref_);
callback_->Run(true);
return;
} else {
if (!backing_store_->WriteBlobFile(database_id_, *iter_, this)) {
callback_->Run(false);
return;
}
waiting_for_callback_ = true;
++iter_;
}
}
bool waiting_for_callback_;
scoped_refptr<ChainedBlobWriterImpl> self_ref_;
WriteDescriptorVec blobs_;
WriteDescriptorVec::const_iterator iter_;
int64 database_id_;
IndexedDBBackingStore* backing_store_;
scoped_refptr<IndexedDBBackingStore::BlobWriteCallback> callback_;
scoped_ptr<FileWriterDelegate> delegate_;
bool aborted_;
};
class LocalWriteClosure : public FileWriterDelegate::DelegateWriteCallback,
public base::RefCounted<LocalWriteClosure> {
public:
LocalWriteClosure(IndexedDBBackingStore::Transaction::ChainedBlobWriter*
chained_blob_writer_,
base::TaskRunner* task_runner)
: chained_blob_writer_(chained_blob_writer_),
task_runner_(task_runner),
bytes_written_(-1) {}
void Run(base::File::Error rv,
int64 bytes,
FileWriterDelegate::WriteProgressStatus write_status) {
if (write_status == FileWriterDelegate::SUCCESS_IO_PENDING)
return; // We don't care about progress events.
if (rv == base::File::FILE_OK) {
DCHECK(bytes >= 0);
DCHECK(write_status == FileWriterDelegate::SUCCESS_COMPLETED);
bytes_written_ = bytes;
} else {
DCHECK(write_status == FileWriterDelegate::ERROR_WRITE_STARTED ||
write_status == FileWriterDelegate::ERROR_WRITE_NOT_STARTED);
}
task_runner_->PostTask(
FROM_HERE,
base::Bind(&LocalWriteClosure::callBlobCallbackOnIDBTaskRunner,
this,
write_status == FileWriterDelegate::SUCCESS_COMPLETED));
}
void writeBlobToFileOnIOThread(const FilePath& file_path,
const GURL& blob_url,
net::URLRequestContext* request_context) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
scoped_ptr<fileapi::FileStreamWriter> writer(
fileapi::FileStreamWriter::CreateForLocalFile(
task_runner_, file_path, 0,
fileapi::FileStreamWriter::CREATE_NEW_FILE));
scoped_ptr<FileWriterDelegate> delegate(
new FileWriterDelegate(writer.Pass()));
DCHECK(blob_url.is_valid());
scoped_ptr<net::URLRequest> blob_request(request_context->CreateRequest(
blob_url, net::DEFAULT_PRIORITY, delegate.get(), NULL));
delegate->Start(blob_request.Pass(),
base::Bind(&LocalWriteClosure::Run, this));
chained_blob_writer_->set_delegate(delegate.Pass());
}
private:
virtual ~LocalWriteClosure() {}
friend class base::RefCounted<LocalWriteClosure>;
void callBlobCallbackOnIDBTaskRunner(bool succeeded) {
DCHECK(task_runner_->RunsTasksOnCurrentThread());
chained_blob_writer_->ReportWriteCompletion(succeeded, bytes_written_);
}
IndexedDBBackingStore::Transaction::ChainedBlobWriter* chained_blob_writer_;
base::TaskRunner* task_runner_;
int64 bytes_written_;
};
bool IndexedDBBackingStore::WriteBlobFile(
int64 database_id,
const Transaction::WriteDescriptor& descriptor,
Transaction::ChainedBlobWriter* chained_blob_writer) {
if (!MakeIDBBlobDirectory(blob_path_, database_id, descriptor.key()))
return false;
FilePath path = GetBlobFileName(database_id, descriptor.key());
if (descriptor.is_file()) {
DCHECK(!descriptor.file_path().empty());
if (!base::CopyFile(descriptor.file_path(), path))
return false;
base::File::Info info;
if (base::GetFileInfo(descriptor.file_path(), &info)) {
// TODO(ericu): Validate the snapshot date here. Expand WriteDescriptor
// to include snapshot date and file size, and check both.
if (!base::TouchFile(path, info.last_accessed, info.last_modified)) {
// TODO(ericu): Complain quietly; timestamp's probably not vital.
}
} else {
// TODO(ericu): Complain quietly; timestamp's probably not vital.
}
task_runner_->PostTask(
FROM_HERE,
base::Bind(&Transaction::ChainedBlobWriter::ReportWriteCompletion,
chained_blob_writer,
true,
info.size));
} else {
DCHECK(descriptor.url().is_valid());
scoped_refptr<LocalWriteClosure> write_closure(
new LocalWriteClosure(chained_blob_writer, task_runner_));
content::BrowserThread::PostTask(
content::BrowserThread::IO,
FROM_HERE,
base::Bind(&LocalWriteClosure::writeBlobToFileOnIOThread,
write_closure.get(),
path,
descriptor.url(),
request_context_));
}
return true;
}
void IndexedDBBackingStore::ReportBlobUnused(int64 database_id,
int64 blob_key) {
DCHECK(KeyPrefix::IsValidDatabaseId(database_id));
bool all_blobs = blob_key == DatabaseMetaDataKey::kAllBlobsKey;
DCHECK(all_blobs || DatabaseMetaDataKey::IsValidBlobKey(blob_key));
scoped_refptr<LevelDBTransaction> transaction =
new LevelDBTransaction(db_.get());
std::string live_blob_key = LiveBlobJournalKey::Encode();
BlobJournalType live_blob_journal;
if (!GetBlobJournal(live_blob_key, transaction.get(), &live_blob_journal)
.ok())
return;
DCHECK(live_blob_journal.size());
std::string primary_key = BlobJournalKey::Encode();
BlobJournalType primary_journal;
if (!GetBlobJournal(primary_key, transaction.get(), &primary_journal).ok())
return;
// There are several cases to handle. If blob_key is kAllBlobsKey, we want to
// remove all entries with database_id from the live_blob journal and add only
// kAllBlobsKey to the primary journal. Otherwise if IsValidBlobKey(blob_key)
// and we hit kAllBlobsKey for the right database_id in the journal, we leave
// the kAllBlobsKey entry in the live_blob journal but add the specific blob
// to the primary. Otherwise if IsValidBlobKey(blob_key) and we find a
// matching (database_id, blob_key) tuple, we should move it to the primary
// journal.
BlobJournalType new_live_blob_journal;
for (BlobJournalType::iterator journal_iter = live_blob_journal.begin();
journal_iter != live_blob_journal.end();
++journal_iter) {
int64 current_database_id = journal_iter->first;
int64 current_blob_key = journal_iter->second;
bool current_all_blobs =
current_blob_key == DatabaseMetaDataKey::kAllBlobsKey;
DCHECK(KeyPrefix::IsValidDatabaseId(current_database_id) ||
current_all_blobs);
if (current_database_id == database_id &&
(all_blobs || current_all_blobs || blob_key == current_blob_key)) {
if (!all_blobs) {
primary_journal.push_back(
std::make_pair(database_id, current_blob_key));
if (current_all_blobs)
new_live_blob_journal.push_back(*journal_iter);
new_live_blob_journal.insert(new_live_blob_journal.end(),
++journal_iter,
live_blob_journal.end()); // All the rest.
break;
}
} else {
new_live_blob_journal.push_back(*journal_iter);
}
}
if (all_blobs) {
primary_journal.push_back(
std::make_pair(database_id, DatabaseMetaDataKey::kAllBlobsKey));
}
UpdatePrimaryJournalWithBlobList(transaction.get(), primary_journal);
UpdateLiveBlobJournalWithBlobList(transaction.get(), new_live_blob_journal);
transaction->Commit();
// We could just do the deletions/cleaning here, but if there are a lot of
// blobs about to be garbage collected, it'd be better to wait and do them all
// at once.
StartJournalCleaningTimer();
}
// The this reference is a raw pointer that's declared Unretained inside the
// timer code, so this won't confuse IndexedDBFactory's check for
// HasLastBackingStoreReference. It's safe because if the backing store is
// deleted, the timer will automatically be canceled on destruction.
void IndexedDBBackingStore::StartJournalCleaningTimer() {
journal_cleaning_timer_.Start(
FROM_HERE,
base::TimeDelta::FromSeconds(5),
this,
&IndexedDBBackingStore::CleanPrimaryJournalIgnoreReturn);
}
// This assumes a file path of dbId/second-to-LSB-of-counter/counter.
FilePath IndexedDBBackingStore::GetBlobFileName(int64 database_id, int64 key) {
return GetBlobFileNameForKey(blob_path_, database_id, key);
}
static bool CheckIndexAndMetaDataKey(const LevelDBIterator* it,
const std::string& stop_key,
int64 index_id,
unsigned char meta_data_type) {
if (!it->IsValid() || CompareKeys(it->Key(), stop_key) >= 0)
return false;
StringPiece slice(it->Key());
IndexMetaDataKey meta_data_key;
bool ok = IndexMetaDataKey::Decode(&slice, &meta_data_key);
DCHECK(ok);
if (meta_data_key.IndexId() != index_id)
return false;
if (meta_data_key.meta_data_type() != meta_data_type)
return false;
return true;
}
// TODO(jsbell): This should do some error handling rather than plowing ahead
// when bad data is encountered.
leveldb::Status IndexedDBBackingStore::GetIndexes(
int64 database_id,
int64 object_store_id,
IndexedDBObjectStoreMetadata::IndexMap* indexes) {
IDB_TRACE("IndexedDBBackingStore::GetIndexes");
if (!KeyPrefix::ValidIds(database_id, object_store_id))
return InvalidDBKeyStatus();
const std::string start_key =
IndexMetaDataKey::Encode(database_id, object_store_id, 0, 0);
const std::string stop_key =
IndexMetaDataKey::Encode(database_id, object_store_id + 1, 0, 0);
DCHECK(indexes->empty());
scoped_ptr<LevelDBIterator> it = db_->CreateIterator();
leveldb::Status s = it->Seek(start_key);
while (s.ok() && it->IsValid() && CompareKeys(it->Key(), stop_key) < 0) {
StringPiece slice(it->Key());
IndexMetaDataKey meta_data_key;
bool ok = IndexMetaDataKey::Decode(&slice, &meta_data_key);
DCHECK(ok);
if (meta_data_key.meta_data_type() != IndexMetaDataKey::NAME) {
INTERNAL_CONSISTENCY_ERROR_UNTESTED(GET_INDEXES);
// Possible stale metadata due to http://webkit.org/b/85557 but don't fail
// the load.
s = it->Next();
if (!s.ok())
break;
continue;
}
// TODO(jsbell): Do this by direct key lookup rather than iteration, to
// simplify.
int64 index_id = meta_data_key.IndexId();
base::string16 index_name;
{
StringPiece slice(it->Value());
if (!DecodeString(&slice, &index_name) || !slice.empty())
INTERNAL_CONSISTENCY_ERROR_UNTESTED(GET_INDEXES);
}
s = it->Next(); // unique flag
if (!s.ok())
break;
if (!CheckIndexAndMetaDataKey(
it.get(), stop_key, index_id, IndexMetaDataKey::UNIQUE)) {
INTERNAL_CONSISTENCY_ERROR_UNTESTED(GET_INDEXES);
break;
}
bool index_unique;
{
StringPiece slice(it->Value());
if (!DecodeBool(&slice, &index_unique) || !slice.empty())
INTERNAL_CONSISTENCY_ERROR_UNTESTED(GET_INDEXES);
}
s = it->Next(); // key_path
if (!s.ok())
break;
if (!CheckIndexAndMetaDataKey(
it.get(), stop_key, index_id, IndexMetaDataKey::KEY_PATH)) {
INTERNAL_CONSISTENCY_ERROR_UNTESTED(GET_INDEXES);
break;
}
IndexedDBKeyPath key_path;
{
StringPiece slice(it->Value());
if (!DecodeIDBKeyPath(&slice, &key_path) || !slice.empty())
INTERNAL_CONSISTENCY_ERROR_UNTESTED(GET_INDEXES);
}
s = it->Next(); // [optional] multi_entry flag
if (!s.ok())
break;
bool index_multi_entry = false;
if (CheckIndexAndMetaDataKey(
it.get(), stop_key, index_id, IndexMetaDataKey::MULTI_ENTRY)) {
StringPiece slice(it->Value());
if (!DecodeBool(&slice, &index_multi_entry) || !slice.empty())
INTERNAL_CONSISTENCY_ERROR_UNTESTED(GET_INDEXES);
s = it->Next();
if (!s.ok())
break;
}
(*indexes)[index_id] = IndexedDBIndexMetadata(
index_name, index_id, key_path, index_unique, index_multi_entry);
}
if (!s.ok())
INTERNAL_READ_ERROR_UNTESTED(GET_INDEXES);
return s;
}
bool IndexedDBBackingStore::RemoveBlobFile(int64 database_id, int64 key) {
FilePath fileName = GetBlobFileName(database_id, key);
return base::DeleteFile(fileName, false);
}
bool IndexedDBBackingStore::RemoveBlobDirectory(int64 database_id) {
FilePath dirName = GetBlobDirectoryName(blob_path_, database_id);
return base::DeleteFile(dirName, true);
}
leveldb::Status IndexedDBBackingStore::CleanUpBlobJournal(
const std::string& level_db_key) {
scoped_refptr<LevelDBTransaction> journal_transaction =
new LevelDBTransaction(db_.get());
BlobJournalType journal;
leveldb::Status s =
GetBlobJournal(level_db_key, journal_transaction.get(), &journal);
if (!s.ok())
return s;
if (!journal.size())
return leveldb::Status::OK();
BlobJournalType::iterator journal_iter;
for (journal_iter = journal.begin(); journal_iter != journal.end();
++journal_iter) {
int64 database_id = journal_iter->first;
int64 blob_key = journal_iter->second;
DCHECK(KeyPrefix::IsValidDatabaseId(database_id));
if (blob_key == DatabaseMetaDataKey::kAllBlobsKey) {
if (!RemoveBlobDirectory(database_id))
return IOErrorStatus();
} else {
DCHECK(DatabaseMetaDataKey::IsValidBlobKey(blob_key));
if (!RemoveBlobFile(database_id, blob_key))
return IOErrorStatus();
}
}
ClearBlobJournal(journal_transaction.get(), level_db_key);
return journal_transaction->Commit();
}
void IndexedDBBackingStore::CleanPrimaryJournalIgnoreReturn() {
CleanUpBlobJournal(BlobJournalKey::Encode());
}
WARN_UNUSED_RESULT static leveldb::Status SetMaxIndexId(
LevelDBTransaction* transaction,
int64 database_id,
int64 object_store_id,
int64 index_id) {
int64 max_index_id = -1;
const std::string max_index_id_key = ObjectStoreMetaDataKey::Encode(
database_id, object_store_id, ObjectStoreMetaDataKey::MAX_INDEX_ID);
bool found = false;
leveldb::Status s =
GetInt(transaction, max_index_id_key, &max_index_id, &found);
if (!s.ok()) {
INTERNAL_READ_ERROR_UNTESTED(SET_MAX_INDEX_ID);
return s;
}
if (!found)
max_index_id = kMinimumIndexId;
if (index_id <= max_index_id) {
INTERNAL_CONSISTENCY_ERROR_UNTESTED(SET_MAX_INDEX_ID);
return InternalInconsistencyStatus();
}
PutInt(transaction, max_index_id_key, index_id);
return s;
}
leveldb::Status IndexedDBBackingStore::CreateIndex(
IndexedDBBackingStore::Transaction* transaction,
int64 database_id,
int64 object_store_id,
int64 index_id,
const base::string16& name,
const IndexedDBKeyPath& key_path,
bool is_unique,
bool is_multi_entry) {
IDB_TRACE("IndexedDBBackingStore::CreateIndex");
if (!KeyPrefix::ValidIds(database_id, object_store_id, index_id))
return InvalidDBKeyStatus();
LevelDBTransaction* leveldb_transaction = transaction->transaction();
leveldb::Status s = SetMaxIndexId(
leveldb_transaction, database_id, object_store_id, index_id);
if (!s.ok())
return s;
const std::string name_key = IndexMetaDataKey::Encode(
database_id, object_store_id, index_id, IndexMetaDataKey::NAME);
const std::string unique_key = IndexMetaDataKey::Encode(
database_id, object_store_id, index_id, IndexMetaDataKey::UNIQUE);
const std::string key_path_key = IndexMetaDataKey::Encode(
database_id, object_store_id, index_id, IndexMetaDataKey::KEY_PATH);
const std::string multi_entry_key = IndexMetaDataKey::Encode(
database_id, object_store_id, index_id, IndexMetaDataKey::MULTI_ENTRY);
PutString(leveldb_transaction, name_key, name);
PutBool(leveldb_transaction, unique_key, is_unique);
PutIDBKeyPath(leveldb_transaction, key_path_key, key_path);
PutBool(leveldb_transaction, multi_entry_key, is_multi_entry);
return s;
}
leveldb::Status IndexedDBBackingStore::DeleteIndex(
IndexedDBBackingStore::Transaction* transaction,
int64 database_id,
int64 object_store_id,
int64 index_id) {
IDB_TRACE("IndexedDBBackingStore::DeleteIndex");
if (!KeyPrefix::ValidIds(database_id, object_store_id, index_id))
return InvalidDBKeyStatus();
LevelDBTransaction* leveldb_transaction = transaction->transaction();
const std::string index_meta_data_start =
IndexMetaDataKey::Encode(database_id, object_store_id, index_id, 0);
const std::string index_meta_data_end =
IndexMetaDataKey::EncodeMaxKey(database_id, object_store_id, index_id);
leveldb::Status s = DeleteRange(
leveldb_transaction, index_meta_data_start, index_meta_data_end);
if (s.ok()) {
const std::string index_data_start =
IndexDataKey::EncodeMinKey(database_id, object_store_id, index_id);
const std::string index_data_end =
IndexDataKey::EncodeMaxKey(database_id, object_store_id, index_id);
s = DeleteRange(leveldb_transaction, index_data_start, index_data_end);
}
if (!s.ok())
INTERNAL_WRITE_ERROR_UNTESTED(DELETE_INDEX);
return s;
}
leveldb::Status IndexedDBBackingStore::PutIndexDataForRecord(
IndexedDBBackingStore::Transaction* transaction,
int64 database_id,
int64 object_store_id,
int64 index_id,
const IndexedDBKey& key,
const RecordIdentifier& record_identifier) {
IDB_TRACE("IndexedDBBackingStore::PutIndexDataForRecord");
DCHECK(key.IsValid());
if (!KeyPrefix::ValidIds(database_id, object_store_id, index_id))
return InvalidDBKeyStatus();
std::string encoded_key;
EncodeIDBKey(key, &encoded_key);
const std::string index_data_key =
IndexDataKey::Encode(database_id,
object_store_id,
index_id,
encoded_key,
record_identifier.primary_key(),
0);
std::string data;
EncodeVarInt(record_identifier.version(), &data);
data.append(record_identifier.primary_key());
transaction->transaction()->Put(index_data_key, &data);
return leveldb::Status::OK();
}
static bool FindGreatestKeyLessThanOrEqual(LevelDBTransaction* transaction,
const std::string& target,
std::string* found_key,
leveldb::Status& s) {
scoped_ptr<LevelDBIterator> it = transaction->CreateIterator();
s = it->Seek(target);
if (!s.ok())
return false;
if (!it->IsValid()) {
s = it->SeekToLast();
if (!s.ok() || !it->IsValid())
return false;
}
while (CompareIndexKeys(it->Key(), target) > 0) {
s = it->Prev();
if (!s.ok() || !it->IsValid())
return false;
}
do {
*found_key = it->Key().as_string();
// There can be several index keys that compare equal. We want the last one.
s = it->Next();
} while (s.ok() && it->IsValid() && !CompareIndexKeys(it->Key(), target));
return true;
}
static leveldb::Status VersionExists(LevelDBTransaction* transaction,
int64 database_id,
int64 object_store_id,
int64 version,
const std::string& encoded_primary_key,
bool* exists) {
const std::string key =
ExistsEntryKey::Encode(database_id, object_store_id, encoded_primary_key);
std::string data;
leveldb::Status s = transaction->Get(key, &data, exists);
if (!s.ok()) {
INTERNAL_READ_ERROR_UNTESTED(VERSION_EXISTS);
return s;
}
if (!*exists)
return s;
StringPiece slice(data);
int64 decoded;
if (!DecodeInt(&slice, &decoded) || !slice.empty())
return InternalInconsistencyStatus();
*exists = (decoded == version);
return s;
}
leveldb::Status IndexedDBBackingStore::FindKeyInIndex(
IndexedDBBackingStore::Transaction* transaction,
int64 database_id,
int64 object_store_id,
int64 index_id,
const IndexedDBKey& key,
std::string* found_encoded_primary_key,
bool* found) {
IDB_TRACE("IndexedDBBackingStore::FindKeyInIndex");
DCHECK(KeyPrefix::ValidIds(database_id, object_store_id, index_id));
DCHECK(found_encoded_primary_key->empty());
*found = false;
LevelDBTransaction* leveldb_transaction = transaction->transaction();
const std::string leveldb_key =
IndexDataKey::Encode(database_id, object_store_id, index_id, key);
scoped_ptr<LevelDBIterator> it = leveldb_transaction->CreateIterator();
leveldb::Status s = it->Seek(leveldb_key);
if (!s.ok()) {
INTERNAL_READ_ERROR_UNTESTED(FIND_KEY_IN_INDEX);
return s;
}
for (;;) {
if (!it->IsValid())
return leveldb::Status::OK();
if (CompareIndexKeys(it->Key(), leveldb_key) > 0)
return leveldb::Status::OK();
StringPiece slice(it->Value());
int64 version;
if (!DecodeVarInt(&slice, &version)) {
INTERNAL_READ_ERROR_UNTESTED(FIND_KEY_IN_INDEX);
return InternalInconsistencyStatus();
}
*found_encoded_primary_key = slice.as_string();
bool exists = false;
s = VersionExists(leveldb_transaction,
database_id,
object_store_id,
version,
*found_encoded_primary_key,
&exists);
if (!s.ok())
return s;
if (!exists) {
// Delete stale index data entry and continue.
leveldb_transaction->Remove(it->Key());
s = it->Next();
continue;
}
*found = true;
return s;
}
}
leveldb::Status IndexedDBBackingStore::GetPrimaryKeyViaIndex(
IndexedDBBackingStore::Transaction* transaction,
int64 database_id,
int64 object_store_id,
int64 index_id,
const IndexedDBKey& key,
scoped_ptr<IndexedDBKey>* primary_key) {
IDB_TRACE("IndexedDBBackingStore::GetPrimaryKeyViaIndex");
if (!KeyPrefix::ValidIds(database_id, object_store_id, index_id))
return InvalidDBKeyStatus();
bool found = false;
std::string found_encoded_primary_key;
leveldb::Status s = FindKeyInIndex(transaction,
database_id,
object_store_id,
index_id,
key,
&found_encoded_primary_key,
&found);
if (!s.ok()) {
INTERNAL_READ_ERROR_UNTESTED(GET_PRIMARY_KEY_VIA_INDEX);
return s;
}
if (!found)
return s;
if (!found_encoded_primary_key.size()) {
INTERNAL_READ_ERROR_UNTESTED(GET_PRIMARY_KEY_VIA_INDEX);
return InvalidDBKeyStatus();
}
StringPiece slice(found_encoded_primary_key);
if (DecodeIDBKey(&slice, primary_key) && slice.empty())
return s;
else
return InvalidDBKeyStatus();
}
leveldb::Status IndexedDBBackingStore::KeyExistsInIndex(
IndexedDBBackingStore::Transaction* transaction,
int64 database_id,
int64 object_store_id,
int64 index_id,
const IndexedDBKey& index_key,
scoped_ptr<IndexedDBKey>* found_primary_key,
bool* exists) {
IDB_TRACE("IndexedDBBackingStore::KeyExistsInIndex");
if (!KeyPrefix::ValidIds(database_id, object_store_id, index_id))
return InvalidDBKeyStatus();
*exists = false;
std::string found_encoded_primary_key;
leveldb::Status s = FindKeyInIndex(transaction,
database_id,
object_store_id,
index_id,
index_key,
&found_encoded_primary_key,
exists);
if (!s.ok()) {
INTERNAL_READ_ERROR_UNTESTED(KEY_EXISTS_IN_INDEX);
return s;
}
if (!*exists)
return leveldb::Status::OK();
if (found_encoded_primary_key.empty()) {
INTERNAL_READ_ERROR_UNTESTED(KEY_EXISTS_IN_INDEX);
return InvalidDBKeyStatus();
}
StringPiece slice(found_encoded_primary_key);
if (DecodeIDBKey(&slice, found_primary_key) && slice.empty())
return s;
else
return InvalidDBKeyStatus();
}
IndexedDBBackingStore::Cursor::Cursor(
const IndexedDBBackingStore::Cursor* other)
: transaction_(other->transaction_),
cursor_options_(other->cursor_options_),
current_key_(new IndexedDBKey(*other->current_key_)) {
if (other->iterator_) {
iterator_ = transaction_->CreateIterator();
if (other->iterator_->IsValid()) {
leveldb::Status s = iterator_->Seek(other->iterator_->Key());
// TODO(cmumford): Handle this error (crbug.com/363397)
DCHECK(iterator_->IsValid());
}
}
}
IndexedDBBackingStore::Cursor::Cursor(LevelDBTransaction* transaction,
const CursorOptions& cursor_options)
: transaction_(transaction), cursor_options_(cursor_options) {}
IndexedDBBackingStore::Cursor::~Cursor() {}
bool IndexedDBBackingStore::Cursor::FirstSeek(leveldb::Status* s) {
iterator_ = transaction_->CreateIterator();
if (cursor_options_.forward)
*s = iterator_->Seek(cursor_options_.low_key);
else
*s = iterator_->Seek(cursor_options_.high_key);
if (!s->ok())
return false;
return Continue(0, READY, s);
}
bool IndexedDBBackingStore::Cursor::Advance(uint32 count, leveldb::Status* s) {
*s = leveldb::Status::OK();
while (count--) {
if (!Continue(s))
return false;
}
return true;
}
bool IndexedDBBackingStore::Cursor::Continue(const IndexedDBKey* key,
const IndexedDBKey* primary_key,
IteratorState next_state,
leveldb::Status* s) {
DCHECK(!key || key->IsValid());
DCHECK(!primary_key || primary_key->IsValid());
*s = leveldb::Status::OK();
// TODO(alecflett): avoid a copy here?
IndexedDBKey previous_key = current_key_ ? *current_key_ : IndexedDBKey();
bool first_iteration = true;
// When iterating with PrevNoDuplicate, spec requires that the
// value we yield for each key is the first duplicate in forwards
// order.
IndexedDBKey last_duplicate_key;
bool forward = cursor_options_.forward;
for (;;) {
if (next_state == SEEK) {
// TODO(jsbell): Optimize seeking for reverse cursors as well.
if (first_iteration && key && forward) {
std::string leveldb_key;
if (primary_key) {
leveldb_key = EncodeKey(*key, *primary_key);
} else {
leveldb_key = EncodeKey(*key);
}
*s = iterator_->Seek(leveldb_key);
first_iteration = false;
} else if (forward) {
*s = iterator_->Next();
} else {
*s = iterator_->Prev();
}
if (!s->ok())
return false;
} else {
next_state = SEEK; // for subsequent iterations
}
if (!iterator_->IsValid()) {
if (!forward && last_duplicate_key.IsValid()) {
// We need to walk forward because we hit the end of
// the data.
forward = true;
continue;
}
return false;
}
if (IsPastBounds()) {
if (!forward && last_duplicate_key.IsValid()) {
// We need to walk forward because now we're beyond the
// bounds defined by the cursor.
forward = true;
continue;
}
return false;
}
if (!HaveEnteredRange())
continue;
// The row may not load because there's a stale entry in the
// index. This is not fatal.
if (!LoadCurrentRow())
continue;
if (key) {
if (forward) {
if (primary_key && current_key_->Equals(*key) &&
this->primary_key().IsLessThan(*primary_key))
continue;
if (current_key_->IsLessThan(*key))
continue;
} else {
if (primary_key && key->Equals(*current_key_) &&
primary_key->IsLessThan(this->primary_key()))
continue;
if (key->IsLessThan(*current_key_))
continue;
}
}
if (cursor_options_.unique) {
if (previous_key.IsValid() && current_key_->Equals(previous_key)) {
// We should never be able to walk forward all the way
// to the previous key.
DCHECK(!last_duplicate_key.IsValid());
continue;
}
if (!forward) {
if (!last_duplicate_key.IsValid()) {
last_duplicate_key = *current_key_;
continue;
}
// We need to walk forward because we hit the boundary
// between key ranges.
if (!last_duplicate_key.Equals(*current_key_)) {
forward = true;
continue;
}
continue;
}
}
break;
}
DCHECK(!last_duplicate_key.IsValid() ||
(forward && last_duplicate_key.Equals(*current_key_)));
return true;
}
bool IndexedDBBackingStore::Cursor::HaveEnteredRange() const {
if (cursor_options_.forward) {
int compare = CompareIndexKeys(iterator_->Key(), cursor_options_.low_key);
if (cursor_options_.low_open) {
return compare > 0;
}
return compare >= 0;
}
int compare = CompareIndexKeys(iterator_->Key(), cursor_options_.high_key);
if (cursor_options_.high_open) {
return compare < 0;
}
return compare <= 0;
}
bool IndexedDBBackingStore::Cursor::IsPastBounds() const {
if (cursor_options_.forward) {
int compare = CompareIndexKeys(iterator_->Key(), cursor_options_.high_key);
if (cursor_options_.high_open) {
return compare >= 0;
}
return compare > 0;
}
int compare = CompareIndexKeys(iterator_->Key(), cursor_options_.low_key);
if (cursor_options_.low_open) {
return compare <= 0;
}
return compare < 0;
}
const IndexedDBKey& IndexedDBBackingStore::Cursor::primary_key() const {
return *current_key_;
}
const IndexedDBBackingStore::RecordIdentifier&
IndexedDBBackingStore::Cursor::record_identifier() const {
return record_identifier_;
}
class ObjectStoreKeyCursorImpl : public IndexedDBBackingStore::Cursor {
public:
ObjectStoreKeyCursorImpl(
LevelDBTransaction* transaction,
const IndexedDBBackingStore::Cursor::CursorOptions& cursor_options)
: IndexedDBBackingStore::Cursor(transaction, cursor_options) {}
virtual Cursor* Clone() OVERRIDE {
return new ObjectStoreKeyCursorImpl(this);
}
// IndexedDBBackingStore::Cursor
virtual IndexedDBValue* value() OVERRIDE {
NOTREACHED();
return NULL;
}
virtual bool LoadCurrentRow() OVERRIDE;
protected:
virtual std::string EncodeKey(const IndexedDBKey& key) OVERRIDE {
return ObjectStoreDataKey::Encode(
cursor_options_.database_id, cursor_options_.object_store_id, key);
}
virtual std::string EncodeKey(const IndexedDBKey& key,
const IndexedDBKey& primary_key) OVERRIDE {
NOTREACHED();
return std::string();
}
private:
explicit ObjectStoreKeyCursorImpl(const ObjectStoreKeyCursorImpl* other)
: IndexedDBBackingStore::Cursor(other) {}
};
bool ObjectStoreKeyCursorImpl::LoadCurrentRow() {
StringPiece slice(iterator_->Key());
ObjectStoreDataKey object_store_data_key;
if (!ObjectStoreDataKey::Decode(&slice, &object_store_data_key)) {
INTERNAL_READ_ERROR_UNTESTED(LOAD_CURRENT_ROW);
return false;
}
current_key_ = object_store_data_key.user_key();
int64 version;
slice = StringPiece(iterator_->Value());
if (!DecodeVarInt(&slice, &version)) {
INTERNAL_READ_ERROR_UNTESTED(LOAD_CURRENT_ROW);
return false;
}
// TODO(jsbell): This re-encodes what was just decoded; try and optimize.
std::string encoded_key;
EncodeIDBKey(*current_key_, &encoded_key);
record_identifier_.Reset(encoded_key, version);
return true;
}
class ObjectStoreCursorImpl : public IndexedDBBackingStore::Cursor {
public:
ObjectStoreCursorImpl(
LevelDBTransaction* transaction,
const IndexedDBBackingStore::Cursor::CursorOptions& cursor_options)
: IndexedDBBackingStore::Cursor(transaction, cursor_options) {}
virtual Cursor* Clone() OVERRIDE { return new ObjectStoreCursorImpl(this); }
// IndexedDBBackingStore::Cursor
virtual IndexedDBValue* value() OVERRIDE { return ¤t_value_; }
virtual bool LoadCurrentRow() OVERRIDE;
protected:
virtual std::string EncodeKey(const IndexedDBKey& key) OVERRIDE {
return ObjectStoreDataKey::Encode(
cursor_options_.database_id, cursor_options_.object_store_id, key);
}
virtual std::string EncodeKey(const IndexedDBKey& key,
const IndexedDBKey& primary_key) OVERRIDE {
NOTREACHED();
return std::string();
}
private:
explicit ObjectStoreCursorImpl(const ObjectStoreCursorImpl* other)
: IndexedDBBackingStore::Cursor(other),
current_value_(other->current_value_) {}
IndexedDBValue current_value_;
};
bool ObjectStoreCursorImpl::LoadCurrentRow() {
StringPiece key_slice(iterator_->Key());
ObjectStoreDataKey object_store_data_key;
if (!ObjectStoreDataKey::Decode(&key_slice, &object_store_data_key)) {
INTERNAL_READ_ERROR_UNTESTED(LOAD_CURRENT_ROW);
return false;
}
current_key_ = object_store_data_key.user_key();
int64 version;
StringPiece value_slice = StringPiece(iterator_->Value());
if (!DecodeVarInt(&value_slice, &version)) {
INTERNAL_READ_ERROR_UNTESTED(LOAD_CURRENT_ROW);
return false;
}
// TODO(jsbell): This re-encodes what was just decoded; try and optimize.
std::string encoded_key;
EncodeIDBKey(*current_key_, &encoded_key);
record_identifier_.Reset(encoded_key, version);
current_value_.bits = value_slice.as_string();
return true;
}
class IndexKeyCursorImpl : public IndexedDBBackingStore::Cursor {
public:
IndexKeyCursorImpl(
LevelDBTransaction* transaction,
const IndexedDBBackingStore::Cursor::CursorOptions& cursor_options)
: IndexedDBBackingStore::Cursor(transaction, cursor_options) {}
virtual Cursor* Clone() OVERRIDE { return new IndexKeyCursorImpl(this); }
// IndexedDBBackingStore::Cursor
virtual IndexedDBValue* value() OVERRIDE {
NOTREACHED();
return NULL;
}
virtual const IndexedDBKey& primary_key() const OVERRIDE {
return *primary_key_;
}
virtual const IndexedDBBackingStore::RecordIdentifier& record_identifier()
const OVERRIDE {
NOTREACHED();
return record_identifier_;
}
virtual bool LoadCurrentRow() OVERRIDE;
protected:
virtual std::string EncodeKey(const IndexedDBKey& key) OVERRIDE {
return IndexDataKey::Encode(cursor_options_.database_id,
cursor_options_.object_store_id,
cursor_options_.index_id,
key);
}
virtual std::string EncodeKey(const IndexedDBKey& key,
const IndexedDBKey& primary_key) OVERRIDE {
return IndexDataKey::Encode(cursor_options_.database_id,
cursor_options_.object_store_id,
cursor_options_.index_id,
key,
primary_key);
}
private:
explicit IndexKeyCursorImpl(const IndexKeyCursorImpl* other)
: IndexedDBBackingStore::Cursor(other),
primary_key_(new IndexedDBKey(*other->primary_key_)) {}
scoped_ptr<IndexedDBKey> primary_key_;
};
bool IndexKeyCursorImpl::LoadCurrentRow() {
StringPiece slice(iterator_->Key());
IndexDataKey index_data_key;
if (!IndexDataKey::Decode(&slice, &index_data_key)) {
INTERNAL_READ_ERROR_UNTESTED(LOAD_CURRENT_ROW);
return false;
}
current_key_ = index_data_key.user_key();
DCHECK(current_key_);
slice = StringPiece(iterator_->Value());
int64 index_data_version;
if (!DecodeVarInt(&slice, &index_data_version)) {
INTERNAL_READ_ERROR_UNTESTED(LOAD_CURRENT_ROW);
return false;
}
if (!DecodeIDBKey(&slice, &primary_key_) || !slice.empty()) {
INTERNAL_READ_ERROR_UNTESTED(LOAD_CURRENT_ROW);
return false;
}
std::string primary_leveldb_key =
ObjectStoreDataKey::Encode(index_data_key.DatabaseId(),
index_data_key.ObjectStoreId(),
*primary_key_);
std::string result;
bool found = false;
leveldb::Status s = transaction_->Get(primary_leveldb_key, &result, &found);
if (!s.ok()) {
INTERNAL_READ_ERROR_UNTESTED(LOAD_CURRENT_ROW);
return false;
}
if (!found) {
transaction_->Remove(iterator_->Key());
return false;
}
if (!result.size()) {
INTERNAL_READ_ERROR_UNTESTED(LOAD_CURRENT_ROW);
return false;
}
int64 object_store_data_version;
slice = StringPiece(result);
if (!DecodeVarInt(&slice, &object_store_data_version)) {
INTERNAL_READ_ERROR_UNTESTED(LOAD_CURRENT_ROW);
return false;
}
if (object_store_data_version != index_data_version) {
transaction_->Remove(iterator_->Key());
return false;
}
return true;
}
class IndexCursorImpl : public IndexedDBBackingStore::Cursor {
public:
IndexCursorImpl(
LevelDBTransaction* transaction,
const IndexedDBBackingStore::Cursor::CursorOptions& cursor_options)
: IndexedDBBackingStore::Cursor(transaction, cursor_options) {}
virtual Cursor* Clone() OVERRIDE { return new IndexCursorImpl(this); }
// IndexedDBBackingStore::Cursor
virtual IndexedDBValue* value() OVERRIDE { return ¤t_value_; }
virtual const IndexedDBKey& primary_key() const OVERRIDE {
return *primary_key_;
}
virtual const IndexedDBBackingStore::RecordIdentifier& record_identifier()
const OVERRIDE {
NOTREACHED();
return record_identifier_;
}
virtual bool LoadCurrentRow() OVERRIDE;
protected:
virtual std::string EncodeKey(const IndexedDBKey& key) OVERRIDE {
return IndexDataKey::Encode(cursor_options_.database_id,
cursor_options_.object_store_id,
cursor_options_.index_id,
key);
}
virtual std::string EncodeKey(const IndexedDBKey& key,
const IndexedDBKey& primary_key) OVERRIDE {
return IndexDataKey::Encode(cursor_options_.database_id,
cursor_options_.object_store_id,
cursor_options_.index_id,
key,
primary_key);
}
private:
explicit IndexCursorImpl(const IndexCursorImpl* other)
: IndexedDBBackingStore::Cursor(other),
primary_key_(new IndexedDBKey(*other->primary_key_)),
current_value_(other->current_value_),
primary_leveldb_key_(other->primary_leveldb_key_) {}
scoped_ptr<IndexedDBKey> primary_key_;
IndexedDBValue current_value_;
std::string primary_leveldb_key_;
};
bool IndexCursorImpl::LoadCurrentRow() {
StringPiece slice(iterator_->Key());
IndexDataKey index_data_key;
if (!IndexDataKey::Decode(&slice, &index_data_key)) {
INTERNAL_READ_ERROR_UNTESTED(LOAD_CURRENT_ROW);
return false;
}
current_key_ = index_data_key.user_key();
DCHECK(current_key_);
slice = StringPiece(iterator_->Value());
int64 index_data_version;
if (!DecodeVarInt(&slice, &index_data_version)) {
INTERNAL_READ_ERROR_UNTESTED(LOAD_CURRENT_ROW);
return false;
}
if (!DecodeIDBKey(&slice, &primary_key_)) {
INTERNAL_READ_ERROR_UNTESTED(LOAD_CURRENT_ROW);
return false;
}
primary_leveldb_key_ =
ObjectStoreDataKey::Encode(index_data_key.DatabaseId(),
index_data_key.ObjectStoreId(),
*primary_key_);
std::string result;
bool found = false;
leveldb::Status s = transaction_->Get(primary_leveldb_key_, &result, &found);
if (!s.ok()) {
INTERNAL_READ_ERROR_UNTESTED(LOAD_CURRENT_ROW);
return false;
}
if (!found) {
transaction_->Remove(iterator_->Key());
return false;
}
if (!result.size()) {
INTERNAL_READ_ERROR_UNTESTED(LOAD_CURRENT_ROW);
return false;
}
int64 object_store_data_version;
slice = StringPiece(result);
if (!DecodeVarInt(&slice, &object_store_data_version)) {
INTERNAL_READ_ERROR_UNTESTED(LOAD_CURRENT_ROW);
return false;
}
if (object_store_data_version != index_data_version) {
transaction_->Remove(iterator_->Key());
return false;
}
current_value_.bits = slice.as_string();
return true;
}
bool ObjectStoreCursorOptions(
LevelDBTransaction* transaction,
int64 database_id,
int64 object_store_id,
const IndexedDBKeyRange& range,
indexed_db::CursorDirection direction,
IndexedDBBackingStore::Cursor::CursorOptions* cursor_options) {
cursor_options->database_id = database_id;
cursor_options->object_store_id = object_store_id;
bool lower_bound = range.lower().IsValid();
bool upper_bound = range.upper().IsValid();
cursor_options->forward =
(direction == indexed_db::CURSOR_NEXT_NO_DUPLICATE ||
direction == indexed_db::CURSOR_NEXT);
cursor_options->unique = (direction == indexed_db::CURSOR_NEXT_NO_DUPLICATE ||
direction == indexed_db::CURSOR_PREV_NO_DUPLICATE);
if (!lower_bound) {
cursor_options->low_key =
ObjectStoreDataKey::Encode(database_id, object_store_id, MinIDBKey());
cursor_options->low_open = true; // Not included.
} else {
cursor_options->low_key =
ObjectStoreDataKey::Encode(database_id, object_store_id, range.lower());
cursor_options->low_open = range.lowerOpen();
}
leveldb::Status s;
if (!upper_bound) {
cursor_options->high_key =
ObjectStoreDataKey::Encode(database_id, object_store_id, MaxIDBKey());
if (cursor_options->forward) {
cursor_options->high_open = true; // Not included.
} else {
// We need a key that exists.
// TODO(cmumford): Handle this error (crbug.com/363397)
if (!FindGreatestKeyLessThanOrEqual(transaction,
cursor_options->high_key,
&cursor_options->high_key,
s))
return false;
cursor_options->high_open = false;
}
} else {
cursor_options->high_key =
ObjectStoreDataKey::Encode(database_id, object_store_id, range.upper());
cursor_options->high_open = range.upperOpen();
if (!cursor_options->forward) {
// For reverse cursors, we need a key that exists.
std::string found_high_key;
// TODO(cmumford): Handle this error (crbug.com/363397)
if (!FindGreatestKeyLessThanOrEqual(
transaction, cursor_options->high_key, &found_high_key, s))
return false;
// If the target key should not be included, but we end up with a smaller
// key, we should include that.
if (cursor_options->high_open &&
CompareIndexKeys(found_high_key, cursor_options->high_key) < 0)
cursor_options->high_open = false;
cursor_options->high_key = found_high_key;
}
}
return true;
}
bool IndexCursorOptions(
LevelDBTransaction* transaction,
int64 database_id,
int64 object_store_id,
int64 index_id,
const IndexedDBKeyRange& range,
indexed_db::CursorDirection direction,
IndexedDBBackingStore::Cursor::CursorOptions* cursor_options) {
DCHECK(transaction);
if (!KeyPrefix::ValidIds(database_id, object_store_id, index_id))
return false;
cursor_options->database_id = database_id;
cursor_options->object_store_id = object_store_id;
cursor_options->index_id = index_id;
bool lower_bound = range.lower().IsValid();
bool upper_bound = range.upper().IsValid();
cursor_options->forward =
(direction == indexed_db::CURSOR_NEXT_NO_DUPLICATE ||
direction == indexed_db::CURSOR_NEXT);
cursor_options->unique = (direction == indexed_db::CURSOR_NEXT_NO_DUPLICATE ||
direction == indexed_db::CURSOR_PREV_NO_DUPLICATE);
if (!lower_bound) {
cursor_options->low_key =
IndexDataKey::EncodeMinKey(database_id, object_store_id, index_id);
cursor_options->low_open = false; // Included.
} else {
cursor_options->low_key = IndexDataKey::Encode(
database_id, object_store_id, index_id, range.lower());
cursor_options->low_open = range.lowerOpen();
}
leveldb::Status s;
if (!upper_bound) {
cursor_options->high_key =
IndexDataKey::EncodeMaxKey(database_id, object_store_id, index_id);
cursor_options->high_open = false; // Included.
if (!cursor_options->forward) { // We need a key that exists.
if (!FindGreatestKeyLessThanOrEqual(transaction,
cursor_options->high_key,
&cursor_options->high_key,
s))
return false;
cursor_options->high_open = false;
}
} else {
cursor_options->high_key = IndexDataKey::Encode(
database_id, object_store_id, index_id, range.upper());
cursor_options->high_open = range.upperOpen();
std::string found_high_key;
// Seek to the *last* key in the set of non-unique keys
// TODO(cmumford): Handle this error (crbug.com/363397)
if (!FindGreatestKeyLessThanOrEqual(
transaction, cursor_options->high_key, &found_high_key, s))
return false;
// If the target key should not be included, but we end up with a smaller
// key, we should include that.
if (cursor_options->high_open &&
CompareIndexKeys(found_high_key, cursor_options->high_key) < 0)
cursor_options->high_open = false;
cursor_options->high_key = found_high_key;
}
return true;
}
scoped_ptr<IndexedDBBackingStore::Cursor>
IndexedDBBackingStore::OpenObjectStoreCursor(
IndexedDBBackingStore::Transaction* transaction,
int64 database_id,
int64 object_store_id,
const IndexedDBKeyRange& range,
indexed_db::CursorDirection direction,
leveldb::Status* s) {
IDB_TRACE("IndexedDBBackingStore::OpenObjectStoreCursor");
*s = leveldb::Status::OK();
LevelDBTransaction* leveldb_transaction = transaction->transaction();
IndexedDBBackingStore::Cursor::CursorOptions cursor_options;
if (!ObjectStoreCursorOptions(leveldb_transaction,
database_id,
object_store_id,
range,
direction,
&cursor_options))
return scoped_ptr<IndexedDBBackingStore::Cursor>();
scoped_ptr<ObjectStoreCursorImpl> cursor(
new ObjectStoreCursorImpl(leveldb_transaction, cursor_options));
if (!cursor->FirstSeek(s))
return scoped_ptr<IndexedDBBackingStore::Cursor>();
return cursor.PassAs<IndexedDBBackingStore::Cursor>();
}
scoped_ptr<IndexedDBBackingStore::Cursor>
IndexedDBBackingStore::OpenObjectStoreKeyCursor(
IndexedDBBackingStore::Transaction* transaction,
int64 database_id,
int64 object_store_id,
const IndexedDBKeyRange& range,
indexed_db::CursorDirection direction,
leveldb::Status* s) {
IDB_TRACE("IndexedDBBackingStore::OpenObjectStoreKeyCursor");
*s = leveldb::Status::OK();
LevelDBTransaction* leveldb_transaction = transaction->transaction();
IndexedDBBackingStore::Cursor::CursorOptions cursor_options;
if (!ObjectStoreCursorOptions(leveldb_transaction,
database_id,
object_store_id,
range,
direction,
&cursor_options))
return scoped_ptr<IndexedDBBackingStore::Cursor>();
scoped_ptr<ObjectStoreKeyCursorImpl> cursor(
new ObjectStoreKeyCursorImpl(leveldb_transaction, cursor_options));
if (!cursor->FirstSeek(s))
return scoped_ptr<IndexedDBBackingStore::Cursor>();
return cursor.PassAs<IndexedDBBackingStore::Cursor>();
}
scoped_ptr<IndexedDBBackingStore::Cursor>
IndexedDBBackingStore::OpenIndexKeyCursor(
IndexedDBBackingStore::Transaction* transaction,
int64 database_id,
int64 object_store_id,
int64 index_id,
const IndexedDBKeyRange& range,
indexed_db::CursorDirection direction,
leveldb::Status* s) {
IDB_TRACE("IndexedDBBackingStore::OpenIndexKeyCursor");
*s = leveldb::Status::OK();
LevelDBTransaction* leveldb_transaction = transaction->transaction();
IndexedDBBackingStore::Cursor::CursorOptions cursor_options;
if (!IndexCursorOptions(leveldb_transaction,
database_id,
object_store_id,
index_id,
range,
direction,
&cursor_options))
return scoped_ptr<IndexedDBBackingStore::Cursor>();
scoped_ptr<IndexKeyCursorImpl> cursor(
new IndexKeyCursorImpl(leveldb_transaction, cursor_options));
if (!cursor->FirstSeek(s))
return scoped_ptr<IndexedDBBackingStore::Cursor>();
return cursor.PassAs<IndexedDBBackingStore::Cursor>();
}
scoped_ptr<IndexedDBBackingStore::Cursor>
IndexedDBBackingStore::OpenIndexCursor(
IndexedDBBackingStore::Transaction* transaction,
int64 database_id,
int64 object_store_id,
int64 index_id,
const IndexedDBKeyRange& range,
indexed_db::CursorDirection direction,
leveldb::Status* s) {
IDB_TRACE("IndexedDBBackingStore::OpenIndexCursor");
LevelDBTransaction* leveldb_transaction = transaction->transaction();
IndexedDBBackingStore::Cursor::CursorOptions cursor_options;
if (!IndexCursorOptions(leveldb_transaction,
database_id,
object_store_id,
index_id,
range,
direction,
&cursor_options))
return scoped_ptr<IndexedDBBackingStore::Cursor>();
scoped_ptr<IndexCursorImpl> cursor(
new IndexCursorImpl(leveldb_transaction, cursor_options));
if (!cursor->FirstSeek(s))
return scoped_ptr<IndexedDBBackingStore::Cursor>();
return cursor.PassAs<IndexedDBBackingStore::Cursor>();
}
IndexedDBBackingStore::Transaction::Transaction(
IndexedDBBackingStore* backing_store)
: backing_store_(backing_store), database_id_(-1) {}
IndexedDBBackingStore::Transaction::~Transaction() {
STLDeleteContainerPairSecondPointers(
blob_change_map_.begin(), blob_change_map_.end());
}
void IndexedDBBackingStore::Transaction::Begin() {
IDB_TRACE("IndexedDBBackingStore::Transaction::Begin");
DCHECK(!transaction_.get());
transaction_ = new LevelDBTransaction(backing_store_->db_.get());
}
leveldb::Status IndexedDBBackingStore::Transaction::Commit() {
IDB_TRACE("IndexedDBBackingStore::Transaction::Commit");
DCHECK(transaction_.get());
leveldb::Status s = transaction_->Commit();
transaction_ = NULL;
if (!s.ok())
INTERNAL_WRITE_ERROR_UNTESTED(TRANSACTION_COMMIT_METHOD);
return s;
}
class IndexedDBBackingStore::Transaction::BlobWriteCallbackWrapper
: public IndexedDBBackingStore::BlobWriteCallback {
public:
BlobWriteCallbackWrapper(IndexedDBBackingStore::Transaction* transaction,
scoped_refptr<BlobWriteCallback> callback)
: transaction_(transaction), callback_(callback) {}
virtual void Run(bool succeeded) OVERRIDE {
callback_->Run(succeeded);
transaction_->chained_blob_writer_ = NULL;
}
private:
virtual ~BlobWriteCallbackWrapper() {}
friend class base::RefCounted<IndexedDBBackingStore::BlobWriteCallback>;
IndexedDBBackingStore::Transaction* transaction_;
scoped_refptr<BlobWriteCallback> callback_;
};
void IndexedDBBackingStore::Transaction::WriteNewBlobs(
BlobEntryKeyValuePairVec& new_blob_entries,
WriteDescriptorVec& new_files_to_write,
scoped_refptr<BlobWriteCallback> callback) {
DCHECK_GT(new_files_to_write.size(), 0UL);
DCHECK_GT(database_id_, 0);
BlobEntryKeyValuePairVec::iterator blob_entry_iter;
for (blob_entry_iter = new_blob_entries.begin();
blob_entry_iter != new_blob_entries.end();
++blob_entry_iter) {
// Add the new blob-table entry for each blob to the main transaction, or
// remove any entry that may exist if there's no new one.
if (!blob_entry_iter->second.size())
transaction_->Remove(blob_entry_iter->first.Encode());
else
transaction_->Put(blob_entry_iter->first.Encode(),
&blob_entry_iter->second);
}
// Creating the writer will start it going asynchronously.
chained_blob_writer_ =
new ChainedBlobWriterImpl(database_id_,
backing_store_,
new_files_to_write,
new BlobWriteCallbackWrapper(this, callback));
}
void IndexedDBBackingStore::Transaction::Rollback() {
IDB_TRACE("IndexedDBBackingStore::Transaction::Rollback");
DCHECK(transaction_.get());
if (chained_blob_writer_) {
chained_blob_writer_->Abort();
chained_blob_writer_ = NULL;
}
transaction_->Rollback();
transaction_ = NULL;
}
IndexedDBBackingStore::Transaction::BlobChangeRecord::BlobChangeRecord(
const std::string& key, int64 object_store_id)
: key_(key), object_store_id_(object_store_id) {
}
IndexedDBBackingStore::Transaction::BlobChangeRecord::~BlobChangeRecord() {
}
void IndexedDBBackingStore::Transaction::BlobChangeRecord::SetBlobInfo(
std::vector<IndexedDBBlobInfo>* blob_info) {
blob_info_.clear();
if (blob_info)
blob_info_.swap(*blob_info);
}
void IndexedDBBackingStore::Transaction::BlobChangeRecord::SetHandles(
ScopedVector<webkit_blob::BlobDataHandle>* handles) {
handles_.clear();
if (handles)
handles_.swap(*handles);
}
// This is storing an info, even if empty, even if the previous key had no blob
// info that we know of. It duplicates a bunch of information stored in the
// leveldb transaction, but only w.r.t. the user keys altered--we don't keep the
// changes to exists or index keys here.
void IndexedDBBackingStore::Transaction::PutBlobInfo(
int64 database_id,
int64 object_store_id,
const std::string& key,
std::vector<IndexedDBBlobInfo>* blob_info,
ScopedVector<webkit_blob::BlobDataHandle>* handles) {
DCHECK_GT(key.size(), 0UL);
if (database_id_ < 0)
database_id_ = database_id;
DCHECK_EQ(database_id_, database_id);
BlobChangeMap::iterator it = blob_change_map_.find(key);
BlobChangeRecord* record = NULL;
if (it == blob_change_map_.end()) {
record = new BlobChangeRecord(key, object_store_id);
blob_change_map_[key] = record;
} else {
record = it->second;
}
DCHECK_EQ(record->object_store_id(), object_store_id);
record->SetBlobInfo(blob_info);
record->SetHandles(handles);
DCHECK(!handles || !handles->size());
}
IndexedDBBackingStore::Transaction::WriteDescriptor::WriteDescriptor(
const GURL& url,
int64_t key)
: is_file_(false), url_(url), key_(key) {}
IndexedDBBackingStore::Transaction::WriteDescriptor::WriteDescriptor(
const FilePath& file_path,
int64_t key)
: is_file_(true), file_path_(file_path), key_(key) {}
} // namespace content
|