]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/CacheEntryBase.java
Merge "Move debugging options under DevelopmentKeys"
[simantics/platform.git] / bundles / org.simantics.db.impl / src / org / simantics / db / impl / query / CacheEntryBase.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2018 Association for Decentralized Information Management
3  * in Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.db.impl.query;
13
14 import java.util.ArrayList;
15 import java.util.Iterator;
16
17 import org.simantics.databoard.Bindings;
18 import org.simantics.db.DevelopmentKeys;
19 import org.simantics.db.exception.DatabaseException;
20 import org.simantics.db.impl.graph.ReadGraphImpl;
21 import org.simantics.db.impl.procedure.InternalProcedure;
22 import org.simantics.utils.Development;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25
26 public abstract class CacheEntryBase<Procedure> extends CacheEntry<Procedure> {
27
28     private static final Logger LOGGER = LoggerFactory.getLogger(CacheEntryBase.class);
29     
30         // Default level is something that is not quite a prospect but still allows for ordering within CacheCollectionResult 
31         public static final short UNDEFINED_LEVEL = 5;
32         
33         public short level = UNDEFINED_LEVEL;
34         public short age = 0;
35         public int GCStatus = 0;
36         
37     final public static CacheEntryBase[] NONE = new CacheEntryBase[0];
38
39         static Object NO_RESULT = new Object() { public String toString() { return "NO_RESULT"; }};
40         static protected Object INVALID_RESULT = new Object() { public String toString() { return "INVALID_RESULT"; }};
41         
42 //      // Just created
43 //    static protected Object FRESH = new Object() { public String toString() { return "CREATED"; }};
44     // Result is computed - no exception
45     static protected Object READY = new Object() { public String toString() { return "READY"; }};
46     // Computation is under way
47     static protected Object PENDING = new Object() { public String toString() { return "PENDING"; }};
48     // Entry is discarded and is waiting for garbage collect
49     static protected Object DISCARDED = new Object() { public String toString() { return "DISCARDED"; }};
50     // The result has been invalidated
51     static protected Object REQUIRES_COMPUTATION = new Object() { public String toString() { return "REFUTED"; }};
52     // The computation has excepted - the exception is in the result
53     static protected Object EXCEPTED = new Object() { public String toString() { return "EXCEPTED"; }};
54
55     // This indicates the status of the entry
56     public Object statusOrException = REQUIRES_COMPUTATION;
57     
58     private CacheEntry p1 = null;
59     private Object p2OrParents = null;
60     
61     private int hash = 0;
62     
63     @Override
64     final public int hashCode() {
65         if(hash == 0) hash = makeHash();
66         return hash;
67     }
68     
69     abstract int makeHash();
70     
71     // This can be tested to see if the result is finished
72     Object result = NO_RESULT;
73     
74     final public boolean isFresh() {
75         return REQUIRES_COMPUTATION == statusOrException;
76     }
77
78     public void setReady() {
79         assert(result != NO_RESULT);
80         statusOrException = READY;
81     }
82
83     @Deprecated
84     final public boolean isReady() {
85         return READY == statusOrException || EXCEPTED == statusOrException;
86     }
87     
88     @Override
89     public void discard() {
90                 if (Development.DEVELOPMENT) {
91                         if(Development.<Boolean>getProperty(DevelopmentKeys.CACHE_ENTRY_STATE, Bindings.BOOLEAN)) {
92                                 System.err.println("[QUERY STATE]: discarded " + this);
93                         }
94                 }
95         statusOrException = DISCARDED;
96     }
97     
98     @Override
99     final public boolean isDiscarded() {
100         return DISCARDED == statusOrException;
101     }
102     
103     @Override
104     final public void refute() {
105                 if (Development.DEVELOPMENT) {
106                         if(Development.<Boolean>getProperty(DevelopmentKeys.CACHE_ENTRY_STATE, Bindings.BOOLEAN)) {
107                                 System.err.println("[QUERY STATE]: refuted " + this);
108                         }
109                 }
110         statusOrException = REQUIRES_COMPUTATION;
111     }
112     
113     @Override
114     final public boolean isRefuted() {
115         return REQUIRES_COMPUTATION == statusOrException;
116     }
117
118     @Override
119     public void except(Throwable throwable) {
120                 if (Development.DEVELOPMENT) {
121                         if(Development.<Boolean>getProperty(DevelopmentKeys.CACHE_ENTRY_STATE, Bindings.BOOLEAN)) {
122                                 System.err.println("[QUERY STATE]: excepted " + this);
123                         }
124                 }
125         if(statusOrException != DISCARDED) {
126                 statusOrException = EXCEPTED;
127                 result = throwable;
128         } else {
129                 LOGGER.warn("Cache entry got excepted status after being discarded: " + getClass().getSimpleName(), throwable);
130                 result = throwable;
131         }
132     }
133     
134     final public void checkAndThrow() throws DatabaseException {
135         if(isExcepted()) {
136             Throwable throwable = (Throwable)result;
137             if(throwable instanceof DatabaseException) throw (DatabaseException)throwable;
138             else throw new DatabaseException(throwable);
139         }
140     }
141     
142     @Override
143     final public boolean isExcepted() {
144         return EXCEPTED == statusOrException;
145     }
146
147     @Override
148     public void setPending() {
149         statusOrException = PENDING;
150     }
151     
152     @Override
153     final public boolean isPending() {
154         return PENDING == statusOrException;
155     }
156     
157     final public boolean requiresComputation() {
158         return REQUIRES_COMPUTATION == statusOrException;
159     }
160     
161     final public boolean assertPending() {
162         boolean result = isPending();
163         if(!result) {
164                 LOGGER.warn("Assertion failed, expected pending, got " + statusOrException);
165         }
166         return result;
167     }
168
169     final public boolean assertNotPending() {
170         boolean result = !isPending();
171         if(!result) {
172                 new Exception(this +  ": Assertion failed, expected not pending, got " + statusOrException).printStackTrace();
173         }
174         return result;
175     }
176
177     final public boolean assertNotDiscarded() {
178         boolean result = !isDiscarded();
179         if(!result) {
180                 new Exception(this +  ": Assertion failed, expected not discarded, got " + statusOrException).printStackTrace();
181         }
182         return result;
183     }
184
185     @Override
186     public void setResult(Object result) {
187         this.result = result;
188     }
189     
190     @SuppressWarnings("unchecked")
191     @Override
192     final public <T> T getResult() {
193         assert(statusOrException != DISCARDED);
194         return (T)result;
195     }
196     
197     @Override
198     public void clearResult(QuerySupport support) {
199         setResult(NO_RESULT);
200     }
201     
202     @Override
203     final public void addParent(CacheEntry entry) {
204          
205         assert(entry != null);
206         
207         if(p1 == entry) {
208                 return;
209         }
210         if(p2OrParents == entry) {
211                 return;
212         }
213         if(p1 == null) {
214                 p1 = entry;
215         } else if(p2OrParents == null) {
216                 p2OrParents = entry;
217         } else if(p2OrParents instanceof QueryIdentityHashSet) {
218             ((QueryIdentityHashSet)p2OrParents).add(entry);
219             ((QueryIdentityHashSet)p2OrParents).purge();
220         } else {
221             CacheEntry tmp = (CacheEntry)p2OrParents;
222             p2OrParents = new QueryIdentityHashSet(2);
223             ((QueryIdentityHashSet)p2OrParents).add(tmp);
224             ((QueryIdentityHashSet)p2OrParents).add(entry);
225         }
226         
227     }
228
229     @Override
230     CacheEntry pruneFirstParents() {
231
232         if(p1 == null) {
233                 // No parents
234                 return null;
235         }
236         
237         if(!p1.isDiscarded()) {
238                 
239                 // First parent is still active
240                 return p1;
241                 
242         } else {
243                 
244                 // Clear p1
245                 p1 = null;
246                 
247                 // First parent is discarded => look for more parents
248                 if(p2OrParents instanceof QueryIdentityHashSet) {
249
250                         QueryIdentityHashSet set = (QueryIdentityHashSet)p2OrParents;
251                         CacheEntry entry = set.removeDiscarded();
252                         if(entry == null) p2OrParents = null;
253                         p1 = entry;
254                         return p1;
255
256                 } else if(p2OrParents instanceof CacheEntry) {
257                         
258                         CacheEntry entry = (CacheEntry)p2OrParents;
259                         if(entry.isDiscarded()) {
260                                 // Second entry is also discarded => all empty
261                                 p2OrParents = null;
262                                 return null;
263                         } else {
264                                 p1 = entry;
265                                 p2OrParents = null;
266                                 return p1;
267                         }
268                         
269                 } else {
270                 
271                         // Nothing left
272                         return null;
273                         
274                 }
275                 
276         }
277         
278     }
279     
280     @Override
281     final public void removeParent(CacheEntry entry) {
282        
283         if(p1 == null) {
284             if(p2OrParents != null) throw new Error("CacheEntryBase.removeParent: corrupted parents (p1 == null, while p2OrParents != null).");
285             else throw new Error("CacheEntryBase.removeParent: no parents.");
286         }
287         if(p1 == entry) {
288             if(p2OrParents == null) {
289                 p1 = null;
290             } else if(p2OrParents instanceof QueryIdentityHashSet) {
291                 QueryIdentityHashSet set = (QueryIdentityHashSet)p2OrParents;
292                 int size = set.size();
293                 if(size == 0) {
294                     p1 = null;
295                     p2OrParents = null;
296                 } else if (size == 1) {
297                     CacheEntry next = set.iterator().next();
298                     p1 = next;
299                     set = null;
300                 } else if(set.size() == 2) {
301                     Iterator<CacheEntry> iterator = set.iterator();
302                     p1 = iterator.next();
303                     p2OrParents = iterator.next();
304                 } else {
305                     p1 = set.iterator().next();
306                     set.remove(p1);
307                 }
308             } else {
309                 p1 = (CacheEntry)p2OrParents;
310                 p2OrParents = null;
311             }
312             
313         } else if(p2OrParents.getClass() == QueryIdentityHashSet.class) {
314             
315             QueryIdentityHashSet set = (QueryIdentityHashSet)p2OrParents;
316             boolean success = set.remove(entry);
317             if(!success) {
318                 throw new Error("CacheEntryBase.removeParent: parent was not found.");
319             }
320             assert(set.size() >= 1);
321             if(set.size() == 1) {
322                 p2OrParents = set.iterator().next();
323             }
324             
325         } else {
326             if(p2OrParents == entry) {
327                 p2OrParents = null;
328             } else {
329                 throw new Error("CacheEntryBase.removeParent: had 2 parents but neither was removed.");
330             }
331         }
332     }
333
334     @Override
335     final public boolean hasParents() {
336         assert(statusOrException != DISCARDED);
337         return p1 != null;
338     }
339     
340     @Override
341         final public Iterable<CacheEntry<?>> getParents(QueryProcessor processor) {
342
343                 ArrayList<CacheEntry<?>> result = new ArrayList<CacheEntry<?>>();
344                 if(p1 != null) result.add(p1);
345                 if(p2OrParents != null) {
346                 if(p2OrParents instanceof QueryIdentityHashSet) {
347                         for(CacheEntry entry : (QueryIdentityHashSet)p2OrParents) {
348                                 result.add(entry);
349                         }
350                 } else {
351                         result.add((CacheEntry)p2OrParents);
352                 }
353                 }
354                 fillImpliedParents(processor, result);
355                 return result;
356                 
357         }
358     
359     @Override
360     CacheEntry getFirstParent(QueryProcessor processor) {
361         return p1;
362     }
363     
364     @Override
365     boolean moreThanOneParent(QueryProcessor processor) {
366         return p2OrParents != null;
367     }
368     
369     @Override
370     int parentCount(QueryProcessor processor) {
371         if(p2OrParents != null) {
372                 if(p2OrParents instanceof QueryIdentityHashSet) {
373                         return ((QueryIdentityHashSet)p2OrParents).size()+1;
374                 } else {
375                         return 2;
376                 }
377         } else {
378                 return p1 != null ? 1 : 0;
379         }
380         
381     }
382     
383     protected void fillImpliedParents(QueryProcessor processor, ArrayList<CacheEntry<?>> result) {
384     }
385     
386     protected String internalError() {
387         return toString() + " " + statusOrException + " " + result;
388     }
389
390     
391     protected boolean handleException(ReadGraphImpl graph, IntProcedure procedure) throws DatabaseException {
392         if(isExcepted()) {
393                 procedure.exception(graph, (Throwable)getResult());
394                 return true;
395         } else {
396                 return false;
397         }
398     }
399     
400     protected boolean handleException(ReadGraphImpl graph, TripleIntProcedure procedure) throws DatabaseException {
401         if(isExcepted()) {
402                 procedure.exception(graph, (Throwable)getResult());
403                 return true;
404         } else {
405                 return false;
406         }
407     }
408
409     protected <T> boolean handleException(ReadGraphImpl graph, InternalProcedure<T> procedure) throws DatabaseException {
410         if(isExcepted()) {
411                 procedure.exception(graph, (Throwable)getResult());
412                 return true;
413         } else {
414                 return false;
415         }
416     }
417     
418     @Override
419     boolean isImmutable(ReadGraphImpl graph) throws DatabaseException {
420         return false;
421     }
422     
423     @Override
424     boolean shouldBeCollected() {
425         return true;
426     }
427     
428     @Override
429     short getLevel() {
430         return level;
431     }
432     
433     @Override
434     short setLevel(short level) {
435         short existing = this.level;
436         this.level = level;
437         return existing;
438     }
439     
440     @Override
441     void prepareRecompute(QuerySupport querySupport) {
442                 setPending();
443                 clearResult(querySupport);
444     }
445     
446     @Override
447     int getGCStatus() {
448         return GCStatus;
449     }
450     
451     @Override
452     int setGCStatus(int status) {
453         GCStatus = status;
454         return GCStatus;
455     }
456     
457     @Override
458     void setGCStatusFlag(int flag, boolean value) {
459         if(value) {
460                 GCStatus |= flag;
461         } else {
462                 GCStatus &= ~flag;
463         }
464     }
465     
466     @Override
467     public Object getOriginalRequest() {
468         // This is the original request for all built-in queries
469         return getQuery();
470     }
471
472     public CacheEntryBase() {
473     }
474
475 }