How can I programmatically restrict node access?
I use a function to build the database rows in node_access and nodeaccess:

  private function set_node_access($nid, $id, $realm='nodeaccess_uid', $view=1, $update=0, $delete=0)
  {
    // ksm("nid: $nid uid: $uid");
    $connection = \Drupal::database();
    $sql = "INSERT INTO nodeaccess (nid, gid, realm, grant_view, grant_update, grant_delete) 
            VALUES($nid,$id,'$realm',$view,$update,$delete) 
            ON DUPLICATE KEY UPDATE grant_view=VALUES(grant_view), grant_update=VALUES(grant_update), grant_delete=VALUES(grant_delete)";
    $connection-&gt;query($sql);
    $sql = "INSERT INTO node_access(nid, langcode, fallback, gid, realm, grant_view, grant_update, grant_delete) 
            VALUES($nid,'de', 1, $id,'$realm',$view,$update,$delete) 
            ON DUPLICATE KEY UPDATE grant_view=VALUES(grant_view), grant_update=VALUES(grant_update), grant_delete=VALUES(grant_delete);";
    $connection-&gt;query($sql);
  }


That's not the nice way, but it works for me.