src/Pure/PIDE/headless.scala
author wenzelm
Tue Sep 18 11:05:14 2018 +0200 (11 months ago ago)
changeset 69012 c91d14ab065f
parent 68987 src/Pure/Thy/thy_resources.scala@22f02724e7d1
child 69013 bb4e4c253ebe
permissions -rw-r--r--
clarified modules;
     1 /*  Title:      Pure/PIDE/headless.scala
     2     Author:     Makarius
     3 
     4 Headless PIDE session and resources from file-system.
     5 */
     6 
     7 package isabelle
     8 
     9 
    10 import java.io.{File => JFile}
    11 
    12 import scala.annotation.tailrec
    13 
    14 
    15 object Headless
    16 {
    17   /** session **/
    18 
    19   def start_session(
    20     options: Options,
    21     session_name: String,
    22     session_dirs: List[Path] = Nil,
    23     include_sessions: List[String] = Nil,
    24     session_base: Option[Sessions.Base] = None,
    25     print_mode: List[String] = Nil,
    26     progress: Progress = No_Progress,
    27     log: Logger = No_Logger): Session =
    28   {
    29     val base =
    30       session_base getOrElse
    31         Sessions.base_info(options, session_name, include_sessions = include_sessions,
    32           progress = progress, dirs = session_dirs).check_base
    33     val resources = new Resources(base, log = log)
    34     val session = new Session(session_name, options, resources)
    35 
    36     val session_error = Future.promise[String]
    37     var session_phase: Session.Consumer[Session.Phase] = null
    38     session_phase =
    39       Session.Consumer(getClass.getName) {
    40         case Session.Ready =>
    41           session.phase_changed -= session_phase
    42           session_error.fulfill("")
    43         case Session.Terminated(result) if !result.ok =>
    44           session.phase_changed -= session_phase
    45           session_error.fulfill("Session start failed: return code " + result.rc)
    46         case _ =>
    47       }
    48     session.phase_changed += session_phase
    49 
    50     progress.echo("Starting session " + session_name + " ...")
    51     Isabelle_Process.start(session, options,
    52       logic = session_name, dirs = session_dirs, modes = print_mode)
    53 
    54     session_error.join match {
    55       case "" => session
    56       case msg => session.stop(); error(msg)
    57     }
    58   }
    59 
    60   private def stable_snapshot(
    61     state: Document.State, version: Document.Version, name: Document.Node.Name): Document.Snapshot =
    62   {
    63     val snapshot = state.snapshot(name)
    64     assert(version.id == snapshot.version.id)
    65     snapshot
    66   }
    67 
    68   class Theories_Result private[Headless](
    69     val state: Document.State,
    70     val version: Document.Version,
    71     val nodes: List[(Document.Node.Name, Document_Status.Node_Status)],
    72     val nodes_committed: List[(Document.Node.Name, Document_Status.Node_Status)])
    73   {
    74     def snapshot(name: Document.Node.Name): Document.Snapshot =
    75       stable_snapshot(state, version, name)
    76 
    77     def ok: Boolean =
    78       (nodes.iterator ++ nodes_committed.iterator).forall({ case (_, st) => st.ok })
    79   }
    80 
    81   val default_check_delay = Time.seconds(0.5)
    82   val default_nodes_status_delay = Time.seconds(-1.0)
    83   val default_commit_cleanup_delay = Time.seconds(60.0)
    84   val default_watchdog_timeout = Time.seconds(600.0)
    85 
    86 
    87   class Session private[Headless](
    88     session_name: String,
    89     session_options: Options,
    90     override val resources: Resources) extends isabelle.Session(session_options, resources)
    91   {
    92     session =>
    93 
    94 
    95     /* temporary directory */
    96 
    97     val tmp_dir: JFile = Isabelle_System.tmp_dir("server_session")
    98     val tmp_dir_name: String = File.path(tmp_dir).implode
    99 
   100     def master_directory(master_dir: String): String =
   101       proper_string(master_dir) getOrElse tmp_dir_name
   102 
   103     override def toString: String = session_name
   104 
   105     override def stop(): Process_Result =
   106     {
   107       try { super.stop() }
   108       finally { Isabelle_System.rm_tree(tmp_dir) }
   109     }
   110 
   111 
   112     /* theories */
   113 
   114     private sealed case class Use_Theories_State(
   115       last_update: Time = Time.now(),
   116       nodes_status: Document_Status.Nodes_Status = Document_Status.Nodes_Status.empty,
   117       already_committed: Map[Document.Node.Name, Document_Status.Node_Status] = Map.empty,
   118       result: Promise[Theories_Result] = Future.promise[Theories_Result])
   119     {
   120       def update(new_nodes_status: Document_Status.Nodes_Status): Use_Theories_State =
   121         copy(last_update = Time.now(), nodes_status = new_nodes_status)
   122 
   123       def watchdog(watchdog_timeout: Time): Boolean =
   124         watchdog_timeout > Time.zero && Time.now() - last_update > watchdog_timeout
   125 
   126       def cancel_result { result.cancel }
   127       def finished_result: Boolean = result.is_finished
   128       def await_result { result.join_result }
   129       def join_result: Theories_Result = result.join
   130       def check_result(
   131           state: Document.State,
   132           version: Document.Version,
   133           dep_theories: List[Document.Node.Name],
   134           beyond_limit: Boolean,
   135           watchdog_timeout: Time,
   136           commit: Option[(Document.Snapshot, Document_Status.Node_Status) => Unit])
   137         : Use_Theories_State =
   138       {
   139         val st1 =
   140           if (commit.isDefined) {
   141             val already_committed1 =
   142               (already_committed /: dep_theories)({ case (committed, name) =>
   143                 def parents_committed: Boolean =
   144                   version.nodes(name).header.imports.forall({ case (parent, _) =>
   145                     Sessions.is_pure(parent.theory) || committed.isDefinedAt(parent)
   146                   })
   147                 if (!committed.isDefinedAt(name) && parents_committed &&
   148                     state.node_consolidated(version, name))
   149                 {
   150                   val snapshot = stable_snapshot(state, version, name)
   151                   val status = Document_Status.Node_Status.make(state, version, name)
   152                   commit.get.apply(snapshot, status)
   153                   committed + (name -> status)
   154                 }
   155                 else committed
   156               })
   157             copy(already_committed = already_committed1)
   158           }
   159           else this
   160 
   161         if (beyond_limit || watchdog(watchdog_timeout) ||
   162           dep_theories.forall(name =>
   163             already_committed.isDefinedAt(name) ||
   164             state.node_consolidated(version, name) ||
   165             nodes_status.quasi_consolidated(name)))
   166         {
   167           val nodes =
   168             for (name <- dep_theories)
   169             yield { (name -> Document_Status.Node_Status.make(state, version, name)) }
   170           val nodes_committed =
   171             for {
   172               name <- dep_theories
   173               status <- already_committed.get(name)
   174             } yield (name -> status)
   175 
   176           try { result.fulfill(new Theories_Result(state, version, nodes, nodes_committed)) }
   177           catch { case _: IllegalStateException => }
   178         }
   179 
   180         st1
   181       }
   182     }
   183 
   184     def use_theories(
   185       theories: List[String],
   186       qualifier: String = Sessions.DRAFT,
   187       master_dir: String = "",
   188       check_delay: Time = default_check_delay,
   189       check_limit: Int = 0,
   190       watchdog_timeout: Time = default_watchdog_timeout,
   191       nodes_status_delay: Time = default_nodes_status_delay,
   192       id: UUID = UUID(),
   193       // commit: must not block, must not fail
   194       commit: Option[(Document.Snapshot, Document_Status.Node_Status) => Unit] = None,
   195       commit_cleanup_delay: Time = default_commit_cleanup_delay,
   196       progress: Progress = No_Progress): Theories_Result =
   197     {
   198       val dep_theories =
   199       {
   200         val import_names =
   201           theories.map(thy =>
   202             resources.import_name(qualifier, master_directory(master_dir), thy) -> Position.none)
   203         resources.dependencies(import_names, progress = progress).check_errors.theories
   204       }
   205 
   206       val use_theories_state = Synchronized(Use_Theories_State())
   207 
   208       def check_result(beyond_limit: Boolean = false)
   209       {
   210         val state = session.current_state()
   211         state.stable_tip_version match {
   212           case Some(version) =>
   213             use_theories_state.change(
   214               _.check_result(state, version, dep_theories, beyond_limit, watchdog_timeout, commit))
   215           case None =>
   216         }
   217       }
   218 
   219       val check_progress =
   220       {
   221         var check_count = 0
   222         Event_Timer.request(Time.now(), repeat = Some(check_delay))
   223           {
   224             if (progress.stopped) use_theories_state.value.cancel_result
   225             else {
   226               check_count += 1
   227               check_result(check_limit > 0 && check_count > check_limit)
   228             }
   229           }
   230       }
   231 
   232       val consumer =
   233       {
   234         val delay_nodes_status =
   235           Standard_Thread.delay_first(nodes_status_delay max Time.zero) {
   236             progress.nodes_status(use_theories_state.value.nodes_status)
   237           }
   238 
   239         val delay_commit_clean =
   240           Standard_Thread.delay_first(commit_cleanup_delay max Time.zero) {
   241             val clean = use_theories_state.value.already_committed.keySet
   242             resources.clean_theories(session, id, clean)
   243           }
   244 
   245         val dep_theories_set = dep_theories.toSet
   246 
   247         Session.Consumer[Session.Commands_Changed](getClass.getName) {
   248           case changed =>
   249             if (changed.nodes.exists(dep_theories_set)) {
   250               val snapshot = session.snapshot()
   251               val state = snapshot.state
   252               val version = snapshot.version
   253 
   254               val theory_progress =
   255                 use_theories_state.change_result(st =>
   256                   {
   257                     val domain =
   258                       if (st.nodes_status.is_empty) dep_theories_set
   259                       else changed.nodes.iterator.filter(dep_theories_set).toSet
   260 
   261                     val (nodes_status_changed, nodes_status1) =
   262                       st.nodes_status.update(resources.session_base, state, version,
   263                         domain = Some(domain), trim = changed.assignment)
   264 
   265                     if (nodes_status_delay >= Time.zero && nodes_status_changed) {
   266                       delay_nodes_status.invoke
   267                     }
   268 
   269                     val theory_progress =
   270                       (for {
   271                         (name, node_status) <- nodes_status1.present.iterator
   272                         if changed.nodes.contains(name) && !st.already_committed.isDefinedAt(name)
   273                         p1 = node_status.percentage
   274                         if p1 > 0 && Some(p1) != st.nodes_status.get(name).map(_.percentage)
   275                       } yield Progress.Theory(name.theory, percentage = Some(p1))).toList
   276 
   277                     (theory_progress, st.update(nodes_status1))
   278                   })
   279 
   280               theory_progress.foreach(progress.theory(_))
   281 
   282               check_result()
   283 
   284               if (commit.isDefined && commit_cleanup_delay > Time.zero) {
   285                 if (use_theories_state.value.finished_result)
   286                   delay_commit_clean.revoke
   287                 else delay_commit_clean.invoke
   288               }
   289             }
   290         }
   291       }
   292 
   293       try {
   294         session.commands_changed += consumer
   295         resources.load_theories(session, id, dep_theories, progress)
   296         use_theories_state.value.await_result
   297         check_progress.cancel
   298       }
   299       finally {
   300         session.commands_changed -= consumer
   301         resources.unload_theories(session, id, dep_theories)
   302       }
   303 
   304       use_theories_state.value.join_result
   305     }
   306 
   307     def purge_theories(
   308       theories: List[String],
   309       qualifier: String = Sessions.DRAFT,
   310       master_dir: String = "",
   311       all: Boolean = false): (List[Document.Node.Name], List[Document.Node.Name]) =
   312     {
   313       val nodes =
   314         if (all) None
   315         else Some(theories.map(resources.import_name(qualifier, master_directory(master_dir), _)))
   316       resources.purge_theories(session, nodes)
   317     }
   318   }
   319 
   320 
   321 
   322   /** resources **/
   323 
   324   object Resources
   325   {
   326     final class Theory private[Headless](
   327       val node_name: Document.Node.Name,
   328       val node_header: Document.Node.Header,
   329       val text: String,
   330       val node_required: Boolean)
   331     {
   332       override def toString: String = node_name.toString
   333 
   334       def node_perspective: Document.Node.Perspective_Text =
   335         Document.Node.Perspective(node_required, Text.Perspective.empty, Document.Node.Overlays.empty)
   336 
   337       def make_edits(text_edits: List[Text.Edit]): List[Document.Edit_Text] =
   338         List(node_name -> Document.Node.Deps(node_header),
   339           node_name -> Document.Node.Edits(text_edits),
   340           node_name -> node_perspective)
   341 
   342       def node_edits(old: Option[Theory]): List[Document.Edit_Text] =
   343       {
   344         val (text_edits, old_required) =
   345           if (old.isEmpty) (Text.Edit.inserts(0, text), false)
   346           else (Text.Edit.replace(0, old.get.text, text), old.get.node_required)
   347 
   348         if (text_edits.isEmpty && node_required == old_required) Nil
   349         else make_edits(text_edits)
   350       }
   351 
   352       def purge_edits: List[Document.Edit_Text] =
   353         make_edits(Text.Edit.removes(0, text))
   354 
   355       def required(required: Boolean): Theory =
   356         if (required == node_required) this
   357         else new Theory(node_name, node_header, text, required)
   358     }
   359 
   360     sealed case class State(
   361       required: Multi_Map[Document.Node.Name, UUID] = Multi_Map.empty,
   362       theories: Map[Document.Node.Name, Theory] = Map.empty)
   363     {
   364       lazy val theory_graph: Graph[Document.Node.Name, Unit] =
   365       {
   366         val entries =
   367           for ((name, theory) <- theories.toList)
   368           yield ((name, ()), theory.node_header.imports.map(_._1).filter(theories.isDefinedAt(_)))
   369         Graph.make(entries, symmetric = true)(Document.Node.Name.Ordering)
   370       }
   371 
   372       def is_required(name: Document.Node.Name): Boolean = required.isDefinedAt(name)
   373 
   374       def insert_required(id: UUID, names: List[Document.Node.Name]): State =
   375         copy(required = (required /: names)(_.insert(_, id)))
   376 
   377       def remove_required(id: UUID, names: List[Document.Node.Name]): State =
   378         copy(required = (required /: names)(_.remove(_, id)))
   379 
   380       def update_theories(update: List[(Document.Node.Name, Theory)]): State =
   381         copy(theories =
   382           (theories /: update)({ case (thys, (name, thy)) =>
   383             thys.get(name) match {
   384               case Some(thy1) if thy1 == thy => thys
   385               case _ => thys + (name -> thy)
   386             }
   387           }))
   388 
   389       def remove_theories(remove: List[Document.Node.Name]): State =
   390       {
   391         require(remove.forall(name => !is_required(name)))
   392         copy(theories = theories -- remove)
   393       }
   394 
   395       def unload_theories(session: Session, id: UUID, dep_theories: List[Document.Node.Name]): State =
   396       {
   397         val st1 = remove_required(id, dep_theories)
   398         val theory_edits =
   399           for {
   400             node_name <- dep_theories
   401             theory <- st1.theories.get(node_name)
   402           }
   403           yield {
   404             val theory1 = theory.required(st1.is_required(node_name))
   405             val edits = theory1.node_edits(Some(theory))
   406             (edits, (node_name, theory1))
   407           }
   408         session.update(Document.Blobs.empty, theory_edits.flatMap(_._1))
   409         st1.update_theories(theory_edits.map(_._2))
   410       }
   411 
   412       def purge_theories(session: Session, nodes: List[Document.Node.Name])
   413         : ((List[Document.Node.Name], List[Document.Node.Name]), State) =
   414       {
   415         val all_nodes = theory_graph.topological_order
   416         val purge = nodes.filterNot(is_required(_)).toSet
   417 
   418         val retain = theory_graph.all_preds(all_nodes.filterNot(purge)).toSet
   419         val (retained, purged) = all_nodes.partition(retain)
   420 
   421         val purge_edits = purged.flatMap(name => theories(name).purge_edits)
   422         session.update(Document.Blobs.empty, purge_edits)
   423 
   424         ((purged, retained), remove_theories(purged))
   425       }
   426 
   427       def frontier_theories(clean: Set[Document.Node.Name]): Set[Document.Node.Name] =
   428       {
   429         @tailrec def frontier(base: List[Document.Node.Name], front: Set[Document.Node.Name])
   430           : Set[Document.Node.Name] =
   431         {
   432           val add = base.filter(b => theory_graph.imm_succs(b).forall(front))
   433           if (add.isEmpty) front
   434           else {
   435             val pre_add = add.map(theory_graph.imm_preds)
   436             val base1 = (pre_add.head /: pre_add.tail)(_ ++ _).toList.filter(clean)
   437             frontier(base1, front ++ add)
   438           }
   439         }
   440         frontier(theory_graph.maximals.filter(clean), Set.empty)
   441       }
   442     }
   443   }
   444 
   445   class Resources(session_base: Sessions.Base, log: Logger = No_Logger)
   446     extends isabelle.Resources(session_base, log = log)
   447   {
   448     resources =>
   449 
   450     private val state = Synchronized(Resources.State())
   451 
   452     def load_theories(
   453       session: Session,
   454       id: UUID,
   455       dep_theories: List[Document.Node.Name],
   456       progress: Progress)
   457     {
   458       val loaded_theories =
   459         for (node_name <- dep_theories)
   460         yield {
   461           val path = node_name.path
   462           if (!node_name.is_theory) error("Not a theory file: " + path)
   463 
   464           progress.expose_interrupt()
   465           val text = File.read(path)
   466           val node_header = resources.check_thy_reader(node_name, Scan.char_reader(text))
   467           new Resources.Theory(node_name, node_header, text, true)
   468         }
   469 
   470       val loaded = loaded_theories.length
   471       if (loaded > 1) progress.echo("Loading " + loaded + " theories ...")
   472 
   473       state.change(st =>
   474         {
   475           val st1 = st.insert_required(id, dep_theories)
   476           val theory_edits =
   477             for (theory <- loaded_theories)
   478             yield {
   479               val node_name = theory.node_name
   480               val theory1 = theory.required(st1.is_required(node_name))
   481               val edits = theory1.node_edits(st1.theories.get(node_name))
   482               (edits, (node_name, theory1))
   483             }
   484           session.update(Document.Blobs.empty, theory_edits.flatMap(_._1))
   485           st1.update_theories(theory_edits.map(_._2))
   486         })
   487     }
   488 
   489     def unload_theories(session: Session, id: UUID, dep_theories: List[Document.Node.Name])
   490     {
   491       state.change(_.unload_theories(session, id, dep_theories))
   492     }
   493 
   494     def clean_theories(session: Session, id: UUID, clean: Set[Document.Node.Name])
   495     {
   496       state.change(st =>
   497         {
   498           val frontier = st.frontier_theories(clean).toList
   499           if (frontier.isEmpty) st
   500           else {
   501             val st1 = st.unload_theories(session, id, frontier)
   502             val (_, st2) = st1.purge_theories(session, frontier)
   503             st2
   504           }
   505         })
   506     }
   507 
   508     def purge_theories(session: Session, nodes: Option[List[Document.Node.Name]])
   509       : (List[Document.Node.Name], List[Document.Node.Name]) =
   510     {
   511       state.change_result(st => st.purge_theories(session, nodes getOrElse st.theory_graph.keys))
   512     }
   513   }
   514 }