Compare commits

...

5 Commits

Author SHA1 Message Date
f5283b86ed fix(app,manifest): manifest serialization
All checks were successful
arcad/edge/pipeline/head This commit looks good
2023-04-11 15:08:07 +02:00
98ebd7a168 doc(app,manifest): add metadata attribute in manifest schema
All checks were successful
arcad/edge/pipeline/head This commit looks good
2023-04-11 11:11:00 +02:00
8ca31d05c0 feat(app,manifest): validation + extendable metadatas
All checks were successful
arcad/edge/pipeline/head This commit looks good
2023-04-11 11:05:09 +02:00
34c6a089b5 fix(client,sdk): permit cross-domain message communication
All checks were successful
arcad/edge/pipeline/head This commit looks good
2023-04-06 20:54:01 +02:00
da73b842e1 fix(sdk,client): initialize crossframe observers after window load event
All checks were successful
arcad/edge/pipeline/head This commit looks good
2023-04-06 19:18:36 +02:00
23 changed files with 435 additions and 84 deletions

View File

@ -0,0 +1,11 @@
package app
import (
"forge.cadoles.com/arcad/edge/pkg/app"
"forge.cadoles.com/arcad/edge/pkg/app/metadata"
)
var manifestMetadataValidators = []app.MetadataValidator{
metadata.WithMinimumRoleValidator("visitor", "user", "superuser", "admin", "superadmin"),
metadata.WithNamedPathsValidator(metadata.NamedPathAdmin, metadata.NamedPathIcon),
}

View File

@ -52,6 +52,10 @@ func PackageCommand() *cli.Command {
return errors.Wrap(err, "could not load app manifest")
}
if valid, err := manifest.Validate(manifestMetadataValidators...); !valid {
return errors.Wrap(err, "invalid app manifest")
}
if err := os.MkdirAll(outputDir, 0o755); err != nil {
return errors.Wrapf(err, "could not create directory ''%s'", outputDir)
}

View File

@ -110,6 +110,10 @@ func RunCommand() *cli.Command {
return errors.Wrap(err, "could not load manifest from app bundle")
}
if valid, err := manifest.Validate(manifestMetadataValidators...); !valid {
return errors.Wrap(err, "invalid app manifest")
}
storageFile := injectAppID(ctx.String("storage-file"), manifest.ID)
if err := ensureDir(storageFile); err != nil {

View File

@ -6,6 +6,7 @@ Une **Edge App** est une application capable de s'exécuter dans un environnemen
### Référence
- [Fichier `manifest.yml`](./apps/manifest.md)
- [API Client](./apps/client-api/README.md)
- [API Serveur](./apps/server-api/README.md)

36
doc/apps/manifest.md Normal file
View File

@ -0,0 +1,36 @@
# Le fichier `manifest.yml`
Le fichier `manifest.yml` à la racine du bundle de votre application contient des informations décrivant celles ci. Vous trouverez ci dessous un exemple commenté.
```yaml
# REQUIS - L'identifiant de votre application. Il doit être globalement unique.
# Un identifiant du type nom de domaine inversé est en général conseillé (ex: tld.mycompany.myapp)
id: tld.mycompany.myapp
# REQUIS - Le numéro de version de votre application
# Celui ci devrait respecter le format "semver 2" (voir https://semver.org/)
version: 0.0.0
# REQUIS - Le titre de votre application.
title: My App
# OPTIONNEL - Les mots-clés associés à votre applications.
tags: ["chat"]
# OPTIONNEL - La description de votre application.
# Vous pouvez utiliser la syntaxe Markdown pour la mettre en forme.
description: |>
A simple demo application
# OPTIONNEL - Métadonnées associées à l'application
metadata:
# OPTIONNEL - Liste des chemins permettant d'accéder à certains URLs identifiées (page d'administration, icône si existante, etc)
paths:
# Si défini, chemin vers la page d'administration de l'application
admin: /admin
# Si défini, chemin vers l'icône associée à l'application
icon: /my-app-icon.png
# OPTIONNEL - Role minimum requis pour pouvoir accéder à l'application
minimumRole: visitor
```

View File

@ -22,23 +22,7 @@ my-app
Ce fichier est le manifeste de votre application. Il permet au serveur d'identifier celle ci et de récupérer des informations la concernant.
```yaml
---
# L'identifiant de votre application. Il doit être globalement unique.
# Un identifiant du type nom de domaine inversé est en général conseillé (ex: tld.mycompany.myapp)
id: tld.mycompany.myapp
# Le titre de votre application.
title: My App
# Les mots-clés associés à votre applications.
tags: ["chat"]
# La description de votre application.
# Vous pouvez utiliser la syntaxe Markdown pour la mettre en forme.
description: |>
A simple demo application
```
[Voir le fichier `manifest.yml` d'exemple](./manifest.md)
## 4. Créer la page d'accueil

View File

@ -54,5 +54,6 @@ interface Manifest {
title: string // Titre associé à l'application
description: string // Description associée à l'application
tags: string[] // Mots clés associés à l'application
metadata: { [key: string]: any } // Métadonnées associées à l'application. Voir ../manifest.md
}
```

View File

@ -5,3 +5,8 @@ version: 0.0.0
description: |
Suite de tests pour le SDK client
tags: ["test"]
metadata:
paths:
icon: /icon.png
minimumRole: visitor

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

View File

@ -4,6 +4,7 @@
<meta charset="utf-8" />
<title>Client SDK Test suite</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" type="image/png" href="/icon.png">
<link rel="stylesheet" href="/vendor/mocha.css" />
<style>
body {

View File

@ -1,39 +0,0 @@
package app
import (
"forge.cadoles.com/arcad/edge/pkg/bundle"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
)
type ID string
type Manifest struct {
ID ID `yaml:"id" json:"id"`
Version string `yaml:"version" json:"version"`
Title string `yaml:"title" json:"title"`
Description string `yaml:"description" json:"description"`
Tags []string `yaml:"tags" json:"tags"`
}
func LoadManifest(b bundle.Bundle) (*Manifest, error) {
reader, _, err := b.File("manifest.yml")
if err != nil {
return nil, errors.Wrap(err, "could not read manifest.yml")
}
defer func() {
if err := reader.Close(); err != nil {
panic(errors.WithStack(err))
}
}()
manifest := &Manifest{}
decoder := yaml.NewDecoder(reader)
if err := decoder.Decode(manifest); err != nil {
return nil, errors.Wrap(err, "could not decode manifest.yml")
}
return manifest, nil
}

85
pkg/app/manifest.go Normal file
View File

@ -0,0 +1,85 @@
package app
import (
"strings"
"forge.cadoles.com/arcad/edge/pkg/bundle"
"github.com/pkg/errors"
"golang.org/x/mod/semver"
"gopkg.in/yaml.v2"
)
type ID string
type Manifest struct {
ID ID `yaml:"id" json:"id"`
Version string `yaml:"version" json:"version"`
Title string `yaml:"title" json:"title"`
Description string `yaml:"description" json:"description"`
Tags []string `yaml:"tags" json:"tags"`
Metadata MapStr `yaml:"metadata" json:"metadata"`
}
type MetadataValidator func(map[string]any) (bool, error)
func (m *Manifest) Validate(validators ...MetadataValidator) (bool, error) {
if m.ID == "" {
return false, errors.New("'id' property should not be empty")
}
if m.Version == "" {
return false, errors.New("'version' property should not be empty")
}
version := m.Version
if !strings.HasPrefix(version, "v") {
version = "v" + version
}
if !semver.IsValid(version) {
return false, errors.Errorf("version '%s' does not respect semver format", m.Version)
}
if m.Title == "" {
return false, errors.New("'title' property should not be empty")
}
if m.Tags != nil {
for _, t := range m.Tags {
if strings.ContainsAny(t, " \t\n\r") {
return false, errors.Errorf("tag '%s' should not contain any space or new line", t)
}
}
}
for _, v := range validators {
valid, err := v(m.Metadata)
if !valid || err != nil {
return valid, errors.WithStack(err)
}
}
return true, nil
}
func LoadManifest(b bundle.Bundle) (*Manifest, error) {
reader, _, err := b.File("manifest.yml")
if err != nil {
return nil, errors.Wrap(err, "could not read manifest.yml")
}
defer func() {
if err := reader.Close(); err != nil {
panic(errors.WithStack(err))
}
}()
manifest := &Manifest{}
decoder := yaml.NewDecoder(reader)
if err := decoder.Decode(manifest); err != nil {
return nil, errors.Wrap(err, "could not decode manifest.yml")
}
return manifest, nil
}

61
pkg/app/map_str.go Normal file
View File

@ -0,0 +1,61 @@
package app
import (
"fmt"
"github.com/pkg/errors"
)
type MapStr map[string]interface{}
func MapStrUnion(dict1 MapStr, dict2 MapStr) MapStr {
dict := MapStr{}
for k, v := range dict1 {
dict[k] = v
}
for k, v := range dict2 {
dict[k] = v
}
return dict
}
func (ms *MapStr) UnmarshalYAML(unmarshal func(interface{}) error) error {
var result map[interface{}]interface{}
err := unmarshal(&result)
if err != nil {
return errors.WithStack(err)
}
*ms = cleanUpInterfaceMap(result)
return nil
}
func cleanUpInterfaceArray(in []interface{}) []interface{} {
result := make([]interface{}, len(in))
for i, v := range in {
result[i] = cleanUpMapValue(v)
}
return result
}
func cleanUpInterfaceMap(in map[interface{}]interface{}) MapStr {
result := make(MapStr)
for k, v := range in {
result[fmt.Sprintf("%v", k)] = cleanUpMapValue(v)
}
return result
}
func cleanUpMapValue(v interface{}) interface{} {
switch v := v.(type) {
case []interface{}:
return cleanUpInterfaceArray(v)
case map[interface{}]interface{}:
return cleanUpInterfaceMap(v)
case string:
return v
default:
return fmt.Sprintf("%v", v)
}
}

View File

@ -0,0 +1,28 @@
package metadata
import (
"forge.cadoles.com/arcad/edge/pkg/app"
"github.com/pkg/errors"
)
func WithMinimumRoleValidator(roles ...string) app.MetadataValidator {
return func(metadata map[string]any) (bool, error) {
rawMinimumRole, exists := metadata["minimumRole"]
if !exists {
return true, nil
}
minimumRole, ok := rawMinimumRole.(string)
if !ok {
return false, errors.Errorf("metadata['minimumRole']: unexpected value type '%T'", rawMinimumRole)
}
for _, r := range roles {
if minimumRole == r {
return true, nil
}
}
return false, errors.Errorf("metadata['minimumRole']: unexpected role '%s'", minimumRole)
}
}

View File

@ -0,0 +1,51 @@
package metadata
import (
"strings"
"forge.cadoles.com/arcad/edge/pkg/app"
"github.com/pkg/errors"
)
type NamedPath string
const (
NamedPathAdmin NamedPath = "admin"
NamedPathIcon NamedPath = "icon"
)
func WithNamedPathsValidator(names ...NamedPath) app.MetadataValidator {
set := map[NamedPath]struct{}{}
for _, n := range names {
set[n] = struct{}{}
}
return func(metadata map[string]any) (bool, error) {
rawPaths, exists := metadata["paths"]
if !exists {
return true, nil
}
paths, ok := rawPaths.(app.MapStr)
if !ok {
return false, errors.Errorf("metadata['paths']: unexpected named path value type '%T'", rawPaths)
}
for n, p := range paths {
if _, exists := set[NamedPath(n)]; !exists {
return false, errors.Errorf("metadata['paths']: unexpected named path '%s'", n)
}
path, ok := p.(string)
if !ok {
return false, errors.Errorf("metadata['paths']['%s']: unexpected named path value type '%T'", n, path)
}
if !strings.HasPrefix(path, "/") {
return false, errors.Errorf("metadata['paths']['%s']: named path value should start with a '/'", n)
}
}
return true, nil
}
}

View File

@ -0,0 +1,7 @@
id: foo.arcad.app
version: v0.0.0
title: Foo
description: A test app
tags: ["test"]
metadata:
minimumRole: foo

View File

@ -0,0 +1,10 @@
id: foo.arcad.app
version: v0.0.0
title: Foo
description: A test app
tags: ["test"]
metadata:
paths:
invalid: /admin
icon: /my-app-icon.png
minimumRole: visitor

View File

@ -0,0 +1,10 @@
id: foo.arcad.app
version: v0.0.0
title: Foo
description: A test app
tags: ["test"]
metadata:
paths:
admin: /admin
icon: /my-app-icon.png
minimumRole: visitor

View File

@ -0,0 +1,74 @@
package metadata
import (
"io/ioutil"
"path/filepath"
"testing"
"forge.cadoles.com/arcad/edge/pkg/app"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
)
type validatorTestCase struct {
File string
ExpectValid bool
ExpectError bool
}
var validatorTestCases = []validatorTestCase{
{
File: "valid.yml",
ExpectValid: true,
},
{
File: "invalid-paths.yml",
ExpectValid: false,
ExpectError: true,
},
{
File: "invalid-minimum-role.yml",
ExpectValid: false,
ExpectError: true,
},
}
var validators = []app.MetadataValidator{
WithMinimumRoleValidator("visitor", "user", "superuser", "admin", "superadmin"),
WithNamedPathsValidator(NamedPathAdmin, NamedPathIcon),
}
func TestManifestValidate(t *testing.T) {
for _, tc := range validatorTestCases {
func(tc *validatorTestCase) {
t.Run(tc.File, func(t *testing.T) {
data, err := ioutil.ReadFile(filepath.Join("testdata/manifests", tc.File))
if err != nil {
t.Fatalf("%+v", errors.WithStack(err))
}
var manifest app.Manifest
if err := yaml.Unmarshal(data, &manifest); err != nil {
t.Fatalf("%+v", errors.WithStack(err))
}
valid, err := manifest.Validate(validators...)
t.Logf("[RESULT] valid:%v, err:%v", valid, err)
if e, g := tc.ExpectValid, valid; e != g {
t.Errorf("valid: expected '%v', got '%v'", e, g)
}
if tc.ExpectError && err == nil {
t.Error("err should not be nil")
}
if !tc.ExpectError && err != nil {
t.Errorf("err: expected nil, got '%+v'", err)
}
})
}(&tc)
}
}

View File

@ -19,6 +19,7 @@ type gojaManifest struct {
Title string `goja:"title" json:"title"`
Description string `goja:"description" json:"description"`
Tags []string `goja:"tags" json:"tags"`
Metadata map[string]any `goja:"metadata" json:"metadata"`
}
func toGojaManifest(manifest *app.Manifest) *gojaManifest {
@ -28,6 +29,7 @@ func toGojaManifest(manifest *app.Manifest) *gojaManifest {
Title: manifest.Title,
Description: manifest.Description,
Tags: manifest.Tags,
Metadata: manifest.Metadata,
}
}

View File

@ -4095,16 +4095,16 @@ var Edge = (() => {
constructor() {
super();
this.debug = false;
this._initResizeObserver();
this._initTitleMutationObserver();
this._handleWindowMessage = this._handleWindowMessage.bind(this);
this._initObservers = this._initObservers.bind(this);
window.addEventListener("load", this._initObservers);
window.addEventListener("message", this._handleWindowMessage);
}
post(message, target = window.parent) {
if (!target)
return;
this._log("sending crossframe message", message);
target.postMessage(message);
target.postMessage(message, "*");
}
_log(...args) {
if (!this.debug)
@ -4119,6 +4119,10 @@ var Edge = (() => {
});
this.dispatchEvent(event);
}
_initObservers() {
this._initResizeObserver();
this._initTitleMutationObserver();
}
_initTitleMutationObserver() {
const titleObserver = new MutationObserver((mutations) => {
const title2 = mutations[0].target.textContent;
@ -4132,24 +4136,27 @@ var Edge = (() => {
}
_initResizeObserver() {
const resizeObserver = new ResizeObserver(() => {
const body = document.body, html = document.documentElement;
const body2 = document.body, html = document.documentElement;
const height = Math.max(
body.scrollHeight,
body.offsetHeight,
body2.scrollHeight,
body2.offsetHeight,
html.clientHeight,
html.scrollHeight,
html.offsetHeight
);
const width = Math.max(
body.scrollWidth,
body.offsetWidth,
body2.scrollWidth,
body2.offsetWidth,
html.clientWidth,
html.scrollWidth,
html.offsetWidth
);
this.post({ type: "size_changed" /* SIZE_CHANGED */, data: { height, width } });
});
resizeObserver.observe(document.body);
const body = document.body;
if (!body)
return;
resizeObserver.observe(body);
}
};

File diff suppressed because one or more lines are too long

View File

@ -17,18 +17,17 @@ export class CrossFrameMessenger extends EventTarget {
super()
this.debug = false;
this._initResizeObserver();
this._initTitleMutationObserver();
this._handleWindowMessage = this._handleWindowMessage.bind(this);
this._initObservers = this._initObservers.bind(this);
window.addEventListener('load', this._initObservers);
window.addEventListener('message', this._handleWindowMessage)
}
post(message: CrossFrameMessage, target: Window = window.parent) {
if (!target) return;
this._log("sending crossframe message", message);
target.postMessage(message)
target.postMessage(message, '*');
}
_log(...args) {
@ -46,6 +45,11 @@ export class CrossFrameMessenger extends EventTarget {
this.dispatchEvent(event);
}
_initObservers() {
this._initResizeObserver();
this._initTitleMutationObserver();
}
_initTitleMutationObserver() {
const titleObserver = new MutationObserver((mutations) => {
const title = mutations[0].target.textContent;
@ -75,6 +79,10 @@ export class CrossFrameMessenger extends EventTarget {
this.post({ type: CrossFrameMessageType.SIZE_CHANGED, data: { height, width }});
});
resizeObserver.observe(document.body);
const body = document.body;
if (!body) return;
resizeObserver.observe(body);
}
}