Skip to content

Commit c6b34f8

Browse files
authored
Merge pull request #1990 from ako/integrate/pr1755-protected-modules
Install protected modules shipped as .mxmodule (#1755, with review fixes)
2 parents d82c738 + 740cd98 commit c6b34f8

6 files changed

Lines changed: 554 additions & 4 deletions

File tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{"area": "cmd/mxcli", "date": "2026-11-06", "symptom": "mendixlabs/mxcli#1754: `marketplace install` of a protected (add-on) module shipped as .mxmodule (Menditect MtaPluginModule 11.5.5, Marketplace 214717) failed with \"file is not a database\"; `mx module-import` refuses such a package outright (\"Importing protected module is not supported\", exit 111).", "cause": "The package's project.mpr is not an SQLite .mpr but one BSON document {_ProductVersion, Contents} holding the project as a single tree with every unit nested in its container, so every reader that expected SQLite failed and mx has no import for it.", "file": "cmd/mxcli/marketplace/moduletree.go (split the tree into units at Folders/Documents/DomainModel/ModuleSettings/ModuleSecurity of modules and folders; write them with AddRawUnit; write the declared package files beside the reference; refuse a tree newer than the project), cmd/mxcli/marketplace/scratch.go (PackageProject takes that path for a tree)", "insight": "Replacing `mx module-import` means replacing everything it does, not just the unit write: it also writes the package's declared files next to the .mpr and converts the module to the project's Mendix version. The first cut of mendixlabs/mxcli#1755 did only the units, which installs fine (install copies files from the .mpk) but gives `marketplace diff`/`update` a reference without javasource/javascriptsource — the #1441 'every action changed locally' failure again — and units in the package's schema. Ask which readers consume the reference (refcache.go isModelFile lists them), not only which writer produced it. The unit test asserts Start.java beside the reference, which only the InstallPackageFiles call writes; the conversion is not reproduced (no mx), only a newer tree is refused.", "refs": ["mendixlabs/mxcli#1754", "mendixlabs/mxcli#1755", "mendixlabs/mxcli#1441"], "test": "cmd/mxcli/marketplace/moduletree_test.go"}

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
1717

1818
- **`alter workflow` no longer guesses which outcome to drop** (ako/mxcli#808) — `drop X outcome 'V'` with two outcomes of value `V` dropped the first; it is refused as ambiguous now. `check --references` also resolves an activity reference by name before caption, as `exec` does, so its guards no longer go silent on a target captioned like another activity's name.
1919
- **describe → exec keeps a decision whose true branch is empty** (ako/mxcli#1963, mendixlabs/mxcli#1742) — `describe microflow` folded such a decision into `if not(X) then <false branch> end if;`, and executing that stored `not(X)` with the true and false outcomes swapped: the same behaviour, a different model in Studio Pro. It is now printed as stored, `if X then else <false branch> end if;`, which builds Studio Pro's shape. A script written from the old output still means the same thing; an `alter microflow` target written in the folded `if not(X) then` form no longer resolves, and is refused rather than applied.
20+
- **`marketplace install` installs protected (add-on) modules shipped as `.mxmodule`** — such a package carries its model not as an SQLite `.mpr` but as one BSON document holding the module as a tree, so install failed with `file is not a database`, and `mx module-import` refuses protected modules outright ("Importing protected module is not supported", exit 111). The reference project is now built by splitting that tree into units and writing them with the same raw-unit writer the transplant uses; protection settings travel unchanged. Measured on Menditect's MtaPluginModule 11.5.5 (Marketplace 214717) into an 11.15 MPR v2 app: 32 units, `mx check` 0 errors, module listed as *Protected AddOn*, and the plugin starts and serves its endpoint. The package's declared files (`javasource/`, `javascriptsource/`, …) are written beside the reference project as `mx module-import` would, so `marketplace diff` and `update` do not report every Java or JavaScript action as changed; the units are not converted to the project's Mendix version, so a package saved with a newer Mendix than the project is refused.
2021
- **`test --attach` on Mendix 11.14.0 says why it is refused instead of blaming an entity** — that version's `mxbuild --serve` fails every build after its first, so since ako/mxcli#1917 the attach builds on a fresh serve process, whose first build asks for a runtime restart whatever changed. The refusal claimed "an entity or association changed" and suggested restarting the dev loop, which does not help; it now says the build could not be done incrementally and points to `--local`. The hosting app's pages survive either way. 11.15.0 builds incrementally and attaches as before.
2122
- **`describe microflow` no longer leaves out a note linked to the start event or to another note** (ako/mxcli#1933, mendixlabs/mxcli#1731) — such a note counted as linked, so it was not printed as a free note, and the element it is linked to prints no `@annotation`, so it was not printed at all; re-executing the description deleted it. It is now described as a free note, after a `-- WARNING` line saying the link itself has no MDL form and a rewrite drops it.
2223
- **Rebuilding a described decision no longer adds a merge** (ako/mxcli#1929, mendixlabs/mxcli#1727) — a `case`, `split type` or `if … elsif` one of whose branches returns is described with its own merge as a label (`end case; join shared1; merge shared1;`). Executing that as a fresh create built the decision's merge and a second one for the label, wired merge to merge, and every further describe → drop + create added another (`join junctionN; merge junctionN;`). The label's merge is now the decision's merge when nothing else reaches it, so the round trip keeps one merge.
Lines changed: 307 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,307 @@
1+
// SPDX-License-Identifier: Apache-2.0
2+
3+
package marketplace
4+
5+
import (
6+
"archive/zip"
7+
"bytes"
8+
"fmt"
9+
"io"
10+
"path/filepath"
11+
"strings"
12+
13+
modelsdk "github.com/mendixlabs/mxcli"
14+
"github.com/mendixlabs/mxcli/internal/zipentry"
15+
"github.com/mendixlabs/mxcli/mdl/types"
16+
"go.mongodb.org/mongo-driver/v2/bson"
17+
)
18+
19+
// A module package normally carries its model as a v1 .mpr — an SQLite
20+
// database. Packages exported as protected (add-on) modules, delivered as
21+
// .mxmodule, carry something else under the same name: one BSON document,
22+
// {_ProductVersion, Contents}, where Contents is the whole project as a single
23+
// tree with every unit nested inside its container. Measured on Menditect's
24+
// MtaPluginModule 11.5.5 (Marketplace 214717): `marketplace install` failed on
25+
// it with "file is not a database", and `mx module-import` refuses it outright
26+
// ("Importing protected module is not supported", exit 111).
27+
//
28+
// The tree holds exactly the units a .mpr would, so it is split back into them
29+
// and written into the reference project with the same raw-unit writer the
30+
// transplant uses. Unit contents are copied as they are, protection settings
31+
// (ModuleSettings.ProtectedModuleType, ExportLevel) included: the result is the
32+
// module as the package ships it, not an unprotected copy.
33+
//
34+
// Two things `mx module-import` does besides writing units are done here too,
35+
// because the reference project is read for more than its units:
36+
//
37+
// - The package's declared files (javasource/, javascriptsource/, ...) are
38+
// written next to the reference .mpr. DESCRIBE JAVA ACTION and DESCRIBE
39+
// JAVASCRIPT ACTION read them, and without them every action of the module
40+
// compares as "changed locally" in `marketplace diff` and `update`
41+
// (mendixlabs/mxcli#1441).
42+
// - The units are NOT migrated. mx converts an imported module to the
43+
// project's Mendix version; these units keep the schema of the version the
44+
// package was saved with. A tree saved with a newer Mendix than the project
45+
// is refused, as mx refuses such an import; an older one is written as it
46+
// is, which is what the measurement above did (11.5.5 into 11.15). A
47+
// comparison against such a reference can therefore also report the
48+
// platform's own migrations of the module.
49+
50+
// sqliteMagic opens every SQLite database file, and so every v1 .mpr.
51+
var sqliteMagic = []byte("SQLite format 3\x00")
52+
53+
// unitContainments are the properties under which a unit holds other units.
54+
// They are stored as separate units in a .mpr, and the parent's own contents
55+
// carry none of them — measured on an 11.15 MPR v2 project: a Projects$Folder
56+
// unit is {$ID, $Type, Name}, a Projects$ModuleImpl has no Folders, Documents,
57+
// DomainModel, ModuleSettings or ModuleSecurity key.
58+
//
59+
// Only the unit kinds that hold units are split (unitHolders): a document that
60+
// happens to have a property of one of these names keeps it.
61+
var unitContainments = map[string]bool{
62+
"Folders": true,
63+
"Documents": true,
64+
"DomainModel": true,
65+
"ModuleSettings": true,
66+
"ModuleSecurity": true,
67+
}
68+
69+
// unitHolders are the unit types that contain other units in a module.
70+
var unitHolders = map[string]bool{
71+
"Projects$ModuleImpl": true,
72+
"Projects$Folder": true,
73+
}
74+
75+
// treeUnit is one unit cut out of a module tree, ready for AddRawUnit.
76+
type treeUnit struct {
77+
id, containerID, containment, unitType string
78+
contents []byte
79+
}
80+
81+
// readModuleTree returns the package's project.mpr and the Mendix version it was
82+
// saved with when it is a module tree, and nil when it is an ordinary .mpr.
83+
func readModuleTree(mpkPath string) (data []byte, productVersion string, err error) {
84+
data, err = readZipEntry(mpkPath, packageProjectEntry)
85+
if err != nil {
86+
return nil, "", err
87+
}
88+
productVersion, ok := moduleTreeVersion(data)
89+
if !ok {
90+
return nil, "", nil
91+
}
92+
return data, productVersion, nil
93+
}
94+
95+
func isModuleTree(data []byte) bool {
96+
_, ok := moduleTreeVersion(data)
97+
return ok
98+
}
99+
100+
// moduleTreeVersion reports the _ProductVersion of a module tree, and false when
101+
// data is not one.
102+
func moduleTreeVersion(data []byte) (string, bool) {
103+
if bytes.HasPrefix(data, sqliteMagic) || len(data) < 5 {
104+
return "", false
105+
}
106+
var head struct {
107+
ProductVersion string `bson:"_ProductVersion"`
108+
}
109+
if bson.Unmarshal(data, &head) != nil || head.ProductVersion == "" {
110+
return "", false
111+
}
112+
return head.ProductVersion, true
113+
}
114+
115+
// checkTreeVersion refuses a module tree saved with a newer Mendix than the
116+
// project it is written into: its units may use properties or types that
117+
// version does not have, and nothing here converts them. Only major.minor.patch
118+
// count — _ProductVersion carries a build number (11.5.5.73100) that the
119+
// project's version usually does not.
120+
func checkTreeVersion(treeVersion, projectVersion string) error {
121+
tv, pv := releaseOf(treeVersion), releaseOf(projectVersion)
122+
if tv == "" || pv == "" || !versionLess(pv, tv) {
123+
return nil
124+
}
125+
return fmt.Errorf("the package was saved with Mendix %s, which is newer than the project's %s; "+
126+
"install it from Studio Pro %s or later, or upgrade the project first", tv, pv, tv)
127+
}
128+
129+
// releaseOf keeps the first three components of a dotted version.
130+
func releaseOf(v string) string {
131+
parts := strings.Split(strings.TrimSpace(v), ".")
132+
if len(parts) > 3 {
133+
parts = parts[:3]
134+
}
135+
return strings.Join(parts, ".")
136+
}
137+
138+
// moduleTreeUnits splits the named module of a module tree into units, parents
139+
// before children. The module unit's containerID is left empty: the caller
140+
// attaches it to its own project unit.
141+
func moduleTreeUnits(data []byte, moduleName string) ([]treeUnit, error) {
142+
var root bson.D
143+
if err := bson.Unmarshal(data, &root); err != nil {
144+
return nil, fmt.Errorf("decode module tree: %w", err)
145+
}
146+
contents, ok := lookup(root, "Contents").(bson.D)
147+
if !ok {
148+
return nil, fmt.Errorf("module tree has no Contents document")
149+
}
150+
modules, _ := lookup(contents, "Modules").(bson.A)
151+
for _, m := range modules {
152+
mod, ok := m.(bson.D)
153+
if !ok || !equalFold(stringOf(lookup(mod, "Name")), moduleName) {
154+
continue
155+
}
156+
var units []treeUnit
157+
if err := splitUnit(mod, "", projectContainment, &units); err != nil {
158+
return nil, err
159+
}
160+
return units, nil
161+
}
162+
return nil, fmt.Errorf("module %q not found in the package's module tree", moduleName)
163+
}
164+
165+
// splitUnit appends doc as a unit, then recurses into the units it contains.
166+
func splitUnit(doc bson.D, containerID, containment string, units *[]treeUnit) error {
167+
id, err := idOf(doc)
168+
if err != nil {
169+
return err
170+
}
171+
unitType := stringOf(lookup(doc, "$Type"))
172+
holder := unitHolders[unitType]
173+
own := make(bson.D, 0, len(doc))
174+
var children []bson.E
175+
for _, e := range doc {
176+
if holder && unitContainments[e.Key] {
177+
children = append(children, e)
178+
continue
179+
}
180+
own = append(own, e)
181+
}
182+
encoded, err := bson.Marshal(own)
183+
if err != nil {
184+
return fmt.Errorf("encode unit %s: %w", id, err)
185+
}
186+
*units = append(*units, treeUnit{
187+
id: id,
188+
containerID: containerID,
189+
containment: containment,
190+
unitType: unitType,
191+
contents: encoded,
192+
})
193+
for _, c := range children {
194+
switch v := c.Value.(type) {
195+
case bson.D:
196+
if err := splitUnit(v, id, c.Key, units); err != nil {
197+
return err
198+
}
199+
case bson.A:
200+
// A Mendix list stores its storage-kind marker as element 0; the
201+
// units are the documents after it.
202+
for _, item := range v {
203+
if child, ok := item.(bson.D); ok {
204+
if err := splitUnit(child, id, c.Key, units); err != nil {
205+
return err
206+
}
207+
}
208+
}
209+
}
210+
}
211+
return nil
212+
}
213+
214+
// buildFromModuleTree is the module-tree counterpart of `mx module-import` for
215+
// the reference project: it writes the package's module into mprPath, a project
216+
// that does not have it yet, and the package's declared files next to it.
217+
func buildFromModuleTree(tree []byte, treeVersion, mpkPath, mprPath, moduleName, projectVersion string) error {
218+
if err := checkTreeVersion(treeVersion, projectVersion); err != nil {
219+
return err
220+
}
221+
if _, err := insertModuleTree(tree, mprPath, moduleName); err != nil {
222+
return err
223+
}
224+
if _, _, err := InstallPackageFiles(mpkPath, filepath.Dir(mprPath)); err != nil {
225+
return fmt.Errorf("write the package's files into the reference project: %w", err)
226+
}
227+
return nil
228+
}
229+
230+
// insertModuleTree writes the tree's module into mprPath, attached to that
231+
// project's project unit, and returns the number of units written.
232+
func insertModuleTree(tree []byte, mprPath, moduleName string) (int, error) {
233+
units, err := moduleTreeUnits(tree, moduleName)
234+
if err != nil {
235+
return 0, err
236+
}
237+
projectID, err := projectUnitID(mprPath)
238+
if err != nil {
239+
return 0, err
240+
}
241+
if err := refuseIfPresent(mprPath, moduleName); err != nil {
242+
return 0, err
243+
}
244+
writer, err := modelsdk.OpenForWriting(mprPath)
245+
if err != nil {
246+
return 0, fmt.Errorf("open %s for writing: %w", mprPath, err)
247+
}
248+
defer writer.Disconnect()
249+
for i, u := range units {
250+
container := u.containerID
251+
if container == "" {
252+
container = projectID
253+
}
254+
if err := writer.AddRawUnit(u.id, container, u.containment, u.unitType, u.contents); err != nil {
255+
return i, fmt.Errorf("write unit %s (%s): %w", u.id, u.unitType, err)
256+
}
257+
}
258+
return len(units), nil
259+
}
260+
261+
func lookup(doc bson.D, key string) any {
262+
for _, e := range doc {
263+
if e.Key == key {
264+
return e.Value
265+
}
266+
}
267+
return nil
268+
}
269+
270+
func stringOf(v any) string {
271+
s, _ := v.(string)
272+
return s
273+
}
274+
275+
func idOf(doc bson.D) (string, error) {
276+
switch v := lookup(doc, "$ID").(type) {
277+
case bson.Binary:
278+
if len(v.Data) == 16 {
279+
return types.BlobToUUID(v.Data), nil
280+
}
281+
case string:
282+
if v != "" {
283+
return v, nil
284+
}
285+
}
286+
return "", fmt.Errorf("%s without an $ID (a 16-byte binary or a non-empty string) in the module tree", stringOf(lookup(doc, "$Type")))
287+
}
288+
289+
func readZipEntry(zipPath, entry string) ([]byte, error) {
290+
zr, err := zip.OpenReader(zipPath)
291+
if err != nil {
292+
return nil, err
293+
}
294+
defer zr.Close()
295+
for _, f := range zr.File {
296+
if f.Name != entry {
297+
continue
298+
}
299+
rc, err := zipentry.Open(f)
300+
if err != nil {
301+
return nil, err
302+
}
303+
defer rc.Close()
304+
return io.ReadAll(rc)
305+
}
306+
return nil, fmt.Errorf("no %s in %s", entry, zipPath)
307+
}

0 commit comments

Comments
 (0)