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