summaryrefslogtreecommitdiffstats
path: root/dom/storage/SessionStorageCache.cpp
blob: 40f29ebc26c18edee38cf3c511c249924e0daa32 (plain)
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "SessionStorageCache.h"

#include "LocalStorageManager.h"
#include "StorageIPC.h"
#include "mozilla/Assertions.h"
#include "mozilla/dom/LSWriteOptimizer.h"
#include "mozilla/dom/PBackgroundSessionStorageCache.h"
#include "nsDOMString.h"

namespace mozilla::dom {

void SSWriteOptimizer::Enumerate(nsTArray<SSWriteInfo>& aWriteInfos) {
  AssertIsOnOwningThread();

  // The mWriteInfos hash table contains all write infos, but it keeps them in
  // an arbitrary order, which means write infos need to be sorted before being
  // processed.

  nsTArray<NotNull<WriteInfo*>> writeInfos;
  GetSortedWriteInfos(writeInfos);

  for (const auto& writeInfo : writeInfos) {
    switch (writeInfo->GetType()) {
      case WriteInfo::InsertItem: {
        const auto& insertItemInfo =
            static_cast<const InsertItemInfo&>(*writeInfo);

        aWriteInfos.AppendElement(
            SSSetItemInfo{nsString{insertItemInfo.GetKey()},
                          nsString{insertItemInfo.GetValue()}});

        break;
      }

      case WriteInfo::UpdateItem: {
        const auto& updateItemInfo =
            static_cast<const UpdateItemInfo&>(*writeInfo);

        if (updateItemInfo.UpdateWithMove()) {
          // See the comment in LSWriteOptimizer::InsertItem for more details
          // about the UpdateWithMove flag.

          aWriteInfos.AppendElement(
              SSRemoveItemInfo{nsString{updateItemInfo.GetKey()}});
        }

        aWriteInfos.AppendElement(
            SSSetItemInfo{nsString{updateItemInfo.GetKey()},
                          nsString{updateItemInfo.GetValue()}});

        break;
      }

      case WriteInfo::DeleteItem: {
        const auto& deleteItemInfo =
            static_cast<const DeleteItemInfo&>(*writeInfo);

        aWriteInfos.AppendElement(
            SSRemoveItemInfo{nsString{deleteItemInfo.GetKey()}});

        break;
      }

      case WriteInfo::Truncate: {
        aWriteInfos.AppendElement(SSClearInfo{});

        break;
      }

      default:
        MOZ_CRASH("Bad type!");
    }
  }
}

SessionStorageCache::SessionStorageCache()
    : mActor(nullptr), mLoadedOrCloned(false) {}

SessionStorageCache::~SessionStorageCache() {
  if (mActor) {
    mActor->SendDeleteMeInternal();
    MOZ_ASSERT(!mActor, "SendDeleteMeInternal should have cleared!");
  }
}

int64_t SessionStorageCache::GetOriginQuotaUsage() {
  return mDataSet.mOriginQuotaUsage;
}

uint32_t SessionStorageCache::Length() { return mDataSet.mKeys.Count(); }

void SessionStorageCache::Key(uint32_t aIndex, nsAString& aResult) {
  aResult.SetIsVoid(true);
  for (auto iter = mDataSet.mKeys.ConstIter(); !iter.Done(); iter.Next()) {
    if (aIndex == 0) {
      aResult = iter.Key();
      return;
    }
    aIndex--;
  }
}

void SessionStorageCache::GetItem(const nsAString& aKey, nsAString& aResult) {
  // not using AutoString since we don't want to copy buffer to result
  nsString value;
  if (!mDataSet.mKeys.Get(aKey, &value)) {
    SetDOMStringToNull(value);
  }
  aResult = value;
}

void SessionStorageCache::GetKeys(nsTArray<nsString>& aKeys) {
  AppendToArray(aKeys, mDataSet.mKeys.Keys());
}

nsresult SessionStorageCache::SetItem(const nsAString& aKey,
                                      const nsAString& aValue,
                                      nsString& aOldValue,
                                      bool aRecordWriteInfo) {
  int64_t delta = 0;

  if (!mDataSet.mKeys.Get(aKey, &aOldValue)) {
    SetDOMStringToNull(aOldValue);

    // We only consider key size if the key doesn't exist before.
    delta = static_cast<int64_t>(aKey.Length());
  }

  delta += static_cast<int64_t>(aValue.Length()) -
           static_cast<int64_t>(aOldValue.Length());

  if (aValue == aOldValue &&
      DOMStringIsNull(aValue) == DOMStringIsNull(aOldValue)) {
    return NS_SUCCESS_DOM_NO_OPERATION;
  }

  if (!mDataSet.ProcessUsageDelta(delta)) {
    return NS_ERROR_DOM_QUOTA_EXCEEDED_ERR;
  }

  if (aRecordWriteInfo && XRE_IsContentProcess()) {
    if (DOMStringIsNull(aOldValue)) {
      mDataSet.mWriteOptimizer.InsertItem(aKey, aValue);
    } else {
      mDataSet.mWriteOptimizer.UpdateItem(aKey, aValue);
    }
  }

  mDataSet.mKeys.InsertOrUpdate(aKey, nsString(aValue));
  return NS_OK;
}

nsresult SessionStorageCache::RemoveItem(const nsAString& aKey,
                                         nsString& aOldValue,
                                         bool aRecordWriteInfo) {
  if (!mDataSet.mKeys.Get(aKey, &aOldValue)) {
    return NS_SUCCESS_DOM_NO_OPERATION;
  }

  // Recalculate the cached data size
  mDataSet.ProcessUsageDelta(-(static_cast<int64_t>(aOldValue.Length()) +
                               static_cast<int64_t>(aKey.Length())));

  if (aRecordWriteInfo && XRE_IsContentProcess()) {
    mDataSet.mWriteOptimizer.DeleteItem(aKey);
  }

  mDataSet.mKeys.Remove(aKey);
  return NS_OK;
}

void SessionStorageCache::Clear(bool aByUserInteraction,
                                bool aRecordWriteInfo) {
  mDataSet.ProcessUsageDelta(-mDataSet.mOriginQuotaUsage);

  if (aRecordWriteInfo && XRE_IsContentProcess()) {
    mDataSet.mWriteOptimizer.Truncate();
  }

  mDataSet.mKeys.Clear();
}

void SessionStorageCache::ResetWriteInfos() {
  mDataSet.mWriteOptimizer.Reset();
}

already_AddRefed<SessionStorageCache> SessionStorageCache::Clone() const {
  RefPtr<SessionStorageCache> cache = new SessionStorageCache();

  cache->mDataSet.mOriginQuotaUsage = mDataSet.mOriginQuotaUsage;
  for (const auto& keyEntry : mDataSet.mKeys) {
    cache->mDataSet.mKeys.InsertOrUpdate(keyEntry.GetKey(), keyEntry.GetData());
    cache->mDataSet.mWriteOptimizer.InsertItem(keyEntry.GetKey(),
                                               keyEntry.GetData());
  }

  return cache.forget();
}

nsTArray<SSSetItemInfo> SessionStorageCache::SerializeData() {
  nsTArray<SSSetItemInfo> data;
  for (const auto& keyEntry : mDataSet.mKeys) {
    data.EmplaceBack(nsString{keyEntry.GetKey()}, keyEntry.GetData());
  }
  return data;
}

nsTArray<SSWriteInfo> SessionStorageCache::SerializeWriteInfos() {
  nsTArray<SSWriteInfo> writeInfos;
  mDataSet.mWriteOptimizer.Enumerate(writeInfos);
  return writeInfos;
}

void SessionStorageCache::DeserializeData(
    const nsTArray<SSSetItemInfo>& aData) {
  Clear(false, /* aRecordWriteInfo */ false);
  for (const auto& keyValuePair : aData) {
    nsString oldValue;
    SetItem(keyValuePair.key(), keyValuePair.value(), oldValue, false);
  }
}

void SessionStorageCache::DeserializeWriteInfos(
    const nsTArray<SSWriteInfo>& aInfos) {
  for (const auto& writeInfo : aInfos) {
    switch (writeInfo.type()) {
      case SSWriteInfo::TSSSetItemInfo: {
        const SSSetItemInfo& info = writeInfo.get_SSSetItemInfo();

        nsString oldValue;
        SetItem(info.key(), info.value(), oldValue,
                /* aRecordWriteInfo */ false);

        break;
      }

      case SSWriteInfo::TSSRemoveItemInfo: {
        const SSRemoveItemInfo& info = writeInfo.get_SSRemoveItemInfo();

        nsString oldValue;
        RemoveItem(info.key(), oldValue,
                   /* aRecordWriteInfo */ false);

        break;
      }

      case SSWriteInfo::TSSClearInfo: {
        Clear(false, /* aRecordWriteInfo */ false);

        break;
      }

      default:
        MOZ_CRASH("Should never get here!");
    }
  }
}

void SessionStorageCache::SetActor(SessionStorageCacheChild* aActor) {
  AssertIsOnMainThread();
  MOZ_ASSERT(aActor);
  MOZ_ASSERT(!mActor);

  mActor = aActor;
}

void SessionStorageCache::ClearActor() {
  AssertIsOnMainThread();
  MOZ_ASSERT(mActor);

  mActor = nullptr;
}

bool SessionStorageCache::DataSet::ProcessUsageDelta(int64_t aDelta) {
  // Check limit per this origin
  uint64_t newOriginUsage = mOriginQuotaUsage + aDelta;
  if (aDelta > 0 && newOriginUsage > LocalStorageManager::GetOriginQuota()) {
    return false;
  }

  // Update size in our data set
  mOriginQuotaUsage = newOriginUsage;
  return true;
}

}  // namespace mozilla::dom