aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/tensorboard/components/tf_storage/storage.ts
blob: bb183d1d5974b5d0011e1e3597a61e408ce3604b (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
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
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
import * as _ from 'lodash';
import {getFakeHash, setFakeHash, TABS, useHash} from '../tf_globals/globals';


/* tslint:disable:no-namespace variable-name */
/**
 * The Storage Module provides storage for URL parameters, and an API for
 * getting and setting TensorBoard's stateful URI.
 *
 * It generates URI components like: events&runPrefix=train*
 * which TensorBoard uses after like localhost:8000/#events&runPrefix=train*
 * to store state in the URI.
 *
 * It also allows saving the values to localStorage for long-term persistance.
 */
type StringDict = {[key: string]: string};

/**
 * A key that users cannot use, since TensorBoard uses this to store info
 * about the active tab.
 */
export let TAB = '__tab__';

/**
 * The name of the property for users to set on a Polymer component
 * in order for its stored properties to be stored in the URI unambiguously.
 * (No need to set this if you want mutliple instances of the component to
 * share URI state)
 *
 * Example:
 * <my-component disambiguator="0"></my-component>
 *
 * The disambiguator should be set to any unique value so that multiple
 * instances of the component can store properties in URI storage.
 *
 * Because it's hard to dereference this variable in HTML property bindings,
 * it is NOT safe to change the disambiguator string without find+replace
 * across the codebase.
 */
export let DISAMBIGUATOR = 'disambiguator';

/**
 * Return a string stored in URI or localStorage.
 * Undefined if not found.
 */
export function getString(key: string, useLocalStorage: boolean): string {
  if (useLocalStorage) {
    return window.localStorage.getItem(key);
  } else {
    return _componentToDict(_readComponent())[key];
  }
}

/**
 * Set a string in URI or localStorage.
 */
export function setString(
    key: string, value: string, useLocalStorage: boolean) {
  if (useLocalStorage) {
    window.localStorage.setItem(key, value);
  } else {
    const items = _componentToDict(_readComponent());
    items[key] = value;
    _writeComponent(_dictToComponent(items));
  }
}

/**
 * Return a boolean stored in stored in URI or localStorage.
 * Undefined if not found.
 */
export function getBoolean(key: string, useLocalStorage: boolean): boolean {
  const item = getString(key, useLocalStorage);
  return item === 'true' ? true : item === 'false' ? false : undefined;
}

/**
 * Store a boolean in URI or localStorage.
 */
export function setBoolean(
    key: string, value: boolean, useLocalStorage = false) {
  setString(key, value.toString(), useLocalStorage);
}

/**
 * Return a number stored in stored in URI or localStorage.
 * Undefined if not found.
 */
export function getNumber(key: string, useLocalStorage: boolean): number {
  const item = getString(key, useLocalStorage);
  return item === undefined ? undefined : +item;
}

/**
 * Store a number in URI or localStorage.
 */
export function setNumber(
    key: string, value: number, useLocalStorage: boolean) {
  setString(key, '' + value, useLocalStorage);
}

/**
 * Return an object stored in stored in URI or localStorage.
 * Undefined if not found.
 */
export function getObject(key: string, useLocalStorage: boolean): {} {
  const item = getString(key, useLocalStorage);
  return item === undefined ? undefined : JSON.parse(atob(item));
}

/**
 * Store an object in URI or localStorage.
 */
export function setObject(key: string, value: {}, useLocalStorage: boolean) {
  setString(key, btoa(JSON.stringify(value)), useLocalStorage);
}

/**
 * Get a unique storage name for a (Polymer component, propertyName) tuple.
 *
 * DISAMBIGUATOR must be set on the component, if other components use the
 * same propertyName.
 */
export function getURIStorageName(
    component: {}, propertyName: string): string {
  const d = component[DISAMBIGUATOR];
  const components = d == null ? [propertyName] : [d, propertyName];
  return components.join('.');
}

/**
 * Return a function that:
 * (1) Initializes a Polymer boolean property with a default value, if its
 *     value is not already set
 * (2) Sets up listener that updates Polymer property on hash change.
 */
export function getBooleanInitializer(
    propertyName: string, defaultVal: boolean,
    useLocalStorage = false): Function {
  return _getInitializer(
      getBoolean, propertyName, defaultVal, useLocalStorage);
}

/**
 * Return a function that:
 * (1) Initializes a Polymer string property with a default value, if its
 *     value is not already set
 * (2) Sets up listener that updates Polymer property on hash change.
 */
export function getStringInitializer(
    propertyName: string, defaultVal: string,
    useLocalStorage = false): Function {
  return _getInitializer(
      getString, propertyName, defaultVal, useLocalStorage);
}

/**
 * Return a function that:
 * (1) Initializes a Polymer number property with a default value, if its
 *     value is not already set
 * (2) Sets up listener that updates Polymer property on hash change.
 */
export function getNumberInitializer(
    propertyName: string, defaultVal: number,
    useLocalStorage = false): Function {
  return _getInitializer(
      getNumber, propertyName, defaultVal, useLocalStorage);
}

/**
 * Return a function that:
 * (1) Initializes a Polymer Object property with a default value, if its
 *     value is not already set
 * (2) Sets up listener that updates Polymer property on hash change.
 *
 * Generates a deep clone of the defaultVal to avoid mutation issues.
 */
export function getObjectInitializer(
    propertyName: string, defaultVal: {}, useLocalStorage = false): Function {
  return _getInitializer(
      getObject, propertyName, defaultVal, useLocalStorage);
}

/**
 * Return a function that updates URIStorage when a string property changes.
 */
export function getBooleanObserver(
    propertyName: string, defaultVal: boolean,
    useLocalStorage = false): Function {
  return _getObserver(
      getBoolean, setBoolean, propertyName, defaultVal, useLocalStorage);
}

/**
 * Return a function that updates URIStorage when a string property changes.
 */
export function getStringObserver(
    propertyName: string, defaultVal: string,
    useLocalStorage = false): Function {
  return _getObserver(
      getString, setString, propertyName, defaultVal, useLocalStorage);
}

/**
 * Return a function that updates URIStorage when a number property changes.
 */
export function getNumberObserver(
    propertyName: string, defaultVal: number,
    useLocalStorage = false): Function {
  return _getObserver(
      getNumber, setNumber, propertyName, defaultVal, useLocalStorage);
}

/**
 * Return a function that updates URIStorage when an object property changes.
 * Generates a deep clone of the defaultVal to avoid mutation issues.
 */
export function getObjectObserver(
    propertyName: string, defaultVal: {}, useLocalStorage = false): Function {
  const clone = _.cloneDeep(defaultVal);
  return _getObserver(
      getObject, setObject, propertyName, clone, useLocalStorage);
}

/**
 * Read component from URI (e.g. returns "events&runPrefix=train*").
 */
function _readComponent(): string {
  return useHash() ? window.location.hash.slice(1) : getFakeHash();
}

/**
 * Write component to URI.
 */
function _writeComponent(component: string) {
  if (useHash()) {
    window.location.hash = component;
  } else {
    setFakeHash(component);
  }
}

/**
 * Convert dictionary of strings into a URI Component.
 * All key value entries get added as key value pairs in the component,
 * with the exception of a key with the TAB value, which if present
 * gets prepended to the URI Component string for backwards comptability
 * reasons.
 */
function _dictToComponent(items: StringDict): string {
  let component = '';

  // Add the tab name e.g. 'events', 'images', 'histograms' as a prefix
  // for backwards compatbility.
  if (items[TAB] !== undefined) {
    component += items[TAB];
  }

  // Join other strings with &key=value notation
  const nonTab = _.pairs(items)
                   .filter((pair) =>  pair[0] !== TAB)
                   .map((pair) => {
                     return encodeURIComponent(pair[0]) + '=' +
                         encodeURIComponent(pair[1]);
                   })
                   .join('&');

  return nonTab.length > 0 ? (component + '&' + nonTab) : component;
}

/**
 * Convert a URI Component into a dictionary of strings.
 * Component should consist of key-value pairs joined by a delimiter
 * with the exception of the tabName.
 * Returns dict consisting of all key-value pairs and
 * dict[TAB] = tabName
 */
function _componentToDict(component: string): StringDict {
  const items = {} as StringDict;

  const tokens = component.split('&');
  tokens.forEach((token) => {
    const kv = token.split('=');
    // Special backwards compatibility for URI components like #events
    if (kv.length === 1 && _.contains(TABS, kv[0])) {
      items[TAB] = kv[0];
    } else if (kv.length === 2) {
      items[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
    }
  });
  return items;
}

/**
 * Return a function that:
 * (1) Initializes a Polymer property with a default value, if its
 *     value is not already set
 * (2) Sets up listener that updates Polymer property on hash change.
 */
function _getInitializer<T>(
    get: (name: string, useLocalStorage: boolean) => T, propertyName: string,
    defaultVal: T, useLocalStorage): Function {
  return function() {
    const URIStorageName = getURIStorageName(this, propertyName);
    // setComponentValue will be called every time the hash changes, and is
    // responsible for ensuring that new state in the hash will be propagated
    // to the component with that property.
    // It is important that this function does not re-assign needlessly,
    // to avoid Polymer observer churn.
    const setComponentValue = () => {
      const uriValue = get(URIStorageName, false);
      const currentValue = this[propertyName];
      // if uriValue is undefined, we will ensure that the property has the
      // default value
      if (uriValue === undefined) {
        let valueToSet: T;
        // if we are using localStorage, we will set the value to the value
        // from localStorage. Then, the corresponding observer will proxy
        // the localStorage value into URI storage.
        // in this way, localStorage takes precedence over the default val
        // but not over the URI value.
        if (useLocalStorage) {
          const useLocalStorageValue = get(URIStorageName, true);
          valueToSet = useLocalStorageValue === undefined ?
              defaultVal :
              useLocalStorageValue;
        } else {
          valueToSet = defaultVal;
        }
        if (!_.isEqual(currentValue, valueToSet)) {
          // If we don't have an explicit URI value, then we need to ensure
          // the property value is equal to the default value.
          // We will assign a clone rather than the canonical default, because
          // the component receiving this property may mutate it, and we need
          // to keep a pristine copy of the default.
          this[propertyName] = _.clone(valueToSet);
        }
        // In this case, we have an explicit URI value, so we will ensure that
        // the component has an equivalent value.
      } else {
        if (!_.isEqual(uriValue, currentValue)) {
          this[propertyName] = uriValue;
        }
      }
    };
    // Set the value on the property.
    setComponentValue();
    // Update it when the hashchanges.
    window.addEventListener('hashchange', setComponentValue);
  };
}

/**
 * Return a function that updates URIStorage when a property changes.
 */
function _getObserver<T>(
    get: (name: string, useLocalStorage: boolean) => T,
    set: (name: string, newVal: T, useLocalStorage: boolean) => void,
    propertyName: string, defaultVal: T, useLocalStorage: boolean): Function {
  return function() {
    const URIStorageName = getURIStorageName(this, propertyName);
    const newVal = this[propertyName];
    // if this is a localStorage property, we always synchronize the value
    // in localStorage to match the one currently in the URI.
    if (useLocalStorage) {
      set(URIStorageName, newVal, true);
    }
    if (!_.isEqual(newVal, get(URIStorageName, false))) {
      if (_.isEqual(newVal, defaultVal)) {
        _unsetFromURI(URIStorageName);
      } else {
        set(URIStorageName, newVal, false);
      }
    }
  };
}

/**
 * Delete a key from the URI.
 */
function _unsetFromURI(key) {
  const items = _componentToDict(_readComponent());
  delete items[key];
  _writeComponent(_dictToComponent(items));
}