@tsplc/build 0.2.21 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +2 -2
  2. package/dist/cli.js +1052 -836
  3. package/dist/cli.js.map +27 -24
  4. package/dist/images.js +165 -0
  5. package/dist/images.js.map +12 -0
  6. package/dist/index.js +888 -668
  7. package/dist/index.js.map +23 -20
  8. package/dist/libraries.js +4 -3
  9. package/dist/libraries.js.map +3 -3
  10. package/docker/Dockerfile.dockerignore +0 -4
  11. package/docker/Dockerfile.source +5 -0
  12. package/docker/build-image +30 -26
  13. package/docker/config.ts +1 -1
  14. package/docker/install/wine-signal/README.md +1 -1
  15. package/docker/runner.ts +9 -7
  16. package/package.json +24 -8
  17. package/python/build.py +231 -20
  18. package/python/codesys_online.py +121 -10
  19. package/python/worker.py +2 -0
  20. package/src/artifacts.ts +9 -7
  21. package/src/build.ts +9 -4
  22. package/src/cli.ts +11 -20
  23. package/src/controller-online.ts +145 -61
  24. package/src/controller-protocol.ts +48 -5
  25. package/src/controller-session.ts +386 -147
  26. package/src/device-tree.ts +1 -1
  27. package/src/docker-build.ts +80 -98
  28. package/src/docker-context.ts +56 -3
  29. package/src/docker-run.ts +56 -3
  30. package/src/engineering-settings.ts +3 -3
  31. package/src/host/codesys-host.ts +3 -3
  32. package/src/host/codesys-worker.ts +77 -3
  33. package/src/images.ts +105 -0
  34. package/src/import-request.ts +1 -0
  35. package/src/index.ts +30 -16
  36. package/src/io.ts +1 -1
  37. package/src/libraries.ts +3 -2
  38. package/src/project-operations.ts +48 -0
  39. package/src/run.ts +9 -6
  40. package/src/sources.ts +2 -2
  41. package/docker/install/wine-signal/check.sh +0 -34
  42. package/docker/install/wine-signal/tests/avx-registers.c +0 -53
  43. package/docker/install/wine-signal/tests/frame-and-handler.c +0 -192
  44. package/docker/install/wine-signal/tests/loader-i386.c +0 -8
  45. package/docker/install/wine-signal/tests/signal-return.c +0 -47
  46. package/python/test_build.py +0 -579
  47. package/python/test_codesys_login.py +0 -139
  48. package/python/test_codesys_online.py +0 -259
  49. package/python/test_installer_packages.py +0 -217
  50. package/python/test_installer_verification.py +0 -307
  51. package/python/test_worker.py +0 -154
package/python/build.py CHANGED
@@ -13,7 +13,9 @@ try:
13
13
  except NameError:
14
14
  unicode = str
15
15
  import shutil
16
+ import tempfile
16
17
  import time
18
+ from xml.sax.saxutils import escape, quoteattr
17
19
 
18
20
  from hardware import apply_controller, configure_device_tree, import_device_description, verify_pinned
19
21
 
@@ -23,6 +25,8 @@ NANOSECONDS_PER_MILLISECOND = 1000000
23
25
  # A task interval is a TIME, which counts milliseconds in 32 bits.
24
26
  MAX_INTERVAL_NANOSECONDS = 0xFFFFFFFF * NANOSECONDS_PER_MILLISECOND
25
27
  MAX_TASK_PRIORITY = 31
28
+ # A long import reports how far it got after this many source objects.
29
+ IMPORT_PROGRESS_INTERVAL = 250
26
30
  # How a task reads back an interval written in milliseconds, such as T#20ms.
27
31
  TIME_MILLISECONDS = re.compile(r"^(?:T|TIME)#([0-9]+(?:\.[0-9]+)?)MS$", re.I)
28
32
 
@@ -143,6 +147,34 @@ def unique_child(parent, name):
143
147
  return matches[0] if matches else None
144
148
 
145
149
 
150
+ class SourceLookup(object):
151
+ """One import's record of the names under each parent it looks in. Every CODESYS lookup crosses
152
+ the scripting bridge, and importing thousands of objects into a template made one per object for
153
+ names the parent cannot hold. A parent's children are listed once; a name absent from that list is
154
+ absent, and only a name it holds is looked up in CODESYS, so a match is always CODESYS's own.
155
+ Names stay recorded after a removal, which only costs that name a lookup."""
156
+
157
+ def __init__(self):
158
+ self.names = {}
159
+ self.folders = {}
160
+
161
+ def held(self, parent):
162
+ key = unicode(parent.guid)
163
+ names = self.names.get(key)
164
+ if names is None:
165
+ names = set(unicode(child.get_name()).lower() for child in parent.get_children())
166
+ self.names[key] = names
167
+ return names
168
+
169
+ def child(self, parent, name):
170
+ if name.lower() not in self.held(parent):
171
+ return None
172
+ return unique_child(parent, name)
173
+
174
+ def created(self, parent, name):
175
+ self.held(parent).add(name.lower())
176
+
177
+
146
178
  def create_object(engine, parent, spec):
147
179
  kind, name = spec["kind"], spec["name"]
148
180
  if kind == "dut":
@@ -178,13 +210,17 @@ def create_object(engine, parent, spec):
178
210
  raise RuntimeError("Unsupported IEC object kind " + kind)
179
211
 
180
212
 
181
- def import_object(engine, parent, spec, previous):
213
+ def import_object(engine, parent, spec, previous, lookup):
182
214
  """Writes the object's text unless `previous`, the spec the project already holds, has the same.
183
215
  Each write costs a parse, and a compiler model that sees nothing changed builds and transfers less.
184
216
  Returns how many objects were written."""
185
- obj = unique_child(parent, spec["name"])
217
+ if previous == spec:
218
+ # The project holds exactly this object and its children, so nothing needs reading either.
219
+ return 0
220
+ obj = lookup.child(parent, spec["name"])
186
221
  if obj is None:
187
222
  obj = create_object(engine, parent, spec)
223
+ lookup.created(parent, spec["name"])
188
224
  previous = None
189
225
  written = 0
190
226
  if previous is None or any(previous.get(key) != spec.get(key) for key in ("declaration", "implementation")):
@@ -202,7 +238,7 @@ def import_object(engine, parent, spec, previous):
202
238
  child.remove()
203
239
  held = dict((child["name"].lower(), child) for child in previous.get("children", [])) if previous else {}
204
240
  for child in children:
205
- written += import_object(engine, obj, child, held.get(child["name"].lower()))
241
+ written += import_object(engine, obj, child, held.get(child["name"].lower()), lookup)
206
242
  return written
207
243
 
208
244
 
@@ -299,21 +335,27 @@ def reconcile(application, previous, current):
299
335
  return gone
300
336
 
301
337
 
302
- def source_folder(application, path):
338
+ def source_folder(application, path, lookup):
303
339
  """The folder at `path` under the application, creating the folders it lacks."""
304
- parent = application
305
- for name in path:
340
+ key = tuple(path)
341
+ if key in lookup.folders:
342
+ return lookup.folders[key]
343
+ parent = application if not path else source_folder(application, path[:-1], lookup)
344
+ if not path:
345
+ return parent
346
+ name = path[-1]
347
+ folder = lookup.child(parent, name)
348
+ if folder is None:
349
+ # create_folder returns None in CODESYS; resolve the inserted object.
350
+ parent.create_folder(name)
306
351
  folder = unique_child(parent, name)
307
352
  if folder is None:
308
- # create_folder returns None in CODESYS; resolve the inserted object.
309
- parent.create_folder(name)
310
- folder = unique_child(parent, name)
311
- if folder is None:
312
- raise RuntimeError("Could not create source folder " + name)
313
- elif not folder.is_folder:
314
- raise RuntimeError("Source folder conflicts with IEC object " + name)
315
- parent = folder
316
- return parent
353
+ raise RuntimeError("Could not create source folder " + name)
354
+ lookup.created(parent, name)
355
+ elif not folder.is_folder:
356
+ raise RuntimeError("Source folder conflicts with IEC object " + name)
357
+ lookup.folders[key] = folder
358
+ return folder
317
359
 
318
360
 
319
361
  def clear_template(application, request):
@@ -321,8 +363,13 @@ def clear_template(application, request):
321
363
  for name in request["removeObjects"]:
322
364
  for obj in application.find_ignore_transient_objects(name, True):
323
365
  obj.remove()
366
+ # A template holds a few objects and a source thousands: one walk of the template's names
367
+ # spares a recursive CODESYS search for each source object it cannot hold.
368
+ names = set(unicode(child.get_name()).lower() for child in application.get_children(True))
324
369
  # Source objects own their complete subtree, including removed methods.
325
370
  for spec in request["objects"]:
371
+ if spec["name"].lower() not in names:
372
+ continue
326
373
  existing = application.find_ignore_transient_objects(spec["name"], True)
327
374
  if len(existing) > 1:
328
375
  raise RuntimeError("Ambiguous IEC object " + spec["name"])
@@ -347,6 +394,161 @@ def configure_entry_task(application, name, entry):
347
394
  raise RuntimeError("Could not configure the entry task: " + repr(list(task.pous)))
348
395
 
349
396
 
397
+ PLCOPEN_NAMESPACE = "http://www.plcopen.org/xml/tc6_0200"
398
+ XHTML_NAMESPACE = "http://www.w3.org/1999/xhtml"
399
+ CODESYS_DATA = "http://www.3s-software.com/plcopenxml/"
400
+ POU_TYPES = {"program": "program", "function_block": "functionBlock", "function": "function"}
401
+
402
+
403
+ def bulk_importable(spec):
404
+ """Kinds whose PLCopenXML form CODESYS exports as plain text: POUs with methods and actions.
405
+ Types, variable lists, interfaces and properties are imported one at a time."""
406
+ return spec["kind"] in POU_TYPES and all(child["kind"] in ("method", "action") for child in spec.get("children", []))
407
+
408
+
409
+ def object_id(spec, *parents):
410
+ """A stable GUID for the object's place in the document; a full download needs no other identity."""
411
+ key = u"/".join([u"/".join(spec.get("folder", []))] + list(parents) + [spec["name"]])
412
+ digest = hashlib.sha256(key.lower().encode("utf-8")).hexdigest()
413
+ return u"{0}-{1}-{2}-{3}-{4}".format(digest[:8], digest[8:12], digest[12:16], digest[16:20], digest[20:32])
414
+
415
+
416
+ def xhtml(text):
417
+ return u'<xhtml xmlns="{0}">{1}</xhtml>'.format(XHTML_NAMESPACE, escape(text))
418
+
419
+
420
+ def plain_text_interface(declaration):
421
+ return (u'<data name="{0}interfaceasplaintext" handleUnknown="implementation">'
422
+ u"<InterfaceAsPlainText>{1}</InterfaceAsPlainText></data>").format(CODESYS_DATA, xhtml(declaration))
423
+
424
+
425
+ def st_body(spec):
426
+ return u"<body><ST>{0}</ST></body>".format(xhtml(spec.get("implementation", u"")))
427
+
428
+
429
+ def pou_element(spec):
430
+ methods = [child for child in spec.get("children", []) if child["kind"] == "method"]
431
+ actions = [child for child in spec.get("children", []) if child["kind"] == "action"]
432
+ parts = [u"<pou name={0} pouType={1}>".format(quoteattr(spec["name"]), quoteattr(POU_TYPES[spec["kind"]])), u"<interface/>"]
433
+ if actions:
434
+ parts.append(u"<actions>{0}</actions>".format(u"".join(
435
+ u"<action name={0}>{1}</action>".format(quoteattr(action["name"]), st_body(action)) for action in actions)))
436
+ parts.append(st_body(spec))
437
+ parts.append(u"<addData>")
438
+ for method in methods:
439
+ parts.append((u'<data name="{0}method" handleUnknown="implementation"><Method name={1} ObjectId={2}>'
440
+ u"<interface/>{3}<addData>{4}</addData></Method></data>").format(
441
+ CODESYS_DATA, quoteattr(method["name"]), quoteattr(object_id(method, spec["name"])),
442
+ st_body(method), plain_text_interface(method["declaration"])))
443
+ parts.append(plain_text_interface(spec["declaration"]))
444
+ parts.append(u'<data name="{0}objectid" handleUnknown="discard"><ObjectId>{1}</ObjectId></data>'.format(
445
+ CODESYS_DATA, object_id(spec)))
446
+ parts.append(u"</addData></pou>")
447
+ return u"".join(parts)
448
+
449
+
450
+ def project_structure(specs):
451
+ """CODESYS's folder tree for the document's objects, which it places them in on import."""
452
+ root = {"folders": {}, "objects": []}
453
+ for spec in specs:
454
+ node = root
455
+ for name in spec.get("folder", []):
456
+ node = node["folders"].setdefault(name, {"folders": {}, "objects": []})
457
+ node["objects"].append(spec)
458
+ def render(node):
459
+ return u"".join([u"<Folder Name={0}>{1}</Folder>".format(quoteattr(name), render(child))
460
+ for name, child in sorted(node["folders"].items())] +
461
+ [u"<Object Name={0} ObjectId={1}/>".format(quoteattr(spec["name"]), quoteattr(object_id(spec)))
462
+ for spec in node["objects"]])
463
+ return u"<ProjectStructure>{0}</ProjectStructure>".format(render(root))
464
+
465
+
466
+ def plcopen_document(specs):
467
+ """One PLCopenXML document holding `specs`, each a `bulk_importable` source object."""
468
+ return u"".join([
469
+ u'<?xml version="1.0" encoding="utf-8"?>',
470
+ u'<project xmlns="{0}">'.format(PLCOPEN_NAMESPACE),
471
+ u'<fileHeader companyName="tsPLC" productName="tsPLC" productVersion="1" creationDateTime="2000-01-01T00:00:00"/>',
472
+ u'<contentHeader name="tsPLC"><coordinateInfo><fbd><scaling x="1" y="1"/></fbd>'
473
+ u'<ld><scaling x="1" y="1"/></ld><sfc><scaling x="1" y="1"/></sfc></coordinateInfo></contentHeader>',
474
+ u"<types><dataTypes/><pous>", u"".join(pou_element(spec) for spec in specs), u"</pous></types>",
475
+ u"<instances><configurations/></instances>",
476
+ u'<addData><data name="{0}projectstructure" handleUnknown="discard">{1}</data></addData>'.format(
477
+ CODESYS_DATA, project_structure(specs)),
478
+ u"</project>",
479
+ ])
480
+
481
+
482
+ def import_reporter(engine, errors):
483
+ """Collects what a PLCopenXML import reports; any error or skipped object fails it."""
484
+ base = getattr(engine, "ImportReporter", object)
485
+ class Reporter(base):
486
+ def error(self, message):
487
+ errors.append(unicode(message))
488
+ def warning(self, message):
489
+ pass
490
+ def resolve_conflict(self, obj):
491
+ errors.append(u"Conflicting object " + unicode(obj))
492
+ return engine.ConflictResolve.Skip
493
+ def added(self, obj):
494
+ pass
495
+ def replaced(self, obj):
496
+ pass
497
+ def skipped(self, obj):
498
+ errors.append(u"Skipped " + unicode(obj))
499
+ @property
500
+ def aborting(self):
501
+ return False
502
+ return Reporter()
503
+
504
+
505
+ def placed_objects(application):
506
+ """(folder path, lowercase name) of every object under the application's folders, one call per folder."""
507
+ placed = set()
508
+ def visit(node, path):
509
+ for child in node.get_children():
510
+ if getattr(child, "is_folder", False):
511
+ visit(child, path + (unicode(child.get_name()),))
512
+ else:
513
+ placed.add((path, unicode(child.get_name()).lower()))
514
+ visit(application, ())
515
+ return placed
516
+
517
+
518
+ def bulk_import(engine, application, request, progress):
519
+ """Imports a template download's POUs in one PLCopenXML import instead of one call and parse
520
+ each. Opt-in: anything CODESYS reports, or an object it didn't place where the source puts it,
521
+ removes what it imported, and every object is then imported one at a time. Returns the objects
522
+ left to import one at a time."""
523
+ objects = request["objects"]
524
+ bulk = [spec for spec in objects if bulk_importable(spec)]
525
+ if not bulk:
526
+ return objects
527
+ progress("Importing {0} POUs in one PLCopenXML import".format(len(bulk)))
528
+ handle, path = tempfile.mkstemp(suffix=".xml")
529
+ os.close(handle)
530
+ try:
531
+ with io.open(path, "w", encoding="utf-8") as output:
532
+ output.write(plcopen_document(bulk))
533
+ errors = []
534
+ application.import_xml(import_reporter(engine, errors), path, True)
535
+ if errors:
536
+ raise RuntimeError("; ".join(errors[:5]))
537
+ placed = placed_objects(application)
538
+ missing = [spec["name"] for spec in bulk if (tuple(spec["folder"]), spec["name"].lower()) not in placed]
539
+ if missing:
540
+ raise RuntimeError("CODESYS did not place " + ", ".join(missing[:5]))
541
+ except Exception as error:
542
+ progress("The PLCopenXML import failed ({0}); importing every object one at a time".format(
543
+ " ".join(unicode(error).split())))
544
+ clear_template(application, request)
545
+ return objects
546
+ finally:
547
+ os.remove(path)
548
+ progress("Imported {0} POUs".format(len(bulk)))
549
+ return [spec for spec in objects if not bulk_importable(spec)]
550
+
551
+
350
552
  def import_objects(engine, application, request, previous, progress):
351
553
  """`previous` lists the source objects the project already holds, reconciled with this request;
352
554
  None imports every object afresh."""
@@ -355,14 +557,21 @@ def import_objects(engine, application, request, previous, progress):
355
557
  manager = application.get_library_manager()
356
558
  for reference in request["libraryReferences"]:
357
559
  manager.add_library(reference)
358
- progress("Importing source objects")
560
+ objects = request["objects"]
359
561
  if previous is None:
562
+ progress("Clearing the template's objects the source replaces")
360
563
  clear_template(application, request)
564
+ if request.get("bulkImport"):
565
+ objects = bulk_import(engine, application, request, progress)
566
+ progress("Importing {0} source objects".format(len(objects)))
361
567
  held = dict(((tuple(item["folder"]), item["name"].lower()), item) for item in previous or [])
568
+ lookup = SourceLookup()
362
569
  written = 0
363
- for spec in request["objects"]:
364
- parent = source_folder(application, spec["folder"])
365
- written += import_object(engine, parent, spec, held.get((tuple(spec["folder"]), spec["name"].lower())))
570
+ for index, spec in enumerate(objects):
571
+ parent = source_folder(application, spec["folder"], lookup)
572
+ written += import_object(engine, parent, spec, held.get((tuple(spec["folder"]), spec["name"].lower())), lookup)
573
+ if (index + 1) % IMPORT_PROGRESS_INTERVAL == 0 and index + 1 < len(objects):
574
+ progress("Imported {0} of {1} source objects ({2} written)".format(index + 1, len(objects), written))
366
575
  progress("Wrote {0} source objects".format(written))
367
576
  if "tasks" in request:
368
577
  return configure_tasks(engine, application, request["tasks"], request["objects"])
@@ -459,6 +668,8 @@ def import_source(engine, application, request, previous, progress):
459
668
  holds, None for a template. Returns the configured task plan, None when the request rewires the template's entry task."""
460
669
  gone = reconcile(application, previous, request["objects"]) if previous is not None else []
461
670
  configured_tasks = import_objects(engine, application, request, previous, progress)
671
+ if gone:
672
+ progress("Removing {0} objects gone from the source".format(len(gone)))
462
673
  for obj in gone:
463
674
  obj.remove()
464
675
  if request["symbols"] and not any(
@@ -576,8 +787,8 @@ def open_project(engine, request, workspace, progress):
576
787
  def compile_application(engine, application, progress):
577
788
  progress("Clearing previous diagnostics")
578
789
  clear_diagnostics(engine)
790
+ # A rebuild cleans first; a separate clean only repeats it.
579
791
  progress("Rebuilding application")
580
- application.clean()
581
792
  application.rebuild()
582
793
  fail_on_errors(engine)
583
794
  progress("Generating application code")
@@ -17,6 +17,13 @@ EMPTY_GUID = '00000000-0000-0000-0000-000000000000'
17
17
  GATEWAY_NAME = 'codesys-build'
18
18
 
19
19
 
20
+ def download_required(message):
21
+ """A refusal only a full download resolves; the worker marks its reply so callers can offer one."""
22
+ error = RuntimeError(message)
23
+ error.download_required = True
24
+ return error
25
+
26
+
20
27
  def core_application(online_application):
21
28
  # The shipped scripting wrapper omits Keep from its login switch. Its core
22
29
  # application provides a session-only login, which never compiles/downloads.
@@ -38,17 +45,64 @@ def loaded_type(name):
38
45
  raise RuntimeError('CODESYS API type is unavailable: ' + name)
39
46
 
40
47
 
41
- def session_login(core):
48
+ def read_only_login(core):
49
+ """A session-only, read-only login; False when the controller holds no application of this name."""
42
50
  kind = loaded_type('_3S.CoDeSys.OnlineManager.OnlineApplicationLoginConfiguration')
43
51
  config = Activator.CreateInstance(kind)
44
52
  mode = loaded_type('_3S.CoDeSys.Core.Online.ApplicationLoginClientModes')
45
53
  kind.GetProperty('ClientModes').SetValue(config, Enum.Parse(mode, 'ReadOnly'), None)
46
54
  api = loaded_type('_3S.CoDeSys.Core.Online.IOnlineApplication23')
47
55
  login = api.GetMethod('Login')
48
- if not login.Invoke(core, Array[Object]([True, config])):
56
+ return bool(login.Invoke(core, Array[Object]([True, config])))
57
+
58
+
59
+ def session_login(core):
60
+ if not read_only_login(core):
49
61
  raise RuntimeError('The controller does not contain this application')
50
62
 
51
63
 
64
+ def enter_phase(request, phase):
65
+ """Tells the host which budget applies: `prepare` may be stopped, a `transfer` never is."""
66
+ path = request.get('phase')
67
+ if path:
68
+ with io.open(path, 'w', encoding='utf-8') as output:
69
+ output.write(phase)
70
+
71
+
72
+ def failure_text(error):
73
+ cause = getattr(error, 'InnerException', None)
74
+ return ' '.join(str(cause if cause is not None else error).split())
75
+
76
+
77
+ def preflight(engine, application, request, progress):
78
+ """Logs in read-only before a download changes anything, so a gateway, controller or user it
79
+ can't reach fails it in seconds, before the import, with the controller untouched. Returns the
80
+ controller's identity and state of this application, None when it holds none of this name."""
81
+ if request.get('initializeUser'):
82
+ progress('Skipping the preflight login: this download creates the controller user')
83
+ return None
84
+ progress('Preflight: logging in read-only to check the gateway, controller and user')
85
+ online_app = engine.online.create_online_application(application)
86
+ try:
87
+ core = core_application(online_app)
88
+ try:
89
+ present = read_only_login(core)
90
+ except Exception as error:
91
+ raise RuntimeError('Preflight login failed, so the controller was not changed: ' + failure_text(error))
92
+ if not present:
93
+ progress('Preflight: the controller holds no application named ' + str(application.get_name()))
94
+ return None
95
+ try:
96
+ found = {'codeId': str(core.CodeId), 'dataId': str(core.DataId), 'state': controller_state(core)}
97
+ finally:
98
+ core.Logout()
99
+ progress('Preflight: the controller runs {0} ({1}, code {2})'.format(
100
+ application.get_name(), found['state'], found['codeId']))
101
+ return found
102
+ finally:
103
+ online_app.Dispose()
104
+
105
+
52
106
  def code_data_ids(compiled, missing):
53
107
  ids = {'codeId': str(compiled.CodeId), 'dataId': str(compiled.DataId)}
54
108
  if EMPTY_GUID in ids.values():
@@ -198,6 +252,53 @@ def open_operation_project(engine, request, prepared, progress):
198
252
  return engine.projects.open(request['project'], primary=True), {}, None
199
253
 
200
254
 
255
+ def restore_previous(engine, request, progress):
256
+ """Downloads the last committed project again after a download failed mid-transfer, unless the
257
+ controller still runs it. The project compiled and ran before, so this needs no import. Returns
258
+ whether it downloaded, and the controller's identity and state afterwards."""
259
+ progress('Restoring the previous application from the last committed download')
260
+ project = engine.projects.open(request['project'], primary=True)
261
+ online_app = None
262
+ online_device = None
263
+ try:
264
+ application = project.active_application
265
+ if application is None:
266
+ raise RuntimeError('The committed project has no active Application')
267
+ device, _ = connect_controller(engine, application, request['online'], request.get('credentialsFile'))
268
+ online_device = engine.online.create_online_device(device)
269
+ online_app = engine.online.create_online_application(application)
270
+ core = core_application(online_app)
271
+ expected = request['baseline']['controllerIds']
272
+ if read_only_login(core):
273
+ try:
274
+ intact = controller_ids(core) == expected and controller_state(core) == 'run'
275
+ except RuntimeError:
276
+ intact = False
277
+ finally:
278
+ core.Logout()
279
+ if intact:
280
+ progress('The controller still runs the previous application')
281
+ return {'restored': False, 'controllerIds': expected, 'state': 'run'}
282
+ enter_phase(request, u'transfer')
283
+ progress('Downloading the previous application')
284
+ online_app.login(engine.OnlineChangeOption.Never, False)
285
+ if controller_state(core) != 'run':
286
+ online_app.start()
287
+ progress('Saving the previous application as controller boot project')
288
+ create_controller_boot_project(core)
289
+ require_current_boot_project(core)
290
+ result = {'restored': True, 'controllerIds': controller_ids(core), 'state': controller_state(core)}
291
+ online_app.logout()
292
+ return result
293
+ finally:
294
+ if online_app is not None:
295
+ online_app.Dispose()
296
+ if online_device is not None:
297
+ online_device.Dispose()
298
+ # A restore never commits: the committed generation already describes this application.
299
+ project.close()
300
+
301
+
201
302
  def run_online(engine, request, prepared=None):
202
303
  """`prepared` is a project a warm worker opened ahead; an online change of that project uses it."""
203
304
  progress_path = request.get('progress')
@@ -205,6 +306,10 @@ def run_online(engine, request, prepared=None):
205
306
  if progress_path:
206
307
  write_progress(progress_path, stage)
207
308
  progress('Starting; processor count {0}'.format(Environment.ProcessorCount))
309
+ if request['operation'] == 'restore':
310
+ if prepared is not None:
311
+ prepared.close()
312
+ return restore_previous(engine, request, progress)
208
313
  previous = request.get('baseline')
209
314
  project, pinned, generated = open_operation_project(engine, request, prepared, progress)
210
315
  application = project.active_application
@@ -221,7 +326,9 @@ def run_online(engine, request, prepared=None):
221
326
  raise RuntimeError('Initial controller user requires an explicit download and credentials')
222
327
  online_device.set_credentials_for_initial_user(*credentials)
223
328
  progress('Controller connection configured')
224
- if request['operation'] != 'download':
329
+ if request['operation'] == 'download':
330
+ preflight(engine, application, request, progress)
331
+ else:
225
332
  online_app = engine.online.create_online_application(application)
226
333
  core = core_application(online_app)
227
334
  if not previous or str(application.guid) != previous['applicationGuid']:
@@ -231,10 +338,10 @@ def run_online(engine, request, prepared=None):
231
338
  try:
232
339
  observed = controller_ids(core)
233
340
  if observed != previous['controllerIds']:
234
- raise RuntimeError('Controller application differs from the saved baseline; use an explicit download')
341
+ raise download_required('Controller application differs from the saved baseline; use an explicit download')
235
342
  progress('Loading downloaded compiler reference')
236
343
  if load_downloaded_reference(application) != observed:
237
- raise RuntimeError('Downloaded compiler reference differs from the controller; use an explicit download')
344
+ raise download_required('Downloaded compiler reference differs from the controller; use an explicit download')
238
345
  progress('Downloaded compiler reference loaded')
239
346
  state = controller_state(core)
240
347
  if request['operation'] == 'online-change' and state != 'run':
@@ -248,18 +355,19 @@ def run_online(engine, request, prepared=None):
248
355
  import_source(engine, application, request, previous['objects'] if previous is not None else None, progress)
249
356
  # Match the normal build's source/template lifecycle. Saving the edited
250
357
  # tree and clearing editor-load diagnostics happens before compilation.
358
+ progress('Saving imported project')
251
359
  project.save()
252
360
  clear_diagnostics(engine)
253
361
  if request['operation'] == 'download':
254
- # A full download replaces the previous compiler model. Use the
255
- # normal build's clean/rebuild path before opening the online session.
362
+ # A full download replaces the previous compiler model. Use the normal build's
363
+ # rebuild, which cleans first, before opening the online session. The project is
364
+ # saved once the controller has it; a failed transfer discards it.
256
365
  progress('Rebuilding application for full download')
257
- application.clean()
258
366
  application.rebuild()
259
367
  fail_on_errors(engine)
368
+ progress('Generating application code')
260
369
  application.generate_code()
261
370
  verify_pinned(pinned)
262
- project.save()
263
371
  else:
264
372
  # Cleaning would discard the downloaded reference needed to decide
265
373
  # whether a source edit can be applied as an online change.
@@ -269,6 +377,8 @@ def run_online(engine, request, prepared=None):
269
377
  if request['operation'] == 'download':
270
378
  online_app = engine.online.create_online_application(application)
271
379
  core = core_application(online_app)
380
+ # From here the controller may hold neither application, so nothing may stop CODESYS.
381
+ enter_phase(request, u'transfer')
272
382
  progress('Downloading application')
273
383
  online_app.login(engine.OnlineChangeOption.Never, False)
274
384
  expected = controller_ids(core)
@@ -286,12 +396,13 @@ def run_online(engine, request, prepared=None):
286
396
  expected = controller_ids(core)
287
397
  if not application.is_uptodate:
288
398
  if not application.is_online_change_possible:
289
- raise RuntimeError('CODESYS cannot apply this source as an online change; use an explicit download')
399
+ raise download_required('CODESYS cannot apply this source as an online change; use an explicit download')
290
400
  progress('Generating online-change code')
291
401
  generate_online_code(application)
292
402
  fail_on_errors(engine)
293
403
  expected = context_ids(consolidated_manager().GetCompileContext(application.guid))
294
404
  mode = loaded_type('_3S.CoDeSys.Core.Online.BootProjectTransferMode')
405
+ enter_phase(request, u'transfer')
295
406
  progress('Applying online change')
296
407
  core.Download(True, Enum.Parse(mode, 'UseProjectSetting'))
297
408
  # An online-change transfer does not itself replace the boot project.
package/python/worker.py CHANGED
@@ -100,6 +100,8 @@ def serve(engine, directory):
100
100
  response = {"id": command["id"], "ok": False, "error": traceback.format_exc()}
101
101
  if isinstance(error, CompilerError):
102
102
  response["diagnostics"] = error.diagnostics
103
+ if getattr(error, "download_required", False):
104
+ response["downloadRequired"] = True
103
105
  write_json(engine, os.path.join(directory, command["id"] + ".json"), response)
104
106
  if command["action"] == "stop":
105
107
  return
package/src/artifacts.ts CHANGED
@@ -8,9 +8,9 @@ import {
8
8
  writeFile,
9
9
  } from "node:fs/promises";
10
10
  import { resolve } from "node:path";
11
+ import { cyclicTasksSchema } from "@tsplc/config/build";
11
12
  import { identifierPattern } from "@tsplc/iec/st";
12
13
  import { z } from "zod";
13
- import { cyclicTasksSchema } from "@tsplc/config/build";
14
14
 
15
15
  export const buildFiles = {
16
16
  project: "Application.project",
@@ -74,12 +74,14 @@ export const publishBuild = async (
74
74
  resolve(compiled.directory, buildFiles.archive),
75
75
  resolve(outDir, buildFiles.archive),
76
76
  ).catch((cause: unknown) => {
77
- if (!(
78
- cause &&
79
- typeof cause === "object" &&
80
- "code" in cause &&
81
- cause.code === "ENOENT"
82
- )) {
77
+ if (
78
+ !(
79
+ cause &&
80
+ typeof cause === "object" &&
81
+ "code" in cause &&
82
+ cause.code === "ENOENT"
83
+ )
84
+ ) {
83
85
  throw cause;
84
86
  }
85
87
  });
package/src/build.ts CHANGED
@@ -8,19 +8,24 @@ import {
8
8
  writeFile,
9
9
  } from "node:fs/promises";
10
10
  import { resolve } from "node:path";
11
+ import type { ResolvedConfig } from "@tsplc/config/build";
11
12
  import { buildFiles, publishBuild, readBuild } from "./artifacts";
12
- import { dockerImage, type ResolvedConfig } from "@tsplc/config/build";
13
- import { buildInDocker } from "./docker-build";
14
13
  import { writeDeviceTree } from "./device-tree";
14
+ import { buildInDocker } from "./docker-build";
15
+ import type { ProgressOptions } from "./docker-run.ts";
15
16
  import { createCodesysWorker, withWorkerLock } from "./host/codesys-worker";
17
+ import { builderImage } from "./images.ts";
16
18
  import { importRequest } from "./import-request";
17
19
  import { loadSources } from "./sources";
18
20
 
19
- export const buildProject = async (config: ResolvedConfig) => {
21
+ export const buildProject = async (
22
+ config: ResolvedConfig,
23
+ { progress = "stdout" }: ProgressOptions = {},
24
+ ) => {
20
25
  if (!config.docker) {
21
26
  throw new Error("Builds require a Docker builder image.");
22
27
  }
23
- return buildInDocker(config, dockerImage);
28
+ return buildInDocker(config, builderImage, progress);
24
29
  };
25
30
 
26
31
  /** The container runner owns Wine; this operation is not a public host build. */