amplify-category-api icon indicating copy to clipboard operation
amplify-category-api copied to clipboard

Subscription stop working when i added hasOne from the model on another model

Open rafaelfaria opened this issue 10 months ago • 10 comments

How did you install the Amplify CLI?

yarn

If applicable, what version of Node.js are you using?

v18.19.0

Amplify CLI Version

12.10.3

What operating system are you using?

Mac

Did you make any manual changes to the cloud resources managed by Amplify? Please describe the changes made.

No manual changes made

Describe the bug

I have a subscription listening to changes of my User @model schema. Everything was working fine, then stopped. The only thing I can think of that has changed its behaviour is that i included the User as a "hasOne" on another 2 models.

Expected behavior

I expected that every time I change an attribute of the User model, that i was able to listen to its change.

Reproduction steps

type User @model
  @auth(
    rules: [
      { allow: owner, operations: [read], ownerField: "myCustomID" },
      { allow: private, provider: iam }
      { allow: groups, groups: ["Admin"] }
    ]
  )
{
  myCustomUserID: String! @primaryKey
  displayName: String!
  points: Float

  # Relationships
  cards: [Card] @hasMany(indexName: "byUserCard", fields: ["myCustomUserID"], limit: 500)
  inventory: [Inventory] @hasMany(indexName: "byUserInventory", fields: ["myCustomUserID"], limit: 200)
}


type Card @model
  @auth(
    rules: [
      { allow: owner, operations: [read], ownerField: "myCustomUserID" },
      { allow: private, provider: iam }
      { allow: groups, groups: ["Admin"] }
    ]
  )
{
  id: ID!
  hasBeenHitBy: String
  hasBeenHitAt: AWSDateTime
  hasBeenHitByUser: User @hasOne(fields: ["hasBeenHitBy"])
  myCustomUserID: String! @index(name: "byUserCard", queryField: "getCardsByMyCustomUserID")
  user: User @hasOne(fields: ["myCustomUserID"])
}

type Inventory @model
  @auth(
    rules: [
      { allow: owner, operations: [read], ownerField: "myCustomUserID" },
      { allow: private, provider: iam }
      { allow: groups, groups: ["Admin"] }
    ]
  )
{
  id: ID!
  item: String! 
  myCustomUserID: String! @index(name: "byUserInventory", queryField: "getInventoryByMyCustomUserID")
  user: User @hasOne(fields: ["myCustomUserID"])
}

Project Identifier

No response

Log output

# Put your logs below this line


Additional information

No response

Before submitting, please confirm:

  • [X] I have done my best to include a minimal, self-contained set of instructions for consistently reproducing the issue.
  • [X] I have removed any sensitive information from my code snippets and submission.

rafaelfaria avatar Mar 30 '24 12:03 rafaelfaria

I can actually confirm that that's EXACTLY the problem. I reverted all my changes to before, removed all the attributes that contains the hasOne linked to my User table, and now voila it works again.

user: User @hasOne(fields: ["myCustomUserID"])

Is there any reason WHY this wouldn't work? Any workarounds? This really makes things a bit harder for me as instead of just having the user in these other models, i need to fetch the user every time i need to the card or inventory. Which defeats completely the use of graphql.

rafaelfaria avatar Mar 30 '24 12:03 rafaelfaria

Instead of modeling your Card.user as a @hasOne, try @belongsTo: https://docs.amplify.aws/javascript/build-a-backend/graphqlapi/data-modeling/#belongs-to-relationship

user: User @belongsTo(fields: ["myCustomUserID"])

palpatim avatar Mar 30 '24 12:03 palpatim

Instead of modeling your Card.user as a @hasOne, try @belongsTo: https://docs.amplify.aws/javascript/build-a-backend/graphqlapi/data-modeling/#belongs-to-relationship

user: User @belongsTo(fields: ["myCustomUserID"])

I did try belongsTo, and while it gets the same result as hasOne, the subscription also doesn't get triggered.

rafaelfaria avatar Mar 31 '24 22:03 rafaelfaria

Can you share some more details:

  1. Can you share the Project Identifier reported when you do amplify diagnose --send-report (This command sends non-sensitive project information to the Amplify team so we can see some project details without you having to manually transcribe them.)
  2. What authorization method are you using to subscribe on the client?
  3. What is the GraphQL operation you're using to trigger the mutation?
  4. What is the GraphQL operation you're using to create the subscription?

I'm asking for the authorization information because the subscription query must be authorized according to both the auth modes configured on the API, and the @auth rules specified in the schema. The operations are important because the required fields in a subscription's selection set must be included in the selection set used to make the triggering mutation.

Using your example schema (corrected as noted below), I am not able to replicate this issue. I created Users, Card, and Inventory records, and was able to subscribe to updates on them as expected.

palpatim avatar Apr 01 '24 15:04 palpatim

Also, I note you have a likely typo in your schema:

type User @model
  @auth(
    rules: [
      { allow: owner, operations: [read], ownerField: "myCustomID" },
      { allow: private, provider: iam }
      { allow: groups, groups: ["Admin"] }
    ]
  )
{
  myCustomUserID: String! @primaryKey
  displayName: String!

Can you confirm that ownerField: "myCustomID" should actually be ownerField: "myCustomUserID"?

palpatim avatar Apr 01 '24 15:04 palpatim

Also, I note you have a likely typo in your schema:

type User @model
  @auth(
    rules: [
      { allow: owner, operations: [read], ownerField: "myCustomID" },
      { allow: private, provider: iam }
      { allow: groups, groups: ["Admin"] }
    ]
  )
{
  myCustomUserID: String! @primaryKey
  displayName: String!

Can you confirm that ownerField: "myCustomID" should actually be ownerField: "myCustomUserID"?

Hey @palpatim Yeah, the typo was because i replaced the real name of the field for that, so might have missed out. the fields should all match.

rafaelfaria avatar Apr 01 '24 22:04 rafaelfaria

Can you share some more details:

  1. Can you share the Project Identifier reported when you do amplify diagnose --send-report (This command sends non-sensitive project information to the Amplify team so we can see some project details without you having to manually transcribe them.)

Identifier: b463d0847a96da9fb9c74f78a192e08b Note, the current version doesn't have the broken model. I had to reverse it, but should be commented in the schema.

  1. What authorization method are you using to subscribe on the client? COGNITO
  1. What is the GraphQL operation you're using to trigger the mutation? I built this method to do the graphql in my lambda functions https://gist.github.com/rafaelfaria/e1f08db9f3067ed64edb35bc68272788 (still uses aws-sdk 2)
const graphQLRun = require('../graphql/GraphQLRun.js');
const { data } = await graphQLRun(updateUser, { input: { ..... } });
  1. What is the GraphQL operation you're using to create the subscription?

I created a custom react hook https://gist.github.com/rafaelfaria/5fd45cc7fa00ff2c233a05c1f82e9c01

import useGraphQLSubscription from "../hooks/useGraphQLSubscription";
import { GRAPHQL_AUTH_MODE } from '@aws-amplify/auth';


const [ updatedItem ] = useGraphQLSubscription<User>({ config: { key: 'onUpdateUser', query: onUpdateUser, authMode: GRAPHQL_AUTH_MODE.AMAZON_COGNITO_USER_POOLS } });

  useEffect(() => {
    console.log({ updatedItem });
  }, [updatedItem]);

I'm asking for the authorization information because the subscription query must be authorized according to both the auth modes configured on the API, and the @auth rules specified in the schema. The operations are important because the required fields in a subscription's selection set must be included in the selection set used to make the triggering mutation.

Using your example schema (corrected as noted below), I am not able to replicate this issue. I created Users, Card, and Inventory records, and was able to subscribe to updates on them as expected.

rafaelfaria avatar Apr 02 '24 04:04 rafaelfaria

I was not able to reproduce the issue with the schema from the project identifier. I uncommented the user field on the User and Card field and was still able to receive subscriptions.

Just to be sure, could you try using the subscription through the AppSync console to rule-out any issue with the client side code?

dpilch avatar Apr 02 '24 16:04 dpilch

The AppSync console doesnt work for me, I am not able to use IAM from there.

rafaelfaria avatar Apr 15 '24 00:04 rafaelfaria

Hey @rafaelfaria, Please follow the instructions in the documentation for testing in AppSync console and let us know the results.

AnilMaktala avatar May 03 '24 18:05 AnilMaktala

Hey 👋 , This issue is being closed due to inactivity. If you are still experiencing the same problem and need further assistance, please feel free to leave a comment. This will enable us to reopen the issue and provide you with the necessary support.

AnilMaktala avatar May 28 '24 13:05 AnilMaktala

This issue is now closed. Comments on closed issues are hard for our team to see. If you need more assistance, please open a new issue that references this one.

github-actions[bot] avatar May 28 '24 13:05 github-actions[bot]

@AnilMaktala I tried with the custom-roles but I still get no authorization for things like listUsers for instance.

{
  "data": {
    "listUsers": null
  },
  "errors": [
    {
      "path": [
        "listUsers"
      ],
      "data": null,
      "errorType": "Unauthorized",
      "errorInfo": null,
      "locations": [
        {
          "line": 2,
          "column": 3,
          "sourceName": null
        }
      ],
      "message": "Not Authorized to access listUsers on type Query"
    }
  ]
}

rafaelfaria avatar Jun 12 '24 12:06 rafaelfaria

As a matter of fact, lately, all my subscriptions stop working. Now for the hasMany subscrtiptions I do receive a response, but the has many relationships comes with empty arrays.

I really don't know what to do. This has completely blocked me from launching my application.

rafaelfaria avatar Jun 12 '24 13:06 rafaelfaria

Hey @rafaelfaria, Could you please share the Amplify version you are using currently?

AnilMaktala avatar Jun 12 '24 18:06 AnilMaktala