Giter Site home page Giter Site logo

symfony / mercure-bundle Goto Github PK

View Code? Open in Web Editor NEW
281.0 7.0 20.0 96 KB

The MercureBundle allows to easily push updates to web browsers and other HTTP clients in the Symfony full-stack framework, using the Mercure protocol.

Home Page: https://symfony.com/doc/current/mercure.html

License: MIT License

PHP 92.35% Twig 7.65%
mercure live-updates subscriptions server-sent-events symfony symfony-bundle bundle php

mercure-bundle's Introduction

mercure-bundle's People

Contributors

azjezz avatar chalasr avatar dunglas avatar grachevko avatar lunetics avatar maxhelias avatar mtarld avatar nicolas-grekas avatar norkunas avatar nyholm avatar safaksaylam avatar samnela avatar smnandre avatar vincentchalamon avatar weaverryan avatar xurudragon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

mercure-bundle's Issues

[mercure] option enable_profiler in configuration of mercure is not work

Symfony version(s) affected: 4.4.2
and versions of mercure :

/* ... */
    "symfony/mercure": "^0.3",
    "symfony/mercure-bundle": "^0.2",
/* ... */

Description
Hi,
I think we have bug in documentation for debugging option when I put like this:

# config/packages/dev/mercure.yaml
mercure:
    enable_profiler: '%kernel.debug%'

I have this :

$ bin/console de:config mercure

In ArrayNode.php line 327:                                                                                                   
  Unrecognized option "enable_profiler" under "mercure". Available options are "default_hub", "hubs".  

And when i put like this :

# config/packages/dev/mercure.yaml
mercure:
    hubs:
        enable_profiler: '%kernel.debug%'
        default:
            url: '%env(MERCURE_PUBLISH_URL)%'
            jwt_provider: App\Services\Mercure\JwtProvider

I have this :

$ bin/console de:config mercure

In MercureExtension.php line 51:
                                         
  Notice: Undefined index: jwt_provider  

Thanks

Can not access "target" property from the mercure panel in profiler

Hi,

I actually get that error when I try to open the mercure panel in my profiler.

Neither the property "targets" nor one of the methods "targets()", "gettargets()"/"istargets()"/"hastargets()" or "__call()" exist and have public access in class "Symfony\Component\Mercure\Update".

Error in : mercure.html.twig (line 70)

Symfony 5.1 deprecation warning

The signature of method "Symfony\Component\DependencyInjection\Alias::setDeprecated()" requires 3 arguments: "string $package, string $version, string $message", not defining them is deprecated.

Problem is in MercureExtension class, line 98.

Documentation about pub/sub

Documentation and examples are showing how to use Mercure from one place. But with Stimulus, each controller could listen to different topics.

What would be the best practice? Is there a recommended pub/sub library that would share the connection and work nicely with Stimulus?

Note that I assumed opening multiple SE connections hurts the server. I don't know if browsers are smart enough to internally share the connection if the URL has already been used.

Mercure annotation missing

First of all, great job!

I've installed this bundle to be able to use it alongside the api platform package, and after configuring the env vars, I tried to add the mercure option to the @ApiResource(mercure=true) annotation and I'm getting the following error:

Unknown property "mercure" on annotation "ApiPlatform\Core\Annotation\ApiResource".

Here is my current version from some packages involved:

"name": "api-platform/api-pack",
"version": "v1.2.0",
"name": "api-platform/core",
"version": "v2.3.6",
"name": "symfony/mercure-bundle",
"version": "v0.1.1",
"name": "symfony/framework-bundle",
"version": "v4.2.4",

Can't transfer cookie to hub

Hello,
I use MercuryBundle for my project symfony. It work when I notify everyone, however, if I want to notify a particular user it does not work!, i can not transfer the cookie that has been generating to my hub.
Still, I put in my javascript option withCredentials: true:

const eventSource = new EventSource(url, {withCredentials: true});

thanks

Serialize server-sent events

Hello, we have a project on Symphony 4 + Api platform. We use Mercure and it works nice but there is one question about serialize " server-sent events". Why when i am getting server-event and if my Json contains a one nested element then this element is an array of one object, but if i am getting the same Json from Mercure(server-event) this element is just an object. I need to get an array of one object. How i can do it?

Multi domain usage

Hi,

Thank for this great project. We have an issue:

  • website have multiple domains for the same code/server: domain.tld, anotherdomain.tld2, newdomain.tld3
  • we have one mercure instance: mercuredomain.com

What value can we set in mercure config of the bundle with multiple domain to avoid Unable to create authorization cookie for a hub on the different second-level domain?

Thanks

PublishController breaks security authenticator

Hi everyone!

I'm trying to integrate Mercure into my application by following this guide: https://symfony.com/doc/current/mercure.html
All is good until I create the PublishController. When this happens, Symfony breaks and keeps on telling me that The service "security.authentication.provider.guard.main" has a dependency on a non-existent service "App\Services\LoginFormAuthenticator".

My configuration should be fine. I checked every similar issue, but cannot seem to resolve it. I'll be happy to provide more details/config files if needed. Thanks!

Mercure hub filename cannot be empty

implementing first hello word according here got this error. why? what is this file and where?

Unable to publish the update to the Mercure hub: file_get_contents(): Filename cannot be empty

UPDATED
i change many params and last get:

Unable to publish the update to the Mercure hub: file_get_contents(http://127.0.0.1:3000/hub): failed to open stream: HTTP request failed! HTTP/1.0 401 Unauthorized

[Informations] How to handle relations ?

We are trying to find a good and easy way to handle relations.

I explain, I have :

  • 1 entity Website
  • n entites Url, related to Website (1 Website can have multiple Url)

I want to get notified when I create an Url related to the Website, I want the topic Website to be updated.

For now, I manually change a property in the parent (for example a field updatedAt).

Can I use some better way ? Or did I miss something in the doc ?

Add support for lcobucci/jwt v5

This bundle currently requires lcobucci/jwt ^3.4|^4.0 and is therefor the only dependency that is currently blocking me to upgrade to the latest JWT lcobucci/jwt release.

Note that the v5 release might need some work here as the release removes deprecated components, makes PHP 8.1 the minimum required version and ships some API improvements.

Unauthorized response with default config

I installed mercure-bundle in my symfony with default values, just switched the URL of mercure to the my own.

Captura de Pantalla 2021-04-19 a la(s) 18 35 21

MERCURE_JWT_SECRET="!ChangeMe!"

And mercure is also running with default config.

SERVER_NAME=:3000 MERCURE_PUBLISHER_JWT_KEY='!ChangeMe!' MERCURE_SUBSCRIBER_JWT_KEY='!ChangeMe!' ./mercure run -config Caddyfile.dev

But i got an Unauthorized response

Captura de Pantalla 2021-04-19 a la(s) 18 32 16

Then i tested in many ways to get it working and finally i found the problem:

When I copy the Token to decode it, the expiration date appears to be in an incorrect format.

Captura de Pantalla 2021-04-19 a la(s) 18 39 24

If I remove the quotes, converting the string into decimal value, the expiration date appears to be correct.

Captura de Pantalla 2021-04-19 a la(s) 18 43 11

Finally I tested with both tokens, first the token generated by symphony and then with decimal expiration date.

Captura de Pantalla 2021-04-19 a la(s) 18 49 11

Mercure: 0.10.4 (Darwin)
Symfony: 5.2
Symfony mercure-bundle: 0.3.2

I don't know if it is a mistake done by me or is a real bug, i hope someone can help me.

Thanks

I cannot submit asynchronous events with Mercure

Symfony version(s) affected: 4.4.2

Description
Hello,
I'm using Mercure for Push Notification for my website and I want to use Messenger to send notifications asynchronously, but the problem is that when I use sending synchronously, I receive the notification but in asynchronous I don't receive it!

Mercure in synchronous :

INFO[3518] Update published                              event_id=6c7008c5-fdb9-49a7-b694-d73891faa1e2 event_retry=0 event_type= remote_addr="127.0.0.1:34528" update_targets="[user-15519]" update_topics="[comment]"
127.0.0.1 - - [05/Mar/2020:12:50:04 +0100] "POST /.well-known/mercure HTTP/1.0" 200 36 "" ""
INFO[3518] Event sent                                    event_id=6c7008c5-fdb9-49a7-b694-d73891faa1e2 event_retry=0 event_type= last_event_id= remote_addr="127.0.0.1:57654" subscriber_targets="[user-14521]" subscriber_topics="[comment]" update_targets="[user-14521]" update_topics="[comment]"
INFO[3518] Update published                              event_id=4aefafd4-b302-4fae-9aa4-a24f338b0992 event_retry=0 event_type= remote_addr="127.0.0.1:34532" update_targets="[user-14521]" update_topics="[comment]"
127.0.0.1 - - [05/Mar/2020:12:50:04 +0100] "POST /.well-known/mercure HTTP/1.0" 200 36 "" ""

Mercure in asynchronous :

INFO[3378] Update published                              event_id=4070dbca-5648-4b8d-8316-2696e867dbab event_retry=0 event_type= remote_addr="127.0.0.1:60488" update_targets="[user-14521]" update_topics="[comment]"
127.0.0.1 - - [05/Mar/2020:12:47:44 +0100] "POST /.well-known/mercure HTTP/1.0" 200 36 "" ""

Anyone have any idea how i can fix this
Thanks

Events never dispatched?

Docs used
https://symfony.com/doc/current/mercure.html#configuration
https://mercure.rocks/spec
https://caddyserver.com/docs/json/apps/http/servers/routes/handle/mercure/
https://mercure.rocks/docs/hub/install

###> symfony/mercure-bundle ###
MERCURE_PUBLISH_URL=https://remote.mercure.api/mercure
MERCURE_ALLOW_ANONYMOUS=1
MERCURE_ADDR=:3000
MERCURE_LISTENED_URI=https://remote.mercure.api/.well-known/mercure
MERCURE_SUBSCRIPTIONS_URI=https://remote.mercure.api/.well-known/mercure/subscriptions
MERCURE_CORS_ALLOWED_ORIGINS=symfchat.loc
MERCURE_PUBLISH_ALLOWED_ORIGINS=symfchat.loc
MERCURE_ACCESS_CONTROL_ALLOW_ORIGIN=http://127.0.0.1
ACCESS_CONTROL_ALLOW_ORIGIN=http://127.0.0.1
#MERCURE_ACCESS_CONTROL_ALLOW_ORIGIN=symfchat.loc
SUBSCRIPTIONS_URI=https://remote.mercure.api.com/.well-known/mercure
MERCURE_SUBSCRIPTIONS=1
MERCURE_PUBLISHER_JWT_KEY=ABC
MERCURE_SUBSCRIBER_JWT_KEY=DEFG


    App\Mercure\JwtProvider:
        arguments:
            $secret: '%env(MERCURE_PUBLISHER_JWT_KEY)%'

  use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Serializer\SerializerInterface;
...
    $key = $_ENV['MERCURE_PUBLISHER_JWT_KEY'];
        $jwt = JWT::encode([], $key);
        $eventTopicData = $this->serializer->serialize([
                                                           'event' => 'new_message',
                                                           'topic' => $topic,
                                                           'jwt' => $jwt,
                                                           'Authorization' => 'Bearer ' . $jwt,
                                                           'payload' => ['test'],
                                                       ], "json");

        $update = new Update(
            $topic,
            $eventTopicData,
            true // false does not work too
        );
        $this->messageBus->dispatch($update);
<?php
namespace App\Mercure;

use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key;

class JwtProvider
{

    private $secret;

    public function __construct(string $secret)
    {
        $this->secret = $secret;
        // this one called
    }

    public function __invoke(): string
    {
     // but never triggered, no errors
        return (new Builder())
            ->withClaim('mercure', ['publish' => []])
            ->getToken(new Sha256(), new Key($this->secret));
    }
}

It is built somewhere here during symfony bundle init, but it is never invoked!

/**
 * @author Kévin Dunglas <[email protected]>
 */
final class MercureExtension extends Extension
{

caddyfile config

{
  auto_https disable_redirects
}

caddy.tamilchatz.com
file_server

log {
   output stdout
   format json
}


route {
  mercure {
        transport_url local://local
        publisher_jwt ABC
        subscriber_jwt DEFG 
        cors_origins *
        anonymous
        subscriptions
  }

caddy logs, we see only new susbcribers and handling GET requests

"level":"info","ts":1614956486.2640092,"logger":"http.handlers.mercure","msg":"New subscriber","subscriber":{"id":"urn:uuid:fa88b1d0-e24f-4b48-a416-88a3cc36b7bf","last_e>
"level":"info","ts":1614956486.2656085,"logger":"http.handlers.mercure","msg":"New subscriber","subscriber":{"id":"urn:uuid:7929b9f7-c4eb-44fe-a3c6-22403dd4d7bf","last_e>
"level":"info","ts":1614956486.2683454,"logger":"http.handlers.mercure","msg":"New subscriber","subscriber":{"id":"urn:uuid:95f8180f-2f01-4cd4-9f52-cc0fd2de15d7","last_e>
level":"info","ts":1614956486.570968,"logger":"http.log.access.log0","msg":"handled request","request":{"

,"request":{"remote_addr":"ip-123123","proto":"HTTP/2.0","method":"OPTIONS","host":"remove.mercure.api","uri":"/.well-known/mercure/subscriptions/test"

framework:
    messenger:
        transports:
            # https://symfony.com/doc/current/messenger.html#transport-configuration
            async: '%env(MESSENGER_TRANSPORT_DSN)%'

        routing:
            'Symfony\Component\Mercure\Update': async
###> symfony/messenger ###
 MESSENGER_TRANSPORT_DSN=redis://localhost:6379/messages
MESSENGER_FAILED_TRANSPORT_DSN=redis://127.0.0.1:6379/messages_failed
MESSENGER_NUMBER_OF_WORKER=4
###< symfony/messenger ###

So, from what I understand, something wrong with dispatching events.
It happened after upgrading legacy mercure binary to the latets build with caddy GO lang server and moving it to separate server.
Subscriptions seems to be working, but events are never dispatched now.
Spent a lot of time trying to figure out is this mercure, caddy or symfony bundle, or transport (Redis) issue.
But because JwtToken is never applied, could be smth wrong with the bundle during invocation or dispatching.
Caddy server does not receives any updates, post requests according to logs.

Tell me please what could be the issue?

Running Mercure on https with Symfony certificate

As of Chrome 88, cookies must be SiteSite=Lax/Strict or SiteSite=none; Secure. That means running a Mercure server on http isn't possible when running a Symfony dev server on https. I've tried upgrading to Mercure v0.11 with HTTPS, but that uses a self-signed certificate that isn't trusted by Chrome. I tried to use the "allow-insecure-localhost" flag in Chrome, but that flag has been removed in Chrome 88. I found a workaround by setting temporary-unexpire-flags-m87. That works only temporarily and isn't a great developer experience either.

It would be great if we can use the Symfony certificate for Mercure as well, like we can with Webpack Encore's dev server.

Installation issue : In MercureExtension.php line 58 : Notice: Undefined index: jwt_provider

Hi
I have an issue when i install symfony/mercure-bundle (version 0.1.2) throught the command :
composer require mercure. Below it'is the issue :

Using version ^0.1.2 for symfony/mercure-bundle
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Restricting packages listed in "symfony/symfony" to "4.3.*"
Package operations: 2 installs, 0 updates, 0 removals
  - Installing symfony/mercure (v0.2.0): Loading from cache
  - Installing symfony/mercure-bundle (v0.1.2): Loading from cache
Writing lock file
Generating autoload files
Symfony operations: 1 recipe (4aead03e23663ff09ae8a2635bc30dd5)
  - Configuring symfony/mercure-bundle (>=0.1): From github.com/symfony/recipes:master
ocramius/package-versions:  Generating version class...
ocramius/package-versions: ...done generating version class
Executing script cache:clear [KO]
 [KO]
Script cache:clear returned with error code 1
!!  
!!  In MercureExtension.php line 52:
!!                                           
!!    Notice: Undefined index: jwt_provider  
!!                                           
!!  
!!  
Script @auto-scripts was called via post-update-cmd

Installation failed, reverting ./composer.json to its original content.

I'm using symfony4.3.
Please could you help me to fix it ! Thank you.

HubInterface and generated JWT token not working fine

Hi,

I've found that with the last mercure-bundle 0.3 and the last mercure server 0.11.3 there is an issue with the generated JWT token.

The generated token looks like :

{
  "exp": 1621589724.242307,
  "mercure": {
    "publish": [
      "*"
    ],
    "subscribe": []
  }
}

And mercure send a 401 error when trying to publish with it.

I've tryed the same token generated but with the removal of "exp": 1621589724.242307, and it worked just fine when publishing in the debug UI !

I haven't found yet how to remove it automatically , maybe somehting with LcobucciFactory to handle.

Symfony: Two topics on one page

Hi,

I'm using two topics on my symfony-project:

/user/notification/{userid} -> Send notifications to user (flash messages, statusupdates)
/user/messenger/{userid} -> Messages from other users

Both (private) topics were created by diefferent symfony-services.
At the client-side I'm using different stimulus-controllers:

"eventEndpoint": mercure(notificationChannelName, { subscribe: notificationChannelName })
"eventEndpoint": mercure(messengerChannelName, { subscribe: messengerChannelName})

Both topics are working perfect.
But when I'm using both on the same page, I get this error:
An exception has been thrown during the rendering of a template ("The "mercureAuthorization" cookie for the "default hub" has already been set. You cannot set it two times during the same request.").

I have no idea how to fix this.

I think I can set the cookie by myself:
$authorization->setCookie($request, ['/user/notification/{userid}','/user/messenger/{userid}']);

But the mercure-twig-helper still tries to set the cookie. -> Error again.

What can I do?

Symfony 7

Hi,
Could you release a release for Symfony 7? Please
Thanks 😃

Nginx+Mercure problems

Right now, I have to use Nginx instead of Docker image. But for last 2 days, I tried infinite number of combinations to make it work; the only one that did work was one with symfony server:start but that can't be put on server.

From multiple nginx configs tried, this is the one I don't get exceptions anymore: (used mysite.flex as an example):

Nginx config
server {
    listen *:80;
    server_name *.mysite.flex mysite.flex;
    root /mnt/Development/mysite/public;

    location ~ ^/.well-known/mercure {
        proxy_pass http://localhost:3000;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_set_header Authorization $http_authorization;
        proxy_pass_header  Authorization;
    }

    location / {
        try_files $uri /index.php$is_args$args;
        add_header 'Access-Control-Allow-Origin' '*';

    }
    location ~ ^/index\.php(/|$) {
        add_header Access-Control-Allow-Origin *;

        fastcgi_pass unix:/run/php/php8.0-fpm.sock;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;

        fastcgi_param BASE_URL mysite.flex;
	proxy_ignore_client_abort on;
    }
}

Mercure is listening at localhost:3000. When I execute code like this (made a command):

$update = new Update( '/new_pbx_call',  'test' );
$this->hub->publish($update);

and open either http://localhost:3000/.well-known/mercure?topic=%2Fnew_pbx_call or http://whitenights.flex/.well-known/mercure?topic=%2Fnew_pbx_call, nothing happens except for infinite loading.

But same thing did work when I used symfony server:start.

Mercure reports this:

image


My hub.url value is url: 'http://localhost:3000'. When I change it to http://localhost:3000/.well-known/mercure then I get 401:

image

even though JWT is identical.

Any help? I would be happy just to make basic functionality first, will fine tune it later.

MercureBundle crashes when the request takes to long / to high load?

Under heavy load the published crashes with a timeout...

{
    "class": "Symfony\\Component\\HttpClient\\Exception\\TransportException",
    "message": "Reading from the response stream reached the idle timeout.",
    "code": 0,
    "file": "/.../vendor/symfony/http-client/Chunk/ErrorChunk.php:56",
    "trace": [
        "/.../vendor/symfony/http-client/Response/CurlResponse.php:125",
        "/.../vendor/symfony/http-client/Response/ResponseTrait.php:97",
        "/.../vendor/symfony/mercure/src/Publisher.php:62",
        "/.../src/Service/Doctrine/PublishMercureCollectionUpdatesListener.php:196",
        "/.../src/Service/Doctrine/PublishMercureCollectionUpdatesListener.php:115",
        "/.../vendor/symfony/doctrine-bridge/ContainerAwareEventManager.php:55",
        "/.../vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:3397",
        "/.../vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:432",
        "/.../vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php:359",
        "/.../var/cache/prod/ContainerVraVAlR/EntityManager_9a5be93.php:83",
        "/.../src/Controller/ApiOperations/AnswerSet/SubmitAnswerSet.php:144",
        "/.../vendor/symfony/http-kernel/HttpKernel.php:151",
        "/.../vendor/symfony/http-kernel/HttpKernel.php:68",
        "/.../vendor/symfony/http-kernel/Kernel.php:198",
        "/.../public/index.php:28"
    ]

Publish with hub doesn't work

I have a problem with publishing events with Hub service. Mercure returns error 400 and message "Missing "topic" parameter when I'm using pure PHP code to send requests all works correctly.

Bundle version: 0.3.4
Component: v0.6.1
Symfony: 5.4

Bundle configuration is simplest:

mercure:
    hubs:
        default:
            url: '%env(MERCURE_URL)%'
            jwt: '%env(MERCURE_JWT_TOKEN)%'

Example code:

$update = new Update(
            'test',
            json_encode(['key' => 'updated value 4'])
        );

        $data = $this->hub->publish($update);

        var_dump($data);

        define('DEMO_JWT', $this->hub->getProvider()->getJwt());

        $postData = http_build_query([
            'topic' => 'test',
            'data' => json_encode(['key' => 'updated value 3']),
        ]);

        echo file_get_contents($this->hub->getUrl(), false, stream_context_create(['http' => [
            'method'  => 'POST',
            'header'  => "Content-type: application/x-www-form-urlencoded\r\nAuthorization: Bearer ".DEMO_JWT,
            'content' => $postData,
        ]]));

var_dump($data); returns Missing "topic" parameter
as you can see in pure PHP code I'm using values (URL and token) from HUB and publish works.

Unable to use the `mercure()` Twig function to subscribe to two different URLs at different places

Hello,

Assume that I want to subscribe to two (or more) private updates. By intuition I'd write this:

<div data-mercure-url="{{ mercure('https://example.com/user/3', { subscribe: 'https://example.com/user/3' }) }}"></div>
...
<div data-mercure-url="{{ mercure('https://example.com/books/1', { subscribe: 'https://example.com/books/1' }) }}"></div>

But doing so will cause the following exception from Symfony\Component\Mercure\Authorization::updateCookies:

An exception has been thrown during the rendering of a template ("The "mercureAuthorization" cookie for the "default hub" has already been set. You cannot set it two times during the same request.").

I am currently working around this by specifying all subscribing URLs in one of the mercure() function call:

<div data-mercure-url="{{ mercure('https://example.com/user/3', { subscribe: ['https://example.com/user/3', 'https://example.com/books/1'] }) }}"></div>
...
<div data-mercure-url="{{ mercure('https://example.com/books/1' }}"></div>

This works, but doesn't look straightforward. Is this a limitation of the current implmentation of the bundle, or am I doing it wrongly?

RS256 algorithm problems

in this pr https://github.com/dunglas/mercure/pull/156/files was added support for RS256 algorithm, but I can't make it work with current bundle.
that's how I used to use it with HS256
SERVER_NAME=:3000 JWT_KEY='cat config/jwt/public.pem' PUBLISHER_JWT_KEY='!ChangeMe!' ./mercure run -config Caddyfile.dev
with RS256 it's supposed to work like this
SERVER_NAME=:3000 MERCURE_JWT_KEY=cat config/jwt/public.pem ./mercure run -config Caddyfile.dev
but it gives me the error a JWT key for publishers must be provided
however mercure documentation says
PUBLISHER_JWT_KEY | must contain the secret key to valid publishers' JWT, can be omited if JWT_KEY is set

I'm stuck with this problem, will be grateful for any advices, thanks

MERCURE_PUBLISH_URL ignored ?

Hello,

I'm having a weird issue with Mercure, here's my .env file :

MERCURE_PUBLISH_URL=http://whateverurl/.well-known/mercure

When I output it like so :

parameters:
    test: '%env(MERCURE_PUBLISH_URL)%'

In a controller : dd( $this->getParameter( 'test' ) );

I get : http://127.0.0.1:8000/.well-known/mercure

I'm trying on a Windows machine, I use Symfony 5.2.4, fresh install with Mercure Bundle 0.2.6

Dumping the complete publisher in DataCollector breaks the Symfony toolbar

  1. Build a custom jwt provider (as stated in the docs)

  2. The Mercure Datacollector uses the whole publisher (object)
    image

  3. Symfore security UsageTrackingTokenStorage uses the ContainerInterface (sessionLocator) which results in the above closure call.

  4. The Symfony debug toolbar will break:

request.CRITICAL: Uncaught PHP Exception Exception: "Serialization of 'Closure' is not allowed" at /app/vendor/symfony/http-kernel/Profiler/FileProfilerStorage.php line 175 {"exception":"[object] (Exception(code: 0): Serialization of 'Closure' is not allowed at /app/vendor/symfony/http-kernel/Profiler/FileProfilerStorage.php:175)"}

Uncaught PHP Exception ErrorException: "Warning: curl_multi_setopt() expects parameter 1 to be resource, integer given"

Symfony version(s) affected: 4.3.6

Description
Hi, Please i have a problem.
After installing mercure bundle who come with symfony/http-client, when i load a simple page, the toolbar didn't show again and i have this error below :

Nov 11 01:18:22 |CRITI| REQUES Uncaught PHP Exception ErrorException: "Warning: curl_multi_setopt() expects parameter 1 to be resource, integer given" at /var/www/html/project_sf4/vendor/symfony/http-client/CurlHttpClient.php line 302 exception="[object] (ErrorException(code: 0): Warning: curl_multi_setopt() expects parameter 1 to be resource, integer given at /var/www/html/project_sf4/vendor/symfony/http-client/CurlHttpClient.php:302)"
Nov 11 01:18:23 |ERROR| SERVER GET  (500) /_wdt/1d91a6

How to reproduce
Just install mercure bundle

composer require mercure

Provide a command to use to test publish / subscribe

When the bundle is installed, there's a lot of moving pieces to get it all working. Sentry has the same problem and their bundle provides a sentry:test command which pushed a fake event to Sentry, allowing you to see your config and keys are correct and working.

This bundle could do the same, provide a basic command to check your hub is operational, Symfony can reach it and can read from it / write to it. The same command could be used to both publish and subscribe (in another window). Alternatively, it could show a sample curl command to use to test using that.

I can access to published messages after user close app sesion, using twig function

I use Mercure out of Api Platform ecosystem with mercure() Twig function in template to notify the completion of tasks executed in the background, or update graphics in real time, and other updates that do not need to be private but must be reflected in the web interface. All this works fine.

mercure recipe:

mercure:
    hubs:
        default:
            url: '%env(MERCURE_URL)%'
            public_url: '%env(MERCURE_PUBLIC_URL)%'
            jwt:
                secret: '%env(MERCURE_JWT_SECRET)%'
                publish: ['squid/status', 'sysinfo/report', 'server/tools/datetime', 'internet/status', 'cuote/consumo-total', 'squid-proxy/access-log/monitor', 'notif/task-complete/{userId}', 'notif/list/latest/{userId}']
                subscribe: ['squid/status', 'sysinfo/report', 'server/tools/datetime', 'internet/status', 'cuote/consumo-total', 'squid-proxy/access-log/monitor', 'notif/task-complete/{userId}', 'notif/list/latest/{userId}']

In base template.html.twig:

{% block eventsource_javascript %}
    {% set config = {'mercureHub':mercure(['squid/status', 'notif/task-complete/'~app.user.idPublico|uuid_encode, 'notif/list/latest/'~app.user.idPublico|uuid_encode], { subscribe:['squid/status', 'notif/task-complete/'~app.user.idPublico|uuid_encode, 'notif/list/latest/'~app.user.idPublico|uuid_encode]})} %}
    <script id="mercure" type="application/json">
        {{ config|json_encode(constant('JSON_UNESCAPED_SLASHES') b-or constant('JSON_HEX_TAG'))|raw }}
    </script>
{% endblock %}

If user init sesion in web app, and copy the mercure url request (
https://squidmgr.lan/.well-known/mercure?topic=squid%2Fstatus&topic=sysinfo%2Freport&topic=server%2Ftools%2Fdatetime&topic=internet%2Fstatus&topic=cuote%2Fconsumo-total&topic=notif%2Ftask-complete%2F2nC0OMu3USsHE0AdKkreLz&topic=notif%2Flist%2Flatest%2F2nC0OMu3USsHE0AdKkreLz), logout application session and paste copied url in browser all messages related to the topics present in the copied url remain accessible, if the same user init session in another browser or computer, the updates of topics that include the user id are visible in the browser that access directly to mercure request url. On the other hand, if the user closes the browser, reopens it and pastes the url, then the message Unauthorized by Mercure is displayed. It's suppose that when logout process occur, the mercureAuthorization cookie is destroyed??? Publics updates don't care that be accessible out of the session, but privates Updates is necessary that do not be accessible out of user session.

I need that'notif/task-complete/{userId}' or 'notif/list/latest/{userId}' for example, don't be accessible if user logout.

Fake hub to functionnal test

Hello,

I try to use mercure in my functionnal tests, i followed the doc but it does not work. I'd like to have a fake class exactly like the doc suggests.
I use symfony 6.3, phpunit 9.5. I tried to configure the default class like this :

    mercure.hub.default:
        class: App\Tests\Functional\Stub\HubStub

I have this error

Symfony\Component\Config\Exception\LoaderLoadException : Container extension "mercure.hub.default" is not registered in /srv/config/packages/mercure.yaml (which is being imported from "/srv/src/Kernel.php").

The bundle works fine in development mode, it's well imported. In the bundles.php, it's all => true setted

I tried to use the default_hub but it's not working either.

Do you have any ideas or recommandations ?
Thanks :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.