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