1 /*******************************************************************************
2 * Copyright (c) 2019 Association for Decentralized Information Management in
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
10 * Semantum Oy - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.scl.db;
14 import java.io.IOException;
15 import java.util.ArrayList;
16 import java.util.List;
18 import org.cojen.classfile.TypeDesc;
19 import org.simantics.Simantics;
20 import org.simantics.db.ReadGraph;
21 import org.simantics.db.Resource;
22 import org.simantics.db.VirtualGraph;
23 import org.simantics.db.WriteGraph;
24 import org.simantics.db.common.procedure.adapter.SyncListenerAdapter;
25 import org.simantics.db.common.procedure.adapter.TransientCacheAsyncListener;
26 import org.simantics.db.common.request.BinaryRead;
27 import org.simantics.db.common.request.DelayedWriteRequest;
28 import org.simantics.db.common.request.ReadRequest;
29 import org.simantics.db.common.request.UnaryRead;
30 import org.simantics.db.common.request.WriteRequest;
31 import org.simantics.db.common.request.WriteResultRequest;
32 import org.simantics.db.exception.DatabaseException;
33 import org.simantics.db.layer0.util.Layer0Utils;
34 import org.simantics.db.layer0.variable.Variables;
35 import org.simantics.db.request.Read;
36 import org.simantics.db.service.ClusterControl;
37 import org.simantics.db.service.QueryControl;
38 import org.simantics.db.service.SerialisationSupport;
39 import org.simantics.db.service.VirtualGraphSupport;
40 import org.simantics.layer0.utils.triggers.IActivationManager;
41 import org.simantics.scl.compiler.elaboration.modules.SCLValue;
42 import org.simantics.scl.compiler.environment.specification.EnvironmentSpecification;
43 import org.simantics.scl.compiler.errors.DoesNotExist;
44 import org.simantics.scl.compiler.errors.Failable;
45 import org.simantics.scl.compiler.errors.Failure;
46 import org.simantics.scl.compiler.internal.codegen.types.JavaTypeTranslator;
47 import org.simantics.scl.compiler.module.Module;
48 import org.simantics.scl.compiler.module.repository.ImportFailureException;
49 import org.simantics.scl.compiler.runtime.RuntimeEnvironment;
50 import org.simantics.scl.compiler.runtime.RuntimeModule;
51 import org.simantics.scl.compiler.top.ValueNotFound;
52 import org.simantics.scl.compiler.types.TCon;
53 import org.simantics.scl.compiler.types.Type;
54 import org.simantics.scl.compiler.types.Types;
55 import org.simantics.scl.compiler.types.exceptions.MatchException;
56 import org.simantics.scl.compiler.types.util.MultiFunction;
57 import org.simantics.scl.osgi.SCLOsgi;
58 import org.simantics.scl.reflection.ValueNotFoundException;
59 import org.simantics.scl.runtime.SCLContext;
60 import org.simantics.scl.runtime.function.Function;
61 import org.simantics.scl.runtime.function.Function1;
62 import org.simantics.scl.runtime.reporting.SCLReportingHandler;
63 import org.simantics.scl.runtime.tuple.Tuple;
64 import org.simantics.scl.runtime.tuple.Tuple0;
65 import org.simantics.utils.DataContainer;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
69 @SuppressWarnings({"rawtypes", "unchecked"})
70 public class SCLFunctions {
72 private static final Logger LOGGER = LoggerFactory.getLogger(SCLFunctions.class);
74 public static final String GRAPH = "graph";
76 public static <T> T safeExec(final Function f) {
78 return (T)f.apply(Tuple0.INSTANCE);
79 } catch (Throwable t) {
80 LOGGER.error("safeExec caught exception", t);
85 public static Function resolveFunction(RuntimeModule rm, String function) throws ValueNotFound {
86 return (Function)rm.getValue(function);
89 private static SCLValue resolveSCLValue(RuntimeModule rm, String function) throws ValueNotFound {
90 return rm.getModule().getValue(function);
93 private static RuntimeModule resolveRuntimeModule(String module) throws ValueNotFound {
94 Failable<RuntimeModule> f = SCLOsgi.MODULE_REPOSITORY.getRuntimeModule(module);
97 else if(f == DoesNotExist.INSTANCE)
98 throw new ValueNotFound("Didn't find module " + module);
100 throw new ValueNotFound(((Failure)f).toString());
103 private static List<TCon> getEffects(SCLValue value) throws ValueNotFoundException, ValueNotFound, MatchException {
105 Type type = value.getType();
106 MultiFunction mfun = Types.matchFunction(type, 1);
107 ArrayList<TCon> concreteEffects = new ArrayList<>();
108 mfun.effect.collectConcreteEffects(concreteEffects);
109 return concreteEffects;
113 public static List<TCon> getEffects(RuntimeModule rm, String function) throws ValueNotFoundException, ValueNotFound, MatchException {
114 return getEffects(resolveSCLValue(rm, function));
117 public static List<TCon> getEffects(String module, String function) throws ValueNotFoundException, ValueNotFound, MatchException {
118 return getEffects(resolveSCLValue(resolveRuntimeModule(module), function));
121 private static <T> T evaluate(Function function, Object ... args) {
122 return (T)function.applyArray(args);
125 private static <T> T evaluate(RuntimeModule rm, String function, Object ... args) throws ValueNotFound {
126 return evaluate(resolveFunction(rm, function), args);
129 public static <T> T evaluate(String module, String function, Object ... args) throws ValueNotFound {
130 return evaluate(resolveRuntimeModule(module), function, args);
133 public static <T> T evaluateDB(String module, String function, Object ... args) throws DatabaseException {
135 RuntimeModule rm = resolveRuntimeModule(module);
136 List<TCon> effects = getEffects(resolveSCLValue(rm, function));
137 Function f = resolveFunction(rm, function);
138 if(effects.contains(Types.WRITE_GRAPH)) {
139 return syncWrite(f, args);
140 } else if(effects.contains(Types.READ_GRAPH)) {
141 return syncRead(f, args);
143 return evaluate(f, args);
145 } catch (ValueNotFound e) {
146 throw new DatabaseException("SCL Value not found: " + e.name);
147 } catch (Throwable t) {
148 if (t instanceof DatabaseException)
149 throw (DatabaseException) t;
150 throw new DatabaseException(t);
154 public static <T> T evaluateGraph(String module, String function, ReadGraph graph, Object ... args) throws DatabaseException {
155 final SCLContext context = SCLContext.getCurrent();
156 SCLContext.push(context);
157 Object oldGraph = context.put(GRAPH, graph);
159 return evaluateDB(module, function, args);
161 context.put(GRAPH, oldGraph);
166 public static void runWithGraph(ReadGraph graph, Runnable r) {
167 final SCLContext context = SCLContext.getCurrent();
168 SCLContext.push(context);
169 Object oldGraph = context.put(GRAPH, graph);
173 context.put(GRAPH, oldGraph);
178 private static Object[] NO_ARGS = new Object[] { Tuple0.INSTANCE };
180 public static <T> void asyncRead(final Function f) throws DatabaseException {
181 asyncRead(f, NO_ARGS);
184 public static void asyncRead(final Function f, final Object ... args) throws DatabaseException {
185 final SCLContext context = SCLContext.createDerivedContext();
186 Simantics.getSession().asyncRequest(new ReadRequest() {
188 public void run(ReadGraph graph) throws DatabaseException {
189 SCLContext.push(context);
190 context.put(GRAPH, graph);
200 public static <T> T syncRead(final Function f) throws DatabaseException {
201 return syncRead(f, NO_ARGS);
204 public static <T> T syncRead(final Function f, final Object ... args) throws DatabaseException {
205 final SCLContext context = SCLContext.getCurrent();
206 Object graph = context.get(GRAPH);
208 return (T)f.applyArray(args);
210 return Simantics.getSession().syncRequest(new Read<T>() {
212 public T perform(ReadGraph graph) throws DatabaseException {
213 SCLContext.push(context);
214 ReadGraph oldGraph = (ReadGraph)context.put(GRAPH, graph);
216 return (T)f.applyArray(args);
218 context.put(GRAPH, oldGraph);
226 public static void asyncWrite(final Function f) throws DatabaseException {
227 asyncWrite(f, NO_ARGS);
230 public static void asyncWrite(final Function f, final Object ... args) throws DatabaseException {
231 SCLContext context = SCLContext.createDerivedContext();
232 if (Simantics.peekSession() != null) {
233 Simantics.getSession().asyncRequest(new WriteRequest() {
235 public void perform(WriteGraph graph) throws DatabaseException {
236 SCLContext.push(context);
237 context.put(GRAPH, graph);
246 LOGGER.warn("No session available for asynchronous write requests");
250 public static <T> T syncWrite(final Function f) throws DatabaseException {
251 return syncWrite(f, NO_ARGS);
254 public static <T> T syncWrite(final Function f, final Object ... args) throws DatabaseException {
255 final SCLContext context = SCLContext.getCurrent();
256 Object graph = context.get(GRAPH);
257 if (graph != null && graph instanceof WriteGraph) {
258 return (T)f.applyArray(args);
262 "SCLContext {} for current thread {} contains an existing graph object but it is not WriteGraph - Somewhere is a function that forgets to remove the graph from the context!!",
263 context, Thread.currentThread());
265 final SCLReportingHandler printer = (SCLReportingHandler)SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
266 return Simantics.getSession().syncRequest(new WriteResultRequest<T>() {
268 public T perform(WriteGraph graph) throws DatabaseException {
269 SCLContext.push(context);
270 SCLReportingHandler oldPrinter = (SCLReportingHandler)context.put(SCLReportingHandler.REPORTING_HANDLER, printer);
271 ReadGraph oldGraph = (ReadGraph)context.put(GRAPH, graph);
273 return (T)f.applyArray(args);
275 context.put(GRAPH, oldGraph);
276 context.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
284 public static <T> T delayedSyncWrite(final Function f) throws DatabaseException {
285 final SCLContext context = SCLContext.getCurrent();
286 final DataContainer<T> dc = new DataContainer<T>(null);
288 DelayedWriteRequest request = new DelayedWriteRequest() {
290 public void perform(WriteGraph graph) throws DatabaseException {
291 final SCLContext context = SCLContext.getCurrent();
292 SCLContext.push(context);
293 ReadGraph oldGraph = (ReadGraph)context.put(GRAPH, graph);
295 dc.set((T)f.apply(Tuple0.INSTANCE));
297 context.put(GRAPH, oldGraph);
303 Object graph = context.get(GRAPH);
305 if (graph instanceof WriteGraph) {
306 ((WriteGraph)graph).syncRequest(request);
308 throw new DatabaseException("Caller is inside a read transaction.");
311 Simantics.getSession().syncRequest(request);
316 public static <T> T virtualSyncWriteMem(WriteGraph graph, String virtualGraphId, final Function f) throws DatabaseException {
317 final SCLContext context = SCLContext.getCurrent();
318 VirtualGraphSupport vgs = graph.getService(VirtualGraphSupport.class);
319 VirtualGraph vg = vgs.getMemoryPersistent(virtualGraphId);
320 return graph.syncRequest(new WriteResultRequest<T>(vg) {
322 public T perform(WriteGraph graph) throws DatabaseException {
323 SCLContext.push(context);
324 ReadGraph oldGraph = (ReadGraph)context.put(GRAPH, graph);
326 return (T)f.apply(Tuple0.INSTANCE);
328 context.put(GRAPH, oldGraph);
335 public static <T> T virtualSyncWriteWS(WriteGraph graph, String virtualGraphId, final Function f) throws DatabaseException {
336 final SCLContext context = SCLContext.getCurrent();
337 VirtualGraphSupport vgs = graph.getService(VirtualGraphSupport.class);
338 VirtualGraph vg = vgs.getWorkspacePersistent(virtualGraphId);
339 return graph.syncRequest(new WriteResultRequest<T>(vg) {
341 public T perform(WriteGraph graph) throws DatabaseException {
342 SCLContext.push(context);
343 ReadGraph oldGraph = (ReadGraph)context.put(GRAPH, graph);
345 return (T)f.apply(Tuple0.INSTANCE);
347 context.put(GRAPH, oldGraph);
354 public static <T> T readValue(final String uri) throws DatabaseException {
355 return Simantics.getSession().syncRequest(new Read<T>() {
357 public T perform(ReadGraph graph) throws DatabaseException {
358 return Variables.getVariable(graph, uri).getValue(graph);
363 public static <T> void writeValue(final String uri, final T value) throws DatabaseException {
364 Simantics.getSession().syncRequest(new WriteRequest() {
366 public void perform(WriteGraph graph) throws DatabaseException {
367 Variables.getVariable(graph, uri).setValue(graph, value);
372 public static void activateOnce(Resource r) {
373 Simantics.getSession().getService(IActivationManager.class).activateOnce(r);
376 public static void syncActivateOnce(WriteGraph graph, Resource r) throws DatabaseException {
377 graph.getService(IActivationManager.class).activateOnce(graph, r);
380 public static Resource resourceFromId(ReadGraph graph, long id) throws DatabaseException, IOException {
381 SerialisationSupport ss = graph.getService(SerialisationSupport.class);
382 return ss.getResource(id);
385 public static void disableDependencies(WriteGraph graph) {
386 Layer0Utils.setDependenciesIndexingDisabled(graph, true);
389 public static void enableDependencies(WriteGraph graph) {
390 Layer0Utils.setDependenciesIndexingDisabled(graph, false);
393 public static void collectClusters() {
394 Simantics.getSession().getService(ClusterControl.class).collectClusters(Integer.MAX_VALUE);
397 public static class SCLUnaryRead extends BinaryRead<Function1<Object,Object>, Object, Object> {
399 public SCLUnaryRead(Function1<Object, Object> parameter1, Object parameter2) {
400 super(parameter1, parameter2);
404 public Object perform(ReadGraph graph) throws DatabaseException {
405 return Simantics.applySCLRead(graph, parameter, parameter2);
410 public static Object unaryQuery(ReadGraph graph, Function1<Object,Object> fn, Object value) throws DatabaseException {
411 return graph.syncRequest(new SCLUnaryRead(fn, value));
414 public static Object unaryQueryCached(ReadGraph graph, Function1<Object,Object> fn, Object value) throws DatabaseException {
415 return graph.syncRequest(new SCLUnaryRead(fn, value), TransientCacheAsyncListener.<Object>instance());
419 private static class Subquery extends UnaryRead<Function, Object> {
421 public Subquery(Function q) {
426 public Object perform(ReadGraph graph) throws DatabaseException {
427 return Simantics.applySCLRead(graph, parameter, Tuple0.INSTANCE);
432 public static Object subquery(ReadGraph graph, Function q) throws DatabaseException {
433 return graph.syncRequest(new Subquery(q));
436 public static Object subqueryC(ReadGraph graph, Function q) throws DatabaseException {
437 return graph.syncRequest(new Subquery(q), TransientCacheAsyncListener.<Object>instance());
440 public static void subqueryL(ReadGraph graph, Function query, Function executeCallback, Function1<Throwable, Tuple> exceptionCallback, Function1<Tuple0, Boolean> isDisposedCallback) throws DatabaseException {
441 graph.syncRequest(new Subquery(query), new SyncListenerAdapter<Object>() {
443 public void execute(ReadGraph graph, Object result) throws DatabaseException {
444 Simantics.applySCLRead(graph, executeCallback, result);
448 public void exception(ReadGraph graph, Throwable t) throws DatabaseException {
449 Simantics.applySCLRead(graph, exceptionCallback, t);
453 public boolean isDisposed() {
454 return isDisposedCallback.apply(Tuple0.INSTANCE);
459 public static Object possibleFromDynamic(Type expectedType, String moduleName, Object value) {
464 Failable<Module> failable = SCLOsgi.MODULE_REPOSITORY.getModule(moduleName);
465 Module module = failable.getResult();
467 RuntimeEnvironment env = SCLOsgi.MODULE_REPOSITORY.createRuntimeEnvironment(
468 EnvironmentSpecification.of(moduleName, ""), module.getParentClassLoader());
470 JavaTypeTranslator tr = new JavaTypeTranslator(env.getEnvironment());
471 TypeDesc desc = tr.toTypeDesc(expectedType);
472 String className = desc.getFullName();
473 Class<?> clazz = env.getMutableClassLoader().loadClass(className);
474 if (!clazz.isAssignableFrom(value.getClass()))
477 } catch (ImportFailureException | ClassNotFoundException e) {
482 public static void restrictQueries(ReadGraph graph, int amount, int step, int maxTimeInMs) {
484 QueryControl qc = graph.getService(QueryControl.class);
485 long start = System.currentTimeMillis();
487 int current = qc.count();
488 if(current < amount) return;
490 long duration = System.currentTimeMillis() - start;
491 if(duration > maxTimeInMs) return;
496 public static int countQueries(ReadGraph graph) {
498 QueryControl qc = graph.getService(QueryControl.class);