618d6a91fbe793e5d982656f19a063f49e297627
[simantics/platform.git] / bundles / org.simantics.scl.db / src / org / simantics / scl / db / SCLFunctions.java
1 package org.simantics.scl.db;
2
3 import java.io.IOException;
4
5 import org.cojen.classfile.TypeDesc;
6 import org.simantics.Simantics;
7 import org.simantics.db.ReadGraph;
8 import org.simantics.db.Resource;
9 import org.simantics.db.VirtualGraph;
10 import org.simantics.db.WriteGraph;
11 import org.simantics.db.common.procedure.adapter.SyncListenerAdapter;
12 import org.simantics.db.common.procedure.adapter.TransientCacheAsyncListener;
13 import org.simantics.db.common.request.BinaryRead;
14 import org.simantics.db.common.request.DelayedWriteRequest;
15 import org.simantics.db.common.request.ReadRequest;
16 import org.simantics.db.common.request.UnaryRead;
17 import org.simantics.db.common.request.WriteRequest;
18 import org.simantics.db.common.request.WriteResultRequest;
19 import org.simantics.db.exception.DatabaseException;
20 import org.simantics.db.layer0.util.Layer0Utils;
21 import org.simantics.db.layer0.variable.Variables;
22 import org.simantics.db.request.Read;
23 import org.simantics.db.service.ClusterControl;
24 import org.simantics.db.service.QueryControl;
25 import org.simantics.db.service.SerialisationSupport;
26 import org.simantics.db.service.VirtualGraphSupport;
27 import org.simantics.layer0.utils.triggers.IActivationManager;
28 import org.simantics.scl.compiler.environment.specification.EnvironmentSpecification;
29 import org.simantics.scl.compiler.errors.Failable;
30 import org.simantics.scl.compiler.internal.codegen.types.JavaTypeTranslator;
31 import org.simantics.scl.compiler.module.Module;
32 import org.simantics.scl.compiler.module.repository.ImportFailureException;
33 import org.simantics.scl.compiler.runtime.RuntimeEnvironment;
34 import org.simantics.scl.compiler.types.Type;
35 import org.simantics.scl.osgi.SCLOsgi;
36 import org.simantics.scl.runtime.SCLContext;
37 import org.simantics.scl.runtime.function.Function;
38 import org.simantics.scl.runtime.function.Function1;
39 import org.simantics.scl.runtime.tuple.Tuple;
40 import org.simantics.scl.runtime.tuple.Tuple0;
41 import org.simantics.utils.DataContainer;
42
43 @SuppressWarnings({"rawtypes", "unchecked"})
44 public class SCLFunctions {
45
46     public static final String GRAPH = "graph";
47
48     public static <T> T safeExec(final Function f) {
49         try {
50             return (T)f.apply(Tuple0.INSTANCE);
51         } catch (Throwable t) {
52             t.printStackTrace();
53             return null;
54         }
55     }
56     
57     public static void asyncRead(final Function f) throws DatabaseException {
58         final SCLContext context = SCLContext.createDerivedContext();
59         Simantics.getSession().asyncRequest(new ReadRequest() {
60             @Override
61             public void run(ReadGraph graph) throws DatabaseException {
62                 SCLContext.push(context);
63                 context.put(GRAPH, graph);
64                 try {
65                     f.apply(Tuple0.INSTANCE);
66                 } finally {
67                     SCLContext.pop();
68                 }
69             }
70         });
71     }
72     
73     public static <T> T syncRead(final Function f) throws DatabaseException {
74         final SCLContext context = SCLContext.getCurrent();
75         Object graph = context.get(GRAPH);
76         if (graph != null) {
77             return (T)f.apply(Tuple0.INSTANCE);
78         } else {
79             return Simantics.getSession().syncRequest(new Read<T>() {
80                 @Override
81                 public T perform(ReadGraph graph) throws DatabaseException {
82                     SCLContext.push(context);
83                     ReadGraph oldGraph = (ReadGraph)context.put(GRAPH, graph);
84                     try {
85                         return (T)f.apply(Tuple0.INSTANCE);
86                     } finally {
87                         context.put(GRAPH, oldGraph);
88                         SCLContext.pop();
89                     }
90                 }
91             });
92         }
93     }
94     
95     public static void asyncWrite(final Function f) throws DatabaseException {
96         SCLContext context = SCLContext.createDerivedContext();
97         Simantics.getSession().asyncRequest(new WriteRequest() {
98             @Override
99             public void perform(WriteGraph graph) throws DatabaseException {
100                 SCLContext.push(context);
101                 context.put(GRAPH, graph);
102                 try {
103                     f.apply(Tuple0.INSTANCE);
104                 } finally {
105                     SCLContext.pop();
106                 }
107             }
108         });
109     }
110     
111     public static <T> T syncWrite(final Function f) throws DatabaseException {
112         final SCLContext context = SCLContext.getCurrent();
113         Object graph = context.get(GRAPH);
114         if (graph != null) {
115             return (T)f.apply(Tuple0.INSTANCE);
116         } else {
117             return Simantics.getSession().syncRequest(new WriteResultRequest<T>() {
118                 @Override
119                 public T perform(WriteGraph graph) throws DatabaseException {
120                     SCLContext.push(context);
121                     ReadGraph oldGraph = (ReadGraph)context.put(GRAPH, graph);
122                     try {
123                         return (T)f.apply(Tuple0.INSTANCE);
124                     } finally {
125                         context.put(GRAPH, oldGraph);
126                         SCLContext.pop();
127                     }
128                 }
129             });
130         }
131     }
132     
133     public static <T> T delayedSyncWrite(final Function f) throws DatabaseException {
134         final SCLContext context = SCLContext.getCurrent();
135         final DataContainer<T> dc = new DataContainer<T>(null);
136
137         DelayedWriteRequest request = new DelayedWriteRequest() {
138             @Override
139             public void perform(WriteGraph graph) throws DatabaseException {
140                 final SCLContext context = SCLContext.getCurrent();
141                 SCLContext.push(context);
142                 ReadGraph oldGraph = (ReadGraph)context.put(GRAPH, graph);
143                 try {
144                     dc.set((T)f.apply(Tuple0.INSTANCE));
145                 } finally {
146                     context.put(GRAPH, oldGraph);
147                     SCLContext.pop();
148                 }
149             }
150         };
151         
152         Object graph = context.get(GRAPH);
153         if (graph != null) {
154             if (graph instanceof WriteGraph) {
155                 ((WriteGraph)graph).syncRequest(request);
156             } else {
157                 throw new DatabaseException("Caller is inside a read transaction.");
158             }
159         } else {
160             Simantics.getSession().syncRequest(request);
161         }
162         return dc.get();
163     }
164
165     public static <T> T virtualSyncWriteMem(WriteGraph graph, String virtualGraphId, final Function f) throws DatabaseException {
166         final SCLContext context = SCLContext.getCurrent();
167         VirtualGraphSupport vgs = graph.getService(VirtualGraphSupport.class);
168         VirtualGraph vg = vgs.getMemoryPersistent(virtualGraphId);
169         return graph.syncRequest(new WriteResultRequest<T>(vg) {
170             @Override
171             public T perform(WriteGraph graph) throws DatabaseException {
172                 SCLContext.push(context);
173                 ReadGraph oldGraph = (ReadGraph)context.put(GRAPH, graph);
174                 try {
175                     return (T)f.apply(Tuple0.INSTANCE);
176                 } finally {
177                     context.put(GRAPH, oldGraph);
178                     SCLContext.pop();
179                 }
180             }
181         });
182     }
183     
184     public static <T> T virtualSyncWriteWS(WriteGraph graph, String virtualGraphId, final Function f) throws DatabaseException {
185         final SCLContext context = SCLContext.getCurrent();
186         VirtualGraphSupport vgs = graph.getService(VirtualGraphSupport.class);
187         VirtualGraph vg = vgs.getWorkspacePersistent(virtualGraphId);
188         return graph.syncRequest(new WriteResultRequest<T>(vg) {
189             @Override
190             public T perform(WriteGraph graph) throws DatabaseException {
191                 SCLContext.push(context);
192                 ReadGraph oldGraph = (ReadGraph)context.put(GRAPH, graph);
193                 try {
194                     return (T)f.apply(Tuple0.INSTANCE);
195                 } finally {
196                     context.put(GRAPH, oldGraph);
197                     SCLContext.pop();
198                 }
199             }
200         });
201     }
202     
203     public static <T> T readValue(final String uri) throws DatabaseException {
204         return Simantics.getSession().syncRequest(new Read<T>() {
205             @Override
206             public T perform(ReadGraph graph) throws DatabaseException {
207                 return Variables.getVariable(graph, uri).getValue(graph);
208             }            
209         });
210     }
211     
212     public static <T> void writeValue(final String uri, final T value) throws DatabaseException {
213         Simantics.getSession().syncRequest(new WriteRequest() {
214             @Override
215             public void perform(WriteGraph graph) throws DatabaseException {
216                 Variables.getVariable(graph, uri).setValue(graph, value);
217             }            
218         });
219     }
220     
221     public static void activateOnce(Resource r) {
222         Simantics.getSession().getService(IActivationManager.class).activateOnce(r);
223     }
224     
225     public static void syncActivateOnce(WriteGraph graph, Resource r) throws DatabaseException {
226         graph.getService(IActivationManager.class).activateOnce(graph, r);
227     }
228
229     public static Resource resourceFromId(ReadGraph graph, long id) throws DatabaseException, IOException {
230         SerialisationSupport ss = graph.getService(SerialisationSupport.class);
231         return ss.getResource(id);
232     }
233     
234     public static void disableDependencies(WriteGraph graph) {
235         Layer0Utils.setDependenciesIndexingDisabled(graph, true);       
236     }
237     
238     public static void enableDependencies(WriteGraph graph) {
239         Layer0Utils.setDependenciesIndexingDisabled(graph, false);       
240     }
241     
242     public static void collectClusters() {
243         Simantics.getSession().getService(ClusterControl.class).collectClusters(Integer.MAX_VALUE);
244     }
245     
246     public static class SCLUnaryRead extends BinaryRead<Function1<Object,Object>, Object, Object> {
247
248                 public SCLUnaryRead(Function1<Object, Object> parameter1, Object parameter2) {
249                         super(parameter1, parameter2);
250                 }
251
252                 @Override
253                 public Object perform(ReadGraph graph) throws DatabaseException {
254                         return Simantics.applySCLRead(graph, parameter, parameter2);
255                 }
256         
257     }
258     
259     public static Object unaryQuery(ReadGraph graph, Function1<Object,Object> fn, Object value) throws DatabaseException {
260         return graph.syncRequest(new SCLUnaryRead(fn, value));
261     }
262
263     public static Object unaryQueryCached(ReadGraph graph, Function1<Object,Object> fn, Object value) throws DatabaseException {
264         return graph.syncRequest(new SCLUnaryRead(fn, value), TransientCacheAsyncListener.<Object>instance());
265     }
266     
267
268     private static class Subquery extends UnaryRead<Function, Object> {
269
270         public Subquery(Function q) {
271             super(q);
272         }
273
274         @Override
275         public Object perform(ReadGraph graph) throws DatabaseException {
276             return Simantics.applySCLRead(graph, parameter, Tuple0.INSTANCE);
277         }
278
279     }
280
281     public static Object subquery(ReadGraph graph, Function q) throws DatabaseException {
282         return graph.syncRequest(new Subquery(q));
283     }
284
285     public static Object subqueryC(ReadGraph graph, Function q) throws DatabaseException {
286         return graph.syncRequest(new Subquery(q), TransientCacheAsyncListener.<Object>instance());
287     }
288     
289     public static void subqueryL(ReadGraph graph, Function query, Function executeCallback, Function1<Throwable, Tuple> exceptionCallback, Function1<Tuple0, Boolean> isDisposedCallback) throws DatabaseException {
290         graph.asyncRequest(new Subquery(query), new SyncListenerAdapter<Object>() {
291             @Override
292             public void execute(ReadGraph graph, Object result) throws DatabaseException {
293                 Simantics.applySCLRead(graph, executeCallback, result);
294             }
295             
296             @Override
297             public void exception(ReadGraph graph, Throwable t) throws DatabaseException {
298                 Simantics.applySCLRead(graph, exceptionCallback, t);
299             }
300             
301             @Override
302             public boolean isDisposed() {
303                 return isDisposedCallback.apply(Tuple0.INSTANCE);
304             }
305         });
306     }
307
308     public static Object possibleFromDynamic(Type expectedType, String moduleName, Object value) {
309         
310         try {
311
312                 
313             Failable<Module> failable = SCLOsgi.MODULE_REPOSITORY.getModule(moduleName);
314             Module module = failable.getResult();
315             
316                 RuntimeEnvironment env = SCLOsgi.MODULE_REPOSITORY.createRuntimeEnvironment(
317                                 EnvironmentSpecification.of(moduleName, ""), module.getParentClassLoader());
318
319             JavaTypeTranslator tr = new JavaTypeTranslator(env.getEnvironment());
320             TypeDesc desc = tr.toTypeDesc(expectedType);
321             String className = desc.getFullName();
322             Class<?> clazz = env.getMutableClassLoader().loadClass(className);
323             if (!clazz.isAssignableFrom(value.getClass()))
324                 return null;
325             
326         } catch (ImportFailureException | ClassNotFoundException e) {
327         }
328         return value;
329     }
330
331     public static void restrictQueries(ReadGraph graph, int amount, int step, int maxTimeInMs) {
332
333                 QueryControl qc = graph.getService(QueryControl.class);
334                 long start = System.currentTimeMillis();
335                 while(true) {
336                         int current = qc.count();
337                         if(current < amount) return;
338                         qc.gc(graph, step);
339                         long duration = System.currentTimeMillis() - start;
340                         if(duration > maxTimeInMs) return;
341                 }
342
343     }
344
345     public static int countQueries(ReadGraph graph) {
346
347                 QueryControl qc = graph.getService(QueryControl.class);
348                 return qc.count();
349
350     }
351     
352 }