1 package fi.vtt.simantics.procore.internal;
3 import java.io.IOException;
4 import java.util.Collection;
5 import java.util.LinkedList;
7 import org.simantics.db.Resource;
8 import org.simantics.db.common.utils.Logger;
9 import org.simantics.db.exception.CancelTransactionException;
10 import org.simantics.db.exception.DatabaseException;
11 import org.simantics.db.impl.graph.WriteGraphImpl;
12 import org.simantics.db.impl.internal.RandomAccessValueSupport;
13 import org.simantics.db.impl.internal.ResourceData;
14 import org.simantics.db.impl.query.QueryProcessor.SessionRead;
15 import org.simantics.db.impl.query.QueryProcessor.SessionTask;
16 import org.simantics.db.request.WriteTraits;
17 import org.simantics.utils.datastructures.Pair;
19 public class SessionRequestManager {
21 private static boolean DEBUG = false;
25 INIT, IDLE, READ, WRITE, WRITE_UPDATE, READ_UPDATE, ERROR
29 final SessionImplSocket session;
30 final fi.vtt.simantics.procore.internal.State transactionState;
31 final LinkedList<SessionTask> writes = new LinkedList<SessionTask>();
32 final LinkedList<SessionRead> reads = new LinkedList<SessionRead>();
34 State state = State.INIT;
36 private boolean legal(State current, State target) {
38 if(State.IDLE == current) {
40 return State.INIT != target && State.WRITE_UPDATE != target && State.READ_UPDATE != target;
42 } else if (State.WRITE == current) {
44 return State.WRITE_UPDATE == target;
46 } else if (State.READ == current) {
48 return State.READ_UPDATE == target;
50 } else if (State.ERROR == current) {
52 return State.IDLE == target;
56 return State.IDLE == target;
62 private synchronized void setState(int thread, State state, SessionTask task) {
64 if(DEBUG) System.err.println("Session state: " + this.state + " => " + state + " - " + task);
65 if(this.state == state) return;
67 assert(legal(this.state, state));
69 if(State.READ == state) {
71 assert(State.IDLE == this.state);
75 State oldState = this.state;
78 if(State.IDLE == oldState && State.IDLE != state) {
83 * We are now executing in new state.
84 * The methods below SHALL NOT start any task
85 * immediately. All tasks shall be scheduled.
88 if(State.READ == state) startRead(thread, (SessionRead)task);
89 else if(State.WRITE == state) startWrite(thread, task);
90 else if(State.READ == oldState) startReadUpdate(thread);
91 else if(State.WRITE == oldState) startWriteUpdate(thread);
93 // Check the need for new transaction
94 if(state == State.IDLE) {
96 closeRandomAccessValues();
98 if(!writes.isEmpty()) {
99 setState(thread, State.WRITE, writes.poll());
100 } else if (!reads.isEmpty()) {
101 setState(thread, State.READ, reads.poll());
110 public SessionRequestManager(SessionImplSocket session, fi.vtt.simantics.procore.internal.State transactionState) {
111 this.session = session;
112 this.transactionState = transactionState;
115 public synchronized void startRead(int thread, final SessionRead task) {
117 session.queryProvider2.scheduleAlways(thread, new SessionTask(task.object, task.thread, task.syncCaller) {
120 public void run(int thread) {
122 transactionState.startReadTransaction(thread);
124 } catch (Throwable t) {
125 Logger.defaultLogError(new DatabaseException("Read transaction could not be started", t));
126 if(task.throwable != null)
127 task.throwable.set(t);
130 if(task.notify != null)
131 task.notify.release();
139 public synchronized void startReadUpdate(int thread) {
141 session.queryProvider2.scheduleAlways(thread, new SessionTask(null, thread) {
144 public void run(int thread) {
146 session.fireFinishReadTransaction();
149 transactionState.stopReadTransaction();
150 } catch (DatabaseException e) {
160 // public synchronized void stopRead(int thread) {
163 // transactionState.stopReadTransaction();
164 // } catch (DatabaseException e) {
165 // e.printStackTrace();
170 public synchronized void startWrite(int thread, final SessionTask task) {
172 session.queryProvider2.scheduleAlways(thread, new SessionTask((WriteTraits)task.object, task.thread) {
175 public void run(int thread) {
178 transactionState.startWriteTransaction(thread);
179 } catch (Throwable t) {
180 DatabaseException e = new DatabaseException("Write transaction could not be started", t);
181 Logger.defaultLogError(e);
192 public synchronized void startWriteUpdate(int thread) {
194 session.queryProvider2.scheduleAlways(thread, new SessionTask(null, thread) {
197 public void run(int thread) {
199 // Support for DelayedWriteRequest cancels during the
200 // read-only part of the request.
201 WriteStateBase<?> delayedState = session.delayedWriteState;
202 session.delayedWriteState = null;
203 if (delayedState != null) {
204 if (session.writeState != null)
205 throw new AssertionError("Both session delayedWriteState and writeState are set, only one can be set.");
207 if (delayedState.isExcepted()) {
208 // There can never be any changes in the cluster stream.
209 // In this case, don't bother rolling back.
210 boolean empty = session.clusterStream.reallyFlush();
212 transactionState.stopWriteTransaction(session.clusterStream);
214 throw new UnsupportedOperationException("delayedWriteState may only exist when request fails.");
216 session.clientChanges = new ClientChangesImpl(session);
217 delayedState.finish();
221 // The session could have been terminated
222 if(!session.state.isAlive()) return;
224 WriteState<?> writeState = session.writeState;
225 WriteGraphImpl graph = writeState.getGraph();
227 if(writeState.isExcepted()) {
229 if(!(writeState.exception instanceof CancelTransactionException))
230 writeState.exception.printStackTrace();
232 transactionState.cancelWriteTransaction(graph);
236 session.handleUpdatesAndMetadata(graph);
238 // long start = System.nanoTime();
239 transactionState.commitWriteTransaction(writeState.getGraph(), session.clusterStream, session.clientChanges, writeState.getRequest(), null);
240 // long duration = System.nanoTime() - start;
241 // System.out.println("commitWriteTransaction " + 1e-9*duration + "s. ");
245 session.clientChanges = new ClientChangesImpl(session);
247 WriteState<?> state = session.writeState;
249 session.writeState = null;
257 // public synchronized void stopWrite(int thread) {
259 // session.clientChanges = new ClientChangesImpl(session);
261 // WriteState<?> state = session.writeState;
263 // System.err.println("D");
265 // System.err.println("E");
267 // session.writeState = null;
271 public synchronized void ceased(int thread) {
273 if(State.WRITE == state) {
275 setState(thread, State.WRITE_UPDATE, null);
277 } else if (State.WRITE_UPDATE == state) {
279 setState(thread, State.IDLE, null);
281 } else if (State.READ_UPDATE == state) {
283 setState(thread, State.IDLE, null);
285 } else if (State.READ == state) {
287 if (!reads.isEmpty()) {
289 final SessionRead read = reads.poll();
290 session.queryProvider2.scheduleAlways(thread, new SessionTask(read.object, read.thread, read.syncCaller) {
293 public void run(int thread) {
295 if(read.notify != null) read.notify.release();
302 setState(thread, State.READ_UPDATE, null);
306 } else if (State.INIT == state) {
308 assert(reads.isEmpty());
309 assert(writes.isEmpty());
310 setState(thread, State.IDLE, null);
312 } else if (State.ERROR == state) {
314 setState(thread, State.IDLE, null);
318 throw new IllegalStateException("State in ceased should be WRITE or READ or INIT (was " + state + ")");
324 public synchronized void scheduleRead(final SessionRead task) {
326 assert(State.INIT != state);
328 if(State.READ == state) {
329 session.queryProvider2.schedule(Integer.MIN_VALUE, new SessionTask(task.object, task.thread, task.syncCaller) {
332 public void run(int thread) {
336 if (task.notify != null) task.notify.release();
341 } else if (State.IDLE == state) {
342 setState(Integer.MIN_VALUE, State.READ, task);
349 public int lastUpdateIndex() {
350 return writes.size();
353 public synchronized void scheduleWrite(SessionTask task) {
355 scheduleWrite(task, null);
360 * @param task the task to schedule
361 * @param combine <code>true</code> or <code>false</code> to explicitly
362 * specify whether to combine the write with the previous operation
363 * or <code>null</code> to use the default logic, i.e. combine when
364 * this schedule is performed from within update processing (state ==
365 * State.WRITE_UPDATE).
367 public synchronized void scheduleWrite(SessionTask task, Boolean combine) {
369 boolean inUpdate = state == State.WRITE_UPDATE;
371 assert(State.INIT != state);
372 //task.combine = combine != null ? combine : inUpdate;
373 if(State.IDLE == state) {
374 setState(Integer.MIN_VALUE, State.WRITE, task);
377 int index = lastUpdateIndex();
378 if(index == writes.size()) writes.offer(task);
379 else writes.add(index, task);
388 * Unregisters and closes all currently registered ResourceData random
389 * access value file handles. Any I/O exceptions occurring during closing
390 * are logged into {@link Logger}.
392 private void closeRandomAccessValues() {
393 RandomAccessValueSupport ravs = session.peekService(RandomAccessValueSupport.class);
396 Collection<Pair<Resource, ResourceData>> values = ravs.removeAll();
397 for (Pair<Resource, ResourceData> value : values) {
399 value.second.binaryFile.close();
400 } catch (IOException e) {
401 Logger.defaultLogError("I/O exception while closing random access value file " + value.second.binaryFile.file() + " for resource " + value.first , e);